PHP: Something to watch out when using global scope variables, or "why globals doesn't (seem to) work!?"

Okay, I guess this is probably a childish mistake for an experienced PHP-er, but I myself got busted tonight, and maybe I’m not the only one :-) So, here it is.

Consider the following small PHP program:

<?php
print_global_a();

$a = 10;

function print_global_a() {
        global $a;
        echo "$an";
}

What would be the output of this code? What?? 10?? Wrooong! Let’s save this as global.php and run it, see what happens.

giannis@ubuntu:~$ php global.php

giannis@ubuntu:~$

It outputs an empty new line… Okay, then maybe something wrong with the ‘globals’ keyword. Let’s try the $GLOBALS array instead:

<?php
print_global_a();

$a = 10;

function print_global_a() {
        echo $GLOBALS['a']."n";
}

Now let’s run it again:

giannis@ubuntu:~$ php global.php
PHP Notice:  Undefined index: a in /home/giannis/global.php on line 7

giannis@ubuntu:~$

It just got even worse; not only we still get an empty new line, we also get a big fat warning.

So, what is really wrong here? It is so simple, you probably noticed on the first glance, but if you didn’t, here it is: At the moment that the function is called the $a global variable is not yet set. Therefore, when we try to access it from within a function, we simply cannot, not because ‘globals’ is not working, but because it is not set in the first place. The fact that the definition of the function comes after the assignment may delude us to think that the variable will be set when the code in the function is executed.

So, in other words, the next time you may face a “globals” that doesn’t seem  to work, make sure that the variable is actually set at the point where the function is called.

Unfortunately, PHP is a tool that does not protect the programmer from doing nasty mistakes… I hope you found this interesting and helpful :-)

Posted in Uncategorized | Leave a comment

How to "un-commit" a revision from the top of a Subversion repository

Sometimes it may occur that a commit was performed in a subversion repository, that was not exactly what the original intention was. In such cases we would like to have an “undo” operation and bring the repository back to its original state, as it was exactly before the inadvertent commit.

The title of this post might be misleading, as technically there is no way to just un-commit or undo an executed commit from a subversion repository; after all, such feature would automatically cancel the very definition of version control.

Below I will describe the second best solution (or work around, if you prefer) on removing the last commit(s) from a subversion repository, which is to create a new repository and replay all the commits from the beginning and up to the revision just before the accidental commit. When done this, simply replacing the new repository with the old one will give the illusion that the unwanted commit(s) have been undone.

In this guide I assume that you have local command-line access and sufficient permission to the repository folder. I also assume that you wish to uncommit the last commit from the top of the repository. Once other commits have been performed, things get complicated and the procedure described below is not applicable. If the repository is used by multiple users make sure to ask from your peers to cease any commits until you are done with reverting the repository state.

First, you need to create a new empty repository:

giannis@ubuntu:~$ svnadmin create new-repository

Then, you need to dump all revision history from the original repository, starting from revision 1 and go up to the revision number that was exactly before the unwanted commit (typically this will be the current revision number minus 1).

giannis@ubuntu:~$ svnadmin dump old-repository -r 1:XXX > old-repository.dump
. . . . .
. . . . .
. . . . .
* Dumped revision XXX.

In the above command make sure to replace XXX with the current revision number decreased by 1.

Then you just need to load the dump file into the new repository:

giannis@ubuntu:~$ svnadmin load new-repository < old-repository.dump

Alternatively, it is possible to perform both dump and load in one single step, without having to create the intermediate dump file:

giannis@ubuntu:~$ svnadmin dump old-repository -r 1:XXX | svnadmin load new-repository

Finally, you just have to replace the new repository with the old one. Before doing so, it would be wise to create a backup of the original repository, just in a case something goes wrong.

giannis@ubuntu:~$ tar cvzf old-repository-backup.tar.gz old-repository/
. . . . .
. . . . .
. . . . .
giannis@ubuntu:~$ rm -rf old-repository
giannis@ubuntu:~$ mv new-repository old-repository

And you’re done! The advantage of this method is that you completely remove the accidental commit from the history of the repository, unlike other methods which simply merge the repository back to a previous revision.

I have done this many times and it helped. I hope you will also find this helpful. :-)

Posted in Uncategorized | 1 Comment

C++: calling a member function pointer

This article is about calling a member function (method) through a “function pointer”. I decided to write about it because it tricked me for a while, and I think this may be useful to others.

I will start with a small introduction and gradually get to the point. If you’re really in a hurry scroll down to the end of the article to see how it’s done!

Calling a “global” function pointer

In good old C, the following code is probably familiar to most seasoned programmers:

#include <stdio.h>

void func1( void (*func)() ) {
func();
}

void func2() {
printf("Goodbye world!n");
}

int main() {
func1(func2);
}

Now if we compile this and execute it we’ll get of course the following output:

giannis@goofy:~$ gcc fpointer.c
giannis@goofy:~$ ./a.out
Goodbye world!

The slightly strange syntax void (*func)() in func1()’s declaration, is what we call a “pointer to a function”. This one specifically declares that “func is pointer to a function with no arguments and no return value”.

Similarly, void (*func)(int) declares a pointer to a function that takes one int argument and returns no value, and int (*func)() declares a pointer to a function that takes no arguments and returns int.

Function pointers are like data pointers, except the point to executable code instead of data. It is pretty much a standard way in C to encapsulate and delegate behaviors or logic.

Now, let’s take the same scenario only this time within the scope of a C++ class. Consider this:

#include <stdio.h>

class MyClass {

private:

void func1( void (*func)() ) {
func();
}

void func2() {
printf("Goodbye world!n");
}

public:

void method() {
func1(func2);
}
};

int main() {
MyClass myObject;
myObject.method();
}

At least for me, this made sense… But what happens if we try to compile?

giannis@goofy:~$ g++ fpointer.cpp
fpointer.cpp: In member function void MyClass::method():
fpointer.cpp:19: error: no matching function for call to MyClass::func1()
fpointer.cpp:8: note: candidates are: void MyClass::func1(void (*)())

What the error message says, more or less, is that that func1() expected to be called with an argument of type void (*)(), however we tried to pass an “unresolved overloaded function type”.

Okay, that’s weird. func1() expects an argument of type void (*)(), and func2 was exactly of that type, right?

Well, not exactly. func2 is actually a MyClass::void (*)(), that is, it belongs to the MyClass namespace. On the other hand, func1() was expecting a void (*)(), which is a pointer to a function in the global scope/namespace (a “stray” function).

To fix this, we need to need to slightly modify the code in several few places.

First of all, the declaration of func1(). As we said the function will be called with an argument of type MyClass::void (*)(). Therefore it has to be altered accordingly:

void func1( void (MyClass::*func)() ) {
func();
}

Furthermore we need to change the way the function pointer is dereferenced inside func1(). It is not enough to just call func(). Remember that all the compiler knows is the address of a method, which remains the same for all instances of a class. When dereferencing a member function pointer, we also need to provide the object for whom the method is being called, in that case this holds a reference to this object, which is the one we aimed for. Thus, the func1()’s code becomes now:

void func1( void (MyClass::*func)() ) {
(*this.*func)();
}

The (*this.*func)(); statement just instructs the compiler to call the code of MyClass pointed by func, for this object.

And we’re almost done, we need to make one final small change, in the code that passes the member function pointer, so it makes clear that func2 is a method of MyClass and not a “stray” global function:

void method() {
func1(&MyClass::func2);
}

Now it should compile and work as expected:

giannis@goofy:~$ g++ fpointer.cpp
giannis@goofy:~$ ./a.out
Goodbye world!

Let’s put it all together:

#include <stdio.h>

class MyClass {

private:

void func1( void (MyClass::*func)() ) {
(*this.*func)();
}

void func2() {
printf("Goodbye world!n");
}

public:

void method() {
func1(&MyClass::func2);
}
};

int main() {
MyClass myObject;
myObject.method();
}

I hope this helped :-)

Posted in Uncategorized | 4 Comments

How to convert FLAC to MP3 on command line

First install ffmpeg (WinFF on Windows) and LAME. Then to convert a .flac to .mp3 type this on the command line:

ffmpeg -i "xxx.flac" -acodec libmp3lame -ab 128000 "xxx.mp3"

Posted in Uncategorized | 1 Comment

How to go off the record in Gmail when "Go off the record" is grayed

It is well known that due to a “bug in Gmail” [sic], it is possible to detect whether a user (that is apparently offline) is really offline (or has blocked you) or he/she is just hiding in invisible mode. To do so all you have to is to go in the Actions menu (in your chat box) and select “Go off the record”, and then send a simple message to the user. Absence of error message implies that the user is online, and hiding.

This is probably yesterday’s news for most of you, but a small detail is being often overlooked is that this option is clickable only if the other party is online. This complicates things a bit, as those people that love to practice the “invisible mode”, almost never show up online giving you almost zero chance to reveal them.

image-1.png

This article explains how to overcome this obstacle, by presenting one way to go off the record with a user, even when he is (or appears to be) offline, causing the “Go off the record” option to be disabled (“grayed”). The procedure that is described below is not trivial, but also not prohibitive, even for the average user. You may also need to install some additional software. So, let’s get started!

We need a Web Browser that is capable of Inspecting Elements (that is, when you right-click somewhere in the page, you get a “Inspect element” item in the context menu). I suggest either using Chrome, or Firefox with the Firebug plugin installed. For this example, I’m going with Chrome, because the desired functionality is built-in, and I don’t have to install any additional plugins.

Whenever you’re ready with the browser of your choice, enter your Gmail account and open a chat window with the person that you want to go off the record. Remember that if the person is offline (which is possibly our case), you must not just click on the person’s name, but rather you must click on the “Chat” button in the pop-up box.

image-2.png

In the chat window, click in the Actions menu. The menu shows up and the “Go off the record” is disabled (grayed):

image-3.png

Now be careful not to close the menu and right-click on exactly that menu item. You will see the context menu:

image-4.png

Now click on the “Inspect element” item of the context menu. The “Developer Tools” console will open at the bottom of your browser (or in a pop-up window), and a TD html element will be highlighted:

image-5.png

Then you must locate the nearest parent DIV element of the TD element. It must be 3-4 lines above:

image-6.png

You should be able to see the attribute class=”jM jK”. What you must do now is to change the class “jM” to “jL”. Double click between the double quotes to start the attribute value editor. Then simply change “jM” to “jL”. And press Enter to save the modification.

image-7.png

And almost magically the “Go off the record” menu item is now enabled for you to click it!

image-8.png

I hope this helped! :-)

See also: How to Detect invisible user in Gmail and gtalk Chat

Posted in Uncategorized | 10 Comments

Replace "\n" with new line characters, using Notepad++

In case you have a file which contains “escaped” new lines (\n), like this:

notepad-1.PNG

and you want to replace the escaped new line sequences with actual new line characters, you can easily accomplish this task using Notepad++.

First load your file (or just copy paste the text) in Notepad++.

notepad-2.PNG

Then select Search → Replace from the menu, or hit Ctrl-H. The Replace dialog will show up. Therein make sure that you fill out the following values; Find what: \\n (yes, two back-slashes), Replace with: \n (yes, just one back-slash), and the most important, make sure you select the Extended (\n, \r, \t, \0, \x, …) radio button. Your Replace dialog must look like this:

replace-1.PNG

Click the Replace All button, and all escaped new line sequences will be replaced with new line characters:

notepad-3.PNG

I hope this helped!

Posted in Uncategorized | 38 Comments

PHP Extensions do not load on fresh WAMP installation

So, you just installed WampServer on your Windows PC but the smile went away from your face as soon as you tried to use mysql. PhpMyAdmin reports that it “cannot load mysqli extension” (or “cannot load mysql extension”), or your mysql application is not working any more, and you can not load and use any PHP Extension.

One possible cause for this, is that an previous installation of PHP existed in your computer, and Apache gets confused and loads the wrong php configuration file. Be aware that although you may have uninstalled PHP (from “Add/Remove programs”), the PHP’s configuration file (php.ini) may still reside in your disk.

To solve the problem do the following. First make sure that the WAMP icon is green (which means that all services are running). Then click on the icon and select Localhost. Go to the Tools section and click on “phpinfo()”. In the new page use your browser’s search dialog (Ctrl-F) and look for “Loaded Configuration File”. You should see something like this:

php2.jpg

If the path does not start with “C:/wamp/…”, then this is a good sign, it means that probably the wrong php.ini file is loaded, and this is easy to fix. Just make sure to delete the php.ini file from the location mentioned in the php info page, then go to the WAMP icon and “restart all services”.

Then refresh the php info page and repeat the search to see which php.ini file is loaded this time. Now you should be able to see the correct one, the one from the C:/WAMP folder:

php3.jpg

Now all PHP extensions should be able to properly load and mysql should be working again.Good luck!

Posted in Uncategorized | 6 Comments

Restore window's visibility (Windows 7)

Sometimes it can happen that an application window may get “locked out” of the visible area of your desktop. Especially when you are extending your desktop in multiple displays and later on one of these displays is disconnected, a program may keep positioning its window in the good-old coordinates it had when it closed, even if these coordinates are not inside the accessible frame any more.

And this is where the move-window-by-keyboard feature comes to the rescue, a feature that I guess most people never ever use, as most of the time we use the mouse to move windows around the screen.

Locate the window that you need to bring back on the Windows taskbar, at the bottom of the screen. Then right-click on it while holding the Shift key down. You must be able to see this context menu:

this is the right menu

It is very important to hold Shift pressed while right-clicking because if you don’t, you’ll get a whole different menu, which is not the one you’re looking for:

this is the wrong menu!

Click on “Move”. After clicking on Move the hidden window should be already focused and movable using the keyboard. Use your keyboard’s arrow keys and within a few seconds you will be able to drag the window with the visible area of your Desktop. When you can see the title bar of the window you can leave the arrow keys and continue with your mouse.

I hope this helped!

Posted in Uncategorized | 2 Comments

counting and listing hard links on Linux

A hard link is actually nothing more than a regular directory entry, which in turn can be seen as a pointer to the actual file’s data on the disk. The cool thing about hard-links is that a file can be stored once on the disk, and be linked to multiple times, from different locations/entries, without requiring to allocate extra disk space for each file instance.

But then a question arises: Given a specific file on disk, how can someone know whether it is linked to by other directory entries or not? This can be easily answered using the ls command:

giannis@zandloper:/etc$ ls -l passwd
-rw-r--r-- 1 root root 1402 2008-03-30 17:49 passwd

Do you ever wonder what is this small number between the file permissions and the owner in the output of ls’s long listing format (its value is usually “1″ for files, or “2″ for directories)? This number is actually the link-count of the file, when referring to a file, or the number of contained directory entries, when referring to a directory (including the . and .. entries).

So, the answer to the question “are there any other directory entries linking to this file, and if so, how many?” can be simply answered by executing ls -l for this file and checking the link-count column. If it is just 1 that means that this is the one and only instance. If it’s greater than 1 then there are other directory entries linked to that same file.

Now, imagine you find out that a file is linked to by some other directory entry. The next thing you would want to know is who is linking to that file. To figure this out you must know what all these directory entries share in common. And that is, an inode.

An inode is a data structure used internally by a (unix-like) file system to store information about a file (it can be also considered as the file’s meta-data). Every inode has a unique (in the scope of the file system) identity number. We will use this property to locate all the hard links of a file within a file system. And this is how we can do it.

By passing the -i option to the ls command we also get the inode number for a directory entry:

giannis@zandloper:/etc$ ls -i passwd
199053 passwd

In this case, the inode number for the /etc/passwd file is 199053. Now that we have the inode number we can now do the actual search for directory entries that have that same inode number. But because it would be pointless to do such a thing since we know that there are no other hard links of this file in existence (recall the link-count “1″ in the output of the previous ls -l command which states that there is only one instance of that file), I’m going to first create a hard link of the file in my home directory:

giannis@zandloper:~$ ln /etc/passwd
giannis@zandloper:~$ ls -l passwd
-rw-r--r-- 2 root root 1402 2008-03-30 17:49 passwd

Now we’re going to search the entire file system for files with inode number equal to 199053. To do so we are going to use the find command and its -inum option:

giannis@zandloper:~$ sudo find / -inum 199053
/etc/passwd
/home/giannis/passwd

And that was it! I hope you learned something useful today :-) .

UPDATE: As “KokNikol” pointed out in the comments section, it seems that there is an easier way to locate all the hard links of a file. This is accomplished by using the “-samefile” parameter of the find command:

giannis@zandloper:~$ sudo find / -samefile passwd
/etc/passwd
/home/giannis/passwd

The benefit of using “-samefile” is that this way you omit the intermediate step of finding the file’s inode number. Thanks “KokNikol”!

Posted in Uncategorized | 12 Comments

Base-2 and Base-N logarithm calculation in Java

I was surprised today to see that the Math package does not provide a method that the calculation of an arbitrary base logarithm, even though it provides a log10() method for base-10 logarithms.

One can easily calculate the logarithm of any base using the following simple equation:

log.png

Where logk is the function that returns the base-k logarithm of a number, and it can be any real number.

In terms of Java it can be written like this:

 public class Logarithm
{
public static double logb( double a, double b )
{
return Math.log(a) / Math.log(b);
}

public static double log2( double a )
{
return logb(a,2);
}

public static void main( String[] args )
{
System.out.println(log2(100));
}
}

Posted in Uncategorized | 2 Comments