code:
from django.db import connection

m = ModelFour.objects.all()[0]

print len(connection.queries)

rawDescription: Django - Foreignkey and Many to Many References - How to Know Number of Queries?


code:
import re
str = ['2 Apple pie $1.50 /each: $3.00',
   'Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory $34.99']

output = [re.match(r"(.+)(\$.*)$", x).groups() for x in str]
print output
# [('2 Apple pie $1.50 /each: ', '$3.00'), ('Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory ', '$34.99')]

rawDescription: Python regex to split last dollar value

description: Python regex to split last dollar value


code:
import copy

def create_array_mutable(dims, obj):
  if len(dims) == 0:
    return copy.deepcopy(obj)
  else:
    return [create_array_mutable(dims[1:], obj) for i in xrange(dims[0])]

class C(object): pass

print create_array_mutable((2,3,4), C())

rawDescription: Better way to initialize multidimensional array with mutable object


code:
import new

def with_bar(func):
    def bar(x):
        return x + 1
    f_globals = func.func_globals.copy()
    f_globals['bar'] = bar
    return new.function(func.func_code, f_globals,
                        func.func_name, func.func_defaults, func.func_closure)

@with_bar
def foo(x):
    return bar(x)

print foo(5) # prints 6

rawDescription: defining functions in decorator

description: Defining functions in decorator


code:
from urlparse import urlparse

parsedurl = urlparse('http://example.com/filename.txt')
print parsedurl.path

rawDescription: Beautiful Soup and URL base names in python


code:
def my_m2m_signal(sender, **kwargs):
    action = kwargs.get('action')
    if action == 'post_add':
        print 'post_add is activated on m2m'

signals.m2m_changed.connect(my_m2m_signal, sender=Person.car.through)

rawDescription: Many to many field not shown in object while using signals to detect save operation in django


code:
import sys
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage

class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.html = None
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        self.connect(self, SIGNAL('loadFinished(bool)'), self._finished_loading)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()

    def _finished_loading(self, result):
        self.html = self.mainFrame().toHtml()
        self.app.quit()

if __name__ == '__main__':
    try:
        url = sys.argv[1]
    except IndexError:
        print 'Usage: %s url' % sys.argv[0]
    else:
        javascript_html = Render(url).html

rawDescription: Screen scraping with Python

description: Screen scraping with Python


code:
import sympy.abc as abc
symbols = ['*','/','(',')',"'",'"']
letters = []
def try_expr(expr):
    try:
        for letter in letters:
            exec('from sympy.abc import %s'%letter) # re-execute after finding each unknown variable
        l = expr.count('(')
        r = expr.count(')')
        if l == r:
            eval(expr)
        elif l < r:
            eval((r-l)*'('+expr)
    except NameError as err:
        msg = str(err)
        pos = msg.find("'")
        letter = msg[pos+1]
        pos = pos +1
        found = False
        while (pos+1 < len(msg)) and (not found): # check for multi-char greek letters
            more = msg[pos+1]
            for symb in symbols:
                if more==symb or more.isdigit():
                    found = True
                    break
            if found is False:
                letter = letter+more
                pos = pos + 1
        for alphabet in abc.__dict__:
            if letter == alphabet:
                letters.append(alphabet)
                try_expr(expr[expr.find(alphabet):]) # search for the next unknown variable

from sympy import sin, sqrt, log, exp, cos, tanh, sinh, cosh, atan, acos, asin
import sys
if len(sys.argv) == 1:
    expr = '(sin(x**2)-log(exp(2*y))) + cos(x**2) + a + b + c + theta*eta'
else:
    expr = sys.argv[1]
try_expr(expr)
for letter in letters:
    exec('from sympy.abc import %s'%letter)
print 'The SymPy expression %s contains the following letters : %s' %(eval('%s'%expr), letters)

rawDescription: Defining sympy.abc variables on the fly : name error handling


code:
import mechanize
cj1 = mechanize.CookieJar()
cj2 = mechanize.CookieJar()
mech1 = mechanize.OpenerFactory().build_opener(mechanize.HTTPCookieProcessor(cj1))
mech2 = mechanize.OpenerFactory().build_opener(mechanize.HTTPCookieProcessor(cj2))
request = mechanize.Request('http://example.com') # testing shows they can share a request
response1 = mech1.open(request)
response2 = mech2.open(request)
print cj1
print cj2

rawDescription: mechanize: cookies getting mixed up?

description: Mechanize: cookies getting mixed up


code:
# copied directly from the docs
from jinja2 import Environment, PackageLoader

env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

rawDescription: How can I use a Jinja2 template inside a Python program?

description: Use a Jinja2 template inside a Python program


code:
for k, v in self.monitors.iteritems():
    def createLambda(k):
        return lambda(r): self.change_brightness(k, r)
    Scale(root, variable = DoubleVar(), command = createLambda(k)).grid(row=0, column=col)

rawDescription: Passing variables to function in python

description: Passing variables to function in python


code:
#!/usr/bin/env python

import SocketServer, argparse

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.server.server_address is a tuple (IP, port) the server is listening on
        (host, port) = self.server.server_address
        print 'port # is: {}'.format(port)
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', required=True, help='the TCP port to listen on')
    args = parser.parse_args()
    HOST, PORT = "localhost", int(args.port)

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

rawDescription: Python socketserver, how to get my own tcp port number


code:
import wx
def onFocus(event):
    print "widget received focus!"

def onKillFocus(event):
    print "widget lost focus!"

app = wx.App()

frame = wx.Frame(None, -1, '')
box = wx.StaticBox(frame, -1, "")
sizer = wx.StaticBoxSizer(box, orient=wx.VERTICAL)
text0 = wx.StaticText(frame,label="1st Item")
text0_input = wx.TextCtrl(frame, wx.ID_ANY, size=(345,25))
text = wx.StaticText(frame, label="Some Text")
text_input = wx.TextCtrl(frame, wx.ID_ANY, size=(345,25))
sizer.Add(text0, wx.ALIGN_LEFT|wx.ALL, border=10)
sizer.Add(text0_input, wx.ALIGN_LEFT|wx.ALL, border=10)
sizer.Add(text, wx.ALIGN_LEFT|wx.ALL, border=10)
sizer.Add(text_input, wx.ALIGN_LEFT|wx.ALL, border=10)
text0_input.Bind(wx.EVT_SET_FOCUS, onFocus)
text0_input.Bind(wx.EVT_KILL_FOCUS, onKillFocus)

main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(sizer)
frame.SetSizer(main_sizer)

frame.Centre()
frame.Show()
text_input.SetFocus()
#print 'text_input.HasFocus?', text_input.HasFocus()

app.MainLoop()

rawDescription: wxPython SetFocus() not working

description: WxPython SetFocus() not working


code:
import unittest

class aa(unittest.TestCase):
    def test_aa(self):
        self.assertTrue(True)

if __name__ == '__main__':
    # this will not run on import, only when tests are running with unittest with python
    testlist = []

    suite = unittest.TestLoader().loadTestsFromTestCase(aa)
    testlist.append(suite)

    allSuites = unittest.TestSuite(testlist)
    unittest.TextTestRunner(verbosity=3).run(allSuites)

    print 'done'

rawDescription: Nosetest overwrites xml output

description: Nosetest overwrites xml output


code:
from bs4 import BeautifulSoup

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
# it takes forever to load the page, therefore we are setting a threshold
driver.set_page_load_timeout(5)

try:
    driver.get("http://kissmanga.com/Manga/Bleach/Bleach-634--Friend-004?id=235206")
except TimeoutException:
    # never ignore exceptions silently in real world code
    pass

soup2 = BeautifulSoup(driver.page_source, 'html.parser')
divImage = soup2.find('div', {"id": "divImage"})

# close the browser
driver.close()

for img in divImage.findAll('img'):
    print img.get('src')

rawDescription: Python Scraper Unable to scrape img src

description: Python Scraper Unable to scrape img src


code:
import numpy as np
import pylab as plt
import scipy.optimize as optimize

# This is your target function
def sineFit(t, (a, f, p)):
    return a * np.sin(2.0*np.pi*f*t + p)

# This is our "error" function
def err_func(p0, X, Y, target_function):
    err = ((Y - target_function(X, p0))**2).sum()
    return err

# Try out different parameters, sometimes the random guess works
# sometimes it fails. The FFT solution should always work for this problem
inital_args = np.random.random(3)

X = np.linspace(0, 10, 1000)
Y = sineFit(X, inital_args)

# Use a random inital guess
inital_guess = np.random.random(3)

# Fit
sol = optimize.fmin(err_func, inital_guess, args=(X,Y,sineFit))

# Plot the fit
Y2 = sineFit(X, sol)
plt.figure(figsize=(15,10))
plt.subplot(211)
plt.title("Random Inital Guess: Final Parameters: %s"%sol)
plt.plot(X,Y)
plt.plot(X,Y2,'r',alpha=.5,lw=10)

# Use an improved "fft" guess for the frequency
# this will be the max in k-space
timestep = X[1]-X[0]
guess_k = np.argmax( np.fft.rfft(Y) )
guess_f = np.fft.fftfreq(X.size, timestep)[guess_k]
inital_guess[1] = guess_f

# Guess the amplitiude by taking the max of the absolute values
inital_guess[0] = np.abs(Y).max()

sol = optimize.fmin(err_func, inital_guess, args=(X,Y,sineFit))
Y2 = sineFit(X, sol)

plt.subplot(212)
plt.title("FFT Guess          : Final Parameters: %s"%sol)
plt.plot(X,Y)
plt.plot(X,Y2,'r',alpha=.5,lw=10)
plt.show()

rawDescription: Failure of non linear fit to sine curve

description: Failure of non linear fit to sine curve


code:
from pyDes import *
import bz2

def encrypt(data,password):
    k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
    d = k.encrypt(data)
    return d

def decrypt(data,password):
    k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
    d = k.decrypt(data)
    return d

password = "eight222" # password length should be 8

data = '''
<?xml version="1.0"?>
  <library>
   <shelf id="fiction">
    <book>
     <title>Of Mice and Men</title>
     <author>John Steinbeck</author>
    </book>
    <book>
     <title>Harry Potter and the Philosopher's Stone</title>
     <author>J.K. Rowling</author>
    </book>
   </shelf>
  </library>
'''

print len(data)

compressed_data = bz2.compress(data)
print len(compressed_data)

encrypted_data = encrypt(compressed_data,password)

print "%r"%encrypted_data

uncompressed_encrypted_data = encrypt(data,password)

print len(encrypted_data)
print len(uncompressed_encrypted_data)
print bz2.decompress(decrypt(encrypted_data,password))

rawDescription: Encrypting XML database in python

description: Encrypting XML database in python


code:
from django.db import connection
tables = connection.introspection.table_names()

for model in connection.introspection.installed_models(tables):
    print model.__name__
    print model._meta.db_table
    print model._meta.get_all_field_names()

rawDescription: Can I find and replace a string in an entire postgresql database of a Django project?

description: Find and replace a string in an entire postgresql database of a Django project


code:
import numpy as np, statsmodels.api as sm

nsample = 100
x = np.linspace(0, 10, nsample)
X = np.column_stack((x, x**2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=nsample)

X = sm.add_constant(X)
y = np.dot(X, beta) + e

mod = sm.OLS(y, X)
res = mod.fit()
print res.conf_int(0.01)   # 99% confidence interval

rawDescription: How to calculate the 99% confidence interval for the slope in a linear regression model in python?

description: Calculate the 99% confidence interval for the slope in a linear regression model in python


code:
import sys
import gtk
import pygtk
pygtk.require('2.0')
import gobject

import threading

class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        for i in range(10):
            print "Hello %d from thread %s" % (i, self.name)

class Console:
    def __init__(self):
        tv = gtk.TextView()
        tv.set_editable(False)
        tv.set_wrap_mode(gtk.WRAP_WORD)
        self.buffer = tv.get_buffer()

        button = gtk.Button("Update")
        button.connect("clicked", self.update, None)

        table = gtk.Table(3, 6, gtk.FALSE)
        table.attach(tv, 0, 6, 0, 1)
        table.attach(button, 0, 6, 1, 2)

        #### Main window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect('destroy_event', lambda w, e: gtk.mainquit())
        self.window.connect('delete_event', lambda w, e: gtk.mainquit())
        self.window.set_border_width(10)
        self.window.add(table)
        self.window.set_title('Search')
        self.window.set_default_size(300, 300)
        self.window.show_all()

    def update(self, widget, data=None):
        print "hello"
        MyThread("A").start()
        MyThread("B").start()

    def main(self):
        gtk.main()

c = Console()

class ConsoleOutput:
    def __init__(self, source):
        self.source=source
        self.buf = []

    def update_buffer(self):
        c.buffer.insert(c.buffer.get_end_iter(), ''.join(self.buf))
        self.buf = []

    def write(self, data):
        self.buf.append(data)
        if data.endswith('\n'):
            gobject.idle_add(self.update_buffer)

    def __del__(self):
        if self.buf != []:
            gobject.idle_add(self.update_buffer)

sys.stdout = ConsoleOutput(None)
c.main()

rawDescription: pygtk console output for debugging

description: Pygtk console output for debugging


code:
from struct import *
from socket import *

for ip in xrange(unpack('!I',inet_pton(AF_INET,"1.47.0.0"))[0],unpack('!I',inet_pton(AF_INET,"1.51.255.255"))[0]):
    print inet_ntop(AF_INET,pack('!I',ip));

f = unpack('!I',inet_pton(AF_INET,"1.47.0.0"))[0]
l = unpack('!I',inet_pton(AF_INET,"1.51.255.255"))[0]
while f < l:
    print inet_ntop(AF_INET,pack('!I',f));
    f = f + 1

rawDescription: How to get list of IP addresses?

description: Get list of IP addresses


code:
import pytz
from datetime import date, timedelta as td, datetime
eastern = pytz.timezone('US/Eastern')

d1 = eastern.localize(datetime(2016, 3, 11, 21, 0, 0))
d2 = eastern.localize(datetime(2016, 3, 12, 5, 0, 0))

d3 = eastern.localize(datetime(2016, 11, 4, 21, 0, 0))
d4 = eastern.localize(datetime(2016, 11, 5, 5, 0, 0))

while(d1<d2):
    print d1
    d1 = eastern.normalize(d1 + td(hours=1))

while(d3<d4):
    print d3
    d3 = eastern.normalize(d3 + td(hours=1))

rawDescription: Python: Printing all hours between two datetime accounting for daylight saving


code:
import subprocess
subp = subprocess.Popen(["cmd"])
subp.wait()
print 'process %d finished' % subp.pid

rawDescription: Python os.waitpid throw `[Errno 10] No child processes`


code:
import numpy as np
x = np.random.random(1000)
y = np.random.random(1000)
z = np.random.random(1000)
nbins = 10
H, [bx, by, bz]=np.histogramdd((x,y,z),bins=(nbins,nbins,nbins),range=((0,1),(0,1),(0,1)))

ix, iy, iz = np.where(H)

for t in zip(bx[ix], by[iy], bz[iz], H[ix,iy,iz]):
    print t

rawDescription: Multidimension histogram in python

description: Multidimension histogram in python


rawDescription: Parsing specific columns from a dataset in python


code:
df = pd.DataFrame(np.random.random((5, 5)))
df
print df.to_latex()

rawDescription: Export a LaTeX table from pandas DataFrame


code:
class Test:
    def __repr__(self):
        return "Test()"
    def __str__(self):
        return "member of Test"

t = Test()
t
print t

rawDescription: How to print a class or objects of class using print()?

description: Print a class or objects of class using print()


code:
from bs4 import BeautifulSoup
import urllib2

url = "http://www.imdb.com/chart/?ref_=nv_ch_cht_2"

data = urllib2.urlopen(url).read()
page = BeautifulSoup(data, 'html.parser')

rows = page.findAll("tr", {'class': ['odd', 'even']})

for tr in rows:
    for data in tr.findAll("td", {'class': ['titleColumn', 'weeksColumn','ratingColumn']}):
        print data.get_text()

rawDescription: html scrapping using python topboxoffice list from imdb website

description: Html scrapping using python topboxoffice list from imdb website


code:
import string
import random

all_chars = list(string.digits + string.ascii_letters + string.punctuation)
random.shuffle(all_chars)
print ''.join(all_chars[:94])

rawDescription: Creating a random string in Python without duplicating characters


code:
poison = None # something you wouldn't normally put in the Queue

class test(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.request_queue = Queue.Queue()

    def kill(self):
        self.addtoqueue(poison)

    def addtoqueue(self, item):
        self.request_queue.put(item)

    def run(self):
        while True:
            item = self.request_queue.get(True)
            if item is poison:
                # do stuff
                return # end thread
            print item

rawDescription: What is the best way to end this thread when a function is called?


code:
f1 = csv.DictReader(open('testconfig'))
last_group = ''
for row in f1:
    if row['group'] != last_group:
        print row['group'] + ':'
        last_group = row['group']
    print "   " + row['monitor']

rawDescription: indent output into groupings by header

description: Indent output into groupings by header


code:
a = [0] * 3
print a
b = [a] * 2
print b
a[0] = 1
print a
print b
b[0][1] = 2
print b

rawDescription: difference between list and array(np)?

description: Difference between list and array(np)


code:
import datetime
target_date = datetime.date(2011,2,7)

delta = datetime.timedelta(days=2)
new_date = target_date - delta

print new_date # 2011-02-05

rawDescription: how to add/subtract 2 days in the target day in python?

description: Add/subtract 2 days in the target day in python


code:
userAgent = "YOUR_UA"
pattern = '(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)'
if(re.search(pattern, userAgent)):
    print "true"

rawDescription: How do I detect a ipad/iphone webview in user agent using regex in Python?

description: Detect a ipad/iphone webview in user agent using regex in Python


code:
namespaces = {"aws": "http://awis.amazonaws.com/doc/2005-07-11"}
texts = doc.xpath("//aws:TrafficData/aws:DataUrl/text()", namespaces=namespaces)
print texts[0]

rawDescription: Parsing Alexa XML with python

description: Parsing Alexa XML with python


code:
productDivs = soup.findAll('div', attrs={'class' : 'dg_u'})
for div in productDivs:
    a_dict = json.loads( div.a['vrhm'] )
    print a_dict['p']

rawDescription: Getting youtube link element from source code


code:
from collections import defaultdict

list1 = [' c', ' a', ' d', 'ee', ' i', 'om', 'a ', 'al', ' s', 'ay', 'ar', 'me', 'ha', 'he', 'e to', 's ', 'l ', 'e th', 'll', "r'", 'su', 'o ', 're', 'sh', 'mp', 'er', 'mm', '?']

list2 = ['a', 'h', 'm', 'l', 'o', 's', 'r', 'e t']

my_dict = defaultdict(int)
for item1 in list1:
    for start in range(len(item1)):
        for end in range(start + 1, len(item1)):
            sslice = item1[start:end]
            my_dict[sslice] += sum(sslice in item2 for item2 in list1)
            my_dict[sslice] += sum(sslice in item3 for item3 in list2)

print my_dict

rawDescription: New to Python: fixing infinite loop in iterated, 2-list search, output to a dictionary


code:
for row in csv.DictReader(items_file, dialect='excel', delimiter='\t'):
    for key in row:
        print 'key=%s, value=%s' % (key, row[key])

rawDescription: CSV to Python Dictionary with all column names?


code:
import imp
def main_is_frozen():
    return (hasattr(sys, "frozen") or # new py2exe
            hasattr(sys, "importers") # old py2exe
            or imp.is_frozen("__main__")) # tools/freeze

from rbtools.clients.svn import SVNClient
from rbtools.clients.git import GitClient
from rbtools.clients.mercurial import MercurialClient
from rbtools.clients.cvs import CVSClient
from rbtools.clients.perforce import PerforceClient
from rbtools.clients.plastic import PlasticClient
from rbtools.clients.clearcase import ClearCaseClient
from rbtools.clients.bazaar import BazaarClient
def load_scmclients(options):
    global SCMCLIENTS

    SCMCLIENTS = {}

    if not main_is_frozen():
        for ep in pkg_resources.iter_entry_points(group='rbtools_scm_clients'):
            try:
                SCMCLIENTS[ep.name] = ep.load()(options=options)
            except Exception, e:
                logging.error('Could not load SCM Client "%s": %s' % (ep.name, e))
    else:
        temp_clients = {}
        temp_clients['svn'] = SVNClient
        temp_clients['git'] = GitClient
        temp_clients['mercurial'] = MercurialClient
        temp_clients['cvs'] = CVSClient
        temp_clients['perforce'] = PerforceClient
        temp_clients['plastic'] = PlasticClient
        temp_clients['clearcase'] = ClearCaseClient
        temp_clients['bazaar'] = BazaarClient
        for ep in temp_clients:
            try:
                SCMCLIENTS[ep] = temp_clients[ep](options=options)
            except Exception, e:
                logging.error('Could not load SCM Client "%s": %s' % (str(ep), e))

description: Py2Exe and pkg_resources.iter_entry_points()


code:
def on_click_pic(self, button, event):
    self.url_win = Gtk.Window()
    self.url_win.set_default_size(500,20)
    self.url_win.set_border_width(10)
    self.url_win.set_title("Enter a URL for the player photo")
    url_entry = Gtk.Entry()  # define your GtkEntry here
    url_entry.connect('activate', self.on_url_enter)
    self.url_win.add(url_entry)
    self.url_win.show_all()

def on_url_enter(self, url_entry):
    search = url_entry.get_text()
    self.url_win.destroy()
    print "getting image: %s " % search
    self.get_image(search, self.e_image)
    self.e_pic = search
    print "e_pic set to %s" % search

rawDescription: Python: Entry Window sometimes will not die


code:
import numpy as np
import pylab as plt

# Sample data
row = np.linspace(-2,2,20)
X,Y = np.meshgrid(row,row)
Z    = np.exp(-((X-1.5)**2+(Y+1)**2))
Z   += np.exp(-((X)**2+(Y)**2))

plt.subplot(121)
plt.imshow(Z,interpolation='none',origin='lower')
plt.subplot(122)
plt.contour(X,Y,Z)
plt.show()
print X,Y

rawDescription: Contour from 2D image

description: Contour from 2D image


code:
import sys
import sqlalchemy as sa
import sqlalchemy.sql
import sqlalchemy.orm
import sqlalchemy.ext.declarative

Base = sa.ext.declarative.declarative_base()

class Entry(Base):
    __tablename__ = "entries"

    id = sa.Column(sa.Integer, primary_key=True)
    value = sa.Column(sa.Numeric)
    account_id = sa.Column(sa.Integer, sa.ForeignKey("accounts.id"))
    account = sa.orm.relationship("Account", backref="entries")

class Account(Base):
    __tablename__ = "accounts"

    id = sa.Column(sa.Integer, primary_key=True)

    @property
    def balance(self):
        return sqlalchemy.orm.object_session(self).query(
                    sa.sql.func.sum(Entry.value)
                ).filter(Entry.account_id == self.id).scalar()

def example(database_url):
    # connect to the database and prepare the schema
    engine = sa.create_engine(database_url, echo=True)
    session = sa.orm.sessionmaker(bind=engine)()

    Base.metadata.create_all(bind = engine)

    # add an entry to an account
    account = Account()

    account.entries.append(Entry(value = 42))

    session.add(account)

    # and look for that entry in the balance
    print "account.balance:", account.balance

    assert account.balance == 42

if __name__ == "__main__":
    example("sqlite://")

rawDescription: can an an ORM column trigger a session flush in SQLAlchemy?

description: Can an an ORM column trigger a session flush in SQLAlchemy


code:
table = soup.find('table', id='DailySettlementTable')

# The slice notation below, [2:7], says to take the third (index 2)
# to the eighth (index 7) values from the rows we get.
for rows in table.find_all('tr')[2:7]:
    cells = rows.find_all('td')
    month = cells[0]
    settle = cells[6]

    print month.string + ':' + settle.string

rawDescription: extracting values from html table using beautifulsoup4 (2nd row onwards, 1st and 6th column)

description: Extracting values from html table using beautifulsoup4 (2nd row onwards, 1st and 6th column)


code:
date = "2013-03-15 05:14:51.327"
newdate = date.rpartition(':')[0]
print newdate

rawDescription: How do you remove seconds and milliseconds from a date time string in python

description: Remove seconds and milliseconds from a date time string in python


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

Base = declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    bs = relationship("B")

class B(Base):
    __tablename__ = "b"

    id = Column(Integer, primary_key=True)

    a_id = Column(Integer, ForeignKey('a.id'))

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([A(bs=[B(), B()]), A(bs=[B()])])
s.commit()

# with_labels() here is to disambiguate A.id and B.id.
# without it, you'd see a warning
# "Column 'id' on table being replaced by another column with the same key."
subq = s.query(A, B).join(A.bs).with_labels().subquery()

# method 1 - select_from()
print s.query(A, B).select_from(subq).all()

# method 2 - alias them both.  "subq" renders
# once because FROM objects render based on object
# identity.
a_alias = aliased(A, subq)
b_alias = aliased(B, subq)
print s.query(a_alias, b_alias).all()

rawDescription: SQLAlchemy ORM select multiple entities from subquery


code:
import regex

# traditional matching - three digits
r = '(?:\d\d\d)'
print regex.findall(r, '1xx22yy333zz')
## ['333']

# fuzzy matching - three digits, allow at most 2 deletions
r = '(?:\d\d\d){d<3}'
print regex.findall(r, '1xx22yy333zz')
## ['1', '22', '333']

rawDescription: Partial Regex matching in Python 3.2

description: Partial Regex matching in Python 3.2


rawDescription: Operation between pandas datetime-indexed DataFrames with non-equal elements


code:
import re
pattern = re.compile(r"/(?P<artist>[a-zA-Z0-9 ]+?)/(?P<release>[a-zA-Z0-9 ]+?)/(?P<tracknumber>\d+?) - (?P<title>[a-zA-Z0-9 ]+?).flac")
s = "/The Prodigy/The Fat Of The Land/04 - Funky Stuff.flac"
m = pattern.search(s)
print m.group('artist')
print m.group('release')
print m.group('track number')
print m.group('title')

rawDescription: Python regex - extracting directories from path


code:
def get_key_name(str):
    first_pos = str.find('[')
    return str[:first_pos]

def get_subkey_name(str):
    '''Used with lists of dictionaries only'''
    first_pos = str.rfind('[')
    last_pos = str.rfind(']')
    return str[first_pos:last_pos+1]

def get_key_index(str):
    first_pos = str.find('[')
    last_pos = str.find(']')
    return str[first_pos:last_pos+1]

def decode(idic):
    odic = {} # Initialise an empty dictionary
    # Scan all the top level keys
    for key in idic:
        # Nested entries have [] in their key
        if '[' in key and ']' in key:
            if key.rfind('[') == key.find('[') and key.rfind(']') == key.find(']'):
                print key, 'is a nested list'
                key_name = get_key_name(key)
                key_index = int(get_key_index(key).replace('[','',1).replace(']','',1))
                # Append can't be used because we may not get the list in the correct order.
                try:
                    odic[key_name][key_index] = idic[key][0]
                except KeyError: # List doesn't yet exist
                     odic[key_name] = [None] * (key_index + 1)
                     odic[key_name][key_index] = idic[key][0]
                except IndexError: # List is too short
                     odic[key_name] = odic[key_name] + ([None] * (key_index - len(odic[key_name]) + 1 ))
                     # TO DO: This could be a function
                     odic[key_name][key_index] = idic[key][0]
            else:
                key_name = get_key_name(key)
                key_index = int(get_key_index(key).replace('[','',1).replace(']','',1))
                subkey_name = get_subkey_name(key).replace('[','',1).replace(']','',1)
                try:
                    odic[key_name][key_index][subkey_name] = idic[key][0]
                except KeyError: # Dictionary doesn't yet exist
                    print "KeyError"
                    # The dictionaries must not be bound to the same object
                    odic[key_name] = [{} for _ in range(key_index+1)]
                    odic[key_name][key_index][subkey_name] = idic[key][0]
                except IndexError: # List is too short
                    # The dictionaries must not be bound to the same object
                    odic[key_name] = odic[key_name] + [{} for _ in range(key_index - len(odic[key_name]) + 1)]
                    odic[key_name][key_index][subkey_name] = idic[key][0]
        else:
            # This can be added to the output dictionary directly
            print key, 'is a simple key value pair'
            odic[key] = idic[key][0]
    return odic

rawDescription: Turn a simple dictionary into dictionary with nested lists


code:
file = service.files().get(fileId=file_id, fields='downloadUrl').execute()
print file['downloadUrl']

rawDescription: How to get downloadurl of an image in google drive using python?

description: Get downloadurl of an image in google drive using python


code:
from entities import *

class Account(Entity):
    id = IntegerField(group=PRIMARY)  # this field is in primary key group
    iban = IntegerField(group=SECONDARY)  # this is in secondary key group
    balance = FloatField(default=0.0)

class Name(Entity):
    first_name = StringField(group=SECONDARY)
    last_name = StringField(group=SECONDARY)

class Customer(Entity):
    id = IntegerField(group=PRIMARY)
    name = EntityField(Name, group=SECONDARY)
    accounts = ListField(ReferenceField(Account), default=list)

# Create Account objects.
a_1 = Account(1, 111, 10.0)  # __init__() recognizes positional arguments
a_2 = Account(id=2, iban=222, balance=20.0)  # as well as keyword arguments

# Generate hashable key using primary key.
print a_1.keyify()  # prints '(1,)'

# Generate hashable key using secondary key.
print a_2.keyify(SECONDARY)  # prints '(222,)'

# Create Customer object.
c = Customer(1, Name('eser', 'aygun'))

# Generate hashable key using primary key.
print c.keyify()  # prints '(1,)'

# Generate hashable key using secondary key.
print c.keyify(SECONDARY)  # prints '(('eser', 'aygun'),)'

# Try validating an invalid object.
c.accounts.append(123)
try:
    c.validate()  # fails
except ValidationError:
    print 'accounts list is only for Account objects'

# Try validating a valid object.
c.accounts = [a_1, a_2]
c.validate()  # succeeds

rawDescription: Object schemas/models without ORM, DOM or forms


code:
for m in '123456789':
    if m not in excluded_num:
        if self.done:
            return
        print 'xxx loop %d' % self.loop
        self.solve(a[:i]+m+a[i+1:])

rawDescription: The return statement in Python

description: The return statement in Python


code:
from PyQt4.QtCore import QVariant

a = QVariant(['one', 'two', 'three'])

aList = [unicode(i.toString()) for i in a.toList()]
print aList

rawDescription: How to get Python List from QVariant

description: Get Python List from QVariant


code:
skips = [0, 1, 2, 4, 5, 6, 7, 9, 10, 14, 15, 16]
skippedValues = set(range(min(skips), max(skips)+1)) - set(skips)
print skippedValues
print list(skippedValues)

rawDescription: Get deleted item into a consecutive Python list


code:
import multiprocessing, copy
from foo import really_expensive_to_compute_object

## Create a really complicated object that is *hard* to initialise.
T = really_expensive_to_compute_object(10)

def f(t, x):
  return t.cheap_calculation(x)

P = multiprocessing.Pool(processes=64)
results = P.map(f, (copy.deepcopy(T) for _ in range(1000000)), range(1000000))

print results

rawDescription: Create a copy of an object rather that reinitialising inside of a new multiprocessing process


code:
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4

p = "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"

# extract rule
import re
matcher = re.compile('plural=(.*);')
match = matcher.search(p)
rule = match.expand("\\1")

# convert rule to python syntax
oldrule = None
while oldrule != rule:
    oldrule = rule
    rule = re.sub('(.*)\?(.*):(.*)', r'(\1) and (\2) or (\3)', oldrule)

rule = re.sub('&&', 'and', rule)
rule = re.sub('\|\|', 'or', rule)

for n in range(40):
    code = "n = %d" % n
    print n, eval(rule)

rawDescription: How to generate examples of a gettext plural forms expression? In Python?

description: Generate examples of a gettext plural forms expression? In Python


code:
import Queue
q = Queue.Queue()
q.put(1)
q.put(2)
with q.mutex:
    for item in q.queue:
            print item

q.get()
q.get()

rawDescription: python: search and browse messages in the queue

description: Python: search and browse messages in the queue


code:
from twython import Twython, TwythonError

# Requires Authentication as of Twitter API v1.1
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
    search_results = twitter.search(q='#python', count=50)
except TwythonError as e:
    print e

for tweet in search_results['statuses']:
    print tweet['user']['screen_name'].encode('utf-8')

rawDescription: Following users who tweets a specific hashtag with tweepy for python?


code:
import csv

# I fake here the opening and extracting from a CSV file
# to obtain a list of the words of the first column
ss = """HelloWorld
HelloWorld
HelloSaturn
HelloMars
HelloPluto
HelloSaturn
HelloMoon
HelloMoon"""
column = ss.splitlines()

# Now, the counting
from collections import Counter
c = Counter(column)

# Seeing the counter we got
print '\n'.join(c)

# Putting the result in a CSV file
with open('resu.csv','wb') as g:
    gw = csv.writer(g)
    gw.writerows([item,c[item]] for item in column)

rawDescription: Python matching lists and returning found value


code:
import random

list_of_groups = [['a', 'b'], ['c', 'd', 'e'], ['f']]
l = [group[:] for group in list_of_groups] # make a copy
random.shuffle(l)
out = []
prev_i = -1
while any(a for a in l):
    new_i = max(((i,a) for i,a in enumerate(l) if i != prev_i), key=lambda x: len(x[1]))[0]
    out.append(l[new_i].pop(random.randint(0, len(l[new_i]) - 1)))
    prev_i = new_i

print out

rawDescription: Specific shuffling list in Python

description: Specific shuffling list in Python


code:
a = "This is a\nmultiline string"
a
print a

rawDescription: How do you define __str__ in python when including newline characters?

description: Define __str__ in python when including newline characters


code:
import urllib
import BeautifulSoup
page = urllib.urlopen('http://stackoverflow.com/users/95810')
soup = BeautifulSoup.BeautifulSoup(page)
therep = str(soup.find(text='Reputation').parent.previous.previous).strip()
print int(therep.replace(',',''))

rawDescription: To build a similar reputation tracker as Jon's by Python


code:
import re
print re.compile('${[a-z]*}').match("${abcd}")
print re.compile('\${[a-z]*}').match("${abcd}")

rawDescription: Regex matching Python

description: Regex matching Python


code:
from bs4 import BeautifulSoup

xml2 = """
<helloWorld>
    :-)
</helloWorld>
"""
soup = BeautifulSoup(xml2, "xml")

for x in soup.find_all("helloWorld"):
    print x

rawDescription: find_all with camelCase tag names with BeautifulSoup 4

description: Find_all with camelCase tag names with BeautifulSoup 4


code:
import Tkinter
root=Tkinter.Tk()

# create a python callback function
def callbackFunc():
    print "I am in callbackFunc"

# register the callback as a Tcl command. What gets returned
# must be used when calling the function from Tcl
cb = root.register(callbackFunc)

# call a tcl command ('eval', for demonstration purposes)
# that calls our python callback:
root.call('eval',cb)

rawDescription: Calling Tcl procedures with Function pointers as argument from Python


code:
def metaclass(future_class_name, future_class_parents, future_class_attrs):
    print "module.__metaclass__"
    future_class_attrs["bar"]="bar"
    return type(future_class_name, future_class_parents, future_class_attrs)

class Foo(object):
    __metaclass__ = metaclass

    def __init__(self):
        print 'Foo.__init__'

f=Foo()

rawDescription: Python metaclass and the object base class


code:
def f(a=1, a_dict=None):
    if a_dict is None:
        a_dict = {}
    try:
        b=a_dict['one']
        print 'fetched from cache'
    except:
        b=10
        a_dict['one']=10
        print 'put in cache'
    return b

rawDescription: python function: scope of function parameter initialized with default value

description: Python function: scope of function parameter initialized with default value


code:
from optparse import OptionParser

parser = OptionParser()
parser.add_option('-s','--some', help = "Print some of the Suspects")
parser.add_option('-a','--all',help = "Print all of the Suspects")

(opts,args) = parser.parse_args()

if opts.some:
    print "some results"
if opts.all:
    print "all results"

rawDescription: How can I use OptionParser to print to the command line?

description: Use OptionParser to print to the command line


code:
import mechanize
from time import sleep
#Make a Browser (think of this as chrome or firefox etc)
br = mechanize.Browser()

#visit http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/
#for more ways to set up your br browser object e.g. so it look like mozilla
#and if you need to fill out forms with passwords.

# Open your site
br.open('http://pypi.python.org/pypi/xlwt')

f=open("source.html","w")
f.write(br.response().read()) #can be helpful for debugging maybe

filetypes=[".zip",".exe",".tar.gz"] #you will need to do some kind of pattern matching on your files
myfiles=[]
for l in br.links(): #you can also iterate through br.forms() to print forms on the page!
    for t in filetypes:
        if t in str(l): #check if this link has the file extension we want (you may choose to use reg expressions or something)
            myfiles.append(l)

def downloadlink(l):
    f=open(l.text,"w") #perhaps you should open in a better way & ensure that file doesn't already exist.
    br.click_link(l)
    f.write(br.response().read())
    print l.text," has been downloaded"
    #br.back()

for l in myfiles:
    sleep(1) #throttle so you dont hammer the site
    downloadlink(l)

rawDescription: Download all the links(related documents) on a webpage using Python


code:
class A(Base):
    __tablename__ = "A"
    id = Column(Integer, primary_key=True)
    word = Column(String)

    def __init__(self):
        self.word = "adefault"

a = A()
print a.word

rawDescription: How do I set attribute default values in sqlalchemy declarative?

description: Set attribute default values in sqlalchemy declarative


code:
# globals
verbose = False # set to True if you want debug info printed
max_iter = 1000 # this stops infinate loops incase the code does not allow for some input

def solve(problem_str):

    def multiply(arg_list):
        x = 1
        for i in arg_list:
            x *= i
        return x

    def find_innermost(x_str):
        a, b, c, i = [0], [0], 0, 0
        while True:
            i += 1
            start = a[-1]+1
            a.append(x_str.find('(', start)) # find next (
            b.append(x_str.find(',', start)) # find next ,
            c = x_str.find(')', start)       # find next )
            if (a[-1] > c) or (a[-1] == -1):
                if (b[-2] > a[-3]) and (b[-2] < a[-2]):
                    return x_str[b[-2]+1:c+1]
                else:
                    return x_str[a[-3]+1:c+1]
            if i >= max_iter:
                raise Exception("Infinite loop")

    def do_sum(x_str):
        args = [int(x) for x in x_str[x_str.find('(')+1:x_str.find(')')].split(',')]
        task = x_str[:3].lower()
        if task == 'add':
            return sum(args)
        elif task == 'sub':
            return args[0] - sum(args[1:])
        elif task == 'abs':
            return abs(args.pop())
        elif task == 'mul':
            return multiply(args)
        else:
            print x_str + ': Task not recognised, please modify program or input'
            raise Exception("Invalid input")

    i = 0
    while True:
        i += 1
        if verbose: print 'debug: problem_str:', problem_str
        if problem_str.count('(') > 1:
            x_str = find_innermost(problem_str)
        else:
            x_str = problem_str
        if verbose: print '.'*6, 'x_str:\t', x_str
        x = do_sum(x_str)
        if verbose: print '.'*6, 'x:\t', x, '\n'
        problem_str = problem_str.replace(x_str, str(x))
        if problem_str.count('(') == 0:
            return int(problem_str)
        if i >= max_iter:
            raise Exception("Infinite loop")

if __name__ == '__main__':
    p1 = 'abs(add(add(9465,38),multiply(add(63303,146),46)))'
    p2 = 'abs(add(multiply(95,multiply(-1,multiply(13,18875))),multiply(-1,add(18293,26))))'
    p3 = 'abs(add(subtract(add(add(151,26875),122),254),subtract(237,multiply(-1,56497))))'
    r1, r2, r3 = solve(p1), solve(p2), solve(p3)
    print 'p1 evaluates to:', r1
    print 'p2 evaluates to:', r2
    print 'p3 evaluates to:', r3

rawDescription: Solving math in python without any built in eval functions or external libraries


code:
def matcher(ex):
    ex = ex.rstrip()
    if re.match(r'^[a-zA-Z0-9][ A-Za-z0-9_-]*$', ex):
        print 'yes'

rawDescription: Regular expression for letters, dash, underscore, numbers, and space


code:
from timeit import Timer

def find_invpow(x,n):
    """Finds the integer component of the n'th root of x,
    an integer such that y ** n <= x < (y + 1) ** n.
    """
    high = 1
    while high ** n < x:
        high *= 2
    low = high/2
    while low < high:
        mid = (low + high) // 2
        if low < mid and mid**n < x:
            low = mid
        elif high > mid and mid**n > x:
            high = mid
        else:
            return mid
    return mid + 1

def find_invpowAlt(x,n):
    """Finds the integer component of the n'th root of x,
    an integer such that y ** n <= x < (y + 1) ** n.
    """
    low = 10 ** (len(str(x)) / n)
    high = low * 10

    while low < high:
        mid = (low + high) // 2
        if low < mid and mid**n < x:
            low = mid
        elif high > mid and mid**n > x:
            high = mid
        else:
            return mid
    return mid + 1

x = 237734537465873465
n = 5
tests = 10000

print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)

rawDescription: How to compute the nth root of a very big integer

description: Compute the nth root of a very big integer


code:
a = input("enter first number\n")
b= input("enter second number\n")
limit=[]
limit.append(a)
limit.append(b)
natNo=range(1,1000)
xyz = []
for i in limit:
    xyz +=filter(lambda x: x == i or x % i==0, natNo)
set = {}
map(set.__setitem__, xyz, [])
nums=set.keys()
print "the multiples of the given numbers are: "+str(nums)
c=reduce(lambda x, y:x+y, nums)
print "the sum of the multiples of the given numbers is "+str(c)

rawDescription: Sum of multiples of two numbers

description: Sum of multiples of two numbers


code:
import re

re.split(ur"[\u200b\s]+", "some string", flags=re.UNICODE)

rawDescription: Python: splitting string by all space characters


code:
nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]
id = 0
for i, names in enumerate(nameList):
    if i % 2 == 0:   # if 'i' is even
        id = id + 1   # or id += 1, both are equivalent
    print names + "," + str(id) # if all elements are strings, 'str()' is not required

rawDescription: Assigning same ID to pairs of names

description: Assigning same ID to pairs of names


code:
import random
def init_maze():
    maze = [[]] * 9
    for counter in range(0, 9):
        maze[counter] = [-1] * 4
    return maze

def print_maze(maze):

    for column in range(0, 9):
        for row in range(0, 4):
            print maze[column][row],
        print ''

def set_cells(maze):
    for column in range(0, 9):
        for row in range(0, 4):
            maze[column][row] = random.randint(1,5)
    return maze

def change_room(room, direction):
    newRoom = 0
    if maze[room][direction] == -1:
        print "you have hit a wall"
    else:
        newRoom = maze[room][direction]
        print "You are now in room {0}".format(newRoom)
    room = newRoom

maze = init_maze()
print_maze(maze)
print 'Randomizing...'
maze = set_cells(maze)
print 'Done'
print_maze(maze)

rawDescription: How do I make this maze?

description: Make this maze


rawDescription: Assign list of IP's to a list of switches in Python


code:
from random import randint
dist = {}
input = []
for x in xrange(1,10):
    input.append(randint(1,5))
keys = []
size = 0
for item in input:
    if item in dist:
        index = keys.index(item)
        del keys[index]
        keys.append(item)
        dist[item] = size-index-1
    else:
        keys.append(item)
        dist[item] = -1
        size += 1
print input
print dist

rawDescription: Number of distinct items between two consecutive uses of an item in realtime


code:
def somefunction():
    val = 3 # calculate value
    globals()['somefunction_return'] = val # store it in globals() first
    return val # return as normal

def do_something():
    print 'got it'

what_i_need = 3

if somefunction() == what_i_need:
    do_something()
    print 'that\'s not what i need', somefunction_return

# result:
#
# got it
# that's not what i need 3

rawDescription: Using function return in if/else statement


code:
from subprocess import Popen

try:
    p = Popen(args)
    p.wait()  # wait for the process to finish
except KeyboardInterrupt,  SystemExit:
    p.kill()
    raise

rawDescription: Will killing Python script that called shell processes also kill the shell processes?


code:
from multiprocessing import Process, Queue

def start_process(queue):
  while True:
    try:
        m = queue.get()
        if m == 'exit':
            print 'cleaning up worker...'
            # add here your cleaning up code
            break
        else:
            print m
    except KeyboardInterrupt:
        print 'ignore CTRL-C from worker'

if __name__ == '__main__':
  queue = Queue()

  process = Process(target=start_process, args=(queue,))
  process.start()

  queue.put(12)

  try:
    process.join()
  except KeyboardInterrupt:
    print 'wait for worker to cleanup...'
    queue.put('exit')
    process.join()

    ## or to kill anyway the worker if is not terminated after 5 seconds ...
    ## process.join(5)
    ## if process.is_alive():
    ##     process.terminate()

rawDescription: Python's multiprocessing.Queue + Process: Properly terminating both programs


code:
from django.core.paginator import Paginator

objects = messages.objects.all()
p = Paginator(objects, 10)
page3 = p.page(3)
print page3.object_list

rawDescription: Django:Querying database

description: Django:Querying database


code:
from itertools import izip_longest
print [tuple(j for j in i if j is not None)for i in izip_longest(a, b, c)]
# [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd'), (5,)]

rawDescription: How to zip lists of uneven length

description: Zip lists of uneven length


code:
for x in range(10):
    print x, '\r',
print "\n"

rawDescription: Updating a line in terminal with python

description: Updating a line in terminal with python


code:
for idx, val in enumerate(catList):
  print dateList[idx]

rawDescription: Python, Lists - Use 'Item' as integer variable


code:
for i in ['a','b','c','d','e','f','g']:
    for j in range(1,15):
        url = BASE_URL + i + str(j)
        print url

rawDescription: Iterative printing over two data types in Python


code:
if not file_path=="":
        if not file_path.find("~$") > 0:
            file_path="\\\\?\UNC"+file_path
            print os.path.exists(file_path)

rawDescription: Can't copy a valid file in python

description: Can't copy a valid file in python


code:
lines = tuple(open('/var/log/fail2ban.log', 'r'))
seen = set()
for item in lines:
  item = item.strip('\n')
  if "fail2ban.actions:" in item and "[postfix]" in item and "Ban" in item:
    item = item.split(' ')
    if item[6] not in seen:
      seen.add(item[6])
      print item

rawDescription: Sorting uniques in multiple lists

description: Sorting uniques in multiple lists


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

fig, axes = plt.subplots(ncols=2)

axes[0].imshow(np.random.random((10,10)), interpolation='none')
axes[1].imshow(np.random.random((10,10)), interpolation='none')

def motion_capture(event):
    if event.inaxes is axes[0]:
        print event.xdata
        print event.ydata

fig.canvas.mpl_connect('motion_notify_event', motion_capture)

plt.show()

rawDescription: 2 graphs mouse motion matplotlib

description: 2 graphs mouse motion matplotlib


code:
client = SSHClient()
lient.load_system_host_keys()
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST,username=USERNAME,password=PASSWORD)
channel = client.invoke_shell()
channel.send('ls\n')
while channel.recv_ready():
    channel.recv(1024)

channel.send('exit\n')
if channel.exit_status_ready():
    print channel.recv_exit_status()

rawDescription: can I capture remotely executed commands with its output in the logfile in python?

description: Capture remotely executed commands with its output in the logfile in python


code:
import collections
import string

def translator(frm='', to='', delete='', keep=None):
    # Python Cookbook Recipe 1.9
    # Chris Perkins, Raymond Hettinger
    if len(to) == 1: to = to * len(frm)
    trans = string.maketrans(frm, to)
    if keep is not None:
        allchars = string.maketrans('', '')
        # delete is expanded to delete everything except
        # what is mentioned in set(keep)-set(delete)
        delete = allchars.translate(allchars, keep.translate(allchars, delete))
    def translate(s):
        return s.translate(trans, delete)
    return translate

alpha = 'abcdefghijklmnopqrstuvwxyz'
keep_alpha=translator(keep=alpha)

while True:
    speech = raw_input("Enter file name:")
    wholeFile = open(speech, 'r+').read()
    lowlet = wholeFile.lower()
    letters = keep_alpha(lowlet)
    n = len(letters)
    occurrences = collections.defaultdict(int)
    for x in letters:
        occurrences[x]+=1
    for x in occurrences:
        print x, occurrences[x], occurrences[x]/float(n)

rawDescription: Letter frequency in python

description: Letter frequency in python


code:
def issue_a():
    input1 = raw_input('1:issue_b  2:arena')
    if input1 == '1':
        return issue_b
    elif input1 == '2':
        return arena(issue_a)

def issue_b():
    input2 = raw_input('1:issue_c  2:arena')
    if input2 == '1':
        return issue_c
    elif input2 == '2':
        return arena(issue_b)

def issue_c():
    print "Game Over!"

def arena(back_to):
    print "doing arena stuff..."
    return back_to

# to let the arena function behave like the other functions, use this instead
#
# def arena(back_to):
#    def inner():
#        print "doing arena stuff..."
#        return back_to
#    return inner

func = issue_a
while func:
    func = func()

rawDescription: Can I build a Python function which can bounce back to any start point at when it was executed?

description: Build a Python function which can bounce back to any start point at when it was executed


code:
#! /usr/bin/env monkeyrunner
import re
import sys
import os
import java
import glob
import os

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device1= MonkeyRunner.waitForConnection(15, "emulator-5554")
mydir="/home/user/apk"
os.chdir(mydir)
for files in glob.glob("*.apk"):
    print files
    print "path " ,os.path.abspath(mydir+"/"+files)
    device1.installPackage(mydir+"/"+files)

rawDescription: Issues using a variable in monkeyrunner's ".installPackage()"


code: print yaml.dump(Dice(3,6))

rawDescription: python %s string substitution and "self"?

description: Python %s string substitution and "self"


code:
for student,grade in student_grades.iteritems():
    print "Name:%s, Grade:%s"%(student,grade)

rawDescription: Python Simple Grade Book Printing Error

description: Python Simple Grade Book Printing Error


code:
import xlrd

current_row = 0
sheet_num = 1
input_total = 0
output_total = 0

# path to the file you want to extract data from
src = r'c:\temp\excel sheet.xls'

book = xlrd.open_workbook(src)

# select the sheet that the data resids in
work_sheet = book.sheet_by_index(sheet_num)

# get the total number of rows
num_rows = work_sheet.nrows - 1

while current_row < num_rows:
    row_header = work_sheet.cell_value(current_row, 4)

    if row_header == 'output':
        output_total += work_sheet.cell_value(current_row, 5)
    elif row_header == 'input':
        input_total += work_sheet.cell_value(current_row, 5)

print output_total
print input_total

rawDescription: How to read an excel file in Python?

description: Read an excel file in Python


code:
# car.py
import cv,sys
print "usage: python car.py <videofile>"

box=[0,0,0,0]
i = 0
global image
#   creating mouse callback function
def my_mouse_callback(event,x,y,flags,param):
    global drawing_box,i
    if event==cv.CV_EVENT_LBUTTONDOWN:
        events = event
        #print event
        drawing_box=True
        [box[0],box[1],box[2],box[3]]=[x,y,0,0]
        print x,y
    if event==cv.CV_EVENT_LBUTTONUP:
        events = event
        drawing_box=False
        events= event
        if box[2]<0:
            box[0]+=box[2]
            box[2]*=-1
        if box[3]<0:
            box[1]+=box[3]
            box[3]*=-1
        rect = (box[0],box[1],box[2],box[3])
        #print rect
        roi = cv.GetSubRect(image,rect)
        filename = str(i)+'.jpg'
        #save(image,rect,filename)
        cv.SaveImage(filename,roi)
        i = i+1

    if event==cv.CV_EVENT_MOUSEMOVE:
        if (drawing_box==True):
            box[2]=x-box[0]
            box[3]=y-box[1]

#   function to draw the rectangle, added flag -1 to fill rectangle. If you don't want to fill, just delete it.
def draw_box(img,box):
    cv.Rectangle(img,(box[0],box[1]),(box[0]+box[2],box[1]+box[3]),(255,0,0),2)

#   main program
capture = cv.CaptureFromFile(sys.argv[1])
image2 = cv.QueryFrame(capture)
drawing_box=False

#   make a clone of image
temp=cv.CloneImage(image2)

cv.NamedWindow("Box Example")
cv.SetMouseCallback("Box Example",my_mouse_callback,temp)

while(1):
#   global image
    image = cv.QueryFrame(capture)
    while(1):
        roi = 0
        save = False
        events = 0
        boxsaver = 0
        cv.Copy(image,temp)

        if drawing_box==True:
            draw_box(temp,box)

            i = i+1

        cv.ShowImage("Box Example",temp)
        if cv.WaitKey(20)==27:
            sys.exit()
        elif cv.WaitKey(20)==32:
            break

rawDescription: How to take pictures from a video with mouse

description: Take pictures from a video with mouse


rawDescription: python how to print space per n'th char

description: Python how to print space per n'th char


code:
lastiterline = None
with open(filename) as f:
    for line in f:
        line = line.strip()
        if line.startswith("iter"):
           lastiterline = line
        elif line.startswith("FLAG"):
           if lastiterline:
               print line
               print lastiterline
           lastiterline = None

rawDescription: Relocate file backwards multiple lines (python)


code:
import Queue
import threading
import time

queue = Queue.Queue()

class High_priority_first(threading.Thread):
    """ a threading class"""

    def __init__ (self, start, stop, queue):

        self.start = start
        self.stop = stop
        self.queue = queue
        threading.Thread.__init__(self)

# Write a function, run(), that counts the higher priority data and extend it to
# also count lower priority, or create another function for low priority data and
# run them with a separate thread than thread 1.

    def run(self):
        while True:
            if self.start != stop:
                self.start += 1
                self.queue.put(self.start)

            else:
                break

thread1_high_priority = High_priority_Thread(1, 10, queue)# start at 1 and stop at 10
thread1_high_priority.start() #start thread1

thread2_lower_priority = High_priority_Thread(1, 3, queue)# start at 1 and stop at 3
thread2_lower_priority.start() #start thread2

while True:
    if queue != None: # check that queue isn't empty
        out =  queue.get()
        print out

    else:
        break

rawDescription: Dynamic array inside a for statement

description: Dynamic array inside a for statement


code:
vs = [{'ID': 1}, {'ID': 4}]
for i, v in enumerate(filter(lambda x: x['ID'] & 1, vs)):
    print i, v

rawDescription: How i can set the increasing of enumerate, that depends on condition?


code:
import dns.resolver

answers = dns.resolver.query('WSCLUSTER', 'A')
for rdata in answers:
    print rdata

rawDescription: Get individual hostnames from round-robin DNS record


code:
#!/usr/bin/python2.6
import re
import urllib
import urllib2

def validate(URL):
    validatorURL = "http://validator.w3.org/check?uri=" + \
        urllib.quote_plus(URL)
    opener = urllib2.urlopen(validatorURL)
    output = opener.read()
    opener.close()
    if re.search("This document was successfully checked as".replace(
            " ", r"\s+"), output):
        print "    VALID: ", URL
    else:
        print "INVALID: ", URL

rawDescription: python check html valid

description: Python check html valid


code:
import urllib3
http = urllib3.PoolManager()

# httpbin does a redirect right after setting a cookie, so we disable redirects
# for this request
r = http.request('GET', 'http://httpbin.org/cookies/set?foo=bar', redirect=False)

# Grab the set-cookie header and build our headers for our next request.
# Note: This is a simplified version of what a browser would do.
headers = {'cookie': r.getheader('set-cookie')}
print headers
# -> {'cookie': 'foo=bar; Path=/'}

r = http.request('GET', 'http://httpbin.org/cookies', headers=headers)
print r.body
# -> {
#      "cookies": {
#        "foo": "bar"
#      }
#    }

rawDescription: python urllib3 login + search

description: Python urllib3 login + search


code:
import sympy

# Define constants
R1=R3=R5 = 1e3
R2=R4=R6 = 2e3
C1 = 1e-6
C2 = 0.5e-6
x_plus = 3
x_minus = 0
w = 1000

# Define relations
V_plus = sympy.symbols('V_plus')
t = sympy.symbols('t')

V_plus = x_plus*sympy.exp(1j*w*t)
V_minus = 0

V1,V2,V3 = sympy.symbols('V1 V2 V3')

# Using a matrix to collect all equations allows you to use a matrix-vector-product below
eqns = sympy.matrices.Matrix([
    (V1-V_plus)/R1 + (V1-V2)/(1/(1j*w*C1)) + (V1-V_minus)/R4,
    (V2-V_plus)/R2 + (V2-V1)/(1/(1j*w*C1)) + (V2-V_minus)/R5 + (V2-V3)/(1/(1j*w*C2)),
    (V3-V_plus)/R3 + (V3-V2)/(1/(1j*w*C2)) + (V3-V_minus)/R6
])

# Prepare
V = [V1,V2,V3]
V_vec = sympy.matrices.Matrix(V)

# The "or 0" does nothing if there are coefficients y in x, but if there aren't, it replaced
# the "None" with "0". This again is required for using A * V_vec below
A = sympy.matrices.Matrix([ [ x.expand().coeff(y) or 0 for y in V ] for x in eqns ])

print(A)

remainder = (eqns - A * V_vec)
remainder.simplify()
print remainder

rawDescription: Solving RC circuit with python/sympy

description: Solving RC circuit with python/sympy


code:
while True:
    input = get_user_input()
    if input == 'exit':
        break
    next_actions = modify_game_state(input)
    print "You can now do: %s" % next_actions

rawDescription: Python Multithreading to allow user to exit at anytime


code:
import pyaudio
import numpy
import struct

CHUNK = 128

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=CHUNK)

data = stream.read(CHUNK)
print numpy.fromstring(data, numpy.int16) # use external numpy module
print struct.unpack('h'*CHUNK, data) # use built-in struct module

stream.stop_stream()
stream.close()
p.terminate()

rawDescription: Converting microphone data to frequency spectrum


code:
json_string = """
{
    "pk": 1,
    "fa": "cc.ee",
    "fb": {
        "fc": "",
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

rawDescription: parsing json python

description: Parsing json python


code:
import csv,os,sys

def helper(file):
    o = csv.reader(open(file,"r"))
    for row in o:
        print row

def delete(filename):
    f1 = csv.reader(open(filename,'r'))
    f2 = csv.writer(open("temp.csv",'a'))
    rid = raw_input("Enter name to find record:")
    found = False
    for row in f1:
        if rid not in row[0]:
            f2.writerow(row)
        else:
            found = True
            print rid, "has been deleted from the database!"

    if found == False:
        print "That name isn't in our database!"
        z = raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
        if z == "1":
            delete(filename)
        if z == "2":
            import program
        if z == "3":
            exit

rawDescription: How do i get python to remove the row i search for from csv file

description: Get python to remove the row i search for from csv file


rawDescription: Joining items in two lists to a string expression


code:
import sys
sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os

class AllowAllKeys(pm.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

HOST = '127.0.0.1'
USER = ''
PASSWORD = ''

client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, password=PASSWORD)

channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')

stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()

stdout.close()
stdin.close()
client.close()

rawDescription: Communicating multiple times w/ subprocess (multiple calls to stdout)


code:
import hashlib
h = hashlib.sha256('something to hash')
h.hexdigest()
n = int(h.hexdigest(),base=16)
print n

rawDescription: Python 256bit Hash function with number output


code:
from Tkinter import *
import numpy as np

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.can = Canvas(master, width=800, height=800)
        self.can.configure(cursor="crosshair")
        self.can.pack()
        self.start_point = [400, 400]
        self.end_point = [250, 400]
        self.line = self.can.create_line(self.start_point, self.end_point)
        self.can.bind("<Button-1>", self.line_end)
        self.can.bind("<Button-3>", self.del_line)

    def line_end(self, event):
        r = 150
        x0 = float(self.start_point[0])
        y0 = float(self.start_point[1])
        x1 = float(event.x)
        y1 = float(event.y)
        p = int(x1)
        q = int(y1)
        if x1 > x0 and y1 < y0:
            theta = np.arctan((y1-y0)/(x1-x0))
            p = int(x0 + r*np.cos(theta))
            q = int(y0 + r*np.sin(theta))
            print 'A', p, q, theta
        if x1 < x0 and y1 < y0:
            theta = np.arctan((y1-y0)/(x0-x1))
            p = int(x0 - r*np.cos(theta))
            q = int(y0 + r*np.sin(theta))
            print 'S', p, q, theta
        self.can.delete(self.line)
        self.line = self.can.create_line(x0, y0, p, q)
        print x0, y0, ' ........ ',x1, y1

    def del_line(self, event):
        self.can.delete(self.line)

root = Tk()
app = App(root)
root.mainloop()

rawDescription: If condition Python being ignored?

description: If condition Python being ignored


code:
import subprocess

retcode = subprocess.call(['convert', 'file.jpg', '-crop',
                           '80x10+90+980', '+repage', 'crop.jpg'])
if retcode != 0:
    print 'error on convert'
else:
    retcode = subprocess.call(['compare', '-metric', 'PSNR',
                               'reference.jpg', 'crop.jpg', 'crop.jpg'])
    print retcode

rawDescription: Running external subprocesses and reading return code


code:
import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname)
            zf.write(absname, arcname)
    zf.close()

# Changed from input() to raw_input()
SrcPath = raw_input("Enter source directory: ")
print SrcPath # checking source path

# done the same and also added the option of specifying the name of Zipped file.
DestZipFileName = raw_input("Enter destination Zip File Name: ") + ".zip" # i.e. test.zip
DestPathName = raw_input("Enter destination directory: ")
# Here added "\\" to make sure the zipped file will be placed in the specified directory.
# i.e. C:\\Users\\md_sarfaraz\\Desktop\\
# i.e. double \\ to escape the backlash character.
DestPath = DestPathName + "\\" + DestZipFileName
print DestPath # Checking Destination Zip File name & Path
zip(SrcPath, DestPath)

rawDescription: Zipping Directory or file(s) in python

description: Zipping Directory or file(s) in python


code:
import random

z = int(input("How many times? "))

for x in range(0, z):
   print "%d\n" % random.randint(1,10)

rawDescription: Carrying out a random-number generator x number of times based on user input


code:
class FooWrapper(object):
    def __init__(self, value):
         self.value = value

# save an object into a list
l = []
obj = FooWrapper(5)
l.append(obj)

# add another object, so the initial object is shifted
l.insert(0, FooWrapper(1))

# change the value of the initial object
obj.value = 3
print l[1].value # prints 3 since it's still the same reference

rawDescription: Python: Get a pointer to a list element

description: Python: Get a pointer to a list element


code:
import multiprocessing as mu

def worker(n):
        print "worker:", n
        n = int(1e4/2)
        for i in range(n):
                for j in range(n):
                        i*j
        return

if __name__ == '__main__':
        jobs = []
        for i in range(5):
                p = mu.Process(target=worker, args=(i,))
                jobs.append(p)

        running = []
        np = mu.cpu_count()

        for i in range(np):
                p = jobs.pop()
                running.append(p)
                p.start()

        while jobs != []:
                for r in running:
                        if r.exitcode == 0:
                                running.remove(r)
                                p = jobs.pop()
                                p.start()
                                running.append(p)

rawDescription: python : multiprocessing managament

description: Python : multiprocessing managament


rawDescription: How can I delete a list in the run time python?

description: Delete a list in the run time python


code:
counterFile = open("counter.txt","r") #counter.txt stores the number of times code has been run. Just create this file manually
counter = counterFile.read()
if(len(counter) == 0):
    counter = 0
else:
    counter = int(counter)
counterFile.close()

exp = 0
with open ('test.txt','r') as b:
    lines = b.readlines()
with open('test.txt','w') as b:
    for i,line in enumerate(lines):
        print i
        if i == exp+counter:
            b.write('test_data\n')
        b.write(line)

counter += 1
counterFile = open("counter.txt","w")
counterFile.write(str(counter))
counterFile.close()

rawDescription: Insert text at specific line python

description: Insert text at specific line python


code:
def count_to(n):
    while True:
        for i in range(n):
            yield i

to100 = count_to(101)
for row in db_parts.execute('''SELECT * from parts''').fetchall():
    i = to100.next()
    db_parts.execute('''UPDATE parts set bin=? where entry=?''',
        (i, str(row[0]))
    )
    print i
conn.commit()

rawDescription: Performance of populating new column in sqlite with python


code:
import os
for env_check in open('env_check.conf'):
    env_check = env_check.strip()
    print '[{}]'.format(env_check)
    newenv = os.getenv(env_check)
    if newenv is None:
        print env_check, 'is not set'
    else:
        print 'Current Setting for {}={}'.format(env_check, newenv)

rawDescription: Read text in a file to check environment variables


code:
import pandas as pd

mylist = ['a.csv','b.csv','c.csv']

dfs = {}
for f in mylist:
    dfs.update({f.rsplit('.csv',1)[0]: pd.read_csv(f)})

print dfs['a']

rawDescription: Pandas read_csv multiple files

description: Pandas read_csv multiple files


code:
class Model(QtCore.QAbstractListModel):
    def __init__(self):
        QtCore.QAbstractListModel.__init__(self)
        self.items=[]
        self.modelDict={}

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

    def data(self, index, role):
        if index.isValid():
            if role==QtCore.Qt.ItemDataRole:
                key=str(index.data().toString())
                returnedValue=self.modelDict.get(key)
                return QtCore.QVariant(returnedValue)

            elif role==QtCore.Qt.DisplayRole:
                row=index.row()
                itemTitle=self.items[row]
                return itemTitle

    def addItems(self):
        for key in self.modelDict:
            index=QtCore.QModelIndex()
            self.beginInsertRows(index, 0, 0)
            self.items.append(key)

            inst=self.modelDict.get(key)
            self.setData(index, inst, QtCore.Qt.DisplayRole)

        self.endInsertRows()

    def removeByIndex(self, index):
        if index.isValid():
            row=index.row()
            self.beginRemoveRows(QtCore.QModelIndex(), row, 0)
            self.items=[each for i,each in enumerate(self.items[:]) if i!=row]
            self.endRemoveRows()

class ListView(QtGui.QListView):
    def __init__(self):
        super(ListView, self).__init__()
        self.model= Model()
        self.model.modelDict=elements
        self.model.addItems()
        self.setModel(self.model)
        self.clicked.connect(self.itemClicked)
        self.show()

    def itemClicked(self, index):
        itemTitle=str(self.model.data(index, QtCore.Qt.DisplayRole))
        print 'itemTitle: "%s"'%(itemTitle)
        self.model.removeByIndex(index)

rawDescription: How to delete raw from .model

description: Delete raw from .model


code:
pyg='gy'
original=raw_input("please enter a word")

# keep asking for an input until the user inputs something valid
while len(original) == 0 or not original.isalpha():
    print "You entered a blank field or a number. Please try again."
    original=raw_input("please enter a word")

# at this point, the input should be valid
original_lc=original.lower()
first=original_lc[0]
rest=original_lc[1:len(original_lc)]

print "Your word: " + original_lc
if first in "aeiou":
    print "your pyglatin translation: " + original_lc + pyg
else:
    print "your pyglatin translation: " + rest + first + pyg

rawDescription: While True statement and Pyg Latin

description: While True statement and Pyg Latin


code:
import os

def upload(file_name_number,files_dict):

    filename = int(raw_input(file_name_number))
    #as the key to dictionary is integer
    if filename in files_dict:
        # upload code here
        print "dummy"
    else:
        print "The selected number does not exist in current directory."
        upload(file_name_number,files_dict)#why are you calling this again
    return filename

def create():
    files_dict = showListAndSaveDict()
    firstFile  = upload("Select the number of first file:",files_dict)
    secondFile = upload("Select the number of second file:",files_dict)
    thirdFile  = upload("Select the number of third file:",files_dict)

def showListAndSaveDict():
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    files_dict = {}
    i=0
    for f in files:
        i = i+1
        print (str(i) + " - " + f)
        files_dict[i] = f
    return files_dict

create()

rawDescription: upload files using a number associated with each file instead of the name of the file

description: Upload files using a number associated with each file instead of the name of the file


code:
# I stole this decorator from another stackoverflow recipe :)
def returnthisclassfrom(specials):
  specialnames = ['__%s__' % s for s in specials.split()]
  def wrapit(cls, method):
    return lambda *a: cls(method(*a))
  def dowrap(cls):
    for n in specialnames:
      method = getattr(cls, n)
      setattr(cls, n, wrapit(cls, method))
    return cls
  return dowrap

def int_getslice(self, i, j):
    # NON-pythonic, will return everything inclusive i.e. x[5:3] returns 3 bits, not 2.
    # Because that's what users normally expect.
    # If you're a purist, modify below.
    if i > 1000000 or j > 1000000:
        raise ValueError, 'BitSize limited to 1 million bits'
    lo = min(i,j)
    hi = max(i,j)
    mask = (1<<((hi-lo)+1))-1

    return (self>>lo) & mask

def int_getitem(self, i):
    # Safety limit
    if i > 1000000:
        raise ValueError, 'BitSize limited to 1 million bits'
    return (self>>i)&1

def int_iter(self):
    # since getitem makes it iterable, override
    raise AttributeError, 'int object is not iterable'

@returnthisclassfrom('abs add and div floordiv lshift mod mul neg or pow radd rand rdiv rdivmod rfloordiv rlshift rmod rmul ror rpow rrshift rshift rsub rxor rtruediv sub truediv xor trunc')
class BitSliceInt(long):
  __getslice__ = int_getslice
  __getitem__ = int_getitem
  __iter__ = int_iter

rawDescription: Python: Can I have a subclass return instances of its own type for operators defined in a superclass?


code:
import sys,os
import pygtk, gtk, gobject

class GTK_Main:
  def __init__(self):
    """ Window """
    button_rc = """
    style "deButton" {
      # Default - Yellow
      bg[NORMAL] = "yellow"
      fg[NORMAL] = "#000000"

      # Mouse-Over - Blue
      fg[PRELIGHT] = "blue"
      bg[PRELIGHT] = "#000000"

      # Click - RED
      bg[ACTIVE] = "red"
      fg[ACTIVE] = "#000000"

    }
    widget "*.deButton" style "deButton"
    """

    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.set_title("Test")
    window.set_default_size(100, 100)
    window.connect("destroy", gtk.main_quit, "WM destroy")
    gtk.rc_parse_string(button_rc)

    hbox_eq = gtk.HBox()

    buttonlist = []

    for i in [1,2,3,4,5,6,7,8,9]:
      b =  gtk.Button( str(i) )

      b.set_name("deButton")
      buttonlist.append(b)
      hbox_eq.pack_start(b, True, True, 0)

    for button in buttonlist:
      print button.get_label()

    window.add(hbox_eq)
    window.show_all()

  def exit(self, widget, data=None):
    gtk.main_quit()

GTK_Main()
gtk.gdk.threads_init()
gtk.main()

rawDescription: Python - how do i make gtk.button as array/lists? so that via index it can be later accessible


code:
import re
import urllib2

if __name__ == "__main__":
    url = 'http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0'

    # http request
    response = urllib2.urlopen(url)
    html = response.read()
    response.close()

    # finding values in html
    results = re.findall(r'fvRequests\.setValue\(\d+, \d+, \'?(.*?)\'?\);', html)
    keys = results[::2]
    values = results[1::2]

    # creating a dictionary
    output = dict(zip(keys, values))

    print output

rawDescription: Parsing URL through Python

description: Parsing URL through Python


rawDescription: Python Regular expression repeat

description: Python Regular expression repeat


rawDescription: How for loop works in python?

description: How for loop works in python


code:
# transform into a source:target dictionary
links = {d['pred'] if d['pred'] else 'root':d['id'] for d in unordered_linked_list}

# follow links and print
source = 'root'
while source in links:
    print links[source]
    source = links[source]

rawDescription: how to sort a list of dependencies

description: Sort a list of dependencies


code:
class A(object):
    def __init__(self):
        print "entering A"
        super(A, self).__init__()
        print "leaving A"

class B(object):
    def __init__(self):
        print "entering B"
        super(B, self).__init__()
        print "leaving B"

class C(A,B):
    def __init__(self):
        print "entering c"
        A.__init__(self)
        B.__init__(self)
        print "leaving c"

rawDescription: How do you add new constructor values for a derived class?

description: Add new constructor values for a derived class


code:
content = [
    {'url':'url1', 'taglist':['b','a','c','d']},
    {'url':'url2', 'taglist':['c','a','b','d']},
    {'url':'url3', 'taglist':['a','b','c','d']},
    {'url':'url4', 'taglist':['a','b','d','c']},
    {'url':'url5', 'taglist':['d','a','c','b']}
]

search = {'d' : 1, 'a' : 2, 'b' : 3}

# We can create the tag cloud like this:
# tagCloud = set(sum((note['taglist'] for note in content), []))
# But we don't actually need it: instead, we'll just use a default value
# when looking things up in the 'search' dict.

# Create a [[relevance, tag],[],[],...] result list & sort
result = sorted(
    [
        [search.get(tag, 100), tag]
        for tag in note['taglist']
    ] + [[note['url']]]
    # The result will look like [ [relevance, tag],... , [url] ]
    # Note that the url is wrapped in a list too. This makes the
    # last processing step easier: we just take the last element of
    # each nested list.
    for note in content
)

# Remove the relevance values & recreate a list containing
# the url string followed by corresponding tags.
finalResult = [
    [x[-1] for x in note]
    for note in result
]

print "Content: ", content
print "Search: ", search
print "Final Result: ", finalResult

rawDescription: Python sorting question - given list of ['url', 'tag1', 'tag2',..]s and search specification ['tag3', 'tag1',...], return relevant url list


code:
import subprocess

netstat = subprocess.Popen("netstat -nptl".split(), stdout=subprocess.PIPE)
grep = subprocess.Popen("grep 192.168.46.134".split(), stdin=netstat.stdout, stdout=subprocess.PIPE)

stdout, stderr = grep.communicate()
print stdout # this is a string containing the output

rawDescription: pass data among processes in python

description: Pass data among processes in python


code:
def run():
    iterator = read()
    for i in iterator:
        print i
        if i == 2:
            break   # stop iterating

    print 'flip'

    # resume iterating
    for i in iterator:
        print i

rawDescription: Resuming list reading and remembering the cursor


code:
#!/usr/bin/python

print 'Content-Type: text/html'
print
print ''
print '<title>Hello from Python</title>'
print ''
print '
Hello from Python
'
print ''

rawDescription: Python on the Web

description: Python on the Web


code:
with app.test_request_context('/'):
    print url_for('core.city', city='new york')

rawDescription: flask url parameters with spaces generates urls with spaces

description: Flask url parameters with spaces generates urls with spaces


code:
iterator = my_object.__iter__()
while True:
    try:
        something = iterator.next()
    except StopIteration:
        # StopIteration exception is raised after last element
        break

    # loop code
    print something

rawDescription: Python Automation "For" "In" statements

description: Python Automation "For" "In" statements


code:
status = """
sale number       : 11/7
NAME               ID    PAWN    PRICE    TIME         %C     STATE     START/STOP
cross-cu-1       1055       1    106284K  07:49:36.19  25.05%   run          1d01h
cross-cu-2        918       1    104708K  07:38:19.08  24.02%   run          1d01h
sale number       : 11/8
NAME               ID    PAWN    PRICE    TIME         %C     STATE     START/STOP
cross-cu-3       1055       1    106284K  07:49:36.19  25.05%   run          1d01h
cross-cu-4        918       1    104708K  07:38:19.08  24.02%   run          1d01h
"""

sale_number = ''

sales = defaultdict(list)

for line in status.split('\n'):
    line = line.strip()
    if line.startswith("NAME"):
         continue
    elif line.startswith("sale number"):
         sale_number = line.split(':')[1].strip()
    elif not line or line.isspace() :
         continue
    else:
         # you can also use a regular expression here
         sales[sale_number].append(line.split())

for sale in sales:
    print sale, sales[sale]

rawDescription: pyparsing OneOrMore's embedded within other OneOrMore's

description: Pyparsing OneOrMore's embedded within other OneOrMore's


code:
import tornado
import datetime
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self, *args):
        self.id = self.generate_id()
        self.stream.set_nodelay(True)
        self.timeout = tornado.ioloop.IOLoop.current().add_timeout(
            datetime.timedelta(minutes=60), self.explicit_close)

        # ... DO STUFF ...

        clients[self.id] = {"id": self.id, "time":datetime.now(), "object": self}
        self.write_message("Connection SUCCESSFUL! Thanks for connecting! Your connection ID is: %d :)" % self.id)
        print datetime.now()
        print "New connection. ID: %d" % self.id
        print "Total number of open connections: %d" % len(clients)

    def on_close(self):
        print datetime.now()
        print "Closing connection %d." % self.id
        if self.id in clients:
            del clients[self.id]
        print "Number of open connections: %d" % len(clients)

    def explicit_close(self):
        self.close() # you wont even have to iterate over the clients.

rawDescription: How to automatically close connection serverside after a certain time in Tornado Websocket

description: Automatically close connection serverside after a certain time in Tornado Websocket


code:
n = 3
board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
print board
n = 4
board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
print board

rawDescription: Create a black and white chessboard in a two dimensional array


code: print ',x'.split(',')

rawDescription: .split() creating a blank line in python3


code:
import os
paths = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines()
for p in paths:
    if os.path.isdir(p):
        print p

rawDescription: Get file path of the highlighted files using nautilus script


code:
import wx
import wx.grid as gridlib

class ScrollbarFrame(wx.Frame):
    def __init__(self):
            wx.Frame.__init__(self, None, wx.ID_ANY,"Grid with Popup Menu")
            self.layout_file = {'ID':[1,5,5],'NAME':[6,12],'STATE':[13,20]}
            print self.layout_file
            self.OnInit()

    def OnInit(self):
        menuBar = wx.MenuBar()

        fileMenu = wx.Menu()
        fileMenu.Append(wx.ID_NEW, '&New')
        fileMenu.Append(wx.ID_OPEN, '&Open')
        fileMenu.Append(wx.ID_SAVE, '&Save')

        menuBar.Append(fileMenu, '&File')

        menu = self.SetMenuBar(menuBar)

        panel = wx.Panel(self, wx.ID_ANY)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

#         hbox1.Add(menu, proportion=1)
#         vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        self.grid = gridlib.Grid(panel)
        self.grid.CreateGrid(10 ,10)

        self.grid.SetCellValue(0,0,'(0,0)')
        self.grid.SetCellValue(0,0,'(0,1)')
        self.grid.SetCellValue(1,0,'(1,0)')
        self.grid.SetCellValue(1,0,'(1,1)')

        hbox2.Add(self.grid,1,wx.EXPAND,5)
        vbox.Add(hbox2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        panel.SetSizer(vbox)

if __name__ == '__main__':

    app = wx.App()
    frame = ScrollbarFrame()
    frame.Show()
    app.MainLoop()

rawDescription: wxpython adding grid and menubar

description: Wxpython adding grid and menubar


code:
from random import random

class Servo(object):
    """Servo controller"""
    def __init__(self):
        self.angle = 0

    def set_angle(self, angle):
        print "Setting angle to %s" % angle
        self.angle = angle
        # Let limb recalculate its position
        self.limb.calc_position()

class HexBone(Servo):
    """A bone that can be attached to a limb and moved."""
    def __init__(self, length):
        super(HexBone, self).__init__()
        self.length = length

        # Will be assigned later when attached to a limb
        self.limb = None

class HexLimb(object):
    """A limb consisting of several bones."""
    def __init__(self):
        self.femur = HexBone(42)
        self.femur.limb = self

        self.tibia = HexBone(30)
        self.tibia.limb = self

    def calc_position(self):
        print "Calculating position..."
        # Something that needs self.femur and self.tibia
        self.x = self.femur.length * random()
        self.y = self.tibia.length * random()

    def extend(self):
        self.tibia.set_angle(0)    # extend knee

left_leg = HexLimb()
left_leg.extend()

rawDescription: Python - Extend Class Instance Method

description: Python - Extend Class Instance Method


code:
default_options={
    "x":10,
    "y":10
}

def f1(**kwargs):
    x=kwargs.get('x', defalut_options['x'])
    return x**2

def f2(**kwargs):
    y=kwargs.get('y', defalut_options['y'])
    return x**4

def f(**kwargs):
    x=kwargs.get('x', defalut_options['x'])
    y=kwargs.get('y', defalut_options['y'])
    return f1(x=x, y=y)

if __name__=="__main__":
    import argparse
    parser = argparse.ArgumentParser(description = "A toy application", formatter_class=argparse.ArgumentDefaultsHelpFormatter )
    parser.add_argument("--f1-x",help="the parameter passed to f1",
      type = float,dest = "x")
    parser.add_argument("--f2-x",help="the parameter passed to f2",
      type = float, dest = "y")

    parser.set_defaults(**default_options)

    options= parser.parse_args()
    print f(options.x,options.y)

rawDescription: Python 2.7: how to pass options for standalone/module code


rawDescription: Creating multidimentional list from mutidimentioal list in python?


code:
list1 = ["a", "b", "c", "xc"]
list2 = ["d", "e", "to", "xc"]
list3 = ["f", "g", "h", "i", "j", "xc"]

print list(set(list1) & set(list2) & set(list3)) # it will print ['xc']

rawDescription: Python - Find a word into n lists (without knowing how many are)


code:
from math import*
x= int(raw_input('Enter the decimal number'))
n=[]
while x>1:
    y=int(x%2)
    n=n+[y]
    x=floor(x/2.0)
if x==1:
    n=n+[1]
elif x==0:
    n=n+[0]
size=len(n)
print 'binary equivalent =',
y=-1
while y>=-size:
    print n[y],
    y=y-1
print ''

rawDescription: Converting Integer to Binary Using the Math Module (Python)


code:
s = r"1\x1b2"
dec = s.decode('string_escape')
print len(dec), repr(dec)

rawDescription: How to convert "\x1b" into a real control character "[Esc]"

description: Convert "\x1b" into a real control character "[Esc]"


code:
d = collections.defaultdict(list)
with open('bigdata.txt', 'r') as datafile:
    for line in datafile:
        id = hashlib.sha256(line).digest()
        # Or id = line[:n]
        k = id[0:2]
        v = id[2:]
        if v in d[k]:
            print "double found:", id
        else:
            d[k].append(v)

rawDescription: Find duplicate records in large text file


code:
def cmds(cmd):
    infile = Popen(cmd, shell=True, stdout=PIPE).stdout
    print infile.readline()
    print infile.readline()
    print infile.readline()
    while True:
        line = infile.readline()
        if not line:
            break
        if line == '\n':
            print infile.readline()
            print infile.readline()
            print infile.readline()

rawDescription: Learning Python: Print 3 consecutives lines from a PIPE


code:
from pymongo import MongoClient

client = MongoClient()
db = client.test

# print collection statistics
print db.command("collstats", "events")

# print database statistics
print db.command("dbstats")

rawDescription: pymongo method of getting statistics for collection byte usage?

description: Pymongo method of getting statistics for collection byte usage


code:
import operator
oldlist = [('A', 6L), ('B', 7L), ('C', 8L), ('D', 8L), ('E', 6L), ('F', 8L)]
newlist = []

oldlist.sort(key=operator.itemgetter(1))
while oldlist and oldlist[0][1] != oldlist[-1][1]:
    newlist.append(oldlist.pop(0) + oldlist.pop())
newlist.extend(oldlist)  #unmatched items

rawDescription: Match dissimilar items inside a list in python


code:
def __init__(self, parent=None):
    super(MyMainWindow, self).__init__(parent)
    self.ui = AutoGeneratedUI()
    self.ui.setupUi(self)
    # connect the clicked signal to on_button_clicked() method
    self.pushButton.clicked.connect(self.on_button_clicked)

def on_button_clicked(self):
    print "button clicked"
    # here is the code to open a new window

rawDescription: How does one make a button in the main window open a different window?

description: Make a button in the main window open a different window


code:
from Tkinter import *
import ttk

class app():

    def __init__(self):
        self.root = Tk()
        self.fill_Combo()
        self.root.mainloop()

    def fill_Combo(self):
        self.combo1= ttk.Combobox(self.root,height=1, width=20)
        self.combo1['values'] = ("AA","BB","CC","DD","EE")
        self.combo1.current(0)
        self.combo1.place(x=5, y = 75)
        self.combo1.bind("<<ComboboxSelected>>",self.select_Combo)

    def select_Combo(self, event):
        self.var_Selected = self.combo1.current()
        print "The user selected value now is:"
        print  self.var_Selected
        # Any other function you want to use as function(self.var_Selected) or a function that gets self

app()

rawDescription: How to get and pass simultaneously a selected value from combo box to functions

description: Get and pass simultaneously a selected value from combo box to functions


code:
A1 = [1, 2, 3, 3, 4, 4, 4]
B1 = [1, 2, 3, 4, 5, 6, 7]
A2 = []
B2 = []

for i in range(len(A1)):
    if A1[i] != A1[i + 1]:
        A2.append(A1[i])
        B2.append(B1[i])
    else:
        j = i + 1
        sum = B1[i]
        while j < len(A1) and A1[i] == A1[j]:
            sum += B1[j]
            del A1[j]
            del B1[j]
        A2.append(A1[i])
        B2.append(sum)
        if j >= len(A1):
            break

print A2
print B2

rawDescription: If column A repeats, sum column 2

description: If column A repeats, sum column 2


code:
import gtk

def changed(window):
    print 'I have resized.'

w = gtk.Window()
w.connect('check-resize', changed)
w.show()
gtk.main()

rawDescription: Python Window Resize

description: Python Window Resize


code: print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined'

rawDescription: Easy way to check that a variable is defined in python?


code:
from collections import OrderedDict as odict
d = [('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)]
print odict(d).keys()

rawDescription: Get ordered key in dictionary by index

description: Get ordered key in dictionary by index


code:
import serial

baud_rate = 4800 #whatever baudrate you are listening to
com_port1 = '/dev/tty1' #replace with your com port path
com_port1 = '/dev/tty2'

listener = serial.Serial(com_port1, baudrate)
forwarder = serial.Serial(com_port2, baudrate)

while 1:
    serial_out = listener.read(size=1)
    print serial_out #or write it to a file
    forwarder.write(serial_out)

rawDescription: How to make a serial port sniffer sniffing pysical port using a python

description: Make a serial port sniffer sniffing pysical port using a python


code:
class Mutstr(object):
    def __init__(self, st=""):
          self.st = st

    def get(self):
          return self.st

    def __delitem__(self, index):
          self.st = self.st[:index] + self.st[index+1:]

one = Mutstr('oogyboogy')
del one[4]
del one[3]
del one[2]
print one.get()

rawDescription: Overloading the del operator in a mutable string class python


code:
sc_txt='''\
Ben,8
Tim,9
Tim,10
Ben,10
Ben,9
Tim,7'''

import csv

scores={}
for line in csv.reader(sc_txt.splitlines()):
    scores.setdefault(line[0], []).append(line[1])

print scores
# {'Tim': ['9', '10', '7'], 'Ben': ['8', '10', '9']}

rawDescription: Grouping data from a csv file in a dictionary


code:
import threading
import time

def sleeper():
    print 'Starting to sleep'
    time.sleep(10)
    print 'Just waking up..'
    print 'snooze'
    print 'oh no. I have to get up.'

def worker():
    print 'Starting to work'
    time.sleep(1) # this also a work. :)
    print 'Done with Work'

t = threading.Thread(name='sleeper', target=sleeper)
w = threading.Thread(name='worker', target=worker)

w.start()
t.start()

rawDescription: What Python Module Should I Use For Updating?


code:
import itertools
print list(itertools.combinations(range(1, 5), r=2))

rawDescription: Python Nested Loop unique pairs

description: Python Nested Loop unique pairs


code:
a = {'aaa': 1, 'bbb': 2, 'ccc': 3}
b = ['aaa', 'bbb', 'ddd', 'eee']
c = dict([(x, a.get(x, 0)) for x in a])

print "%(aaa)s %(bbb)s %(ccc)s" % c

rawDescription: How to skip a variable value in eval

description: Skip a variable value in eval


code:
list1 = [1, 1, 2]
list2 = ['a', 'b', 'c']
dikt = dict(zip(list1,list2))
print len(dikt)
print dikt

rawDescription: python list to dict weirdness

description: Python list to dict weirdness


code:
class MyClass:
    def do_something(self):
        print 'MyClass did something'

getattr(MyClass(),'do_something')()

rawDescription: Getting a class' method with a string

description: Getting a class' method with a string


code:
server = sshtunnel.open_tunnel(ip, ssh_username="test",
                               ssh_password="test",
                               remote_bind_address=("1.2.3.4", 23))
try:
    with server:
        print "SSH connected"
except KeyboardInterrupt:
    print "Pressed Ctrl-C"
    server._stop_transport()

print "SSH Closed"

rawDescription: Why does sshtunnel prevent SIGINT from closing my python app?


code:
checklist = ['a','b','c']
checklist[1] += 'd'
print checklist
#['a', 'bd', 'c']

rawDescription: Adding a string to a string in a list

description: Adding a string to a string in a list


code:
def reverse(S, start, stop):
    if start < stop - 1:
        S[start], S[stop-1] = S[stop-1], S[start]
        return reverse(S, start+1, stop-1)   # This should return as well
    else:
        return S

if __name__ == "__main__":
    x = reverse([1, 2, 3], 0, 3)
    print x

rawDescription: recursive function does not return value

description: Recursive function does not return value


code:
import itertools

list1 = ["a"]
list2 = ["a","b","c","d"]
list3 = ["b","e"]
list4 = ["f","g","a"]

f = lambda x: len(x) == len(set(x))
it = itertools.ifilter(f, itertools.product(list1, list2, list3, list4))

# print all combinations
for combination in it:
    print combination

rawDescription: Python Calculating Unique List Permutation Possibilities


code:
import hashlib
h = hashlib.sha512()

text = 'beruk makye'
text_compare = '3beruk makye'
text_compare_hash = h.update(text_compare)
text_compare_hash = h.hexdigest()

ids = [1,2,3]
texts = []
bool_text = []
bool_text_hash = []

for id in ids:
    texts.append(str(id) + text)

for i in texts:
    hash = hashlib.sha512(i).hexdigest()
    print i, hash, hash == text_compare_hash

rawDescription: SHA512 Python produced different result for the same string


code:
import sys
import os
import xml.etree.ElementTree as ET

def main():
    project_name=str(sys.argv[1])
    top_dir=os.environ['ANDROID_BUILD_TOP']       # There is a global variable that is set
                                                  # that will help you do croot while
                                                  # running in python shell.
    manifest_file='.repo/manifests.xml'

    os.chdir(top_dir)
    tree = ET.parse(manifest_file)
    root = tree.getroot()
    for project in root.findall('project'):
        if (project_name == project.get('name')):
            print project.get('path')
            exit()

if __name__ == "__main__":
    main()

rawDescription: how does croot work in android? Additionally, how do I replicate this functionality inside a python script?

description: How does croot work in android? Additionally, how do I replicate this functionality inside a python script


code:
import datetime, calendar

today = datetime.date.today()
week_from_today = today + datetime.timedelta(days=6)
last_day_of_month = today.replace(day=calendar.monthrange(today.year,today.month)[-1])

if today.month != week_from_today.month:
    print datetime.date(week_from_today.year, week_from_today.month, 1)
elif today <= last_day_of_month <= week_from_today:
    print last_day_of_month

rawDescription: python get day if its in a dates range

description: Python get day if its in a dates range