Get your learn on

20 Dec


MeasurePlans.com|Construction Job Cost Estimating Software

Browse our catalog of easy to use yet powerful estimating software programs for the professional construction estimator.



General Sites:


Schools and Universities:

Other General Sites:


Specialized Sites:


Computer Related:

Music:

Language:

Cooking/Food:

eBooks/Online Books/Academic Journals:

Other Subjects:

Random Story Plots Revisted

18 Dec

Once again I found myself in a situation where I needed to use a grab-bag of plot lines. So I revisited my IMDB plot randomizer and reloaded it with thousands and thousands of random plots. Give it a try : Rand Plot Generator

Works great if you need help being creative in any writing projects (poems, short stores, songs, ect.)

Buddypress Esperanto

26 Nov

I have recently created a plugin filter that converts x-convention Esperanto translations into proper html entities for Esperanto character encoding. This is part of my Esperanto for Buddypress project.

Array Node Wondering

11 Nov

This function will walk through an array structure randomly (thus “wondering”). In some instances you may have an array that is structured like a tree. You may also need to randomly build a path from the trunk to the end leaf while mapping all nodes in between. The following function will walk through the nodes while recording the keys in text format :

        function node_wonder($in_array,$load=null) {
                $keys = array_keys( $in_array );
                shuffle( $keys );
                $item = current($keys);
                if (is_array($in_array[$item])) {
                        if ($load) $load .= " ";
                        return node_wonder($in_array[$item],$load.$item);
                } else {
                        if ($load) $load .= " ";
                        return $load.$in_array[$item];
                }
        }

As an example, we will use this array :

        $testArray = array(
                "The dog" => array(
                        "barked at"=>array(
                                "the mail man",
                                "the moon",
                                "the passing" => array(
                                        "cars",
                                        "trucks",
                                        "people"
                                ),
                        ),
                        "chased"=>array(
                                "its tail",
                                "another dog",
                                "after the airplane"
                        ),
                        "wagged its tail"
                ),
                "The cat" => array(
                        "slept" => array(
                                "lazily",
                                "all afternoon",
                                "curled in a ball"
                        ),
                        "played with" => array(
                                "its mouse toy",
                                "a ball of yarn",
                                "another cat"
                        ),
                ),
                "The fish" => array(
                        "swam",
                        "ate flakes"
                )
        );

When we pass the $testArray to the node_wonder() function we will get a new story each time :

The dog barked at the passing people
The cat played with another cat
The fish ate flakes
The dog chased after the airplane
The fish swam
The dog barked at the mail man
The cat slept curled in a ball
The dog chased after the airplane
The cat slept lazily

Why and how would you use this function? I have built this function to condense my list of UserAgents in my generator function.
This is also closely related to my content spinner function.

Storing Arbitrary Information with PHP and MySQL

8 Nov

I have seen too many times where people struggle and toil with customizing database tables to fit every small aspect of their data models. Many times they end up using many tables because they have dynamic data relationship needs.

However this may just simply be overkill.

If you are going to store data that is not going to appear in a WHERE clause then you can store it arbitrarily. And by arbitrary I simply mean that you can store PHP data objects themselves into the database.

In your table you wish to store the arbitrary data just create a field that is BLOB. For the following example the field ‘arb_data’ is set to a BLOB.

$objects = array("session"=>$session,"cache"=>$cache,"user"=>$user);
$arb_data = mysql_escape_string(gzdeflate(serialize($objects)));
$query = "INSERT into my_table (id,arb_data) values ({$id},'{$arb_data}')";
mysql_query($query);

This will serialize and gzip the data objects then insert them into the BLOB field. To retrieve the data we do the opposite :

$query = "SELECT arb_data from my_table where id = {$id}";
$q = mysql_query($query);
$res = mysql_fetch_array($q);
$objects = unserialize(gzinflate($res["arb_data"]));
var_dump($objects);

This will obviously not work if you need to have your queries conditional on the data stored as arbitrary data (i.e. If arb_data doesn’t need to be in WHERE,ORDER BY, JOIN, etc..).

Non-sequential Iterating in PHP

7 Nov

I needed to iterate through an unknown amount of records, but I need to do it in a non-sequential manner, as to appear that I was not enumerating the data set in its entirety.

So how could someone enumerate every single record, non-sequential, without duplication, indefinably? I modified my Fisher Yates shuffle to do this exact task:

function nonseq($amount,$iter=0,$seed=NULL) {
	if (!$seed) {
		list($usec, $sec) = explode(' ', microtime());
		$seed = (float) $sec + ((float) $usec * 100000);
	}

	srand($seed);

	for($i=0;$i<$amount;$i++) $map[$i] = ($i + 1);

	for($i=(count($map)-1);$i>=0;$i--) {
		$j = @rand(0,$i);
		$tmp = $map[$i];
		$map[$i] = $map[$j];
		$map[$j] = $tmp;
	}
	if ($iter > ($amount)) {
		$base = floor($iter / $amount);
		$niter = $iter - ($base * $amount);
		$prec = nonseq($amount,($niter+1),$seed+1);
		return $prec + ($base * $amount);
	}
	return $map[$iter-1];
}

The code is also located here

This function takes 3 parameters, but two are optional. The first, and required, parameter is increment partition size. The second parameter is the normal sequential pointer. If you do not provide a second parameter then it will default to 0. The third parameter is a random seed.

Logic of the function:
X = Increment Partition Size, Y = Sequential Pointer, Z = Random Seed.
If (X >= Y), results = (FYShuffled number between 0 and X randomed by Z)
If (X < Y ), results = ((FYShuffled number between 0 and X randomed by ( Z+(X/Y) )) + (largest multiple of X that is less than Y))

<?
include("nonseq.php");
echo nonseq(10,50,5);
?>

The above examples first parameter instructs the function to randomize sequential in increments of 10. The second value asks what the 50th sequential iteration would be converted to, and the 5 is a simple random seed. Since the first value is 10, then we can assure that the output will be between 51 and 60, and in my case was : 60. If we run the same function with the sequential iteration set to 51 we get : 54.

So if you were to normally iterate through records as such :

for($i=1;$i<=3000;$i++) {
   $cont = file("http://www.scrape-site.com/sites.php?id={$i}");
   record_info($cont);
}

This example would iterate sequentially ( id=1, id=2, id=3, id=4, id=5...)
However, if you use the nonseq function :

for($i=1;$i<=3000;$i++) {
   $nsid = non_seq(1000,$i,5);
   $cont = file("http://www.scrape-site.com/sites.php?id={$nsid}");
   record_info($cont);
}

This would iterate in a non-sequential manner(id=832, id=272, id=698, id=177...). It would continue and without repeating any numbers indefinably.

Better than var_dump and print_r

4 Oct

This function, created by stlawson from joyfulearthtech.com makes life much easier for a php developer. Calling do_dump with a variable will create an HTML formatted output that is easy to read and understand. Give it a shot :

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#666666;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    // So this is always visible and always left justified and readable
    echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color\"".htmlentities($avar)."\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> ".htmlentities($avar)."<br>";

        $var = $var[$keyvar];
    }

    echo "</div>";
}
?>

Random Plot Summaries

8 Aug

Another project completed. This simple program will pick 10 random plot summaries from the IMDB.


Random Plot Summaries


I created this tool to aid me with a creative writing that ties into another future project. If you find yourself to be a creative writer then please drop me an email as I will need help for this upcoming project.

Array Wheels in PHP

24 Jun

Arrays are variables that can hold more than one piece of data. Traditional arrays have a starting point and an ending point. In some instances you may need an array that loops back to the beginning once you have fully iterated through its contents. I have created a php class called array_wheel that does just this simple task. Not only can you iterate through the array indefinably , but you can also “turn” the array wheel, changing the datas indexes to the left, or to the right. You can also add as well as remove arbitrary data in any slot within the wheel. Accessing numeric keys of this array_wheel will iterate through each data element until it finds the corresponding number.

Download the Array Wheel Class

This type of data class is very helpful in charts that work in circles, such as many aspects of music theory.

Here is a list of the functionality of this class :

array_wheel($array=NULL) – If $array is provided then the contents of the array wheel will be set to the array. Otherwise the array_wheel will be empty.

add($var,$position=-1) – This will append a variable to the end of the array wheel. If the position is provided then the variable will be inserted into that section of the array wheel. A position of 0     indicates the start of the array wheel, and a position of -1 indicates the end of the array wheel.

remove($position=-1) – This will remove an element from the array wheel. If the position is provided then the variable will be removed from that section of the array wheel. A position of 0 indicates the start      of the array wheel, and a position of -1 indicates the end of the array wheel.

cw($steps=1) – Rotates the variables clockwise in the wheel. This will move all variables to the next higher key, and the last variable to the start of the array.

ccw($steps=1) – Rotates the variables counter clockwise in the wheel. This will move all variables to the next lower key, and the first variable will be moved to the end of the array.

turn_to($element) – Turns the wheel so that the matching element is at the 0 location (top of the wheel). Returns false if the element can not be matched.

next() – returns the next element in the wheel

prev() – returns the previous element in the wheel

reset() – Sets the internal index to zero

An Example of the Array Wheel in Action :


include("array_wheel.php");

 $aw = new array_wheel(array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B"));
 $root = "A#";
 if ($aw->turn_to($root)) {
 echo "The chord of {$root} Maj13 is : ";
 echo $aw->get(0).", ";
 echo $aw->get(4).", ";
 echo $aw->get(7).", ";
 echo $aw->get(11).", ";
 echo $aw->get(21)." ";
 }

Simple PHP JSON Rest Post Client

9 Jun

I just needed a simple way to post JSON formatted variables to an API and get the return. So here is a quick dirty function to do so :


<?
function restcall($url,$vars) {
 $headers = array(
 'Accept: application/json',
 'Content-Type: application/json',
 );
 $data = json_encode( $vars );

 $handle = curl_init();
 curl_setopt($handle, CURLOPT_URL, $url);
 curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
 curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

 curl_setopt($handle, CURLOPT_POST, true);
 curl_setopt($handle, CURLOPT_POSTFIELDS, $data);

 $response = curl_exec($handle);
 $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
 return $response;
}
?>

Don’t forget to json_decode(); the return if required.