Browsing Category

Software Engineering

Add Functionality to Button or Call Function with Button in Unity 5

With all of the changes to how Unity operates with even basics like Buttons, its easy to read deprecated information that just won’t work in your new Unity 5 (5.5 or 5.6+) projects. It really seems like the major wave of changes started occurring around 4.7, and what happened to how we used to make “buttons” with OnClick() functions or whatever.

However, even now, I still see a lot of misinformation that does actually work, but its the wrong way to do it, and can only lead to confusion or problematic behavior down the road. It is surprisingly easy to do button functionality, and I’ll try to explain each part as I go so you understand the mechanics behind what’s going on.

So we’ll roll with a simple and easy example, doing a step-by-step on how to make make a proper quit button.

1. We’ll be creating a script to attach the button.

2. Then we’ll be adding a call to a function in this script, using the built-in OnClick() list in the inspector.

Implementing Multiple Canvas Groups in Unity 5


There is often confusion about how to implement canvas groups in Unity 5. The documentation makes it fairly plain what canvas groups are, but doesn’t help so much on just how to use them. This confusion leads to people asking about creating multiple canvases (which is actually possible to do in Unity 5+).

The multiple canvas solution is simply the wrong way to go about implementing multiple canvas groups however. It shows a lack of understanding on how you can use this UI feature. Now, I do want to make it clear that I’ve noted others (including myself) managing to use multiple canvases (lightly) in a scene, without any seemingly majot detriment to performance. This is keeping in mind that performance is basically the primary reason touted as to why its best sticking to a single Canvas in a scene (the other reason being organization).

So, there are reasons (not relating to Canvas Groups) as to why you’d want to use multiple canvases, but I won’t be covering that here this time.

PHP Fatal Error Call to undefined function mysql_connect()

Its a brave new world these days with Ubuntu 16.04, PHP 7.0, and so many other new and exciting versions of software.

You’ve probably become frustrated trying to re-install the php mysql libraries or trying to get the mysql module loaded into Apache2. The truth is though, is that mysql_* functions are now defunct. There was still some backwards compatibility up until PHP 7.0, but now you’re forced into using the new libraries MySQLi or PDO_MySQL. Personally, I decided with a current project to transition using the MySQLi library as its the closest analogue to the original mysql library and requires less effort.

Get Top results in fuzzy matches with Python

There is usually some scenario that inevitably comes up for me every couple years where I need to see if a phrase or word matches comparably with another one. However, there is the unfortunate circumstance (especially when dealing with thousands and thousands of possible matches) that the best match is not always the correct match.

So I hacked together this basically ugly set of functions to ultimately do one thing, return the top 3 results and their match percentage.

PHP Function to check URL for 404

I found myself writing up some code for a website application that needed to display a slider of images for different inventory. Now, there is a ridiculous amount of inventory (thousands and thousands) and the images are not stored in a DB. Likewise, not all of them were made equal (read: some inventory has alot of pictures, some have none, and there are many in between).

Now, also interestingly enough, the images are stored on a separate server.. so a simple file check was out of the question. This left me with using a display program that was either forced to only display a few pictures so that most of them would not hang upon not being able to find inventory_xxxx.jpg

To solve this situation I had to put together this simple PHP function that simply returns a Boolean, true if the link is valid, false if some error is encountered instead. Of course, that may seem a little backward, so here is a slightly modified version that simply “checks the url for a 404 error code” and return false if it does, otherwise true.

function checkurl($url)
    // Simple check
    if (!$url)
        return FALSE;

    // Create cURL resource using the URL string passed in
    $curl_resource = curl_init($url);

    // Set cURL option and execute the "query"
    curl_setopt($curl_resource, CURLOPT_RETURNTRANSFER, true);

    // Check for the 404 code (page must have a header that correctly display 404 error code according to HTML standards
    if(curl_getinfo($curl_resource, CURLINFO_HTTP_CODE) == 404)
        // Code matches, close resource and return false
        return FALSE;
        // No matches, close resource and return true
        return TRUE;

    // Should never happen, but if something goofy got here, return false value
    return FALSE;

Ideally, a better version would probably be a container function for a similar function which actually return the error codes or a NULL/FALSE value for a URL which returns no code.

For my purposes, this works perfectly and I make sure that the URLs I am checking against are located on a server where I control whether or not the 404 page send a correct 404 header back to the client.

Either way, enjoy and I hope its of use.

Unpacking Packed JavaScript Code

I’m sure if you are reading this, you too, as I have many times, come across packed JavaScript code that you needed either to check for maliciousness, modification, curiosity, or perhaps even something more sinister. Don’t judge me, I won’t judge you. Either way, you’ve probably had the same cringing look on your face the first time you saw this.

So, of course, I went about to figure out how to decipher, unscramble, or generally “decrypt” this annoyance. I’ve come across several methods while surfing the Internet, and I’d like to share what I’ve found.

As there are many different methods for JS packing, your mileage may vary greatly on the usefulness of the functionality here for unpacking. However, there are only so many ways to skin a cat and invariably most people have their code packed with the same method.

There are several ways to go about unpacking the code, and I’ll go ahead and list my quick and dirty favorites.

Method 1

The following method (by the guys at, of course their code needs to be decoded itself by looking at their reformat.js

function unpack()
    var p = G('txtPacked').value, c="";
    if (p != "")
        c = p;
        if (/eval(+function(/.test(c))
            var _e = eval;
            var s = "eval = function(v) { c = v; };" + c + "; eval = _e;";
        c = R(c,{indent_size: 1, indent_char: 't'});

    G('txtUnpacked').value = unescape(c);

Method 2

Another method supposed is to replace the eval() function call with a document.write() call




Of course, that is just enough to get you started, but it was enough for me, and I hope it helps out others. Good luck, happy hunting & happy hacking!

PHP Function in_array_by_id Search an array for an elements location or index

It seems crazy that there isn’t a function that already does this very simple task, namely, search an array for an element, and return its index (i.e. location) in that array.

  • in_array() will tell you if the element is in the array, but not where it is.
  • search_array() will search an associative array, but not a normal array.

So here is an example array with 7 string elements and what I want to be able to do.

> $myarray = array('Home', 'Control Panel', 'Members', 'Todays Figures', 'History', 'Listing', 'Add New Offer');
> echo in_array_by_id($myarray, 'Control Panel');

We passed two variables to our currently non-existent function in_array_by_id(). The array being searched and the element whose index we are search for (i.e. the proverbial needle in the haystack) respectively.

So I put together this sadly simple function:

 function in_array_by_id($array, $needle)
     $array_index = 0;
     foreach ($array as $element)
         if ($needle == $element)
              return $array_index;
     return NULL; 

As you can see, it returns a NULL value if the element is not found. So when doing checks you’ll want to remember to use the !== or === since you will be dealing with return values of 0 when the element is the first in the array.

Resolving Prototype Scriptaculous jQuery Conflictions with noConflict() Example

There is a good chance if you are reading this, you were under the same problem I myself had a short while ago…

You’re using Scriptaculous or something else built on top of Prototype and everything works fine when one fine day or hour, you decide you want to incorporate a widget or some code that uses jQuery.

So you do what I did, search around only to have people mention with a high and mighty, auspicious sounding response that the answer to all your problems, the magical cure-all for your what ails ya:


Of course they mention that all you have to do is “call this code” after importing the jquery script.. and possibly that you should call it like this ‘$.noConflict();’ or perhaps ‘jQuery.noConflict();’ or laughingly ‘$jQuery.noConflict();’

Some of the smarter (but no more helpful) ones tell you correctly to use assign the noConflict to a variable

like so:
$var = jQuery.noConflict();

Yet they then expect you to just know what to do from there. Great. Thanks. So you spend a couple hours thinking that maybe if you call the statement before the script is imported or right after or before that one or after that one, and then you start to change some of the references in your code.

No luck?

The thing is that all references to $ need to be changed.

Let’s go over an example. I was using a script for a neat little widget on a site that I was working on and it sat on top of Scriptaculous (and of course Prototype). When I dropped in the jQuery code… things went all to hell.

Courage Wolf Says its Better to Have Tried and Failed than to Never Try At All
He may be right, but we're not going to fail this time!

The Scriptaculous is not important, we do not have to make any changes to any of that code at all to get your new jQuery code to work. In my example I dropped in a modalbox, one of my favorites called “Sexylightbox“.

I placed my new modalbox code after my old code.

It required these lines to work:

Import/Src these scripts:


Then it also needed to be initialized:

<script type=”text/javascript>


SexyLightbox.initialize({color:’black‘, dir: ‘../../images/sexyimages‘});


Then I had to decide what to name my noConflict variable.. in this case I decided to go with $sexy.

So I changed


<script type=”text/javascript>


SexyLightbox.initialize({color:’black‘, dir: ‘../../images/sexyimages‘});




<script type=”text/javascript>


SexyLightbox.initialize({color:’black‘, dir: ‘../../images/sexyimages‘});


This is just the first step! I made sure to edit sexylightbox.v2.3.jquery.js and I added in this line to the top of the file:

$sexy = jQuery.noConflict();

Then, I completed it with my finish move and in my editor VI I replaced every instance of the $ character with the $sexy string using a global search and replace command while in Escape mode. If you’re more of the GUI type and using BlueFish or SlickEdit or something else, then you should have a “Replace” and then “Replace All Instances of” option under the Find menubar option.

Then as crazy as it may sound, everything just started working perfectly.

The important thing to keep in mind is that every single instance of where jQuery code is using the $, you have to replace it with the new variable you’ve created with the noConflict function. I wish someone had spelled it out that simply for me.. would have saved me hours of wasted time and frustration.

Converting XML to Associative Array in PHP

Sometimes there are situations where I have had code that is expecting an Associative Array with its corresponding values to deal with. However, as can often stand the case when propagating over to XML, sometimes its not possible (or digitally healthy) to convert everything all at once and I end up in a situation where I have all my data in single layer XML objects but need to interact with it on an associate array level.

So, as a quick to fix I wrote this small function entitled xml2AssArray() to deal with the children of a single layer XML object and turn it into an array with the children’s names used as the key-names of the array.

function xml2AssArray($xmlobj)
    $assarray = array(); // Initialize the Array
    // Loop through the XML object's children
    foreach ($xmlobj->children() as $child)
        // Assign the childs name as the key for the next entry while assigning the value itself as well
        $assarray[$child->getName()] = $child;
    return $assarray; // Return the new Array

Let’s take this XML object (called $myxml which we create using SimpleXML) for example:

<?xml version="1.0"?>
    <FullName>Israel Smith</FullName>

When we run it through our new function, the array that is returned, is now an associate array:

> $myarray = xml2AssArray($myxml);
> echo $myarray['FullName'];
Israel Smith


PHP Simple Outbound Email API Library

On occasion I find it necessary on a project to setup my mini library for outbound email. I may not need a full set of functionality like the super large libraries (nor do I want the bloat), however, I do have some basic (semi-advanced) features as a requirement.

1. Sending an E-mail should be as Simple as 1 function call
2. Normal Text Mail Support
3. HTML Mail Support
4. Attachment Support

My “email” function which I’ve aptly named “email” can be used like thus:

For a simple E-mail Message:
email($to, $subject, $text_message);

For an E-Mail with both Text and HTML:
email($to, $subject, $text_message, $html_message);

For an E-Mail with just text and an Attachment:

email($to, $subject, $text_message, NULL, $attachment);

Lets go over the file in 3 separate parts, the global variables/definitions whatever you’d like to call them, support function, and the main function.

Global Variables:

// Globals
$__FROM_NAME__ = "Company Name";
$__FROM_ADDR__ = "";

// MIME Types
$MediaTypes = array();
// Application Types
$MediaTypes['js']  = 'application/javascript';
$MediaTypes['ogg'] = 'application/ogg';
$MediaTypes['pdf'] = 'application/pdf';
$MediaTypes['ps']  = 'application/postscript';
$MediaTypes['zip'] = 'application/zip';
// Audio
$MediaTypes['mp3'] = 'audio/mpeg';
$MediaTypes['wma'] = 'audio/x-ms-wma';
$MediaTypes['wax'] = 'audio/x-ms-wax';
$MediaTypes['wav'] = 'audio/vnd.wave';
// Image
$MediaTypes['gif']  = 'image/gif';
$MediaTypes['jpg']  = 'image/jpeg';
$MediaTypes['jpeg'] = 'image/jpeg';
$MediaTypes['png']  = 'image/png';
$MediaTypes['svg']  = 'image/svg+xml';
$MediaTypes['tiff'] = 'image/tiff';
$MediaTypes['ico']  = 'image/';
// Text
$MediaTypes['css']  = 'text/css';
$MediaTypes['csv']  = 'text/javasccsvript';
$MediaTypes['html'] = 'text/html';
$MediaTypes['txt']  = 'text/plain';
$MediaTypes['xml']  = 'text/xml';
// Video
$MediaTypes['mpg']  = 'video/mpeg';
$MediaTypes['mp4']  = 'video/mp4';
$MediaTypes['qt']   = 'video/quicktime';
$MediaTypes['wmv']  = 'video/x-ms-wmv';
// Other
$MediaTypes['rar']  = 'application/x-rar-compressed';
$MediaTypes['gz']   = 'application/x-gzip-compressed';

You should change __FROM_ADDR__ and __FROM_NAME__ to whatever fits into your project. Also, feel free to add to the MediaTypes array with any and all mime types you think you’ll be using / running across on your project.

We’ll move onto the only support function which I’m calling “createAttachment”. It takes filepath (e.g. /www/whatever/file.exa or ./file.exa) and then determines the filename, filetype and after reading in the file, stores all three bits of information into an associate array that we can use when we call the email() function.

Support Function

// Function: createAttachment()
// Description:
//        Takes a string which points at the file location and creates an
// array to be used by the email() function's $attachment parameter.
// Returns: Array (3 parts; name of the file, mime type, and file contents)
function createAttachment($filename)
    global $MediaTypes;
    $attachment = array();
    $filelocation   = explode('/', $filename);
    $attachment['filename'] = $filelocation[sizeof($filelocation) - 1];
    $filenameparts  = explode('.', $filename);
    $extension      = $filenameparts[sizeof($filenameparts) - 1];
    if ($MediaTypes[$extension])
        $attachment['filetype'] = $MediaTypes[$extension];
    $attachment['file'] = file_get_contents($filename);

    return $attachment;

Simple enough for my purposes, haven’t run across any problems yet.

Now we move onto the main function: email(). it will automatically generate the boundary types and set all of the appropriate headers for an e-mail. I know there are other header(s), and types, however in all my project I’ve never come across the need to use anything other than what this function produces.

If a message (of any type) or an attachment has been passed along, it will appropriately use them respectively and send out the e-mail using your hosts default PHP associated sendmail program/server.

Main Function

// Function: email()
// Description:
//        Takes self-explanatory parameters in order to send an email.
//        $to           - String (An email address)
//        $subject      - String (The Subject line)
//        $text_message - String (The body of the E-Mail Message)
//        $html_message - String (The body of the HTML E-Mail Message)
//        $attachment   - Non-Alphanumeric String (File contents)
// See also: createAttachment()
// Returns: Boolean (Based on Success)
function email($to, $subject, $text_message = NULL, $html_message = NULL, $attachment = NULL)
    // Initialize Message String
    $message = '';

    // Boundary Section
    // So we know where to look for the start of the data
    $boundary = uniqid("Part_"); 
    $boundary = '----=_'.$boundary;

    // Headers Section
    $headers  = 'To: ' . $to . "rn";
    $headers .= 'From: "'.$__FROM_NAME__.'" <'.$__FROM_ADDR__.'>' . "rn";
    $headers .= 'MIME-Version: 1.0' . "rn";
    $headers .= "Content-Type: multipart/alternative;rn".
            "        boundary="$boundary"rnrn";

    // Plain Text Message
    if ($message)
        $message .= "--$boundaryrn".
                "Content-Type: text/plain; charset=UTF-8rn".
                "Content-Transfer-Encoding: 7bitrnrn";
        $message .= $text_message;
        $message .= "rnrnrnrn";

    // HTML Message
    if ($html_message)
        $message .= "--$boundaryrn".
                    "Content-Type: text/html; charset=UTF-8rn".
                    "Content-Transfer-Encoding: 7bitrnrn";
        $message .= $html_message;
        $message .= "rn";

    // Attachment
    // $attachment should be an array with the
    // filename, filetype, and file entries.
    if ($attachment)
         $message .= "--$boundaryrn".
                     "Content-Type: ".$attachment['filetype']."; name=".$attachment['filename']."rn".
                     "Content-Disposition: attachment; filename=".$attachment['filename']."rn".
                     "Content-Transfer-Encoding: base64rnrn";
         $message .= chunk_split(base64_encode($attachment['file']));
         $message .= "rnrnrnrn";

    if (@mail($to, $subject, $message, $headers))
        return true;
        return false;
    return true;

In theory you should be able to plug this code in and use right away, although having a general understanding of email construction and also on subjects like the 5-point SPAM detection scale (usually dictated by advanced anti-spam products like spamassassin) would be good.

Likewise, you'll notice there isn't much in the way of error-catching, nor multiple attachments.. go ahead and add that in if you please. (If you do, please feel free to share them on here or with me!)