Developer to developer

Playing yowsup2 and whatsapi

This yowsup2 installation requirement is valid. But I found I had to apt-get install python2.7-dev too, before I can pip install Pillow. Next you can register your number using yowsup-cli. Now test send messages using this command yowsup-cli demos -c -y. Type /help for all command and /L to quick login. Type /message send <number-to> <your-message-here>.

WhatsAPI is more easy to install but I wanna share simple .php test. First git clone the source from github to your /var/www/, and after downloaded, place this php file on /var/www/WhatsApi-Official/.

<?php
require 'src/whatsprot.class.php';
require 'src/events/MyEvents.php';
$username = "your-phone-number ex.62811987654";
$identity = "your-phone-number";
$nickname = "your-phone-number";
$password = "your-password"; // The one we got registering the number
$debug = true;

// Create a instance of WhastPort.
$w = new WhatsProt($username, $identity, $nickname, $debug);
connect(); // Connect to WhatsApp network
$w->loginWithPassword($password); // logging in with the password we got!

//Send Messages
$target = ‘to-phone-number’; // The number of the person you are sending the message ex.6285798766543
$message = ‘Hi! 🙂 this is a test message’;
$w->sendMessage($target , $message);

//Receive Messages
$events = new MyEvents($w);
$events->setEventsToListenFor($events->activeEvents);
$w->pollMessage();
?>

Advertisements
Standard
Daily Snippet, Developer to developer

Installing cx_Oracle (python 2.7) on ubuntu 64 bit

I use non-unicode version.

1. wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.1.2-11g-py27-1.x86_64.rpm

Convert rpm to deb

2. sudo alien -d cx_Oracle-5.1.2-11g-py27-1.x86_64.rpm

Install the deb

3. sudo dpkg -i cx_Oracle-5.1.2-2_amd64.deb

4. The Most important :

cd /usr/lib/python2.7
sudo mv site-packages/cx_Oracle* dist-packages/
sudo rmdir site-packages/
sudo ln -s dist-packages site-packages
sudo ldconfig
 
5. Check import cx_Oracle
Standard
Daily Snippet, Developer to developer

python’s time:html parser

Nyoba-nyoba code dari Dive Into Python tentang html parser.
Code ini akan membuka dokumen html http://www.detik.com dan mengenali semua link di dalamnya.

import urllibfrom sgmllib import SGMLParser

class URLLister(SGMLParser):
    def reset(self):
        SGMLParser.reset(self)
        self.urls = []

    def start_a(self, attrs):
        href = [v for k, v in attrs if k=='href']
        if href:
            self.urls.extend(href)

sock = urllib.urlopen("http://www.detik.com")
parser = URLLister()
parser.feed(sock.read())
sock.close()
parser.close()
for url in parser.urls: print url

Standard
Daily Snippet, Developer to developer

python’s time:using sqlautocode

While playing with sqlalchemy, I want to generate entity class for tables in database. That’s sqlautocode come in.

The first thing to do  to use sqlautocode is declare class DummyConfig where we put connection string.

I have a sqlite file ‘sqlal.db’ and table users and employee.

class DummyConfig:
    def __init__(self, engine='sqlite:///D:/PROYEK/Sample And Exercise goes HERE/pyCoba/src/db/sqlal.db'):
        self.engine  = engine

    example = True
    schema = None
    interactive = None

declare some variable and print your entity class.


from sqlautocode.declarative import ModelFactory
from sqlalchemy.orm import class_mapper

config = DummyConfig()
factory = ModelFactory(config)

factory.used_model_names = []
factory.used_table_names = []

User = factory.create_model(factory._metadata.tables['users'])
Employee = factory.create_model(factory._metadata.tables['employee'])

class_mapper(User, True)
class_mapper(Employee, True)

print User.__repr__()
print Employee.__repr__()

This is the output

class User(DeclarativeBase):
 __tablename__ = 'users'

 #column definitions
 fullname = Column(u'fullname', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))
 id = Column(u'id', INTEGER(), primary_key=True, nullable=False)
 name = Column(u'name', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))
 password = Column(u'password', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))

 #relation definitions

class Employee(DeclarativeBase):
 __tablename__ = 'employee'

 #column definitions
 id = Column(u'id', INTEGER(), primary_key=True, nullable=False)
 nama = Column(u'nama', CHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))

 #relation definitions
Standard
Daily Snippet, Developer to developer

python’s time:how to add column in ArcSDE Tables and fill the value

## Script untuk menambah kolom OLD_FID, OLD_TDATAID, dan UNIT, kemudian mengisinya.
## Inputan : Feature Dataset dan Unit.
## Dilakukan per unit.
import sys, os, re, arcgisscripting, datetime, logging

gp = arcgisscripting.create()
inDataset = gp.GetParameterAsText(0)
unit = gp.GetParameterAsText(1)
logging_path = gp.GetParameterAsText(2)
##  set logging ke file
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=logging_path,
                    filemode='w')

def log_me(gp, msg, is_info):
    gp.AddMessage(str_log)
    if is_info == 1:
        logging.info(str_log)
    else:
        logging.error(str_log)

##boolean method special jika ada error di tengah jalan, maka feature yang dicatat di list_proceed_fc akan di-ignore.
def isInListProceed(nama_fc):

##   list_proceed_fc mencatat feature yang telah diproses, misal: 'SDE.MRuteBM', 'SDE.MTrafo', dan 'SDE.MBlokGardu'
##   list_proceed_fc=('SDE.MRuteBM', 'SDE.MTrafo', 'SDE.MBlokGardu')
    
   list_proceed_fc=('')
   for fcPro in list_proceed_fc:
       if fcPro == nama_fc:
           return True
   return False 

try:
    from time import gmtime, strftime
    str_log = ""

    str_log = "Unit : %s " % unit
    log_me(gp,str_log,1)
    gp.workspace = inDataset

    # Get a list of feature classes in the workspace.
    fcs = gp.ListFeatureClasses()
        
    # Loop through the list of feature classes.
    fcs.reset()
    fc = fcs.next()
    
##    Deklarasi list feature class yang akan diproses
    listProceedFc = []

    while fc:
        listProceedFc.append(str(fc))
        
##      log feature yang akan diproses        
        str_log = "list featureclass : %s " % listProceedFc
        logging.info(str_log)
	
        str_log = "Nama featureclass : %s " % fc
        log_me(gp, str_log, 1)

        
##        Syarat add field  dan pengisian data adalah tidak ada user lain yang locking
##        Add field OLD_FID, Double(38,8)
        try:    
            gp.AddField_management(fc, "OLD_FID", "DOUBLE", 38, 8)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_FID telah ditambahkan."
            log_me(gp, str_log, 1)
            
##        Add field OLD_TDATAID, Double(38,8)
        try:
            gp.AddField_management(fc, "OLD_TDATAID", "DOUBLE", 38, 8)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_TDATAID telah ditambahkan."
            log_me(gp, str_log, 1)

##        Add field UNIT, Text(50)
        try:
            gp.AddField_management(fc, "UNIT", "TEXT", 50)
        except Exception, ErrorFieldExists:
            str_log = "Kolom UNIT telah ditambahkan."
            log_me(gp, str_log, 1)

##        Add field OLD_GLOBALID, Text(50)
        try:    
            gp.AddField_management(fc, "OLD_GLOBALID", "TEXT", 50)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_GLOBALID telah ditambahkan."
            log_me(gp, str_log, 1)

##      update row cursor OLD_FID sangat lambreta. coba ganti dengan gp.CalculateField_management
        gp.AddMessage("CalculateField OLD_FID from OBJECTID on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
        gp.CalculateField_management(fc,"OLD_FID", "!OBJECTID!", "PYTHON")

##      update field OLD_GLOBALID menggunakan value dari GLOBALID
        gp.AddMessage("CalculateField OLD_GLOBALID from GLOBALID on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
        gp.CalculateField_management(fc,"OLD_GLOBALID", "!GLOBALID!", "PYTHON")
        
##        update old_tdataid terpaksa menggunakan cursor karena calculatefield tidak stabil
        str_log = "Sedang memproses OLD_TDATAID dari TDATA_ID yang <> None dan <> 0 ..."
        log_me(gp, str_log, 1)
        try:
    ##      Get data feature class         
            rows = gp.UpdateCursor(fc, "TDATA_ID IS NOT NULL AND TDATA_ID > 0", "", "TDATA_ID; OLD_TDATAID")
            row = rows.Next()

            i=1
            while row <> None:
##                tulis ke log jika sudah mencapai 5000 record
                if i % 5000 == 0:
                    str_log = "Record %s ke %s." % (fc,i)
                    logging.info(str_log)
                                        
                objTDATAID_old = row.GetValue("TDATA_ID")
                row.SetValue("OLD_TDATAID", objTDATAID_old)
                rows.UpdateRow(row)
                i += 1
                row = rows.Next()
       
            # Delete row yang digunakan sebagai koleksi data feature class
            del row, rows
        except Exception, ErrorTDataID:
            del row, rows
            str_log = "Error set value TDataID %s" % str(ErrorTDataID)
            logging.error(str_log)
        

        str_log = "CalculateField UNIT from x on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime())
        log_me(gp, str_log, 1)
        gp.CalculateField_management(fc,"UNIT", "x", "PYTHON", "x = '" + unit + "'")

        fc = fcs.next()
except Exception, ErrorDesc:
    str_log = "error desc %s" % str(ErrorDesc)
    log_me(gp, str_log, 0)
Standard