code:
client = EvernoteClient(token=your_access_token)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks();
for n in notebooks:
    print n.name

rawDescription: How to avoid user having to re-authorize Evernote every time?

description: Avoid user having to re-authorize Evernote every time


code:
import csv  #ignore my stupidity with the indentation and spaces#
with open('Sampledata.csv', 'r') as csvfile :
    regnumber = raw_input("Enter the time:")
    reader = csv.reader(csvfile)
    for row in reader:
        if(row[0]==regnumber):
            print ', '.join(row)
        else:
            continue

rawDescription: Reading row data from CSV file

description: Reading row data from CSV file


rawDescription: Print from specific positions in NumPy array


code:
import re

def doitall(number):
  # get 9 or 10 digits, or None:
  mo = re.search(r'\d{9,10}', number)
  if mo is None: return None
  # add a leading 0 if they were just 9
  digits = ('0' + mo.group())[-10:]
  # now put a dot after each 2 digits
  # and discard the resulting trailing dot
  return re.sub(r'(\d\d)', r'\1.', digits)[:-1]

number = "+33.300000000"
print doitall(number)

rawDescription: How to perform this RegExp in Python?

description: Perform this RegExp in Python


code:
for x in range(5):
  print x

sum(x * 2 for x in range(5))

rawDescription: Joining each element of a list to another element in Python


code:
import os

class Foo():
    def __init__(self):
        self.stored_end = 0

    def account(self, a, b):
        c = float(a) + b
        print a
        print b
        print c
        self.stored_end = c
        print self.stored_end

    def testy(self, q, v):
        print "\n"
        print " _ " * 10
        z = float(q) + v
        print self.stored_end
        self.stored_end = self.stored_end + z
        print " _ " * 10
        print self.stored_end

class Bar():
    def __init__(self):
        pass

    def zippy(self, a, b):
        print " _ " * 10
        print "this is zippy"
        foo.testy(a, b)

class Baz():
    def __init__(self):
        pass

    def cracky(self, g, m):
        y = g + m
        print " _ " * 10
        print "calling stored_end"
        foo.stored_end = foo.stored_end + y
        print " _ " * 10
        print "this is cracky"
        print "y = %r" % y
        print foo.stored_end

os.system("clear")
foo = Foo()
foo.account(5, 11)
foo.testy(100, 100)
bar = Bar()
bar.zippy(10, 100)
baz = Baz()
baz.cracky(1000, 1)

rawDescription: python: how do I call a function without changing an argument?

description: Python: how do I call a function without changing an argument


code:
lib = 'test.so'
dll = cdll.LoadLibrary(lib)

dll.add.argtypes=[POINTER(c_int)]
#                ^^^^^^^^^^^^^^^^
#         One argument of type `int *̀

dll.add.restype=c_int
# return type

res =dll.add((c_int*5)(5,1,7,33,99))
#            ^^^^^^^^^
#       cast to an array of 5 int

print res

rawDescription: Calling C function from python using ctypes


code:
#! /usr/bin/env python
import random
codes = ["A", "B", "C", "D", "E"]
random.shuffle(codes)

def print_sys_result(sys_code):
    results = {
        "A": "is really great",
        "B": "has improved greatly over the years",
        "C": "sucks",
        "D": "screwed us up really badly",
        "E": "stinks like monkey balls"
    }
    print "\n"
    print "-"*10
    print 'This is a test of the {0} system'.format(sys_code)
    if sys_code in results:
        print "The {0} system {1}.".format(sys_code, results[sys_code])
    else:
        print "No results available for system " + sys_code
    print "-"*10
    print "\n"

print_sys_result(codes[0])

rawDescription: How to do an if statement based on a randomized string in Python?

description: Do an if statement based on a randomized string in Python


code:
import os

os.system('clear')
os.system('CLS') # windows

# Solution for IDLE
N = 40 # you might need to adjust this
for i in range(N):
    print "\n"

rawDescription: clear python idle using command

description: Clear python idle using command


code:
def foo():
    def bar():
        print 'i am bar'
    return bar
b1 = foo()
b2 = foo()
b1 is b2
b1.func_code is b2.func_code

rawDescription: How to get the nested function objects?

description: Get the nested function objects


code:
for newr in new_r:
  print [(r[i+1]-r[i])**3 * ro[i+1] for i in xrange(len(r) - 1) if r[i] < newr]

rawDescription: Comparison of arrays and calculation

description: Comparison of arrays and calculation


code:
def triangle(n):
    a=[]
    for i in range(n):
        b=[]
        for j in range(n-i):
            b.append(i)
        a.append(b)
    for row in a:
        print row

rawDescription: Return a triangled-shaped list of lists

description: Return a triangled-shaped list of lists


code:
def play_music():
    while True:
        if not ch.get_queue():
            for x in range(BUFFERSIZE):
                    if x % BLOCKSIZE == 0:
                        outbuf = m.process(inbuf)
                    samples[selector][x][0] = outbuf[(x % BLOCKSIZE) * 2]
                    samples[selector][x][1] = outbuf[(x % BLOCKSIZE) * 2 + 1]
            ch.queue(sounds[selector])
            selector = int(not selector)
        libpd_release()

play_music_thread = threading.Thread(target=play_music)
play_music_thread.daemon = True
play_music_thread.start()

while True:
    command = raw_input().lower()

    if command == "commands":
        print '"look around"'
        print '"explore"'
        print '"inventory"'
        print '"examine"'
        print '"take"'
        print '"combine"'
        print '"quit"'
    elif command == "look" or command == "look around":
        char.look()

rawDescription: While loop issue - Python

description: While loop issue - Python


code:
# Define the metaclass
class metacls(type):
    counter = 0
    def __new__(meta_class, name, bases, attributes):
        attributes['id'] = metacls.counter
        metacls.counter += 1
        return type.__new__(meta_class, name, bases, attributes)

# Set the metaclass
class Master(object): __metaclass__ = metacls

class Slave1(Master): pass
class Slave2(Master): pass
class Slave3(Master): pass

print Slave1.id, Slave1().id
# 1 1
print Slave2.id, Slave2().id
# 2 2
print Slave3.id, Slave3().id
# 3 3

rawDescription: Assign identifier to every inheriting class


code:
from lxml import etree

print etree.tostring(node)

rawDescription: Return the XML source for the node with lxml


code:
def predict(lst):
    print "predicting for", lst
    print "result", max(lst) + 0.0
    return max(lst) + 0.0

def window(lst, n=3):
    for x in range(1, len(lst)+1): # or len(l)+n to continue till the end
        yield(lst[max(0, x-n):x])

def sliding_tristep(full_trace, future_step = 2, window_size = 3):

    for user_trace in full_trace:
        for current_input in window(user_trace):
            counter = 0
            trace = current_input
            accumulator = []
            while counter <= future_step:      # this loop is used to define how many times you want to perform the given function (in this case predict())
                next_prediction = predict(trace)
                trace.append(next_prediction)
                accumulator.append(next_prediction)
                trace = trace[-window_size:]    # slicing the next input happens here
                counter += 1

            print current_input, accumulator

rawDescription: Some complex list calculations and slicing; How to make it work?


code:
prefix = "aws"
uri = "http://alexa.amazonaws.com/doc/2005-10-05/"
import lxml.etree as lET
lET.register_namespace(prefix, uri)
doc=lET.parse('alexa_response.xml')
doc_root=doc.getroot()
for value in doc_root.xpath('.//UsageStatistic[TimeRange/Days="7"]/PageViews/PerUser/Value'):
    print value.text

rawDescription: Pythonic way to get a XML tree element in the same subtree with another element


code:
while health > 0 and health1 > 0:

    if turn == 1:
            while loopx == False:
                    try:
                            move = raw_input("Do you want to attack or gegenerate health? Press 1 to ATTACK and 2 to REGEN. ")
                            print ""
                            move = int(move)
                            if move == 1:
                                    health1 = health1 - damage
                                    print "You attacked!"
                                    loopx = True                        # fix1
                            elif move == 2:
                                    health = health+regen
                                    print "You regenerated health!"
                                    loopx = True
                            else:
                                    print "Invalid number, try again"
                                    continue
                    except:
                                    print "Invalid number, try again"
                                    continue
            turn = 2                                                    # fix 2

    if turn == 2:
            AImove = r.randint(1,2)
            if AImove == 1:
                    print "AI attacked!"
                    health = health - damage1
            else:
                    print "AI regenerated!"
                    health1 = health1+regen1
            turn = 1                                                    # fix 3
            continue

print "game over!"

rawDescription: How to make a turn based game loop in python 2.7(solved!)

description: Make a turn based game loop in python 2.7(solved!)


code:
menu = optionMenu["menu"]
last = menu.index("end")
items = []
for index in range(last+1):
    items.append(menu.entrycget(index, "label"))
print "items:", items

rawDescription: Get a list of all options from OptionMenu


code:
#!/usr/bin/python

import ldap, sys

l = ldap.initialize('ldap://myldapserver:389')
search_filter = "(&(uid=myID)(objectClass=inetOrgPerson))"
base_dn="O=MyCompanyGroup"
password = "mypassword"
try:
  l.protocol_version = ldap.VERSION3
  result = l.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter, None)
  user_dn = result[0][0]
  print user_dn
  l.simple_bind_s(user_dn, password)
  valid = True
  print "OK"
  l.unbind()
except Exception, error:
  print error

rawDescription: LDAP uid path not known

description: LDAP uid path not known


code:
INDENT = ' ' #Change this to taste

def print_family(parent,family,indent=0):
    for child in family:
        if child['parent'] == parent:

             # Print here
             print '%s%s' % (INDENT * indent,child['name'])

             # Call on the child
             print_family(child['name'],family,indent + 1)

# Kick it off with the root node
print_family('',family)

rawDescription: Python family tree from dict with defined parents


code:
import nltk
from requests import session

payload = {
    'user': '<Username>',
    'password': '<Password>',
    'logon': 'username',
    'submit': 'Log In'
}

headers = {
    'Referer': 'https://www.myebill.com/index.asp?startnam',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36'
    }

with session() as c:
    c.post('https://www.myebill.com/index.asp?startnam', data=payload, headers=headers)
    request = c.get('https://www.myebill.com/index.asp')
    print request.headers
    print( nltk.clean_html( request.text ) )

rawDescription: Logging in, navigating, and extracting text on SSL site using Python?


code:
import time
lines = []
with open("somelog.txt") as f:
      lines = [line for line in f]
def OnlyRecent(line):
      return time.strptime(line.split("[")[0].strip(),"%a %b %d %h:%m:%s %Y") < (time.time()-(60*60*24*5)) #5 days old
print "\n".join(filter(OnlyRecent,lines))

rawDescription: Python filter script

description: Python filter script


code:
def route(route, method):
    def decorator(f):
        print 'decorator defined'
        print 'defining route'
        @wraps(f)
        def wrapper(*args, **kwargs):
            print 'Hello'
            # do stuff here such as authenticate, authorise, check request json/arguments etc.
            # these will get passed along with the route and method arguments above.
            return f(*args, **kwargs)

        app.add_url_rule(route, methods=method, view_func=wrapper)
        print 'route defined'
        return wrapper
    return decorator

rawDescription: Flask app.add_url_rule in decorator error


code:
print val1 / (val2 + 0.0)
print (val1 + 0.0) / val2
print float(val1) / val2
print val1 / float(val2)

rawDescription: Forcing to make floating point calculations


code:
from BeautifulSoup import BeautifulSoup
ht = '<title>foo</title>
whatever:

'
soup = BeautifulSoup(ht)
soup
soup.findAll('img')
for img in soup.findAll('img'):
    ht = int(img['height'])
    wi = int(img['width'])
    img['height'] = str(ht * 2)
    img['width'] = str(wi * 2)

print soup.prettify()

rawDescription: how to make the width and height x2 using python Regular

description: Make the width and height x2 using python Regular


code:
import urllib2
f = urllib2.urlopen('http://tejp.de')
print str(f.info())

rawDescription: Unescape a string inside a string

description: Unescape a string inside a string


code:
import os
import subprocess

def launch_app():
    os.environ['APPLICATION_ENVIRON'] = 'usr/path'
    application_path = 'path/to/application'
    return subprocess.Popen([application_path])

def _purge_finished_apps(apps):
    still_running = set()
    for app in apps:
        return_code = app.poll()
        if return_code is not None:
            print "  PID {} no longer running (return code {})".format(app.pid, return_code)
        else:
            still_running.add(app)
    return still_running

def ui():
    apps = set()

    while True:
        print
        print "1. To launch new instance"
        print "2. To view all instances"
        print "3. To exit, terminating all running instances"
        print "4. To exit, leaving instances running"
        opt = int(raw_input())

        apps = _purge_finished_apps(apps)

        if opt == 1:
            app = launch_app()
            apps.add(app)
            print "  PID {} launched".format(app.pid)

        elif opt == 2:
            if not apps:
                print "There are no instances running"
            for app in apps:
                print "  PID {} running".format(app.pid)

        elif opt == 3:
            for app in apps:
                print "Terminating PID {}".format(app.pid)
                app.terminate()
            for app in apps:
                app.wait()
                print "PID {} finished".format(app.pid)
            return

        elif opt == 4:
            return

if __name__ == "__main__":
    ui()

rawDescription: Tracking application launched with a python file


code:
for fare in schedule.GetFareAttributeList():
    for rule in fare.GetFareRuleList():
        if rule.origin_id == 'B1' and rule.destination_id == 'B1':
            print rule

rawDescription: How to find an item in a dict with nested classes?

description: Find an item in a dict with nested classes


code:
import re

q1 = r'^Organism.*('
q2 = raw_input("Enter organism (e.g., moth)")
q3 = r').*</td>'

s="Organism: moth </td>"

regex = re.compile(q1+q2+q3)
test = re.search(regex,s).group(1)

print "test", test

rawDescription: How to combine several regex search patterns into on pattern (i.e., use an addition operator) in python

description: Combine several regex search patterns into on pattern (i.e., use an addition operator) in python


code:
match = re.search(r"(?<=').*?(?=')", "a 'quoted' string. 'second' quote")
print match.group(0)

rawDescription: Python regex non-capturing issue?

description: Python regex non-capturing issue


code:
class DefaultKeyDict(dict):
    def __init__(self, default_key, *args, **kwargs):
        self.default_key = default_key
        super(DefaultKeyDict, self).__init__(*args, **kwargs)

    def __missing__ (self, key):
        if self.default_key not in self:  # default key not defined
            raise KeyError(key)
        return self[self.default_key]

    def __repr__(self):
        return ('{}({!r}, {})'.format(self.__class__.__name__,
                                      self.default_key,
                                      super(DefaultKeyDict, self).__repr__()))

    def __reduce__(self):  # optional, for pickle support
        args = (self.default_key if self.default_key in self else None,)
        return self.__class__, args, None, None, self.iteritems()

dkdict = DefaultKeyDict('b', {'a': 1, 'b': 2, 'c': 3})

print dkdict['a']  # -> 1
print dkdict['b']  # -> 2
print dkdict['c']  # -> 3
print dkdict['d']  # -> 2 (value of the default key)

del dkdict['b']  # delete the default key
try:
    print dkdict['d']  # should now raise exception like normal
except KeyError:
    print("dkdict['d'] raised a KeyError")

rawDescription: Python dictionary with default key

description: Python dictionary with default key


code:
import random
import Tkinter
import ttk

# Make 5 "questions" with varied number of answers to pick from.
QUESTION = [u"Question %d" % (i + 1) for i in range(5)]
QOPTS = []
k = 1
for _ in QUESTION:
    num_opts = random.randint(3, 6)
    QOPTS.append([u"text %d" % (k + i) for i in range(num_opts)])
    k += num_opts

class Question:
    def __init__(self, master):
        self._common_var = Tkinter.StringVar()

        self._title = None
        self._lframe = None
        self._rb = []
        self._make_gui(master)

    def get_answer(self):
        return self._common_var.get()

    def reset_answer(self):
        self._common_var.set("")

    def _make_gui(self, master):
        self._title = ttk.Label(master, padding=(0, 6, 0, 0))
        self._title.grid(in_=master, padx=6, row=0, column=0, sticky='ew')

        self._lframe = ttk.Labelframe(master)
        self._lframe.grid(in_=master, padx=6, row=1, column=0, sticky='nsew')

    def update_gui(self, question, options):
        self._title['text'] = question
        for i, opt in enumerate(options):
            if i < len(self._rb):
                if not self._rb[i].grid_info():
                    self._rb[i].grid()
                self._rb[i]['text'] = opt
            else:
                rb = ttk.Radiobutton(self._lframe, text=opt, value=i,
                        variable=self._common_var)
                rb.grid(in_=self._lframe, row=i, column=0, sticky='w')
                self._rb.append(rb)
        # Deal with i < total.
        for k in xrange(i + 1, len(self._rb)):
            self._rb[k].grid_remove()

class Base:
    def __init__(self, frame, q, o):
        self.master = frame

        self.question = None
        self.curr_question = 0
        self.q = q
        self.o = o
        self._make_gui(frame)
        self._update_gui()

    def next_question(self):
        answer = self.question.get_answer()
        try:
            answer = int(answer)
        except ValueError:
            print "Question not answered, stay here."
            return
        print "Answer for question %d: %d" % (self.curr_question, answer)
        self.question.reset_answer()

        self.curr_question += 1
        self._update_gui()

    def _make_gui(self, frame):
        self.question = Question(frame)
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(1, weight=1)

        btn = [(u"Next", self.next_question)]
        self._btn = []
        for i, (text, cmd) in enumerate(btn):
            # Assumption: the Question instance always uses the rows 0 and 1.
            b = ttk.Button(frame, text=text, command=cmd)
            b.grid(in_=frame, padx=6, pady=6, row=2, column=i, sticky='e')
            self._btn.append(b)

    def _update_gui(self):
        if self.curr_question == len(self.q):
            print "Done"
            self.master.quit()
            return
        elif self.curr_question == len(self.q) - 1:
            for btn in self._btn:
                # No next question
                btn['text'] = u"Finish"

        self.question.update_gui(self.q[self.curr_question],
                self.o[self.curr_question])

root = Tkinter.Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.geometry('300x250')
frame = ttk.Frame(root)
frame.grid(sticky='nsew')
Base(frame, QUESTION, QOPTS)
root.mainloop()

rawDescription: How to design GUI sequence in Tkinter with Python 2.7

description: Design GUI sequence in Tkinter with Python 2.7


code:
def product_search(*params):
    results = []
    upperParams = [ param.upper() for param in params ]

    for product in products:
        name = str(product.name).upper()
        item_number = str(product.item_number).upper()
        for upperParam in upperParams:
            if upperParam in name or upperParam in item_number:
                results.append(product)
    print results

rawDescription: Python search list of objects that contain objects, partial matches


code:
from Tkinter import *

def callback():
    print 'You clicked the button!'

top = Tk()
L1 = Label(top, text="User Name")
L1.grid(row=0, column=0)
E1 = Entry(top, bd = 5)
E1.grid(row=0, column=1)

MyButton1 = Button(top, text="Submit", width=10, command=callback)
MyButton1.grid(row=1, column=1)

top.mainloop()

rawDescription: Entry field with submit button in python?


code:
import urllib2
proxy = urllib2.ProxyHandler({'https': '127.0.0.1:8081'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
print urllib2.urlopen('https://www.google.com').read()

rawDescription: httplib and HTTPs proxies

description: Httplib and HTTPs proxies


code:
class N:
    def __init__(self):
        self.s = []
    def add(self,u):
        self.s.append(u)
    def check(self):
        if sorted(self.s) == True:
            print "List is sorted"
        else:
            print "Not sorted but it will sort now"
            return sorted(self.s)

rawDescription: initializing queue with condition

description: Initializing queue with condition


code:
class MetaState(type):
    _baseclasses = {}  # registry of instances & number of subclasses of each
    def __new__(cls, name, bases, attrs):
        cls = super(MetaState, cls).__new__(cls, name, bases, attrs)
        if bases == (object,):  # definition of a base class?
            MetaState._baseclasses[cls] = 0  # create initial registry entry
        else:  # must be derived from a previously defined base state class
            for base in bases:  # find base state class
                if base in MetaState._baseclasses:
                    setattr(cls, 'enum', 2 ** MetaState._baseclasses[base])
                    MetaState._baseclasses[base] += 1
                    break
            else:
                raise TypeError('Class not derived from base state class')
        return cls

class BaseState(object):
    """ Abstract base class for each derived state subclass. """
    __metaclass__ = MetaState

    def is_flag(self, flag):
        return flag & self.enum == self.enum

class A(BaseState): pass
class B(BaseState): pass
class C(BaseState): pass

print A.enum  # -> 1
print B.enum  # -> 2
print C.enum  # -> 4

rawDescription: Python metaclass to generate correct enum values for class


code:
import igraph as ig
G1=ig.Graph(directed=True)
G2=ig.Graph(directed=True)
G1.add_vertices(2)
G2.add_vertices(2)
G1.vs[0]['gaga'] = 'gugu'
G2.vs[0]['gaga'] = 'gogo'
G1.add_edge(0,1)
G2.add_edge(1,0)

print G1.isomorphic_vf2(G2)

def cmp_nodes(g1, g2, i1, i2):
    return g1.vs[i1]['gaga'] == g2.vs[i2]['gaga']

print G1.isomorphic_vf2(G2, node_compat_fn=cmp_nodes)

rawDescription: Compare two small directed graphs with attributes on edges and nodes


code:
from subprocess import Popen, PIPE, STDOUT
import re

## Text result of the whois is stored in whois_result...
whois_result = Popen(['whois', domain], stdout=PIPE,
    stderr=STDOUT).communicate()[0]
if 'No match for' in whois_result:
    print "Processing whois failure on '%s'" % domain
    whois_result = Popen(['whois', p_ip], stdout=PIPE,
        stderr=STDOUT).communicate()[0]
    if 'No match for' in whois_result:
            print "complete and utter whois failure, its you isnt it, not me."
    test = re.search("country.+([A-Z].)",whois_result)
    countryid = test.group(1)

rawDescription: Python Popen WHOIS OS command fail test

description: Python Popen WHOIS OS command fail test


rawDescription: Bytes and integers and concatenation and python


code:
def startcave():
    print "You awake in an dark cave. You can't remember your past, but you need to find a way out. You feel hungry, although tired."
    print "Would you like to delve deeper via a cave passage, or look for a way out in this room?"
    answer = raw_input("Do you go -Deeper-, -Search-, or -Rest-?").lower()
    if answer == "Deeper" or answer == "deeper":
        lowcave1()
    elif answer == "Search" or answer == "search":
        searchcave()
    elif answer == "Rest" or answer == "rest":
        caverest()
    else:
        print "You must either say -Deeper- or -Search-"
        startcave()

def lowcave1():
    print "You go deeper into the cave, walking down a steadily reclining corridor for some time, you have lost track of time."
    print "There is a large ledge before you. You can jump down, but there is no way back up."
    print "The cave may be dangerous, and you could end up being trapped. Do you turn back?"
    answer = raw_input("Do you -Jump- or -Turn back-?").lower()
    if answer == "Jump" or answer == "jump":
        lowcave2()
    elif answer == "Turn back":
        caverest2()

startcave()

lowcave1()

rawDescription: How do I define global names?

description: Define global names


code:
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('
X	Color Digest	THE DIGEST
')
for cell in soup.html.tr.findAll('td'):
    if 'Color Digest' == cell.text:
         print cell.nextSibling.text

rawDescription: BeautifulSoup: How to extract data after specific html tag


code:
days = set( Post.objects.filter(user=TARGET).values_list("log_date", flat=True) )
curr = min(days)
while curr <= date.today():
    print curr,
    if curr not in days:
        print "NO ENTRY",
    print
    curr += timedelta(days=1)

rawDescription: Display gaps in dates with Python and Django


code:
sourcepath = "/home/julien/csv/ABORD.csv"
destpath =  "/home/julien/csv/ABORD-fixed.csv"

with open(sourcepath, "rb") as source, open(destpath, "wb") as dest:
    # XXX are you sure you want this as quotechar ???
    reader = csv.reader(source, delimiter = ';', quotechar=' ')
    writer = csv.writer(dest,  delimiter = ';', quotechar=' ')

    # first copy the (augmented) headers
    headers = reader.next()
    headers.append("CONTROL")
    writer.writerow(headers)

    # then let's loop on the content
    for rownum, row in enumerate(reader):
        # we need to convert data to int
        # adding proper error handling here might help...
        # status = "result OK" if (int(row[1]) > 10 and int(row[2]) < 20) else "result fail"
        try:
            l1 = int(row[1])
            l2 = int(row[2])
        except (TypeError, ValueError), e:
            err = "non integer value for l1 and or l2 in row %s line %s - got : %s" % (
                rownum, reader.linenum, row
                )
            print >> sys.stderr, err
            result = "invalid values"
        else:
            if l1 > 10 and l2 < 20:
                result = "result OK"
            elif rownum == 42: # stupid value for if/elif/else exemple
                result = "what's the question ?"
            else:
                result = "result fail"

        row.append(result)
        writer.writerow(row)

rawDescription: Python : populate a new column with an if/else statement


code:
s = "Client: Company X"
print s.split(":")[-1]
s = "Fund: ABCD"
print s.split(":")[-1]

rawDescription: Extracting certain parts of an email using Python (Regex)


code:
label = gtk.Label()
button = gtk.Button()
def callback(obj):
   print obj
button.connect('clicked', callback)  # button will be passed by default
button.emit('clicked')
button.disconnect_by_func(callback)
button.connect_object('clicked', callback, label)  # label will be passed instead of button
button.emit('clicked')

rawDescription: Difference between connect() and connect_object() in pygtk


code:
target_word = "hello world"
target_size = len(target_word)
alphabet = "abcdefghijklmnopqrstuvwxyz "
def make_guess(alphabet,size):
   return "".join(random.choice(alphabet) for _ in range(size))

guess = make_guess(alphabet,target_size)

for i in itertools.count(0):
   if guess == target_word:
      break;
   if not i % 1000:
      print "Best So Far:",guess
   #climb hill and replace our guess if our next guess is better
   guess = min(guess,make_guess(alphabet,target_size),key=lambda _guess:levenstein(_guess,target_word))
print "Final Guess:",guess

rawDescription: Hill-climbing algorithm to generate a string using Levenshtein distance as heuristic in Python?


code:
import matplotlib
from matplotlib.mlab import csv2rec
import matplotlib.pyplot as plt
import numpy
import datetime

inputfilename="test_tpm_log.log"

data = csv2rec(inputfilename, names=['packets', 'time'])

old_value = 0
counter_tpm = []
counter_rollmean = []

for tpm in data['packets']:
        new_value = (tpm + old_value) / 2
        old_value = tpm
        counter_tpm.append(tpm)
        counter_rollmean.append(new_value)

dates_in_file = str(data['time'])
for dates in dates_in_file:
        print dates

rec = zip(counter_tpm, counter_rollmean, data['time'])

print rec

rawDescription: Python fit a normal curve to data: matplotlib / scipy and graph


code: print " ".join([str(function(first)), str(function(second)), str(function(third))])

rawDescription: Python: how to add spaces between strings


code:
path = "/Users/air/Desktop/book vocab/b CS tutr"
filenames = os.listdir(path)
print filenames

os.chdir(path)

for i, filename in enumerate(filenames):
    newname = filename.translate(None, '12345')
    os.rename(filename, newname)
    filenames[i] = newname

print filenames

rawDescription: How do I see the renamed files in Python script output?

description: See the renamed files in Python script output


code:
l1 = ['a', 'b', 'c', 'b', 'c']
l2 = ['a', 'b', 'c', 'b']

from collections import Counter

c1 = Counter(l1)
c2 = Counter(l2)

diff = c1-c2
print list(diff.elements())

rawDescription: Difference Between Two Lists with Duplicates in Python


code:
import sys
if sys.flags.interactive:
    print 'I am in interactive mode!'
else:
    print 'I am in batch mode!'

rawDescription: Is is possible for a python script to know whether it is run with the interactive option '-i'?


code:
myarray = [ 10.54552827, 0.10287327, 0.21923103 ]
rounded = ["%.2f" % i for i in myarray]

lst = [ cntr, n_obs ]
print ','.join( lst.extend(lst) )

rawDescription: print array without brackets

description: Print array without brackets


rawDescription: Slow array operation in python

description: Slow array operation in python


code:
import wx

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

class MyPanel(wx.Panel):

    def __init__(self, parent, state, button_image, background_image):
        wx.Panel.__init__(self, parent=parent)

        print "(debug) MyPanel.__init__: state:", state

        self.parent = parent
        self.state  = state

        self.button_image = button_image
        self.background_image = background_image

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        vsizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        #self.buttonOne=wx.Image("image1.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
        self.buttonImage = wx.Image(button_image, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.button = wx.BitmapButton(self, -1, self.buttonImage, pos=(100,50))

        self.button.Bind(wx.EVT_LEFT_DCLICK, self.buttonClick)

        self.backgroundImage = wx.Bitmap(self.background_image)

        vsizer.Add(self.button, 0, wx.ALL, 5)

        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(vsizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)

        self.SetSizer(hSizer)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    def buttonClick(self, evt):
        print "(debug) MyPanel.buttonClick"
        self.parent.ChangePanel()

    def OnEraseBackground(self, evt):
        dc = evt.GetDC()

        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        dc.DrawBitmap(self.backgroundImage, 0, 0)

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

class MyFrame(wx.Frame):

    def __init__(self, size=(800,480)):
        wx.Frame.__init__(self, None, size=size)

        self.state = None
        self.panel = None

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)

        self.Show() # Show is used to show/hide window not to update content

        self.ChangePanel()

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

    def ChangePanel(self):

        print "(debug) MyFrame.ChangePanel: state:", self.state

        if self.state is None or self.state == 1:
            # change state
            self.state = 0

            # destroy old panel
            if self.panel:
                self.panel.Destroy()

            # create new panel
            self.panel = MyPanel(self, self.state, "ball1.png", "admin0.png")

            # add to sizer
            self.sizer.Add(self.panel, 1, wx.EXPAND)
        elif self.state == 0 :
            # change state
            self.state = 1

            # destroy old panel
            if self.panel:
                self.panel.Destroy()

            # create new panel
            self.panel = MyPanel(self, self.state, "ball2.png", "admin1.png")

            # add to sizer
            self.sizer.Add(self.panel, 1, wx.EXPAND)
        else:
            print "unkown state:", self.state

        self.Layout() # refresh window content

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

class Application(wx.App):

    def __init__(self, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)
        self.frame = MyFrame((800, 480))

    def run(self):
        self.MainLoop()

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

if __name__ == "__main__":
    Application().run()

rawDescription: wxpython : changing background / foreground image dynamically

description: Wxpython : changing background / foreground image dynamically


code:
print timeit.timeit(lambda: it_fib(10))
print timeit.timeit(lambda: rec_fib(10))

rawDescription: How to pass a method to timeit in python?

description: Pass a method to timeit in python


code:
import datetime

date1 = datetime.date(2000,1,1)
date2 = datetime.date(2099, 12, 31)

delta = date2-date1

print round(delta.days/365.25,0)

rawDescription: Rounding the duration of two date values


code:
import os
for path, dirs, files in os.walk('FDF\FDF'):
    for file in files:
        print file
        filepath = os.path.join(path, file)
        print filepath
        fdf = open(filepath, "r")

rawDescription: IOError: [Errno 2] No such file or directory


code:
import sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-e")
parser.add_option("-g")

print sys.argv # unmodified
(options, args) = parser.parse_args()
print (options, args)

sys.argv = ['module.py','-e','42','-g','84'] # define your commandline arguments here

(options, args) = parser.parse_args()
print (options, args)

rawDescription: How to pass command line arguments from one python module to another

description: Pass command line arguments from one python module to another


code:
# Built-in namespace
import __builtin__

# Extended subclass
class mystr(str):
    def first_last(self):
        if self:
            return self[0] + self[-1]
        else:
            return ''

# Substitute the original str with the subclass on the built-in namespace
__builtin__.str = mystr

print str(1234).first_last()
print str(0).first_last()
print str('').first_last()
print '0'.first_last()

output = """
14
00

Traceback (most recent call last):
  File "strp.py", line 16, in <module>
    print '0'.first_last()
AttributeError: 'str' object has no attribute 'first_last'
"""

rawDescription: Can I add custom methods/attributes to built-in Python types?

description: Add custom methods/attributes to built-in Python types


code:
import StringIO
import sys

filelike = StringIO.StringIO(sys.stdin.read())

# Now use `filelike` as a regular open file, e.g.:
filelike.seek(2)
print filelike.read()

rawDescription: Load an image from an input stream in Python


code:
#!/usr/bin/python

# Imports
import base64
import sys
import requests
import json
from base64 import b64encode
# Facedetection.py sends us an argument with a filename
filename = (sys.argv[1])
# API-Keys
rekognition_key = ""
rekognition_secret = ""
url = "http://rekognition.com/func/api/"

j1 = requests.post(
    url,
    data = {
        'api_key': rekognition_key,
        'api_secret': rekognition_secret,
        'jobs': 'face_recognize',
        'name_space': 'multify',
        'user_id': 'demo',
        'base64': b64encode(open(filename, 'rb').read()),
    }
)

data = json.loads(j1.text)
print data

rawDescription: Post file and data to API using Python

description: Post file and data to API using Python


code:
def recursive_thing(calls=1):
    # "calls" argument keeps track of recursion depth
    if keep_recursing():
        # pass a higher count to the recursive call
        recursive_thing(calls + 1)
    else:
        print calls
        return

rawDescription: counting iterations in recursion python

description: Counting iterations in recursion python


code:
import  Tkinter as tk

class StartStop():
    def __init__(self, root):
        self.x="False"
        self.ctr=0

        x_btn = tk.Button(root, text="Stop", background="Snow", width=20)
        x_btn.grid(row=0, column=4, sticky="W", padx=20, pady=5)
        x_btn.bind('<Button-1>', self.stop)

        self.resume_btn = tk.Button(root, text="Start", background="Snow", width=20)
        self.resume_btn.configure(state="disabled")
        self.resume_btn.grid(row=0, column=6, sticky="W", padx=20, pady=5)
        self.resume_btn.bind('<Button-1>', self.start)

    def xval(self):
        if self.x=="False":
            print "x=false %d=counter value"%self.ctr
            self.ctr += 1
            if self.ctr < 9:
                ## after gives the program time to update
                ## time.sleep() stops everyting
                root.after(1000, self.xval)

    def stop(self, event):
            self.resume_btn.configure(state="normal")
            self.x ="True"
            print "execution stopped:%s"%self.x

    def start(self, event):
            self.x ="False"
            print "execution started:%s"%self.x
            self.ctr=0
            self.xval()

root = tk.Tk()
S=StartStop(root)
root.mainloop()

rawDescription: Button not working till current loop ends in python


code:
from random import*

def f():
    b=[0]*101
    for i in range(0, 1000):
        b[randrange(0,101)]+=1
    return b

print f()

rawDescription: Trying to make a list that counts numbers


code:
from Tkinter import *

def print_data():
    print "printing data..."
    if read_button["text"] == "Stop":
        #call this again in 10 milliseconds
        root.after(10, print_data)

def read_button_clicked():
    read_button.config(command=stop_button_clicked)
    read_button.config(text="Stop")
    print_data()

def stop_button_clicked():
    read_button.config(command=read_button_clicked)
    read_button.config(text="Read Data")

root = Tk()

read_button = Button(root, text="Read Data", command=read_button_clicked)
read_button.pack()

root.mainloop()

rawDescription: tkinter read button state

description: Tkinter read button state


code:
import json
from mptt.templatetags.mptt_tags import cache_tree_children

def recursive_node_to_dict(node):
    result = {
        'id': node.pk,
        'name': node.name,
    }
    children = [recursive_node_to_dict(c) for c in node.get_children()]
    if children:
        result['children'] = children
    return result

root_nodes = cache_tree_children(Node.objects.all())
dicts = []
for n in root_nodes:
    dicts.append(recursive_node_to_dict(n))

print json.dumps(dicts, indent=4)

rawDescription: fastest way to create JSON to reflect a tree structure in Python / Django using mptt

description: Fastest way to create JSON to reflect a tree structure in Python / Django using mptt


code:
import numpy as np
from collections import OrderedDict

a1 = [1,2,3,4,5,6,7,8,9]
b1 = ['a','b','c','d','e','f','g','h','i']
c1 = ['A','B','C','D','E','F','G','H','I']

array2 = np.array([a1,b1,c1]).tolist()

keys = ['name', 'type','description','logo']

print OrderedDict(zip(keys, zip(*array2)))
# prints: OrderedDict([('name', ('1', 'a', 'A')), ('type', ('2', 'b', 'B')), ('description', ('3', 'c', 'C')), ('logo', ('4', 'd', 'D'))])

rawDescription: Dictionary is not giving all elements - Python


code:
def decodeNumber(test):
    if not test: # check if test is empty
        return 1

    count = 0

    for i in mapping:
        if test.startswith(i):
            count += decodeNumber(test[len(i):])

    return count

for test in encodedCases:
    test = test.strip()
    print test, "==>" , decodeNumber(test)

rawDescription: Count the number of ways a message can be decoded given the mapping


code:
Rate = 0
while (Rate < 0.5) or (Rate > 2.0):
    Rate = input ("Enter Desired Rate of Charge: ") #User will be prompted to enter the charge rate of the system
    if Rate < 0.5:
    #If the charge rate entered is less than 0.5 kWhs
        print "Charge Rate Too Low: Please consider revision" #Tells the user the rate is too low
    elif Rate > 2.0:
    #Also, if the charge rate entered is greater than 2.0 kWhs...
        print "Charge Rate Too High: Please consider revision" #Tells the user the rate is too high
    else:
    #Otherwise, for any number entered between the bounds of 0.5 and 2.0 kWhs...
        print '\n' #Page break for new conditions.

rawDescription: Python If Else Loop

description: Python If Else Loop


code:
# of course you should read the file someway
s = """
Row1Iteration1, Row1Iteration2, Row1Iteration3
Row2Iteration1, Row2Iteration2, Row2Iteration3
Row3Iteration1, Row3Iteration2, Row3Iteration3
Row4Iteration1, Row4Iteration2, Row4Iteration3
Row5Iteration1, Row5Iteration2, Row5Iteration3
"""
ncols = 3

iterations = []
for line in s.strip().split('\n'):
    iterations.append([l.strip() for l in line.split(',')])

with open('output.csv', 'w') as out:
    for col in xrange(ncols):
        for it in iterations:
            print it[col]
            out.write(col)

rawDescription: Appending to a .csv File in Python

description: Appending to a .csv File in Python


code:
from Tkinter import * # Tkinter -> tkinter in Python 3

root = Tk()

#############################################################
selected = None  # This is the variable mentioned in step 1

def print_label():
    print selected["text"]  # This is step 3

def popup(event):
    global selected  # Tell Python that selected is global

    menu.post(event.x_root, event.y_root)

    selected = event.widget  # This is step 2
#############################################################

# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Display the label", command=print_label)

# create the 3 labels
label1_text=StringVar()
label2_text=StringVar()
label3_text=StringVar()

label1_text.set("my label 1")
label2_text.set("my label 2")
label3_text.set("my label 3")

label1=Label(root, textvariable=label1_text)
label2=Label(root, textvariable=label2_text)
label3=Label(root, textvariable=label3_text)

label1.pack()
label2.pack()
label3.pack()

# attach popup to frame
label1.bind("<Button-3>", popup)
label2.bind("<Button-3>", popup)
label3.bind("<Button-3>", popup)

root.mainloop()

rawDescription: Adding a right click context menu with link with multiple widgets?


code:
from multiprocessing import Process, Queue
import numpy as np

input_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

def func1(dictionary, q):
    # do some work
    for x in xrange(5):
        q.put(
            np.random.randint(2, size=20)
        )
    q.put('STOP')

def func2(dictionary, q):
    # do different work
    q.put(
        np.array([1, 1, 1, 1, 0, 1, 1, 0, 1, 0,
                  1, 0, 1, 0, 1, 0, 0, 1, 1, 1])
    )

if __name__ == '__main__':
    q1 = Queue()
    q2 = Queue()
    p1 = Process(target=func1, args=(input_dict, q1))
    p2 = Process(target=func2, args=(input_dict, q2))
    p1.start()
    p2.start()

    f1_results = []
    # Keep adding items from func1 to the results list, until it sees a 'STOP' item
    for array in iter(q1.get, 'STOP'):
        f1_results.append(array)

    b = q2.get()
    p1.join()
    p2.join()

    for a in f1_results:
        result = np.dot(a, b)
        print result

rawDescription: How to run different methods in parallel and obtain the outputs for further processing?

description: Run different methods in parallel and obtain the outputs for further processing


code:
with open('hello-world.pdf','rb') as input_data:
    input_data.seek(89)      # Move to byte #89, i.e. skip first 89 bytes
    ima = input_data.read()  # Read all bytes from 89 to end of file
    print ima

rawDescription: read pdf file from specific byte to end of a file

description: Read pdf file from specific byte to end of a file


code:
for row in rd:
    list = []
    list.append(row)
    print list
    for items in row:
        pass # or whatever other logic you want, if you do not want to do anything remove this loop
    print len(row)

rawDescription: How to print the number of columns and lines in a csv file?

description: Print the number of columns and lines in a csv file


code:
from sqlalchemy import Table, MetaData, Column, Integer, Enum

m1 = MetaData()

t1 = Table(
    't1',
    m1, Column('a', Integer),
    Column('b', Enum('a', 'b', 'c', inherit_schema=True)), schema='x')

m2 = MetaData()
t2 = t1.tometadata(m2, schema='y')

print t2.schema
print t2.c.b.type.schema

rawDescription: How to swap the postgres schema attribute for a sqlalchemy metadata

description: Swap the postgres schema attribute for a sqlalchemy metadata


code:
class Counter:
  def __init__(self):
    self.c = 0

  def count(self):
    self.c += 1
    print 'in count() value is ' , self.c
    return self.c

class Test:
  counter = Counter() # A class variable counts its instantiations
  print 'in class Test'
  def __init__(self):
    print 'in Testinit'
    self.counter.count() # A method that prints the number of instances of Counter

test1 = Test() # Prints 1
test2 = Test()

rawDescription: Can I store objects in Python class members?

description: Store objects in Python class members


code:
import json
import requests

def myFunction(item):
    # do something here
    print item['paper_item_id']
    pass

json_obj = requests.get('http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json').json()

for item in json_obj:
    if 'is_bait' in item and item['is_bait'] == "1":
        # item['is_bait'] == "1", in case you ever get is_bait = "0" in your json response.
        print item['paper_item_id']
        continue
    else:
        myFunction(item)

rawDescription: Extract JSON attributes using Python and filter out some data


code:
import Tkinter as tk

lists = [1,2,3,4,5,6,7]

class selects():

    def __init__(self,root):
        self.root = root
        self.selectwin()

    def selectwin(self):
        """ listbox and scrollbar for selection """
        sb = tk.Scrollbar(self.root)
        lb = tk.Listbox(self.root, relief ='sunken', cursor='hand2')
        sb.config(command=lb.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        lb.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        lb.config(yscrollcommand=sb.set, selectmode='single')
        for value in lists: lb.insert(tk.END,value)

        lb.bind('<Double-1>',lambda event: self.getvalue())
        self.listbox = lb

    def getvalue(self):
        """ get the selected value """
        value = self.listbox.curselection()
        if value:
            self.root.quit()
            text = self.listbox.get(value)
            self.selectvalue = int(text)
            self.root.destroy() # destroy the Toplevel window without needing the Tk mainloop

    def returnvalue(self):
        return self.selectvalue

class do():

    def __init__(self, master):
        self.top = tk.Toplevel()
        self.top.transient(master) # Make Toplevel a subwindow ow the root window
        self.top.grab_set() # Make user only able to interacte with the Toplevel as long as its opened
        self.sl = selects(self.top)
        self.top.protocol("WM_DELETE_WINDOW", self.sl.getvalue) # use the if value: in getvalue to force selection
        master.wait_window(self.top) # Wait until the Toplevel closes before continuing

        # do something... for example, get the value and print value+2, as coded below
        value = self.sl.returnvalue()
        print value+2

if __name__ == '__main__':
    root = tk.Tk()
    d = do(root)
    root.mainloop()

rawDescription: Communicate classes via tkinter's bind method


code:
import numpy as np
df = DataFrame({
'k1': ['na'] * 3 + ['two'] * 4,
'k2': [1, 'na', 2, 'na', 3, 4, 4]})

print df

df = df.replace('na', np.nan)

print df

rawDescription: Converting Pandas Dataframe types

description: Converting Pandas Dataframe types


code:
from collections import defaultdict

counts = defaultdict(int)
with open('filename.txt', 'r') as f:
  for line in f:
    info = line.split('(')[0]
    counts[info] += 1

for c in counts:
  print '%s %d time(s).' % (c, counts[c])

rawDescription: How to count the amount of times a substring is in a csv file using python

description: Count the amount of times a substring is in a csv file using python


code:
tmp_vis = []

frame_tracker = []

while True:
  for i in xrange(8):
     rets, frame = cap[i].read()
     try:
       tmp_vis.append(cv2.resize(frame, (self.w, self.h)))
     except:
       continue

  print "\nbreak"

  frame_tracker.append(tmp_vis)

  print hashlib.sha1(frame_tracker[0][0].view(np.uint8)).hexdigest()

  if len(frame_tracker) > 1:
    print hashlib.sha1(frame_tracker[1][0].view(np.uint8)).hexdigest()

  if len(frame_tracker) > 2:
    print hashlib.sha1(frame_tracker[2][0].view(np.uint8)).hexdigest()

rawDescription: Having issues with mutable default values in python


code:
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('lensfun_cut.jpg',0)

# Adaptive threshold to detect rectangles independent from background illumination
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,31,5)

# Detect contours
_, contours, hierarchy = cv2.findContours( th3.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

# Draw contours
h, w = th3.shape[:2]
vis = np.zeros((h, w, 3), np.uint8)
cv2.drawContours( vis, contours, -1, (128,255,255), 3)

# Print Features of each contour and select some contours
contours2=[]
for i, cnt in enumerate(contours):
    cnt=contours[i]
    M = cv2.moments(cnt)

    if M['m00'] != 0:
        # for definition of features cf http://docs.opencv.org/3.1.0/d1/d32/tutorial_py_contour_properties.html#gsc.tab=0
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        area = cv2.contourArea(cnt)
        x,y,w,h = cv2.boundingRect(cnt)
        aspect_ratio = float(w)/h
        rect_area = w*h
        extent = float(area)/rect_area

        print i, cx, cy, area, aspect_ratio, rect_area, extent

        if area < 80 and area > 10:
            contours2.append(cnt)

#Draw selected contours
h, w = th3.shape[:2]
vis2 = np.zeros((h, w, 3), np.uint8)
cv2.drawContours( vis2, contours2, -1, (128,255,255), 3)

titles = ['Original Image', 'Adaptive Gaussian Thresholding', 'Contours', 'Selected Contours']
images = [img, th3, vis, vis2]
for i in xrange(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

rawDescription: find rectangles in image, preferably with skimage

description: Find rectangles in image, preferably with skimage


code:
from datetime import datetime

strdate = ["6/4/2014 12:55:36 AM", "2014-06-04 6:27:55 PM"]

def get_date_format(text):
    date_formats = (
        '%d/%m/%Y %H:%M:%S %p',
        '%Y-%m-%d %H:%M:%S %p'
    ) # <--- adjust as necessary
    for date_format in date_formats:
        try:
            datetime.strptime(text, date_format)
            return lambda L: datetime.strptime(L, date_format)
        except ValueError:
            pass
    raise ValueError("No suitable formats found")

for item in strdate:
    formatter = get_date_format(item)
    print formatter(item)

# 2014-04-06 12:55:36
# 2014-06-04 06:27:55

rawDescription: getting the format of a string date

description: Getting the format of a string date


code:
from itertools import combinations

final=set()

with open('keywords.txt') as file:
    for line in file:
        words=line.strip().split()
        for i in range(2,len(words)):
            for j in combinations(words,i):
                final.add(' '.join(j))

print '\n'.join(final)

rawDescription: How to generate all combinations from a list of keywords?

description: Generate all combinations from a list of keywords


code:
def main():
    print "This is main"

if __name__ == "__main__":
    main()

rawDescription: Understanding "def main" and "overloading" in Python


code:
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function

def main():
    code = compile('x = (5*y + 8) if z<3 else (4*y+9)', '<main>', 'exec')
    namespace = {'y': 10, 'z': 8}
    exec code in namespace
    print(namespace['x'])

if __name__ == '__main__':
    main()

rawDescription: Evaluating a member in an evaluated mathematical expression using python


code:
submit_btn = Button(top, text="Submit", width=10, command=check_vincent)

def check_vincent():
    if username.get() == "Vincent":
        print "Hi, Vincent!"
    else:
        print "Where's Vincent?"

rawDescription: Checking value of Tkinter Entry widget

description: Checking value of Tkinter Entry widget


code:
import requests
r = requests.get('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=123&client_secret=XXX')
access_token = r.text.split('=')[1]
print access_token

rawDescription: How to connect to Facebook Graph API from Python using Requests if I do not need user access token?

description: Connect to Facebook Graph API from Python using Requests if I do not need user access token


code:
import random
import string

def random_strings(n):
    strings = set()
    while len(strings) < n:
        strings.add(''.join(random.choice(string.ascii_uppercase) for _ in xrange(2)))
    return list(strings)

print random_strings(4)

rawDescription: generate unique and random list of string pairs python

description: Generate unique and random list of string pairs python


code:
n = 0
while True:
    y = 8 * 10**n - 64
    if y % 79 == 0:
        x = y / 79
        break
    n += 1

print x
print int("8"+str(x))==8*int(str(x)+"8")

rawDescription: Efficiently solving a letter/number problem in Python


code:
from multiprocessing import Process
import time

def function():
    print "Here is where I am creating the function I need to kill"
    ProcessToKill = Process(target = killMe)
    ProcessToKill.start()
    return ProcessToKill

def killMe():
    while True:
        print "kill me"
        time.sleep(0.5)

if __name__ == '__main__':
    Process1 = function()
    time.sleep(5)
    Process1.terminate()

rawDescription: Killing a process launched from a process that has ended - Python


code:
def __getitem__(self, index):
   row, col = index
   if isinstance(row, int) and isinstance(col, (int, slice)):
      return self._Cells[row][col]
   elif isinstance(row, slice) and isinstance(col, (int, slice)):
      return [r[col] for r in self._Cells[row]]
   else:
      raise TypeError, "Invalid argument type"

rawDescription: __getitem__ with slices on a list of lists


code:
#!/usr/bin/env python
import hashlib
import sys

def main():
    if len(sys.argv) < 2:
        print "[ + ] Usage: %s <hash>" % sys.argv[0]
        sys.exit(0)

    commonStrings = [
        "Diaa",
        "Diab",
        "Mohammad",
        "test",
        "7amama",
        "sos",
        "lolo",
        "hacked",
        "try",
        "a_diaa_2007@yahoo.com",
        "secgeek",
        "lnxg33k",
        "diaa.diab.2012@gmail.com",
        "dia2diab@yandex.com",
        "dia2diab@yahoo.com"
    ]

    for i in commonStrings:
        if hashlib.md5(i).hexdigest() == sys.argv[1]:
            print "[ + ] OK i got it."
            print "[ + ] The hash value [ %s ] is the md5 of [ %s ]." % (sys.argv[1], i)
            sys.exit(0)

    print "[ ! ] The hash not found on your own list."

if __name__ == "__main__":
    main()

rawDescription: IndentationError: expected an indented block help please


code:
import matplotlib.pyplot as plt
fig = plt.figure()
def onclick(event):
    if event.dblclick:
         print event.button

connection_id = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

rawDescription: How can I detect double click events in matplotlib?

description: Detect double click events in matplotlib


code:
one, two, three = False, False, False
print "before:", one, two, three  # before: False False False
num = "two"
eval("globals().update({%r: True})" % num)
print " after:", one, two, three  #  after: False True False

rawDescription: How to use eval instead if else in python

description: Use eval instead if else in python


code:
#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk

class ComboBoxExample:
    def __init__(self):
        window = gtk.Window()
        window.connect('destroy', lambda w: gtk.main_quit())
        combobox = gtk.combo_box_new_text()
        window.add(combobox)
        combobox.append_text('Select a pie:')
        combobox.append_text('Apple')
        combobox.append_text('Cherry')
        combobox.append_text('Blueberry')
        combobox.append_text('Grape')
        combobox.append_text('Peach')
        combobox.append_text('Raisin')
        combobox.connect('changed', self.changed_cb)
        combobox.set_active(0)
        window.show_all()
        return

    def changed_cb(self, combobox):
        model = combobox.get_model()
        index = combobox.get_active()
        if index:
            print 'I like', model[index][0], 'pie'
        return

def main():
    gtk.main()
    return

if __name__ == "__main__":
    bcb = ComboBoxExample()
    main()

rawDescription: Python GTK adding signal to a combo box

description: Python GTK adding signal to a combo box


code:
number=int(raw_input("enter the number:"))
power=2
root=0

for power in range(6):
    while root**power < abs(number):
        root=root+1
        if root**power == abs(number):
            if number < 0:
                if power % 2 == 1:  # Note a change here,
                                    # you won't get negative number with even power
                    root = -root
                    print 'root=',root
                    print 'power=',power
                    break
            else:
                print 'root=',root
                print 'power=',power
                break
    if root**power == number:  # Make sure we break "for" too
        break
else:
    print "No such number"

rawDescription: how to find root**power=number and print out "cannot find the number" message?

description: Find root**power=number and print out "cannot find the number" message


code:
class oObject (object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return str(self.value)
    def __add__(self,val):
        return str(self.value)+val

new = oObject(50)
'''if I use print it's Okay'''
print new
'''But if i try to do something like that ...'''
print new + '.kine'   #prints 50.kine

rawDescription: About class and __str__

description: About class and __str__


code:
test = "1$%a"
print not test.isalnum()
# returns true

rawDescription: Is there a way to check against all special characters?


code:
def findRegion(lat, lon):
    regions = ( ('A', 'B', 'C', 'D'), ('E', 'F', 'G', 'H'), ('I', 'J', 'K', 'L'), ('M', 'N', 'O', 'P'))

    lat_index = 0;
    if lat >= 50:
        lat_index = 0
    elif lat >= 0:
        lat_index = 1
    elif lat <= -50:
        lat_index = 2
    else:
        lat_index = 3

    lon_index = 0
    if lon <= -90:
        lon_index = 0
    elif lon <= 0:
        lon_index = 1
    elif lon_index <= 90:
        lon_index = 2
    else:
        lon_index = 3

    return regions[lat_index][lon_index]

print findRegion(-45, 50)

rawDescription: Fastest way to identify area from 2D coordinates


code:
class mywords:
    def __init__(self, a):
        self.words = a
        self.length = map(lambda w: len(w), a)
    def append(self, string):
        self.words.append(string)
        self.length.append(len(string))

a = mywords(['A', 'list', 'of', 'words'])

a.append("this")
print a.words
print a.length

rawDescription: Is it possible to synchronize lists in Python?


code:
import math

def get_power_law_variables(data):
    c = data[0]
    middle_index = len(data) / 2
    division = float(data[middle_index]) / c
    logarithm_base = middle_index + 1
    a = math.log(division, logarithm_base)
    return c, a

# Example usage
data = range(50, 150)
c, a = get_power_law_variables(data)
print c, a

rawDescription: Solving Power Law Distribution in Python


code:
from Tkinter import *
class GraphicsInterface:

    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        self.clicked=[]
        button1 = Button(self.window, text="Dice 1", width=13)
        button2 = Button(self.window, text="Dice 2", width=13)
        button1.pack()
        button2.pack()

        button1.configure(command=lambda btn=button1: self.OnClick(btn))
        button2.configure(command=lambda btn=button2: self.OnClick(btn))

        self.window.mainloop()

    def OnClick(self, btn):
        text = btn.cget("text")
        self.clicked.append(text)
        print "clicked:", self.clicked

app = GraphicsInterface()

rawDescription: Working on a way to return the text of a button after the button is clicked in tkinter


code:
for idx, item in enumerate(color):
    print 'I am %s' % item
    rest = color[:idx] + color[idx+1:]
    print 'Rest is %s' % ','.join(rest)

rawDescription: retrieving the elements from list: python

description: Retrieving the elements from list: python


code: string_stuff = re.sub(ur'#\s?([0-9]+)', 'NUMBER \1', string_stuff)

rawDescription: Python regex with special character, optional space and any amount of numbers


code:
string = open('file.txt').read()

for word in string.split():
    print len(word)

rawDescription: Python world length count from a text file


code:
try:
    from maya import cmds
except ImportError:
    print 'Not Maya'

rawDescription: Determine if PyQt is running within Maya


code:
from PyQt4  import QtGui
from PyQt4  import QtCore
from PyQt4  import uic
import sys

FORM_1, BASE_1 = uic.loadUiType(r"C:/mydesign.ui")

APP = QtGui.QApplication(sys.argv)

class MyApp(FORM_1, BASE_1):
    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        self.setupUi(self)

        self.connect(self.btn_add, QtCore.SIGNAL("released()"), self.do_something)

    def do_something(self):
        print "working"

FORM = MyApp()
FORM.show()
APP.exec_()

rawDescription: Call functions in PyDev Eclipse in form generated by Qt Designer


code:
from xml.etree import ElementTree as etree
corpus = """<typeBoxes>
    <typeBox type="counter">
        <text fontSize="140">123456</text>
        <text fontSize="26">Foobar</text>
        <incrementTextFieldNum>1</incrementTextFieldNum>
        <timing>1</timing>
        <increment>1</increment>
    </typeBox>
    <typeBox>
        <image>images/foo.png</image>
        <text fontSize="26">Foo</text>-->
    </typeBox>
</typeBoxes>"""

doc = etree.fromstring(corpus)

for typeBox in doc.findall('typeBox'):
    if typeBox.attrib.get('type') == 'counter':
        fieldnum = int(typeBox.find('incrementTextFieldNum').text)
        incr = int(typeBox.find('increment').text)
        text_field = typeBox.findall('text')[fieldnum-1]
        text_field.text = str(int(text_field.text) + incr)

print etree.tostring(doc)

rawDescription: Parsing XML with minidom

description: Parsing XML with minidom


code:
word="timer"
print list(word).reverse()
word[::-1]
"".join(reversed(word))

rawDescription: Using sets in a list comprehension

description: Using sets in a list comprehension


code:
bigList = [1, (1, 2), {(3,9): [4, 5]}, [{6: 7} , 8]]
linear_dict = dict()

def nestedList(l, index = None, break_tuple = False):
    for count, item in enumerate(l):
        if type(item) is list:
            nestedList(item, index if index else count)
        elif type(item) is dict:
            nestedList(item.iteritems(), index if index else count, True)
        elif type(item) is tuple and break_tuple:
            nestedList(list(item), index)
        else:
            linear_dict[item] = index if index else count

nestedList(bigList)
print linear_dict

{(1, 2): 1, 1: 0, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, (3, 9): 2}

rawDescription: Convert hybrid nested list into linear dict


code:
import time

class MyObj(object):
    def __init__(self):
        self.start_time = time.time()

    def get_time_elapsed(self):
        return time.time() - self.start_time

m = MyObj()
print m.get_time_elapsed()

rawDescription: Get object value outside of class?

description: Get object value outside of class


code:
#capture the nearby zips in a new dict
near_zips={}
for x in matched:
    longRad1= getLongRad(matched[x]['longitude'])
    latRad1= getLatRad(matched[x]['latitude'])
    dlon = longRad2 - longRad1
    dlat = latRad2 - latRad1
    a = math.sin(dlat/2)**2 + math.cos(latRad1) * math.cos(latRad2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    m = 3960 * c
    if m <thresh: # cant figure out how to return zipcodes instead of m value
        #add the nearby zipcodes to the dict
        print '%f < %f' % (m,thresh)
        print 'adding %s to near_zips' % (x,)
        near_zips[x] = matched[x]

#return the nearby zips
return near_zips

rawDescription: printing out dictionary values after filtering through it

description: Printing out dictionary values after filtering through it


code:
import mechanize
import lxml.html

br = mechanize.Browser()
response = br.open("somewebsite")

for link in br.links():
    print link
    br.follow_link(link)  # takes EITHER Link instance OR keyword args
    print br
    br.back()

# you can also display the links with lxml
html = response.read()
root = lxml.html.fromstring(html)
for link in root.iterlinks():
    print link

rawDescription: Crawler with Python?

description: Crawler with Python


code:
from instagram.client import InstagramAPI

access_token = "YOUR_ACCESS_TOKEN" # get this from instagram
client_secret = "YOUR_CLIENT_SECRET" # this, too, from instagram
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
recent_media, next_ = api.user_recent_media(user_id="userid", count=10)
for media in recent_media:
    print media.caption.text

rawDescription: Error logging into instagram with python


code:
lst = range(1, 149)
lst = [lst[i:i+13] for i in xrange(0, len(lst), 13)]
lst = zip(*[lst[i] + lst[i+4] + lst[i+8] for i in xrange(4)])

for row in lst:
    for col in row:
        print col,
    print

rawDescription: Printing a rather specific matrix

description: Printing a rather specific matrix


code:
class TestClass(object):
    def __init__(self):
        pass

    @property
    def get_data1_from_db(self):
        data= {'1_testkey':'1_testvalue',"1_testkey2":"1_testvalue2"}
        return data.values()

    @property
    def get_data2_from_db(self):
        data= {'2_testkey':'2_testvalue',"2_testkey2":"2_testvalue2"}
        return data.values()

testcase = TestClass()
print testcase.get_data1_from_db  # ['1_testvalue', '1_testvalue2']
print testcase.get_data2_from_db  # ['2_testvalue', '2_testvalue2']

rawDescription: How to format output of methods inside of a class in an efficient way?

description: Format output of methods inside of a class in an efficient way


code:
import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

rawDescription: Set external inputs in python program

description: Set external inputs in python program


code:
from z3 import *

def str2array(a):
    """
    Convert a string into a list of Z3 bit-vector values of size 8
    """
    return [ BitVecVal(int(a[x].encode('hex'), 16), 8) for x in range(len(a)) ]

a = str2array("\xff\x33\x01\x88\x02\x11\x03\x55")
# 'a' is a list of Z3 bitvector constants.
print "a:", a
# The elements of 'a' may look like Python integers but they are Z3 expressions.
# We can use the method sexpr() to get these values in SMT 2.0 syntax.
print [ a_i.sexpr() for a_i in a ]

# b is a Z3 symbolic variable.
b = BitVec('b', 8)

# We compute a list 'c' of Z3 expressions from 'a' and 'b'.
# We use Python list comprehensions but we can also use a for-loop.
c = [ a_i ^ b for a_i in a ]

print "c:", c

second = '\x23\x23'
# We convert 'second' in a Z3 bit-vector value of size 16
second = BitVecVal(int(second.encode('hex'), 16), 16)
print "second:", second

# The Z3 operation Concat concatenates two or more bit-vector expressions.
d = []
x = 0
while x < len(c):
    # c[x] is a Bit-vector of size 8, second is a Bit-vector of size 16.
    # In Z3, we have to do the "casting" ourselves.
    # We use ZeroExt(8, c[x]) to convert c[x] into a Bit-vector of size 16,
    # by adding 0-bits.
    d.append(ZeroExt(8, c[x]) ^ second)
    x += 2
print "d:", d

goal = str2array('\xbd\x23\x43\x23\x40\x23\x41\x23')
print "goal:", goal
# Note that, len(goal) == 2*len(d)
# We can use Concat to concatenate adjacent elements.

# We want each element of d[i] == Concat(goal[2*i], goal[2*i+1])
# We can use Z3 to find the 'b' that will satisfy these constraints

s = Solver()
# 's' is a Z3 solver object
i = 0
while i < len(d):
    s.add(d[i] == Concat(goal[2*i+1], goal[2*i]))
    i += 1
print s
# Now, 's' contains a set of equational constraints.
print s.check()
print s.model()

rawDescription: Learning Z3py - Is there support for arrays and loops


code:
with open('tester_everything.txt') as f:
    mylist = []
    other_list = []
    for lines in f:
        if lines == '\n':
            mylist.append(other_list)
            other_list = []
        else:
            other_list.append(lines)
    print mylist

rawDescription: Python reading chunks of text

description: Python reading chunks of text


code:
#!/usr/bin/python
import sys
import os
import signal
import subprocess as sp

try:
    if(len(sys.argv) < 2):
        print "Choose an EngineID!"
    engineID = sys.argv[1]

    logdir='/data/work/silverlocal-%s/log' % engineID
    logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('log-%s' % engineID)])
    lastlog = (logdir + "/" + logfiles[-1])

    old_action = signal.signal(signal.SIGINT, signal.SIG_IGN)
    os.spawnlpe(os.P_WAIT, 'less', 'less', '+F', (lastlog), os.environ)
    signal.signal(signal.SIGINT, old_action)    # restore old signal disposition
except KeyboardInterrupt:
    pass

print("I'm still running!")

rawDescription: Python shell script open less with +F option


code: print "Too fast! The fine is ${0}".format((clocked - limit) * 5 + 50)

rawDescription: removing space from output Python 2.7

description: Removing space from output Python 2.7


code:
import psutil
for p in psutil.process_iter():
    print p.name

rawDescription: Inform OS of installation

description: Inform OS of installation


code:
from Tkinter import *
from tkFileDialog import *
import os.path
import shutil
import sys
import tempfile
from zipfile import ZipFile
import subprocess

class uiclass():
    def __init__(self,root):
        b = Button(root, text="Browse", command=self.callback)
        w = Label(root, text="Please choose a .pages file to convert.")
        w.pack()
        b.pack()

    def callback(self):
        print "click!"
        global y
        y = askopenfilename(parent=root, defaultextension=".pages")
        self.view_file(y)

    def view_file(self,filepath):
        subprocess.Popen(filepath, shell=True).wait()

        PREVIEW_PATH = 'QuickLook/Preview.pdf'  # archive member path
        #pages_file = raw_input('Enter the path to the .pages file in question: ')
        pages_file = y
        pages_file = os.path.abspath(pages_file)
        filename, file_extension = os.path.splitext(pages_file)
        if file_extension == ".pages":
            tempdir = tempfile.gettempdir()
            temp_filename = os.path.join(tempdir, PREVIEW_PATH)
            with ZipFile(pages_file, 'r') as zipfile:
                zipfile.extract(PREVIEW_PATH, tempdir)
            if not os.path.isfile(temp_filename):  # extract failure?
                sys.exit('unable to extract {} from {}'.format(PREVIEW_PATH, pages_file))
            final_PDF = filename + '.pdf'
            shutil.copy2(temp_filename, final_PDF)  # copy and rename extracted file
            # delete the temporary subdirectory created (along with pdf file in it)
            shutil.rmtree(os.path.join(tempdir, os.path.split(PREVIEW_PATH)[0]))
            print('Check out the PDF! It\'s located at "{}".'.format(final_PDF))
            self.view_file(final_PDF) # see Bonus below
        else:
            sys.exit('Sorry, that isn\'t a .pages file.')

if __name__ == '__main__':
    root = Tk()
    uiclass(root)
    root.wm_title("Pages to PDF")
    root.mainloop()

rawDescription: Running `mainloop()` in its own thread or process?


code:
frames = []
peaks = []

for row in csv_dic:
    frames.append(row[0])
    peaks.append(row[1])
    for column in row:
        print column, "***",   #I can print out the column
    print

rawDescription: Python: reading in a csv file and saving columns as variables


code:
i = inspect(model)
for relation in i.relationships:
        print relation.direction.name
        print relation.remote_side
        print relation._reverse_propery
        dir(relation)

rawDescription: SqlAlchemy: Inspect/Reflect information about relationship


code:
l = [1, 2, 3]

it = iter(l)
while True:
    try:
        print next(it)
    except StopIteration:
        break

rawDescription: writing python for loops as while?

description: Writing python for loops as while


code:
class Box(object):

    things = []

class BoxManager(object):

    def __set__(self, instance, value):
        if isinstance(value, Box):
            instance._box = value
            Box.things.append(instance)

    def __get__(self, instance, type_=None):
        return instance._box

class Thing(object):
    box = BoxManager()

thing = Thing()
box = Box()

# thing.box updates the box.things
thing.box = box
print 'Thing is in box.things', thing in box.things  # should be true

# box.things updates thing.box
box.things.append(thing)
thing.box == box  # should be true
print 'thing.box == box is', thing.box == box

import pdb
pdb.set_trace()

rawDescription: How to implement object properties in two directions

description: Implement object properties in two directions


code:
#!/usr/bin/python

import csv

with open('Inschool.csv') as f:
    reader =  csv.reader(f)
    in_school = list(reader)

with open('notinschool.csv') as f:
    reader =  csv.reader(f)
    not_in_school = list(reader)

for grade, name, status, hr_teacher in not_in_school:
    print grade, name, status, hr_teacher
for grade, name, status, hr_teacher in in_school:
    print grade, name, status, hr_teacher

iFile = open('Inschool.csv',)
reader = csv.reader(iFile)
IFILE = open('notinschool.csv')
READER = csv.reader(IFILE)
oFile = open('combined.csv','wb')
writer_a = csv.writer(oFile, delimiter='|', quoting=csv.QUOTE_ALL)
writer_b = csv.writer(oFile, delimiter='|', quoting=csv.QUOTE_ALL, lineterminator="\n\n\n\n")

for row in READER:
     writer_a.writerow(row)

writer_b.writerow([])

for row in reader:
     writer_b.writerow(row)

rawDescription: How to insert 3 blank lines in python after each grade

description: Insert 3 blank lines in python after each grade


code:
entrys = Entry.objects.all().prefetch_related('color_set')

for e in entrys:
    print e.color_set.all()

rawDescription: how to efficiently use _set.all() in django?

description: Efficiently use _set.all() in django


code:
list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]

print ''.join([str(a) + b for a,b in zip(list1,list2)])

rawDescription: Combining two lists to string

description: Combining two lists to string


code:
sum = 0.0
count = 0
while True:
    inp = raw_input('Enter a number: ')
    if inp == 'done':
        break
    try:
        sum += int(inp)
        count += 1
    except ValueError:
        print 'Invalid input'
print sum
print count
if count != 0:  # Avoid division by zero
    print sum / count

rawDescription: Loop that uses try/except for input and loops until 'done' is entered


code:
from Tkinter import *
from tkFileDialog import askopenfilename
from tkMessageBox import *

app = Tk()
app.title("Picture Formatting")
app.geometry('500x350+200+200')

#
def callback():
    global chart_path
    chart_path = askopenfilename()
    return

def title_data():
    title_data = chart_title
    return

def calculate():
    chart_title = title.get()
    chart_subtitle = subtitle.get()
    chart_source = source.get()
    chart_sample_size = sample_size.get()

    print "chart_path : ", chart_path
    print "chart_title : ", chart_title
    print "chart_subtitle : ", chart_subtitle
    print "chart_source : ", chart_source
    print "chart_sample_size : ", chart_sample_size

    #Call your functions here

    return

errmsg = 'Error!'

# Get chart data

chart_path = ''
browse_botton = Button(app, text="Choose png", width=15, command=callback)
browse_botton.pack(side='top', padx=15, pady=15)

chart_title = StringVar()
title = Entry(app, textvariable = chart_title)
title.pack(padx=15, pady=15)

chart_subtitle = StringVar()
subtitle = Entry(app, textvariable = chart_subtitle)
subtitle.pack(padx=15, pady=15)

chart_source = StringVar()
source = Entry(app, textvariable = chart_source)
source.pack(padx=15, pady=15)

chart_sample_size = IntVar()
sample_size = Entry(app, textvariable = chart_sample_size)
sample_size.pack(padx=15, pady=15)

submit_button = Button(app, text="Submit", width=15, command=calculate)
submit_button.pack(side='bottom', padx=15, pady=15)

app.mainloop()

rawDescription: Pass values to python script with Tkinter


code:
class MixInClass1(object):
    def __init__(self):
        self.__old_method1,self.method1=self.method1,self.__method1
        super(MixInClass1, self).__init__()
    def __method1(self):
        print "pre1()"
        self.__old_method1()
        print "post1()"

class MixInClass2(object):
    def __init__(self):
        super(MixInClass2, self).__init__()
    def method1_hook(self):
        print('MixIn method1')

class Foo(MixInClass2,MixInClass1):
    def method1(self):
        print "do_something()"
        getattr(self,'method1_hook',lambda *args,**kw: None)()
        print "do_more()"

foo=Foo()
foo.method1()

rawDescription: What are the elegant ways to do MixIns in Python?


code:
from itertools import groupby
import csv, operator, itertools
with open('trial.csv', 'rb') as f:
    reader = csv.reader(f)
    sortedlist = list(reader)
    things= sorted(sortedlist, key=operator.itemgetter(0), reverse=True)
    things.sort()
    things = list(k for k,_ in itertools.groupby(things))

for key, group in groupby(things, lambda x: x[0]):
    listOfThings = len(",".join([thing[1] for thing in group if not thing in things[1]]).split(","))
    print key + "," + str(listOfThings)

rawDescription: Python: Itertools groupby for unique key value pairs


code:
def merge_sort(list_a):
    mid = len(list_a) // 2
    print('Mid is ', mid)
    if len(list_a) > 1:
        left = list_a[:mid]
        print('Left is now ', left)
        right = list_a[mid:]
        print('Right is now ', right)
        merge_sort(left)
        merge_sort(right)
        return merge(list_a, left, right)

def merge(comb_list, list_a, list_b):
    print('Starting the merge.')
    a1, b1, c1 = 0, 0, 0
    na, nb, nc = len(list_a), len(list_b), len(comb_list)
    while a1 < na and b1 < nb:
        if list_a[a1] < list_b[b1]:
            print('Adding from A')
            comb_list[c1] = list_a[a1]
            a1 += 1
        else:
            print('Adding from B')
            comb_list[c1] = list_b[b1]
            b1 += 1

        c1 += 1

    while len(list_a)>a1:
        comb_list[c1] = list_a[a1]
        del list_a[a1]
        c1 += 1
        a1 += 1

    while len(list_b)>b1:
        comb_list[c1] = list_b[b1]
        c1 += 1
        b1 += 1

if __name__ == '__main__':
    list_a = [54,26,93,17,77,31,44,55,20]
    merge_sort(list_a)
    print list_a

rawDescription: Difficulty with merge sort algorithm

description: Difficulty with merge sort algorithm


code:
#!/usr/bin/env python
#
# pyGrr!
#
# This code was originally found @
# http://www.cocoaforge.com/viewtopic.php?f=6&t=13359&p=91992&hilit=pyobjc+growl
# It is (to the best of our knowledge) the work of user 'tooru' on the same
# website.
#
# I make no claim to this code, all I did was get it working with PyObjC on Lion
# reformatted it a bit and added some more verbose explanations of what the script
# does. To be honest, I haven't touched pyobjc in a couple years and I was amazed
# that it still works! Even more amazed that I was able to get this example working
# in about 20 minutes.
#
# Great job tooru!
#
#   I have verified this code works with the following combination of
#   packages / versions
#
#   * OSX Lion 10.7.3
#   * Python 2.7
#   * Growl 1.3
#   * Growl SDK 1.3.1
#
#
# - Nathan Ramella nar@hush.com (http://www.remix.net)
##################################################################################

import objc
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
import time
import sys
import os

myGrowlBundle = objc.loadBundle(
  "GrowlApplicationBridge",
  globals(),
  bundle_path = objc.pathForFramework(
    '/Library/Frameworks/Growl.framework'
  )
)

class MenuMakerDelegate(NSObject):

  """
  This is a delegate for Growl, a required element of using the Growl
  service.

  There isn't a requirement that delegates actually 'do' anything, but
  in this case, it does. We'll make a little menu up on the status bar
  which will be named 'pyGrr!'

  Inside the menu will be two options, 'Send a Grr!', and 'Quit'.

  Send a Grr! will emit a growl notification that when clicked calls back
  to the Python code so you can take some sort of action - if you're that
  type of person.
  """

  statusbar = None
  state = 'idle'

  def applicationDidFinishLaunching_(self, notification):

    """
    Setup the menu and our menu items. Getting excited yet?
    """

    statusbar = NSStatusBar.systemStatusBar()
    # Create the statusbar item
    self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength)

    self.statusitem.setHighlightMode_(1)  # Let it highlight upon clicking
    self.statusitem.setToolTip_('pyGrr!')   # Set a tooltip
    self.statusitem.setTitle_('pyGrr!')   # Set an initial title

    # Build a very simple menu
    self.menu = NSMenu.alloc().init()
    menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
      'Send a Grr!',
      'rcNotification:',
      ''
    )
    self.menu.addItem_(menuitem)

    # Default event
    menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
      'Quit',
      'terminate:',
      ''
    )
    self.menu.addItem_(menuitem)

    # Bind it to the status item
    self.statusitem.setMenu_(self.menu)

  def rcNotification_(self,notification):

    """
    This is run when you select the 'Send a Grr!' menu item. It
    will lovingly bundle up a Grr and send it Growl's way.
    """

    print "Sending a growl notification at", time.time()

    GrowlApplicationBridge.notifyWithTitle_description_notificationName_iconData_priority_isSticky_clickContext_(
      "Grr! - I'm a title!",
      "This is where you put notification information.",
      "test1",
      None,
      0,
      False,
      "this ends up being the argument to your context callback"
    )

class rcGrowl(NSObject):

  """
  rcGrowl registers us with Growl to send out Grrs on behalf
  of the user and do 'something' with the results when a
  Grr has been clicked.

  For additional information on what the what is going on
  please refer to the growl dox @

  http://growl.info/documentation/developer/implementing-growl.php
  """

  def rcSetDelegate(self):
    GrowlApplicationBridge.setGrowlDelegate_(self)

  def registrationDictionaryForGrowl(self):

    """
    http://growl.info/documentation/developer/implementing-growl.php#registration
    """

    return {
      u'ApplicationName'    :   'rcGrowlMacTidy',
      u'AllNotifications'   :   ['test1'],
      u'DefaultNotifications' :   ['test1'],
      u'NotificationIcon'   :   None,
    }

  # don't know if it is working or not
  def applicationNameForGrowl(self):
    """
    Identifies the application.
    """
    return 'rcGrowlMacTidy'

  #def applicationIconDataForGrowl(self):
    """
    If you wish to include a custom icon with the Grr,
    you can do so here. Disabled by default since I didn't
    want to bloat up this up
    """
    #icon = NSImage.alloc().init()
    #icon = icon.initWithContentsOfFile_(u'remix_icon.tiff')
    #return icon

  def growlNotificationWasClicked_(self, ctx):

    """
    callback for onClick event
    """
    print "we got a click! " + str(time.time()) + " >>> " + str(ctx) + " <<<\n"

  def growlNotificationTimedOut_(self, ctx):

    """
    callback for timing out
    """
    print "We timed out" + str(ctx) + "\n"

  def growlIsReady(self):

    """
    Informs the delegate that GrowlHelperApp was launched
    successfully. Presumably if it's already running it
    won't need to run it again?
    """
    print "growl IS READY"

if __name__ == "__main__":

  # Both 'growlnotify' and this script seem to have the following
  # error after emitting a Grr!
  #
  # Error Domain=GCDAsyncSocketErrorDomain Code=4 "Read operation timed out"
  # UserInfo=0x7fa444e00070 {NSLocalizedDescription=Read operation timed out}
  #
  # So, we redirect stderr to /dev/null so that it doesn't muck up
  # the output of this script. Some folks say upgrading Growl fixes it,
  # others still have the problem. Doesn't seem to make much of a difference
  # one way or another, things still seem to work regardless.

  fp = os.open('/dev/null', os.O_RDWR|os.O_CREAT, 0o666)
  dupped = os.dup(2)
  os.dup2(fp, 2)

  # set up system statusbar GUI
  app = NSApplication.sharedApplication()
  delegate = MenuMakerDelegate.alloc().init()
  app.setDelegate_( delegate )

  # set up growl delegate
  rcGrowlDelegate=rcGrowl.new()
  rcGrowlDelegate.rcSetDelegate()
  AppHelper.runEventLoop()

rawDescription: Growl Python binding with Click feedback?


code:
import re

result = re.match("\{\{((if|else|endif).*?)\}\}","{{if 100 > 1}}",re.I)
print result.groups()

result = re.match("\{\{((if|else|endif).*?)\}\}","{{else}}",re.I)
print result.groups()

result = re.match("\{\{((if|else|endif).*?)\}\}","{{endif}}",re.I)
print result.groups()

rawDescription: Searching strings with Python

description: Searching strings with Python


code:
files = []

try:
    files = ftp.nlst()
except ftplib.error_perm, resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
    else:
        raise

for f in files:
    print f

rawDescription: Using Python's ftplib to get a directory listing, portably


code:
def FileWrite():
    try:
        if os.path.exists("Temp.xml") == True:
            os.remove("Temp.xml")
        root = ET.Element("Refunds")
        tree = ET.ElementTree(root)

        EventDumpCounter = 0

        for Eventes in EventTags:
            try:
                if float(EventCost[EventDumpCounter]) > float(Price[EventDumpCounter]):
                    if "Horse" in EventTags[EventDumpCounter]:
                        Eventes = ET.SubElement(root, "Event", type = EventTags[EventDumpCounter])
                        ET.SubElement(Eventes, "EventTime").text = str(EventTimes[EventDumpCounter])
                        ET.SubElement(Eventes, "EventName").text = str(EventName[EventDumpCounter])
                        ET.SubElement(Eventes, "EventLoc").text = str(EventLoc[EventDumpCounter])
                        ET.SubElement(Eventes, "EventSpace").text = str(EventSpace[EventDumpCounter])
                        ET.SubElement(Eventes, "EventCost").text = str(EventCost[EventDumpCounter])
                        ET.SubElement(Eventes, "EventPrice").text = str(EventPrice[EventDumpCounter])
                        ET.SubElement(Eventes, "EventParking").text = str(EventParking[EventDumpCounter])
                        ET.SubElement(Eventes, "EventDist").text = str(EventDist[EventDumpCounter])
                EventDumpCounter +=1

            except: # bad idea, you just supressed debug info
                # potential problem = since you supress the error and continue
                # processing but EventDumpCounter never advanced, you could
                # get stuck in an infinite error loop.
                print "Problem writing XML"

        tree.write("Temp.xml")

    #except:
    except WindowsError, e:
        print "Problem creating XML 2"
        #e = sys.exc_info()[0]
        print e

rawDescription: XML Write Getting Steadily Slower

description: XML Write Getting Steadily Slower


code:
c = ord(u'\x02') + ord('0')
print chr(c)

rawDescription: python how to convert Special string u'\x08' u'\x09' u'\x03' to 8 9 3

description: Python how to convert Special string u'\x08' u'\x09' u'\x03' to 8 9 3


code:
import urllib, urllib2
url = 'http://httpbin.org/post?cid=42'
headers = {
    'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
    'X-CRFS-Token': 'csrf_token_mocked',
    'X-Requested-With' : 'XMLHttpRequest'
}
values = {}
data    = urllib.urlencode(values)
req     = urllib2.Request(url, data, headers)
req.has_data()
req.get_method()
resp    = urllib2.urlopen(req)
body = resp.read()
print body
from pprint import pprint
import json
pprint(json.loads(body))

rawDescription: How to send POST request with no data

description: Send POST request with no data


code:
import numpy as np
A = np.array([1,5,2,7,1])
print np.argsort(A) #prints [0 4 2 1 3]

rawDescription: Python find index of all array elements in another array


code:
s = r'..\Users\TS\Desktop\Program\Nowy dokument tekstowy - Kopia (2).txt '
s = s.replace('\\', '/')
print s

rawDescription: Python - replace backslash with forward slash (Dropbox aspect)


code: print "I have worked %s hours, %s minutes, and %s seconds" % (hours, minutes, seconds);

rawDescription: printing something that includes text and variables

description: Printing something that includes text and variables


code:
#!/usr/bin/env python

from Crypto.Cipher import AES
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

def step1():
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    print "Step 1: This is my rsa-key:\n%s" % rsaKey.exportKey()

def step2_encrypt(string):
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    pkcs1CipherTmp = PKCS1_OAEP.new(rsaKey)
    encryptedString = pkcs1CipherTmp.encrypt(string)
    print "Step 2: encrypted %s is %s" % (string, encryptedString)
    return encryptedString

def step3_decrypt(encryptedString):
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    pkcs1CipherTmp = PKCS1_OAEP.new(rsaKey)
    decryptedString = pkcs1CipherTmp.decrypt(encryptedString)
    print "Step 3: decryptedString %s is %s" % (encryptedString, decryptedString)
    return decryptedString

if __name__ == "__main__":
    step1()
    encryptedString = step2_encrypt("hello, duuude")
    decryptedString = step3_decrypt(encryptedString)
    print "Tadaaaa: %s" % decryptedString

rawDescription: How to print a public key as string and encrypt with it?

description: Print a public key as string and encrypt with it


code:
x = []
n = 10
for i in range(1, n):
    x.append(i) # you push your element here, as of now I have push i

print x

rawDescription: How to create a dynamic list in Python?

description: Create a dynamic list in Python


code:
list1 = [1,2,3,4,5]
list2=['a', 'b','c', 'a', 'b']

b=list2.count('a')
print b
print

for i, j in enumerate(list2):
    if j == 'a':
        print i,": ", list1[i]

rawDescription: Is there any way to find the index of everything found after using the count function


code:
def chart(occurance_list):
    hour_list = [t.hour for t in occurance_list]
    print hour_list
    numbers=[x for x in xrange(0,24)]
    labels=map(lambda x: str(x), numbers)
    plt.xticks(numbers, labels)
    plt.xlim(0,24)
    plt.hist(hour_list)
    plt.show()

rawDescription: plot histogram of datetime.time python / matplotlib

description: Plot histogram of datetime.time python / matplotlib


code:
import sys
from PyQt4 import QtCore, QtGui

class QCustomTreeWidget (QtGui.QTreeWidget):
    itemMoveOutActivated = QtCore.pyqtSignal(object)
    itemNewMoveActivated = QtCore.pyqtSignal(object)

    def __init__ (self, parent = None):
        super(QCustomTreeWidget, self).__init__(parent)
        self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)

    def dragEnterEvent (self, eventQDragEnterEvent):
        sourceQCustomTreeWidget = eventQDragEnterEvent.source()
        if isinstance(sourceQCustomTreeWidget, QCustomTreeWidget) and (self is not sourceQCustomTreeWidget):
            eventQDragEnterEvent.accept()
        else:
            QtGui.QTreeWidget.dragEnterEvent(self, eventQDragEnterEvent)

    def dropEvent (self, eventQDropEvent):
        sourceQCustomTreeWidget = eventQDropEvent.source()
        if isinstance(sourceQCustomTreeWidget, QCustomTreeWidget) and (self is not sourceQCustomTreeWidget):
            sourceQTreeWidgetItem      = sourceQCustomTreeWidget.currentItem()
            destinationQTreeWidgetItem = sourceQTreeWidgetItem.clone()
            self.addTopLevelItem(destinationQTreeWidgetItem)
            sourceQCustomTreeWidget.itemMoveOutActivated.emit(destinationQTreeWidgetItem)
            self.itemNewMoveActivated.emit(destinationQTreeWidgetItem)
        else:
            QtGui.QTreeWidget.dropEvent(self, eventQDropEvent)

class QCustomQWidget (QtGui.QWidget):
    def __init__ (self, parent = None):
        super(QCustomQWidget, self).__init__(parent)
        self.my1QCustomTreeWidget = QCustomTreeWidget(self)
        self.my2QCustomTreeWidget = QCustomTreeWidget(self)
        self.my1QCustomTreeWidget.itemMoveOutActivated.connect(self.itemMoveOutActivatedCallBack1)
        self.my2QCustomTreeWidget.itemMoveOutActivated.connect(self.itemMoveOutActivatedCallBack2)
        self.my1QCustomTreeWidget.itemNewMoveActivated.connect(self.itemNewMoveActivatedCallBack1)
        self.my2QCustomTreeWidget.itemNewMoveActivated.connect(self.itemNewMoveActivatedCallBack2)
        listsExampleQTreeWidgetItem = [QtGui.QTreeWidgetItem([name]) for name in ['Part A', 'Part B', 'Part C']]
        self.my1QCustomTreeWidget.addTopLevelItems(listsExampleQTreeWidgetItem)
        self.allQHBoxLayout = QtGui.QHBoxLayout()
        self.allQHBoxLayout.addWidget(self.my1QCustomTreeWidget)
        self.allQHBoxLayout.addWidget(self.my2QCustomTreeWidget)
        self.setLayout(self.allQHBoxLayout)

    @QtCore.pyqtSlot(QtGui.QTreeWidgetItem)
    def itemMoveOutActivatedCallBack1 (self, goneQTreeWidgetItem):
        print 'QTreeWidget 1 has move QTreeWidgetItem to Another QTreeWidget'

    @QtCore.pyqtSlot(QtGui.QTreeWidgetItem)
    def itemMoveOutActivatedCallBack2 (self, goneQTreeWidgetItem):
        print 'QTreeWidget 2 has move QTreeWidgetItem to Another QTreeWidget'

    @QtCore.pyqtSlot(QtGui.QTreeWidgetItem)
    def itemNewMoveActivatedCallBack1 (self, newQTreeWidgetItem):
        print 'Another QTreeWidget has move QTreeWidgetItem in QTreeWidget 1'

    @QtCore.pyqtSlot(QtGui.QTreeWidgetItem)
    def itemNewMoveActivatedCallBack2 (self, newQTreeWidgetItem):
        print 'Another QTreeWidget has move QTreeWidgetItem in QTreeWidget 2'

app = QtGui.QApplication(sys.argv)
myQCustomQWidget = QCustomQWidget()
myQCustomQWidget.show()
sys.exit(app.exec_())

rawDescription: Drag and Drop between two QTreeViews

description: Drag and Drop between two QTreeViews


code:
def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

rawDescription: Easiest way to calculate execution time of a python script?


code:
import sys

def outer(value=0):
    count = [value]
    print "started at:", count[0]
    def inner(x=1):
        print "current val:", count[0]
        count[0] += x
        if count[0] > 10:
            print "stopped at:", count[0]
            sys.exit(0)
    return inner

f = outer(5)
while True:
    f(1)

rawDescription: Why doesn't program print value?

description: Why doesn't program print value