09 Mar

Pointers? Pointers.

This is my attempt at demystifying pointers, a very useful concept available in C, C++ and other programming languages that do not lack balls. Java and PHP have references, a similar feature (C++ also has this) but pointers pretty much are the same thing and for some reason pointers seem ancient, complex or downright frightening to some (or, most).

Why I’m writing this is because I feel a lot of tutorials do not explain pointers as well as I’d like them to explain, considering they are useful and not some archaic curiosity from the 1970s. I originally expressed the concern over here. This tutorial, or introduction, is aimed at C and C++ people because Java doesn’t have pointers and because other languages are generally for wussies.

Note: This is a living tutorial, i.e. you can suggest things and I’ll make it better. I’m all for a good pointer tutorial.

What are pointers?

At first, let’s think about computers. A very basic computer has memory for the data and the code. In a programming language, a variable refers to a location in the memory. The location, referred by address, is something like a page number in a book. At the very least, a programming language automatically assigns these memory locations and acts as a directory for the book, allowing you to refer to the locations by the variable name instead of the page number.

In a programming language, pointer is a variable that contains the address. Simple as that. In most cases, a pointer contains an address of another variable. The pointer can then be used to read or change the contents of the referred variable.

How do I use pointers?

In C, using pointers is easy. To make a variable as a pointer to another variable of type A, you define the pointer to be of type A*.

A variable=42;
A* pointer_to_a_variable=&variable;
*pointer_to_a_variable=0;

& can be read as “address of”. * can be read as “contents of”. Try reading the above example like that and you should figure out what it does.

Here is the answer:

A variable=42;
A* pointer_to_a_variable=&variable; // a pointer to the above variable
*pointer_to_a_variable=0; // the contents of the variable referred are zeroed

When should I use pointers?

A pointer can be very useful in a variety of situations. The simplest use would be something like passing a reference to a variable as a function parameter and the function then changes the variable. This is impossible without either references or pointers. At the very far end of the same spectrum, pointers are the only way to implement polymorphism in C++, which is an important and useful concept in object oriented programming.

Using pointers is natural when in a function you need to use the contents of an object given as a parameter and change them. If you don’t pass a pointer or a reference to the object, you will only change the data in the copied object. For example, see the C++ function below.

void func(Object obj) {
  obj.data=0;
}

This bit of code would be quite useless, considering the object obj is discarded after the function exits. The data member of the object passed as a parameter will not be modified because the object is duplicated for use in the function. The below function does the same but with the exact same object that was passed as a parameter.

void func(Object& obj) {
  obj.data=0;
}

Now the object is not duplicated but obj is a direct reference to the original object. data will be zeroed. Below is yet another version of the same functionality, this time with a pointer.

void func(Object* obj) {
  obj->data=0;
}

This does the same thing, only that obj is a pointer to the object. The above examples show how pointers indeed can be avoided by using references or other more modern concepts (and in some languages you are forced do it with references).

However, in C++, the above example (the one with the pointer) would also allow you to pass an object as a parameter that was inherited from the class Object. By using C++ references this is not possible. Now, if the function called a member function, it would call different bits of code depending on the object! This can be a very, very powerful and nice feature. And you can’t do it without pointers (in C++).

Show me more examples.

In C and C++, the line between arrays and pointers is a bit blurred. For example, you can use a pointer as an array, in that you can use an index with an array and a pointer. Below is an example:

int a[2]={123,456};
int* b=a;
a[0]=0;
b[1]=0;

The array a is now full of zeros. Note that b only refers to the array, it doesn’t have its own data. Also note that specifying an index eliminates the asterisk in front of b. This is because in effect b[1] is the same as *(b+1).

Continuing from the above:

int a[2]={123,456};
int* b=a;
a[0]=0;
b=b+1;
*b=0;

This also zeros the array, because the pointer b is incremented. A pointer is simply a variable with an address and you of course can change that value. This is called pointer arithmetic. It can be very helpful and actually will often allow faster code: using an index needs a multiplication while smartly incrementing pointers only needs an addition (your mileage may vary — compilers are getting better and better). See the below example:

int a[100];
int i;
for (i=0;i<100;i++) a[i]=0;

The below modification should be marginally faster.

int a[100];
int *ptr=a;
int i;
for (i=0;i<100;i++) { *ptr=0; ++ptr; }

This is because in effect, the below example only increments the pointer while the above calculates the address using index.

Note: Many younger coders suffer of premature optimization. This is not a permanent condition and will reduce with some experience. The above is not a good place to optimize (what computer can’t do that fast enough for 100 times?) but do keep that trick in mind. At the very least, it can make code a bit shorter.

Afterword

This is it for now, I can’t think of anything more about basic pointer use. Honestly, it is a bit hard to imagine things from the perspective of an absolute beginner. Any ideas are welcome.

01 Mar

Use Macross to automate common WordPress post content

Here’s a macro plugin for WordPress I made. It features useful features for advertising, e.g. limiting the maximum amount of displayed ads.

macro view

What are macros?

A macro is a bit of text inside a post that, when displayed, will be substituted with other text. It simplifies editing of post and also provides a convenient way to insert repeating content.

Macros are useful for various uses:

  • Adding common content shared by multiple posts/pages
    • Post headers, footers and navigation between a series of posts
    • License disclaimers
    • Advertising inside post content (much more effective than leaving the ads outside the content)
  • Simplifying complex layout by hiding unnecessary formatting, e.g. adding an image with a caption using only a short macro
  • Quickly changing information on multiple pages, e.g. disclaimers, important notifications

Features

  • Configurable via the WordPress control panel system
  • Automatically limits the number of injected macros (useful for e.g. Adsense whose TOS states you can only have three instances per page)
  • Can be extensively controlled depending of page type (archive page, home page, single post etc.)

How it works

The macros are used by inserting text inside HTML comments when writing the post. Below is an example of a macro:

<!--adsense_inside_post-->

The macro looks like the above code when editing the post but when viewing the post (or page) it will be substituted with a Google Adsense advert (given that you have defined the macro).

Parameters can be used inside macros as follows. The first example is the text inside a post and the second is the macro defined on the Macross options page (with the name “image_with_caption”).

<--image_with_caption "image.jpg" "A photo I took last summer"-->
<p><img src="$1" alt="$2" /><br/>$2</p>

This macro will insert the text “A photo I took last summer” as the alt attribute for the tag and add it as a caption below the image.

You can use macros in a page template by using the expand_macro($name,$echo=true) function. This will also increment the counters. Here is the above example reinterpreted using expand_macro:

<?php expand_macro('image "image.jpg" "A photo I took last summer"'); ?>

By cleverly using macro priority (a lower priority macro gets injected first) you can use macros inside other macros. In combination with macro display options (i.e. if the macro is enabled for content, excerpts or feeds) you can use the same macro to expand into different text depending on where it is used.

Installation and configuration

Unzip the contents of macross.zip in your WordPress plugin directory and activate the plugin from Options > Plugins. Go to Options > Macross to create a macros. Counters work so that each successive macro injection increments the counter. If any of the specified counters for a macro exceeds the maximum value, the macro simply will not epand (also, none of the counters will be incremented).

The checkboxes next to a macro specify on which pages the macro will work. The first colum (Hook) tells Macross whether to expand the macro when actions the_content() or the_excerpt() is called. The third option enables the macro for the expand_macro() function. The rest of the checkboxes specify a page type, as returned by is_page(), is_single() and other conditional WordPress tags.

Download

Yes, the following is done with a macro, too. ;)

Links

  • Another macro plugin Originally, I wanted to use this, but found it cumbersome to edit macros. Also, it doesn’t have a counter/limiter system
29 Feb

Travis Bickle, Superhero

When talking about modern, more realistic, gritty superheroes, people most often mention Batman as the definitive example. When compared to more archetypal superheroes such as Superman, Batman is clearly a more realistic character. He has a past. In addition, he does not have any superhuman abilities — all he has is dedication, skill and wealth.

However, since the concept of a superhero can be bent to include characters that are less cartoony and in theory could exist in the real world, people often forget classic films that also could be seen as superhero movies. One whole genre full of potential overlooked “superhero” films is the 1970s vigilante genre with such classics as Death Wish with Charles Bronson and Scorsese’s Taxi Driver.

Taxi Driver is an interesting example for a variety of reasons. The movie exhibits extreme realism. The characters are everyday people — albeit from the seedy underbelly of life. There is a story of a hero single-handedly fighting evil.

The story could be thought as an origin story for the character of Travis Bickle, whose character shares common superhero traits: strong moral values, vigilantism and heroism. Origin stories, such as the graphic novel Batman: Year One or the movie Spider-man, are an important part of superhero mythos: it usually is the single defining reason why someone becomes a superhero. For Batman, this would be the death of his parents by a street punk (motivation) and later, him being an extremely wealthy industrialist (resources — skills).

Holy Bat-gun, Travis!

For Travis, the motivation is much more complex: in part, he is either just disgusted by the dark aspects of city life, he’s going insane or it could be that he tries to prove his manhood to his love-interest. In any case, he takes it as his duty to clean the city of all the filth. Even if it is just a single street at a time.

Travis’ resources obviously are limited compared to that of a millionaire’s. He does however have combat experience. He obtains weapons and routinely practices with them. In a feat comparable to a Bat-device, he builds a special device for quickly wielding his backup gun from his jacket sleeve.

Travis 2.0

At the same time Travis is preparing both mentally and physically for whatever he will do, he still maintains a facade of sorts by going to work. While his second persona clearly bleeds into public, it could be thought as a double identity — maybe just for himself. He is both a taxi driver and a killing machine. As if to differentiate his two sides, he shaves his head before going to work as a vigilante hero. Maybe as a logo of sorts, Travis adopts he catchphrase of presidential candidate Palantine and is seen sporting a pin carrying the slogan even when he makes an attempt at the candidate’s life.

One important feature of a superhero is that he or she continually fights crime and evil. When Taxi Driver comes to an end, it is not implied in any way Travis won’t do something similar in the future. In fact, his treatment as a hero probably just feeds his ambition of becoming a person of importance — a hero.

27 Feb

A tribute to Richard Feynman

Feynman diagramRichard Feynman was the most awesome person ever. He essentially was an upgraded version of Einstein, at least when it comes to human features. His personality is much more accessible to ordinary people: he’s the subject of anecdotes featuring bongo drums, nuclear secrets and lock picking. He was somewhat a ladies’ man, he frequented strip clubs. He was curious of how things worked and eager to teach what he found out about them — something I think is the most admirable quality in a person.

FeynmanMost people could learn something important from Feynman. People should maintain their natural curiosity through their lives. People should try to find things that are interesting to them, and them actively find out what makes them tick. To me, “I don’t know” is a very weird answer when practically everyone in the developed world has access to the Internet.

Most people seem to think finding out about things and knowing about things is something you can’t do — unless you get a monthly salary of it. Or, that knowledge is for the elite. Or, that knowledge is inherently dangerous and against their values. They should realize there indeed is a good salary for someone who upkeeps and uses the ignorance.

People are afraid of knowledge because of they don’t want to be a part of the elite. People think of Albert Einstein when they think of a genius, they should be thinking of Richard Feynman. Einstein was eccentric, Feynman was cool. Richard Feynman knew about things but still went to strip clubs, broke into offices for fun and I would think generally enjoyed his life.

So, next time, refer to someone as a regular Feynman — sarcastically or not — when you refer to a genius.

24 Feb

Google Chart API is pretty cool

I just stumbled upon the Google Chart API and I couldn’t resist playing with it (statistics being a fetish of mine). A few moments later, I came up with some PHP code that uses my stats plugin for WordPress to fetch page views and generates an URL for the Google API (see below for the attached source code).

The main idea behind Google Chart is that the chart is an image and all data for the chart is in the URL. That includes the chart title, size and the data sets. Personally, I think this is a brilliant idea. You can embed the charts anywhere you can use images and best of all, you don’t need to have data anywhere else but in the URL (you don’t even need to duplicate the generated image in your own webspace).
You can also pretty much generate charts by hand if needed.

On the other hand, when using dynamic data fetched from a database, it is a relatively small task to encode the data into the format Google Chart uses. They even provide a Javascript snippet for that (obviously, you might want to do that server-side – see below). Or, you can simply use floating point numbers if you don’t mind long URLs (and I’m not even sure you can always use very long URLs).

For example, below there’s a graph generated from daily visits to this site:

And here is the URL used to get that graph (lines split for convenience):

http://chart.apis.google.com/chart?
chs=400x150&chd=s:NQGHJ&cht=lc&chdl=Page+views
&chxt=x,y&chxl=0:|Mon|Tue|Wed|Thu|Fri|1:|200|500

The above URL has quite Google-like short parameter names but that’s obviously because of technical limitations. The chd parameter is where the data set for the graph is: s:NQGHJsimple encoding : encoded data.

One interesting aspect arises because of the encoding: you need to fit your data set to use the granularity the encoding has. E.g. when using simple encoding and encoding a data set of 0, 4.7 and 244, you have to normalize and remap the data so the data goes from 0 (character A) to 61 (character 9), not from 0 to 244. That may sound horribly inaccurate but remember, nobody measures the charts with a ruler – they look at the numbers for accurate data. And there are more accurate encodings.

I like how the charts look slick. A lot of existing libraries and APIs for similar stuff tend to have less aesthetic appeal. Anti-aliasing does not better stats make but it certainly looks more professional. The API also has nice features such as adding arrows and red X’es on a graph (think an arrow with the caption “stock market crash” – after which the graph plummets), the always useful Venn diagrams (see right) and other usual stuff you’d need.

Anyway, my original point was that Chart is a cool API, is probably easier to use and faster to install than gnuplot or other chart drawing software, is compatible with any browser able to display images and it’s free for everyone to use (the limit is something like 50 thousand views per user per day – and I guess their policy says nothing against caching the charts on your own site). Check it out.

P.S. This is quite obvious but… I predict that in the future, Google will use the accumulated charts for some kind of statistics search. The charts contain text (label, title) so a Google search result might include relevantly labeled graphs. Which is an interesting scenario, considering the Internet is full of lies, kooks and gullible users.