rawDescription: How to get min, seconds and milliseconds from datetime.now() in python?

description: Get min, seconds and milliseconds from datetime.now() in python


code:
import foo

foo.__doc__ = '''My docstring for this module'''

rawDescription: How to add docstrings to a module that I can't write to

description: Add docstrings to a module that I can't write to


code:
class SchoolAdmin(admin.ModelAdmin):
  list_display = ('school', 'student__name', 'student__subject__name')
  list_filter = ('school', 'student__name', 'student__subject__name')

admin.site.register(School, SchoolAdmin)

rawDescription: Filter by non field in Django

description: Filter by non field in Django


code:
def Socket(hosts, port):
    # create socket
    sock = connect(hosts, port)

    # Send
    Request = "GET services\n"
    sock.sendall(Request)
    sock.shutdown(socket.SHUT_WR)
    data = ""
    while 1:
        buf = sock.recv(255)
        if not buf:
            break
        data += buf
    sock.close()
    table = [line.split(';') for line in data.split('\n')[:-1]]
    return table

def connect(hosts, port):
    for host in hosts:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect((str(host), port))
        except socket.error:
            # Unable to establish a connection, lets move on to the next host.
            continue
        return sock
    raise Exception('Unable to establish connection')

rawDescription: How to open socket in Python with Active/Passive host?

description: Open socket in Python with Active/Passive host


code:
table = dict([(x + 0xFF00 - 0x20, unichr(x)) for x in xrange(0x21, 0x7F)] + [(0x3000, unichr(0x20))])
data.translate(table)

rawDescription: Convert exotic charset to string with python


code:
user_columns = User.__table__.columns
sess.query(*user_columns).all()  # unpack user_columns into arguments

rawDescription: Sqlalchemy get result as KeyedTuple instead of mapped objects


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

x0, y0, sigma = 5.5, 4.2, 1.4

x, y = np.arange(9), np.arange(9)

gx = np.exp(-(x-x0)**2/(2*sigma**2))
gy = np.exp(-(y-y0)**2/(2*sigma**2))
g = np.outer(gx, gy)
g /= np.sum(g)  # normalize, if you want that

plt.imshow(g, interpolation="nearest", origin="lower")
plt.show()

rawDescription: efficiently generate "shifted" gaussian kernel in python

description: Efficiently generate "shifted" gaussian kernel in python


code:
import numpy as np
from scipy.signal import convolve2d

image = np.random.random((100,100))
nbCameras = np.abs(np.random.normal(size=(100,100)).round())

maskWidth = 3
mask = np.ones((maskWidth, maskWidth))

visibilityMask = (nbCameras>1).astype(np.float)
visibilityMask = convolve2d(visibilityMask, mask, mode="same").astype(np.bool)

imgFinal = image.copy()
imgFinal[~visibilityMask] *= 0

import matplotlib.pyplot as plt
for i, (im, title) in enumerate([(image, "image"),
                                 (nbCameras, "nbCameras"),
                                 (visibilityMask, "visibilityMask"),
                                 (imgFinal, "imgFinal")]):
    plt.subplot(2,2,i+1)
    plt.title(title)
    plt.imshow(im, cmap=plt.cm.gray)

plt.show()

rawDescription: Improving performance iterating in 2d numpy array


code:
idx = image[:,:,0] > threshold
image[idx,0] = threshold

rawDescription: NumPy - Faster way to implement threshold value ceiling


code:
import ImageShow
[viewer.get_command_ex('file')[0] for viewer in ImageShow._viewers]

rawDescription: Displaying an image with Python Matlibplot and im.show() , why are they different?


code:
class izip_cycle(object):
    def __init__(self, *iterables ):
        self.remains = len(iterables)
        self.items = izip(*[self._gen(it) for it in iterables])

    def __iter__(self):
        return self.items

    def _gen(self, src):
        q = []
        for item in src:
            yield item
            q.append(item)

        # done with this src
        self.remains -=1
        # if there are any other sources then cycle this one
        # the last souce remaining stops here and thus stops the izip
        if self.remains:
            while True:
                for item in q:
                    yield item

rawDescription: python izip which cycles through all iterables until the longest finishes

description: Python izip which cycles through all iterables until the longest finishes


rawDescription: Python (1..n) syntax?

description: Python (1..n) syntax


code:
def OnMessageStatus(msg, status):
    if status == Skype4Py.cmsReceived:
        msg.Chat.SendMessage("n/a")

rawDescription: Skype4Py replying

description: Skype4Py replying


code:
import psutil, os

def kill_proc_tree(pid, including_parent=True):
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    for child in children:
        child.kill()
    psutil.wait_procs(children, timeout=5)
    if including_parent:
        parent.kill()
        parent.wait(5)

me = os.getpid()
kill_proc_tree(me)

rawDescription: subprocess: deleting child processes in Windows

description: Subprocess: deleting child processes in Windows


code:
class MyRecord:
    #....
    def __getitem__(self, key):
        return getattr(self, key)

rawDescription: Elegant ways to print out a bunch of instance attributes in python 2.6?


rawDescription: Have a number as identifier for a json

description: Have a number as identifier for a json


code:
seen = {}
for x in your_list:
    a,b,c,d = x
    seen.setdefault(a, []).append(x)

newlist = []
for a,x_vals in seen.iteritems():
    if len(x_vals) == 1:
        newlist.append(x_vals[0])

rawDescription: sorting a list of tuples

description: Sorting a list of tuples


code:
import praw

r = praw.Reddit(UNIQUE_AND_DESCRIPTIVE_USERAGENT)
submission = r.get_submission("http://www.reddit.com/r/redditdev/comments/16m0uu/praw_20_is_coming_release_in_2_days/")
comment = submission.comments[0]
author = comment.author  # This returns a ``Redditor`` object.
print(author.name)  # The username

rawDescription: PRAW: Comment Submitter's Username

description: PRAW: Comment Submitter's Username


code:
a = set()
for i in range(1000000): a.add(str(i))
for i in range(6, 1000000): a.remove(str(i))
b = set()
for i in range(6): b.add(str(i))
a == b
list(a)
list(b)

rawDescription: Python: Are `hash` values for built-in numeric types, strings standardised?


rawDescription: Numpy: stack array by the last dimension


code:
from xml.dom import minidom
import os, time, shutil

domConf=('/home/test/JBoss/jboss-eap-6.2/domain/configuration/domain.xml')
resultFile='result.xml'
commentSub=('urn:jboss:domain:messaging:1.4')

now=str(int(time.time()))
bkup=(domConf+now)
shutil.copy2(domConf, bkup)

xmldoc = minidom.parse(domConf)
itemlist = xmldoc.getElementsByTagName('subsystem')
for s in itemlist:
        if commentSub in s.attributes['xmlns'].value:
            commentText = s.toxml()
            commentText = commentText.replace('--', '- -')
            s.parentNode.insertBefore(xmldoc.createComment(commentText), s)
            s.parentNode.removeChild(s)
file = open("result.xml", "wb")
xmldoc.writexml(file)
file.write('\n')
file.close()

shutil.copy2(resultFile, domConf)

rawDescription: Using Python to comment out XML

description: Using Python to comment out XML


code:
gb = test.groupby('score1')
gb.grouper
gb.grouper.groupings
gb.grouper.groupings[0]
gb.grouper.groupings[0].indices

rawDescription: Pandas duplicated indexes still shows correct elements


code: grid = [[None]*n for i in range(n)]

rawDescription: Generating NXN spirals

description: Generating NXN spirals


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

width=0.5

strong_dis = np.array((20, 10, 5, 10, 15))
disagree = np.array((20, 25, 15, 15, 10))
# shortcut here
therest = np.subtract(100, strong_dis + disagree)

q = np.arange(5)

bsd=plt.barh(q, strong_dis, width, color='red')
bd=plt.barh(q, disagree, width, left=strong_dis, color='pink')
br=plt.barh(q, therest, width, left=strong_dis+disagree, color='lightblue')

ylabels = tuple(reversed(['A', 'B', 'C', 'D', 'E']))
plt.yticks(q+width/2., ylabels)

plt.xlabel('Responses (%)')
plt.legend((bsd, bd, br), ('strong disagree', 'disagree', 'the rest'))
plt.show()

rawDescription: Stacked distribution graph (possibly in python)


code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im = np.arange(100)
im.shape = 10, 10
images = [im for i in range(20)]

fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111,
                 nrows_ncols=(2, 10),
                 axes_pad=0,
)

for i in range(20):
    grid[i].imshow(images[i], cmap=plt.get_cmap('Greys_r'))  # The AxesGrid object work as a list of axes.
    grid[i].axis('off')
plt.show(block=True)

rawDescription: Is there a good solution for space efficiently showing multiple images in pylab/matplotlib?


code:
import ipaddress  # IP is lowercase because this is a module
ipaddress.IPv4Address  # IP is uppercase because this is a class
ipaddress.ip_network  # IP is lowercase because this is a function

rawDescription: Python: Naming with Acronyms

description: Python: Naming with Acronyms


code:
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('europe.pool.ntp.org', version=3)
ctime(response.tx_time)

rawDescription: DetermineThe Correct Time

description: DetermineThe Correct Time


rawDescription: Where do I call the BatchNormalization function in Keras?


code:
import wx

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)

        control_panel = wx.Panel(panel)
        control_panel.SetBackgroundColour("Yellow")
        main_panel = wx.Panel(panel)
        main_panel.SetBackgroundColour("Blue")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(control_panel, 3, wx.EXPAND)
        sizer.Add(main_panel, 1, wx.EXPAND)
        panel.SetSizer(sizer)

# Run the program
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()

rawDescription: Placing elements (panels) within a wx.GridBagSizer


code:
class myplot(object):
    def __init__(self, filename):
        self._filename = filename

    def resetFileName(self, fileName):
        self._filename = fileName

    def __call__(self):
        matplotlib.pylab.savefig(self._filename)

plotfunction = myplot("foo.png")
matplotlib.pylab.draw_if_interactive = plotfunction

rawDescription: Non-interactive ploting with matplotlib on Mac OS X


code:
class AcademicProgramsSerializer(serializers.ModelSerializer):

    class Meta:
        model = AcademicPrograms
        depth = 1

class StudentAcademicProgramsSerializer(serializers.ModelSerializer):
    academic_program = AcademicProgramsSerializer(source='academic_program')

    class Meta:
        model = StudentAcademicPrograms
        fields = (
            'credits_completed',
            'academic_program_gpa',
            'primary_program',
            'academic_program'
        )

rawDescription: Django rest framework serializer not giving the expected output


rawDescription: Pandas; calculate mean and append mean to original frame


code:
from twisted.python.modules import getModule
script = getModule(__name__).filePath.path
# ...
reactor.spawnProcess(..., script, ...)

rawDescription: how to access source tree in Twisted trial tests?

description: Access source tree in Twisted trial tests


code:
from Bio import SeqIO
fnames = ["file.fastq", "file1.fastq", "file2.fastq"]
for fname in fnames:
    adaptor = (rec for rec in \
                    SeqIO.parse(fname, "fastq") \
                    if rec.seq.startswith("TGA"))
    count = SeqIO.write(adaptor, "adaptor.fastq", "fastq")
    print("Saved %i adaptor in file %s" %(count, fname))

rawDescription: Count occurence adaptor in multiple fasta file


code:
from sqlalchemy import Integer, Column, ForeignKey, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('postgresql://hal:hal@localhost/hal')

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref=backref('parent', order_by=id))

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_fk = Column(Integer, ForeignKey('parent.id'))

Base.metadata.create_all(engine)
session_maker = sessionmaker(engine)
s = scoped_session(session)

parent = Parent()
parent.children.append(Child())

s.add(parent)
s.commit()
engine.execute('select * from child').fetchall()
# prints: [(1, 1)]

parent2 = Parent()
s.add(parent2)
s.commit()

parent2.children.append(Child())
parent2.children.append(Child())
parent2.children.append(Child())

# ``parent2`` does not need to be ``added`` to the session again, as
# user this-vidor pointed out in the comments.
# Committing the session will persist the changes, i.e. adding the
# related three child rows to the database.
s.commit()

engine.execute('select * from child').fetchall()
# prints: [(1, 1), (2, 2), (3, 2), (4, 2)]

rawDescription: SQLAlchemy: Why does appending to this many-to-one relationship fail?


rawDescription: Bar plotting with pandas

description: Bar plotting with pandas


code:
def create_dictionary(file):
    if file == fileDec:
        sortBins = {item : [] for item in dictionIndexes[:10]}
        return sortBins
    elif file == fileOct:
        sortBins = {item : [] for item in dictionIndexes[:8]}
        return sortBins
    elif file == fileHex:
        sortBins = {item : [] for item in dictionIndexes}
        return sortBins

rawDescription: How to use dictionary comprehension to limit its creation?

description: Use dictionary comprehension to limit its creation


code:
from BeautifulSoup import BeautifulSoup

html = \
"""
String1 :
112.674448  handle

String2 :
60.90402  handle

String3 :
51.770428  handle

String4 :
182712  handle
"""

soup = BeautifulSoup(html)

soup.findAll("font",id="font1")

rawDescription: parsing website data with beautifulSoup

description: Parsing website data with beautifulSoup


code:
obj = someobject
obj.a = lambda: None
setattr(obj.a, 'somefield', 'somevalue')

rawDescription: Python: create object and add attributes to it


code:
import datetime as dt
...

Data['yourdatetimecolumn'] = pd.to_datetime(Data['yourdatetimecolumn'])
JanData = Data[Data['yourdatetimecolumn'].dt.month==1]

rawDescription: Subset of Dataframe based on substring (python)


code:
def weighted_random(deck):
    total = sum(deck.values())
    r = randint(1, total)
    for c in deck.keys():
        r -= deck[c]
        if r <= 0:
            deck[c]-=1
            return c

results = weighted_random(deck)

rawDescription: random card from a deck with probabilities

description: Random card from a deck with probabilities


code:
gameDisplay.fill(your_color_tuple)

# afterwards add your drawing code

rawDescription: Replace Text On Pygame Window

description: Replace Text On Pygame Window


code:
len_max = 0
list_items = ["item2", "item2", "item3+a few characters for the size"]
for m in list_items:
    if len(m) > len_max:
        len_max = len(m)

import tkinter
master = Tk()

my_listbox1 = Listbox(master, width = len_max)
my_listbox1.grid(row = 0, column = 0)

my_listbox2 = Listbox(master, width = len_max)
my_listbox2.grid(row = 0, column = 1)

my_listbox1.insert(END, list_items[0])
my_listbox2.insert(END, list_items[1])
my_listbox2.insert(END, list_items[2])

master.mainloop()

rawDescription: Resizing tkinter listbox to width of largest item, using .grid


code:
import datetime
while 1:
    now = datetime.datetime.now()
    if now.hour < 3:
        at_3 = datetime.datetime.combine(datetime.date.today(),
                                         datetime.time(3))
        to_sleep = (at_3 - now).seconds
        time.sleep(to_sleep)

    # do the work ...

rawDescription: How can I set up the time to run in Python Script

description: Set up the time to run in Python Script


code:
credit=0
x=1
d=1
def sum1():
    global x
    global credit
    while x>0:
        g=int(input("Press 1 to continue inputting money or press 0 to select    and item"))
        if g==1:
            inpt=int(input("Please insert 10p, 20p, 50p, or £1 (100p) coins   into the machine."))
            credit=credit+inpt
        else:
            print("You have "+str(credit)+" pence in your credit balance")
            x=0
sum1()
print("something")
sum1()

rawDescription: How do I use a function multiple times in Python?

description: Use a function multiple times in Python


code:
limit = 10
limited_artists = xml.findall('artist')[:limit]
results = [xml_to_dict(artist) for artist in limited_artists]

rawDescription: Python idiom: List comprehension with limit of items


rawDescription: splitting a number into the integer and decimal parts in python

description: Splitting a number into the integer and decimal parts in python


code:
# Global Variables
username, password, mailboxname = '', '', '[Gmail]/&kc 2JgQ-'

# Set up
import gmail
g = gmail.Gmail()
g.login(username, password)

# Actual code.
emails = []
for email in g.mailbox(mailboxname).mail():
    emails.append(email.fetch())

# Tear down.
g.logout()

rawDescription: How can I remove all the email not in the important or sent folder?

description: Remove all the email not in the important or sent folder


code:
from decimal import *

html = open("html.txt").read()
out = open("legoShipping.txt", "w")

out.write("Order Number" + "\t" +
          "Grand Total (currency)" + "\t" +
          "Order Total (currency)" + "\t" +
          "Shipping Cost (currency)" + "\t" +
          "Order Weight (grams)" + "\t" +
          "Order Weight (oz.)" + "\t" +
          "Shipping Class" + "\n")

#split html on order number
legoOrders = html.split("Order #")

for order in legoOrders[1:]:
  orderNumber = order.split("<")[0]

  #get Grand Total
  grand = order.split("Grand Total:	")[1].split('')[1].split("<")[0].split(' ')
  grandCurrency = grand[0]
  grandTotal = grand[1]

  #get Order Total
  orderTotalAndCurrency = order.split('Order Total:	')[1].split('')[1].split("<")[0].split(' ')
  orderCurrency = orderTotalAndCurrency[0]
  orderTotal = orderTotalAndCurrency[1]

  #get Shipping Cost
  shipping = order.split("Shipping:	")[1].split('')[1].split("<")[0].split(' ')
  shippingCurrency = shipping[0]
  shippingCost = shipping[1]

  #get Weights
  weightString = order.split('Estimated Weight of Order:	')[1]
  splitWeightString = weightString.split('   ')
  splitStringFinal = splitWeightString[1].split("<")
  grams = splitStringFinal[0]
  ozs = weightString.split('&nbsp')[0]

  #convert grams to mathematical value
  gramsValue = Decimal(grams[:-1])

  #create default shipping class value. Set it to ""
  shippingClass = ""

  if gramsValue > 0:
    if gramsValue < 100:
      shippingClass = "A"

  if gramsValue >= 100:
    if gramsValue < 200:
      shippingClass = "B"

  out.write(str(orderNumber) + "\t" +
            str(grandTotal) + " (" + str(grandCurrency) + ")" + "\t" +
            str(orderTotal) + " (" + str(orderCurrency) + ")" + "\t" +
            str(shippingCost) + " (" + str(shippingCurrency) + ")" + "\t" +
            str(grams) + "\t" +
            str(ozs) + "\t" +
            str(shippingClass) + "\n")

rawDescription: Using data from a website, match it to a table and pull data


code:
def partial_duplicates1(l):
    check_list = []
    final_list = []
    for item in l:
        first_two_elems = item[:2]
        if first_two_elems not in check_list:
            final_list.append(item)
            check_list.append(first_two_elems)
    return final_list

def partial_duplicates2(l):
    already_included = {item[:2]: False for item in l}
    final_list = []
    for item in l:
        first_two_elems = item[:2]
        if not already_included[first_two_elems]:
            final_list.append(item)
            already_included[first_two_elems] = True
    return final_list

rawDescription: Remove duplicate elements from a list of sequences ONLY if first two sequence elements are duplicated (python)


rawDescription: Count of a given item in a particular position across sublists in a list


code:
from webapp2_extras.appengine.auth.models import User
from ndb import key, model

class MUser(User): # child class of User
    displayname = model.StringProperty() # show on screen, auto create 'user-{id}'
    lastaccess = model.DateTimeProperty(auto_now=True)

    @classmethod
    def update_or_insert_user(cls, user):
        """update some user's prop if exited else create new muser
        return : MUser object or None
        """
        u = MUser.get_by_auth_id(user.email())
        if u is None:
            ok, u = MUser.create_user(user.email(), id=newid)
            if ok == True:
                u.displayname = 'user-'+str(u.get_id())
            else:
                log.error('create new user error : ' + user.email())
                u = None
        else :
            u.put() # Update last access (auto fill def in model class)

        return u

class MyPageHandler(NewBaseHandler):
    """
    Only accessible to users that are logged in
    """
    @user_required
    def get(self):
        user = self.get_current_muser()
        self.render_template('mypage.htm', {'user': user.displayname })

    def get_current_muser(self):
        # come from gae login page, convert current gae user to muser
        user = users.get_current_user() # google users
        if user:
            # user have login, try to create or update
            log.info('create user')
            mu = MUser.update_or_insert_user(user)
            if mu:
                # save to session
                self.session['muserid'] = mu.key.id()
                return mu

        return None

rawDescription: How to have usernames with webapp2's User model?

description: Have usernames with webapp2's User model


code:
cmd = ["./my_program.sh"]
p = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE)   # launch the process
while p.poll() is None:          # check if the process is still alive
    out = p.stdout.readline()    # if it is still alive, grab the output
    do_something_with(out)       # do what you want with it

rawDescription: How can I capture output and show it at the same time with Python?

description: Capture output and show it at the same time with Python


code:
order = ['C','B','W','E','K']
possibilities = ['E','C','W']
possibilities_in_order = sorted(possibilities, key=order.index)
possibilities_in_order

rawDescription: most pythonic way to order a sublist from a ordered list

description: Most pythonic way to order a sublist from a ordered list


code:
from django.db import models
from a1.models import Foo, Bar

f1 = Foo.objects.create(aaa=5)
f2 = Foo.objects.create(aaa=8)
f3 = Foo.objects.create(aaa=1)
f4 = Foo.objects.create(aaa=12)
f5 = Foo.objects.create(aaa=3)

b1 = Bar.objects.create(foo=f2, bbb=True)
b2 = Bar.objects.create(foo=f1, bbb=True)
b3 = Bar.objects.create(foo=f5, bbb=False)
b4 = Bar.objects.create(foo=f3, bbb=True)
b5 = Bar.objects.create(foo=f2, bbb=True)
b6 = Bar.objects.create(foo=f3, bbb=True)
b7 = Bar.objects.create(foo=f4, bbb=True)
b8 = Bar.objects.create(foo=f5, bbb=False)
b9 = Bar.objects.create(foo=f4, bbb=False)
b10 = Bar.objects.create(foo=f5, bbb=True)
b11 = Bar.objects.create(foo=f4, bbb=True)
b12 = Bar.objects.create(foo=f4, bbb=True)
b13 = Bar.objects.create(foo=f4, bbb=True)
b14 = Bar.objects.create(foo=f4, bbb=True)
b15 = Bar.objects.create(foo=f4, bbb=True)

Foo.objects.filter(bar__bbb=True).count()
Foo.objects.filter(bar__bbb=True).aggregate(models.Sum("aaa"))['aaa__sum']
Foo.objects.filter(bar__bbb=True).distinct().count()
Foo.objects.filter(bar__bbb=True).distinct().aggregate(models.Sum("aaa"))['aaa__sum']

rawDescription: Django bug when using distinct() and models.Sum()


rawDescription: python tuple to dict

description: Python tuple to dict


code:
s = repr("ab\r")
s
from ast import literal_eval
literal_eval(s)

rawDescription: Reverse repr function in Python

description: Reverse repr function in Python


code:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'ugly name1':[1,2,3], 'ugly name2':[2,3,4]})

df.plot()
plt.legend(['pretty1', 'pretty2'],loc='upper left')

rawDescription: Use temprary label for pandas.DataFrame.plot in legend


code: my_dict = {x : [y, z, t] for x,y,z,t in zip(inst, degree, major, dates)}

rawDescription: How to create a dictionary out of four lists?

description: Create a dictionary out of four lists


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

N = 5
menMeans = (20, 35, 30, 35, 27,43,444,44)
menStd =   (2, 3, 4, 1, 2,43,4,33)

ind = np.arange(8)  # the x locations for the groups
width = 0.35       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 25,322,3,443,3)
womenStd =   (3, 5, 2, 3, 3,32,33,322)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5','K','K','Z') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )
ax.set_ylim(0)

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

rawDescription: Floating Bars in Matplotlib Pyplot Bar Graph


code:
import os.path
from PIL import Image

HORIZONTAL_BAND_1_Y = range(37, 64)
HORIZONTAL_BAND_2_Y = range(125, 149)

img = Image.open(filename)
img = img.convert('RGBA')
pixdata = img.load()

for band in HORIZONTAL_BAND_1_Y, HORIZONTAL_BAND_2_Y:
    for y in band:
        for x in range(img.size[0]):
            pixdata[x,y] = pixdata[x, band[0]-1]

new_filename = os.path.join(os.path.dirname(filename),
                   'new_{}'.format(os.path.basename(filename)))

img.save(new_filename)

rawDescription: Replace same line of pixels in dynamic images with Pillow in python


rawDescription: Python-equivalent of short-form "if" in C++


code:
import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

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

        self.initUI()
    def initUI(self):
        hbox = QtGui.QHBoxLayout()
        grid = QtGui.QGridLayout()

        #Definition des Tracing Parameters widgets
        WindowSize = QtGui.QLabel("Window size (m)")
        SampPts = QtGui.QLabel("Sampling points")
        WindowSizeEdit = QtGui.QLineEdit()
        SampPtsEdit = QtGui.QLineEdit()
        TracParamFrame = QtGui.QGroupBox(self)
        TracParamFrame.setTitle("Tracing Parameters")
        hbox.addLayout(grid)

        grid.addWidget(WindowSize,0,0)
        grid.addWidget(WindowSizeEdit,0,1)
        grid.addWidget(SampPts,1,0)
        grid.addWidget(SampPtsEdit,1,1)
        TracParamFrame.setLayout(hbox)

        #self.setLayout(hbox)

        self.setGeometry(300,300,350,300)
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt : How to add a grid layout inside a QGroupBox in PyQt4


code:
from datetime import datetime

line_to_add = 'def'

with open('file.txt', 'a+') as openfile:
    if not (item for item in openfile if line_to_add not in line):
        openfile.write(str(datetime.now()) + " " + line_to_add + ' \n')

rawDescription: file accessing in python

description: File accessing in python


code:
def index(number_list, start=0):
    if start >= len(number_list):
        return -1
    elif number_list[start] == start:
        return start
    else:
        return index(number_list, start+1)

rawDescription: Return list[i] = i index of a list

description: Return list[i] = i index of a list


code:
files_to_ignore = ('abc.txt', 'foo.txt', 'bar.txt')

for root,dirnames,filenames in os.walk('D:/datast12'):
    for filename in fnmatch.filter(filenames, '*.txt'):
        if filename in files_to_ignore: continue
        matches.append([root,filenames])

rawDescription: How can I ignore specific files when I am parsing a directory?

description: Ignore specific files when I am parsing a directory


code:
l.sort(key=operator.itemgetter(1))
l

rawDescription: Python sort list based on value in list, in list


code:
# -*- coding: utf-8 -*-
# String for doctests and  example:
"""
            >>> a = NotifierList()
            >>> flag.has_changed
            False
            >>> a.append(NotifierDict())
            >>> flag.has_changed
            True
            >>> flag.clear()
            >>> flag.has_changed
            False
            >>> a[0]["status"]="new"
            >>> flag.has_changed
            True
            >>>

"""

changer_methods = set("__setitem__ __setslice__ __delitem__ update append extend add insert pop popitem remove setdefault __iadd__".split())

def callback_getter(obj):
    def callback(name):
        obj.has_changed = True
    return callback

def proxy_decorator(func, callback):
    def wrapper(*args, **kw):
        callback(func.__name__)
        return func(*args, **kw)
    wrapper.__name__ = func.__name__
    return wrapper

def proxy_class_factory(cls, obj):
    new_dct = cls.__dict__.copy()
    for key, value in new_dct.items():
        if key in changer_methods:
            new_dct[key] = proxy_decorator(value, callback_getter(obj))
    return type("proxy_"+ cls.__name__, (cls,), new_dct)

class Flag(object):
    def __init__(self):
        self.clear()
    def clear(self):
        self.has_changed = False

flag = Flag()

NotifierList = proxy_class_factory(list, flag)
NotifierDict = proxy_class_factory(dict, flag)

rawDescription: Check if huge list in python has changed


code:
import pygame
from pygame.locals import *

pygame.display.init()
screen = pygame.display.set_mode((800, 600))
img = pygame.image.load('sky.png')

imgPos = pygame.Rect((0, 0), (0, 0))

LeftButton = 0
while 1:
    for e in pygame.event.get():
        if e.type == QUIT: exit(0)
        if e.type == MOUSEMOTION:
            if e.buttons[LeftButton]:
                # clicked and moving
                rel = e.rel
                imgPos.x += rel[0]
                imgPos.y += rel[1]
    screen.fill(0)
    screen.blit(img, imgPos)
    pygame.display.flip()
    pygame.time.delay(30)

rawDescription: Pygame drag background image

description: Pygame drag background image


code:
def get_upload_to(instance, filename):
    return School._meta.get_field(instance.field_name).upload_to+"/"+filename

rawDescription: django change image file location with setattr

description: Django change image file location with setattr


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

fig, (ax1, ax2) = plt.subplots(nrows=2)

# Some demo data
x = np.linspace(0, 18)
y = np.linspace(0, 1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + Y

# Something on axes 1
ax1.plot(x, np.sin(x))

# Plot the pcolormesh
pcm = ax2.pcolormesh(X, Y, Z)

# create color bar: the important part!
axColor = plt.axes([box.x0 + box.width * 1.05, box.y0, 0.01,     box.height])
plt.colorbar(pcm, cax=axColor, orientation="vertical")
plt.show()

rawDescription: Error colorbar position in matplotlib 5 subplot


code:
import wx
import wx.lib.agw.aui as aui

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        style = aui.AUI_NB_DEFAULT_STYLE ^ aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
        self.notebook = aui.AuiNotebook(self, agwStyle=style)

        self.panel1 = wx.Panel(self.notebook)
        self.panel2 = wx.Panel(self.notebook)
        self.panel3 = wx.Panel(self.notebook)

        self.notebook.AddPage(self.panel1, "First")
        self.notebook.AddPage(self.panel2, "Second")
        self.notebook.AddPage(self.panel3, "Third")

        self.notebook.EnableTab(1, False)

        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython: Disable a notebook tab?

description: WxPython: Disable a notebook tab


code:
allpeople = list(results.order_by('name'))
total = len(allpeople)
if request.GET.has_key('offset'):
    offset = int(request.GET.get('offset').strip())
    results = allpeople[100*offset:100*(offset+1)]
people = results

rawDescription: Django: How to count a queryset and return a slice without hitting DB twice?


code:
from sympy import *
init_printing()
ComplexRegion(Interval(0, 2)*Interval(0, pi), polar=True)
ComplexRegion(Interval(-oo, oo)*Interval(0, oo))

rawDescription: How to represent Complex plane regions in SymPy?

description: Represent Complex plane regions in SymPy


code:
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in csv.reader(infile):
        writer.write(row)

rawDescription: how do i write a text file to csv in python with consideration to columns

description: Write a text file to csv in python with consideration to columns


code:
import arcpy
from arcpy import env
env.workspace = ('C:\\StudyAreas\\Aggregates.gdb')
InFolder = ('C:\\dre\\python\\tables')
OutputFile = open(InFolder + '\\' + 'RasterProps.txt', 'a')
rlist = arcpy.ListRasters('*','*')
for grid in rlist:
    if grid[-8:] == "Clip_30m":
        resultX = arcpy.GetRasterProperties_management(grid,'CELLSIZEX')
        CellSizeX = resultX.getOutput(0)
        resultY = arcpy.GetRasterProperties_management(grid,'CELLSIZEY')
        CellSizeY = resultY.getOutput(0)
OutputFile.write(grid + ',' + str(CellSizeX) + ',' + str(CellSizeY) + '\n')
OutputFile.close()

rawDescription: Appending multiple raster properties to a comma-delimited table


code:
class Example(object):
    def foo(self):
        print("this is foo")
    def bar(self):
        print("this is bar")
    def __getattr__(self, name):
        def method(*args):
            print("tried to handle unknown method " + name)
            if args:
                print("it had arguments: " + str(args))
        return method

example = Example()

example.foo()        # prints “this is foo”
example.bar()        # prints “this is bar”
example.grill()      # prints “tried to handle unknown method grill”
example.ding("dong") # prints “tried to handle unknown method ding”
                     # prints “it had arguments: ('dong',)”

rawDescription: Can I create an object that receives arbitrary method invocation in python?

description: Create an object that receives arbitrary method invocation in python


rawDescription: How to make python window run as "Always On Top"?

description: Make python window run as "Always On Top"


code:
import matplotlib.pyplot as plt
from numpy.random import random, randint
import pandas as pd

dates = ["Tue  2 Jun 16:55:51 CEST 2015",
"Wed  3 Jun 14:51:49 CEST 2015",
"Fri  5 Jun 10:31:59 CEST 2015",
"Sat  6 Jun 20:47:31 CEST 2015",
"Sun  7 Jun 13:58:23 CEST 2015",
"Mon  8 Jun 14:56:49 CEST 2015",
"Tue  9 Jun 23:39:11 CEST 2015",
"Sat 13 Jun 16:55:26 CEST 2015",
"Sun 14 Jun 15:52:34 CEST 2015",
"Sun 14 Jun 16:17:24 CEST 2015",
"Mon 15 Jun 13:23:18 CEST 2015"]

values = [3,3,3,3,3,2,1,2,3,3,1]

X = pd.to_datetime(dates)
fig, ax = plt.subplots(figsize=(6,1))
ax.scatter(X, [1]*len(X), c=values,
           marker='s', s=100)
fig.autofmt_xdate()

# everything after this is turning off stuff that's plotted by default

ax.yaxis.set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')

ax.get_yaxis().set_ticklabels([])
day = pd.to_timedelta("1", unit='D')
plt.xlim(X[0] - day, X[-1] + day)
plt.show()

rawDescription: is it possible to plot timelines with matplotlib?

description: Is it possible to plot timelines with matplotlib


rawDescription: replaces multiple occurances of a character (except for first and last) in a python string

description: Replaces multiple occurances of a character (except for first and last) in a python string


rawDescription: Using dictionaries and compound field format() with Integer key stored as String


code:
import wx
class TextDropTarget(wx.TextDropTarget):
    def __init__(self, obj, callback):
        wx.TextDropTarget.__init__(self)
        self.obj = obj
        self._callback = callback

    def OnDropText(self, x, y, data):
        self.obj.WriteText(data + '\n\n')
        wx.MessageBox("Error", "Error", style = wx.ICON_ERROR)

    def OnDragOver(self, *args):
        wx.CallAfter(self._callback)
        return wx.TextDropTarget.OnDragOver(self, *args)

class DropFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        text = wx.TextCtrl(self, wx.ID_ANY)
        text.SetDropTarget(TextDropTarget(text, self._callback))

    def _callback(self):
        self.Raise()
        self.SetFocus()

app = wx.PySimpleApp()
frame = DropFrame()
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

rawDescription: wxpython drag&drop focus problem

description: Wxpython drag&drop focus problem


code:
import dateutil.parser as dp
t = '1984-06-02T19:05:00.000Z'
parsed_t = dp.parse(t)
t_in_seconds = parsed_t.strftime('%s')
t_in_seconds

rawDescription: Converting ISO 8601 date time to seconds in python


code:
__default = object()
def get_data(replace_nan=__default):
    if replace_nan is __default:
        ...

rawDescription: Default value for optional argument in Python:


code:
from otherfile import foo
Bar = foo()

x = Bar()  # create an instance of Bar

rawDescription: Is it possible to import a class defined inside a function?


code:
class MailSpider(CrawlSpider):
    ...

    def parse_start_url(self, response):
        return self.parse_item(response)

    def parse_item(self, response):
        hxs = HtmlXPathSelector(response)
        items = []
        ...

rawDescription: Using Regex to Select Index Page Only

description: Using Regex to Select Index Page Only


code:
import logging
logging.basicConfig(level=logging.INFO)
def add_log(cls):
    setattr(cls, 'dbg', logging.getLogger(cls.__name__))
    return cls

@add_log
class LongClassName:
    def test_info(self):
        self.dbg.info("helloWorld")
x = LongClassName()
x.test_info()

rawDescription: attach common python logging snippet to different class definition?

description: Attach common python logging snippet to different class definition


code:
import copy
from pprint import pprint
dicti = {'files':
    {'a':{'offset':100, 'start': 0},
     'b':{
         'c':{'offset':50, 'start':0},
         'd':{'offset':70, 'start':0},
         },
     'e':{
         'f':{'offset':80, 'start':0},
         'g':{'offset':30, 'start':0},
         'h':{'offset':20, 'start':0},
         }
    }
}

# Solution 1, two passes
def modify(d):
    if isinstance(d, dict):
        if d.get('offset', 0) > 50:
            d['offset'] = 0
        for k,v in d.items():
            modify(v)
dictj = copy.deepcopy(dicti)
modify(dictj)
pprint(dictj)

# Solution 2, copy and modify in one pass
def copy_and_modify(d):
    if isinstance(d, dict):
        d2 = {k:copy_and_modify(v) for k,v in d.items()}
        if d2.get('offset') > 50:
            d2['offset'] = 0
        return d2
    return d
dictj = copy_and_modify(dicti)
pprint(dictj)

rawDescription: python change value in nested dictionary if condition is met

description: Python change value in nested dictionary if condition is met


rawDescription: Generate random non repeating numbers in a range except a specific number in python


code:
import base64, PIL, urllib, Tkinter
from Tkinter import *
from PIL import ImageTk
from urllib import *

root = Tk()

raw_data = urllib.urlopen("http://dl.dropboxusercontent.com/s/qtlincxkbbiz1qv/stat.gif").read()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

root.tk.call('wm', 'iconphoto', root._w, image)

root.mainloop()

rawDescription: How can I set a tkinter app icon with a URL?

description: Set a tkinter app icon with a URL


code:
types = ('Blue', 'Polka', 'Red', 'Stripe', 'Yellow', 'Purple', 'Pink', 'Orange', 'Crazy', 'Plain')
for t in types:
    setattr(self, '%sEgg' % t, PhotoImage(file='assets/%segg.gif' % t.lower()))

rawDescription: Reducing the following lines of PhotoImage code to as few lines as possible


code: import models

rawDescription: Separating Models and Request Handlers In Google App Engine


code:
from itertools import product
for i,j in product(range(len(a)), repeat=2):
    ...

rawDescription: looping over list of lists without nesting too much

description: Looping over list of lists without nesting too much


code:
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename = "report.xls"'
response = render_to_response("facturas.html",context_instance=RequestContext(request), content_type='application/vnd.ms-excel')
book.save(response)
return response

rawDescription: Not the right download type of file...Django


code:
newlist = []
for index, item in enumerate(timelist):
    if index % 24 == 0:
        newlist.append(item)
    else:
        newlist.append('')
ax.set_xticklabels(newlist, rotation=17)

rawDescription: how to evenly set limited number of label matplotlib python

description: Evenly set limited number of label matplotlib python


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

Base= declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    data = Column(String)
    otherdata = Column(String)

@event.listens_for(A, "before_insert")
def gen_default(mapper, connection, instance):
    instance.data = "Some default %s" % instance.otherdata

e = create_engine("sqlite://")
Base.metadata.create_all(e)

a = A(otherdata="some other data")
s = Session(e)
s.add(a)
s.commit()

assert a.data == "Some default some other data"

rawDescription: Object-based default value in SQLAlchemy declarative


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

x1 = np.random.randint(-5, 5, 50)
x2 = np.random.randn(20)

fig = plt.figure(figsize=(8,6))  # sets the window to 8 x 6 inches

# left, bottom, width, height (range 0 to 1)
# so think of width and height as a percentage of your window size
big_ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
small_ax = fig.add_axes([0.52, 0.15, 0.3, 0.3]) # left, bottom, width, height (range 0 to 1)

big_ax.fill_between(np.arange(len(x1)), x1, color='green', alpha=0.3)
small_ax.stem(x2)

plt.setp(small_ax.get_yticklabels(), visible=False)
plt.setp(small_ax.get_xticklabels(), visible=False)
plt.show()

rawDescription: matplotlib chart area vs plot area

description: Matplotlib chart area vs plot area


code:
segments = [Segment() for i in range(MaxN)]
for seg in segments:
    seg.left = input()
    seg.right = input()

rawDescription: Array of class objects in Python 3.4

description: Array of class objects in Python 3.4


code: match = re.findall('arfcn: (\d*)(?:,bsic: (\d*))?,dBm: (-\d*)', data)

rawDescription: Python regexp multiple expressions with grouping


code:
import csv
with open("mycsv.csv", "rb") as infile, open("newcsv.csv", "wb") as outfile:
    reader = csv.reader(infile, delimiter="\t")
    writer = csv.writer(outfile, delimiter="\t", quoting=csv.QUOTE_ALL)
    # Now you can remove all the newlines within fields
    # and write them back to a new CSV file:

    for row in reader:
        writer.writerow([field.replace("\n", " ") for field in row])

rawDescription: Python script using regex (re) to remove extra newlines


code:
if new_game_x_pos == True and new_game_y_pos == True:
    draw_main_menu_ng()
    return

rawDescription: Pygame: Weird blitting bug

description: Pygame: Weird blitting bug


code:
def get_next_filename(existing_filename):

    prefix = existing_filename.split("_")[0] # get string prior to _
    int_string = existing_filename.split("_")[-1].split(".")[0] # pull out the number as a string so we can extract an integer value as well as the number of characters
    try:
        extension = existing_filename.split("_")[-1].split(".")[-1] # check for extension
    except:
        extension = None
    int_current = int(int_string) # integer value of current filename
    int_new = int(int_string) + 1 # integer value of new filename
    digits = len(int_string) # number of characters/padding in name
    formatter = "%0"+str(digits)+"d" # creates a statement that int_string_new can use to create a number as a string with leading zeros
    int_string_new = formatter % (int_new,) # applies that format
    new_filename = prefix+"_"+int_string_new # put it all together
    if extension: # add the extension if present in original name
        new_filename += "."+extension
    return new_filename

# since we only want to do this when the file already exists, check if it exists and execute function if so

our_filename = 'file_0026.txt'
while os.path.isfile(our_filename):
    our_filename = get_next_filename(our_filename) # loop until a unique filename found

rawDescription: Python - Concatenate a variable into string format


code:
import re
mystr = "This house is small. That house is big."
for token in re.findall(r"([\w]+|[^\s])", mystr):
    print (token)
    if re.match(r"[.!?]", token):
        print()

rawDescription: Python: regexp sentence segmentation

description: Python: regexp sentence segmentation


code:
def clean(self):
    super(MyUserAdminForm, self).clean()
    # more cleaning

rawDescription: Django - Keeping the original method's work and add new custom validation


code:
iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24])

rawDescription: Retrieving network mask in Python

description: Retrieving network mask in Python


code:
ps.wait()
t.join()

rawDescription: Tkinter GUI stops responding when launched


code:
from django.db.models import Q

queryset = Evento.objects.filter(Q(mod__isnull=True, aprobado=True) | Q(mod__isnull=False, mod__activo=False))

rawDescription: How to do a complex lookup like this?

description: Do a complex lookup like this


rawDescription: python re.sub() with pair or characters

description: Python re.sub() with pair or characters


code:
class C(object): pass
z = C()
z.blah = "xyzzy"
dir(z)

rawDescription: Ruby Mash equivalent in Python?

description: Ruby Mash equivalent in Python


code:
myWords = random.sample(wordList, 3) # returns a list
myWords_query = ' '.join(myWords) # so turn it into a space separated string
...
browser.fill('search_query', myWords_query)

rawDescription: YouTube Python Game

description: YouTube Python Game


code:
#make sure DNS is running before you start
if not natlink.isNatSpeakRunning():
  raiseError('must start up Dragon NaturallySpeaking first!')
  shutdownServer()
  return
#connect to natlink and load the grammer it's supposed to recognize
natlink.natConnect()
loggerGrammar = LoggerGrammar()
loggerGrammar.initialize()
if natlink.getMicState() == 'off':
   natlink.setMicState('on')
userName = 'Danni'
natlink.openUser(userName)
#natlink.waitForSpeech() continuous loop waiting for input.
#Results are sent to gotResultsObject method of the logger grammar
natlink.waitForSpeech()
natlink.natDisconnect()

rawDescription: Dragon NaturallySpeaking Programmers

description: Dragon NaturallySpeaking Programmers


code:
import Tkinter as tk

class Screen(tk.Frame):
    '''This defines one "screen"'''

    def __init__(self, parent, label):
        tk.Frame.__init__(self, parent)
        l = tk.Label(self, text=label)
        self.entry = tk.Entry(self)
        l.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x", padx=20)
        self.entry.insert(0, "this is the entry for " + label)

class Example(tk.Frame):
    '''This is the main application'''

    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        # an array of screens, and a pointer to the current screen
        self.current = None
        self.screens = []

        # the basic layout is a toolbar on top and
        # a container on the bottom which will hold all
        # of the "screens"
        container = tk.Frame(self)
        toolbar = tk.Frame(self)
        toolbar.pack(side="top", fill="x")
        container.pack(side="bottom", fill="both", expand=True)

        # create 10 "screens" that we can cycle through
        for i in range(10):
            screen = Screen(container, "screen %s" % i)
            screen.place(x=0, y=0, anchor="nw", relwidth=1.0, relheight=1.0)
            self.screens.append(screen)

        # create a "next" button to cycle through the screens
        next = tk.Button(toolbar, text="next", command=self.next)
        next.pack(side="right")

        # start by showing screen zero
        self.show(0)

    def show(self, index):
        self.current = index
        self.screens[self.current].lift()

    def next(self):
        '''Show the next screen, or screen zero if at the end'''
        if self.current == len(self.screens)-1:
            self.show(0)
        else:
            self.show(self.current+1)

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("600x400")
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: In Tkinter How do I make a child window that closes the parent but shows all the widgets in the child?


code: list("Word to Split")

rawDescription: Is there a function in python to split a word into a list?


code:
import itertools

G = [0, 1, 2, 3, 4, 5] # or whatever your group might be

def is_associative(x, y, z):
    if (x*y)*z == x*(y*z):
        return True
    return False

xyz = itertools.product(G, repeat=3)

for three in xyz:
    if not is_associative(*three):
         print("associativity fails for %s, %s, %s") % three

rawDescription: Determine if (*,G) forms an associative group in group theory


code:
import Image
im=Image.open("test.bmp")
im.size
im.getbbox()
im2=im.crop(im.getbbox())
im2.size
im2.save("test2.bmp")

rawDescription: Crop a PNG image to its minimum size

description: Crop a PNG image to its minimum size


code:
from django.db import models

class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        return self.text[:50] + ("..." if len(self.text) > 50 else "")

rawDescription: Exercise from the book Python CRASH COURSE: Exercise 18-2


code:
import gc
some_list = []
gc.get_referents(some_list)
some_list.append(some_list)
some_list[0] is some_list
gc.get_referents(some_list)

rawDescription: What happens if you append a list to itself?


code:
from sympy import symarray

m1 = symarray('', 2)
m1[0] = [1, 0]

rawDescription: Declare list elements as symbols sympy python


code:
heatmap = [

    [0.0, (0, 0, 0)],
    [1.00, (0.8, 0.0, 1.0)],
]

# x y coordinates of starting point for gradient
start_x = 0
start_y = 0

for x in range(im.size[0]):
    for y in range(im.size[1]):
        # taxicab distance for linear gradient
        dist = math.fabs(start_x - x) + math.fabs(start_y - y)
        # for circular gradient
        # dist = math.sqrt(math.pow(start_x - x,2) + math.pow(start_y - y,2))
        start_rgb = heatmap[0][1]
        end_rgb = heatmap[1][1]
        dist = dist / (im.size[0] + im.size[1])
        # for circular gradient
        # dist = dist / (math.sqrt(math.pow(im.size[0],2) + math.pow(im.size[1],2))
        r, g, b = map(lambda x,y: x+y, map(lambda a: a*dist, start_rgb), map(lambda b: b*dist, end_rgb))
        r, g, b = [int(256 * v) for v in (r, g, b)]
        ld[x, y] = r, g, b

rawDescription: Python change gradient to start diagonally


code:
from collections import Counter
c=Counter()

with open('Reviews') as f:
    for line in f:
        for word in line.split(" "):
            c[word]+=1

rawDescription: Reading text file into python

description: Reading text file into python


code:
def integers(blk_size=100):
    x = arange(0, blk_size)
    while True:
        yield x
        yield -x -1
        x += blk_size

#
# For convergent summation
# on not necessarily finite sequences
# processes in blocks which can be any size
# shape that the function can handle
#
def converge_sum(f, x_strm, eps=1e-5, axis=0):
    total = sum(f(x_strm.next()), axis=axis)
    for x_blk in x_strm:
        diff = sum(f(x_blk), axis=axis)
        if abs(linalg.norm(diff)) <= eps:
            # Converged
            return total + diff
        else:
            total += diff

rawDescription: Infinite Summation in Python

description: Infinite Summation in Python


code:
for offset in range(longLength):
    subInt = longInt // 10**(longLength - offset - 1) % 10**(shortLength)

rawDescription: How to loop through an integer and extract another shorter integer (from left to right)?

description: Loop through an integer and extract another shorter integer (from left to right)


code:
y = np.empty_like(x)
y[:-1] = np.diff(x, axis=0) / dx
y[-1] = -x[-1] / dx

rawDescription: Partial derivative in Python

description: Partial derivative in Python


code:
which = input('Which package would you like?: ')

with open('packages.txt') as f:
    i = 1
    for line in f:
        if i == (int(which)):
            break
        i += 1
print (line)

rawDescription: Print specific line in python?

description: Print specific line in python


code:
...
import StringIO

buf = open("test.jpg", "rb").read()
# buf = get_image_data()
sbuf = StringIO.StringIO(buf)

image = wx.ImageFromStream(sbuf)
...

rawDescription: How do I create a wx.Image object from in-memory data?

description: Create a wx.Image object from in-memory data


code:
import itertools
x = list(itertools.product([1,2,3],[4,5],[6,7,8]))

rawDescription: How to iterate few elements in Python arrays?

description: Iterate few elements in Python arrays


rawDescription: django model: get primary key of the model just created

description: Django model: get primary key of the model just created


code:
indef = Integral(x)
to_be_integrated, (free_var,) = indef.args
definite = Integral(to_be_integrated, (free_var, 1, 2))

rawDescription: SymPy - apply limits to an indefinite integral


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

try:
    element = WebDriverWait(browser, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, ".cashout"))
    )
    element.click()
except TimeoutException:
    browser.find_element_by_css_selector('#start_game').click()

rawDescription: Python Selenium NoSuchElementException

description: Python Selenium NoSuchElementException


code:
import datetime
from dateutil.relativedelta import relativedelta

expires = datetime.datetime.now() - relativedelta(hours=7)

rawDescription: How to get strftime 7 hours in the past?

description: Get strftime 7 hours in the past


code:
import sys
from PyQt4.QtGui import QApplication, QSlider, QMainWindow

class Window(QMainWindow):
    def __init__(self, parent = None):
        super(Window, self).__init__(parent)

        slider = QSlider()
        slider.setMinimum(0)
        slider.setMaximum(100)

        slider.setTickInterval(20)
        slider.setSingleStep(20)

        self.setCentralWidget(slider)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = Window()
    window.show()

    sys.exit(app.exec_())

rawDescription: QSlider stepping?

description: QSlider stepping


code:
fileName = "file_Iter" + str(It) + "_V_" +str(V)+".txt"
file_out=io.open(fileName, 'w')
os.system("echo - START RUN $(LANG=en_US date +%b_%d_%Y_%k_%M)- | tee -a " + fileName)

rawDescription: write to file with tee command in python

description: Write to file with tee command in python


code:
from flask import json, jsonify

return jsonify(**json.loads(json.htmlsafe_dumps(obj)))

rawDescription: Flask jsonify: how to escape characters

description: Flask jsonify: how to escape characters


code:
seen = set()
for seq in sequences:
    tup = tuple(sequence) # you only need to make a tuple if seq is not already hashable
    if tup not in seen:
        seen.add(tup)

        # do whatever you want with seq here, it has not been seen before

    else:
        pass # if you want to do something with duplicated sequences, do it here

rawDescription: maintaining hierarchically sorted lists in python

description: Maintaining hierarchically sorted lists in python


code:
from django.db.models import Q
Guild.objects.filter(Q(guild_one__tournament=t) |\
Q(guild_two__tournament=t)).values_list('name', flat=True)

rawDescription: Django model with relationships

description: Django model with relationships


rawDescription: Work with twitter JSON responses

description: Work with twitter JSON responses


code:
import subprocess

subprocess.call(["xdotool", "mousemove", "945", "132"])

rawDescription: How can I use xdotool from within a python module/script?

description: Use xdotool from within a python module/script


code:
from datetime import datetime as DateTime
import requests
import json

URL = "https://myUrl.xxx"

message = {
    "Request": {
        "MessageID": "xxxx",
        "MessageDateTime": DateTime.now().isoformat(),
        "SourceSystem": "xxxx",
    }
}

response = requests.post(URL, data=json.dumps(message), verify=False, headers={"Content-Type":"application/json"})
data = response.json()

rawDescription: Python HTTP Request to replace bash curl


code:
from numpy.random import rand, randint
from matplotlib import pyplot as plt
n = 1000
# Generate random data
data = rand(n, 2)
# Make a random array to mimic datingLabels
labels = randint(1, 4, n)
# Separate the data according to the labels
data_1 = data[labels==1]
data_2 = data[labels==2]
data_3 = data[labels==3]
# Plot each set of points separately
# 's' is the size parameter.
# 'c' is the color parameter.
# I have chosen the colors so that they match the plot shown.
# With each set of points, input the desired label for the legend.
plt.scatter(data_1[:,0], data_1[:,1], s=15, c='r', label="label 1")
plt.scatter(data_2[:,0], data_2[:,1], s=30, c='g', label="label 2")
plt.scatter(data_3[:,0], data_3[:,1], s=45, c='b', label="label 3")
# Put labels on the axes
plt.ylabel("ylabel")
plt.xlabel("xlabel")
# Place the Legend in the plot.
plt.gca().legend(loc="upper left")
# Display it.
plt.show()

rawDescription: Python: How to create a legend using an example


code:
fig, axes = plt.subplots(nrows=1, ncols=4, sharex=True, sharey=True)
for ax in axes:
    ax.plot(range(20),range(10,30))
    plt.setp(ax.get_yticklabels(),visible=True) # set property

rawDescription: matplotlib multiple plots - show yticks for all subplots

description: Matplotlib multiple plots - show yticks for all subplots


code:
#! /usr/bin/env python3

from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2

# Function to get rid of padding
def clean(x):
    return x[:-x[-1]].decode('utf8')

# replace with your encrypted_value from sqlite3
encrypted_value = ENCRYPTED_VALUE

# Trim off the 'v10' that Chrome/ium prepends
encrypted_value = encrypted_value[3:]

# Default values used by both Chrome and Chromium in OSX and Linux
salt = b'saltysalt'
iv = b' ' * 16
length = 16

# On Mac, replace MY_PASS with your password from Keychain
# On Linux, replace MY_PASS with 'peanuts'
my_pass = MY_PASS
my_pass = my_pass.encode('utf8')

# 1003 on Mac, 1 on Linux
iterations = 1003

key = PBKDF2(my_pass, salt, length, iterations)
cipher = AES.new(key, AES.MODE_CBC, IV=iv)

decrypted = cipher.decrypt(encrypted_value)
print(clean(decrypted))

rawDescription: Decrypting Chromium cookies

description: Decrypting Chromium cookies


code:
W = W.reshape(8,10)
W.shape

rawDescription: Convert 1D array into numpy matrix

description: Convert 1D array into numpy matrix


code:
if len(x)==len(y):
   return min(x,y)

rawDescription: Compare strings based on alphabetical ordering


rawDescription: Python: Renaming first 5 files of a folder


code:
handle = open(sys.argv[1])
with open('protparams.csv', 'w') as fp:
    writer = csv.writer(fp, delimiter=',')
    writer.writerow(['heading1','heading2','heading3'])
    for record in SeqIO.parse(handle, "fasta"):
            seq = str(record.seq)
            X = ProtParam.ProteinAnalysis(seq)
            data = [seq,X.get_amino_acids_percent(),X.aromaticity(),X.gravy(),X.isoelectric_point(),X.secondary_structure_fraction(),X.molecular_weight(),X.instability_index()]
            writer.writerow(data)

rawDescription: generate a header row using python's csv.writer

description: Generate a header row using python's csv.writer


code:
import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

rawDescription: Custom id field in Django model

description: Custom id field in Django model


code:
from ftplib import FTP
ftpretr = FTP('get.ftp.com')   # connect to host, default port
ftpretr.login()               # user anonymous, passwd anonymous@
ftpretr.retrbinary('RETR README', open('README', 'wb').write)
ftpretr.quit()
ftpsend = FTP('send-to.ftp.com','login','password')
ftpsend.storbinary('STOR todo.txt', open('README','rb'))
ftpsend.quit()

rawDescription: how to sync two ftp server by python

description: Sync two ftp server by python


code:
angle_box_2d
angle_contains_ray_2d
angle_deg_2d
angle_half_2d # MLM: double *
angle_rad_2d
angle_rad_3d
angle_rad_nd
angle_turn_2d
anglei_deg_2d
anglei_rad_2d
annulus_area_2d
annulus_sector_area_2d
annulus_sector_centroid_2d # MLM: double *
ball_unit_sample_2d # MLM: double *
ball_unit_sample_3d # MLM: double *
ball_unit_sample_nd # MLM; double *
basis_map_3d #double *
box_01_contains_point_2d
box_01_contains_point_nd
box_contains_point_2d
box_contains_point_nd
box_ray_int_2d
box_segment_clip_2d
circle_arc_point_near_2d
circle_area_2d
circle_dia2imp_2d
circle_exp_contains_point_2d
circle_exp2imp_2d
circle_imp_contains_point_2d
circle_imp_line_par_int_2d
circle_imp_point_dist_2d
circle_imp_point_dist_signed_2d
circle_imp_point_near_2d
circle_imp_points_2d # MlM: double *
circle_imp_points_3d # MLM: double *
circle_imp_points_arc_2d
circle_imp_print_2d
circle_imp_print_3d
circle_imp2exp_2d
circle_llr2imp_2d # MLM: double *
circle_lune_area_2d
circle_lune_centroid_2d # MLM; double *
circle_pppr2imp_3d

rawDescription: Fast python GIS library that supports Great Circle Distance and polygon


code:
# note the single backslash in \n
key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAwK(...)J90XccMb+iro=\n-----END RSA PRIVATE KEY-----\n"
keyfile = StringIO.StringIO(key)
key = paramiko.RSAKey.from_private_key(keyfile)

rawDescription: how to use a paramiko.PKey() in the .connect() method?

description: Use a paramiko.PKey() in the .connect() method


code: indices.sort(key = lambda x:mylist[x], reverse = True)

rawDescription: sorting list of indices

description: Sorting list of indices


code:
import sqlite3
import pandas.io.sql as sql
con = sqlite3.connect('database.db')
table = sql.read_frame('select * from some_table', con)
table.to_csv('output.csv')

rawDescription: Sqlite3 / python - Export from sqlite to csv text file does not exceed 20k


code:
import urllib
from bs4 import BeautifulSoup

url = "http://www.cnn.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

rawDescription: BeatifulSoup4 get_text still has javascript


code: propertiesList = Property.objects.filter(**{i+"__title__in": amn})

rawDescription: Python - setattr function without self parameter, 2 parameters instead of 3


code: [x for x in mylist2 if x[:2] not in mylist1]

rawDescription: how to find unmatch list which are content of another list, from comparision of list of lists(python)

description: Find unmatch list which are content of another list, from comparision of list of lists(python)


code:
from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    # Executes every weekday morning at 7:30 A.M
    'weekdays': {
        'task': 'tasks.A',
        'schedule': crontab(hour=7, minute=30, day_of_week='1-5'),
        'args': (x1, y1),
    },
    # Executes saturday morning at 4:00 A.M
    'saturday': {
        'task': 'tasks.B',
        'schedule': crontab(hour=7, minute=30, day_of_week='sat'),
        'args': (x1, y1),
    },
    # Executes sunday morning at 2:15 A.M
    'sunday': {
        'task': 'tasks.A',
        'schedule': crontab(hour=2, minute=15, day_of_week='sun'),
        'args': (x2, y2),
    },
}

rawDescription: How to schedule weekday-aware jobs in celery

description: Schedule weekday-aware jobs in celery


code:
import os
import pty
import select
import termios

child_pid, child_fd = pty.fork()

if not child_pid: # child process
    os.execv("/path/to/command", ["command", "arg1", "arg2"])

# disable echo
attr = termios.tcgetattr(child_fd)
attr[3] = attr[3] & ~termios.ECHO
termios.tcsetattr(child_fd, termios.TCSANOW, attr)

while True:
    # check whether child terminal has output to read
    ready, _, _ = select.select([child_fd], [], [])

    if child_fd in ready:
        output = []

        try:
            while True:
                s = os.read(child_fd, 1)

                # EOF or EOL
                if not s or s == "\n":
                    break

                # don't store carriage returns (no universal line endings)
                if not s == "\r":
                    output.append(s)
        except OSError: # this signals EOF on some platforms
            pass

        if output.find("Enter password:") > -1:
            os.write(child_fd, "password")

rawDescription: How can I interact with another program in Python?

description: Interact with another program in Python


code:
import tempfile
import os
for idx in xrange(1024 + 1):
    outfd, outsock_path = tempfile.mkstemp()
    outsock = os.fdopen(outfd,'w')
    outsock.close()

rawDescription: How do I close the files from tempfile.mkstemp?

description: Close the files from tempfile.mkstemp


code:
import csv

input_csv = 'aliases.csv'
output_csv = 'output.csv'

def first_word(value):
    return value.split(' ', 1)[0]

with open(input_csv, 'r') as infile:
    # Specify the fieldnames in your aliases CSV
    input_fields = ('name', 'number')

    # Set up the DictReader, which will read the file into an iterable
    # where each row is a {column_name: value} dictionary
    reader = csv.DictReader(infile, fieldnames=input_fields)

    # Now open the output file
    with open(output_csv, 'w') as outfile:
        # Define the new 'flag' field
        output_fields = ('name', 'number', 'flag')
        writer = csv.DictWriter(outfile, fieldnames=output_fields)

        # Write the column names (this is a handy convention seen elsewhere on SO)
        writer.writerow(dict((h, h) for h in output_fields))

        # Skip the first row (which is the column headers) and then store the
        # first row dictionary
        next(reader)
        first_row = next(reader)

        # Now begin your iteration through the input, writing all fields as they
        # appear, but using some logic to write the 'flag' field
        # This is where the dictionary comes into play - 'row' is actually a
        # dictionary, so you can use dictionary syntax to assign to it
        for next_row in reader:
            # Set up the variables for your comparison
            first_name = first_word(first_row['name'])
            next_name = first_word(next_row['name'])
            first_id = first_row['number']
            next_id = next_row['number']

            # Compare the current row to the previous row
            if first_name == next_name and first_id != next_id:
                # Here we are adding an element to our row dictionary - 'flag'
                first_row['flag'] = 'Y'
            # Now we write the entire first_row dictionary to the row
            writer.writerow(first_row)

            # Change the reference, just like you did
            first_row = next_row

rawDescription: Output to CSV: Change Existing Code to Add "Flag" Column Instead


code:
df = pd.DataFrame({'a': [2, 4, 5], 'b': [3, 9, 4]}, dtype=np.float) # a DataFrame
df
df = df.div(df.loc[0]) # normalise DataFrame and bind back to df
df

rawDescription: Normalize each column of the Pandas Dataframe


code:
word_dict = {'et': ['horse','dog'], 'ft': ['horses','dogs']}
dict(word_dict.values())

rawDescription: Create a word replacement dictionary from list of tuples


code:
class TicketForm(forms.Form):

  Type = Type.GetTicketTypeField()

  def __init__(self, ticket, *args, **kwargs):
    super(TicketForm, self).__init__(*args, **kwargs)
    self.fields['state'] = State.GetTicketStateField(ticket.Type)

rawDescription: Django: Overriding __init__ for Custom Forms


code: [f[0:21] for f in file_list_zvec]

rawDescription: Comparing two lists of filenames that are not identical


code:
import dis
l = [1,2,3]
m = [4,5,6]
def f1(l, m):
    l.extend(m)
def f2(l,m):
    l += m
dis.dis(f1)
dis.dis(f2)

rawDescription: Is `extend` faster than `+=`?

description: Is `extend` faster than `+=`


code:
from matplotlib.pyplot import cm
imshow(A, interpolation='nearest', cmap=cm.Blues)

rawDescription: Matplotlib heatmap with one color

description: Matplotlib heatmap with one color


code:
from collections import Counter
counter = Counter()

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']
deduped = []
for name in dup_list:
    new = name + str(counter[name]) if counter[name] else name
    counter.update({name: 1})
    deduped.append(new)

rawDescription: Python 2.7: Dedup list by adding suffix

description: Python 2.7: Dedup list by adding suffix


code:
from itertools import combinations
lst = [1, 2, 3]
list(combinations(lst, 2))
[list(x) for x in combinations(lst, 2)]

rawDescription: generate all combinations from 3 numbers

description: Generate all combinations from 3 numbers


code:
def f(x):
    result = []
    for part in x.split(','):
        if '-' in part:
            a, b = part.split('-')
            a, b = int(a), int(b)
            result.extend(range(a, b + 1))
        else:
            a = int(part)
            result.append(a)
    return result

f('1,2,5-7,10')

rawDescription: How to convert numeric string ranges to a list in Python

description: Convert numeric string ranges to a list in Python


code:
def match(path, actual):
    path = path.strip('/').split('/')
    actual = iter(actual.strip('/').split('/'))
    for pathitem in path:
        for item in actual:
            if pathitem == item:
                break
        else:
            # The for-loop never breaked, so pathitem was never found
            return False
    return True

q1 = '/foo/baz/myfile.txt'
q2 = '/bar/foo/myfile.txt'
p1 = '/foo/bar/bar/myfile.txt'
p2 = '/bar/bar/baz/myfile.txt'
actual = '/foo/bar/baz/bar/myfile.txt'

print(match(q1, actual))
# True

print(match(q2, actual))
# False

print(match(p1, actual))
# True

print(match(p2, actual))
# False

rawDescription: Matching incompletely qualified paths

description: Matching incompletely qualified paths


code:
import re
myre = re.compile("(?<!:)//")
uniprotFileList = myre.split(uniprotFileContent)

rawDescription: split a file based on string

description: Split a file based on string


code:
with multiprocessing.Lock():
    ...

rawDescription: Can I acquire multiprocessing's Lock in a with statement?

description: Acquire multiprocessing's Lock in a with statement


code:
import os

files_in_folder_1 = [os.path.join(path1, f) for f in os.listdir(path1) if os.path.isfile(os.path.join(path1, f))]

files_in_folder_2 = [os.path.join(path2, f) for f in os.listdir(path2) if os.path.isfile(os.path.join(path2, f))]

for file1, file2 in zip(files_in_folder_1, files_in_folder_2):
    with open(file1) as f1, open(file2) as f2:
        ...

rawDescription: Loop over multiple .csv files python/pandas


code: sum([pair[0] for pair in list_of_pairs])

rawDescription: How do I sum the first value in each tuple in a list of tuples in Python?

description: Sum the first value in each tuple in a list of tuples in Python


code:
searchdata = essearch.search(index=indexname, body= {
    "query": {
        "filtered": {
          "query": {
            "query_string": {
              "query": "name:fred"
            }
          },
          "filter": {
            "bool": {
              "must": [

                {
                  "exists": {
                    "field": "fieldname"
                  }
                },
                {
                  "exists": {
                    "field": "secondfieldname"
                  }
                }

              ]
            }
          }
        }
      },
      "size": 5000,
      "sort": [
         {
            "loggeddate": {
               "order": "desc"
            }
         }
      ]
    }
           )

rawDescription: Elasticsearch build dynamic query - python


code:
def ByteCountingStreamReader(stream):
  fr = stream.read
  stream.count = 0

  def inner(size=-1):
      s = fr(size)
      stream.count += len(s)
      return s

  stream.read=inner
  return stream

# testing it
myStream = open('/etc/hosts', 'r')
with ByteCountingStreamReader(myStream) as f:
  while True:
      s = f.read(20)
      if s == '':
          break
      print (s, end='')

  print (f.count)

rawDescription: How to implement a ByteCountingStreamReader?

description: Implement a ByteCountingStreamReader


code:
@app.route('/download')
@login_required
def download():
    "Export a CSV of all sales data"
    purchases = Purchase.query.all()
    csvfile = cStringIO.StringIO()
    headers = [
        'uuid',
        'recipient_name',
        'recipient_email',
        'shipping_street_address_1',
        'shipping_street_address_2',
        'shipping_city',
        'shipping_state',
        'shipping_zip',
        'purchaser_name',
        'purchaser_email',
        'personal_message',
        'sold_at',
        'coupon_used'
    ]
    rows = []
    for purchase in Purchase.query.all():
        rows.append(
            {
                'uuid': purchase.uuid,
                'recipient_name': purchase.recipient_name,
                'recipient_email': purchase.recipient_email,
                'shipping_street_address_1': purchase.shipping_street_address_1,
                'shipping_street_address_2': purchase.shipping_street_address_2,
                'shipping_city': purchase.shipping_city,
                'shipping_state': purchase.shipping_state,
                'shipping_zip': purchase.shipping_zip,
                'purchaser_name': purchase.purchaser_name,
                'purchaser_email': purchase.purchaser_email,
                'personal_message': purchase.personal_message,
                'sold_at': purchase.sold_at.strftime('%c'),
                'coupon_used': purchase.coupon_used
            }
        )
    writer = csv.DictWriter(csvfile, headers)
    writer.writeheader()
    for row in rows:
        writer.writerow(
            dict(
                (k, v.encode('utf-8') if type(v) is unicode else v) for k, v in row.iteritems()
            )
        )
    csvfile.seek(0)
    return send_file(csvfile, attachment_filename='sales_export.csv', as_attachment=True)

rawDescription: How to stream CSV from Flask via sqlalchemy query?

description: Stream CSV from Flask via sqlalchemy query


code: re.sub(r'#\[(.+?)\]', lambda m:'<a style="color:%s">' % colors[m.group(1)], s)

rawDescription: Python Regex String Replace

description: Python Regex String Replace


code:
from threadlocals.threadlocals import get_current_user

class SummaryAdmin(admin.ModelAdmin):
    list_display = ('date', 'display_user', 'from_till', 'hours_worked',
                    'productivity_status',)
    list_filter = ['date', 'user_crm']

    def display_user(self, obj):
       current_user = get_current_user()
       ...

rawDescription: How to get logged in user modelAdmin callable in django

description: Get logged in user modelAdmin callable in django


code:
from Tkinter import *
root = Tk()
Window = Frame(root)
TextWidget = Text(Window)
TextWidget.pack()
Window.pack()
TextWidget.focus_set()
root.mainloop()

rawDescription: How do I give focus to a python Tkinter text widget?

description: Give focus to a python Tkinter text widget


code:
from IPython.display import HTML
HTML(filename='myhtml.html')

rawDescription: Import html to ipython notebook file

description: Import html to ipython notebook file


code:
def get_queryset(self):
    """
    Get the list of items for this view. This must be an interable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

rawDescription: Django - queryset vs model in Generic View


code:
class MyView(QtGui.QGraphicsView):
    def mousePressEvent(self, event):
        if event.button() == Qt.MidButton:
            self.__prevMousePos = event.pos()
        else:
            super(MyView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MidButton:
            offset = self.__prevMousePos - event.pos()
            self.__prevMousePos = event.pos()

            self.verticalScrollBar().setValue(self.verticalScrollBar().value() + offset.y())
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() + offset.x())
        else:
            super(MyView, self).mouseMoveEvent(event)

rawDescription: How to scrolling QGraphicsScene in QGraphicsView by middle mouse?

description: Scrolling QGraphicsScene in QGraphicsView by middle mouse


code:
from random import sample

sample(range(0, 100), 10)

rawDescription: How to choose 10 different integers from range (0, 99)

description: Choose 10 different integers from range (0, 99)


code: arr = list(map(int, input.split()))

rawDescription: How to read an array of integers from single line of input in python3

description: Read an array of integers from single line of input in python3


rawDescription: Pandas preserve fixed-length char field in structured ndarray


code:
myList = ['apples', 'oranges', 'bananas']

newString = 'peach'

position = 1

myList.insert(position, newString)

rawDescription: Appending new items to a list

description: Appending new items to a list


code:
import collections

with open('topics.txt') as f:
    d = collections.defaultdict(list)
    for line in f:
        value, *keys = line.strip().split('~')
        for key in filter(None, keys):
            d[key].append(value)

rawDescription: how to create a dictionary from a file?

description: Create a dictionary from a file


code:
from numba import njit
import numpy as np

@njit
def update_array(array, myarray):
    elements = myarray.shape[0]
    for i in range(elements):
        array[myarray[i][0]][myarray[i][1]] += 1
    return array

myarray = np.array([[0, 0], [0, 1], [1, 1],
                    [1, 2], [2, 2], [1, 3]])

# Calculate the size of the numpy array that replaces the dict:
lens = np.max(myarray, axis=0) # Maximum values
array = np.zeros((lens[0]+1, lens[1]+1)) # Create an empty array to hold all indexes in myarray
update_array(array, myarray)

rawDescription: numba @njit to update a big dict

description: Numba @njit to update a big dict


code:
import matplotlib.pyplot as plt
plt.bar(range(0,100), x)
plt.show()

rawDescription: python plot simple histogram given binned data

description: Python plot simple histogram given binned data


code:
def OnDropFiles(self, x, y, filenames):
    mouse = wx.GetMouseState()
    if mouse.CmdDown():
        self.frame.paths += filenames
    else:
        self.frame.paths = filenames
    self.frame.draw_figure()

rawDescription: Drag and drop with modifiers in wxpython


code:
# bad habit to be using the old style class definition (i.e. `class Foo:`)
# the `@property` decorator wont work if you use the old style

class Sync(object):

    def __init__(self, name, value, *dependants):
        """Sync the attribute `name` on all `dependants` when `self.value` is updated"""
        self._name = name
        self._value = value
        self._updating = False
        self._dependants = list(dependants)
        self._update_dependants()

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, x):
        if x != self._value:
            self._value = x
            self._update_dependants()

    def _update_dependants(self):
        self._updating = True
        for d in self._dependants:
            if getattr(d, self._name) != self.value:
                if isinstance(d, Sync):
                    if not d._updating:
                        setattr(d, self._name, self.value)
                else:
                    setattr(d, self._name, self.value)
        self._updating = False

    def add_dependant(self, other):
        self._dependants.append(other)
        self._update_dependants()

    def del_dependnant(self, other):
        self._dependants.remove(other)

    def __repr__(self):
        return "Sync('"+self._name+"': "+repr(self.value)+")"

    def __eq__(self, other):
        if isinstance(other, Sync):
            return self.value == other.value
        else:
            return self.value == other

    def __ne__(self, other):
        return not self.__eq__(other)

s1 = Sync('value', 2)
s2 = Sync('value', 1)
print('setup the Sync objects:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))

s1.add_dependant(s2)
s2.add_dependant(s1)
print('add sync objects as dependants of each other:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))

s1.value += 1
print('check that value changes transfer from one to the other:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))

rawDescription: How do I change the value of an object's attribute that's a reference to another object's attribute?

description: Change the value of an object's attribute that's a reference to another object's attribute


code:
processHeader(f.readline())
for line in f:
    processBody(line)

rawDescription: How to treat the first line of a file differently in Python?

description: Treat the first line of a file differently in Python


code:
x = int(input())
if x == 1:
   print("1st")
elif x == 2:
   print("2nd")
elif x == 3:
   print("3rd")
else:
   print(str(x)+"th")

rawDescription: Python Logic - Simplify/more efficient multiple if elif statements


code:
def process(self, formdata=None, obj=None, **kwargs):
    if formdata is not None and not hasattr(formdata, 'getlist'):
        if hasattr(formdata, 'getall'):
            formdata = WebobInputWrapper(formdata)
        else:
            raise TypeError("formdata should be a multidict-type wrapper that supports the 'getlist' method")

    for name, field, in iteritems(self._fields):
        if obj is not None and hasattr(obj, name):
            field.process(formdata, getattr(obj, name))
        elif name in kwargs:
            field.process(formdata, kwargs[name])
        else:
            field.process(formdata)

rawDescription: Unpacking Argument Lists and Instantiating WTForms objects from web.py


code:
for item in infile_list:
    infile = file(item)
    outfile = file(item + 'parsed.txt','w')
    p = subprocess.call(['/home/myfolder/ParZu/parzu', '-l', 'tagged'], stdin=infile, stdout=outfile)
    infile.close()
    outfile.close()

rawDescription: include shell command into program python

description: Include shell command into program python


rawDescription: Neo4j and django models

description: Neo4j and django models


code:
local = dict(page=page, name=name, save_url=save_url, title='add new',
     url='/new', points=points, num_badges=badges)
local.update(retrieve_common_information(request))
return local

rawDescription: How can I share a selected amount of data with all my templates in pyramid?

description: Share a selected amount of data with all my templates in pyramid


code:
class FormSetWithInstances(BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.instances = kwargs.pop('instances')
        super(FormSetWithInstances, self).__init__(*args, **kwargs)

    def get_form_kwargs(self, index):
        form_kwargs = super(FormSetWithInstances, self).get_form_kwargs(index)
        if index < len(self.instances):
            form_kwargs['instance'] = self.instances[index]
        return form_kwargs

rawDescription: Set instance of each form in Django model formset


code: from functools import reduce

rawDescription: what functional tools remain in Python 3k?

description: What functional tools remain in Python 3k


code:
class ArticleAdmin(admin.ModelAdmin):
    class Media:
        css = {
             "all": ("my_styles.css",)
         }
        js = ("my_code.js",)

rawDescription: Django Admin: Can I create a field that can only be used if a specific choice has been picked in a previous field on the same model?


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('''test1
test2
test3

test4

test4

''')
[tag.parent for tag in soup.findAll(attrs = {"class": "test4"})
 if tag.name in ['a', 'div'] and tag.parent.name == 'td']

rawDescription: finding a tag based on what it surrounds (using beautifulsoup)

description: Finding a tag based on what it surrounds (using beautifulsoup)


rawDescription: Please help extract text from HTML tags using Python Regex


code:
import scrapy
from scrapy.http import FormRequest

class MySpider(scrapy.Spider):
    # ...
    def start_requests(self):
        yield FormRequest(some_post_url,
                          formdata=dict(param1='value1', param2='value2'))

rawDescription: Python Scrapy override content type to be multipart/form-data on post Request


rawDescription: Regex with repeating groups

description: Regex with repeating groups


code:
class BookDetail(DetailView):
    model = Book

    def get_object(self):
        self.booktranslation = BookTranslation.objects.select_related('book').get(book__slug=self.kwargs['slug'],
                                     language=self.kwargs['language'])
        return self.booktranslation.book

rawDescription: filter prefetch_related and select_related results

description: Filter prefetch_related and select_related results


code:
from freezegun import freeze_time

@freeze_time("2015-02-25")
def test_third_day_from_now():
    assert third_day_from_now() == datetime.datetime(2015, 2, 28)

rawDescription: How to write time dependent tests Python

description: Write time dependent tests Python


code:
date_list = Note.objects.all().dates('created', 'year')

for years in date_list:
    Note.objects.filter(created__year = years.year)

rawDescription: Django: Filtering datetime field by *only* the year value?


code:
import argparse
parser = argparse.ArgumentParser()
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_const",
    dest="mutex", const="show")
mutex_group.add_argument("--insert", action="store_const",
    dest="mutex", const="insert")
mutex_group.add_argument('--delete', action="store_const",
    dest="mutex", const="delete")

parser.set_defaults(mutex='show')
args = parser.parse_args()
print(args)

rawDescription: Set the default to false if another mutually exclusive argument is true


code: template.generate().render('html', doctype= 'html', encoding= 'us-ascii')

rawDescription: Can one prevent Genshi from parsing HTML entities?


code: grouped = [list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[2])]

rawDescription: How to group related .tif files?

description: Group related .tif files


rawDescription: Why does this pandas groupby object have all these extra groups?


code:
def dashrepl(matchobj):
    return matchobj.group(0) + ' '

rawDescription: Why don't backreferences work in Python's re.sub when using a replacement function?


rawDescription: Python: Associativity of (**) not behaving as desired


code:
pwc = doc.checkout()
pwc.setContentStream(contentFile=tempfile)
pwc.checkin

rawDescription: Alfresco Versioning via cmis setContentStream


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

plt.style.use('ggplot')

mean = 100
std = 16

x = np.linspace(mean - 5 * std, mean + 5 * std, 1000)

iq = stats.norm(mean, std)

plt.plot(x, iq.pdf(x), 'r-', lw=3)

colors = ['c', 'r', 'b', 'g', ]
colors = colors + list(reversed(colors))

for i, color in zip(range(-4, 4), colors):
    low = mean + i * std
    high = mean + (i + 1) * std
    px = x[np.logical_and(x >= low, x <= high)]
    plt.fill_between(
        px,
        iq.pdf(px),
        color=color,
        alpha=0.5,
        linewidth=0,
    )

plt.tight_layout()
plt.savefig('test.png', dpi=300)

rawDescription: How can I shade an area under a curve between two lines in matplotlib / pandas?

description: Shade an area under a curve between two lines in matplotlib / pandas


code:
listName = [[0, 1, 2, 15, 16, 17, 2, 3, 4, 6, 8, 9]]

from itertools import chain
def split(l):
    it = chain(*l)
    prev = next(it)
    tmp = [prev]
    for ele in it:
        if ele < prev:
            yield tmp
            tmp = [ele]
        else:
            tmp.append(ele)
        prev = ele
    yield tmp

print(list(split(listName)))

rawDescription: If statement in list comprehension with lambda


code:
def clean(self, value):
    if not value and not self.required:
        return value
    """Check if given CC number is valid and one of the
       card types we accept"""
    if value and (len(value) < 13 or len(value) > 16):
        raise forms.ValidationError("Please enter in a valid "+\
                "credit card number.")
    elif self.get_cc_type(value) not in ("Visa", "MasterCard",
                                             "American Express"):
        raise forms.ValidationError("Please enter in a Visa, "+\
            "Master Card, or American Express credit card number.")
    return super(CreditCardField, self).clean(value)

rawDescription: How to make a subclassed, custom Django form field non-required?

description: Make a subclassed, custom Django form field non-required


rawDescription: How to control sorting arrow indicator on QTableView

description: Control sorting arrow indicator on QTableView


code:
class MyDiagram(FigureCanvas):
    def __init__(self, fig):
        FigureCanvas.__init__(self, fig)
        self._cursor = None

    def enterEvent(self, event):
        if (self._cursor is not None and
            QApplication.overrideCursor() is None):
            QApplication.setOverrideCursor(self._cursor)
        FigureCanvas.enterEvent(self, event)

    def leaveEvent(self, event):
        self._cursor = QCursor(QApplication.overrideCursor())
        QApplication.restoreOverrideCursor()
        FigureCanvas.leaveEvent(self, event)

rawDescription: how to emit (fire) axes_leave_event

description: Emit (fire) axes_leave_event


code:
for word in words:
    if word not in list_of_words:
        list_of_words[index] = word
        list_of_positions[index] = position
        index = index + 1
        position = position + 1
    else:
        list_of_positions[index] = list_of_positions[list_of_words.index(word)]
        index = index + 1

rawDescription: PYTHON - test compression program two lists


code:
from scipy.signal import lfilter, butter
from scipy.io.wavfile import read,write
from numpy import array, int16
import sys

def butter_params(low_freq, high_freq, fs, order=5):
    nyq = 0.5 * fs
    low = low_freq / nyq
    high = high_freq / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a

def butter_bandpass_filter(data, low_freq, high_freq, fs, order=5):
    b, a = butter_params(low_freq, high_freq, fs, order=order)
    y = lfilter(b, a, data)
    return y

if __name__ == '__main__':
    fs,audio = read(sys.argv[1])
    low_freq = 300.0
    high_freq = 3000.0
    filtered_signal = butter_bandpass_filter(audio, low_freq, high_freq, fs, order=6)
    fname = sys.argv[1].split('.wav')[0] + '_moded.wav'
    write(fname,fs,array(filtered_signal,dtype=int16))

rawDescription: Adding effects to make voice sound like it’s over a telephone


code:
import zipfile

zf = zipfile.ZipFile('some_file.zip', 'r')

for name in zf.namelist():
    if name.endswith('/'): continue

    if 'folder2/' in name:
        f = zf.open(name)
        # here you do your magic with [f] : parsing, etc.
        # this will print out file contents
        print(f.read())

rawDescription: Read xml files directly from a zip file using Python


code:
from scipy import *
from scipy.integrate import *
import time
from multiprocessing import Pool
from matplotlib.pyplot import figure, plot

def lct(f, a, b, c, d):
    def X(u):
        coeff=sqrt(-1j)*e**(1j*pi*(d/b)*(u**2))
        integrand_R= lambda t,f,a,b: (e**(-2j*pi*u*t/b)*e**(1j*pi*a*t**2/b)*f(t)).real
        integrand_I= lambda t,f,a,b: (e**(-2j*pi*u*t/b)*e**(1j*pi*a*t**2/b)*f(t)).imag
        # integral= sum of integrals of real and imaginary parts
        integral=quad(integrand_R,-Inf,0,args=(f,a,b))[0]+1j*quad(integrand_I,-Inf,0,args=(f,a,b))[0]
        #print(integral)
        return coeff*integral
    return X

def test():
    global test_lct, x
    y=abs(p.map(test_lct,x))
    figure(figsize=(6*3.13,4*3.13/2))
    plot(x,y)
    for i in range(y.size):
        if y[i]>1e15:
            print(x[i])
            print(y[i])
            print('\n')
            print(x[130:140])
            print('\n')
            print(y[130:140])
            print('\n')

if __name__ == '__main__':
  p=Pool()
  x=arange(4,step=0.005)
  start=time.clock()
  test_lct=lct(lambda x: sin(x),1,2,3,7)
  test()
  test_lct=lct(lambda x: sin(2*x),1,2,3,7)
  test()
  stop=time.clock()
  print(stop-start)

rawDescription: Why does running 2 threads crash python?

description: Why does running 2 threads crash python


code:
from djcelery.models import PeriodicTask, TaskMeta

last_run = PeriodicTask.objects.only('last_run_at')\
                               .get(task=task_name).last_run_at
task_meta = TaskMeta.objects.filter(task_id=task_name, date_done__gte=last_run)\
                            .order_by('date_done').only('meta')[:1][0].meta

rawDescription: django-celery PeriodicTask getting last run time using DatabaseScheduler

description: Django-celery PeriodicTask getting last run time using DatabaseScheduler


code:
from Spotfire.Dxp.Application.Visuals import Treemap
treeChart = vis.As[Treemap]()
vis.Title="tree map title"
treeChart.Data.DataTableReference = "Your Expression"
treeChart.ColorAxis.Expression = "Your Expression"

rawDescription: TreeMap properties(Hierarchy, Size by) using ironpython script in spotfire


code:
from pyparsing import (CaselessKeyword,Word,nums,QuotedString,alphas,alphanums,
    Forward,Group,Optional,OneOrMore,ZeroOrMore,delimitedList)

LET,IN,END = map(CaselessKeyword, "let in end".split())

number = Word(nums).setName("number")
string = QuotedString('"')
ident = ~(LET | IN | END) + Word(alphas, alphanums+'_')
ident.setName("ident")

literal = number | string

simple_var = ident

exp = Forward().setName("exp")
let_in_exp = Group(LET + IN + ZeroOrMore(exp) + END).setName("let_in_exp")

param = number | string
params = delimitedList(param)
function_call = ident() + '(' + Optional(params) + ')'

exp <<= let_in_exp | simple_var | literal | function_call

code = OneOrMore(exp)

tests = """\
    let in let in let in end end end
    let in let in let in "blah" end end end
    let in let in let in "blah" end 1729 end end
    """
code.runTests(tests)

rawDescription: PEG recursive grammar

description: PEG recursive grammar


code:
# PDF GENERATION LIBRARIES
# import the report lab PDF generation tools
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

parts = []
msg = ''
progName = "PDF"
progVers = "1.0"
vehID = "vehID"

def sumFile(msgStr = None, COMPLETE = 0):

    global parts, msg, progName, progVers, vehID

    pdfmetrics.registerFont(TTFont('Inconsolata', 'Inconsolata-Regular.ttf'))

    style = ParagraphStyle(
        name='Normal',
        fontName='Inconsolata',
        fontSize=8,
    )

    msgStr = msgStr.replace(' ',' ')
    msgStr = msgStr.replace('\n','<br />')
    msgStr = msgStr.replace('\t','    ')

    if msgStr == "PageBreak":
        if msg != '':
            parts.append(Paragraph(msg, style = style))
            msg = ''
        parts.append(PageBreak())
    else:
        msg += msgStr

    if COMPLETE == 1:
        if msg != '':
            parts.append(Paragraph(msg, style = style))
            msg = ''
        genStr = "Generated using " + progName + " " + str(progVers)
        parts.append(Paragraph(genStr, style = style))
        summaryName = SimpleDocTemplate(vehID+".pdf")
        summaryName.build(parts)

if __name__ == "__main__":
    sumFile("%9s %s\n" % ("Bobby", "Sue"))
    sumFile("{0:12}{1:7}{2:5}deg_C\tsmp {3}\n".format("20", "1000", "3.0", "535"))
    sumFile("{0} {1}\n\n".format("09/06/2016", "11:51:39"))
    # sumFile("{0} {1}\n\n".format("09/06/2016", "11:51:39"), COMPLETE=1)

rawDescription: ReportLab Paragraph and text formatting

description: ReportLab Paragraph and text formatting