Print 1 to 1000 without conditionals or loops

I came across a brilliant solution on the web to print out 1 to 1000 without conditionals or loops. Here is the code:

int main (int j, const char * argv[])

{

     printf("%d\n", j);

     (1000 - j) && main(j + 1, NULL);

}

In the first iteration, j is equal to 1.  In order to understand why, think of running this program from the command line.  The program has a name, say ‘myprg’.  If you run ‘myprg’ from the command line, ‘myprg’ counts as one argument.  So j will have a value of 1. The genius of this solution lies in the rule that the right side of the && operator only executes if the left side evaluates to a non-zero value.  When j is equal to 1000, (1000 – j) is equal to 0, so the right side won’t execute.   This is what prevents infinite recursion.  For every case between 1 – 999, (1000 – j) is a non-zero number and main will run recursively, incrementing by one each time until 1000 is reached.

Note that the performance of this solution isn’t great because a function that calls itself many times consumes a lot of memory on the thread’s stack.

 

Posted in C++, Recursion | Leave a comment

PHP strtotime not working

I was working on a client’s web site using the environment on my local machine and everything seemed to be working just fine. However, on the client’s live web site, which is hosted by 1and1, something just wasn’t working. I narrowed the problem down to different values being return by the PHP strtotime function in php.

Here was the code running on my MAC:

<!--?php echo strtotime("2100-01-01") . " " . strtotime("2100-01-02") ?-->

This echoes 4102473600 4102560000 to my screen. If you subtract the first number from the second, (4102560000 – 4102473600), you get 86400. 86400 = 60 * 60 * 24, which is the number of seconds in a day. So far so good.

However, when I uploaded the SAME EXACT code to my client’s web site and tested it out, the output was empty. I looked at the documentation for strtotime (http://php.net/manual/en/function.strtotime.php) and discovered the function can return false. so I tried running this code on my local server:

<!--?php
if (! strtotime("2100-01-01"))
{
	echo "strtotime failed";
}
?-->

Nothing printed out locally. When uploaded to my 1and1 environment, “strtotime failed” was printed to the screen. After some digging, I noticed that the machine that was hosting my 1and1 account was using a 32-bit processor. On a 32 bit processor, the largest positive integer that can be represented is 2147483647. 4102560000 and 4102473600 are both greater than 2147483647, and can’t be represented by simple means on a 32 bit machine. The function was failing because of overflow. It turns out that maximum future date and time that can be represented by normal means on a 32 bit machine is Tue, 19 Jan 2038 03:14:07 GMT, which corresponds to 2147483647.

Luckily I only chose 2100-01-02 as an upper bound. For my needs, I required a date that was far off in the future. Unfortunately this is too far off for a 32 bit machine to easily represent. I simply chose 2038-01-01, which is a date far into the future that can be represented on both a 32 and 64 bit machine.

Lesson learned, if strotime acts differently in different environments, start off by finding out what kind of processors are running in each environment. If they are different, you have a good starting point in diagnosing whatever problem you have. For more information about representing larger numbers on 32 bit machines, check out this link: http://www.php.net/manual/en/book.gmp.php

Posted in PHP | Leave a comment

Merging Multiple PDFs in php

In a recent gig, I had take two PDF files and merge them together in PHP somehow. This was easily accomplished using a tool that I discussed in my previous post. The name of the tool is pdftk. It is available for *nix and PC. It can be found here.

If you look at the Examples page, you’ll see how to do many things. Merging two documents is very simple. It is a command line tool, so you can call is using the exec command in php. Here is some sample code.

<?php
     exec("pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf")
?>

This will take existing files 1.pdf, 2.pdf, and 3p.df and create a new file called 123.pdf. Although you see the “cat” statement it’s just a command line option that pdftk understands, so this is not the *nix only way of running the tool. This works fine on a PC.

Posted in PDF, PHP | Leave a comment

Populating PDF fields using a web form in PHP

I was recently tasked with populating fields in a PDF file with data inside of a form on a web page. This ended up being a relatively simple task to do after digging around and finding the tools that I needed.

The first step was to set the name attribute of all of the form fields on the web page to match the names of the form fields in the PDF. The form submits itself to a file called generatePDF.php Here is the code of generatePDF.php

<?php

    if(isset($_POST) ){

		require_once 'createFDF.php';

		$pdf_template_name = "pdf_to_populate.pdf";
		$output_dir = "/var/www/results/";
		$application_location = "http://localhost/";

		// file name will be <the current timestamp>.fdf
		$now = time();

		$fdf_file_no_ext = $_POST['lastName'] . "_" . $_POST['firstName'] . "_" . $now;
		$fdf_file=  $fdf_file_no_ext . '.fdf';

		$pdf_doc= $application_location . $pdf_template_name;

		// create the file content
		$fdf_data=createFDF($pdf_doc,$_POST);

		if($fp=fopen($output_dir.'/'.$fdf_file,'w'))
		{
			fwrite($fp,$fdf_data,strlen($fdf_data));
			$execString = 'pdftk ' . $pdf_template_name . ' fill_form ' . $output_dir . $fdf_file . ' output ' . $output_dir . $fdf_file_no_ext . '.pdf flatten';
			exec($execString);
			exec('rm ' . $output_dir . $fdf_file);
		}
		else
		{
			die('Unable to create file: '.$output_dir.'/'.$fdf_file);
		}

		fclose($fp);
	}

?>

I couldn’t find any tool that directly creates a PDF from a web form. So first, I used open source tools to create what is called an FDF file. For more information about an FDF file, see this link.

Line 5 includes the class necessary to create the FDF file, which I found here

The other important line in this is line 25. Notice the call to execute pdftk. This converts an fdf file to a pdf file. You can find pdftk here. The command line arguments instruct pdftk to fill the form (fill_form) in the pdf ($pdf_template_name) with the contents of the FDF file, the FDF file is then deleted.

Note that the PDF file you pass to pdftk is just being used as a template. pdf_to_populate.pdf is not actually being populated. It will remain unchanged. Using pdf_to_populate.pdf, as a template, a new file will be created and populated. The ‘flatten’ argument of pdftk makes the newly generated PDF read only.

Posted in PDF, PHP | 2 Comments