code:
import random

class Card(object):
    '''Remember, a 'card' is completely different from a deck. You can have a
    card that is not contained in a deck, and a deck is simply another object
    that contains one or more cards, with a few convenience methods attached.'''

    def __init__(self, rank, suite):
        self.rank = rank
        self.suite = suite

    def __repr__(self):
        '''The different between '__repr__' and '__str__' is not particularly
        important right now. You can google the difference yourself.'''
        return "Card({0}, {1})".format(self.rank, self.suite)

    def __str__(self):
        return "{0} of {1}".format(self.rank, self.suite)

    def value(self):
        ranks = ["Ace", "2", "3", "4", "5", "6", "7",
            "8", "9", "10", "Jack", "Queen", "King"]

        # This is something called a 'dictionary comprehension'. It lets you
        # map the rank of the card to its corresponding value.
        #
        # 'enumerate' is a built-in. Try doing `enumerate(["a", "b", "c", "d"])`
        # in the shell, and see what happens.
        values = {rank: i + 1 for (i, rank) in enumerate(ranks)}

        return values[self.rank]

class Deck(object):
    '''Now, we have the deck.'''

    def __init__(self):
        self.suites = ["Clubs", "Diamonds", "Hearts", "Spades"]
        self.ranks = ["Ace", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "Jack", "Queen", "King"]

        # Here, I've chosen to create a full deck when instantiating the object.
        # You may chose to modify your code to pass in the cards you want instead.
        #
        # Notice how we're keeping track of all of our cards inside of a list.
        # This way, we're free to write whatever methods we want, while still
        # internally representing our deck of cards in the cleanest manner possible.

        self.cards = []
        for suite in self.suites:
            for rank in self.ranks:
                self.cards.append(Card(suite, rank))

    def shuffle(self):
        random.shuffle(self.cards)

    def remove(self, card):
        # idk if this will actually work -- you should test it.
        self.cards.remove(card)

    def append(self, card):
        '''In this method, we're taking a card, and adding it to our deck.
        We've written the entire thing ourselves -- no need to call to super
        (which doesn't work, in any case)'''
        self.cards.append(card)

    def get_top_card(self):
        '''This is a common operation when dealing with decks -- why not add it?'''
        return self.cards.pop()

    def __repr__(self):
        return "[" + ", ".join(repr(card) for card in self.cards) + "]"

    def __str__(self):
        return '\n'.join(str(card) for card in self.cards)

def main():
    deck = Deck()
    deck.shuffle()

    hand = []

    while True:
        user = int(input('Enter a number of cards: 1-7 '))
        print()
        if not 1 <= user <= 7:
            print ("Only a number between 1-7:")
        else:
            break

    for i in range(user):
        hand.append(deck.get_top_card())
    print(hand)

if __name__ == '__main__':
    main()

rawDescription: Super object has no attribute 'append'

description: Super object has no attribute 'append'


code:
from calendar import Calendar, SUNDAY

cal = Calendar(SUNDAY)
month_dates = list(cal.itermonthdates(year, month))

month_start = month_dates[0]
month_end = month_dates[-1]

rawDescription: Getting the first and last item in a python for loop


code:
def updateTooltip(self, win, lbl):
    lbl.set_text(str(time.time()))
    x, y, mods = win.get_screen().get_root_window().get_pointer()   #this gets absolute mouse possition on screen
    win.move(x+15, y+10)

rawDescription: PyGTK: move custom build tooltip window

description: PyGTK: move custom build tooltip window


code:
import Tkinter, Tkconstants, tkFileDialog

class TkFileDialogExample(Tkinter.Frame):

    def __init__(self, root):

        Tkinter.Frame.__init__(self, root)
        button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
        Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt)

        self.file_opt = options = {}
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
        options['initialfile'] = 'myfile.txt'
        options['parent'] = root

    def asksaveasfilename(self):
        filename = tkFileDialog.asksaveasfilename(**self.file_opt)

        if filename:
            return open(filename, 'w')

if __name__=='__main__':
    root = Tkinter.Tk()
    TkFileDialogExample(root).pack()
    root.mainloop()

rawDescription: how to use Python SaveAs dialog

description: Use Python SaveAs dialog


code:
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"

from mysite.polls.models import Poll, Choice

rawDescription: What do I need to import to gain access to my models?


code:
import urllib3

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
                           ca_certs="cert.pem",
                           assert_hostname=False)
try:
    r = http.request('GET', 'https://127.0.0.1:4443/')
    print("STATUS:", r.status)
    print("Certificate verification NO HOSTNAME successful")

except urllib3.exceptions.SSLError as e:
    print ("SSL Error:", e)
    return -1

return 0

rawDescription: Replace opener for urllib.request.urlopen(url, ca*)


code:
from collections import defaultdict
myarray = defaultdict(dict)
myarray[4][5] = 34

rawDescription: Python - Dynamic PHP-like arrays

description: Python - Dynamic PHP-like arrays


code:
delimiter = Word(printables, exact=1)
text = Forward() #(Word(printables) + ~delimiter)
def setTextExcludingDelimiter(s,l,t):
    # define Word as all printable characters, excluding the delimiter character
    # the excludeChars argument for Word is how this is done
    text_word = Word(printables, excludeChars=t[0]).setName("text")
    # use '<<' operator to assign the text_word definition to the
    # previously defined text expression
    text << text_word
# attach parse action to delimiter, so that once it is matched,
# it will define the correct expression for text
delimiter.setParseAction(setTextExcludingDelimiter)

# make the text expressions Optional with default value of '' to satisfy 3rd test case
parser = delimiter + Optional(text,'') + delimiter + Optional(text,'') + delimiter

rawDescription: Reference token value at parse time

description: Reference token value at parse time


code:
setup(...,
      entry_points = {"gui_scripts" : ['name-of-executable = name_of_package.launcher:main']})

rawDescription: Python GUI(tkinter; pygtk+glade), py2exe


rawDescription: get rid of commas in a list python

description: Get rid of commas in a list python


code:
from .models import CustomUser

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)

    class Meta:
        model = CustomUserModel
        # Note - include all *required* CustomUser fields here,
        # but don't need to include password1 and password2 as they are
        # already included since they are defined above.
        fields = ("email",)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            msg = "Passwords don't match"
            raise forms.ValidationError("Password mismatch")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

rawDescription: Unable to render Email field in the registration form in an Django app


code:
a = [1, 2, 3, 4, 5]

user_input = raw_input('next action:') # e.g. append 6
action = append_input.split()

rawDescription: to isolate commands and values read in a single line

description: To isolate commands and values read in a single line


code:
def saveSnapshot(dcSource):
    # based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08
    size = dcSource.Size

    # Create a Bitmap that will later on hold the screenshot image
    # Note that the Bitmap must have a size big enough to hold the screenshot
    # -1 means using the current default colour depth
    bmp = wx.EmptyBitmap(size.width, size.height)

    # Create a memory DC that will be used for actually taking the screenshot
    memDC = wx.MemoryDC()

    # Tell the memory DC to use our Bitmap
    # all drawing action on the memory DC will go to the Bitmap now
    memDC.SelectObject(bmp)

    # Blit (in this case copy) the actual screen on the memory DC
    # and thus the Bitmap
    memDC.Blit( 0, # Copy to this X coordinate
        0, # Copy to this Y coordinate
        size.width, # Copy this width
        size.height, # Copy this height
        dcSource, # From where do we copy?
        0, # What's the X offset in the original DC?
        0  # What's the Y offset in the original DC?
        )

    # Select the Bitmap out of the memory DC by selecting a new
    # uninitialized Bitmap
    memDC.SelectObject(wx.NullBitmap)

    img = bmp.ConvertToImage()
    img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)

rawDescription: Saving an image of what a device context drew, wxPython


code:
...
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('{'+q+'}{'+str(code)+'}')

rawDescription: Print web response in <code> format Google app engine python project


code:
from lxml import etree as ET
import random

def random_color():
    r = lambda: random.randint(0,255)
    return '#%02X%02X%02X' % (r(),r(),r())

new_style = 'font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:'

tree = ET.parse('USA_Counties_with_FIPS_and_names.svg')
root = tree.getroot()
for child in root:
    if 'path' in child.tag and child.attrib['id'] not in ["separator", "State_Lines"]:
        child.attrib['style'] = new_style + random_color()

tree.write('counties_new.svg')

rawDescription: Beautiful Soup - `findAll` not capturing all tags in SVG (`ElementTree` does)


code:
from requests.compat import urljoin, quote_plus
url = "http://some-address.com/api/"
term = 'This is a test'
urljoin(url, quote_plus(term))

rawDescription: Build a URL using Requests module Python


code:
def col(B,j):
    Z=[]
    for i in range(len(B)):
        Z.append(B[i][j])
    return Z

rawDescription: extracting column from matrix

description: Extracting column from matrix


code:
import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)

rawDescription: Python read JSON file and modify

description: Python read JSON file and modify


code:
import os
for dirpath,dirs,files in os.walk('A Folder/Another folder'):
  for f in files:
    fn = os.path.join(dirpath, f)
    myzipfile.write(fn)

rawDescription: Python - Writing a folder and its contents to a ZipFile


code: y_pred = cross_validation.cross_val_predict(rfc, X, y, cv=cv, n_jobs = 1)

rawDescription: Get single prediction values scikit-learn


code:
import matplotlib.pyplot as plt

# Turn on LaTeX formatting for text
plt.rcParams['text.usetex']=True

# Place the command in the text.latex.preamble using rcParams
plt.rcParams['text.latex.preamble']=r'\makeatletter \newcommand*{\rom}[1]{\expandafter\@slowromancap\romannumeral #1@} \makeatother'

fig,ax = plt.subplots(1)

# Lets try it out. Need to use a 'raw' string to escape
# the LaTeX command properly (preface string with r)
ax.text(0.2,0.2,r'\rom{28}')

# And to use a variable as the roman numeral, you need
# to use double braces inside the LaTeX braces:
for i in range(1,10):
    ax.text(0.5,float(i)/10.,r'\rom{{{}}}'.format(i))

plt.show()

rawDescription: Pyplot annotation: roman numerals

description: Pyplot annotation: roman numerals


code:
from operator import attrgetter
your_list.sort(key=attrgetter('age'), reverse=True)

rawDescription: Most efficient way to sort list of objects by attribute?


code:
from bitstring import BitArray
b = BitArray([randint(0, 1) for i in range(50*98)])

rawDescription: Building a list with binary numbers in binary representation in Python


code:
qs = Model.objects.filter(...) # qs with objects to exclude
result = Model.objects.exclude(pk__in=qs.values_list('pk', flat=True))

rawDescription: Django: Getting complement of queryset

description: Django: Getting complement of queryset


code:
import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(150,100), title='MainFrame')
        pan =wx.Panel(self)
        self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
        self.but = wx.Button(pan,-1, pos=(10,30), label='Tell child')
        self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)
        self.child = ChildFrame(self)
        self.child.Show()

    def onbutton(self, evt):
        text = self.txt.GetValue()
        self.child.txt.write('Parent says: %s' %text)

class ChildFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, None, size=(150,100), title='ChildFrame')
        self.parent = parent
        pan = wx.Panel(self)
        self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
        self.but = wx.Button(pan,-1, pos=(10,30), label='Tell parent')
        self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)

    def onbutton(self, evt):
        text = self.txt.GetValue()
        self.parent.txt.write('Child says: %s' %text)

if __name__ == "__main__":

    App=wx.PySimpleApp()
    MainFrame().Show()
    App.MainLoop()

rawDescription: Show another window wxpython?

description: Show another window wxpython


code: [s for s in partyinfo[partyinfo.index('Defendant'):] if s != 'Defendant']

rawDescription: Python List Index Comprehension

description: Python List Index Comprehension


rawDescription: How to create a non-UTF8 string?

description: Create a non-UTF8 string


code:
graphics(pet, SNR_dB)
graphics(another_pet, SNR_dB)
pl.show()

def graphics(Pe, SNR_dB):

    pl.semilogy(SNR_dB, Pe[0],linewidth=1)
    pl.semilogy(SNR_dB, Pe[1],linewidth=2)
    pl.legend(('Symbol', 'bit'))

    pl.xlim([0, max(SNR_dB)])
    pl.ylim([1e-10,1])

    pl.title('Error vs SNR_dB')
    pl.grid(True)
    pl.xlabel('SNR_dB')
    pl.ylabel('Pe')

rawDescription: How to hold on pylab.semilogy figures?

description: Hold on pylab.semilogy figures


code:
myDict = {'foo': 'bar', 'foobar baz': 'qux'}
{k:v for k, v in myDict.items() for k in k.split()}

rawDescription: Split on whitespaces in keys of dict, take value


code:
positions = ['TW', 'IV', 'MF', 'ST']
multi_lines = [[
        randint(18,33),
        names.get_full_name(gender='male'),
        random.choice(positions),
        randint(50,100),
        randint(500000,5000000)
    ]
    for i in range(2)
]

c.executemany('INSERT INTO player(Age, Name, Position, Skill, Value)  VALUES (?,?,?,?,?)', multi_lines)

rawDescription: Create list with random input for SQL multiple line input


code:
from functools import partial, wraps
from django.forms.formsets import formset_factory

ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3)

rawDescription: Django Passing Custom Form Parameters to Formset


code:
class User(models.Model):
    name = models.CharField(max_length=200)
    is_editor = models.BooleanField(default=False)
    is_supervisor = models.BooleanField(default=False)
    is_consultant = models.BooleanField(default=False)

rawDescription: How to implement a bitmask in a Django choice field

description: Implement a bitmask in a Django choice field


code:
from datetime import datetime

date_format = "%d/%m/%Y"
start_date = datetime.strptime(startDate, date_format)
end_date = datetime.strptime(endDate, date_format)
items = coll.find({})

def compare(c, item):
    item_date = datetime.strptime(item['Date'], date_format)
    if start_date < item_date < end_date:
        return c+1
    else:
        return c

count = reduce(compare, items, 0)

rawDescription: Pymongo date query in "DD/MM/YYYY" format


rawDescription: Python Regex for hyphenated words

description: Python Regex for hyphenated words


rawDescription: Remove some numbers from a list of data with Python


code:
import collections

counter = collections.Counter()

with open("data.json") as f:
    for line in f:
        result = json.loads(line)
        if 'text' in result.keys():
            response = result['text']
            words = response.encode("utf-8").split()
            counter.update(words)
print(counter)

rawDescription: Total of each element in dictionary by python


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

# Plot data
x = np.linspace(0,1,100)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(221) #small subplot to show how the legend has moved.

# Create legend
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
leg = plt.legend( loc = 'upper right')

plt.draw() # Draw the figure so you can find the positon of the legend.

# Get the bounding box of the original legend
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)

# Change to location of the legend.
xOffset = 1.5
newX0 = bb.x0 + xOffset
newX1 = bb.x1 + xOffset
bb.set_points([[newX0, bb.y0], [newX1, bb.y1]])
leg.set_bbox_to_anchor(bb)

# Update the plot
plt.show()

rawDescription: Move and resize legends-box in matplotlib


code:
class DropableComboBox(QtGui.QComboBox):
    def __init__(self):
        super(DropableComboBox, self).__init__()
        self.model_mime_type = 'application/x-qabstractitemmodeldatalist'
        self.setAcceptDrops(True)
        self._proxymodel = QtGui.QStandardItemModel(self)

    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.emit(QtCore.SIGNAL("dropped"), links)
        elif event.mimeData().hasFormat(self.model_mime_type):
            self._proxymodel.setRowCount(0)
            self._proxymodel.dropMimeData(
                event.mimeData(), QtCore.Qt.CopyAction,
                0, 0, QtCore.QModelIndex())
            for index in range(self._proxymodel.rowCount()):
                item = self._proxymodel.item(index, 0)
                self.addItem(item.text())
            # no point calling the base-class dropEvent here,
            # because it's a NO-OP in QComboBox
            self.emit(QtCore.SIGNAL("dropped"))

rawDescription: How to Drag and Drop from ListWidget onto ComboBox


code:
import pandas as pd

records = [tuple(f(A, O) for A in AP) for O in OP]
pd.DataFrame.from_records(records)

rawDescription: Python apply a func to two lists of lists, store the result in a Dataframe


rawDescription: How to fetch json argument in handler (json is in body of post request with no key to json)

description: Fetch json argument in handler (json is in body of post request with no key to json)


code:
super(B, B).my_method
super(B, B).my_method is A.my_method

rawDescription: Python: Why can't I use `super` on a class?


code:
from collections import defaultdict

def catatlog(request):
    cars = defaultdict(list)
    for i in Car.objects.all():
        cars[i.name].append(i.model)
    return render(request, 'index.html', {'cars':cars})

rawDescription: How can I group model atributes

description: Group model atributes


code:
# States and their colors
state_list = [1, 2, 1]
STATE_COLOR = { 1 : 'r', 2 : 'y' }

L = 1.5 # Constant state length

x = np.linspace(0, 4.5)
y = x**2 - 3

# Draw states
for i, state in enumerate(state_list):
    x1 = i * L
    x2 = (i+1) * L
    plt.axvspan(x1, x2, color=STATE_COLOR[state])

# Draw line data
plt.plot(x, y)

rawDescription: What is this plot called and how to make it in matplotlib?


rawDescription: In-place sort of sublist

description: In-place sort of sublist


code:
import codecs

self.response.out.write(codecs.BOM_UTF8)
writer = csv.writer(self.response.out)
row = []
row.append(transaction.name.encode('utf8'))
writer.writerow(row)

rawDescription: Google App engine python writing csv in arabic


code:
app = Frame(root)
app.grid()

rawDescription: frame widget in tkinter prevents child widgets from being displayed

description: Frame widget in tkinter prevents child widgets from being displayed


code:
import time
target = time.strptime('2014-03-14-18-00-00', '%Y-%m-%d-%H-%M-%S')
int(time.mktime(target))

rawDescription: Calculating the floating point number expressed in seconds since the epoch, in UTC for a set time / date


code:
data = [['Y', 'K', 'E'],
 [3, 1, 2],
 [6, 4, 5]]
key = 'KEY'
sorted(zip(*data), key=lambda x: key.index(x[0]))
list(zip(*sorted(zip(*data), key=lambda x: key.index(x[0]))))

rawDescription: How can I sort a list of lists by making the first row match another list?

description: Sort a list of lists by making the first row match another list


code:
from functools import wraps
from functools import update_wrapper

def retry(prompt_text="An error occured! Retry (y/n)?",
          prompt_match='y',
          exception=Exception):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            while True:
                try:
                    ret = func(*args, **kwargs)
                    break
                except exception:
                    if raw_input(prompt_text) == prompt_match:
                        ret = None
                        break
            return ret
        return update_wrapper(wrapper, func)
    return decorator

@retry(prompt_text="your prompt: ", prompt_match="quit", exception=OSError)
def do_write(myobject, filename):
    myobject.write(filename)

if __name__ == "__main__":
    myobject = ...
    filename = ...
    do_write(myobject, filename) # This will be retried.

rawDescription: Concise exception handling in Python

description: Concise exception handling in Python


code:
import fractions
fractions.Fraction("1")
fractions.Fraction("1/2")

rawDescription: Parsing a fraction in a Django form

description: Parsing a fraction in a Django form


code:
def foo(bar='spam', eggs=[]):
    eggs.append(bar)
    return eggs

foo.__defaults__
foo()
foo.__defaults__
foo() is foo.__defaults__[1]

rawDescription: Python function: Optional argument evaluated once?


code:
import os
import glob
directory = raw_input("path to base directory?")

for fle in glob.glob(os.path.join(directory,"savedrecs*.txt")):
     with open(fle) as f:
         sm = sum(not line.strip() for line in f)
         print("{} has {} empty lines".format(fle, sm))

rawDescription: How do I count the number of blank lines in a text file?

description: Count the number of blank lines in a text file


rawDescription: Slice Numpy character array using a view


code:
request.responseHeaders.setRawHeaders(
    'Content-Disposition', ['attachment; filename="foo"'])

rawDescription: How to Force File Download on Twisted HTTP Server?


code:
#!python3

import tkinter as tk

class popup(object):
    def __init__(self, parent):
        self.root=tk.Toplevel(parent)
        self.root.title("Popup")
        self.root.bind("<FocusOut>", self.Alarm)

    def Alarm(self, event):
        self.root.focus_force()
        self.root.bell()

main = tk.Tk()
main.title("Main")
pop = popup(main)
main.mainloop()

rawDescription: Tkinter: Window flash when attempting to click away


rawDescription: Appending Multiple JSON values to same element in python list


code:
def zip_write(zip, filename):
    zip.write(filename, os.path.basename(filename))

z = zipfile.ZipFile('myzip.zip', 'w')
zip_write(z, '/some/path/mytxt1.txt')
zip_write(z, '/some/other/path/mytxt2.txt')
z.close()

rawDescription: Flat files within a zipfile in Python

description: Flat files within a zipfile in Python


code:
import re

digits = re.compile(r'(\d+)')
def tokenize(filename):
    return tuple(int(token) if match else token
                 for token, match in
                 ((fragment, digits.search(fragment))
                  for fragment in digits.split(filename)))

# Now you can sort your PDF file names like so:
pdfList.sort(key=tokenize)

rawDescription: Sort a list of files using Python

description: Sort a list of files using Python


rawDescription: using numpy to convert an int to an array of bits

description: Using numpy to convert an int to an array of bits


code: fout.writelines(islice(fin,3,None,4)) # line with index 3 is the fourth line

rawDescription: Read every fourth line in Python

description: Read every fourth line in Python


code:
import sys

class Mock(object):

    __all__ = []

    def __init__(self, *args, **kwargs):
        pass

    def __call__(self, *args, **kwargs):
        return Mock()

    @classmethod
    def __getattr__(cls, name):
        if name in ('__file__', '__path__'):
            return '/dev/null'
        elif name[0] == name[0].upper():
            mockType = type(name, (), {})
            mockType.__module__ = __name__
            return mockType
        else:
            return Mock()

MOCK_MODULES = ['pygtk', 'gtk', 'gobject', 'argparse',
                'numpy', 'numpy.random']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()

rawDescription: Sphinx adds documentation for NumPy modules to my docs


code:
for p in  [player, player1, player2]:
    p.sendMessage()

rawDescription: Doing something with every segment of list?


code: re.sub(r'\d+\.\d*', lambda match: str(int(round(float(match.group(0))))), line)

rawDescription: Accessing capture groups during substitution


code:
import datetime
import re

PAT = re.compile('(\d{2}):(\d{2}):(\d{2})')
TSTR = "01:12:00"

def fun1():
    dt = datetime.datetime.strptime(TSTR, "%H:%M:%S")
    return dt

def fun2():
    h,m,s = [int(i) for i in TSTR.split(':')]
    dt = datetime.time(hour=h, minute=m, second=s)
    return dt

def fun3():
    mat = PAT.match(TSTR)
    dt = datetime.time(hour=int(mat.group(1)), minute=int(mat.group(2)), second=int(mat.group(3)))
    return dt

def fun4():
    h,m,s = int(TSTR[0:2]), int(TSTR[3:5]), int(TSTR[6:8])
    dt = datetime.time(hour=h, minute=m, second=s)
    return dt

if __name__ == "__main__":
    import timeit
    # Use the default repeat arguments: repeat=3, number=1000000
    print(min(timeit.repeat("fun1()", setup="from __main__ import fun1"))) # 15.5739
    print(min(timeit.repeat("fun2()", setup="from __main__ import fun2"))) #  3.4544
    print(min(timeit.repeat("fun3()", setup="from __main__ import fun3"))) #  4.1829
    print(min(timeit.repeat("fun4()", setup="from __main__ import fun4"))) #  2.8675

rawDescription: Most efficient way to convert string-time to time


code:
class defaultlist(list):
    def __init__(self, fx):
        self._fx = fx
    def _fill(self, index):
        while len(self) <= index:
            self.append(self._fx())
    def __setitem__(self, index, value):
        self._fill(index)
        list.__setitem__(self, index, value)
    def __getitem__(self, index):
        self._fill(index)
        return list.__getitem__(self, index)

rawDescription: creating a defaultlist in python

description: Creating a defaultlist in python


code: dict({'blah': 10}, new_item='Hello')

rawDescription: Multiple dictionary operations in one line


code:
...
from IPython import embed
embed()
...

rawDescription: python, ipython run interactive script

description: Python, ipython run interactive script


code: processedString = fileAsString(foundStatements[iterator], latexPreparedString)

rawDescription: regex search&replace a variable string including a regex statement

description: Regex search&replace a variable string including a regex statement


code:
import BaseHTTPServer

class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_GET(self):
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write("You accessed path: {}".format(self.path))

BaseHTTPServer.HTTPServer(('', 80), MyHTTPRequestHandler).serve_forever()

rawDescription: Python program to serve the output of a command via HTTP


code: np.vstack(y) - x

rawDescription: Numpy columnwise subtraction; subtract (k,n) array from values in a (k,) array


code:
class PersonTest(CreateView):
    model = Person

    def form_invalid(self, form):
        try:
            person = Person.objects.get(full_name=form.cleaned_data['full_name'], date_of_birth=form.cleaned_data['date_of_birth'], country=form.cleaned_data['country'])
            return HttpResponseRedirect(reverse('checker:detail', kwargs={'pk': person.id}))
        except:
            return super(ModelFormMixin, self).form_invalid(form)

rawDescription: Unique Fields return detail view on form submit


rawDescription: In Django, how do I select 100 random records from the database?


code:
from django.core.exceptions import PermissionDenied

def get(self, request, *args, **kwargs):
    team_id = self.kwargs.get('team_id')
    team = team_model.objects.get(pk=team_id)
    if team.name != TEAM_NAME:
        raise PermissionDenied
    else:
        return super(PlayerList, self).get(request, *args, **kwargs)

rawDescription: Django restricting access to view for certain objects


code:
import urllib2
def get_part_of_url(link, start_byte, end_byte):
    req = urllib2.Request(link)
    req.add_header('Range', 'bytes=' + str(start_byte) + '-' + str(end_byte))
    resp = urllib2.urlopen(req)
    content = resp.read()

rawDescription: Read specific bytes using urlopen()

description: Read specific bytes using urlopen()


code:
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Menu(MPTTModel):
    menuName = models.CharField(max_length=50)
    menuAlias = models.CharField(max_length=50, unique=True, validators=[aliasvalidator])
    published = models.BooleanField()
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

rawDescription: Building 'limitless' menu trees with Django


code:
from django.views.generic.base import RedirectView

url(r'^$', RedirectView.as_view(url='/home/')),

rawDescription: django redirecting blank url to named url

description: Django redirecting blank url to named url


code: data = struct.pack("{0}s".format(len(unknown_string)), unknown_string)

rawDescription: Python struct string to bin

description: Python struct string to bin


code:
min_date = min(search_count, key=itemgetter(2, 1))
max_date = max(search_count, key=itemgetter(2, 1))

rawDescription: Find max and min date

description: Find max and min date


code:
from datetime import datetime, timedelta
now = datetime.now()
now = now - timedelta(minutes = now.minute % 15, seconds = now.second, microseconds = now.microsecond )

rawDescription: Find current time interval in python?

description: Find current time interval in python


code:
class DataForm(forms.Form):

      years = Servizi.objects.all().dates('data','year')

      asd = []
      for year in years:
          asd.append((year.year,year.year))

      year = forms.ChoiceField(choices=asd)

rawDescription: django populate a ModelMultipleChoiceField with date__year

description: Django populate a ModelMultipleChoiceField with date__year


code:
def dotProduct(x,y):
    prod=0
    for i in range(len(x)):
        prod=prod+x[i]*y[i]
    return prod

rawDescription: Dot product Matrices

description: Dot product Matrices


code:
import dis
def f1():
  for i in range(5):
     l.append(i)

def f2():
  [i for i in range(5)]

dis.dis(f1)
dis.dis(f2)

rawDescription: Why is list comprehension so faster?

description: Why is list comprehension so faster


code:
def connect(s):
    while True:
        ip = getFromInputField()
        for x in range(100):
            try:
                s.connect((ip, port + x))
                return
            except socket.error as e:
                print("Cannot connect")
                print(e)

s = socket.socket()
connect(s)

rawDescription: python3 port scanner outer variable

description: Python3 port scanner outer variable


code:
# Main Inventory
Inventory = createInventory()

# Populating given inventory aray with items to be used throughout the game.
def createItems(inv):
    items = inv
    items[1] = "Axe"
    items[2] = "Gas"
    items[3] = "keys"
    items[4] = "gun"
    items[5] = "note"
    items[9] = "full"

# Check if the item passed to it is still in the inventory array
def checkItems(item):
    items = Inventory
    for i in range(len(items)):
        if items[i] == item:
            return "yes"
    return "no"

def createInventory():
    inv = range(11)
    inv[10] = "made"
    return inv

def stockInventory(item):
    inv = Inventory
    for i in range (11):
        if inv[i] == 0:
            inv[i] = item
            break
    return inv

def checkInventory(item):
    inv = Inventory
    for i in range(0, 11):
        if item == inv[i]:
            return "yes"
    return "no"

rawDescription: Text based adventure game inventory probems python


code:
#debug_toolbar settings
if DEBUG:
    INTERNAL_IPS = ('127.0.0.1',)
    MIDDLEWARE_CLASSES += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )

    INSTALLED_APPS += (
        'debug_toolbar',
    )

    DEBUG_TOOLBAR_PANELS = [
        'debug_toolbar.panels.versions.VersionsPanel',
        'debug_toolbar.panels.timer.TimerPanel',
        'debug_toolbar.panels.settings.SettingsPanel',
        'debug_toolbar.panels.headers.HeadersPanel',
        'debug_toolbar.panels.request.RequestPanel',
        'debug_toolbar.panels.sql.SQLPanel',
        'debug_toolbar.panels.staticfiles.StaticFilesPanel',
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.cache.CachePanel',
        'debug_toolbar.panels.signals.SignalsPanel',
        'debug_toolbar.panels.logging.LoggingPanel',
        'debug_toolbar.panels.redirects.RedirectsPanel',
    ]

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
    }

rawDescription: How do I see the Django debug toolbar?

description: See the Django debug toolbar


code:
l[0:-1]
l[0::2]  # start at first and step of 2
l[0::3]  # start at first and step of 3

rawDescription: Referencing index of List -1

description: Referencing index of List -1


code:
fin = open("students","r")
for line in fin:
  line = line.split()
  if len(line) > 1:
    name = line[0]
    grades = map(float, line[1:])
    mean = sum(grades) / len(grades)
    print( "{:<10}: {:>5.2f}".format(name,mean) )

rawDescription: python calculating average grade from a reading file

description: Python calculating average grade from a reading file


code:
import datetime
MONTH_NAMES = {1: 'jan', 2: 'feb', 3: 'mar'}  # and so on
ONE_DAY = datetime.timedelta(1)

def date_strings(first_date, last_date):
    current_date = first_date
    while current_date <= last_date:
        yield '{0.day:02}-{1}-{0.year:04}'.format(
            current_date, MONTH_NAMES[current_date.month])
        # If running on a US locale, you can just use:
        # yield current_date.strftime('%d-%b-%Y').lower()
        current_date += ONE_DAY

first_date = datetime.date(2016, 1, 8)
last_date = datetime.date(2016, 3, 29)

for date_string in date_strings(first_date, last_date):
    print(date_string)
    # Do whatever scraping you need using date_string

rawDescription: Scrape Websites with Python + Beautiful Soup 4 All pages


rawDescription: Iterating through a python list of list and creating a new list


code:
setup(
    name="mypkg", version="0.0.1",
    # etc etc blah blah blabh
    install_requires=["PIL"],
)

rawDescription: Using 3rd Party Libraries in Python

description: Using 3rd Party Libraries in Python


code:
def percent(total):
    return total*0.21276595744

print (percent(450))

rawDescription: Why isn't this python code for percentage calculation not working?


code: casted_obj = Object.cast_(obj)

rawDescription: How to cast variables in python with jcc

description: Cast variables in python with jcc


code:
from guppy import hpy
hp = hpy()
hp.setrelheap() # ignore all existing objects
d = {}
d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
hp.heap()

rawDescription: Python: How to estimate / calculate memory footprint of data structures?


code:
someinfo.message += ' World'
someinfo.save()

rawDescription: How to do an append to an existing field in a Django Model?

description: Do an append to an existing field in a Django Model


code: self.axes.format_coord = lambda x, y: ""

rawDescription: Disable coordinates from the toolbar of a Matplotlib figure


code:
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np

# create data to be fitted
xf = [0.5,0.85] # two given datapoints to which the exponential function with power pw should fit
yf = [0.02,4]

# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
    pw = params['pw'].value
    adj1 = params['adj1'].value
    adj2 = params['adj2'].value

    model = adj1 * np.power(x + adj2, pw)
    return model - data

pw=2

# create a set of Parameters
params = Parameters()
params.add('pw',   value= pw, vary=False)
params.add('adj1', value= 1)
params.add('adj2', value= 1)

# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(xf, yf))

# calculate final result
final = yf + result.residual

# write error report
report_fit(result.params)
adj1=result.params['adj1']
adj2=result.params['adj2']

# try to plot results
x = np.linspace(0, 1, 100)
y = adj1 * np.power(x + adj2, pw)

import pylab
pylab.plot(xf, yf, 'ko')
pylab.plot(x, y, 'r')
pylab.show()

rawDescription: Fitting exponential function through two data points with scipy curve_fit


rawDescription: how to remove brackets from python string

description: Remove brackets from python string


code:
user.no_of_logins += 1
session.commit()

rawDescription: how to update SQLAlchemy row entry

description: Update SQLAlchemy row entry


code: response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

rawDescription: In Memory CSV download file name

description: In Memory CSV download file name


code:
from itertools import groupby
blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/']
chunks = (list(g) for k,g in groupby(blist, key=lambda x: x != '/') if k)
for chunk in chunks:
    print(chunk)

rawDescription: Split a list into chunks determined by a separator


code:
from celery import Celery
from celery.bin import Option
from celery.bootsteps import ConsumerStep
from kombu import Consumer, Exchange, Queue

class CustomConsumer(ConsumerStep):
   queue = Queue('custom', Exchange('custom'), routing_key='custom')

   def __init__(self, c, enable_custom_consumer=False, **kwargs):
       self.enable = self.enable_custom_consumer

   def get_consumers(self, connection):
       return [
           Consumer(connection.channel(),
               queues=[self.queue],
               callbacks=[self.on_message]),
       ]

   def on_message(self, body, message):
       print('GOT MESSAGE: %r' % (body, ))
       message.ack()

celery = Celery(broker='amqp://localhost//')
celery.steps['consumer'].add(CustomConsumer)
celery.user_options['worker'].add(
    Option('--enable-custom-consumer', action='store_true',
           help='Enable our custom consumer.'),
)

rawDescription: Using Celery with existing RabbitMQ messages


code:
0x02
0x104
import ctypes
ctypes.c_int(0x104)

rawDescription: How do I properly pass a hex value into a C dll in Python ctypes?

description: Properly pass a hex value into a C dll in Python ctypes


code:
path = Path(VERTS, CODES)
outline = path.to_polygons()

rawDescription: Matplotlib export text as line elements in Python


code:
def icon32(PATH):
    SHGFI_ICON = 0x000000100
    SHGFI_ICONLOCATION = 0x000001000
    SHIL_EXTRALARGE = 0x00002
    ret, info = shell.SHGetFileInfo(PATH, 0, SHGFI_ICONLOCATION | SHGFI_ICON | SHIL_EXTRALARGE)
    hIcon, iIcon, dwAttr, name, typeName = info
    tempDirectory = os.getenv("temp")
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    #creating a destination memory DC
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), hIcon)
    win32gui.DestroyIcon(hIcon)
    hbmp.SaveBitmapFile(hdc, tempDirectory + "\Icontemp.bmp")
    icon = QIcon(tempDirectory + "\Icontemp.bmp")
    os.remove(tempDirectory + "\Icontemp.bmp")
    return icon

rawDescription: Python- Saving/Accessing file extension icons and using them in a Tkinter program


code:
from multiprocessing import Pool

def api_call(id):
    pass # call API for given id

if __name__ == '__main__':
    p = Pool(5)
    p.map(api_call, [1, 2, 3])

rawDescription: calling an api concurrently in python

description: Calling an api concurrently in python


code:
df = pd.DataFrame({'a':range(3), 'b':list('abc')})
s = StringIO()
df.to_csv(s)
my_csv = s.getvalue()
my_csv

rawDescription: pandas and csv how to create csv as a string without saving

description: Pandas and csv how to create csv as a string without saving


rawDescription: How do I query for a set of all unique values present in my table?

description: Query for a set of all unique values present in my table


code:
import bisect
grid = [0, 5, 10, 15, 20]
value = 8
bisect.bisect(grid, value)

rawDescription: A pythonic way how to find if a value is between two values in a list


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText

# make some data
x = np.arange(10)
y = x

# set up figure and axes
f, ax = plt.subplots(1,1)

# loc works the same as it does with figures (though best doesn't work)
# pad=5 will increase the size of padding between the border and text
# borderpad=5 will increase the distance between the border and the axes
# frameon=False will remove the box around the text

anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)

plt.show()

rawDescription: automatically position text box in matplotlib

description: Automatically position text box in matplotlib


code: parser.add_argument("foo", help="Give me an arbitrary number of arguments", nargs="+")

rawDescription: Forcing argparse to take everything as one input


code:
import re
re.sub("&#(\d+);",lambda x:unichr(int(x.group(1),10)),": or .")

rawDescription: How do I convert characters like ":" to ":" in python?

description: Convert characters like ":" to ":" in python


code:
import numpy as np
from scipy.interpolate import interp1d

ntime, nheight_in, nlat, nlon = (10, 20, 30, 40)

heights = np.linspace(0, 1, nheight_in)

t_in = np.random.normal(size=(ntime, nheight_in, nlat, nlon))
f_out = interp1d(heights, t_in, axis=1)

nheight_out = 50
new_heights = np.linspace(0, 1, nheight_out)
t_out = f_out(new_heights)

rawDescription: Best way to interpolate a numpy.ndarray along an axis

description: Interpolate a numpy.ndarray along an axis


code:
# tasks.py
import redis
from celery import shared_task

@shared_task
def update_number():
    r = redis.StrictRedis()
    r.set('my_number', randint(0,9))

# views.py
import redis

def home(request):
    r = redis.StrictRedis()
    context = {
        'add': r.get('my_number')
    }
    return render(request, 'home.html', context)

# settings.py
from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    'context': {
        'task': 'tasks.update_number',
        'schedule': crontab(minute=30),
    }
}

rawDescription: How to periodically schedule a task django celery

description: Periodically schedule a task django celery


code:
import scipy.spatial.distance as ssd
distmatrix = ssd.squareform(distmatrix + distmatrix.T)

rawDescription: Distance calculation in hierarchical clustering "complete" linkage


code:
formulario =   get_object_or_404(adendum,adendum_credencial=credencial,
    adendum_fecha__year=date_for_search.year,
    adendum_fecha__month=date_for_search.month,
    adendum_fecha__day=date_for_search.day,
    adendum_fecha__hour=1)

rawDescription: Filter by Datetime

description: Filter by Datetime


code:
#!/usr/bin/env python3

import xmlrpc.client

# PyPI classifiers for all Python 3 versions
PY3 = [
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.0",
    "Programming Language :: Python :: 3.1",
    "Programming Language :: Python :: 3.2",
    "Programming Language :: Python :: 3.3",
    "Programming Language :: Python :: 3.4",
]

# PyPI classifiers for all Python 2 versions
PY2 = [
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.7",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.5",
    "Programming Language :: Python :: 2.4",
    "Programming Language :: Python :: 2.3",
]

def main():
    client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi')
    # name[0] is package name
    # name[1] is package version
    py3names = [
        name[0] for classifier in PY3 for name in client.browse([classifier])
    ]
    py2names = [
        name[0] for classifier in PY2 for name in client.browse([classifier])
    ]
    py3only = [name for name in py3names if name not in py2names]
    template = "Python3-only packages: {} (of {})"
    print(template.format(len(py3only), len(set(py2names + py3names))))

if __name__ == "__main__":
    main()

rawDescription: Is there somewhere an index of Py3k-only libraries?


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

def xticklabels_example():
    fig = plt.figure()

    x = np.arange(20)
    y1 = np.cos(x)
    y2 = (x**2)
    y3 = (x**3)
    yn = (y1,y2,y3)
    COLORS = ('b','g','k')

    for i,y in enumerate(yn):
        ax = fig.add_subplot(len(yn),1,i+1)

        ax.plot(x, y, ls='solid', color=COLORS[i])

        if i != len(yn) - 1:
            # all but last
            ax.set_xticklabels( () )
        else:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(14)
                # specify integer or one of preset strings, e.g.
                #tick.label.set_fontsize('x-small')
                tick.label.set_rotation('vertical')

    fig.suptitle('Matplotlib xticklabels Example')
    plt.show()

if __name__ == '__main__':
    xticklabels_example()

rawDescription: Matplotlib make tick labels font size smaller


code:
timeit("frozenset(a)", "a=range(100)")
timeit("hash(a)", "a=frozenset(range(100))")
timeit("(lambda x:x)(a)", "a=hash(frozenset(range(100)))")

rawDescription: Memoization when arguments can be very large


code:
from Tkinter import *

def changeMsg():
    label.configure(text="I will self destruct in 2 secs")
    label.after(2000, root.destroy)

root = Tk()
mainContainer = Frame(root)
label = Label(mainContainer, text="")
label.configure(text="msg will change in 3 secs")
label.pack(side=LEFT, ipadx=5, ipady=5)
mainContainer.pack()
label.after(3000, changeMsg)
root.title("Timed event")
root.mainloop()

rawDescription: Refreshing a window in Tkinter

description: Refreshing a window in Tkinter


code:
wait = WebDriverWait(driver, 10)
dropDown = wait.until(expected_conditions.visibility_of_element_located((By.ID, 'asd')))
select = Select(dropDown)
select.select_by_value('01')

rawDescription: Selecting options from drop down list in python using Selenium Webdriver


code:
import numpy as np
a3 = np.empty(4, dtype=[('RowName1','double'),('RowName2','double')])
a3['RowName1'] = a1
a3['RowName2'] = a2

rawDescription: Assign column and row labels to merged numpy arrays?


rawDescription: How to detect the row and column number of cellwidget user clicked on QTableWidget in PyQt4?

description: Detect the row and column number of cellwidget user clicked on QTableWidget in PyQt4


code:
import heapq

class PrioritySet(object):
    def __init__(self):
        self.heap = []
        self.set = set()

    def add(self, d, pri):
        if not d in self.set:
            heapq.heappush(self.heap, (pri, d))
            self.set.add(d)

    def get(self):
        pri, d = heapq.heappop(self.heap)
        self.set.remove(d)
        return d

rawDescription: How can I make a unique value priority queue in Python?

description: Make a unique value priority queue in Python


code:
fig = plt.Figure(figsize=(20, 3))
gs = gridspec.GridSpec(2, 1, width_ratios=[20,10], height_ratios=[10,5])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplots(gs[1])

ax1.plot(...)
ax1.set_ylabel(...)
...

ax2.plot(...)
ax2.set_xlabel(...)

rawDescription: how to resize figures within a subplot using matplotlib

description: Resize figures within a subplot using matplotlib


code:
import sys, logging

class Logger:
    def __init__(self, name):
        formatter = logging.Formatter('%(filename)s:%(lineno)s %(levelname)s:%(message)s')
        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setFormatter(formatter)
        self.logger=logging.getLogger(name)
        self.logger.addHandler(stdout_handler)
        self.logger.setLevel(logging.DEBUG)

    def debug(self, message):
        self.logger.debug(message)

rawDescription: Weird stuff happening while importing modules


code:
resultquery = (Q(field1='val11') | Q(field1='val12')) & ...
result = SomeModel.objects.filter(resultquery)

rawDescription: Complex filters in Django Model

description: Complex filters in Django Model


code: filter(lambda x: x!='\n', obj)

rawDescription: Get rid of all white spaces in between lines


code:
mask = (r < rt) & (g < gt) & (b < bt)
image[mask] = 0

rawDescription: numpy: Setting values to zero based on multiple conditions

description: Numpy: Setting values to zero based on multiple conditions


code:
import matplotlib
import seaborn as sns; sns.set()

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
g = sns.clustermap(flights)
for l in g.ax_row_dendrogram.lines:
        l.set_linewidth(10)
for l in g.ax_col_dendrogram.lines:
        l.set_linewidth(10)

rawDescription: How to specify linewidth in Seaborn's clustermap dendrograms

description: Specify linewidth in Seaborn's clustermap dendrograms


code:
y = []
for i in x:
    y.append([i[2],i[3]])

rawDescription: extracting multiple characters from a nested list

description: Extracting multiple characters from a nested list


code:
for key, value in d.items():
    d[key] = value / 2

rawDescription: Modify dict values inplace

description: Modify dict values inplace


code:
class HouseResource(ModelResource):
    dogs = fields.ToManyField('DogResource', 'dog_set', full=True)

rawDescription: Django reverse lookup in API

description: Django reverse lookup in API


code: ax.set_position((left, bottom, width, height))

rawDescription: change the colorbar width

description: Change the colorbar width


code:
def grep(regex, base_dir):
    matches = list()
    # os.walk() returns a tuple - the directory path, a list of directories and the files
    for dirpath, dirname, files in os.walk(base_dir):
        # Iterate through the directory list, reading the files
        for directory in dirname:
          for filename in os.listdir(directory):
              with open(os.path.join(base_dir, directory, filename)) as fh:
                  content = fh.read()
                  matches = matches + re.findall(regex, content)
    return matches

rawDescription: Search dir and subdirs

description: Search dir and subdirs


rawDescription: Using wget with subprocess

description: Using wget with subprocess


code:
import os
os.getcwd()
os.path.exists('j:\\Rpmv\\make.py')
os.path.exists('j:/rpmv/make.py')
os.path.isfile('j:\\Rpmv/make.py')

rawDescription: python storing path names with forward vs backward slash

description: Python storing path names with forward vs backward slash


code:
import logging

# create logger
logger = logging.getLogger('my_logger')

# create RabbitMQ handler
rh = RabbitMQHandler()  # You need to create this.

# add rh to logger
logger.addHandler(rh)

# start logging stuff
logger.error("An error!")

rawDescription: Centralize logs from Python and NodeJS thanks to RabbitMQ


code:
def isKeeper( duration ):
    if (duration > (mean_duration + (devs * std_dev_one_test))) or \
            (duration < (mean_duration - (devs * std_dev_one_test))):
        return False
    return True

durations = [duration for duration in durations if isKeeper(duration)]

rawDescription: Better way to remove statistical outliers than this?


code:
import MySQLdb
import time
import datetime

ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
              user="root",
              passwd="newpassword",
              db="db1")
x = conn.cursor()

try:
   x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
   conn.commit()
except:
   conn.rollback()

conn.close()

rawDescription: insert into a mysql database timestamp

description: Insert into a mysql database timestamp


rawDescription: pytz - Converting UTC and timezone to local time

description: Pytz - Converting UTC and timezone to local time


code:
import copy
class TestClass:
    def __init__(self, value):
        if isinstance(value, TestClass):
            self.__dict__ = copy.deepcopy(value.__dict__)
        else:
            self.data = value

rawDescription: how to assign self to another instance of itself

description: Assign self to another instance of itself


code: system("python myscript.py myargs > /dev/null 2>&1 &");

rawDescription: How to make Python script executed in background?

description: Make Python script executed in background


code:
text = "Somewhere over the rainbow Way up high And the dreams that you dreamed of Once in a lullaby..."

class Label(QtGui.QLabel):
    def __init__(self, parent=None):
        super(Label, self).__init__(parent)

    def resizeEvent(self, event):
        self.formatText()
        event.accept()

    def formatText(self):
        width = self.width()
        text = self.text()
        new = ''
        for word in text.split():
            if len(new.split('\n')[-1])<width*0.1:
                new = new + ' ' + word
            else:
                new = new + '\n' + ' ' + word
        self.setText(new)

myLabel = Label()
myLabel.setText(text)
myLabel.resize(300, 50)
font = QtGui.QFont("Courier New", 10)
font.setStyleHint(QtGui.QFont.TypeWriter)
myLabel.setFont(font)
myLabel.formatText()
myLabel.show()

rawDescription: How to auto-format the QLabel text

description: Auto-format the QLabel text


code:
def creating():
    global mySurface                # make mySurface a global variable

    a = 0
    pygame.init()

    red = (255,0,0)
    mySurface = pygame.display.set_mode((400,250))
    while a == 0:
        for event in pygame.event.get():
            if event.type == QUIT:
                a = 1               # this will stop the loop without ending the program

        pygame.draw.rect(mySurface,red,(35,23,48,64),0)
        pygame.display.update()

def otherprocedure():
    a = 0
    blue = (0,0,255)
    while a == 0:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.draw.rect(mySurface,blue,(100,100,20,20),0)     # this will just work now
        pygame.display.update()

creating()
otherprocedure()

rawDescription: Using Interface between 2 procedures with Pygame


rawDescription: replace values in an array

description: Replace values in an array


code:
self.ui.tblContents.horizontalHeader().hide()
# or
# self.ui.tblContents.horizontalHeader().setVisible(False)

self.ui.tblContents.verticalHeader().hide()
# or
# self.ui.tblContents.verticalHeader().setVisible(False)

rawDescription: How can I enable / disable QTableWidget's horizontal / vertical header?

description: Enable / disable QTableWidget's horizontal / vertical header


code:
# Initialize models
vectorizer = CountVectorizer(min_df=1)
pca = RandomizedPCA(n_components=50, whiten=True)
km = KMeans(n_clusters=2, init='random', n_init=1, verbose=1)

# Fit models
X = vectorizer.fit_transform(sentences)
X2 = pca.fit_transform(X)
km.fit(X2)

# Predict with models
X_new = vectorizer.transform(["hello world"])
X2_new = pca.transform(X_new)
km.predict(X2_new)

rawDescription: How do I convert new data into the PCA components of my training data?

description: Convert new data into the PCA components of my training data


code:
# -*- coding: utf-8 -*-
normalString = "äöü"

# Now convert to unicode. Specified encoding must match the file encoding
# in this example. In general, you must specify how the bytes-only string
# contained in "normalString" is encoded.
unicodeString = unicode(normalString, "utf-8")

with open(unicodeString, "w") as f:
    ...

rawDescription: Python and windows filesystem with none-ascii characters


code:
def inversions(s):
        count = 0
        for i in range(len(s)-1):
            for j in range(i+1,len(s)):
                if s[i] > s[j]:
                    print(s[i],s[j])
                    count +=  1
                    break
#remove 'break' if you want to count every possible
#out of order pair for a particular character in the string
        print(count)

rawDescription: Counting inversions in a string

description: Counting inversions in a string


code:
import os
import glob

filenames = glob.glob('/path/to/cake_cake*.ab1')
for filename in filenames:
    newname = filename[:-10] + '-2101plus.ab1'
    os.rename(filename, newname)

rawDescription: Python: replacing filenames

description: Python: replacing filenames


code:
url(r'^login/$',
        auth_views.login,
        {'template_name': 'your/login/template.html', 'form':YourExtendedForm},
        name='auth_login'),

rawDescription: Create 'rememeber me' feature in defult django login view


code:
# Sorry but was not able to check code below
def get_diff(fileObj1, fileObj2):
    f1Diff = []
    f2Diff = []
    outputData = []
    # x is one row
    f1Data = set(x.strip() for x in fileObj1)
    f2Data = set(x.strip() for x in fileObj2)
    f1Column1 = set(x.split('\t')[0] for x in f1Data)
    f2Column1 = set(x.split('\t')[0] for x in f2Data)
    l1Col1Diff = f1Column1 ^ f2Column1
    l2Col1Diff = f2Column1 ^ f1Column1
    commonPart = f1Column1 & f2column1
    for line in f1Data.union(f2Data):
        lineKey = line.split('\t')[0]
        if lineKey in common:
            outputData.append(line)
        elif lineKey in l1ColDiff:
            f1Diff.append(line)
        elif lineKey in l2ColDiff:
            f2Diff.append(line)
    return outputData, f1Diff, f2Diff

outputData, file1Missed, file2Missed = get_diff(open(file1, 'r'), open(file2, 'r'))

rawDescription: Python loop through two files, do computation, then output 3 files


code: soup.select('div#top div.foo.bar')

rawDescription: Match multiple CSS classes

description: Match multiple CSS classes


code:
import numpy as np
s = "[ABC] [text text] [1234]\n[DEF] [text text: text] [2345]"
lines = s.split('\n')
rows = [line.lstrip('[').rstrip(']').split('] [') for line in lines] # list comprehension
rows
np_rows = np.array(rows)
np_rows.T
np_rows.transpose()

rawDescription: python numpy text file splitting

description: Python numpy text file splitting


code: besseli_vec = numpy.frompyfunc(lambda *a: float(mpmath.besseli(*a)), 2, 1)

rawDescription: How to make mpmath function return python float?

description: Make mpmath function return python float


code:
import os
import pandas as pd

#list the files
filelist = os.listdir(targetdir)
#read them into pandas
df_list = [pd.read_table(file) for file in filelist]
#concatenate them together
big_df = pd.concat(df_list)

rawDescription: creating pandas data frame from multiple files

description: Creating pandas data frame from multiple files


code:
class Login(ndb.Model):
    # other stuff neede for authentication etc..
    user = ndb.KeyProperty(User)

    @ndb.transactional(xg=True)
    @classmethod
    def create_login(cls,username):
        # maybe pass in extra user details
        key = ndb.Key(cls, keyname)
        login = key.get()
        if login:
            raise DuplicateUsernameError(username)

        login = Login(key_name=username)
        user =  User.create_user(login=login.key)
        login.user = user.key
        login.put()
        return (login,user)

class User(ndb.Model):
    login = ndb.KeyProperty(Login)  # this property is only for convenience.
    nickname = ndb.StringProperty()
    # etc

    @classmethod
    def create_user(cls,login_key):
        # yes you would pass in more user stuff.

        user = cls(login=login_key)
        user.put()

        # the unique user key is system generated.
        return user

rawDescription: AppEngine Python - how to ensure that users register with unique uersnames


code:
players = []
for player in Player.instances:
    dist = player.distance(my_point)
    if dist <= max_radius:
        players.append((dist, player))

#Sort in order of distance. If two distances match, sort by player.
players.sort()

#Strip out dist info
players = [v for u,v in players]

#or
players = zip(*players)[1]

rawDescription: Appending list elements into the correct sorted position


code:
if value1:
    Decimal(value1) > value2

rawDescription: python: comparing values string/integer

description: Python: comparing values string/integer


code:
class Modifiedabcd(abcd):
    def test1(self, list_of_ids):
        ###some other statements
        temp = super(Modifiedabcd, self).test1(list_of_ids)
        return list(set(temp))

rawDescription: add a single line of code to a function of a class in python

description: Add a single line of code to a function of a class in python


code:
result = []
fin = open("c:/temp/temp.txt","r")
fout = open("c:/temp/temp2.txt","w")
for line in fin:
    result.append(tuple(line.strip())) #break into characters

for line in zip(*result):  #transpose
    fout.write("".join(line))  #join characters as string
    fout.write("\n")

rawDescription: numpy matrix is not completely transposed

description: Numpy matrix is not completely transposed


code:
df = pd.DataFrame({'animal': r'"cat" "dog" "cat" "fish" "dog" "cat" "cat"'.split(),
           'size': list(r'"S" "S" "M" "M" "M" "L" "L"'.split()),
           'weight': [8, 10, 11, 1, 20, 12, 12],
           'adult' : [False] * 5 + [True] * 2});
df['weight'] = '%s' %('NA')
df.to_csv("ejemplo.csv", sep=';', decimal=',',quoting=csv.QUOTE_NONE, index=False)

rawDescription: Save pandas dataframe but conserving NA values


code:
import ast
ast.literal_eval('["a", "b", "c"]')
ast.literal_eval("['a', 'b', 'c']")
ast.literal_eval('["mixed", \'quoting\', """styles"""]')

rawDescription: Single versus double quotes in json loads in Python


code:
class BaseClass(object):
    def is_the_one(self, s):
        return inspect.isclass(s)

def get_dynamic_classes(classes):
    return [type(i, (BaseClass, ), {}) for i in classes]

rawDescription: Return a list of classes created dynamically that are named the same as the names passed in in Python


code:
class TreeNode(Base):
   # ...

   @property
   def object(self):
       return self.meter or self.site

rawDescription: SQLAlchemy modelling a complex relationship using reflection


code:
class Joiner(Thread):
    def __init__(self, q):
        self.__q = q
    def run(self):
        while True:
            child = self.__q.get()
            if child == None:
                return
            child.join()

rawDescription: Python join a process without blocking parent


code:
def parse(self, response):
    sites = response.xpath('//*[@id="ctl00_ContentPlaceHolder1_divData"]/table[3]/tr')[1:-2]

    for site in sites:
        item = Digi()
        item['sl'] = site.xpath('td[1]/text()').extract()
        item['player_name'] = site.xpath('td[2]/a/text()').extract()
        item['dismissal_info'] = site.xpath('td[3]/text()').extract()
        item['bowler_name'] = site.xpath('td[4]/text()').extract()
        item['runs_scored'] = site.xpath('td[5]/b/text()').extract()
        item['balls_faced'] = site.xpath('td[6]/text()').extract()
        item['minutes_played'] = site.xpath('td[7]/text()').extract()
        item['fours'] = site.xpath('td[8]/text()').extract()
        item['sixes'] = site.xpath('td[9]/text()').extract()
        item['strike_rate'] = site.xpath('td[10]/text()').extract()
        yield item

rawDescription: Scraping Data from a table with Scrapy

description: Scraping Data from a table with Scrapy


rawDescription: Get the common prefix substring through Regex


code:
#!/usr/bin/env python

import time
from pylab import *

ion() # turn interactive mode on

# initial data
x = arange(-8, 8, 0.1);
y1 = sin(x)
y2 = cos(x)

# initial plot
line1, line2, = plot(x, y1, 'r', x, y2, 'b')
line1.axes.set_xlim(-10, 10)
line1.axes.set_ylim(-2, 2)
line1.set_label("line1")
line2.set_label("line2")
legend()
grid()
draw()

# update line 1
for i in xrange(50):
    time.sleep(0.1)

    # update data
    y1 = sin(x + float(i) / 10)

    # update plot
    line1.set_ydata(y1)
    draw()

# update line 2
for i in xrange(50):
    time.sleep(0.1)

    # update data
    y2 = cos(x + float(i) / 10)

    # update plot
    line2.set_ydata(y2)
    draw()

rawDescription: Update Lines in matplotlib

description: Update Lines in matplotlib


code:
import threading
lock = threading.Lock()

shared_dict = {}

def do_thing(user, value):
    lock.acquire()
    try:
        shared_dict[user] = value
    finally:
        # Always called, even if exception is raised in try block
        lock.release()

rawDescription: How would you make this Python Dictionary thread-safe?


code:
def unified_diff(to_file_path, from_file_path, context=1):

    """ Returns a list of differences between two files based
    on some context. This is probably over-complicated. """

    pat_diff = re.compile(r'@@ (.[0-9]+\,[0-9]+) (.[0-9]+,[0-9]+) @@')

    from_lines = []
    if os.path.exists(from_file_path):
        from_fh = open(from_file_path,'r')
        from_lines = from_fh.readlines()
        from_fh.close()

    to_lines = []
    if os.path.exists(to_file_path):
        to_fh = open(to_file_path,'r')
        to_lines = to_fh.readlines()
        to_fh.close()

    diff_lines = []

    lines = difflib.unified_diff(to_lines, from_lines, n=context)
    for line in lines:
        if line.startswith('--') or line.startswith('++'):
            continue

        m = pat_diff.match(line)
        if m:
            left = m.group(1)
            right = m.group(2)
            lstart = left.split(',')[0][1:]
            rstart = right.split(',')[0][1:]
            diff_lines.append("@@ %s %s @@\n"%(left, right))
            to_lnum = int(lstart)
            from_lnum = int(rstart)
            continue

        code = line[0]

        lnum = from_lnum
        if code == '-':
            lnum = to_lnum
        diff_lines.append("%s%.4d: %s"%(code, lnum, line[1:]))

        if code == '-':
            to_lnum += 1
        elif code == '+':
            from_lnum += 1
        else:
            to_lnum += 1
            from_lnum += 1

    return diff_lines

rawDescription: Python unified diff with line numbers from both "files"


code:
while 1:
   packet = f.read()
   if not packet:
      break
   localFile.write(packet)
f.close()

rawDescription: Python: How to download a zip file

description: Python: How to download a zip file


rawDescription: get css pseudo-element content with python or selenium

description: Get css pseudo-element content with python or selenium


code:
import numpy as np
import scipy.ndimage as ndi

data = np.random.rand(30000,2)*255       ## create random dataset

img = np.zeros((256,256))                ## blank image
for i in xrange(data.shape[0]):          ## draw pixels
    img[data[i,0], data[i,1]] += 1
img = ndi.gaussian_filter(img, (10,10))  ## gaussian convolution

rawDescription: Efficient method of calculating density of irregularly spaced points


code:
import matplotlib.pyplot as plt

import numpy as np

# Just some example data (random)
data = np.random.rand(10,5)

rows,cols = data.shape

plt.imshow(data, interpolation='nearest',
                 extent=[0.5, 0.5+cols, 0.5, 0.5+rows],
                 cmap='bwr')

rawDescription: Graphing a colored grid in python

description: Graphing a colored grid in python


code:
instances = MyModel.objects.only('name')
data = [{'name': instance.name,
         'favourite': instance.favouriteNumber()} for instance in instances]

rawDescription: Return the result of a method in a QuerySet.values() or values_list()?


code:
#Taken from http://wiki.scipy.org/Cookbook/Finding_Convex_Hull

import numpy as n, pylab as p, time

def _angle_to_point(point, centre):
    '''calculate angle in 2-D between points and x axis'''
    delta = point - centre
    res = n.arctan(delta[1] / delta[0])
    if delta[0] < 0:
        res += n.pi
    return res

def _draw_triangle(p1, p2, p3, **kwargs):
    tmp = n.vstack((p1,p2,p3))
    x,y = [x[0] for x in zip(tmp.transpose())]
    p.fill(x,y, **kwargs)

def area_of_triangle(p1, p2, p3):
    '''calculate area of any triangle given co-ordinates of the corners'''
    return n.linalg.norm(n.cross((p2 - p1), (p3 - p1)))/2.

def convex_hull(points, graphic=False, smidgen=0.0075):
    '''
    Calculate subset of points that make a convex hull around points
    Recursively eliminates points that lie inside two neighbouring points until only convex hull is remaining.

    :Parameters:
    points : ndarray (2 x m)
    array of points for which to find hull
    graphic : bool
    use pylab to show progress?
    smidgen : float
    offset for graphic number labels - useful values depend on your data range

    :Returns:
    hull_points : ndarray (2 x n)
    convex hull surrounding points
    '''

    if graphic:
        p.clf()
        p.plot(points[0], points[1], 'ro')
    n_pts = points.shape[1]
    assert(n_pts > 5)
    centre = points.mean(1)
    if graphic: p.plot((centre[0],),(centre[1],),'bo')
    angles = n.apply_along_axis(_angle_to_point, 0, points, centre)
    pts_ord = points[:,angles.argsort()]
    if graphic:
        for i in xrange(n_pts):
            p.text(pts_ord[0,i] + smidgen, pts_ord[1,i] + smidgen, \
                   '%d' % i)
    pts = [x[0] for x in zip(pts_ord.transpose())]
    prev_pts = len(pts) + 1
    k = 0
    while prev_pts > n_pts:
        prev_pts = n_pts
        n_pts = len(pts)
        if graphic: p.gca().patches = []
        i = -2
        while i < (n_pts - 2):
            Aij = area_of_triangle(centre, pts[i],     pts[(i + 1) % n_pts])
            Ajk = area_of_triangle(centre, pts[(i + 1) % n_pts], \
                                   pts[(i + 2) % n_pts])
            Aik = area_of_triangle(centre, pts[i],     pts[(i + 2) % n_pts])
            if graphic:
                _draw_triangle(centre, pts[i], pts[(i + 1) % n_pts], \
                               facecolor='blue', alpha = 0.2)
                _draw_triangle(centre, pts[(i + 1) % n_pts], \
                               pts[(i + 2) % n_pts], \
                               facecolor='green', alpha = 0.2)
                _draw_triangle(centre, pts[i], pts[(i + 2) % n_pts], \
                               facecolor='red', alpha = 0.2)
            if Aij + Ajk < Aik:
                if graphic: p.plot((pts[i + 1][0],),(pts[i + 1][1],),'go')
                del pts[i+1]
            i += 1
            n_pts = len(pts)
        k += 1
    return n.asarray(pts)

if __name__ == "__main__":

    import scipy.interpolate as interpolate

#    fig = p.figure(figsize=(10,10))

    theta = 2*n.pi*n.random.rand(1000)
    r = n.random.rand(1000)**0.5
    x,y = r*p.cos(theta),r*p.sin(theta)

    points = n.ndarray((2,len(x)))
    points[0,:],points[1,:] = x,y

    scale = 1.03
    hull_pts = scale*convex_hull(points)

    p.plot(x,y,'ko')

    x,y = [],[]
    convex = scale*hull_pts
    for point in convex:
        x.append(point[0])
        y.append(point[1])
    x.append(convex[0][0])
    y.append(convex[0][1])

    x,y = n.array(x),n.array(y)

#Taken from http://stackoverflow.com/questions/14344099/numpy-scipy-smooth-spline-representation-of-an-arbitrary-contour-flength
    nt = n.linspace(0, 1, 100)
    t = n.zeros(x.shape)
    t[1:] = n.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2)
    t = n.cumsum(t)
    t /= t[-1]
    x2 = interpolate.spline(t, x, nt)
    y2 = interpolate.spline(t, y, nt)
    p.plot(x2, y2,'r--',linewidth=2)

    p.show()

rawDescription: draw a smooth polygon around data points in a scatter plot, in matplotlib

description: Draw a smooth polygon around data points in a scatter plot, in matplotlib


code:
import base64
import os
from Tkinter import *
##The Base64 icon version as a string
icon = \
""" REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
"""
icondata= base64.b64decode(icon)
## The temp file is icon.ico
tempFile= "icon.ico"
iconfile= open(tempFile,"wb")
## Extract the icon
iconfile.write(icondata)
iconfile.close()
root = Tk()
root.wm_iconbitmap(tempFile)
## Delete the tempfile
os.remove(tempFile)

rawDescription: Embed icon in python script

description: Embed icon in python script


code:
import csv
import random

spamReader = csv.reader(open('A3_words.csv', 'r'))

data = sum([i for i in spamReader],[]) #To flatten the list
print(random.choice(data))

rawDescription: Getting random element from a csv file

description: Getting random element from a csv file


code:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
lefts = df['EndUse_91_1.0'].fillna(0)
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts)
lefts = lefts + df['EndUse_91_1.0'].fillna(0)
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts)
lefts = lefts + df['EndUse_91_1.0'].fillna(0)
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts)
plt.show()

rawDescription: Horizontal stacked bar chart in Matplotlib


code:
import random

nodeCount = 6
vertexCount = 10

vertices = {}
while len(vertices) < vertexCount:
    x = random.randint (1, nodeCount)
    y = random.randint (1, nodeCount)
    if x == y: continue
    #comment the following line if the graph is directed
    if y < x: x, y = y, x
    w = random.random ()
    vertices [x, y] = w

#just for debug
for (x, y), w in vertices.items ():
    print ('Vertex from {} to {} with weight {}.'.format (x, y, w) )

rawDescription: Generate connected undirected graph script


code:
df
df

rawDescription: Python/Pandas - DataFrame Index - Move one month forward


code:
sub_pos_list = []

last_found_pos = 0
for i in xrange(last_found_pos, len(pos_list)):
  difference = pos_list[i] - pos_list[last_found_pos]
  if difference >= 1000000:
    sub_pos_list.append(pos_list[last_found_pos:i + 1])
    last_found_pos = i

rawDescription: Create list of sublists

description: Create list of sublists


code:
class A(ndb.Model):
   some_property = ndb.KeyProperty('B' , required=True)

class B(ndb.Model):
   some_other_property = ndb.KeyProperty(A , required=True)

rawDescription: how to make ndb model declarations order independent

description: Make ndb model declarations order independent


code:
from pygame import mixer # Load the required library

mixer.init()
mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3')
mixer.music.play()

rawDescription: Playing mp3 song on python

description: Playing mp3 song on python


code:
county = []
x_coor = []
y_coor = []
observed = []
expected = []

for line in lines:
    row = line.split(',')

    county.append(row[0])
    x_coor.append(row[1])
    y_coor.append(row[2])
    observed.append(row[3])
    expected.append(row[4])

rawDescription: Python 2.7, how to store multiple fields into seperate list


code:
import numpy as np

def wc(weights):
    cs = np.cumsum(weights)
    idx = cs.searchsorted(np.random.random() * cs[-1], 'right')
    return np.unravel_index(idx, weights.shape)

rawDescription: Efficient way of sampling from indices of a Numpy array?


code:
arguments = [security,
             'add-generic-password',
             '-a', networkDict['name'],
             '-l', networkDict['name'],
             '-D', 'Airport network password',
             '-s', networkDict['uuid'],
             '-w', networkDict['pass'],
             '-T', 'group://Aiport',
             '-T', '/System/Library/CoreServices/SystemUIServer.app',
             '-T', '/Applications/System Preferences.app',
             '-T', '/usr/libexec/airportd',
             keychain]

rawDescription: Formatting a long list to 80 columns

description: Formatting a long list to 80 columns


code:
objs = A.objects.select_related().all()
for a in objs:
    print(a.name, a.meta.n_views, a.meta.created)

rawDescription: Django: Best way to join data from multiple, associate models


code:
from nltk.stem.lancaster import LancasterStemmer
st = LancasterStemmer()
st.stem('happily')
st.stem('cooks')
st.stem('helping')
st.stem('running')
st.stem('finds')

rawDescription: Is there a way to correctly remove the tense or plural from a word?


code:
def urlnorm(base, link=''):
  '''Normalizes an URL or a link relative to a base url. URLs that point to the same resource will return the same string.'''
  new = urlparse(urljoin(base, url).lower())
  return urlunsplit((
    new.scheme,
    (new.port == None) and (new.hostname + ":80") or new.netloc,
    new.path,
    new.query,
    ''))

rawDescription: Canonize / normalize an URL in Python

description: Canonize / normalize an URL in Python


code:
import datetime, calendar
date1 = datetime.date(year1, month1, day1) # month and day are 1-base
date2 = datetime.date(year2, month2, day2)
days_in_first_year = (datetime.date(year1,12,31)-date1).days
days_in_last_year = (date2 - datetime.date(year2, 1, 1)).days
if year1 != year2:
    n_days_list = [days_in_first_year]
    for year in range(year1+1, year2): n_days_list.append(365 + (1*calendar.isleap(year)))
    n_days_list.append(days_in_last_year)
else: n_days_list = [days_in_first_year + days_in_last_year]

rawDescription: How to Calculate the number of days in the year(s) between 2 dates in python


code:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')

rawDescription: How do I add a header to urllib2 opener?

description: Add a header to urllib2 opener


code:
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

def validateName(name):

    while True:
        if [i for i in name if i not in alpha]:
            continueP = raw_input("Do you want to continue, input Yes to continue, input No to Exit: ")
            if not continueP == "Yes":
                exit(1)
            else:
                name = raw_input("Please input a valid name, a valid name is only with characters A-Z: ")
                continue
        break
    print("You have entered a valid name")

name = raw_input("Please input a valid name, a valid name is only with characters A-Z: ")
validateName(name)

rawDescription: Nested For loop in python?

description: Nested For loop in python


code: foreground = self.foreground or c4d.COLOR_TRANS

rawDescription: Is there a better solution for this ternary condition?


code:
1+1
_
def f(x):
    return x+1

f(3)
_

rawDescription: Does python have Matlab's `ans` variable that captures returned value not stored in any variable?


code:
import RPi.GPIO as GPIO
GPIO.BOARD
GPIO.BCM

rawDescription: GPIO.getmode() in Python on Raspberry Pi gets different value than on wiki


code:
text = "thisfragmentiwant"
text[4 : 12]

rawDescription: How to cut a specific fragment from a given string

description: Cut a specific fragment from a given string


rawDescription: Stripping characters from tuples in a list


code:
import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

rawDescription: Different logging levels for filehandler and display in Python


code:
import pandas as pd

data = pd.read_csv("mycsv.csv")

rawDescription: Store data in array as an input file in python


code:
idx1 = A[:,0]<B[:,0]
idx2 = A[:,1]>B[:,1]
idx = np.column_stack((idx1,idx2))
np.where(idx,A,B)

rawDescription: Python/NumPy: Return a List of Smaller (LHS) + Larger Elements (RHS) out of the Two Lists


code:
from django.utils.hashcompat import md5_constructor
from django.utils.http import urlquote

def template_cache_key(fragment_name, *vary_on):
    """Builds a cache key for a template fragment.

    This is shamelessly stolen from Django core.
    """
    base_cache_key = "template.cache.%s" % fragment_name
    args = md5_constructor(u":".join([urlquote(var) for var in vary_on]))
    return "%s.%s" % (base_cache_key, args.hexdigest())

rawDescription: How can explicitly reset a template fragment cache in Django?


code:
import numpy as np

size = 2000

a = np.arange(size)
np.random.shuffle(a)
b = np.arange(size)
np.random.shuffle(b)
c = np.random.rand(size,1)

matrix = np.column_stack((a,b,c))

#get unique value list of nm
fields = np.unique(matrix[:,:2])
n = len(fields)

#make reverse lookup dict
lookup = dict(zip(fields, range(n)))

#make empty n by n matrix
t1 = np.zeros([n, n])

for src, dest, val in matrix:
    i = lookup[src]
    j = lookup[dest]

    t1[i, j] += val

rawDescription: Transforming a 3 Column Matrix into an N x N Matrix in Numpy


code:
import urllib
urllib.urlretrieve('http://www.example.com/myfile.zip', 'path/to/download/dir/myfile.zip')

rawDescription: Download an internet resource in Python and save it on my desired location


code:
def importIfPresent():
  global opt
  if chkFunction() is True:
      opt = importlib.import_module("myOptionModule")

rawDescription: Is there an accepted way in Python to import a module from within a function?


code: return reverse(f, *args)

rawDescription: What is an alternative to eval in this situation?


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

# some artificial data
data = np.random.multivariate_normal([0,0], [[1,-0.5],[-0.5,1]], size=100)

# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 10.5)
sns.regplot(data[:,0], data[:,1], ax=ax)
sns.despine()

rawDescription: How do I change the plot size of a regplot in Seaborn?

description: Change the plot size of a regplot in Seaborn


rawDescription: Transparent inline matplotlibs in IPython


code:
def get_by_id(cls, id, session=session):
    return session.query(cls).filter_by(id=id).one()

Base.get_by_id = classmethod(get_by_id)

rawDescription: How to write a common get_by_id() method for all kinds of models in Sqlalchemy?

description: Write a common get_by_id() method for all kinds of models in Sqlalchemy


code: result = list(db.collection.find())

rawDescription: PyMongo and toArray() method

description: PyMongo and toArray() method


code:
idx = training_data[:,334] == 0
mean = np.nanmean(training_data[idx, 2])

rawDescription: Finding a Mean of an Attribute for a Specific Class in Python


code:
from ctypes import *

liblibrary = cdll.LoadLibrary('liblibrary.so')

def py_library_hook(strings, n):
    return 0

# First argument to CFUNCTYPE is the return type:
LIBRARY_HOOK_FUNC = CFUNCTYPE(c_int, POINTER(c_char_p), c_int)
hook = LIBRARY_HOOK_FUNC(py_library_Hook)
ptr = c_void_p.in_dll(liblibrary, 'library_hook')
ptr.value = cast(hook, c_void_p).value

rawDescription: How do I use ctypes to set a library's extern function pointer to a Python callback function?

description: Use ctypes to set a library's extern function pointer to a Python callback function


code:
photo_keys = [ndb.Key(Photo, id) for id in photoid_list]
photos = ndb.get_multi(photo_keys)

rawDescription: filter by id in ndb model

description: Filter by id in ndb model


code:
import time, calendar, datetime, numpy
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# draw map with markers for float locations
m = Basemap(projection='hammer',lon_0=180)
m.drawmapboundary(fill_color='#99ffff')
m.fillcontinents(color='#cc9966',lake_color='#99ffff')

m.scatter([-73.98, 238., 0.08, 0., 116.38],[40.78,47.6,  51.53,0., 39.91],
          latlon=True, # Ta-da!
          marker='o',color='k',
          zorder=10)

plt.title('Hammer projection, data on top',fontsize=12)
plt.show()

rawDescription: scatter plot data does not appear on continents in 'hammer' basemap

description: Scatter plot data does not appear on continents in 'hammer' basemap


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

def sigmoid(x):
    a = []
    for item in x:
        a.append(1/(1+math.exp(-item)))
    return a

x = np.arange(-10., 10., 0.2)
sig = sigmoid(x)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Move left y-axis and bottim x-axis to centre, passing through (0,0)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

# Eliminate upper and right axes
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Show ticks in the left and lower axes only
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.plot(x,sig)
plt.show()

rawDescription: Drawing axis in the middle of the figue in python


code: row = [x.strip() for x in row]

rawDescription: How to remove leading and trailing spaces from strings in a Python list

description: Remove leading and trailing spaces from strings in a Python list


rawDescription: why are assigning functions to identifiers necessary while invoking them?

description: Why are assigning functions to identifiers necessary while invoking them


rawDescription: Getting the different between two 2D lists


code:
def drui(request):
    disease_id = request.GET.get('disease_id', '2')
    disease = get_object_or_404(Disease, pk=disease_id)

    if request.method == "POST":
       diseaseForm = DiseaseForm(request.POST, instance=disease)
       if diseaseForm.is_valid():
          new_disease = diseaseForm.save(commit=False)
          indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES,
                                                    instance=new_disease)
          if indicatorInlineFormSet.is_valid():
             new_disease.save()
             indicatorInlineFormSet.save()
             return HttpResponseRedirect(reverse(somewhere))
    else:
       diseaseForm = DiseaseForm(instance=disease)
       indicatorInlineFormSet = IndicatorFormSet(instance=disease)

    return render_to_response("drui.html", {
        'diseaseForm': diseaseForm,
        'indicatorInlineFormSet': indicatorInlineFormSet
    },context_instance=RequestContext(request))

rawDescription: Django populating initial data in formset


code:
from sys import argv

script, filenames = argv[0], argv[1:]

# looping through files
for file in filenames:
    print('You opened file: {0}'.format(file))
    with open(file) as f:
        words = [line.split() for line in f] # create a list of the words in the file
        # note the above line will create a list of list since only one line exists,
        # you can edit/change accordingly
        print('There are {0} words'.format(len(words[0]))) # obtain length of list
        print('The first word is "{0}" and it is of length "{1}"'.format(words[0][0],
                                                                         len(words[0][0])))
        # the above line provides the information, the first [0] is for the first
        # set in the list (loop for multiple lines), the second [0] extract the first word
    print('*******-------*******')

rawDescription: Python - How to Accept and Loop Over Multiple Files? Using agrv


code:
for col in df.columns:
    if 'Unnamed' in col:
        del df[col]

rawDescription: Deleting mulitple columns in Pandas

description: Deleting mulitple columns in Pandas


code:
if p2cwrite is not None:
    self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
if c2pread is not None:
    if universal_newlines:
        self.stdout = os.fdopen(c2pread, 'rU', bufsize)
    else:
        self.stdout = os.fdopen(c2pread, 'rb', bufsize)
if errread is not None:
    if universal_newlines:
        self.stderr = os.fdopen(errread, 'rU', bufsize)
    else:
        self.stderr = os.fdopen(errread, 'rb', bufsize)

rawDescription: In subprocess.Popen, which file does bufsize apply to?


code:
class A(object):
    pass

class A:
    pass

rawDescription: Python 'object' type and inheritance

description: Python 'object' type and inheritance


code: reverse_df['week_str'] = pd.to_datetime((np.arange(1,366,7)[reverse_df['week']]).astype(str) + reverse_df['year'].astype(str), format="%j%Y")

rawDescription: python pandas find first day and year of timeseries.weekofyear

description: Python pandas find first day and year of timeseries.weekofyear


code:
payload = {'some':'data'}
headers = {'content-type': 'application/json'}
url = "https://www.toggl.com/api/v6/" + data_description + ".json"
response = requests.delete(url, data=json.dumps(payload), headers=headers,auth=HTTPBasicAuth(toggl_token, 'api_token'))

rawDescription: How to do a HTTP DELETE request with Requests library

description: Do a HTTP DELETE request with Requests library


code:
class First(object):

    glob = 'Global data'

    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
        #print (arg1, arg2)

class Second(First):
    def __init__(self, *args):
        super(Second, self).__init__(*args)
        print (self.glob, self.arg1, self.arg2)

data1 = 'First data part'
data2 = 'Second data part'

inst1 = First(data1, data2)
inst2 = Second(data1, data2)

rawDescription: Inherit variable from superclass

description: Inherit variable from superclass


code:
def trim_equations_lwidth( equation_list, width ):
  '''expects string-expressions like "1 + 3 = x"
  and trims all of the left expr to same width.
  Expects width to be >= length of lexp
  '''

  def _replace(equation):
     lexpr = equation[:equation.find('=')]
     return equation.replace(lexpr, lexpr.rjust(width, ' '))

  ltrimmed_equations = [_replace(equation) for equation in equation_list]

  return ltrimmed_equations

rawDescription: Improve pythons list conprehensions using local function/intermediate variable for readability


code:
def decorate_method(f):
  def wrapper(self, name, value, attrs):
    self.attrs = attrs
    return f(self, name, value, attrs)
  return wrapper

def decorate_class(c):
  for n in dir(c):
    f = getattr(c, n)
    if hasattr(f, 'im_func'):
      setattr(c, n, decorate_method(f.im_func))

rawDescription: Decorating Instance Methods in Python

description: Decorating Instance Methods in Python


code:
plt.hist(np.log(x), bins=50, normed=True)
plt.xticks(np.log(z), z)

rawDescription: choose scale of x values in matplotlib

description: Choose scale of x values in matplotlib


code:
import re
usa = (u'ç¾Žå›½', u'ç±³å›½', u'ë¯¸êµ')
re.sub('|'.join(usa), 'USA', u'ç¾Žå›½ is a country.')

rawDescription: Regular Expressions Python - unicode to plain text


code:
def biggest(a, y, z):
    Max = a
    if y > Max:
        Max = y
    if z > Max:
        Max = z
        if y > z:
            Max = y
    return Max

rawDescription: Find the maximum of three numbers in python


rawDescription: Python & Matlab Difference in Matrix Calculation for Nesting Loop


code:
tuple = ('a','b','c')
list = ['a','b','c']
dict = {'a':1, 'b': true, 'c': "name"}

list.append('d') #will add 'd' to the list
list[0] #will get the first item 'a'

list.insert(i, x) # Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.pop(2) # will remove items by postion, remove the 2nd item
list.remove(x) # Remove the first item from the list whose value is x.

list.index(x) # Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x) # Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False) # Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse() # Reverse the elements of the list, in place.

rawDescription: Python: Array v. List

description: Python: Array v. List


code:
f = open('workfile', 'w')
for l in list:
       f.write(l)
       f.write("\n")
f.close()

rawDescription: How to write the elements of a list into file by lines?

description: Write the elements of a list into file by lines


code:
import matplotlib.pyplot as plt

y  = [0, 0, -4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0]
x = xrange(len(y))

fig, ax = plt.subplots(1, 2)
# show with default limits
h0 = ax[0].bar(x, y)
# same data, but explicitly set x range
h1 = ax[1].bar(x, y)
ax[1].set_xlim(x[0], x[-1]+1)

plt.show()

rawDescription: How to disable auto zoom in a matplotlib bar chart?

description: Disable auto zoom in a matplotlib bar chart


code:
my_plot = pg.PlotWidget()
my_layout.addWidget(my_plot)
my_plot.plot(x, y)

rawDescription: Embedding PyQtGraph in Qt without generating new Window


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

data = np.random.random((100, 10))
extent = [0.0001, 0.001, 100, 200]

plt.figure(1)
plt.imshow(data)

plt.figure(2)
plt.imshow(data, extent=extent)

plt.figure(3)
plt.imshow(data, extent=extent, aspect='auto')

plt.show()

rawDescription: Labelling axes in matplotlib

description: Labelling axes in matplotlib


code:
import datetime
import pytz

ts = '2005-01-03 16:00:00:000 America/New_York'
tPart, tzPart = ts.rsplit(' ', 1)
dt = datetime.datetime.strptime(tPart, "%Y-%m-%d %H:%M:%S:%f")
tz = pytz.timezone(tzPart)
d = tz.localize(dt)

rawDescription: How to convert string with timezone string to datetime?

description: Convert string with timezone string to datetime


code:
# Our string with the text that we're after.
blob = "filler text filler text BEGIN This is what we're after. END filler text."

# Use .find() to find the first occurrence of two given substrings.
start = blob.find("BEGIN")
end = blob.find("END")

# Our result will be: 'BEGIN This is what we're after. '
result = blob[start:end]

rawDescription: How do I set where a string starts and ends in python?

description: Set where a string starts and ends in python


code:
# Use the with statement to open a file so it will later be closed automatically
with open("in.bin", "rb") as infile:  # rb = read binary
    infile.seek(0x3F000, 0)           # 0 = start of file, optional in this case
    data = infile.read(0x800)

with open("out.bin", "wb") as outfile:
    outfile.write(data)

rawDescription: Extract certain offsets in a file with python


code: connect_string = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(DB_USER, DB_PASS, DB_HOST, DB_PORT, DATABASE)

rawDescription: Using SQLAlchemy and pymysql, how can I set the connection to utilize utf8mb4?


code:
my_obj = MyModel.objects.get(pk=1)
my_obj._state.db

rawDescription: How to get the database where a model instance was saved to in Django?

description: Get the database where a model instance was saved to in Django


code:
def clean_text(rgx_list, text):
    new_text = text
    for r in rgx_list:
        new_text = re.sub(rgx, '', new_text)
    return new_text

rawDescription: Python regex, how to delete all matches from a string


code:
import csv

n = 3
m = 5

read = 0
with open("so.csv") as csvfile:
    reader = csv.reader(csvfile)
    for record in reader:
        read += 1
        if read >= n and read <= m:
            print(record)

rawDescription: Python csv seek() not working

description: Python csv seek() not working


code:
scribble=open("scrib1.txt")
for line in scribble:
    if line.startswith("<polygon"):
        rightline=line.split('"')
commas=rightline[13].split(' ')
newlist=[]
for i in commas:
    tup=i.split(',')
    newlist.append((tup[0],tup[1]))

rawDescription: Parsing SVG file paths with Python

description: Parsing SVG file paths with Python


rawDescription: Pandas DataFrame extract columns where all


code:
from nose.tools import assert_not_equal
assert_not_equal(1, 1)

rawDescription: Is there a shortcut for self.assertNotEqual() in nose?


code:
np.random.seed(0)
y = np.random.normal(size=37, loc=2, scale=1.5)
fig, (ax1, ax2) = plt.subplots(ncols=2)
x = np.array([0] * y.shape[0])
ax1_lim = ((0, min(y)), (len(x), max(y)))
ax2_lim = ((0, min(y) * 328), (len(x), max(y) * 328))
ax1.update_datalim(ax1_lim)
ax2.update_datalim(ax2_lim)
ax1.autoscale()
ax2.autoscale()

rawDescription: Use matplotlib Axes autoscaling without plotting anything


rawDescription: Numpy array operation using another indices array