A Simple way to Generate Random number in Java

Math.Random class

In Java Programming, Math.Randoms class generates random integers, doubles, longs and so on, in various ranges.

To generate a series of random numbers as a unit, you need to use a single Random object – do not create a new Random object for each new random number.

Following example shows this:

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */


public class RandomInteger 

{

public static final void main(String… aArgs)

{
log(“Generating 10 random integers in range 0..99.”);
//note a single Random object is reused here Random randomObj = new Random();
for (int idx = 1; idx <= 10; ++idx)

{
int randomInt = randomGenerator.nextInt(100);

log("Generated : " + randomInt);

}
log(“Done.”);
}
private static void log(String aMessage)

{
System.out.println(aMessage);
}
}

Database Connectivity using Type I – JDBC Driver in Java(J2SE)

What is JDBC?

  • JDBC(Java DataBase Connectivity) is used for connecting to different database by which user can shift from one database to another database very easily in platform independent manner.
  • JDBC contains set of functions & specification in the form of packages i.e.:
    • java.sql.*–Core SQL Package
    • javax.sql.*–Extended SQL Package
  • JDBC Driver act like an interface between front end application and back end database.
  • There are four types of JDBC Driver
    • Type I-ODBC(Open DataBase Connectivity) Bridge Driver 
    • Type II-Java Native Interface Driver
    • Type III-Net Protocol Driver
    • Type-IV-Native Protocol Drover
  • Type I Driver, there exist an implementation class by which user can be able to connect to different database.
  • This implementation class, named JdbcOdbcDriver.class is provided within rt.jar file.

Connecting to any Database:-

Step 1) Loading a Driver: 

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Step 2) Getting Connection: 

Connection con = DriverManager.getConnection(“<URL>”,”<UserName>”,”<Password>”);

Step 3) Create Statement Object:

Statement st = con.createStatement();

Step 4) Prepare a query and execute the query at backend database.

  • ResultSet rs = st.executeQuery(“<SQL SELECT command>”);
  • boolean flag = st.execute(“<SQL Non-SELECT command>”);
  • int x = st.executeUpdate(“<SQL DML command>”);

Step 5) Close all connections: 

st.close();

con.close();

Sample JDBC code for this demonstration:

import java.sql.*;

class DBConnectivity

{

public static void main( String [] args)

{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Connection conn = DriverManager.getConnection(“jdbc:odbc:OracleDSN”,”scoot”,”tiger”);

Statement st = conn.createStatement();

boolean flag = st.execute(“create table student(ID varchar2(5), NAME varchar2(30), MARKS number(5))”);

int x = st.executeUpdate(“inser into stud values(‘101′,’Pallavi’,879)”);

ResultSet rs = st.executeQuery(“<SELECT ID,NAME,MARKS from student>”);

while (re.nwex())

{

logout(“ID:-“+rs.getString(1)+”\t”);

logout(“NAME:-“+rs.getString(2)+”\t”);

logout(“MARKS:-“+rs.getInt(3)+”\n”);

}

}


public void logout(String msg)

{

System.out.println(msg);

}


}

 

 


Note: Here “OracleDSN” is User Created DSN (Data Source Name), in Administrative Tools–>Data Source

Fetch GooglePlus Feeds using PHP

Fetch GooglePlus Feeds to your website using PHP

[php]
<?php function fetchAPI($url) {

$content = '';

if (ini_get('allow_url_fopen') == true) {
$content = file_get_contents($url);
}
else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $key);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
}
return $content;
}

// Google+ ID
$googlePlusID = 'YOUR ID';
$url = "https://plus.google.com/YOUR ID/posts";
// Google+ API key
$key = 'DEVELOPER KEY';

$url = 'https://www.googleapis.com/plus/v1/people/' . $googlePlusID . '/activities/public?alt=json&pp=1&key=';

$content = fetchAPI($url . $key);

if ($content)
file_put_contents($cacheFile, $content);
if (!$content)
die('Failed to load G+ data');
$gplus = json_decode($content);

if (!$gplus)
die('Failed to decode G+ data');
echo "
<pre>";
print_r($gplus);
die;

[/php]

HTML5 canvas using JavaScript

The canvas is HTML5 element used to draw graphics using JavaScript. 

 

[sourcecode language=”plain”]</code><!DOCTYPE html>

<html>

<body>

<canvas id="myCanvas" style="border:1px solid #000000;">Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById(‘myCanvas’);

var ctx=c.getContext(‘2d’);

//ctx.fillStyle=’#FF0000′;

for (var x = 0, y = 0; x < 150 && y < 200; x += 50, y += 37) {

var i = x+125;

var color =’FF0’+i;

//alert(color);

ctx.fillStyle=’#’+color;

ctx.fillRect(x,y,60,60);

}

</script>

</body>

</html>

<div> <code>[/sourcecode]


Demo :

PDO (PHP Data Object)

PDO(PHP Data Object)  : PDO is a PHP extension for accessing databases in PHP.

Advantages:

1) Security : In MYSQL connection we manually sanitise using mysql_real_escape_string() functions in order to avoid SQL injections. But with PDO this is all taken care for us and means we no longer have to worry about SQL injection.

2) Performance : PDO uses PHP 5′s OOP characteristics (Object Oriented Programming) so it is working with classes and objects. PDO is written in C and compiled into PHP providing a performance increase over solutions written in PHP.

3) PDO provides single interface across multiple databases. That means to easily migrate to a different database engine (SQLite, Oracle, MSSQL, ODBC, etc.)

4) We can use error handling in PDO by using try, catch and throw.

Connection Syntex:
[php]
$user = USER_NAME;

$pass = PASSWORD;

$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);

<b>Exception handling in PDO:</b>

try {

$dbh = new PDO(‘mysql:host=localhost;dbname=test’, $user, $pass);

}

catch (PDOException $e) {

print "Error!: " . $e-&gt;getMessage() . "&lt;br/&gt;";

die();

}
[/php]

 Insert query:
[php]
$sth = $dbh-&gt;prepare("INSERT INTO `table` (`id`, `title`) VALUES (:id, :title)");

$sth-&gt;execute(array(‘:id’    =&gt; 123,’:title’ =&gt; ‘I am the title’));

<b>Select Query:</b>

$sth = $dbh-&gt;prepare("SELECT `id`, `title` FROM `table` WHERE `id` &gt; :country_id");

$sth-&gt;execute(array(

‘:country_id’ =&gt; 200

));

$count = $sth-&gt;rowCount();
[/php]

Increase Media file upload size in WordPress Multisite

In WordPress, Maximum upload file size will not change even when changed in the php.ini file.

Here are the steps to change the Maximum upload file size within WP admin:

1. At the top, hover over My Sites and then click Network Admin

2. At the left, hover over Settings and then click Network Settings.

3. Scroll to the bottom of the page and change the Max upload file size to whatever you would like in KB.

4. Click Save Changes.

Checking if URL contains “HTTP” OR “HTTPS”

Checking if URL contains “HTTP” OR “HTTPS”

Code

[php]$site = "https://www.abc.com?id=123&r=sdsdsdsdd";
$url = parse_url($site);
if(in_array("http", $url) || in_array("https", $url)) {
echo "Present";
}
else{
echo "Not Present";
}[/php]

Note:  parse_url : Parse URL ans returns its components.

PHP Code for Locating Train stations, ATM’s, Mall’s and many things Nearby Using Google Map API

[sourcecode language=”plain”]<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">

<style>
html, body, #googleMap
{
height: 100%;
margin: 0px;
padding: 0px;
}

.controls
{
position: absolute;
z-index: 10;
margin-top: 16px;
margin-left:100px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#country_name
{
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
position: absolute;
background-color: #fff;
padding: 0 11px 0 13px;
margin-left:100px;
margin-top:50px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
z-index: 10;
}

#coord0
{
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
position: absolute;
z-index: 10;
margin-left:100px;
margin-top:760px;
width:1000px;
}

#selection
{
background-color: #fff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
position: absolute;
z-index: 10;
margin-left:100px;
margin-top:30px;
}
</style>

<script src="jquery-1.7.1.js" type="text/javascript">
</script>
<script src="jquery.fancybox-1.3.4.pack.js" type="text/javascript">
</script>
<!–script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script–>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=true&amp;libraries=places,drawing"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<link rel="stylesheet" href="jquery.fancybox-1.3.4.css"/>

<script>
var map;
var infowindow;
var new_map;
var center;
var place_name = [];
var tubes;
var place_type;
var remove_marker = [];
////////////////////////////////////////
function initialize()
{
mapProp = {
center:new google.maps.LatLng(23.8989,12.4731),
zoom:4,
mapTypeId:google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("googleMap")
,mapProp);

$(window).click(function(){

place_type = $("#place_type").val();
});

$(window).keydown(function(event){
if(event.keyCode == 13)
{
place_type = $("#place_type").val();
///event.preventDefault();
//return false;
}
});

//—————————————————————–//
var input = /** @type {HTMLInputElement} */(
document.getElementById(‘country_name’));

//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

var options = {
types: [‘(cities)’],
componentRestrictions: {country: "in"}
};

var autocomplete = new google.maps.places.Autocomplete(input, options);
//autocomplete.bindTo(‘bounds’, map);

var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});

google.maps.event.addListener(autocomplete, ‘place_changed’, function() {
infowindow.close();
marker.setVisible(true);

google.maps.event.addListener(autocomplete, ‘resize’);

var place = autocomplete.getPlace();
google.maps.event.trigger(map, ‘resize’);

for (var i = 0; i < remove_marker.length; i++) {

var marker1 = new google.maps.Marker
({
map: map,
position: remove_marker[i]
});

marker1.setMap(null);
}

if (!place.geometry) {

return;
}

// If the place has a geometry, then present it on a map.
if (place.geometry.viewport)
{
map.fitBounds(place.geometry.viewport);
//console.log(place.geometry);
var getbounds = map.getCenter(place.geometry.location);
//alert(place_type);
var newcenter = [];
newcenter[0] = place.geometry.location.lat();
newcenter[1] = place.geometry.location.lng();
//alert("My center"+newcenter);

var getcenter = new google.maps.LatLng(newcenter[0], newcenter[1]);
//alert("GEOMETRY"+getcenter);

var request = {
location: getcenter,
radius: ‘1609.34’,
types: [""+place_type+""]
};

var circle = new google.maps.Circle({
map: map,
strokeWeight: 0.5,
strokeColor: ‘#3FAA3A’,
radius: 2000.34, // 1 mile in metres
fillColor: ‘#64F25E’,
center: getcenter
});

//alert("Your Center"+request);
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);

}
else
{

var newcenter = [];
newcenter[0] = place.geometry.location.lat();
newcenter[1] = place.geometry.location.lng();
//alert("My center"+newcenter);
//alert(place_type);
var getcenter = new google.maps.LatLng(newcenter[0], newcenter[1]);
//alert("Your Center"+getcenter);

var request = {
location: getcenter,
radius: ‘1609.34’,
types: [""+place_type+""]
};

var circle = new google.maps.Circle({
map: map,
strokeWeight: 0.5,
strokeColor: ‘#3FAA3A’,
radius: 2000.34, // 1 mile in metres
fillColor: ‘#64F25E’,
center: getcenter
});

service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);

}
marker.setIcon(/** @type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);

var address = ”;
if (place.address_components) {
//alert(place.address_components[1].short_name);
address = [
(place.address_components[0] && place.address_components[0].short_name || ”),
(place.address_components[1] && place.address_components[1].short_name || ”),
(place.address_components[2] && place.address_components[2].short_name || ”)
].join(‘ ‘);
//alert("ADDRESS: "+address);

}

infowindow.setContent(‘<div><strong>’ + place.name + ‘</strong><br>’ + address);
infowindow.open(map, marker);

});

}
//—————————————————————–//

//————————FUNCTION CALLBACK FOR PLOTING MARKERS OF NEARBY SEARCH———————————//

function callback(results, status) {
var area_name = document.getElementById(‘coord0’);

if (status == google.maps.places.PlacesServiceStatus.OK) {
//alert(status);

console.log(results);
var placelat = results[0].geometry.location.lat();
var placelng = results[0].geometry.location.lng();

var center1 = new google.maps.LatLng(placelat,placelng);
//alert(placelat+", "+placelng);

for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
remove_marker.push(results[i].geometry.location);
place_name.push(results[i].name);
}

map.setZoom(14);
map.setCenter(center1);
//alert(tubes);
tubes = "";
//alert(tubes);
//alert(place_name);
area_name.value = place_name;
place_name = [];
/*if (results)
{
for (i in results)
{
results[i].setMap(null);
}
results.length = 0;
}*/
//alert(place_name);
}
else
{
area_name.value = place_name;
}
}

function createMarker(place) {
var placelat = place.geometry.location.lat();
var placelng = place.geometry.location.lng();

var center1 = new google.maps.LatLng(placelat,placelng);

infowindow = new google.maps.InfoWindow();

tubes = new google.maps.Marker({
map: map,
position: place.geometry.location
});

tubes.setMap(map);

google.maps.event.addListener(tubes, ‘click’, function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});

}

function removeMarker(place) {
var placelat = place.lat();
var placelng = place.lng();

alert(place);
var center1 = new google.maps.LatLng(placelat,placelng);

infowindow = new google.maps.InfoWindow();

tubes = new google.maps.Marker
({
map: map,
position: place
});

tubes.setMap(null);

}

//————————FUNCTION CALLBACK FOR PLOTING MARKERS OF NEARBY SEARCH———————————//

google.maps.event.addDomListener(window, ‘load’, initialize);

</script>
</head>
<body>

<textarea id="coord0" width="700"></textarea><br>
<div id="selection">
Select Your Place Type
<select id="place_type">
<option value="airport">Airpot</option>
<option value="amusement_park">Amusement_park</option>
<option value="aquarium">Aquarium</option>
<option value="art_gallery">Art_gallery</option>
<option value="atm">ATM</option>
<option value="bakery">Bakery</option>
<option value="bank">Bank</option>
<option value="bar">Bar</option>
<option value="beauty_salon">Beauty_salon</option>
<option value="bicycle_store">Bicycle_store</option>
<option value="book_store">Book_store</option>
<option value="bowling_alley">Bowling_alley</option>
<option value="bus_station">Bus_station</option>
<option value="cafe">Cafe</option>
<option value="car_dealer">Car_dealer</option>
<option value="car_rental">Car_rental</option>
<option value="car_repair">Car_repair</option>
<option value="car_wash">Car_wash</option>
<option value="casino">Casino</option>
<option value="cemetery">Cemetery</option>
<option value="church">Church</option>
<option value="city_hall">City_hall</option>
<option value="clothing_store">Clothing_store</option>
<option value="convenience_store">Convenience_store</option>
<option value="courthouse">Courthouse</option>
<option value="dentist">Dentist</option>
<option value="department_store">Department_store</option>
<option value="doctor">Doctor</option>
<option value="electrician">Electrician</option>
<option value="electronics_store">Electronics_store</option>
<option value="embassy">Embassy</option>
<option value="establishment">Establishment</option>
<option value="fire_station">Fire_station</option>
<option value="florist">Florist</option>
<option value="food">Food</option>
<option value="funeral_home">Funeral_home</option>
<option value="furniture_store">Furniture_store</option>
<option value="gas_station">Gas_station</option>
<option value="general_contractor">General_contractor</option>
<option value="grocery_or_supermarket">Grocery_or_supermarket</option>
<option value="gym">Gym</option>
<option value="hair_care">hair_care</option>
<option value="hardware_store">hardware_store</option>
<option value="health">health</option>
<option value="hindu_temple">hindu_temple</option>
<option value="home_goods_store">home_goods_store</option>
<option value="hospital">hospital</option>
<option value="insurance_agency">insurance_agency</option>
<option value="jewelry_store">jewelry_store</option>
<option value="laundry">laundry</option>
<option value="lawyer">lawyer</option>
<option value="library">library</option>
<option value="liquor_store">liquor_store</option>
<option value="local_government_office">local_government_office</option>
<option value="locksmith">locksmith</option>
<option value="lodging">lodging</option>
<option value="meal_delivery">meal_delivery</option>
<option value="meal_takeaway">meal_takeaway</option>
<option value="mosque">mosque</option>
<option value="movie_rental">movie_rental</option>
<option value="museum">museum</option>
<option value="night_club">night_club</option>
<option value="movie_theater">movie_theater</option>
<option value="painter">painter</option>
<option value="park">park</option>
<option value="pet_store">pet_store</option>
<option value="pharmacy">pharmacy</option>
<option value="physiotherapist">physiotherapist</option>
<option value="police">police</option>
<option value="post_office">post_office</option>
<option value="restaurant">restaurant</option>
<option value="school">school</option>
<option value="shopping_mall">shopping_mall</option>
<option value="shoe_store">shoe_store</option>
<option value="spa">spa</option>
<option value="stadium">stadium</option>
<option value="store">store</option>
<option value="subway_station">subway_station</option>
<option value="synagogue">synagogue</option>
<option value="taxi_stand">taxi_stand</option>
<option value="train_station">train_station</option>
<option value="travel_agency">travel_agency</option>
<option value="university">university</option>
<option value="veterinary_care">veterinary_care</option>
<option value="zoo">zoo</option>
</select>
</div><br>
<input type="text" id="country_name" >

<div id="googleMap">

</div>

</body>
</html>[/sourcecode]