code:
with open('file.txt', 'r') as file:
    #The file is now open and you can iterate over the lines
    for line in file:
        print line

rawDescription: I need feedback on how to open a file.txt on python


code:
import math

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

if __name__ == '__main__':
    l = [1, 1, 1]
    v = [0, 0, 0]

    h = normalize(add(l, v))
    print h

rawDescription: Vector normalization

description: Vector normalization


code:
labels = ET.findall(label)
alist =[]
for one_label in labels:
     alist.append(etree.tostring(one_label))

print sorted(alist, reverse=True)

rawDescription: lxml findall and reverse order

description: Lxml findall and reverse order


code:
import re, os, shutil
#directory you wish to copy all the files to.
dst = "c:\path\to\dir"
src = "c:\path\to\src\dir"

with open("file.cproj", 'r') as fread:

    for line in fread:
        match = re.search(r'Include',line)
        if match:
            loc = line.split('"')
            #concatenates destination and source path with subdirectory path and copies file over.
            dst_file_path = "%s\%s" % (dst,loc[1])
            (root,file_name) = os.path.splitext(dst_file_path)

            # Creates directory if one doesn't exist

            if not os.path.isdir(root):
                     os.makedirs(root)

            src_file_path = os.path.normcase("%s/%s" % (src,loc[1]))
            shutil.copyfile(src_file_path,dst_file_path)
            print dst + loc[1]

rawDescription: How to copy files from list of files in python

description: Copy files from list of files in python


code:
import time

while True:
    # sleep up until then next 1/2 hour
    time.sleep(1800-time.time()%1800)

    temp = bmp.readTemperature()
    pressure = bmp.readPressure()
    altitude = bmp.readAltitude()

    print "Temperature: %.2f C" % temp
    print "Pressure:    %.2f hPa" % (pressure / 100.0)
    print "Altitude:    %.2f" % altitude

rawDescription: Creating loop for BMP085 Code?

description: Creating loop for BMP085 Code


code:
from csv import DictReader
the_reader = DictReader(open('filename.csv', 'rb'))

for line_dict in the_reader:
  print line_dict
  #{'Name': 'Ted', 'Age': '21', 'Goals': '1', 'Passes': '20', 'Fouls': '1'}

rawDescription: Python3 CSV module and dictionary

description: Python3 CSV module and dictionary


code:
sys_fs_enc = sys.getfilesystemencoding() or 'mbcs'

@staticmethod
def tempDir(prefix=None):
    try: # workaround for http://bugs.python.org/issue1681974 see there
        return tempfile.mkdtemp(prefix=prefix)
    except UnicodeDecodeError:
        try:
            traceback.print_exc()
            print 'Trying to pass temp dir in...'
            tempdir = unicode(tempfile.gettempdir(), sys_fs_enc)
            return tempfile.mkdtemp(prefix=prefix, dir=tempdir)
        except UnicodeDecodeError:
            try:
                traceback.print_exc()
                print 'Trying to encode temp dir prefix...'
                return tempfile.mkdtemp(
                    prefix=prefix.encode(sys_fs_enc)).decode(sys_fs_enc)
            except:
                traceback.print_exc()
                print 'Failed to create tmp dir, Bash will not function ' \
                      'correctly.'

rawDescription: Deal with unicode usernames in python mkdtemp


code:
for i in range(numberOfValues):
    print startValue + i * increment

rawDescription: Basic for loop in Python 3

description: Basic for loop in Python 3


code:
def p(n):
  is_p=[False]*2 + [True]*(n-1)
  for i in range(2, int(n**0.5)):
    if is_p[i]:
        for j in range(i*i, n, i):
            is_p[j] = False
  for i in range(2, n):
    if is_p[i]:
      yield i

print list(p(102))

rawDescription: Sieve of Eratosthenes in Python

description: Sieve of Eratosthenes in Python


code:
A = [0.1,   0.05,  0.05,  0.05,  0.1,   0.1,   0.1]
T = ['19730101', '19730102', '19730103', '19730104', '19730105', '19730106', '19931231']

combined = zip(A, T)
combined = sorted(combined, key=lambda x: x[1]) # Sort on timestamp

splits = []
current_month = None
for a, t in combined:
    month = t[4:6]
    print month
    if not month == current_month:
        splits.append([a,]) # Add new split
        current_month = month
    else:
        splits[-1].append(a) # Add to current split
print splits

rawDescription: Split numpy array into sub-arrays based on conditions


code:
import json
print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4)

rawDescription: How to make Python 2.x Unicode strings not print as u'string'?

description: Make Python 2.x Unicode strings not print as u'string'


code:
import sys
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import resolve1

filename = sys.argv[1]
fp = open(filename, 'rb')

parser = PDFParser(fp)
doc = PDFDocument(parser)
doc.initialize()
fields = resolve1(doc.catalog['AcroForm'])['Fields']
for i in fields:
    field = resolve1(i)
    name, value = field.get('T'), field.get('V')
    print '{0}: {1}'.format(name, value)

rawDescription: How to extract PDF fields from a filled out form in Python?

description: Extract PDF fields from a filled out form in Python


code:
class C:
 def f1(self, arg1): print arg1
 def f2(self): return getattr(self, "f1")

x=C()
x.f2()(1)

rawDescription: python variable method name

description: Python variable method name


code:
from time import time, sleep
import itertools
from threading import Thread, RLock
import signal

class CacheEntry():
  def __init__(self, string, ttl=20):
    self.string = string
    self.expires_at = time() + ttl
    self._expired = False

  def expired(self):
    if self._expired is False:
      return (self.expires_at < time())
    else:
      return self._expired

class CacheList():
  def __init__(self):
    self.entries = []
    self.lock = RLock()

  def add_entry(self, string, ttl=20):
    with self.lock:
        self.entries.append(CacheEntry(string, ttl))

  def read_entries(self):
    with self.lock:
        self.entries = list(itertools.dropwhile(lambda x:x.expired(), self.entries))
        return self.entries

def read_entries(name, slp, cachelist):
  while True:
    print "{}: {}".format(name, ",".join(map(lambda x:x.string, cachelist.read_entries())))
    sleep(slp)

def add_entries(name, ttl, cachelist):
  s = 'A'
  while True:
    cachelist.add_entry(s, ttl)
    print("Added ({}): {}".format(name, s))
    sleep(1)
    s += 'A'

if __name__ == "__main__":
  signal.signal(signal.SIGINT, signal.SIG_DFL)

  cl = CacheList()
  print_threads = []
  print_threads.append(Thread(None, read_entries, args=('t1', 1, cl)))
  # print_threads.append(Thread(None, read_entries, args=('t2', 2, cl)))
  # print_threads.append(Thread(None, read_entries, args=('t3', 3, cl)))

  adder_thread = Thread(None, add_entries, args=('a1', 2, cl))
  adder_thread.start()

  for t in print_threads:
    t.start()

  for t in print_threads:
    t.join()

  adder_thread.join()

rawDescription: Python cache with time to live

description: Python cache with time to live


code:
# abspath to a folder as a string
folder = '/home/myname/a_folder/'
# in windows:
# folder = r'C:\a_folder\'
# or folder = 'C:/a_folder/'

count = 0
lines = 0
for dirname, dirs, files in os.walk(folder):
    for filename in files:
        filename_without_extension, extension = os.path.splitext(filename)
        if extension == '.py':
            count +=1
            with open(os.path.join(dirname, filename), 'r') as f:
                for l in f:
                    lines += 1
print count, lines

rawDescription: Iterate over files in multiple directories or an entire hard drive in python


code:
def bytestomb(b):
    mb = float(b) / (1024*1024)
    return mb

def bytessubidatransferidos():
    interface= 'ppp0'
    for line in open('/proc/net/dev', 'r'):
        if interface in line:
            data = line.split('%s:' % interface)[1].split()
            tx_bytes =  (data[8])
    return bytestomb(tx_bytes)

def bytesbajadatransferidos():
    interface= 'ppp0'
    for line in open('/proc/net/dev', 'r'):
        if interface in line:
            data = line.split('%s:' % interface)[1].split()
            rx_bytes = (data[0])
    return bytestomb(rx_bytes)

print bytessubidatransferidos()
print bytesbajadatransferidos()

rawDescription: Modules or functions to obtain information from a network interface in Python


code:
import paramiko
print paramiko.__version__

rawDescription: How to check paramiko version installed?

description: Check paramiko version installed


code:
while(1):
    print word_2
    #Letting the person guess the word/ letter
    guess_number = int(raw_input("choose a number:  "))
    guess_letter = raw_input("choose a letter:  ")

    i = word.index(guess_letter)
    if word_2[i] == guess_number:
        word_2[i] = guess_letter # put guessed letter into word_2, for example "3 A 20"
        print "Correct: ", word_2
        if word == word_2:
            break
    else:
        print "Nope"
    print "continue guessing"

rawDescription: I'm stuck with a certain task about lists and appending integers and strings


code:
import Tkinter as tk

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.frame_Light = tk.Frame(self, background="bisque")
        self.frame_Light.pack(side="top", fill="both", expand=True)
        self.light_on = True
        self.canvas = tk.Canvas(self.frame_Light)
        self.canvas.create_oval(10, 10, 30, 30, fill="yellow", tags="light")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.draw_light()

    def draw_light(self):

        if self.light_on:
            self.canvas.itemconfig("light", fill="blue")
            self.light_on = False
            print "on"
        else:
            self.canvas.itemconfig("light", fill="red")
            self.light_on = True
            print "of"

        self.after(1000, self.draw_light)

app = App()
app.mainloop()

rawDescription: tkinter canvas not updating color

description: Tkinter canvas not updating color


code:
result = []
while n != 1:
      result.append(n)
      if n % 2 == 0:
          n //= 2
      else:
          n = n * 3 + 1
result.append(n)

print result

rawDescription: How can I put these numbers in list?

description: Put these numbers in list


code:
if __name__ == "__main__":
    from tornado.ioloop import IOLoop
    print IOLoop.instance().run_sync(routine1)

rawDescription: Need help on tornado coroutines

description: Need help on tornado coroutines


code:
for y in range(10):
    print
    i = 10 - y
    print ' ' * (y * 2),  # whitespaces
    for x in range(i):
        print x,
        i = i - 1

rawDescription: python for loop to print multiple lines of a descending range

description: Python for loop to print multiple lines of a descending range


code:
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 6969))
s.listen(10)
c, a = s.accept()

while True:
    data = c.recv(100000)
    if data:
        print data
    else:
        print "Client closed connection"
        break

rawDescription: Python 2.7.8: Socket - Client Server Data loss in TCP socket


code:
import elementtree.ElementTree as ET

html = """

TEXT STRING HERE ......

"""

for e in ET.fromstring(html).getiterator():
    if e.text.find('TEXT STRING HERE') != -1:
        print "Found string %r, element = %r" % (e.text, e)

rawDescription: Finding the parent tag of a text string with ElementTree/lxml


code:
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
while True:
  line = proc.stdout.readline()
  if line != '':
    #the real code does filtering here
    print "test:", line.rstrip()
  else:
    break

rawDescription: read subprocess stdout line by line

description: Read subprocess stdout line by line


code:
tempstring=['DateTime']
while i<=numsensors:
 tempstring.append("%02d"%i +'.Cooked')
 i=i+1
 print tempstring
 writer.writerow(tempstring)

rawDescription: Avoiding quotes around row of string data with csv.writer


code:
m = re.search(r'(FullName=.*?),', str)
if m:
   print m.group(1)

rawDescription: Regex for fixed string followed by characters up to a delimiter character


code:
import multiprocessing

def do_calculation(data):
    """
    @note: you can define your calculation code
    """
    return data * 2

def start_process():
    print 'Starting', multiprocessing.current_process().name

if __name__ == '__main__':
    analsys_jobs = list(range(10))  # could be your analysis work
    print 'analsys_jobs :', analsys_jobs

    pool_size = multiprocessing.cpu_count() * 2
    pool = multiprocessing.Pool(processes=pool_size,
                                initializer=start_process,
                                maxtasksperchild=2, )
    #maxtasksperchild = tells the pool to restart a worker process \
    # after it has finished a few tasks. This can be used to avoid \
    # having long-running workers consume ever more system resources

    pool_outputs = pool.map(do_calculation, analsys_jobs)
    #The result of the map() method is functionally equivalent to the \
    # built-in map(), except that individual tasks run in parallel. \
    # Since the pool is processing its inputs in parallel, close() and join()\
    # can be used to synchronize the main process with the \
    # task processes to ensure proper cleanup.

    pool.close() # no more tasks
    pool.join() # wrap up current tasks

    print 'Pool :', pool_outputs

rawDescription: Subprocess management with python

description: Subprocess management with python


code:
import uuid

class Element(object):
   def __init__(self,element_type):
        self.oid = None
        self.uuid = uuid.uuid4()
        self.key = None
        self.element_type = element_type

   def params(self):
       print 'here Element'
       return dict(uuid=self.uuid, key=self.key)

class Vertex(Element):
   def __init__(self):
       super(Vertex,self).__init__("vertex")

class Person(Vertex):

   def __init__(self,name=None,uri=None,email=None):
       super(Person,self).__init__()
       self.name=name
       self.uri=uri
       self.email = email

   def params(self):
       print 'here Person'
       params = dict(name=self.name,uri=self.uri,email=self.email)
       params.update(super(Person,self).params())
       return params

class User(Person):

   def __init__(self,
                name=None,
                uri=None,
                email=None,
                first_name=None,
                last_name=None,
                facebook_id=None,
                facebook_link=None,
                facebook_username=None,
                gender=None,
                locale=None):
       super(User,self).__init__(name,uri,email)
       self.first_name = first_name
       self.last_name = last_name
       self.facebook_id = facebook_id
       self.facebook_link = facebook_link
       self.facebook_username = facebook_username
       self.gender = gender
       self.locale = locale

   def params(self):
       params = dict(first_name=self.first_name,
                     last_name=self.last_name,
                     facebook_id=self.facebook_id,
                     facebook_link=self.facebook_link,
                     facebook_username=self.facebook_username,
                     gender=self.gender,
                     locale=self.locale)
       print 'here User'
       params.update(super(User, self).params())
       return params

if __name__ == '__main__':
   u = User()
   print '\n'.join(sorted(u.params().keys()))

rawDescription: Using super() Multiple Times in a Python Class


code:
import arrow

start_time = arrow.get(2014, 10, 6, tzinfo='US/Eastern')
end_time = start_time.replace(seconds=400)

print start_time.isoformat()
print end_time.isoformat()

# alternate form

start_time = arrow.get('2014-10-06T18:00:00.000-04:00')
end_time = start_time.replace(seconds=400)

print start_time.isoformat()
print end_time.isoformat()

# get a datetime from an arrow object
start_time_dt = start_time.datetime

rawDescription: Unable to get proper timestamp ranges

description: Unable to get proper timestamp ranges


code:
for key, value in jdata.iteritems():
    print key, value

rawDescription: Parsing JSON string/object in Python

description: Parsing JSON string/object in Python


code:
import boto3

ec2 = boto3.resource('ec2')
insts = list(ec2.instances.all())
for inst in insts:
  for iface in inst.network_interfaces:
    print inst.instance_id, iface.mac_address

rawDescription: How to list MAC Address of an AWS EC2 instance with Python and boto3

description: List MAC Address of an AWS EC2 instance with Python and boto3


code:
#!/usr/bin/python

def travel():
    travel.totrate=0
    def guide():
        print"Due to prefer a guide??"
        print"a guide inperson...rate=1000"
        print"maps,3g....rate=2000"
        ch6=raw_input("ENter your choice")
        if(ch6=="person") or (ch6=="PERSON"):
            increment = 1000
        elif(ch6=="gadget" or ch6=="GADGET"):
            increment = 2000
        else:
            print "invalid"
        travel.totrate += increment
        print travel.totrate

    guide()
travel()

rawDescription: How do I declare a global variable in python?

description: Declare a global variable in python


code:
Family = {'Jim' : ['cool guy', 'has facial hair'],
          'Ned' : ['hot stuff', ' wears Tees']}

query = input("Look up database on whom? > ")
if query in Family.keys():
    for (name, info) in Family.items():
        if name in query or name.lower() in query:
            print("{} is {}".format(name, info))
else:
    print "Print Something - Not in Family"

rawDescription: Python: Problems when iterating over a dictionary


code:
from itertools import islice, izip
iterable = "abcdefg"
for x in izip(iterable, islice(iterable, 1, None)): print x

rawDescription: Elegant / Efficient way of getting one element and the following in an iterable


code:
#!/usr/bin/env python

from sys import argv

def average_values(n1, n2):
    res = 0.5 * (n1 + n2)
    return res

script, file_1 = argv

print "Hello my name is Lenard or, as my creator called me, %s. \
You have been instructed to do this:\n" % script

txt = open(file_1)
print txt.read()
txt.close()

print "The results will be copied to a new Text document but they will also \
be printed at the end of the program, thanks for your preference!"
n1 = int(raw_input("Introduce Number 1, please: "))
n2 = int(raw_input("Introduce Number 2, please: "))

res = average_values(n1, n2)

fname = 'Results.txt'
file_sample = open(fname, 'w')
file_sample.write(str(res))
file_sample.close()

print "Here are the results:..."
print res

file_sample = open(fname, 'r')
print file_sample.read()
file_sample.close()

rawDescription: First program using Functions

description: First program using Functions


code:
import rdflib

g = rdflib.Graph()
has_border_with = rdflib.URIRef('http://www.example.org/has_border_with')
located_in = rdflib.URIRef('http://www.example.org/located_in')

germany = rdflib.URIRef('http://www.example.org/country1')
france = rdflib.URIRef('http://www.example.org/country2')
china = rdflib.URIRef('http://www.example.org/country3')
mongolia = rdflib.URIRef('http://www.example.org/country4')

europa = rdflib.URIRef('http://www.example.org/part1')
asia = rdflib.URIRef('http://www.example.org/part2')

g.add((germany,has_border_with,france))
g.add((china,has_border_with,mongolia))
g.add((germany,located_in,europa))
g.add((france,located_in,europa))
g.add((china,located_in,asia))
g.add((mongolia,located_in,asia))

q = "select ?country where { ?country <http://www.example.org/located_in> <http://www.example.org/part1> }"
x = g.query(q)
print list(x)
# write graph to file, re-read it and query the newly created graph
g.serialize("graph.rdf")
g1 = rdflib.Graph()
g1.parse("graph.rdf", format="xml")
x1 = g1.query(q)
print list(x1)

rawDescription: Is there a Hello World example for SPARQL with RDFLib?


code:
for filename in  os.listdir(r"c:\python26\\"):
  if filename.endswith('.txt') or filename.endswith('.log'): print filename

rawDescription: I defined a search path, but files in otrher folders are being searched


code:
import pylab
import time

pylab.ion() # animation on

# Note the comma after line. This is placed here because
# plot returns a list of lines that are drawn.
line, = pylab.plot(0,1,'ro',markersize=6)
pylab.axis([0,1,0,1])

line.set_xdata([1,2,3])  # update the data
line.set_ydata([1,2,3])
pylab.draw() # draw the points again
time.sleep(6)

line1, = pylab.plot([4],[5],'g*',markersize=8)
pylab.draw()

for i in range(10):
    line.set_xdata([1,2,3])  # update the data
    line.set_ydata([1,2,3])
    pylab.draw() # draw the points again
    time.sleep(1)

print "done up there"
line2, = pylab.plot(3,2,'b^',markersize=6)
pylab.draw()

time.sleep(20)

rawDescription: Basic Animation with matplotlib's pyplot


code:
def indexMatching(seq, condition):
    for i,x in enumerate(seq):
        if condition(x):
            return i
    return -1

class Z(object):
    def __init__(self, name):
        self.name = name

class X(object):
    def __init__(self, zs):
        self.mylist = list(zs)

    def indexByName(self, name):
        return indexMatching(self.mylist, lambda x: x.name==name)

x = X([Z('Fred'), Z('Barney'), Z('Wilma'), Z('Betty')])

print x.indexByName('Wilma')

rawDescription: Python list operations , Lambda Expression


code:
from multiprocessing import Process
import time
import resource
import signal

def do_something():
    import resource
    resource.setrlimit(resource.RLIMIT_CPU, (1,1))
    def f(signo, stackframe):
        raise Exception('stop')
    signal.signal(signal.SIGXCPU, f)
    try:
        while 1:
            print 'hello'
    except:
        print 'aborted'

def run_process_limited_time(function):

    # init Process
    p = Process(target=function, args=())

    # start process
    p.start()

    p.join(2)
    p.terminate()

if __name__ == "__main__":
    run_process_limited_time(do_something)

rawDescription: python 2.7 - run sub-process and terminate it if user time exceeded max time

description: Python 2.7 - run sub-process and terminate it if user time exceeded max time


code:
from celery.result import ResultSet

result_set = ResultSet()
for meta_data_dict in chunk_generator:
    # Add the task to the queue immediately
    result = task.generate_sorts.delay(params, meta_data_dict)
    result_set.add(result)

print "Waiting for results"
results = result_set.join_native()
print "Results:"
# Process the results

rawDescription: Celery add tasks to queue when ready

description: Celery add tasks to queue when ready


code:
f = open('foo.dat','rb') # NOTE b for binary
data = f.read()
print len(data), f.tell()
print repr(data[60:70])

rawDescription: Python stops reading file using read

description: Python stops reading file using read


code:
import matplotlib.pyplot as pyplot

Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.plot(i+1, i+1, color=color,
            marker=mark,
            markerfacecolor='None',
            markeredgecolor=color,
            linestyle = 'None',
            label=`i`)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(numpoints=1)
pyplot.show()

rawDescription: Remove line through marker in matplotlib legend


code:
def previous_and_next(some_iterable):
    items, nexts = tee(some_iterable, 2)
    nexts = chain(islice(nexts, 1, None), [None])
    return izip(items, nexts)

with open(to_file, 'w') as output:
    for line in fhand:
        words = line.split()
        for item, nxt in previous_and_next(words):
            if item == '2':
                words.remove(item)
                words.remove(nxt)
            elif item == '4':
                words.remove(item)
                words.remove(nxt)
        print words
        output.write(str(words)+'\n')

rawDescription: Multiple lists saved in a single text file


code:
import cPickle as pickle
rawinput = msg['payload']
input = rawinput.decode("base64")
data = pickle.loads(input)
print data

rawDescription: base64 'payload' string from rabbitmq queue can't be decoded properly

description: Base64 'payload' string from rabbitmq queue can't be decoded properly


code:
import requests

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'}

with requests.Session() as session:
    session.headers = headers
    session.get('http://nametrends.net/name.php', params={'name': 'ruby'}, headers=headers)

    response = session.get('http://nametrends.net/chartdata/getfrequencyjson.php', params={'name': 'ruby'})
    results = response.json()
    print results

rawDescription: python urllib2 - reading a page after all scripts ran

description: Python urllib2 - reading a page after all scripts ran


code:
from collections import defaultdict

def getDuplicateinTuple(dataInput):
    d = defaultdict(list)
    for t in dataInput:
        item1 = t[1]
        d[item1].append(t)
    return [t for ts in d.itervalues() if len(ts) > 1 for t in ts]

data = [
    ('2013 Jul  5 06:56:07:', 'PATIENT:COUNTER1'),
    ('2013 Jul  5 06:56:07:', 'PATIENT:COUNTER2'),
    ('2013 Jul  5 06:56:07:', 'PATIENT:COUNTER3'),
    ('2013 Jul  5 06:56:07:', 'PATIENT:COUNTER4'),
    ('2013 Jul  5 06:57:11:', 'PATIENT:COUNTER1'),
    ('2013 Jul  5 06:56:11:', 'PATIENT:COUNTER5')
]

data1 = [
    ('2013 Jul  5 04:26:40:', 'PATIENT:COUNTER1', 'COUNTER INFO: : 500 '),
    ('2013 Jul  5 04:26:40:', 'PATIENT:COUNTER2', 'COUNTER INFO: : 500 '),
    ('2013 Jul  5 04:26:40:', 'PATIENT:COUNTER3', 'COUNTER INFO: : 100 '),
    ('2013 Jul  5 04:26:40:', 'PATIENT:COUNTER4', 'COUNTER INFO: : 100 ')
]

print getDuplicateinTuple(data)
# => [('2013 Jul  5 06:56:07:', 'PATIENT:COUNTER1'),
#     ('2013 Jul  5 06:57:11:', 'PATIENT:COUNTER1')]
print getDuplicateinTuple(data1)
# => []

rawDescription: Reporting duplicate from tuple list python (by its index)


code:
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="c:\\temp\\book1.xls",ReadOnly=1)
xl.Application.Run("setA1", '4')
res = xl.Application.Run("getA1")
print res
xl = 0

rawDescription: How to call Excel VBA functions and subs using Python win32com?

description: Call Excel VBA functions and subs using Python win32com


code:
import itertools
import numpy as np

my_array = np.array([[0,1,2],[3,4,5],[6,7,8]])

n = len(my_array)

for r in itertools.combinations(xrange(n), 2):
    rows = np.array(r)
    on = np.zeros(n, dtype=bool)
    on[rows] = True
    print my_array[on]
    print my_array[~on]

rawDescription: Python iterator that generates combinatorial splits


code:
import threading
import time
import random

keep_running = True

def runOften(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)

def runLessOften(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)

def runRandomly(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)

def main():
    global keep_running

    # Create the threads
    threads = []
    threads.append(threading.Thread(target=runOften, args=("Often Runs", 2)))
    threads.append(threading.Thread(target=runLessOften, args=("Less Often Runs!", 2)))
    threads.append(threading.Thread(target=runRandomly, args=("Fast and random", random.random())))

    # Start the threads
    for t in threads:
        t.start()

    # Wait for all of the threads to finish.
    # Note: KeyboardInterrupt will not be raised inside of a call to join()
    #       with no timeout. So we set an arbitrarily large timeout, which
    #       (for whatever reason) allows KeyboardInterrupt to be raised.
    while threads:
        for t in list(threads):          # Iterate over a copy
            try:
                t.join(1000)             # Arbitrary timeout value
                if not t.isAlive():      # If thread finished (join didn't time-out),
                    threads.remove(t)    # We'll no longer join() on it
            except KeyboardInterrupt:    # If we get a Ctrl+C,
                keep_running = False     # Set global flag, telling threads to stop looping

if __name__ == '__main__':
    main()

rawDescription: Python printing nothing?

description: Python printing nothing


code:
assumptions = {'assume01': {'fund1':10, 'fund2':15, 'fund3':12},
               'assume02': {'fund1':1000, 'fund3':950},
               'assume03': {'fund1':3, 'fund2':2, 'fund3':3}}

def fund_assumptions(fund):
    return dict((k, assumptions[k].get(fund)) for k in assumptions)

print fund_assumptions('fund2')
#prints {'assume02': None, 'assume03': 2, 'assume01': 15}

rawDescription: How to Transpose Dictionary Names from one module into Dictionary Keys in another module?


code:
def get_decorator(arg1):
    def my_decorator(function):
        print "get_decorator argument: %s" % arg1
        return function
    return my_decorator

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1
        self.method1 = get_decorator(self.var1)(self.method1)

    def method1(self):
        print "method1"

foo = Foo("abc")
foo.method1()

rawDescription: How can I use a class instance variable as an argument for a method decorator in Python?

description: Use a class instance variable as an argument for a method decorator in Python


code:
s = """

 Heading 1

 Subheading 1.1

Link 1 | Link 2  | Link 3

 Subheading 1.2

Link 1 | Link 2  | Link 3 | Link 4

 Subheading 1.3

Link 1

 Heading 2

 Subheading 2.1

Link 1 | Link 2

 Subheading 2.2

Link 1 | Link 2

 Subheading 2.3

Link 1

 Heading 3

"""

from bs4 import BeautifulSoup as bs

soup = bs(s)

for i in soup.find_all('h2'):
    print i.text
    for j in i.next_siblings:
        if j.name == 'h2': break
        if j.name == 'h3':
            print '\t'+j.text
            for k in j.next_siblings:
                if k.name == 'h3': break
                if k.name == 'a':
                    print '\t\t'+k.text

rawDescription: Python - How to extract elements between multiple tags


code:
import numpy as np
import scipy.stats as ss

def plot_2d_probsurface(data, resolution=20, ax = None, xlim=None, ylim=None):
    # create a function to calcualte the density at a particular location
    kde = ss.gaussian_kde(data.T)

    # calculate the limits if there are no values passed in
    # passed in values are useful if calling this function
    # systematically with different sets of data whose limits
    # aren't consistent
    if xlim is None:
        xlim = (min(data[:,0]), max(data[:,0]))

    if ylim is None:
        ylim = (min(data[:,1]), max(data[:,1]))

    # create some tick marks that will be used to create a grid
    xs = np.linspace(xlim[0], xlim[1], resolution)
    ys = np.linspace(ylim[0], ylim[1], resolution)

    # wrap the KDE function and vectorize it so that we can call it on
    # the entire grid at once
    def calc_prob(x,y):
        return kde([x,y])[0]
    calc_prob = vectorize(calc_prob)

    # check if we've received a plotting surface
    if ax is None:
        fig = plt.figure(figsize=(6,6))
        ax = fig.add_subplot(1,1,1)

    # create the grid and calculate the density at each point
    X,Y = np.meshgrid(xs, ys)
    Z = calc_prob(X,Y)

    # plot the contour
    cont = ax.contour(X,Y,Z)
    point_values = kde(data.T)
    print point_values
    #print cont
    ax.scatter(data[:,0], data[:,1], c=point_values)

    return (None, None)

data_x = np.random.random((50,2))
cont = plot_2d_probsurface(data_x)

rawDescription: Color points according to their contour color


code:
from matplotlib import dates
import matplotlib.pyplot as plt
import numpy as np
import time
from datetime import datetime

# how often to show xticklabels and repeat yticklabels:
xtickinterval = 10

# Make random data
my_data = list()
for i in range(3000):
    my_data.append((datetime.fromtimestamp(i + time.time()), np.random.randint(120, 160), np.random.randint(10, 100)))

hfmt = dates.DateFormatter('%H:%M:%S')
fig = plt.figure()

actg = fig.add_subplot(2, 1, 1)  # two rows, one column, first plot
actg.set_ylim(50, 210)

atoco = fig.add_subplot(2, 1, 2,sharex=actg)  # second plot, share the xaxis with actg
atoco.set_ylim(-5, 105)

# Set the major ticks to the intervals specified above.
actg.xaxis.set_major_locator(dates.MinuteLocator(byminute=np.arange(0,60,xtickinterval)))
# Set the minor ticks to every 30 seconds
minloc = dates.SecondLocator(bysecond=[0,30])
minloc.MAXTICKS = 3000
actg.xaxis.set_minor_locator(minloc)
# Use the formatter specified above
actg.xaxis.set_major_formatter(hfmt)

times = []
fhr1 = []
toco = []

for key in my_data:
    times.append(key[0])
    fhr1.append(key[1])
    toco.append(key[2])

print times[-1]-times[0]

# Make your plot
actg.plot_date(times, fhr1, '-')
atoco.plot_date(times, toco, '-')

for ax in [actg,atoco]:
    # Turn off the yticklabels on the right hand side
    ax.set_yticklabels([])

    # Set the grids
    ax.xaxis.grid(True,which='both',color='r')
    ax.yaxis.grid(True,which='major',color='r')

    # Create new yticklabels every major tick on the xaxis
    for tick in ax.get_xticks():
        tx = ax.twinx()
        tx.set_ylim(ax.get_ylim())
        tx.spines['right'].set_position(('data',tick))
        tx.spines['right'].set_color('None')
        for tic in tx.yaxis.get_major_ticks():
            tic.tick1On = tic.tick2On = False

plt.tight_layout()
plt.show()

rawDescription: Is it possible to generate a chart with this very specific background?


code:
states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI",
          "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI",
          "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
          "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT",
          "VT", "VA", "WA", "WV", "WI", "WY"]
if lead_state.upper().strip() not in states:
    print " == msg ==> ERROR! abbreviation not recognized!"

rawDescription: How to have user input state abbreviation and reject or accept in matched with list of abbreviations?

description: Have user input state abbreviation and reject or accept in matched with list of abbreviations


code:
class X:
    def __getitem__(self, i):
        return str(i)

x = X()

print x[2, 3]

rawDescription: Python pixel access object [x, y]

description: Python pixel access object [x, y]


code:
# on module 1
def function_one(parameter):
    return function_two(parameter,parameter)

# on module 2
def function_two(parameter,original_param):
    return function_three(parameter,original_param)

# on module 3
def function_three(parameter,original_param):
    return function_four(parameter,original_param)

# on module 4
def function_four(parameter,original_param):
    return function_five(parameter,original_param)

# on module 5
def function_five(parameter,original_param):
    return function_six(parameter,original_param)

# on module 1
def function_six(parameter,original_param):
    result = "foobar"
    return result # returns foobar

user_input = 'blahblah'
processed = function_one(user_input)
print processed # prints foobar

rawDescription: At certain levels of functions, where does the final function returns the value?


code:
class A(object):
    bar = 1

a = A()
b = A()
b.bar = 2
print a.bar  # outputs 1
A.bar = 3
print a.bar  # outputs 3
print b.bar  # outputs 2

rawDescription: What is the difference between class and data attributes?


code:
class A(object):
   def __repr__(self):
       return 'A()'
   def __nonzero__(self):
       return False
class B(object):
   def __repr__(self):
       return 'B()'
   def __len__(self):
       return 0
class C(object):
   def __repr__(self):
       return 'C()'
   def __cmp__(self, other):
       return 0
class D(object):
   def __repr__(self):
       return 'D()'
   def __eq__(self, other):
       return True
for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
    print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
        (repr(obj), bool(obj), obj == None, obj is None)

rawDescription: Why is "if not someobj:" better than "if someobj == None:" in Python?


code:
if 1:
    print 1

rawDescription: Python command line: ignore indentation

description: Python command line: ignore indentation


code:
dict ={
"modules": [
    {
        "outputs": {
            "AdminAZ1": "value1",
            "AdminAZ2": "value2",
            "AWSRegion": "value6"
       }
    }]
 }
#check if outputs is present
print reduce(lambda x,y: x or y, map(lambda x: "outputs" in x.keys(),dict["modules"]), False)
#return outputs if present
print reduce(lambda x,y: x if x else y, map(lambda x: x["outputs"] if "outputs" in x.keys() else None,dict["modules"]), None)

rawDescription: Python Dict: Find key in a dictionary list


code:
import wx, sys

try:
    import win32gui #, win32con
    WIN32 = True
except:
    WIN32 = False

class BalloonTaskBarIcon(wx.TaskBarIcon):
    """
    Base Taskbar Icon Class
    """
    def __init__(self):
        wx.TaskBarIcon.__init__(self)
        self.icon = None
        self.tooltip = ""

    def ShowBalloon(self, title, text, msec = 0, flags = 0):
        """
        Show Balloon tooltip
         @param title - Title for balloon tooltip
         @param msg   - Balloon tooltip text
         @param msec  - Timeout for balloon tooltip, in milliseconds
         @param flags -  one of wx.ICON_INFORMATION, wx.ICON_WARNING, wx.ICON_ERROR
        """
        if WIN32 and self.IsIconInstalled():
            try:
                self.__SetBalloonTip(self.icon.GetHandle(), title, text, msec, flags)
            except Exception:
                pass # print(e) Silent error

    def __SetBalloonTip(self, hicon, title, msg, msec, flags):

        # translate flags
        infoFlags = 0

        if flags & wx.ICON_INFORMATION:
            infoFlags |= win32gui.NIIF_INFO
        elif flags & wx.ICON_WARNING:
            infoFlags |= win32gui.NIIF_WARNING
        elif flags & wx.ICON_ERROR:
            infoFlags |= win32gui.NIIF_ERROR

        # Show balloon
        lpdata = (self.__GetIconHandle(),   # hWnd
                  99,                       # ID
                  win32gui.NIF_MESSAGE|win32gui.NIF_INFO|win32gui.NIF_ICON, # flags: Combination of NIF_* flags
                  0,                        # CallbackMessage: Message id to be pass to hWnd when processing messages
                  hicon,                    # hIcon: Handle to the icon to be displayed
                  '',                       # Tip: Tooltip text
                  msg,                      # Info: Balloon tooltip text
                  msec,                     # Timeout: Timeout for balloon tooltip, in milliseconds
                  title,                    # InfoTitle: Title for balloon tooltip
                  infoFlags                 # InfoFlags: Combination of NIIF_* flags
                  )
        win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, lpdata)

        self.SetIcon(self.icon, self.tooltip)   # Hack: because we have no access to the real CallbackMessage value

    def __GetIconHandle(self):
        """
        Find the icon window.
        This is ugly but for now there is no way to find this window directly from wx
        """
        if not hasattr(self, "_chwnd"):
            try:
                for handle in wx.GetTopLevelWindows():
                    if handle.GetWindowStyle():
                        continue
                    handle = handle.GetHandle()
                    if len(win32gui.GetWindowText(handle)) == 0:
                        self._chwnd = handle
                        break
                if not hasattr(self, "_chwnd"):
                    raise Exception
            except:
                raise Exception, "Icon window not found"
        return self._chwnd

    def SetIcon(self, icon, tooltip = ""):
        self.icon = icon
        self.tooltip = tooltip
        wx.TaskBarIcon.SetIcon(self, icon, tooltip)

    def RemoveIcon(self):
        self.icon = None
        self.tooltip = ""
        wx.TaskBarIcon.RemoveIcon(self)

# ===================================================================
app = wx.PySimpleApp()

class TestTaskBarIcon(BalloonTaskBarIcon):

    def __init__(self):
        wx.TaskBarIcon.__init__(self)
        # create a test icon
        bmp = wx.EmptyBitmap(16, 16)
        dc = wx.MemoryDC(bmp)
        dc.SetBrush(wx.RED_BRUSH)
        dc.Clear()
        dc.SelectObject(wx.NullBitmap)

        testicon = wx.EmptyIcon()
        testicon.CopyFromBitmap(bmp)

        self.SetIcon(testicon)
        self.Bind(wx.EVT_TASKBAR_LEFT_UP, lambda e: (self.RemoveIcon(),sys.exit()))

        self.ShowBalloon("", "Hello world!")

icon = TestTaskBarIcon()
app.MainLoop()

rawDescription: Unable to use wx.NotificationMessage properly with wxPython


code:
import wx

def get_path(wildcard):
    app = wx.App(None)
    style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
    dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
    if dialog.ShowModal() == wx.ID_OK:
        path = dialog.GetPath()
    else:
        path = None
    dialog.Destroy()
    return path

print get_path('*.txt')

rawDescription: Python easygui can't select file

description: Python easygui can't select file


code:
print [v for k in my_dict for v in my_dict[k]]
# ['a', 'b', 'c', 'x', 'y', 'z']

rawDescription: Extract and merge lists from dictionary

description: Extract and merge lists from dictionary


code:
def recurse(yaml_data, m):
    for k,v in yaml_data.iteritems():
        if isinstance(v, dict):
            # m = m + "." + k
            recurse(v, m + "." + k)
        else:
            m = m + "." + k
            print str(m)+ " " +str(v)

# In [4]: recurse(yaml_data, 'system')
# system.treeroot.branch2.branch2-1.name 4
# system.treeroot.branch2.name 3
# system.treeroot.branch1.branch1-1.name 2
# system.treeroot.branch1.name 1

rawDescription: Python Convert YAML to string

description: Python Convert YAML to string


code:
lastline = None

with open('test.txt', 'r') as f:
    for line in f.readlines():
        if not lastline:
            lastline = line.rstrip('\n')
            continue
        if line.rstrip('\n') == 'Sequence unavailable':
            _, _, id = lastline.split('|')
            print 'Sequence unavailable|' + id
        lastline = None

rawDescription: Difficulty in selection specific row and merge with specific column


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class MachineSpider(CrawlSpider):
    name = 'weedmaps'
    allowed_domains = ['weedmaps.com']
    start_urls = ['https://weedmaps.com/dispensaries/shakeandbake']

    rules = [
        Rule(LinkExtractor(allow=r'/dispensaries/'), callback='parse_hours')
    ]

    def parse_hours(self, response):
        print response.url

        for hours in response.css('span[itemid="#store"] div.row.hours-row div.col-md-9'):
            print hours.xpath('text()').extract()

rawDescription: Get Web Bot To Properly Crawl All Pages Of A Site


code:
import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

rawDescription: Python - how to count item in json data

description: Python - how to count item in json data


code:
import re
line = '0 1 1 75 55'
x = re.findall("(\d+)", line)
print x

rawDescription: repeating previous regex

description: Repeating previous regex


code:
import xml.etree.ElementTree as etree
from StringIO import StringIO
s = """<?xml version="1.0"?>
<definitions
  name="DateService"
  targetNamespace="http://dev-b.handel-dev.local:8080/DateService.wsdl"
  xmlns:tns="http://dev-b.handel-dev.local:8080/DateService.wsdl"
  xmlns="http://schemas.xmlsoap.org/wsdl/"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:myType="DateType_NS"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
</definitions>"""
file_ = StringIO(s)
namespaces = []
for event, elem in etree.iterparse(file_, events=('start-ns',)):
    print elem

rawDescription: Parsing wsdl (retrieve namespaces from the definitions)using an Element Tree


code:
class ExposedMeta(type):

    def __init__(cls, name, bases, attrs):
        if not "exposed_properties" in attrs:
            cls.exposed_properties = []
        all_props = set(cls.exposed_properties)
        for base in bases:
            all_props.update(getattr(base, "all_exposed_properties", []))
        cls.all_exposed_properties = list(all_props)
        super(ExposedMeta, cls).__init__(name, bases, attrs)

class A(object):
    __metaclass__ = ExposedMeta
    exposed_properties = ['A1', 'A2']

class B(A):
    exposed_properties = ['B']

class C(A):
    pass

class D(object):
    __metaclass__ = ExposedMeta
    exposed_properties = ['D']

class E(B, D):
    exposed_properties = ['E1', 'E2']

for cls in [A, B, C, D, E]:
    print "Class %s, exposed: %s, all exposed: %s" % (cls.__name__, cls.exposed_properties, cls.all_exposed_properties)

rawDescription: How do I concatenate objects stored in an inheritance chain in Python?

description: Concatenate objects stored in an inheritance chain in Python


code:
haystack = 'I like your code "I like your code"'
needle = "code"
replacement = "bucket"

parts = haystack.split('"')
for i in range(0,len(parts),2):
   parts[i] = parts[i].replace(needle,replacement)

print '"'.join(parts)

rawDescription: Ignore characters in quotation marks inside a find and replace algorithm


code:
check = "asdf"
checkLower = check.lower()

print any(checkLower == val.lower() for val in ["qwert", "AsDf"])

# prints true

rawDescription: Python: check if value is in a list no matter the CaSE


code:
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
parsed_xml = etree.XML(s,parser)
for i in parsed_xml.iter('*'):
   print i.tag
   for x in i.items():
      print '%s,%s' % (x[0],x[1])

rawDescription: extract xml tag name, attributes and values

description: Extract xml tag name, attributes and values


code:
import Tkinter
import threading

def create_frame():
    MessFrame = Tkinter.Tk()
    MessFrame.geometry('800x400+200+200')
    MessFrame.title('Main Frame')
    Framelabel = Tkinter.Label(MessFrame, text='Text Here', fg= 'red')
    Framelabel.place(x=10,y=10)
    MessFrame.mainloop()

t1 = threading.Thread(target=create_frame)
t1.start()

#continue
print 1234

rawDescription: Continue code after loop continues?

description: Continue code after loop continues


rawDescription: Filter Python list to remove similar values


code:
l = n * [1]
l.append(10)   # returns None ..
print l        # .. but list was mutated

rawDescription: Creating a list with n integers followed by an integer


code:
someobj = SomeClass()
for _attr in someobj.__dict__:
    # double underscore are mostly used by python
    if not _attr.startswith("__") and not callable(_attr):
        print someobj.__dict__[_attr]

rawDescription: Is it possible to run through instance variables in Python


code:
if myList.count('X') == 2:
    print "count is 2"

rawDescription: How to check for 2 of the same letters

description: Check for 2 of the same letters


code:
# calculate x scale
ax = fig.gca()
foo = ax.get_xmajorticklabels()
bar = [float(foo[i].get_text()) for i in range(len(foo))]
scale_x = bar[1]-bar[0]

# calculate y scale
foo = ax.get_ymajorticklabels()
bar = [float(foo[i].get_text()) for i in range(len(foo))]
scale_y = bar[1]-bar[0]

print scale_x, scale_y

rawDescription: Matplotlib - get value of autoscale

description: Matplotlib - get value of autoscale


code:
import itertools
import operator

L = [("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3), ("denny", 0), ("mark",0)]

print list(itertools.groupby(L, operator.itemgetter(1)).next()[1])

# [('tearing', 3), ('me', 3), ('apart', 3), ('lisa', 3)]

rawDescription: Partitioning a list based on values in tuples - Python


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
from copy import copy

## generate some random data
pts = np.random.uniform(0,10,(10,20,30))

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
patch_collection_instance = ax.scatter(pts[:,0],pts[:,1], pts[:,2], c='m', marker='o')
x, y, z = patch_collection_instance._offsets3d
print x
x = [i + 10 for i in x]
offsets = (x, y, z)
patches2 = copy(patch_collection_instance)
patches2._offsets3d = offsets
patches2._facecolor3d = [[0, 0, 1, 1]]
ax.add_collection3d(patches2)
plt.xlim(0, 20)
plt.show()

rawDescription: Modifying matplotlib patchcollecton3d data


code:
from itertools import groupby

for video, group in groupby(sorted(data, key=lambda x: x[1]), key=lambda x: x[1]):
    times = [x[2] for x in group]
    print 'Video: %s, interval: %f' % (video, max(times) - min(times))

rawDescription: list calculation in python

description: List calculation in python


code:
import shlex

def newSplit(value):
    lex = shlex.shlex(value)
    lex.quotes = '"'
    lex.whitespace_split = True
    lex.commenters = ''
    return list(lex)

print newSplit('''This string has "some double quotes" and 'some single quotes'.''')

rawDescription: Python shlex.split(), ignore single quotes


code:
from os import listdir
from os.path import join

DATA_ROOT = "testdata"

def folder_items_no_regex(month_name):

   # dict holding the items (assuming ordering is irrelevant)
   items = {}

   # 1. Loop through all filenames in said folder
   for file in listdir( join( DATA_ROOT, month_name ) ):
      date, name = file.split( "_", 1 )

      # skip files that were not possible to split on "_"
      if not date or not name:
         continue

      # ignore non-.xml files
      if not name.endswith(".xml"):
         continue

      # cut off the ".xml" extension
      name = name[0:-4]

      # keep a list of filenames
      items.setdefault( name, set() ).add( file )

   return items

def folder_items_regex(month_name):

   import re

   # The pattern:
   # 1. match the beginnning of line "^"
   # 2. capture 1 or more digits ( \d+ )
   # 3. match the "_"
   # 4. capture any character (as few as possible ): (.*?)
   # 5. match ".xml"
   # 6. match the end of line "$"
   pattern = re.compile( r"^(\d+)_(.*?)\.xml$" )

   # dict holding the items (assuming ordering is irrelevant)
   items = {}

   # 1. Loop through all filenames in said folder
   for file in listdir( join( DATA_ROOT, month_name ) ):

      match = pattern.match( file )
      if not match:
         continue

      date, name = match.groups()

      # keep a list of filenames
      items.setdefault( name, set() ).add( file )

   return items
if __name__ == "__main__":
   from pprint import pprint

   data = folder_items_no_regex( "02" )

   print "--- The dict ---------------"
   pprint( data )

   print "--- The items --------------"
   pprint( sorted( data.keys() ) )

   print "--- The files for item1 ---- "
   pprint( sorted( data["item1"] ) )

   data = folder_items_regex( "02" )

   print "--- The dict ---------------"
   pprint( data )

   print "--- The items --------------"
   pprint( sorted( data.keys() ) )

   print "--- The files for item1 ---- "
   pprint( sorted( data["item1"] ) )

rawDescription: Python file manipulation

description: Python file manipulation


code:
import numpy
import theano
import theano.tensor as tt

def v1():
    # NOTE: [9, 9] element changed to [0, 0]
    # since zero padding must be used for
    # this method
    x_data = [[[1, 1], [1, 1], [0, 0], [0, 0]],
              [[2, 2], [2, 2], [2, 2], [0, 0]],
              [[3, 3], [3, 3], [3, 3], [3, 3]]]
    x = tt.tensor3()
    x.tag.test_value = x_data
    y = x.sum(axis=1)
    f = theano.function([x], outputs=y)
    print f(x_data)

def v2_step(i_t, s_tm1, x, l):
    in_sequence = tt.lt(i_t, l).dimshuffle(0, 'x')
    s_t = s_tm1 + tt.switch(in_sequence, x[i_t], 0)
    return s_t

def v2():
    x_data = [[[1, 1], [1, 1], [0, 0], [9, 9]],
              [[2, 2], [2, 2], [2, 2], [0, 0]],
              [[3, 3], [3, 3], [3, 3], [3, 3]]]
    l_data = [2, 3, 4]
    x = tt.tensor3()
    x.tag.test_value = x_data
    l = tt.lvector()
    l.tag.test_value = l_data
    # Must dimshuffle first because scan can only iterate over first (0'th) axis.
    x_hat = x.dimshuffle(1, 0, 2)
    y, _ = theano.scan(v2_step, sequences=[tt.arange(x_hat.shape[0])],
                       outputs_info=[tt.zeros_like(x_hat[0])],
                       non_sequences=[x_hat, l], strict=True)
    f = theano.function([x, l], outputs=y[-1])
    print f(x_data, l_data)

def v3():
    x_data = [[[1, 1], [1, 1], [0, 0], [9, 9]],
              [[2, 2], [2, 2], [2, 2], [0, 0]],
              [[3, 3], [3, 3], [3, 3], [3, 3]]]
    l_data = [2, 3, 4]
    x = tt.tensor3()
    x.tag.test_value = x_data
    l = tt.lvector()
    l.tag.test_value = l_data
    indexes = tt.arange(x.shape[1]).dimshuffle('x', 0)
    mask = tt.lt(indexes, l.dimshuffle(0, 'x')).dimshuffle(0, 1, 'x')
    y = (mask * x).sum(axis=1)
    f = theano.function([x, l], outputs=y)
    print f(x_data, l_data)

def main():
    theano.config.compute_test_value = 'raise'
    v1()
    v2()
    v3()

main()

rawDescription: Scanning over different dimensions of tensors in theano


code:
lst = ['one', 'two', 'three']
resp = { 'one': num1, 'two': num2, 'three': num3 }

for item in lst:
  print resp[item]

rawDescription: Simplifying small code example

description: Simplifying small code example


code:
def main():
    inGolf = open('golf.txt', 'r')
    names = [] # to store names
    scores = [] # to store scores
    for line in inGolf: # reads file line by line
        line_list = line.split(",") # list formed by each word (separated by comma)
        names.append(line_list[0]) # append to respective list
        scores.append(line_list[1])

    for i in range(len(names)): # printing
        print "{0:20}{1:10}".format(names[i], scores[i]) # 20 and 10 are the field length

    inGolf.close()

def w(numPlayers): # to write the file
    counter = 0
    outGolf = open('golf.txt', 'w')
    while counter < numPlayers:
        name = raw_input("Please enter the player's name:")
        outGolf.write(name + ",") # separate name and score by a comma
        score = input("Please enter that player's score:")
        outGolf.write(str(score) + "\n") # just add a "\n" to write in different line next time
        counter = counter + 1
    outGolf.close()

w(2)
main()

rawDescription: Creating columns with lists read from a file in Python


code:
from pandas import *
from numpy.random import randn
rng = date_range('1/1/2011', periods=7200, freq='H')
ts = Series(randn(len(rng)), index=rng)
for key, data in ts.groupby([rng.year, rng.month]):
    print key, data.sum()

rawDescription: Grouping data by multiple dates in pandas


code:
t1 = ("A", "B", "C")
t2 = ("1", "2", "3")
[x + y for x in t1 for y in t2]
[[x + y for y in t2] for x in t1]
x = _  # assign x to the last value
for row in x:
  print " ".join(row)

for x in t1:
  for y in t2:
    print x + y,  # notice the comma, special print-statement syntax
  print

rawDescription: Group and stack tuples

description: Group and stack tuples


code:
print sum(Score[x] for x in A)
print sum(map(lambda x: Score[x], A))

rawDescription: Most efficient way to calculate this sum in python


code:
max = list[0]
for x in list:
    if x > max:
        max = x
print max

rawDescription: max value of list without max() method

description: Max value of list without max() method


code:
with open(os.path.expanduser('~/file')) as inputfile:
    for eachLine in inputfile:
        print eachLine

rawDescription: Python for line in file?

description: Python for line in file


code:
import numpy as np

a = np.arange(3*3*3).reshape(3,3,3)
z = np.array([[1, 0, 2],
       [2, 2, 1],
       [1, 1, 0]])
i = np.arange(a.shape[0]).repeat(a.shape[0]).reshape(a.shape[0], a.shape[1])
j = i.T
#Should do the same as this. possible more efficient, did not test.
#i, j = np.indices(a[...,0].shape)
print a[i,j,z]

rawDescription: Numpy: Index 3d array by z-index array

description: Numpy: Index 3d array by z-index array


code:
import csv
from pylab import *

with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file
    x = []
    y = []
    for row in spamreader:
        x.append(row[0])
        y.append(row[1])
        print ', '.join(row) #  in each loop, row is getting the data,
                         # first row is [1,1] , then [2,2] and so on

plot(x, y)
show()

rawDescription: How to create a list in python, add values, and take them out

description: Create a list in python, add values, and take them out


code:
from Tkinter import *
from matplotlib.figure import *
import matplotlib

matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = Tk()
graph = Figure(figsize=(5,4), dpi=100)
ax = graph.add_subplot(111)
plot = ax.plot([1,2,3,4],[5,6,2,8])
canvas = FigureCanvasTkAgg(graph, master=root)
canvas.show()
canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))

class Zoom(object):
    def __init__(self):
        self.graph = Figure(figsize=(5,4), dpi=100)
        self.ax = graph.add_subplot(111)

        # should be Rectangle((0,0),0,0)
        self.rect = Rectangle((10,10),100,100)
        self.ax.add_patch(self.rect)

        self.ax.plot([1,2,3,4],[5,6,2,8])
        self.is_pressed = False
        self.x0 = 0.0
        self.y0 = 0.0
        self.x1 = 0.0
        self.y1 = 0.0
        self.aid = graph.canvas.mpl_connect('button_press_event', self.on_press)
        self.bid = graph.canvas.mpl_connect('button_release_event', self.on_release)
        self.cid = graph.canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.is_pressed = True
        if event.xdata is not None and event.ydata is not None:
            self.x0, self.y0 = event.xdata, event.ydata

            print 'press:', self.x0, self.y0

            # only remove old rectangle
            self.rect.set_width(0)
            self.rect.set_height(0)
            self.rect.set_xy((self.x0, self.y0))
            self.ax.figure.canvas.draw()

            # color and linestyle for future motion
            self.rect.set_facecolor('red')
            self.rect.set_linestyle('dashed')

    def on_motion(self, event):
        if self.is_pressed:
            if event.xdata is not None and event.ydata is not None:
                self.x1, self.y1 = event.xdata, event.ydata
                self.rect.set_width(self.x1 - self.x0)
                self.rect.set_height(self.y1 - self.y0)
                self.rect.set_xy((self.x0, self.y0))
                self.ax.figure.canvas.draw()
                print 'rect:', self.x0, self.y0, self.x1, self.y1, (self.x1-self.x0), (self.y1-self.y0)

    def on_release(self, event):
        self.is_pressed = False
        print 'release:', event.xdata, event.ydata

        # change only color and linestyle

        #self.rect.set_width(self.x1 - self.x0)
        #self.rect.set_height(self.y1 - self.y0)
        #self.rect.set_xy((self.x0, self.y0))

        self.rect.set_facecolor('blue')
        self.rect.set_linestyle('solid')
        self.ax.figure.canvas.draw()

my_object = Zoom()
root.mainloop()

rawDescription: Selection area is not showing up in Tkinter


code:
genome = [1,1,1,0,1,0,1,0,1,1]
host = [1,1,0,0,1]
print sum(1 for g, h in zip(genome, host) if g and h)
# or
print sum(g * h for g, h in zip(genome, host))

rawDescription: How can I find matching values in two lists?

description: Find matching values in two lists


code:
import numpy as np

rows, cols = 4, 6
n = 3
d = (n-1)/2
data = np.arange(rows*cols).reshape(rows, cols)
padded = np.pad(data, d, mode='constant')
for x, y in  np.indices(data.shape).reshape(2, -1).T:
    sub = padded[x:x+n, y:y+n]
    print sub
    bootstrap_nxn = np.random.choice(sub.ravel(), (n, n))

rawDescription: Accessing ndarray and discarding invalid positions - Python


code:
from threading import Timer

def x():
    print "Hello"

Timer(10, x, ()).start()
print "World!"

rawDescription: Python understanding the scheduler

description: Python understanding the scheduler


code:
from twisted.enterprise import adbapi

dbpool = adbapi.ConnectionPool('psycopg2', 'mydb', 'andrew', 'password') # replace psycopg2 with your db client name.

def getAge(user):
    return dbpool.runQuery('SELECT age FROM users WHERE name = ?', user)

def printResult(l):
    if l:
        print l[0][0], "years old"
    else:
        print "No such user"

getAge("joe").addCallback(printResult)

rawDescription: Twisted LoopingCall with blocking function


code:
#!/usr/bin/python

import sys
import random

if __name__ == "__main__":
    for line in sys.stdin:
        if random.random() < 0.70:
            print line

rawDescription: Print a percentage of all lines parsed in python


code:
def moveLeadingItem(tokens):
    first = tokens[0]
    del tokens[0]
    tokens[-1].insert(0,first)

Sentence.setParseAction(moveLeadingItem)
print Sentence.parseString("testA foobar testB testC")

rawDescription: Pyparsing: How do I store a token into a following list/group?


code:
import csv
import random

class TilePool(list):
    def __init__(self):
        with open("tiles.csv") as f:
            tiles_csv = csv.reader(f, delimiter=",")
            list.__init__(self, (line[0:2]
                           for line in tiles_csv if len(line[0]) == 1
                           for x in xrange(int(line[2]))))

    def pop(self, tile_count=None):
        # non-empty list is truthy
        assert self, "# Tile Pool is empty"

        if tile_count is None:
            tile_count = 7

        assert tile_count in range(1, 8), "# Tile Count must be between 1 and 7"

        new_tiles = []
        counter = 1
        while self and counter <= tile_count:
            rand_choice = random.choice(self)  # Get a random tile
            new_tiles.append(rand_choice)  # Add it to new_tiles list
            self.remove(rand_choice)  # Delete it from pool
            counter += 1
        return new_tiles

    def view_pool(self):
        if not self:
            print("# Tile Pool is empty")
        else:
            for tile in self:
                print("{letter}: {score}".format(letter=tile[0], score=tile[1]))
            print len(self)

t = TilePool()
t.pop(3)
t.view_pool()

rawDescription: How to properly create a list subclass that returns a list generated from file in python?

description: Properly create a list subclass that returns a list generated from file in python


code:
from lxml import etree
from copy import deepcopy

xml = '''<root xmlns="default_ns">
    <subelement>
        <!-- here we can have an element of any namespace  -->
        <some_prefix:a xmlns:some_prefix="some_namespace">
            <some_prefix:b/>
        </some_prefix:a>
    </subelement>
</root>'''
root = etree.fromstring(xml)
evaluator = etree.XPathEvaluator(root, namespaces={'def':'default_ns'})
child = evaluator.evaluate('//def:subelement/child::*')[0]
child = deepcopy(child)
a_string = etree.tostring(child)
print a_string

rawDescription: Unwanted namespace declaration in lxml XPath


code:
import Tkinter as tk
root = tk.Tk()

def nothing(event=None):
    print "click"

bgbutton= tk.Button(root, )
bgbutton.pack()
bgbutton.configure(relief=tk.GROOVE, borderwidth=5, background="#2244FF", activebackground="#FF0000", highlightcolor="#00FF00")
button= tk.Button(bgbutton, text="Glance at my border", command=nothing)
button.pack()

button.configure(relief=tk.GROOVE, borderwidth=2)

root.mainloop()

rawDescription: Making themed TK button have a border

description: Making themed TK button have a border


code:
def prompt_age(min=11, max=100):
    while True:
        try:
            age = int(raw_input('ENTER YOUR AGE: '))
        except ValueError:
            print 'Please enter a valid number'
            continue
        if not min <= age <= max:
            print 'You are too young/old'
            continue
        return age

rawDescription: Function which asks for age

description: Function which asks for age


code:
def connect():
    print "starting to connect"
    env.host_string = 'vpnuser@10.0.0.70'
    env.password = "vpnuser "
    run("ls -lrth")

rawDescription: Python - Connect to a remote host from tkinter Script


code:
first_set, second_set = {("A", 23), ("B", 15)}, {("X", 23), ("B", 42)}

# Group items based on the first elements, as dictionaries
d1, d2 = {}, {}
for item in first_set:
    d1.setdefault(item[0], []).append(item)
for item in second_set:
    d2.setdefault(item[0], []).append(item)

# Merge the dictionaries to form a list of grouped items
s = [d1.get(key, []) + d2.get(key, []) for key in d1.viewkeys() | d2]

# Filter out all the groups if the length is lesser than 1
print [item for item in s if len(item) > 1]
# [[('B', 15), ('B', 42)]]

rawDescription: python set of tuple intersection

description: Python set of tuple intersection


code:
import calendar
import xml.etree.ElementTree as etree

myCal = calendar.HTMLCalendar(calendar.SUNDAY)
htmlStr = myCal.formatmonth(2009, 7)
htmlStr = htmlStr.replace(" "," ")

root = etree.fromstring(htmlStr)
for elem in root.findall("*//td"):
    if elem.get("class") != "tue":
        continue
    elem.text += "!"

    br = etree.SubElement(elem, "br")
    br.tail = "cool!"

print etree.tostring(root)

rawDescription: python calendar.HTMLCalendar

description: Python calendar.HTMLCalendar


code:
if all(x not in s for x in ignore_list):
    print s

rawDescription: Search a pattern if exists

description: Search a pattern if exists


code:
import Tkinter
import sys
import tkMessageBox

class GUI(Tkinter.Tk):
    """docstring for Values"""
    def __init__(self, parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent

        ###if user hits close button
        def callback():
            if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
                self.destroy()
                sys.exit()

        self.protocol("WM_DELETE_WINDOW", callback)
        self.initialize()

    def initialize(self):
        self.grid()
        stepOne = Tkinter.LabelFrame(self, text=" 1. Enter Values ")
        stepOne.grid(row=0, columnspan=7, sticky='W',padx=5, pady=5, ipadx=5, ipady=5)
        self.Val1Lbl = Tkinter.Label(stepOne,text="Value 1")
        self.Val1Lbl.grid(row=0, column=0, sticky='E', padx=5, pady=2)
        self.Val1Txt = Tkinter.Entry(stepOne)
        self.Val1Txt.grid(row=0, column=1, columnspan=3, pady=2, sticky='WE')
        self.Val2Lbl = Tkinter.Label(stepOne,text="Value 2")
        self.Val2Lbl.grid(row=1, column=0, sticky='E', padx=5, pady=2)
        self.Val2Txt = Tkinter.Entry(stepOne)
        self.Val2Txt.grid(row=1, column=1, columnspan=3, pady=2, sticky='WE')

        self.val1 = None
        self.val2 = None

        self.SubmitBtn = Tkinter.Button(stepOne, text="Submit",command=self.submit)
        self.SubmitBtn.grid(row=4, column=3, sticky='W', padx=5, pady=2)

    def submit(self):
        self.val1 = self.Val1Txt.get()
        if self.val1 == "":
             tkMessageBox.showinfo(message="Value 1 has no values entered")
             return

        self.val2 = self.Val2Txt.get()
        if self.val2 == "":
             tkMessageBox.showinfo(message="Value 2 has no values entered")
             return

        ###Close GUI if Val1 and Val2 have values
        if self.val1 and self.val2:
             self.destroy()

app = GUI(None)
app.title('Values')
app.mainloop()
#calculate values of Val1 and Val2
a=float(app.val1)
b=float(app.val2)
c=a+b
print c

rawDescription: if statement causes tkinter program to hang

description: If statement causes tkinter program to hang


code:
import re
pattern = re.compile("match here")
input = "don't match here, but do match here"
start = input.find(",")
print pattern.search(input, start).span()

rawDescription: Applying a Regex to a Substring Without using String Slice


code:
import couchdb
from couchdb.http import urljoin
from couchdb.client import _encode_view_options
server = couchdb.Server()
db = server['blog']
res = db.view('posts/by_author', key='Mike', reduce=False, include_docs=True)
print urljoin(res.view.resource.url, **_encode_view_options(res.options))

rawDescription: Encoding curl-ready URL for CouchDB, with query options


code:
import unicodedata
print unicodedata.normalize("NFC",u"c\u0327")

rawDescription: How do I reverse Unicode decomposition using Python?

description: Reverse Unicode decomposition using Python


code:
with open('Simon.csv', 'rb') as csvfile:
    myExSpreadSheet = csv.reader(csvfile)
    headers = next(myExSpreadSheet, None)  # grab first row

    for row in myExSpreadSheet:
        if 'cocaColaIsTheBest' in row:
            print headers
            print row

rawDescription: Parsing CSV files in Python

description: Parsing CSV files in Python


code:
from multiprocessing import Process, Manager

def f(d):
    for i in range(10000):
        d['blah'] += 1

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    d['blah'] = 0
    procs = [ Process(target=f, args=(d,)) for _ in range(10) ]
    for p in procs:
        p.start()
    for p in procs:
        p.join()

    print d

rawDescription: How to share a dictionary between multiple processes in python without locking

description: Share a dictionary between multiple processes in python without locking


code:
for word in file('myfile.txt').read().split():
    if 'x' in word and 'z' in word:
        print word

rawDescription: How to display all words that contain these characters?

description: Display all words that contain these characters


code:
import ImageFont, ImageDraw, Image

image = Image.open('hsvwheel.png')
draw = ImageDraw.Draw(image)
txt = "Hello World"
fontsize = 1  # starting font size

# portion of image width you want text width to be
img_fraction = 0.50

font = ImageFont.truetype("arial.ttf", fontsize)
while font.getsize(txt)[0] < img_fraction*image.size[0]:
    # iterate until the text size is just larger than the criteria
    fontsize += 1
    font = ImageFont.truetype("arial.ttf", fontsize)

# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("arial.ttf", fontsize)

print 'final font size',fontsize
draw.text((10, 25), txt, font=font) # put the text on the image
image.save('hsvwheel_txt.png') # save it

rawDescription: PIL how to scale text size in relation to the size of the image


rawDescription: Check if n members of a list are in another list in python


code:
f = open('your_file.txt')
for x in f:
    k = re.search(r"'(user|fullname|birthday)', '(.*)'", x)
    if  k:
        print "{} {}".format(k.group(1), k.group(2))

rawDescription: python extract data from textfile

description: Python extract data from textfile


code:
import re

reviews = [
    "This bike is amazing, but the brake is very poor",
    "This ice maker works great, the price is very reasonable, some bad smell from the ice maker",
    "The food was awesome, but the water was very rude"
    ]

positive_words = set(['amazing', 'great', 'awesome', 'reasonable'])
negative_words = set(['poor', 'bad', 'rude'])

for sentence in reviews:
    tagged = []
    for word in re.split('\W+', sentence):
        tagged.append(word)
        if word.lower() in positive_words:
            tagged.append("POSITIVE")
        elif word.lower() in negative_words:
            tagged.append("NEGATIVE")
    print ' '.join(tagged)

rawDescription: Modifying corpus by inserting codewords using Python


code:
class MetaClass(type):
    @staticmethod
    def wrap(run):
        """Return a wrapped instance method"""
        def outer(self):
            print "PRE",
            return_value = run(self)
            print "POST"
            return return_value
        return outer
    def __new__(cls, name, bases, attrs):
        """If the class has a 'run' method, wrap it"""
        if 'run' in attrs:
            attrs['run'] = cls.wrap(attrs['run'])
        return super(MetaClass, cls).__new__(cls, name, bases, attrs)

class MyClass(object):
    """Use MetaClass to make this class"""
    __metaclass__ = MetaClass
    def run(self): print 'RUN',

myinstance = MyClass()

# Prints PRE RUN POST
myinstance.run()

rawDescription: Python Wrap Class Method

description: Python Wrap Class Method


code:
import random
import time
import wx

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

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        self.flashingText = wx.StaticText(self, label="I flash a LOT!")
        self.flashingText.SetFont(self.font)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update, self.timer)
        self.timer.Start(1000)

    #----------------------------------------------------------------------
    def update(self, event):
        """"""
        now = int(time.time())
        mod = now % 2
        print now
        print mod
        if mod:
            self.flashingText.SetLabel("Current time: %i" % now)
        else:
            self.flashingText.SetLabel("Oops! It's mod zero time!")
        colors = ["blue", "green", "red", "yellow"]
        self.flashingText.SetForegroundColour(random.choice(colors))

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

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Flashing text!")
        panel = MyPanel(self)
        self.Show()

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

rawDescription: Flashing text in wxPython

description: Flashing text in wxPython


code:
import urllib2
url = "http://www.opcom.ro/rapoarte/export_csv_raportPIPsiVolumTranzactionat.php?zi=13&luna=1&an=2012&limba=ro"
request = urllib2.Request(url)
response = urllib2.urlopen(request)
print response.read()

rawDescription: python download file under form with: urllib2 ClientForm

description: Python download file under form with: urllib2 ClientForm


code:
from itertools import product
strs = "123**7*9"
c = strs.count("*")              #count the number of "*"'s
strs = strs.replace("*","{}")    #replace '*'s with '{}' for formatting
for x in product("0123456789",repeat=c):
    print strs.format(*x)               #use `int()` to get an integer

rawDescription: Generate all possible numbers with mask

description: Generate all possible numbers with mask


code:
def partition_list(lst, sep):
    """Slices a list in two, cutting on index matching "sep"

    >>> partition_list(['a', 'b', 'c'], sep='b')
    (['a'], ['c'])
    """
    if sep in lst:
        idx = lst.index(sep)
        return (lst[:idx], lst[idx+1:])
    else:
        return (lst[:], )

def args_to_dict(args):
    """Crudely parses "--blah=123" type arguments into dict like
    {'blah': '123'}
    """
    ret = {}
    for a in args:
        key, _, value = a.partition("=")
        key = key.replace("--", "", 1)
        ret[key] = value

    return ret

if __name__ == '__main__':
    import sys

    # Get stuff before/after the "%%" separator
    string, args = partition_list(sys.argv[1:], "%%")

    # Join input string
    string_joined = " ".join(string)

    # Parse --args=stuff
    d = args_to_dict(args)

    # Do string-interpolation
    print string_joined.format(**d)

rawDescription: Parse Args that aren't declared

description: Parse Args that aren't declared


code:
import random

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # Taken from itertools recipes:
    # https://docs.python.org/2/library/itertools.html#recipes
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

students = ['Joe', 'Sam', 'Bob', 'Jill', 'Paul', 'Eric', 'Chai', 'Chris',
            'Sui', 'Matt', 'Leon', 'Nami', 'Leonard', 'Sai', 'Mike',
            'Julie', 'Jim', 'Holly', 'Marge', 'Ed']

random.shuffle(students)

for first_student, second_student in grouper(students, 2):
    print str(first_student), "and", str(second_student)

rawDescription: Randomly pair items in a list using Python


code:
import lxml.html

htmltree = lxml.html.parse('http://www.google.com/intl/en/about/corporate/index.html')

p_tags = htmltree.xpath('//p')
p_content = [p.text_content() for p in p_tags]

print p_content

rawDescription: Parsing html to get a whole paragraph while avoiding interruption from other tags


code:
name = "oridm"
if name.replace(" ", "").isalpha():
    print "Name is valid"
else:
    print "Name is invalid"

rawDescription: Best way to validate a name in Python

description: Validate a name in Python


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

class MyView(QGraphicsView):
    moved = pyqtSignal(QMouseEvent)

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

    def mouseMoveEvent(self, event):
        # call the base method to be sure the events are forwarded to the scene
        super(MyView, self).mouseMoveEvent(event)

        print "Mouse Pointer is currently hovering at: ", event.pos()
        self.moved.emit(event)

rawDescription: pyQt signals/slots with QtDesigner

description: PyQt signals/slots with QtDesigner


code:
import difflib, re

list_a = ['A', 'B', 'C', 'D', 'F', 'H', 'G']
list_b = ['A', 'C', 'D', 'E', 'H']

for i in difflib.Differ().compare(list_a, list_b):
    differ_char, letter = re.match(r'([\s\-+]) ([A-Z])', i).groups()
    choices = ['  ' + letter, letter + '  ', letter + ' ' + letter]
    print choices[['+', '-', ' '].index(differ_char)] # print lines

rawDescription: Best algorithm to compare two lists in python


code:
word = "alpha"
index = 0

while (index < len(word)):
    print word + "   " + word[::-1]
    word = word[1:] + word[0]
    index += 1

rawDescription: Need help with While Loop

description: Need help with While Loop


code:
import re
import os
r = re.compile(r'\d{2}.+gif$')
for root, dirs, files in os.walk('/home/vinko'):
  l = [os.path.join(root,x) for x in files if r.match(x)]
  if l: print l #Or append to a global list, whatever

rawDescription: How do I search through a folder for the filename that matches a regular expression using Python?

description: Search through a folder for the filename that matches a regular expression using Python


code:
import re
m = re.search(r'\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

rawDescription: Python - Check if the last characters in a string are numbers


code:
h1_element = elm.find('h1',{id:'aiv-content-title'})
num_seasons = h1_element.find('span',{'class':'num-of-seasons'}).getText().strip()
release_year = h1_element.find('span',{'class':'release-year'}).getText().strip()

while h1_element.find('span'):
   h1_element.find('span').extract()
   # This will remove the span elements in the h1 element

print h1_element.getText().strip()
print num_seasons
print release_year

rawDescription: only get the h1 text no span text in python

description: Only get the h1 text no span text in python


code:
import numpy as np

mat = np.arange(16.0).reshape((4,4))

mat_out = np.zeros_like(mat)

mat_out[mat < 6] = 0.2 * mat[mat < 6]  # using a conditional for indexing
# or use a variable for the boolean 'masking' index array
mask1 = np.logical_and(mat >= 6, mat < 10)
mat_out[mask1] = 0.3 * mat[mask1]
mask2 = mat >= 10
mat_out[mask2] = 0.5 * mat[mask2]

print mat
print mat < 6
print mask1
print mat_out

rawDescription: Python array, conditionally change elements on classification


code:
def find_paths(graph, start, path, allpaths, dmax):
    if dmax == 0:
        allpaths.append([start])
    else:
        newpath = path + [start]
        for edge in graph[start]:
            d = graph[start][edge]
            if dmax - d >= 0:
                find_paths(graph, edge, newpath, allpaths, dmax - d)
            else:
                allpaths.append(newpath + [edge])
    return allpaths

graph = {
          1: {2: 33, 3: 15},
          2: {1: 33, 4: 57, 5: 7},
          3: {1: 15},
          4: {2: 57},
          5: {1: 89, 2: 7},
        }

print find_paths(graph, 1, [], [], 50)

rawDescription: Recursion. Find all longest path given a starting point and a maximum distance


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

# Set up global variables
num_threads = 3 #you can set it to any number of threads (although 1 would be enough)

queue = Queue()
url_list = [
    "http://google.com",
    "http://googleeeeeee1111.com"
]

def notify(i, q):
    url = q.get()
    print "Thread %d: notification sent for site: %s" % (i, url)
    q.task_done()

def thread_func(i, q):
    print "Thread %d: started" % i
    while True:
        notify(i, q)
    print "Thread %d: ending" % i

def make_requests():
    while True:
        for url in url_list:
            try:
                request = urllib2.urlopen(url)
                response_code = request.getcode()

                # If the response code was 200, do something
                if response_code == 200:
                    print "URL: %s  -  Success %d" % (url, response_code)
                else:
                    print "Bad response code for %s  -  %d " % (url, response_code)
                    queue.put(url)

            except Exception as e:
                print "ERROR MAKING REQUEST TO %s - %s" % (url, e)
                queue.put(url)
        time.sleep(10)  # wait 10 seconds and start again

if __name__ == "__main__":
    # Set up some threads to fetch the enclosures
    for i in xrange(num_threads):
        worker = Thread(target=thread_func, args=(i, queue))
        worker.setDaemon(True)
        worker.start()

    make_requests()

rawDescription: Python 2.7 threading queue, reuse threads


code:
def closesturl(keyword, website):
    keylist = []
    urllist = []
    closest = []
    urls = []
    urlregex = "(http|https)://[-A-Za-z0-9\\./]+"
    urlmatches = re.finditer(urlregex, website, re.IGNORECASE)
    keymatches = re.finditer(keyword, website, re.IGNORECASE)
    for n in keymatches:
        keylist.append([n.start(), n.end()])
    if(len(keylist) > 0):
        for m in urlmatches:
            urllist.append([m.start(), m.end()])
    if((len(keylist) > 0) and (len(urllist) > 0)):
        for i in range (0, len(keylist)):
            closest.append([abs(urllist[0][0]-keylist[i][0])])
            urls.append(website[urllist[0][0]:urllist[0][1]])
            if(len(urllist) >= 1):
                for j in range (1, len(urllist)):
                    if((abs(urllist[j][0]-keylist[i][0]) < closest[i])):
                        closest[i] = abs(keylist[i][0]-urllist[j][0])
                        urls[i] = website[urllist[j][0]:urllist[j][1]]
                        if((abs(urllist[j][0]-keylist[i][0]) > closest[i])):
                            break # local minimum / inflection point break from url list
    if((len(keylist) > 0) and (len(urllist) > 0)):
        return urls #return website[urllist[index[0]][0]:urllist[index[0]][1]]
    else:
        return ""

    somestring = "hey whats up... http://www.firstlink.com some other test http://www.secondlink.com then mykeyword"
    keyword = "mykeyword"
    print closesturl(keyword, somestring)

rawDescription: Using Regex to Search for HTML links near keywords


code:
import win32api

def get_version_info():
    try:
        filename = APP_FILENAME
        return get_file_properties(filename)['FileVersion']
    except BaseException, err:
        log_error(err.message)
        return '0.0.0.0'

def get_file_properties(filename):
    """
    Read all properties of the given file return them as a dictionary.
    """
    propNames = ('Comments', 'InternalName', 'ProductName',
        'CompanyName', 'LegalCopyright', 'ProductVersion',
        'FileDescription', 'LegalTrademarks', 'PrivateBuild',
        'FileVersion', 'OriginalFilename', 'SpecialBuild')

    props = {'FixedFileInfo': None, 'StringFileInfo': None, 'FileVersion': '0.0.0.0'}

    try:
        # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc
        print filename
        fixedInfo = win32api.GetFileVersionInfo(filename, '\\')
        props['FixedFileInfo'] = fixedInfo
        props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536,
                fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536,
                fixedInfo['FileVersionLS'] % 65536)

        # \VarFileInfo\Translation returns list of available (language, codepage)
        # pairs that can be used to retreive string info. We are using only the first pair.
        lang, codepage = win32api.GetFileVersionInfo(filename, '\\VarFileInfo\\Translation')[0]

        # any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle
        # two are language/codepage pair returned from above

        strInfo = {}
        for propName in propNames:
            strInfoPath = u'\\StringFileInfo\\%04X%04X\\%s' % (lang, codepage, propName)
            ## print str_info
            strInfo[propName] = win32api.GetFileVersionInfo(filename, strInfoPath)

        props['StringFileInfo'] = strInfo
    except BaseException, err:
        log_error(err.message)
    return props

rawDescription: How check application verision information in PySide


code:
urlpatterns = patterns('',
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
    url(ur'(?P<search_word>[ÆØÅæøåa-zA-Z]*)/?$', 'website.views.index_view', name='website_index'),
)

rawDescription: Multiple url dispatches with Regex

description: Multiple url dispatches with Regex


rawDescription: What should be the regex for strings?

description: What should be the regex for strings


code:
def depth(expr):
    if not isinstance(expr, tuple):
        return 0
    # this says: return the maximum depth of any sub-expression + 1
    return max(map(depth, expr)) + 1

print depth(("a", "b"))
# 1
print depth(('+', ('expt', 'x', 2), ('expt', 'y', 2)))
# 2
print depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2))))
# 4

rawDescription: Recursion to find depth of expression

description: Recursion to find depth of expression


code:
import posixpath
import urlparse
from bs4 import BeautifulSoup

html = 'imagesgoogle'
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
    dirpath = posixpath.dirname(urlparse.urlparse(a['href']).path)
    if dirpath and dirpath != '/':
       print dirpath #NOTE: urllib.unquote_plus() may introduce `/`

rawDescription: BeautifulSoup Finding Subdirectories

description: BeautifulSoup Finding Subdirectories


code:
for line in file:
    line = line.strip()
    line = line.upper()

    if len(line) == wordlen:

        # Set some counters/containers.
        pair_is_abbrev = 1 #<-- Marks true/false if pair is in abbrev list.
        cur_letter_indx = 0 #<-- Counts the location we're at in this line.

        # Loop until we find a two-letter sequence that's not an abbrev.
        # or until we hit the end of this line (the word length).
        while(pair_is_abbrev and cur_letter_indx <= wordlen-1):
            cur_pair = line[cur_letter_indx:(cur_letter_indx+2)] #<-- Get current two letters
            pair_is_abbrev = (cur_pair in states) #<-- Python way to check if that pair is in your list of abbrevs.
            cur_letter_indx = cur_letter_indx + 1 #<-- Increment the counter.

        # Once the loop terminates, pair_is_abbrev can only be true if we
        # made it all the way to the end of the line successfully. If so,
        # then we found an all-abbrevs word. Otherwise, move on to the next line.
        if(pair_is_abbrev):
            print "Found a word made of abbreviations that is the right length:"
            print line

rawDescription: easy python program, not easy for me

description: Easy python program, not easy for me


code:
import multiprocessing
from time import sleep

def proc():
    for i in range(10000):
        sleep(.05)

if __name__ == '__main__':
    list = []
    for i in xrange(4):
        p = multiprocessing.process.Process(target=proc, name='name' + str(i))
        p.start()
        list.append(p)

    # Mainthread check which is still alive and which is not.
    while 1:
        for p in list:
            if not p.is_alive():
                print p.name + " is Done!"
                p.join()
                list.remove(p)

rawDescription: Python check proccess still runnig via its name


code:
import wx
class myframe(wx.Frame):
    def __init__(self):
        "Constructor. No arguments"
        wx.Frame.__init__(self, None, size=(2000,2000))
        self.myPanel1 = wx.Panel( self, size=(300, 300) )
        myPanel2 = wx.Panel( self, size=(300, 300) )

        self.myPanel1.SetBackgroundColour("green")
        myPanel2.SetBackgroundColour("red")
        myGridSizer = wx.GridBagSizer()
        myGridSizer.Add(self.myPanel1, pos=(0, 0), span=(1,1), flag=wx.EXPAND)
        myGridSizer.Add(myPanel2, pos=(1, 0), span=(1,1), flag=wx.EXPAND)
        self.SetSizer(myGridSizer)
        self.myPanel1.Bind(wx.EVT_LEFT_DCLICK, self.hideMe)
        myPanel2.Bind(wx.EVT_LEFT_DCLICK, self.showMe)
        myGridSizer.SetEmptyCellSize((0, 0))

    def hideMe(self, event):
        print "hide!"
        self.myPanel1.Hide()
        self.Layout()

    def showMe(self, event):
        print "show!"
        self.myPanel1.Show()
        self.Layout()

if __name__ == "__main__":
    print "Running Demo"
    app = wx.App()
    region = myframe()
    region.Show()
    app.MainLoop()

rawDescription: WxPython: How to move Items in a sizer by showing and hiding items within it


code:
from bs4 import BeautifulSoup
html = '''

       Target Text 1

'''
soup = BeautifulSoup(html)
for td in soup.select('td.target'):
    span = td.select('span.wlb_wrapper')
    if span:
        print span[0].get('data-tconst') # To get `tt0082971`
    print td.a.text.strip() # To get target text

rawDescription: Trouble using BeautifulSoup to parse HTML


code:
#!/usr/bin/python

from optparse import OptionParser

class Permutate:

    email_dict = {}
    email_provider = (
        '@gmail.com',
        '@aol.com',
        '@yahoo.com'
    )

    def __init__(self, fname, lname):
        '''
            vars:
            [fname] - first name of the permutation
            [lname] - last name of the permutation
            [email_combination] - first and last name
        '''
        assert isinstance(fname, str) and isinstance(lname, str), "Only strings may be supplied as names"

        self.fname = fname
        self.lname = lname
        self.email_combination = fname + "." + lname

        for provider in Permutate.email_provider:
            print "%s%s" % (self.email_combination, provider)

def compute_first_last():
    '''
        compute_first_last():
            email_combination = <string> + <string> + <string>
                computes the first name and last name combination plus and email provider.

                Loop through all combinations of first + last + email_provider while the value *is u

                A single combination looks like <fname>.<lname>@<email_provider>
    '''
    parser = OptionParser(usage='%prog -f fname -l lname', version='%prog 1.1')

    parser.add_option('-f', '--fname', dest='fname')
    parser.add_option('-l', '--lname', dest='lname')

    (opt, args) = parser.parse_args()

    perm = Permutate(opt.fname, opt.lname)

if __name__ == '__main__':
    compute_first_last()

rawDescription: Run python script from Python Shell with parameters


code:
from sympy import *

class AlgebraicSet(object):
    def __init__(self, polynomials,field):

        self.polynomials = polynomials
        self.field = field

    def get_symbols(self):

        symbols = set()

        for f in self.polynomials:
            symbols = set(symbols | f.atoms(Symbol))

        return symbols

    def get_coordinate_ring(self):
        poly_ring = self.field.old_poly_ring(*self.get_symbols(),order="ilex")
        return poly_ring / poly_ring.ideal(*self.polynomials)

from sympy.abc import x, y, z

print AlgebraicSet([y**2 - z*x, x*y*2 + z], QQ).get_coordinate_ring()

rawDescription: Polynomial rings where number of generators is not known in sympy


code:
csv = open('login.csv', 'r').read().split('\n')[6].split(';')
username = input("Put your username here: ")
if username == "admin" or username in csv:
    print "Username Found"
else:
    print "Username Not Found"

rawDescription: Check if username is admin OR is in csv file


code:
station_dir = os.listdir(station)
station_file = sorted([f for f in station_dir if f.startswith('OD__CAAL')])
new_files = station_file[-3:]
print new_files[0], new_files[1], new_files[2]

rawDescription: Selecting a set number of files using Python


code:
import re

myString = "This is my tweet check it out http://tinyurl.com/blah"

print re.search("(?P<url>https?://[^\s]+)", myString).group("url")

rawDescription: Extracting a URL in Python

description: Extracting a URL in Python


code:
dict1 = {"foo": "bar"}
dict2 = {"car": "vroom"}
dict(dict1, **dict2)
print "Value 1 is %(foo)s and value 2 is %(car)s" % dict(dict1, **dict2)

rawDescription: Python 2.7 - String Substitution using multiple dictionaries


code:
# Echo client program
import socket

HOST = '127.0.0.1'    # The host
PORT = 3333              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

rawDescription: Call process running on Ubuntu localhost in python


code:
def word_chain(chain_so_far, target, dictionary):
    last_word = chain_so_far[-1]
    if last_word == target:
        print chain_so_far
        return True
    for word in dictionary:
        if have_one_different_letter(word, last_word) and word not in chain_so_far:
            word_chain(chain_so_far + [word], target)

rawDescription: Two functions in a recursive functions?

description: Two functions in a recursive functions


code:
import urllib
url='example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
urllib.unquote(url).decode('utf8')
print urllib.unquote(url).decode('utf8')

rawDescription: Encoding arabic results from Google search


code:
url = xmldoc.getElementsByTagName('link')[1].firstChild.data
print url

rawDescription: Getting a single line from Python output


code:
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]

TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]

# print the top row of team names, tab separated, starting two tabs over:
print '\t\t', '\t'.join(team[0] for team in TeamList)

# for each row in the chart
for team in TeamList:
    # put two tabs between each score difference column
    scoreline = '\t\t'.join(str(team[1] - other[1]) for other in TeamList)
    # and print the team name, a tab, then the score columns
    print team[0], '\t', scoreline

rawDescription: Two-dimensional list in Python?

description: Two-dimensional list in Python


code:
import time
import thread

def input_thread(L):
    derp = raw_input()
    L.append(derp)

def show_thread(foo):
    while 1:
        print "Z is " + repr(Z) # Do not use backtick(`). Use `repr`
        print "\n"
        time.sleep(2)

def main():
    global Z  # declare `Z` as global
    L = []
    thread.start_new_thread(input_thread, (L,))
    thread.start_new_thread(show_thread, (1,))

    while 1:
        if L:
            Z = 2
            # Remove following print statements,
            #   otherwise it will cover the terminal with empty lines.
            #print L[0]  <---------
            #print "\n"  <---------

Z = 1
main()

rawDescription: Global variable cross-thread not updating


code:
import maya.cmds as mc

Shader = mc.ls(type = 'surfaceShader')
for i in Shader:
    con = mc.listConnections('%s.outColor' % i)
    names = mc.listConnections(con, type="mesh")
    print i, "->", ", ".join(names)

rawDescription: Getting the name of the mesh that shader was assigned to


rawDescription: Find biggest value in a python dict

description: Find biggest value in a python dict


code:
rdd = rdd.groupBy(lambda x: x.split(",")[9])
new_rdds = [sc.parallelize(x[1]) for x in rdd.collect()]

for x in new_rdds:
    print x.collect()

rawDescription: Divide rdd with spark

description: Divide rdd with spark