code:
import decimal
numbers = ['5.5','499','1','0.5']
for i in numbers:
  the_number = int(decimal.Decimal(i))
  if the_number / 10:
     the_number = the_number + 10 - (the_number % 10)
  print the_number

rawDescription: round off function in django

description: Round off function in django


code: print "So you're {height} tall.".format(height=height)

rawDescription: How to get rid of forward slash in Python raw_input()

description: Get rid of forward slash in Python raw_input()


code:
in_string  = False
input_str  = 'foo,bar,\n"hihi","hi\nhi"'
output_str = ''

for ch in input_str:
    if ch == '"': in_string = not in_string
    if ch == '\n' and in_string: continue
    output_str += ch

print output_str

rawDescription: How do I removes \n founds between double quotes from a string?

description: Removes \n founds between double quotes from a string


code:
import networkx as NX
import matplotlib.pyplot as PLT
Gh = NX.Graph()
Gh.add_edge("You", "Bike", weight=1.0)
Gh.add_edge("Bike", "Apple", weight=0.9)
Gh.add_edge("Me", "Bike", weight=1.1)
all_nodes = Gh.nodes()
# to scale node size with degree:
scaled_node_size = lambda(node) : NX.degree(Gh, node) * 700
position = NX.spring_layout(Gh)    # just choose a layout scheme
NX.draw_networkx_nodes(Gh, position, node_size=map(scaled_node_size, all_nodes))
NX.draw_network_edges(Gh, position, Gh.edges(), width=1.0, alpha=1.0, edge_color="red")
# now for the Matplotlib part:
PLT.axis("off")
PLT.show()

rawDescription: Arched Relationship Infographic In Python


code:
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
for i in xrange(0, len(food_list), 4):
    print '\t'.join(food_list[i:i+4])

rawDescription: Python: Print in rows

description: Python: Print in rows


code:
# grab input file name from user
read = raw_input("Input filename? ")

# grab output file name from user
write = raw_input("Output filename? ")

# open the files, assign objects to variables
readfile = open(read, "r")
writefile = open(write, "w")

# read each line from input file into list "lines"
lines = readfile.readlines()

# for each line in lines, translate the line and write it to the output file
for line in lines:
    line = toPigLatin(line.strip("\n"))
    writefile.write(line + "\n")

# we're done, close our files!
readfile.close()
writefile.close()
print "Done!"

rawDescription: Python Strings and Piglatin

description: Python Strings and Piglatin


code:
n = 2
while n <= 128:
    print n
    n <<= 1

rawDescription: How to convert expression "<<=1" in Java to Python

description: Convert expression "<<=1" in Java to Python


code:
markets = {}

markets['Walmart'] = "food","bread"
markets['Costco'] = "furniture","electronics"

for k,v in markets.iteritems():  #use items if you are using python 3x
    print k,v

rawDescription: LOOPING LISTS of Lists

description: LOOPING LISTS of Lists


code:
import urllib
from bs4 import BeautifulSoup

# This function will get the Nth link object from the given url.
# To be safe you should make sure the nth link exists (I did not)
def getNthLink(url, n):
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')
    tags = soup('a')
    return tags[n-1]

url = "https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html"

# This iterates 4 times, each time grabbing the 3rd link object
# For convenience it prints the url each time.
for i in xrange(4):
    tag = getNthLink(url,3)
    url = tag.get('href')
    print url

# Finally after 4 times we grab the content from the last tag
print tag.contents[0]

rawDescription: retrieve links from web page using python and BeautifulSoup than select 3 link and run it 4 times

description: Retrieve links from web page using python and BeautifulSoup than select 3 link and run it 4 times


code:
from xml.dom.minidom import Document, parseString
import nltk

sentences = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."

tagged = nltk.sent_tokenize(sentences.strip())
tagged = [nltk.word_tokenize(sent) for sent in tagged]
tagged = [nltk.pos_tag(sent) for sent in tagged]

# Write to xml string
doc = Document()

base = doc.createElement("Document")
doc.appendChild(base)

headline = doc.createElement("headline")
htext = doc.createTextNode("Article Headline")
headline.appendChild(htext)
base.appendChild(headline)

body = doc.createElement("body")
btext = doc.createTextNode(sentences)
headline.appendChild(btext)
base.appendChild(body)

pos_tags = doc.createElement("pos_tags")
tagtext = doc.createTextNode(repr(tagged))
pos_tags.appendChild(tagtext)
base.appendChild(pos_tags)

xmlstring = doc.toxml()

# Read back tagged

doc2 = parseString(xmlstring)
el = doc2.getElementsByTagName("pos_tags")[0]
text = el.firstChild.nodeValue
tagged2 = eval(text)

print "Equal? ", tagged == tagged2

rawDescription: Reading and writing POS tagged sentences from text files using NLTK and Python


code:
import operator,functools
import numpy
class Vector: #encompass the behavior in its own class
    @classmethod
    def dot_product(cls,p1,p2):
        #treat p1 and p2 as tuples
        return numpy.dot(p1,p2)
    @classmethod
    def cross_product(cls,p1,p2):
        #treat p1,p2 as tuples
        return numpy.cross(p1,p2)

class Vector2d: #encapsulate the data in its own class
    def __init__(self,points):
        #validate construction data
       self.points = points
    def __getitem__(self,item): #now this will act like an array
       return self.points[item] #allows indexing
    def __getattr__(self,attr): #allows it to act like a vector (above)
       return functools.partial(getattr(Vector,attr),self.points)

class Vector3d(Vector2d):
    pass

a = Vector2d([2,3])
b = [4,5]
c = Vector3d([2,3,4])
d = [3,4,5]
print a.dot_product(b)
print c.cross_product(d)

rawDescription: Choosing between whether to provide object-oriented implementations or functional implementations of primitives


code:
import types

class Someclass():

  def __init__(self, x):
    self.x = x

  def do(self):
    print self.x

if __name__ == "__main__":

  def patch(self):
    print "goodbye"

  obj = Someclass("hello")
  obj.do  = types.MethodType(patch, obj)

  obj.do()    # prints "goodbye"

rawDescription: How to Convert Java to Python using anonymous object function and overriding a method


code:
s = "You won't need to bring a lot of food with you. Before packing your food you should run through the wish list. All food will be inspected upon arrival."
t = "food"
s.split(t)
result = [part[-5:] for part in s.split(t)[:-1]]
print result
print len(result)

rawDescription: Python script for finding a word in a text and returning text and count


code:
html = '''
<input type="hidden" name="SECRETCODE" value="l53DLeOfj1" />
<input type="hidden" name="NotSoSecretCode" value="Nr4MNjyK" />
'''
soup = BeautifulSoup(html)
print soup.find("input", {"name":"SECRETCODE"})
print soup.find("input", {"name":"NotSoSecretCode"})

rawDescription: Python: Extracting data values from a website


code:
from bs4 import BeautifulSoup
src = """

         www.somewebsite.com/\U+200E

"""
soup = BeautifulSoup(src)
soup.find_all('cite')
soup.find_all('cite', attr={'class': 'vurls'})
soup.find_all('cite', class_='vurls')

rawDescription: BeautifulSoup parse returning empty set

description: BeautifulSoup parse returning empty set


code:
x = ['i like cats', 'i like dogs', 'i like both']

for position in range(len(x)):
    if 'cats' in x[position]:
        print ".".join([x[pos] for pos in range(position-1, position+2) if pos in range(0, len(x))]) + "."

rawDescription: How do I pull the string before and after a specific string in a list without going out of index range?

description: Pull the string before and after a specific string in a list without going out of index range


code:
dictlist = [{'192.168.15.90': {'process': {'master': 1}}},
 {'192.168.15.90': {'process': {'varnish': 1}}},
 {'192.168.15.91': {'process': {'tomcat': 1}}}]

dd = {
'192.168.15.90':
    {'process': {'master': 1,'varnish': 1}},
'192.168.15.91':
    {'process': {'tomcat': 1}
}}

new = {}

# for each dict in the list
for dct in dictlist:
    # get the ip address
    ip, = dct
    # if the ip address is already in the new dict
    if ip in new:
        # copy in the process info
        new[ip]['process'].update(dct[ip]['process'])
    # if the ip address isn't in the new dict yet
    else:
        # add the ip address and its info to the new dict
        new.update(dct)

print dd == new # True!

rawDescription: How to merge a list of dict to one dict

description: Merge a list of dict to one dict


code:
print "to:", new or "EMPTY" , "from:" , old or "EMPTY"
new = []
print "to:", new or "EMPTY" , "from:" , old or "EMPTY"

rawDescription: How to shorten this Python print expression?

description: Shorten this Python print expression


rawDescription: Python Code Shortening

description: Python Code Shortening


code:
from bs4 import BeautifulSoup as bs
data = '''

1.2 GHz Qualcomm Snapdragon 400 Quad Core Processor and 1 GB RAM

Android v4.4 (KitKat) OS

Wi-Fi Enabled

8 GB Internal Memory

Dual SIM (GSM + GSM)

HD Recording

5 MP Primary Camera and 1.3 MP Secondary Camera

4.5-inch HD Display

'''
soup = bs(data)
ul = soup.find('ul', attrs={'class':'fk-key-features'})
for item in ul.find_all('li'):
    print item.get_text().strip()

rawDescription: Extract sub division text of a site using Python


code:
def parse(self, response):
    for tr in response.xpath('//div[@class="section group"][5]/div[@class="col span_2_of_2"][1]/table//tr'):
        if tr.xpath(".//td[@class='i']"):
            name = tr.xpath('./td[1]/a/text()').extract()[0]
            location = tr.xpath('./td[2]//text()').extract()[0]
            print name, location

rawDescription: scrapy spider not returning any results

description: Scrapy spider not returning any results


code:
def main():
    range_dur = [0]
    xrange_dur = [0]

    def do_range():
        start = time.time()
        for i in range(2,10):
            print i
        range_dur[0] += time.time() - start

    def do_xrange():
        start = time.time()
        for i in xrange(2,10):
            print i
        xrange_dur[0] += time.time() - start

    do_range()
    do_xrange()
    print range_dur[0]
    print xrange_dur[0]

if __name__ == '__main__':
    main()

rawDescription: Python variable visibility

description: Python variable visibility


code:
file2=list(csv.reader(open(table2,'r')))
for row in file1:
     print row
     for prow in file2:
         print prow

rawDescription: Python, nested for loop

description: Python, nested for loop


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

im = plt.imshow(np.random.rand(10,10)*255, interpolation='nearest')
fig = plt.gcf()
ax = plt.gca()

class EventHandler:
    def __init__(self):
        fig.canvas.mpl_connect('button_press_event', self.onpress)

    def onpress(self, event):
        if event.inaxes!=ax:
            return
        xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
        value = im.get_array()[xi,yi]
        color = im.cmap(im.norm(value))
        print xi,yi,value,color

handler = EventHandler()

plt.show()

rawDescription: Color values in imshow for matplotlib?

description: Color values in imshow for matplotlib


code:
import urllib

print urllib.unquote("cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf")

rawDescription: How to unescape a query string

description: Unescape a query string


code:
for s in dir(settings):
    print s, ':', getattr(settings, s)

rawDescription: How can iterate over all the settings in Django?


code:
import itertools

def partlst(lst, n):
    """Partition @lst in @n balanced parts, in given order"""
    parts, rest = divmod(len(lst), n)
    lstiter = iter(lst)
    for j in xrange(n):
        plen = len(lst)/n + (1 if rest > 0 else 0)
        rest -= 1
        yield list(itertools.islice(lstiter, plen))

parts =  list(partlst(range(1, 15), 5))
print len(parts)
print parts

rawDescription: Splitting up a list into parts of balanced lengths


code:
#!/usr/bin/env python

print 'Hi mom!'

rawDescription: Standardized python binary location?

description: Standardized python binary location


code:
from itertools import chain
def fetch_data(*args):
    return list(chain.from_iterable(zip(*args)))

a = [ [1,2,3], [4,5,6], [7, 8, 9] ]

print fetch_data(*a)
# [1, 4, 7, 2, 5, 8, 3, 6, 9]

rawDescription: python-2.7 .zip multiple generated lists

description: Python-2.7 .zip multiple generated lists


code:
import _ctypes

def di(obj_id):
    """ reverse of id() function """
    return _ctypes.PyObj_FromPtr(obj_id)

if __name__ == '__main__':
    a = 42
    b = 'answer'
    print di(id(a))  # 42
    print di(id(b))  # answer

rawDescription: Is it possible to dereference variable id's?


code:
text_ = """
MSG1          .STRINGZ   "This is my sample string : "
MEMORYSPACE   .BLKW      9
NEWLINE       .FILL      #10
NEG48         .FILl      #-48

      .END
"""

STRINGZ_ = '.STRINGZ'
line_count_ = 0

lines_ = text_.split('\n')

to_ignore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" ,
            "LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "JMP", "RTI" ,
            "BR", "ST", "STI" , "STR" , "BRz", "BRn" , "HALT"]

label = []
instructions = []

for line in lines_:
    if STRINGZ_ in line:
        stringz_ = line.split(STRINGZ_)[1]
        print stringz_
        print 'len(stringz_): ' + str(len(stringz_))
    elem = line.split() if line.split() else ['']
    if len(elem) > 1 and elem[0] not in to_ignore:
        label.append(elem[0])
        instructions.append(elem[1])
        line_count_ += 1
    elif elem[0] in to_ignore:
        line_count_ += 1

rawDescription: Python: Grabbing an entire string as one element


code:
from myro import *
from math import *

def main():
    z = 3
    a = 2
    b = 2
    x = 3
    y = 3

    lim = 25

    c = (a**x + b**y)**(1.0/z)

    #while int(c) != c:
    while z <= lim:
        while a <= lim:
            while b <= lim:
                while x <= lim:
                    while y <= lim:
                        c = (a**x + b**y)**(1.0/z)
                        print a, b, c, x, y, z
                        if int(c) == c:
                            print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(c) + "^" + str(z)
                            return
                        y = y + 1

                    y = 3
                    print a, b, c, x, y, z
                    x = x + 1

                x = 3
                print a, b, c, x, y, z
                b = b + 1

            b = 3
            print a, b, c, x, y, z
            a = a + 1

        a = 3
        print a, b, c, x, y, z
        z = z + 1

    print "code cycle complete. no numbers meet criteria"

main()

rawDescription: How to compare floating point numbers and integers

description: Compare floating point numbers and integers


code:
import objc
objc.loadBundle('CoreWLAN',
                bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                module_globals=globals())

for iname in CWInterface.interfaceNames():
  interface = CWInterface.interfaceWithName_(iname)
  print """
Interface:      %s
SSID:           %s
Transmit Rate:  %s
Transmit Power: %s
RSSI:           %s""" % (iname, interface.ssid(), interface.transmitRate(),
                         interface.transmitPower(), interface.rssi())

rawDescription: Is there any way to access OS X wi-fi data using Python? (Signal strength, for example)


code:
value, mylist = 3.5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
from bisect import bisect
print bisect(mylist, value)
# 3

rawDescription: Find the index of a value (with approximation) in Python list


code:
import cgi
import os

print "Content-type: text/html"
print ""
print cgi.escape(os.environ["REMOTE_ADDR"])

rawDescription: Is it possible to obtain the IP address from a HTTP Request


code:
food_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
    print '
' + '	'.join(food_list[i:i+4]) + '
'

rawDescription: Python and HTML table

description: Python and HTML table


code:
for dirpath, dirnames, files in os.walk(os.path.abspath(os.curdir)):
    print files

# insert long (or short) list of files here

rawDescription: PYTHON - Search a directory

description: PYTHON - Search a directory


code: print pydoc.text.document(object)

rawDescription: In Python how to construct a str for help(object)


code:
import myModule as myModule
myModule.printY()
print myModule.variableY

myModule.variableX = 10
print myModule.variableX

myModule.printX()

rawDescription: How to declare global variable that is visible to imported module functions

description: Declare global variable that is visible to imported module functions


code:
for link in soup.findAll('td', text='GIS 84F'):     # get the relevant tds
    parent = link.parent                            # get the parent tr
    for a in parent.findAll('a', href=True):        # get all the a tags within
        print a['href']                             # do whatever you want

rawDescription: Getting specific link from a source code Python


code:
import re
import sys
import socket
import encodings.idna
import stringprep

# These characters aren't allowed in domain names that are used
# in XMPP
BAD_DOMAIN_ASCII = "".join([chr(c) for c in range(0,0x2d) +
                    [0x2e, 0x2f] +
                    range(0x3a,0x41) +
                    range(0x5b,0x61) +
                    range(0x7b, 0x80)])

# check bi-directional character validity
def bidi(chars):
    RandAL = map(stringprep.in_table_d1, chars)
    for c in RandAL:
        if c:
            # There is a RandAL char in the string. Must perform further
            # tests:
            # 1) The characters in section 5.8 MUST be prohibited.
            # This is table C.8, which was already checked
            # 2) If a string contains any RandALCat character, the string
            # MUST NOT contain any LCat character.
            if filter(stringprep.in_table_d2, chars):
                raise UnicodeError("Violation of BIDI requirement 2")

            # 3) If a string contains any RandALCat character, a
            # RandALCat character MUST be the first character of the
            # string, and a RandALCat character MUST be the last
            # character of the string.
            if not RandAL[0] or not RandAL[-1]:
                raise UnicodeError("Violation of BIDI requirement 3")

def nodeprep(u):
    chars = list(unicode(u))
    i = 0
    while i < len(chars):
        c = chars[i]
        # map to nothing
        if stringprep.in_table_b1(c):
            del chars[i]
        else:
            # case fold
            chars[i] = stringprep.map_table_b2(c)
            i += 1
    # NFKC
    chars = stringprep.unicodedata.normalize("NFKC", "".join(chars))
    for c in chars:
        if (stringprep.in_table_c11(c) or
            stringprep.in_table_c12(c) or
            stringprep.in_table_c21(c) or
            stringprep.in_table_c22(c) or
            stringprep.in_table_c3(c) or
            stringprep.in_table_c4(c) or
            stringprep.in_table_c5(c) or
            stringprep.in_table_c6(c) or
            stringprep.in_table_c7(c) or
            stringprep.in_table_c8(c) or
            stringprep.in_table_c9(c) or
            c in "\"&'/:<>@"):
            raise UnicodeError("Invalid node character")

    bidi(chars)

    return chars

def resourceprep(res):
    chars = list(unicode(res))
    i = 0
    while i < len(chars):
        c = chars[i]
        # map to nothing
        if stringprep.in_table_b1(c):
            del chars[i]
        else:
            i += 1
    # NFKC
    chars = stringprep.unicodedata.normalize("NFKC", "".join(chars))
    for c in chars:
        if (stringprep.in_table_c12(c) or
            stringprep.in_table_c21(c) or
            stringprep.in_table_c22(c) or
            stringprep.in_table_c3(c) or
            stringprep.in_table_c4(c) or
            stringprep.in_table_c5(c) or
            stringprep.in_table_c6(c) or
            stringprep.in_table_c7(c) or
            stringprep.in_table_c8(c) or
            stringprep.in_table_c9(c)):
            raise UnicodeError("Invalid node character")

    bidi(chars)

    return chars

def parse_jid(jid):
    # first pass
    m = re.match("^(?:([^\"&'/:<>@]{1,1023})@)?([^/@]{1,1023})(?:/(.{1,1023}))?$", jid)
    if not m:
        return False

    (node, domain, resource) = m.groups()
    try:
        # ipv4 address?
        socket.inet_pton(socket.AF_INET, domain)
    except socket.error:
        # ipv6 address?
        try:
            socket.inet_pton(socket.AF_INET6, domain)
        except socket.error:
            # domain name
            dom = []
            for label in domain.split("."):
                try:
                    label = encodings.idna.nameprep(unicode(label))
                    encodings.idna.ToASCII(label)
                except UnicodeError:
                    return False

                # UseSTD3ASCIIRules is set, but Python's nameprep doesn't enforce it.
                # a) Verify the absence of non-LDH ASCII code points; that is, the
                for c in label:
                    if c in BAD_DOMAIN_ASCII:
                        return False
                # Verify the absence of leading and trailing hyphen-minus
                if label[0] == '-' or label[-1] == "-":
                    return False
                dom.append(label)
            domain = ".".join(dom)
    try:
        if node is not None:
            node = nodeprep(node)
        if resource is not None:
            resource = resourceprep(resource)
    except UnicodeError:
        return False

    return node, domain, resource

if __name__ == "__main__":
    results = parse_jid(sys.argv[1])
    if not results:
        print "FAIL"
    else:
        print results

rawDescription: Validating an XMPP jid with python?

description: Validating an XMPP jid with python


code:
in_text = input_file.read()
frequencies = []

for i in range(65,91): #from A to Z
    frequencies.append(in_text.count(chr(i)))

print frequencies

rawDescription: Cannot read character from the list to use in ord()


code:
with open("file.txt", "r") as data_file:
    for line in data_file.readlines():
        line = line.strip().split()
        print line[1], line[3]

rawDescription: How can I have Python read a file from my directory and print the data in columns?

description: Have Python read a file from my directory and print the data in columns


code:
import subprocess
p = subprocess.Popen(('gedit',"testFile"))
p.wait()
print file("testFile").readlines()

rawDescription: How do I wait for user input to a text file in python?

description: Wait for user input to a text file in python


code:
while minute < 46 :
    print "test"
    time.sleep(5)
    now = datetime.datetime.now()
    minute = now.minute

rawDescription: executing a while loop between defined time

description: Executing a while loop between defined time


code:
class Character(object):
    def __init__(self, name="DEFAULT"):
        self.name = name

pc = Character("Bob")

def print_name(character):
    print character.name

def run():
    print_name(pc)

run()

import shelve
mysave = shelve.open("save1")
# save all Character instances without the default name
mysave["all characters"] = {varname:value for varname,value in
                                globals().iteritems() if
                                    isinstance(value, Character) and
                                    value.name != "DEFAULT"}
mysave.close()

del pc

mysave = shelve.open("save1")
globals().update(mysave["all characters"])
mysave.close()

run()

rawDescription: python load from shelve - can I retain the variable name?

description: Python load from shelve - can I retain the variable name


code:
import sqlite3
from string import Template

conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")

results = []

for row in cursor:
    results.append({'date': row[0], 'gb': row[1]})
    print "date :", row[0]
    print "gb :", row[1]

template = '''

'''

with open('chart.html', 'w') as html:
    data = ','.join(['["{date}", {gb}]'.format(**r) for r in results])
    html.write(Template(template).substitute(res=data))

rawDescription: how to access sqlite3 database table values from javascript?

description: Access sqlite3 database table values from javascript


code:
import binascii
print binascii.hexlify("ABCZ")

rawDescription: How can I unpack binary hex formatted data in Python?

description: Unpack binary hex formatted data in Python


code:
student_list = Student.objects.all()
for student in student_list:
    print student.name

rawDescription: Get all table data in Django

description: Get all table data in Django


code:
file=sys.argv[1]
data=open(file).readlines()
for line in data:
  split=line.split()
  if split[1]=="x":
    print split[1], split[4], split[5]

rawDescription: Altering Print Conditions

description: Altering Print Conditions


code:
keycode = 65
char = chr(keycode)
print char

rawDescription: Get character from keycode

description: Get character from keycode


rawDescription: Python fails Tor check using urllib2 to initiate requests


code:
import urllib2
import StringIO
from zipfile import ZipFile
import csv

baseUrl = "http://api.worldbank.org/v2/en/indicator/ny.gdp.pcap.cd?downloadformat=csv"
remoteCSV = urllib2.urlopen(baseUrl)

sio = StringIO.StringIO()
sio.write(remoteCSV.read())
    # We create a StringIO object so that we can work on the results of the request (a string) as though it is a file.

z = ZipFile(sio, 'r')
    # We now create a ZipFile object pointed to by 'z' and we can do a few things here:

print z.namelist()
    # A list with the names of all the files in the zip you just downloaded
    # We can use z.namelist()[1] to refer to 'ny.gdp.pcap.cd_Indicator_en_csv_v2.csv'

with z.open(z.namelist()[1]) as f:
# Opens the 2nd file in the zip
    csvr = csv.reader(f)
    for row in csvr:
        print row

rawDescription: How to download a CSV file from the World Bank's dataset

description: Download a CSV file from the World Bank's dataset


code:
import pandas as pd

html_data = '''

SUB CODE

SUB NAME

THEORY

PRACTICAL

MARKS

GRADE

     301
    ENGLISH CORE
    067

    067
    C2

'''

print pd.read_html(html_data)[0].to_csv(index=False, header=False)

rawDescription: convert html table to csv using python

description: Convert html table to csv using python


code:
data = pd.read_csv('1.csv', parse_dates=[0,1])
data['time_delay'] = data['completed'] - data['deadline']
print data['time_delay']
data.to_csv(sys.stdout)
data['time_delay'] = data['time_delay'].apply(pd.lib.repr_timedelta64)
data.to_csv(sys.stdout)

rawDescription: Calculating time diference and printing to csv using python pandas


code:
class MyForm(forms.Form):
    CHOICES = (('Option 1', 'Option 1'),('Option 2', 'Option 2'),)
    field = forms.ChoiceField(choices=CHOICES)

print MyForm().as_p()

# out:
Field: <select name="field" id="id_field">\n<option value="Option 1">Option 1</option>\n<option value="Option 2">Option 2</option>\n</select>

rawDescription: How do I use Django's form framework for select options?

description: Use Django's form framework for select options


code:
import numpy as np

A = np.array([[0.3, 0.2],[1.0, 0.1],[0.3, 0.1], [1.0, 0.1]])

def f(x,tol=1.e-10):
  l = [np.allclose(x,row,tol) for row in A]
  return l.count(True)/float(A.shape[0])

print f(np.array([0.3,0.2]))
print f(np.array([1.0, 0.1]))
print f(np.array([-12, 140]))

rawDescription: Empirical distribution of rows in 2d numpy array


code:
sequence = 'TCATGAGGCTTTGGTAAATAT'

frame1 = sequence.find('ATG')

my_list = []

for codon in range(len(sequence)):
    next_codon = sequence[frame1:frame1+3]
    my_list.append(next_codon)
    frame1 +=3
    if next_codon == 'TAA':
        break

print my_list

rawDescription: Scan Reading frame [3] Python

description: Scan Reading frame [3] Python


code:
import ast
val = ast.literal_eval(input_str)
print type(val)

rawDescription: Python Returning Appropriate Type From a String


code:
from datetime import date, timedelta
import calendar
import time

last = date(2014, 3, 31)
delta = (last.weekday() - calendar.SUNDAY) % 7
lastsunday = last - timedelta(days=delta)            # 2014-03-30
print time.mktime(lastsunday.timetuple())

rawDescription: Python get summertime breakpoints

description: Python get summertime breakpoints


code:
import pyglet
from pyglet.window import mouse

window = pyglet.window.Window()

@window.event
def on_draw():
    pass

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x, y, x-dx, y, x-dx, y-dy, x, y-dy]))
    print x, y, dx, y, dx, dy, x, dy
pyglet.app.run()

rawDescription: Drawing a rectangle around mouse drag Pyglet


code:
times = [u'04:20', u'03:00', u'03:40']
to_min = lambda t: int(t.split(':')[0])*60 + int(t.split(':')[1])
to_hr = lambda m: '%02d:%02d' % ((m - m%60)/60, m%60)
average = to_hr(sum([to_min(t) for t in times])/len(times))
print average
# 03:40

rawDescription: Calculate average of list with hh:mm format


code:
import wx
import wx.lib.masked as masked

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

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

        control = ["Phone No", "(###) ###-#### x:###", "", 'F^-', "^\(\d{3}\) \d{3}-\d{4}", '','','']
        maskText = masked.TextCtrl(self,
                                   mask = control[1],
                                   excludeChars = control[2],
                                   formatcodes  = control[3],
                                   includeChars = "",
                                   validRegex   = control[4],
                                   validRange   = control[5],
                                   choices      = control[6],
                                   choiceRequired = True,
                                   defaultValue = control[7],
                                   demo         = True,
                                   name         = control[0],
                                   style=wx.TE_PROCESS_ENTER)
        maskText.Bind(wx.EVT_KEY_DOWN, self.onEnter)

    #----------------------------------------------------------------------
    def onEnter(self, event):
        """"""
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
            print "you pressed ENTER!"
        event.Skip()

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

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

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

rawDescription: wxPython: Put wx.TE_PROCESS_ENTER on Masked TextCtrl

description: WxPython: Put wx.TE_PROCESS_ENTER on Masked TextCtrl


code:
def Find():
    def find_button_pressed():
        targetfind = e1.get()
        print targetfind
        if targetfind:
            where = textPad.search(targetfind, INSERT, END)
            if where:
                print where
                pastit = where + ('+%dc' % len(targetfind))
                #self.text.tag_remove(SEL, '1.0', END)
                textPad.tag_add(SEL, where, pastit)
                textPad.mark_set(INSERT, pastit)
                textPad.see(INSERT)
                textPad.focus()
        win.destroy()
    win = Toplevel()
    Label(win, text="Find:").pack()
    e1 = Entry(win)
    e1.pack()
    Button(win, text="Find Me!!!!", command=find_button_pressed).pack()

rawDescription: Cannot get python 2.7 tkinter text editor find function to work


code:
from kivy.app import App
from kivy.lang import Builder
from functools import partial

kv_str = """
<MyButton@Button>:
    _cb: []
    my_id: 1
    text: "hello {}".format(self.my_id)
BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        Button:
            id: a_button
            text: "a button"
        Button:
            id: b_button
            text: "b button"
        Button:
            id: c_button
            text: "clear callbacks"
    GridLayout:
        cols: 4
        id: grid
        MyButton:
            my_id: 1
        MyButton:
            my_id: 2
        MyButton:
            my_id: 3
        MyButton:
            my_id: 4
"""

def cb(sender, arg='nothing'):
    print "we got: {} pressed with {}".format(sender.text, arg)

class MyApp(App):
    def build(self):
        root = Builder.load_string(kv_str)

        def set_callbacks(sender):
            for b in root.ids.grid.children:
                new_cb = partial(cb, arg=sender.text)
                b._cb.append(new_cb)
                b.fbind('on_press', new_cb)
        def clear_callbacks(sender):
            for b in root.ids.grid.children:
                for cb in b._cb:
                    b.funbind('on_press', cb)
                b._cb = []
        root.ids.a_button.bind(on_press=set_callbacks)
        root.ids.b_button.bind(on_press=set_callbacks)
        root.ids.c_button.bind(on_press=clear_callbacks)
        return root

if __name__ == '__main__':
    a = MyApp()
    a.run()

rawDescription: Kivy - unbind all methods attached to a button


code:
updatedRec = CVE(row[0], row[1], row[2], row[10])
uDict = updatedRec.__dict__
uDict.pop("_sa_instance_state", None)

originalRec = db.session.query(CVE).filter_by(CVE_ID=row[0]).one()
oDict = originalRec.__dict__

# cveid will be used throughout the update process. Do not modify this value!
cveid = originalRec.idCVE
print "Record ID:",cveid

# Compare converted CVE records
changedItems = set(uDict.values()) - set(oDict.values())
print "Changed items:", len(changedItems)
for item in changedItems:
    # Get column to be updated
    print uDict.keys()[uDict.values().index(item)]+":", getattr(updatedRec, uDict.keys()[uDict.values().index(item)])
    # Set new value of column
    setattr(originalRec, uDict.keys()[uDict.values().index(item)], getattr(updatedRec, uDict.keys()[uDict.values().index(item)]))
print "-"*40

rawDescription: Python & SQLAlchemy - Pass column name as a parameter?


code:
if request.GET:
    values = request.GET
    print values

rawDescription: Passing variable from template to views function in django


code:
matches=[ ("A", 120, "B", 56 ), ("A", 120, "C", 56 ), ("B", 120, "C", 56 )]

TEAM={}

for match in matches:
    TEAM[match[0]]=0
    TEAM[match[2]]=0

for match in matches:
    if match[1] > match[3]:
        TEAM[match[0]]+=2
    elif match[3] > match[1]:
        TEAM[match[2]]+=2

for match in TEAM:
    print match, ":", TEAM[match]

rawDescription: Getting score from a list of matches

description: Getting score from a list of matches


rawDescription: Find Maximum of 3D np.array along Axis = 0


code:
import re
class gf2pim(object):#Your classes should generally inherit from object

    def __init__(self, binary):
        '''__init__ is a standard special method used to initialize objects.  Here __init__
        will initialize a gf2pim object based on a binary representation.'''
        self.bin = binary

    @classmethod
    def from_string(cls, string):
        return cls(cls._string_to_binary(string))

    def to_string(self):
        raw = "{0:b}".format(self.bin); raw = str(raw[::-1]); g = [] #reverse binary string for enumeration
        g = [i for i,c in enumerate(raw) if c == '1']
        processed = "x**"+" + x**".join(map(str, g[::-1]))
        if len(g) == 0: return 0 #return 0 if list empty
        return processed  #returns result in gf(2) polynomial form

    @classmethod
    def id(cls, lst):
        """returns modulus 2 (1,0,0,1,1,....) for input lists"""
        return [int(lst[i])%2 for i in range(len(lst))]

    @classmethod
    def _list_to_int(self, lst):
        """converts list to integer for later use"""
        result = self.id(lst)
        return int(''.join(map(str,result)))

    @classmethod
    def _string_to_list(cls, string):
        """performs regex on raw string and converts to list"""
        c = [int(i.group(0)) for i in re.finditer(r'\d+', string)]
        return [1 if x in c else 0  for x in xrange(max(c), -1, -1)]

    @classmethod
    def _string_to_binary(cls, string):
        """converts to base 2; bina,binb are binary values like 110100101100....."""
        x = cls._string_to_list(string)
        a = cls._list_to_int(x)
        bina = int(str(a),2)
        return bina  #

    def __add__(self,other):
        """
        __add__ is another special method, and is used to override the + operator.  This will only
        work for instances of gf2pim and its subclasses.

        a,b are GF(2) polynomials like x**7 + x**3 + x**0 ...; returns binary string"""
        return gf2pim(self.bin^other.bin)

    def __sub__(self,other):
        """
        __sub__ is the special method for overriding the - operator

        same as addition in GF(2)"""
        return self.add(other)

    def __str__(self):
        return self.to_string()

if __name__ == '__main__':
    a = gf2pim.from_string("x**14 + x**1 + x**0")
    b = gf2pim.from_string("x**6 + x**2 + x**1")
    smadd1 = a+b
    print "smadd1   ",smadd1

rawDescription: Python -- special method arithmetic using existing class methods


code:
x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
p.seek(0)  # <== Seek to the beginning
print p.read()
p.close()

rawDescription: Creating a variable filename for every new file in loop,python


code:
K_max = 20
K_min = 0
L_max = 20
L_min = 0
ax = plt.subplot(111)
x_offset = 7 # tune these
y_offset = 7 # tune these
plt.setp(ax, 'frame_on', False)
ax.set_ylim([0, (K_max-K_min +1)*y_offset ])
ax.set_xlim([0, (L_max - L_min+1)*x_offset])
ax.set_xticks([])
ax.set_yticks([])
ax.grid('off')

for k in np.arange(K_min, K_max + 1):
    for l in np.arange(L_min, L_max + 1):
        ax.plot(np.arange(5) + l*x_offset, 5+rand(5) + k*y_offset,
                'r-o', ms=1, mew=0, mfc='r')
        ax.plot(np.arange(5) + l*x_offset, 3+rand(5) + k*y_offset,
                'b-o', ms=1, mew=0, mfc='b')
        ax.annotate('K={},L={}'.format(k, l), (2.5+ (k)*x_offset,l*y_offset), size=3,ha='center')
plt.savefig(os.path.join(os.getcwd(), 'plot-average.pdf'))

print 'Final plot created.'

rawDescription: matplotlib very slow. Is it normal?

description: Matplotlib very slow. Is it normal


code:
tup = (((2,4),6,(9,(3,7))))
listversion = []
def loopthroughtup(tup):
    for i in tup:
        if type(i) == tuple:
            print str(i) + " is a tuple"
            loopthroughtup(i)
        else:
            print str(i) + " is not a tuple"
            listversion.append(i)

loopthroughtup(tup)
print listversion

rawDescription: How can I return a list of objects within a tuple in python?

description: Return a list of objects within a tuple in python


code:
import tweepy
def twitter_fetch(search_name,maxnumtweets):
    consumer_token = ''
    consumer_secret = ''
    access_token = ''
    access_secret = ''

    auth = tweepy.OAuthHandler(consumer_token,consumer_secret)
    auth.set_access_token(access_token,access_secret)

    api  = tweepy.API(auth)
    count = 0
    count_url = 0
    count_url_total = 0
    count_tweets = 0

    try:
       for tweet in tweepy.Cursor(api.search,q=(search_name), lang = 'en').items(maxnumtweets):
          count_url =  len(tweet.entities['urls'])
          count_url_total += count_url
          count +=1
          if count_url > 0:
                        count_check_text = 0
                        text = tweet.text

                        print "urls: "
                        for url in tweet.entities['urls']:
                            print url['url']
                            count_check_text += 1

                            no_expanded_urls.write(url['url'].encode('utf-8'))
                            no_expanded_urls.write('\n')

                        out = tweet.id_str +" " + text
                        print "\nid_str and tweet: "
                        print out.encode('utf-8')

                        tweets.write(out.encode('utf-8'))
                        tweets.write('\n')
                        count_tweets+=1
                        print "-------------------------------------------------------------"
       print "-------------------------------------------------------------"
       print "-------------------------------------------------------------"
       tweets.close()
       no_expanded_urls.close()
       print "Searched for: " + hashtag
       print "Count tweets:"
       print count_tweets
       print "Count urls:"
       print count_url_total
       print count

    except tweepy.TweepError as e:
        print "error"

if __name__ == '__main__':
     archive = open('hashtag.txt', 'r')
     hashtag = archive.readline()
     archive.close()
     count_tweets = 0
     max_tweets = 50

     tweets = open('tweets.txt', 'a')
     tweets = open('tweets.txt', 'w')
     no_expanded_urls = open('noExpandedUrls.txt', 'w')
     twitter_fetch(hashtag, max_tweets)

rawDescription: Tweepy can't find Track

description: Tweepy can't find Track


code:
import requests
id="j4156f9150ece727e38bbf982634ee"
cookie = {'id': id}
content = requests.post('http://www.google.com',cookies=cookie)
print id
print cookie
print content.url
print content.cookies
print content.cookies.get('id')

rawDescription: Curl code to python convert

description: Curl code to python convert


code:
MODE = ["Only Even", "Only Odds", "All Numbers"]
for i,v in enumerate(MODE):
    print i+1, v
count = 1                 #changed 0 to 1
s = int(raw_input("Enter Mode Wanted: "))
if s == 3:
    while count <= 10:    #changed < to <=
        print count       #changed count+1 to count
        count += 1
elif s == 2:
    while count <=10:
        if count%2 != 0:
            print count
        count += 1
elif s == 1:
    while count <= 10:
        if count%2 == 0:
            print count
        count += 1

rawDescription: Looping 1-10 PRINT either only EVEN, only ODDS, or ALL


code:
class Observable:
    def subscribe(self,callback):
        self.callback = callback

    def fire(self):
        self.callback()

class CallBackStuff:
    storedInput = None # Class member to store the input
    def doCallback(self):
        self.storedInput = raw_input("Please enter Y or N?")

if __name__ == '__main__':
    s = CallBackStuff()
    o = Observable()
    o.subscribe(s.doCallback)
    o.fire()
    print s.storedInput # Print stored input from call-back object

rawDescription: Returning values from callback(s) in Python


code:
import requests

headers = {
    "User-Agent":
        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
}

s = requests.session()
s.headers.update(headers)

# There is a dedicated login page, which is the url of the Login button on the site, you can open that directly.
# Requests will automatically take care of rediects
s.get('https://loginka.ru/auth/?url=http%3A%2F%2F72.ru')

# Generate the post data
data = {
    'url': 'http://72.ru',
    'email': username,
    'password': password
}

# Perform the post request
r = s.post('https://loginka.ru/auth/?url=http%3A%2F%2F72.ru', data=data)

# There is an extra post request on this site which uses token from redirect url
token = r.url[r.url.index('token=')+6:]
url = 'http://72.ru/put_token_to_user/?token=' + token + '&dummy_put_token_to_user=yes'
headers2 = {'X-Requested-With': 'XMLHttpRequest', 'Referer': r.url}
r = s.get(url, headers=headers2)

r = s.get('http://72.ru/passport/mypage.php')
print r.url
print r.status_code
with open('abc.txt', 'wb') as f:
    f.write(r.content)

rawDescription: python requests with redirection

description: Python requests with redirection


code:
globals()["a"] = "asd"
print globals()["a"]

rawDescription: Is it possible to access a previously-created variable without knowing its name?


code:
for line in codecs.open("filename", "rt", "utf32"):
    print line

rawDescription: How do I decode unicode one line at a time in Python 2.7?

description: Decode unicode one line at a time in Python 2.7


code:
accountlist = []
with open('mydatafile.txt', 'r') as infile:
    for line in infile:
        if "has been granted access." in line:
            if line.strip().split('|')[1].strip(" ") not in accountlist:
                accountlist.append(line.strip().split('|')[1].strip(" "))
    print accountlist

    with open('output.txt', 'w') as outfile:
        for account in accountlist:
            outfile.write("%s\n" % account)

rawDescription: Loop through each line in a text file to extract a unique list


code:
import pygame, sys

pygame.init(); clock = pygame.time.Clock()
scr = pygame.display.set_mode((640, 480))

image = pygame.image.load('image.png')
rect = image.get_rect()
rect.center = (320, 240)

while True:
    pygame.display.flip()
    clock.tick(60)
    scr.fill((0, 0, 0))
    scr.blit(image, rect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()

    if pygame.mouse.get_pressed()[0]:
        if rect.collidepoint(pygame.mouse.get_pos()):
            print 'The mouse was click inside the image.'

rawDescription: Pygame - How to make pygame.mouse.get_pos in a rectangular area


code:
tab = "     " # five spaces
with open('input.txt', 'r') as f:
    for line in f:
        if line.startswith(tab):
            print line

rawDescription: How to parse the section of the following file in Python?

description: Parse the section of the following file in Python


code:
import OpenGL
from OpenGL.GL import *
from OpenGL.GLUT import *

import numpy, math, sys, os
import glutils

import cyglfw3 as glfw

strVS = """
#version 330 core

layout(location = 0) in vec3 aVert;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform vec4 uColor;
uniform float uTheta;

out vec4 vCol;
out vec2 vTexCoord;

void main() {
  // rotational transform
  mat4 rot =  mat4(
        vec4( cos(uTheta),  sin(uTheta), 0.0, 0.0),
        vec4(-sin(uTheta),  cos(uTheta), 0.0, 0.0),
        vec4(0.0,         0.0,         1.0, 0.0),
        vec4(0.0,         0.0,         0.0, 1.0)
        );
  // transform vertex
  gl_Position = uPMatrix * uMVMatrix * rot * vec4(aVert, 1.0);
  // set color
  vCol = vec4(uColor.rgb, 1.0);
  // set texture coord
  vTexCoord = aVert.xy + vec2(0.5, 0.5);
}
"""
strFS = """
#version 330 core

in vec4 vCol;
in vec2 vTexCoord;

uniform sampler2D tex2D;
uniform bool showCircle;

out vec4 fragColor;

void main() {
  if (showCircle) {
    // discard fragment outside circle
    if (distance(vTexCoord, vec2(0.5, 0.5)) > 0.5) {
      discard;
    }
    else {
      fragColor = texture(tex2D, vTexCoord);
    }
  }
  else {
     fragColor = texture(tex2D, vTexCoord);
  }
}
"""

class Scene:
    """ OpenGL 3D scene class"""
    # initialization
    def __init__(self):
        # create shader
        self.program = glutils.loadShaders(strVS, strFS)

        glUseProgram(self.program)

        self.pMatrixUniform = glGetUniformLocation(self.program,
                                                   'uPMatrix')
        self.mvMatrixUniform = glGetUniformLocation(self.program,
                                                  "uMVMatrix")
        self.colorU = glGetUniformLocation(self.program, "uColor")

        # color
        self.col0 = [1.0, 0.0, 0.0, 1.0]

        # texture
        self.tex2D = glGetUniformLocation(self.program, "tex2D")

        # define quad vertices
        quadV = [
            -0.5, -0.5, 0.0,
            0.5, -0.5, 0.0,
            -0.5, 0.5, 0.0,
             0.5, 0.5, 0.0
            ]

        # set up vertex array object (VAO)
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)
        # vertices
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        vertexData = numpy.array(quadV, numpy.float32)
        glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData,
                     GL_STATIC_DRAW)
        # enable vertex array
        glEnableVertexAttribArray(0)
        # set buffer data
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        # unbind VAO
        glBindVertexArray(0)

        # time
        self.t = 0

        # texture
        self.texId = glutils.loadTexture('test.png')

        # show circle?
        self.showCircle = False

    # step
    def step(self):
        # increment angle
        self.t = (self.t + 1) % 360
        # set shader angle in radians
        glUniform1f(glGetUniformLocation(self.program, 'uTheta'),
                    math.radians(self.t))

    # render
    def render(self, pMatrix, mvMatrix):
        # use shader
        glUseProgram(self.program)

        # set proj matrix
        glUniformMatrix4fv(self.pMatrixUniform, 1, GL_FALSE, pMatrix)

        # set modelview matrix
        glUniformMatrix4fv(self.mvMatrixUniform, 1, GL_FALSE, mvMatrix)

        # show circle?
        glUniform1i(glGetUniformLocation(self.program, 'showCircle'),
                    self.showCircle)

        # enable texture
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self.texId)

        glUniform1i(self.tex2D, 0)

        # bind VAO
        glBindVertexArray(self.vao)
        # draw
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
        # unbind VAO
        glBindVertexArray(0)

class RenderWindow:
    """GLFW Rendering window class"""
    def __init__(self):

        # save current working directory
        cwd = os.getcwd()

        # initialize glfw - this changes cwd
        glfw.Init()

        # restore cwd
        os.chdir(cwd)

        # version hints
        glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
        glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        # make a window
        self.width, self.height = 640, 480
        self.aspect = self.width/float(self.height)
        self.win = glfw.CreateWindow(self.width, self.height, "test")
        # make context current
        glfw.MakeContextCurrent(self.win)

        # initialize GL
        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.5, 0.5, 0.5,1.0)

        # set window callbacks
        glfw.SetMouseButtonCallback(self.win, self.onMouseButton)
        glfw.SetKeyCallback(self.win, self.onKeyboard)
        glfw.SetWindowSizeCallback(self.win, self.onSize)

        # create 3D
        self.scene = Scene()

        # exit flag
        self.exitNow = False

    def onMouseButton(self, win, button, action, mods):
        #print 'mouse button: ', win, button, action, mods
        pass

    def onKeyboard(self, win, key, scancode, action, mods):
        #print 'keyboard: ', win, key, scancode, action, mods
        if action == glfw.PRESS:
            # ESC to quit
            if key == glfw.KEY_ESCAPE:
                self.exitNow = True
            else:
                # toggle cut
                self.scene.showCircle = not self.scene.showCircle

    def onSize(self, win, width, height):
        #print 'onsize: ', win, width, height
        self.width = width
        self.height = height
        self.aspect = width/float(height)
        glViewport(0, 0, self.width, self.height)

    def run(self):
        # initializer timer
        glfw.SetTime(0.0)
        t = 0.0
        while not glfw.WindowShouldClose(self.win) and not self.exitNow:
            # update every x seconds
            currT = glfw.GetTime()
            if currT - t > 0.1:
                # update time
                t = currT
                # clear
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

                # build projection matrix
                pMatrix = glutils.perspective(45.0, self.aspect, 0.1, 100.0)

                mvMatrix = glutils.lookAt([0.0, 0.0, -2.0], [0.0, 0.0, 0.0],
                                          [0.0, 1.0, 0.0])
                # render
                self.scene.render(pMatrix, mvMatrix)
                # step
                self.scene.step()

                glfw.SwapBuffers(self.win)
                # Poll for and process events
                glfw.PollEvents()
        # end
        glfw.Terminate()

# main() function
def main():
    print 'starting simpleglfw...'
    rw = RenderWindow()
    rw.run()

# call main
if __name__ == '__main__':
    main()

rawDescription: Looking for a simple OpenGL (3.2+) Python example that uses GLFW


code:
file1 = sorted([int(l) for l in open('file1.txt').read().split()])
file2 = sorted([int(l) for l in open('file2.txt').read().split()])

i = 0
for file2_number in file2:
    while i+1 < len(file1) and file1[i+1] < file2_number:
        i += 1
    print file1[i]

rawDescription: Compare columns and print smaller and bigger rows


code:
import serial

ser = serial.Serial('/dev/ttyUSB1', 115200, timeout=5)
ser.write("AT\r")
response =  ser.read(2)
print response
ser.close()

rawDescription: Read response AT command with pySerial

description: Read response AT command with pySerial


code:
def foo():
    print "Hello"
import pickle
code = pickle.dumps(foo.__code__)
def bar():
    pass
bar()
bar.__code__ = pickle.loads(code)
bar()

rawDescription: reverse engineering python to strings

description: Reverse engineering python to strings


code:
from operator import itemgetter
from itertools import groupby

a = [{'type': 'abc', 'values': 1},
     {'type': 'abc', 'values': 2},
     {'type': 'abc', 'values': 3},
     {'type': 'xyz', 'values': 4},
     {'type': 'xyz', 'values': 5},
     {'type': 'pqr', 'values': 6},
     {'type': 'pqr', 'values': 8},
     {'type': 'abc', 'values': 9},
     {'type': 'mno', 'values': 10},
     {'type': 'def', 'values': 11}]

typegetter = itemgetter('type')
valuesgetter = itemgetter('values')

groups = groupby(sorted(a, key=typegetter), key=typegetter)

print {k:list(map(valuesgetter, v)) for k, v in groups}

rawDescription: How to use list comprehensions to make a dict having list of list as values

description: Use list comprehensions to make a dict having list of list as values


code:
s3conn = boto.connect_s3(access_key, secret_key, security_token=token)
bucket = s3conn.get_bucket(bucket_name)
folders = bucket.list('', '/')
for folder in folders:
    print folder.name

rawDescription: Can you list all folders in an S3 bucket?

description: List all folders in an S3 bucket


code:
import subprocess

output = subprocess.check_output([ 'top', '-n', '1' ])

print output

rawDescription: How to call shell command for a single output when they run in a loop?

description: Call shell command for a single output when they run in a loop


code:
import stopwatch

class TimedClass():

    def __init__(self):
        t = stopwatch.Timer()
        # do stuff here
        t.stop()
        print t.elapsed

rawDescription: Python - Timeit within a class

description: Python - Timeit within a class


code:
from yourapp.forms import UserForm, UserProfileForm

def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds -- which is optional.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        form = UserForm(data=request.POST, prefix='upf')
        form2 = UserProfileForm(data=request.POST, prefix='upf')

        # If the two forms are valid...
        if form.is_valid() and form2.is_valid():
            # Save the user's form data to the database.
            user_reg = form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user_reg.set_password(user_reg.password)
            user_reg.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = form2.save(commit=False)
            profile.user = user_reg

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'avatar' in request.FILES:
                profile.avatar = request.FILES['avatar']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful --- which is optional.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print form.errors, form2.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        form = UserForm(prefix='upf')
        form2 = UserProfileForm(prefix='upf')

    # Render the template depending on the context.
    return render_to_response(
            'profile/register.html',
            {'form': form, 'form2': form2, 'registered': registered},
        context)

rawDescription: Set ForeignKey before save in form with two models


code:
from itertools import tee, izip

def bigrams(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

with open("data.txt", 'r') as f:
    for line in f:
        words = line.strip().split()
        uni = words
        bi = bigrams(words)
        print uni
        print list(bi)

rawDescription: unigram using python

description: Unigram using python


code:
#!/usr/bin/python
import os, sys, pycurl
model = """{
name: 'zxy',
targets: [ 'abc']
}"""
path = '/deployments/MyApp.ear'
c = pycurl.Curl()
c.setopt(pycurl.URL, 'https://abc.cde')
c.setopt(pycurl.HTTPHEADER, ['Accept:application/json'])
send = [("model", model),
        ('deployment', (pycurl.FORM_FILE, path)),]
c.setopt(pycurl.HTTPPOST, send)
#c.setopt(pycurl.VERBOSE, 1)
c.perform()
print c.getinfo(pycurl.RESPONSE_CODE)
c.close()

rawDescription: Form data in pycurl request

description: Form data in pycurl request


code:
with tempfile.NamedTemporaryFile(mode="wb") as jpg:
    jpg.write(b"Hello World!")
    print jpg.name

rawDescription: How to save a temporarily jpg file by using python?

description: Save a temporarily jpg file by using python


code:
# assuming the parsed json is stored in my_data
timestamp = int(my_data['createdDate'])
# split out the seconds and remaining milliseconds
seconds, milli = divmod(timestamp, 1000)
# convert to datetime instance and add microseconds (milliseconds * 1000)
dt = datetime.utcfromtimestamp(seconds).replace(microsecond=milli * 1000)
# print string representation
print dt.strftime('yyyy-mm-dd')

rawDescription: Not understanding the format of date in json


code:
from Tkinter import *
import tkFileDialog, Tkconstants,collections

root = Tk()
root.title("TEST")
root.geometry("800x600")

def openFile():
    f_in = tkFileDialog.askopenfile(
                            parent=root,
                            title="Open .txt file",
                            filetypes=[("txt file",".txt"),("All files",".*")])

    frequencies = collections.defaultdict(int)
    for line in f_in:
        for char in line:
            frequencies[char] += 1
    f_in.close()
    total = float(sum(frequencies.values()))
    print 'total:', total

button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
Button(root, text = 'Open .txt file',
       fg = 'black',
       command= openFile).pack(**button_opt)

root.mainloop()

rawDescription: How to respond to tkinter events?

description: Respond to tkinter events


code:
class LimitedList:
    def __init__(self, inputList=[]):
        self._list = []
        self.append(inputList)

    def append(self, inputList):
        for i in inputList:
            if i in [0,1,2] and i not in self._list:
                self._list += [i]
        return self._list.sort()

    def set(self, inputList=[]):
        self.__init__(inputList)

    def get(self):
        return self._list

    def __iter__(self):
        return (i for i in self._list)

    def __add__(self, inputList):
        temp = LimitedList(self._list)
        for i in inputList:
            if i in [0,1,2] and i not in temp._list:
                temp._list += [i]
        temp._list.sort()
        return temp

    def __getitem__(self, key):
        return self._list[key]

    def __len__(self):
        return len(self._list)

a = LimitedList([2,3,4,5,6,0]) # create a LimitedList

print a.get()  # get the LimitedList

a += [2,3,4,5,6,6,1] # use the "+" operator to append a list to your limited list

print len(a) # get the length

print a[1]   # get the element at position 1

for i in a:  # iterate over the LimitedList
    print i

rawDescription: how to hold 0,1,2 in a list using python

description: Hold 0,1,2 in a list using python


code:
if selling in Pickaxes:

       confirm = raw_input ("Are you sure you wish to sell the item {} "
                 "for {} Coins? (y/n)\n>>".format(
                     selling,Pickaxes[selling]["sell"]))
       if confirm.lower() in ["yes","y"]:
            i = inventory.index(selling)
            del inventory[i]
            money = money + Pickaxes[selling]["sell"]
            print "You now have", money, "Coins"
            time.sleep(2)
            raw_input("\nHit Enter to return to the menu\n")
            home()

rawDescription: Dictionary string formatting

description: Dictionary string formatting


code:
file_list = []
results = []
for filename in file_list:
    with open(filename, "r") as fileobj:
        if "#" in fileobj.read():
            results.append("%s Yes" % filename)
        else:
            results.append("%s No" % filename)

for item in results:
    print item

rawDescription: Keep track whether text file has or has not certain symbol


code:
import apollocaffe
from apollocaffe.layers import NumpyData, Convolution, EuclideanLoss
import numpy as np

def save():
    net = apollocaffe.ApolloNet()
    for i in range(1000):
        example = np.array(np.random.random()).reshape((1, 1, 1, 1))
        net.clear_forward()
        net.f(NumpyData('data', example))
        net.f(NumpyData('label', example*3))
        net.f(Convolution('conv', (1,1), 1, bottoms=['data']))
        net.f(EuclideanLoss('loss', bottoms=['conv', 'label']))
        net.backward()
        net.update(lr=0.1)
        if i % 100 == 0:
            print net.loss
        net.save("model.h5")

def load():
    print "LOAD"
    net = apollocaffe.ApolloNet()
    net.load("model.h5")
    #example = np.array(np.random.random()).reshape((1, 1, 1, 1))
    example = np.asarray([[[[ 0.92890837]]]])
    net.clear_forward()
    net.f(NumpyData('data', example))
    net.f(NumpyData('label', example*3))
    net.f(Convolution('conv', (1,1), 1, bottoms=['data']))
    net.f(EuclideanLoss('loss', bottoms=['conv', 'label']))
    net.backward()
    net.update(lr=0.1)
    print net.loss

save()
load()

rawDescription: Issues in save - load apollocaffe models


code:
with open('file.txt', 'r') as handle:
    for index, line in enumerate(handle, 1):
        if line.strip() == 'google talk':
            print 'Match found on line', index

rawDescription: How to search a string in a file with exact length using python

description: Search a string in a file with exact length using python


code:
IDs = {}

tables = ['Fruit','Colour'];
for table in tables:
  rows = db_conn.execute("SELECT ID FROM %s" % table)
  for row in rows:
    if IDs.has_key(row['ID']):
      print "Duplicate ID %s is present in both %s and %s" % (row['ID'], table, IDs[row['ID']])
    else:
      IDs[row['ID']] = table

rawDescription: Enforce/check uniqueness of primary key across multiple tables


code:
def partition(queue):
    partition1, partition2, partition3 = [], [], []
    while queue:
        ele = queue.popleft()
        if 0 < ele <= 3:
            partition1.append(ele)
        elif 3 < ele <= 6:
            partition2.append(ele)
        else:
            partition3.append(ele)
    return partition1, partition2, partition3
import collections
p1, p2, p3 = partition(collections.deque(range(10)))
print p1
print p2
print p3

rawDescription: What's the efficient way to split a List to several list in python


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

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 500
        screenHeight = 400
        screenSize = (screenWidth,screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        self.locationFont = locationFont = wx.Font(12, wx.MODERN, wx.NORMAL, wx.BOLD)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        myPanelA = wx.Panel(self, style=wx.SIMPLE_BORDER)
        myPanelA.SetBackgroundColour('#C0FAE0')
        self.myTextA = wx.StaticText(myPanelA, -1, "Testing")
        mainSizer.Add(myPanelA, 1, wx.EXPAND, 5)
        self.SetSizer(mainSizer)
        self.Bind(wx.EVT_CLOSE, self.closeWindow)
        pub.subscribe(self.updatePanelA, 'Update-panelA')

        self.thd = threadA()

    def updatePanelA(self, message):
        self.myTextA.SetLabel(message)

    def closeWindow(self, event):
        # -->  Code for killing the thread :)
        pub.unsubscribe(self.updatePanelA, 'Update-panelA')
        self.thd.running = False
        self.Destroy()

class threadA(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        self.running = True
        self.start()

    def run(self):
        while self.running:
            time.sleep(2)
            print 'Sending update'
            wx.CallAfter(pub.sendMessage, 'Update-panelA', message='Yes, It works')

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

rawDescription: What are the bad effects of not stopping/killing all the spawned threads in python/wxPython


code:
mylist = [['name','party','city','0','0','1'],['name','party','city','1','1','1']]

print sum([sum(map(int, item[3:])) for item in mylist])  # prints 4

rawDescription: How to sum list elements starting from a specific position

description: Sum list elements starting from a specific position


code:
class A(object):
    @classmethod
    def load(cls):
        return cls

class B(A):
    @classmethod
    def load(cls):
        # return A.load() would simply do "A.load()" and thus return a A
        return super(B, cls).load() # super figures out how to do it right ;-)

print B.load()

rawDescription: Invoking a superclass's class methods in Python


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

Base = declarative_base()

class Thing(Base):
    __tablename__ = 'thing'
    id = Column(Integer, primary_key=True)
    Rate = Column(Integer)
    Code = Column(String)
    Name = Column(String)

rules = {
    "groupOp": "AND",
    "rules":[
        {
            "field":"Rate",
            "op":"eq",
            "data":"6"
        }
    ],
    "groups":[
        {"groupOp":"OR",
        "rules":[
            {"field":"Code", "op":"eq", "data":"abc"},
            {"field":"Name","op":"eq","data":"fd"}
        ],
        "groups":[]
    }
]}

from sqlalchemy import and_, or_
from operator import eq
lookup = {
    "AND": and_,
    "OR": or_,
    "eq": eq
}

def visit_rule(rules):
    fn = lookup[rules['groupOp']]
    return fn(
                *(
                    [visit_expr(expr) for expr in rules['rules']] +
                    [visit_rule(subrule) for subrule in rules['groups']]
                )
            )

def visit_expr(expr):
    return lookup[expr["op"]](
                getattr(Thing, expr["field"]),
                expr["data"]
            )

# thing."Rate" = :Rate_1 AND (thing."Code" = :Code_1 OR thing."Name" = :Name_1)
print visit_rule(rules)

rawDescription: generate sqlalchemy filters dynamically from user input (in this case Jqgrid)

description: Generate sqlalchemy filters dynamically from user input (in this case Jqgrid)


code:
file1 = open("file1.txt","r")
file2 = open("file2.txt","w")
always_print = False
lines = fo.readlines()
for line in lines:
  if always_print or "3" in line:
     print line
     file2.write(line)
     always_print = True

rawDescription: How to print all the lines after it found certain string in python?

description: Print all the lines after it found certain string in python


code:
import inspect
from optparse import OptionParser
import sys

def do_stuff(opt0, opt1="a", opt2="b", opt3="c"):
    print opt0, opt1, opt2, opt3

if __name__ == "__main__":
    parser = OptionParser()
    args, varargs, varkw, defaults = inspect.getargspec(do_stuff)
    if varargs or varkw:
      sys.exit("Sorry, can't make opts from a function with *a and/or **k!")
    lend = len(defaults)
    nodef = args[:-lend]
    for a in nodef:
      parser.add_option("--%s" % a)
    for a, d in zip(args[-lend:], defaults):
      parser.add_option("--%s" % a, default=d)

    options, args = parser.parse_args()
    d = vars(options)
    for n, v in zip(nodef, args):
      d[n] = v

    do_stuff(**d)

rawDescription: Python optparse defaults vs function defaults


code:
def outer():
  def inner(): return 'boo'
  print inner()

eval(outer.func_code.co_consts[1])

rawDescription: How can I call a inner function from the Python shell?

description: Call a inner function from the Python shell


code:
any_results = False
for x in g:
    any_results = True
    print x
if not any_results:
    print 'Done'

rawDescription: Python execute code only if for loop did not begin iteration (with generator)?


code:
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', '.',
                               '--router', 'portland'])

# Start timing the code
import time
start_time = time.time()

# Get the default router
# Could also be called: router = otp.getRouter('paris')
router = otp.getRouter('portland')

# Create a default request for a given time
req = otp.createRequest()
req.setDateTime(2015, 9, 15, 10, 00, 00)
req.setMaxTimeSec(7200)
req.setModes('WALK,BUS,RAIL')

# The file points.csv contains the columns GEOID, X and Y.
points = otp.loadCSVPopulation('points.csv', 'Y', 'X')
dests = otp.loadCSVPopulation('points.csv', 'Y', 'X')

# Create a CSV output
matrixCsv = otp.createCSVOutput()
matrixCsv.setHeader([ 'Origin', 'Destination', 'Walk_distance', 'Travel_time' ])

# Start Loop
for origin in points:
  print "Processing origin: ", origin
  req.setOrigin(origin)
  spt = router.plan(req)
  if spt is None: continue

  # Evaluate the SPT for all points
  result = spt.eval(dests)

  # Add a new row of result in the CSV output
  for r in result:
    matrixCsv.addRow([ origin.getStringData('GEOID'), r.getIndividual().getStringData('GEOID'), r.getWalkDistance() , r.getTime()])

# Save the result
matrixCsv.save('traveltime_matrix.csv')

# Stop timing the code
print("Elapsed time was %g seconds" % (time.time() - start_time))

rawDescription: Origin Destination matrix with Open Trip Planner scripting in Jython / Python


code:
def coins_given(amount):
    coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
    answer = {}
    for coin_value, coin_name in coins:
        if amount >= coin_value:
            number_coin, amount = divmod(amount, coin_value)
            answer[coin_name] = number_coin
    return answer

print coins_given(76)
# {'quarter': 3, 'penny': 1}

rawDescription: Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario


code:
# show what's in the file
with open("some_file.txt", 'r') as f:
    print f.read()

new_content = []
with open("some_file.txt", "r") as asmr:
    for line in asmr.readlines():
        if "Gandalf" in line:
            # we have a match,we want something but we before that...
            new_content += "The greatest wizard of all times was:"
        new_content += line

# write the file with the new content
with open("some_file.txt", "w") as asmw:
    asmw.writelines(new_content)

# show what's in the file now
with open("some_file.txt", 'r') as f:
    print f.read()

rawDescription: Writing before specific line python

description: Writing before specific line python


rawDescription: Python failed to parse dates when reading from csv file


code:
class Main(QtGui.QWindow):
  def __init__(self):
    super(Main, self).__init__()
    self.run_button = QtGui.QPushButton("Run")

    mainLayout = QtGui.QVBoxLayout()
    mainLayout.addWidget(self.run_button)
    self.setLayout(mainLayout)

    self.run_button.clicked.connect(self.run_event)

  def run_event(self):
    # Create the dialog to display output
    self.viewer = OutputDialog()

    # Create the worker thread and run it
    self.thread = WorkerThread()
    self.thread.message.connect(self.viewer.write)
    self.thread.start()

class WorkerThread(QtCore.QThread):
  message = QtCore.Signal(str)

  def run(self):
    sys.stdout = self

    for i in range(10):
      print "Im doing stuff"
      time.sleep(1)

  def write(self, text):
    self.message.emit(text)

rawDescription: PySide: redirect stdout to a dialog

description: PySide: redirect stdout to a dialog


code:
#!/usr/bin/python
import sys
import zlib
z = zlib.decompressobj(31)
count = 0
while True:
    if z.unused_data == "":
        buf = sys.stdin.read(8192)
        if buf == "":
            break
    else:
        print count
        count = 0
        buf = z.unused_data
        z = zlib.decompressobj(31)
    got = z.decompress(buf)
    count += len(got)
print count

rawDescription: Read multiple files from concatenated gzip in Python


code:
class Foo(object):
    def __init__(self):
        self.__baz = 42
    def foo(self):
        print self.__baz

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()
        self.__baz = 21
    def bar(self):
        print self.__baz
x = Bar()
x.foo()
x.bar()
print x.__dict__

rawDescription: Why are Python's 'private' methods not actually private?


code:
from random import choice
import string

dictionary = set(open('words.txt','r').read().lower().split())
max_len = max(map(len, dictionary)) #longest word in the set of words

text = ''.join([choice(string.ascii_lowercase) for i in xrange(28000)])
text += '-'+text[::-1] #append the reverse of the text to itself

words_found = set() #set of words found, starts empty
for i in xrange(len(text)): #for each possible starting position in the corpus
    chunk = text[i:i+max_len+1] #chunk that is the size of the longest word
    for j in xrange(1,len(chunk)+1): #loop to check each possible subchunk
        word = chunk[:j] #subchunk
        if word in dictionary: #constant time hash lookup if it's in dictionary
            words_found.add(word) #add to set of words

print words_found

rawDescription: How to find possible English words in long random string?

description: Find possible English words in long random string


code:
items = itertools.chain.from_iterable( iter(list_returning_method, None) )

for item in items:
    # do something with item
    print item

    if not Condition:
       break

rawDescription: Python nested for loop Vs generator for repeatedly iterating over a list provided by a function


code:
#!/usr/bin

import pytz
import datetime
import ntplib
import time

LOCALTIMEZONE = pytz.timezone("Europe/London") # time zone name from Olson database

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=pytz.utc).astimezone(LOCALTIMEZONE)

def get_time_from_NTPClient():
    from time import ctime
    try:
        c = ntplib.NTPClient()
        response = c.request('europe.pool.ntp.org', version=3)
        formatted_date_with_micro_seconds =    datetime.datetime.strptime(str(datetime.datetime.utcfromtimestamp(response.tx_time)),"%Y-%m-%d %H:%M:%S.%f")
        local_dt = utc_to_local(formatted_date_with_micro_seconds)
        #Remove micro seconds from the string
        formatted_date_with_corrections = str(local_dt).split(".")[0]
        return formatted_date_with_corrections
    except:
        print "Error At Time Sync: Let Me Check!"
        return "Error At Time Sync: Let Me Check!"

formatted_date = get_time_from_NTPClient()

rawDescription: NTPLib Time Difference + Python

description: NTPLib Time Difference + Python


code:
import Tkinter
from PIL import Image, ImageTk
from sys import argv

window = Tkinter.Tk(className="bla")

image = Image.open(argv[1] if len(argv) >=2 else "bla2.png")
canvas = Tkinter.Canvas(window, width=image.size[0], height=image.size[1])
canvas.pack()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk)

def callback(event):
    print "clicked at: ", event.x, event.y

canvas.bind("<Button-1>", callback)
Tkinter.mainloop()

rawDescription: Capturing x,y Coordinates with Python PIL


code:
for member in list:
    if member not in ('a', 'b', 'c'):
        print member

rawDescription: Using the or and not operators

description: Using the or and not operators


code:
print "let's talk about this %s" % my_name
print "let's talk about this {:s}".format(my_name)
print "let's talk about this", my_name

rawDescription: How to print lines in Python

description: Print lines in Python


rawDescription: Print in tabulated form

description: Print in tabulated form


code:
from django.db.models import Count

queryset = models.short_url.objects.filter(
    created_at__month=m,
    url_hash='DCmuih',
).annotate(click_info_count=Count('click_info__id'))

for short_url in queryset:
    print short_url, short_url.click_info_count

rawDescription: How to query Django model using filter

description: Query Django model using filter


code:
import re

def stripwhite(text):
    lst = text.split('"')
    for i, item in enumerate(lst):
        if not i % 2:
            lst[i] = re.sub("\s+", "", item)
    return '"'.join(lst)

print stripwhite('This is a string with some "text in quotes."')

rawDescription: Python Regular expression must strip whitespace except between quotes


code:
with open('test.csv', 'rb') as file:
    reader = csv.reader(file)
    for row in reader:
        seq_id = row[0]
        seqs = []
        for n in range(1,7):
            if n % 2 != 0:
                start = row[n] # all start positions for the slice occupy non-even rows
            else:
                end = row[n]

                for key, value in sorted(seq_dict.iteritems()):
                    #print key, value
                    if key == seq_id: # cross check matching sequence identities
                        try:
                            seqs.append(value[int(start):int(end)])
                        except ValueError:
                            print 'Ignore empty slice indices.. '
        print ' '.join(str(x) for x in seqs)

rawDescription: Concatenating sliced strings based on slice indices in csv file


code:
BigList = ['server1','server2','server3','server4']

# here we use enumerate to generate the index i for the current item
# we pass in a temp list with an extra entry concatenated so that we
# dont need to duplicate the print expression
input_list = BigList + ['Return to main menu']
for i, item in enumerate(input_list):
    print "%d. %s" % (i, item)

# get user input
menu_input = raw_input("Enter the selection with comma:")

# the list of selection indexes
menu_selection_indexes = []

# sanitize and store the indexes from user input string
for i in menu_input.split(','):
    # could print/throw errors on bad input
    # here we choose to discard bad list items silently
    try:
            # convert the string e.g. "2" into an integer type
            # so that we can use it to index into our menu list
        val = int(i.strip())
    except ValueError, ve:
            # some strings (e.g. "a") cannot be converted to an integer
            # a ValueError exception is thrown if this is attempted
            # we catch this exception and just ignore this value,
            # skipping this value continuing on with the next for-loop item
        continue
    # ignore indexes that exceeed the acceptable input list size
    if val > len(input_list):
        continue
    menu_selection_indexes.append(val)

# print indexes
print menu_selection_indexes

# if the last possible input index was chosen, we return to menu
if len(BigList) in menu_selection_indexes:
    if not len(menu_selection_indexes) == 1:
        print "warning: mixed commands"
    print "will return to main menu"

else:
    # list of items selected, using list comprehensions
    menu_selection_names = [input_list[i] for i in menu_selection_indexes]

    # print names
    print menu_selection_names

rawDescription: Multiple selections from a list using Python


code:
from datetime import datetime, timedelta
import time

event_sequences = [
  [1368136883, 1368137089],
  [1368214777, 1368214966],
  [],
  [],
  [1368747495, 1368747833],
  [1368830501, 1368831869]
]

#take the last_day recorded date as a datetime object from the event_sequences and return a 2-element list
#with the unix timestamps for 00:00 and 23:59
def getNextDay(last_day):
    next_day = last_day + timedelta(days=1)
    next_day_start = next_day.replace(hour=0,minute=0,second=0)
    next_day_end = next_day.replace(hour=23,minute=59,second=0)
    return [int(next_day_start.strftime("%s")), int(next_day_end.strftime("%s"))]

def fillEmptyDates(event_list):
    new_event_list = []
    #note: this will fail if the first element in the list of event_sequences is blank
    last_day = int(time.time())
    for x in event_sequences:
        if len(x) == 0:
            next_day = getNextDay(last_day)
            last_day = datetime.utcfromtimestamp(next_day[1])
        else:
            next_day = x
        last_day = datetime.utcfromtimestamp(next_day[1])
        new_event_list.append(next_day)
    return new_event_list

new_event_sequence = fillEmptyDates(event_sequences)

print new_event_sequence

#[[1368136883, 1368137089], [1368214777, 1368214966], [1368230400, 1368316740], [1368316800, 1368403140], [1368747495, 1368747833], [1368830501, 1368831869]]

for event in new_event_sequence:
    print str(datetime.utcfromtimestamp(event[0]))+ ' and '+str(datetime.utcfromtimestamp(event[1]))

#2013-05-09 22:01:23 and 2013-05-09 22:04:49
#2013-05-10 19:39:37 and 2013-05-10 19:42:46
#2013-05-11 00:00:00 and 2013-05-11 23:59:00
#2013-05-12 00:00:00 and 2013-05-12 23:59:00
#2013-05-16 23:38:15 and 2013-05-16 23:43:53
#2013-05-17 22:41:41 and 2013-05-17 23:04:29

rawDescription: Python: How to get the next day of unix timestamps at 00:00 and 23:59?


code:
from Tkinter import *

root = Tk()

var = StringVar()
var.set("Choose a name...")
names = []

# Appends names to names list and updates OptionMenu
def createName(n):
    names.append(n)
    personName.delete(0, "end")
    menu = nameMenu['menu']
    menu.delete(0, "end")
    for name in names:
        menu.add_command(label=name, command=lambda name=name: selection(name))

# what to run when a name is selected
def selection(name):
    var.set(name)
    print "Running"  # For testing purposes to see when/if selection runs
    print name

# Option Menu for names
nameMenu = OptionMenu(root, var, ())
nameMenu.grid(row=0, column=0, columnspan=2)
nameMenu.config(width=20)

# Entry for user to submit name
Label(root, text="Name").grid(row=1, column=0)
personName = Entry(root, width=17)
personName.grid(row=1, column=1)

# Add person Button
Button(root, text="Add Person", width= 20, command=lambda: createName(personName.get())).grid(row=5, column=0, columnspan=2)

mainloop()

rawDescription: tkinter dynamic optionMenu command not working

description: Tkinter dynamic optionMenu command not working


code:
import numpy as np
a = np.array(3)
b = np.array('3')
a_int = a.tolist()
b_str = b.tolist()
print type(a_int), type(b_str)

rawDescription: Convert numpy scalar to simple python type


code:
def record_callback(reply):
    if reply.category != record.FromServer:
        return
    if reply.client_swapped:
        print "* received swapped protocol data, cowardly ignored"
        return
    if not len(reply.data) or ord(reply.data[0]) < 2:
        # not an event
        return

    data = reply.data
    clients=local_dpy.screen().root.query_tree().children
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(data, record_dpy.display, None, None)
        if event.type == X.ButtonRelease:
            if(event.detail==1):
                for btn in buttons:
                  if(event.root_x>=btn[0] and event.root_x<=btn[1]):
                      if(event.root_y>=btn[2] and event.root_y<=btn[3]):
                          doit=1
                          for win in clients:
                              if win==local_dpy.screen().root.query_pointer().child:
                                  doit=2
                          if doit==1:
                              os.system(btn[4])

rawDescription: selective RECORD using python xlib?

description: Selective RECORD using python xlib


code:
import re

with open ("data.txt", "r") as myfile:
    data = myfile.read()

dict = {"FIRSTSTART(.+)FIRSTEND": "FIRSTSTART\n1a\nFIRSTEND", "SECONDSTART(.+)SECONDEND": "SECONDSTART\n2b\nSECONDEND",
        "THIRDSTART(.+)THIRDEND": "THIRDSTART\n3c\nTHIRDEND", "FORTHSTART(.+)FORTHEND": "FORTHSTART\n4d\nFORTHEND",
        "FIFTHSTART(.+)FIFTHEND": "FIFTHSTART\n5e\nFIFTHEND", "SIXTHSTART(.+)SIXTHEND": "SIXTHSTART\n6f\nSIXTHEND",
        "SEVENTHSTART(.+)SEVENTHEND": "SEVENTHSTART\n7g\nSEVENTHEND", "EIGTHSTART(.+)EIGTHEND": "EIGTHSTART\n8h\nEIGTHEND",
        "NINETHSTART(.+)NINETHEND": "NINETHSTART\n9i\nNINETHEND", "TENTHSTART(.+)TENTHEND": "TENTHSTART\n10j\nTENTHEND"
        }

for key, value in dict.iteritems():
    re_comp = re.compile(key, re.DOTALL)
    data = re_comp.sub(value, data)

print data

rawDescription: Replace strings between two substrings by using python


code:
from collections import Counter

# load file
with open('tab.txt') as f:
    lines = f.read().split('\n')

# replace separating whitespace with exactly one space
lines = [' '.join(l.split()) for l in lines]

# find all years and genres
genres = sorted(set(l.split()[0] for l in lines))
years = sorted(set(l.split()[1] for l in lines))

# count genre-year combinations
C = Counter(lines)

# print table
print "Year".ljust(10),
for y in years:
    print y.rjust(6),
print
for g in genres:
    print g.ljust(10),
    for y in years:
        print `C[g + ' ' + y]`.rjust(6),
    print

rawDescription: Python group by 2 columns, output multiple columns


code:
def getcircs(mylist):
    circs=[]
    x=mylist
    y=list(x)
    dig=len(x)-1
    j=0

    circs.append(x)

    while j < dig:
        temp = y[:]
        for i in range(0,dig):
            r=i+1
            g=x[r]
            temp[i]=g
        temp[dig]=x[0]
        print temp
        circs.append(temp)
        x=list(temp)
        j+=1

    print circs
    return circs

rawDescription: Python list append returning odd results


code:
import os
dir = os.path.dirname(__file__)
path = raw_input()
if os.path.isabs(path):
    print "input path is absolute"
else:
    path = os.path.join(dir, path)
    print "absolute path is %s" % path

rawDescription: How to resolve relative paths in python?

description: Resolve relative paths in python


code:
from Tkinter import Tk

root = Tk()

def click(e):
    print "hi"

root.bind("<Prior>", click) # Bind to PageUp
root.bind("<Next>", click)  # Bind to PageDown

root.mainloop()

rawDescription: Tkinter python detecting PgUp/PgDn

description: Tkinter python detecting PgUp/PgDn


code:
for root, dirs, files in os.walk("."):
    if ".hg" in dirs:
        dirs.remove(".hg")
    for f in files:
        print os.path.join(root, f)

rawDescription: How to skip .hg / .git / .svn directories while recursing tree in python

description: Skip .hg / .git / .svn directories while recursing tree in python


code:
for i in range(1940,2005):
   print i

rawDescription: Increase numbers in python until max

description: Increase numbers in python until max


code:
def prompt():
    while True:
        user_input = raw_input()
        if input == '?':
            print help_o
        elif not user_input.isalpha():
            print "You entered bad characters"
        elif user_input == 'r': #Restart
            raise RestartException
        else:
            return user_input

class RestartException(Exception):
    pass

while True:
    load_word_list() ##Load words into list
    try:
        for word in wordList: ##Loop that needs to restart
            for i in range(5):
                to_speak = "Spell, %s" %word
                subprocess.Popen(['espeak', to_speak])
                answer = prompt()
                if answer != word:
                    print "You got it wrong"
    except RestartException:
        # catch the exception and return to while loop
        pass
    else:
        # exit while loop
        break

rawDescription: How do I do something GOTO could do, in Python - reload then restart outer loop

description: Do something GOTO could do, in Python - reload then restart outer loop


code:
import re
print re.sub(r'[\\/:"*?<>|]+', "", "This\ Ăwesomé_Song?©.mp3")

rawDescription: How to remove unsafe characters to save file

description: Remove unsafe characters to save file


code:
from selenium.webdriver.support.select import Select

select = Select(driver.find_element_by_id('FCenter'))
selected_option = select.first_selected_option
print selected_option.text

rawDescription: How to get selected option using Selenium WebDriver with Python?

description: Get selected option using Selenium WebDriver with Python


code:
d={}
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2]}
print d
values=[]
for key in d:
    count = 0
    values = d[key]
    for value in values:
       for i in  (d[value]):
            if i in values:
                count += 1
    print "count: ",count/2, " key: ", key

rawDescription: Manipulation Searching Dictionary with list as value in Python


code:
data_file = raw_input("Please type name of input data! ")
data = open(data_file)

new_list = list()

for line in data:
    line = line.rstrip()
    first_empty = line.find(" ")
    items_whole = line[first_empty + 1:]
    items_list = items_whole.split()
    # Use a 'list comprehension' to convert the items list into a list of floats
    floats_list = [float(i) for i in items_list]

    # Use the built in 'sorted' method to sort the floats
    # If the sorted float list is the same as the original float list, then all the items are ascending
    if floats_list == sorted(floats_list):
        print items_list
        # Add the list of floats into the 'new_list' for any post processing
        new_list += [floats_list]

rawDescription: Python: Only extract lines in a file where values are continuously getting bigger


code:
import string

numbers = 0
letters = 0

for letter in raw_input('Enter a password: '):
  if letter in string.ascii_letters:
    letters += 1
  elif letter in string.digits:
    numbers += 1

print numbers, letters

rawDescription: Letter and number count in raw_input

description: Letter and number count in raw_input


code:
def repeat(x,Y):
    A = list(str(x)) #makes a list, A, of each digit: 101 becomes ['1','0','1']
    A = map(int,A)  #converts each value of the new list to integers
    print 'Proceessing', x
    for i in range(0,10):
        b = A.count(i) #counts how many times each digit is present
        if b>1:         #if there is repetition
            print 'Removed', x
            Y.remove(x)

B = []
for i in range(100,1000):   #needs to be a 3 digit number (100 until 999)
    if i%17 == 0:
        B.append(i)         #creates list of factors of 17
print B

for j in B:                 #removes any values that have digits that occur more than once
    repeat(j,B)

print B

rawDescription: Function used to remove numbers with a repeating integer skips one entry and i dont know why


code:
import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while 1:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print "Message length is " + repr(len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

rawDescription: Python script progress email

description: Python script progress email


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Firefox() # Get local session of firefox

# 0 wait until the pages are loaded
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it

browser.get("http://www.google.com") # Load page

# 1 & 2
title = browser.title
print title, len(title)

# 3 & 4
curre = browser.current_url
print curre, len(curre)

#5
browser.refresh()

#6
page_source = browser.page_source
print page_source, len(page_source)

rawDescription: storing the browser title derived from selenium

description: Storing the browser title derived from selenium


code:
import sys
lst = [u'\u5de5', u'\u5de5']
msg = repr([x.encode(sys.stdout.encoding) for x in lst]).decode('string-escape')
print msg

rawDescription: Python print unicode list

description: Python print unicode list


code:
import itertools
for x in itertools.count():
    print x
    if x > 10: break

rawDescription: Using an arbitrary maximum in range()

description: Using an arbitrary maximum in range()


code:
import zmq
import time
import sys
import threading

SOCKET_NAME = "tcp://127.0.0.1:8000"
#SOCKET_NAME = "inproc://mysocket"

def dealerRoutine(context):
    socket = context.socket(zmq.DEALER)
    socket.bind(SOCKET_NAME)
    time.sleep(1)
    socket.send("", zmq.SNDMORE)
    socket.send("hello")
    socket.send("", zmq.SNDMORE)
    socket.send("hello")
    print socket.recv()
    print socket.recv()
    socket.close()

def workerRoutine(context):
    socket = context.socket(zmq.REP)
    socket.connect(SOCKET_NAME)
    s = socket.recv()
    print s
    socket.send("world")

context = zmq.Context()

workers = []
for i in range(0, 2):
    worker = threading.Thread(target=workerRoutine, args=([context]))
    workers.append(worker)
    worker.start()

dealerRoutine(context)

for worker in workers:
    worker.terminated = True

context.term()

rawDescription: Multithreading and ZMQ DEALER/REP hello world doesn't work


code:
data = {}

for dir_item in os.listdir(path):
    dir_item_path = os.path.join(path, dir_item)
    if os.path.isfile(dir_item_path):
        with open(dir_item_path, 'r') as f:
            data[dir_item] = f.read()
            for part in data[dir_item].split():
                if part.startswith('color='):
                    print part[6:]

rawDescription: Python: read all files from directory

description: Python: read all files from directory


code:
if match:
   print match.group(1)

rawDescription: re: matching 'a href' tag

description: Re: matching 'a href' tag


code:
import struct

# Pack a Python long as if it was a C unsigned integer, little endian
bytes = struct.pack("<I", 0x78FF00AA)
print [hex(ord(byte)) for byte in bytes]

['0xaa', '0x0', '0xff', '0x78']

rawDescription: Integer (representing a sequence of bits) reinterpretation as Character Array in Python


code:
from xattr import xattr
from struct import unpack

colornames = {
    0: 'none',
    1: 'gray',
    2: 'green',
    3: 'purple',
    4: 'blue',
    5: 'yellow',
    6: 'red',
    7: 'orange',
}

attrs = xattr('./test.cpp')

try:
    finder_attrs = attrs[u'com.apple.FinderInfo']
    flags = unpack(32*'B', finder_attrs)
    color = flags[9] >> 1 & 7
except KeyError:
    color = 0

print colornames[color]

rawDescription: getting and setting mac file and folder finder labels from Python

description: Getting and setting mac file and folder finder labels from Python


code:
x = np.array([0, 0, 0, 10, 10, 10, 10, 10])

elements, repeats = np.unique(x, return_counts=True)
index = repeats.argmax()
elem = elements[index]

print "Max elem is " + str(elem) + " with " + str(repeats[index]) + " repetitions."

rawDescription: numpy: find the count of each unique element in an array

description: Numpy: find the count of each unique element in an array


code:
from csv import DictReader

city_codes = {}
for row in DictReader(open('file2.csv', 'rb')):
    city_codes[row['city']] = row['code']

for row in DictReader(open('file1.csv', 'rb')):
    print city_codes[row['city']]

rawDescription: How to search values in a dictionary in python

description: Search values in a dictionary in python


code:
try:
   self.spawn(pp_args)
except DistutilsExecError as msg:
    print "DistutilsExecError : " + str(DistutilsExecError(msg))
    print
    print "The above exception was the direct cause of the following exception:"
    raise CompileError

rawDescription: making python 3 exception backward compatible

description: Making python 3 exception backward compatible


code:
import threading
import time

def printit():
  threading.Timer(n, printit).start()
  print "Hello, World!"

threading.Timer(x, printit)

rawDescription: Run certain code after x seconds, every n seconds in python