code:
from win32com.client import Dispatch

oConn = Dispatch('ADODB.Connection')
oRS = Dispatch('ADODB.RecordSet')

oConn.ConnectionString = "Provider=PIOLEDB;Data Source=<server>;User ID=<username>;database=<database>;Password=<password>"
oConn.Open()

if oConn.State == 0:
    print "We've connected to the database."
    db_cmd = """SELECT tag FROM pipoint WHERE tag LIKE 'TAG0001%'"""
    oRS.ActiveConnection = oConn
    oRS.Open(db_cmd)
    while not oRS.EOF:
        #print oRS.Fields.Item("tag").Value   # Ability to print by a field name
        print oRS.Fields.Item(0).Value        # Ability to print by a field location
        oRS.MoveNext()
    oRS.Close()
    oRS = None
else:
    print "Not connected"

if oConn.State == 0:
    oConn.Close()
oConn = None

rawDescription: How can I connect Python 2.6 to OSI PI?

description: Connect Python 2.6 to OSI PI


code:
for node in root.iter("*"):
    print node.text
    # print node.tail # e.g.: <div> <span> abc </span> def </div> => abc def

rawDescription: parse nested html lists using lxml in python

description: Parse nested html lists using lxml in python


code:
for file, n in num.iteritems():
    print file, n

rawDescription: Python: counting specific words in file of corpus


code:
import subprocess

output = subprocess.check_output(["echo", "1", "2", "3"])
print "Output: %s" % output
int1, int2, int3 = output.split(' ')
print "%s, %s, %s" % (int1, int2, int3)

rawDescription: Getting output from a Python script subprocess


code:
MAX_TIMEOUT = 100 # Max seconds before we abort

stop_time = time.time() + MAX_TIMEOUT

nw=1000
abort = False
for i in range(nw):
    w_list.append(-3+0.006*i)
    chi_1=0
    chi_2=0
    k=1
    while k<10 and not abort:
        l=1
        while l<10 and not abort:
            n_1=0
            while n_1<10 and not abort:
                n_2=0
                while n_2<5 and not abort:
                    chi_2+=(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2,0]*e_vecs[2*n_2,l])**2*(1.0/(w_list[i]+(E0-e_vals[l]-k*w_b+b*w_b)-0.001j))+(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2+1,0]*e_vecs[2*n_2+1,l])**2*(1.0/(w_list[i]-(E0-e_vals[l]-k*w_b+b*w_b)+0.001j))
                    n_2+=1

                    # We check here if we need to abort
                    if time.time() >= stop_time:
                        abort = True # This will force the while loops to end
                        print 'Aborted because we took too long!' #Probably a good idea to log this somewhere
                n_1+=1
            l+=1
        k+=1
    chi_on.append(chi_2.imag)

    if abort:
         break #No point staying in the forloop if we need to abort

rawDescription: Stop the loop in time in Python.

description: Stop the loop in time in Python.


code:
[ a+b for a in 'san' for b in '123' ]
for a in 'san':
    for b in '123':
            print a+b,

rawDescription: list comprehension multiple and dependant levels

description: List comprehension multiple and dependant levels


rawDescription: In Python, can I print 3 lists in order by index number?


code:
from urllib2 import urlopen, Request
from bs4 import BeautifulSoup

resp = urlopen(Request('https://en.wikipedia.org/wiki/Anniston_City_Schools',
                       headers={'User-Agent': 'Stack Overflow'}))
soup = BeautifulSoup(resp.read())

table = soup.find('table', class_='infobox')

for row in table.find_all('tr'):
    if 'NCES' in row.th.text:
        nces = row.td.a.text
        print nces
        break

rawDescription: REGEX To get seven numbers in a row?

description: REGEX To get seven numbers in a row


code: print sorted(salary_data, key=lambda k:salary_data[k]['wage'])

rawDescription: Sort dictionary of dictionaries by value of lower-level


code:
from selenium import webdriver as driver

browser = driver.Firefox()
browser.get("http://www.google.com")
print browser.find_element_by_xpath("html").text

rawDescription: How to get text from webpage using selenium and python?

description: Get text from webpage using selenium and python


code:
import ast

for line in open('listaraw.csv'):
    line = ast.literal_eval(line.replace('""', '\\"'))
    if isinstance(line, tuple):
        items = map(ast.literal_eval, list(line))
    else:
        items = ast.literal_eval(line)
    if isinstance(items, dict):
        items = [items]
    for item in items:
        print item['geometry']['location']

rawDescription: extract information from csv file

description: Extract information from csv file


code:
import threading, time
class th(threading.Thread):
    def __init__(self, n):
        self.n = n
    def run(self):
        print "Hi"
        time.sleep(self.n)
        print "Bye"

rawDescription: Multithread parameters passing

description: Multithread parameters passing


code:
class Manager(object):
    def new_thread(self):
        return MyThread(parent=self)
    def on_thread_finished(self, thread, data):
        print thread, data

class MyThread(Thread):

    def __init__(self, parent=None):
        self.parent = parent
        super(MyThread, self).__init__()

    def run(self):
        # ...
        self.parent and self.parent.on_thread_finished(self, 42)

mgr    = Manager()
thread = mgr.new_thread()
thread.run()

rawDescription: Python: How to pass and run a callback method in Python


code:
def printNames():
    json_obj = urllib2.urlopen(url)
    data = json.load(json_obj)
    for each in data['data']:
        print each['name']
    return data['paging']['next']  # Return the URL to the next page of data

url = 'https://graph.facebook.com/v2.5/1671554786408615/members?access_token=<MY_CUSTOM_ACCESS_CODE_HERE>'

url = printNames()
print "====END OF PAGE 1===="
url = printNames()
print "====END OF PAGE 2===="

rawDescription: Unable to get Facebook Group members after first page using Python


code:
def multiples():
     for i in range(5):
        print 3*i

if __name__ == "__main__":
    multiples()

rawDescription: calling a function with an argument 'self' in main block

description: Calling a function with an argument 'self' in main block


code:
for part in mail.walk():
    if part.get_content_type() == 'text/plain':
        content = part.get_payload()
        message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content)
        # This will just substitue the '=\r\' with nothing.
        message = re.sub(r'=\\r\\', '', message)
        print message

rawDescription: Matching text with regex/python - remove "=/r/" at line breaks


code:
def foo(array):
    array[0] = 3 # do stuff to the array in place

huge_array = [1,2,3]
foo(huge_array) # returns None
print huge_array # [3,2,3]

rawDescription: Pass large data structure in Python

description: Pass large data structure in Python


code:
data = u'\u10e2\u10d4\u10e1\u10e2'
import json
json.dumps(data)
json.dumps(data, ensure_ascii=False)
print json.dumps(data, ensure_ascii=False)
json.dumps(data, ensure_ascii=False).encode('utf8')

rawDescription: python jsonify dictionary in utf-8

description: Python jsonify dictionary in utf-8


code:
from shapely.geometry import LineString
from shapely.geometry import Point

p = Point(5,5)
c = p.buffer(3).boundary
l = LineString([(0,0), (10, 10)])
i = c.intersection(l)

print i.geoms[0].coords[0]
(2.8786796564403576, 2.8786796564403576)

print i.geoms[1].coords[0]
(7.121320343559642, 7.121320343559642)

rawDescription: What is most efficient way to find the intersection of a line and a circle in python?


code:
array_of_dicts = [{'state': 'OK', 'sname': 'sig1', 'extra': None}, {'state': 'OFF', 'sname': 'sig2', 'extra': None}, {'state': 'OK', 'sname': 'sig3', 'extra': None}, {'state': 'UNKNOWN', 'sname': 'sig4', 'extra': None}]
snames = [d['sname'] for d in array_of_dicts]
print snames

rawDescription: Create an array of items pulled from an array of dicts?


code:
from HTMLParser import HTMLParser

class MyParser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.line = ""
    self.in_tr = False
    self.in_table = False

  def handle_starttag(self, tag, attrs):
    if self.in_table and tag == "tr":
      self.line = ""
      self.in_tr = True
    if tag=='a':
     for attr in attrs:
       if attr[0] == 'href':
         self.line += attr[1] + " "

  def handle_endtag(self, tag):
    if tag == 'tr':
      self.in_tr = False
      if len(self.line):
        print self.line
    elif tag == "table":
      self.in_table = False

  def handle_data(self, data):
    if data == "Website":
      self.in_table = 1
    elif self.in_tr:
      data = data.strip()
      if data:
        self.line += data.strip() + " "

if __name__ == '__main__':
  myp = MyParser()
  myp.feed(open('table.html').read())

rawDescription: Please help parse this html table using BeautifulSoup and lxml the pythonic way


code:
from bs4 import BeautifulSoup as BS
soup = BS(' bar baz link')
print soup.find('span').contents

rawDescription: What do group() and contents[] mean?

description: What do group() and contents[] mean


code:
def get_boundries_from_user():
    upper_boundary = input("Enter upper boundary please:\n")
    lower_boundary = input("Enter lower boundary please:\n")
    return upper_boundary,lower_boundary

def print_prime_numbers():
    upper_boundry,lower_boundry = get_boundries_from_user()
    if (lower_boundry<0 or upper_boundry<0):
        print "Negative values cannot be prime numbers"
        return
    print "\nPrimes"
    for i in range(lower_boundry,upper_boundry+1):
        prime = True
        for k in range(2,i):
            if (i%k==0):
                prime = False
        if prime:
            print i

print_prime_numbers()

rawDescription: Printing Prime Numbers within Boundries

description: Printing Prime Numbers within Boundries


code:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.implicitly_wait(10)
driver.get("http://www.egglandsbest.com/where-to-buy/")
driver.switch_to.frame(driver.find_element_by_id("destini"))
print driver.find_elements_by_xpath('//div[@class="top_search"]')

rawDescription: Why can Selenium not access these dynamically loaded elements?


code:
#!/usr/bin/python

import sys
import os.path
from optparse import OptionParser
from shutil import rmtree, copy, copytree
import subprocess

cmdOpts = ''
cmdArgs = ''
config = ''

menu = """
Please select your operating system:
1. Windows 32 bit
2. Windows 64 bit
3. Linux 32 bit
4. Linux 65 bit
5. OSX 32 bit
6. OSX 64 bit
"""

def isInt( s ):
   try:
      int(s)
      return True
   except ValueError:
      return False

class SDKPackager:
   def __init__( self ):
      self.versionMajor = 1
      self.versionMinor = 0
      self.versionMacro = 1

      self.currentDirectory = os.path.dirname(os.path.realpath(__file__))
      self.platform = ""

      self.linux_32 = []
      self.linux_64 = []
      self.osx = []
      self.osx64 = []

      print "\nSixense SDK Installation Script v%02d.%02d.%02d" % ( self.versionMajor, self.versionMinor, self.versionMacro )
      if( not cmdOpts.printVersionAndExit ):
         print "============================================"

   def cleanString( self, string ):
      string = string.lstrip()
      string = string.rstrip(" \t\r\n\0")
      return string

   def cleanList( self, lst):
      if "" in lst:
         lst.remove("")
      return lst

   def forceString( self, value ):
      if not isinstance(value, str):
         return value[0]
      else:
         return value

   def getValue( self, key ):
      returnValue = []

      file = open(cmdOpts.config)
      for line in file:
         line = self.cleanString(line)
         if len(line) == 0:
            continue

         if line[0] == '#':
            continue

         pairs = line.split("=")

         keyFile = self.cleanString(pairs[0])
         if keyFile == key:
            for element in pairs[1].split(","):
               returnValue.append(self.cleanString(element))
            return returnValue

      return returnValue

   def find_in_file(self, filename, searchstr):    # see whether a string appears in a file at all, and tell on which line
      libfd = open(filename,"r")
      contents = libfd.readlines()
      libfd.close()
      index = 0
      for fline in contents:
         if searchstr in fline:
            return True, index
         index = index + 1
      return False, index

   def append_to_file(self, filename, newstr):
      libfd = open(filename,"a")
      libfd.write(newstr)
      libfd.close()

   def parseConfig( self ):

      print "-----------------------------------------------"
      print "Parsing Config File %s" % cmdOpts.config
      print "-----------------------------------------------"

      self.parseItem()

   def parseItem( self ):
      print "Finding Items"
      file = open(cmdOpts.config)

      for line in file:
         line = self.cleanString(line)

         if len(line) == 0:
            continue

         if line[0] == '#':
            continue

         pairs = line.split("=")

         key = self.cleanString(pairs[0])
         value = []

         if key == "linux_32" and self.platform == "linux_32":
            sys.stdout.write("Found Linux 32 bit")
            sys.stdout.flush()
            for element in pairs[1].split(","):
               if len(element) > 0:
                  self.linux_32.append(self.cleanString(element))
            print "                              Done"
         if key == "linux_64" and self.platform == "linux_64":
            sys.stdout.write("Found Linux 64 bit")
            sys.stdout.flush()
            for element in pairs[1].split(","):
               if len(element) > 0:
                  self.linux_64.append(self.cleanString(element))
            print "                             Done"
         if key == "osx_32" and self.platform == "osx_32":
            sys.stdout.write("Found OSX 32 bit")
            sys.stdout.flush()
            for element in pairs[1].split(","):
               if len(element) > 0:
                  self.osx.append(self.cleanString(element))
            print "                                 Done"
         if key == "osx_64" and self.platform == "osx_64":
            sys.stdout.write("Found OSX 64 bit")
            sys.stdout.flush()
            for element in pairs[1].split(","):
               if len(element) > 0:
                  self.osx64.append(self.cleanString(element))
            print "                                 Done"

      file.close()
      print "Done\n"

   def chooseTargetPlatform( self ):
      response = ""
      print menu

      response = raw_input("Enter Selection: ")

      if response == "3":
         self.platform = "linux_32"
      elif response == "4":
         self.platform = "linux_64"
      elif response == "5":
         self.platform = "osx_32"
      elif response == "6":
         self.platform = "osx_64"
      else:
         if response == "1" or response == "2":
            print "Currently Unsupported Target Operating System"
         else:
            print "Invalid Selection"
         self.chooseTargetPlatform()

   def preInstall( self ):
      return

   def install( self ):
      self.copyFilesHelper( self.linux_32, "Linux 32 bit" )
      self.copyFilesHelper( self.linux_64, "Linux 64 bit" )
      self.copyFilesHelper( self.osx, "OSX 32 bit" )
      self.copyFilesHelper( self.osx64, "OSX 64 bit" )
      return

   def copyFilesHelper( self, folderList, userText ):
      if not cmdOpts.verbose:
         self.firstErrorAfterHeader = True
      destination = ""
      source = ""
      files = []
      if len(folderList) > 0:
         sys.stdout.write("- for %s\r" % userText)
         sys.stdout.flush()
         if cmdOpts.verbose:
            print ""
         for element in folderList:
            destination = self.getValue(element+"_destination")
            source = self.getValue(element+"_source")
            files = self.getValue(element+"_file")
            source = self.cleanList(source)
            files = self.cleanList(files)
            for outfile in files:
               self.copyFileParser( destination, source, outfile )
         if not cmdOpts.verbose:
            sys.stdout.write("%46s\r" % "Done")
            sys.stdout.write("- for %s\n" % userText)
            sys.stdout.flush()
         else:
            print "Done\n"

   def copyFileParser( self, dstPath, srcPath, srcFile ):
      dst = ""
      src = ""
      if not isinstance(dstPath, str):
         dst = dstPath[0]
      else:
         dst =  dstPath
      if not isinstance(srcPath, str):
         src = srcPath[0]
      else:
         src =  srcPath

      pathsExist = True

      if not os.path.isdir(src):
         if self.firstErrorAfterHeader:
            print ""
            self.firstErrorAfterHeader = False
         print "Source Path Does Not Exist: %s" % src
         pathsExist = False
      if not os.path.isdir(dst):
         if self.firstErrorAfterHeader:
            print ""
            self.firstErrorAfterHeader = False
         print "Destination Path Does Not Exist: %s" % dst
         pathsExist = False

      if not pathsExist:
         return

      #copy all files
      if srcFile.split('.')[0] == '*' and srcFile.split('.')[1] == '*':
         for filename in os.listdir( os.path.join(".",src) ):
            self.copyFile( dst, src, filename )
      #copy all files by extention
      elif srcFile.split('.')[0] == '*' and srcFile.split('.')[1] != '*':
         for filename in os.listdir( os.path.join(".",src) ):
            if os.path.isfile(filename):
               if filename.split('.')[1] == srcFile.split('.')[1]:
                  self.copyFile( dst, src, filename )
      #copy all files starting with <>
      elif srcFile.split('.')[0] != '*' and srcFile.split('.')[1] == '*':
         for filename in os.listdir( os.path.join(".",src) ):
            if filename.split('.')[0] == srcFile.split('.')[0]:
               self.copyFile( dst, src, filename )
      #copy individual file
      else:
         self.copyFile( dst, src, srcFile )

   def copyFile( self, dstPath, srcPath, srcFile ):
      fileExists = True

      if not os.path.isfile(os.path.join(srcPath,srcFile)):
         if os.path.isdir(os.path.join(srcPath,srcFile)):
            if cmdOpts.verbose:
               print "Copying all files from %s to %s" % (os.path.join(srcPath,srcFile), dstPath )
            copytree(srcPath,os.path.join(dstPath,srcFile))
            return
         else:
            if self.firstErrorAfterHeader:
               print ""
               self.firstErrorAfterHeader = False
            print "Source File Does Not Exist: %s" % os.path.join(srcPath,srcFile)
            fileExists = False

      if not fileExists:
         return

      if cmdOpts.verbose:
         print "Copying File %s from %s to %s" % (srcFile, srcPath, dstPath )
      copy( os.path.join(srcPath,srcFile), dstPath)

   def postInstall( self ):
      if self.platform =="linux_32" or self.platform == "linux_64":
         configFile = self.forceString(self.getValue("linux_library_config_file"))
         libPath = self.forceString(self.getValue("linux_library_path"))
         if os.path.isfile( configFile ):
            found, index = self.find_in_file(configFile,libPath)    # is lib path already there?
            if found:
               print "Library path is already registered in %s, on line %d." % (configFile,index)
            else:
               print "Library path not registered yet. Adding library path to %s..." % configFile
               self.append_to_file(configFile,"\n"+libPath+"\n")
            lib_update_cmd = "ldconfig"
            p = subprocess.Popen(lib_update_cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
         else:
            print "Unable to Find ld.so.conf"

   def run( self ):
      self.chooseTargetPlatform()
      self.parseConfig()
      self.preInstall()
      self.install()
      self.postInstall()

# main program starts here
if __name__ == '__main__':
   #configFile = "sdk_hierarchy_default"

   parser = OptionParser(usage="%prog [options]")

   parser.add_option('',"--version",
                     action="store_true",
                     dest="printVersionAndExit",
                     default=False,
                     help="Prints the version and exits",)

   parser.add_option('-c',"--config",
                     action="store",
                     dest="config",
                     default="install.cfg",
                     help="Config File to use",)

   parser.add_option('-v',"--verbose",
                     action="store_true",
                     dest="verbose",
                     default=False,
                     help="Print Extra Information",)

   parser.add_option('-w',"--warning",
                     action="store_true",
                     dest="warning",
                     default=False,
                     help="Print Only Warning Information",)

   (cmdOpts, cmdArgs) = parser.parse_args()

   package = SDKPackager()

   if( cmdOpts.printVersionAndExit ):
      exit()
   package.run()

rawDescription: python, inconsistent indentation detected

description: Python, inconsistent indentation detected


code:
def testthis(): print "hello"
import inspect
inspect.getsourcelines(testthis)

rawDescription: Return function code

description: Return function code


code:
def RandomHtml():
    yield ''
    yield ''
    yield RandomBody()
    yield ''

def RandomBody():
    yield RandomSection()
    if random.randrange(2) == 0:
        yield RandomBody()

def RandomSection():
    yield '
'
    yield RandomSentence()
    yield '
'
    sentences = random.randrange(5, 20)
    for _ in xrange(sentences):
         yield RandomSentence()

def RandomSentence():
    words = random.randrange(5, 15)
    yield (' '.join(RandomWord() for _ in xrange(words)) + '.').capitalize()

def RandomWord():
    chars = random.randrange(2, 10)
    return ''.join(random.choice(string.ascii_lowercase) for _ in xrange(chars))

def Output(generator):
    if isinstance(generator, str):
        print generator
    else:
        for g in generator: Output(g)

Output(RandomHtml())

rawDescription: How to generate random html document

description: Generate random html document


code:
class SomeProtocol(Protocol):
    def connectionMade(self):
        print 'Connection made to', self.transport.getHost(),
        print 'from', self.transport.getPeer()

rawDescription: Detect client is connected to which port


code:
import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)

api = tweepy.API(auth)

public_tweets = api.search("stackoverflow")
for tweet in public_tweets:
    print api.retweets(tweet.id)

rawDescription: Using the twitter API and Python to obatain retweeter's id


code:
from itertools import cycle

n = 1
lst = [n]
for i in cycle(lst):
   print i
   n += 1
   if n < 100:
     lst.append(n)

rawDescription: Roundrobin over changing set

description: Roundrobin over changing set


code:
import sys, os
sys.path.append(os.path.join(os.getcwd(), "site-packages"))
import numpy as np

a = np.arange(15).reshape(3, 5)

print "%r" % a

rawDescription: Import Numpy in Python WebJob on Azure

description: Import Numpy in Python WebJob on Azure


code:
class Service(object):
    def __init__(self, host, binary, topic, manager, report_interval=None,
             periodic_interval=None, *args, **kwargs):
        print 'Initializing Service'
        super(Service, self).__init__(*args, **kwargs)

class Color(object):
    def __init__(self, color='red', **kwargs):
        print 'Initializing Color'
        self.color = color
        super(Color, self).__init__(**kwargs)

class ColoredService(Service, Color):
    def __init__(self, *args, **kwds):
        print 'Initializing Colored Service'
        super(ColoredService, self).__init__(*args, **kwds)

c = ColoredService('host', 'bin', 'top', 'mgr', 'ivl', color='blue')

rawDescription: what does object's __init__() do in python?

description: What does object's __init__() do in python


code:
from BeautifulSoup import BeautifulSoup
import urllib

url = 'http://python-data.dr-chuck.net/comments_42.html'
soupy = urllib.urlopen(url).read()
soup = BeautifulSoup(soupy)
rows = soup.findAll('span')
for row in rows:
    text = ''.join(row.findAll(text=True)) #<--- Here the text is unicode (1)
    data = int(text) #<--- to do math convert it to int (2)
    print data, type(data)

rawDescription: Python list returns a unicode list

description: Python list returns a unicode list


code: print img.shape

rawDescription: OpenCV: What is the dimension of the array representing a BGR image?


code:
def replace(thelist,a,b):

 assert type(thelist)==list, `thelist` + ' is not a list'

 assert type(a)==int, `a` + ' is not an integer'

 assert type(b)==int, `b` + ' is not an integer'
 if len(thelist)==0:
     return []
 return ([b] if thelist[0]==a else [thelist[0]])+replace(thelist[1:],a,b)

rawDescription: recursive function in python that returns copy of list given as argument with a's replaced by b's and does not alter the list given as argument

description: Recursive function in python that returns copy of list given as argument with a's replaced by b's and does not alter the list given as argument


code:
s = 'blah blah iden=\ntifier blah blah'
print s
s.replace('=\n', '')
s.replace('=\n', '').find('identifier')

rawDescription: How can I remove line continuation markers from a Python email.Message object's get_payload call?

description: Remove line continuation markers from a Python email.Message object's get_payload call


code:
from sgmllib import SGMLParser
import urllib2
import urllib

# Define the class that will parse the suggestion XML
class PullSuggestions(SGMLParser):

   def reset(self):
      SGMLParser.reset(self)
      self.suggestions = []
      self.queries = []

   def start_suggestion(self, attrs):
      for a in attrs:
         if a[0] == 'data': self.suggestions.append(a[1])

   def start_num_queries(self, attrs):
      for a in attrs:
         if a[0] == 'int': self.queries.append(a[1])

# ENTER THE BASE QUERY HERE

base_query = ""  #This is the base query

base_query += "%s"
alphabet = "abcdefghijklmnopqrstuvwxyz"
for letter in alphabet:
   q = base_query % letter;
   query = urllib.urlencode({'q' : q})
   url = "http://google.com/complete/search?output=toolbar&%s" % query

   res = urllib2.urlopen(url)
   parser = PullSuggestions()
   parser.feed(res.read())
   parser.close()

   for i in range(0,len(parser.suggestions)):
      print "%s\t%s" % (parser.suggestions[i], parser.queries[i])

rawDescription: Is there a Google Insights API?

description: Is there a Google Insights API


code:
out = 'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
import binascii
print binascii.hexlify(out)

rawDescription: Print python os.urandom output on terminal


code:
# Additional stuff for the LaTeX preamble.
latex_elements['preamble'] = '\usepackage{amsmath}\n\usepackage{amssymb}\n'

#####################################################
# add LaTeX macros

f = file('latex_macros.sty')

try:
    pngmath_latex_preamble  # check whether this is already defined
except NameError:
    pngmath_latex_preamble = ""

for macro in f:
    # used when building latex and pdf versions
    latex_elements['preamble'] += macro + '\n'
    # used when building html version
    pngmath_latex_preamble += macro + '\n'

#####################################################

rawDescription: Creating LaTeX math macros within Sphinx


code:
list1 = ["python", "java", "perl", "sql"]
list2 = [ "scala", "python", "perl"]

d1 = dict.fromkeys(list1)
d2 = dict.fromkeys(list2)
difference = [i for i in d1 if i not in d2] + [i for i in d2 if i not in d1]

print difference

rawDescription: Difference between two string list without using SET


code:
import sys

def processData(filename, key):
    with open(filename, 'rb') as inf, open(filename+'.xor', 'wb') as outf:
        for line in inf:
            line = ''.join([chr(ord(c)^ord(key)) for c in line])
            outf.write(line)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'Usage: xor_it filename key'
        print '       key = a single character'
    else:
        processData(sys.argv[1], sys.argv[2])

rawDescription: Simple Python code to scramble descramble file contents


code:
from win32com.client import Dispatch

from ctypes import Structure, pointer, windll
from ctypes import c_int, c_long, c_uint
import win32con
import pywintypes

class POINT(Structure):
    _fields_ = [('x', c_long),
                ('y', c_long)]
    def __init__( self, x=0, y=0 ):
        self.x = x
        self.y = y

class MSG(Structure):
    _fields_ = [('hwnd', c_int),
                ('message', c_uint),
                ('wParam', c_int),
                ('lParam', c_int),
                ('time', c_int),
                ('pt', POINT)]

def wait_until_ready(ie):
    pMsg = pointer(MSG())
    NULL = c_int(win32con.NULL)

    while True:

        while windll.user32.PeekMessageW(pMsg, NULL, 0, 0, win32con.PM_REMOVE) != 0:
            windll.user32.TranslateMessage(pMsg)
            windll.user32.DispatchMessageW(pMsg)

        if ie.ReadyState == 4:
            break

ie = Dispatch("InternetExplorer.Application")

ie.Visible = True

ie.Navigate("http://google.com/")

wait_until_ready(ie)

print "title:", ie.Document.Title
print "location:", ie.Document.location

rawDescription: Python Scraper for Javascript?

description: Python Scraper for Javascript


code:
def DupSearch(list):
    for i in range(len(list)):
        for j in range(i+1, len(list)):
            if list[i]==list[j]:
                print "Duplicate found"
                return
    print "No duplicated"

rawDescription: How to find a duplicate in a list without in-built functions in Python?

description: Find a duplicate in a list without in-built functions in Python


code:
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(html) ## feed your html page to beautifulsoup

pleaseFind = soup.find(text="ASD")

whatINeed = pleaseFind.findNext('td')

print whatINeed.text

rawDescription: Reading element from HTML - <td>

description: Reading element from HTML - <td>


code:
import sys

# this part executes when the script is run from the command line
if __name__ == '__main__':
    if len(sys.argv) != 2: # check for the correct number of arguments
        print 'usage: python kb.py cur'
    else:
        call_your_code(sys.argv[1]) # first command line argument

rawDescription: Getting Command line in Python

description: Getting Command line in Python


code:
for line in result.stdout:
    print line

rawDescription: Getting output of a process at runtime

description: Getting output of a process at runtime


code:
import sys
while 1:
    c=''
    while len(c) < 10:
        g = getch()
        sys.stdout.write(g)
        c += g
    print "\nYou said", c

rawDescription: How to make an Interactive CLI based application in python?

description: Make an Interactive CLI based application in python


code:
import csv
from collections import defaultdict, Counter
from datetime import datetime
from urlparse import urlsplit

indiv = Counter()

domains = defaultdict(lambda: defaultdict(int))
with open("history.csv", "rb") as f:
    for timestr, url in csv.reader(f):
        dt = datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S")
        if 6 <= dt.hour < 11: # between 6am and 11am
            today_domains = domains[dt.date()]
            domain = urlsplit(url).hostname
            if len(today_domains) < 5 and domain not in today_domains:
                today_domains[domain] += 1
                indiv += Counter([domain])
for domain in indiv:
    print '%s,%d' % (domain, indiv[domain])

rawDescription: Python CSV row value based flow control

description: Python CSV row value based flow control


code:
expression = re.compile('\,[\s\w()-]+\,')
textnode = HTML.body.p.find_all(text=expression)
print expression.search(textnode).group(0)

rawDescription: matching commas in BeautifulSoup

description: Matching commas in BeautifulSoup


code:
from itertools import combinations

# n is the number of dimensions of the cube (3 for a 3d cube)
def generate_vertices(n):
    for number_of_ones in xrange(0, n + 1):
        for location_of_ones in combinations(xrange(0, n), number_of_ones):
            result = [0] * n
            for location in location_of_ones:
                result[location] = 1
            yield result

for vertex in generate_vertices(3):
    print vertex

# result:
# [0, 0, 0]
# [1, 0, 0]
# [0, 1, 0]
# [0, 0, 1]
# [1, 1, 0]
# [1, 0, 1]
# [0, 1, 1]
# [1, 1, 1]

rawDescription: Permutations with repetition in Python

description: Permutations with repetition in Python


code:
#!/usr/bin/env python
from __future__ import division
import numpy as np

__date__ = "2011-06-15 jun denis"

#...............................................................................
def sumtriangles( xy, z, triangles ):
    """ integrate scattered data, given a triangulation
    zsum, areasum = sumtriangles( xy, z, triangles )
    In:
        xy: npt, dim data points in 2d, 3d ...
        z: npt data values at the points, scalars or vectors
        triangles: ntri, dim+1 indices of triangles or simplexes, as from
http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html
    Out:
        zsum: sum over all triangles of (area * z at midpoint).
            Thus z at a point where 5 triangles meet
            enters the sum 5 times, each weighted by that triangle's area / 3.
        areasum: the area or volume of the convex hull of the data points.
            For points over the unit square, zsum outside the hull is 0,
            so zsum / areasum would compensate for that.
            Or, make sure that the corners of the square or cube are in xy.
    """
        # z concave or convex => under or overestimates
    npt, dim = xy.shape
    ntri, dim1 = triangles.shape
    assert npt == len(z), "shape mismatch: xy %s z %s" % (xy.shape, z.shape)
    assert dim1 == dim+1, "triangles ? %s" % triangles.shape
    zsum = np.zeros( z[0].shape )
    areasum = 0
    dimfac = np.prod( np.arange( 1, dim+1 ))
    for tri in triangles:
        corners = xy[tri]
        t = corners[1:] - corners[0]
        if dim == 2:
            area = abs( t[0,0] * t[1,1] - t[0,1] * t[1,0] ) / 2
        else:
            area = abs( np.linalg.det( t )) / dimfac  # v slow
        zsum += area * z[tri].mean(axis=0)
        areasum += area
    return (zsum, areasum)

#...............................................................................
if __name__ == "__main__":
    import sys
    from time import time
    from scipy.spatial import Delaunay

    npt = 500
    dim = 2
    seed = 1

    exec( "\n".join( sys.argv[1:] ))  # run this.py npt= dim= ...
    np.set_printoptions( 2, threshold=100, edgeitems=5, suppress=True )
    np.random.seed(seed)

    points = np.random.uniform( size=(npt,dim) )
    z = points  # vec; zsum should be ~ constant
    # z = points[:,0]
    t0 = time()
    tessellation = Delaunay( points )
    t1 = time()
    triangles = tessellation.vertices  # ntri, dim+1
    zsum, areasum = sumtriangles( points, z, triangles )
    t2 = time()

    print "%s: %.0f msec Delaunay, %.0f msec sum %d triangles:  zsum %s  areasum %.3g" % (
        points.shape, (t1 - t0) * 1000, (t2 - t1) * 1000,
        len(triangles), zsum, areasum )
# mac ppc, numpy 1.5.1 15jun:
# (500, 2): 25 msec Delaunay, 279 msec sum 983 triangles:  zsum [ 0.48  0.48]  areasum 0.969
# (500, 3): 111 msec Delaunay, 3135 msec sum 3046 triangles:  zsum [ 0.45  0.45  0.44]  areasum 0.892

rawDescription: Looking for Python package for numerical integration over a tessellated domain


code:
f = open("myfile.txt")
myDict = {}
for line in f:
    if line.strip().startswith('"ID":'):
        key = line.split('"')[3]
    if line.strip().startswith('"name":'):
        value = line.split('"')[3]
        myDict.setdefault(key,[]).append(value)

for key in myDict:
    print key
    print '\n'.join(myDict[key])
    print

rawDescription: How to Group repeated lines into one variable and print the second line after each using Python


code:
#!/usr/bin/env python2.7
#
# camera.py -- by Trevor Bentley (02/04/2011)
#
# This work is licensed under a Creative Commons Attribution 3.0 Unported License.
#
# Run from the command line on an Apple laptop running OS X 10.6, this script will
# take a single frame capture using the built-in iSight camera and save it to disk
# using three methods.
#

import sys
import os
import time
import objc
import QTKit
from AppKit import *
from Foundation import NSObject
from Foundation import NSTimer
from PyObjCTools import AppHelper

class NSImageTest(NSObject):
    def init(self):
        self = super(NSImageTest, self).init()
        if self is None:
            return None

        self.session = None
        self.running = True

        return self

    def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput,
                                                                           videoFrame, sampleBuffer,
                                                                           connection):
        self.session.stopRunning() # I just want one frame

        # Get a bitmap representation of the frame using CoreImage and Cocoa calls
        ciimage = CIImage.imageWithCVImageBuffer_(videoFrame)
        rep = NSCIImageRep.imageRepWithCIImage_(ciimage)
        bitrep = NSBitmapImageRep.alloc().initWithCIImage_(ciimage)
        bitdata = bitrep.representationUsingType_properties_(NSBMPFileType, objc.NULL)

        # Save image to disk using Cocoa
        t0 = time.time()
        bitdata.writeToFile_atomically_("grab.bmp", False)
        t1 = time.time()
        print "Cocoa saved in %.5f seconds" % (t1-t0)

        # Save a read-only buffer of image to disk using Python
        t0 = time.time()
        bitbuf = bitdata.bytes()
        f = open("python.bmp", "w")
        f.write(bitbuf)
        f.close()
        t1 = time.time()
        print "Python saved buffer in %.5f seconds" % (t1-t0)

        # Save a string-copy of the buffer to disk using Python
        t0 = time.time()
        bitbufstr = str(bitbuf)
        f = open("python2.bmp", "w")
        f.write(bitbufstr)
        f.close()
        t1 = time.time()
        print "Python saved string in %.5f seconds" % (t1-t0)

        # Will exit on next execution of quitMainLoop_()
        self.running = False

    def quitMainLoop_(self, aTimer):
        # Stop the main loop after one frame is captured.  Call rapidly from timer.
        if not self.running:
            AppHelper.stopEventLoop()

    def startImageCapture(self, aTimer):
        error = None
        print "Finding camera"

        # Create a QT Capture session
        self.session = QTKit.QTCaptureSession.alloc().init()

        # Find iSight device and open it
        dev = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo)
        print "Device: %s" % dev
        if not dev.open_(error):
            print "Couldn't open capture device."
            return

        # Create an input instance with the device we found and add to session
        input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(dev)
        if not self.session.addInput_error_(input, error):
            print "Couldn't add input device."
            return

        # Create an output instance with a delegate for callbacks and add to session
        output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()
        output.setDelegate_(self)
        if not self.session.addOutput_error_(output, error):
            print "Failed to add output delegate."
            return

        # Start the capture
        print "Initiating capture..."
        self.session.startRunning()

    def main(self):
        # Callback that quits after a frame is captured
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(0.1,
                                                                                self,
                                                                                'quitMainLoop:',
                                                                                None,
                                                                                True)

        # Turn on the camera and start the capture
        self.startImageCapture(None)

        # Start Cocoa's main event loop
        AppHelper.runConsoleEventLoop(installInterrupt=True)

        print "Frame capture completed."

if __name__ == "__main__":
    test = NSImageTest.alloc().init()
    test.main()

rawDescription: How to capture frames from Apple iSight using Python and PyObjC?

description: Capture frames from Apple iSight using Python and PyObjC


code:
import re
s = '<form id="blah" action="/p-submi.html" method="post"><input type="hidden" id="" name="uber_token" value="123456789"/><div class="container-info"'
regex=re.search(r'name="uber_token" value="([0-9]+)"',s)
print regex.group(1)

rawDescription: How to parse a string in python

description: Parse a string in python


code:
#!/usr/bin/env python

username = "username"
password = "password"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re

driver = webdriver.PhantomJS()
driver.get("http://insta.friendorfollow.com")
driver.find_elements_by_tag_name("a")[1].click()

print "Perimene file....".upper()
driver.find_element_by_name('username').send_keys(username)
driver.find_element_by_name('password').send_keys(password)
driver.find_element_by_class_name("button-green").click()

try:
  driver.find_elements_by_name("allow")[1].click()
except:
  pass

f = open(username+".txt", 'w')
malakes = re.findall(ur'data-id=\"([0-9]*)\"', driver.page_source)[::-1]
for malakas in malakes:
  print >> f, malakas

f.close()
driver.quit()

rawDescription: Logging to Instagram using Python requests


code:
class Foo(object):
    def __setitem__(self, key, value):
        print key

a = Foo()
a[1:1] = 1

a[1:1:1] = 1

a[1:1, 1:1] = 1

rawDescription: Extended slice in python?

description: Extended slice in python


code:
newDict = {}
for k, v in dict_id.iteritems():
    if v[0] in newDict:
        newDict[v[0]] += 1
    else:
        newDict[v[0]] = 1
print newDict

rawDescription: Getting frequency count of first item of a value in dictionary in Python


code:
def f(a,b,c,d,e):
 print a,b,c,d,e
my_tuple = (1,2,3)
def apply(f, mid, *args, **kwargs):
 return f(*args+mid, **kwargs)
apply(f, my_tuple, 0, e=4)
apply(f, ('a', 'b'), '_', d='c', e='d')

rawDescription: Python 2.5 and lists in function arguments


code:
import os
import sys

biggest = ("", -1)
directory = sys.argv[1]

print "Searching", directory

def search(dir):
    global biggest
    for item in os.listdir(dir):
        item = dir + "/" + item
        if os.path.isdir(item):
            search(item)
        else:
            itemsize = os.path.getsize(item)
            if itemsize > biggest[1]:
                    biggest = (item, itemsize)

search(directory)
if biggest[1] != -1:
    print "Found: ", biggest
    # Do something with biggest

rawDescription: Find Largest File and Deleting Folders

description: Find Largest File and Deleting Folders


rawDescription: Flattened out a mixed type of list

description: Flattened out a mixed type of list


code:
for index, line in enumerate(excelRead, start=1):
    keywrds=[]
    title=line.split("+")
    title=[lines.strip()for lines in title]
    print title[0]
    print index

rawDescription: How do I get index of line

description: Get index of line


code:
import lxml.html
import scraperwiki
from unidecode import unidecode
from BeautifulSoup import UnicodeDammit

def decode_html(html_string):
    converted = UnicodeDammit(html_string, isHTML=True)
    if not converted.unicode:
        raise UnicodeDecodeError(
            "Failed to detect encoding, tried [%s]",
            ', '.join(converted.triedEncodings))
    return converted.unicode

html = scraperwiki.scrape("http://www.timeshighereducation.co.uk/world-university-rankings/2012-13/world-ranking/range/001-200")
root = lxml.html.fromstring(decode_html(html))
for tr in root.cssselect("table.ranking tr"):
    if len(tr.cssselect("td.rank")) > 0 and len(tr.cssselect("td.uni")) > 0:
        university = unidecode(tr.cssselect("td.uni")[0].text_content()).strip().title()
        if 'cole' in university:
            print university

rawDescription: Scraperwiki character encoding anomaly

description: Scraperwiki character encoding anomaly


code:
for r in result:
  for d in dict:
    if d['value'] == r:
       print "ok"

rawDescription: Python - value in list of dictionaries

description: Python - value in list of dictionaries


code:
import pygame

WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )
RED   = (255,0  ,0  )
GREEN = (0  ,255,0  )
BLUE  = (0  ,0  ,255)

class Player():

    def __init__(self, x=0, y=0, width=150, height=150):

        self.rect = pygame.Rect(x, y, width, height)

        self.speed_x = 5
        self.speed_y = 5

        self.move_x = 0
        self.move_y = 0

        self.collision = [False] * 9

        self.font = pygame.font.SysFont("", 32)
        self.text = "";

    def set_center(self, screen):
        self.rect.center = screen.get_rect().center

    def event_handler(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                self.move_x -= self.speed_x
            elif event.key == pygame.K_RIGHT:
                self.move_x += self.speed_x
            elif event.key == pygame.K_UP:
                self.move_y -= self.speed_y
            elif event.key == pygame.K_DOWN:
                self.move_y += self.speed_y

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                self.move_x += self.speed_x
            elif event.key == pygame.K_RIGHT:
                self.move_x -= self.speed_x
            elif event.key == pygame.K_UP:
                self.move_y += self.speed_y
            elif event.key == pygame.K_DOWN:
                self.move_y -= self.speed_y

    def update(self):
        self.rect.x += self.move_x
        self.rect.y += self.move_y

    def draw(self, screen):

        pygame.draw.rect(screen, WHITE, self.rect, 2)
        self.draw_point(screen, self.rect.topleft, self.collision[0])
        self.draw_point(screen, self.rect.topright, self.collision[1])
        self.draw_point(screen, self.rect.bottomleft, self.collision[2])
        self.draw_point(screen, self.rect.bottomright, self.collision[3])

        self.draw_point(screen, self.rect.midleft, self.collision[4])
        self.draw_point(screen, self.rect.midright, self.collision[5])
        self.draw_point(screen, self.rect.midtop, self.collision[6])
        self.draw_point(screen, self.rect.midbottom, self.collision[7])

        self.draw_point(screen, self.rect.center, self.collision[8])

    def draw_point(self, screen, pos, collision):
        if not collision:
            pygame.draw.circle(screen, GREEN, pos, 5)
        else:
            pygame.draw.circle(screen, RED, pos, 5)

    def check_collision(self, rect):
        self.collision[0] = rect.collidepoint(self.rect.topleft)
        self.collision[1] = rect.collidepoint(self.rect.topright)
        self.collision[2] = rect.collidepoint(self.rect.bottomleft)
        self.collision[3] = rect.collidepoint(self.rect.bottomright)

        self.collision[4] = rect.collidepoint(self.rect.midleft)
        self.collision[5] = rect.collidepoint(self.rect.midright)
        self.collision[6] = rect.collidepoint(self.rect.midtop)
        self.collision[7] = rect.collidepoint(self.rect.midbottom)

        self.collision[8] = rect.collidepoint(self.rect.center)

    def render_collision_info(self):

        text = "collision: "
        print "collision:",

        if self.collision[0] or self.collision[2] or self.collision[4]:
            text += "left "
            print "left",

        if self.collision[1] or self.collision[3] or self.collision[5]:
            text += "right "
            print "right",

        if self.collision[0] or self.collision[1] or self.collision[6]:
            text += "top "
            print "top",

        if self.collision[2] or self.collision[3] or self.collision[7]:
            text += "bottom "
            print "bottom",

        if self.collision[8]:
            text += "center "
            print "center",

        print

        self.text = self.font.render(text, 1, WHITE)

    def draw_collision_info(self, screen, pos):
        screen.blit(self.text, pos)

#----------------------------------------------------------------------

class Game():

    def __init__(self):

        pygame.init()

        self.screen = pygame.display.set_mode( (800,600) )
        pygame.display.set_caption("Side Collision")

        self.player = Player()
        self.enemy  = Player()
        self.enemy.set_center(self.screen)

    def run(self):
        clock = pygame.time.Clock()

        RUNNING = True

        while RUNNING:

            # --- events ----

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    RUNNING = False

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False

                self.player.event_handler(event)

            # --- updates ---

            self.player.update()
            self.enemy.update()

            self.player.check_collision(self.enemy.rect)
            self.enemy.check_collision(self.player.rect)
            self.player.render_collision_info()
            self.enemy.render_collision_info()

            # --- draws ----

            self.screen.fill(BLACK)

            self.player.draw(self.screen)
            self.enemy.draw(self.screen)

            self.player.draw_collision_info(self.screen, (0,0))
            self.enemy.draw_collision_info(self.screen, (0,32))

            pygame.display.update()

            # --- FPS ---

            clock.tick(30)

        pygame.quit()

#----------------------------------------------------------------------

Game().run()

rawDescription: Pygame: Collision by Sides of Sprite

description: Pygame: Collision by Sides of Sprite


code:
import copy
order = [['yhjK', 'F'], 'gap', ['bcsA', 'F'], ['bcsB', 'F'], ['bcsZ', 'F'],
'gap', ['yhjK', 'R']]
order_1 = copy.deepcopy(order)

# Now changing order_1 will not change order
order_1[1] = ['TEST LIST']
print order[1] # Prints 'gap'
print order_1[1] # Prints '['TEST LIST']

rawDescription: replacing items in nested lists python

description: Replacing items in nested lists python


code:
class SymDict(object):
    def __init__(self, *args, **kwrds):
        self._mapping = _SubSymDict(*args, **kwrds)
    def __getitem__(self, key1):
        self._mapping.set_key1(key1)
        return self._mapping
    def __setitem__(self, key1, value):
        raise NotImplementedError
    def __str__(self):
        return '_mapping: ' + self._mapping.__str__()
    def __getattr__(self, name):
        return getattr(self._mapping, name)

class _SubSymDict(dict):
    def __init__(self, *args, **kwrds):
        dict.__init__(self, *args, **kwrds)
    def set_key1(self, key1):
        self.key1 = key1
    def __getitem__(self, key2):
        return dict.__getitem__(self, frozenset((self.key1, key2)))
    def __setitem__(self, key2, value):
        dict.__setitem__(self, frozenset((self.key1, key2)), value)

symdict = SymDict()
symdict[2][4] = 24
symdict[4][2] = 42

print 'symdict[2][4]:', symdict[2][4]
# symdict[2][4]: 42
print 'symdict[4][2]:', symdict[4][2]
# symdict[4][2]: 42
print 'symdict:', symdict
# symdict: _mapping: {frozenset([2, 4]): 42}

print symdict.keys()
# [frozenset([2, 4])]

rawDescription: Python symmetric dictionary where d[a][b] == d[b][a]


code:
s = '\\n'
print s
print repr(s)

rawDescription: How to keep new line character \n in list element?

description: Keep new line character \n in list element


code:
import json
response = '{"response": {"players": [{"steamid": "12345","communityvisibilitystate": 3,"profilestate": 1,"personaname": "aSteamID","lastlogoff": 1351676021,"profileurl": "http:\/\/steamcommunity.com\/id\/aSteamID\/","avatar": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/b2\/b261f66a17bfa6c95b24f8b4c6b58bb3776d57e4.jpg","avatarmedium": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/b2\/b261f66a17bfa6c95b24f8b4c6b58bb3776d57e4_medium.jpg","avatarfull": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/b2\/b261f66a17bfa6c95b24f8b4c6b58bb3776d57e4_full.jpg","personastate": 4,"realname": "Real Name","primaryclanid": "103582791429705688","timecreated": 1250966723,"loccountrycode": "GB"}]}}'
data = json.loads(response)
for player in data["response"]["players"]:
    # add code to get game count by player here
    # set to zero for this example
    totalgames = 0
    player["totalgames"] = totalgames

print json.dumps(data, sort_keys=True, indent=4)

rawDescription: Parsing and mixing Steam API calls

description: Parsing and mixing Steam API calls


code:
if interactive is True:
    proc = subprocess.Popen(args)
    proc.wait()
    if proc.returncode:
        print "returncode " + str(proc.returncode)
        sys.exit(1)
else:
    proc = subprocess.Popen(args, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    val = proc.communicate()
    if proc.returncode:
        print ""
        # send email with val[0] + val[1]

rawDescription: redirecting shell output using subprocess

description: Redirecting shell output using subprocess


code:
def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid):
    branch = local or master
    revision = branch.repository.get_revision(new_revid)
    print revision.message

rawDescription: How can I get a commit message from a bzr post-commit hook?

description: Get a commit message from a bzr post-commit hook


code:
import psycopg2
import psycopg2.extensions

class myconnection(psycopg2.extensions.connection):
    def __init__(self, database, user, password, host = 'localhost',
                port=5432, **kwargs):
        self.__dict__['conn'] = psycopg2.connect(dsn = None, database = database, user=user,
                                password=password, host=host, port=port, **kwargs)
        self.__dict__['username'] = user

    def cursor(self, username=None, **kwargs):
        curs = self.conn.cursor(**kwargs)
        if username is None:
            username = self.username
        curs.execute("select set_config('currentuser.name', %s, false)", [username])
        return curs

    def __getattr__(self, name):
        return getattr(self.conn, name)

    def __setattr__(self, name, value):
        setattr(self.conn, name, value)

connection = myconnection(database="my_database",
                          user="my_user",
                          password="my_password",
                          host='127.0.0.1')

cursor = connection.cursor(username='michael')

cursor.execute("select current_setting('currentuser.name')")
user = cursor.fetchall()[0][0]
print user
cursor.close()

rawDescription: Setting a custom runtime parameter every time I get the db cursor in psycopg2


code:
from Tkinter import *
import random

class BubbleFrame:

    def __init__(self, root):
        root.title("Math Bubbles")
        self.bubbles = {}  # this will hold bubbles ids, positions and velocities
        self.score = 0
        Button(root, text="Start", width=8, command=self.initialize_bubbles).pack()  # This button starts the game, making the bubbles move across the screen
        Button(root, text="Quit", width=8, command=quit).pack()
        self.canvas = Canvas(root, width=800, height=650, bg='#afeeee')
        self.canvas.create_text(400, 30, fill="darkblue", font="Times 20 italic bold", text="Click the bubbles that are multiples of two.")
        self.canvas.pack()

    def initialize_bubbles(self):
        for each_no in xrange(1, 21):
            xval = random.randint(5, 765)
            yval = random.randint(5, 615)
            oval_id = self.canvas.create_oval(xval, yval, xval + 30, yval + 30,
                                              fill="#00ffff", outline="#00bfff",
                                              width=5, tags="bubble")
            text_id = self.canvas.create_text(xval + 15, yval + 15, text=each_no, tags="bubble")
            self.canvas.tag_bind("bubble", "<Button-1>", lambda x: self.click(x))
            self.bubbles[oval_id] = (xval, yval, 0, 0, each_no, text_id)  # add bubbles to dictionary

    def click(self, event):
        if self.canvas.find_withtag(CURRENT):
            item_uid = event.widget.find_closest(event.x, event.y)[0]
            is_even = False
            try:  # clicked oval
                self.bubbles[item_uid]
            except KeyError:  # clicked the text
                for key, value in self.bubbles.iteritems():
                    if item_uid == value[5]:  # comparing to text_id
                        if value[4] % 2 == 0:
                            is_even = True
                        self.canvas.delete(key)  # deleting oval
                        self.canvas.delete(item_uid)  # deleting text
            else:
                if self.bubbles[item_uid][4] % 2 == 0:
                    is_even = True
                self.canvas.delete(item_uid)  # deleting oval
                self.canvas.delete(self.bubbles[item_uid][5])  # deleting text
            if is_even:
                self.score += 1
            else:
                self.score -= 1
            print self.score

    def loop(self, root):
        for oval_id, (x, y, dx, dy, each_no, text_id) in self.bubbles.items():
            # update velocities and positions
            dx += random.randint(-1, 1)
            dy += random.randint(-1, 1)
            # dx and dy should not be too large
            dx, dy = max(-5, min(dx, 5)), max(-5, min(dy, 5))
            # bounce off walls
            if not 0 < x < 770:
                dx = -dx
            if not 0 < y < 620:
                dy = -dy
            # apply new velocities
            self.canvas.move(oval_id, dx, dy)
            self.canvas.move(text_id, dx, dy)
            self.bubbles[oval_id] = (x + dx, y + dy, dx, dy, each_no, text_id)
        # have mainloop repeat this after 100 ms
        root.after(100, self.loop, root)

if __name__ == "__main__":
    root = Tk()
    frame = BubbleFrame(root)
    frame.loop(root)
    root.mainloop()

rawDescription: Python: How to get the use of a mouse click to work?


code:
import atexit
import weakref

class CallableMethodWeakRef:
    def __init__(self, object, method_name):
        self.object_ref = weakref.ref(object)
        self.method_name = method_name
    def __call__(self):
        object = self.object_ref()
        if object:
            getattr(object, self.method_name)()

class Recorder:
    def __init__(self, *args):
        atexit.register(CallableMethodWeakRef(self, 'flush'))

    def flush(self):
        print 'flushing'

rawDescription: Cannot unregister functions from atexit in python 2.7


code:
response = urllib2.urlopen("...")
print response.info().getheader("Set-Cookie") # get the value of the Set-Cookie header

rawDescription: get HTTPS header in python

description: Get HTTPS header in python


code:
#-----!!!!SPACE INVADERS!!!!-----

import pygame
from pygame.locals import *

#----------------------------------------------------------------------

class Ship():

    def __init__(self, screen_rect):

        #self.image = pygame.image.load("spaceship.png")
        self.image = pygame.image.load("ball1.png")
        self.image = pygame.transform.scale(self.image, (100,50))

        self.rect = self.image.get_rect()

        # put ship bottom, center x
        self.rect.bottom = screen_rect.bottom
        self.rect.centerx = screen_rect.centerx

        self.move_x = 0

        self.shots = []
        self.shots_count = 0

        self.max_shots = 2

    #--------------------

    def event_handler(self, event):

        #print "debug: Ship.event_handler"

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                self.move_x = -5
            elif event.key == K_RIGHT:
                self.move_x = 5
            elif event.key == K_SPACE:
                if len(self.shots) < self.max_shots:
                    self.shots.append(Bullet(self.rect.centerx, self.rect.top))

        if event.type == KEYUP:
            if event.key in (K_LEFT, K_RIGHT):
                self.move_x = 0

    def update(self):

        #print "debug: Ship.update: move_x", self.move_x
        self.rect.x += self.move_x

        for s in self.shots:
            s.update()

        for i in range(len(self.shots)-1, -1, -1):
            print "debug: Ship.update: testing bullet ", i
            if not self.shots[i].is_alive:
                print "debug: Ship.update: removing bullet ", i
                del self.shots[i]

    #--------------------

    def draw(self, screen):

        #print "debug: Ship.draw"

        screen.blit(self.image, self.rect.topleft)

        for s in self.shots:
            s.draw(screen)

    def bullet_detect_collison(self, enemy_list):

        for s in self.shots:
            for e in enemy_list:
                if pygame.sprite.collide_circle(s, e):
                    s.is_alive = False
                    e.is_alive = False

#----------------------------------------------------------------------

class Bullet():

    def __init__(self, x, y):

        #self.image = pygame.image.load("SingleBullet.png")
        self.image = pygame.image.load("ball2.png")
        self.image = pygame.transform.scale(self.image, (25,25))

        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y

        self.is_alive = True

    #--------------------

    def update(self):

        self.rect.y -= 15

        if self.rect.y < 0:
            self.is_alive = False

    #--------------------

    def draw(self, screen):

        screen.blit(self.image, self.rect.topleft)

#----------------------------------------------------------------------

class Enemy():

    def __init__(self, x, y):

        self.image = pygame.image.load("ball3.png")

        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y

        self.is_alive = True

    #--------------------

    def update(self):

        self.rect.y += 1

        #~ if self.rect.y < 0:
            #~ self.is_alive = False

    #--------------------

    def draw(self, screen):

        screen.blit(self.image, self.rect.topleft)

#----------------------------------------------------------------------

class Game():

    def __init__(self):

        pygame.init()

        w, h = 800, 800
        self.screen = pygame.display.set_mode((w,h))

        pygame.mouse.set_visible(False)

        self.ship = Ship(self.screen.get_rect())

        self.enemies = []

        for i in range(100, 800, 100):
            self.enemies.append(Enemy(i, 100))

        font = pygame.font.SysFont("", 72)
        self.text_paused = font.render("PAUSED", True, (255, 0, 0))
        self.text_paused_rect = self.text_paused.get_rect(center=self.screen.get_rect().center)

    #-----MAIN GAME LOOP-----

    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        PAUSED = False

        while RUNNING:

            clock.tick(30)

            #--- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        RUNNING = False

                    if event.key == K_p:
                        PAUSED = not PAUSED

                if not PAUSED:
                    self.ship.event_handler(event)

            #--- changes ---
            if not PAUSED:

                self.ship.update()

                for e in self.enemies:
                    e.update()

                self.ship.bullet_detect_collison(self.enemies)

                for i in range(len(self.enemies)-1, -1, -1):
                    print "debug: Ship.update: testing bullet ", i
                    if not self.enemies[i].is_alive:
                        print "debug: Ship.update: removing bullet ", i
                        del self.enemies[i]

            #--- draws ---

            self.screen.fill((0,0,0))

            self.ship.draw(self.screen)

            for e in self.enemies:
                e.draw(self.screen)

            if PAUSED:
                self.screen.blit(self.text_paused, self.text_paused_rect)

            pygame.display.update()

        #--- quit ---

        pygame.quit()

#---------------------------------------------------------------------

Game().run()

rawDescription: Space Invaders project

description: Space Invaders project


code: print "Client disconnected, Awaiting new connections..."

rawDescription: Python Socket (Simple server script)

description: Python Socket (Simple server script)


code:
def tag_text(self, items, text):
    text = text.decode('utf-8')
    for item in items:
        text = re.sub(
            re.escape(item),
            ur'\g<0>',
            text,
            flags=re.IGNORECASE | re.UNICODE)
    return text

print tag_text(None, ["foo", "bar"], "text with Foo and BAR")
# text with Foo and BAR

rawDescription: Regular expression python optimising or idea for text hightlight


code:
from sklearn.linear_model.logistic import _logistic_loss
print _logistic_loss(clf.coef_, X, y, 1 / clf.C)

rawDescription: How to evaluate cost function for scikit learn LogisticRegression?

description: Evaluate cost function for scikit learn LogisticRegression


code:
for word in output.decode('utf-8').split('\n'):
    print word

rawDescription: split bytes variable on newline

description: Split bytes variable on newline


code:
import Tkinter as tk
import TkTreectrl as treectrl
import sqlite3

def setup_table(connection):
    cursor=connection.cursor()
    cursor.execute('''CREATE TABLE foo
                      (id INTEGER PRIMARY KEY AUTOINCREMENT,
                      bar TEXT)''')
    sql='INSERT INTO foo (bar) values (?)'
    for i in range(10):
        cursor.execute(sql,(i,))
    cursor.execute(sql,(u'\N{INFINITY}',))

def select_cmd(selected):
    print 'Selected items:', selected

def main():
    connection=sqlite3.connect(':memory:')
    setup_table(connection)
    cursor=connection.cursor()

    root = tk.Tk()
    root.title('Simple MultiListbox demo')
    mlb = treectrl.MultiListbox(root)
    mlb.pack(side='top', fill='both', expand=1)
    tk.Button(root, text='Close', command=root.quit).pack(side='top', pady=5)
    mlb.focus_set()
    mlb.configure(selectcmd=select_cmd, selectmode='extended')
    mlb.config(columns=('Column 1', 'Column 2'))
    cursor.execute('SELECT * from foo')
    for row in cursor.fetchall():
        mlb.insert('end',*map(unicode,row))
    root.mainloop()

if __name__=='__main__':
    main()

rawDescription: Display Listbox with columns using Tkinter?


code:
def obtener_canales():
    for i in range (1,3):
        url = "http://arenavision.in/agenda"
        peticion = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
        leemos_page = urllib2.urlopen(peticion)
        enlace_acestream = leemos_page.read()
        leemos_page.close()
    partido = enlace_acestream
    for item in partido.split("\n"):
        if "LIGA BBVA" in item:
              print item
    return partido

rawDescription: The variable is not the same after return


code:
import wx
from wx.lib.pubsub import pub

########################################################################
class OtherFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY, "Secondary Frame")
        panel = wx.Panel(self)

        msg = "Enter a Message to send to the main frame"
        instructions = wx.StaticText(panel, label=msg)
        self.msgTxt = wx.TextCtrl(panel, value="")

        sendBtn = wx.Button(panel, label="Send Msg")
        sendBtn.Bind(wx.EVT_BUTTON, self.onSendMsg)

        closeBtn = wx.Button(panel, label="Send and Close")
        closeBtn.Bind(wx.EVT_BUTTON, self.onSendAndClose)

        sizer = wx.BoxSizer(wx.VERTICAL)
        flags = wx.ALL|wx.CENTER
        sizer.Add(instructions, 0, flags, 5)
        sizer.Add(self.msgTxt, 0, flags, 5)
        sizer.Add(sendBtn, 0, flags, 5)
        sizer.Add(closeBtn, 0, flags, 5)
        panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def onSendMsg(self, event):
        """"""
        msg = "Another message!"
        pub.sendMessage("anotherListener",
                        message=msg,
                        listener="anotherListener")

    #----------------------------------------------------------------------
    def onSendAndClose(self, event):
        """
        Send a message and close frame
        """
        msg = self.msgTxt.GetValue()
        pub.sendMessage("panelListener",
                        message=msg,
                        listener="panelListener")
        self.Close()

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        pub.subscribe(self.myListener, "panelListener")
        pub.subscribe(self.myListener, "anotherListener")

        btn = wx.Button(self, label="Open Frame")
        btn.Bind(wx.EVT_BUTTON, self.onOpenFrame)

    #----------------------------------------------------------------------
    def myListener(self, message, listener=None):
        """
        Listener function
        """

        if listener == "panelListener":
            print "panel listener has sent the following: ",
            print message
        elif listener == "anotherListener":
            print "another listener sent the following: ",
            print message

    #----------------------------------------------------------------------
    def onOpenFrame(self, event):
        """
        Opens secondary frame
        """
        frame = OtherFrame()
        frame.Show()

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="New PubSub API Tutorial")
        panel = MyPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: python pubsub subscribe to more than one topic

description: Python pubsub subscribe to more than one topic


code:
mystr = u'<url host="bing.com" method="GET" uri="/update?v=1&uid=\xdf\xe2\x80|\xff\xff\xff\xff\xf3\x99\x83|\x88\xe2\x80|\xff\xff\xff\xff\xf6\x80|n\x80|&os=45" user_agent=""/>\n    <url host="zaloopa.co.cc" method="GET" uri="/update?v=1&uid=\xdf\xe2\x80|\xff\xff\xff\xff\xf3\x99\x83|\x88\xe2\x80|\xff\xff\xff\xff\xf6\x80|n\x80|&os=45" user_agent=""/>'

import json
print json.dumps({'url': mystr}, ensure_ascii=False)

rawDescription: 'utf8' codec can't decode byte 0xdf in position 59: invalid continuation byte


code:
inputs = (
    (Clients, 'Clients.csv'),
    (Simulation, 'Simulation.csv'),
    (Indicators, 'Indicators.csv'),
    (LegalEntity, 'LegalEntity.csv'),
    (DefaultPortfolio, 'DefaultPortfolio.csv'),
    (ExcludedProductTypes, 'ExcludedProductTypes.csv'),
)

results = {}
errors = []
for cls, filename in inputs:
    try:
        results[cls.__name__[0].lower() + cls.__name__[1:]] = cls(filename)
    except Exception, e:
        errors.append(e)

if errors:
    raise MultipleErrors(errors)

rawDescription: A Pythonic way for "resume next" on exceptions?


code:
import sys
sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os

class AllowAllKeys(pm.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

HOST = '127.0.0.1'
USER = ''
PASSWORD = ''

client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, password=PASSWORD)

channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')

stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()

stdout.close()
stdin.close()
client.close()

rawDescription: How do you execute multiple commands in a single session in Paramiko? (Python)

description: Execute multiple commands in a single session in Paramiko? (Python)


code:
data = open('hugedataset.txt').read()  # Assuming it fits in memory
present=[]  # As @svk points out, you could make this a set

with open('list.txt', 'r') as f:
    list1 = [line.strip() for line in f]

print list1

for title in list1:
   if title in data:
      print title
      present.append(title)

set=set(present)
print set

rawDescription: Simplify python code for txt searching

description: Simplify python code for txt searching


code:
import Tkinter as tk

class VerticalScrolledFrame(tk.Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    """
    def __init__(self, parent, *args, **kw):
        tk.Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)
        vscrollbar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
        canvas = tk.Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = tk.Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=tk.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

root = tk.Tk()
root.title("Scrollable Frame Demo")
root.configure(background="gray99")

scframe = VerticalScrolledFrame(root)
scframe.pack()

lis = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
for i, x in enumerate(lis):
    btn = tk.Button(scframe.interior, height=1, width=20, relief=tk.FLAT,
        bg="gray99", fg="purple3",
        font="Dosis", text='Button ' + lis[i],
        command=lambda i=i,x=x: openlink(i))
    btn.pack(padx=10, pady=5, side=tk.TOP)

def openlink(i):
    print lis[i]

root.mainloop()

rawDescription: Dynamic Button with ScrollBar in tkinter - Python


code:
#!/usr/bin/python

# -*- coding: utf-8 -*-

import numpy as np
import wx
import time
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

class myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,parent = None, id = -1, title = 'SWAP!', size = (480,390))

        self.figurePanel = FigurePanel(parent = self)

        self.canvas1 = self.figurePanel.canvas
        self.canvas2 = self.figurePanel.enlarged_canvas

        self.fig1 = self.figurePanel.enlarged_figure
        self.fig2 = self.figurePanel.figure

        self.fig1.set_canvas(self.canvas1) #enlarged_fig resides in canvas1

        self.canvas1.Show()
        self.Show()

        self.canvas2.mpl_connect("button_release_event",self.OnLoadFigure) #Enable the detection of mouseclicks for the plots in the plotting window
        print "Click anywhere on the figure to swap the plots!"
        self.display = 1

    def OnLoadFigure(self,event = None):
        print "Tried to load figure"
        if event != None:
            self.display = self.SwapView(big_plot = self.fig1 ,small_plots = self.fig2 , display = self.display, main_canvas = self.canvas1 , shadow_canvas = 0)

    def SwapView(self,big_plot = None,display = -1, small_plots = None,main_canvas = None,shadow_canvas = None):
        '''
            Keep swapping the main_canvas with the shadow_canvas to show either fig1 or fig2.

            Initially, big_plot has main_canvas and small_plots have shadow_canvas
        '''
        wx.Yield()
        print display
        if display == 1: #Show the big plot
            print 'big_plot showing'
            big_plot.set_canvas(main_canvas)
            main_canvas.Show()
            time.sleep(0.01) #Fastest time you can pick
            wx.Yield()
        else:
            print 'small_plots showing'
            main_canvas.Hide()
            wx.Yield()

        self.Refresh(canvas = main_canvas)
        display = not(display)
        return display

    def Refresh(self,canvas = None,figure = None):
        wx.Yield()
        if canvas != None:
            print "draw"
            canvas.draw()
        self.Update()
        self.figurePanel.Update()
        wx.Yield()

class FigurePanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.figPanel = self
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.figure = Figure(figsize = (8,6.1), dpi =60)
        self.ax = self.figure.add_subplot(1,1,1)
        self.ax.plot([1,2,3],[1,2,3])
        self.enlarged_figure = Figure(figsize = (8,6.1), dpi = 60)
        self.ax1 = self.enlarged_figure.add_subplot(2,1,1)
        self.ax2 = self.enlarged_figure.add_subplot(2,1,2)
        self.ax1.plot([1,2,3],[1,4,9])
        self.ax2.plot([1,2,3],[1,4,9])
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.enlarged_canvas = FigureCanvas(self,-1,self.enlarged_figure)
        self.Layout()
        self.Fit()

if __name__ == "__main__":
    app = wx.App(False)
    fr = myframe()
    app.MainLoop()

rawDescription: Relating a canvas to a figure wxPython

description: Relating a canvas to a figure wxPython


code:
def count(limits):
    idcs = [0] * len(limits)
    while True:
        yield tuple(idcs)
        for n in range(len(limits)-1, -1, -1):
            idcs[n] += 1
            if idcs[n] != limits[n]:
                break
            elif n == 0:
                raise StopIteration
            else:
                idcs[n] = 0

words = ['foo', 'bar', 'xyzzy']
for idcs in count(map(len, words)):
    chars = map(lambda w, i: w[i], words, idcs)
    print idcs, chars

rawDescription: n-dimensional traverse

description: N-dimensional traverse


code:
from sqlalchemy import Column, Integer, ForeignKey, Table, ForeignKeyConstraint, create_engine
from sqlalchemy.orm import relationship, backref, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
from itertools import chain

Base = declarative_base()

class SupervisionAssociation(Base):
    __tablename__ = 'supervision'

    supervisor_id = Column(Integer, ForeignKey('supervisor.id'), primary_key=True)
    client_id = Column(Integer, ForeignKey('client.id'), primary_key=True)

    supervisor = relationship("Supervisor", backref="client_associations")
    client = relationship("Client", backref="supervisor_associations")
    schedules = relationship("Schedule")

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)

class Supervisor(User):
    __tablename__ = 'supervisor'
    __mapper_args__ = {'polymorphic_identity': 'supervisor'}

    id = Column(Integer, ForeignKey('user.id'), primary_key = True)

    clients = association_proxy("client_associations", "client",
                        creator=lambda c: SupervisionAssociation(client=c))

    @property
    def schedules(self):
        return list(chain(*[c.schedules for c in self.client_associations]))

class Client(User):
    __tablename__ = 'client'
    __mapper_args__ = {'polymorphic_identity': 'client'}

    id = Column(Integer, ForeignKey('user.id'), primary_key = True)

    supervisors = association_proxy("supervisor_associations", "supervisor",
                        creator=lambda s: SupervisionAssociation(supervisor=s))
    @property
    def schedules(self):
        return list(chain(*[s.schedules for s in self.supervisor_associations]))

class Schedule(Base):
    __tablename__ = 'schedule'
    __table_args__ = (
        ForeignKeyConstraint(['client_id', 'supervisor_id'],
        ['supervision.client_id', 'supervision.supervisor_id']),
    )

    id = Column(Integer, primary_key=True)
    client_id = Column(Integer, nullable=False)
    supervisor_id = Column(Integer, nullable=False)
    client = association_proxy("supervisor_association", "client")

engine = create_engine('sqlite:///temp.db', echo=True)
db_session = scoped_session(sessionmaker(bind=engine))
Base.metadata.create_all(bind=engine)

c1, c2 = Client(), Client()
sp1, sp2 = Supervisor(), Supervisor()
sch1, sch2, sch3 = Schedule(), Schedule(), Schedule()

sp1.clients = [c1]
c2.supervisors = [sp2]
c2.supervisor_associations[0].schedules = [sch1, sch2]
c1.supervisor_associations[0].schedules = [sch3]

db_session.add_all([c1, c2, sp1, sp2, ])
db_session.commit()

print c1.schedules
print sp2.schedules

rawDescription: SQLAlchemy relationship on many-to-many association table


code:
#changed original code to simple plot() because manual window structure
#somehow didn't automatically cooperate with viewbox' map methods

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

voieTT=np.ones(100)
voieTemps=np.ones(100)
for i in range(100):
    voieTT[i]=np.random.random_sample()
    voieTemps[i]=i

signemax=np.max(voieTT)
tmax=np.where(voieTT==np.max(voieTT))[0][0]

grapheTT = pg.plot(enableMenu=False)

grapheTTVB=grapheTT.getViewBox()
grapheTT.plot(voieTemps, voieTT)
grapheTT.plot([tmax],[signemax],symbol='o',symbolSize=8)
grapheTT.showGrid(x=True, y=True)

textVmax = pg.TextItem(anchor=(0.5,1.5), border='w', fill=(0,0,255))
textVmax.setHtml('
Vmax=%0.1f mm/s @ %0.1f s
'%(np.abs(signemax),tmax))
grapheTT.addItem(textVmax)
textVmax.setPos(tmax, signemax)

#DISCLAIMER: there's likely a better way, but this works too:

#you can get pixel dimensions x,y,w,h from bounding rectangle
br = textVmax.boundingRect()
print br

#and scale them into viewbox data dimensions
sx, sy = grapheTTVB.viewPixelSize() #scaling factors
print sx, sy
print sx*br.width(), sy*br.height()

#ALSO, you can just use ViewBox autorange
#ViewBox autoranges based on its contained items' dataBounds() info
#however TextItem.py is a UIGraphicsItem.py with dataBounds() return None
"""Called by ViewBox for determining the auto-range bounds.
By default, UIGraphicsItems are excluded from autoRange."""

#so, following example of... ArrowItem.py
#here is a simple dataBounds() for TextItem

def Autoranging_TextItem_dataBounds(axis, frac=1.0, orthoRange=None):
    br = textVmax.boundingRect()
    sx, sy = grapheTTVB.viewPixelSize()
    w, h = sx*br.width(), sy*br.height()
    if axis == 0: return [-w/2, w/2]
    if axis == 1: return [0, h]

textVmax.dataBounds = Autoranging_TextItem_dataBounds

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

rawDescription: pyqtgraph : how to know the size of a TextItem?

description: Pyqtgraph : how to know the size of a TextItem


code:
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class TestItem():
    def __init__(self, name, checked):
        self.checked = checked
        self.name = name

class StbTreeView(QAbstractListModel):
    def __init__(self, args, parent=None):
        super(StbTreeView, self).__init__(parent)

        self.args = []
        for item_name in args:
            self.args.append(TestItem(item_name, False))

        for item in self.args:
            print item.name

    def rowCount(self, parent):
        return len(self.args)

    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return QString("Select STB's")

    def flags(self, index):
        return  Qt.ItemIsUserCheckable | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            row = index.row()
            print self.args[row].name
            return self.args[row].name

        if role == Qt.CheckStateRole:
            row = index.row()
            print self.args[row].checked
            if self.args[row].checked == False:
                return QVariant(Qt.Unchecked)
            else:
                return QVariant(Qt.Checked)

    def setData(self, index, value, role):
        if role == Qt.CheckStateRole:
            row = index.row()
            self.args[row].checked = not self.args[row].checked
        return True

def main():
    myapp = QApplication(sys.argv)

    data = ['STB1', 'STB2', 'STB3', 'STB4', 'STB5', 'STB6', 'STB7', 'STB8']

    model = StbTreeView(data)
    tree_view = QTreeView()
    tree_view.show()
    tree_view.setModel(model)

    myapp.exec_()

if __name__ == '__main__':
    main()

rawDescription: Unable to select Checkbox inside TreeView


code:
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
import time
from threading import Thread
import threading

class selfUpdatePanel(wx.Panel):
    def __init__(self, parent, mystyle, interval, topic, message):
        wx.Panel.__init__(self, parent, style = mystyle)
        pub.subscribe(self.updatePanel, topic)
        self.updateMsg = message
        self.textCtrl = None
        self.interval = interval
        self.topic = topic
        pub.subscribe(self.updatePanel, self.topic)

    def setTextCtrl(self,text):
        self.textCtrl = text

    def updatePanel(self):
        self.textCtrl.SetLabel(self.updateMsg)

    def threadMethod(self):
        while True:
            print "threadMethod"
            time.sleep(self.interval)
            wx.CallAfter(pub.sendMessage, self.topic)

    def startThread(self):
        self.thread = Thread(target=self.threadMethod)
        self.thread.start()

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 500
        screenHeight = 400
        screenSize = (screenWidth,screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        self.locationFont = locationFont = wx.Font(12, wx.MODERN, wx.NORMAL, wx.BOLD)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        #myPanelA = wx.Panel(self, style=wx.SIMPLE_BORDER)

        myPanelA = selfUpdatePanel(self, wx.SIMPLE_BORDER, 3, 'Update-panelA', 'Problem solved')
        myPanelA.SetBackgroundColour('#C0FAE0')
        self.myTextA = wx.StaticText(myPanelA, -1, "I have a problem :( ")
        myPanelA.setTextCtrl(self.myTextA)

        #myPanelB = wx.Panel(self, style=wx.SIMPLE_BORDER)
        myPanelB = selfUpdatePanel(self, wx.SIMPLE_BORDER, 5, 'Update-panelB', 'Mine too')
        myPanelB.SetBackgroundColour('#C0FAFF')
        self.myTextB = wx.StaticText(myPanelB, -1, "Me too :( ")
        myPanelB.setTextCtrl(self.myTextB)
        mainSizer.Add(myPanelA, 1, wx.EXPAND, 5)
        mainSizer.Add(myPanelB, 1, wx.EXPAND, 5)
        self.SetSizer(mainSizer)

        myPanelB.startThread()
        myPanelA.startThread()

if __name__=='__main__':
    app = wx.App()
    frame = GUI(parent=None, id=-1, title="Problem Demo")
    frame.Show()
    app.MainLoop()

rawDescription: Good approach for updating the GUI continuously in wxPython using threads?


code:
def dynProgSolution(text, probs):
  probUpTo = [1]
  for i in range(1, len(text)+1):
    cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))
    probUpTo.append(cur)
  return probUpTo[-1]

print dynProgSolution(
  'abc',
  {'a': 0.1, 'b': 0.2, 'c': 0.3,
   'ab': 0.4, 'bc': 0.5, 'abc': 0.6}
  )

rawDescription: Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string?


rawDescription: what data structure for python data reconcile script?

description: What data structure for python data reconcile script


code:
import heapq

def find_kth_smallest(k, a_list, smallest_k = [], top_level = True):
    l = len(a_list)
    if l > 1:
        l /= 2
        smallest_k = find_kth_smallest(k, a_list[:l], smallest_k, False)
        smallest_k = find_kth_smallest(k, a_list[l:], smallest_k, False)
    elif l < 1:
        return []
    else:
        if isinstance(a_list[0], list):
            smallest_k = find_kth_smallest(k, a_list[0], smallest_k, False)
        else:
            smallest_k.append(a_list[0])
            smallest_k = heapq.nsmallest(k, smallest_k)
    if top_level:
        return smallest_k[-1]
    else:
        return smallest_k

print find_kth_smallest(3, [10, [9, 8, [[]]], [7, 6, [[5], 4, 3]], 2, 1]) # => 3

rawDescription: Recursively find the kth largest int in list of list of int in Python


code:
width = 6
for i in range(len(sequence) - width):
    print " " * i + sequence[i:i+width]

rawDescription: Loops for sequence output - python

description: Loops for sequence output - python


code:
# Iterable object that has a return on append
class SymGroup(list):
    def add(self, value):
        self.append(value)
        return value

# Create my list that represents a group of symbol values
valid_animals = SymGroup()

# Assign and append values at the same time
hippo = valid_animals.bind("hippo")
gator = valid_animals.bind("gator")
mouse = valid_animals.bind("mouse")

# Symbol can be used by itself
print "There is a", mouse, "in my house"

# Can iterate across the symbol values
print mouse in valid_animals  # True
print "horse" in valid_animals  # False

rawDescription: Python: Iterating over a group of symbols


code:
mens_name_upper = [name.upper() for name in mens_name]

if current_name.upper() in mens_name_upper:
   print 'I know that name.'

rawDescription: List verification. Upper and lower case

description: List verification. Upper and lower case


code:
def hello_world():
    print "hello world"

d = {'hello':hello_world}

d['hello']()

locals()['hello_world']()

rawDescription: Calling a function from a string (key[:-1]())


code:
import random

def Main() :

    print "TESTING"
    print
    print
    print "1 1d4"

    sum = raw_input("> ")

    if sum == '1':
        numberr = random.randrange(1, 5)
        if numberr == 1:
            print "Small"
        elif numberr == 2:
            print "Medium"
        elif numberr == 3:
            print "Large"
        elif numberr == 4:
            print "Huge"

while 1:
    input = raw_input("Press Enter to continue or q to quit").upper()
    if input == 'Q': break
    elif input == '' : Main()

rawDescription: How do I have a program reference an internal random result and apply it to a list to print a result?

description: Have a program reference an internal random result and apply it to a list to print a result


code:
#!/usr/bin/env python
numbers = set() # create a set for storing numbers that were already written
out = open('output', 'w') # open 'output' file for writing
for line in open('input'): # loop through each line of 'input' file
    try:
        i = int(line) # try to convert line to integer
    except ValueError:  # if conversion to integer fails display a warning
        print "Warning: cannot convert to number string '%s'" % line.strip()
        continue # skip to next line on error
    if i not in numbers: # check if the number wasn't already added to the set
        out.write('%d\n' % i) # write the number to the 'output' file followed by EOL
        numbers.add(i) # add number to the set to mark it as already added

rawDescription: PYTHON how to search a text file for a number


code:
import numpy as np
import matplotlib.pyplot as plt

class DraggableRectangle:
    def __init__(self, rect):
        self.rect = rect
        self.press = None

    def connect(self):
        'connect to all the events we need'
        #self.cidpress = self.rect.figure.canvas.mpl_connect(
        #    'button_press_event', self.on_press)
        self.cidrelease = self.rect.figure.canvas.mpl_connect(
            'button_release_event', self.on_release)
        self.cidmotion = self.rect.figure.canvas.mpl_connect(
            'motion_notify_event', self.on_motion)

    def on_press(self, event):
        'on button press we will see if the mouse is over us and store some data'
        if event.inaxes != self.rect.axes: return

        contains, attrd = self.rect.contains(event)
        if not contains: return
        print 'event contains', self.rect.xy

        x0, y0 = self.rect.xy
        self.press = x0, y0, event.xdata, event.ydata

    def on_motion(self, event):
        'on motion we will move the rect if the mouse is over us'
        if self.press is None: return
        if event.inaxes != self.rect.axes: return
        x0, y0, xpress, ypress = self.press
        dx = event.xdata - xpress
        dy = event.ydata - ypress
        #print 'x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f'%(x0, xpress, event.xdata, dx, x0+dx)
        self.rect.set_x(x0+dx)
        self.rect.set_y(y0+dy)

        self.rect.figure.canvas.draw()

    def on_release(self, event):
        'on release we reset the press data'
        self.press = None
        self.rect.figure.canvas.draw()

    def disconnect(self):
        'disconnect all the stored connection ids'
        self.rect.figure.canvas.mpl_disconnect(self.cidpress)
        self.rect.figure.canvas.mpl_disconnect(self.cidrelease)
        self.rect.figure.canvas.mpl_disconnect(self.cidmotion)

class RectangleHandler():

    def __init__(self, drs):
        self.drs = drs
        self.ax = drs[0].rect.axes

        self.cidpress = self.ax.figure.canvas.mpl_connect(
            'button_press_event', self.on_press)

    def on_press(self, event):
        if event.inaxes != self.ax: return
        for dr in self.drs:
            rect = dr.rect
            contains, attrd = rect.contains(event)
            if contains:
                zorder = rect.zorder
                try:
                    if zorder > maxZorder:
                        maxZorder = zorder
                        rectToDrag = dr
                except NameError:
                    maxZorder = zorder
                    rectToDrag = dr
        try:
            if rectToDrag:
                rectToDrag.on_press(event)
        except UnboundLocalError:
            pass

fig = plt.figure()
ax = fig.add_subplot(111)
rects = ax.bar(range(10), 20*np.random.rand(10))
drs = []
for i, rect in enumerate(rects):
    rect.zorder = i
    dr = DraggableRectangle(rect)
    dr.connect()
    drs.append(dr)

rh = RectangleHandler(drs)
plt.show()

rawDescription: matplotlib: how to constrain mouse event handling to top-most artist?

description: Matplotlib: how to constrain mouse event handling to top-most artist


code:
import cgi
import cgitb; cgitb.enable() # Optional; for debugging only

print "Content-Type: text/html"
print ""

arguments = cgi.FieldStorage()
for i in arguments.keys():
 print arguments[i].value

rawDescription: Getting HTTP GET arguments in Python

description: Getting HTTP GET arguments in Python


code:
import sys
import cv2

def elongation(m):
    x = m['mu20'] + m['mu02']
    y = 4 * m['mu11']**2 + (m['mu20'] - m['mu02'])**2
    return (x + y**0.5) / (x - y**0.5)

img = cv2.cvtColor(cv2.imread(sys.argv[1]), cv2.COLOR_BGR2GRAY)
# Assuming input has grayscale dark contours:
img = 255 - cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1]

m = cv2.moments(img)
print elongation(m)

rawDescription: Retrieve elongation feature in python opencv, what kind of moment it supposed to be used?


code:
Basket = {
          'Fruit1' : "none",
          'Fruit2' : "none",
          'Fruit3' : "none",
          'Fruit4' : "none",
          'Fruit5' : "none"
         }

basketSize = len(Basket)

if 'apple' not in Basket.values():
    print "Couldn't find the apple"

    for i in range(basketSize):
        curItem = "Fruit"+str(i+1)
        if Basket[curItem] == "none":
            Basket[curItem] = "apple"
            break

print Basket

rawDescription: Modifying a value in a Python dictionary


code:
import SocketServer
import threading

class Handler(SocketServer.StreamRequestHandler):

    def handle(self):
        print self.client_address,'connected'
        self.server.add_client(self.request)
        while 1:
            data = self.request.recv(1024)
            if not data: break
            self.server.send(self.request,data)
        self.server.remove_client(self.request)

class Server(SocketServer.ThreadingTCPServer):

    def __init__(self,*args,**kwargs):
        SocketServer.ThreadingTCPServer.__init__(self,*args,**kwargs)
        self.clients = []
        self.lock = threading.Lock()

    def add_client(self,c):
        with self.lock:
            self.clients.append(c)

    def remove_client(self,c):
        with self.lock:
            self.clients.remove(c)

    def send(self,sender,data):
        with self.lock:
            for c in self.clients:
                if c is not sender:
                    c.sendall(data)

s = Server(('',8000),Handler)
s.serve_forever()

rawDescription: Python TCP Client to Client message forwarding