Category Archives: Snippets

Creating an Instance of an Object without Calling Its Constructor in PHP

Today, I stumbled upon an article in a local PHP developers group. It was about creating an instance of an object without calling its constructor (as mentioned in post title).

At first, the idea made no sense to me. Because, constructor method is run every time an object is instantiated, this property is the whole point of writing a constructor. Out of curiosity, I started reading the article. As it turns out, it is really beneficial for testing and mocking purposes. The more interesting thing is the method used to achieve this is simply brilliant.

The trick which originally occurs in PHPUnit source code is as follows:

$object = unserialize(
    sprintf('O:%d:"%s":0:{}', strlen($className), $className)
);

As of PHP 5.4, there is a built-in method for this in ReflectionClass:

$reflection = new ReflectionClass($className);
$object = $reflection->newInstanceWithoutConstructor();

Graphical Visualization of databases with PostgreSQL Autodoc

When it comes to software, database systems are beneficial in many ways. They offer us to keep our data organized and a fast way to access them. However as the number of components in a software project increases, it gets harder to preserve the organized structure. In situations like this, visualizing the scheme helps to understand the structure and the relations between the tables.

PostgreSQL Autodoc provides simple tools for description of the PostgreSQL databases in various formats such as HTML, DocBook, Dia and GraphViz. Continue reading

Sharing Screen Sessions

Recently, I learned a new feature of screen, it is referred as “multi display mode” in the manual. You can attach to a screen session that is not detached and the session is simply shared. In this mode, anything you typed are transferred simultaneously to the other display(s) as well. My mentor from my Google Summer of Code project used this feature to work collaboratively. In order to get in to multi display mode, you need to use “-x” parameter:

screen -x

If there are multiple sessions, you need to provide the session name as well:

screen -x session_name

Quick Guide to D-Bus with Python

Recent weeks, I dealt with D-Bus for my Google Summer of Code project. I was trying to control system services, and systemd has a D-Bus interface. In the beginning, D-Bus seemed a little confusing for me, but I believe I understand it now. In this post I will try to explain it in simple terms and an example.

D-Bus is a interprocess communication tool. It delivers messages to applications. The most confusing thing for me was that taxonomy of D-Bus having several terms such as bus names, objects, paths, methods, signals, properties, interfaces, proxies… But when you learn their meanings, the bigger picture gets more clear.

  • Bus names are applications. They often have well known names in a format similar to namespaces in Java (e.g “com.onurguzel.MyIntergalacticApplication”).
  • Objects are synonymous to the objects in programming languages, and paths are the object instances.
  • Methods are functions that is run on the object, and signals are the broadcasts from the object. Properties are the constants or variables in the object.
  • Interfaces are the types of the object. Thus, some object may support several interfaces. Their format is the same as bus names, but they should not be mixed with each other.
  • Proxies are higher level objects. When a method is invoked on the proxy, it is converted to D-Bus method call message, sent, and reply message is returned. They offer easier operation with D-Bus then manually creating messages, sending them and waiting for a reply.

Since all major Linux distributions use NetworkManager for network connections, I preferred to create this tutorial with it.

import dbus

bus = dbus.SystemBus()

# Warning: Bus names and interfaces are different terms.
# Just because they contain same format or even same data
# does not mean they are the same thing.
# I used these variables to denote the diffrance where bus names and
# interfaces are used.
NM_BUSNAME = 'org.freedesktop.NetworkManager'
NM_IFACE = 'org.freedesktop.NetworkManager'

# Create Python object from /org/freedesktop/NetworkManager instance
# in org.freedesktop.NetworkManager application.
nm = bus.get_object(NM_BUSNAME, '/org/freedesktop/NetworkManager')

# Get list of active connections from the properties
# "Get" method is in "org.freedesktop.DBus.Properties" interface
# It takes the interface name which has the property and name of
# the property as arguments.

connections = nm.Get(NM_BUSNAME, 'ActiveConnections',
                     dbus_interface=dbus.PROPERTIES_IFACE)

# While invoking a method on the object, dbus_interface keyword
# argument is provided to specify which interface has the method.

# Now, lets disconnect. This time we are using the NetworkManager
# interface: "org.freedesktop.NetworkManager"
for path in connections:
    nm.DeactivateConnection(path, dbus_interface=NM_IFACE)

If you have questions about this tutorial, you can ask in the comments section below. For more information about D-Bus, my references:

Install LESS on Ubuntu with npm

LESS is available on Ubuntu repositories as “node-less” package. However, as of writing this post, it is an old version (1.3.1) which contains lots of bugs, while a newer and more stable one (1.3.3) is available. And you can install latest LESS version with npm:

sudo apt-get install npm
sudo npm install -g less

Because the command name of the node.js is nodejs (instead of node) on Ubuntu, when the installation is complete, you need to change this first line of lessc command. Open /usr/local/bin/lessc with your favorite text editor (with root privileges), and change the end of the first line from node to nodejs.

--- lessc.old	2013-05-21 13:50:00 +0300
+++ lessc	2013-05-21 13:51:00 +0300
@@ -1,4 +1,4 @@
-#!/usr/bin/env node
+#!/usr/bin/env nodejs
 
 var path = require('path'),
     fs = require('fs'),

After saving the file, you can test if lessc command is available, and the correct version is installed.

which lessc
lessc -v

If you have any trouble, you can ask me on the comment section below.

VirtualBox, Shared Folders and Cache

I have recently set up a virtual server environment using VirtualBox for quick web development. Using shared folders feature, I wanted to avoid file uploads between VM host and guest. However, when I make request to an updated a file, server responses with the old version.

First, I cleared and disabled my browser cache. The result was the same. Second, I checked the file both on host and guest machines. Both were up to date, so the issue was about the server. Then I have made some experiments with expires headers, again, no luck.

I continued searching on the internet and found this blog post. Sendfile option is disabled by default on Nginx (see documentation), but apparently Ubuntu had turned it on with the configuration file on the package. You can turn it off by setting the flag off or commenting the line:

# sendfile on;
# or
sendfile off;

Sendfile is enabled by default of Apache. In order to turn it off, you can refer to the official documentation here.

Google Play Port Number for Android Devices

An Android device contacts Google Play servers for several reasons, such as checking internet connectivity, push notifications and application installations triggered from web. These services will fail to operate if the Google Play ports are blocked in your network (mobile data, wireless, vpn).

If you are using a firewall and would like to allow (or block) these services, Google Play uses TCP and UDP 5228 port. You can refer to connectivity requirements page on Google Play Help for more information.

Storing MAC address in a MySQL database

Today, I encountered a problem: storing MAC address in a MySQL database. MAC addresses (something like “01:23:45:67:78:AB”) contain six hexadecimal (base 16) values. This means each hexadecimal field can store 256 (2 to the power of 8, in base 10) values. It’s 8 bits (= 1 byte) for each value.

6 field x 8 bit = 48 bit = 6 bytes

Thus, instead of storing the address as string, I prefer to store it as an integer. Because as a string (without colons “0123456789AB”), it can be stored in 12 bytes. Storing MAC address as integer allows us to store it using less space and also fast indexing.

In database, we can use unsigned BIGINT data type as it can store up to 8 bytes. While reading from database,

SELECT HEX(mac_addr) FROM `devices`;

While saving,

INSERT INTO `devices` (mac_addr) VALUES (x'0123456789AB');

If you prefer to make conversions in PHP,

function mac2int($mac) {
    return base_convert($mac, 16, 10);
}

function int2mac($int) {
    return base_convert($int, 10, 16);
}

You can use this function to make the address human readable

function int2macaddress($int) {
    $hex = base_convert($int, 10, 16);
    while (strlen($hex) < 12)
        $hex = '0'.$hex;
    return strtoupper(implode(':', str_split($hex,2)));
}

WikiLeaks Cablegate Count v2

Since the official WikiLeaks page has changed, the previous script needs to be updated. Here it is:

import urllib, piksemel, re

wleaks = int(re.search(r"(d+) / [0-9,]+", piksemel.parseString(urllib.urlopen("http://www.wikileaks.ch/cablegate.html").read()).getTag("body").getTag("div").getTag("div").getTag("a").nextTag().getTag("p").toString()).groups()[0])

Please remember to install piksemel module.