Skip to content

Recent Articles

11
Mar

How do you add two matrices?

Consider the two matrices, M and N.

An image showing matrices M and N

We can add N to M by adding each element of M to each element of N in turn.

An image showing the addition of matrices M and N

The order of addition does not matter.  You could show that M + N = N + M.

If you want to subtract two matrices, you can do so using a similar rule.  This is shown below.

Image showing the subtraction of Matrices

11
Mar

What is a matrix?

A matrix is a collection of numbers or equations.

The name of the matrix is written in bold typeface to distinguish it from other types of names used in maths.  If writing a matrix out by hand, it is usual to underline the name of the matrix.  A matrix is shown below.  We shall call this matrix M.

An image to show the matrix M: M = [1,2,3.4,5,6]

A matrix is described by how many rows and columns the matrix has.  The rows run from left to right and the columns run from top to bottom.

The matrix M has 2 rows and 3 columns: we say this is a 2 x 3 matrix.

An individual item in a matrix is called an element. We can refer to an element by referencing its row position and its column position.  The element M1,2 refers to the number in row 1, column 2: i.e. the number 2.

Matrices crop up a lot in mathematics, in fields such as graph theory and computer graphics.

10
Feb

Naming an array dynamically in PHP

If you wish to use name an array dynamically in php, you can use dynamic variables. However, naming an array dynamically causes a minor problem which you first need to get around: you need to consider the ambiguity that a dynamic array may create.

If you write $$a[1] then the php parser needs to know if you meant to use the [1] index from the variable $$a or whether you meant to use $a[1] as the dynamic name for the array. To clarify the ambiguity, you can use the {} brackets.

For example, you may have the array $days, defined as follows:

Array ([1] => monday [2] => tuesday [3] => wednesday [4] => thursday [5] => friday [6] => saturday [7] => sunday)

and you may wish to set a dynamic variable for the 3rd day of the week, i.e. Wednesday.

To set up this dynamic variable you can use the code:

${$days[3]} = some_value;

to produce the variable:

$wednesday = some_value;

Alternatively, you may have set up the days array as using a dynamic name, with the name set from the variable $arrayLabel. To read data from the array, you would use the code:

${$arrayLabel}[1]

to read the index 1, i.e. “Monday”.

10
Feb

PHP Dynamic Variables

php allows you to use dynamic variable names in code. Instead of referring to the variable by a single dollar, $, you can use a double dollar sign, $$, to tell php that the name of your variable is set by another variable.

For example, you may have a list of people and whether they attended an event stored in an array. The array may look like:

Array ([JohnSmith] => 1 [RobinWalker] => 0 [ChloeJones] => 1)

where 1 represents attendance and 0 represents non-attendance.

You may wish to convert the data in this array to individual variables for some reason. The following code will allow you to do that:


// assume that $arrayPeople contains the names of the People concerned
foreach ($arrayPeople as $person => $attendance) {
$$person = $attendance;
}

This would create the following variables:

$JohnSmith = 1;
$RobinWalker = 0;
$ChloeJones = 1;

7
Feb

Error creating a foreign key constraint in MySQL

A colleague came to see me today, frustrated that they couldn’t seem to create a foreign key constraint on a MySQL table.  After a few minutes investigation, I was happy that I helped them spot that the table they were using was a MyISAM table.  MyISAM tables do not support foreign key constraints.  To use foreign key constraints with MySQL, you must use an InnoDB table.

On further investigation, it became clear that the table in question was built after the other tables in the main database build.  By mistake, the table had been created as a MyISAM table; all the other tables in the database were InnoDB hence why other foreign key constraints were working.  I suggested changing the table to InnoDB which solved the problem.

28
Jan

Cron job examples

I recently wrote a post describing how to add a cron job to a UNIX like server.  That post didn’t describe in any detail the format of the crontab file.  This post should help you understand the format of the crontab file.

Code Explanation
* * * * * /scriptname Runs /scriptname every minute
* 1 * * * /scriptname Runs /scriptname every minute between 0100 and 0159 every day
* 1 1 * * /scriptname Runs /scriptname every minute between 0100 and 0159 on the 1st of every month
*/10 * * * * /scriptname Runs /scriptname every ten minutes. This is interpreted as running at each minute which is exactly divisible by 10 – i.e. every ten minutes.

It should be remembered that cron doesn’t deal with seconds and so you can’t use cron to schedule a job that runs more frequently than every minute.

Each user has their own crontab file.  cron will execute the script as the user who owns the specific crontab file.  Remember that cron doesn’t source any files in the user’s home directory and so each file required by the script should be referenced within the script itself.

If cron jobs don’t appear to be running, check that the cron deamon is running.  If the files etc/cron.allow and etc/cron.deny exist then the user would need to be specifically listed in the etc/cron.allow file in order for cron jobs to run correctly.

27
Jan

How to add a cron job

On UNIX like systems, cron is a time based job scheduler which allows users to schedule jobs to run periodically at set times.  For example, I may wish to run a script which backs up a MySQL database each night at 8pm.

cron is managed by a crontab file.  To see a list of cron jobs which are scheduler for your user, type the following command on the command line:

crontab -l

This will list all the current cron jobs stored for your user.

Each user has their own crontab file.  To edit the crontab file for your user, type the following command on the command line:

crontab -e

This will open the crontab file for editing, although you will have to press the a key before you can actually edit the file.

The crontab file allows you to specify the time to run the script and the script to be run.  For example:

1 0 * * * /scriptname

would execute the script at /scriptname at 00:01 every day.

The crontab file has 5 variables which set the time the script will run at:

minute hour dayofmonth month dayofweek

Multiple jobs can be scheduled independently in the same crontab file.

Once you’ve finished editing the crontab file, hit the escape key and then type zz. You should see confirmation that the crontab has either been changed or was saved with no changes.

To read more detail on what format the crontab file takes, please read this post.

8
Jan

MySQL Database Locks

A database lock is used when multiple users need to access the database at the same time. This stops shared resources, such as tables, from being corrupted. For example, if user A is changing the value of a field, the database management system must decide what to do with user B who also wants to update the value of the field at the same time. Locking comes in a number of forms and each form determines what will happen in situations where data is being used by multiple users.

MySQL uses row-level locking for InnoDB tables, table-level locking for MyISAM, Memory and Merge tables and page-level locking for DBD tables. Prior to version 5.5, MyISAM was the default storage engine for tables. From version 5.5 onwards, InnoDB is the default storage engine for tables.

MySQL has switched to implementing InnoDB as the default storage engine because InnoDB is now considered more appropriate in most situations than MyISAM. However, the choice which is made is wholly dependent on what the database is being designed to do and how it needs to perform. Each time we design a table, we must make a choice over which type of database locking we require for the table.

It should be remembered that there is no requirement to have each table in a database using the same storage engine; it may be appropriate to have some MyISAM tables and some InnoDB tables within the same database. Remember that the storage engine is specified for each table in MySQL and is specified when the table is created.

InnoDB tables allow multiple sessions and applications to read from and write to the same database table at the same time, without the need to make different sessions or applications wait for each other. MyISAM tables on the other hand acquire locks very quickly and allow for multiple sessions and applications to read data at the same time. However, MyISAM tables, which use table-locking rather than row-locking, force sessions wanting to write to the table to wait for exclusive access to the table. In practice, this means that the session needs to wait until earlier processes are completed. A read statement that takes a long time to run will prevent other sessions from updating the table making the other sessions appear slow. While the table is waiting to be updated, other sessions that issue read statements will queue up behind it. Applications which require concurrent read-writes from multiple sessions would, therefore, be better served using the InnoDB storage engine.

A big advantage of row-level locking is that a single row can be locked for a long time. Whilst this stops the row being updated by another process, other sessions can access data in other rows without waiting for the persistent row lock to be released. Row-level locking generates fewer locking conflicts when different sessions access different rows and also requires fewer changes if the database requires a rollback.

Row-level locking has some disadvantages too. Row-level locking requires more memory that table-level locks and is also slower than table locking when used on a large part of the table because of the number of locks which need to be acquired. Row-level locking is also slower if group by operations are done frequently or if the entire table requires scanning frequently.

For tables which use table-locking, the lock is always deadlock free. Deadlock avoidance is managed by always requesting all needed locks at once at the beginning of a query and always locking the tables in the same order.

Table write locks always take precedence over table read locks. If a write access is queued alongside a read access, the write access will be granted first. This means tables are never starved of data but it does mean that if there is heavy updating going on in the table, select queries are made to wait until there are no more updates. The MySQL variables Table_locks_immediate and Table_locks_waited indicate the number of times that table locks were granted immediately as requested or whether they were queued.

Generally speaking, table-level locks (and hence MyISAM tables) are considered superior to row-level locks in the following situations:

  • Most statements for the table are reads, such as the databases which power websites where the content doesn’t change too often
  • Statements for the table are a mix of reads and writes, where writes are updates or deletes for a single row that can be fetched with one key read – i.e. through using a where clause which uses the primary key value for the table
  • Statements which require a high number of full table scans, or statements which use a group by clause
In other scenarios, you should consider using InnoDB tables as the row-level locking is probably more appropriate. That said, as mentioned at the beginning of this post, each scenario should be taken on its merits and a case-by-case decision made regarding the most appropriate locking strategy to take.
2
Dec

Baby Computing in Manchester

I headed over to Manchester today to go to the Manchester Museum of Science and Industry. As a kid, I visited a lot in the late 80′s, finding the mix of collections fascinating. In the days before I owned any kind of computer, I remember spending hours being entranced by the endless of rows of early computers and reading about their applications. I think it was those Saturday mornings with my parents which sparked my interest in computers and logic and motivated me to learn more about programming.

The museum has a replica of “the Baby” – the Manchester Small Scale Experimental Machine, which was the worlds first stored-program computer. Baby was built in 1948 as a testbed for a primitive form of computer memory. Baby could store 32, 32 bit words and was used to find the highest proper divisor of 262,144. After running for 52 minutes, and performing 3.5 million operations in testing every integer downwards from 262,143, Baby calculated the correct answer: 131,072. For a primitive computer, 1.1 kIPS (Instructions per Second) is pretty impressive!

14
Apr

Ten Pin Bowling Maths

I’ve just got home from an evening of bowling.  My performance these days is a long way from the heady days of my youth, where I’d regularly achieve 150+ and sometimes top 200.  I can’t recall properly, but I think I passed 200 on 3 occasions, with 232 being my best ever score.  Today’s scores of 113 and 95 aren’t bad, but certainly aren’t what I’d consider good.

image showing the bowling score

Tonight got me thinking about the possible scores you could achieve in one game.  There are 1,924,226 different game combinations which would bring about a final score of 232.  The most likely score is 77, with 172,542,309,343,731,946 different combinations which would bring about that score.

This problem, that of working out how many individual ways there are of making a particular bowling score, suffers from combinatorial explosion.  For the first ball you bowl, there are 11 possible outcomes.  You could score 0, 1, 2, through to 10, a strike.  What happens on the second ball depends on what happens on the first ball; if you have hit 8 pins first time around you only have 3 options available for the second throw.

So, when you consider that the mean of the possible score distributions is 79.7, I realise that my scores from tonight are still “above average”.  Maybe I just need a bit more practice to get me back into the highest few percent of bowling scores.  For the record, the total number of possible games, i.e. ways to get a final score in bowling, is 5,726,805,883,325,784,576.  That’s quite a few.  Maybe a couple more games are called for after all.