顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2013年9月22日 星期日

python-threading


from threading import Thread
class MyThread(Thread):
    def __init__(self,il):
         Thread.__init__(self);
         self.il=il;
    def run(self)
         for aa inrange(100):
              print ('hello from thread %s' self.name)
              print(self.il)
for i in range(1):
   my.thread=MyThread('a')
   my.thread.name=i;
   my.thread.start()
print('end....')



2013年9月20日 星期五

python-utf8

python decode
utf8
utf16-le



s='<60s 60s'
mVariableName,mVariableName2=unpack(streamData,0,120)


aa=str(mVariableName, "utf-8")
print (mVariableName.decode('utf-16le'))

2013年9月19日 星期四

python-hello-world

import Timer
def hello():
    print ("hello, world")

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

2013年9月14日 星期六

Sending messages between class threads Python


inf : http://stackoverflow.com/questions/14508906/sending-messages-between-class-threads-python

ref : http://www.rabbitmq.com/tutorials/tutorial-two-python.html

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

import threading

print "Press Escape to Quit"

# Global variable
data = None

class threadOne(threading.Thread): 
    def run(self):
        self.setup()

    def setup(self):
        global data
        print 'hello world - this is threadOne'

        with lock:
            print "Thread one has lock"
            data = "Some value"


class threadTwo(threading.Thread):
    def run(self):
        global data
        print 'ran'
        print "Waiting"

        with lock:
            print "Thread two has lock"
            print data

lock = threading.Lock()

threadOne().start()
threadTwo().start()

2013年8月31日 星期六

python-datetime


datetime.datetime.utcnow() ## datetime.datetime(2013, 9, 1, 4, 12, 55, 254769)

python-mysql-connector


python-mysql-connector

config = {
  'user': 'root',
  'password': 'root',
  'host': '127.0.0.1',
  'database': 'test',
  'raise_on_warnings': True,
}
cnx = mysql.connector.connect(**config)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW DATABASES;")

python-mongodb-select-insert-reccount






python-mongodb-select



## python-mongo-connector ## connection

import pymongo
import datetime
from pymongo import MongoClient
cnx=MongoClient('localhost', 27017)

#### Show available databases ####
print (cnx.database_names())
db=cnx['mypymongdb'] #### DatabaseName ####
print (db.name)
print (db.profiling_level())
collection=db.abc ## = foxpro use tableName


## mongo-insert ##


#row = {"_id": str(datetime.datetime.now()), "author": "Mike", "text": "Hello PyMongo!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()}

row = {
       "author": "Mike",
       "text": "Hello PyMongo!",
       "tags": ["mongodb", "python", "pymongo"],
       "date": datetime.datetime.utcnow()
       }

## mongodb-use difference table(posts) to update =>db.posts
dbHandler=db.posts
record=dbHandler.insert(row)

row = {
       "authors": "Mike", ## it will be difference field
       "text": "Hello PyMongo!",
       "tags": ["mongodb", "python", "pymongo"],
       "date": datetime.datetime.utcnow()
       }
dbHandler=db.posts
record=dbHandler.insert(row)



## mongodb-reccount => dbHandler.count() ##
print("There are " + str(dbHandler.count()) + " records in the collection (aka Table). Details are:")

## mongodb-select ##
for queryset in dbHandler.find():
    print( queryset )

## mongodb-close ##
db.logout()




2013年7月5日 星期五

wnframework (python)


Web Notes Framework wnframework
http://code.google.com/p/wnframework/

Open Source Python + Javascript Framework Web Notes Framework is a Python based web app framework, that helps you build database driven apps. It includes an Object-Relational Mapper and a rich admin / development web interface. How is wnframework different from Django?

It is tightly integrated with the front-end.
In Django, the views are generated on the server-side but in wnframework, the views are rendered in the browser It contains a very rich development web interface and the entire application can be built from the browser It automates a lot of tasks so that you have to write minimum code Built-in Role based permission structure Built-in Report Builder with filters and column picking.

stack and heap memroy (standard , java, python)

Stack Memory

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

Heap Memroy

The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns. Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).

python Polymorphism (standard, python)

python sample Polymorphism  


class Fruit:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Apple(Fruit):
    def talk(self):
        return 'Red!'

class Orange(Fruit):
    def talk(self):
        return 'orangeColor! orangeColor!'

Fruits = [Apple('Missy'),
           Orange('Lassie')]

for Fruit in Fruits:
    print(Fruit.name + ': ' + Fruit.talk())


# prints the following:
# Missy: Red!
# Lassie: orangeColor! orangeColor!

2013年6月26日 星期三

Python String (python string)

String


python.split
s='python, jquery,javascript'
s.split(',') # ['python','jquery','javascript')
a,b,c=s.split(",")

python.find = foxpro.at
s="---<ABC>"

python.int string to value = fondpro.val ,
a="545.222"
float(a) # 545.2220000004
int(a)    # 545

python byte to string  / byte 2 string
b'abcd'
b'abcd'.decode('utf-8') # abcd