Sunday, June 12, 2016

A better way to split a node in a trie

This is the previous function for splitting a branch in the trie.


static typeNode* SplitBranch(typeNode* parent,unsigned long index)
  {
  typeNode*     working;
  char*         data;
  unsigned long I;

  if ((index < 1) || (index >= parent->Length))
    return 0;

  working = CreateBranch(0,parent->Data + index,parent->Length - index);
  if (working == 0)
    return 0;

  working->Child = parent->Child;
  parent->Child = working;

  data = (char*)malloc(index);
  if (data == 0)
    return 0;

  for (I = 0;I < index;I++)
    data[I] = parent->Data[I];

  free(parent->Data);

  parent->Length = index;
  parent->Data   = data;

  return working;
  }

This is a bit complicated. We first create a new node for the back end of the split point, that part is fine. But then we go and allocate a whole new buffer for the front end, fill it up with the front part of the split buffer, and then replace the node string with the new buffer. The problem with this besides too much code is, what if we want to improve the create string function later.


static typeNode* SplitBranch(typeNode* parent,unsigned long index)
  {
  typeNode*     node1;
  typeNode*     node2;
  char*         data;
  unsigned long I;

  if ((index < 1) || (index >= parent->Length))
    return 0;

  node1 = CreateBranch(0,parent->Data,index);
  if (node1 == 0)
    return 0;

  node2 = CreateBranch(0,parent->Data + index,parent->Length - index);
  if (node2 == 0)
    return 0;
 
  free(parent->Data);

  parent->Length = node1->Length;
  parent->Data   = node1->Data;

  free(node1)

  node2->Child = parent->Child;
  parent->Child = node2;

  return working;
  }

This is the improved version of the code. We have not really changed much, except that it is a lot easier to read. What we have done here is made the code simpler and more robust by pushing all the hard work to earlier functions. Instead of creating the first part of the split buffer int a second function, it is now done in the one function that is dedicated to that one thing. If we want to change something later, we can just change create branch and not have to worry about too many other things.

  node1 = CreateBranch(0,parent->Data,index);
  if (node1 == 0)
    return 0;

  node2 = CreateBranch(0,parent->Data + index,parent->Length - index);
  if (node2 == 0)
    return 0;
In this part of the code we just create two new nodes that contain the two parts of the string we are splitting. Because of the way a trie works, we have to keep the original node and discard the first node.

  free(parent->Data);

  parent->Length = node1->Length;
  parent->Data   = node1->Data;

  free(node1)

  node2->Child = parent->Child;
  parent->Child = node2;
In this part, we free the original string buffer of the parent node, then replace it with the buffer of the first node we have just created. Then we free the first node. We only created it a in order to get a new buffer. Doing that by calling create branch is a lot easier and safer than doing it manually inside a new function. As I said before, it is a good habit to keep memory operations isolated in a few places. In fact, even freeing the node and the data here would be a mistake, but it is fine because all the operations are isolated inside the CreateBranch and SplitBranch functions.

The next two line do something a bit complicated and not really obvious. The nodes inside a trie form strings with their children. The parent is the first part of the string, and each child is part of a separate string. When we split a node, we still need to have a single string. This is why all the children that the split node had before must be moved to the new node we have created, because the parent node and the new node are a single prefix for all the nodes that the parent had before. This means that after the split, nothing has changed. The next to last line in the code above gives all the children of the parent to the new node, and the last line sets the new node as the parent's only child. Later, after the split, the parent will receive new children, that is why we need to split the node.

This is not quite clear yet, but I will try to make a visual explanation later.

Simple JavaScript Canvas Animation with source code

A quick and simple canvas example. I am going to do some canvas animation later, I am going to use this to set up the basics.


<html>
<head>
  <title>Bouncing balls with gravity</title>
</head>
<body>
<canvas id="canvas" width="640" height="480">
<script>
  var canvas  = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  var width   = canvas.width;
  var height  = canvas.height;
  var maxspeed = 5;
  var particlecount = 20;
  var gravity = -1;
  var density = 0.5;

  function particle(x, y, radius, color)
    {
this.tx = x;
    this.ty = y;
    this.vx = 0;
    this.vy = 0;
this.color = color;
this.radius = radius
this.mass = radius * density;
};

  particle.prototype.draw = function()
    {  
    context.beginPath();
    context.arc(this.tx, this.ty, this.radius, 0, 2 * Math.PI, false);
    context.fillStyle = this.color;
    context.fill();
    };

  particle.prototype.move = function()
    {
    this.tx += this.vx;
this.ty += this.vy;
    };

  particle.prototype.limit = function(maxspeed)
    {
    if (this.vx > +maxspeed)
      this.vx = +maxspeed;
    if (this.vx < -maxspeed)
      this.vx = -maxspeed;
    if (this.vy > +maxspeed)
      this.vy = +maxspeed;
    if (this.vy < -maxspeed)
      this.vy = -maxspeed;
    };

  particle.prototype.clip = function(left, top, right, bottom)
    {
    if (this.tx < left + this.radius)
      {
      this.tx = left + this.radius;
      this.vx = 0 - this.vx;
      }
    if (this.ty < top + this.radius)
      {
      this.ty = top + this.radius;
      this.vy = 0 - this.vy;
      }
    if (this.tx > right - this.radius)
      {
      this.tx = right - this.radius;
      this.vx = 0 - this.vx;
      }
    if (this.ty > bottom - this.radius)
      {
      this.ty = bottom - this.radius;
      this.vy = 0 - this.vy;
      }
    };

  particle.prototype.gravitate = function(target)
    {
    var dx = target.tx - this.tx;
    var dy = target.ty - this.ty;
    var distance = Math.sqrt(dx * dx + dy * dy);
if (distance > (this.radius + target.radius))
 {
      var force = (gravity * target.mass * this.mass) / (distance * distance);

      this.vx += (dx / distance * force) / this.mass;
      this.vy += (dy / distance * force) / this.mass;

      target.vx -= (dx / distance * force) / target.mass;
      target.vy -= (dy / distance * force) / target.mass;
      }
    };

  particle.prototype.interact = function(target)
    {
    var dx = target.tx - this.tx;
    var dy = target.ty - this.ty;
    var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < (this.radius + target.radius))
 {
 var intersect = ((this.radius + target.radius) - distance);

      this.vx += (-dx / distance * intersect * density) / this.mass;
      this.vy += (-dy / distance * intersect * density) / this.mass;

      target.vx += (dx / distance * intersect * density) / target.mass;
      target.vy += (dy / distance * intersect * density) / target.mass;
 }
}

  var particles = [];

  function init()
    {
    for (var i = 0; i < particlecount; i++)
      {
 var radius = Math.random() * 50 + 5;
 var color = Math.random() * 5;

 if (color < 1)
        color = "yellow";
 else
 if (color < 2)
        color = "cyan";
 else
 if (color < 3)
        color = "red";
 else
 if (color < 4)
        color = "magenta";
 else
 if (color < 5)
        color = "green";
 else
        color = "blue";
   
      particles[i] = new particle(Math.random() * width, Math.random() * height,radius,color);
      }
    };

  function drawframe()
    {
    requestAnimationFrame(drawframe);

    context.fillStyle = "black";
    context.fillRect(0, 0, width, height);

    for (i = 0;i < particlecount;i++)
 {
      for (j = i+1;j < particlecount;j++)
        {
particles[i].gravitate(particles[j]);
        particles[i].interact(particles[j]);
   }
 }

for (i = 0;i < particlecount;i++)
 {
      particles[i].clip(0,0,width,height);
      particles[i].limit(maxspeed);
      particles[i].move();
      particles[i].draw();
 }
    };

  init();
  drawframe();

</script>
</body>
</html>

Saturday, June 11, 2016

Converting a sixty four bit number into a string

This is one of the functions that I had the most trouble with, even though it is quite simple. The point here is to translate a sixty four bit number into a string using any base from two to sixty four.


long stringAppendInt64(typeString* str,unsigned long long value,long base)
  {
  static const char digits[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz-_";
  unsigned long     start,length;

  if ((base < 2) || (base > 64))
    return 0;

  start = str->Length;

  do
    {
    stringAppendCharacter(str,digits[value % base]);

    value = value/base;
    }
  while (value != 0);

  length = str->Length - start;

  stringReverseRange(str,start,length);

  return 1;
  }

long stringAppendInt64(typeString* str,unsigned long long value,long base)
This function takes a sixty four bit number, and appends a string with the text equivalent. The parameters are the string object, the number to be converted as a sixty four bit integer, and the base that we use to represent the number. The return value is just a Boolean value. I call it long because for some reason, my compiler does not like bool as value.

static const char digits[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz-_";
The first thing to notice after that is the digits array. In the video below, Tom Scott Explains how the YouTube video ID's use a sixty four bit number system with eleven digits. This code does not limit itself to eleven digits, it just converts any number you give it into a string, and the string is as long as it needs to be. Anyway, the characters used to represent the resulting number are, zero to nine, followed by uppercase A through Z, followed by lowercase a through z followed by two other characters. As it says in the video, the characters that YouTube uses are dash and underscore because that is what works best in URL's. If you want to change what symbols are used to build your number, just change the symbols, just make sure that there are enough of them. This function limits itself to sixty four, but you can just use any base you want up to infinity, or until you run out of symbols.

 if ((base < 2) || (base > 64))
    return 0;
The first thing the function does is check that the base is more than two and less than sixty four. A base of zero or one would not make any sense, and any base of more than sixty four would not work simply because we don't have enough symbols. If you don't understand what we mean by base with numbers, read this article on Wikipedia about Positional Notation to get the idea.

 start = str->Length;
 length = str->Length - start;
 stringReverseRange(str,start,length);
These three lines of code are important because of the way the string object is structured, they really have nothing to do with building the number string. We are appending the numbers to the end of an existing string. We also need to reverse the resulting string because of the way the math works. We need the start and length variables in order to know where the resulting numbers string is located inside the main string. The first line saves the current length of the string before we start adding digits, the second lines calculates how far we have gone into after we have added our digits. After that, the third line reverses that portion of the string. The reason we reverse is because we are subtracting digits out of the number starting with the least significant digits at the right, but we are adding characters to the string by starting at the left and going right. This results in the number being inverted. There is a way we could do this from left to right, but it would be slow and complicated.

 do
    {
    stringAppendCharacter(str,digits[value % base]);

    value = value/base;
    }
  while (value != 0);
This is the part were we actually convert the number into a string. First, the reason why it is a do while loop is for when the number we are converting is zero. In that case, we want to run through the loop at least once, otherwise nothing would be displayed. We just loop as long as the result is not zero. This method would work for negative numbers, but there is the problem of what to do with the minus sign. I don't want to include that here because with the various bases, that is best left with the client function to decide how to represent extra symbols like plus or minus signs as well as hexadecimal or bit filed markers. The math is, divide the number by the base, and use the remainder as in index into the list of symbols. Here we do the division twice, first with the modulo operator to get the remainder, and then again to set the value to the result of the division. I am wondering if there is a way to do this in one operation, I don't think there is. Each time we loop, the value last digit of the number is taken out. For example, with the number one hundred and twenty three in base ten, we would go through the loop three times. After the first time the digit to be printed would be three, and the value would become twelve. After the second loop the digit to be printed will be two, and the value will become one. And after the third loop , the digit we print will be one, and the value is now zero and the loop will not run again because it will hit the while part of the while loop. After all that we reverse the string to get it printed correctly and we are done. Note here that there is no way to know how long the final string will be. A number that is three digits long is bases sixty four may be dozens of digits long is base two, so make sure that there is enough space allocated before trying to print large numbers.

Main file for testing the Trie

This is the main file that I use to test my string builder and Trie classes.

#include "typestring.h"
#include "typetrie.h"

typeString   str;
typeNode     trie;
char         buffer[4096];
const char*  strings[] =  {
  "remove",
  "rename",
  "renumber",
  "repack",
  "repaint",
  "repay",
  "replace",
  "replay",
  "reread",
  "rerun",
  "resale",
  "reshape",
  "retell",
  "rethink",
  "retrace",
  "reword",
  "rewrite",
  "rethinking",
  "retracing",
  "rewording",
  "impatience",
  "imperfect",
  "impolite",
  "impossible",
  "impure",
  "inactive",
  "incorrect",
  "indefinite",
  "incident",
  "ant",
  "apple",
  "zebra",
  "cross",
  "rock",
  "cloud",
  "turtle",
  "rodent",
  "solar",
  "volume",
  "purple",
  "romeo",
  "overlord",
  "sequence",
  "virtue",
  "parent",
  "starlight",
  "source",
  "theory",
  "underworld" };

int main()
  {
  stringCreate(&str,4096);

  stringAppendCString(&str,"Hello World = ");
  stringAppendInt64(&str,92233736854775807,2);
  stringGetCString(&str,buffer,4096);
  printf("%s\n",buffer);

  stringSetLength(&str,0);
  stringAppendInt64(&str,92233720364775807,16);
  stringGetCString(&str,buffer,4096);
  printf("%s\n",buffer);

  stringSetLength(&str,0);
  stringAppendInt64(&str,92233720364775807,64);
  stringGetCString(&str,buffer,4096);
  printf("%s\n",buffer);

  trieCreate(&trie);
  int length = sizeof(strings) / sizeof(strings[0]);
  for (int I = 0;I < length;I++)
    trieInsertCString(&trie,strings[I]);
  trieDraw(&trie,0);

  return 1;
  }

Source code for a string builder class

This one is a string class. I should really call it string builder, but that name is just too long. At some point I am going to explain how each part of the code works, but I really don't feel like writing right now. I am including the full source code here just so I can refer to it later. None of these code files are really that good, they are just some quick stuff that I made without much thought.

#ifndef TYPESTRING_H
#define TYPESTRING_H

#include <stdlib.h>

#define STRING_MIN     1
#define STRING_MAX     4096

typedef struct
  {
  unsigned long Capacity;
  unsigned long Length;
  char*         Data;
  } typeString;

long stringCreate(typeString* str,unsigned long capacity);
long stringGetCString(typeString* str,char* buffer,unsigned long buffersize);
long stringSetLength(typeString* str,unsigned long length);
long stringSetCapacity(typeString* str,unsigned long capacity);
long stringReverse(typeString* str);
long stringReverseRange(typeString* str,unsigned long start,unsigned long length);
long stringAppendCharacter(typeString* str,char value);
long stringAppendCString(typeString* str,const char* value);
long stringAppendString(typeString* str,typeString* value);
long stringAppendInt64(typeString* str,unsigned long long value,long base);
long stringDestroy(typeString* str);

long stringCreate(typeString* str,unsigned long capacity)
  {
  char*  buffer;

  if (capacity < STRING_MIN)
    capacity = STRING_MIN;

  buffer = (char*)malloc(capacity);

  if (buffer == 0)
    return 0;

  str->Capacity = capacity;
  str->Length   = 0;
  str->Data     = buffer;

  return 1;
  }

long stringGetCString(typeString* str,char* buffer,unsigned long buffersize)
  {
  unsigned long I;

  I = 0;
  while ((I < str->Length) && (I < buffersize-1))
    {
    buffer[I] = str->Data[I];
    buffer[I+1] = 0;
    I++;
    }

  return 1;
  }

long stringSetLength(typeString* str,unsigned long length)
  {
  if (length > str->Capacity)
    return 0;

  str->Length = length;

  return 1;
  }

long stringSetCapacity(typeString* str,unsigned long capacity)
  {
  unsigned long I;
  char*         buffer;

  if (capacity == str->Capacity)
    return 1;

  if (capacity < STRING_MIN)
    capacity = STRING_MIN;

  buffer = (char*)malloc(capacity);

  if (buffer == 0)
    return 0;

  I = 0;
  while (I < capacity)
    {
    if (I < str->Length)
      buffer[I] = str->Data[I];
    else
      buffer[I] = 0;
    }

  free(str->Data);

  if (str->Length > capacity)
    str->Length = capacity;

  str->Capacity = capacity;
  str->Data     = buffer;

  return 1;
  }

long stringReverse(typeString* str)
  {
  unsigned long I,J;
  char          temp;
  I = 0;
  J = str->Length - 1;

  while (I < J)
    {
    temp = str->Data[I];
    str->Data[I] = str->Data[J];
    str->Data[J] = temp;

    I++;
    J--;
    }

  return 1;
  }

long stringReverseRange(typeString* str,unsigned long start,unsigned long length)
  {
  unsigned long I,J;
  char          temp;

  I = start;
  J = start + length - 1;

  if ((I < 0) || (J > str->Length))
    return 0;

  while (I < J)
    {
    temp = str->Data[I];
    str->Data[I] = str->Data[J];
    str->Data[J] = temp;

    I++;
    J--;
    }

  return 1;
  }

long stringAppendCharacter(typeString* str,char value)
  {
  if (str->Length >= str->Capacity)
    return 0;

  str->Data[str->Length] = value;

  str->Length++;

  return 1;
  }

long stringAppendCString(typeString* str,const char* value)
  {
  unsigned long I,J;

  I = str->Length;
  J = 0;
  while ((value[J] != 0) &&
         (J < STRING_MAX) &&
         (I < str->Capacity))
    {
    str->Data[I] = value[J];

    I++;
    J++;
    }

  str->Length = I;

  return 1;
  }

long stringAppendString(typeString* str,typeString* value)
  {
  unsigned long I,J;

  I = str->Length;
  J = 0;
  while ((I < str->Capacity) && (J < value->Length))
    {
    str->Data[I] = value->Data[J];

    I++;
    J++;
    }

  str->Length = I;

  return 1;
  }

long stringAppendInt64(typeString* str,unsigned long long value,long base)
  {
  static const char digits[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz-_";
  unsigned long     start,length;

  if ((base < 2) || (base > 64))
    return 0;

  start = str->Length;

  do
    {
    stringAppendCharacter(str,digits[value % base]);

    value = value/base;
    }
  while (value != 0);

  length = str->Length - start;

  stringReverseRange(str,start,length);

  return 1;
  }

long stringDestroy(typeString* str)
  {
  free(str->Data);

  return 1;
  }

#endif // TYPESTRING_H

Source code for a Trie Dictionary

This is a piece of code for inserting a string into a Trie dictionary. This is a bit complicated but it works.


#ifndef TYPETRIE_H
#define TYPETRIE_H

#include <stdio.h>
#include <stdlib.h>

#define TRIE_ROOT     01
#define TRIE_BRANCH   02
#define TRIE_LEAF     03

typedef struct tagNode
  {
  long          Type;
  unsigned long Length;
  char*         Data;
  tagNode*      Child;
  tagNode*      Next;
  } typeNode;

long trieCreate(typeNode* working)
  {
  working->Type   = TRIE_ROOT;
  working->Length = 0;
  working->Data   = 0;
  working->Child  = 0;
  working->Next   = 0;

  return 1;
  }

static typeNode* CreateNode(unsigned long type)
  {
  typeNode*   working;

  working = (typeNode*)malloc(sizeof(typeNode));
  if (working == 0)
    return 0;

  working->Type   = type;
  working->Length = 0;
  working->Data   = 0;
  working->Child  = 0;
  working->Next   = 0;

  return working;
  }

static typeNode* CreateBranch(typeNode* parent,char* buffer,unsigned long buffersize)
  {
  typeNode*     working;
  char*         data;
  unsigned long I;

  working = CreateNode(TRIE_BRANCH);
  if (working == 0)
    return 0;

  data = (char*)malloc(buffersize);
  if (data == 0)
    return 0;

  for (I = 0;I < buffersize;I++)
    data[I] = buffer[I];

  working->Length = buffersize;
  working->Data   = data;

  if (parent)
    {
    working->Next   = parent->Child;
    parent->Child   = working;
    }

  return working;
  }

static typeNode* SplitBranch(typeNode* parent,unsigned long index)
  {
  typeNode*     working;
  char*         data;
  unsigned long I;

  if ((index < 1) || (index >= parent->Length))
    return 0;

  working = CreateBranch(0,parent->Data + index,parent->Length - index);
  if (working == 0)
    return 0;

  working->Child = parent->Child;
  parent->Child = working;

  data = (char*)malloc(index);
  if (data == 0)
    return 0;

  for (I = 0;I < index;I++)
    data[I] = parent->Data[I];

  free(parent->Data);

  parent->Length = index;
  parent->Data   = data;

  return working;
  }

static typeNode* FindBranch(typeNode* parent,char value)
  {
  typeNode*      working;

  working = parent->Child;

  while (working)
    {
    if (working->Type == TRIE_BRANCH)
      {
      if (working->Data[0] == value)
        return working;
      }

    working = working->Next;
    }

  return 0;
  }

static typeNode* CreateLeaf(typeNode* parent)
  {
  typeNode*      working;

  working = CreateNode(TRIE_LEAF);
  if (working == 0)
    return 0;

  working->Next = parent->Child;
  parent->Child = working;

  return working;
  }

static long FindLeaf(typeNode* parent)
  {
  typeNode*      working;

  working = parent->Child;

  while (working)
    {
    if (working->Type == TRIE_LEAF)
      return 1;

    working = working->Next;
    }

  return 0;
  }

long trieFind(typeNode* root,char* buffer,unsigned long buffersize)
  {
  typeNode*     working;
  typeNode*     result;
  unsigned long I,J;

  working = root;
  if (working == 0)
    return 0;

  I = 0;
  while (I < buffersize)
    {
    result = FindBranch(working,buffer[I]);

    if (result == 0)
      return 0;
    else
      working = result;

    J = 0;
    while (J < working->Length)
      {
      if (buffer[I] != working->Data[J])
        return 0;

      if (I >= buffersize)
        return 0;

      I++;
      J++;
      }
    }

  return FindLeaf(working);
  }

long trieInsert(typeNode* root,char* buffer,unsigned long buffersize)
  {
  typeNode*     working;
  typeNode*     result;
  unsigned long I,J;

  working = root;
  if (working == 0)
    return 0;

  I = 0;
  while (I < buffersize)
    {
    result = FindBranch(working,buffer[I]);

    if (result == 0)
      {
      working = CreateBranch(working,buffer + I,buffersize - I);
      break;
      }
    else
      working = result;

    J = 0;
    while (J < working->Length)
      {
      if (buffer[I] != working->Data[J])
        {
        SplitBranch(working,J);
        working = CreateBranch(working,buffer + I,buffersize - I);
        I = buffersize;

        break;
        }

      if (I >= buffersize)
        {
        SplitBranch(working,J);

        break;
        }

      I++;
      J++;
      }
    }

  if (working == 0)
    return 0;

  if (FindLeaf(working) == 0)
    CreateLeaf(working);

  return 1;
  }

long trieInsertCString(typeNode* root,const char* buffer)
  {
  unsigned long I;

  I = 0;
  while ((buffer[I] != 0) && (I < STRING_MAX))
    I++;

  return trieInsert(root,(char*)buffer,I);
  }

int trieDraw(typeNode* root,int indent)
  {
  typeNode*   working;

  if (root == 0)
    return 0;

  if (root->Type == TRIE_ROOT)
    printf("\nRoot\n");
  else
  if (root->Type == TRIE_BRANCH)
    {
    printf("%*s\"",indent," ");
    fwrite(root->Data,1,root->Length,stdout);
    printf("\"\n");
    }

  working = root->Child;

  while (working)
    {
    trieDraw(working,indent + 2);

    working = working->Next;
    }

  return 1;
  }

long trieDestroy(typeNode* parent)
  {
  typeNode* working;
  typeNode* temp;

  if (parent->Type == TRIE_BRANCH)
    free(parent->Data;
 
  working = (parent->Child);

  while (working)
    {
    temp = working->Next;

    trieDestroy(working);
    free(working);

    working = temp;
    }

  return 1;
  }

#endif // TYPETRIE_H

Sunday, December 20, 2015

I have finally finished reading that code complete book. Before I had been thinking of drawing diagram for every piece of code that I need to build. Now I am thinking that the best way to do everything is to ask a lot of questions at every level. For example, my next program is a back to basics windows program. I have done this dozens of times before so there is no point going over it again. However, while I always got it to work right, I can never get past it to build more complex code. Drawing a diagram or making a plan would not work simply because I have no idea what I am doing. The only way I can fix this properly is to ask a series of simple questions about why each small thing is done. First: What is the point of all this code. This code does three main things. One: It initializes a window object by defining a custom class and then creating it. Two: I runs a message loop to get event messages from the window object. Three: it processes those messages, using them to update the window and close the program. Question: Why does it take so much code to create the window. Windows are very generic objects that are used all over the operating system. They all have to work the same way because they must all work together on the same screen. All these options in the two create functions are there to allow a whole set of customizations that most people will not ever need. You can mostly pick a preference and stick with it. Question: Why do we need the running global variable. The problem with the message loop is that it controls the entire program, but there is not safe way for the loop to know by itself when the program is over. The running variable is set to true before the loop starts, and then set to true when the event procedure receives a message to terminate the entire program. The event loop simply checks each time if running is true, and exits the loop, and the entire program when it is not. Why does the event procedure call a default event procedure. The window objects works entirely by responding to messages. The program can respond to messages that it cares about and modify the window accordingly, it can just ignore the ones it does not need. However there are a large number of messages and some of them will cause the window to not work properly if they are ignored. The default window procedure is there to make sure that everything works properly why allowing a program to just ignore anything it does not need. How can I simplify all this useless code. Creating a window, like most things in coding, can be encapsulated. There are too many details to put it all inside one function, but we can put it inside a class. The parts that are required for the class are the application Instance, and the window procedure. The application Instance is obtained from the first parameter of the win-main procedure, the window procedure is created for each application. Why can't we just encapsulate the window procedure along with everything else. The window procedure is a function that is defined entirely by the operating system, and can only be called by the operating system. There is no simple way to tell it what window class it should be working on. There is a difference between our window class and the window object created by the operating system. While it is possible to make the window object point to our custom class, this is not an elegant solution. On top of all that, the window procedure takes care of things that are unique to each application, so it would not make sense to make a generic one for each class. Is there a point where a generic window procedure would be useful. Yes, there are window classes, like those that require scrolling ability, that need to respond to very specific messages. It would not make sense to have each application know about what those messages are and call the class to deal with them. This is a case where having a class would not make everything simpler.There are some big problems that I will have to solve tin the future if I am going to make this work properly, but this is enough just to get started.

Monday, December 14, 2015

I am really out of shape lately. I am starting an exercise program for the next little while. I am going to start slow to find out what I can do and gradually increase my limit. For today it is just running up and down the thirteen steps in my house for five. Later we will gradually increase as I get better.

1. Monday December Fourteen. Time : Five Minutes. Repetitions : Twenty One.
2. Tuesday December Fifteen. Time : Five Minutes. Repetitions : Twenty One.
3. Wednesday December Sixteen. Time : Ten Minutes. Repetitions : Thirty Seven.
4. Thursday December Seventeen. Time : Fifteen Minutes. Repetitions : Fifty Five.
5. Friday December Eighteen. Time : Fifteen Minutes. Repetitions : Fifty Five.
6. Saturday December Nineteen. Time : Fifteen Minutes. Repetitions : Fifty Eight.
7. Sunday December Twenty. Time : Fifteen Minutes. Repetitions : Fifty.
8. Monday December Twenty One. Time :  Fifteen Minutes. Repetitions : Forty One.
9. Tuesday December Twenty Two. Time : Fifteen Minutes. Repetitions : Forty Eight.
10. Wednesday December Twenty Three. Time : Fifteen Minutes. Repetitions : Forty Seven.
11. Thursday December Twenty Four. Time : Fifteen Minutes. Repetitions : Fifty Four.
12. Friday December Twenty Five. Time : Fifteen Minutes. Repetitions : Forty Eight.
13. Saturday December Twenty Six. Time : Fifteen Minutes. Repetitions : Forty Nine.
14. Sunday December Twenty Seven. Time : Fifteen Minutes. Repetitions : Fifty One.
15. Monday December Twenty Eight. Time : Fifteen Minutes. Repetitions : Forty.
16. Tuesday December Twenty Nine. Time : Fifteen Minutes. Repetitions : Fifty Three.
17. Wednesday December Thirty. Time : Fifteen Minutes. Repetitions : Fifty Five.
18. Thursday December Thirty One. Time : Fifteen Minutes. Repetitions : Fifty One.
19. Friday January First. Time : Fifteen Minutes. Repetitions : Forty One.
20. Saturday January Second. Time : Thirty Minutes. Repetitions : One Hundred and Two.

At this point, I have increased the time to thirty minutes and I do not feel anything like when I started. I don't think that I am really going to get any better from this point on. I am still sweating a lot and I feel out of breath while running, but I recover very quickly. At this point I feel like I am just wasting time. I need a way to improve my performance without taking more of my time. The solution that I am thinking of is weights. I have a set of adjustable dumbbells and I think that running with them on my shoulders will give be an extra kick. I am going to start with a low weight and gradually increase as I feel more up to it. I will still keep the time constant and record my score.

21. Sunday January Three. Time : Fifteen Minutes. Weight : Forty Pounds. Reps : Thirty Nine.
22. Monday January Four. Time : Five Minutes. Weight : Fifty Pounds. Reps : Thirteen.
23. Tuesday January Five. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty One.
24. Wednesday January Six. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Eight.
25. Thursday January Seven. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Four.
26. Friday January Eight. Time : Five Minutes. Weight : Eighty Pounds. Reps : Eleven.
27. Saturday January Nine. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Seven.
28. Sunday January Ten. Time : Fifteen Minutes.  Weight : Eighty Pounds. Reps : Twenty Four.
29. Monday January Eleven. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Four.
30. Tuesday January Twelve. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty.
31. Wednesday January Thirteen. Time : Five Minutes. Weight : Eighty Pounds. Reps : Ten.
32. Thursday January Fourteen. Time : Five Minutes. Weight : Eighty Pounds. Reps : Twelve.
33. Friday January Fifteen. Time : Five Minutes. Weight : Eighty Pounds. Reps : Fourteen.
34. Saturday January Sixteen. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Six.
35. Sunday January Seventeen. Time: Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Seven.
36. Monday January Eighteen. Time : Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Two.
37. Tuesday January Nineteen. Time : Five Minutes. Weight : Eighty Pounds. Reps : Thirteen.
38. Wednesday January Twenty. Time Fifteen Minutes. Weight : Eighty Pounds. Reps : Thirty One.
39. Thursday January Twenty One. ///SKIPPED///
40. Friday January Twenty Two. Time Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Seven.
41. Saturday January Twenty Three. Time Fifteen Minutes. Weight : Eighty Pounds. Reps : Twenty Seven.
42. Sunday January Twenty Four. Time Five Minutes. Weight : Eighty Pounds. Reps : Ten.

Wednesday, December 9, 2015

In the past month I made a point to read one full book a day for thirty days. I got there, mostly, but the problem is that I dd not learn as much as I wanted. I don't have that good a memory and most of those books were not that deep. Also I was spending four to eight hours a day reading right after coming from a full day at work. Also most of the time I was doing this reading well after midnight and almost falling asleep. This was not the best way to do things, but it was also not the point. The real point of this exercise was to jump start my self into a new set of habits. My current life plans for the future require that I completely change the way I look at myself and the world. I could have made a point to read a book a week or follow some kind of long term plan that would eventually get me somewhere in a year if I managed to stay with it, but there is no way that was going to happen. My view of how things are done as well as my habits from a month ago would have pushed me along for a few day of a week, but eventually I would have found some excuse to stop and move on to some other thing. The only way I was ever going to move past that was to do something stupid like read a lot of books in a short time and hope that one or more of those books would change my world view into something that could sustain a more healthy habit structure, and I think this is what happened. Every night so far my first thought has been to sit down and read something. I will not do this every night but I am doing other related things that involve absorbing new information. I cannot remember most of the facts that I read but I do remember the general idea. For the next little while, I will work on expanding on that.

Sunday, November 15, 2015

I just finish reading Mastery by Robert Greene. At over a thousand pages, it took over six hours non stop. I put the audio player at the maximum speed where I could still understand what was going on. I have to go to work during the week so I have to wait until the weekend to read a book this long. So far, I have been reading lighter books and have been avoiding the big ones because I am not used to reading this much and I don't want to feel overwhelmed.

So, How was the book itself beside very long. What I got from it is that all the things that I am expecting to accomplish during the next year are completely impossible with my current mindset. Nothing that I can do today is up to the level of my dreams. My only option is to pick a few simple things and do them over and over until I can learn the skills needed to move to the next level. Right now it is past three in the morning, I have just spent over six hours staring at a computer screen, so it is unlikely that I can write anything intelligent here, but I am starting to form some ideas. What I have learned from the book is that big things take time and dedication. I already know this, but also that I need a clear path in my hear as to how I will move forward.

I am falling a sleep here, I will pick this up in the morning.

Wednesday, November 11, 2015

I just finished reading another book called the one hundred dollar startup. What I am thinking of right now is how do I start my own business. I do have a YouTube channel that could make money as well as other ideas. But the problem is that I completely fail when it comes to project management. What I am thinking of doing is simply to take programming concepts, sometimes from Wikipedia or other places, and translate them into simple visual explanations. That is clear enough, but the problem is that even the simplest things will have hundreds of sub-projects that will need to be explained separately. Whenever I try to code something, I usually try to do it all at once from memory. Even if I try to make a plan or diagram, I have no real concepts about how to follow a plan and do things step by step. It is easy for someone who knows how to do this sort of thing naturally to not understand how I could have trouble with following a plan, but I have a lifetime of difficulty with this and have only recently learned that breaking down a project into smaller steps was something that you are supposed to do.

For example, what is a suffix tree. I first figured out how to do one of these by drawing a picture. Eventually it was simple enough to understand. When I try to code it, I had some trouble, but I eventually forced my way through it. Even as I am writing this paragraph, the same problem is coming through. I am just writing what comes into my head. There is no way that I could ever run any business this way, but that is just how I think. Before I can move forward, I need to get into the habit of planning before I act. If I can just do this simple thing, everything else will follow.

Monday, November 9, 2015

I think I got an idea as to why I can never get anything done, I have no plan. There are many times during the day when I just cannot think of what to do next. For example, I just finished reading a book. I had planned for the book to take four hours because I listen to audio books at double speed while reading the text at the same time. This book only took about three hours and at the end, I just became confused as to what to do next. I figured that it would be time for bed when I was done, and now there is nothing for me to do. If I had a clear to-do list, this would not be a problem at all. One of the books that I recently read told me that habits are just what our brain turn to when there is nothing pulling on us. Like gravity, if we do not push ourselves in the direction we want to go in, we will simply get pulled back towards whatever feels good at the time. Addiction is not a compulsion to do something, it is just what our brain defaults to when it has nothing better to do. If I were to make a to-do list right now, what would be on it. I really don't know for sure. I can pretend like there are those things that I want to do, but those are all random dreams. I really cannot think of anything right now that I very concretely want to do right this moment. There is nothing that is not just a wish like make more money. I could clean my house, wash the dishes, write some JavaScript code, make a YouTube video. All those things are just small disconnected pieces. If you want to learn, there are to be a reason. I would like to learn how to speak Finnish, why? Can I figure out a good way to incorporate that desire into my life goals. I am going to read another book after work tomorrow night, what will I do after I am done. What are my goals, beyond the small things that I would like to do. I really don't know. I keep getting advice from small blogs about how I should write down all I need to do during the day, but what will that do for me. To start with, there is no need to remake your entire life in one day. Having a list of things to do is not a life plan, it is just something to get you started. Making a checklist for a single day and completing everything on it will start you towards something bigger, even if it doesn't look that big at first. At the very least, it is better than nothing.


I really need to update the look of my pages here. Read something about how to get all this to look the way you want.
Books I have been reading, plan to do thirty in thirty days.
1. Saturday November Seven : Charles Duhigg -The Power of Habit. 
2. Sunday November Eight : Brendon Burchard - The Motivation Manifesto.
3. Monday November Nine : Gary Vaynerchuk - Crush It! Why NOW Is the Time.
4. Tuesday November Ten : Chris Guillebeau - $100 Startup Reinvent the Way You Make a Living 
5. Wednesday November Eleven : Dave Lakhani - The Power of an Hour
6. Thursday November Twelve : Alan Deutchman - Change or Die
7. Friday November Thirteen : Rolf Dobelli - The Art of Thinking Clearly
8. Saturday November Fourteen : Robert Greene - Mastery
9. Sunday November Fifteen : Daniel Coyle - The Talent Code
10. Monday November Sixteen : Alistair Croll - Lean Analytics - Use Data to Build a Better Startup Faster
11. Tuesday November Seventeen : Bill OHanlon - A Lazy Mans Guide to Success 2009
12. Wednesday November Eighteen : Mihaly Csikszentmihalyi - Flow - The Psychology of Optimal Experience
13. Thursday November Nineteen : Dave Logan - Three Laws of Performance
14. Friday November Twenty : Pat Mesiti - The $1Million Reason to Change Your Mind
15. Saturday November Twenty One : Eric Ries - The Lean Startup
16. Sunday November Twenty Two : Ryan Holiday - The Obstacle Is the Way
17. Monday November Twenty Three : Dale Carnegie - How-to-win-friends-and-influence-people
18. Tuesday November Twenty Four : Topher Morrison - Settle For Excellence
19. Wednesday November Twenty Five :  Gabriel Wyner - Fluent Forever
************November 26************* House got robbed. No book tonight.
20. Friday November Twenty Seven : Richard Bandler - Using Your Brain for A Change
21. Saturday November Twenty Eight : Richard Bandler - Frogs into Princes
22.                      Richard Bandler and John Grinder - Reframing - NLP & The Transformation Of Meaning     *****************Read two books this day to make up for Thursday.                                       
23. Sunday November Twenty Nine : Maxwell Maltz - Psycho-Cybernetics
24. Monday November Thirty : George Clason - The Richest Man In Babylon
25. Tuesday December First : Josh Linkner - Disciplined Dreaming
26. Wednesday December Second : Howard Dvorkin - Power Up Taking Charge of Your Financial Destiny
27. Thursday December Thrid : Gay Hendricks - The Big Leap
28. Friday December Four : Lisa Haneburg - Two Weeks to a Breakthrough
29. Saturday December Five : Pete Goodliffe - Becoming a Better Programmer
30. Sunday December Six : Theodore Bryant - Self-Discipline in 10 days - How To Go From Thinking To Doing
**** Done the first thirty, but will not stop here.

31. Wednesday December Nine : Gary Keller - The One Thing
32. Saturday December Twelve : Steve Siebold - How Rich People Think
33. Sunday December Twenty : Steve McConnell -  Code Complete (2nd Edition)
34. Sunday December Twenty : Gary Vaynerchuk - The Thank You Economy
35. Monday December Twenty One : Jesse Itzler - Living with a SEAL
36. Saturday January Second : Ayn Rand - Ayn-Rand-Atlas-Shrugged

37. Sunday January Eighteen : John Templeton - The Templeton Plan.
38. Monday January Nineteen : Nietzsche, Friedrich - The Birth of Tragedy.

Sunday, November 8, 2015

I have a slight problem here. There is this Finnish Song that I am trying to learn and my current method is to write down something twenty times, mostly from memory until I know it perfectly well. I have use this method to learn the alphabet backwards and also other small things. The problem is not really learning the song, its the way that I am trying to learn it. Instead of learning parts of the song and then moving on to another part, I just try to learn the whole thing all at once. I have spent two nights now trying to copy every word in a text that I mostly don't understand. My brain has been fighting against the process all the time and I have a lot of trouble getting up the will power to even start doing it. All I can think about is that I have to do this twenty times, that does not make any sense. Right this moment, I have no idea what to do next, nothing really seems to work. But of course, how could anything work, I have never taken the time to really learn anything about learning a language. There are no good books about learning Finnish that I can find, but I could simply read one on learning Spanish and apply some of the same methods to the Finnish language. I have been reading, or at least looking at all I can find on this language for seven years so I do know how it works well enough to get through it, all I need is a method for learning and practicing.

On another note, what I am focusing on? I have all these things that I want to do but there is no one thing that I really focus on during the day. I come home from work and I either go look at my computer all night or look for something that I can do in the house. At best I try to think of new ways to make money or learn something. Tonight I am going to read the book, Brendon Burchard - The Motivation Manifesto. I just got a preview of that and what it shows is that you must say no to most things and focus all of your attention on a single thing in order to move forward.


This is a video from the author of the book. From this I am seeing how much I have been wasting my time trying to do too many things at once. I am going to start reading the book now. I am not sure how much I can learn from it, but we will see how far this gets me.

Saturday, November 7, 2015

I just had an idea: I have been writing posts, making videos and reading articles about programming of all sorts, but it never really occurred to me to just read a book on the subject. I could simply read a book on game programming, make a number of small programs, then assemble each one of these programs into a fairly good game with relatively little effort. However my life habit has always been to look for the shortcuts or the quick fix. I am the kind of person who will gladly work double shifts at work five days a week. Getting just four hours of sleep every night for months at the time is something I am used to do quite often. Because of these events, I have always assumed that this meant that I was a hard worker, but now I am realizing that it is quite the opposite. The reason why I can work harder than anyone else at my job is because the job does not require any thinking. It is all stuff that can be done with habit, and an ability to remain focused on an endless series of simple tasks. With programming there is not simple task, at least not the way I do it. I can write pages of code and just sit there for hours staring at a screen, as long as it is all stuff I already know. I like the idea of finally figuring out a difficult problem, but when I have a long series of problems with no end in sight, the feeling of accomplishment that I anticipate and crave from being able to last a sixteen or eighteen hour shift at work, or the satisfaction of completing a project the way that I want never shows up. I just lose interest, and soon revert to looking for a simpler, quicker way of getting my fix.

I have been reading this book called The Power of Habit by Charles Duhigg, in it it shows that our behaviors are mostly the product of small subconscious actions that are triggered in ways that we do not even notice. I need to break my habit of looking for short cuts and start setting clearly written programming goals. Before long, I need to have a working game. Before that however, I have to write down what I need to do to get there. I think that the problem is the fact that I never really try to plan anything. At my job, all the planning is done for me. I am assigned a task, I do it as best I can, then I get another on. It does not matter how long I have to work, I never need to try to figure out what to do next. At home however, when I need to get something done, my only strategy is to just sit down and try to do it, without a plan. I am accustomed to just figuring out what to do by simply knowing how to do it. But if something comes along that is too big to hold in my head, my only habit is to just push against it, sometimes for years, until I just give up in frustration. Most things are easy if you can break them down into smaller tasks, and then do those tasks one at the time, but I have never learned how to do that. I have tried to break down tasks, but I quickly give up because it is the complete opposite of how I am accustomed to doing things. That is the real power of habits, I just have to push and break my head on every problem I come across. I have been trying to learn the Finnish language for seven years now. I have spent months of my life trying to translate an entire book form Finnish to English. I have read many articles that shows grammar rules and other aspects of the language. I have forced myself to sit down and do all of those things, but I don't remember ever really trying to follow an actual course. I think I have read books on the subject, but really all I ever did was skim across the pages looking for tricks that would help me learn faster. I never really stopped to plan how I was going to approach the language. I am sure that I could have read a book for real, followed a course plan, and be at least functional in the language by now, but I never did any of this. My only habit is to work harder than anyone else, for as long as it takes. Now I need to change everything and learn to work smarter. The plan for now is to read something about programming and practice it exactly, even when all my instincts are telling me to jump ahead. This is going to be the hardest part, to not just feel as if I know enough and just jump in.

Question - How do I Draw a Multiplication table using the JavaScript Canvas.
Answer:
First you create a canvas and a context. To get all the numbers to fit neatly in a grid pattern, we need to calculate the position of each cell, and each number. To make everything look better here I will use a margin and patting to make each cell look like a button. You could also use JQuery or something else to get a better look, but this is just to make code that you can replicate and play with. To draw each cell in the right place, we need a nested for loop for the X and Y axis, rows and columns. It is not important here which loop comes first, we just need one inside the other. Because we are making a multiplication table, we need one row and column than is specified. For example, to show a times table for every number from one to twelve, we would need thirteen rows and thirteen columns. Inside the inner loop, we are drawing each cell. At this point you would only need to draw the number at the center of each cell and you are done, but we need to know where the center of the cell is and where to draw the margins. The code also uses different colors for when a cell in a source number or a result number. Red for a result number and green for a source. Because both the loops count from zero, we identify a source number as when the row or column value is zero and set the colors accordingly. If the number in the cell is not a source, then its value is just the value of the first for loop, multiplied by the value of the second for loop. Now to draw the cell. The starting position of the cell begins with the X and Y values from the two for loops, multiplied by the width and height of each cell. The ending position is those values plus the width and height of each cell. But that is not enough in this case, we now need to calculate the padding and the margins. This is used to show a space between cells and to give the appearance of a raised button. Padding and margin at the top of the cell is achieved by just adding the values from the top of the cell. However, because JavaScript function fillRect in the HTML 5 canvas uses heights and width to draw rectangles, we need to calculate the size of the rectangle by taking into account all the sides of the cell. So the width of the rectangle in the middle of the cell is the width of the cell, minus the padding times two. To calculate for both the padding and margin together, just do the same thing by first adding both values before multiplying them by two and subtracting that from the cell's size. Now that we have our separation between our buttoned cells, it is time to draw the number using the JavaScript canvas methods for text drawing. We first set the font, then we align the text to the center of the the position we provide and set the color to white to make it stand out. Now we draw the number. To convert a number to string in JavaScript, we use the toString method. All numbers and strings are objects with their own methods in JavaScript. To calculate the point where we draw the number, we take the position of the cell plus the size of the cell divided by two to get the center. By that is not enough. Even though we specified that the text should be centered, JavaScript and the canvas only centers horizontally, so that the text is above the center of the cell. To compensate, we add half the height of our font to the center of the cell to get the text centered properly. It is possible to calculate the height of the text on the fly using JavaScript HTML5 canvas methods, but this works differently of each browser and I just don't want to get into that here. The result of this code is a simple looking multiplication table. I have also added code to change the color of cells when the mouse comes inside of them. For this to work however, you will have to remember to update the canvas each time you get the JavaScript onMouseMove event.  Otherwise, the image will not change. The mouse coordinates are for the window, not the image, so we subtract canvas.offsetLeft and canvas.offsetTop to compensate for the position of the HTML5 canvas on the page.

Thursday, November 5, 2015

This is my first post on blogger. I am wondering jut how much I can put in here.
the one on the top is about gravity, the one below is about bouncing balls. They are not of very good quality because I cannot get the capture software to work right.