code:
from Tkinter import *

master = Tk()
master.title("Select Groups")

rows=10
columns=10

boxes = []
boxVars = []

# Create all IntVars, set to 0

for i in range(rows):
    boxVars.append([])
    for j in range(columns):
        boxVars[i].append(IntVar())
        boxVars[i][j].set(0)

def checkRow(i):
    global boxVars, boxes
    row = boxVars[i]
    deselected = []

    # Loop through row that was changed, check which items were not selected
    # (so that we know which indeces to disable in the event that 2 have been selected)

    for j in range(len(row)):
        if row[j].get() == 0:
            deselected.append(j)

    # Check if enough buttons have been selected. If so, disable the deselected indeces,
    # Otherwise set all of them to active (in case we have previously disabled them).

    if len(deselected) == (len(row) - 2):
        for j in deselected:
            boxes[i][j].config(state = DISABLED)
    else:
        for item in boxes[i]:
            item.config(state = NORMAL)

def getSelected():
    selected = {}
    for i in range(len(boxVars)):
        temp = []
        for j in range(len(boxVars[i])):
            if boxVars[i][j].get() == 1:
                temp.append(j + 1)
        if len(temp) > 1:
            selected[i + 1] = temp
    print selected

for x in range(rows):
    boxes.append([])
    for y in range(columns):
        Label(master, text= "Group %s"%(y+1)).grid(row=0,column=y+1)
        Label(master, text= "Test %s"%(x+1)).grid(row=x+1,column=0)
        boxes[x].append(Checkbutton(master, variable = boxVars[x][y], command = lambda x = x: checkRow(x)))
        boxes[x][y].grid(row=x+1, column=y+1)

b = Button(master, text = "Get", command = getSelected, width = 10)
b.grid(row = 12, column = 11)
mainloop()

rawDescription: Python Tkinter Grid Checkbox

description: Python Tkinter Grid Checkbox


code:
import random

class Fight(object):
  def enter(self):
    print "\n", "-" * 10
    print "There are two muchachos:"
    print "MUCHACHO1"
    print "MUCHACHO2"
    print "One of them looks wounded or something."

    your_hit_points = 20
    muchacho1_hit_points = 6
    muchacho2_hit_points = 11
    muchacho1 = True
    muchacho2 = True

    while your_hit_points > 0 and (muchacho1 or muchacho2):
      print "\n", "-" * 10
      your_attack = random.randint(4,12)
      muchacho1_attack = random.randint(1,4)
      muchacho2_attack = random.randint(4,8)

      attack = int(raw_input("Type 1 to attack MUCHACHO1, 2 to attack MUCHACHO2 >"))
      if attack == 1:
        if muchacho1:
          muchacho1_hit_points = muchacho1_hit_points - your_attack
          print "You hit MUCHACHO1 for %d hit points." % your_attack
          if muchacho1_hit_points <= 0:
            muchacho1 = False
            print "MUCHACHO1 killed!"
        else:
          print "MUCHACHO 1 is already dead!"
      elif attack == 2:
        if muchacho2:
          muchacho2_hit_points = muchacho2_hit_points - your_attack
          print "You hit MUCHACHO2 for %d hit points." % your_attack
          if muchacho2_hit_points <= 0:
            muchacho2 = False
            print "MUCHACHO2 killed!"
        else:
          print "MUCHACHO 2 is already dead!"
      else:
        print "DOES NOT COMPUTE"

      if muchacho1:
        your_hit_points = your_hit_points - muchacho1_attack
        print ("MUCHACHO1 hits you for %d points, you have %d"
           " hit points left." %(muchacho1_attack, your_hit_points))
        if your_hit_points <= 0:
          print 'You are dead'
          break
      if muchacho2:
        your_hit_points = your_hit_points - muchacho2_attack
        print ("MUCHACHO2 hits you for %d points, you have %d"
            " hit points left." % (muchacho2_attack, your_hit_points))
        if your_hit_points <= 0:
          print 'You are dead'

a_fight = Fight()
a_fight.enter()

rawDescription: Creating fighting system in very simple Python game


code:
import wx

class PanelX(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.x = 3

class PanelY(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.y = 4

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Main Frame", size = (500,450))

        p = wx.Panel(self)
        nb = wx.Notebook(p)

        nb.AddPage(PanelX(nb), "Panel X")
        nb.AddPage(PanelY(nb), "Panel Y")

        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND)
        p.SetSizer(sizer)

        page = nb.GetPage(0)
        print "PanelX's X value is %s" % page.x

        page = nb.GetPage(1)
        print "PanelY's Y value is %s" % page.y

if __name__ == "__main__":
    app = wx.App()
    MainFrame().Show()
    app.MainLoop()

rawDescription: how do I get variables from one wx notebook page to a different wx notebook page?

description: Get variables from one wx notebook page to a different wx notebook page


code:
class Pop(object):
    def __init__(self):
        self.boobs = 16
        self.sent = "pop"
    def together(self):
        print "%s : %i" % (self.sent, self.boobs)

pop = Pop()

pop.together()

rawDescription: Class/self problem

description: Class/self problem


code:
import socket, threading

def handler(s):
    data = "none"
    while len(data):
        data = s.recv(4096)
        print "Data: %s"%(data)
    s.close()

if __name__ == "__main__":
    tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # here you set socket options, this is what you need
    tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # than you bind the socket
    tcpsocket.bind(('', 1234))
    tcpsocket.listen(5)
    while True:
        s, (ip, port) = tcpsocket.accept()
        threading.Thread(target = handler, args = (s,)).start()

rawDescription: Python: Client-Server Communication - How to receive messages from different clients on the same server port simultaneously?


code:
import sys
import re

def colorize(text):
    # Underline <email addresses>:
    text = re.sub('<.*>',lambda m: '\x1b[4m{}\x1b[0m'.format(m.group()), text)
    # Make [IP addresses] peach:
    return re.sub('\[[0-9.]*\]',lambda m: '\x1b[38;5;180m{}\x1b[0m'.format(m.group()), text)

class MyStdout(object):
    def __init__(self, term=sys.stdout):
        self.term = term
    def write(self, text):
        text = colorize(text)
        self.term.write(text)

sys.stdout = MyStdout()
print 'this is an email: <someone@whatever.com>'
print 'this is an ip: [1.1.1.1]'

rawDescription: python: coloring regex matches

description: Python: coloring regex matches


code:
import numpy
a = numpy.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
print a[1, 2]
point = (1, 2)
print a[point]

rawDescription: Python 2D Array access with Points (x,y)


code:
import pandas as pd
for line in open("whitespace.csv"):
    print repr(line)

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")
pd.read_csv("whitespace.csv", header=None, delim_whitespace=True)

rawDescription: How to make separator in read_csv more flexible wrt whitespace?

description: Make separator in read_csv more flexible wrt whitespace


code:
import tweepy

auth = tweepy.OAuthHandler(consumer_key='AAA', consumer_secret='BBB')
auth.set_access_token('CCC', 'DDD')
api = tweepy.API(auth_handler=auth, secure=True, retry_count=5)

mentions = api.mentions_timeline()
for mention in mentions:
    print mention.id, mention.author.screen_name, mention.text

rawDescription: How to filter Stream by mentions

description: Filter Stream by mentions


code:
def freqCount(y_list):
        x =array(y_list)
        y = bincount(x)
        ii = nonzero(y)[0]
        freq = zip(ii,y[ii])
        f = open(fn_freq,'w')
        f.write('Distribution:\n')
        print
        print "Distribution:"
        freq_dict={}
        for ff in freq:
            temp = "%s %s\n" % (ff[0],ff[1])
            f.write(temp)
            print ff[0],ff[1]
            freq_dict[ff[0]]=ff[1]
        f.close()
        return freq_dict

rawDescription: Python: NLTK Probability of List of words


code:
def mean_score(table):
    for i, reviewer in enumerate(table):
        score = float(sum(reviewer))/len(reviewer)
        print 'Reviewer %i average rating: %.2f' %(i,score)
return

rawDescription: Average of Rows in 2D List/Array

description: Average of Rows in 2D List/Array


code:
import networkx as nx
from itertools import tee, izip

list1 = ['a','b','c']
list2 = ['c','d','e']
list3 = ['b','c','d']

g = nx.DiGraph()
for items in [list1, list2, list3]:
    a, b = tee(items)
    next(b)
    g.add_edges_from(izip(a, b))

print nx.topological_sort(g)
# ['a', 'b', 'c', 'd', 'e']

rawDescription: finding sequences from small length sequences

description: Finding sequences from small length sequences


code:
import random
import itertools

def arrivalGenerator(rate):
    t = 0
    while True:
        t += random.expovariate(rate)
        yield t

rates = [10, 1, 15, 4, 2]
t = [(i, 0) for i in range(0, len(rates))]
arrivals = []
for i in range(len(rates)):
    t = 0
    generator = arrivalGenerator(rates[i])
    arrivals += [(i, arrival) \
                 for arrival in itertools.takewhile(lambda t: t < 100, generator)]

sorted_arrivals = sorted(arrivals, key=lambda x: x[1])
for arrival in sorted_arrivals:
    print arrival[0], arrival[1]

rawDescription: Simulating multiple Poisson processes

description: Simulating multiple Poisson processes


code:
import inspect, dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe()
    f = f.f_back.f_back
    c = f.f_code
    i = f.f_lasti
    bytecode = c.co_code
    instruction = ord(bytecode[i + 3])
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = ord(bytecode[i + 4])
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def f(n):
    howmany = expecting()
    a = n * n
    b = a + 1
    if howmany == 1:
        return b
    else:
        return b, a

a = f(1)
print a # this prints 2

a, b = f(1)
print a # this prints 2
print b # this prints 1

rawDescription: Allow user to read only first variable of the return of function in python


code:
strings = ["and","the","woah"]
#Get a null set to be filled in
new = ["" for x in range(max([len(m) for m in strings]))]
#Cycle through new list
for index,item in enumerate(new):
    for w in strings:
        try:
            item += w[index]
            new[index] = item
        except IndexError,err:
            pass
print new

rawDescription: Python string extraction from array of strings


code:
import multiprocessing, time, psycopg2

class Consumer(multiprocessing.Process):

    def __init__(self, task_queue, result_queue):
        multiprocessing.Process.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue
        self.pyConn = psycopg2.connect("dbname='geobase_1' host = 'localhost'")
        self.pyConn.set_isolation_level(0)

    def run(self):
        proc_name = self.name
        while True:
            next_task = self.task_queue.get()
            if next_task is None:
                print 'Tasks Complete'
                self.task_queue.task_done()
                break
            answer = next_task(connection=self.pyConn)
            self.task_queue.task_done()
            self.result_queue.put(answer)
        return

class Task(object):
    def __init__(self, a):
        self.a = a

    def __call__(self, connection=None):
        pyConn = connection
        pyCursor1 = pyConn.cursor()

        procQuery = 'UPDATE city SET gid_fkey = gid FROM country  WHERE ST_within((SELECT the_geom FROM city WHERE city_id = %s), country.the_geom) AND city_id = %s' % (self.a, self.a)

        pyCursor1.execute(procQuery)
        print 'What is self?'
        print self.a

        return self.a

    def __str__(self):
        return 'ARC'
    def run(self):
        print 'IN'

rawDescription: Create DB connection and maintain on multiple processes (multiprocessing)


code:
def collect_names( node ):
    names = []
    while True:
        names.append(node[u'Name'])
        try:
            # deeper node
            node = node[u'Ancestors'][u'BrowseNode']
        except KeyError:
            # we are done, no ancestors
            return names[::-1]

print collect_names(data[u'BrowseNode'])
# >> [u'Books', u'Subjects', u'Science', u'Physics', u'Electromagnetism']

rawDescription: Parsing dictionaries within dictionaries


code:
from operator import itemgetter
from itertools import groupby

key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)

for gender, people in iter:
    print '===', gender, '==='
    for person in people:
        print person

rawDescription: What's the idiomatic Python equivalent to Django's 'regroup' template tag?


code:
while done:
     quit = str(raw_input ("Do you want to quit? "))
     if quit == 'y' :
         done=False
     else:
         attack = str(raw_input("Does your elf attack the dragon? "))
         if attack=='y':
             print "Bad choice, you died."
             done=False

rawDescription: What's wrong with this simple while loop ? (python)


code:
def add_new_car(brand, horse_power, car_list):
    for x in car_list:
        if x[0] == brand:
            x[1] += 1
            break
    else:
        # run if not break
        #car_list += [[brand, 1, False, horse_power]]
        car_list.append([brand, 1, False, horse_power]) #  Adam Smith suggestion

car_list = [
    ['BMW',4,False,200],
    ['Mercedes',3,False,250],
    ['Renault',2,False,150],
    ['Audi',3,False,180]
]

print car_list

add_new_car('Mercedes', 123, car_list)

print car_list

rawDescription: String lists / Python

description: String lists / Python


code:
import pickle

class Foo(object):
    pass

foo = Foo()
bar = Foo()
bar.foo_ref = foo

f = open('tmp.pkl', 'wb')
p = pickle.Pickler(f)
p.dump(foo)
p.dump(bar)
f.close()

f = open('tmp.pkl', 'rb')
up = pickle.Unpickler(f)
foo2 = up.load()
bar2 = up.load()

print id(foo) == id(bar.foo_ref) # True
print id(foo2) == id(bar2.foo_ref) # True

rawDescription: Pickle linked objects

description: Pickle linked objects


code:
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler

# Subclass HTTPServer with some additional callbacks
class CallbackHTTPServer(HTTPServer):

    def server_activate(self):
        self.RequestHandlerClass.pre_start()
        HTTPServer.server_activate(self)
        self.RequestHandlerClass.post_start()

    def server_close(self):
        self.RequestHandlerClass.pre_stop()
        HTTPServer.server_close(self)
        self.RequestHandlerClass.post_stop()

# HTTP request handler
class HttpHandler(BaseHTTPRequestHandler):

    @classmethod
    def pre_start(cls):
        print 'Before calling socket.listen()'

    @classmethod
    def post_start(cls):
        print 'After calling socket.listen()'

    @classmethod
    def pre_stop(cls):
        print 'Before calling socket.close()'

    @classmethod
    def post_stop(cls):
        print 'After calling socket.close()'

    def do_POST(self):
        print "I have just received an HTTP POST request"

def main():

    # Create server
    try:
        print "Creating server"
        server = CallbackHTTPServer(('', 8000), HttpHandler)
    except KeyboardInterrupt:
        print "Server creation aborted"
        return

    # Start serving
    try:
        print "Calling serve_forever()"
        server.serve_forever()
    except KeyboardInterrupt:
        print "Calling server.server_close()"
        server.server_close()

if __name__ == '__main__':
    main()

rawDescription: Python BaseHTTPServer.HTTPServer - callback for start and stop event


rawDescription: python csv reader scientific notations

description: Python csv reader scientific notations


code:
import matplotlib.pyplot as plt

figure = plt.figure()
# plotting
plt.plot([1,2,3],[10,20,30],'bo-')
plt.grid()
plt.legend()

def on_press(event):
    print 'you pressed', event.button, event.xdata, event.ydata
    event.canvas.figure.clear()
    # select new curves to plot, in this example [1,2,3] [0,0,0]
    event.canvas.figure.gca().plot([1,2,3],[0,0,0], 'ro-')
    event.canvas.figure.gca().grid()
    event.canvas.figure.gca().legend()
    event.canvas.draw()

figure.canvas.mpl_connect('button_press_event', on_press)

rawDescription: Change dynamically the contents of a matplotlib plot


code:
html_contents = ['
Name	id
' , '
Smith	1001
']
html_body = """\

%s

""" % ("".join(html_contents))
print html_body

rawDescription: how to build html body using list elements

description: Build html body using list elements


code:
import _mysql

db = _mysql.connect(host="localhost",user="user", passwd="pass", db="db")
db.execute('select now()')
r = db.store_result()

time_var = r[0][0]

print time_var

rawDescription: Getting server time and using it in python


code:
for i in range(0,10):
    try:
        x = my_get_fuction
    except:
        print "error"
        print i
        time.sleep(100)
        continue
    break
print x

rawDescription: how to exit try loop after code succeed?

description: Exit try loop after code succeed


code:
import scrapy

from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["lib-web.org"]
    start_urls = [
        "http://www.lib-web.org/united-states/public-libraries/michigan/"
    ]

    def __init__(self,  *args, **kwargs):
        super(DmozSpider, self).__init__(*args, **kwargs)

        self.count = 0

    def increment(self):
        self.count += 1

    def getCount(self):
        return self.count

    def parse(self, response):
        self.increment()

        for sel in response.xpath('//div/div/div/ul/li'):
            item = DmozItem()
            item['title'] = sel.xpath('a/text()').extract()
            item['link'] = sel.xpath('a/@href').extract()
            item['desc'] = sel.xpath('p/text()').extract()
            x = self.getCount()
            print x

            yield item

rawDescription: In a Scrapy bot, how do I call one function from within another?


code:
def find_condition(cond_mk, cond_ck, *args):
    """
    .. function:: find_condition(cond_mk, cond_ck) -> cond

       Create conditions by calling cond_mk until one is found that passes
       the condition check, cond_ck.  Once cond_ck returns True, iteration
       over cond_mk stops and the last value processed is returned.

       ** WARNING **
       This function could loop infinitely.

       ``cond_mk`` - callable that creates a condition.  It's return value is
       passed to cond_ck for verification.

       ``cond_ck`` - callable that checks the return value of cond_mk.

       ``args`` - any arguments to pass to cond_mk should be supplied here.
    """
    v = cond_mk(*args)
    while not cond_ck(v):
        v = cond_mk(*args)
    return v

# Test it out..
import random
random.seed()
print find_condition(random.randint, lambda x: x > 95, 1, 100)

rawDescription: Python: do r = random_stuff() while not meets_condition(r)


code:
from scrapy.selector import HtmlXPathSelector

def node_to_string(node):
    return node.xpath("string(.)").extract()[0]

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

body = """

you are foolish!I am superman!

hi girl<legend >I love you!</legend>

If I<legend > marry your mother
then I am your father!
</legend>

"""

hxs = HtmlXPathSelector(text=body)

# single target use
print node_to_string(hxs.xpath('//div[@id="novelintro"]'))
print

# multi target use
for div in hxs.xpath('//body/div'):
    print node_to_string(div)
print

# alternatively
print [node_to_string(n) for n in hxs.xpath('//body/div')]
print

rawDescription: How to use xpath to extract text in more than one label of html scripts

description: Use xpath to extract text in more than one label of html scripts


code:
from nltk.corpus import wordnet as wn

word = "dog"
synsets = wn.synsets(word)

sense2freq = {}
for s in synsets:
  freq = 0
  for lemma in s.lemmas:
    freq+=lemma.count()
  sense2freq[s.offset+"-"+s.pos] = freq

for s in sense2freq:
  print s, sense2freq[s]

rawDescription: How to get the wordnet sense frequency of a synset in NLTK?

description: Get the wordnet sense frequency of a synset in NLTK


code:
class Foo:
    def __init__(self, bla=None):
        if bla is None:
            bla = {}
        self.task_defs = bla
    def __str__(self):
        return ''.join(str(self.task_defs))

a = Foo()
b = Foo()
a.task_defs['BAR'] = 1
print 'B is ==> %s' % str(b)
print 'A is ==> %s' % str(a)

rawDescription: Weird Problem with Classes and Optional Arguments


code:
s1 = 'This is where lies a person'
s2 = 'ボウリング・フォー・コロンバイン(字幕版)'
s3 = 'Ep. 2448 : épisode du 12 mars 2014 (Plus belle la vie, Saison 10, Vol. 6)'

import guess_language
print guess_language.guessLanguage(s1)
print guess_language.guessLanguage(s2)
print guess_language.guessLanguage(s3)
en
ja
fr

rawDescription: Python way to detect language ISO code

description: Python way to detect language ISO code


code:
prNum, login, firstFileFound, label = None,None,None,None
multiLineFlag = False
list1 = ["jsfile","csfile"]
inputFile = '' # Provide your input filename here
outputFile = '' # Provide your output filename here
labelFound = False
with open(outputFile, 'w') as w:
    w.write("PR Number, Login, First File Found, Suggested Label\n")
    for line in open(inputFile):
        line = line.strip()
        if multiLineFlag and not(firstFileFound):
            if line.startswith('file_label') and any(fileType in line for  fileType in list1):
                firstFileFound = prevLine
                multiLineFlag = False
            else:
                prevLine = line

        if not multiLineFlag:
            if line.startswith('PR Number:'):
                prNum = line[len('PR Number: '):]
            elif line.startswith('Login:'):
                login = line[len('Login: '):]
            elif line.startswith('Suggested Label:'):
                labelFound = True
                label = line[len('Suggested Label: '):]
                print "label is %s "%label

            elif line.startswith('Files:'):
                multiLineFlag = True

        if all([prNum, login, firstFileFound, labelFound]):
            w.write("%s,%s,%s,%s\n" %(prNum, login, firstFileFound, label))
            prNum, login, firstFileFound, label = None,None,None,None
            labelFound=False

rawDescription: Python: Append first match of filename to a row in csv file


code:
for dict1_key, dict1_values in dict1.iteritems():
    for dict1_value in dict1_values:
        try:
            dict2_value = dict2[dict1_value]
            print str(dict1_key) + '\t' + str(dict1_value) + '\t' + str(dict2_value)
        except KeyError:
            pass

rawDescription: Comparing keys of one dictionary to another dictionary with a list of values


code:
from Tkinter import *
from functools import partial

class ButtonsTest:
    def __init__(self):
        self.top = Tk()
        self.top.title('Buttons Test')
        self.top_frame = Frame(self.top, width =400, height=400)
        self.colors = ("red", "green", "blue", "yellow")
        self.colors_selected = []
        self.num_clicks = 0
        self.wait_for_number = 5
        self.buttons()
        self.top_frame.grid(row=0, column=1)

        Button(self.top_frame, text='Exit',
         command=self.top.quit).grid(row=2,column=1, columnspan=5)

        self.top.mainloop()

    ##-------------------------------------------------------------------
    def buttons(self):
        for but_num in range(4):
            b = Button(self.top_frame, text = str(but_num+1),
                  command=partial(self.cb_handler, but_num))
            b.grid(row=1, column=but_num+1)

    ##----------------------------------------------------------------
    def cb_handler( self, cb_number ):
        print "\ncb_handler", cb_number
        self.num_clicks += 1
        this_color = self.colors[cb_number]
        if (self.num_clicks > self.wait_for_number) \
             and (this_color in self.colors_selected):
            print "%s already selected" % (this_color)
        self.colors_selected.append(this_color)

##===================================================================
BT=ButtonsTest()

rawDescription: How do I wait for a certain number of buttons to be clicked in Tkinter/Python?

description: Wait for a certain number of buttons to be clicked in Tkinter/Python


code:
import re

s = "Jul 15 12:12:51 whitelist logger: 1|999999999999|id:d9faff7c-4016-4343-b494-37028763bb66 submit date:1307130919 done date:1307130919 stat:DELIVRD err:0|L_VB3_NM_K_P|1373687445|vivnel2|L_VB3_GH_K_P|promo_camp1-bd153424349bc647|1"

logger_re = re.compile(
"logger: ([^ ]+)\
 submit date:(\d+)\
 done date:(\d+)\
 stat:(.+)\
 err:(.+)$")

print logger_re.search(s).groups()

rawDescription: split string to be inserted into database

description: Split string to be inserted into database


code:
while True:
    user_input = requestInteger("Enter a number between 0 and 9...")

    if not 0 <= user_input <= 9:
        printNow("Error! Input must be between 0 and 9. Please re-enter.")
    else:
        print "Thanks, you've entered: ", user_input
        break

rawDescription: while loop not functioning correctly

description: While loop not functioning correctly


code:
def vc_changed(stack, gparamstring):
    print "visible child changed"

my_stack.connect("notify::visible-child", vc_changed)

rawDescription: How to detect the change of a GtkStack or GtkStackSwitcher

description: Detect the change of a GtkStack or GtkStackSwitcher


code:
import struct

data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
myint = struct.unpack("!i", data)[0]

rawDescription: Handling output of python socket recv

description: Handling output of python socket recv


rawDescription: Code shows results when run interactively, but not when run from a shell


code:
class str_usr(str):
    def dup(self):
        return self + self # or 2 * self

s = str_usr("hi")
print s # prints hi
print s.dup() # print hihi

rawDescription: How to access string value from new class that inherit string type

description: Access string value from new class that inherit string type


code:
import os

import win32file
import win32event
import win
import glob
import win32com.client
import time
from pywinauto.findwindows    import find_window
from pywinauto.win32functions import SetForegroundWindow

def print_photo(filename):
    print filename
    filename = path_to_watch +"\\" + filename[0]
    os.startfile(filename, "print")
    shell = win32com.client.Dispatch("WScript.Shell")
    time.sleep(2)
    SetForegroundWindow(find_window(title='Print Pictures'))
    shell.AppActivate("Print Pictures")
    shell.SendKeys("{ENTER}")

path_to_watch = os.path.abspath ("C:\\Users\\Ciaran\\Desktop\\")

change_handle = win32file.FindFirstChangeNotification (
  path_to_watch,
  0,
  win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)

try:

  old_path_contents = dict ([(f, None) for f in os.listdir     (path_to_watch)])
  while 1:
    result = win32event.WaitForSingleObject (change_handle, 500)

    if result == win32con.WAIT_OBJECT_0:
      new_path_contents = dict ([(f, None) for f in os.listdir     (path_to_watch)])
      added = [f for f in new_path_contents if not f in     old_path_contents]
      print_photo(added)
      deleted = [f for f in old_path_contents if not f in new_path_contents]
      if added: print "Added: ", ", ".join (added)
      if deleted: print "Deleted: ", ", ".join (deleted)

      old_path_contents = new_path_contents
      win32file.FindNextChangeNotification (change_handle)

finally:
  win32file.FindCloseChangeNotification (change_handle)

rawDescription: Monitoring a folder and printing - alternative methods not using an "endless" while loop?


code:
import os

def bounded_lines(filepath, start=None, stop=None,
                  preprocess = lambda l: l[:-1]):
    """
    Generator that returns lines from a given file.
    If start is specifed, emits no lines until the
    start line is seen. If stop is specified, stops
    emitting lines after the stop line is seen.
    (The start and stop lines are themselves emitted.)
    Each line can be pre-processed before comparison
    or yielding. By default, this is just to strip the
    final character (the newline or \n) off. But you
    can specify arbitrary transformations, such as
    stripping spaces off the string, folding its case,
    or just whatever.
    """
    preprocess = lambda x: x if preprocess is None else preprocess
    filepath = os.path.expanduser(filepath)
    with open(filepath) as f:
        # find start indicator, yield it
        for rawline in f:
            line = preprocess(rawline)
            if line == start:
                yield line
                break
        # yield lines until stop indicator found, yield
        # it and stop
        for rawline in f:
            line = preprocess(rawline)
            yield line
            if line == stop:
                raise StopIteration

for l in bounded_lines('test.txt', 'DOCHELLO', 'SIRFORHE'):
    print l

rawDescription: Delete lines from text file - python

description: Delete lines from text file - python


code:
from System import *
from System.Collections.Generic import *
names = List[str]()

def get_names():
  names = List[str]()
  names.Add("Sam")
  names.Add("Carla")
  names.Add("Woody")
  names.Add("Rebecca")
  names.Add("Cliff")
  names.Add("Norm")
  return names

for name in get_names():
  print name

rawDescription: Ironpython: IEnumerator

description: Ironpython: IEnumerator


code:
@ndb.tasklet
def callback(msg):
  acct = yield ndb.get_async(msg.author)
  raise tasklet.Return('On %s, %s wrote:\n%s' % (msg.when, acct.nick(), msg.body))

qry = Messages.query().order(-Message.when)
outputs = qry.map(callback, limit=20)
for output in outputs:
  print output

rawDescription: parallel code execution python2.7 ndb

description: Parallel code execution python2.7 ndb


code:
counter = 1
while counter <= 100:
    if counter % 2 == 0:
        print counter
    counter += 1

rawDescription: Make this script work

description: Make this script work


code:
def my_print(obj):
    if hasattr(obj, '__len__') and len(obj) > 100:
        print '... omitted object of %s with length %d ...' % (type(obj), len(obj))
    else: print obj

rawDescription: How can I stop IDLE from printing giant lists?

description: Stop IDLE from printing giant lists


code:
def get_repeated_values(sessions):
    known = set()
    already_repeated = set()
    for lst in sessions.itervalues():
        session_set = set(tuple(x) for x in lst)
        repeated = (known & session_set) - already_repeated
        already_repeated |= repeated
        known |= session_set
        for val in repeated:
            yield val

sessions = {1:[[100,0],[22,1],[23,2]],10:[[100,0],[232,0],[10,2],[11,2]],22:[[5,2],[23,2]]}
for x in get_repeated_values(sessions):
    print x

rawDescription: Compare Dictionary Values for each key in the same Dictionary in Python


code:
for curdir, dirs, files in os.walk('/home/n00b'):
     print 'searching', files
     if 'program1.py' in files:
          print 'found'
          break

rawDescription: Can't find file with os.walk()

description: Can't find file with os.walk()


code:
mylist = [3,5,7,8,4,6,3,8,7]
for index in range(len(mylist)):
    print 'number '+str(mylist[index])+' has index '+str(index)

rawDescription: trying to get an index of an item in a list

description: Trying to get an index of an item in a list


code:
best_friend_alias = sa.orm.aliased(User)
query = (Query([User, sa.func.count(friendship)-1])
         .join(friendship, User.id==friendship.c.m1_id)
         .join((best_friend_alias, User.best_friend))
         .group_by(User)
         .order_by(best_friend_alias.name))
print query

rawDescription: Ordering by relationship name in sqlalchemy


rawDescription: How do I check to see if a mouse click is within a circle in pygame?

description: Check to see if a mouse click is within a circle in pygame


code:
from itertools import izip_longest, chain

minver = (1, 1, 3)
maxver = (1, 3, 19)

def version_range(start, end):
    start, end = zip(*izip_longest(start, end, fillvalue=0))
    base = max(max(chain(start, end)), 9) + 1
    def _toint(seq, base):
        return sum(base ** n * val for n, val in enumerate(reversed(seq)))
    def _totuple(num, base, length):
        ret = []
        for n in (base ** i for i in reversed(range(length))):
            res, num = divmod(num, n)
            ret.append(res)
        return tuple(ret)
    for se in xrange(_toint(start, base), _toint(end, base) + 1):
        print _totuple(se, base, len(start))

version_range(minver, maxver)

rawDescription: Range between two tuples of integers?

description: Range between two tuples of integers


code:
def tracefunc(frame, event, arg, indent=[0]):
      if event == "call":
          indent[0] += 2
          print "-" * indent[0] + "> call function", frame.f_code.co_name
      elif event == "return":
          print "<" + "-" * indent[0], "exit function", frame.f_code.co_name
          indent[0] -= 2
      return tracefunc

import sys
sys.settrace(tracefunc)

main()   # or whatever kicks off your script

rawDescription: How do I print functions as they are called

description: Print functions as they are called


code:
class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

import string
c = 'A'
for case in switch(c):
    if case(*string.lowercase): # note the * for unpacking as arguments
        print "c is lowercase!"
        break
    if case(*string.uppercase):
        print "c is uppercase!"
        break
    if case('!', '?', '.'): # normal argument passing style also applies
        print "c is a sentence terminator!"
        break
    if case(): # default
        print "I dunno what c was!"

rawDescription: Emulate a full-featured switch in Python


rawDescription: Python: Find closest match of multiple words in text file


code:
r = FH(file('classfhtry.csv', 'r'))
for line in r:
    print line

rawDescription: How do I see the results of my class on a file?

description: See the results of my class on a file


code:
class_list = []
class CollectSubclasses(type):
    def __new__(cls, name, bases, attrs):
        abstract = False
        if attrs.get('abstract', False):
            abstract = True
            del attrs['abstract']
        res = super(CollectSubclasses, cls).__new__(cls, name, bases, attrs)
        if not abstract:
            class_list.append(res)
        return res

class BaseFoo(object):
    __metaclass__ = CollectSubclasses
    abstract = True

class Concrete1(BaseFoo):
    pass

class Abstract(BaseFoo):
    abstract = True

class Concrete2(Abstract):
    pass

print class_list

rawDescription: How do I create a class in Python that behaves like Django's abstract base class?

description: Create a class in Python that behaves like Django's abstract base class


code:
try:
    import MySQLdb.converters
except ImportError:
    _connarg('conv')

def connect(host='abc.dev.local', user='abc', passwd='def', db='myabc', port=3306):

    try:
        orig_conv = MySQLdb.converters.conversions
        conv_iter = iter(orig_conv)
        convert = dict(zip(conv_iter, [str,] * len(orig_conv.keys())))
        print "Connecting host=%s user=%s db=%s port=%d" % (host, user, db, port)
        conn = MySQLdb.connect(host, user, passwd, db, port, conv=convert)
    except MySQLdb.Error, e:
        print "Error connecting %d: %s" % (e.args[0], e.args[1])
    return conn

rawDescription: mysqldb converts timestamp data to None

description: Mysqldb converts timestamp data to None


code:
mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)

rawDescription: How do I reverse a list using recursion in Python?

description: Reverse a list using recursion in Python


code:
tree = [[],[[],[[],[]]]]

def print_tree(tree, indent = ""):
    if len(tree) > 0:
        print indent + "["
        for child in tree:
            print_tree(child, indent + "    ")
        print indent + "]"
    else:
        print indent + "[]"

print_tree(tree)

rawDescription: How to "nicely" print out a tree without node information


code:
random_list = []
list_length = 20

count = 0
number = 0

while number < list_length:
    #Generate a random number and assign it to randInt
    randInt = random.randint(0,10)

    #Append the number you just generated to the list
    random_list.append(randInt)
    number += 1

def countNines(list):
    count = 0

    #If the number is 9, add to the count
    for num in list:
        if num == 9:
            count += 1

    return count

count = countNines(random_list)

print random_list
print count

rawDescription: Python how count an occurrence of a number in a random list


code:
from sympy import *
psi, x, a = symbols('psi, x, a',positive=True) #Where a is a real constant
def psi(x):
    return 1./(x**2 + a**2)
I = integrate(psi(x)**2 ,(x,-oo,oo))  #No complex conjugate
print I

rawDescription: Trouble using Sympy to integrate

description: Trouble using Sympy to integrate


code:
headers = """GET / HTTP/1.0
Host: 10.2.0.12
User-Agent: Wget/1.12 (linux-gnu)
Accept: */*
Connection: Keep-Alive"""

headers = headers.splitlines()
firstLine = headers.pop(0)
(verb, url, version) = firstLine.split()
d = {'verb' : verb, 'url' : url, 'version' : version}
for h in headers:
    h = h.split(': ')
    if len(h) < 2:
        continue
    field=h[0]
    value= h[1]
    d[field] = value

print d

print d['User-Agent']
print d['url']

rawDescription: Python regular expression for HTTP Request header


code:
s = """2, 200, 487
1, 199, 486"""
print [line.split() for line in s.splitlines()]

rawDescription: Rows of string to List set

description: Rows of string to List set


code:
import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
            # self.request is the TCP socket connected to the client
            self.data = self.request.recv(1024).strip()
            print "%s wrote:" % self.client_address[0]
            print self.data
            if '<policy-file-request/>' in self.data:
                print 'received policy'
                conn.send('<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="50007" /></cross-domain-policy>')
                conn.send('hellow wolrd')

def main():
    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

rawDescription: Flash sockets with python server

description: Flash sockets with python server


code:
matrx = [ [1,2,3], [4,5,6] ]

def LookupByTuple(tupl):
    answer = matrx
    for i in tupl:
        answer = answer[i]
    return answer

print LookupByTuple( (1,2) )

rawDescription: Use tuples/lists as array indices (Python)


code:
final_array = []

with open('new.txt') as f:
    for line in f:
        temp_list = [int(x) for x in line.strip().split()]
        if len(temp_list) > 0:  # don't append an empty list (blank line)
            final_array.append(temp_list)

print final_array

rawDescription: Python: how to form an array with comma?

description: Python: how to form an array with comma


code:
from Xlib.display import Display
from Xlib import X
from Xlib.ext import record
from Xlib.protocol import rq

disp = None

def handler(reply):
    """ This function is called when a xlib event is fired """
    data = reply.data
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(data, disp.display, None, None)

        # KEYCODE IS FOUND USERING event.detail
        print event.detail

        if event.type == X.KeyPress:
            # BUTTON PRESSED
            print "pressed"
        elif event.type == X.KeyRelease:
            # BUTTON RELEASED
            print "released"

# get current display
disp = Display()
root = disp.screen().root

# Monitor keypress and button press
ctx = disp.record_create_context(
            0,
            [record.AllClients],
            [{
                    'core_requests': (0, 0),
                    'core_replies': (0, 0),
                    'ext_requests': (0, 0, 0, 0),
                    'ext_replies': (0, 0, 0, 0),
                    'delivered_events': (0, 0),
                    'device_events': (X.KeyReleaseMask, X.ButtonReleaseMask),
                    'errors': (0, 0),
                    'client_started': False,
                    'client_died': False,
            }])
disp.record_enable_context(ctx, handler)
disp.record_free_context(ctx)

while 1:
    # Infinite wait, doesn't do anything as no events are grabbed
    event = root.display.next_event()

rawDescription: Listening for global key-combinations in python on Linux


code:
for csvFile in directory:
    root = Element('Order')
    with open(csvFile, 'rt') as f:
        junk = next(f)         #read the first line, don't do anything with it.
        reader = csv.reader(f)
        for row in reader:
            queue = row[0]
            token = row[1]
            current_order = SubElement(root, 'Token', {'text':token})
            details = SubElement(current_order, 'Queue',
                                 {'queue':queue})

    print prettify(root)

rawDescription: Stripping headers from CSV data when converting to XML in Python


code:
s = repr('''\n\t\n\t\n\t\tApple - Wikipedia, the free encyclopedia\n\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\n\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\tLanguage:English\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9Aragon\xc3\xa9sAsturianuAz\xc9\x99rbaycanca\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbeB\xc3\xa2n-l\xc3\xa2m-g\xc3\xbaBasa Banyumasan\xd0\x91\xd0\xb5\xd0\xbb\xd0\xb0\xd1\x80\xd1\x83\xd1\x81\xd0\xba\xd0''')
s =  re.sub(r'\\[tn]', '', s)
s =  re.sub(r'\\x..', '', s)
print s

rawDescription: Removing certain characters from a long string in python


code:
import numpy as np

strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']

k=len(strings)

data = np.zeros((k,k))

for i,string1 in enumerate(strings):
    for j,string2 in enumerate(strings):
        data[i][j] = 1-Levenshtein.ratio(string1, string2)

print data

rawDescription: Using reduce, map or other function to avoid for loops in python


code:
import wmi
import os
import time
import wx
import ctypes

app = wx.PySimpleApp(0)
c = wmi.WMI()

for cdrom in c.Win32_CDROMDrive():
    status = cdrom.MediaLoaded
    drive = cdrom.Drive

checkFile = os.path.join(drive,'IWPCpatch-2','install.zip')
print checkFile

testForFile = os.path.exists(checkFile)
while testForFile == False:
    print 'file present', testForFile

    for cdrom in c.Win32_CDROMDrive():
        status = cdrom.MediaLoaded
        print 'Media present', status

    #Eject
    ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None)

    #Warn
    sMessage = """ Please insert the media that contains the file """ + checkFile

    successWarning = wx.MessageBox(sMessage, "WARNING")

    #wait for new cd
    for cdrom in c.Win32_CDROMDrive():
        status = cdrom.MediaLoaded
        print 'Media present', status

    while status == False:
        for cdrom in c.Win32_CDROMDrive():
            status = cdrom.MediaLoaded
            print 'Media present', status
        time.sleep(5)

    #test and exit loop or restart
    testForFile = os.path.exists(checkFile)

print 'FILE PASSED'

rawDescription: python How to detect a new piece of media in the CD?

description: Python How to detect a new piece of media in the CD


code:
import os
print os.path.dirname(os.path.realpath(__file__))

rawDescription: How can I find script's directory with Python?

description: Find script's directory with Python


code:
import pipes
p = pipes.Template()
f = p.open('path/to/unix/opipe','r')
build_str = ''
while True:
    latest_char = f.read(1)
    if latest_char == '\n':
       break
    build_str.append(latest_char)
print build_str

rawDescription: How to read from unix named pipe in python

description: Read from unix named pipe in python


code:
with open('C:/Test/fun/output.csv', 'wb') as fou:
    writer = csv.DictWriter(fou, delimiter=",", quotechar="|", fieldnames=    ['sku', 'stock.qty', 'stock.is_in_stock'], extrasaction='ignore')
    writer.writeheader()

    for fn in os.listdir(path):
        if ".csv" in fn:
            with open(fn, 'rb') as f:
                reader = csv.DictReader(f, delimiter=",", quotechar="|")
                for row in reader:
                    print row
                    writer.writerow(row)

rawDescription: Why is DictWriter not Writing all rows in my Dictreader instance?


code:
from datetime import datetime

start_date = "2016-01-01 14:18:45"
stop_date = "2016-01-01 18:21:12"

current_datetime = datetime.now().replace(microsecond=0)
start_datetime = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
stop_datetime = datetime.strptime(stop_date, '%Y-%m-%d %H:%M:%S')

if current_datetime == start_datetime:
    print "program started"
elif start_datetime < current_datetime < stop_datetime:
    print "program half way"
else:
    print "program finished"

rawDescription: how to get past on the if statement when check for values

description: Get past on the if statement when check for values


code:
from itertools import imap

def RemDup(L):
    ListComp = {}
    for sublist in L:
        try: ListComp[sublist[0]].append(sublist[1:])
        except KeyError: ListComp[sublist[0]] = [sublist[1:]]
    return imap( list, ListComp.items() )

DupList = [['5th ave', 111, -30.00, 38.00],
['5th ave', 222, -30.00, 33.00],
['6th ave', 2224, -32.00, 34.90]]

print [ uniq for uniq in RemDup(DupList) ]

rawDescription: python list comprehension: gathering duplicate columns

description: Python list comprehension: gathering duplicate columns


code:
string = ' a      title of foo        b '
print re.search(r'\S+(?:(?!\s{2}).)+', string).group()

rawDescription: How to match anything except two or more consecutive spaces in a regex?

description: Match anything except two or more consecutive spaces in a regex


code:
import psycopg2

conn = psycopg2.connect('host=localhost4 port=5432 dbname=cpn')
cursor = conn.cursor()
cursor.execute('''
    select
        datetime::date as day,
        avg(c1) as c1_average,
        avg(c2) as c2_average
    from os_table
    where datetime between %s and %s
    group by 1
    order by 1
    ''',
    (time_cur, date_end)
);

rs = cursor.fetchall()
conn.close()

for day in rs:
    print day[0], day[1], day[2]

rawDescription: How to make an efficient query for extracting enteries of all days in a database in sets?

description: Make an efficient query for extracting enteries of all days in a database in sets


code:
import re

matcher = re.compile(u"([1-9]\d*|0)(,([1-9]\d*|0)){3}$")

print matcher.match(u"12,45")
# None
print matcher.match(u"0,1001,13,578")
# <_sre.SRE_Match object at 0x7fb0e911ca48>

rawDescription: Python Regular Expression not match

description: Python Regular Expression not match


code:
goods1 = {'coal': 1, 'boxes': 2}
Newcastle = ['Newcastle' , dict(goods1)]
Wylam = ['Wylam' , dict(goods1)]

print Newcastle
print Wylam

Newcastle[1]['coal'] = 4;
print Newcastle
print Wylam

rawDescription: Python change a value in a dictionary that is a item in a list


code:
def getRelevantFolders():
    pattern = re.compile('[edb]-(heme|gome|jome)-([^/]+)')
    for root, dirs, files in os.walk('/jome'):
        print root # f.e.: /jome/stat/d-heme-sdfsdf
        if pattern.search(root):
            print 'Matched: ' + root

rawDescription: Python - Conditional regex matching

description: Python - Conditional regex matching


rawDescription: Manipulating Dictionary Values Python

description: Manipulating Dictionary Values Python


code:
def read_data(file_name, *extras):
    # Read the data from file_name, organizing in a dict,
    # using the key names that your caller will pass into the function.
    # In this example, we have the main data that will always be
    # returned, plus optional data stored under keys a, b, c, d.
    data = dict(_main = 'MAIN', a = 'AA', b = 'BB', c = 'CC', d = 'DD')

    # Return a tuple, list, or even dict of that data.
    ks = sorted(data.keys())
    return tuple(data[k] for k in ks if k in extras or k == '_main')

# Caller requests the optional data they want.
# This example shows the caller passing a list of optional data keys.
# You could also have them pass keyword args instead.
wanted = 'a b d'.split()
print read_data('data_file', *wanted)  # ('MAIN', 'AA', 'BB', 'DD')

rawDescription: Elegant way to return different variables based on input flags


code:
from bs4 import BeautifulSoup
import json

html_doc = """
<title>The Dormouse's story</title>

2

"""

soup= BeautifulSoup(html_doc, "html.parser")
# usually `try` that but for the moment we let it raise
js = soup.find("script").get_text()
assert len(js) > 0
# here the markers for start and end  of json
from_ = "mapInitWithData("
to_ = "]}]"
index_from = js.find(from_)
assert index_from > 0
index_to = js.find(to_)
assert index_to > 0
j = js[index_from+len(from_):index_to+len(to_)]
data = json.loads(j)
for row in data:
    print row["city"], ":", [float(c) for c in row["g"]] # <g>

rawDescription: BeautifulSoup find contents inside "([{}]}"


code:
import collections
result = collections.defaultdict(int) # works like a dictionary
# but all keys have a default value of zero
for key, value in mylist:
    result[key] += value

print result

rawDescription: list manipulation in python

description: List manipulation in python


code:
f = file('sourcefile')
for line in f:
    if 'pattern' in line:
            # mind the , at the end,
            # since there's no stripping involved
            # and print adds a newline without it
            print line,

rawDescription: python system call

description: Python system call


code:
import re
strings = 'abc534loif tvd645kgjf tv96fjbd_gfgf'.split()
for s in strings:
  for match in re.finditer(r'\b([a-z]+)(\d+)(.+?)\b', s):
    print match.groups()

rawDescription: How do I extract certain parts of strings in Python?

description: Extract certain parts of strings in Python


code:
import os
import mock
with mock.patch.dict('os.environ'):
    del os.environ['PATH']
    print 'PATH' in os.environ
print 'PATH' in os.environ

rawDescription: Using python's mock to temporarily delete an object from a dict


code:
def update_hscale(event):
    global t
    fm = hscale.get_value()
    y_new = numpy.sin(2*fm*t)
    l.set_ydata(y_new)
    canvas.draw()
    print "doing fm=", fm

rawDescription: Comunication between windows with python matplotlib using gtk.WindowGroup


code:
def test(a):
    return a

def invoker(*args):
    print sum(args) # Prints 25
    print args # Prints (10, 15)

invoker(test(10), test(15))

rawDescription: Function with arguments from other function


code:
import sys
from math import log, sqrt
from itertools import combinations

def cosine_distance(a, b):
    cos = 0.0
    a_tfidf = a["tfidf"]
    for token, tfidf in b["tfidf"].iteritems():
        if token in a_tfidf:
            cos += tfidf * a_tfidf[token]
    return cos

def normalize(features):
    norm = 1.0 / sqrt(sum(i**2 for i in features.itervalues()))
    for k, v in features.iteritems():
        features[k] = v * norm
    return features

def add_tfidf_to(documents):
    tokens = {}
    for id, doc in enumerate(documents):
        tf = {}
        doc["tfidf"] = {}
        doc_tokens = doc.get("tokens", [])
        for token in doc_tokens:
            tf[token] = tf.get(token, 0) + 1
        num_tokens = len(doc_tokens)
        if num_tokens > 0:
            for token, freq in tf.iteritems():
                tokens.setdefault(token, []).append((id, float(freq) / num_tokens))

    doc_count = float(len(documents))
    for token, docs in tokens.iteritems():
        idf = log(doc_count / len(docs))
        for id, tf in docs:
            tfidf = tf * idf
            if tfidf > 0:
                documents[id]["tfidf"][token] = tfidf

    for doc in documents:
        doc["tfidf"] = normalize(doc["tfidf"])

def choose_cluster(node, cluster_lookup, edges):
    new = cluster_lookup[node]
    if node in edges:
        seen, num_seen = {}, {}
        for target, weight in edges.get(node, []):
            seen[cluster_lookup[target]] = seen.get(
                cluster_lookup[target], 0.0) + weight
        for k, v in seen.iteritems():
            num_seen.setdefault(v, []).append(k)
        new = num_seen[max(num_seen)][0]
    return new

def majorclust(graph):
    cluster_lookup = dict((node, i) for i, node in enumerate(graph.nodes))

    count = 0
    movements = set()
    finished = False
    while not finished:
        finished = True
        for node in graph.nodes:
            new = choose_cluster(node, cluster_lookup, graph.edges)
            move = (node, cluster_lookup[node], new)
            if new != cluster_lookup[node] and move not in movements:
                movements.add(move)
                cluster_lookup[node] = new
                finished = False

    clusters = {}
    for k, v in cluster_lookup.iteritems():
        clusters.setdefault(v, []).append(k)

    return clusters.values()

def get_distance_graph(documents):
    class Graph(object):
        def __init__(self):
            self.edges = {}

        def add_edge(self, n1, n2, w):
            self.edges.setdefault(n1, []).append((n2, w))
            self.edges.setdefault(n2, []).append((n1, w))

    graph = Graph()
    doc_ids = range(len(documents))
    graph.nodes = set(doc_ids)
    for a, b in combinations(doc_ids, 2):
        graph.add_edge(a, b, cosine_distance(documents[a], documents[b]))
    return graph

def get_documents():
    texts = [
        "foo blub baz",
        "foo bar baz",
        "asdf bsdf csdf",
        "foo bab blub",
        "csdf hddf kjtz",
        "123 456 890",
        "321 890 456 foo",
        "123 890 uiop",
    ]
    return [{"text": text, "tokens": text.split()}
             for i, text in enumerate(texts)]

def main(args):
    documents = get_documents()
    add_tfidf_to(documents)
    dist_graph = get_distance_graph(documents)

    for cluster in majorclust(dist_graph):
        print "========="
        for doc_id in cluster:
            print documents[doc_id]["text"]

if __name__ == '__main__':
    main(sys.argv)

rawDescription: Clustering text in Python

description: Clustering text in Python


code:
import sys, os
from PyQt import QtGui, QtCore

class Item(object):
    def __init__(self,ID=None,name=None,category=None,area=None):
        self.ID=ID
        self.name=name
        self.category=category
        self.area='South'

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self.currentItems=[]
        self.items = []
        self.filterCategory = None
        self.searchField = None

        self.mainColumn=0
        self.order=QtCore.Qt.SortOrder.DescendingOrder

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len( self.currentItems )

    def columnCount(self, parent=QtCore.QModelIndex()):
        return 5

    def data(self, index, role):
        if not index.isValid(): return
        row=index.row()
        column=index.column()

        item=self.currentItems[row]

        if role == QtCore.Qt.DisplayRole:
            if column==0: return item.ID
            elif column==1: return item.name
            elif column==2: return item.category
            elif column==4 or column==5: return item.area

        if role == QtCore.Qt.UserRole:
            return item

    def insertRows(self, row, item, column=1, index=QtCore.QModelIndex()):
        self.beginInsertRows(QtCore.QModelIndex(), row, row+1)
        self.items.append(item)
        self.endInsertRows()

    def setFilter(self, comboText=None, searchText=None, mainColumn=None, order=None):
        if comboText: self.filterCategory=comboText
        if searchText: self.searchText=searchText
        if mainColumn!=None: self.mainColumn=mainColumn
        self.order=order

        self.currentItems=[item for item in self.items if item.category==self.filterCategory]
        if searchText:
            self.currentItems=[item for item in self.currentItems if searchText in '%s%s%s'%(item.ID, item.name, item.category)]

        values=[]
        if self.mainColumn==0: values=[[item.ID, item, False] for item in self.currentItems]
        elif self.mainColumn==1: values=[[item.name, item, False] for item in self.currentItems]
        elif self.mainColumn==2: values=[[item.category, item, False] for item in self.currentItems]
        elif self.mainColumn==3 or self.mainColumn==4: values=[[item.area, item, False] for item in self.currentItems]

        keys=sorted([value[0] for value in values if isinstance(value, list)])
        if self.order==QtCore.Qt.AscendingOrder: keys=list(reversed(keys))

        filtered=[]
        for key in keys:
            for each in values:
                if each[0]!=key: continue
                if each[2]==True: continue
                item=each[1]

                filtered.append(item)
                each[2]=True

        if filtered: self.currentItems=filtered

        self.layoutChanged.emit()

class ItemDelegate(QtGui.QItemDelegate):
    def __init__(self, parent):
        QtGui.QItemDelegate.__init__(self, parent)

    def flags(self, index):
        if (index.column() == 1):
            return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled
        else:
            return QtCore.Qt.ItemIsEnabled

    def createEditor(self, parent, option, index):
        tableView=parent.parent()
        model=tableView.model()

        item=model.data(index, QtCore.Qt.UserRole)

        combo=QtGui.QComboBox(parent)
        combo.addItems(['South','West','North','East'])
        combo.currentIndexChanged.connect(self.comboIndexChanged)

        if item.area:
            comboIndex=combo.findText(item.area)
            if comboIndex>=0:
                combo.setCurrentIndex(comboIndex)
        else: combo.setCurrentIndex(0)

        return combo

    def comboIndexChanged(self):
        self.commitData.emit(self.sender())

    def setModelData(self, combo, model, index):
        item=model.data(index, QtCore.Qt.UserRole)
        comboText=combo.currentText()
        item.area=comboText

class MyWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        vLayout=QtGui.QVBoxLayout(self)
        self.setLayout(vLayout)

        self.tableModel = TableModel()

        self.searchLine=QtGui.QLineEdit()
        vLayout.addWidget(self.searchLine)

        self.searchLine.textEdited.connect(self.searchLineEditied)
        self.searchLine.returnPressed.connect(self.searchLineEditied)

        self.tableView=QtGui.QTableView(self)
        self.tableView.setSortingEnabled(True)
        self.tableView.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.tableView.setShowGrid(False)
        self.tableView.setSelectionBehavior(QtGui.QTableView.SelectRows)
        self.tableView.setAlternatingRowColors(True)

        self.delegate=ItemDelegate(self.tableView)
        self.tableView.setItemDelegate(self.delegate)

        self.tableView.clicked.connect(self.viewClicked)
        vLayout.addWidget(self.tableView)

        for row in range(15):
            if row%2:  category='Pet'
            else: category='Birds'
            item=Item(category=category, ID=row, name='%s_%s'%(category,row))
            self.tableModel.insertRows(row, item)

        self.tableView.setModel(self.tableModel)

        self.combo=QtGui.QComboBox()
        self.combo.addItems(['Pet','Birds'])
        self.combo.activated.connect(self.comboActivated)
        vLayout.addWidget(self.combo)

        currentComboCategory=self.combo.currentText()
        self.tableModel.setFilter(currentComboCategory)

        self.horizontalHeader=self.tableView.horizontalHeader()
        self.horizontalHeader.sortIndicatorChanged.connect(self.headerTriggered)
        self.addComboDelegates()

    def headerTriggered(self, mainColumn=None, order=None):
        self.tableModel.setFilter(mainColumn=mainColumn, order=order)
        self.deleteComboDelegates()
        self.addComboDelegates()

    def comboActivated(self, comboIndex=None):
        self.deleteComboDelegates()
        comboText=self.combo.currentText()
        self.tableModel.setFilter(comboText=comboText)
        self.addComboDelegates()
        self.tableModel.layoutChanged.emit()

    def searchLineEditied(self, searchText=None):
        self.tableModel.setFilter(searchText=searchText)

    def viewClicked(self, indexClicked):
        item=self.tableModel.data(indexClicked, QtCore.Qt.UserRole)
        print 'ID: %s, name: %s, category: %s'%(item.ID,item.name,item.category)

    def deleteComboDelegates(self):
        for row in range(self.tableModel.rowCount()):
            index=self.tableModel.index(row, 3, QtCore.QModelIndex())
            self.tableView.closePersistentEditor(index)

    def addComboDelegates(self):
        for row in range(self.tableModel.rowCount()):
            index=self.tableModel.index(row, 3, QtCore.QModelIndex())
            self.tableView.openPersistentEditor(index)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

rawDescription: How to sort and filter using QAbstractTableModel instead of QSortFilterProxyModel

description: Sort and filter using QAbstractTableModel instead of QSortFilterProxyModel


code:
data = open("data.txt", "r")

last_time = 0.0
last_ip = None
last_hash = None

for line in data:
        timestamp, ip, hash_value = line.split()
        if ip==last_ip and hash_value==last_hash and float(timestamp) - float(last_time) < 5.0:
                print "Remove ", line
        else:
                print "Keep ", line
        last_time, last_ip, last_hash = timestamp, ip, hash_value

rawDescription: compare values in a file python

description: Compare values in a file python


code:
import time
import threading
from threading import Thread
import Queue

q = Queue.Queue()

def func1():
    while True:
        try:
            item = q.get(True, 1)
            if item == 'quit':
                print 'quitting'
                break
        except:
            pass
        print 'working 1'

def func2():
    time.sleep(10)
    q.put("quit")
    while True:
        time.sleep(1)
        print 'Working2'

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

rawDescription: Stop a thread Python

description: Stop a thread Python


rawDescription: most efficient way to go about identifying sub-strings in a string in python?

description: Most efficient way to go about identifying sub-strings in a string in python


code:
url = 'http://bioinformatics.clemson.edu/G-SESAME/Program/GOCompareTwo2.php'
GOterms = {'GOTerm1':'0005777','GOTerm2':'0005739', 'submit':'Submit'}
r = requests.post(url, data=GOterms)
print r.text

rawDescription: Python Requests POST to PHP

description: Python Requests POST to PHP


code:
import multiprocessing, Queue

class Worker(multiprocessing.Process):
    def process(self, x):
        for i in range(15):
            x += (float(i) / 2.6)
        return x

    def __init__(self, input, output):
        self.input = input
        self.output = output
        super(Worker, self).__init__()

    def run(self):
        try:
            while True:
                self.output.put(self.process(self.input.get_nowait()))
        except Queue.Empty:
            pass

if name == 'main':
    dataset = range(10)
    processes = multiprocessing.cpu_count()
    input = multiprocessing.Queue()
    output = multiprocessing.Queue()

    for obj in dataset:
        input.put(obj)
    for i in range(processes):
        Worker(input, output).start()

    for i in range(len(dataset)):
        print output.get()

rawDescription: Dynamic processes in Python

description: Dynamic processes in Python


code:
a=open('owlcreek.txt').read().split()
lengths=dict()
for word in a:
    length = len(word)
    # if the key is not present, add it
    if not lengths.has_key(length):
        # the value should be the list of words
        lengths[length] = []
    # append the word to the list for length key
    lengths[length].append(word)

# print them out as length, count(words of that length)
for length, wrds in lengths.items():
    print "Words of length %d: %d" % (length, len(wrds))

rawDescription: counting lengths of the words in a .txt

description: Counting lengths of the words in a .txt


code:
import sys
sys.path.append("C:\Users\Username\Dropbox\Projects")
import Projects.MyUtilities.Utility1

rawDescription: Multiple user created modules from a directory not in PATH using just command window (Anaconda 3)


code:
import inspect
import sys
from types import MethodType

class MyHandler(object):

    def __init__(self):
        self.format_string = 'class format string'
        self.database = 'class database'
        self.mode = "class mode"
        self._populate_methods()

    def _populate_methods(self):
        to_add = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
        to_add = [x[0] for x in to_add if not x[0].startswith('_')]
        for func_name in to_add:
            func = getattr(sys.modules[__name__], func_name)  # strings to functions
            self._add_function_as_method(func_name, func)

    def _add_function_as_method(self, func_name, func):
        def f(self, *args, **kwargs):  #  the template for the method we'll add
            return self._pass_to_function(func, *args, **kwargs)
        setattr(MyHandler, func_name, MethodType(f, None, MyHandler))

    def _pass_to_function(self, function, *overrided_args, **overrided_kwargs):
        functon_kwargs = inspect.getargspec(function)[0][len(overrided_args):]
        handler_vars = vars(self)
        kwargs_to_pass = {}

        for arg in functon_kwargs:
            if arg in handler_vars:
                kwargs_to_pass[arg] = handler_vars[arg]
        for arg in overrided_kwargs:
            kwargs_to_pass[arg] = overrided_kwargs[arg]

        return function(*overrided_args, **kwargs_to_pass)

def rename(targets, format_string=None, database=None, mode=None,
           not_in_class='None'):
    print 'targets = {}'.format(targets)
    print 'format_string = {}'.format(format_string)
    print 'database = {}'.format(database)
    print 'mode = {}'.format(mode)
    print 'not_in_class = {}\n'.format(not_in_class)
    return

def something_else():
    print "this function should become a method"

def _not_a_member():
    print "this function should not become a method"

rawDescription: python: generating methods for a convenience class programatically

description: Python: generating methods for a convenience class programatically


code:
from twisted.internet import reactor, defer

def callback_func_2(result, previous_data):
    # here we pass the result of the deferred down the callback chain
    # (done synchronously)
    print "calling function 1 on result:%s with previous result:%s" % (result, previous_data)
    return result

def callback_func(result):
    #let's do some asynchronous stuff in this callback
    # simple trick here is to return a deferred from a callback
    # instead of the result itself.
    #
    # so we can do asynchronous stuff here,
    # like firing something 1 second later and have
    # another method processing the result
    print "calling function 1 on result:%s" % result
    d = defer.Deferred()
    reactor.callLater(1, d.callback, "second callback")
    d.addCallback(callback_func_2, result)
    return d

def do():
    d = defer.Deferred()
    reactor.callLater(1, d.callback, "first callback")
    d.addCallback(callback_func)
    return d

do()
reactor.run()

rawDescription: twisted deferred/callbacks and asynchronous execution

description: Twisted deferred/callbacks and asynchronous execution


code:
class Singleton(object):
    _instance = None
    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
            return class_._instance

class Foo(Singleton):
    def __init__(self):
        self.data = []
    pass

a = Foo()
a.data.append('Never see this')
b = Foo()
print a is b  #True
print a.data  # []

rawDescription: What is a singleton/borg pattern? Why don't they work for me/where is my concept wrong?


code:
import sys

from twisted.internet.task import deferLater
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS

CONFIG_IP = ''
CONFIG_PORT = 9000

def isOffline(status):
    print status

class StatusCheckerProtocol(WebSocketClientProtocol):

    def __init__(self):
        self.operation_name = "STATUS_SRV"
        self.user_id = 'u00000000000000'
        self.file_id = "000000000000000000000.log"

    def onOpen(self):
        data = '[' + str(self.user_id) + ':' + str(self.operation_name) + ':' + str(self.file_id) + ']'
        self.sendMessage(data, isBinary=True)

    def onMessage(self, payload, isBinary):
        cmd = payload[1:4]
        result_cmd = payload[6]
        data = payload[8:]
        print data
        reactor.stop()

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print "using python statuschecker.py [IP] [PORT]"
    else:
        # read preferences
        CONFIG_IP = sys.argv[1]
        CONFIG_PORT = int(sys.argv[2])
        server_addr = "ws://%s:%d" % (CONFIG_IP, CONFIG_PORT)
        # connection to server
        factory = WebSocketClientFactory(server_addr)
        factory.protocol = StatusCheckerProtocol
        connectWS(factory)
        # create special Deffered, which disconnect us from some server, if can't connect within 3 seconds
        d = deferLater(reactor, 3, isOffline, 'OFFLINE')
        d.addCallback(lambda ignored: reactor.stop())
        # run all system...
        reactor.run()

rawDescription: Check server status on Twisted

description: Check server status on Twisted


code:
"""Generates and submits an email as a draft.
"""

import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os

from apiclient import errors

def CreateDraft(service, user_id, message_body):
  """Create and insert a draft email. Print the returned draft's message and id.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    message_body: The body of the email message, including headers.

  Returns:
    Draft object, including draft id and message meta data.
  """
  try:
    message = {'message': message_body}
    draft = service.users().drafts().create(userId=user_id, body=message).execute()

    print 'Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])

    return draft
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

def CreateMessage(sender, to, subject, message_text):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

  Returns:
    An object containing a base64 encoded email object.
  """
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.b64encode(message.as_string())}

def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir,
                                filename):
  """Create a message for an email.

  Args:
    sender: The email address of the sender.
    to: The email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.
    file_dir: The directory containing the file to be attached.
    filename: The name of the file to be attached.

  Returns:
    An object containing a base64 encoded email object.
  """
  message = MIMEMultipart()
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject

  msg = MIMEText(message_text)
  message.attach(msg)

  path = os.path.join(file_dir, filename)
  content_type, encoding = mimetypes.guess_type(path)

  if content_type is None or encoding is not None:
    content_type = 'application/octet-stream'
  main_type, sub_type = content_type.split('/', 1)
  if main_type == 'text':
    fp = open(path, 'rb')
    msg = MIMEText(fp.read(), _subtype=sub_type)
    fp.close()
  elif main_type == 'image':
    fp = open(path, 'rb')
    msg = MIMEImage(fp.read(), _subtype=sub_type)
    fp.close()
  elif main_type == 'audio':
    fp = open(path, 'rb')
    msg = MIMEAudio(fp.read(), _subtype=sub_type)
    fp.close()
  else:
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()

  msg.add_header('Content-Disposition', 'attachment', filename=filename)
  message.attach(msg)

  return {'raw': base64.b64encode(message.as_string())}

rawDescription: Creating Gmail draft after deployment not working


code:
#!/usr/bin/env python
import imaplib
from re import findall

MAXSIZE = 1000
MINSIZE = 1

m = imaplib.IMAP4_SSL('imap.gmail.com')
m.login('example@gmail.com','testPassword')
m.select()
typ, data = m.search(None, 'ALL')
typ, data = m.search(None,'(SMALLER %d) (LARGER %d)' % (MAXSIZE * 1000,MINSIZE * 1000))
for num in data[0].split():
    typ, data = m.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, len(data[0][1]))
m.close()
m.logout()

rawDescription: How to delete the biggest emails from my gmail using a python script?

description: Delete the biggest emails from my gmail using a python script


code:
from multiprocessing import Pool
import numpy as np

class RowProcessor(object):
    def __init__(self, src):
        self.__src = src
    def __call__(self, row):
        return np.sum(self.__src[row])

def main():
    src=np.ones((100,100))
    p = RowProcessor(src)

    pool=Pool(processes=16)
    rows = pool.map(p, range(100))
    print rows

if __name__ == "__main__":
    main()

rawDescription: Alternative use patterns for python multiprocessing avoiding proliferation of global state?


code:
I = indx[0,...]*slope + indx[1,...]>=M
imArr1 = imArr.copy()
imArr1[I]=0
print np.average(indx[0,...],weights=imArr1)
print np.average(indx[1,...],weights=imArr1)

imArr1 = imArr.copy()
imArr1[~I]=0

print np.average(indx[0,...],weights=imArr1)
print np.average(indx[1,...],weights=imArr1)

rawDescription: Array slice maximum that depends on the index of the previous axis


code:
filepath = raw_input('Input file path:\n')
with open(filepath) as f:
    for line in f:
        print line.split(',')[1]

rawDescription: Python: getting info from file?

description: Python: getting info from file


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

for t in np.arange(0.,2., 0.4):
    x = np.linspace(0.,4, 100)
    y = np.sin(x-2*t) + 0.01 * np.random.normal(size=x.shape)
    yint = interp1d(x, y)
    print t
    col = (t/2.0, t/2.0, t/2.0)
    plt.plot(x, yint(x), color=col)

plt.show()

rawDescription: matplotlib: coloring line plots by iteration-dependent gray scale

description: Matplotlib: coloring line plots by iteration-dependent gray scale


code:
from json import loads

json_data = """{
    "my_test": [{
        "group_name": "group-A",
        "results": [{
            "test_name": "test1",
            "time": "8.556",
            "status": "pass"
        }, {
            "test_name": "test2",
            "time": "45.909",
            "status": "pass"
        }, {
            "test_name": "test3",
            "time": "9.383",
            "status": "fail"
        }]
    }]
}"""

data = loads(json_data)

for group in data["my_test"]:
    print group["group_name"]
    sorted_results = sorted(group["results"], key=lambda a: float(a["time"]))
    for result in sorted_results:
        print(result["test_name"] + ": " + result["time"])

rawDescription: python- reading JSON in ascending order

description: Python- reading JSON in ascending order


code:
def check(_list):
    return all(map(has_id, list))

print check(l)

False

rawDescription: How to check all item in your list

description: Check all item in your list


code:
from datetime import datetime, timedelta

def daterange(start_date, end_date):
  for n in range((end_date - start_date).days):
    yield start_date + timedelta(n)

start_date = '2011-09-01'
end_date = '2011-09-15'
format = '%Y-%m-%d'

start_date_object = datetime.strptime(start_date, format)
end_date_object = datetime.strptime(end_date, format)

for day in daterange(start_date_object, end_date_object):
  if day.weekday() in [5, 6]:
    print day.strftime(format)

rawDescription: How to get sat and sun dates from given date ranges in python

description: Get sat and sun dates from given date ranges in python


code:
my_dashes = ['_', '_', '_', '_']
print ''.join(my_dashes)
print ' '.join(my_dashes)

rawDescription: Convert list of strings to space-separated string


code:
test = ['1', '2', '3', '4']
i = 0
while i < len(test):
    print test[i]
    # Do anything with i here, e.g.
    i = i - 2
    # This is part of the loop
    i = i + 1

rawDescription: Manipulate index of for loop in Python

description: Manipulate index of for loop in Python


code:
import getopt, sys

def usage():
  print "\nThis is the usage function\n"
  print 'Usage: '+sys.argv[0]+' -i <file1> [option]'

def main(argv):
  try:
    opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
    if not opts:
      print 'No options supplied'
      usage()
  except getopt.GetoptError,e:
    print e
    usage()
    sys.exit(2)

  for opt, arg in opts:
    if opt in ('-h', '--help'):
      usage()
      sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:])

rawDescription: usage function doesn't work with getopt

description: Usage function doesn't work with getopt


code:
import urllib
data = urllib.urlencode({"mode_login":"Agree","redirect":"http://stackoverflow.com"})
result = urllib.urlopen("http://192.168.100.1:5280/",data).read()
print result

rawDescription: How to do a Post Request in Python?

description: Do a Post Request in Python


code:
from reverend.thomas import Bayes
g = Bayes()    # guesser
g.train('french','La souris est rentrÃ©e dans son trou.')
g.train('english','my tailor is rich.')
g.train('french','Je ne sais pas si je viendrai demain.')
g.train('english','I do not plan to update my website soon.')
print g.guess('Jumping out of cliffs it not a good idea.')
print g.guess('Demain il fera trÃ¨s probablement chaud.')

rawDescription: What is a relatively simple way to determine the probability that a sentence is in English?


rawDescription: can't use variable inside regex

description: Can't use variable inside regex


code:
tree=et.fromstring(xml)

for bad in tree.xpath("//fruit[@state=\'rotten\']"):
  bad.getparent().remove(bad)     # here I grab the parent of the element to call the remove directly on it

print et.tostring(tree, pretty_print=True, xml_declaration=True)

rawDescription: how to remove an element in lxml

description: Remove an element in lxml


code:
#!/usr/bin/env python2.7
import re
import json

def jsonify(config='/var/lib/alsa/asound.state'):
    g = re.MULTILINE
    p1 = re.compile(r'((?:^|"[^"]+"|\'[^\']+\'|[\s:{}])+)([^\s{}]+)', g)
    p2 = re.compile(r'^(\s*\"[\w.]+"(?!\s*[\:]))', g)
    p3 = re.compile(r'([\"\}])\n(?!\s*\})', g)

    with open(config) as fh:
        context = fh.read()
        # replace all the quote with quotes
        context = context.replace("'", '"')
        # surround the name:value objects by quotes
        context = re.sub(p1, r'\g<1>"\g<2>"', context)
        # add a trailing comma after the values assignment
        context = re.sub(p2, r'\g<1>:', context)
        # add a colon before the values as a delimiter
        context = re.sub(p3, r'\g<1>,\n', context)

    return json.loads('{\n%s\n}' % context[:-2])

if __name__ == '__main__':
    print 'you should use it as module :D'

rawDescription: alsamixer amixer to python dictionary format

description: Alsamixer amixer to python dictionary format


code:
a =  "It's time. "
b = "Alarm rings!!! "
c = "Are you ready to get up ? "
counter = 0
print a +  b +  c
answer = raw_input("Enter Yes or No:  ")
if answer =='Yes':
  print "Climb Out of Bed"
while answer == 'No' and counter < 3:
  print a + b + c
  answer = raw_input("Enter Yes or No: ")
  counter += 1

rawDescription: how to set a python while loop stop after 3 times?

description: Set a python while loop stop after 3 times


code:
#!/usr/bin/env python

import urllib
import urllib2
import cookielib
from BeautifulSoup import BeautifulSoup
from getpass import getpass

# Define URLs
google_accounts_url = 'http://accounts.google.com'
authentication_url = 'https://accounts.google.com/ServiceLoginAuth'
stack_overflow_url = 'http://stackoverflow.com/users/authenticate'
genuwine_url = 'http://stackoverflow.com/inbox/genuwine'

# Build opener
jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))

def request_url(request):
    '''
        Requests given URL.
    '''
    try:
        response = opener.open(request)
    except:
        raise
    return response

def authenticate(username='', password=''):
    '''
        Authenticates to Google Accounts using user-provided username and password,
        then authenticates to StackOverflow.
    '''
    # Build up headers
    user_agent = 'Mozilla/5.0 (Ubuntu; X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'
    headers = {'User-Agent' : user_agent}

    # Set Data to None
    data = None

    # Build up URL request with headers and data
    request = urllib2.Request(google_accounts_url, data, headers)
    response = request_url(request)

    # Build up POST data for authentication
    html = response.read()
    dsh = BeautifulSoup(html).findAll(attrs={'name' : 'dsh'})[0].get('value').encode()

    auto = response.headers.getheader('X-Auto-Login')

    follow_up = urllib.unquote(urllib.unquote(auto)).split('continue=')[-1]

    galx = jar._cookies['accounts.google.com']['/']['GALX'].value

    values = {'continue' : follow_up,
              'followup' : follow_up,
              'dsh' : dsh,
              'GALX' : galx,
              'pstMsg' : 1,
              'dnConn' : 'https://accounts.youtube.com',
              'checkConnection' : '',
              'checkedDomains' : '',
              'timeStmp' : '',
              'secTok' : '',
              'Email' : username,
              'Passwd' : password,
              'signIn' : 'Sign in',
              'PersistentCookie' : 'yes',
              'rmShown' : 1}

    data = urllib.urlencode(values)

    # Build up URL for authentication
    request = urllib2.Request(authentication_url, data, headers)
    response = request_url(request)

    # Check if logged in
    if response.url != request._Request__original:
        print '\n Logged in :)\n'
    else:
        print '\n Log in failed :(\n'

    # Build OpenID Data
    values = {'oauth_version' : '',
              'oauth_server' : '',
              'openid_username' : '',
              'openid_identifier' : 'https://www.google.com/accounts/o8/id'}

    data = urllib.urlencode(values)

    # Build up URL for OpenID authetication
    request = urllib2.Request(stack_overflow_url, data, headers)
    response = request_url(request)

    # Retrieve Genuwine
    data = None
    request = urllib2.Request(genuwine_url, data, headers)
    response = request_url(request)
    print response.read()

if __name__ == '__main__':
    username = raw_input('Enter your Gmail address: ')
    password = getpass('Enter your password: ')
    authenticate(username, password)

rawDescription: How to request pages from website that uses OpenID?

description: Request pages from website that uses OpenID


code:
class Progress(RemoteProgress):
    def line_dropped(self, line):
        print line
    def update(self, *args):
        print self._cur_line

rawDescription: GitPython pipe output to stdout

description: GitPython pipe output to stdout


code:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class Echo(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)
        self.transport.write(data, (host, port))

reactor.listenUDP(9999, Echo())
reactor.run()

rawDescription: Clear threads in python?

description: Clear threads in python


code:
import re  # re is Python's regex library
SAMPLE_TEXT = "\t\t45\t\tbsadfd\t\t839\t\tds532\t\t0\t\t"  # Test text to run the regex on

# Run the regex using re.sub (for substitute)
# re.sub takes three arguments: the regex expression,
# a function to return the substituted text,
# and the text you're running the regex on.

# The regex looks for substrings of the form:
# Two tabs ("\t\t"), followed by one to three digits 0-9 ("[0-9]{1,3}"),
# followed by two more tabs.

# The lambda function takes in a match object x,
# and returns the full text of that object (x.group(0))
# with "TEXT" prepended.
output = re.sub("\t\t[0-9]{1,3}\t\t",
                lambda x: "TEXT" + x.group(0),
                SAMPLE_TEXT)

print output  # Print the resulting string.

rawDescription: replace wildcard numbers in pattern with additional text + same numbers

description: Replace wildcard numbers in pattern with additional text + same numbers


code:
def onClick(event):
    print 'hello'

rawDescription: passing event to function outside of class in wxPython

description: Passing event to function outside of class in wxPython


code:
import pprint

results = [
['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000'],
['aaa665487', 'Completed', 'location', 'mode', '2014-xx-ddT19:00:00.000'],
['aaa661965', 'Completed', 'location', 'mode', '2014-xx-ddT18:00:00.000']
]

# Go from results -> results1
results1 = [', '.join(x) for x in results]
pprint.pprint(results1)
#  ['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000',
#   'aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000',
#   'aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']

# Go from results1 to new_Result
new_Result = [x.split(', ') for x in results1]
pprint.pprint(new_Result)
#  [['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000'],
#   ['aaa665487', 'Completed', 'location', 'mode', '2014-xx-ddT19:00:00.000'],
#   ['aaa661965', 'Completed', 'location', 'mode', '2014-xx-ddT18:00:00.000']]

print results == new_Result    # True

rawDescription: nesting a series of lists within a list - python

description: Nesting a series of lists within a list - python


code:
import random
import math

def gaussianRandom ( count):
    count += 1
    if count%2 == 0:
        while (1):
            x1 = random.uniform(-1, 1)
            x2 = random.uniform(-1, 1)
            r = x1**2 + x2**2
            if (r < 1):
                break

    y1 = x1 * math.sqrt( (-2 * math.log(r)) / r )
    gaussianRandom.y2 = x2 * math.sqrt( (-2 * math.log(r)) / r )

    print(gaussianRandom.y2)
    return y1

gaussianRandom.y2 = 99
print "y2", gaussianRandom(3)
print gaussianRandom(3)
print gaussianRandom(3)

rawDescription: Python : How to store a value generated in a function for the second call of that function


code:
a = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
b = [1, 2, 3, 4, 5]

for x in a:
    for y in b:
        if a[x] == b[y]:
            #Do stuff here
            print "found a match " + str(a[x])
        elif y == len(b) - 1:
            break

rawDescription: Comparing values of a list in python with a for loop


code:
import random as rnd
coin=["h","t"]
seed=10
rnd.seed(seed)

for i in range(100):
    print coin[rnd.randint(0,1)]

rawDescription: randomly pick an element from a list in python using pseudo random generator which should happen 50 percent of time

description: Randomly pick an element from a list in python using pseudo random generator which should happen 50 percent of time


code:
s=str(616263)
print "".join([chr(int(s[x:x+2], 16)) for x in range(0,len(s),2)])

rawDescription: Convert hex-string to string using binascii


code:
from collections import deque

myList = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']

def swap(items):
    items = deque(items)
    while items:
        yield items.popleft()
        try:
            yield items.pop()
        except IndexError:
            pass

print list(swap(myList))

rawDescription: Swap all elements in a list in python 3.4


code:
testOutput = { [1,0,0,1] : [1], [1,1,0,1] : [0], [1,0,1,1]:[0], [1,0,1,0]:[1] }

for input, expectedOutput in testInput.items():
    output = net.activate(input)
    if output != expectedOutput:
        print "{} didn't match the desired output."
        print "Expected {}, got {}".format(input, expectedOutput, output)

rawDescription: PyBrain - how to validate my trained network against a test data?


code:
#A = adjacency matrix, u = vertex u, v = vertex v
def weight(A, u, v):
    return A[u][v]

#A = adjacency matrix, u = vertex u
def adjacent(A, u):
    L = []
    for x in range(len(A)):
        if A[u][x] > 0 and x <> u:
            L.insert(0,x)
    return L

#Q = min queue
def extractMin(Q):
    q = Q[0]
    Q.remove(Q[0])
    return q

#Q = min queue, V = vertex list
def decreaseKey(Q, K):
    for i in range(len(Q)):
        for j in range(len(Q)):
            if K[Q[i]] < K[Q[j]]:
                s = Q[i]
                Q[i] = Q[j]
                Q[j] = s

#V = vertex list, A = adjacency list, r = root
def prim(V, A, r):
    u = 0
    v = 0

    # initialize and set each value of the array P (pi) to none
    # pi holds the parent of u, so P(v)=u means u is the parent of v
    P=[None]*len(V)

    # initialize and set each value of the array K (key) to some large number (simulate infinity)
    K = [999999]*len(V)

    # initialize the min queue and fill it with all vertices in V
    Q=[0]*len(V)
    for u in range(len(Q)):
        Q[u] = V[u]

    # set the key of the root to 0
    K[r] = 0
    decreaseKey(Q, K)    # maintain the min queue

    # loop while the min queue is not empty
    while len(Q) > 0:
        u = extractMin(Q)    # pop the first vertex off the min queue

        # loop through the vertices adjacent to u
        Adj = adjacent(A, u)
        for v in Adj:
            w = weight(A, u, v)    # get the weight of the edge uv

            # proceed if v is in Q and the weight of uv is less than v's key
            if Q.count(v)>0 and w < K[v]:
                # set v's parent to u
                P[v] = u
                # v's key to the weight of uv
                K[v] = w
                decreaseKey(Q, K)    # maintain the min queue
    return P

A = [ [0,  4,  0,  0,  0,  0,   0,  8,  0],
      [4,  0,  8,  0,  0,  0,   0, 11,  0],
      [0,  8,  0,  7,  0,  4,   0,  0,  2],
      [0,  0,  7,  0,  9, 14,   0,  0,  0],
      [0,  0,  0,  9,  0, 10,   0,  0,  0],
      [0,  0,  4, 14, 10,  0,   2,  0,  0],
      [0,  0,  0,  0,  0,  2,   0,  1,  6],
      [8, 11,  0,  0,  0,  0,   1,  0,  7],
      [0,  0,  2,  0,  0,  0,   6,  7,  0]]
V = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]

P = prim(V, A, 0)
print P

[None, 0, 5, 2, 3, 6, 7, 0, 2]

rawDescription: Prim's Algorithm input parameter (values) in Python


code:
from Tkinter import *
import tkFileDialog

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.create_wgts()

    def create_wgts(self):
        self.MainMenu=Menu(self.master)

        self.wgt_confirm = Button(text='Confirm', command=self.traceback).pack(side=RIGHT)

        self.wgt_entry = Entry()
        self.wgt_entry.pack(side=RIGHT, fill=X, expand=1, ipadx=200)
        self.wgt_entry.bind('<Key-Return>', self.hit_enter)

        self.casMenu_File = Menu(self.MainMenu)
        self.casMenu_File.add_command(label="Open File", command=self.file_select)
        self.casMenu_File.add_command(label="Write to File", command=self.file_write)
        self.casMenu_File.add_separator()
        self.casMenu_File.add_command(label="Exit", command=self.traceback)

        self.MainMenu.add_cascade(label='File', menu=self.casMenu_File)
        self.master.config(menu=self.MainMenu)

    def traceback(self):
        print "traceback called"

    def hit_enter(self, event):
        print "Hit ENTER"

    def file_select(self):
        print "File>Open called"

    def file_write(self):
        print "File>Write File called"

root = Tk()
app = Application(master=root)
app.mainloop()

rawDescription: Python/Tkinter: Why is my cascade menu not working?


code:
mylist.sort()
print mylist

rawDescription: Sorting a list of objects by attribute

description: Sorting a list of objects by attribute


code:
data = {"1.12.2015":5, "4.12.2015":3, "2.12.2015":6}

from datetime import datetime

for k,v in sorted([(datetime.strptime(k, '%d.%m.%Y'), v) for k,v in data.iteritems()]):
    print datetime.strftime(k, '%d.%m.%Y'), v

rawDescription: python, read keys from dict by size, to plot them

description: Python, read keys from dict by size, to plot them


code:
import re

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Firefox()
browser.get('http://www.spokeo.com/search?q=Joe+Henderson,+Phoenix,+AZ&sao7=t104#:18643819031')

WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "profile_details_section_header")))
content = browser.page_source

m_obj = re.search(r"(\(\d{3}\)\s\d{3}-\*{4})", content)
if m_obj:
    print m_obj.group(0)

browser.quit()

rawDescription: Parse from a JS generated site

description: Parse from a JS generated site


rawDescription: Convert hex stream to arabic language string


code:
with open ('/home/thamer/SAMPLE.TXT','r') as f:
    tracker = Tracker("")
    for line in f:
        tracker.region = line
        region = tracker.make_tracker()

        if region =="CPM or IOM":
            print "CPM or IOM"

rawDescription: how to create only one object in python every time the code runs

description: Create only one object in python every time the code runs


code:
def set_variables():
    to_print = []
    if cbtn_var1.get():
        to_print.append(ent_var1.get())
    if cbtn_var2.get():
        to_print.append(ent_var2.get())
    if cbtn_var3.get():
        to_print.append(ent_var3.get())
    print " ".join(to_print)
    return

rawDescription: Possible to remove/deactivate variables from an executed line?


code:
import random
with open("words.txt") as f:
   words = random.sample([x.strip() for x in f], 6)

grouped = [words[i:i+3] for i in range(0, len(words), 3)]
for l in grouped:
    print "".join("{:<10}".format(x) for x in l)

rawDescription: Using a text file to lay out a words into a grid form