Get error message “G is null” or “a is null” on jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var obj = null;
    // ...maybe there are complexed lines...
    $.each(obj, function(){
    });
});
</script>

Will get an error message “a is null”. When using jquery.min.js, it might be hard to recognize what kind of error it is. On version 1.3.2 the message says “G is null”.

Posted in Tweak | Tagged , | Leave a comment

Bracket auto completion in vim for PHPer

I used to use this setting in .vimrc:

inoremap \( (
inoremap ( ()<LEFT>

But escape bracket every time for

second\(first();

is a little bit stressful. (typed “first()”, then move to the head of the line, typing “second”, back slash and bracket)

Here is an improved script:

function! CompleteDetachedBracket()
    let line = line('.')
    let col = col('.')
    let c = getline(".")[col(".")]
    execute "normal \<RIGHT>%"
    if c == "$"
        execute "normal 2wi)"
    elseif line != line('.') || col != col('.')
        execute "normal a)"
    else
        execute "normal a)"
        startinsert
    endif
endfunction
inoremap ( (<ESC>:call CompleteDetachedBracket()<CR>

This is the first time to code vim script for me. I was guessing vim script is a weird language, so have avoided long time. But at least coding small one is not so difficult than I thought. Documentation is very organized. There are many sample codes in your .vim/plugin directory. Not like a GUI programming, but still like a Tetris. It maybe just because of the first time, I think it’s pretty fun.

Posted in Create | Tagged | Leave a comment

Convert multiple object to array in PHP

For simple object, just use cast syntax should be fine.

$array = (array)$object;

However, this way doesn’t work for complexed object (or array+object combination) like this:

array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(1)
  }
}

Then, simply this one liner works well.

$multipleArray = array_map('get_object_vars', $complexedObject);

Since I’m getting use more json_decode(), I get “PHP Fatal error: Cannot use object of type stdClass as array” sometimes. Actually in this context, to use the second parameter of json_decode is the simplest way.

$it_will_be_array = json_decode($json, true);
Posted in Tweak | Tagged | Leave a comment

Complete working sample for Services_Twitter OAuth in PHP PEAR

% pear install --alldeps Services_Twitter-alpha

You can get some sample codes for Services_Twitter with OAuth from php doc, but it’s not a complete code. I rewrite some parts.

<?php
if (isset($_GET['clear'])) { // sometimes you need to clear session, just access ?clear=1
    session_start();
    $_SESSION = array();
    session_destroy();
    die('session has been cleared.');
}
 
 
define('CONSUMER_KEY', '***');
define('CONSUMER_SECRET', '***');
 
 
require_once 'Services/Twitter.php';
require_once 'HTTP/OAuth/Consumer.php';
 
try {
    session_start();
 
    if (isset($_SESSION['token2'], $_SESSION['token_secret2'])) {
        $twitter = new Services_Twitter;
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token2'], $_SESSION['token_secret2']);
        $twitter->setOAuth($oauth);
        print_r($twitter->statuses->home_timeline());
 
    } else if (isset($_SESSION['token'], $_SESSION['token_secret'], $_GET['oauth_verifier'])) {
        $twitter = new Services_Twitter;
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'], $_SESSION['token_secret']);
        $oauth->getAccessToken('http://twitter.com/oauth/access_token', $_GET['oauth_verifier']);
        $twitter->setOAuth($oauth);
 
        $_SESSION['token2'] = $oauth->getToken();
        $_SESSION['token_secret2'] = $oauth->getTokenSecret();
 
        $msg = $twitter->statuses->update("I'm coding with PEAR right now!");
        print_r($msg);
 
    } else {
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET);
        $oauth->getRequestToken('http://twitter.com/oauth/request_token', 'http://zuzara.com/twitter_oauth.php'); // callback URL should be the same as that you registered at http://twitter.com/apps/new
 
        $_SESSION['token']        = $oauth->getToken();
        $_SESSION['token_secret'] = $oauth->getTokenSecret();
 
        $url = $oauth->getAuthorizeUrl('http://twitter.com/oauth/authorize');
 
        http_redirect($url); // function from pecl_http
    }
 
} catch (Exception $e) {
    echo $e->getMessage();
}
Posted in Tweak | Tagged , , , | Leave a comment

Compiling mongo php driver on pecl for MAMP

MAMP 1.8.2 includes pecl but actually it doesn’t work. When trying to “pecl install mongo”, there will be an error.
grep: /Applications/MAMP/bin/php5/include/php/main/php.h: No such file or directory

So, I downloaded source tar ball of PHP 5.2.10 (same version as MAMP’s PHP) and configure && make && make install. Then $prefix/include directory will be created. Just copy them into /Application/MAMP/bin/php5/. It might be better to set prefix like this “./configure –prefix=/opt/apps/php-5.2.10″

Now pecl works well. You can get version 1.0.2 right now.

BTW, there is a link for a compiled .so file (http://osdir.com/ml/mongodb-user/2009-11/msg00463.html) but it’s old (1.0.0+) that means “$connection->database” syntax doesn’t work well.
Notice: Undefined property: Mongo::$database in /Users/nobu/Sites/mongo.php on line 4

Posted in Tweak | Tagged , , | 1 Comment

Load remote CSS file dynamically with jQuery

These codes are for dynamic loading for remote CSS. It’s easy to load all CSS files from the beginning or just append link element (ref. Switch stylesheets with jQuery). But it rarely needs to load a file dynamically and wait until CSS file has been loaded completely.

test.html:

<html>
<head>
<title>css.html</title>
<script src="/jquery-1.3.2.js"></script>
<script>
$(document).ready(function()
{
     // if it's a local file just using $.get() should be fine
    $.getJSON('http://remote-server/css.php?callback=?', function(data){
        //$('head').append('<style>');
        //$('head > style:last').html(data); // it doesn't work on IE
        $('body').append('<style>' + data + '</style>');
        //  edit dom tree. these elements need new properties of stylesheet
        $('body').append('<div id="something-special"><h1>Hello World!</h1></div>');
    });
});
</script>
</head>
<body>
</body>
</html>

css.php:

<?php
ob_start();
?>
 
div#something-special h1 {
    color: red;
}
 
<?php
sleep(10); // it's for test
if (isset($_GET['callback'])) {
    $buf = ob_get_contents();
    ob_clean();
    echo filter_var($_GET['callback'], FILTER_SANITIZE_STRING), '(', json_encode($buf), ')';
}
Posted in Tweak | Tagged , , | Leave a comment

Catch Up On The News Mashup For Social Media

“Catch Up On The News” is a mashup for social news media such as digg, tweetmeme, techmeme and delicious. It is showing top 20 popular articles from yesterday, last week or whenever you can specify.

Do you have an experience that after finishing a vacation, would like to read a week’s news all at one time? This is what you’re looking for.
catchup_screenshot

Posted in Create | Tagged , | 1 Comment

Call a method of object with string in JavaScript

var call_user_func = function(obj, method) {
    return eval('obj.' + method).apply(obj, Array.prototype.slice.call(arguments, 2));
}
var test1 = {
    method1: function(arg1, arg2, arg3) {
        return alert(arg1 + arg2 + arg3);
    }
}
call_user_func(test1, 'method1', 1, 2, 3);

It works on Firefox3, Safari4, IE6.

Posted in Uncategorized | Leave a comment

tpcc-mysql rough benchmark for Amazon RDS

I tried to do tpcc-mysql benchmark for Amazon RDS. Before do that, did the same test for EC2 small instance.

From EC2 small instance to small. Fedora8 and MySQL 5.0.45. Default configuration. (no change for a my.cnf; innodb_buffer_pool_size = 8388608)

# mysql -h domU-12-31-39-06-7C-86.compute-1.internal -u mymasteruser -p
mysql> grant all privileges on tpcc.* to tpcc@'%' identified by 'hogehoge';
mysql> create database tpcc;
# mysql -u tpcc -p -h domU-12-31-39-06-7C-86.compute-1.internal tpcc < create_table.sql
# mysql -u tpcc -p -h domU-12-31-39-06-7C-86.compute-1.internal tpcc < add_fkey_idx.sql
# ./tpcc_load domU-12-31-39-06-7C-86.compute-1.internal tpcc tpcc hogehoge 10
# ./tpcc_start domU-12-31-39-06-7C-86.compute-1.internal tpcc tpcc hogehoge 10 3 60 60
527.000 TpmC
# ./tpcc_start domU-12-31-39-06-7C-86.compute-1.internal tpcc tpcc hogehoge 10 6 60 180
560.667 TpmC

Changed to innodb_buffer_pool_size = 1336934400. (same as RDS small instance) Drop database, and restore. Then,

# ./tpcc_start domU-12-31-39-06-7C-86.compute-1.internal tpcc tpcc hogehoge 10 6 60 180
2358.667 TpmC

From EC2 small instance to RDS small instance. (MySQL 5.1.38)

# ./tpcc_load myinstance.cpxpgflqvl3w.us-east-1.rds.amazonaws.com tpcc tpcc hogehoge 10

There will be an error "server phrase is too long". Use IP address.

# ./tpcc_start 10.210.155.149 tpcc tpcc hogehoge 10 6 60 180
2437.000 TpmC

This is a pretty rough benchmark, but I can say EC2 small instance and RDS small instance have the same performances as CPU and memory are the same spec. RDS is about 30% expensive. (EC2=$0.085, RDS=$0.11/h)

ref) tpcc-mysqlによるMySQLのベンチマーク

Posted in Tweak | Tagged , | 1 Comment

Amazon RDS quick start

I’ve tried to use Amazon Relational Database Service. Easy to scale-up appeals to me.

Official Getting Started Guide is very good. I almost followed this document.

Works on Mac OSX 10.5.8.

% rds-create-db-instance --db-instance-identifier myinstance  --allocated-storage 5 --db-instance-class db.m1.small --engine MySQL5.1 --master-username mymasteruser --master-user-password **** --db-name MyDatabase --headers

It takes several minutes.

% rds-describe-db-instances --headers
Unable to find a $JAVA_HOME at "/usr/", continuing with system-provided Java...
Unable to find a $JAVA_HOME at "/usr/", continuing with system-provided Java...
DBINSTANCE  DBInstanceId  Class        Engine    Storage  Master Username  Status    AZ          Backup Retention
DBINSTANCE  myinstance    db.m1.small  mysql5.1  5        mymasteruser     creating  us-east-1d  1
      SECGROUP  Name     Status
      SECGROUP  default  active
      PARAMGRP  Group Name        Apply Status      PARAMGRP  default.mysql5.1  in-sync
% rds-describe-db-instances --headers
Unable to find a $JAVA_HOME at "/usr/", continuing with system-provided Java...
Unable to find a $JAVA_HOME at "/usr/", continuing with system-provided Java...
DBINSTANCE  DBInstanceId  Created                   Class        Engine    Storage  Master Username  Status     Endpoint Address                                     Port  AZ          Backup Retention
DBINSTANCE  myinstance    2009-10-30T07:01:42.163Z  db.m1.small  mysql5.1  5        mymasteruser     available  myinstance.cpxpgflqvl3w.us-east-1.rds.amazonaws.com  3306  us-east-1d  1
      SECGROUP  Name     Status
      SECGROUP  default  active
      PARAMGRP  Group Name        Apply Status
      PARAMGRP  default.mysql5.1  in-sync

There is an error about $JAVA_HOME, but it works.

% rds-authorize-db-security-group-ingress default --ec2-security-group-name mytestgroup --ec2-security-group-owner-id 69145810****

You can see ec2-security-group-name (Security Groups) and ec2-security-group-owner-id (Owner) on AWS Management Console for EC2.

Login to EC2 server, then:

# mysql -h myinstance.cpxpgflqvl3w.us-east-1.rds.amazonaws.com -P 3306 -u mymasteruser -p

Create snapshot, and delete.

% rds-create-db-snapshot myinstance --db-snapshot-identifier myinstance-snapshot
% rds-delete-db-instance myinstance --skip-final-snapshot true --headers

It takes a couple of minutes.

Restore.

% rds-restore-db-instance-from-db-snapshot myinstance2 --db-snapshot-identifier myinstance-snapshot

Modify instance size (scale-up).

% rds-modify-db-instance myinstance --db-instance-class db.m1.large --apply-immediately

small to large takes about 5 minutes. (mysqldumped-size is 700MB)

similar post:
tpcc-mysql rough benchmark for Amazon RDS

Posted in Tweak | Tagged | Leave a comment
  • About

    I'm Nobu, a web developer living in Mountain View, CA. Feel free to comment on any posts. I'm also tweeting on twitter.

  • Archives

  • Recent Posts