Perl strict Benchmark

This is a Example-Benchmark about to turn off things you don’t need in Perl:

use Benchmark qw(:all) ;
 
cmpthese(-1, {
'dev'      => sub {my($x,$y) = (4,3); $x = $x/$y;},
'strict'   => sub {my($x,$y) = (4,3); use strict; $x = $x/$y;},
});

Our Result:

            Rate    dev strict 
dev    3841286/s     --    -8%  
strict 4170472/s     9%     --

Maybe a good solution is to use it to check your code and then to comment it out, maybe with a debug variable, for this take a look at Perl Debug Output.

(This is just an Example, don’t turn of use strict.)

C# Calculator

This is an old calculator program I wrote in C# :

using System;
using System.Threading;
namespace Rechner
{
	class MainClass
	{
		public static double vari1=1,vari2=1;
		public static void Main (string[] args)
		{

			do{
			Einführung();
			string einlese = Convert.ToString(Console.ReadLine());
			Double ergebniss=0;
			switch(einlese)
			{
			case "+" : ergebniss = plus();break;
			case "-" : ergebniss = minus();break;
			case "*" : ergebniss = Mal();break;
			case "/" : ergebniss = Div();break;
			case "var1" : var1();break;
			case "var2" : var2();break;
			}
			Console.WriteLine("Die Lösung ist nach Adam Rieße "+ergebniss);
				Console.WriteLine("");
			Console.WriteLine ("Enter zum fortsetzen,var1 oder var2 zum speichern in Variablen !");
			try{
					string speichern = Console.ReadLine();
					if(speichern == "var1")
					{vari1 = ergebniss;Console.WriteLine("Variable 1 ist "+ergebniss);Console.ReadLine();} 
					if(speichern == "var2")
					{vari2 = ergebniss;Console.WriteLine("Variable 2 ist "+ergebniss);Console.ReadLine();} 
			}catch{}
			}while(true);
		}
		static Double plus()
		{
			Double summe=0;
			do{
				Console.Clear();
			Console.WriteLine("= zum beenden eingeben !");
			Console.WriteLine("Ergebnis = "+summe);
								Console.WriteLine ("");
				Console.WriteLine ("Variable 1 :"+vari1);
				Console.WriteLine ("Variable 2 :"+vari2);
			Console.Write("Zahl (+):");
				
			string a = Console.ReadLine(); 
           if (a == "=")
           {
               break;
           }
				           if (a == "var1")
           {
               summe = summe + vari1;
           }
				           if (a == "var2")
           {
               summe = summe + vari2;
           }
           else
           {
               try
               {
                   summe = summe + Convert.ToDouble(a);
               }
               catch { }
           }		
			}while(true);
			
			return (summe);
			
		}
		static Double minus()
		{
			Double summe=0;
			do{Console.Clear();
			Console.WriteLine("= zum beenden eingeben !");
			Console.WriteLine("Ergebnis = "+summe);
								Console.WriteLine ("");
				Console.WriteLine ("Variable 1 :"+vari1);
				Console.WriteLine ("Variable 2 :"+vari2);
			Console.Write("Zahl (-):");
				
			string a = Console.ReadLine(); 
           if (a == "=")
           {
               break;
           }
				           if (a == "var1")
           {
               summe = summe - vari1;
           }
				           if (a == "var2")
           {
               summe = summe - vari2;
           }
           else
           {
               try
               {
                   summe = summe - Convert.ToDouble(a);
               }
               catch { }
           }		
			}while(true);
			
			return(summe);
			
		}
		static void var1()
		{			Console.Clear();	Console.Write ("Variable 1 ändern:");
			try{
			string einlese = Convert.ToString(Console.ReadLine());
			vari1 = Convert.ToDouble(einlese);
			Console.WriteLine ("Variable 1 geändert:"+vari1);
								if(vari2 == 0){vari2 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
				if(vari1 == 0){vari1 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
			}catch{Console.WriteLine ("ERROR !");}
		}
		static void var2()
		{			Console.Clear();	Console.Write ("Variable 2 ändern:");
			try{
			string einlese = Convert.ToString(Console.ReadLine());
				vari2 = Convert.ToDouble( einlese);
			Console.WriteLine ("Variable 2 geändert:"+vari2);
								if(vari2 == 0){vari2 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
				if(vari1 == 0){vari1 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
			}catch{Console.WriteLine ("ERROR !");}
		}
		static Double Mal()
		{Double summe = 0;
			try{
						Console.Write("Zahl :");
			 summe=Convert.ToDouble(Console.ReadLine());
			}catch{}
			do{
				Console.Clear();
			Console.WriteLine("= zum beenden eingeben !");
			Console.WriteLine("Ergebnis = "+summe);
								Console.WriteLine ("");
				Console.WriteLine ("Variable 1 :"+vari1);
				Console.WriteLine ("Variable 2 :"+vari2);
			Console.Write("Zahl (*):");
				
			string a = Console.ReadLine(); 
           if (a == "=")
           {
               break;
           }
				           if (a == "var1")
           {
               summe = summe * vari1;
           }
				           if (a == "var2")
           {
               summe = summe * vari2;
           }
           else
           {
               try
               {
                   summe = summe * Convert.ToDouble(a);
               }
               catch { }
           }		
			}while(true);
			
			return(summe);
			
		}
		static Double Div()
		{Double summe = 0;string summe1 = "";
			try{
			do{	
			Console.WriteLine("");
			Console.Write("Zahl :");
			summe1 =Convert.ToString( Console.ReadLine());
			}while(Convert.ToDouble(summe1) <= 0);
				summe = Convert.ToDouble(summe1);
			}catch{}
			if(summe <= 0)
			{summe = 1;}
			do{
				Console.Clear();
			Console.WriteLine("= zum beenden eingeben !");
			Console.WriteLine("Ergebnis = "+summe);
								Console.WriteLine ("");
				Console.WriteLine ("Variable 1 :"+vari1);
				Console.WriteLine ("Variable 2 :"+vari2);
			Console.Write("Zahl (/):");
				
			string a = Console.ReadLine(); 
           if (a == "=")
           {
               break;
           }
				           if (a == "var1")
           {
               summe = summe / vari1;
           }
				           if (a == "var2")
           {
               summe = summe / vari2;
           }
           else
           {
               try
               {
						if(Convert.ToDouble(a) != 0)
						{
                   summe = summe / Convert.ToDouble(a);
						}else{Console.WriteLine("nicht möglich !");
						System.Threading.Thread.Sleep(2400);
						}
               }
               catch { }
           }		
			}while(true);
			
			return(summe);
			
		}
		static void Einführung()
		{Console.Clear();
			Console.WriteLine ("+ Plus rechnen");
			Console.WriteLine ("- Minus rechnen");
				Console.WriteLine ("* Mal rechnen");
				Console.WriteLine ("/ Dividiert rechnen");
				Console.WriteLine ("");
				Console.WriteLine ("var1 variable 1 ändern ");
				Console.WriteLine ("var2 variable 2 ändern ");
				Console.WriteLine ("");
				Console.WriteLine ("Variable 1 :"+vari1);
				Console.WriteLine ("Variable 2 :"+vari2);
				Console.WriteLine ("");
				Console.Write (">");
				if(vari2 == 0){vari2 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
				if(vari1 == 0){vari1 = 1;Console.WriteLine ("0 nicht erlaubt !");Console.ReadLine();}
		}

		
	}

}

Feel free to copy and share.

JavaScript location

In this article I wrote about the location object in JavaScript and what are the different between them.

Host

This two prints the host name, the different between them are that only host is with the port number from the host.

console.log(location.host);
console.log(location.hostname);

as example:

http://example.com:8080/

and we get this:

example.com:8080
example.com

 

Port

If you just want to get the Port you could use this:

console.log(location.port);

as example:

http://example.com:8080/

and we get this:

8080

Together with “location.host” and “location.port” you could get “location.hostname”.

 

Protocol

To get the Server protocol you just need this:

console.log(location.protocol);

as example:

http://example.com:8080/

and we get this:

http:

 

Href,Origin and Pathname

To get some other URL information run this:

console.log(location.href);
console.log(location.origin);
console.log(location.pathname);
console.log(window.location.search);

as example:

http://example.com/test/?s=test

and we get this:

http://example.com/category/c/
http://example.com
/category/c/
?s=test

Href just returns the URL with the pathname, origin just the URL without the pathname, pathname just the path behind the URL and at least the search parameter returns the parameters behind the “?”.

Perl random password generator

This is an little example how to generate some password with numbers,lower letter, upper letter and some special chars in Perl :

use strict;

print   randPW(join("",0..9),3).
        randPW(join("",'A'..'Z'),4).
        randPW(join("",'a'..'z'),4).
        randPW("+-*:;!@",3).$/ for(0..10);


sub randPW {
my @arr = glob(("{".join(",",split("",$_[0]))."}")x$_[1]);
return($arr[int rand($#arr)])    
}

Some random passwords:

728UEJXjltw+!+
019PBRPzsgm+-+
266MQSDizmg:!:
327YNEXqsgt:@:
183XTANfktm;-;
812BMXEpbwz::;
108TAFJbcve;+!
288SMLIbqko!!@
393JTJXoktj--:
702IKLHfetm++!
875VQUKmsyy+;:

Perl trim decimal number

This is a function to trim a decimal number in Perl, this function did not round the number just make an sub string from the dot to the end:

use strict;

print trim_deciamal("2.1",3).$/;
print trim_deciamal("2.12",3).$/;
print trim_deciamal("2.123",3).$/;
print trim_deciamal("2.1234",3).$/;
print trim_deciamal("2.12345",3).$/;

sub trim_deciamal{
my ($f,$h) = split(/\./o,$_[0]);
if(length($h) >= $_[1]){
    $h = substr($h,0,$_[1]);    
}else{
    $h = sprintf("%-".$_[1]."s",$h);
    $h =~ tr/ /0/;
}
return($f.".".$h);
}

Result looks like this:

2.100 
2.120 
2.123 
2.123 
2.123

we see missing positions are filled with 0 and longer numbers are trimmed.

Java CSV to Array and Array to CSV

This is a little example in Java to convert a CSV String into an Multidimensional Array, after that i convert the Array back into a CSV String, you could choose the delimiter by yourself. In this case i take the “-” to see the different:

public class HelloWorld{

     public static void main(String []args){
        String str="1;2;3\n4;5;6\n7;8;9\n10;11;12";
        System.out.println(str);
        String[][] out = csv2array(str);
        System.out.print(array2csv(out,"-"));
        
     }
     
    public static int count(String s, char c) {
        return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
    }
    
    public static String[][] csv2array(String str){
        String[] parts   = str.split("\n");
        String[][] out = new String[count(str,'\n')+1][count(parts[0],';')+1];
        for(int i = 0;i< parts.length;++i){
            if(!parts[i].equals("")){
                out[i] = parts[i].split(";");
            }
        }
        return(out);
     }
     
     public static String array2csv(String[][] in,String delim){
         String out = "";
        for(int x = 0;x < in.length;x++){
        for(int y = 0;y < in[x].length;y++){
            out += (in[x][y]);
            if(y!=in[x].length-1){
                out += delim;
            }
        }
        out += ("\n");
        }
        return(out);
     }
     
}

This is the Output, fist block separated with the “;” is the input and with “-” is the output:

1;2;3
4;5;6 
7;8;9
10;11;12
1-2-3
4-5-6
7-8-9
10-11-12

PHP image upload

This is my image upload solution:

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
    <br>
    By clicking the Upload button you accept that you are the owner of the file.
</form>

 <?php
$target_dir = "./i/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$ext = pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION);
$uploadOk = 1;
$FILENAME = hash_file("md5",$_FILES["fileToUpload"]["tmp_name"]).".".$ext;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "<h5>File is not an image.</h5>";
        $uploadOk = 0;
    }
	// Check if file already exists
	if (file_exists("./i/".$FILENAME)) {
	    echo "<h5>Sorry, file already exists.</h5>";
	    create_output($FILENAME);
	    $uploadOk = 0;
	}
	// Check file size
	if ($_FILES["fileToUpload"]["size"] > 5000000) {
	    echo "<h5>Sorry, your file is too large.</h5>";
	    $uploadOk = 0;
	}
	// Allow certain file formats
	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
	&& $imageFileType != "gif" && $imageFileType != "svg" ) {
	    echo "<h5>Sorry, only JPG, JPEG, SVG PNG & GIF files are allowed.</h5>";
	    $uploadOk = 0;
	}
	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk == 1){
	    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "./i/".$FILENAME)) {
		echo "<h5>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</h5>";
		create_output($FILENAME);
	    } else {
		echo "<h5>Sorry, there was an error uploading your file.</h5>";
	    }
	}
}else{
	echo "<br><br><br><br>Recent uploaded images:<br>";
	$files = scandir($target_dir);
	$count = 0;
	foreach($files as $result) {
		if( $result != "." && $result !=".."){
    			echo "\n<a href='http://scheinast.eu/i/$result' target='_blank'><img src='http://scheinast.eu/i/$result' style='width:304px;height:228px'></a>";
    		}
    		if($count > 10){break;}++$count;
	}

}


function create_output($FILE){
echo "<a href='http://scheinast.eu/i/$FILE'>http://scheinast.eu/i/$FILE</a>";
echo "<a href='http://scheinast.eu/i/$FILE'><img src='http://scheinast.eu/i/$FILE'></img></a>";
}

?> 
</body>
</html>

The name its stored is always an md5 hash of the file to avoid duplicate files.

Perl sub Benchmark

This is a Benchmark about the subroutines in Perl:

use Benchmark qw(:all) ;
 
sub calc { return($_[0]*$_[1]);}

my %subs;
$subs{'calc1'} = eval 'sub { return($_[0]*$_[1]);}';
$subs{'calc2'} = sub { return($_[0]*$_[1]);};
print $subs{'calc1'}->(1234,1234).$/;
print $subs{'calc2'}->(1234,1234).$/;
print calc(1234,1234).$/;
 
cmpthese(-2, {
'normal'  => sub {calc(1234,1234)},
'comp'    => sub {$subs{'calc1'}->(1234,1234);},
'ref'     => sub {$subs{'calc2'}->(1234,1234);},
});

Result:

1522756
1522756
1522756
            Rate    ref   comp normal
ref    1920352/s     --    -4%   -17%
comp   1996495/s     4%     --   -14% 
normal 2313035/s    20%    16%     --

We see the normal way is the best solution.