Iterate over a HashMap in Java
If you want to iterate over a Java HashMap simply use one of the following code:
public static void hashMapIteration() {
HashMap myMap = new HashMap();
myMap.put("1","A");
myMap.put("2","B");
myMap.put("3","C");
myMap.put("4","D");
// Iterate over keys and values as pairs
Iterator it = myMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println("Key: " + pairs.getKey() + " --- Value: " + pairs.getValue());
}
//Iterate over only values
Iterator it2 = myMap.values().iterator();
while (it2.hasNext()) {
System.out.println("Value: " + it2.next());
}
//Iterate over only keys
Iterator it3 = myMap.keySet().iterator();
while (it3.hasNext()) {
System.out.println("Key: " + it3.next());
}
}
Boolean to NSString
If you want to convert the value of an objective c BOOL variable into a nice, human readable format you can do this using the ternary operator as shown here:
BOOL myBooleanVar = YES; NSLog(@"The value is: %@", myBooleanVar ? @"YES" : @"NO");
That's all.
Java – Convert InputStream to String
Depending on the jre you are using you can convert an InputStream to string in different ways.
Using Java 1.4 you can make the conversion as this:
public static String convertStreamToString(InputStream is, int bufferSize, String encoding) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(is, encoding));
StringBuffer content = new StringBuffer();
char[] buffer = new char[bufferSize];
int n;
while ( ( n = reader.read(buffer)) != -1 ) {
content.append(buffer,0,n);
}
return content.toString();
}
With Java 1.5 and above you can make the conversion with much less code.
The shortest way is using the Scanner class.
public static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
However this solution can be a bit hard to understand.
You can also use a third party library like Apache IOUtils and do the conversion with it as shown here:
public static String convertStreamToString(InputStream is, String encoding) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, encoding);
return writer.toString();
}
MySQL backup with cron
To backup a mysql database on your server you can simply setup a cron job to do this. Simply use the official mysqldump utilities and compress the result with gzip. However you should check if mysqldump and gzip is accessible on your server.
The syntax is the following:
15 2 * * * root mysqldump -u root -pPASSWORD --all-databases | gzip > /mnt/disk2/database_`data '+%m-%d-%Y'`.sql.gz
Later you can email this file with a PHP script.
PHP file copy
You can simply copy files in PHP using the built in copy function. You need to provide the source and destination file and that's it.
The copy syntax is quite simple:
boolean $result = copy(src_file, dst_file);
The function returns with a boolean value that indicates whether the copy was success or not.
Here is a complete php file copy example:
<?php
$srcFile = "/home/demo/test/myFile.txt";
$dstFile = "/home/other/newFile.txt";
if (copy($srcFile, $dstFile)) {
echo "File copy was success!";
} else {
echo "File copy failed";
}
?>
PHP – Remove multiple spaces
To remove multiple spaces in a string and replace it with a single space character simply use the following code:
$text = preg_replace('/\s+/', ' ', $text);
PHP – Convert string to array
To convert any string into an array you need 2 inputs. You need the text/string itself and a separator character. If you have them you can simply use the explode function to make the conversion.
$text = 'This is a demo text to demonstrate explode function'; $delimiter = ' '; // This is a simple space character $myArray = explode($delimiter, $text); echo var_dump($myArray);
JavaScript – Character count
If you want to inform the user how many characters he/she was written in a textarea then you can simply add a function to the onkeyup event of the input field. The function simply reads the text from the textarea and get its length. Later you can display the result in any location you want.
The core function looks like this:
function getCharacterCount(element){
var counter = element.value.length();
}
PHP – suppress errors and warnings
In some cases you want to be sure that no error or warning messages will be printed out to the visitors browser window. If you can't edit php.ini settings or want to overwrite the general settings for some special cases then you can use the @ operator before the relevant function call. For example you can try top open a file in this way:
$myFile = @fopen($fileName);
PHP – Redirect page
If you want to redirect page in your php script you can simply use the header function with the new location. However don't forget that after redirection the original script runs to the end, so if you want to stop it you need to do it manually. Here is an example how to use it:
header('Location:http://www.coralcode.com');
die();
MySQL – List values without duplication
If you want to list all unique values from a table where the field has no unique constraint then you can use the DISTINCT keyword to remove duplications.
Use the following syntax:
SELECT DISTINCT lastname FROM user;
MySQL – Change auto increment value
Sometimes you may want to change the auto increment value in your table. You can do this by simply altering the table and set the auto_increment value as here:
ALTER TABLE tablename AUTO_INCREMENT = 1;
MySQL – Concatenate fields and strings
If you want to concatenate some of the table fields in MySQL you can easily do it using the concat() function. You can give as many parameter as you want, they can be field names and also strings. For example create a full address from the zip_code, city, street, house_nr as follows:
SELECT CONCAT(zip_code, ' ' , city, ', ' street, ' ', house_nr) FROM address;
PHP – Generate random string
If you want to generate random string with PHP - for example to send a new password to the user or some validation purposes - you can use the following simple function to get it. You simply need to list all characters you want to allow in the string and the length of the string.
function getString($length=6) {
$charList = "abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_!@#$%&*=+/";
for ($i = 0; $i < $length; $i++) {
$string .= $charList[mt_rand(0, strlen($charList)-1)];
}
return $string;
}
MySQL – Select random record
If you want to display only a single randomly selected record from a MySQL table you can do this by using the rand() function. Additionally you need to limit the result to select only as many rows as you want. For example to select 1 random record from table "books" you can use the following SQL:
SELECT * FROM books ORDER BY RAND() LIMIT 1;
PHP – Get image dimensions
To get image dimensions - the width and height values - with PHP is quite simple with using the getimagesize() function. You need to pass the image filename as input and you will get an array as output. From this array you can read out the requested width and height values like this:
$info = getimagesize('demo.gif');
echo "Width: " . $info[0];
echo "<br/>Height: " . $info[1];
or you can use this form to make it easier to read:
list($width, $height) = getimagesize('demo.gif');
echo "Width: " . $width;
echo "<br/>Height: " . $height;
PHP – Get file extension
To get a file extension in PHP is quite simple. You don't have to use any string manipulation functions or regular expression, but simply use the pathinfo() function, which returns an associative array with information about the given path. From this array simply read out the value of extension key like here:
$filename = 'myFile.gif'; $path_info = pathinfo($filename); echo $path_info['extension'];
or an even more simple solution:
$filename = 'myFile.gif'; echo pathinfo($filename, PATHINFO_EXTENSION);
PHP – Get current directory
If you want to know the current directory in your PHP script you can simply use one of the following methods:
- string getcwd ( void )
- string dirname ( string $path )
Here is a small code example:
$currentDir = getcwd(); echo $currentDir . "<br/>"; $currentDir2 = dirname(__FILE__); echo $currentDir2;
PHP – Get array length
To get the length of an array in PHP is quite simple. You can use 2 functions to do this:
- count()
- sizeof()
Both functions count all elements in the given array.
See it in action:
$myArray = array('red','blue','green');
$size = sizeof($myArray);
echo $size;
PHP – Get current date
To get the actual date in PHP you can use simply the date() function, which returns with the current formatted date. You need to provide the date format as this is a mandatory parameter.
Here are some examples:
// 2010-05-25
$currentDate = date("Y-m-d");
echo $currentDate."<br/>";
// May 25, 2010
$currentDate = date("F j, Y");
echo $currentDate."<br/>";