示例#1
0
 def __init__(self):
     self.Receipt = {}
     self._lock = thread.allocate()
     self._evtMailGot = threading.Event()
     self._eventSerial = 0
     self._timeOut = 15
     self._timeLimit = 0
     self._ready = False
示例#2
0
def loop2():
    print "loop2程序开始 ",ctime()
    locks = []
    nloops = range(len(loops))
    for i in nloops:  #用于批量创建锁对象
        lock = thread.allocate() #创建锁对象
        lock.acquire() #尝试获取锁对象
        locks.append(lock)
    for i in nloops:
        thread.start_new_thread(loop,(i,loops[i],locks[i]))
    sleep(4)
    print "---all done---"
示例#3
0
    def __init__(self, func, func_args=(), encoding='gbk', failed_delay=2, max_retry=10):
        self.encoding = encoding        
        self.lock = thread.allocate()
        self.failed_delay = failed_delay
        self.max_retry = max_retry
        self.finished = False
        self.retry_times = 0
        self.worker_func = func
        self.func_args = func_args
        self.thread = threading.Thread(target=self._func)

        super(SingleThread, self).__init__()
示例#4
0
def initialize():
    """Setup the Kinect hardware and register callbacks"""
    global screen_lock, screen, kinect
    screen_lock = thread.allocate()

    kinect = KinectRuntime()

    kinect.depth_frame_ready += depth_frame_ready
    # kinect.video_frame_ready += video_frame_ready

    # kinect.video_stream.open(nui.ImageStreamType.Video, 2,
    # nui.ImageResolution.Resolution640x480, nui.ImageType.Color)
    kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution640x480, nui.ImageType.Depth)
示例#5
0
def search(domains, results):
    now = datetime.now()
    lock = thread.allocate()
    sys.stdout.write('Date: %s' %now.strftime('%Y-%m-%d %H:%M:%S\n\n'))
    for domain in domains:
        if domain in results:
            continue

        thread.start_new(can_taken_via_whois, (domain, lock))

        #can_taken_via_whois(domain, lock)
        time.sleep(0.5)
    sys.stdout.write('\n')
    sys.stdout.flush()
示例#6
0
文件: thread_test.py 项目: mdavid/dlr
def test_start_new_thread():
    #--Sanity
    global CALLED
    CALLED = False
    
    lock = thread.allocate()    
    def tempFunc(mykw_param=1):
        global CALLED
        lock.acquire()
        CALLED = mykw_param
        lock.release()
        thread.exit_thread()
        
    id = thread.start_new_thread(tempFunc, (), {"mykw_param":7})
    while CALLED==False:
        print ".",
        time.sleep(1)
    AreEqual(CALLED, 7)
    
    id = thread.start_new_thread(tempFunc, (), {"mykw_param":8})
    while CALLED!=8:  #Hang forever if this is broken
        print ".",
        time.sleep(1)
    
    #--Sanity Negative
    global temp_stderr
    temp_stderr = ""
    se = sys.stderr
    
    class myStdOut:
        def write(self, text): 
            global temp_stderr
            temp_stderr += text

    try:
        sys.stderr = myStdOut()
        
        id = thread.start_new_thread(tempFunc, (), {"my_misspelled_kw_param":9})
        time.sleep(5)
        if not is_silverlight:
            se.flush()
    finally:
        sys.stderr = se
    
    AreEqual(CALLED, 8)
    Assert("tempFunc() got an unexpected keyword argument 'my_misspelled_kw_param" in temp_stderr)
示例#7
0
 def __init__(self):
     super(ChangeTimeWidget, self).__init__()
     proxy = dbus.SystemBus().get_object("org.gnome.SettingsDaemon.DateTimeMechanism", "/")
     self.dbus_iface = dbus.Interface(proxy, dbus_interface="org.gnome.SettingsDaemon.DateTimeMechanism")
     
     # Ensures we're setting the system time only when the user changes it
     self.changedOnTimeout = False
     
     # Ensures we don't update the values in the date/time fields during the DBus call to set the time
     self._setting_time = False
     self._setting_time_lock = thread.allocate()
     self._time_to_set = None
     
     self.thirtyDays = [3, 5, 8, 10]
     months = ['January','February','March','April','May','June','July','August','September','October','November','December']
     
     # Boxes
     timeBox = Gtk.HBox()
     dateBox = Gtk.HBox()
     
     # Combo Boxes
     self.monthBox = Gtk.ComboBoxText()
     
     for month in months:
         self.monthBox.append_text(month)
     
     # Adjustments
     hourAdj = Gtk.Adjustment(0, 0, 23, 1, 1)
     minAdj = Gtk.Adjustment(0, 0, 59, 1, 1)
     yearAdj = Gtk.Adjustment(0, 0, 9999, 1, 5)
     dayAdj = Gtk.Adjustment(0, 1, 31, 1, 1)
     
     # Spin buttons
     self.hourSpin = Gtk.SpinButton()
     self.minSpin = Gtk.SpinButton()
     self.yearSpin = Gtk.SpinButton()
     self.daySpin = Gtk.SpinButton()
     
     self.hourSpin.configure(hourAdj, 0.5, 0)
     self.minSpin.configure(minAdj, 0.5, 0)
     self.yearSpin.configure(yearAdj, 0.5, 0)
     self.daySpin.configure(dayAdj, 0.5, 0)
     self.hourSpin.set_editable(False)
     self.minSpin.set_editable(False)
     self.yearSpin.set_editable(False)
     self.daySpin.set_editable(False)
     
     self.update_time()
     GObject.timeout_add(1000, self.update_time)
     
     # Connect to callback
     self.hourSpin.connect('changed', self._change_system_time)
     self.minSpin.connect('changed', self._change_system_time)
     self.monthBox.connect('changed', self._change_system_time)
     self.yearSpin.connect('changed', self._change_system_time)
     self.daySpin.connect('changed', self._change_system_time)
     
     timeBox.pack_start(self.hourSpin, False, False, 2)
     timeBox.pack_start(Gtk.Label(_(":")), False, False, 2)
     timeBox.pack_start(self.minSpin, False, False, 2)
     
     dateBox.pack_start(self.monthBox, False, False, 2)
     dateBox.pack_start(self.daySpin, False, False, 2)
     dateBox.pack_start(self.yearSpin, False, False, 2)
     
     self.pack_start(Gtk.Label(_("Date : ")), False, False, 2)
     self.pack_start(dateBox, True, True, 2)
     self.pack_start(Gtk.Label(_("Time : ")), False, False, 2)
     self.pack_start(timeBox, True, True, 2)
示例#8
0
	def __init__(self):
		self.mutex = thread.allocate()
		self.todo = thread.allocate()
		self.todo.acquire()
		self.work = []
		self.busy = 0
示例#9
0
        
        if len(histl)>3:
            histr=histr[len(histr)-3:len(histr):1]
            histl=histl[len(histl)-3:len(histl):1]



if __name__ == '__main__':
        import libardrone
        drn=libardrone.ARDrone()

        full_screen = False
        draw_skeleton = True
        video_display = False

        screen_lock = thread.allocate()
        screen = pygame.display.set_mode(DEPTH_WINSIZE,0,16)    
        pygame.display.set_caption('Mirror Ver.K')
        Flight_mode=False
        Malayalam_mode=True

        skeletons = None
        #screen.fill(THECOLORS["black"])
        kinect = nui.Runtime()
        kinect.skeleton_engine.enabled = True
        
 
        def post_frame(frame):
            try:
                   pygame.event.post(pygame.event.Event(KINECTEVENT, skeletons = frame.SkeletonData))
            except:
示例#10
0
 def __init__(self, *args, **kwdargs):
     self.lock = thread.allocate()
     return super(ThreadSafeWriter, self).__init__(*args, **kwdargs)
示例#11
0
import thread
import time

lock=thread.allocate()

def start_thread(func, params):
  lock.acquire()
  thread.start_new_thread(thread_wrapper, (func, params))

def thread_wrapper(func, params):
  lock.release()
  apply(func, params)

def mythread(id):
  print 'id = %d'%id
  time.sleep(1)

for i in range(100):
  start_thread(mythread, (i,))

print 'Success!'
示例#12
0
 def __init__(self):
     self._lock = thread.allocate()
示例#13
0
# -*- coding: cp936 -*-
'''
author:郎芭
QQ:149737748
'''
import os,urllib2,time,sys,re
import thread
from bs4 import BeautifulSoup
start_time=time.clock()
za='<div.*</div>'
a=thread.allocate()#多线程用的锁
a.acquire()  #设置第二部份锁为阻塞
b=thread.allocate()
b.acquire()#第三部分
c=thread.allocate()
c.acquire()#第四部分
d=thread.allocate()
d.acquire()


def runa(qi,zhi,wurl,x,y):
    result=''
    soup=bsp(wurl)
    lzname=soup.find('div',{'class':'atl-menu clearfix js-bbs-act'})['js_activityusername']
    for i in xrange(int(qi),int(zhi)+1):
        newurl='http://bbs.tianya.cn/post-%s-%s-%s.shtml'%(x,y,i)
        txt=pagecollect(newurl,lzname)
        if txt:print u'The page %s  is completed!\r'%i,
        else:  print u'The page %s  is None!     \r'%i,
        result +=txt
    #优先写入第一部分内容,再解锁第二部分阻塞!    
示例#14
0
sys.path.append(os.path.join('soc_scan', 'tools', 'vulscan'))
sys.path.append(os.path.join('soc_scan', 'tools', 'vulscan', 'vuldb'))

db_conn = pymongo.MongoClient(settings.MONGO_DB['DB'],
                              settings.MONGO_DB['PORT'])
na_db = getattr(db_conn, settings.MONGO_DB['DBNAME'])
na_db.authenticate(settings.MONGO_DB['DBUSERNAME'],
                   settings.MONGO_DB['DBPASSWORD'])

na_task = na_db.Task
na_result = na_db.Result
na_plugin = na_db.Plugin
na_config = na_db.Config
na_heart = na_db.Heartbeat
lock = thread.allocate()
PASSWORD_DIC = []
THREAD_COUNT = 50
TIMEOUT = 10
PLUGIN_DB = {}
TASK_DATE_DIC = {}
WHITE_LIST = []


class vulscan():
    def __init__(self, task_id, task_netloc, task_plugin):
        self.task_id = task_id
        self.task_netloc = task_netloc
        self.task_plugin = task_plugin
        self.result_info = ''
        self.start()
示例#15
0
def gameK():
    KINECTEVENT = pygame.USEREVENT
    DEPTH_WINSIZE = 320, 240
    VIDEO_WINSIZE = 640, 480
    pygame.init()

    SKELETON_COLORS = [
        THECOLORS["red"], THECOLORS["blue"], THECOLORS["green"],
        THECOLORS["orange"], THECOLORS["purple"], THECOLORS["yellow"],
        THECOLORS["violet"]
    ]

    LEFT_ARM = (JointId.ShoulderCenter, JointId.ShoulderLeft,
                JointId.ElbowLeft, JointId.WristLeft, JointId.HandLeft)
    RIGHT_ARM = (JointId.ShoulderCenter, JointId.ShoulderRight,
                 JointId.ElbowRight, JointId.WristRight, JointId.HandRight)
    LEFT_LEG = (JointId.HipCenter, JointId.HipLeft, JointId.KneeLeft,
                JointId.AnkleLeft, JointId.FootLeft)
    RIGHT_LEG = (JointId.HipCenter, JointId.HipRight, JointId.KneeRight,
                 JointId.AnkleRight, JointId.FootRight)
    SPINE = (JointId.HipCenter, JointId.Spine, JointId.ShoulderCenter,
             JointId.Head)

    skeleton_to_depth_image = nui.SkeletonEngine.skeleton_to_depth_image

    def draw_skeleton_data(pSkelton, index, positions, width=4):
        start = pSkelton.SkeletonPositions[positions[0]]

        for position in itertools.islice(positions, 1, None):
            next = pSkelton.SkeletonPositions[position.value]

            curstart = skeleton_to_depth_image(start, dispInfo.current_w,
                                               dispInfo.current_h)
            curend = skeleton_to_depth_image(next, dispInfo.current_w,
                                             dispInfo.current_h)

            pygame.draw.line(screen, SKELETON_COLORS[index], curstart, curend,
                             width)

            start = next

    # recipe to get address of surface: http://archives.seul.org/pygame/users/Apr-2008/msg00218.html
    if hasattr(ctypes.pythonapi, 'Py_InitModule4'):
        Py_ssize_t = ctypes.c_int
    elif hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
        Py_ssize_t = ctypes.c_int64
    else:
        raise TypeError("Cannot determine type of Py_ssize_t")

    _PyObject_AsWriteBuffer = ctypes.pythonapi.PyObject_AsWriteBuffer
    _PyObject_AsWriteBuffer.restype = ctypes.c_int
    _PyObject_AsWriteBuffer.argtypes = [
        ctypes.py_object,
        ctypes.POINTER(ctypes.c_void_p),
        ctypes.POINTER(Py_ssize_t)
    ]

    def surface_to_array(surface):
        buffer_interface = surface.get_buffer()
        address = ctypes.c_void_p()
        size = Py_ssize_t()
        _PyObject_AsWriteBuffer(buffer_interface, ctypes.byref(address),
                                ctypes.byref(size))
        bytes = (ctypes.c_byte * size.value).from_address(address.value)
        bytes.object = buffer_interface
        return bytes

    def draw_skeletons(skeletons):
        for index, data in enumerate(skeletons):
            # draw the Head
            #HeadPos = skeleton_to_depth_image(data.SkeletonPositions[JointId.Head], dispInfo.current_w, dispInfo.current_h)
            #draw_skeleton_data(data, index, SPINE, 10)
            #pygame.draw.circle(screen, SKELETON_COLORS[index], (int(HeadPos[0]), int(HeadPos[1])), 20, 0)
            HandPos = skeleton_to_depth_image(
                data.SkeletonPositions[JointId.HandRight], dispInfo.current_w,
                dispInfo.current_h)
            pygame.draw.circle(screen, SKELETON_COLORS[5],
                               (int(HandPos[0]), int(HandPos[1])), 10, 0)
            LHandPos = skeleton_to_depth_image(
                data.SkeletonPositions[JointId.HandLeft], dispInfo.current_w,
                dispInfo.current_h)
            pygame.draw.circle(screen, SKELETON_COLORS[5],
                               (int(LHandPos[0]), int(LHandPos[1])), 10, 0)
            ZLayer = data.SkeletonPositions[JointId.HandRight].z
            # drawing the limbs
            #draw_skeleton_data(data, index, LEFT_ARM)
            #draw_skeleton_data(data, index, RIGHT_ARM)
            #draw_skeleton_data(data, index, LEFT_LEG)
            #draw_skeleton_data(data, index, RIGHT_LEG)

            #lastxy =
            return (int(HandPos[0]),
                    int(HandPos[1])), (int(LHandPos[0]),
                                       int(LHandPos[1])), int(ZLayer)
            #return lastxy

    def depth_frame_ready(frame):
        if video_display:
            return

        with screen_lock:
            address = surface_to_array(screen)
            frame.image.copy_bits(address)
            del address
            if skeletons is not None and draw_skeleton:
                draw_skeletons(skeletons)
            pygame.display.update()
            #pdb.gimp_displays_flush()

    def video_frame_ready(frame):
        if not video_display:
            return

        with screen_lock:
            address = surface_to_array(screen)
            frame.image.copy_bits(address)
            del address
            if skeletons is not None and draw_skeleton:
                draw_skeletons(skeletons)
            pygame.display.update()
            #pdb.gimp_displays_flush()

    full_screen = False
    draw_skeleton = True
    video_display = False

    screen_lock = thread.allocate()

    screen = pygame.display.set_mode(DEPTH_WINSIZE, 0, 16)
    pygame.display.set_caption('Python Kinect Demo')
    skeletons = None
    #screen.fill(THECOLORS["black"])
    #screen.fill(THECOLORS["red"])
    kinect = nui.Runtime()
    kinect.skeleton_engine.enabled = True

    def post_frame(frame):
        try:
            pygame.event.post(
                pygame.event.Event(KINECTEVENT, skeletons=frame.SkeletonData))
        except:
            # event queue full
            pass

    kinect.skeleton_frame_ready += post_frame

    kinect.depth_frame_ready += depth_frame_ready
    kinect.video_frame_ready += video_frame_ready

    kinect.video_stream.open(nui.ImageStreamType.Video, 2,
                             nui.ImageResolution.Resolution640x480,
                             nui.ImageType.Color)
    kinect.depth_stream.open(nui.ImageStreamType.Depth, 2,
                             nui.ImageResolution.Resolution320x240,
                             nui.ImageType.Depth)

    #print('Controls: ')
    #print('     d - Switch to depth view')
    #print('     v - Switch to video view')
    #print('     s - Toggle displaing of the skeleton')
    #print('     u - Increase elevation angle')
    #print('     j - Decrease elevation angle')

    pdb.gimp_context_set_foreground(THECOLORS["red"])
    #pdb.gimp_context_set_background((255,255,255))
    #pdb.gimp_context_set_brush('Circle (01)')
    img = pdb.gimp_image_new(320, 240, RGB)
    #set up four paint layers to use depth data
    drw = (img.new_layer('kinect0',
                         alpha=0), img.new_layer('kinect1', opacity=80),
           img.new_layer('kinect2',
                         opacity=60.0), img.new_layer('kinect3', opacity=40.0))

    width = pdb.gimp_image_width(img)
    height = pdb.gimp_image_height(img)
    lastxy = (width / 2, height / 2)
    pdb.gimp_display_new(img)
    # main game loop
    done = False

    while not done:
        e = pygame.event.wait()
        dispInfo = pygame.display.Info()
        #dispInfo.current_w = dispInfo.current_w*2
        #dispInfo.current_w = dispInfo.current_w*2
        if e.type == pygame.QUIT:
            done = True
            break
        elif e.type == KINECTEVENT:
            skeletons = e.skeletons
            if draw_skeleton:
                sq = 100
                palette = []
                for col in SKELETON_COLORS:
                    pygame.draw.rect(screen, col, (sq, 0, 20, 20), 0)
                    palette.append(Rect(sq, 0, 20, 20))
                    sq += 20

                Hand, LHand, ZLayer = draw_skeletons(skeletons)
                pygame.display.update()
                ctrlPoints = [
                    int(Hand[0]),
                    int(Hand[1]),
                    int(Hand[0]),
                    int(Hand[1])
                ]
                #lastxy = Hand
                #use left hand to control brush size
                pdb.gimp_context_set_brush_size(abs(float(LHand[1] / 2)))
                if LHand[1] < 20:
                    for index, item in enumerate(palette):  #select colour
                        if item.collidepoint(LHand):
                            pdb.gimp_context_set_foreground(
                                SKELETON_COLORS[index])
                #use distance from sensor to change layer
                pdb.gimp_paintbrush(drw[ZLayer % 4], 0, len(ctrlPoints),
                                    ctrlPoints, 0, 0)
                pdb.gimp_displays_flush()
        elif e.type == KEYDOWN:
            if e.key == K_ESCAPE:
                done = True
                break
            elif e.key == K_d:
                with screen_lock:
                    screen = pygame.display.set_mode(DEPTH_WINSIZE, 0, 16)
                    video_display = False
            elif e.key == K_v:
                with screen_lock:
                    screen = pygame.display.set_mode(VIDEO_WINSIZE, 0, 32)
                    video_display = True
            elif e.key == K_s:
                draw_skeleton = not draw_skeleton
            elif e.key == K_u:
                kinect.camera.elevation_angle = kinect.camera.elevation_angle + 2
            elif e.key == K_j:
                kinect.camera.elevation_angle = kinect.camera.elevation_angle - 2
            elif e.key == K_x:
                kinect.camera.elevation_angle = 2
示例#16
0
    def __init__(self):
        self.width = 640
        self.height = 480
        pygame.time.set_timer(TIMER_EVENT, 25)
        self.screen_lock = thread.allocate()
        self.last_kinect_event = time.clock()
        self.screen = pygame.display.set_mode((self.width, self.height), 
                                              0, 32)

        self.dispInfo = pygame.display.Info()
        self.screen.convert()
        pygame.display.set_caption('Python Kinect Game')
        self.screen.fill(THECOLORS["black"])
    
        self.background = pygame.Surface((self.width, self.height), 0, 32)
        self.background.fill(THECOLORS["black"])
        self.background.convert()

        self.video_screen = pygame.SurfaceType((self.width, self.height),
                                               0,
                                               32)    

        self.ball_group = sprite.Group(
            Ball(self, 'white', direction = math.atan2(.5, 1), 
                 x = 30, y = 410), 
            Ball(self, 'white', direction = math.atan2(0, -1), 
                 x = 600, y = 400),
            Ball(self, 'white', direction = math.atan2(0, -1), 
                 x = 30, y = 240),
            Ball(self, 'white', direction = math.atan2(1, -1.1), 
                 x = 10, y = 140),
        )
        self.known_players = {}

        self.score_font = pygame.font.SysFont('Segoe UI', 20, bold=True)

        self.pieces_group = sprite.Group()
        
        self.left_margin = (self.width / 5)
        self.top_margin = (self.height / 5)
        self.blocks_across = 10
        self.blocks_down = 10
        width = ((self.width - self.left_margin) / self.blocks_across) - 5
        height = ((self.height - self.top_margin) / self.blocks_down) - 5
        for y in xrange(self.blocks_down):
            for x in xrange(self.blocks_across):
                if x not in (3, 4, 5, 6) or not y in (4, 5):
                    x_loc = ((self.width - self.left_margin) / 
                             self.blocks_across) * x + (self.left_margin / 2)
                    y_loc = ((self.height - self.top_margin) / 
                             self.blocks_down) * y + (self.top_margin / 2)

                    bp = BoardPiece(x_loc, y_loc, width, height)
                    bp.add(self.pieces_group)

        self.bumper_group = sprite.Group()

        self.kinect = nui.Runtime()
        self.kinect.skeleton_engine.enabled = True
        self.kinect.skeleton_frame_ready += post_frame
        self.kinect.video_frame_ready += self.video_frame_ready    
        self.kinect.video_stream.open(nui.ImageStreamType.Video, 2, 
                                      nui.ImageResolution.Resolution640x480, 
                                      nui.ImageType.Color)
示例#17
0
             {"drawPhone": "13798580366", "drawUserId": "488984"},
             {"drawPhone": "13510212603", "drawUserId": "488984"},
             {"drawPhone": "18912352222", "drawUserId": "488984"},
             {"drawPhone": "18912351111", "drawUserId": "488984"},
             {"drawPhone": "18912348888", "drawUserId": "488984"},
             {"drawPhone": "18912347777", "drawUserId": "488984"},
             {"drawPhone": "18912346666", "drawUserId": "488984"},
             {"drawPhone": "18912345555", "drawUserId": "488984"},
             {"drawPhone": "18912344444", "drawUserId": "488984"}
             ]

# 字段说明,必须一一对应
# login为空表示使用随机用户名

now_count = 0
lock_obj = thread.allocate()


def send_http():
    global now_count
    try:
        index = random.randint(0, (len(user_list) - 1))
        user = user_list[index]
        url = 'http://' + addr + ':' + str(
            port) + restful + '?token=' + token + '&' + params + '&drawPhone=' + user.get(
            'drawPhone') + '&drawUserId=' + user.get('drawUserId')
        response = requests.get(url)

        #print '发送数据: ' + url
        #print '返回码: ' + str(response.status_code)
        #print '返回数据: ' + response.content
 def __init__(self, *args, **kwdargs):
     self.lock = thread.allocate()
     return super(ThreadSafeWriter, self).__init__(*args, **kwdargs)
示例#19
0
 def __init__(self):
     self.robot_lock = thread.allocate()
     self.robot = robot_init()
示例#20
0
文件: main.py 项目: cabama/TFM
        return

    with screen_lock:
        address = surface_to_array(screen)
        frame.image.copy_bits(address)
        del address
        if skeletons is not None and draw_skeleton:
            draw_skeletons(skeletons)
        pygame.display.update()

if __name__ == '__main__':
    full_screen = False
    draw_skeleton = True
    video_display = False

    screen_lock = thread.allocate()

    screen = pygame.display.set_mode(DEPTH_WINSIZE,0,16)    
    pygame.display.set_caption('Python Kinect Demo')
    skeletons = None
    screen.fill(THECOLORS["black"])

    kinect = nui.Runtime()
    kinect.skeleton_engine.enabled = True
    def post_frame(frame):
        try:
            pygame.event.post(pygame.event.Event(KINECTEVENT, skeletons = frame.SkeletonData))
        except:
            # event queue full
            pass
示例#21
0
文件: find.py 项目: mcyril/ravel-ftn
# A parallelized "find(1)" using the thread module.
def process():
    KINECTEVENT = pygame.USEREVENT
    DEPTH_WINSIZE = 320,240
    VIDEO_WINSIZE = 640,480
    pygame.init()

    SKELETON_COLORS = [THECOLORS["red"], 
                       THECOLORS["blue"], 
                       THECOLORS["green"], 
                       THECOLORS["orange"], 
                       THECOLORS["purple"], 
                       THECOLORS["yellow"], 
                       THECOLORS["violet"]]

    LEFT_ARM = (JointId.ShoulderCenter, 
                JointId.ShoulderLeft, 
                JointId.ElbowLeft, 
                JointId.WristLeft, 
                JointId.HandLeft)
    RIGHT_ARM = (JointId.ShoulderCenter, 
                 JointId.ShoulderRight, 
                 JointId.ElbowRight, 
                 JointId.WristRight, 
                 JointId.HandRight)
    LEFT_LEG = (JointId.HipCenter, 
                JointId.HipLeft, 
                JointId.KneeLeft, 
                JointId.AnkleLeft, 
                JointId.FootLeft)
    RIGHT_LEG = (JointId.HipCenter, 
                 JointId.HipRight, 
                 JointId.KneeRight, 
                 JointId.AnkleRight, 
                 JointId.FootRight)
    SPINE = (JointId.HipCenter, 
             JointId.Spine, 
             JointId.ShoulderCenter, 
             JointId.Head)

    skeleton_to_depth_image = nui.SkeletonEngine.skeleton_to_depth_image

    def draw_skeleton_data(pSkelton, index, positions, width = 4):
        start = pSkelton.SkeletonPositions[positions[0]]
           
        for position in itertools.islice(positions, 1, None):
            next = pSkelton.SkeletonPositions[position.value]
            
            curstart = skeleton_to_depth_image(start, dispInfo.current_w, dispInfo.current_h) 
            curend = skeleton_to_depth_image(next, dispInfo.current_w, dispInfo.current_h)

            pygame.draw.line(screen, SKELETON_COLORS[index], curstart, curend, width)
            
            start = next

    # recipe to get address of surface: http://archives.seul.org/pygame/users/Apr-2008/msg00218.html
    if hasattr(ctypes.pythonapi, 'Py_InitModule4'):
       Py_ssize_t = ctypes.c_int
    elif hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
       Py_ssize_t = ctypes.c_int64
    else:
       raise TypeError("Cannot determine type of Py_ssize_t")

    _PyObject_AsWriteBuffer = ctypes.pythonapi.PyObject_AsWriteBuffer
    _PyObject_AsWriteBuffer.restype = ctypes.c_int
    _PyObject_AsWriteBuffer.argtypes = [ctypes.py_object,
                                      ctypes.POINTER(ctypes.c_void_p),
                                      ctypes.POINTER(Py_ssize_t)]

    def surface_to_array(surface):
       buffer_interface = surface.get_buffer()
       address = ctypes.c_void_p()
       size = Py_ssize_t()
       _PyObject_AsWriteBuffer(buffer_interface,
                              ctypes.byref(address), ctypes.byref(size))
       bytes = (ctypes.c_byte * size.value).from_address(address.value)
       bytes.object = buffer_interface
       return bytes

    def draw_skeletons(skeletons):
        for index, data in enumerate(skeletons):
            # draw the Head
            HeadPos = skeleton_to_depth_image(data.SkeletonPositions[JointId.Head], dispInfo.current_w, dispInfo.current_h) 
            draw_skeleton_data(data, index, SPINE, 10)
            pygame.draw.circle(screen, SKELETON_COLORS[index], (int(HeadPos[0]), int(HeadPos[1])), 20, 0)
        
            # drawing the limbs
            draw_skeleton_data(data, index, LEFT_ARM)
            draw_skeleton_data(data, index, RIGHT_ARM)
            draw_skeleton_data(data, index, LEFT_LEG)
            draw_skeleton_data(data, index, RIGHT_LEG)


    def depth_frame_ready(frame):
        if video_display:
            return

        with screen_lock:
            address = surface_to_array(screen)
            frame.image.copy_bits(address)
            del address
            if skeletons is not None and draw_skeleton:
                draw_skeletons(skeletons)
            pygame.display.update()    


    def video_frame_ready(frame):
        if not video_display:
            return

        with screen_lock:
            address = surface_to_array(screen)
            frame.image.copy_bits(address)
            del address
            if skeletons is not None and draw_skeleton:
                draw_skeletons(skeletons)
            pygame.display.update()


    full_screen = False
    draw_skeleton = True
    video_display = False

    screen_lock = thread.allocate()

    screen = pygame.display.set_mode(DEPTH_WINSIZE,0,16)    
    pygame.display.set_caption('Python Kinect Demo')
    skeletons = None
    screen.fill(THECOLORS["black"])

    kinect = nui.Runtime()
    kinect.skeleton_engine.enabled = True
    def post_frame(frame):
        try:
            pygame.event.post(pygame.event.Event(KINECTEVENT, skeletons = frame.SkeletonData))
        except:
            # event queue full
            pass

    kinect.skeleton_frame_ready += post_frame
    
    kinect.depth_frame_ready += depth_frame_ready    
    kinect.video_frame_ready += video_frame_ready    
    
    kinect.video_stream.open(nui.ImageStreamType.Video, 2, nui.ImageResolution.Resolution640x480, nui.ImageType.Color)
    kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution320x240, nui.ImageType.Depth)

    print('Controls: ')
    print('     d - Switch to depth view')
    print('     v - Switch to video view')
    print('     s - Toggle displaing of the skeleton')
    print('     u - Increase elevation angle')
    print('     j - Decrease elevation angle')

    # main game loop
    done = False

    while not done:
        e = pygame.event.wait()
        dispInfo = pygame.display.Info()
        if e.type == pygame.QUIT:
            done = True
            break
        elif e.type == KINECTEVENT:
            skeletons = e.skeletons
            if draw_skeleton:
                draw_skeletons(skeletons)
                pygame.display.update()
        elif e.type == KEYDOWN:
            if e.key == K_ESCAPE:
                done = True
                break
            elif e.key == K_d:
                with screen_lock:
                    screen = pygame.display.set_mode(DEPTH_WINSIZE,0,16)
                    video_display = False
            elif e.key == K_v:
                with screen_lock:
                    screen = pygame.display.set_mode(VIDEO_WINSIZE,0,32)    
                    video_display = True
            elif e.key == K_s:
                draw_skeleton = not draw_skeleton
            elif e.key == K_u:
                kinect.camera.elevation_angle = kinect.camera.elevation_angle + 2
            elif e.key == K_j:
                kinect.camera.elevation_angle = kinect.camera.elevation_angle - 2
            elif e.key == K_x:
                kinect.camera.elevation_angle = 2