среда, 15 августа 2012 г.

Python gtk draw rectangle with mouse

There are some messy kind of mistakes:)

import gtk,math,cairo
from transparent import Transparent

class PaintBoard (gtk.Window,Transparent):
    def __init__(self):
        gtk.Window.__init__(self) 
        Transparent.__init__(self,(0.0,1.0,0.0,0.3))
        self.set_size_request(200,200)
        self.board=Board()
        self.add(self.board)
        self.show_all()

class Board(gtk.DrawingArea,Transparent):
    def __init__(self):
        gtk.DrawingArea.__init__(self)
        Transparent.__init__(self)
        self.connect("expose_event", self.expose)
        self.connect("motion_notify_event", self.motion_notify_event)
        self.connect("button_press_event", self.button_press_event)
        self.connect("button_release_event", self.button_release_event)

        self.set_events(gtk.gdk.EXPOSURE_MASK
                                 | gtk.gdk.LEAVE_NOTIFY_MASK
                                 | gtk.gdk.BUTTON_PRESS_MASK
                                 | gtk.gdk.BUTTON_RELEASE_MASK
                                 | gtk.gdk.POINTER_MOTION_MASK
                                 | gtk.gdk.POINTER_MOTION_HINT_MASK)
        self.start_x,self.start_y,self.finish_x,self.finish_y=0,0,0,0
        self.start_x,self.start_y,self.finish_x,self.finish_y=10,10,100,100
    def button_release_event(self, widget, event):
        self.finish_x,self.finish_y=event.get_coords()
    def button_press_event(self, widget, event):
        self.start_x,self.start_y=event.get_coords()

    def motion_notify_event(self,widget, event):
        if event.is_hint: #existance of POINTER_MOTION_HINT_MASK mask
            #file:///usr/share/gtk-doc/html/pygtk/class-gdkevent.html
            x, y, state = event.window.get_pointer()
        else:
            x = event.x
            y = event.y
            state = event.state

        if state & gtk.gdk.BUTTON1_MASK:
            self.finish_x,self.finish_y=x,y
            self.queue_draw()
        return True

    def expose(self, widget, event):
        context = widget.window.cairo_create()
        area=(0,0)+widget.window.get_size()
        context.rectangle(area)
        context.clip()
        self.draw(context)
        return False

    def draw(self,context):
        context.set_source_rgba(0, 0, 1,1)
        context.move_to(self.start_x,self.start_y)
        context.line_to(self.start_x,self.finish_y)
        context.line_to(self.finish_x,self.finish_y)
        context.line_to(self.finish_x,self.start_y)
        context.line_to(self.start_x,self.start_y)
        context.stroke()

if __name__ == "__main__":
    window = PaintBoard()
    window.show()
    window.connect("destroy", gtk.main_quit)
    gtk.main()

python http multi-task client with retry-timer



from blessings import Terminal
import thread
from time import strftime,time,sleep
from twisted.internet import reactor
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent, HTTPConnectionPool
from twisted.web.http_headers import Headers
from twisted.internet.error import AlreadyCalled, AlreadyCancelled

class BeginningPrinter(Protocol):
    def __init__(self,handler):
        self.handler=handler
    def dataReceived(self, received):
        self.handler(received)
    def connectionLost(self, reason):
        pass

class Site():
    def __init__(self,url,rest,wait,pool,md5=None,ind=None,name=None):
        self.url=url
        self.rest=rest
        self.wait=wait
        self.pool=pool
        self.md5=md5
        self.ind=ind if ind else 0
        self.name=name if name else self.url
        self.last_ask=0
        self.last_received=0
        self.agent = Agent(reactor, pool=pool)
        self.deferred=None
        self.delayedCall=None
    def __request(self):
        self.deferred = self.agent.request(
            'GET',
            self.url,
            Headers({'User-Agent': ['Mozilla/5.0']})
        )
        self.last_ask=time()
    def again(self):
        print strftime('%X'),'again'
        try:
            self.deferred.cancel()
        except (AlreadyCalled, AlreadyCancelled) :
            pass
        try:
            self.delayedCall.reset(self.wait)
        except (AlreadyCalled, AlreadyCancelled) :
            self.delayedCall = reactor.callLater(self.wait, self.timeIsOff)

        self.__request()
        self.deferred.addCallback(self.gotRequest)
    def timeIsOff(self):
        print strftime('%X'),'time is off'
        self.again()
    def handleReceived(self, received):
        print strftime('%X'),'received: ',received
    def gotRequest(self, response):
        print strftime('%X'),'gotRequest'
        self.last_received=time()
        self.again()
        print 'Response code:', response.code
        response.deliverBody(BeginningPrinter(self.handleReceived))
    def startLive(self):
        print strftime('%X'),'startLive'
        self.__request()
        self.deferred.addCallback(self.gotRequest)
        self.delayedCall = reactor.callLater(self.wait, self.timeIsOff)
    def norm_time(self,t):
        now=time()
        seconds=int(now-t) if now>t else int(t-now)
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        return "%d:%02d:%02d" % (h, m, s) if h!=0 else "%d:%02d" % (m, s) if m!=0 else "%ds" % (s)
    def report(self):
        return {'name':self.name,
                'wait':self.wait,
                'last_ask':self.norm_time(self.last_ask),
                'last_received':self.norm_time(self.last_received),
                'when_next':self.norm_time(self.delayedCall.getTime())}
pool = HTTPConnectionPool(reactor)
site1 = Site(url='http://wool/cgi-bin/wait.cgi',rest=3,wait=4,pool=pool)
site1.startLive()


t = Terminal()

def live_report(*a):
    while True:
        print t.green_on_black,
        print site1.report(),
        print t.normal,
        sleep(2)
thread.start_new(live_report,(0,))
reactor.run()

четверг, 9 августа 2012 г.

How to make gtk.Widget (and Layout particularly) transparent.

Don be afraid of that big class - it was interesting for me to write so it could work in that universal way. It could be the parent-class for transparent elements, and not-parent. so, the trouble. it can make transparent the main gtk.Window, the gtk.EventBox as in example below, and other gtk.widgets


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
import cairo
class Transparent:
    def __init__(self,*rgba):
        Transparent.makeTransparent(self)
        if len(rgba)>0:
            self.rgba=rgba[0]
    @staticmethod
    def expose (widget, event):
        cr = widget.window.cairo_create()
        cr.set_operator(cairo.OPERATOR_CLEAR)
        cr.rectangle(event.area)
        cr.fill()
        cr.set_operator(cairo.OPERATOR_OVER)
        try:
            widget.rgba
        except AttributeError:
            widget.rgba=(0.0,0.0,0.0,0.0)
        cr.set_source_rgba(*widget.rgba)
        cr.rectangle(event.area)
        cr.fill()  
    @staticmethod
    def makeTransparent(thing,*rgba): 
        if len(rgba)>0:
            thing.rgba=rgba[0]   
        thing.expose=Transparent.expose
        thing.set_app_paintable(True)
        screen = thing.get_screen()
        rgba = screen.get_rgba_colormap()
        thing.set_colormap(rgba)
        thing.connect('expose-event', thing.expose)

win = gtk.Window()
Transparent.makeTransparent(win)

#works with EventBox:
eb=gtk.EventBox()
win.add(eb)
Transparent.makeTransparent(eb)

#but not with Layout:
#l=gtk.Layout(None,None)
#win.add(l)
#Transparent.makeTransparent(l)

win.show_all()
win.show()
gtk.main()

About how to apply it for Layout - read there

Clevo m1110m BIOS

Clevo m1110m (DNS (0130183) (WSVGA)) BIOS 1.01.04 and firmware 1.00.09.
http://s.stdns.ru/up/message/86745_1.zip

четверг, 19 июля 2012 г.

python save console module


For know where python stores his default modules which we could include via "import module_name":

$ python -c 'import sys; print "\n".join(sys.path)'
for me it was /usr/lib/python2.7
so create file savemodule.py in this dir with this content:


 
import readline
"""Use savemodule.save(file_path) for saving your console-written module"""
def get_all_hist():
	l = readline.get_current_history_length()
	paper = ""
	for i in range(l):
		paper+=readline.get_history_item(i).__str__()+"\n"
	return paper
def save(*path):
    if len(path)==0:
        print "usage: save(file_path)"
    else:
        histfile=open(path[0],'w')
        histfile.write(get_all_hist())
        histfile.close()

viola!:) now we can write code in python console as much as we want, then
import savemodule
savemodule.__doc__
savemodule.save(/path/to/file/where/we/want/save)

среда, 20 июня 2012 г.

Vk.com python photo uploader


#!/usr/bin/python
# -*- coding: utf-8 -*-

import vkontakte
#XXXXX is your vk application id
#http://oauth.vk.com/authorize?client_id=XXXXXXX&scope=photos&response_type=token
#then you get 'token' from address line
access_token='soo_long_token_string_that_you_get'
vk = vkontakte.API('vk_application_id_again', 'vk_application_secrete_code')
vk = vkontakte.API(token=access_token)
upload_url_=vk.photos.getUploadServer(aid=vk.photos.getAlbums()[0]['aid'])['upload_url']
import requests
img_from=234 #you own number - it is the part of file name for me
blocks=500-img_from#vk albums cant contain more then 500 photos
block_size=1#it can not be bigger than 5! see vk developer docs
img = img_from
import json
print 'well connected, start upload by blocks of '+str(block_size)+' files'

while img<img_from+blocks*block_size:
   files = {}
   for f in range(1,block_size+1):
      files['file'+str(f)]= open('/home/argon/py/lxml/artkritka/'+str(img+f-1)+'.jpg', 'rb')
   img+=block_size
   #print files.__str__()+"\n\n"
   r=requests.post(upload_url_,files=files)
   s=json.loads(r.text)
   vk.photos.save(aid=s['aid'],server=s['server'],photos_list=s['photos_list'],hash=s['hash'])
   print 'last uploaded file:'+str(img-1)+'.jpg'