Saturday, July 26, 2014

Quick Guide to Using MySQL in Python

If you are using windows 7 32 bit, then download the python-mysql-connector msi installer and install first.

MySqlPython.py


import MySQLdb
import sys

try :
    db = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="python")
except Exception:
    pass

if db is None:
    print("The database could not connect");
    sys.exit(0)
else:
    print("The database connected");
    cursor = db.cursor();

def executeQuery(query, params = None):
    return cursor.execute(query, params);

def listQuery(query, params = None):
    cursor.execute(query, params);
    return cursor.fetchall();

def readQuery(query, params = None):
    cursor.execute(query, params);
    return cursor.fetchone();

print("Deleting all user from database");
executeQuery("DELETE FROM USER");

print("Inserting user to database...");
query = """Insert into user(name, roll) values(%s, %s)""";
params = ('Pritom', '001');
result = executeQuery(query, params);
print("Insert result: " + str(result));

params = ('Sumon', '002');
result = executeQuery(query, params);
print("Insert result: " + str(result));

params = ('Liton', '003');
result = executeQuery(query, params);
print("Insert result: " + str(result));

print("Reading total user count...");
result = readQuery("SELECT COUNT(*) FROM user");
print("Total user: " + str(result[0]));

print("Reading total user list...");
result = listQuery("SELECT * FROM user");
for row in result:
    print("Id: " + str(row[0]) + ", Name: " + str(row[1]) + ", Roll: " + str(row[2]));

cursor.close();
db.close();   
sys.exit();

Output be as follows:


The database connected
Deleting all user from database
Inserting user to database...
Insert result: 1
Insert result: 1
Insert result: 1
Reading total user count...
Total user: 3
Reading total user list...
Id: 66, Name: Pritom, Roll: 001
Id: 67, Name: Sumon, Roll: 002
Id: 68, Name: Liton, Roll: 003

Check Null Value Using Python

fieldNullable = None
fieldNotNullable = 'Some Value'
fieldBoolean = False

if fieldNullable is None:
    print("fieldNullable is null/None")
else:
    print("fieldNullable is not null/None")

if fieldNotNullable is None:
    print("fieldNotNullable is null/None")
else:
    print("fieldNotNullable is not null/None")

if fieldBoolean is None:
    print("fieldBoolean is null/None")
else:
    print("fieldBoolean is not null/None")


class TheClass1:
    def __main__(self, theObject):
        self.theObject = theObject


theClass1 = TheClass1()
if theClass1 is None:
    print("theClass1 is null/None")
else:
    print("theClass1 is not null/None")
    
if theClass1 == None:
    print("theClass1 is null/None")
else:
    print("theClass1 is not null/None")






class TheClass2:
    def __eq__(self, theObject):
        self.theObject = theObject
        #Always return true when check using ==
        return True


theClass2 = TheClass2()
if theClass2 is None:
    print("theClass2 is null/None")
else:
    print("theClass2 is not null/None")
    
if theClass2 == None:
    print("theClass2 is null/None")
else:
    print("theClass2 is not null/None")   

fieldNullable is null/None
fieldNotNullable is not null/None
fieldBoolean is not null/None
theClass1 is not null/None
theClass1 is not null/None
theClass2 is not null/None
theClass2 is null/None 

Install python on windows 7

1. Download python stable version (2.7.8) msi installer from https://www.python.org/download/.

2. After download run the msi installer.

3. Open the Command Prompt. Start > All Programs > Accessories > Command Prompt and type
set path=%path%;C:\Python27\
and hit enter button.


4. Download simplejson from: http://pypi.python.org/pypi/simplejson or from: https://drive.google.com/file/d/0B5nZNPW48dpFNEJSeGJtT2dxX1U/edit?usp=sharing & then extract to any folder your want. Suppose I extracted into C:\simpleJson\ folder.

5. From Command Prompt go to C:\simpleJson\ folder using type: cd C:\simpleJson and then type:
python setup.py install
and hit enter.

6. Open directory at C:\Python27\Lib\site-packages\. You'll see simplejson-2.1.6-py2.7.egg has been added to the directory.

7. Now open IDLE (Start > All Programs > Python 2.7 > IDLE (Python GUI)) and type the following:
>>> import simplejson

8. See all that nothing that happens? Congratulations. You've just installed and imported your first package for Python on Windows 7. Repeat as needed.

9. Finally your are at the end to execute python program in your computer.

Friday, July 25, 2014

Java: Convert Map/List to JSON Using google-gson


package com.pkm.com.java.json;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainClass {
    public static void main(String[] args) {
        Map dataMap = new HashMap();
        dataMap.put("args1", "Args 1");
        dataMap.put("args2", "Args 2");
        dataMap.put("args3", "Args 3");
        dataMap.put("args4", "Args 4");
        
        Map subMap = new HashMap();
        subMap.put("subArgs1", "Sub Args 1");
        subMap.put("subArgs2", "Sub Args 2");
        subMap.put("subArgs3", "Sub Args 3");
        dataMap.put("args5", subMap);
        
        List subList = new ArrayList();
        subList.add("List 1");
        subList.add("List 2");
        subList.add("List 3");
        subList.add(subMap);
        dataMap.put("args6", subList);
        
        Gson gson = new Gson();
        String json = gson.toJson(dataMap);
        System.out.println("json = " + json);
        
        Map dataMapFromJSONString = gson.fromJson(json, Map.class);
        display(dataMapFromJSONString, 0);
    }
    
    private static void display(Map map, Integer depth) {
        for (Object key : map.keySet()) {
            Object value = map.get(key.toString());
            if (value == null) {
                displaySpace(depth);
                System.out.println(key + ": <NULL>");
            }
            else if (value instanceof Map) {
                displaySpace(depth);
                System.out.println(key + ": ");
                Integer nextDepth = depth + 1;
                display((Map) value, nextDepth);
            }
            else if (value instanceof List) {
                displaySpace(depth);
                System.out.println(key + ": ");
                Integer nextDepth = depth + 1;
                display((List) value, nextDepth);
            }
            else {
                displaySpace(depth);
                System.out.println(key + ": " + value);
            }
        }
    }
    
    private static void display(List list, Integer depth) {
        for (Integer index = 0; index < list.size(); index++) {
            Object value = list.get(index);
            if (value == null) {
                displaySpace(depth);
                System.out.println("<NULL>");
            }
            else if (value instanceof Map) {
                displaySpace(depth);
                System.out.print("---->\n");
                Integer nextDepth = depth + 1;
                display((Map) value, nextDepth);
            }
            else if (value instanceof List) {
                displaySpace(depth);
                System.out.print("---->\n");
                Integer nextDepth = depth + 1;
                display((List) value, nextDepth);
            }
            else {
                displaySpace(depth);
                System.out.println(value);
            }
        }
    }
    
    private static void displaySpace(Integer depth) {
        for (Integer index = 0; index < depth; index++) {
            System.out.print("    ");
        }
    }
}

Google gson link
Download full source code

Output:


JSON String = {"args5":{"subArgs1":"Sub Args 1","subArgs2":"Sub Args 2","subArgs3":"Sub Args 3"},"args6":["List 1","List 2","List 3",{"subArgs1":"Sub Args 1","subArgs2":"Sub Args 2","subArgs3":"Sub Args 3"}],"args3":"Args 3","args4":"Args 4","args1":"Args 1","args2":"Args 2"}

Data Display From JSON String:

args5: 
    subArgs1: Sub Args 1
    subArgs2: Sub Args 2
    subArgs3: Sub Args 3
args6: 
    List 1
    List 2
    List 3
    ---->
        subArgs1: Sub Args 1
        subArgs2: Sub Args 2
        subArgs3: Sub Args 3
args3: Args 3
args4: Args 4
args1: Args 1
args2: Args 2

Wednesday, July 23, 2014

Php & MySql oAuth Server & Client Example

Server side common.php (Need to include in all server side scripts)


<?php
require_once 'oauthLibrary/OAuthServer.php';
session_start();
 
// Add a header indicating this is an OAuth server
header('X-XRDS-Location: http://' . $_SERVER['SERVER_NAME'] . '/services.xrds.php');
 
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=oauthdb', 'root', '');
 
// Create a new instance of OAuthStore and OAuthServer
$store = OAuthStore::instance('PDO', array('conn' => $db));
$server = new OAuthServer();
OAuthRequestLogger::enableLogging($store);
?>

Client side common.php (Need to include in all client side scripts)


<?php
session_start();

define("PATH_URL_CLIENT", "/oauth/client");
define("PATH_URL_SERVER", "/oauth/server");

define("REQUEST_TOKEN", "REQUEST_TOKENsdsdfw324ft3f3f34r34");
define("ACCESS_TOKEN", "ACCESS_TOKENkdfj33jdl23");
define("OAUTH_TOKEN", "OAUTH_TOKENdfs34fre45u67jyu");
define("OAUTH_VERIFIER", "OAUTH_VERIFIERslsjlf32j3jlfj");


require './lib/OAuthClient.php';
$client = new OAuthClient('8179e89ff6558cce5628e60643a7124c053cfc204', 'f46dfa522890df25e71ccd9db463a708');

function getServerUrl() {
    return "http://".$_SERVER["HTTP_HOST"].PATH_URL_SERVER;
}

function getClientUrl() {
    return "http://".$_SERVER["HTTP_HOST"].PATH_URL_CLIENT;
}

function toSession($key, $value) {
    $_SESSION[$key] = is_null($value) ? $value : serialize($value);
}

function fromSession($key) {
    if(isset($_SESSION[$key]) && !is_null($_SESSION[$key])) {
        return unserialize($_SESSION[$key]);
    }
    return null;
}
?>

1. Browse http://localhost/oauth/server/registration.html and fill up all fields.


2. You will be view the following information which will need to communication to server.


3. Browse the following url to get the token url, copy the url and browse

4. If you logged in success in server url, you will redirect to your callback url you specified when registration with token & verifier.


5. You are now ready to request data from server.


Download full code example.

Sunday, July 13, 2014

Audio Record Using Java

package com.pkm.sound.record;

import java.io.File;

public class AudioRecorder {
    private static final int RECORD_TIME = 6 * 1000;   // 6 seconds
    
    public static void main(String[] args) {
        File wavFile = new File("Record.wav");
        final SoundRecordingUtil recorder = new SoundRecordingUtil();
        Thread recordThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Start recording...");
                    recorder.start();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.exit(-1);
                }              
            }
        });
         
        recordThread.start();
         
        try {
            Thread.sleep(RECORD_TIME);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
         
        try {
            recorder.stop();
            recorder.save(wavFile);
            System.out.println("STOPPED");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
         
        System.out.println("DONE");        
    }
}

Monday, July 7, 2014

Php, convert time between two timezones


<?php
$src_tz = new DateTimeZone('Australia/Melbourne');
$dest_tz = new DateTimeZone('GMT');

$dt = new DateTime("2014-07-06 00:00:00", $src_tz);
echo 'Australia/Melbourne: ' . $dt->format('Y-m-d H:i:s');
$dt->setTimeZone($dest_tz);
echo '<br/>GMT: ' . $dt->format('Y-m-d H:i:s');

$dt = new DateTime("2014-10-06 00:00:00", $src_tz);
echo '<br/><br/>Australia/Melbourne: ' . $dt->format('Y-m-d H:i:s');
$dt->setTimeZone($dest_tz);
echo '<br/>GMT (DST Enabled): ' . $dt->format('Y-m-d H:i:s');
?>

Output

Australia/Melbourne: 2014-07-06 00:00:00
GMT: 2014-07-05 14:00:00

Australia/Melbourne: 2014-10-06 00:00:00
GMT (DST Enabled): 2014-10-05 13:00:00

Saturday, July 5, 2014

Grails default version=false to all domain classes

Need to write the following line of code Config.groovy:


grails.gorm.default.mapping = { 
    version false 
}

Request Mocking In Grails For Back-end/Background Threads


import javax.servlet.http.HttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.springframework.web.context.support.WebApplicationContextUtils

def getRequest() {
    def webRequest = RequestContextHolder.getRequestAttributes();
    if(!webRequest) {
        def servletContext  = ServletContextHolder.getServletContext();
        def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        webRequest = grails.util.GrailsWebUtil.bindMockWebRequest(applicationContext);
    }
    return webRequest.request;
}


This code can broke while working on a WAR environment. The problem was that the 
MockWebRequest class was part of the org.springframework:org.springframework.test:3.0.3.RELEASE jar 
and had to be included in the BuildConfig.groovy as

dependencies {
    runtime 'org.springframework:org.springframework.test:3.0.3.RELEASE'
}

Ensure that the line:

mavenCentral()


is not commented in BuildConfig.groovy

https://drive.google.com/file/d/0B5nZNPW48dpFd3U2UG9DMmVsX28/edit?usp=sharing

Tuesday, July 1, 2014

Strict Standards: Non-static method Configure::getInstance() should not be called

I Got this error as follows:

Strict Standards: Redefining already defined constructor for class Object in C:\Xampp\htdocs\webapp\cake\libs\object.php on line 54

Strict Standards: Non-static method Configure::getInstance() should not be called statically in C:\Xampp\htdocs\webapp\cake\bootstrap.php on line 38

I solved this problem by changing in /cake/bootstrap.php.

FIND:
error_reporting(E_ALL & ~E_DEPRECATED);

REPLACE:
error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);