code:
def rsum(eleList, ans, index):
    if index == len(eleList) - 1:
        if max(eleList) == eleList[index] or min(eleList) == eleList[index]:
            return ans+eleList[index]
        else:
            return ans
    else:
        if max(eleList) == eleList[index] or min(eleList) == eleList[index]:
            return ans + eleList[index] + rsum(eleList, ans, index + 1)
        else:
            return rsum(eleList, ans, index + 1)

print rsum([9, 2, 3, 4], 0, 0)

rawDescription: Add minimum and maximum number in list using Recursion: Python


code:
with open("dtest.txt", "r") as posnfile:
    previous = None
    for line in posnfile:
        current = [float(x) for x in line.split()]
        if previous:
            delta = [abs(c - p) for c, p in zip(current, previous)]
            print ' '.join(str(d) for d in delta)
        previous = current

rawDescription: Printing in a loop

description: Printing in a loop


code:
def remove_unwanted(s):
    '''• ½ cup flour -> ½ cup flour'''
    allowed = '[\w½¾]+'
    return ' '.join(re.findall(allowed, s))

print remove_unwanted('• ½ cup flour ->')

rawDescription: How to remove nonalphanumeric character in python but keep some special characters

description: Remove nonalphanumeric character in python but keep some special characters


code:
string="abc&def#ghi"
for ch in ['&','#']:
  if ch in string:
     string=string.replace(ch,"\\"+ch)
print string

rawDescription: Multiple character replace with python

description: Multiple character replace with python


code:
def print_timing(func):
    import time
    def wrapper(*args, **kwargs):
        t1 = time.time()
        res = func(*args, **kwargs)
        t2 = time.time()
        funcname = func.__name__
        # Special case; a "name" instance has a "name" attribute we want to use instead.
        if len(args) >= 1 and isinstance(args[0], name):
            funcname = args[0].name
        print '%s took %0.3f s ~ %0.0f min and %0.1f sec' % (funcname, t2-t1, int(t2 - t1)/60, (t2-t1) % 60 )
        return res
    return wrapper

rawDescription: returning a user defined function name when using a decorator with a callable object

description: Returning a user defined function name when using a decorator with a callable object


code:
# enter the data like this
X={'A':(0,0),'B':(0,1),'C':(1,2),'D':(0,1)}

# size of grid
xi=map(tuple.__getitem__,X.values(),[1]*len(X))
yi=map(tuple.__getitem__,X.values(),[0]*len(X))
xrng = (min(xi), max(xi)+1)
yrng = (min(yi), max(yi)+1)

for y in range(*yrng):         # rows
  print '+' * ((xrng[1]-xrng[0])*3) + '+'
  k={}  # each item k[x] is list of elements in xth box in this row
  for x in range(*xrng):
    # list of items in this cell
    k[x]=[u for u in X.keys() if X[u]==(y,x)]
  h=max(map(len, k.values()))  # row height
  for v in range(h):           # lines of row
    c=[]
    for x in range(*xrng):     # columns
      if k[x]:
        c.append(k[x][0])
        del k[x][0]
      else:    c.append(' ')   # shorter cell
    s="+ " + "+ ".join(c) + "+"
    print s
print "+" * ((xrng[1]-xrng[0])*3) + '+'

rawDescription: Matplotlib draw boxes

description: Matplotlib draw boxes


rawDescription: How to preform all valid calculations with a set number of identical values in python?

description: Preform all valid calculations with a set number of identical values in python


code:
import urllib

urlStr = "http://www..."

fileObj = urllib.urlopen(urlStr)

for line in fileObj:
    if ('<input name="extWarrantyProds"' in line):
        startIndex = line.find('value="') + 7
        endIndex = line.find('"',startIndex)
        print line[startIndex:endIndex]

rawDescription: How can I get an specific value in a webpage?

description: Get an specific value in a webpage


code:
m = re.search(r'^([^A-Z]*[A-Z]){2}', 'Paul likes Ice cream.');
print m.span()[1]
12

rawDescription: Python How to find index of second Uppercase letter in a string


code:
def a():
 x = ""
 def b():
  x += "X"
 b()
 print x

a()

def a():
 x = []
 def b():
  x.append("X")
 b()
 print "".join(x)

a()

rawDescription: Nested functions scope in Python

description: Nested functions scope in Python


code:
word = raw_input('Enter a word: ')
word1 = 0
for i in range(0,len(word)) :
    if word[i] in ['a','e','i','u','A','E','I','O','o','U']:
        word1=i
        break
print word[word1+1:]+word[:word1]+word[word1]

rawDescription: How to save each letter while the while loop is running

description: Save each letter while the while loop is running


code:
import ast

with open('app.py') as fp:
    code = fp.read()
    tree = ast.parse(code)
    print ast.dump(tree)

rawDescription: How to parse the whole script in Python?

description: Parse the whole script in Python


code:
SearchValue = SearchValue.splitlines()
for targetValue in SearchValue:
    print LineText.get(targetValue, 'Error:' + targetValue)

rawDescription: Best performance of getting values of the dictionary in python


code:
import re
from subprocess import Popen, PIPE

limit_type = re.compile(r'We are one|foo\.txt')

# Run ls -1 and store stdout output
output = Popen(["ls", "-1"], stdout=PIPE).communicate()[0]
output = str(output).split('\n')
print output

for line in output:
    if limit_type.search(line):
        print "Found it: %s" % line
        exit(0)

print "Not Found it!"

rawDescription: Python script could not find a filename

description: Python script could not find a filename


code:
from threading import Thread
import time

def drive_bus():
    time.sleep(1)
    print "Igor: I'm Igor and I'm driving to... Moskow!"
    time.sleep(9)
    print "Igor: Yei, Moskow!"

def build_house():
    print "Peter: Let's start building a large house..."
    time.sleep(10.1)
    print "Peter: Urks, we have no tools :-("

threads = [Thread(target=drive_bus), Thread(target=build_house)]

for t in threads:
    t.start()

for t in threads:
    t.join()

rawDescription: Alternative python library for managing threads


code:
q = (select([Item.identifier_id, func.count(Item.id).label("cnt")]).
     group_by(Item.identifier_id).having(func.count(Item.id)>1)).alias("subq")
qry =  (session.query(Item).join(q, Item.identifier_id==q.c.identifier_id))
print qry # prints SQL statement generated
items = qry.all() # result

rawDescription: Eager loading of non-singleton collections


rawDescription: Eliminating text in a list with .replace and wildcards


code:
p = 0
for i in occurrence:
    print dates[p:p+i]
    p += i

rawDescription: Python working with two list generating new lists with values


code:
class Cat:
    def __init__(self, lives):
        self.lives = lives
    def meow(self):
        print "I have " + str(self.lives) + " lives"

kitty = Cat(3)
kitty.meow()

rawDescription: Python basic class understanding

description: Python basic class understanding


code:
from Tkinter import *
import Tkinter

def immediately(e):
    print Lb1.curselection()

top = Tk()

Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()

Lb1.bind('<<ListboxSelect>>', immediately)
top.mainloop()

rawDescription: Tkinter Listbox

description: Tkinter Listbox


code:
import pickle
import sys
import imp

foo = imp.new_module("foo")
sys.modules["foo"] = foo

exec "def f():    print 'Hi!'" in foo.__dict__

code = pickle.dumps(foo.f)
print code

rawDescription: Pickle and exec in python

description: Pickle and exec in python


code:
#!/user/bin/python.exe
import math
from multiprocessing import Pool

global primes
primes = set()

def log(result):
    global primes

    if result:
        # since the result is a batch of primes, we have to use
        # update instead of add (or for a list, extend instead of append)
        primes.update(result)

def isPrime( n ):
    if n < 2:
        return False
    if n == 2:
        return True, n

    max = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max:
        if n % i == 0:
            return False
        i += 1
    return True, n

def isPrimeWorker(start, stop):
    """
    find a batch of primes
    """
    primes = set()
    for i in xrange(start, stop):
        if isPrime(i):
            primes.add(i)

    return primes

def main():

    global primes

    pool = Pool()

    # pick an arbitrary chunk size, this will give us 100 different
    # chunks, but another value might be optimal
    step = 10000

    # use xrange instead of range, we don't actually need a list, just
    # the values in that range.
    for i in xrange(1000000, 2000000, step):
        # call the *worker* function with start and stop values.
        pool.apply_async(isPrimeWorker,(i, i+step,), callback = log)

    pool.close()
    pool.join()

    print sum(primes)

    return

if __name__ == "__main__":
    main()

rawDescription: python prime crunching: processing pool is slower?

description: Python prime crunching: processing pool is slower


code:
import regex
sequence = 'aaaaaaaaaaaabbbbbbbbbbbbcccccccccccc' #being searched
query = 'aaabbbbbbbbbbbbccc' #100% coverage
query_1 = 'aaaabbbbbbbbcbbbcccc' #95% coverage
query_2 = 'aaabbbbcbbbbbcbccc' #90% coverage
threshold = 0.97
queries = (query, query_1, query_2)
for q in queries:
    error = int(len(q) - (len(q)*threshold))
    m = regex.search(r'(%s){e<=%d}'%(q,error), sequence)
    print 'match' if m else 'nomatch'

rawDescription: How to add variable error to regex fuzzy search. Python

description: Add variable error to regex fuzzy search. Python


code:
lista = [1, 2, 3, 4]
listb = lista
print lista
print listb
lista[0] = 3
print listb
listc = lista[:]
print listc
lista[0] = 1
print listc

rawDescription: Python Lists(Slice method)

description: Python Lists(Slice method)


code:
def getUrl(opt, baseUrl):
    out_folder = "/monedasWiki/monedas"
    print "Instrucciones del script \n No te preocupes, no es complicado pero atiende a los pasos"
    print "Introduce 1 para obtener los archivos del 00001 al 00010"
    print "Introduce 2 para obtener los archivos del 00010 al 00099"
    print "Introduce 3 para obtener los archivos del 00100 al 00999"
    print "Introduce 4 para obtener los archivos del 01000 al 09999"
    print "Introduce 5 para obtener los archivos del 10000 al 19999"
    optSel = int(input(opt))
    # i es el rango
    # urlI es la transformacion de i en cadena
    # baseUrl es el enlace al sitio web de Pliego
    # url es la url completa con los parametros necesarios
    if optSel == 1:
        try:
            for i in range(0,10):
                r = str(0).zfill(4)
                urlI = str(i)
                print r + urlI # it's only to verify that works fine.
                url = baseUrl + r + urlI
                main(url, out_folder)
        except ValueError:
            print "Introduce el rango correcto"
    elif optSel == 2:
        try:
            for i in range(10,100):
                r = str(0).zfill(3)
                urlI = str(i)
                print r + urlI # it's only to verify that works fine.
                url = baseUrl + r + urlI
                main(url, out_folder)
        except ValueError:
            print "Introduce el rango correcto"
    elif optSel < 0:
        print "Valor inferior a 0"
    else:
        print "Algo ha salido mal"

rawDescription: Extract images and text from a sequence of urls


code:
import wx

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test",size=(300,200))

        self.Btn = wx.Button(self, label="New",pos=(10,10),size=(30,30))
        self.Bind(wx.EVT_BUTTON, self.show_newFrame, self.Btn)

        # create the newFrame instance, keep it around.
        self.new_frame = newFrame()

    def show_newFrame(self, event):
        self.new_frame.Show()

class newFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test 2",size=(300,200))

        self.ch0 = wx.CheckBox(self, -1,"Choice 1",pos=(10,10))
        self.Bind(wx.EVT_CHECKBOX, self.OnCB0, self.ch0)
        self.ch1 = wx.CheckBox(self, -1,"Choise 2",pos=(10,30))
        self.Bind(wx.EVT_CHECKBOX, self.OnCB1, self.ch1)
        self.ch2 = wx.CheckBox(self, -1,"Choise 3",pos=(10,50))
        self.Bind(wx.EVT_CHECKBOX, self.OnCB2, self.ch2)

        self.Bind(wx.EVT_CLOSE, self.onClose)

    # hide ourself on close, don't destroy
    def onClose(self, event):
        self.Hide()

    def OnCB0(self, event):
        if self.ch0.IsChecked():
            print "Checked 1"
        else:
            print "UnChecked 1"

    def OnCB1(self, event):
        if self.ch1.IsChecked():
            print "Checked 2"
        else:
            print "UnChecked 2"

    def OnCB2(self, event):
        if self.ch2.IsChecked():
            print "Checked 3"
        else:
            print "UnChecked 3"

if __name__ == '__main__':
    app = wx.App(False)
    app.frame = MainFrame()
    app.frame.Show()
    app.MainLoop()

rawDescription: wxPython: How the CheckBox can remember my choice when I close the frame

description: WxPython: How the CheckBox can remember my choice when I close the frame


rawDescription: How can limit a certain number of decimal places being shown without rounding?


code:
import urllib2, BeautifulSoup
opener = urllib2.build_opener()
host = "http://google.com"
site = opener.open(host)
html = site.read()
soup = BeautifulSoup(html)
print soup.pretiffy()

rawDescription: How can I get all the attributes of a HTML tag?

description: Get all the attributes of a HTML tag


code:
balance = 320000
annualInterestRate = 0.2

originalBalance = balance
month = 1
monthly_interest = annualInterestRate / 12
low = originalBalance/12
high = (originalBalance*(1 + monthly_interest)**12)/12
epsilon = 0.01
min_payment = (high + low)/2.0

while min_payment*12 - originalBalance > epsilon:
    month = 1          # < -- do this
    while month < 13:
        balance = (originalBalance - min_payment)/10 * (1+ monthly_interest)
        if balance < 0.00:
            low = min_payment
            min_payment = (high + low)/2.0
        elif balance > 0.00:
            high = min_payment
            min_payment = (high + low)/2.0
        month += 1
print "Lowest payment: " + str(round(min_payment, 2))

rawDescription: Bisection Search on the Lowest Payment on Credit Card Debt: Answers are always way off


code:
img = Image.open(GIF_FILENAME)
rgbimg = img.convert('RGB')
for i in range(5):
    print rgbimg.getpixel((i, 0))

rawDescription: Python PIL: color index to RGB

description: Python PIL: color index to RGB


code:
class URLValidator(RegexValidator):
    regex = re.compile(
        r'^https?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    def __init__(self, verify_exists=False, validator_user_agent=URL_VALIDATOR_USER_AGENT):
        super(URLValidator, self).__init__()
        self.verify_exists = verify_exists
        self.user_agent = validator_user_agent

    def __call__(self, value):
        try:
            super(URLValidator, self).__call__(value)
        except ValidationError, e:
            # Trivial case failed. Try for possible IDN domain
            if value:
                value = smart_unicode(value)
                scheme, netloc, path, query, fragment = urlparse.urlsplit(value)
                try:
                    netloc = netloc.encode('idna') # IDN -> ACE
                except UnicodeError: # invalid domain part
                    raise e
                url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
                super(URLValidator, self).__call__(url)
            else:
                raise
        else:
            url = value

        if self.verify_exists:
            import urllib2
            headers = {
                "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
                "Accept-Language": "en-us,en;q=0.5",
                "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
                "Connection": "close",
                "User-Agent": self.user_agent,
            }
            try:
                req = urllib2.Request(url, None, headers)
                u = urllib2.urlopen(req)
            except ValueError:
                raise ValidationError(_(u'Enter a valid URL.'), code='invalid')
            except: # urllib2.URLError, httplib.InvalidURL, etc.
                raise ValidationError(_(u'This URL appears to be a broken link.'), code='invalid_link')

rawDescription: What is the exact pattern of legal values for filling URLFields in Django?


code:
cursor = connection.cursor().execute(sql)
columns = [column[0] for column in cursor.description]
print columns
results = []
for row in cursor.fetchall():
    results.append(dict(zip(columns, row)))
print results

rawDescription: Output pyodbc cursor results as python dictionary


code:
import hmac
from base64 import b64encode
from hashlib import sha256

secret_key = '1234567890'

to_sign = """GET
webservices.amazon.com
/onca/xml
AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReviews&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&Version=2009-01-06"""

print b64encode(hmac.new(secret_key, to_sign, sha256).digest())

rawDescription: Why am I getting the wrong signature for the Amazon Product Advertising API?


code:
import libtorrent as lt
import time

ses = lt.session()
params = { 'save_path': '/home/downloads/'}
link = "magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker.vodo.net:6970/announce"
handle = lt.add_magnet_uri(ses, link, params)

print 'downloading metadata...'
while (not handle.has_metadata()): time.sleep(1)
print 'got metadata, starting torrent download...'
while (handle.status().state != lt.torrent_status.seeding):
    print '%d %% done' % (handle.status().progress*100)
    time.sleep(1)

rawDescription: Loading Magnet LINK using Rasterbar libtorrent in Python


rawDescription: How do I determine if the Shift key was pressed in wxPython event handler?

description: Determine if the Shift key was pressed in wxPython event handler


code:
import urllib2

def process_item(x):
    return urllib2.unquote(x).replace('_', ' ')

def process_line(line):
    return tuple(process_item(i) for i in line.split())

with open('t.txt', 'r') as infile:
    unique_wines = set(process_line(l) for l in infile)

for dom, rang in sorted(unique_wines):
    print dom, ':', rang

rawDescription: unique sorting in python

description: Unique sorting in python


code:
dic = {'Cohen'     : ['Calvino', 'Evertt', 'Borges'],
       'Larry'     : ['The Bible'],
       'Volanski'  : ['Phone Book']}

# Get max name size
mx_nm_len = len(max(dic,key=len))
mx_bk_len = max([len(max(books, key=len)) for books in dic.itervalues()])

# Store max name size + 1
mx = max([mx_nm_len, mx_bk_len]) + 1

# Store people
keys = dic.keys()

# Create generic format code to print neat list
fmat = ("%-"+str(mx)+"s")*len(keys)

# Print header line
print fmat % tuple(keys)

# similar to zip command but works for any number of lists
# Assumes all dic.values() are lists
# "zips" to longest list and uses None when any given list runs out of values
books = map(None, *dic.values())

# replaces None values in row outputs with empty strings and prints result using
# string format code (fmat)
for row in books:
    row = tuple([book if book!= None else "" for book in row])
    print fmat % row

rawDescription: looping through a dictionary and printing it in a certain format

description: Looping through a dictionary and printing it in a certain format


code:
from itertools import tee, izip
import re

def grouper(iterable):
    fst, snd = tee(iterable)
    next(snd, '')
    for prev, curr in izip(fst, snd):
        if set(re.findall('\w+', prev)).intersection(re.findall('\w+', curr)):
            yield prev

with open('qwer.txt') as fin:
    print list(grouper(fin))

# ['/n i also have a appartment and./n\n', '/nappartment good by the way/n\n', '/nby good  fine/n\n', '/nfine is life/n\n']

rawDescription: python to print line from obtained output

description: Python to print line from obtained output


code:
d={'foo': 10,'bar': 12,'asd': 4}
key_list = []
key_index = []
for k,v in d.iteritems():
    if v<=10:
        key_list.append(k)
        key_index.append(d.keys().index(k) + 1)

print key_list
print key_index

rawDescription: find all elements in a dictionary satisfying a criteria

description: Find all elements in a dictionary satisfying a criteria


code:
if string1.startswith(('M')):
    sub=string1[1:]
    rule2=('M'+sub+sub)
    print rule2

rawDescription: appending characters to string in python

description: Appending characters to string in python


code:
#Creates Html page
f = open("Oceaneering_Server_Status.html", "w")
f.write('''<!DOCTYPE html>

Oceaneering Server Status:

<input type="text" id="search" placeholder="Type to search">

Last updated: {time}
Services Running: XXXX

>

Last updated: XXXX Total Services: XXXX Services Stopped: XXX Services Running: XXX

<col width="100">

    Service
    Folder
    Service URL
    Configured State
    Real Time State
    Server Type

'''.format(time=date))

stopped = []
for item in json_read["folders"]:
        services_url = "https://www.ocsdev.oceaneering.com/arcgis/admin/services/" + item + "/report?f=pjson&token=" + token
        t = []
        t.append(services_url)
        print t

        for i in t:
            services_open = urllib.urlopen(services_url)
            services_js = json.loads(services_open.read())
            #print services_js

        #z = open("test.text", "w")
        for i in services_js["reports"]:
            f = open("Oceaneering_Server_Status.html", "a")
            line1 = "
" + "\n\t" + i["instances"]["serviceName"] + "	\n"
            serv_count = i["instances"]["serviceName"]+ "\n"
            line2 = "\t" + i["instances"]["folderName"] + "	\n"
            line3 = '\t' + i["instances"]["serviceName"] + "" + "	\n"
            line4 = "\t" + i["status"]["configuredState"] + "	\n"
            line5 = "\t" + i["status"]["realTimeState"] + "	\n"
            line6 = "\t" + i["instances"]["type"] + "	\n"
            f.write(line1 + line2 + line3 + line4 + line5 + line6 )
            #z.write(serv_count)

            if i["status"]["realTimeState"] == "STOPPED":
                stopped.append(i)

#z.close()

##with open('test.text') as b:
##    aws = len(b.readlines())
##print aws

f.write('''

''')
f.close()

print "completed"

#_______________________________________________________________________________#
#Create TXT file of Services

import json
with open('Oceaneering_Server_Status.txt', 'w') as outfile:
    json.dump(stopped, outfile)

print "completed"

rawDescription: Create txt file of specified objects from JSON


code:
import sys
from os import listdir
from os.path import isfile, join
import hashlib
path = sys.argv[1] #PATH OF THE FILES, ex: /etc/shadow, /bin/*, etc.
files = [ f for f in listdir(path) if isfile(join(path,f)) ]
my_files = {}
for fil in files:
    with open(fil,'rb') as fh:
       md5 = hashlib.md5()
       while True:
          data = fh.read(8192)
          if not data:
             break
          md5.update(data)
    my_files[fil] = md5.hexdigest()
for k,v in my_files.iteritems():
    print 'file_name is {} | hash is {}'.format(k,v)

rawDescription: Python Recursive Hashlib

description: Python Recursive Hashlib


code:
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
    ip = x_forwarded_for.split(',')[-1].strip()
else:
    ip = request.META.get('REMOTE_ADDR')
print ip

rawDescription: How to find out if an image is loaded?

description: Find out if an image is loaded


code:
user_typed = raw_input()
try:
    user_number = float(user_typed)
except ValueError:
    print "Couldn't convert this to a number, please try again: %r" % user_typed

rawDescription: Unicode Prefix on Numbers - Python

description: Unicode Prefix on Numbers - Python


code:
import sys
from mock import Mock
sys.modules['C'] = Mock()
import A
print A.B.C.__name__

rawDescription: Mock an import from an import

description: Mock an import from an import


code:
def parseString(userInput):
    namePosition = userInput.find('-u')
    emailPosition = userInput.find('-e')
    passwordPosition = userInput.find('-p')

    if namePosition != -1 and emailPosition != -1 and passwordPosition != -1:
        nameText = userInput[namePosition+1:emailPosition] # will look like 'u peter'
        emailText = userInput[emailPosition+1:passwordPosition]
        passwordText = userInput[passwordPosition+1:]
        return [nameText,emailText,passwordText]
    else:
        print 'improper number or type of parameters given as input'

someText = '-u peter -e myemail@email.com -p password'

parsedText = parseString(someText)
print parsedText

rawDescription: Finding all instances of a pattern in a string in python


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")

header = driver.find_element_by_id("header")

# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")

print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))

rawDescription: Selenium Python get all children elements


code:
import random

pin = random.randint(999, 9999)
print pin

rawDescription: Python create a random pin four digits long using random


code: p = Popen(["ls", "-hal"]);sleep (5);print "Word"

rawDescription: Python subprocess.Popen()

description: Python subprocess.Popen()


code:
import sqlite3

conn = sqlite3.connect("growll.db")
cursor = conn.cursor()

print "\nHere's a listing of all the records in the table:\n"
cursor.execute("select lchar from GrowLLDados")

print [int(record[0]) for record in cursor.fetchall()]

rawDescription: How to make fetch methods return int values for INTEGER columns instead of strings Python sqlite?

description: Make fetch methods return int values for INTEGER columns instead of strings Python sqlite


code:
import time
print "Your GoodBye Message"
time.sleep(5)

rawDescription: How to stop console from exiting

description: Stop console from exiting


code:
dicmorning = {"goodmorning", "morning"}
raw_string = raw_input("test: ")
tokens = raw_string.split()
if dicmorning.intersection(tokens):
    print "good morning"
else:
    print "test"

rawDescription: Check for a string in the user inout

description: Check for a string in the user inout


code:
import urllib
html = urllib.urlopen(pageToLawyersBio)

htmlstr=''
for line in html.readlines():
    htmlstr += line.lower()

for school in listOfSchools:
    if school.lower() in htmlstr:
        print "This lawyer went to", school

rawDescription: How to search a HTML page for an item in a given list

description: Search a HTML page for an item in a given list


code:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])

c = np.array([a,b]) # < ---- this line!

print repr(c)
print a in c

print np.array([1,2,3]) in c

print [1,2,3] in c # Success!!!
print np.array([1,2,3]).tolist() in c# also success!!!

rawDescription: Existance of array in list of arrays

description: Existance of array in list of arrays


code:
df=pandas.read_csv('myfile.csv')   #parse CSV
posts=df[df['post']=='Hi guys']    #Get entries where post is 'Hi Guys'
print posts.comment_by             #show comment user

rawDescription: Selective printing of rows and columns of csv file in python pandas


code:
import codecs
f = codecs.open('import.txt', 'w', 'utf-8')
f.write("hello\nworld\n")
f.close()
print repr(open("import.txt").read())

rawDescription: Writing newline with Python codecs.write


code:
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print 'Killed by user'
        sys.exit(0)

rawDescription: Python Global Exception Handling

description: Python Global Exception Handling


code:
for key, val in zip(jobids, jobdeps):
    if key == '0':
        print val

rawDescription: Associating 2 lists

description: Associating 2 lists


code:
def memsetObject(bufferObject):
    "Note, dangerous"
    import ctypes
    data = ctypes.POINTER(ctypes.c_char)()
    size = ctypes.c_int()  # Note, int only valid for python 2.5
    ctypes.pythonapi.PyObject_AsCharBuffer(ctypes.py_object(bufferObject), ctypes.pointer(data), ctypes.pointer(size))
    ctypes.memset(data, 0, size.value)

testObject = "sneakyctypes"
memsetObject(testObject)
print repr(testObject)
# '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

rawDescription: How to do a memset with Python buffer object?

description: Do a memset with Python buffer object


code:
from collections import Counter
common = Counter(yourList).most_common()
min = common[0][1]
print "Minimum Occurrence Number: {0}".format(min)
print "Codes that Occur this much:"
for item in common:
    if item[1] != min:
        break
    print item[0]
max = common[-1][1]
print "Maximum Occurrence Number: {0}".format(max)
print "Codes that Occur this much:"
for item in reversed(common):
    if item[1] != max:
        break
    print item[0]

rawDescription: Printing the minimum & maximum counts for elements within Iist of output, from a function as well as the item itself


code:
import lxml.html

def main():
    doc = lxml.html.parse("http://thisisnthappiness.com/").getroot()
    for e in doc.cssselect("div.post"):
       print e # this is an object representing the element

if __name__ == "__main__":
    main()

rawDescription: Get data between tags for tags that fit defined CSS selector with Python's HTMLParser


code:
from subprocess import call

def main():
    fp = open('path/to/your/file')
    f = fp.readlines()
    fp.close()
    myIter = MyIterator(f,12)
    #                      ^replace with the actual index the line you want to look at
    print myIter.current()
    cmd = raw_input()

    #Input is no optimal, but this is beyond the scope of your question

    while cmd != "quit":
        call(["clear"])
        if cmd == "u":
            myIter.previous()
        elif cmd == "d":
            myIter.next()
        for line in myIter.current():
            print line
        cmd = raw_input()

class MyIterator():
    def __init__(self,f,index):
        self.f = []
        for line in f:
            #Otherwise you would have a blank line between every line
            self.f.append(line.replace('\n',''))
        self.upper_index = index-1
        self.lower_index = index

    def hasNext(self):
        if self.upper_index > len(self.f):
            return False
        else:
            return True

    def hasPrevious(self):
        if self.lower_index <= 0:
            return False
        else:
            return True

    def next(self):
        self.upper_index += 1
        return self.current()

    def previous(self):
        self.lower_index -= 1
        return self.current()

    def current(self):
        return self.f[self.lower_index:self.upper_index]

if __name__ == "__main__":
    main()

rawDescription: Searching for lines in a file and giving users flexible context


code:
import os, sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print os.path.join(dirname, "b.txt")

rawDescription: Python, find a file in the same directory


code:
chunk_size = 50

for i in range(0, alignment.get_alignment_length(), chunk_size):
    print ""
    for record in alignment:
        print "%s\t%s %i" % (record.name,  record.seq[i:i + chunk_size], i + chunk_size)

rawDescription: Print 50 sequences from each line using Clustal


code:
import joblib
print joblib.cpu_count()

rawDescription: python joblib.Parallel vs Parallel-Python: parallelise over multiple cores of a single CPU?

description: Python joblib.Parallel vs Parallel-Python: parallelise over multiple cores of a single CPU


code:
from twisted.internet.protocol import ClientFactory
from twisted.internet.protocol import Protocol
from twisted.internet.defer import Deferred
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.defer import returnValue
from twisted.internet.ssl import CertificateOptions
from twisted.internet.ssl import AcceptableCiphers

import time
import json

normalCyphers = AcceptableCiphers.fromOpenSSLCipherString(
    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
    '!eNULL:!MD5'
)
normalCtxFac = CertificateOptions(acceptableCiphers=normalCyphers)

weakCiphers = AcceptableCiphers.fromOpenSSLCipherString('ALL:!aNULL:!eNULL')
weakCtxFac = CertificateOptions(acceptableCiphers=weakCiphers)

def asn1DateToTimestamp(asn1Date):
    expirationDate = time.strptime(asn1Date[:8], '%Y%m%d')
    return int(time.mktime(expirationDate))

class CertCheckProtocol(Protocol):

    def __init__(self, dfd, isWeakSsl):
        self.dfd = dfd
        self.isWeakSsl = isWeakSsl

    def connectionMade(self):
        reactor.callLater(0.01, self.getCert, 20)

    def getCert(self, depth):
        cert = self.transport.getPeerCertificate()
        transportHandle = self.transport.getHandle()
        if cert is None or transportHandle is None:
            if depth <= 0:
                self.transport.loseConnection()
                return
            reactor.callLater(0.01, self.getCert, depth - 1)
        else:
            cipherName = transportHandle.get_cipher_name()
            timestamp = asn1DateToTimestamp(cert.get_notAfter())
            expiresIn = timestamp - time.time()

            self.dfd.callback({
                'name': 'certificate',
                'expiresIn': expiresIn,
                'sha1Digest': cert.digest('sha1'),
                'signatureAlgorithm': cert.get_signature_algorithm(),
                'issuer': cert.get_issuer().CN,
                'notAfter': timestamp,
                'notBefore': asn1DateToTimestamp(cert.get_notBefore()),
                'serialNumber': cert.get_serial_number(),
                'subject': cert.get_subject().CN,
                'sslVersion': cert.get_version(),
                'usedCipher': cipherName,
                'weakCipher': self.isWeakSsl
            })

    def connectionLost(self, reason):
        if not self.dfd.called:
            self.dfd.errback(Exception('Connection lost'))

class CertCheckFactory(ClientFactory):

    def __init__(self, dfd, isWeakSsl):
        self.dfd = dfd
        self.isWeakSsl = isWeakSsl

    def clientConnectionFailed(self, connector, reason):
        self.dfd.errback(reason)

    def buildProtocol(self, addr):
        return CertCheckProtocol(self.dfd, self.isWeakSsl)

@inlineCallbacks
def getCertificateInfo(ip, port=443):
    dfd = Deferred()
    factory = CertCheckFactory(dfd, isWeakSsl=False)
    reactor.connectSSL(ip, int(port), factory, contextFactory=normalCtxFac)
    try:
        res = yield dfd
    except Exception as ex:
        if hasattr(ex, 'reason') and 'HANDSHAKE_FAILURE' in ex.reason:
            dfd = Deferred()
            factory = CertCheckFactory(dfd, isWeakSsl=True)
            reactor.connectSSL(ip, int(port), factory,
                               contextFactory=weakCtxFac)
            res = yield dfd
        else:
            raise
    returnValue(res)

@inlineCallbacks
def testit(ip):
    res = yield getCertificateInfo(ip)
    print json.dumps(res)
    reactor.stop()

if __name__ == '__main__':
    testit('google.com')
    reactor.run()

rawDescription: twisted get cipher name

description: Twisted get cipher name


code:
from multiprocessing import Process,Manager

def a(b):
    for i in range(10):
        b[i] = i

b = [0 for _ in range(10)]

#create a manager to manage access to `b`
manager = Manager()
b = manager.list(b)

p = Process(target=a, args=(b,))
p.start()
p.join()

print sum(b)

rawDescription: How to use multiprocessing in python?

description: Use multiprocessing in python


code:
s = 'ç'
s
print s
len(s)
s.decode('utf-8')
len(s.decode('utf-8'))
ord(s.decode('utf-8'))

rawDescription: How to store non-english text?

description: Store non-english text


code:
import sys

class Kangaroo(object):
    def __str__(self):
        flocals = sys._getframe(1).f_locals
        for ident in flocals:
            if flocals[ident] is self:
                name = ident
                break
        else:
            name = 'roo'
        return "in {0}'s pouch, there is {1}".format(name, self.pouch_contents)

kang = Kangaroo()
print kang

rawDescription: Accessing the name of an instance in Python for printing


code:
class host_struct: # no need for parentheses if not inheriting from something besides object
    host_id = {} # use of {} is more idiomatic than dict()
    host_license_id = {}

def m(a):
    exec a

host = host_struct()
m('host.host_id.update({1:1})') # updating will add to existing dict instead of replacing

print host.host_id[1]

rawDescription: How to call a function with a class object as a parameter in string form

description: Call a function with a class object as a parameter in string form


code:
from bs4 import BeautifulSoup
import csv
import urllib2
import os

def processData( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    f.close()
    soup = BeautifulSoup(page)

    one = soup.findAll('td', attrs={"width": "18%"}) #close
    two = soup.findAll("span", attrs={"style":"color: #999999"})  #close
    three = soup.findAll("div", attrs={"style":"font-size: 9pt"}) #works
    four = soup.findAll("div", attrs={"style":"padding-top: 4px;"})

    names = []
    threads = []
    posts = []
    timestamps = []

    print four

    for html in one:
            text = BeautifulSoup(str(html).strip()).get_text().encode("utf-8").replace("\n", " ")
            names.append(text.split('UID')[0].strip()) #works, at the moment

    for color in two:
            text2 = BeautifulSoup(str(color).strip()).get_text().encode("utf-8").replace("\n", "")
            threads.append(text2.strip())

    for html in three:
            text3 = BeautifulSoup(str(html).strip()).get_text().encode("utf-8").replace("\n", "").replace(" ", "")
            posts.append(text3.strip())

    for html in four:
            text4 = BeautifulSoup(str(html).strip()).get_text().encode("utf-8").replace("\n", "").replace(" ", "")
            timestamps.append(text4.split("Post at")[1].split('Profile')[0].strip())

    csvfile = open('S141test.csv', 'ab')
    writer = csv.writer(csvfile)

    for name, thread, post, timestamp in zip(names, threads, posts, timestamps):
            writer.writerow([name, thread, post, timestamp])

    csvfile.close()

dir = "S141test"
csvFile = "S141test.csv"
csvfile = open(csvFile, 'wb')
writer = csv.writer(csvfile)
writer.writerow(["Name", "thread", "post", "timestamp"])
csvfile.close()

# get a list of files in the directory
fileList = os.listdir(dir)
# define variables we need for status text
totalLen = len(fileList)
count = 1
# iterate through files and read all of them into the csv file
for htmlFile in fileList:
    path = os.path.join(dir, htmlFile) # get the file path
    processData(path) # process the data in the file
    print "Processed '" + path + "'(" + str(count) + "/" + str(totalLen) + ")..." # display status
    count = count + 1 # incriment counter

rawDescription: Scraping a forum page with Beautiful Soup 4 -- csv file ends up empty


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Content(Base):
    __tablename__ = 'contents'

    grandma_id = Column(Integer, primary_key=True)
    author_id = Column(Integer, primary_key=True)

s = Session()

unique_users_contents = s.query(Content).distinct(
                            Content.grandma_id, Content.author_id).\
                            subquery('c')

q = s.query(
        Content,
        func.row_number().over(
                partition_by=Content.grandma_id,
                order_by=func.random()).label("row_number")
    ).select_entity_from(unique_users_contents).subquery()

q = s.query(Content).select_entity_from(q).filter(q.c.row_number <= 4)

print q

rawDescription: Complex query (subqueries, window functions) with sqlalchemy


code:
import os
import shutil

def doit():
    shutil.rmtree('c:/pythontest', ignore_errors=True)
    os.mkdir('c:/pythontest')
    os.chdir('c:/pythontest')

    for i in range(0,3):
        fileName = 'folder%d' % i
        print fileName
        os.mkdir(fileName)
        os.chdir(fileName)
        for j in range(0,3):
            fileName = 'folder%d_%d' % (i,j)
            print fileName
            os.mkdir(fileName)
            os.chdir(fileName)
            for k in range(0,3):
                try:
                    with open('file%d_%d_%d.txt' % (i,j,k), 'w'):
                        pass
                except IOError:
                    pass
            os.chdir('..')
        os.chdir('..')

rawDescription: python create recursive folder structure

description: Python create recursive folder structure


code:
import re
p =re.compile(r'.*UID(\d+)')
with open('infile') as infile:
    for line in infile:
        m = p.match(line)
        if m:
           print m.groups[0]

rawDescription: python - How to extract strings from each line in text file?

description: Python - How to extract strings from each line in text file


code:
class Command(BaseCommand):
    def hello(self):
        print "Hello!"
    def my_god(self):
        print "OMG!"

    def handle(self):
        # this was def main():
        self.hello()
        self.my_god()

rawDescription: Unit testing functions inside the handle method of custom django-admin command modules


code:
import osgeo.ogr
# using ESRI Shape file in this example but there are a number
# of different files this lib supports: http://www.gdal.org/ogr/ogr_formats.html
driver = osgeo.ogr.GetDriverByName('ESRI Shapefile')
osgeo.ogr.UseExceptions()

# Create a data source using the driver...
dataSource = driver.Open("/home/user1/data.shp")

# Get the layer
lyr = dataSource.GetLayer()

# Select the feature in this case using an attribute query
lyr.SetAttributeFilter("column = 'value'")

# verify that you have a feature selected
print 'features in layer:', lyr.GetFeatureCount()

# get the firest feature from the layer
feature = lyr.GetNextFeature()

# get the geometry from the feature
geom = feature.GetGeometryRef()

# perform a 100 unit buffer, not sure what units the coordinates of the
# the data you have are in.
bufferGeom = geom.buffer(100)

# bufferGeom is a geometry object, which is described here:
# <http://cosmicproject.org/OGR/ogr_classes.html#Geometry>

rawDescription: How can I take a list of points that create a line and extend them into polygons inward of a certain length?

description: Take a list of points that create a line and extend them into polygons inward of a certain length


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

from numpy import uint8
from numpy import uint16
from numpy import uint32
from numpy import uint64

def sizeof(x):
    return 2 ** [uint8, uint16, uint32, uint64].index(x)

def rot(x, i):
    return type(x)((x >> i) | (x << (sizeof(type(x))*8 - i)))

def plotShifts(x):
    fig = plt.figure() # make a new figure
    ax = fig.add_axes([0.15, 0.2, 0.65, 0.7]) # add data axes
    origType = type(x)
    maxval = type(x)(-1)

    numrots = sizeof(type(x)) * 8
    vals = [rot(x, type(x)(i)) for i in range(numrots)]

    print vals
    print maxval
    l, = ax.plot(range(numrots), vals, 'ro') # plot to data axes

    axcolor = 'lightgoldenrodyellow'
    inputax = fig.add_axes([0.15, 0.05, 0.65, 0.03], axisbg=axcolor)
    inputsl = Slider(inputax, 'Input', 0, maxval, valinit=0, valfmt="%d")

    def update(x):
        vals = [rot(origType(x), origType(i)) for i in range(numrots)]
        l.set_ydata(vals)
        plt.draw()
    inputsl.on_changed(update)

    ax.set_ylim([-2,maxval +2]) # set ylim on data axes
    ax.set_xlim([-.5,numrots-1+.05]) # set xlim on data axes

    return inputsl

sldr = plotShifts(uint8(1))
plt.show()

rawDescription: Why does matplotlib's Slider only allow a range of 0-7?


code:
num = 4
val = [3,2,5,6,1,6]
pair = [(1,3),(3,2),(7,3),(6,5),(3,4),(5,7)]

import random
print random.choice([random.choice(pair[v]) for v in range(len(val)) if val[v] == max(val)])

rawDescription: How to random choose several value from a list based on the value from other list?

description: Random choose several value from a list based on the value from other list


code:
from time import sleep
from threading import Thread

def send_message(msg):
    print msg
    sleep(2)

jobs = []
for datum in testdata:
    proc = Thread(target=send_msg, args=(datum,))
    jobs.append(proc)
    proc.start()

rawDescription: multi threading in Python using text file

description: Multi threading in Python using text file


code:
def printfirst(lst):
    print lst[0]
printfirst('hello')
printfirst(['hello'])

rawDescription: Cast string to first element of a new list in function call


code:
ele7 = browser.find_element_by_id("nav")
ele5 = ele7.find_elements_by_class_name("fl")

urls = [elem.get_attribute('href') for elem in ele5]  # <-----

browser.implicitly_wait(20)

for url in urls[:2]:  # <------
    print url
    browser.get(url)  # <------ used `browser.get` instead of `click`.
                      #         ; using `element.click` will cause the error.

    ele6 = browser.find_elements_by_class_name("rc")
    for result in ele6:
        f = result.find_elements_by_class_name("r")
        for line in f:
            link = line.find_elements_by_tag_name("a")[0].get_attribute("href")
            links.append(link)
            parsed_uri = urlparse(link)
            domains.append('{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri))

rawDescription: StaleElementReferenceException selenium webdriver python


code:
from numpy import arange
from matplotlib import pyplot as plt
from sympy import sympify, solve

f1= '2**(T - 74)' #note these are strings
f2= '2**(T - 60)'

y_bounds= (0.001, 1) #exponential functions never take 0 value, so we use 0.001
mm= (min, max)
x_bounds= [m(solve(sympify(f+"-"+str(y)))[0] for f in (f1,f2)) for y,m in zip(y_bounds, mm)]
print x_bounds

N_STEPS=100 #distributed over x_bounds
T = arange(x_bounds[0], x_bounds[1]+0.001, (x_bounds[1]-x_bounds[0])/N_STEPS)

curve1 = eval(f1) #this evaluates the function over the range, by evaluating the string as a python expression
curve2 = eval(f2)
plt.plot(T,curve1)
plt.plot(T,curve2)
plt.ylim([0,1])
plt.show()

rawDescription: Plotting functions at a specific y-interval


code:
from lxml.html import parse
import sys

def process(htmlpage):
    tree = parse(htmlpage).getroot()

    # Helper function
    xpath_to_column = lambda expr: [el.text for el in tree.xpath(expr)]

    symbol = xpath_to_column('//*[@id="idcquoteholder"]/table/tr/td[1]/a')
    price  = xpath_to_column('//*[@id="idcquoteholder"]/table/tr/td[3]')
    volume = xpath_to_column('//*[@id="idcquoteholder"]/table/tr/td[6]')

    return zip(symbol, price, volume)

def main():
    for filename in sys.argv[1:]:
        with open(filename, 'r') as page:
            print process(page)

if __name__ == '__main__':
    main()

rawDescription: Extracting with Python

description: Extracting with Python


code:
import re

a = 'foo 123 blah 234 xxx 655'
for m in re.finditer(r'(\d+)', a):
  print m.group(1)

rawDescription: how to findall with python regex and preserve group numbers on matches

description: Findall with python regex and preserve group numbers on matches


rawDescription: Refining fnmatch pattern for more specific results


code:
def detail(request, id):
    posts = Post.objects.get(id=id)
    comments = posts.comment_set.all()
    forms = CommentForm
    if request.method == 'POST':
        form = CommentForm(request.POST,instance=posts)
        print form
        if form.is_valid():
            # create a comment instance in memory first
            comment = form.save(commit=False)
            # fill out the title field
            comment.title = posts
            comment.save()
        else:
          print form.errors
    else:
        form = PostForm()

    return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})

rawDescription: django unable to saved forms in database

description: Django unable to saved forms in database


code:
f = open("/tmp/test.txt", "r")

depth = 0
root = { "txt": "root", "children": [] }
parents = []
node = root
for line in f:
    line = line.rstrip()
    newDepth = len(line) - len(line.lstrip("\t")) + 1
    print newDepth, line
    # if the new depth is shallower than previous, we need to remove items from the list
    if newDepth < depth:
        parents = parents[:newDepth]
    # if the new depth is deeper, we need to add our previous node
    elif newDepth == depth + 1:
        parents.append(node)
    # levels skipped, not possible
    elif newDepth > depth + 1:
        raise Exception("Invalid file")
    depth = newDepth

    # create the new node
    node = {"txt": line.strip(), "children":[]}
    # add the new node into its parent's children
    parents[-1]["children"].append(node)

json_list = root["children"]
print json_list

rawDescription: Creating a JSON object from a tabbed tree text file


code:
from Tkinter import *

class MyObj:
    def callback(self, event):
        print event.widget.message

obj = MyObj()
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', obj.callback)
btn.pack()
btn.message = 'Hello'

btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', obj.callback)
btn2.message = 'Salut'
btn2.pack()

root.mainloop()

rawDescription: How do I tell which widget triggered an event in Tkinter?

description: Tell which widget triggered an event in Tkinter


code:
try:
    response = raw_input("Select a monitoring plot from the list: ")

    if response == 'q':
        break

    selected = dataList[int(plotSelect) + 1]

    print 'You selected : ', selected[1]
    break
except ValueError:
    print "Error: Please enter a number between 0 and 9"

rawDescription: Get user input as int or str

description: Get user input as int or str


code:
media_qs = Media.objects.all()
for media in media_qs:
    reviews = media.rev_media.all() #basically, this is the queryset of all the associated reviews for this media object.
    if reviews.exists():

        print ", ".join([review.message for review in reviews])

rawDescription: Django ForeignKey getting results

description: Django ForeignKey getting results


code:
import csv, sys
import requests
import urllib2
import os

filename = 'test.csv'
with open(filename, 'rb') as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            if 'http' in row[0]:
                #print row
                rev  = row[0][::-1]
                i  = rev.index('/')
                tmp = rev[0:i]
                #print tmp[::-1]
                rq = urllib2.Request(row[0])
                res = urllib2.urlopen(rq)
                if not os.path.exists("./"+tmp[::-1]):
                    pdf = open("./" + tmp[::-1], 'wb')
                    pdf.write(res.read())
                    pdf.close()
                else:
                    print "file: ", tmp[::-1], "already exist"
    except csv.Error as e:
        sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))

rawDescription: Python download files by links stored in csv


code:
#!/usr/bin/env python

# difflib_test

import difflib

file1 = open('/home/saad/Code/test/new_tweets', 'r')
file2 = open('/home/saad/PTITVProgs', 'r')

diff = difflib.ndiff(file1.readlines(), file2.readlines())
delta = ''.join(x[2:] for x in diff if x.startswith('- '))
print delta

rawDescription: python difflib comparing files

description: Python difflib comparing files


code:
import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('thisisexample')

print soup.getText(separator=u' ')
# u'this is example'

rawDescription: extracting element and insert a space

description: Extracting element and insert a space


code:
def _get_default_tempdir():
    """Calculate the default directory to use for temporary files.
    This routine should be called exactly once.

    We determine whether or not a candidate temp dir is usable by
    trying to create and write to a file in that directory.  If this
    is successful, the test file is deleted.  To prevent denial of
    service, the name of the test file must be randomized."""

    namer = _RandomNameSequence()
    dirlist = _candidate_tempdir_list()
    flags = _text_openflags

    for dir in dirlist:
        if dir != _os.curdir:
            dir = _os.path.normcase(_os.path.abspath(dir))
        # Try only a few names per directory.
        for seq in xrange(100):
            name = namer.next()
            filename = _os.path.join(dir, name)
            try:
                fd = _os.open(filename, flags, 0o600)
                try:
                    try:
                        with _io.open(fd, 'wb', closefd=False) as fp:
                            fp.write(b'blat')
                    finally:
                        _os.close(fd)
                finally:
                    _os.unlink(filename)
                return dir
            except (OSError, IOError) as e:
                if e.args[0] == _errno.EEXIST:
                    continue
                if (_os.name == 'nt' and e.args[0] == _errno.EACCES and
                    _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
                    # On windows, when a directory with the chosen name already
                    # exists, EACCES error code is returned instead of EEXIST.
                    continue
                break # no point trying more names in this directory
    raise IOError, (_errno.ENOENT,
                    ("No usable temporary directory found in %s" % dirlist))

rawDescription: Python `tempfile.gettempdir()` does not respect TMPDIR


code:
from BeautifulSoup import BeautifulSoup

# Insert whatever networking stuff you're doing here. I'm going to assume
# that you've already downloaded the page and assigned it to a variable
# named 'html'

soup = BeautifulSoup(html)
headings = ['Internship', 'Residency', 'Fellowship']
values = []
for heading in headings:
    x = soup.find('span', text=heading)
    if x:
        span_id = x.parent['id']
        table_id = span_id.replace('dnnTITLE_lblTitle', 'Display_HtmlHolder')
        values.append(soup.find('td', attrs={'id': table_id}).text)
    else:
        values.append('')

print zip(headings, values)

rawDescription: How to extract table information using BeautilSoup?

description: Extract table information using BeautilSoup


code:
import datetime

someDict = {}
for iter in range(5):
    date_now = datetime.datetime.utcnow()
    date = '%s.%02d.%sX%s%s%s' % (date_now.day, date_now.month, date_now.year, date_now.minute, date_now.second, date_now.microsecond) #

    someValue = raw_input('Value:')
    print date
    someDict[date] = someValue

rawDescription: How to make different Time-based keys for a dictionary?

description: Make different Time-based keys for a dictionary


code:
import anydbm
from random import random
import time

# open DBM outside of the timed loops
db = anydbm.open("dbm2", "c")

max_records = 100000

# only time read and write operations
t = time.time()

# create some records
for i in range(max_records):
  db[str(i)] = 'x'

# do a some random reads
for i in range(max_records):
  x = db[str(int(random() * max_records))]

time_taken = time.time() - t
print "Took %0.3f seconds, %0.5f microseconds / record" % (time_taken, (time_taken * 1000000) / max_records)

db.close()

rawDescription: Is Python DBM really fast?

description: Is Python DBM really fast


code:
import pickle
data = [int(el) for el in raw_input().split()]
try:
    new = pickle.load(open("save.p", "rb")) + data
except IOError:
    new = data
pickle.dump(new, open("save.p", "wb"))
print pickle.load(open("save.p", "rb"))

rawDescription: Store dynamic values in a data structure


code:
s = 'Hello World'
rev = []
for i in s.split(' '):
    rev.append(i[::-1])

print ' '.join(rev)

rawDescription: 100 Projects in Python - Reverse String alternate answer


code:
import itertools

nplayers=4
nsides=2
max_number=8

assert nplayers*nsides <= max_number
assert nsides % 2 == 0 #otherwise x^x (dot product) is not even, so half_wins_fairness always fails

iterations=[]
def half_wins_fairness( dice1,dice2 ):
    dice1_wins= map( lambda x: x[0]>x[1], itertools.product(dice1,dice2) )
    dice_wins_prob= float(sum(dice1_wins))/len(dice1_wins)
    #probs.append(dice_wins_prob)
    return dice_wins_prob==0.5

def fair( all_dice ):
    all_fair= True
    for d1,d2 in itertools.combinations( all_dice, 2):
        if not half_wins_fairness(d1,d2):
            all_fair=False
    return all_fair

for i,dice_pattern in enumerate(itertools.permutations(range(max_number), nplayers*nsides)):
    #cut dice pattern into dices
    dice= [dice_pattern[p*nsides:(p+1)*nsides] for p in range(nplayers)]
    if fair(dice):
        print dice
        iterations.append(i)

def discrete_derivative(l):
    last=0
    for i,x in enumerate(l):
        tmp= x
        l[i]=x-last
        last=tmp

#discrete_derivative(iterations)
#import pylab
#pylab.plot(iterations)
#pylab.show()

rawDescription: How can I generate "Go First" Dice for N dice?

description: Generate "Go First" Dice for N dice


code:
s='cde'
for i in s:
    i=chr(ord(i)-2)
print s

rawDescription: results of list comprehension and for loop not the same

description: Results of list comprehension and for loop not the same


code:
from gevent import monkey
monkey.patch_all()

import urllib2
from gevent.pool import Pool

def download(url):
    return urllib2.urlopen(url).read()

if __name__ == '__main__':
    urls = ['http://httpbin.org/get'] * 100
    pool = Pool(20)
    print pool.map(download, urls)

rawDescription: Python - getting multiple URLs

description: Python - getting multiple URLs


code:
import base64
import re

def has_gave(raw_email):
    email_body = base64.b64decode(raw_email)
    match = re.search(r'.*gave.*', email_body , re.IGNORECASE)
    if match:
        done = 'yes'
        print 'match found for word ', match.group()
    else:
        done = 'no'
        print 'no match found'

    return done

rawDescription: Python search imap email for a string

description: Python search imap email for a string


code:
from sys import *
from subprocess import *
import multiprocessing

class ProcessNAS(multiprocessing.Process):
    def __init__ (self, name):
        self.name_ = name
        self.status = False
        self.process = None
        super(ProcessNAS, self).__init__(target=self.StartCheck)

    def StartCheck(self):
        print "Checking for NAS..."
        stdout.flush()
        self.process = Popen( ["dns-sd", "-B", "_ssh._tcp", "."], stdout=PIPE )

        while True:
            line = self.process.stdout.readline()[:-1]
            print line
            if "Add" in line and self.name_ in line:
                self.status = True
                print "NAS '" + self.name_ + "' is available."
            elif "Rmv" in line and self.name_ in line:
                self.status = False
                print "NAS '" + self.name_ + "' is unavailable."

newCheckNAS = ProcessNAS("Drobo-FS")
newCheckNAS.start()  # <-- instead of StartCheck(), call start()

import time
time.sleep(4)
newCheckNAS.terminate()  # <-- now have two processes - able to kill the child

rawDescription: Python, running a subprocess and read output and not hanging the program


code:
for line in soup.find_all('h1',attrs={'itemprop':'name'}):
    [s.extract() for s in line('span')]
print line.get_text()
# => New Men's Genuine Leather Bifold ID Credit Card Money Holder Wallet Black

rawDescription: beautifulsoup .get_text() is not specific enough for my HTML parsing

description: Beautifulsoup .get_text() is not specific enough for my HTML parsing


code:
import numpy

# Create some fake data
frame_count = 10
frame_width = 2
frame_height = 3
frames = numpy.random.randn(frame_count, frame_width, frame_height).astype(numpy.float32)
print 'Original frames\n', frames

# Compute the modified frames over a specified range
mean_range_size = 2
assert frame_count >= mean_range_size * 2

start_mean = frames[:2 * mean_range_size + 1].mean(axis=0)
start_frames = frames[:mean_range_size] - start_mean

middle_frames = numpy.empty((frames.shape[0] - 2 * mean_range_size,
                             frames.shape[1], frames.shape[2]),
                            dtype=frames.dtype)

for index in xrange(middle_frames.shape[0]):
    middle_frames[index] = frames[mean_range_size + index] - \
                           frames[index:index + 2 * mean_range_size + 1].mean(axis=0)

end_mean = frames[-2 * mean_range_size - 1:].mean(axis=0)
end_frames = frames[-mean_range_size:] - end_mean

modified_frames = numpy.concatenate([start_frames, middle_frames, end_frames])
print 'Modified frames\n', modified_frames

rawDescription: Numpy averaging a series

description: Numpy averaging a series


code:
def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
    """Report download progress."""
    print u'[download] %s of %s at %s ETA %s' % (percent_str, data_len_str, speed_str, eta_str)

rawDescription: Python Script: Print new line each time to shell rather than update existing line


code:
def name_to_number(name):
    if name=='rock':
        number=0
    elif name=='Spock':
        number=1
    elif name=='paper':
        number=2
    elif name=='lizard':
        number=3
    elif name=='scissors':
        number=4
    else:
        print 'Not a valid input'
        return number

rawDescription: Not able to understand where white spaces are or indentation is missing in Python code : Line 6: SyntaxError: bad input (' ')


code:
def onclick(x, y):
    print x, y

turtle.Screen().onscreenclick(onclick)

rawDescription: Tic Tac Toe Game on Python using TURTLE

description: Tic Tac Toe Game on Python using TURTLE


code:
grades = [1, 7, 2, 5, 6, 9, 11, 11, 1, 6, 1]

def streak(grades):
    def streak_rec(longest, challenger, previous, rest):
        if rest == []:             # Base case
            return max(longest, challenger)
        elif previous <= rest[0]:  # Streak continues
            return streak_rec(longest, challenger + 1, rest[0], rest[1:])
        else:                      # Streak is reset
            return streak_rec(max(longest, challenger), 1, rest[0], rest[1:])

    return streak_rec(0, 0, 0, grades)

print streak(grades) # => 6
print streak([2])    # => 1

rawDescription: Find the number of consecutively increasing elements in a list


code:
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

rawDescription: Creating command line switches in python


code:
#!/usr/bin/python
# SUPER LIVER ADVENTURE 12!
# If you steal my stuff, credit me.
# Owen Sanders on StackOverflow
#
# Updated December 5, 2011
# OregonTrail on StackOverflow

from sys import exit
from random import randint

quips = [
    "Welcome!",
    "have a wonderful day",
    "Livers are cool!",
    "this text was chosen at random",
    "Writen in python",
    "woo, splash text!",
    "Notch loves ez!",
    "Almost dragon free!"
]

print quips[randint(0, len(quips)-1)]

def first_thing():
    print ("You are a liver, congratulations! "
           "You should do some liver stuff now.")
    print "Here comes some blood, what should you do?"
    filterblood = raw_input ("> ")

    if filterblood in ("filter", "filter blood", "filter the blood"):
        return 'second_thing'

    elif filterblood == "who cares":
        print "I care, be more considorate!"
        return "first_thing"

    else:
        print "Sorry, no (Hint, it is your main purpose!)"
        return "first_thing"

def second_thing():
    print "You are now filtering the blood, good for you!"
    print "oh no! There is too much aldosterone! what would that do?"
    fluidz = raw_input ("> ")

    if fluidz in ("retain fluid", "fluid retention", "keep fluids",
                  "keep fluid"):
        return 'third_thing'

    else:
        print "nope! (hint, what does aldosterone do?)"
        return "second_thing"

def third_thing():
    print "Oh no!, that's bad!"
    print "What should you do about that aldosterone?"
    metabolize = raw_input ("> ")

    if metabolize == "metabolize":
        return 'fourth_thing'

    else:
        print "BRZZZZ, wrong!"
        return "third_thing"

def fourth_thing():
    print "super duper!"
    print ("the aldosterone has been taken care of, no problems at the "
           "current moment")
    print "..."
    print "..."
    print "..."
    print ("After a couple of months a problem arises, you are inflamed, "
           "what could this be?")
    hepatitis = raw_input ("> ")

    if hepatitis == "hepatitis":
        return 'fifth_thing'

    else:
        return "fourth_thing"

def fifth_thing():
    print "OH NO! Hepatitis!"
    print "What could have caused this?"
    idunno_somthing = raw_input ("> ")

    if idunno_somthing in ("infection", "an infection"):
        print "neat, thats no good."
        print "thank you for coming"
        exit (0)

    elif idunno_somthing in ("sex", "drugs", "rock n roll"):
        print "very funny, what specificly caused it?"
        return "fifth_thing"

    else:
        return "fifth_thing"

ROOMS = {
    'first_thing': first_thing,
    'second_thing': second_thing,
    'third_thing': third_thing,
    'fourth_thing': fourth_thing,
    'fifth_thing': fifth_thing
}

def runner(rooms, start):
    nextRoom = start
    while True:
        room = rooms[nextRoom]
        print "--------"
        nextRoom = room()

runner(ROOMS, 'first_thing')

rawDescription: This is probably a trivial overlook, just starting out with python


code:
import csv

country_to_prefix = {}

with open("countrylist.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        country_to_prefix[row["ISO 3166-1 2 Letter Code"]] = row["ITU-T Telephone Code"]

print country_to_prefix["US"] # +1
print country_to_prefix["GB"] # +44
print country_to_prefix["CL"] # +56

rawDescription: get a phone number's international prefix from a country code in python

description: Get a phone number's international prefix from a country code in python


code:
import json

with open('numbers') as f:
    numbers = json.load(f)

print numbers['+27792955555']    #  De Wet

rawDescription: How to store a Python dictionary as an Environment Variable

description: Store a Python dictionary as an Environment Variable


code:
from tkinter import *
from functools import partial

canvas_height = 400
canvas_width = 600
canvas_colour = "grey50"
moveBoolean = "True"

def move_it(ctr=0):
    if ctr < len(coords):
        x, y = coords[ctr]
        ctr += 1
        print ctr, x, y
        canvas.move(square, x, y)
        window.after(1000, partial(move_it, ctr))

window = Tk()

canvas = Canvas(bg=canvas_colour, height=canvas_height,
         width=canvas_width, highlightthickness=0)
canvas.pack()

square = canvas.create_rectangle(50, 50, 50, 50, width=50, fill="black")

coords = ((90, 90),
          (180, 180),
          (50, 50))
move_it()

window.mainloop()

rawDescription: Tkinter window not opening

description: Tkinter window not opening


code:
import os
import sys
import time

# acquire: open file for write, create if possible, exclusive access guaranteed
fname = 'my_lock_file.pid'
try:
    fd = os.open(fname, os.O_CREAT|os.O_WRONLY|os.O_EXCL)
except OSError:
    # failed to open, another process is running
    with open(fname) as f:
        print "other process running:", f.readline()
        sys.exit()

try:
    os.write(fd, '%d\n' % os.getpid())
    os.fsync(fd)
    # do something
    time.sleep(5)
finally:
    os.close(fd)
    # release: delete file
    os.remove(fname)

rawDescription: How to delete a locked (flock) file without race condition: before or after releasing the lock?

description: Delete a locked (flock) file without race condition: before or after releasing the lock


code:
target = '''
LINCOLN STREET
CHESTNUT ST
CHISHOLM TR
LAKE TRAIL
CHISHOLM TRAIL
COVERED WAGON TRL
'''

import re
print re.sub('\s+(STREET|ST|TRAIL|TRL|TR)\s*$', '', target, flags=re.M)

rawDescription: regex match and replace multiple patterns

description: Regex match and replace multiple patterns


code:
def sim_function(row_set, set_from_listofsets): # Note that the arguments are reversed from what you had before
    pass

def find_similar(db, num, listofsets):
    pool = Pool()
    threshold = 0.49

    similar_db_rows=[]
    for row in db.execute("SELECT thing1, thing2, thing3 FROM table WHERE num !={n};".format(n=num)):
            func = partial(sim_function, set(row[3].strip().split(',')))
            list_process_results = pool.map(func, listofsets)
            print list_process_results

            if any(t < threshold for t in list_process_results):
                #print "appending a row"
                similar_db_rows.append(row)
    pool.close()
    pool.join()

rawDescription: Python multiprocessing issue with arguments set/list completion of processes


code:
class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        # The int() call is for Python 3
        return int(dict.__len__(self) / 2)

d = TwoWayDict()
for i in range(10):
    d["FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l"+str(i)] = str(i)

for i in range(10):
    print d['FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l'+str(i)], "<->", d[str(i)]

rawDescription: Python: encode/decode a string in Django


code:
def main():
    print 'doing stuff'
    foo()
    bar()

def foo():
    print 'inside foo'

def bar():
    print 'inside bar'

if __name__ == '__main__':
    main()

rawDescription: Python Method Placement

description: Python Method Placement


code:
parser = argparse.ArgumentParser(description="Will take arguments... or none")

parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")

args = parser.parse_args()
if not (args.b or args.c or args.d):
    args.a=True
print args

rawDescription: How can I get argparse to set a flag to True if that flag is selected or none are selected, but discard that flag if I select another one?

description: Get argparse to set a flag to True if that flag is selected or none are selected, but discard that flag if I select another one


code:
xml = '<ParameterGroup name="Experiment_22">\
<Parameter name="Data is Row Oriented" type="bool" value="1"/>\
<Parameter name="Experiment Type" type="unsignedInteger" value="0"/>\
<Parameter name="File Name" type="file" value="Cyp26A1_atRA_minus_tet_plus.txt"/>\
<Parameter name="First Row" type="unsignedInteger" value="1"/>\
</ParameterGroup>'

from bs4 import BeautifulSoup
import os
soup = BeautifulSoup(xml)

for tag in soup.find_all("parameter", {'name': 'File Name'}):
    tag['value'] = os.path.join('new_dir', tag['value'])

print soup

rawDescription: Identify and replace elements of XML using BeautifulSoup in Python


code:
import numpy as np

# Make some fake data:
x = np.zeros(10, dtype={'names':['P', 'TEST'], 'formats':[np.int, '|S5']})
x['P'] = np.arange(10)
x['TEST'] = ['GENO', 'TREND', 'ALLEL', 'DOM', 'REC',
             'GENO', 'TREND', 'DOM', 'ALLEL', 'REC']

# Get values in field "P" where field "TEST" == "GENO":
print x['P'][x['TEST'] == 'GENO']

rawDescription: numpy: query a data from masked record?

description: Numpy: query a data from masked record


code:
import time

def record(mylist, duration, count):
    start_time=time.time()
    while len(mylist) < count:
        mylist.append(1)

    remaining_time = time.time() - start_time;
    time.sleep(duration - remaining_time)

print "calling first pass"
start_time=time.time()
l1 = []
record(l1, 5, 100)  #second time
actual_duration = time.time() - start_time
print "length is", len(l1), "actual time was", actual_duration

print "calling second pass"
start_time=time.time()
l2 = []
record(l2, 5, 100)  #second time
actual_duration = time.time() - start_time
print "length is", len(l2), "actual time was", actual_duration

rawDescription: Run a function for a duration of 5 secs exactly every time using time.time() in python


code:
'тест'
bytelist = ['\xd1', '\x82', '\xd0', '\xb5', '\xd1', '\x81', '\xd1', '\x82']
''.join(bytelist).decode('utf-8')
print ''.join(bytelist).decode('utf-8') # encodes to the terminal encoding
''.join(bytelist) == 'тест'

rawDescription: How to convert list of bytes (unicode) to Python string?

description: Convert list of bytes (unicode) to Python string


code:
import libvirt

conn = libvirt.openReadOnly(None)  # $LIBVIRT_DEFAULT_URI, or give a URI here
assert conn, 'Failed to open connection'

names = conn.listDefinedDomains()
domains = map(conn.lookupByName, names)

ids = conn.listDomainsID()
running = map(conn.lookupByID, ids)

columns = 3

states = {
    libvirt.VIR_DOMAIN_NOSTATE: 'no state',
    libvirt.VIR_DOMAIN_RUNNING: 'running',
    libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
    libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
    libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
    libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
    libvirt.VIR_DOMAIN_CRASHED: 'crashed',
}
def info(dom):
    [state, maxmem, mem, ncpu, cputime] = dom.info()
    return '%s is %s,' % (dom.name(), states.get(state, state))

print 'Defined domains:'
for row in map(None, *[iter(domains)] * columns):
    for domain in row:
        if domain:
            print info(domain),
    print
print

print 'Running domains:'
for row in map(None, *[iter(running)] * columns):
    for domain in row:
        if domain:
            print info(domain),
    print

rawDescription: Alternative to virsh (libvirt)

description: Alternative to virsh (libvirt)


code:
if charint >= 65 and charint <=90:
        cipher_int = ((charint-65 + k) % 26)+65
        code_char = chr(cipher_int)
        print code_char,

elif charint >= 97 and charint <=122:
    cipher_int = ((charint-97 + k) % 26)+97
    code_char = chr(cipher_int)
    print code_char,

else:
    print char,

rawDescription: Python: Caesar Cipher, If statement and else statement both True at the same time?


code:
def handle(self, item, column):
    self.treeWidget.blockSignals(True)
    if item.checkState(column) == QtCore.Qt.Checked:
        self.handleChecked(item, column)
    elif item.checkState(column) == QtCore.Qt.Unchecked:
        self.handleUnchecked(item, column)
    self.treeWidget.blockSignals(False)

class TreeWidgetItem(QtGui.QTreeWidgetItem):
    def setData(self, column, role, value):
        state = self.checkState(column)
        QtGui.QTreeWidgetItem.setData(self, column, role, value)
        if (role == QtCore.Qt.CheckStateRole and
            state != self.checkState(column)):
            treewidget = self.treeWidget()
            if treewidget is not None:
                treewidget.itemChecked.emit(self, column)

class Window(QtGui.QTreeWidget):
    itemChecked = QtCore.pyqtSignal(object, int)

    def __init__(self, rows, columns):
        QtGui.QTreeWidget.__init__(self)
        self.itemChecked.connect(self.handleItemChecked)

    def handleItemChecked(self, item, column):
        print 'ItemChecked', int(item.checkState(column))

rawDescription: How to check state of QTreeWidget Item?

description: Check state of QTreeWidget Item


rawDescription: morse potential fit using python and curve fit from scipy

description: Morse potential fit using python and curve fit from scipy


code:
query = db.session.query(Empleado)

if form.nombre.data != '':
    query = query.filter_by(nombre=form.nombre.data.lower())
if form.apellido.data != '':
    query = query.filter_by(apellido=form.apellido.data.lower())
if form.departamento.data != '':
    query = query.filter_by(departamento_id=form.departamento.data)

print query.all()

rawDescription: Python, SqlAlchemy. How to make a more efficient search?


code:
jechoota = "diddiimaa adadii babaxxee babbareedaa gaggaarii guguddaa hahhamaa hahapphii"

token = jechoota.split()
def stem(word):
    if(word[0] == word[2] and word[1] == word[3]):
        stemed = word[2:]
    elif(word[0] == word[2] and word[0] == word[3] and word[1] == word[4]):
        stemed = word[3:]
    return stemed
for i in token:
    print stem(i)

rawDescription: python stemming words for local languages

description: Python stemming words for local languages


code:
from bs4 import BeautifulSoup

doc = BeautifulSoup(xmlstring, 'xml')

print doc.prettify()

rawDescription: XML Prettifying from file in Python

description: XML Prettifying from file in Python


code:
#!/usr/bin/python

from AppKit import *

pb = NSPasteboard.generalPasteboard()
pbstring = pb.stringForType_(NSStringPboardType)
print u"Pastboard string: %s".encode("utf-8") % repr(pbstring)

rawDescription: Python get mac clipboard contents

description: Python get mac clipboard contents


code:
from multiprocessing import Process

from tornado import ioloop
from tornadoadapter.applications import APPLICATION

def run_server():
    print "Service running on port 8000"
    APPLICATION.listen(8000)
    ioloop.IOLoop.instance().start()

def before_all(context):
    context.server_thread = Process(target=run_server)
    context.server_thread.deamon = True
    context.server_thread.start()

rawDescription: How to run Tornado IO Loop during Behave environment setup

description: Run Tornado IO Loop during Behave environment setup


code:
print xy.index(min(xy))
# 6

rawDescription: Find the smallest number in a python list and print the position


code:
import unicodedata
for codepoint in range(2**16):
    chr = unichr(codepoint)
    if chr.isnumeric() and not chr.isdigit():
        print u'{:04x}: {} ({})'.format(codepoint, chr, unicodedata.name(chr, 'UNNAMED'))

rawDescription: Difference between unicode.isdigit() and unicode.isnumeric()


code:
matrix = np.random.random([1024, 64])  # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids]  # prints a matrix of shape [4, 64]

rawDescription: What does tf.nn.embedding_lookup function do?


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

x = [
    np.array([0, 1., 2, 3, 4]),
    np.array([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]),
    np.array([0, 2., 4])
]
y = [
    np.array([0, 0, 1., 0, 0]),
    np.array([1, 0.75, 0.5, 0.25, .25, 0, .5, 0.75, 1]),
    np.array([0, 1., 0,])
]

N = 30
xd = np.linspace(0, 4, 30)

data = np.zeros((len(x), N), dtype=np.float)
print data.shape

for i in range(len(x)):
    xi, yi = x[i], y[i]
    f = interpolate.interp1d(x[i], y[i], kind="nearest")
    data[i] = f(xd)

fig, ax = plt.subplots()
i = ax.imshow(data, cmap=cm.gray, interpolation='nearest')
#fig.colorbar(i)

plt.show()

rawDescription: Brightness plot (or image) with rows corresponding to arrays of varying length


code:
for root, dirs, files in os.walk(os.getcwd()):
    for name in dirs:
        try:
            os.rmdir(os.path.join(root, name))
        except WindowsError:
            print 'Skipping', os.path.join(root, name)

rawDescription: Ways to Move up and Down the dir structure in Python


code:
from lxml import etree
import resource

class InfiniteXML (object):
    def __init__(self):
        self._root = True
    def read(self, len=None):
        if self._root:
            self._root=False
            return "<?xml version='1.0' encoding='US-ASCII'?><records>\n"
        else:
            return """<record>\n\t<ancestor attribute="value">text value</ancestor>\n</record>\n"""

def parse(fp):
    context = etree.iterparse(fp, events=('end',))
    for action, elem in context:
        if elem.tag=='record':
            # processing goes here
            pass

        #memory usage
        print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

        # cleanup
        # first empty children from current element
            # This is not absolutely necessary if you are also deleting siblings,
            # but it will allow you to free memory earlier.
        elem.clear()
        # second, delete previous siblings (records)
        while elem.getprevious() is not None:
            del elem.getparent()[0]
        # make sure you have no references to Element objects outside the loop

parse(InfiniteXML())

rawDescription: Python sax to lxml for 80+GB XML

description: Python sax to lxml for 80+GB XML


code:
from apscheduler.schedulers.background import BackgroundScheduler
def some_job():
    print "successfully finished job!"
apsched = BackgroundScheduler()
apsched.start()
apsched.add_job(my_job, 'interval', seconds=10)

rawDescription: Redis or threads in Python/Heroku?

description: Redis or threads in Python/Heroku


code:
for sd, i  in enumerate(exons[name]):
    if snpos<=max(i) and snpos>=min(i):
        print sd+1,name
        break

rawDescription: Determine location given a dictionary with lists inside of a list


code:
nsmap = {'xmlns': 'urn:tva:metadata:2010'}

for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap):
    print info.get('programId') # retrieve crid
    print info.find('.//xmlns:Title', namespaces=nsmap).text # retrieve title
    print info.find('.//xmlns:Genre/xmlns:Name', namespaces=nsmap).text # retrieve genre

rawDescription: Need help understanding XPATH in a specific XML example


code:
visitors = dict()
# this should be same for each line
line = '95.11.113.x - [15/Nov/2013]'
ip = line.split(" - ")[0]  # assuming it must have " - " in line
visitors[ip] = line

# finally when you are done with above things
for visitor in visitors:
    print visitors[visitor]

rawDescription: Extract a list of unique visitors from a log file


code:
#!/usr/bin/env python

import glob
import gzip
import subprocess

for f in glob.glob('logs/*'):
  if f.endswith('.gz'):
    # Open a compressed file. Here is the easy way:
    #   file = gzip.open(f, 'rb')
    # Or, here is the hard way:
    proc = subprocess.Popen(['zcat', f], stdout=subprocess.PIPE)
    file = proc.stdout
  else:
    # Otherwise, it must be a regular file
    file = open(f, 'rb')

  # Process file, for example:
  print f, file.readline()

rawDescription: How to test a directory of files for gzip and uncompress gzipped files in Python using zcat?

description: Test a directory of files for gzip and uncompress gzipped files in Python using zcat


code:
lst = []
lst.append('hello')  # appends 'hello' to the list
lst
result = lst.append('world')  # append method returns None
result  # nothing is displayed
print result
lst  # the list contains 'world' as well now

rawDescription: a=list().append("hello") vs a=list(); a.append("hello") in python?

description: A=list().append("hello") vs a=list(); a.append("hello") in python


code:
@app.task(bind=True)
def task_with_context(self, *args, **kwargs):
    print self.request.is_eager, self.request.called_directly

rawDescription: In Django Celery how can I tell if a task has been executed asynchronously


rawDescription: Python: Boolean return if arbitrary element is in arbitrary list


code:
dict_grade= {'Alice':[68,70,90], 'Chris':[95,90,87], 'Cindy':[89,80,75], 'Adam':[75,70,69], 'Richard':[81,80,93], 'Ryan':[51,62,70], 'Edward':[88,90,94], 'Larry':[93,95,97], 'Seth':[67,70,80]}
def get_avg(record):
    return sum(record)/ float(len(record))
for k, v in dict_grade.items():
     avg_score =  get_avg(v)
     print 'Name: ', k, 'and the average score is: ', avg_score

rawDescription: Python 2.7.11 Dictionary Assignment (very simple)


code:
with open('/tmp/file1') as f:
  lines1 = f.readlines()

with open('/tmp/file2') as f:
  for line in f:
    if any(line.startswith(x.strip()) for x in lines1):
      print line,

rawDescription: Use python to grep lines from one file out of another file


code:
with open("newfile.txt") as f:
 for num,line in enumerate(f,1):
      print line,'\n',num

rawDescription: Strange behavior for loop in python

description: Strange behavior for loop in python


rawDescription: Python - Creating a list of X's and Y's in every order they can occur


code:
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.dailypress.com"
soup = BeautifulSoup(urllib2.urlopen(url))
most_viewed = soup.find('div', class_=re.compile('mostViewed'))
for item in most_viewed.find_all('a'):
    print item.text.strip()

rawDescription: Using BeautifulSoup only consider a certain part of contents of a webpage


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

#Your new customized QTableView
class CustomQTableView(QTableView):
    def __init__(self, *args, **kwargs):
        QTableView.__init__(self, *args, **kwargs) #Use QTableView constructor

    def keyPressEvent(self, event): #Reimplement the event here, in your case, do nothing
        return

class Model(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = ['Item_A_001','Item_A_002','Item_B_001','Item_B_002']

    def rowCount(self, parent=QModelIndex()):
        return len(self.items)
    def columnCount(self, parent=QModelIndex()):
        return 1

    def data(self, index, role):
        if not index.isValid(): return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()

        row=index.row()
        if row<len(self.items):
            return QVariant(self.items[row])
        else:
            return QVariant()
    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        print "c"
        tableModel=Model(self)

        self.view=CustomQTableView(self) #Call your custom QTableView here
        self.view.setModel(tableModel)
        self.view.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        layout = QVBoxLayout(self)
        layout.addWidget(self.view)
        self.setLayout(layout)

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

rawDescription: How to make QTableView to enter the editing mode only on double-click

description: Make QTableView to enter the editing mode only on double-click


code:
import re
import cPickle as pickle_module
import pickle # Importing just to get dispatch table, not pickling with it.
import copy_reg
import types

from garlicsim.general_misc import address_tools
from garlicsim.general_misc import misc_tools

def is_atomically_pickleable(thing):
    '''
    Return whether `thing` is an atomically pickleable object.

    "Atomically-pickleable" means that it's pickleable without considering any
    other object that it contains or refers to. For example, a `list` is
    atomically pickleable, even if it contains an unpickleable object, like a
    `threading.Lock()`.

    However, the `threading.Lock()` itself is not atomically pickleable.
    '''
    my_type = misc_tools.get_actual_type(thing)
    return _is_type_atomically_pickleable(my_type, thing)

def _is_type_atomically_pickleable(type_, thing=None):
    '''Return whether `type_` is an atomically pickleable type.'''
    try:
        return _is_type_atomically_pickleable.cache[type_]
    except KeyError:
        pass

    if thing is not None:
        assert isinstance(thing, type_)

    # Sub-function in order to do caching without crowding the main algorithm:
    def get_result():

        # We allow a flag for types to painlessly declare whether they're
        # atomically pickleable:
        if hasattr(type_, '_is_atomically_pickleable'):
            return type_._is_atomically_pickleable

        # Weird special case: `threading.Lock` objects don't have `__class__`.
        # We assume that objects that don't have `__class__` can't be pickled.
        # (With the exception of old-style classes themselves.)
        if not hasattr(thing, '__class__') and \
           (not isinstance(thing, types.ClassType)):
            return False

        if not issubclass(type_, object):
            return True

        def assert_legit_pickling_exception(exception):
            '''Assert that `exception` reports a problem in pickling.'''
            message = exception.args[0]
            segments = [
                "can't pickle",
                'should only be shared between processes through inheritance',
                'cannot be passed between processes or pickled'
            ]
            assert any((segment in message) for segment in segments)
            # todo: turn to warning

        if type_ in pickle.Pickler.dispatch:
            return True

        reduce_function = copy_reg.dispatch_table.get(type_)
        if reduce_function:
            try:
                reduce_result = reduce_function(thing)
            except Exception, exception:
                assert_legit_pickling_exception(exception)
                return False
            else:
                return True

        reduce_function = getattr(type_, '__reduce_ex__', None)
        if reduce_function:
            try:
                reduce_result = reduce_function(thing, 0)
                # (The `0` is the protocol argument.)
            except Exception, exception:
                assert_legit_pickling_exception(exception)
                return False
            else:
                return True

        reduce_function = getattr(type_, '__reduce__', None)
        if reduce_function:
            try:
                reduce_result = reduce_function(thing)
            except Exception, exception:
                assert_legit_pickling_exception(exception)
                return False
            else:
                return True

        return False

    result = get_result()
    _is_type_atomically_pickleable.cache[type_] = result
    return result

_is_type_atomically_pickleable.cache = {}

rawDescription: Python: Checking if an object is atomically pickleable


code:
import re
from BeautifulSoup import BeautifulSoup

# find ".html" or ".pdf" in a string
match = re.compile('\.(html|pdf)')

# parse page content
status, response = http.request("http://www.example.com")
page = BeautifulSoup(response)

# check links
for link in page.findAll('a'):
    try:
        href = link['href']
        if re.search(match, href):
            print href
    except KeyError:
        pass

rawDescription: BeautifulSoup SoupStrainer strain html and pdf links


code:
class Foo(object):
    def __init__(self, angle=120):
        self.angle = angle

    def __add__(self, other):
        """Check for recursion, then return the added value."""
        print "Foo.add"
        val = self.angle + other
        while val > 360:
            val -= 360
        while val < 0:
            val += 360
        return val

    def __iadd__(self, other):
        """Augmented addition assignment."""
        print "Foo.iadd"
        val = self.__add__(other)
        self.angle = val

f = Foo()
f += 20

print f is None

rawDescription: Python Magic Method Augmented Assignment misunderstanding


code:
def wheelEvent(self, event):
    print "Wheel Event:"
    for child in self.children()[1:]:
        print child.text(), 'is visible?', not child.visibleRegion().isEmpty()
    event.ignore()

rawDescription: How to find out whether child widget of QScrollArea is visible?

description: Find out whether child widget of QScrollArea is visible


code:
search = Account.search()
response = search[:1].execute()
for hit in response:
    print hit

rawDescription: Elasticsearch DSL limit filter returning more results than specified


code:
from pandas import  DataFrame

df1 = DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})
df2 = DataFrame({'col1':[4,2,5], 'col2':[6,3,5]})

print df2[~df2.isin(df1).all(1)]
print df2[(df2!=df1)].dropna(how='all')
print df2[~(df2==df1)].dropna(how='all')

rawDescription: set difference for pandas

description: Set difference for pandas


code:
from threading import Thread,Event
from time import sleep

class Counter(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.count = 0
        self._stop = Event()

    def run(self):
        while not self._stop.is_set():
            sleep(1)
            self.count+=1

    def stop(self):
        self._stop.set()

count = Counter()

# here we create a thread that counts from 0 to infinity(ish)
count.start()

# raw_input is blocking, so this will halt the main thread until the user presses enter
raw_input("taking input")

# stop and read the counter
count.stop()
print "User took %d seconds to enter input"%count.count

rawDescription: How do I make my code do things in the background

description: Make my code do things in the background


code:
print d
d.groupby('Sp').apply(lambda t: t[t.Count==t.Count.max()])

rawDescription: Python : How can I get Rows which have the max value of the group to which they belong?


code:
import os

direc = os.getcwd() # Get current working directory
ext = '.txt' # Select your file delimiter

file_dict = {} # Create an empty dict

# Select only files with the ext extension
txt_files = [i for i in os.listdir(direc) if os.path.splitext(i)[1] == ext]

# Iterate over your txt files
for f in txt_files:
    # Open them and assign them to file_dict
    with open(os.path.join(direc,f)) as file_object:
        file_dict[f] = file_object.read()

# Iterate over your dict and print the key/val pairs.
for i in file_dict:
    print i, file_dict[i]

rawDescription: Python – files from folder to a dict

description: Python – files from folder to a dict


code:
def comp(old_dict, new_dict):
    for key, old_val in old_dict.items():
        new_val = new_dict[key]  # warning: to be used on keys in both dict
        print 'evolutions for', key
        print 'new content:', [x for x in new_val if x not in old_val]
        print 'removed content:', [x for x in old_val if x not in new_val]
o = {'key1': ['a', 'b', 'c']}
n = {'key1': ['b', 'c', 'd']}
comp(o, n)

rawDescription: iterate dictionary multiple values by keys in python

description: Iterate dictionary multiple values by keys in python


code:
import random
with open("1000.txt", "w") as f:
    for x in range(1000):
        f.write(str(random.randint(0, 9999))+"\n")

def readList():
    infile = raw_input("Please enter the file name: ")
    rawList = list()
    with open(infile, 'r') as infi:
        for line in infi:
            rawList.append(int(line))
    sortedList = sortList(rawList) #function call for sorting the list, returned sorted list is stored
    n = int(raw_input("please enter the nth number in the list you would like to find: "))
    m = int(float(n-1))
    return sortedList, m

def sortList(inpList): #function needs list as input and returns sorted list
    inpList.sort()
    return inpList

if __name__=='__main__': #This is how the main is defined in python
    sortedList, user_num = readList() #function call of readList, returned two objects are stored in variables
    first = sortedList[0]
    lines = len(sortedList)
    minimum_val = min(sortedList)
    maximum_val = max(sortedList)
    if user_num > 1000:
        print user_num, "is greater than 1000!" # you don't need brackets when printing
    elif user_num > lines:
        print "There aren't that many numbers in the list!"
    elif lines < 1000:
        print "WARNING: only", lines, "numbers were read into the list!"
    print user_num
    print minimum_val
    print maximum_val

rawDescription: How to run Python code through multiple function definitions (2.7)

description: Run Python code through multiple function definitions (2.7)


code:
from selenium import selenium
import unittest
import lxml.html

class TestMyDomain(unittest.TestCase):
    def setUp(self):
        self.selenium = selenium("localhost", \
            4444, "*firefox", "http://www.MyDomain.com")
        self.selenium.start()

    def test_mydomain(self):

        htmldoc = open('site-list.html').read()
        url_list = [link for (element, attribute,link,pos) in lxml.html.iterlinks(htmldoc)]
        for url in url_list:

            try:
                sel = self.selenium
                sel.open(url)
                sel.select_window("null")
                js_code = '''
                myDomainWindow = this.browserbot.getUserWindow();
                for(obj in myDomainWindow) {

                   /* This code grabs the OMNITURE tracking pixel img */
                    if ((obj.substring(0,4) == 's_i_') && (myDomainWindow[obj].src)) {
                        var ret = myDomainWindow[obj].src;
                    }
                }
                ret;
                '''
                omniture_url = sel.get_eval(js_code) #parse&process this however you want

            except Exception, e:
                print 'We ran into an error: %s' % (e,)

        self.assertEqual("expectedValue", observedValue)

    def tearDown(self):
        self.selenium.stop()

if __name__ == "__main__":
    unittest.main()

rawDescription: Using Python/Selenium/Best Tool For The Job to get URI of image requests generated through JavaScript?


code:
#!/usr/bin/python
import math

address = raw_input("Enter your address : ")
digits = []

for c in address:
    if c.isdigit():
        digits.append(c)

if len(digits) >= 2:
    print "The first number to the power of the second number in your address is : "
    print math.pow(float(digits[0]), float(digits[1]))
else:
    print "Your address contains less than 2 numbers"

rawDescription: How do I find specific characters in a given string?

description: Find specific characters in a given string


code:
import csv
from itertools import groupby
from operator import itemgetter

with open("data.csv", "rb") as f:
    next(f)    # Skip header
    for account, lines in groupby(csv.reader(f), itemgetter(0)):
        gross_amount = 0.
        for line in lines:
            print line
            gross_amount += float(line[2])
        print "The total gross amount for account", account, "is", gross_amount

rawDescription: Parsing a Comma Delimited File With Python and adding currency fields