Adding floats together with commas and decimal places 

January 12th, 2011

Someone contacted me about adding some numbers together with comma’s and dots within there values, here is the email via the contact me page.

“Please I need a javascript code that can enable me add two or more numbers containing dot(.) and/or comma (,) together. For example, 122.34 + 233.56. Or/And 233,239.34 + 323,322.44. Thanks in advance.”

Here is the code that will accomplish the request.

<html>
<script type="text/javascript" >
       function load()
       {
               var value1="233,122.34";
               var value2="233.56";
               alert(parseFloat(value1.replace(",",""))+parseFloat(value2.replace(",","")));
       }
 
</script>
<body onload="load()">
</body>
</html>

The main part is the parseFloat and replacing the “,” with nothing “” to remove the none float characters via the object replace method.

CKEditor – adding custom style sheet 

December 10th, 2010

Within the CKEditor editor you can add in custom style sheets to assist with styling of the content within the editor and here is how you do it

CKEDITOR.config.contentsCss = '/css/mycssfilename.css' ;

After you have created the instance of the CKEditor you just need to add in to the configuration the contents cascading style sheet file.

CKEditor – auto save 

December 10th, 2010

A follow on from the previous post CKEditor custom dialog you can auto save the content with sending a AJAX call to another page that will save the content and also give back a updated time of that content saved.

I created a function called autosave(), that will call itself every 20 seconds (20000 milliseconds). This will get the data (getData()) from the CKEditor instance called content and then go some JQuery to do the actual AJAX function which in-turn calls the url autosave.php (can be any backend page that will deal with saving the data) and once the backend page has completed then update the HTML element with the ID of lastsavetime to the new time that is returned from the webpage.

function autosave()
{
   var t = setTimeout("autosave()", 20000);
 
  var content = escape(CKEDITOR.instances.content.getData());
   if (content.length > 0)
   {
       $.ajax(
       {
           type: "POST",
           url: "autosave.php?method=saveCKEditor",
           data : "content="+content,
           cache: false,
           success: function(message)
           {
               $("#lastsavetime").empty().append("Last saved : "+message);
           },
       });
   }
}
$(document).ready(function(){
    autosave();
}); ";

CKEditor – custom dialog 

December 10th, 2010

The CKEditor is a great WYSIWYG and the best thing is that you are able to customize the interface to have buttons on the toolbars, here is a way that I created a custom button with custom image attached to it.

The editor is created with

var editor = CKEDITOR.replace( 'Content');

So from now on in the variable editor is linked to the CKEditor instance, to setup the plugins to load when the CKEditor is created you call the pluginsLoaded function

 editor.on( 'pluginsLoaded', function( ev )
         {
           if ( !CKEDITOR.dialog.exists( 'statisticsDialog' ) )
                 CKEDITOR.dialog.add( 'statisticsDialog','/statistics.js');
           // Register the command used to open the dialog.
           editor.addCommand( 'statisticsAddCmd', new CKEDITOR.dialogCommand('statisticsDialog' ) );
           editor.ui.addButton( 'Statistics',
                    {
                        label : 'Statistic',
                        command : 'statisticsAddCmd',
                        icon : '/statistics_small.png',
                    } );
});

The first part will check to make sure that there is not dialog already created with the same name, and if not then load the javascript file that is the custom built dialog. The second part is adding the command (the button clicked) to be linked to the custom dialog, and the third part is to add the actual button to the user interface (editor.ui). The addButton function links to the command to bring up the custom dialog.

Here is the custom dialog code that will be called when the user interface button is clicked.

CKEDITOR.dialog.add( 'statisticsDialog', function( editor )
{
      // Load data asynchronously.
       return {
               title : 'Pick a statistic',
               minWidth : 400,
               minHeight : 200,
               onOk : insertOntoEditor,
               contents : [
                       {
                               id : 'tab1',
                               label : 'First Tab',
                               title : 'First Tab',
                               elements :[
                                       {  id : 'graphselect',
                                               type : 'select',
                                               items : [ ["option1", "link to image"] ] ,
                               }]
                       }
               ]
       };
} );

The dialog, will load up a screen and have a one drop down box that will allow the user to choose from the options (will you need to insert more options, or dynamic created options if you wanted to) and once the OK button is clicked (onOK) it will call this function below

function insertOntoEditor()
{
       elem = this.getContentElement('tab1','graphselect');
       value = elem.getValue();
       if (value != -1)
       {
               var writer = new CKEDITOR.htmlWriter();
               var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<img src="http://'+document.domain+elem.getValue()+'"/>' );
               fragment.writeHtml( writer )
 
               // need to wrap up the graph image insertion into the ckeditor
               CKEDITOR.instances.Content.insertHtml(writer.getHtml());
       }
}

This will basically insert some code into the CKEditor from the drop down box, the “link to image” you will need to insert a link for the insertion.

CKEditor – Custom upload dialog 

December 10th, 2010

The great WYSIWYG editor called CKEditor allows you to do a custom file upload, so that you can handle where the file is stored and also you can do your database extra inserts for example.

To start with you have to tell the CKEditor where to post the file uploaded to custom built page

var editor = CKEDITOR.replace( 'Content',{ filebrowserUploadUrl :'/custom.imageuploader.php'});

Where the custom.imageuploader.php is the actual php page that will deal with the custom page, can be done in any other language if required. In the above code, the ‘Content’ is the textarea to change to a CKEditor WYSIWYG.

Here is a basic php page that you will need to alter to store the $_FILES["upload"] into the place where you want to store and do any database code to link to the resource that you are uploading, but the bit underneath that you need to have, this will tell the CKEditor what to do after your PHP code has stored the file, the CKEditoFuncName, is required (but passed in) to tell the CKEditor what function to call after the upload has happened, the $wherestorage, is where the actual file is so that the WYSIWYG can show the image and any $message that may help the CKEditor user for any error reports.

<?php
// the files are stored within the upload part of the $_FILES 
$_FILES["upload"];
?>
<html>
<body>
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(
   <?php echo $_REQUEST["CKEditorFuncNum"].",\"".$wherestorage."\",\"".$message."\"";?>
);
</script>
</body>
</html>
?>

Custom wordpress page on a new URL 

September 6th, 2010

I liked to have the idea of having google search my site and have it displayed within my current site design, and since wordpress allows to have action hooks that allow you to interrupt the present flow of generating the wordpress outputted page.

So to have the google searched and display results within the style that I am using I first needed to create a plugin, if you create a file within your

wordpress base directory/wp-content/plugins/codingfriendsgooglesearch

within the file below within the that directory created above, (I saved this file as googlesearch.php, but it does not matter as long as it is a .php file with the plugin details at the top of the file between the /*… */ parts.

<?php
/*
Plugin Name: Google search page
Plugin URI: http://www.codingfriends.com
Donate link: http://www.codingfriends.com
Description: Google search page
Version: 0.1
Author: Ian Porter
Author URI: http://www.codingfriends.com
*/
 
function get_requested_uri() {
       $requesturi = $_SERVER['REQUEST_URI'];
       if (substr($requesturi, -1)!="/") {
               $requesturi = $requesturi."/";
       }
       preg_match_all('#[^/]+/#', $requesturi, $matches);
       $uri = $matches[0];
       return $uri;
}
 
function google_search_display() {
       $uri = get_requested_uri();
       if ($uri[0]=='googlesearch/') {
               include(TEMPLATEPATH . '/googlesearch.php');
               exit;
               }
}
 
add_action( 'template_redirect', 'google_search_display');
 
?>

What basically happens is when the template_redirect is called, this is when most of the processing of the page has already been done, and we are about to display the requested page from the blog, well in this case I would like to add function call to google_search_display, which is within this same file, and what it does is to search for ‘googlesearch/’ within the first part of the URL requested e.g.

http://www.codingfriends.com/googlesearch/

and if so display the googlesearch.php php file from within the templates directory, and here is my googlesearch.php file, and it displays the content within the div tag with cse-search-results, with the present style around the google search results.

<?php get_header(); ?>
<div id="content" class="narrowcolumn" role="main">
<div id="cse-search-results"></div>
<script type="text/javascript">
 var googleSearchIframeName = "cse-search-results";
 var googleSearchFormName = "cse-search-box";
 var googleSearchFrameWidth = 795;
 var googleSearchDomain = "www.google.co.uk";
 var googleSearchPath = "/cse";
</script>
<script type="text/javascript"
src="http://www.google.com/afsonline/show_afs_search.js"></script>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

wordpress is really nice where you are able to alter the present execution process.

CS107 – Assignment 2 – Six degrees 

August 25th, 2010

This is assignment 2 from a older CS107 course, because the latest course work is held on a UNIX server which in turn you need access to!!.. kinder does not help when you do not have access too!!.. Here is where I got the files from cs107 link, there is a zip file at the bottom of that page which has all of the assignments and handouts etc.

I have included the PDF of the assignment in the above file link, but since the actual assignment includes a few massive files you can download them from the CS107 link of the whole course work that I am using from the cs107 link.

As a note, within my linux setup, I need to setup the environment variable to tell the program to use a Linux little endian by

export OSTYPE=linux

Basically the assignment is to load in cast/movie details (which the base code from the assignment already does for use) and then we are needed to pull out the data from the structure of the file, the structure of the actors is (as taken from the PDF file)

  1. The name of the actor is laid out character by character, as a normal null-terminated C-string. If the length of the actor’s name is even, then the string is
    padded with an extra ‘\0′ so that the total number of bytes dedicated to the name is always an even number. The information that follows the name is most
    easily interpreted as a short integer, and virtually all hardware constrains any address manipulated as a short * to be even.
  2. The number of movies in which the actor has appeared, expressed as a two-byte short. (Some people have been in more than 255 movies, so a single byte just
    isn’t enough.) If the number of bytes dedicated to the actor’s name (always even) and the short (always 2) isn’t a multiple of four, then two additional ‘\0′’s
    appear after the two bytes storing the number of movies. This padding is conditionally done so that the 4-byte integers than follow sit at addresses that are
    multiples of four.
  3. An array of offsets into the movieFile image, where each offset identifies one of the actor’s films.

with the base of the actors information containing a 4 byte integer value of how many actors are in the block of data and then the following values are in 4 bytes again with the offsets into the block of where the actual data is stored.

So the method that you need to write is to pull in that data from the actorInfo block of memory, and here is my version of it, the method is getCredits and takes the cast member (player) as the method will insert all of the films that cast as been in.

bool imdb::getCredits(const string& player, vector<film>& films) const
{
    int numberOfActors,data;
    char *actorName;
    memcpy(&numberOfActors,(int*)actorInfo.fileMap, 4);
    // loop though the number of actors
    for (int i =2; i < numberOfActors; i++)
    {
        memcpy(&data, ((int*)actorInfo.fileMap)+i,4);
        actorName = ((char*)actorInfo.fileMap + (data));
        if (strcmp(actorName,player.c_str())==0)
        {
            // find the padding lengths
            int actorNameLength = strlen(actorName)+1;
            int movieNumberPad = actorNameLength % 2;
            int fourOffset = (actorNameLength + movieNumberPad + 2) % 4;
            short numberMovies;
            memcpy(&numberMovies,((short*)((char*)actorInfo.fileMap + data + actorNameLength + movieNumberPad)),2);
            for (int j=0; j < numberMovies; j++)
            {
                int movieOffset;
                film theFilm;
                memcpy(&movieOffset, ((int*)((char*)actorInfo.fileMap + data + actorNameLength + movieNumberPad + (j*4) + fourOffset + 2)),4);
                theFilm.title = ((char*)movieInfo.fileMap + movieOffset);
                theFilm.year = 1900 + (int)((char*)movieInfo.fileMap + movieOffset + theFilm.title.length() + 1)[0];
                films.push_back(theFilm);
            }
            return true;
        }
    }
    return false;
}

The block of memory for the movie block is similar to the actor block and as taken from the PDF attached file here is the details of that block of memory,

  1. The title of the movie, terminated by a ‘\0′ so the character array behaves as a normal C-string.
  2. The year the film was released, expressed as a single byte. This byte stores the year – 1900. Since Hollywood is less than 28 years old, it was fine to just store the year as a delta from 1900. If the total number of bytes used to encode the name and year of the movie is odd, then an extra ‘\0′ sits in between the one-byte year and the data that follows.
  3. A two-byte short storing the number of actors appearing in the film, padded with two additional bytes of zeroes if needed.
  4. An array of four-byte integer offsets, where each integer offset identifies one of the actors in the actorFile. The number of offsets here is, of course, equal to
    the short integer read during step 3

And once again like the actor block there is a 4 byte integer value that stores how many movies within the block of memory with the next 4 bytes storing the offset into that block of memory, here is my implementation of the method getCast that will take a movie as a parameter and find all of the cast (players) and return that vector list.

bool imdb::getCast(const film& movie, vector<string>& players) const
{
    int numberOfMovies, data;
    film theFilm;
    char *movieName;
    memcpy(&numberOfMovies, (int*)movieInfo.fileMap, 4);
    for (int i = 1; i < numberOfMovies; i++)
    {
        memcpy(&data, (int*)movieInfo.fileMap+i,4);
        movieName = ((char*)movieInfo.fileMap + data);
        theFilm.title = movieName;
        theFilm.year = 1900 + (int)((char*)movieInfo.fileMap + data + theFilm.title.length() + 1)[0];
        if (movie == theFilm)
        {
            int paddingFirst = theFilm.title.length() % 2;
            // paddingSecond = paddingfirst + length of title + 2 (year + \0) and then + 2 for the actors number
            int paddingSecond = (paddingFirst + theFilm.title.length() +2 + 2) %4;
            short numberOfActors;
            memcpy(&numberOfActors, (short*)((char*)movieInfo.fileMap + data + theFilm.title.length() + 2 + paddingFirst),2);
 
            // get the actors offsets and insert into the players list
            for (int k =0; k < numberOfActors; k++)
            {
                int offset;
                memcpy(&offset, ((int*)((char*)movieInfo.fileMap + data + strlen(movieName) + 2 + paddingFirst + 2 + paddingSecond + (k*4))), 4);
                players.push_back((char*)actorInfo.fileMap + offset);
            }
            return true;
        }
    }
    return false;
}

After you have sorted out reading in the information you have to find out if there is a link from actor1 to another actor2 (six degrees) with linking them together the cast that they have been with with the films that they have stared in, so here is my breath search setup as taken from the assignment.

/**
  * @param actor1 - first actor to look for
  * @param actor2 - second actor to look for to link to the first
  * @param db - the imdb database loaded
  */
static bool generateShortestPath(const string& actor1, const string& actor2, const imdb& db)
{
    list<path> partialPaths;
    set<string> previouslySeenActors;
    set<film> previouslySeenFilms;
 
    path actorsFirst(actor1);
    partialPaths.push_front(actorsFirst);
 
    while (!partialPaths.empty() && partialPaths.front().getLength() <=5)
    {
        path frontPath = (path)partialPaths.front();
        partialPaths.pop_front();
        vector<film> actorsFilms;
        db.getCredits(frontPath.getLastPlayer(), actorsFilms);
        for (int filmI=0; filmI < actorsFilms.size(); filmI++)
        {
            film filmData;
            filmData = actorsFilms.at(filmI);
            // not seen the film before
            if (previouslySeenFilms.find(filmData) == previouslySeenFilms.end())
            {
                previouslySeenFilms.insert(filmData);
                vector<string> movieCast;
                db.getCast(filmData, movieCast);
                for (int castI =0; castI < movieCast.size(); castI++)
                {
                    // if not already seen
                    if (previouslySeenActors.find(movieCast.at(castI)) == previouslySeenActors.end())
                    {
                        previouslySeenActors.insert(movieCast.at(castI));
                        path newfrontPath = frontPath;
                        newfrontPath.addConnection(filmData, movieCast.at(castI));
                        if (movieCast.at(castI) == actor2)
                        {
                            cout << newfrontPath << endl;
                            return true;
                        } else
                            partialPaths.push_back(newfrontPath);
                    }
                }
            }
        }
    }
    return false;
}

You can do some speed ups from the assignments PDF file, but they are mainly the icing on the cake and I thought that I would assignment 3 first, so if I do the extras for this I will update this post.

But this was a fun assignment, because of the memory block and finding out the data within it.