2013-03-23

PHP - utf-8 strings handling

PHP - utf-8 strings handling

Enable mbstring function overloading mode and set default encoding for string functions to utf-8 in php.ini:

mbstring.internal_encoding = UTF-8
mbstring.func_overload = 7

These settings allow us to use "usual" php string functions like substr() for utf-8 strings. It is not recommended to set function overloading in per-directory context (via Apache config or in the .htaccess).

Default encoding can also be set using mb_internal_encoding function:

mb_internal_encoding('UTF-8');

Or encoding can be set explicitly as argument in mbstring function:

$sub = mb_substr($mbstr, 0, 1, 'utf-8');

Links

PHP Docs - Multibyte String

Yii Wiki - How to set up Unicode

2013-03-19

Want Scalable Application Architecture? Check AngularJS.

Want Scalable Application Architecture? Check AngularJS.

The Scalable JavaScript Application Architecture is a presentation by Nicholas Zakas where he suggests a flexible and scalable architecture for JavaScript applications. Here are other related resources:

The presentation is interesting but it also leaves many open questions. In short, the architecture contains following application layers:

  • base library (jquery, etc)
  • application core:
    • manages modules (register modules, tell when to start and when to stop)
    • handle errors (like wrap all modules' methods into try/catch and log errors)
    • enable inter-module communication
    • should be extensible (error handling, ajax wrapper, general utilites, anything!)
    • can use base library
  • sandbox:
    • facade for modules above the core
    • interaction between modules via messages (events)
  • modules:
    • do not know about each other, only about sandbox
    • call only own methods or sandbox methods
    • DOM access only inside own box (but do not use base library)
    • no access to non-native global objects, don't create global objects
    • ask sandbox for anything you need, don't reference other modules
    • preferably no access to base library, use pure JS

Here are some questions raised by the presentation:

  • It is mentioned that the architecture covers 'controller' part of MVC, but it is not clear how to plug M and V here. Should the module act as controller and handle model / view interaction (this can be complex without access to the base library)? For me the 'module' here looks more like a widget - some self-contained element with own box in the HTML and related js code.
  • Modules do not interact directly and only send messages to each other. This way we can change them independently. But messages are sent with some data and the receiver should expect some data structure. So in the case when this data changes it is necessary to review and fix all possible receivers.
  • App core responsibilities are too wide (rememver "anything!") and the same is related to sandbox (because it acts as a facade on top of the core).

Of course good answers can be found for all these points and more questions can be raised. It is clear that the suggested architecture is an idea and the way to go but not a complete design. It was interesting to see if there are frameworks build upon this idea. And here is the list (descriptions are taken from their sites):

  • Aura is a decoupled, event-driven architecture for developing widget-based applications.
  • Hydra.js is the library that will help you to scale your app.
  • Kernel.js is an ultra lightweight (~4k) architecture for building scalable javascript applications.
  • TerrificJS provides you a Scalable Javascript Architecture, that helps you to modularize your jQuery/Zepto Code in a very intuitive and natural way.
  • scaleApp is a tiny JavaScript framework for scalable One-Page-Applications / Single-Page-Applications.
  • framework by Legalbox - the Scalable JavaScript Application framework.
  • AngularJS - Superheroic JavaScript MVW Framework.
  • Stackoverflow question on the topic

Presence of the AngualrJS here can be unexpected and reasons why I included it are below. Others are directly built on the idea from Nicholas' presentation and most popular of them (looking at the number of stars on the github) is Aura. Here are todo application examples built on Aura.

So why AngularJS is here? Actually I do not have much experience with it, but from what I know it looks very close to the Nicholas' Scalable Architecture:

  • base library - jQuery or angular's own jqLite implementation
  • app core - angular itself
  • sandbox - scope passed to the controller
  • module - angular's controller

Besides the main parts of the scalable architecture AngularJS has more. For example, along with the sandbox (scope) we can pass additional services to the controller (like $http for ajax requests). So the sandbox does not turn into a God-object with too much responsibilities.

And angular controllers are very similar to scalable architecture modules:

  • self-contained and sandboxed
  • can be built in pure JS without access to the base library
  • interaction between modules is done via events or via special service but not directly

This way the idea of the scalable architecture is present in the AngularJS. And angular also gives other essential components (views, models, services, etc) and provides complete and ready to use architecture.

2012-12-17

Speedup unit tests by moving MySql data to memory [Ubuntu]

Speedup unit tests by moving MySql data to memory [Ubuntu]

There are several ways to speedup slow unit tests which interact with database:

  • Refactor code and tests and do not interact with db in unit tests
  • Use sqlite db in memory instead of MySql
  • Use MySql MEMORY engine
  • Move MySql data to memory

It is better to try other listed approaches and I think of last method as of quick temporary hack, but here it is:

  • stop mysql
  • move /var/lib/mysql to /dev/shm/mysql
  • link /var/lib/mysql to /dev/shm/mysql
  • start mysql

In Ubuntu there is also a problem with apparmor which will not allow mysql to read from /dev/shm. To fix this it is recommended to add following to the /etc/apparmor.d/usr.sbin.mysqld:

/dev/shm/mysql/ r,
/dev/shm/mysql/** rwk,

But it doesn't work for me and I disabled apparmor for mysql (not recommended):

sudo mv /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable

Below are shell scripts to move MySql data to /dev/shm and back, restore backed up data and check db state.

Move db to memory script

#!/bin/sh
#Check if run as root
if [ `whoami` != root ]
then
    echo "You must be root to do that!"
    exit 1
fi

service mysql stop
if [ ! -s /var/lib/mysql.backup ]
then
    cp -pRL /var/lib/mysql /var/lib/mysql.backup
fi
mv /var/lib/mysql /dev/shm/mysql
chown -R mysql:mysql /dev/shm/mysql
ln -s /dev/shm/mysql /var/lib/mysql
chown -h mysql:mysql /var/lib/mysql
service mysql start

Move db to disk script

#!/bin/sh
#Check if run as root
if [ `whoami` != root ]
then
    echo "You must be root to do that!"
    exit 1
fi

service mysql stop
rm /var/lib/mysql
if [ ! -s /dev/shm/mysql ]
then
    cp -pRL /var/lib/mysql.backup /var/lib/mysql
else
    mv /dev/shm/mysql /var/lib/mysql
fi
service mysql start

Restore db backup script

#!/bin/sh
#Check if run as root
if [ `whoami` != root ]
then
    echo "You must be root to do that!"
    exit 1
fi

service mysql stop
if [ ! -s /var/lib/mysql.backup ]
then
    exit -1
fi
rm /var/lib/mysql
cp -pRL /var/lib/mysql.backup /var/lib/mysql
rm -rf /dev/shm/mysql
service mysql start

Check db state script

#!/bin/sh
#Check if run as root
if [ `whoami` != root ]
then
    echo "You must be root to do that!"
    exit 1
fi

if [ -L /var/lib/mysql ]
then
    echo "Mem db"
    exit 0
else
    echo "File db"
    exit 1
fi

Links

Unit test application including database is too slow

Force an entire MySQL database to be in memory

How to run django's test database only in memory?

Script to put mysqld on a ram disk in ubuntu 10.04. Runs on every hudson slave boot

MySQL tmpdir on /dev/shm

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

2012-12-09

PHP - friend a class via extend

PHP - friend a class via extend

C++ allows to declare one class as a friend of another one.

This can be useful if you want to keep some details of class protected, but available for another particular (friend) class.

For example this can be used in State pattern to keep setState method of context class protected.

To emulate this in PHP we can inherit state class from context class:

class AContext {
    private $_state;

    protected function setState(AState $state) {
        $this->_state = $state;
    }

    public function request() {
        $this->_state->handle();
    }

}

abstract class AState extends AContext {
    private $_owner;

    public function __construct(AContext $owner) {
        $this->_owner = $owner;
    }

    protected function getOwner() {
        return $this->_owner;
    }

    abstract function handle();

}

class AConcreteState extends AState {

    public function handle() {
        ...
        $this->getOwner()->setState(new AnotherState($this->getOwner());
    }
}

class AnotherState extends AState {
    ...
}

Window managers for Google Chrome

Window managers for Google Chrome

A list of extensions to manage position of chrome tabs / windows and to create splits. Descriptions are original texts from extension pages.

Tabs Outliner

Next Generation Session/Windows/Tabs Manager and Too_Many_Open_Tabs Solution That Really Works.

  • Ultimate overview for all of your open, and not so open (read further), browser windows and tabs, in a resizable vertical side view, with a Tree Style Tab feature.
  • A KILLER FEATURE – Has the unique ability to close and preserve “in place” any tab or window, without removing them from the original context in the tree. Then, if needed, reopen them in the same way you select already open windows or tabs. This is a real innovation in Web browser usability. It diminishes the cognitive distinction between closed-preserved and open tabs. Therefore, there will be no substantial difference between closed or open tabs, and because of this, there will be no desire to keep them all open anymore!!!
  • Outliner Features – You will be able annotate open or closed windows and tabs, add comments to them, notes, a summary of main ideas, to-do items. Organize all of this in logical hierarchies and delimited groups; freely reorder to specify priority or importance.
  • Crash Resistance and Restore Feature Done Right.

Frame two pages

Merge the active tab and the previous one into a frameset.

Once you click at the extension's icon, the current tab will be merged with the previous one (on the left) into a frameset with two columns (frames) or rows (options offer 3 buttons: rows/columns/ad_hoc). They'll be ordered in the same way as the tabs (left, right).

In other words, your physical screen will be split into two areas.

If the current window only has one tab, you'll be asked about the URL of the left frame. Recursive frames work - e.g. if you activate the extension on a new tab - but each smaller frame's URL has to be typed manually ("same origin policy").

This gadget may be helpful if you are e.g. translating one page to another page or otherwise editing a text, using two windows.

Split Screen

Prompts the user for two URL addresses and then displays both in one window!

Opens a new tab and prompts the user for two URL's, then displays both sites on one page. Great for cross-reference studying and surfing the web in general! Watch a video, (or wait for it to buffer) while you surf another webpage.

Dual View Split Screen

Splits the screen into two vertical tiles. Dual View Split Screen lets you split your screen into two vertical tiles. You are able to view two different pages side by side which comes in handy when you want to compare content, translate content and so on.

Click on the screen icon in your browser bar. You will be asked to provide the URL of the left window. Then you will be asked for the right window accordingly.

Nothing else to take care of. It is as easy as that. Enjoy!

Alum: Window and tab manager

This extension is for power users who constantly find themselves moving around windows and tabs to maximize usable screen area. The goal is efficiency and reducing RSI. Please see the video at right for a full demo of Alum.

Features:

  • Open non-overlapping windows to take up full screen area
  • Rotate tabs between windows under Alum's control
  • Focus stays on primary content window-- never touch your mouse!
  • Move tabs between Alum windows for quick webpage classificiation
  • Hot-keys for all actions

Known issues:

  • No support for multiple monitors
  • A few screen pixels unaccounted for on Mac OS X

Dualless

Dualless - For those who don't have dual monitor. Dualless splits your browser windows into two by just 2 clicks. The ratio can be adjusted according to your needs.You may have a browser window showing on the right that occupy 30% of your screen. Then the rest of space leave to Google+.

The extension simulates the environment of dual monitor. Utilize the space for 16:9 monitor.

Chromie: Window and Tab Tools

Manipulates (splits, merges, scrolls, indexes) Chrome's windows with simple clicks.

  • Split/Merge Chrome Windows to occupy the whole screen with different workspaces.
    • Double-click Chromie icon to create 2 workspaces.
    • Triple-click Chromie icon to create 3 workspaces.
    • Quadruple-click to create 4 workspaces.
    • and so on to unlimited workspaces theoretically (but it seems that 4 windows or less are the most efficient).
    • Yeah and of course, single-click will merge all windows into 1 big Chromie.
    • Another single-click will toggle between the big Chromie and the original Chromie where we started off with.
  • Synchronize Windows scrolling actions (syncScroll) among different windows by holding Alt + mouse wheel(or Shift + mouse wheel will be implemented soon enough).
  • There are options of layouts for you to pick and you decide how fast you can click by choosing click timeout parameter (where 200 millisecs is recommended).

Tab Resize - split screen layouts

Split Screen Layouts made easy. Automates resizing tab windows to predefined and user defined layouts. A simple extension designed to provide ease in resizing your tabs. A set of default layouts are provided but you can add and remove from the list of layouts to fit your needs.

DEMO video

How it works

  • The selected/highlighted tab along with all tabs to the right of it will be considered. Whether you have more or less tabs than are needed the extension will resize only the available tabs.
  • Undo button will undo the previous layout resize. You can only perform undo once at any time.
  • In 'single tab' mode, only the selected/highlighted tab will considered. Only the current window/tab will change in size, all other tabs to the right will be ignored.
  • You can create your own custom layouts within reason and reset to default configurations if desired. Layouts are sorted most recent used on right.

Tab Scissors

This simple tab organization tool divides one window into two. If you have at least two tabs in the selected Chrome window, it… This simple tab organization tool divides one window into two. If you have at least two tabs in the selected Chrome window, it will split that window into two smaller side-by-side windows. All the tabs on the left side of the selected tab will stay in the left window, and the rest will move to the window on the right. It is especially helpful for those who have lots of tabs opened at a time. This extension works great with Tab Glue, which will glue all those pesky Chrome windows back together.

Split Meister V

Makes a vertical split by productively moving the tab to the side, instead of using frames. This extension makes a vertical split for vieing two tabs at once. It's accomplished by resizing your current window, and putting the current tab to the right of it.

Other

Browser instead of window manager

Project Tab Manager

2012-11-16

git - rename a submodule

git - rename a submodule

Rename a submodule:

$ mv submodule-oldpath ~/another-location
$ git rm submodule-oldpath
$ git submodule add submodule-repository-URL submodule-newpath

Result:

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
# renamed: submodule-oldpath -> submodule-newpath

Links

Bertrand Cachet - Rename Git submodule

2012-10-10

GImport yii extension

GImport yii extension

GImport yii extension implements recursive import of directories with caching.

Import is performed recursively for specified path alias. Classes found are cached, so the import process can be slow only first time.