GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Thursday, March 31, 2011

JS - Simulation Of Gravitational Forces

<h1>Canvas Element</h1>
<p style="font: 12px sans-serif;">height: <span id="h"></span><br/>velocity: <span id="v"></span></p>
<canvas id="canvas" style="border: 1px solid blue;">Not Supported</canvas>


Share/Bookmark

PyQt - QComboBox

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

cb = QtGui.QComboBox(widget)
label = QtGui.QLabel(widget)

lang = ['Python','Java','Javascript','PHP','C','C++','Ruby']
for i in lang:
    cb.addItem(i)

cb.setGeometry(10, 10, 150, 20)
label.setGeometry(170, 10, 100, 20)

def hello(text):
    label.setText(text)

widget.connect(cb, QtCore.SIGNAL('activated(QString)'), hello)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

Wednesday, March 30, 2011

PyQt - QLineEdit

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

save = QtGui.QPushButton('Save', widget)
name = QtGui.QLineEdit(widget)
show = QtGui.QLabel(widget)

name.setGeometry(10, 10, 200, 20)
save.setGeometry(10, 40, 80, 20)
show.setGeometry(100, 100, 200, 20)

def showText():
    show.setText(name.text())
widget.connect(save, QtCore.SIGNAL('clicked()'), showText)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

pyQt - QProgressBar

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

pb = QtGui.QProgressBar(widget)
pb.setGeometry(10, 10, 300, 20)
pb.setValue(50)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

PyQt - QSlider

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

slider = QtGui.QSlider(QtCore.Qt.Horizontal, widget)
slider.setGeometry(10, 10, 200, 30)
slider.setFocusPolicy(QtCore.Qt.NoFocus)

def getValue(value):
    print value
widget.connect(slider, QtCore.SIGNAL('valueChanged(int)'), getValue)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

PyQt - QCheckBox

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')


show = QtGui.QCheckBox('Ayam Bakar',widget)
show.move(10, 10)

def hello():
    if show.isChecked():
        widget.setWindowTitle('Ayam Bakar')
    else:
        widget.setWindowTitle('')
       
widget.connect(show, QtCore.SIGNAL('stateChanged(int)'), hello)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

PyQt - Multiple CheckBox

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

foods = ['Ayam Bakar','Lalapan','Soto','Sate'];
len = len(foods)
cb = []
a = 0

for i in foods:
    cb.append(QtGui.QCheckBox(i, widget))
    a = a + 1;
   
a = 0
for i in foods:
    cb[a].move(10, 20*a)
    a = a + 1

def hello():
    for i in range(0,len):
        if cb[i].isChecked():
            widget.setWindowTitle(foods[i])
            break;
        else:
            widget.setWindowTitle('None')
           
for i in range(0,len):
    widget.connect(cb[i], QtCore.SIGNAL('stateChanged(int)'), hello)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

PyQt - QPushButton

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')

close = QtGui.QPushButton(QtGui.QIcon('lucia.png'), 'Close', widget)
close.setGeometry(10, 10, 100, 30)

def hello():
    print 'hello everybody'

widget.connect(close, QtCore.SIGNAL('clicked()'), hello)

widget.show()
sys.exit(app.exec_())



Share/Bookmark

PyQt - QWidget

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

#widget.resize(400, 300)
widget.setGeometry(200, 100, 400, 300)
widget.setWindowTitle('PyQt Application')
widget.setWindowIcon(QtGui.QIcon('lucia_2d.png'))
widget.setToolTip('Indonesia is a nice one')
widget.setStyleSheet('background: blue')
widget.setWindowStyle(0.5)

widget.show()
sys.exit(app.exec_())

Share/Bookmark

PyQt - Introduction

Below is the basic setting for displaying the app using PyQt:

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

widget.show()
sys.exit(app.exec_())
Share/Bookmark

Canvas - Gravitational Forces

<!-- This program provide implementation for gravitational forces using Javascript OOP style -->

<h1>Gravitational Forces</h1>
<canvas id="canvas">Not Supported</canvas>

<script>
function GF(id){
 this.x = 30;
 this.y = 0;
 this.width = 50;
 this.height = 30;
 this.screen_width = 500;
 this.screen_height = 2000;
 this.vo = 0;
 this.vt = 0;
 this.ho = 0;
 this.ht = 0;
 this.canvas = document.getElementById(id);
 this.ctx = this.canvas.getContext('2d');
 this.canvas.height = this.screen_height;
 this.canvas.width = this.screen_width;
 this.g = 10;
 this.t = 0;

}
GF.prototype.drawLine = function(){
 for(var i=0;i<100;i++){
  this.ctx.fillStyle = '#444';
  this.ctx.fillText(i,1,i*30);
 }
}
GF.prototype.down = function(){
 this.ht = this.ho + 0.5 * this.g * this.t * this.t;
 this.vt = this.vo + this.g * this.t;
 this.t = this.t + 0.1;

 this.ctx.clearRect(20, 0, this.screen_width, this.screen_height);
 this.ctx.fillRect(this.x, this.ht, this.width, this.height);

 this.ctx.fillStyle = '#10f';
 this.ctx.fillText('v: '+Math.round(this.vt),this.x+5,this.ht+10);
 this.ctx.fillText('h: '+Math.round(this.ht),this.x+5,this.ht+20);
 this.ctx.fillStyle = '#af0';

 var d = this;
 setTimeout(function(){d.down();},100);

}

var gf = new GF('canvas');
gf.down();
gf.drawLine();

</script>

Share/Bookmark

PyQt - Reference

QtGui Reference:
1. Label
   label = QtGui.QLabel('Lucia Corp', widget)
   label.move(10, 10)
2. Button
   button = QtGui.QPushButton('Close', widget)
   button.setGeometry(10, 10, 80, 30)
3. Textarea
    textEdit = QtGui.QTextEdit()
    widget.setCentralWidget(textEdit)
4. Input Dialog
    text, ok = QtGui.QInputDialog.getText(widget, 'Login', 'Enter your name:')
5. Color Dialog
    color = QtGui.QColorDialog.getColor()
6. Font Dialog
    font, okey = QtGui.QFontDialog.getFont()
7. File Dialog
    filename = QtGui.QFileDialog.getOpenFileName(widget, 'Open File', 'E:\')
8. Calendar
    calendar = QtGui.QCalendarWidget(widget)
    print calendar.selectedDate()
9. Pixmap
    pixmap = QtGui.QPixmap('lucia.png')
    label.setPixmap(pixmap)
Share/Bookmark

Tuesday, March 29, 2011

AJAX - Sample Of Post Method

<table>
<tr><td>Name</td><td>:</td><td><input type="text" id="name"/></td></tr>
<tr><td>City</td><td>:</td><td><input type="text" id="city"/></td></tr>
<tr><td>Age</td><td>:</td><td><select id="age">
    <?php
        $output = '';
        for($i=21; $i<61; $i++){
            $output .= '<option value="'.$i.'">'.$i.'</option>';
        }
        echo $output;
    ?>
    </select></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" onclick="Send()" value="Send"/></td></tr>
</table>

<script>
    var lucia = lucia || {};
    lucia.getById = function(id){
        return document.getElementById(id);
    }
    function Send(){
        var name = lucia.getById('name');
        var city = lucia.getById('city');
        var age = lucia.getById('age');
       
        var data = {
            'name': name.value,
            'city' : city.value,
            'age' : age.value
        };
        var json_data = JSON.stringify(data);
       
        var ajax = new XMLHttpRequest();
        ajax.open('POST','hello.php', false);
        ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        ajax.send('data='+json_data);
       
        var response = eval('('+ajax.responseText+')');
       
       
       
       
    }
</script>

Share/Bookmark

PHP - PDO MySQL

<?php

$hostname = 'localhost';
$username = 'root';
$password = 'indonesia';

try{
    $db = new PDO("mysql:host=$hostname;dbname=a", $username, $password);
    echo 'Connected to database';
    $db = null;
}catch(PDOException $e){
    echo $e->getMessage();
}

Share/Bookmark

Drupal - Skills In Drupal

There are some fundamental skills in drupal:
1. Theming
2. Module Creation:
  a. Menu
  b. Form
  c. Ajax
  d. Database
Share/Bookmark

Sunday, March 27, 2011

HTML5 - Rotate

To make rotate transformation, use translate first, then rotate, then back to translate again:
ctx.translate(230,10)
ctx.rotate(45/57)
ctx.translate(-230,-10);
ctx.fillRect(230, 10, 100, 100)
Share/Bookmark

Thursday, March 24, 2011

Drupal - Manu

It's so simple to make a menu in Drupal, just like this below:
<?php

function mac_menu(){
    $item = array();
    $item['mac/main'] = array(
        'title' => 'Mac Menu',
        'page callback' => 'main',
        'access callback' => TRUE,
    );
    return $item;
}

function main(){
    return t('Hello. This is mac main menu');
}
Share/Bookmark

Django - Handling Data

>>> sys.path.append('C:\\Python27\\Project\\App')
>>> sys.path.append('C:\\Python27\\lucia\\blog')
>>> import your_app
>>> import blog

>>> User.object.all()

>>> u = User(username='lady gaga', password='secret')
>>> u.save()

>>> p.id
>>> p.username
>>> p.password

You can update a value in a table just by:
>>> p.username = 'aura kasih'
>>> p.save()

To get the table as object, use:
>>> a = User.objects.all()
>>> for i in a:
        print i.username, i.password
Share/Bookmark

Wednesday, March 23, 2011

Python - Picle

Save a data to file:
>>> import pickle
>>> data = [{'name':'lady gaga','city':'new york','age':24},{'name':'luna maya','city':'denpasar','age':27}]
>>> output = open('lola.txt', 'w')
>>> pickle.dump(data, output)
>>> output.close()

Load a data from a file:
>>> import pickle, pprint
>>> pkl = open('lola.txt', 'r')
>>> data = pickle.load(pkl)
>>> pprint.pprint(data)
Share/Bookmark

WP - Write Plugin

<?php
/**
Plugin Name: Lucia Plugin
Plugin URI: http://hohohuhu.blogspot.com
Description: This plugin will do access database and will do what you want here.
Version: 1.0
Author: Irfanudin Ridho
Author URI: http://hohohuhu.blogspot.com
**/


Share/Bookmark

Tuesday, March 22, 2011

JS - Namespace

To make namespace, do like
var lucia = lucia || {};

Then you can do
lucia.name = 'New York';
lucia.say = function(){
    alert('Okey');
}

More details:
<script>
var lucia = function(){
    return {
        methodA: function(){
            alert('Method A');
        },
        methodB: function(){
            alert('Method B');
        }
    }
};

var a = new lucia();
a.methodB()
a.methodA()

</script>

For private member:
<script>
    var lucia = function(){
    var name = 'Lucia Namespace';
    function say(){
        return name;
    }
    return {
        methodA: function(){
            alert('Method A');
        },
        methodB: function(){
            alert('Method B');
        }
    }
};

var a = new lucia();
a.methodB()
a.methodA()

</script>
Share/Bookmark

Python - Django Setup

To setup Django, do like this:
1. download the django
2. then place the extracted downloaded in python directory.
3. through command line, type: django\setup.py install
4. after it, you will get Script directory created that just consist of one file: django-admin.py
7. type: Scripts\django-admin.py startproject lucia
8. then you will get 4 new files:
   a. __init__
   b. manage
   c. settings
   d. urls
9. run your server by: python.exe lucia\manage.py runserver
10. browse: localhost:8000
Share/Bookmark

Python - Time

>>> from time import strftime, gmtime
>>> strftime('%a, %d %b %Y %H:%M:%S', gmtime())
Share/Bookmark

Python - Regular Expression

Module re is for handling regular expression:
>>> import re
>>> name = re.split(':', 'lady gaga:luna maya:barack obama')
>>> print name
Share/Bookmark

Python - StringIO

StringIO is like a file. We treat a string like a file:
>>> import StringIO
>>> output = StringIO.StringIO()
>>> output.write('Hello World\n')
>>> content = output.getvalue()
>>> output.close();
Share/Bookmark

Monday, March 21, 2011

C - File I/O

The functions used:
For writing to a file
1. fprintf( file_pointer, string_format, argument_lists )
2. fputs( string_data, file_pointer )
3. fwrite
4. fputc( char, file_pointer )
5. putc( char, file_pointer )

For reading from a file, use:
1. fscanf ( file_pointer, string_format, argument_lists )
2. fread
3. fgetc( file_pointer ) : char
4. fgets( char_array, size, file_pointer )


FILE *input;
input = fopen("lola.txt","r");

char a;
while(a != EOF){
    a = fgetc(input);
    putchar(a);
}
fclose(input);
Share/Bookmark

C - Console I/O

The available for console I/O functions are:
General:
1. printf
2. scanf
Character:
3. putchar -> int putchar(char)
4. getchar -> char getchar()
String:
5. puts(char[])
6. gets(char[])

Example using putchar and getchar:
char a;
while(a != '.'){
    a = getchar();
    putchar(a);
}
Share/Bookmark

Joomla - Template Basic

Here's a basic for Joomla templating system. Create two files and place it in a folder then archive it for installing:
1. index.php
<?php defined( '_JEXEC' ) or die( 'Restricted access' );?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/system.css" type="text/css" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/general.css" type="text/css" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template?>/css/template.css" type="text/css" />
</head>
<body>
<jdoc:include type="modules" name="top" />
<jdoc:include type="component" />
<jdoc:include type="modules" name="bottom" />
</body>
</html>

2. templateDetails.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE install PUBLIC "-//Joomla! 1.5//DTD template 1.0//EN" "http://www.joomla.org/xml/dtd/1.5/template-install.dtd">
<install version="1.6" type="template">
        <name>lucia</name>
        <creationDate>2011-05-01</creationDate>
        <author>irfa.ub@gmail.com</author>
        <authorEmail>irfan.ub@gmail.com</authorEmail>
        <authorUrl>http://www.hohohuhu.blogspot.com</authorUrl>
        <copyright>irfan 2011</copyright>
        <license>GNU/GPL</license>
        <version>1.0.2</version>
        <description>My New Template</description>
        <files>
                <filename>index.php</filename>
        </files>
        <positions>
                <position>breadcrumb</position>
                <position>left</position>
                <position>right</position>
                <position>top</position>
                <position>user1</position>
                <position>user2</position>
                <position>user3</position>
                <position>user4</position>
                <position>footer</position>
        </positions>
</install>

Share/Bookmark

Python - MD5

This is the most simple library to use:
>>> import md5
>>> m = md5.new()
>>> m.update('The text')
>>> m.update('You supply')
>>> digested = m.digest()

Share/Bookmark

Python - ZipFile

To list the file name contains in a zip file, type:
>>> import zipfile
>>> f = zipfile.ZipFile('hello.zip', 'r')
>>> for i in f.namelist():
        print i

To get the more info of the files contained in a zip file, type:
>>> for i in f.infolist():
        print i.filename, i.date_time, i.file_size

To read a file from an zip archive, use read method and supply a file name as its argument
>>> content = f.read(file_name[2]);

To create a zip archive, you need to type
>>> f = zipfile.ZipFile('hello.zip', 'w')
>>> f.write('source.txt', 'name_in_archive.txt', zipfile.ZIP_DEFLATED)
>>> f.write('luna.txt', 'maya.txt', zipfile.ZIP_DEFLATED)
>>> f.close()

For appending a file to an existing zip archive file, use append as mode
>>> f = zipfile.ZipFile('hello.zip', 'a')
>>> f.write('lady.txt', 'gaga.txt', zipfile.ZIP_DEFLATED)
>>> f.close()

For writing a string to an zip archive, use
>>> string_data = 'This the data'
>>> info = zipfile.ZipInfo(string_data)
>>> f.writestr(info, string_data)
Share/Bookmark

Python - gzip File

To create a gzip file, type
>>> import gzip
>>> content = 'This is the big text file'
>>> f = gzip.open('hello.gz', 'wb')
>>> f.write(content)
>>> f.close()

To read from a gz file, type
>>> f = gzip.open('hello.gz', 'rb')
>>> content = f.read()

Share/Bookmark

Python - Data Compression With zlib

The first step is import it
>>> import zlib
Then do compress your data
>>> data = 'What this would like to be compressed if you do what you hope'
>>> comprez = zlib.compress(data)

If you want to decompress it, use
>>> decomprez = zlib.decompress(comprez)
Share/Bookmark

Python - File IO

It's simple to write for a file in Python,
>>> hello = open('hello.txt','w+')
>>> data = 'Indonesia is a nice one and what we hope here is like this one'
>>> hello.write(data)
>>> hello.close();

To read a file, use:
>>> hello = open('hello.txt', 'r+')
>>> data = hello.read()         # read all file
>>> data = hello.readlines()    # read all file
>>> data = hello.readline()     # just read one line
Share/Bookmark

Sunday, March 20, 2011

Python - SQLite

To do operating with sqlite, you need
>>> import sqlite3
>>> con = sqlite3.connection('data.db')
>>> cur = con.cursor()
>>> cur.execute('''CREATE TABLE data (name TEXT, age INT, city TEXT)''')
>>> cur.execute('''INSERT INTO data VALUES('lady gaga', 24, 'luna maya')''')
>>> cur.execute('''INSERT INTO data VALUES('luna maya', 27, 'denpasar')''')
>>> cur.execute('''INSERT INTO data VALUES('barack obama', 49, 'white house')''')
>>> con.commit()
>>> cur.close()

To display it, just do
>>> cur.execute('''SELECT * FROM data''')
>>> for row in cur:
       print row
Share/Bookmark

Ajax - TinyMCE Saving

 To get the content of the editor of TinyMCE, use
function save(){
    var mce = tinyMCE.get('content');
    alert(mce.getContent());
}

For initializing the editor, use:
tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Skin options
        skin : "o2k7",
        skin_variant : "silver",       
});

To send the content to the server, use:
function send(){
    var data = tinyMCE.get('content').getContent();
    var ajax = new XMLHttpRequest();
    ajax.open('POST','hello.php',false);
    ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    ajax.send('data='+data);
}

Share/Bookmark

Ajax - Params In Post

To do sending parameter with post, what you need is do a little bit of code:

var ajax = new XMLHttpRequest();
ajax.open('POST', 'hello.php', false);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// below is data you send
ajax.send('name=luna&city=denpasar');

With ajax, you can also get info response from server:
var content_length = ajax.getResponseHeader('Content-length');

Share/Bookmark

JS - Play With Closure

1. var data = ( function(){
        alert('hello');
   });
   data();

2. var data = ( function(name){
        alert(name);
   });
   data('Americas');

3. (function(){
        alert('Hello');
   })();

4. (function(name){
        alert(name);
   })('Americas');

Share/Bookmark

Saturday, March 19, 2011

CPP - Array Of Pointer

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include <vector>
#include <fstream>

using namespace std;

int main(int argc, char *argv[]){
    system("color 2f");

    char *data[2];
    data[0] = "Indonesia";
    data[1] = "Malaysia";

    cout << data[0] << endl;
    cout << data[1] << endl;

    return 0;
}

Share/Bookmark

CPP - Writing To Output File

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char* argv[]){
    ofstream output("lola.txt");
    output << "Indonesia is a nice one" << endl;
    return 0;
}

Share/Bookmark

CPP - Reading A File

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include <vector>
#include <fstream>


using namespace std;

int main(int argc, char *argv[]){
    system("color 2f");

    ifstream input("main.cpp");

    while(input.good())
        cout << (char) input.get();

    return 0;
}



Share/Bookmark

Friday, March 18, 2011

CPP - Data Structure

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include <vector>


using namespace std;

int main(int argc, char *argv[]){
    system("color 2f");

    int age;
    float sallary;
    string name, city;
    bool male;
    char code;

    cout << "Your name: ";
    getline(cin,name);
    cout << "\nYour city: ";
    getline(cin, city);
    cout << "\nYour age: ";
    cin >> age;
    cout << "\nYour code: ";
    cin >> code;
    cout << "\nYour sallary: ";
    cin >> sallary;
    cout << "\nYOur gender is male: ";
    cin >> male;

    string gender;
    if(male){
        gender = "Male";
    }else{
        gender = "Female";
    }

    system("cls");
    cout << "Your data: " << endl;
    cout << "Your name: " << name << endl;
    cout << "Your city: " << city << endl;
    cout << "Your age: " << age << " years old" << endl;
    cout << "Your sallary: " << sallary << " dollars" << endl;
    cout << "Your gender: " << gender << endl;
    cout << "Your code: " << code << endl;


    return 0;
}



Share/Bookmark

CPP - Vector Without Iterator

#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>

using namespace std;

int main(int argc, char *argv[]){
    system("color 2f");

    vector <string> name;

    name.push_back("Luna Maya");
    name.push_back("Aura Kasih");
    name.push_back("Lady Gaga");

    for(int i=0;i<name.size(); i++){
        cout << name[i] << endl;
    }

    return 0;
}



Share/Bookmark

CPP - Map

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>


using namespace std;

int main(int argc, char *argv[]){
    system("color 2f");

    map<string, string> name;
    name["lady"] = "Gaga";
    name["luna"] = "Maya";
    name["barack"] = "Obama";
    name["aura"] = "Kasih";

    map<string, string>::iterator it;

    for(it = name.begin(); it != name.end(); it++){
        cout << (*it).first << " => " << (*it).second << endl;
    }

    return 0;
}



Share/Bookmark

CPP - Classes With Constructor

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Data{
public:
    Data(string, int);
    void setName(string);
    void setAge(int);
    string getName();
    int getAge();
private:
    string name;
    int age;
};
Data::Data(string name="", int age=0){
    Data::name = name;
    Data::age = age;
}
void Data::setName(string name){
    Data::name = name;
}
void Data::setAge(int age){
    Data::age = age;
}
string Data::getName(){
    return Data::name;
}
int Data::getAge(){
    return Data::age;
}


int main(int argc, char *argv[]){
    system("color 2f");

    Data data("Malaysia",12);
    data.setName("Indonesia");
    data.setAge(70);
    cout << data.getName() << endl;
    cout << data.getAge() << endl;
    return 0;
}



Share/Bookmark

CPP - Classes

#include <iostream>
#include <string>

using namespace std;

class Data{
public:
    void setName(string);
    void setAge(int);
    string getName();
    int getAge();
private:
    string name;
    int age;
};

void Data::setName(string name){
    Data::name = name;
}
void Data::setAge(int age){
    Data::age = age;
}
string Data::getName(){
    return Data::name;
}
int Data::getAge(){
    return Data::age;
}


int main(int argc, char *argv[]){
    system("color 2f");

    Data data;
    data.setName("Indonesia");
    data.setAge(70);
    cout << data.getName() << endl;
    cout << data.getAge() << endl;
    return 0;
}



Share/Bookmark

PHP - SQLite3

<?php

// automatically created if doesn't exist
$db = new SQLite3("data.db");

$db->execute("CREATE TABLE data ( name STRING)");
$db->execute("INSERT INTO data (name) VALUES ('Lady Gaga')");

$result = $db->query("SELECT name FROM data");
print_r($result->fetchArray());         // equiv mysql_fetch_array
Share/Bookmark

PHP - Get the result of MySQL

mysql_fetch_row
    Array ( [0] => 2 [1] => corolla [2] => toyota ) 
mysql_fetch_assoc
    Array ( [id] => 3 [brand] => accord [owner] => honda ) 
mysql_fetch_array
    Array ( [0] => 1 [id] => 1 [1] => saab [brand] => saab [2] => gm [owner] => gm ) 
mysql_fetch_object
    stdClass Object ( [id] => 4 [brand] => kijang [owner] => toyota )  

Share/Bookmark

MySQL - View

If you have a base table like this one:
Table car:
   id INT NOT NULL AUTO_INCREMENT KEY,
   brand CHAR(50) NOT NULL UNIQUE
   owner CHAR(50) NOT NULL DEFAULT ''

Then you can have the view like this one:
mysql> CREATE VIEW v_car
       AS SELECT * FROM car
mysql> CREATE VIEW v_car
                 AS SELECT DISTINCT(owner) FROM car
mysql> CREATE VIEW v_car (nama, pemilik)
       AS SELECT brand, owner FROM car
Share/Bookmark

MySQL - Function

mysql> CREATE FUNCTION f()
       RETURNS int DETERMINISTIC
       RETURN 2;
mysql> SELECT f();
mysql> CREATE FUNCTION addTwo(x INT)
       RETURNS int DETERMINISTIC
       RETURN x + 2;
mysql> SELECT addTwo(3);

mysql> CREATE FUNCTION maxId()
       RETURNS int DETERMINISTIC
       RETURN (SELECT MAX(id) FROM data);
mysql> SELECT maxId();


Share/Bookmark

MySQL - Stored Procedure

Look directly to this example:
mysql> DELIMITER //
mysql> CREATE PROCEDURE p()
       BEGIN
           SELECT * FROM data;
       END //
mysql> DELIMITER //
mysql> CALL p()

Other example
mysql> CREATE PROCEDURE p(a INT)
       BEGIN
           SELECT * FROM data WHERE id = a;
       END //

mysql> CREATE PROCEDURE p(a INT)
       BEGIN
           SET @add = 1;
           SELECT * FROM data WHERE id = @add + a;
       END //
Share/Bookmark

MySQL - Trigger

For example you have two table:
1. data
    id int not null auto_increment key,
    username char(50) not null default ''
2. meta
    value int

The syntax for trigger is:
mysql> CREATE TRIGGER t BEFORE INSERT ON data
       FOR EACH ROW INSERT INTO meta VALUES (5);

Trigger time can be one: BEFORE or AFTER
Trigger even can be one: UPDATE, INSERT OR DELETE
Share/Bookmark

Thursday, March 17, 2011

JSON - Response As An Array

When you hope your json response as an array, not as an object, so do it like this one:
Server:
    $data = array();
    $data[] = 'lady gaga';
    $data[] = 'luna maya';
    $data[] = 'barack obama';

    echo json_encode($data);

Client:
    $data = eval('('+ajax.responseText+')');
    for(i=0; i<data.length; i++){
        element.innerHTML = innerHTML + data[i];
    }
Share/Bookmark

jQuery - Manipulating DOM

it's easy to do manipulating DOM using jQuery althought it's not compatible with the native DOM manipulation.
To insert content, use
before - insert outside before the selector
after - insert outside after the selector
append - insert in the inside but the last one
prepend - insert in the inside but the first one
detach - remove the selector as well as its content
empty - remove the all the child inside the selector
remove - remove the selector as well as its event and data.
insertAfter - insert content after the target
insertBefore - insert content before the target
Share/Bookmark

Wednesday, March 16, 2011

C++ - List Of STL

Declaring a list:
list<string> city;

For inserting data to the list at the last position, use:
city.push_back("London");
city.push_back("Singapore");
city.push_back("Sydney");

For inserting data to the list at the first position, use:
city.push_front("Tokyo");

For removing an element at the last position, use:
city.pop_back();

For removing an element at the first position, use:
city.pop_front()

To get the first inserted element, use:
cout << city.front();

To get the last inserted element, use:
cout << city.back()

To iterate all of the elements, use:
list<string>::iterator it;
for(it = city.begin(); it != city.end(); it++){
     cout << *it << endl;
}
Share/Bookmark

C - CMD Alternate Program

/**
 * This program is an alternatif for native cmd program in windows
 * But this version doesn't support for keeping the state.
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @version : 1.0
 * @date    : March 16, 2011
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "lola.h"

int main()
{
    system("color 2f");

    printf("Enter your command for cmd: ");

    // without malloc, the program will broke
    char *pause = malloc(sizeof(char));

    while(strcmp(pause,"exit") != 0){
        fflush(stdin);                  // free the buffer
        gets(pause);
        fflush(stdin);                  // free the buffer

        system(pause);
    }

    return 0;
}


Share/Bookmark

C - Using malloc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 20

int main()
{
    system("color f0");

    printf("Enter your name: ");
    char *name = malloc(sizeof(char));
    fflush(stdin);                      // free the buffer
    gets(name);

    printf("Your age: ");
    int age;
    scanf("%d", &age);

    puts("");
    printf("Your data:\n");
    printf("Name: %s\n", name);
    printf("Age : %d\n", age);

    puts("");
    system("pause");

    return 0;
}

Share/Bookmark

C - Pointer For List

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 20

struct data{
    int age;
    struct data *nextAge;
};

int main()
{
    system("color 2f");

    struct data zero, satu, dua, tiga;
    zero.age = 24;
    satu.age = 27;
    dua.age = 32;
    tiga.age = 55;

    struct data* next, *current;

    zero.nextAge = &satu;
    satu.nextAge = &dua;
    dua.nextAge = &satu;
    tiga.nextAge = NULL;

    current = zero.nextAge;

    int i;
    for(i=0; i< 3; i++){
        printf("%d\n", (current-i)->age);
    }


    return 0;
}

Share/Bookmark

C - Pointer To Structure

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 20

struct data{
    int age;
    struct data *nextAge;
};

int main()
{
    system("color 2f");

    struct data zero, satu, dua, tiga;
    zero.age = 24;

    struct data* ptr;
    ptr = &zero;

    (*ptr).age = 24;

    printf("%d\n", zero.age);
    printf("%d\n", (*ptr).age);
    printf("%d\n", ptr->age);

    return 0;
}

Share/Bookmark

Tuesday, March 15, 2011

C - strncpy

/**
 * This copy n character of the string
 * strncpy(destination, source, n characters)
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 20

int main()
{
    system("color 2f");

    char *data = malloc(sizeof(char));
    strncpy(data,"Indonesia is full countries",10);
    puts(data);

    return 0;
}

Share/Bookmark

C - strcpy And malloc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define N 20

int main()
{
    system("color 2f");

    char *data = malloc(sizeof(char));
    strcpy(data,"Successfull Compliance");
    puts(data);

    char msg[200];
    strcpy(msg, "Indonesia is a nice one");
    puts(msg);

    return 0;
}

Share/Bookmark

C - getchar, putchar and malloc

#include <stdio.h>
#include <stdlib.h>

#define N 20

int main()
{
    system("color 2f");

    // use malloc for avoiding error of system
    char *data = malloc(sizeof(char));

    int i;
    for(i=0;i<N;i++){
        data[i] = getchar();
    }

    int k;
    for(k=0;k<N;k++){
        putchar(data[k]);
    }

    return 0;
}

Share/Bookmark