code:
lines = urllib.urlopen(link).readlines()
for line in lines:
    if "vcore" in line:
        print line

rawDescription: Search for a string in webpage and print the entire line containing it using python


code:
#!/usr/bin/env python
from twisted.internet import protocol
from twisted.internet import reactor

class ProcessProtocol(protocol.ProcessProtocol):
    def outReceived(self, data):
        print 'got stdout:', data
    def errReceived(self, data):
        print 'got stderr:', data
    def processEnded(self, reason):
        reactor.stop()

process = ProcessProtocol()
reactor.spawnProcess(process, 'cmd', ['cmd', 'arg 1', 'arg 2'])
reactor.run()

rawDescription: How do I retrieve stderr for a shell command with a large data buffer?

description: Retrieve stderr for a shell command with a large data buffer


code:
import zipfile

with zipfile.ZipFile() as input_zipfile:
    for f in input_zipfile.namelist():
        lines = input_zipfile.read(f).split("\n")
        print lines[1]

rawDescription: python: extracting specific lines from all files in a zip archive

description: Python: extracting specific lines from all files in a zip archive


code:
from stl import mesh
from matplotlib import collections
from matplotlib import pyplot

figure, axes = pyplot.subplots(frameon=False)
pixel_width = 7158  # ADDED
pixel_height = 16392  # ADDED
req_dpi = 72  # ADDED
figure.set_size_inches(pixel_width / float(req_dpi),  # MODIFIED
                       pixel_height / float(req_dpi))  # MODIFIED
# Read the STL file
your_mesh = mesh.Mesh.from_file('2d_35MeshTest.STL')

axes.set_xlim(your_mesh.min_[0], your_mesh.max_[0])
axes.set_ylim(your_mesh.min_[1], your_mesh.max_[1])

axes.add_collection(collections.PolyCollection(your_mesh.vectors[:, :, :2],
                                               linewidth=1,
                                               facecolors=(1,1,1),alpha=1,
                                               edgecolors=(1,0,0) ))

print your_mesh.vectors.shape
pyplot.gca().set_aspect('equal')

pyplot.axis('off')
ax = pyplot.Axes(figure, [0., 0., 1., 1.], )
figure.set_dpi(72)

figure.subplots_adjust(bottom = 0)
figure.subplots_adjust(top = 1)
figure.subplots_adjust(right = 1)
figure.subplots_adjust(left = 0)

figure.savefig('image_refined7.png', format='png',
               transparent=True, dpi=req_dpi)  # MODIFIED

rawDescription: matplotlib draw only the image with desired resolution and dpi

description: Matplotlib draw only the image with desired resolution and dpi


code:
def __init__(self, num):
    self.a = self.func(num)  # return value of function is None
    print self.a             # self.a is now None

def func(self, num):
    self.a = range(num)      # sets self.a to [0..19]
    print self.a             # prints [0..19]
    # implicit "return None"

rawDescription: Can't set class attributes in python using a method


code:
class ClassMapping(type):
    def __new__(cls, name, bases, dct):
        t = type.__new__(cls, name, bases, dct)
        t._instances = {}
        return t
    def __delitem__(cls, my_str):
        del cls._instances[my_str]

class Foo(object):
    __metaclass__ = ClassMapping
    def __init__(self, my_str):
        n = len(Foo._instances) + 1
        Foo._instances[my_str] = n
        print "Now up to {} instances".format(n)

rawDescription: Using __delitem__ with a class object rather than an instance in Python


code:
sl = slice(0L, 832L)
sl
start = sl.start
stop = sl.stop
start, stop

rawDescription: Get start and stop from a python slice object


code:
import theano
import theano.tensor as T

a = T.vector('X', dtype='int64')
b = T.vector('Y', dtype='int64')
c = a[b.nonzero()]
g = function([a,b],c)

x = np.array([5,3,2,3,4,6], dtype=int)
y = np.array([0,0,1,0,0,1], dtype=int)
print g(x,y)

rawDescription: How to to 0/1 subsetting in Theano?

description: To 0/1 subsetting in Theano


code:
my_dict_final = {}  # Create an empty dictionary
with open('pickle_file1', 'rb') as f:
    my_dict_final.update(pickle.load(f))   # Update contents of file1 to the dictionary
with open('pickle_file2', 'rb') as f:
    my_dict_final.update(pickle.load(f))   # Update contents of file2 to the dictionary
print my_dict_final

rawDescription: Python - Load multiple Pickle objects into a single dictionary


code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from xvfbwrapper import Xvfb

class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.timerScreen = QTimer()
        self.timerScreen.setInterval(7000)
        self.timerScreen.setSingleShot(True)
        self.timerScreen.timeout.connect(self.getHtml)
        self.loadFinished.connect(self.timerScreen.start)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
    def getHtml(self):
        self.frame = self.mainFrame()
        self.app.quit()
args = {"nolisten":"tcp"}
vdisplay = Xvfb(**args)
vdisplay.start()
url = 'url here'
r = Render(url)
html = r.frame.toHtml()
print html
f = open("./test.html","wb")
f.write(html.__str__().encode("utf-8"))
f.close()
#stri = str(html).encode("utf-8")
vdisplay.stop()

rawDescription: How do you pass html to Selenium

description: Pass html to Selenium


code:
def a():
    pass

import inspect
print inspect.getsource(a)

rawDescription: Python: literally "printing" a function

description: Python: literally "printing" a function


code:
from Tkinter import *

raiz = Tk()
frame = Frame(raiz)
out = []

def cadastro():
    form = Toplevel(raiz)

    Label(form, text='Nome: ').grid(column=0, row=0, sticky=E)
    Label(form, text='Celular: ').grid(column=0, row=1, sticky=E)

    nome = StringVar()
    celular = StringVar()

    a=Entry(form, textvariable=nome, width=15)
    a.grid(column=1, row=0, sticky=W)
    Entry(form, textvariable=celular, width=15).grid(column=1, row=1, sticky=W)

    def onCancel():
        form.destroy()

    def onOk():
        with open('outt.txt','w') as txt:
            txt.write('Name : ' + str(nome.get()) + '  ' + 'Telephone No. : ' + str(celular.get()))
        onCancel()

    Button(form, text='OK', command=onOk).grid(column=0, row=2, sticky=E)
    Button(form, text='Cancel', command=onCancel).grid(column=1, row=2, sticky=W)

def listar():
    with open('outt.txt','r') as txt_read:
        print txt_read.read()

w = Button(raiz, text='Cadastrar',command=cadastro).grid()
x = Button(raiz, text='Listar' , command=listar).grid()

raiz.mainloop()

rawDescription: Python: how to create a file .txt and record information in it


code:
for i in range(list.getLength()):
    node = list.item(i)
    if node != None and node.getNodeName() == "book":
        children = node.getChildNodes()
        for j in range(children.getLength()):
            print "Looking for J K. Rowling in book"
            child = children.item(j)
            if  child.getNodeName() == "author" and child.getTextContent() == "J K. Rowling":
                print "************"
                print "Found!!!!!"
                print child.getNodeName()
                print node.getTextContent()
                node1= node.getParentNode().removeChild(child.getParentNode())

rawDescription: How to delete an XML element using Java DOM in Jython?

description: Delete an XML element using Java DOM in Jython


code:
d = {'Komp': ['values'], 'Forx': ['values'], 'Rove': ['values']}
from itertools import combinations
for x in combinations(d, 2):
   print x

rawDescription: Python paired dictionary keys()

description: Python paired dictionary keys()


code:
class FloatWithUnits(float):
    def __new__(cls, value, units):
        inst = super(FloatWithUnits, cls).__new__(cls, value)
        inst.units = units
        return inst

    def withval(self, newval):
        return FloatWithUnits(newval, self.units)

T = FloatWithUnits(100, 'C')
T = T.withval(200)
print T, T.units  # 200.0 C

rawDescription: Updating value of class derived from float


code:
class MyDescriptor(object):
    __slots__ = ['name']
    def __init__(self, name_):
        self.name = name_
    def __get__(self, instance, owner):
        return getattr(instance, self.name)
    def __set__(self, instance, value):
        setattr(instance, self.name, value)

class C(object):
    __slots__ = ['_a']
    a = MyDescriptor('_a')
    def __init__(self, val):
        self.a = val

foo = C(1)
print foo.a
foo.a = 2
print foo.a

rawDescription: Using Python descriptors with slots

description: Using Python descriptors with slots


code:
def txtTranslate():
    with open('normalDNA.txt') as inputfile:
        normalDNA_input = inputfile.read()
        print normalDNA_input

    with open('mutatedDNA.txt') as inputfile:
        mutatedDNA_input = inputfile.read()
        print mutatedDNA_input

    #todo: get codon_list from somewhere
    print translate(normalDNA_input, codon_list)
    print translate(mutatedDNA_input, codon_list)

txtTranslate()

rawDescription: Function inheritance Python

description: Function inheritance Python


code: print [line for line in file  if re.match(targetregex, line)]

rawDescription: returning string matching regular expression

description: Returning string matching regular expression


code:
import scrapy
import logging
from scrapy.http import Request
from scrapy.selector import Selector

class insiderSpider(scrapy.Spider):
    name = 'insider'
    allowed_domains = ["insider.in"]
    start_urls = ["http://www.insider.in/mumbai/"]
    event_details = list() # Changed. Now event_detail is a menber data of class

    def parse(self, response):
        source_link = []
        temp = []
        title =""
        Price = ""
        Venue_name = ""
        Venue_address = ""
        description = ""
        alllinks = response.xpath('//div[@class="bottom-details-right"]//a/@href').extract()
        print alllinks
        for single_event in alllinks:
            if "https://insider.in/event" in single_event:
                yield Request(url = single_event, callback = self.parse_event)
            else:
                print 'Other part'

    def parse_event(self, response):
        title = response.xpath('//div[@class = "cell-title in-headerTitle"]/h1//text()').extract()
        print title
        temp = response.xpath('//div[@class = "cell-caption centered in-header"]//h3//text()').extract()
        print temp
        a = len(response.xpath('//div[@class = "bold-caption price"]//text()').extract())
        if a > 0:
            Price = response.xpath('//div[@class = "bold-caption price"]//text()').extract()
        else:
            Price = "RSVP"
        print Price
        Venue_name = response.xpath('normalize-space(//div[@class = "address"]//div[@class = "section-title"]//text())').extract()

        print Venue_name
        Venue_address = response.xpath('normalize-space(//div[@class ="address"]//div//text()[preceding-sibling::br])').extract()

        print Venue_address
        description = response.xpath('normalize-space(//div[@class="cell-caption accordion-padding"]//text())').extract()

        print description
        self.event_details.append([title,temp,Price,Venue_name,Venue_address,description]) # Notice that event_details is used as self.event_details ie, using member data
        print self.event_details # Here also self.event_details

rawDescription: Scrapy xpath returning empty list in python


code:
from re import findall

def a(*args):
    for i in args:
        print i

config = {"methods": ["a('hello')", "a('hello','bye')", "a()"]}

for i in config['methods']:
    x,y = findall(r'(.*?)\((.*?)\)', i)[0]
    y = [i.strip() for i in y.split(',')]
    globals()[x](*y)

[OUTPUT]
'hello'
'hello'
'bye'

rawDescription: Taking a list of functions(with parameters) as input in python


code:
import sys

import regex

def main(patterns):
    patterns = [regex.compile(p) for p in patterns]
    for line in sys.stdin:
        line = line.decode('utf8')
        for regexp in patterns:
            if regexp.search (line):
                print line.strip('\n')

if __name__ == '__main__':
    main([ur'^\d+\t(\p{L}|\p{M})+$', ])

rawDescription: How to implement \p{L} in python regex

description: Implement \p{L} in python regex


code:
import multiprocessing.pool # for ThreadPool, not multiprocessing
import Queue

_endofinput = object()

def _queueiter(queue):
    while True:
        item = queue.get()
        if item is _endofinput:
            break
        yield item

def parallel_execute(funcs, iterable, maxqueue):
    '''Interleaves the execution of funcs[0](iterable), funcs[1](iterable), etc.

    No function is allowed to lag more than maxqueue items behind another.
    (This will require adjustment if a function might return before consuming
    all input.)

    Makes only one pass over iterable.

    '''

    queues = [Queue.Queue(maxsize=maxqueue) for func in funcs]
    queueiters = [_queueiter(queue) for queue in queues]
    threadpool = multiprocessing.pool.ThreadPool(processes=len(funcs))

    results = threadpool.map_async(lambda (f, x): f(x), zip(funcs, queueiters))

    for item in iterable:
        for queue in queues:
            queue.put(item)

    for queue in queues:
        queue.put(_endofinput)

    threadpool.close()
    return results.get()

rawDescription: How to split one iterator into two?

description: Split one iterator into two


code:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()
conn = SSH2()
conn.connect('192.168.1.11')
conn.login(account)

conn.execute('terminal length 0')

conn.execute('show version')
print conn.response

conn.send('exit\r')
conn.close()

rawDescription: Python: SSH into Cisco device and run show commands


code:
letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)

rawDescription: How do I enumerate() over a list of tuples in Python?

description: Enumerate() over a list of tuples in Python


code:
import argparse
parser = argparse.ArgumentParser()
# The -- indicates that it is optional
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print "verbosity turned on"
else:
    print "Default option"

rawDescription: how set default value if cmd arguments is not set in getopt

description: How set default value if cmd arguments is not set in getopt


code:
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PFD = xmldoc.getElementsByTagName("PFD")
PNT = xmldoc.getElementsByTagName("PNT")
for element in PNT:
    if element.getAttribute('A') == "1":
        print "element found"

rawDescription: XML: How to get Elements by Attribute Value - Python 2.7 and minidom


code:
import time
def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

@timeit
def timeme():
    time.sleep(3)

rawDescription: Measuring the time it takes for a function to run and complete in Python


code:
import itertools as it

pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]

# with normal zip and slicing
for a,b in zip(pp,pp[1:]):
    if a[1] != b[1]:
        x=(a[0],b[0])
        print x
        break
# with generators and izip
iterfirst = (b for a,b in pp)
itersecond = (b for a,b in pp[1:])
iterfirstsymbol = (a for a,b in pp)
itersecondsymbol = (a for a,b in pp[1:])
iteranswer = it.izip(iterfirstsymbol, itersecondsymbol, iterfirst, itersecond)

print next((symbol1, symbol2)
           for symbol1,symbol2, first, second in iteranswer
           if first != second)

rawDescription: Python: find sequential change in one member of list pairs, report other


code:
import time

def modify_recipe():
    Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
    with open(Choice_Exist + ".txt", "r+") as f:
        content = f.readlines()
        data_list = [word.replace("\n","") for word in content]

    time.sleep(2)

    ServRequire = int(input("Please enter how many servings you would like: "))

    print data_list[0]
    print data_list[1]
    print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
    print ServRequire

modify_recipe()

rawDescription: Writing and Editing Files (Python)

description: Writing and Editing Files (Python)


code:
import Console
import time

c = Console.getconsole()
c.cursor(0)
print 'Hello, world!'
time.sleep(2)

rawDescription: How to turn off blinking cursor in command window?

description: Turn off blinking cursor in command window


code:
import json
import random

# read data from JSON file
questions = json.load(open("questions.json"))

# pick a random question
question = random.choice(questions.keys())

# get the list of possible answers and correct answer for this question
answers = questions[question]['answers']
correct_answer = questions[question]['correct_answer']

# display question and list of possible answers
print question
for n, answer in enumerate(answers):
    print "%d) %s" % (n + 1, answer)

# ask user for answer and check if it's the correct answer for this question
resp = raw_input('answer: ')
if resp == str(correct_answer):
    print "correct!"
else:
    print "sorry, the correct answer was %s" % correct_answer

rawDescription: create random questions using a txt file

description: Create random questions using a txt file


code:
import json
master_objects = {
    "tomorrow" : "ma\xc3\xb1ana" # UTF-8 encoding, just like what comes from db
}

print master_objects["tomorrow"] # Should print man~ana, only prettier

with open("output.json", "wt") as output_file:
    json.dump(master_objects, output_file, ensure_ascii=False)

rawDescription: unable to store special characters from mysql into a json file - Python

description: Unable to store special characters from mysql into a json file - Python


rawDescription: What does this mean "0100644" mean in Python 2?


code:
import os
import gevent

def follow(filename):
    fd = os.open(filename, os.O_RDONLY|os.O_NONBLOCK)
    os.lseek(fd, 0, os.SEEK_END)
    while True:
        lines = os.read(fd, 4096).splitlines()
        if not lines:
            gevent.sleep(.5)
            continue
        else:
            for line in lines:
                print "%s:%s" % (filename, line)

    os.close(fd)

if __name__ == '__main__':
    job1 = gevent.spawn(follow, '/var/log/syslog')
    job2 = gevent.spawn(follow, '/var/log/messages')

    gevent.joinall([job1, job2])

rawDescription: How to tail a file with gevent

description: Tail a file with gevent


code:
RootDir1 = r'*your directory*'
TargetFolder = r'*your target folder*'
for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False):
        for name in files:
            if name.endswith('.csv'):
                print "Found"
                SourceFolder = os.path.join(root,name)
                shutil.copy2(SourceFolder, TargetFolder) #copies csv to new folder

rawDescription: Copy files from multiple directories into one directory using Python


code:
from lxml import etree

raw_xml = '''<projects>
  <project>
    <name>Shockwave</name>
    <language>Ruby</language>
    <owner>Brian May</owner>
    <state>New</state>
    <startDate>31/10/2008 0:00:00</startDate>
  </project>
  <project>
    <name>Other</name>
    <language>Erlang</language>
    <owner>Takashi Miike</owner>
    <state>Canceled</state>
    <startDate>07/11/2008 0:00:00</startDate>
  </project>
</projects>'''
raw_xslt = '''<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>
  <xsl:template match="/">
    <xsl:text>Hi</xsl:text>
  </xsl:template>
</xsl:stylesheet>'''

sysroot = etree.fromstring(raw_xml)
xslroot = etree.fromstring(raw_xslt)
transform = etree.XSLT(xslroot)

print str(transform(sysroot))
# output:
# Hi

rawDescription: Python etree XSLT Requires Tag output?

description: Python etree XSLT Requires Tag output


code:
from socket import *
import sys
import select
address = ('localhost', 6005)
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(address)

while(1):
    print "Listening"
    recv_data, addr = server_socket.recvfrom(2048)
    print recv_data
    if recv_data == "Request 1" :
        print "Received request 1"
        server_socket.sendto("Response 1", addr)
    elif recv_data == "Request 2" :
        print "Received request 2"
        data = "Response 2"
        server_socket.sendto(data, addr)

rawDescription: Python UDP client/server program, problems


code:
import nltk
from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()

# Ngrams with 'creature' as a member
creature_filter = lambda *w: 'creature' not in w

## Bigrams
finder = BigramCollocationFinder.from_words(
   nltk.corpus.genesis.words('english-web.txt'))
# only bigrams that appear 3+ times
finder.apply_freq_filter(3)
# only bigrams that contain 'creature'
finder.apply_ngram_filter(creature_filter)
# return the 10 n-grams with the highest PMI
print finder.nbest(bigram_measures.likelihood_ratio, 10)

## Trigrams
finder = TrigramCollocationFinder.from_words(
   nltk.corpus.genesis.words('english-web.txt'))
# only trigrams that appear 3+ times
finder.apply_freq_filter(3)
# only trigrams that contain 'creature'
finder.apply_ngram_filter(creature_filter)
# return the 10 n-grams with the highest PMI
print finder.nbest(trigram_measures.likelihood_ratio, 10)

rawDescription: NLTK collocations for specific words

description: NLTK collocations for specific words


code:
def test(n):
    old = uuid.uuid1()
    print old
    for x in range(n):
            new = uuid.uuid1()
            if old >= new:
                    print "OOops"
                    break
            old = new
    print new
test(1000000)

rawDescription: Is python uuid1 sequential as timestamps?


code:
from scrapy.utils.markup import remove_tags

# it'll print 'hello, world'
print remove_tags('
hello, world
')

rawDescription: How to return only visible text when using Scrapy

description: Return only visible text when using Scrapy


code:
from itertools import chain, count

s1 = "this is is a foo"
s2 = "this is a a bar"
s3 = "that 's a foobar"

# convert each sentence into a list of words, because the lists
# will be used twice, to build the dictionary and to vectorize
w1, w2, w3 = all_ws = [s.split() for s in [s1, s2, s3]]

# chain the lists and turn into a set, and then a list, of unique words
index_to_word = list(set(chain(*all_ws)))

# build the inverse mapping of index_to_word, by pairing it with a counter
word_to_index = dict(zip(index_to_word, count()))

# create the vectors of word indices and of word count for each sentence
v1 = [(word_to_index[word], w1.count(word)) for word in w1]
v2 = [(word_to_index[word], w2.count(word)) for word in w2]
v3 = [(word_to_index[word], w3.count(word)) for word in w3]

print v1
print v2
print v3

rawDescription: Is there a simpler way to build a dictionary from strings and then vectorize the strings? Python


code:
import win32com.client as com
from win32com.client import constants as wcons

app = com.Dispatch('Word.Application')
# Find the text
app.Selection.Find.Execute('Call Tree',
        False, False, False, False, False,
        True, wcons.wdFindContinue, False,
        False,False,)
# Extend the selection to the end
app.Selection.EndKey(Unit=wcons.wdLine)
while True:
    # Move the selection to the next character
    app.Selection.MoveRight(Unit=wcons.wdCharacter, Count=1)
    # And Select the whole line
    app.Selection.EndKey(Unit=wcons.wdLine, Extend=wcons.wdExtend)
    # If I hit the table...
    if app.Selection.Tables.Count:
        print "Table found... Stop"
        # I leave the loop
        break
    # Otherwise delete the selection
    print "Deleting ...",app.Selection.Text
    app.Selection.Delete()
    # And delete the return
    app.Selection.TypeBackspace()

rawDescription: Word : Deleting Lines in between a Table and a Heading using Python


code:
for i,j in zip(a,b):
    tmp = ''.join(v if v!=i[k] else '*' for k,v in enumerate(j) )
    if tmp!='***':
          print i,j,tmp

rawDescription: Getting positional difference between two strings within the lists python


code:
height = input("Please enter the tree height : ")
height1 = height
trunk = height/3
spacevar = str(" ")

for i in range(0,height):
    print spacevar*(height-1)+"*"*(((i+1)*2)-1)
    height = height-1
for p in range (0,trunk):
    print spacevar*(height1-1)+"*"

rawDescription: Python - Removing the whitespace before the output


code:
from django.contrib import admin
from django.db import models
from bookstore.models import Book
from django.contrib.admin.views.main import ChangeList
import operator

class MyChangeList(ChangeList):
    def __init__(self, *a):
        super(MyChangeList, self).__init__(*a)

    def get_queryset(self, request):
        print dir(self)
        # First, we collect all the declared list filters.
        (self.filter_specs, self.has_filters, remaining_lookup_params,
         use_distinct) = self.get_filters(request)

        # Then, we let every list filter modify the queryset to its liking.
        qs = self.root_queryset
        for filter_spec in self.filter_specs:
            new_qs = filter_spec.queryset(request, qs)
            if new_qs is not None:
                qs = new_qs

        try:
            # Finally, we apply the remaining lookup parameters from the query
            # string (i.e. those that haven't already been processed by the
            # filters).
            qs = qs.filter(**remaining_lookup_params)
        except (SuspiciousOperation, ImproperlyConfigured):
            # Allow certain types of errors to be re-raised as-is so that the
            # caller can treat them in a special way.
            raise
        except Exception, e:
            # Every other error is caught with a naked except, because we don't
            # have any other way of validating lookup parameters. They might be
            # invalid if the keyword arguments are incorrect, or if the values
            # are not in the correct type, so we might get FieldError,
            # ValueError, ValidationError, or ?.
            raise IncorrectLookupParameters(e)

        # Use select_related() if one of the list_display options is a field
        # with a relationship and the provided queryset doesn't already have
        # select_related defined.
        if not qs.query.select_related:
            if self.list_select_related:
                qs = qs.select_related()
            else:
                for field_name in self.list_display:
                    try:
                        field = self.lookup_opts.get_field(field_name)
                    except Exception as ex:# models.FieldDoesNotExist:
                        print ex
                        pass
                    else:
                        if isinstance(field.rel, models.ManyToOneRel):
                            qs = qs.select_related()
                            break

        # Set ordering.
        ordering = self.get_ordering(request, qs)
        qs = qs.order_by(*ordering)

        # Apply keyword searches.
        def construct_search(field_name):
            if field_name.startswith('^'):
                return "%s__istartswith" % field_name[1:]
            elif field_name.startswith('='):
                return "%s__iexact" % field_name[1:]
            elif field_name.startswith('@'):
                return "%s__search" % field_name[1:]
            else:
                return "%s__icontains" % field_name

        if self.search_fields and self.query:
            orm_lookups = [construct_search(str(search_field))
                           for search_field in self.search_fields]
            or_queries = []
            for bit in self.query.split():
                or_queries += [models.Q(**{orm_lookup: bit})
                              for orm_lookup in orm_lookups]
            if len(or_queries) > 0:
                qs = qs.filter(reduce(operator.or_, or_queries))
            if not use_distinct:
                for search_spec in orm_lookups:
                    if admin.utils.lookup_needs_distinct(self.lookup_opts, search_spec):
                        use_distinct = True
                        break

        if use_distinct:
            return qs.distinct()
        else:
            return qs

@admin.register(Book)
class AdminBookstore(admin.ModelAdmin):
    list_display = ('title', 'author', 'description')
    search_fields = ('title', 'author', 'description')
    def get_changelist(*a, **k):
        return MyChangeList

rawDescription: django - simplest way to customize admin search

description: Django - simplest way to customize admin search


code:
def read_and_avg(sum_,n,left,i):  ## left is the number of times the input is to be taken
    if left == 0:
        print (sum_/float(n))
        return (sum_/float(n))
    else:
        i = i + 1
        print "Enter the values for pair number "+str(i)
        a = int(input())
        b = int(input())
        sum_ = sum_ + (a*b)                 ## Increment the sum
        n = n + b                           ## Increment the total count
        print sum_,n,left
        return read_and_avg(sum_,n,left-1,i)  ## Decrease left by 1,

def func(n):
    read_and_avg(0,0,n,0)

rawDescription: Python: Average based on Input of Values and Frequencies


code:
import gtk, os

class PyApp(gtk.Window):
    def __init__(self):
        super(PyApp, self).__init__()
        self.set_size_request(250, 200)
        self.set_position(gtk.WIN_POS_CENTER)
        self.connect("destroy", gtk.main_quit)
        self.set_title("SteveFM")
        vbox = gtk.VBox(False, 8)
        sw = gtk.ScrolledWindow()
        sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        vbox.pack_start(sw, True, True, 0)
        store = self.create_model()
        self.treeView = gtk.TreeView(store)
        self.treeView.connect("row-activated", self.on_activated)
        self.treeView.set_rules_hint(True)
        sw.add(self.treeView)
        self.create_columns(self.treeView)
        self.add(vbox)
        self.show_all()

    #  Take the names of files and subdirectories in
    #  the current directory and sort them into a list for treeview

    def create_model(self):
        store = gtk.ListStore(str)
        dirList=os.listdir(os.getcwd())
        dircontents = []
        for item in dirList:
            if item[0] != '.':
                if os.path.isdir(item):
                    dircontents.append(['/'+item])
                else:
                    dircontents.append([item])
        dircontents.sort()
        for act in dircontents:
            store.append([act[0]])
        return store

    #  If a file is clicked, open with leafpad.
    #  If a directory is clicked, change the current working directory to it
    #  and (my hurdle) replace the current treeview list with the contents of the
    #  new directory, just like a file manager.

    def on_activated(self, widget, row, col):
        model = widget.get_model()
        target = model[row][0]
        if target[0] != "/":
            cmd = "leafpad "+target
            os.system(cmd)
        else:
            os.chdir(os.getcwd()+target)
            print os.getcwd()   # Just for debugging
            self.treeView.set_model(self.create_model())

    def create_columns(self, treeView):
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(None, rendererText, text=0)
        column.set_sort_column_id(0)
        self.treeView.append_column(column)

PyApp()
gtk.main()

rawDescription: Python GtkTreeview; How to refresh the list when an item is selected


code: print 'Number is: %.8f' % (float(a[0]/a[1]))

rawDescription: Convert scientific notation to decimal - python


code:
def startingNode(self,destID,message,counter):
    pack =  self.pac.packet(self.name,destID,message)
    switch1Flow = []
    switch2Flow = []
    switch3Flow = []
    if counter == "0":
        nextHop = self.controller.selectSwitch(self.name)
        print "Switch",self.name,"contacts controller"
        nextHop.receivePacket(pack)
        switch1Flow = [nextHop.name] //list1
        print switch1Flow
        nextHop1 = self.controller.selectSwitch(nextHop.name)
        print "Switch",nextHop.name,"contacts controller"
        nextHop1.receivePacket(pack)
        nextHop2 = self.controller.selectSwitch(nextHop1.name)
        print "Switch",nextHop1.name,"contacts controller"
        nextHop2.receivePacket(pack)
        switch2Flow = [self.name,nextHop1.name] //list2
        print switch2Flow
        switch3Flow = [nextHop.name,nextHop2.name] //list3
        print switch3Flow
    elif counter == "1":
        if 's2' in switch1Flow:
           print "forwarding to s2"
           if 's1' in switch2Flow and 's3' in switch2Flow:
             print "forwarding to s3"
             if 's2' in switch3Flow and 's4' in switch3Flow:
                 print "forwarding to s4"
                 print "message reched s4"

rawDescription: How to make list accessible outside if statement?

description: Make list accessible outside if statement


code:
lines = """foo: bar
foo: baz
a: b"""

result = {}
for line in lines.split("\n"):
    (word, sentence) = line.split(":",1)
    word = word.strip()
    if word not in result:
        result[word] = []
    result[word].append(sentence.strip())

for word in result.keys():
    print word + ": " + "; ".join(result[word])

rawDescription: Replace all occurrences of the same key of an array with a character, skip the first replacement


code:
for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s
for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s

rawDescription: Best Way To Determine if a Sequence is in another sequence in Python


code:
#!/usr/bin/env python
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command(COMMAND)
while True:
  rl, wl, xl = select.select([channel],[],[],0.0)
  if len(rl) > 0:
      # Must be stdout
      print channel.recv(1024)

rawDescription: Executing a long running command through paramiko


code:
import sys

groups = {}
for l in sys.stdin:
    group, value = l.split()
    s = groups.get(group, 0)
    groups[group] = s + int(value)

print groups

rawDescription: How to sum-up the numbers for the similar groups?

description: Sum-up the numbers for the similar groups


code:
def nothing(*args):
    pass

def print_debug(msg):
    print msg

if not DEBUG:
    print_debug = nothing

rawDescription: Mimic C preprocessor with Python/Ruby?

description: Mimic C preprocessor with Python/Ruby


rawDescription: Wrong Exponential Power Plot - How to improve curve fit


code:
headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
for header in filter(None, headers):
    print header

rawDescription: Iterate over non None items in Python

description: Iterate over non None items in Python


code: print s.replace('\n', '').replace('\t', '').replace('\\','')

rawDescription: Scrapy and content updated with JavaScript


code: a='a=%r;print a%%a';print a%a

rawDescription: What are quines? Any specific purpose to have them?


rawDescription: Comparing all elements of 2 lists with Python 2


code:
def on_html_page_context(app, pagename, templatename, context, doctree):
    if doctree:
        print doctree.attributes['source'] # Path to .rst file

def setup(app):
    app.connect('html-page-context', on_html_page_context)

rawDescription: Getting the source .rst file path in Sphinx extension


code:
import simplejson
content = simplejson.loads(YourJsonObject)

from xml.etree.ElementTree import Element
from xml.etree.ElementTree import tostring

def dict_to_xml(tag, d):
    '''
    Turn a simple dict of key/value pairs into XML
    '''
    elem = Element(tag)
    for key, val in d.items():
        child = Element(key)
        child.text = str(val)
        elem.append(child)
    return elem

for i in range(1,len(content)):
    e = dict_to_xml('SomeNode',content[i][0])

    # print e
    print tostring(e)

rawDescription: Json to RDF/XML file in Python

description: Json to RDF/XML file in Python


code:
class NamedInteger(int):

    def __new__(cls, value, name='pony'):
        inst = super(NamedInteger, cls).__new__(cls, value)
        inst.name = name
        return inst

    def __str__(self):
        return self.name

x = NamedInteger(5)
print x + 3                 # => 8
print str(x)                # => pony
x = NamedInteger(3, "foo")
print x + 3                 # => 6
print str(x)                # => foo

rawDescription: How to add a constructor to a subclassed numeric type?

description: Add a constructor to a subclassed numeric type


code:
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider

class GoodsSpider(BaseSpider):
    name = 'goods'

    def start_requests(self):
        yield Request(url="http://www.amazon.com", callback=self.parse_amazon)

    def parse_amazon(self, response):
        hxs = HtmlXPathSelector(response)

        print hxs.select('//title/text()').extract()[0]

        yield Request(url="http://www.ebay.com", callback=self.parse_ebay)

    def parse_ebay(self, response):
        hxs = HtmlXPathSelector(response)

        print hxs.select('//title/text()').extract()[0]

rawDescription: using scrapy to extract information from different sites

description: Using scrapy to extract information from different sites


code:
class WrapStr(object):
    def __init__(self,str):
       self.str = str
    def __eq__(self,other):
       return self.str == other.str
    def __repr__(self):
       return self.str
    def __hash__(self):
        return hash(self.str)

first_ins = WrapStr('col1')
my_ix = pd.Index([first_ins])
sec_ins = WrapStr('col1')

print first_ins in my_ix # True
print sec_ins in my_ix # False

rawDescription: Pandas Index from objects

description: Pandas Index from objects


code:
from pygithub3 import Github

username = raw_input("Please enter a Github username: ")
password = raw_input("Please enter the account password: ")

gh = Github(login=username, password = password)

get_user = gh.users.get()

user_repos = gh.repos.list().all()

for repo in user_repos:
    print repo.language

rawDescription: Getting repository information using pygithub3 for Python


code:
import numpy as np

def combine_matrix(*args):
    n=len(args)
    rows,cols=args[0].shape
    a=np.zeros((n,cols*rows))
    m=0
    for i in range(n/rows):
        for j in range(n/cols):
            a[i*rows:(i+1)*rows,j*cols:(j+1)*cols]=args[m]
            m+=1

    return a

def example1():
    print '#'*10
    a=np.arange(1,17)

    n=4
    rows,cols=n/2,n/2

    lst=[]
    for i in range(n):
        ai=a[i*n:(i+1)*n]
        ai.shape=rows,cols
        lst.append(ai)

    print lst
    print combine_matrix(*lst)

def example2():
    print '#'*10
    m=24
    a=np.arange(m)

    n=6
    rows,cols=m/n/2,n/2

    lst=[]
    for i in range(m/n):
        ai=a[i*n:(i+1)*n]
        ai.shape=rows,cols
        lst.append(ai)

    print lst
    print combine_matrix(*lst)

def example3():
    print '#'*10
    m,n=36,6
    a=np.arange(m)

    arrs=np.array_split(a,n)
    for i in range(n):
        ln=arrs[i].shape[0]
        arrs[i].shape=2,ln/2

    print combine_matrix(*arrs)

example1()
example2()
example3()

rawDescription: Python : How to dynamically combine any number of small matrices into one big matrix


rawDescription: Dividing two pandas values

description: Dividing two pandas values


code:
for file_data in self.request.POST.getall('fileToUpload'):
     print "File Contents : ", file_data.value

rawDescription: get contents of multiple files using webapp2

description: Get contents of multiple files using webapp2


code:
# Your lists goes here
list1 = [1.0, 2.0, 3.1, 4.2]
list2 = [3.0, 2.0, 7.2, 5.1, 9.2]
list3 = [2.1, 4.2, 5.1, 9.2]

# Collect all the lists
list_of_lists = []
list_of_lists.append(list1)
list_of_lists.append(list2)
list_of_lists.append(list3)

# This list will contain the final result
result = []

# Loop the inner lists from list_of_lists, this will be list1, list2, list3...
for inner_list in list_of_lists:
    # Loop each element of the inner lists
    for element in inner_list:
        # Make sure the element is not already in the result (this can also be done with sets)
        if element not in result:
            # Add the inner element to result
            result.append(element)

# Sort the result
result = sorted(result)

# Finally output the list
print result # Outputs: [1.0, 2.0, 2.1, 3.0, 3.1, 4.2, 5.1, 7.2, 9.2]

rawDescription: How to automate my Python code?

description: Automate my Python code


code:
a_list = driver.find_elements_by_xpath('//p[@class="info"]//a[@data-ember-action]')
for element in a_list:
    print element.text

rawDescription: Python selenium questions href

description: Python selenium questions href


code:
ignorelist = [r'^test', r'[abc]set']

def guess(a,il):
    for reg in il:
        if re.search(reg,a):
            return "LOSE"
    return "WIN"

a = raw_input()
print guess(a,ignorelist)

rawDescription: Using variable in re.match in python

description: Using variable in re.match in python


code:
import numpy as np

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

# get length of flat array
a_length, =  a.shape

# reshape array
#(column by row must respect number of elements)
b = a.reshape(( 2, a_length/2 ))

# assign array except last column to a variable
result = b[:,:-1]
print result

rawDescription: Moving non-overlapping window in Numpy

description: Moving non-overlapping window in Numpy


rawDescription: How to use replace mode for python

description: Use replace mode for python


code:
"""Rate limiters with shared token bucket."""

import os
import sys
import threading
import time
import urllib
import urlparse

class TokenBucket(object):
    """An implementation of the token bucket algorithm.
    source: http://code.activestate.com/recipes/511490/

    >>> bucket = TokenBucket(80, 0.5)
    >>> print bucket.consume(10)
    True
    >>> print bucket.consume(90)
    False
    """
    def __init__(self, tokens, fill_rate):
        """tokens is the total tokens in the bucket. fill_rate is the
        rate in tokens/second that the bucket will be refilled."""
        self.capacity = float(tokens)
        self._tokens = float(tokens)
        self.fill_rate = float(fill_rate)
        self.timestamp = time.time()
        self.lock = threading.RLock()

    def consume(self, tokens):
        """Consume tokens from the bucket. Returns 0 if there were
        sufficient tokens, otherwise the expected time until enough
        tokens become available."""
        self.lock.acquire()
        tokens = max(tokens,self.tokens)
        expected_time = (tokens - self.tokens) / self.fill_rate
        if expected_time <= 0:
            self._tokens -= tokens
        self.lock.release()
        return max(0,expected_time)

    @property
    def tokens(self):
        self.lock.acquire()
        if self._tokens < self.capacity:
            now = time.time()
            delta = self.fill_rate * (now - self.timestamp)
            self._tokens = min(self.capacity, self._tokens + delta)
            self.timestamp = now
        value = self._tokens
        self.lock.release()
        return value

class RateLimit(object):
    """Rate limit a url fetch.
    source: http://mail.python.org/pipermail/python-list/2008-January/472859.html
    (but mostly rewritten)
    """
    def __init__(self, bucket, filename):
        self.bucket = bucket
        self.last_update = 0
        self.last_downloaded_kb = 0

        self.filename = filename
        self.avg_rate = None

    def __call__(self, block_count, block_size, total_size):
        total_kb = total_size / 1024.

        downloaded_kb = (block_count * block_size) / 1024.
        just_downloaded = downloaded_kb - self.last_downloaded_kb
        self.last_downloaded_kb = downloaded_kb

        predicted_size = block_size/1024.

        wait_time = self.bucket.consume(predicted_size)
        while wait_time > 0:
            time.sleep(wait_time)
            wait_time = self.bucket.consume(predicted_size)

        now = time.time()
        delta = now - self.last_update
        if self.last_update != 0:
            if delta > 0:
                rate = just_downloaded / delta
                if self.avg_rate is not None:
                    rate = 0.9 * self.avg_rate + 0.1 * rate
                self.avg_rate = rate
            else:
                rate = self.avg_rate or 0.
            print "%20s: %4.1f%%, %5.1f KiB/s, %.1f/%.1f KiB" % (
                    self.filename, 100. * downloaded_kb / total_kb,
                    rate, downloaded_kb, total_kb,
                )
        self.last_update = now

def main():
    """Fetch the contents of urls"""
    if len(sys.argv) < 4:
        print 'Syntax: %s rate url1 url2 ...' % sys.argv[0]
        raise SystemExit(1)
    rate_limit  = float(sys.argv[1])
    urls = sys.argv[2:]
    bucket = TokenBucket(10*rate_limit, rate_limit)

    print "rate limit = %.1f" % (rate_limit,)

    threads = []
    for url in urls:
        path = urlparse.urlparse(url,'http')[2]
        filename = os.path.basename(path)
        print 'Downloading "%s" to "%s"...' % (url,filename)
        rate_limiter = RateLimit(bucket, filename)
        t = threading.Thread(
            target=urllib.urlretrieve,
            args=(url, filename, rate_limiter))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    print 'All downloads finished'

if __name__ == "__main__":
    main()

rawDescription: Throttling with urllib2

description: Throttling with urllib2


code:
from collections import namedtuple
MyType= namedtuple("MyType", "field1 method1")
x = MyType(field1="3", method1=lambda x: x+1)
print x.field1, x.method1(3)

rawDescription: Create Class Implicitly In Python

description: Create Class Implicitly In Python


code:
dic_std_dev = {}
base_path = '.'
for root, dirs, files in os.walk(base_path):
    #print dirs
    for f in files:
        if root != base_path: #If this is a subdirectory
            ds = dicom.read_file(os.path.join(root, f)) #reading in DICOM images
            lx, ly = ds.pixel_array.shape  # beginning of operation
            X, Y = np.ogrid[0:lx, 0:ly]
            mask = (X - lx/2)**2 + (Y - ly/2)**2 < lx*ly/8
            array = ds.pixel_array[mask]
            if array:
                st_dev = np.std(array) # end of operation
                if root in dic_std_dev.keys():
                    dic_std_dev[root].append(st_dev)
                else:
                    dic_std_dev[root] = [st_dev]

dic = {}
for key in dic_std_dev.keys():
    if len(dic_std_dev[key]) > 0:
        dic[key] = np.mean(dic_std_dev[key])

print dic

rawDescription: Populating a dict from a for loop in Python


code:
string = "how to dye my brunet hair to blonde? "
list = ['how', 'how to',"bananas"]
list.sort(key=len,reverse=True)  # sort by decreasing length

for sample in string, "bananas taste swell", "how do you do?":
  for beginning in list:
    if sample.startswith(beginning):
      print sample[len(beginning):]
      break
  else:   # None of the beginnings matched
    print sample

rawDescription: Python string slice

description: Python string slice


code:
#UNTESTED
class Engine(object):
    def __init__(self, variable):
        self.variable = variable

class Event(object):
    def __init__(self, engine):
        super().__init__()
        self.engine = engine
    def process(self):
        print self.engine.variable

engine = Engine('123')
Event = functools.partial(Event, engine)

ThirdPartyApiThatNeedsAnEventClass(Event)

rawDescription: Share values between objects in the same Python module


code:
from parsley import makeGrammar, unwrapGrammar
from collections import OrderedDict

configFileGrammer = r"""

file = block+:bs end -> OrderedDict(bs)

block = ws name:b ws '{' ws members:m ws '}' ws -> (b, OrderedDict(m))

members = (setting:first (ws setting)*:rest ws -> [first] + rest) | -> []

setting = pair | flag

pair = ws name:k ws '=' ws name:v ws ';' ws -> (k, v)

flag = ws name:k ws ';' ws -> (k, True)

name = <(~('='|';'|'{') anything)+>:n -> n.strip()

"""

testSource = r"""
    portsbuild {
            path = /jails/portsbuild;
            allow.mount;
            mount.devfs;
            host.hostname = portsbuild.home;
            ip4.addr = 192.168.0.200;
            interface = nfe0;
            exec.start = "/bin/sh /etc/rc";
            exec.stop = "/bin/sh /etc/rc.shutdown";
    }

    web01 {
            path = /jails/web01;
            allow.mount;
            mount.devfs;
            host.hostname = web02.site.com;
            ip4.addr = 10.0.0.1;
            interface = eth0;
            exec.start = "/bin/sh /etc/rc";
    }

    db01 {
            path = /jails/db01;
            mount.devfs;
            host.hostname = db01.home;
            ip4.addr = 192.168.6.66;
            interface = if0;
            exec.start = "/bin/mysql";
    }

"""
ConfigFile = makeGrammar(configFileGrammer, globals(), name="ConfigFile")

config = unwrapGrammar(ConfigFile)(testSource).apply('file')[0]
for block in config:
    print "%s {" % block
    for key in config[block]:
        if config[block][key] == True:
            print "\t%s;" % key
        else:
            print "\t%s = %s;" % (key, config[block][key])
    print "}"

rawDescription: Parsing text file content into Python objects and writing back the objects into parse-able text file


code:
list = [ 'a',       'b',       'c',        'd'  ]
var1 = list[2]   #Assign it to var1
print var1       #Now printing var1 would give you 'c'

rawDescription: Pick non-random object from list Python

description: Pick non-random object from list Python


code:
from Tkinter import *
# import thread # not needed

class App:
    def __init__(self, master):
        print master

        def creatnew(): # recommend making this an instance method

            admin=Toplevel() # changed Tk to Toplevel
            lab=Label(admin,text='Workes')
            lab.pack()
            admin.minsize(width=250, height=250)
            admin.maxsize(width=250, height=250)
            admin.configure(bg='light green')
            # admin.mainloop() # only call mainloop once for the entire app!
        def other(): # you don't need define this as a function
            la=Label(master,text='other')
            la.pack()
            bu=Button(master,text='clicks',command=creatnew) # removed lambda+thread
            bu.pack()
        other() # won't need this if code is not placed in function

Admin = Tk()

Admin.minsize(width=650, height=500)
Admin.maxsize(width=650, height=500)
app = App(Admin)
Admin.mainloop()

rawDescription: why do I get a blank tkinter window?

description: Why do I get a blank tkinter window


code:
string = raw_input("Please enter a string: ").lower()
substring = raw_input("Please enter a substring: ").lower()
print string.replace(substring, substring.upper())

rawDescription: How can I capitalize a substring in a string in Python?

description: Capitalize a substring in a string in Python


code:
myjson = json.dumps(testdata)

mydata = json.loads(myjson)
#prints [u'word', u'is', u'bond', False, 6, 99], which contains unicode strings
print mydata
#prints ["word", "is", "bond", false, 6, 99], which is still just a string
print myjson

# Iterates over each character, since it's a string
for i in myjson:
    print i
# Iterates over the list
for i in mydata:
    print i

rawDescription: needed: simple way to force json to decode to "normal" iterable python lists

description: Needed: simple way to force json to decode to "normal" iterable python lists


rawDescription: Python Regex with split Method

description: Python Regex with split Method


code:
import os
import re

for root, dirs, files in os.walk('/path/to/directory'):
    for filename in files:
        with open(os.path.join(root, filename)) as file:
            for line in file:
                if re.match(b'\x64', line):
                    print filename

rawDescription: Searching in file content

description: Searching in file content


code:
print re.search('(a|(?<=b)c)', 'bc').group(1)
print re.search('(a|(?<=b)c)', 'a').group(1)

rawDescription: Regex match alternates with optional part


code:
import win32gui
import win32process
import win32api

fg_win = win32gui.GetForegroundWindow()
fg_thread, fg_process = win32process.GetWindowThreadProcessId(fg_win)
current_thread = win32api.GetCurrentThreadId()
win32process.AttachThreadInput(current_thread, fg_thread, True)
try:
    print win32gui.GetCaretPos()
finally:
    win32process.AttachThreadInput(current_thread, fg_thread, False) #detach

rawDescription: Python: Get caret position

description: Python: Get caret position


code:
#authors_list is a list that has the authors of the current publication I'm parsing.
#all_authors is a list that has all the authors found so far.

last_author_id = 0 #keeps track of authors index in all_authors list
all_authors = {}
for author in authors_list:
    if author in all_authors:
        author_index = all_authors[author]
        print "Author exists: ", author_index
    else:
        last_author_id += 1
        all_authors[author] = author_index = last_author_id
        au.writerow([author_index, author])
    aup.writerow([author_index, pid])

rawDescription: Faster way to write the following code

description: Faster way to write the following code


code:
d = {
    "data": {
        "id": 2,
        "name": "My TEST",
        "image": "1.jpg",
        "article": [
            {
                "id": 1,
                "name": "TEST"
            }
        ]
    }
}

myitems=[{
    'title': d["data"]['name'],
    'image': d["data"]['image'],
    'article_id': d["data"]['article'][0]['id']
}]
print myitems
[{'image': '1.jpg', 'article_id': 1, 'title': 'My TEST'}]

rawDescription: How to Parsing JSON With Python in relationship


code:
def playoffScoring(team1, team2):
    return team1  # replace with actual scoring function

def games_round(games):
    winners = []
    for team1, team2 in games:
        winning_team = playoffScoring(team1, team2)
        winners.append(winning_team)

    return winners

def plan_games(teams):
    return zip(teams[::2], teams[1::2])

teams = [1, 2, 3, 4, 5, 6, 7, 8]
round = 0
while len(teams) > 1:
     round += 1
     print "Round {}: teams: {}".format(round, teams)
     games = plan_games(teams)
     teams = games_round(games)

champion = teams[0]  # only one left
print "Champion is {}".format(champion)

rawDescription: Eliminating Teams in Playoff Brackets Using Python


code:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading

class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message =  threading.currentThread().getName()
        self.wfile.write(message)
        self.wfile.write('\n')
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

if __name__ == '__main__':
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

rawDescription: Multithreaded web server in python

description: Multithreaded web server in python


code:
class QuestionSinglePartForm(AutoExtensibleForm, form.Form):

    ignoreContext = True

    autoGroups = False

    @property
    def schema(self):
        return self._schema

    @property
    def additionalSchemata(self):
        return self._additionalSchemata

    def __init__(self, context, request, schema, additional=()):
        self.context = context
        self.request = request
        if not IInterface.providedBy(schema):
            raise ValueError('Schema is not interface object')
        self._schema = schema
        if not all(IInterface.providedBy(s) for s in additional):
            raise ValueError('Additional schema is not interface')
        self._additionalSchemata = additional

    @button.buttonAndHandler(u'Save')
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            return False
        obj = self.createAndAdd(data)
        if obj is not None:
            # mark only as finished if we get the new object
            self._finishedAdd = True
            IStatusMessage(self.request).addStatusMessage(_(u"Changes saved"), "info")
        print data

    @button.buttonAndHandler(u'Cancel')
    def handleCancel(self, action):
        print 'cancel'

class QuestionSinglePartView(object):

    schema = IQuestion
    additional = (IQuestionPart,)
    index = ViewPageTemplateFile('questionsinglepart_templates/questionsinglepart.pt')

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.form = QuestionSinglePartForm(context, request, self.schema, self.additional)
        alsoProvides(self.form, IWrappedForm)

    def magic(self, data, errors):
        pass
        """
        question = Question()
        question.number = data['number']
        question.questionContent = data['questionContent']

        questionPart = QuestionPart()
        questionPart.typeOfQuestion = data['IQuestionPart.typeOfQuestion']
        questionPart.explanation = data['IQuestionPart.explanation']
        questionPart.fileSize = data['IQuestionPart.fileSize']
        questionPart.fileType = data['IQuestionPart.fileType']
        questionPart.hints = data['IQuestionPart.hints']
        questionPart.table = data['IQuestionPart.table']
        questionPart.contype = data['IQuestionPart.contype']
        questionPart.content = data['IQuestionPart.content']
        """

    def update(self, *args, **kwargs):
        self.form.update(*args, **kwargs)
        self.formdisplay = self.form.render()

    def __call__(self, *args, **kwargs):
        self.update(*args, **kwargs)
        return self.index(*args, **kwargs)

rawDescription: How can I create a z3c.form that has multiple schemas?

description: Create a z3c.form that has multiple schemas


code:
def function(x, y):
    """A simple function, but 'y' will be a tuple.
    """
    a,b = y
    return (a*b) + x

print function(3,(4, 5))

rawDescription: How to make an argument into a tuple?

description: Make an argument into a tuple


code:
for item in b:
    if item in A:
        print A[item]

rawDescription: repeated items in a list python

description: Repeated items in a list python


code:
from random import random

def zeroG():
  n = random()
  if 0 <= n < 0.3:
    print "miss"
  elif 0.3 <= n < 0.7:
    print "1 point"
  elif 0.7 <= n <= 1:
    print "3 points"
  print n

rawDescription: Python random number generator program not printing results


code:
class counted(object):
    """ counts how often a function is called """
    def __init__(self, func):
        self.func = func
        self.counter = 0

    def __call__(self, *args, **kwargs):
        self.counter += 1
        return self.func(*args, **kwargs)

@counted
def something():
    pass

something()
print something.counter

rawDescription: Difference between decorator classes and decorator functions


code:
import csv
with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print ', '.join(row)

rawDescription: AttributeError on import csv

description: AttributeError on import csv


code:
#!/usr/bin/env python2.7

import sys, binascii, subprocess
import dpkt, pcap, socket

cottonelle = 'f0272d8b52c0'

def main():
    name = pcap.lookupdev()
    try:
        pc = pcap.pcap(name)
    except:
        print pc.geterr()

    try:
        print 'listening on %s' % (pc.name)
        for ts, pkt in pc:
            eth = dpkt.ethernet.Ethernet(pkt)
            ip_hdr = eth.data
            if eth.type != dpkt.ethernet.ETH_TYPE_ARP:
                continue
            if binascii.hexlify(eth.src) == cottonelle:
                subprocess.call("/usr/local/bin/stopsim", shell=True)
    except Exception as e:
        print e, pc.geterr()

if __name__ == '__main__':
    main()

rawDescription: python: using raw socket with OSX

description: Python: using raw socket with OSX


code:
import time
import sys

print "Please enter your name."
userName=raw_input();
print "Now let's wait a few seconds, {}.".format(userName)
sys.stdout.flush() # <- *** it goes here ***
time.sleep(3)
print "Did you lose your patience?"

rawDescription: Python time.sleep in Spyder: how to pause between print statements?


code:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///example.db')
engine.echo = True
Base = declarative_base()

class Location(Base):
    __tablename__ = 'locations'

    locationid = Column(Integer, primary_key=True)
    name = Column(String)
    address = Column(String)

    def __init__(self, name, address):
        self.name = name
        self.address = address

Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

def insertlocations(locationlist):
    session.add_all(locationlist)
    session.commit()

loc1 = Location('loc1', 'Foostreet 42')
loc2 = Location('loc2', 'Barstreet 27')

neighbourhoodlist = [loc1, loc2]

insertlocations(neighbourhoodlist)
for neighbourhood in neighbourhoodlist:
    print neighbourhood.locationid

session.close()

rawDescription: Inserting objects and using ids in SqlAlchemy


rawDescription: Url Regex: Finding Either or string(s) within another string with preference to an earlier one


code:
import gtk

class GUI(object):

    OPEN_IMAGE = gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON)
    CLOSED_IMAGE = gtk.image_new_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_BUTTON)
    toggled = True

    def __init__(self):
        self.window = gtk.Window()
        self.window.set_size_request(100, 150)
        self.window.connect("delete_event", gtk.main_quit)

        vbox = gtk.VBox()

        self.button = gtk.Button() # THIS is the button to modify
        self.button.set_image(self.OPEN_IMAGE)

        liststore = gtk.ListStore(str)
        liststore.append(["foo"])
        liststore.append(["bar"])
        self.treeview = gtk.TreeView(liststore)
        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn("Column 1")
        col.pack_start(cell, True)
        col.set_attributes(cell,text=0)
        self.treeview.append_column(col)

        vbox.pack_start(self.button, False, False, 1)
        vbox.pack_start(self.treeview, False, False, 1)

        self.treeview.connect('row-activated', self.the_method_wrapper, "plop")
        self.button.connect('clicked', self.the_method, "plop")

        self.window.add(vbox)
        self.window.show_all()
        return

    def the_method_wrapper(self, button, *args):
        self.the_method(self, "foo")

    def the_method(self, button, filename):
        print filename
        print vars(self)

        if self.toggled:
            self.button.set_image(self.CLOSED_IMAGE)
            self.toggled = False
        else:
            self.button.set_image(self.OPEN_IMAGE)
            self.toggled = True

def main():
    gtk.main()

if __name__ == "__main__":
    GUI()
    main()

rawDescription: Python : How can two GTK widgets interact with each other?


code:
import UnRAR2

rarc = UnRAR2.RarFile('test.rar')
list = rarc.infolist()

if list[0].isdir:
    print 'Parent directory in archive: %r' % list[0].filename

rawDescription: How to acquire extracted directory using pyUnrar2?

description: Acquire extracted directory using pyUnrar2


rawDescription: Chain last element of list with equal first element of another list


code:
def output(input1, input2):
    with input1:  # automatically close when done
        # set comprehension of all lines starting with @, minus last character
        to_match = {line.strip()[:-1] for line in input1 if line[0] == '@'}

    with input2:
        for line in input2:
            if line[0] == '@' and line.strip()[:-1] in to_match:
                print line.strip()
                for i in range(3):
                    print next(input2, '').strip()

rawDescription: python - extract several lines following a matched string

description: Python - extract several lines following a matched string


code:
f=0
s=1
for i in range (10):
    t = f + s
    print t
    f = s
    s = t

rawDescription: Python code for generating Fibonacci numbers is not working


code:
def A(heads, path, path_len):
    if heads < -1:
        path = []
        return float('inf') #Impossible to kill
    heads -= 6
    if heads < 0:
        return float('inf')
    path_len = path_len + 1
    path.append("A")
    if heads == 0:
        print path
        return path_len
    heads += 3
    return min(A(heads, path, path_len), B(heads, path, path_len))

def B(heads, path, path_len):
    if heads < -1:
        path = []
        return float('inf') #Impossible to kill
    heads -= 4
    if heads < 0:
        return float('inf')
    path_len = path_len + 1
    path.append("B")
    if heads == 0:
        print path
        return path_len
    heads += 2
    return min(A(heads, path, path_len), B(heads, path, path_len))

A(10, [], 0)

rawDescription: Monster heads problem in Python

description: Monster heads problem in Python


code:
def slope(X,Y,i):
    res = (Y[i]-Y[0])*1.0/(X[i]-X[0])
    return res

len_thold=0.2

def notgood(lst1,lst2):
    if len(lst1)<2 or len(lst2)<2:
        return True
    return  False

def adjust_miss(X,Y):
    slope_thold=1.1
    if len(X)==len(Y):
        return
    newlen=min(len(X),len(Y))
    if len(Y)-len(X)<0:
        aim=X
    else:
        aim=Y
    difflen=abs(len(Y)-len(X))
    roughk=slope(X,Y,newlen-1)
    for i in xrange(1,newlen):
        if difflen==0:
            break
        k=slope(X,Y,i)
        if (len(Y)<len(X) and k>slope_thold*roughk) or (len(Y)>len(X) and k<1.0/(slope_thold*roughk)):
            aim.pop(i)
            difflen-=1
    if difflen>0:
        for i in xrange(difflen):
            aim.pop(-1)
    assert len(X) == len(Y)

def test_adjust():
    X=range(10)
    Y=range(10)
    Y.pop(3)
    adjust_miss(X,Y)
    print X,Y

rawDescription: how to do linear regression in python, with missing elements

description: Do linear regression in python, with missing elements


code:
contents = open("file.dat").read()
for line in contents.split("*"):
  if not line: continue  # Remove initial empty string.
  line = line.strip()   # Remove whitespace from beginning/end of lines.
  items = line.split("-")
  print items[0], ":", " ".join(items[1:])

rawDescription: data.dat python

description: Data.dat python


rawDescription: Why is md5 hashing so much faster on strings than on numpy arrays in python?


code:
import subprocess
p = subprocess.Popen(["some", "command"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
stdout=stdout.split("\n")
for line in stdout:
    if line.startswith("This is the line:"):
        print line

rawDescription: How to get only one specific line from subprocess output

description: Get only one specific line from subprocess output


code:
import pymedia.removable.cd as cd

def readTrack(track, offset, bytes):
  cd.init()
  if cd.getCount() == 0:
    print 'There is no cdrom found. Bailing out...'
    return 0

  c = cd.CD(0)
  props = c.getProperties()
  if props['type'] != 'AudioCD':
    print 'Media in %s has type %s, not AudioCD. Cannot read audio data.' % (c.getName(), props['type'])
    return 0

  tr0 = c.open(props['titles'][track - 1]['name'])
  tr0.seek(offset, cd.SEEK_SET)
  return tr0.read(bytes)

rawDescription: Python Ripping CD Files to WAV

description: Python Ripping CD Files to WAV


code:
from bs4 import BeautifulSoup

html = '''

Hey, sexy!Hello

'''
soup = BeautifulSoup(html)
print soup.find('li').find(text=True, recursive=False)

rawDescription: How to only get inner text of a tag in BeautifulSoup, excluding the embedded one?

description: Only get inner text of a tag in BeautifulSoup, excluding the embedded one


code:
def haystack(b,e,u):
    i = re.search(b+'(.*)'+e, u)
    if i:     #check if there is any result
        return i.group(1)    #return match

#now try to call it
print haystack("this","str","this is str")    #this should output ' is '
print haystack("no","no", "this is str")      #this should not print anything

rawDescription: How do I put these variables in place correctly?

description: Put these variables in place correctly


code:
'''
Created on Oct 3, 2010

@authors: Daphna Rosenbom,Gitty Zinger,Moshe Cohavi and Yoav Glazner
The widget is contributed by NDS ltd under the same license as wxPython

items_picker.ItemsPicker:
  - Displays available items to choose from,

  - Selection is done by the Add button or Double Click,

  - De-Selection is done by the Remove button or Double Click,

  Derived from wxPanel
'''
import wx
__version__ = 0.1

IP_DEFAULT_STYLE = 0
IP_SORT_CHOICES = 1
IP_SORT_SELECTED = 2
IP_REMOVE_FROM_CHOICES = 4

wxEVT_IP_SELECTION_CHANGED = wx.NewEventType()
EVT_IP_SELECTION_CHANGED = wx.PyEventBinder(wxEVT_IP_SELECTION_CHANGED, 1)
LB_STYLE = wx.LB_EXTENDED|wx.LB_HSCROLL

class IpSelectionChanged(wx.PyCommandEvent):
    def __init__(self, id, items, object = None):
        wx.PyCommandEvent.__init__(self, wxEVT_IP_SELECTION_CHANGED, id)
        self.__items = items
        self.SetEventObject(object)

    def GetItems(self):
        return self.__items

class ItemsPicker(wx.Panel):
    '''
    ItemsPicker is a widget that allows the user to form a set of picked
    items out of a given list
    '''
    def __init__(self, parent, id=wx.ID_ANY, choices = [],
                 label = '', selectedLabel = '',
                 ipStyle = IP_DEFAULT_STYLE,
                 *args, **kw):
        '''
        ItemsPicker(parent, choices = [], label = '', selectedLabel = '',
                    ipStyle = IP_DEFAULT_STYLE)
        '''
        wx.Panel.__init__(self, parent, id, *args, **kw)
        self._ipStyle = ipStyle
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self._CreateSourceList(choices, label), 1,
                   wx.EXPAND|wx.ALL, 5)
        sizer.Add(self._CreateButtons(), 0, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(self._CreateDestList(selectedLabel), 1,
                   wx.EXPAND|wx.ALL, 5)
        self.SetSizer(sizer)

    def SetItems(self, items):
        '''SetItems(self, items)=> None
        items - Sequence of strings that the user can pick from'''
        return self._source.SetItems(items)

    def GetItems(self):
        '''GetItems(self)=> items
        returns list of strings that the user can pick from'''
        return self._source.GetItems()

    Items = property(fget = GetItems,
                     fset = SetItems,
                     doc = 'See GetItems/SetItems')

    def GetSelections(self):
        '''GetSelections(self)=>items
        returns list of strings that were selected
        '''
        return self._dest.GetItems()

    def SetSelections(self, items):
        '''SetSelections(self, items)=>None
        items - Sequence of strings to be selected
        The items are displayed in the selection part of the widget'''
        assert len(items)==len(set(items)),"duplicate items are not allowed"
        if items != self._dest.GetItems():
            self._dest.SetItems(items)
            self._FireIpSelectionChanged()

    Selections = property(fget = GetSelections,
                     fset = SetSelections,
                     doc = 'See GetSelections/SetSelections')

    def _CreateButtons(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.bAdd = wx.Button(self, -1, label = 'Add ->')
        self.bAdd.Bind(wx.EVT_BUTTON, self._OnAdd)
        self.bRemove = wx.Button(self, -1, label = '<- Remove')
        self.bRemove.Bind(wx.EVT_BUTTON, self._OnRemove)
        sizer.Add(self.bAdd, 0, wx.EXPAND|wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer.Add(self.bRemove, 0, wx.EXPAND|wx.ALL, 5)
        return sizer

    def _set_add_button_label(self, label=None):
        if label is None:
            return
        self.bAdd.SetLabel(label)

    add_button_label = property(fset = _set_add_button_label, fget = lambda x:x)

    def _set_remove_button_label(self, label=None):
        if label is None:
            return
        self.bRemove.SetLabel(label)

    remove_button_label = property(fset = _set_remove_button_label, fget = lambda x:x)

    def _OnAdd(self, e):
        if self._ipStyle & IP_REMOVE_FROM_CHOICES:
            self._MoveItems(self._source,self._dest)
        else:
            self._AddSelectedItems()

    def _MoveItems(self,source,dest):
        selections = source.GetSelections()
        selectedItems = map(source.GetString, selections)
        dest.SetItems(dest.GetItems() + selectedItems)
        selections = set(selections)
        source.SetItems([item for i, item in enumerate(source.GetItems())\
                      if i not in selections])
        self._FireIpSelectionChanged()

    def _AddSelectedItems(self):
        newItems = map(self._source.GetString, self._source.GetSelections())
        items = self._dest.GetItems()
        oldItems = set(items)
        for newItem in newItems:
            if newItem not in oldItems:
                items.append(newItem)
        self.SetSelections(items)

    def _FireIpSelectionChanged(self):
            self.GetEventHandler().ProcessEvent(
                        IpSelectionChanged(self.GetId(),
                                            self._dest.GetItems(),
                                             self ))

    def _OnRemove(self, e):
        if self._ipStyle & IP_REMOVE_FROM_CHOICES:
            self._MoveItems(self._dest, self._source)
        else:
            self._RemoveSelected()

    def _RemoveSelected(self):
        selections = self._dest.GetSelections()
        if selections:
            allItems = self._dest.GetItems()
            items = [item for i, item in enumerate(allItems)\
                      if i not in selections]
            self.SetSelections(items)
            self._FireIpSelectionChanged()

    def _CreateSourceList(self, items, label):
        style = LB_STYLE
        if self._ipStyle & IP_SORT_CHOICES:
            style |= wx.LB_SORT
        sizer = wx.BoxSizer(wx.VERTICAL)
        if label:
            sizer.Add(wx.StaticText(self, label = label), 0,
                       wx.ALIGN_LEFT|wx.ALL, 5)
        self._source = wx.ListBox(self, -1, style = style)
        self._source.Bind(wx.EVT_LISTBOX_DCLICK, self._OnDClick)
        self._source.SetItems(items)
        sizer.Add(self._source, 1, wx.EXPAND|wx.ALL, 5)
        return sizer

    def _CreateDestList(self, label):
        style = LB_STYLE
        if self._ipStyle & IP_SORT_SELECTED:
            style |= wx.LB_SORT
        sizer = wx.BoxSizer(wx.VERTICAL)
        if label:
            sizer.Add(wx.StaticText(self, label = label), 0,
                       wx.ALIGN_LEFT|wx.ALL, 5)
        self._dest = wx.ListBox(self, -1, style = style)
        self._dest.Bind(wx.EVT_LISTBOX_DCLICK,  self._OnDClick)
        sizer.Add(self._dest, 1, wx.EXPAND|wx.ALL, 5)
        return sizer

    def _OnDClick(self, e):
        lb = e.GetEventObject()
        selections = lb.GetSelections()
        if len(selections) != 1:
            return #DCLICK only works on one item
        if e.GetSelection() != selections[0]:
            #this can happen using ^DCLICK when two items are selected
            return
        if lb  == self._source:
            self._OnAdd(e)
        else:
            self._OnRemove(e)

if __name__ == '__main__':
    test = wx.PySimpleApp(0)
    frame = wx.Frame(None, -1)
    d = wx.Dialog(frame, style = wx.RESIZE_BORDER|wx.DEFAULT_DIALOG_STYLE)

    d.sizer = wx.BoxSizer(wx.VERTICAL)
    d.sizer.Add(wx.StaticText(d, -1, label = 'Example of the ItemsPicker'),
                 0, wx.ALL, 10)
    ip = ItemsPicker(d, -1, ['pop', 'cool', 'lame'],
                      'Stuff:', 'Selected stuff:',IP_SORT_SELECTED|IP_SORT_CHOICES|IP_REMOVE_FROM_CHOICES)
    ip.add_button_label = u'left -> right'
    ip.remove_button_label = u'right -> left'
    d.sizer.Add(ip, 1, wx.EXPAND, 1)
    d.SetSizer(d.sizer)
    test.SetTopWindow(frame)
    def callback(e):
        print 'selected items', e.GetItems()
    d.Bind(EVT_IP_SELECTION_CHANGED, callback)
    d.ShowModal()
    d.Destroy()
    frame.Close()

rawDescription: Looking for a wxPython widget

description: Looking for a wxPython widget


code:
def sorting(*args):
    sorted_list, args = sorted(args), list(args)
    if sorted_list == args:
        print "Rising"
    elif sorted_list[::-1] == args:
        print "Descending"
    else:
        print "No Fish"

sorting(1, 2, 3, 4)        # Rising
sorting(5, 4, 3, 2, 1)     # Descending
sorting(2, 1, 3, 6, 4, 5)  # No Fish

rawDescription: Comparing lists which have the same elements, are in the same order?


code:
import shlex, subprocess
filesystems = ['/dev/mapper/VolGroup00-LogVol00', '/dev/vda1', 'tmpfs']
for fs in filesystems:
    command = '/sbin/dumpe2fs ' + fs
    p = subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = p.communicate()[0]
    if 'superblock at' in output:
            print "{fs} has superblock".format(fs=fs)
    else:
            print "No superblock found for {fs}".format(fs=fs)

rawDescription: Find the superblock on disk

description: Find the superblock on disk


code:
strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

rawDescription: python: check if a line has one of the strings in a list

description: Python: check if a line has one of the strings in a list


code:
import pyodbc
# Create connection
con = pyodbc.connect(driver="{SQL Server}",server=SERVERNAME,database=DATA_BASE_INFO,uid=username,pwd=password)
cur = con.cursor()
db_cmd = "SELECT * FROM table_name"
res = cur.execute(db_cmd)
# Do something with your result set, for example print out all the results:
for r in res:
    print r

rawDescription: Sql Server query with python

description: Sql Server query with python


code:
start = int(input("Enter the start Number:"))
end = int(input("Enter the end number:"))

while(start < end):
    print start, start + 10
    start = start + 10

rawDescription: Take 2 integer inputs say x = 10 and y = 50 and print in the format 10,20 20,30, 30,40 and 40,50


code:
x = ['http://exampleurl.com/index.php', 'http://exampleurl2.com/in_dex1.php',
     'http://exampleurl.com/posts/images', 'http://exampleurl2.com/posts/tags/etc']
for i in x:
    if 'posts' in i:
        print i
        break

rawDescription: Get the first url from list that contains 'posts' in it


code:
string = "Here is my dog"

def alternateUppercase(s):
    i = 0
    a = s.split(' ')
    l = []
    for w in a:
        if i:
            l.append(w.upper())
        else:
            l.append(w)
        i = int(not i)
    return " ".join(l)

print alternateUppercase(string)

rawDescription: how to upper case every other word in string in python

description: Upper case every other word in string in python


code:
def get_target_match(target, targets):
    '''
    Approximates a match for a target from a sequence of targets,
    if a match exists.
    '''
    source, targets = targets, map(str.lower, targets)
    target = target.lower()

    matches = get_close_matches(target, targets, n=1, cutoff=0.25)

    if matches:
        match = matches[0]
        return source[targets.index(match)]
    else:
        return None

target = 'Z'
targets = ['Joe', 'Bob', 'zombie', 'Susan', 'kobold', 'Bill']
match = get_target_match(target, targets)
print "Going nom on %s" % match # IT'S A ZOMBIE!!!

rawDescription: Python Disambiguation

description: Python Disambiguation


code:
y={'5':'8'}
x=raw_input('hi?')

if x in y:
    print 'yeah'
else:
    print 'nope'

rawDescription: Check if key is in a dictionary

description: Check if key is in a dictionary


code:
from time import sleep # this should go at the top of the file

sleep(5)
html = driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
print html

rawDescription: How to get html with javascript rendered sourcecode by using selenium

description: Get html with javascript rendered sourcecode by using selenium


code:
class ListData:
        def __init__(self):
                 self.data = []

        def add(self, x):
                 self.data.append(x)

        def delete(self, x):
                 self.data.remove(x)

        def data(self):
            return self.data

a = ListData()
a.add(1)
a.add(2)
print a.data

rawDescription: Python data list issue

description: Python data list issue


code:
from boto.s3.connection import S3Connection

conn = S3Connection(settings.AWS_ACCESS_KEY_ID,settings.AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(settings.MEDIA_BUCKET)

for key in bucket.list():
    print key.name

rawDescription: Django retrieval of list of files in S3 bucket


code:
import os,csv, glob

for file in glob.glob(os.path.join(os.getcwd(), '*.txt')):
    with open(file) as f:
        mydict = {}
        for line in f:
            mydict[",".join(line.split()[0:4])] = ",".join(line.split()[4:6])
    for key,val in mydict.iteritems():
        print file, key, val

rawDescription: Python: dict.items() is printing more rows (rows that are not in actual file)


code:
import urllib,httplib

conn = httplib.HTTPConnection("auburn.craigslist.org")
params = urllib.urlencode({'query': 'english tutor', 'catAbb': 'bbb'})
conn.request("GET","/search?%s" % params)
response = conn.getresponse()

print response.read()

rawDescription: html get request "you didn't select a category"

description: Html get request "you didn't select a category"


code:
from web import form

# field validators
username_required = form.Validator("Username not provided", bool)
password_required = form.Validator("Password not provided", bool)
password_length = form.Validator("Password length should be minimum 7 characters", lambda p: p is None or len(p) >= 7)

# form validators
login_details_required = form.Validator("Please Enter Login Details", lambda f: f["username"] or f["password"])

def check_login(f):
    # check for login here
    return False
valid_credentials = form.Validator("Invalid username or password", check_login)

login_form = form.Form(
    form.Textbox('username', username_required),
    form.Password('password', password_required, password_length, description="Password"),
    form.Button('Login'),
    validators=[login_details_required, valid_credentials],
)

my_form = login_form()
if not my_form.validates(dict(username="", password="small")):
    print my_form.render_css()

if not my_form.validates(dict(username="notnull", password="just-enough")):
    print my_form.render_css()

rawDescription: How to display validation message on the browser in web.py python

description: Display validation message on the browser in web.py python


code:
import sys
from PySide import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        self.do_something() #sanity check
        self.cw = ChildWidget(self)
        self.setCentralWidget(self.cw)
        self.show()

    def do_something(self):

        print 'doing something!'

class ChildWidget(QtGui.QWidget):

    def __init__(self, parent):
        super(ChildWidget, self).__init__(parent)

        self.button1 = QtGui.QPushButton()
        self.button1.clicked.connect(self.do_something_else)

        self.button2 = QtGui.QPushButton()
        self.button2.clicked.connect(self.parent().do_something)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.setLayout(self.layout)
        self.show()

    def do_something_else(self):

        print 'doing something else!'

def main():
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: calling a parent method from a child widget in pyside/pyqt

description: Calling a parent method from a child widget in pyside/pyqt


code:
import pickle
import math
import urllib2
from lxml import etree
from bs4 import BeautifulSoup
from urllib import urlopen

year = '2014'
lastWeek = '2'
favQB1 = "Tom Brady"

favQBurl2 = 'http://www.nfl.com/player/tombrady/2504211/gamelogs'
favQBhtml2 = urlopen(favQBurl2).read()
favQBsoup2 = BeautifulSoup(favQBhtml2)
favQBpass2 = favQBsoup2.find_all("table", { "summary" : "Game Logs For %s In %s" % (favQB1, year)})[1]
favQBrows2 = []

for row in favQBpass2.findAll("tr"):
    if lastWeek in row.findNext('td'):
        for item in row.findAll("td"):
            favQBrows2.append(item.text)
print ("Enter: Starting Quarterback QB Rating of Favored Team for the last game played (regular season): "),
print favQBrows2[15]

rawDescription: Python Beautiful Soup Table Data Scraping Specific TD Tags


code:
SSN = raw_input("enter SSN (ddd-dd-dddd):")
chunks = SSN.split('-')
valid=False
if len(chunks) ==3:
   if len(chunks[0])==3 and len(chunks[1])==2 and len(chunks[2])==4:
       valid=True
print valid

rawDescription: Social Security Number Check - Python

description: Social Security Number Check - Python


code:
from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday
from datetime import datetime

cal = get_calendar('USFederalHolidayCalendar')  # Create calendar instance
cal.rules.pop(7)                                # Remove Veteran's Day rule
cal.rules.pop(6)                                # Remove Columbus Day rule
tradingCal = HolidayCalendarFactory('TradingCalendar', cal, GoodFriday)
print tradingCal.rules

#new instance of class
cal1 = tradingCal()

print cal1.holidays(datetime(2014, 12, 31), datetime(2016, 12, 31))

#DatetimeIndex(['2015-01-01', '2015-01-19', '2015-02-16', '2015-04-03',
#               '2015-05-25', '2015-07-03', '2015-09-07', '2015-11-26',
#               '2015-12-25', '2016-01-01', '2016-01-18', '2016-02-15',
#              '2016-03-25', '2016-05-30', '2016-07-04', '2016-09-05',
#               '2016-11-24', '2016-12-26'],
#              dtype='datetime64[ns]', freq=None, tz=None)

rawDescription: Create trading holiday calendar with Pandas


code:
import datetime
import time

def getA():
  import random
  return random.random()

def getB():
  return .01

checkTime = datetime.timedelta(minutes=10)
checkIntervalInSecs = .5

c = False
timeToStop = datetime.datetime.now() + checkTime
while(datetime.datetime.now() < timeToStop):
  if getA() < getB():
    c = True
    break
  time.sleep(checkIntervalInSecs)

print c

rawDescription: Conditional over a time duration

description: Conditional over a time duration


code:
input = '''
DIR   s3://foo/versions/4.4.1.2/
DIR   s3://foo/versions/4.5.0.10a/
DIR   s3://foo/versions/4.5.0.11a/
DIR   s3://foo/versions/4.5.0.12a/
DIR   s3://foo/versions/4.5.0.13a/
'''
print re.findall("versions/([^/]*)/", input)

rawDescription: Parsing Amazon S3 URIs using regex in Python?


code:
# /myapp/enviroment/__init__.py

class ThatSingleInstanceClass: pass

# create the singleton object directly or have a function init the module
singleton = ThatSingleInstanceClass()

# /myapp/somewhere.py

# all you need to use the object is importing it
from myapp.enviroment import singleton

class SomeClass:

    def __init__(self): # no need to pass that object
        print "Always the same object:", singleton

rawDescription: How can I set up global for every imported file in Python automatically?

description: Set up global for every imported file in Python automatically


code:
def kaboom(n):
    if (n % 2) == 0: print n,
    if n == 0: return # we "hit bottom"
    kaboom(n-1) # make the recursive call
    # From this point on, we are "on the way back", and print each value.
    print n,

rawDescription: recursive function

description: Recursive function


code:
import win32com.client
import pythoncom
import re

class Handler_Class(object):
    def OnNewMailEx(self, receivedItemsIDs):
        # RecrivedItemIDs is a collection of mail IDs separated by a ",".
        # You know, sometimes more than 1 mail is received at the same moment.
        for ID in receivedItemsIDs.split(","):
            mail = outlook.Session.GetItemFromID(ID)
            subject = mail.Subject
            try:
                # Taking all the "BLAHBLAH" which is enclosed by two "%".
                command = re.search(r"%(.*?)%", subject).group(1)

                print command # Or whatever code you wish to execute.
            except:
                pass

outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)

#and then an infinit loop that waits from events.
pythoncom.PumpMessages()

rawDescription: Microsoft Outlook Create Rule Run Application/Script Python


code:
def guesser(low = 0, up = 100):
    print("Choose a number between %d and %d" % (low, up-1))
    while low < up - 1:
        mid = (low+up)//2
        yn = raw_input("Is Your Number Smaller Than %s? (y/n): " % mid)
        if yn not in ['y', 'n']: continue
        low, up =  (low, mid) if yn == 'y' else (mid, up)
    print "Your Number is:", low

guesser()

rawDescription: Number Guesser: Please Review and Make it More Pythonic


code:
class MyDict(object):
    def __init__(self, items=()):
        self._dict = dict(items)

    def keys(self):
        return self._dict.keys()

    def __getitem__(self, item):
        print "Doing some stuff for item:", item
        return self._dict[item]

    def __setitem__(self, item, value):
        self._dict[item] = value

    # You can add some more dict methods

d1 = MyDict({'1': 1, '2': 2})
d2 = {}
# Now you will see some stuff executed for each
# value extracted from d1 while updating d2
d2.update(d1)

rawDescription: Intercept dict __getitem__ method call when it's passed to update method of another dict


code:
def main():
    # We will store the running threads in this
    threads = []
    # Start the threads
    for nums in [range(0,5), range(5,10)]:
        t = Spider(nums)
        t.start()
        print 'started a thread'
        threads.append(t)
    # All the threads have been started
    # Now we wait for them to finish
    for t in threads:
        t.join()
    print "done"

rawDescription: Python threaded code not acting threaded


code:
from binascii import b2a_hex, a2b_hex
import active_directory as ad

# entry_type, see http://msdn.microsoft.com/en-us/library/cc840018.aspx
#  + AB_DT_CONTAINER     0x000000100
#  + AB_DT_TEMPLATE      0x000000101
#  + AB_DT_OOUSER        0x000000102
#  + AB_DT_SEARCH        0x000000200
# ab_flags, maybe see here: https://svn.openchange.org/openchange/trunk/libmapi/mapidefs.h

def gen_exchange_entry_id(user_id, ab_flags=0, entry_type = 0):
    muidEMSAB = "DCA740C8C042101AB4B908002B2FE182"
    version = 1

    # Find user and bail out if it's not there
    ad_obj = ad.find_user(user_id)
    if not ad_obj:
        return None

    return "%08X%s%08X%08X%s00" % (
        ab_flags,
        muidEMSAB,
        version,
        entry_type,
        b2a_hex(ad_obj.legacyExchangeDN.upper()).upper(),
    )

data = gen_exchange_entry_id("myusername")
print data
print len(a2b_hex(data))

rawDescription: Retrieve User Entry IDs from MAPI

description: Retrieve User Entry IDs from MAPI


code:
import urllib
URL_TEMPLATE="http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-%d-%.4d&language=EN"
maxRange=300

for year in [2010, 2011]:
    for page in range(1,maxRange):
        f=urllib.urlopen(URL_TEMPLATE%(year, page))
        text=f.read()
        if "<title>Application Error</title>" in text:
            print "year %d and page %.4d NOT found" %(year, page)
        else:
            print "year %d and page %.4d FOUND" %(year, page)
        f.close()

rawDescription: Determining number of sites on a website in python


code:
fn = 'mydownload.pdf'
print 'Content-Type:application/pdf';
print 'Content-Disposition: attachment; filename="%s"' %(fn);
print
print sio.getvalue()

rawDescription: serve a stringIO (pdf) as download python

description: Serve a stringIO (pdf) as download python


code:
import decimal

def main():
    principle = decimal.Decimal(raw_input('Please enter your loan amount:'))
    rate = decimal.Decimal(raw_input('Please enter rate of interest (percent):')) / 100
    term = decimal.Decimal(raw_input('Please enter loan period (years):')) * 12

    interest = (principle * rate).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_HALF_EVEN)
    balance = principle + interest
    payment = (balance / term).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_CEILING)
    print "Payment\t\tAmount Paid\t\tRem.Bal."
    for count in range(1+term):
        if count == 0:
            print count, "\t\t0.00\t\t\t", balance
        elif count == term: # last payment?
            payment = balance
            balance -= payment
            print count, "\t\t", payment, "\t\t\t", balance
        else:
            balance -= payment
            print count, "\t\t", payment, "\t\t\t", balance

main()

# > python loan_calc.py
# Please enter your loan amount:100
# Please enter rate of interest (percent):6
# Please enter loan period (years):1
# Payment         Amount Paid             Rem.Bal.
# 0               0.00                    106.00
# 1               8.84                    97.16
# 2               8.84                    88.32
# 3               8.84                    79.48
# 4               8.84                    70.64
# 5               8.84                    61.80
# 6               8.84                    52.96
# 7               8.84                    44.12
# 8               8.84                    35.28
# 9               8.84                    26.44
# 10              8.84                    17.60
# 11              8.84                    8.76
# 12              8.76                    0.00

rawDescription: am I doing it right ? question regarding piece of code I wrote

description: Am I doing it right ? question regarding piece of code I wrote


code:
import threading
import time
import gtk, gobject, glib

gobject.threads_init()

class Test():
    def __init__(self):
        self.counter = 0
        self.label = gtk.Label()
        self.progress_bar = gtk.ProgressBar()
        self.progress_bar_lock = threading.Lock()
        button = gtk.Button("Test")

        window = gtk.Window()

        box = gtk.VBox()
        box.pack_start(self.label)
        box.pack_start(self.progress_bar)
        box.pack_start(button)
        window.add(box)

        window.connect("destroy", lambda _: gtk.main_quit())
        button.connect("clicked", self.on_button_click)
        window.show_all()

    def update_label(self, counter):
        self.label.set_text("Thread started (counter: {0})"
                            .format(counter))
        time.sleep(5)
        self.label.set_text("Thread finished (counter: {0})"
                            .format(counter))
        return False

    def pulse_progress_bar(self):
        print threading.active_count()
        if threading.active_count() > 1:
            self.progress_bar.pulse()
            return True

        self.progress_bar.set_fraction(0.0)
        self.progress_bar_lock.release()
        return False

    def on_button_click(self, widget):
        self.counter += 1
        thread = threading.Thread(target=self.update_label,
                                  args=(self.counter,))
        thread.start()

        if self.progress_bar_lock.acquire(False):
            glib.timeout_add(250, self.pulse_progress_bar)

if __name__ == '__main__':
    test = Test()
    gtk.main()

rawDescription: Stop pygtk GUI from locking up during long-running process


code:
import threading
import time
import Queue
import sys
import random

class FlowController(threading.Thread):
    def __init__(self,queueStream):
        threading.Thread.__init__(self)
        self.queueStream=queueStream
    def run(self):
        while True:
            if not self.queueStream.empty():
                print 'Handling tweet'
                self.handleNextTweet()
            else:
                print 'No tweets, sleep for 1 second'
                time.sleep(1)
    def handleNextTweet(self):
        status = self.queueStream.get()
        print(status)

class RunStream(threading.Thread):
    def __init__(self,queueStream):
        threading.Thread.__init__(self)
        self.queueStream=queueStream
    def run(self):
        i=0
        while True:
            addToQueue(self.queueStream,i)
            i+=1
            time.sleep(random.randint(0,2))

def addToQueue(queueStream,status):
    print 'adding tweets to the queue'
    queueStream.put(status)
    if not queueStream.empty():
        print 'queueStream is non-empty'

if __name__ == '__main__':
    queueStream = Queue.Queue()
    try:
        runner = RunStream(queueStream)
        runner.daemon=True
        runner.start()
        flow = FlowController(queueStream)
        flow.daemon=True
        flow.start()
        time.sleep(100)
    except KeyboardInterrupt:
        pass
    finally:
        print('Bye!')

rawDescription: Python scoping and threading question

description: Python scoping and threading question


code:
def get_text(file_name):
    with open(file_name) as file:
        return pickle.load(file)

def matching(sourceText,suspectText):
    matching = difflib.SequenceMatcher(None,sourceText,suspectText)
    print matching.ratio()

def main():
    for suspect_file in list_of_suspect_files:
        print ('----------------SEPERATOR-----------------')
        suspect_text = get_text(suspect_file)
        for source_file in list_of_source_files:
            source_text = get_text(source_file)
            matching(source_text, suspect_text)

main()

rawDescription: Python for loop to go through directory files


code:
def prefix(input):
  op, num1, num2 = input.split(" ")
  num1 = int(num1)
  num2 = int(num2)
  if op == "+":
    return num1 + num2
  elif op == "*":
    return num1 * num2
  else:
    # handle invalid op
    return 0

print prefix("+ 2 2")

rawDescription: prefix notation parsing in python

description: Prefix notation parsing in python