code:
data = re.sub(r"Content-Type: image.*-----","Content-Type: imageXXXXXXX-----",
              raw_data, 0, re.DOTALL)

rawDescription: python re module to replace the binary data inside a text file?

description: Python re module to replace the binary data inside a text file


code:
lookupDictionary = input()
dictionaryTest = {
    1 : lambda: file1.write(variableTowrite)
}
dictionaryTest.get(lookupDictionary)()

rawDescription: Using Lambda in Python with a Dictionary


code:
import dateutil.rrule as DateRule
import datetime as DT

def NextRunTime(After):
    Sched = {'Hours': [12,18], 'Days': [0,1,2,3,4]}
    rule = DateRule.rrule(DateRule.HOURLY,
                          byweekday=Sched['Days'],
                          byhour=Sched['Hours'],
                          byminute=0,
                          bysecond=0,
                          bysetpos=1,
                          # dtstart=After means rule might return After
                          dtstart=After,
                          # To ensure NextRunTime returns something after After, use
                          # dtstart=After+DT.timedelta(seconds=1),
                          count=1)
    return rule[0]

tests = [
    (DT.datetime(2013,4,29,10,11,12),
     DT.datetime(2013,4,29,12,0,0)),
    (DT.datetime(2013,4,29,11,22,33),
     DT.datetime(2013,4,29,12,0,0)),
    (DT.datetime(2013,4,29,12,0,1),
     DT.datetime(2013,4,29,18,0,0)),
    (DT.datetime(2013,5,3,12,0,1),
     DT.datetime(2013,5,3,18,0,0)),
    (DT.datetime(2013,5,3,18,0,1),
     DT.datetime(2013,5,6,12,0,0)),
    (DT.datetime(2013,4,29,12,0,0),  # Note that NextRunTime(After) returns After
     DT.datetime(2013,4,29,12,0,0)),
    ]

for After, answer in tests:
    result = NextRunTime(After)
    try:
        assert result == answer
    except AssertionError:
        print('''\
result:
{result}
answer:
{answer}
'''.format(**locals()))
        raise

rawDescription: rrule in future but relative to this morning

description: Rrule in future but relative to this morning


code:
import pygame
pygame.init()
pygame.mixer.Sound('sound.wav').play()

rawDescription: Python 2.7 library for WAV+FLAC file verification, analysis, and visualization


code:
import pandas as pd
import numpy as np
from io import BytesIO
text = """A    B    C
x    x    0
x    x    5
x    x    2
x    x    0
x    x    0
x    x    3
x    x    0
y    x    1
y    x    10
y    x    0
y    x    5
y    x    0
y    x    0"""

df = pd.read_csv(BytesIO(text), delim_whitespace=True)

def count_consecutive_zeros(s):
    v = np.diff(np.r_[0, s.values==0, 0])
    s = pd.value_counts(np.where(v == -1)[0] - np.where(v == 1)[0])
    s.index.name = "num_consecutive_zeros"
    s.name = "count"
    return s

df.groupby(["A", "B"]).C.apply(count_consecutive_zeros).reset_index()

rawDescription: Pandas calculate length of consecutive equal values from a grouped dataframe


code:
def _get_appdata_path():
    import ctypes
    from ctypes import wintypes, windll
    CSIDL_APPDATA = 26
    _SHGetFolderPath = windll.shell32.SHGetFolderPathW
    _SHGetFolderPath.argtypes = [wintypes.HWND,
                                 ctypes.c_int,
                                 wintypes.HANDLE,
                                 wintypes.DWORD,
                                 wintypes.LPCWSTR]
    path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
    result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf)
    return path_buf.value

def dropbox_home():
    from platform import system
    import base64
    import os.path
    _system = system()
    if _system in ('Windows', 'cli'):
        host_db_path = os.path.join(_get_appdata_path(),
                                    'Dropbox',
                                    'host.db')
    elif _system in ('Linux', 'Darwin'):
        host_db_path = os.path.expanduser('~'
                                          '/.dropbox'
                                          '/host.db')
    else:
        raise RuntimeError('Unknown system={}'
                           .format(_system))
    if not os.path.exists(host_db_path):
        raise RuntimeError("Config path={} doesn't exists"
                           .format(host_db_path))
    with open(host_db_path, 'r') as f:
        data = f.read().split()

    return base64.b64decode(data[1])

rawDescription: How can I get the Dropbox folder location programmatically in Python?

description: Get the Dropbox folder location programmatically in Python


code:
with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in myDict.iteritems():
        writer.writerow(row)

rawDescription: Write python dictionary to CSV columns: keys to first column, values to second


rawDescription: How to join list of strings?

description: Join list of strings


code: result = exec("python script.py params")

rawDescription: Call python script from ruby

description: Call python script from ruby


code:
import sys
def noInf(f):
  def wrapped(*args, **kwargs):
    res = f(*args, **kwargs)
    if res == float('inf'):
      return sys.float_info.max
    return res
  return wrapped

@noInf
def myMult(x, y):
  return x*y

print(myMult(sys.float_info.max, 2)) # prints 1.79769313486e+308

rawDescription: Python: Return max float instead of infs?


code:
import sys
import time
from gmpy2 import powmod
from concurrent import futures

BLOCKSIZE = 10**8

def blocktest(block):
    start = max(10, block * BLOCKSIZE)
    end = (block + 1) * BLOCKSIZE

    now = time.time()
    result = []
    result.extend(i for i in range(30*(start//30) + 1, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 7, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 11, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 13, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 17, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 19, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 23, end, 30) if powmod(2, i-1, i) == i-3)
    result.extend(i for i in range(30*(start//30) + 29, end, 30) if powmod(2, i-1, i) == i-3)

    return (start, end - 1, time.time() - now, result)

if __name__ == "__main__":
    print("starting time: ", time.strftime("%H:%M:%S"))
    with futures.ProcessPoolExecutor(max_workers=4) as executor:
        for s, e, t, r in executor.map(blocktest, range(10)):
            print("range({:,}, {:,}) time: {} et: {:6.2f} {!r}".format(s, e, time.strftime("%H:%M:%S"), t, r))

rawDescription: Checking divisibility of numbers

description: Checking divisibility of numbers


code: pstree -p -a

rawDescription: Grepping for Python processes

description: Grepping for Python processes


code:
import importlib
mods = {}
def loadModules(aModule):
    global mods
    mods[module] = importlib.import_module(d_utility[module])
    # or maybe globals()[module] = ... would work also (exactly as you expect it to

rawDescription: Python: import modules dynamically in different namespace


code:
class MyFilteredAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyFilteredAdmin, self).queryset(request)
        if is_related_to(self.model, Profile):
            qs = qs.exclude(user__email='guest@mysite.com')
        return qs

rawDescription: Django customize AdminModel view

description: Django customize AdminModel view


rawDescription: Parsing a WKT-file

description: Parsing a WKT-file


code:
import json

with open('json_file') as f:
    data = json.load(f)

rawDescription: converting string into a list of tuple_ python

description: Converting string into a list of tuple_ python


code:
#!/usr/bin/python

# repository.py

import wx
import sys
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin

packages = [('abiword', '5.8M', 'base'), ('adie', '145k', 'base'),
    ('airsnort', '71k', 'base'), ('ara', '717k', 'base'), ('arc', '139k', 'base'),
    ('asc', '5.8M', 'base'), ('ascii', '74k', 'base'), ('ash', '74k', 'base')]

class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        CheckListCtrlMixin.__init__(self)
        ListCtrlAutoWidthMixin.__init__(self)

class Repository(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(450, 400))

        panel = wx.Panel(self, -1)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        leftPanel = wx.Panel(panel, -1)
        rightPanel = wx.Panel(panel, -1)

        self.log = wx.TextCtrl(rightPanel, -1, style=wx.TE_MULTILINE)
        self.list = CheckListCtrl(rightPanel)
        self.list.InsertColumn(0, 'Package', width=140)
        self.list.InsertColumn(1, 'Size')
        self.list.InsertColumn(2, 'Repository')

        for i in packages:
            index = self.list.InsertStringItem(sys.maxint, i[0])
            self.list.SetStringItem(index, 1, i[1])
            self.list.SetStringItem(index, 2, i[2])

        vbox2 = wx.BoxSizer(wx.VERTICAL)

        sel = wx.Button(leftPanel, -1, 'Select All', size=(100, -1))
        des = wx.Button(leftPanel, -1, 'Deselect All', size=(100, -1))
        apply = wx.Button(leftPanel, -1, 'Apply', size=(100, -1))

        self.Bind(wx.EVT_BUTTON, self.OnSelectAll, id=sel.GetId())
        self.Bind(wx.EVT_BUTTON, self.OnDeselectAll, id=des.GetId())
        self.Bind(wx.EVT_BUTTON, self.OnApply, id=apply.GetId())

        vbox2.Add(sel, 0, wx.TOP, 5)
        vbox2.Add(des)
        vbox2.Add(apply)

        leftPanel.SetSizer(vbox2)

        vbox.Add(self.list, 1, wx.EXPAND | wx.TOP, 3)
        vbox.Add((-1, 10))
        vbox.Add(self.log, 0.5, wx.EXPAND)
        vbox.Add((-1, 10))

        rightPanel.SetSizer(vbox)

        hbox.Add(leftPanel, 0, wx.EXPAND | wx.RIGHT, 5)
        hbox.Add(rightPanel, 1, wx.EXPAND)
        hbox.Add((3, -1))

        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

    def OnSelectAll(self, event):
        num = self.list.GetItemCount()
        for i in range(num):
            self.list.CheckItem(i)

    def OnDeselectAll(self, event):
        num = self.list.GetItemCount()
        for i in range(num):
            self.list.CheckItem(i, False)

    def OnApply(self, event):
        num = self.list.GetItemCount()
        for i in range(num):
            if i == 0: self.log.Clear()
            if self.list.IsChecked(i):
                self.log.AppendText(self.list.GetItemText(i) + '\n')

app = wx.App()
Repository(None, -1, 'Repository')
app.MainLoop()

rawDescription: How to create a CheckListBox in wx python that allows multiple selections - wxComboBox

description: Create a CheckListBox in wx python that allows multiple selections - wxComboBox


code:
senseIdToSynset = {s.offset:s for s in wn.all_synsets()}
senseIdToSynset[2084071]

rawDescription: How to get the princeton WN sense id given a sense offset? Python-NLTK

description: Get the princeton WN sense id given a sense offset? Python-NLTK


code:
def get_related_managers(self):
    managers = []
    for related_object in self._meta.get_all_related_objects():
        managers.append(getattr(self, related_object.get_accessor_name()))
    return managers

rawDescription: How can I get all RelatedManagers from a particular Django Model instance?

description: Get all RelatedManagers from a particular Django Model instance


code:
import random, time
from threading import Thread

class Students(Thread):
    ''' Represents a sleepy thread.'''
    count = 1
    course = 1

    def __init__(self, number, sleepMax):
        ''' Creates a thread with a given Name
        and a random sleep interval less than the maximum. '''
        Thread.__init__(self, name = "Student " + str(number))
        self._RequestInterval = random.randint(1, sleepMax)

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''
        print(" %s, Awaiting Request: %d seconds" % \
              ( self.getName(), self._RequestInterval))
        time.sleep(self._RequestInterval)
        if Students.count >= 20:
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            print("Class", Students.course, "has reached it limit!")
            Students.course += 1
            Students.count = 0
        else:
            #print("Class ", course, " is full.")
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            Students.count += 1

def main():
    ''' Creates the user's number of threads with sleep
    interval less than the user's maximum. Then start
    the threads'''

    NumberOfStudents = 100
    RequestTimer = 5
    threadList = []
    for count2 in range(NumberOfStudents):
        threadList.append(Students(count2 + 1, RequestTimer))
    for thread in threadList: thread.start()

main()

rawDescription: Python Threading loop

description: Python Threading loop


code:
form = SomeItemCreateForm(...)
form.helper.layout = Layout(
    Field('latitude', template='custom_field_template.html'),
    Field('longitude', template='custom_field_template.html')
)

rawDescription: Unlocalize crispy forms field (such as latitude and longitude)


code:
from matplotlib import pylab

x = [1,2,3,4,5]
y = [2,4,6,8,10]

pylab.plot(x,y)
frame = pylab.gca()

frame.axes.get_xaxis().set_ticks([])
frame.axes.get_yaxis().set_ticks([])

pylab.show()

rawDescription: How to remove values on x,y axis on plot in matplotlib

description: Remove values on x,y axis on plot in matplotlib


code: [ (i,j) for i in range(1,3) for j in range(1,5) ]

rawDescription: In Python, is there a concise way to use a list comprehension with multiple iterators?


code:
import numpy as np
import scipy
import scipy.ndimage as ndimage
import scipy.ndimage.filters as filters
import matplotlib.pyplot as plt

fname = '/tmp/slice0000.png'
neighborhood_size = 5
threshold = 1500

data = scipy.misc.imread(fname)

data_max = filters.maximum_filter(data, neighborhood_size)
maxima = (data == data_max)
data_min = filters.minimum_filter(data, neighborhood_size)
diff = ((data_max - data_min) > threshold)
maxima[diff == 0] = 0

labeled, num_objects = ndimage.label(maxima)
slices = ndimage.find_objects(labeled)
x, y = [], []
for dy,dx in slices:
    x_center = (dx.start + dx.stop - 1)/2
    x.append(x_center)
    y_center = (dy.start + dy.stop - 1)/2
    y.append(y_center)

plt.imshow(data)
plt.savefig('/tmp/data.png', bbox_inches = 'tight')

plt.autoscale(False)
plt.plot(x,y, 'ro')
plt.savefig('/tmp/result.png', bbox_inches = 'tight')

rawDescription: Get coordinates of local maxima in 2D array above certain value


rawDescription: Binary random array with a specific proportion of ones?


code: lst2 = [max(x) for x in lst1]

rawDescription: Max of each tuple

description: Max of each tuple


code:
import tkinter as tki

class App(object):

    def __init__(self):
        self.root = tki.Tk()
        self.root.wm_title("Play With python")
        for r in range(8):
            self.root.rowconfigure(r, weight=1)
        for c in range(2):
            self.root.columnconfigure(c, weight=1)

        # Create a list of the Frames in the order they were created
        frames = []
        j = 0
        for i in range(1,5):
            Frame = tki.Frame(self.root, borderwidth=1, bg = 'blue')
            Frame.grid(row = j, column = 0, rowspan = 2, columnspan = 2, sticky = 'w, e, n, s')

            # Add the Frame to the list
            frames.append(Frame)

            # Also, just as an FYI, j = j + 2 can be better written like this
            j += 2

        # To demonstrate
        print(frames)

        # This is the first Frame created
        print(frames[0])

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

rawDescription: How to create multiple frames in python through For Loop?

description: Create multiple frames in python through For Loop


code:
from shapely.geometry import Point, Polygon
pt = Point(0.75, 0.25)
poly = Polygon([(0, 0), (1, 1), (1, 0)])
poly.contains(pt)

rawDescription: Find if point inside polygon on google maps using python


code:
import random
import tkinter as tk

root = tk.Tk()

psu_volts = tk.IntVar(root)
tk.Label(root, text='Mock PSU').grid(row=0, column=0)
psu = tk.Scale(root, orient=tk.HORIZONTAL, showvalue=0, variable=psu_volts)
psu.grid(row=0, column=1)

def drift():
    psu_volts.set(psu_volts.get() + random.randint(0, 8) - 4)
    root.after(200, drift)
drift()

volts_read=tk.IntVar(root)
tk.Label(root, text='PSU Volts').grid(row=1, column=0)
tk.Label(root, textvariable=volts_read).grid(row=1, column=1)

def read_psu():
    volts_read.set(psu_volts.get())
    root.after(2000, read_psu)
read_psu()

lb = tk.Label(root, text="Enter 'from=n' or 'to=n', where n is an integer")
lb.grid(row=2, column=0, columnspan=2)
envar = tk.StringVar()
entry = tk.Entry(textvariable=envar)
entry.grid(row=3, column=0)
def psu_set():
    try:
        cmd, val = envar.get().split('=')
        psu[cmd.strip()] = val
        psu_volts.set((psu['to']-psu['from'])//2)
    except Exception:
        pass
    envar.set('')
tk.Button(root, text='Change PSU', command=psu_set).grid(row=3, column=1)

root.mainloop()

rawDescription: Run Python with IDLE on a Windows machine, put a part of the code on background so that IDLE is still active to receive command


code:
df = pd.DataFrame(np.random.random((10, 2)), index=pd.DatetimeIndex(start=date(2015,1,1), periods=10, freq='D'))
df.index.name = 'Date'
df.columns = pd.MultiIndex.from_product([['Hits'], ['UK', 'FR']], names=['', 'Country'])

rawDescription: Pandas dataframe: Can you assign a label for the column names and/or the df values?


code:
import shelve
s=shelve.open('shelve.bin')
s['a']='value'

rawDescription: Python dictionary loaded from disk takes too much space in memory


code: one(next(cnt))

rawDescription: python 3 iterator not executing next

description: Python 3 iterator not executing next


code:
tmp = sorted(zip(xVars, yVars),key=lambda x: x[1])
xVars = [x[0] for x in tmp]
yVars = [x[1] for x in tmp]
xVars
yVars

rawDescription: Python sort list and associated list

description: Python sort list and associated list


code:
a = np.arange(6).reshape(3,2)  # a.shape = (3, 2)
b = np.arange(12).reshape(3,4)  # b.shape = (3, 4)

c = np.einsum('mn,ml->mnl', a, b)  # c.shape = (3, 2, 4)

rawDescription: How to do dyadics-like operations in numpy

description: Do dyadics-like operations in numpy


code:
a
list(a)

rawDescription: Access to the values of set()

description: Access to the values of set()


code:
from multiprocessing import Pool

class Foo:
    def __fetch(self, statistic):
        params = {
            'Operation': 'GetRequesterStatistic',
            'Statistic': statistic,
            'TimePeriod': 'LifeToDate'
        }
        response = self.conn.make_request(
            action=None, params=params, path='/', verb='GET'
        )
        return self.conn._process_response(response).LongValue

    def get_stats(self):
        pool = Pool()
        results = pool.map(self.__fetch, [
            'NumberHITsAssignable', 'NumberAssignmentsPending'
        ])
        data['ActiveHITs'], data['PendingAssignments'] = results

rawDescription: How to do two requests in parallel

description: Do two requests in parallel


code:
def changeWord(word):
    for letter in word:
        if letter != "i":
            word = word.replace(letter,"!")
    return word

rawDescription: How do I replace a character in a string with another character in Python?

description: Replace a character in a string with another character in Python


code:
def my_input(prompt):
    #.. blah blah..
    return the_value

month = my_input("Please enter the month")
# etc.

rawDescription: Python function parameter as a global variable


code:
name = input("Insert the name you want to delete: ")
# let's strip excessive whitespace and change to lower case:
name = name.strip().lower()
book = "data.txt"

# use 'with' construct to ensure that file is closed after use:
with open(book, 'r') as f:
    lines = f.read().splitlines()

filtered = []
for line in lines:
    try: # guard against incorrect record, e.g. 'Guido, 1956'
        name_, sex, year = line.split(',')
    except ValueError:
        print("cannot unpack this line:", line)
        continue
    if name == name_.strip().lower():
        continue # we don't want this line, so we skip it
    filtered.append(line) # line is ok, we keep it

# join list of lines into one string and write to the file:
with open(book, 'w') as f:
    f.write('\n'.join(filtered))

rawDescription: Delete a specific string from a list of strings in a file python


code:
n = 8.92138
'%.42f' % n   # what n really is
100000 * n # result is slightly lower than 892138
int(100000 * n) # int takes the floor

rawDescription: Python: How to manage rounding behavior between float and int?


code:
import sys
import types

def getobj(astr):
    """
    getobj('scipy.stats.stats') returns the associated module
    getobj('scipy.stats.stats.chisquare') returns the associated function
    """
    try:
        return globals()[astr]
    except KeyError:
        try:
            return __import__(astr, fromlist=[''])
        except ImportError:
            modname, _, basename = astr.rpartition('.')
            if modname:
                mod = getobj(modname)
                return getattr(mod, basename)
            else:
                raise

class ClassA(object):
    def __init__(self, methpath):
        super(ClassA, self).__init__()
        self.a = 1
        self.b = 2
        self.meth1 = types.MethodType(getobj(methpath), self)

a = ClassA('moduleB.meth2')
print(a.meth1())
# 3

rawDescription: Dynamically bind method to class instance in python


code: Popen(["cmd.exe"], cwd=mypath)

rawDescription: cd to user defined path in python

description: Cd to user defined path in python


code:
datetime_column = [datetime.datetime.strptime('{} {}'.format(d, t),
                                              '%Y-%m-%d %H:%M:%S')
                   for d, t in zip(date, time)]

rawDescription: converting dates and times with list comprehension

description: Converting dates and times with list comprehension


code:
import pygame

#----------------------------------------------------------------------

class Sprite:

    def __init__(self, x, y, curren_time):

        self.rect = pygame.Rect(x, y, 100, 110)

        self.images = []

        #for x in range(12):
        for x in range(1,4):
            img = pygame.image.load("ball" + str(x) +".png")
            #img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite" + str(x) +".PNG")
            self.images.append( img )

        self.current_image = 0

        self.time_num = 100 # miliseconds
        self.time_target = curren_time + self.time_num

    def update(self, curren_time):

        if curren_time >= self.time_target:

            self.time_target = curren_time + self.time_num

            self.current_image += 1

            if self.current_image == len(self.images):
                self.current_image = 0

    def render(self, window):

        window.blit(self.images[self.current_image], self.rect)

#----------------------------------------------------------------------
# CONSTANS - uppercase

BLACK = (0  ,0  ,0  )
WHITE = (255,255,255)

#----------------------------------------------------------------------
# MAIN

def main():

    pygame.init()

    window = pygame.display.set_mode((800,600))

    pygame.display.set_caption("TEST2")

    move_x, move_y = 0, 0

    clock = pygame.time.Clock()
    curren_time = pygame.time.get_ticks()

    player = Sprite(110,100, curren_time)

    font = pygame.font.SysFont(None, 150)
    pause_text = font.render("PAUSE", 1, WHITE)
    pause_rect = pause_text.get_rect( center = window.get_rect().center ) # center text on screen

    # mainloop

    state_game = True
    state_pause = False

    while state_game:

        curren_time = pygame.time.get_ticks()

        # events

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                state_game = False

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    state_game = False

                elif event.key == pygame.K_SPACE:
                    state_pause = not state_pause

                if event.key == pygame.K_LEFT:
                    move_x = -3

                elif event.key == pygame.K_RIGHT:
                    move_x = 3

                elif event.key == pygame.K_UP:
                    move_y = -3

                elif event.key == pygame.K_DOWN:
                    move_y = 3

            elif event.type == pygame.KEYUP:

                if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                    move_x = 0

                elif event.key in (pygame.K_UP, pygame.K_DOWN):
                    move_y = 0

        # moves

        if not state_pause:
            player.rect.x += move_x
            player.rect.y += move_y
            player.update(curren_time)

        # draws

        window.fill(BLACK)

        player.render(window)

        if state_pause:
            window.blit(pause_text, pause_rect)

        pygame.display.flip()

        # FPS

        clock.tick(50)

    # the end

    pygame.quit()

#----------------------------------------------------------------------

if __name__ == '__main__':
    main()

rawDescription: Pygame animation using mutiple images overlapping/not working


code:
def check_time(until_when, def_time, how_long):
    arg_dict = {def_time:how_long}
    dt = datetime.timedelta(**arg_dict)
    if until_when- datetime.datetime.now() > dt:
        input('Task has been finished.\nPress any key to quit\n')
        exit()

rawDescription: how to pass argument to datetime.timedelta

description: Pass argument to datetime.timedelta


code:
from cStringIO import StringIO
output = StringIO()
numpy.savetxt(output, numpy_array)
csv_string = output.getvalue()

rawDescription: Returning a Numpy Array as a CSV from Flask


code:
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
# Use module.__name__

rawDescription: how to get the caller's filename, method name in python

description: Get the caller's filename, method name in python


code:
my_html = """\

        <title>Something goes here</title>

            When:  {0}

""".format(raw_input("What's the start time?\n"))

rawDescription: Python mail script and inserting variables into the html code


rawDescription: Determine arguments where two numpy arrays intersect in Python


code:
def comparator(lop, rop):
    def comp(i, j, k):
        if j <= k:
            return lop(j, i) and rop(i,k)
        return lop(j, i) or rop(i,k)

    return comp

from operator import le, lt

inRange = comparator(le, lt)
inStrictRange = comparator(lt, lt)
inRange2 = comparator(lt, le)

rawDescription: Pythonic way to implement three similar integer range operators?


code:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys

class My_Model_table(QAbstractTableModel):
    def __init__(self, table_data=[], parent=None):
        super().__init__()
        self.table_data = table_data

    def rowCount(self, parent):
        return len(self.table_data)

    def columnCount(self, parent):
        return 1

    def data(self, index, role):
        if role == Qt.DisplayRole:
            value = self.table_data[index.row()]
            return value
        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter

class My_table(QTableView):
    def __init__(self, parent=None):
        super().__init__()
        self.activated.connect(self.double_click_enter)

    def double_click_enter(self, QModelIndex):
        row = QModelIndex.row()

        self.setStyleSheet(
           '''
           QTableView::item:selected:active {
                background: #00ff00;
            }
           '''
        )

        self.alarm = QTimer()
        self.alarm.timeout.connect(self.row_color_back)
        self.alarm.setSingleShot(True)
        self.alarm.start(200)
        return

    def row_color_back(self):
        self.setStyleSheet('')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    data = ['1', '2', '3', '4', '5']
    main_table = My_table()
    main_table.setModel(My_Model_table(data))

    main_table.show()
    sys.exit(app.exec_())

rawDescription: On mouse click changing selection's background color in tableview PyQt on Linux


code:
lst = [1,2,3,4]
[list(x) for x in zip(lst)]

rawDescription: Python- for each for loop iteration, append into a different list


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')

worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})

data = [
    [1, 2, 3, 4, 5],
    [2, 4, 6, 8, 10],
]

worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])

chart.add_series({
    'categories': '=Sheet1!$A$1:$A$5',
    'values': '=Sheet1!$B$1:$B$5',
    'points': [None, None, None, None, {'fill': {'color': 'red'}}],
})

worksheet.insert_chart('D3', chart)

workbook.close()

rawDescription: XLSXWRITER changing color for individual column


rawDescription: Add all Second Items of Each Sublist in List


code:
def group(items):
  iterator = iter(items)
  group = [next(iterator)]
  result =[group]
  for item in iterator:
    (a, b), (c, d) = item, group[-1]
    if a in (c, d) or b in (c, d):
      group.append(item)
    else:
      group = [item]
      result.append(group)
  return result

print(group([(1,2),(2,3),(3,4),(7,8),(8,9),(2,1),(2,3),(1,4)]))

rawDescription: Grouping Tuples that Share Elements into Separate Lists


code:
class Base:
    def __init__(self, x):
        self.x = x

    def square(self):
        return self.x**2

class Derived(Base):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

    def square(self):
        return super().square() + self.y**2

class CubeMixin(Base):
    def square(self):
        return self.x**3

class MultiplyDerived(Derived, CubeMixin):
    pass

rawDescription: Why we using super() when inherit is already enough


code:
xy = np.vstack([xx.ravel(), yy.ravel()])
xy_t = np.dot(s, xy)
xx_t, yy_t = xy_t.reshape((2, image_dimension, image_dimension))

rawDescription: Applying a Fast Coordinate Transformation in Python


code:
def reverse(num):
    return num[::-1]

def is_pal(num):
    return num == reverse(num)

inp = input("Enter a positive number:")

if is_pal(inp):
    print("{} is a palindrome".format(inp))
else:
    print("Generating...")
    while not is_pal(inp):
        inp = str(int(inp) + int(reverse(inp)))
        print(inp)

rawDescription: Python Palindrome

description: Python Palindrome


code: new_log = ActivityLog.objects.create(user=self.user, activity=activity)

rawDescription: How do I chain object instantiation with its methods?

description: Chain object instantiation with its methods


code:
keyword = "*"
keyphrase = "*"
while not(re.match('[a-z ]*$',keyword)):
    keyword = raw_input("enter a keyword:-").lower()
while not(re.match('[a-z ]*$',keyphrase)):
    keyphrase = raw_input("enter a key phrase:-").lower()

rawDescription: re.match not working in python 2.7

description: Re.match not working in python 2.7


code:
name = browser.find_element_by_css_selector('elementname')
print(name.text)

rawDescription: Object to string doesn't return expect result


code: df.col = df.col.str.slice(0, 9)

rawDescription: substring of an entire column in pandas dataframe

description: Substring of an entire column in pandas dataframe


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

class ZoomPlot():

    def __init__(self):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.xmin = -2.5; self.xmax = 1.0;
        self.ymin = -1.5; self.ymax = 1.5;
        self.xpress = self.xmin
        self.xrelease = self.xmax
        self.ypress = self.ymin
        self.yrelease = self.ymax
        self.resolution = 200
        self.maxiters = 30

        self.fig.canvas.mpl_connect('button_press_event', self.onpress)
        self.fig.canvas.mpl_connect('button_release_event', self.onrelease)
        self.plot_fixed_resolution(self.xmin, self.xmax,
                                   self.ymin, self.ymax)

    def mandlebrot(self, X, Y):
        C = X + Y*1j
        Z = C
        divtime = self.maxiters + np.zeros(Z.shape, dtype=int)
        for n in range(self.maxiters):
            Z = Z**2 + C
            diverge = Z*np.conj(Z) > 2**2
            div_now = diverge & (divtime == self.maxiters)
            divtime[div_now] = n
            Z[diverge] = 2

        return divtime

    def plot_fixed_resolution(self, x1, x2, y1, y2):
        x = np.linspace(x1, x2, self.resolution)
        y = np.linspace(y1, y2, self.resolution)
        X, Y = np.meshgrid(x, y)
        C = self.mandlebrot(X, Y)
        self.ax.clear()
        self.ax.set_xlim(x1, x2)
        self.ax.set_ylim(y1, y2)
        self.ax.pcolormesh(X, Y, C)
        self.fig.canvas.draw()

    def onpress(self, event):
        if event.button != 1: return
        self.xpress = event.xdata
        self.ypress = event.ydata

    def onrelease(self, event):
        if event.button != 1: return
        self.xrelease = event.xdata
        self.yrelease = event.ydata
        self.xmin = min(self.xpress, self.xrelease)
        self.xmax = max(self.xpress, self.xrelease)
        self.ymin = min(self.ypress, self.yrelease)
        self.ymax = max(self.ypress, self.yrelease)
        self.plot_fixed_resolution(self.xmin, self.xmax,
                                   self.ymin, self.ymax)

plot = ZoomPlot()
plt.show()

rawDescription: Python matplotlib - replot on zoom

description: Python matplotlib - replot on zoom


code:
# Tested on Ubuntu 14.04.3 LTS
os.system("x-terminal-emulator -e /bin/bash")

rawDescription: How to open new bash terminal using Python

description: Open new bash terminal using Python


code:
from multiprocessing import Pool
import math
import time

cores = 4  # Number of cores to use
wordlist = []

for i in range(127):  # Remove this for your own word list.
    wordlist.append(str(i))  # Creates a large 'word' list for testing.

def pwd_find(start, stop):

    for word in range(start, stop):
        print(wordlist[word])
        time.sleep(0.1)  # Slows things down so it's easier to see that your system is using more than one core.
        ### Add your code here... ###

break_points = []  # List that will have start and stopping points
for i in range(cores):  # Creates start and stopping points based on length of word list
    break_points.append({"start":math.ceil(len(wordlist)/cores * i), "stop":math.ceil(len(wordlist)/cores * (i + 1))})

if __name__ == '__main__':  # Added this because the multiprocessor module acts funny without it.

    p = Pool(cores)  # Number of processors to utilize.
    for i in break_points:  # Cycles though the breakpoints list created above.
        print(i)  # shows the start and stop points.
        a = p.apply_async(pwd_find, kwds=i, args=tuple())  # This will start the separate processes.
    print("Done!")
    p.close()
    p.join()

rawDescription: Python Multiprocessing password cracker

description: Python Multiprocessing password cracker


code: df["idx1_mod"] = df.index.get_level_values(0).values + 100

rawDescription: Pandas: How to access the value of the index


code:
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event
import datetime

Base= declarative_base()

def validate_int(value):
    if isinstance(value, basestring):
        value = int(value)
    else:
        assert isinstance(value, integer)
    return value

def validate_string(value):
    assert isinstance(value, basestring)
    return value

def validate_datetime(value):
    assert isinstance(value, datetime.datetime)
    return value

validators = {
    Integer:validate_int,
    String:validate_string,
    DateTime:validate_datetime,
}

# this event is called whenever an attribute
# on a class is instrumented
@event.listens_for(Base, 'attribute_instrument')
def configure_listener(class_, key, inst):
    if not hasattr(inst.property, 'columns'):
        return
    # this event is called whenever a "set"
    # occurs on that instrumented attribute
    @event.listens_for(inst, "set", retval=True)
    def set_(instance, value, oldvalue, initiator):
        validator = validators.get(inst.property.columns[0].type.__class__)
        if validator:
            return validator(value)
        else:
            return value

class MyObject(Base):
    __tablename__ = 'mytable'

    id = Column(Integer, primary_key=True)
    svalue = Column(String)
    ivalue = Column(Integer)
    dvalue = Column(DateTime)

m = MyObject()
m.svalue = "ASdf"

m.ivalue = "45"

m.dvalue = "not a date"

rawDescription: How can I verify Column data types in the SQLAlchemy ORM?

description: Verify Column data types in the SQLAlchemy ORM


code:
def setHost(host):
    global _host
    _host = host

rawDescription: Passing variables between modules

description: Passing variables between modules


code:
def isbn_dictionary(filename):
    file = open(filename, 'r')
    isbn_dict = {}
    for line in file:
        data = line.strip('\n')
        author, title, isbn = data.split(',')
        isbn_dict[isbn] = (author, title)
    print(isbn_dict)

rawDescription: Creating a dictionary from CSV data

description: Creating a dictionary from CSV data


rawDescription: Regex: how to extract only first IP address from string (in Python)


code:
import numpy as np
value = precipitationVariable[:]
mask = (value < -99999.98) & (value > -100000.00)
value = np.ma.MaskedArray(value, mask=mask)

rawDescription: How to read NetCDF variable float data into a Numpy array with the same precision and scale as the original NetCDF float values?

description: Read NetCDF variable float data into a Numpy array with the same precision and scale as the original NetCDF float values


code:
s="BANANA"
vowels = 'AIEOU'
sorted(s[i:j] for i, x in enumerate(s) for j in range(i + 1, len(s) + 1) if x in vowels)

rawDescription: Find all possible substrings begining with characters from capturing group


code: return random.choice(filter(myCondition, myList) or myList)

rawDescription: Pythonic way of doing so?

description: Pythonic way of doing so


code: englishDict = dict(map(lambda x: (convert_keys(x[0]),convert_values(x[1])),japaneseDict.items()))

rawDescription: Full re-map of keys and values in a dictionary, set, list, etc?


code:
counts = {}
for integerDatum in fileData:
  try:
    counts[integerDatum] += 1
  except KeyError:
    counts[integerDatum] = 1

rawDescription: Divide a huge data set ( integers) into some small sets.(I have a very ugly method, seek for a nicer way)


code:
import numpy as np

amp = 1.
sfreq = 1000.
duration = 1000.
nse_amp = 0.9
freq1_start = 200
freq1_end = 300
freq_band1 = np.linspace(freq1_start, freq1_end, times.size)
#____
n_epochs = 120
epoch_length = 1 # make epoch of 1 second each
times = np.arange(0,epoch_length,1/(sfreq))

def simulate_x_y(times, n_epochs, amp, freq_band1):
    x  = np.zeros((n_epochs, times.size))
    for i in range(0, n_epochs):
                    x[i] = (amp  * np.sin(2 * np.pi * freq_band1 * times))
    return x

rawDescription: Python Signal simulation for frequency band


code:
def main():
    endProgram = input('do you wish to end the program?')
    while endProgram == 'no':
        print('Welcome')
        username = 778922
        password = 2713
        login = input('What\'s your login info?')
        if login==username:
            username = int(input("Username: "))
            password = int(input("Password: "))

main()

rawDescription: How to make a program loop until the user inputs the correct username and password

description: Make a program loop until the user inputs the correct username and password


rawDescription: Simpler way of sorting list of lists indexed by one list in Python


code:
import struct

value = 13.37  # arbitrary float
bin = struct.pack('f', value)

for b in bin:
    ser.write(b)

rawDescription: python 2.7 - converting float to bytes and looping through the bytes

description: Python 2.7 - converting float to bytes and looping through the bytes


rawDescription: python pandas df: adding to one column depending on the value in that row in another column

description: Python pandas df: adding to one column depending on the value in that row in another column


code: np.arange(6).reshape(3, -1, order='F')

rawDescription: forming pairs of non-contiguous elements from an array

description: Forming pairs of non-contiguous elements from an array


code:
class Slave(object):
    def __init__(self,getfunc,setfunc):
        self.getfunc = getfunc
        self.setfunc = setfunc
    @property
    def bound_value(self):
        return self.getfunc()

    @bound_value.setter
    def bound_value(self, value):
        self.setfunc(value)

rawDescription: python: multiple objects that can modify the attributes of a single 'master' object

description: Python: multiple objects that can modify the attributes of a single 'master' object


code:
EXTENSIONS = {
    'project_name.myextension.MyExtension': 1000,
}

rawDescription: How can I trigger scrapy spider start and close?

description: Trigger scrapy spider start and close


code:
import os
import signal
from subprocess import check_output

def get_pid(name):
    return check_output(["pidof", name])

def main():
    os.kill(get_pid(whatever_you_search), signal.SIGTERM) #or signal.SIGKILL

if __name__ == "__main__":
    main()

rawDescription: Get a PID number of a process and than kill it with Python


code:
import warnings
try:
    fcntl.flock(myfile, fcntl.LOCK_EX|fcntl.LOCK_NB)
except IOError:
    warnings.warn("can't immediately write-lock the file ($!), blocking ...")
    fcntl.flock(myfile, fcntl.LOCK_EX)

rawDescription: How to use fcntl reading status of lock file?

description: Use fcntl reading status of lock file


code:
import sys
from PyQt4 import QtGui, QtCore

class TestTreeWidget(QtGui.QTreeWidget):
    def __init__(self, parent = None):
        super(TestTreeWidget, self).__init__(parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)

    def startDrag(self, dropAction):
        # create mime data object
        mime = QtCore.QMimeData()
        mime.setData('application/x-item', '???')
        # start drag
        drag = QtGui.QDrag(self)
        drag.setMimeData(mime)
        drag.start(QtCore.Qt.CopyAction | QtCore.Qt.CopyAction)

    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat("application/x-item"):
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dragEnterEvent(self, event):
        if (event.mimeData().hasFormat('application/x-item')):
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if (event.mimeData().hasFormat('application/x-item')):
            event.acceptProposedAction()
            data = QtCore.QString(event.mimeData().data("application/x-item"))
            item = QtGui.QTreeWidgetItem(self)
            item.setText(0, data)
            self.addTopLevelItem(item)
        else:
            event.ignore()

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

        self.view = TestTreeWidget(self)
        self.view.setColumnCount(1)
        item0 = QtGui.QTreeWidgetItem(self.view)
        item0.setText(0, 'item0')
        item1 = QtGui.QTreeWidgetItem(self.view)
        item1.setText(0, 'item1')
        self.view.addTopLevelItems([item0, item1])

        self.setCentralWidget(self.view)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: How do I get a handle to the TreeWidgetItem being dropped in PyQt DragNDrop?

description: Get a handle to the TreeWidgetItem being dropped in PyQt DragNDrop


code:
def branch(list_):
    if len(list_) == 1:
        return list_[0]
    else:
        return {
            0: branch(list_[:1]),
            1: branch(list_[1:])}

rawDescription: recursively cut a list into defaultdict tree leaves

description: Recursively cut a list into defaultdict tree leaves


code:
sortedSubjects = sorted(tmpSubjects.iteritems(),
                        key=operator.itemgetter(1),
                        cmp=comparator,   # What about specifying the comparison?
                        reverse=True)

rawDescription: Sort dict of tuples by either tuple value with customised comparator


code:
def combine_dicts(x, y):
    x.update(y)
    return x

def get_passwords():
    dict = {"a":"test", "b":"testa"}
    return dict

firstDict = {"this":"is", "a":"test"}
secondDict = get_passwords()
combinedDict = combine_dicts(firstDict, secondDict)

rawDescription: Appending a dict from another program in Python


code:
#completely untested.
import sys
def run_script(script_name,*args):
    _argv = sys.argv[:]
    sys.argv = list(args)
    execfile(script_name)
    sys.argv = _argv

rawDescription: execute python script with argparse inside python script

description: Execute python script with argparse inside python script


code:
def f():
    x = [1,2,3,4,5,6,7]
    return x

def g():
    x = (1,2,3,4,5,6,7)
    return x

import dis
dis.dis(f)

dis.dis(g)

rawDescription: Tuples readability : [0,0] vs (0,0)

description: Tuples readability : [0,0] vs (0,0)


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

# create some random data
data = np.random.rand(150, 10)

# get the tick label font size
fontsize_pt = plt.rcParams['ytick.labelsize']
dpi = 72.27

# comput the matrix height in points and inches
matrix_height_pt = fontsize_pt * data.shape[0]
matrix_height_in = matrix_height_pt / dpi

# compute the required figure height
top_margin = 0.04  # in percentage of the figure height
bottom_margin = 0.04 # in percentage of the figure height
figure_height = matrix_height_in / (1 - top_margin - bottom_margin)

# build the figure instance with the desired height
fig, ax = plt.subplots(
        figsize=(6,figure_height),
        gridspec_kw=dict(top=1-top_margin, bottom=bottom_margin))

# let seaborn do it's thing
ax = sns.heatmap(data, ax=ax)

# save the figure
plt.savefig('/tmp/test.png')

rawDescription: Overlapping yticklabels: Is it possible to control cell size of heatmap in seaborn?


code:
class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

rawDescription: What is the difference between SimpleNamespace and empty class definition?


code:
import praw

def get_data_reddit(search, after=None):
    r = praw.Reddit(user_agent='StackOverflow example')
    params = {"q": search}
    if after:
        params["after"] = "t3_" + str(after.id)
    posts = r.get_content(r.config['search'] % 'all', params=params, limit=100)
    return posts

search = "stackoverflow"
post = None
count = 0
while True:
    posts = get_data_reddit(search, post)
    for post in posts:
        print(str(post.id))
        count += 1
    print(count)

rawDescription: Reddit search API not giving all results


code:
from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<MouseWidget>:
    image: image
    label: label
    orientation: 'vertical'
    Image:
        id: image
        source: root.source
    Label:
        id: label
        size_hint_y: None
        height: 50
        text: 'no touch detected'

''')

class MouseWidget(BoxLayout):
    image = ObjectProperty()
    label = ObjectProperty()
    source = StringProperty()

    def on_touch_down(self, touch):
        if self.image.collide_point(*touch.pos):
            self.label.text = str(touch.pos)

    def on_touch_up(self, touch):
        self.label.text = 'no touch detected'

class MyApp(App):
    def build(self):
        root = Accordion(orientation='horizontal')

        item= AccordionItem(title='Picture1')
        src = "picture1.png"
        image = MouseWidget(source=src)
        # add image to AccordionItem
        item.add_widget(image)
        root.add_widget(item)

        item= AccordionItem(title='Picture2')
        src = "picture2.png"
        image = MouseWidget(source=src)
        # add image to AccordionItem
        item.add_widget(image)
        root.add_widget(item)

        return root

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

rawDescription: Kivy accordian interaction

description: Kivy accordian interaction


code:
def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.
    Returns string. """
    return ";".join(["%s=%s" % (k,v) for k,v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpligrim",\
        "database":"master",\
        "uid":"sa",\
        "pwd":"secret" }

    print(buildConnectionString(myParams))

rawDescription: Running program in Python [ActiveState Python on Windows]


code:
title = soup.find("meta",  property="og:title")
url = soup.find("meta",  property="og:url")

print(title["content"] if title else "No meta title given")
print(url["content"] if url else "No meta url given")

rawDescription: Get meta tag content property with BeautifulSoup and Python


code:
import urlparse
a = "sequence=1,2,3,4&counter=3,4,5,6"
{key: [int(x) for x in value[0].split(',')]
 for key, value in urlparse.parse_qs(a).items()}

rawDescription: Python - Parse a string and convert it into list


code:
if form.is_valid():
    instance = form.save(commit=False)
    instance.commonObject = pk.loads(request.session.get('commonObject'))
    instance.save()
    return self.add_success(request, instance)

rawDescription: Changing data in form.clean_data

description: Changing data in form.clean_data


code:
import os
from gi.repository import Gtk, Gio

# This allows Ctrl+C to exit the program
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

def callback(m, f, o, event):
    # Without this check, multiple 'ok's will be printed for each file change
    if event == Gio.FileMonitorEvent.CHANGES_DONE_HINT:
        print ('ok')

gio_file = Gio.File.new_for_path(os.environ['HOME']+'/temp')
monitor = gio_file.monitor_file(Gio.FileMonitorFlags.NONE, None)
monitor.connect("changed", callback)

Gtk.main()

rawDescription: Am I using Gio GFile monitor_file wrong?

description: Am I using Gio GFile monitor_file wrong


code:
class UsersModelForm(forms.ModelForm):
    passwordrepeat = forms.PasswordInput()
    class Meta:
        model = Users

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        passwordrepeat = cleaned_data.get("passwordrepeat")
        if password != passwordrepeat:
            raise forms.ValidationError("Passwords must match.")

        return cleaned_data

rawDescription: How can i compare password with retypepassword during registering/creating account without having a field 'retyppassword' in models.py?

description: Compare password with retypepassword during registering/creating account without having a field 'retyppassword' in models.py


code:
from scipy.ndimage.filters import gaussian_filter
np.random.seed(12345)
a = np.random.randn(27, 36)
b = gaussian_filter(a, 4)
ymin = 0
ymax = 1
plt.imshow(b, origin='lower', extent=[-90, 90, ymin, ymax], aspect='auto')
plt.xticks([-90, -60, -30, 0, 30, 60, 90])

rawDescription: Changing tick labels without affecting the plot


code:
def partitions(n):
    if n == 0:
        yield []
    else:
        for partial_partition in partitions(n-1):
            for i in range(len(partial_partition)):
                copy_partition = partial_partition[:]
                copy_partition[i] += (n,)
                yield copy_partition
            yield partial_partition + [(n,)]

rawDescription: Finding all possible combination of all possible subsets of lists


code:
def pmi(dff, x, y):
    df = dff.copy()
    df['f_x'] = df.groupby(x)[x].transform('count')
    df['f_y'] = df.groupby(y)[y].transform('count')
    df['f_xy'] = df.groupby([x, y])[x].transform('count')
    df['pmi'] = np.log(len(df.index) * df['f_xy'] / (df['f_x'] * df['f_y']) )
    return df

rawDescription: Can Pandas DataFrame efficiently calculate PMI (Pointwise Mutual Information)?


rawDescription: Sending bytes via UDP packets without further conversion


code:
import re

text = open( path ).read()
match_found=False
matches = re.finditer(line_pattern, text)

m = None      # optional statement. just for clarification
for m in matches:
   match_found=True
   pass       # just loop to the end

if (match_found):
   m.start()  # equals the starting index of the last match
   m.end()    # equals the ending index of the last match

   # now you can do your substring of text to add whatever
   #   you wanted to add. For example,
   text[1:m.end()] + "hi there!" + text[(m.end()+1):]

rawDescription: Python insert text after last match in search


code:
ax = sns.tsplot(gammas, time="time", unit="subj",
                condition="condition", value="BOLD", marker="o")
ax.lines[-1].set_marker("s")

rawDescription: How can I set multiple markers with tsplot?

description: Set multiple markers with tsplot


code:
from string import punctuation
"-asdf".lstrip(punctuation)
"'asdf".lstrip(punctuation)
'"asdf'.lstrip(punctuation)
',asdf'.lstrip(punctuation)

rawDescription: Strip all non alphabetic characters from beginning of Python string w/o using RegEx


rawDescription: Why does insert change my list to None type?


code:
def on_dialog_key_press(dialog, event):
    if event.string == ' ':
        dialog.response(gtk.RESPONSE_OK)
        return True
    return False

dialog = gtk.MessageDialog(message_format='Some message', buttons=gtk.BUTTONS_OK_CANCEL)
dialog.add_events(gtk.gdk.KEY_PRESS_MASK)
dialog.connect('key-press-event', on_dialog_key_press)
dialog.run()

rawDescription: How to get a gtkDialog's default response to trigger of the space bar as well

description: Get a gtkDialog's default response to trigger of the space bar as well


code:
df = DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in range(5):
    df.loc[i] = [randint(-1,1) for n in range(3)]
print(df)

rawDescription: add one row in a pandas.DataFrame

description: Add one row in a pandas.DataFrame


code:
def allsums(a):
  x = a[0]
  if len(a) > 1:
    yy = allsums(a[1:])
    return set(x + y for y in yy).union(yy)
  else:
    return set([0, x])

rawDescription: Creating a recursive function that gets the sum of all possible subsets in a list of integers


code:
a = [0.1,0.2,0.4,0.5]
b = [0.5,0.6,0.7, 0.8]

# find all of the possible sums
# - store with the sum the item indices that were used
# - enumerate will give us the index and the item
c = [(x + y, x_i, y_i) for x_i, x in enumerate(a)
                       for y_i, y in enumerate(b)]

# sort this list
# - as we are sorting tuples, it will sort on the first
#   tuple item initially (ie the sum), and then the others
# - then just take the list five items
indices = [(x_i, y_i) for _, x_i, y_i in sorted(c)[-5:]]

rawDescription: Finding the indices which has generate 5 larges sums


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

fig, axs = plt.subplots(ncols=2, sharey=True)
for ax in axs:
    ax.plot([0,1],[0,1], 'r-')
    ax.set_xticks([0.5,1.0])
    ax.set_xticklabels(['0.5','1.0'])
axs[-1].legend(('Some plot'), loc=2)
for ax in axs[1:]:
    ax.yaxis.set_visible(False)
fig.subplots_adjust(wspace=0)
plt.show()

rawDescription: matplotlib: Remove subplot padding when adding tick labels

description: Matplotlib: Remove subplot padding when adding tick labels


code:
import re

s = re.sub("[aeiou]r", "r", s) # remove a vowel preceding `r`

rawDescription: Python Beginners 3 - How do I create a loop that does this?


code: g = eval("Word(alphas) + Word(nums)")

rawDescription: pyparsing how to create grammar object from string

description: Pyparsing how to create grammar object from string


code:
food = "pizza"
json.dumps({"favorite_food":[food]})

rawDescription: Python json.dumps with string interpolation?


code:
import SendKeys

SendKeys.SendKeys("""
{CAPSLOCK}
{SCROLLOCK}
{NUMLOCK}
""")

rawDescription: Change keyboard locks in Python

description: Change keyboard locks in Python


code:
from abc import ABCMeta, abstractmethod

class ThisIsAnAbstractClass(object):
    __metaclass__ = ABCMeta # <--

    @abstractmethod
    def __init__(self, parameter):
        self.parameter = parameter

    def do_something():
        """do something"""

class ConcreteClass(ThisIsAnAbstractClass):
    def __init__(self, parameter):
        super(ConcreteClass, self).__init__(parameter)

try:
    ThisIsAnAbstractClass('test')
    assert False, 'Abstract class instance created!'
except TypeError:
    pass

assert ConcreteClass('test').parameter == 'test'

rawDescription: Testing abstract classes in Python

description: Testing abstract classes in Python


code:
from bs4 import BeautifulSoup

data = """

    NO MATCH 1
    ABBA
    NO MATCH 2

"""

soup = BeautifulSoup(data)
for a in soup.find_all('a', abcd='_blank'):
    print(a.text)

rawDescription: Python Regex matching string between abcd="_blank"> and </a>


code:
frozen = Freezer(with_no_argument_rules=False, log_url_for=False)

@frozen.register_generator
def your_generator_here():
    yield "your", {"paths": "here"}

rawDescription: Can you choose what files Frozen-Flask freezes?

description: Choose what files Frozen-Flask freezes


code:
# exclude = set([...])
for root, dirs, files in os.walk(top, topdown=True):
    dirs[:] = [d for d in dirs if d not in exclude]

rawDescription: Excluding directories in os.walk

description: Excluding directories in os.walk


code:
import win32ui

def WindowExists(windowname):
    try:
        win32ui.FindWindow(None, windowname)

    except win32ui.error:
        return False
    else:
        return True

process = True
while process == True:
    if WindowExists(r"C:\LTR_STRUC\LTR_STRUC_1_1.exe"):
        process = True
    else:
        process = False
        time.sleep(5)

rawDescription: Pass keyboard input to a windows executable


code: b = memoryview(a)[:-20]

rawDescription: linking to a part of bytes object in python 3

description: Linking to a part of bytes object in python 3


code: dollar_dec = float(dollars[1:])

rawDescription: python: how to convert currency to decimal?

description: Python: how to convert currency to decimal


code:
class MyModelAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        if not obj:
            return MyModelCreateForm
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

rawDescription: How to make separate forms for one model in Django admin

description: Make separate forms for one model in Django admin


code:
import re
data = {}
temp_s = match = ''
with open('myfile.txt', 'r') as infile:
     for line in infile:
          if ":" in line:
               line = line.split(':')
               data[line[0]] = line[1]
          elif re.search(r'.*\w+', line):
               match = re.search(r'(\w.*)', line)
               match = match.group(1)
               temp_s += match
               while 1:
                    line = infile.next()
                    if re.search(r'.*\w+', line):
                         match = re.search(r'(\w.*)', line)
                         temp_s += match.group(1)
                    else:
                         break
               data['abstract'] = temp_s

rawDescription: Read and select specific rows from text file regex Python


rawDescription: evaluating a sympy function at an arbitrary-precision floating point

description: Evaluating a sympy function at an arbitrary-precision floating point


code:
class myGUI(QtGui.QWidget):

    def __init__(self, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)

        self.data = {"multiplier": 0,
                     "multiplicand": 0}

        self.myGUIInit()

    def myGUIInit(self):
        a1_label = QtGui.QLabel("a1")
        a1_edit = QtGui.QLineEdit()
        a1_edit.setObjectName("multiplicand")

        a2_label = QtGui.QLabel("a2")
        a2_edit = QtGui.QLineEdit()
        a2_edit.setObjectName("multiplier")

        # skipped the rest because same

    def TxtChanged(self, text):
        sender = self.sender()

        # casting to int while assigning seems logical.
        self.data[sender.objectName()] = int(text)

        product = self.data["multiplier"] * self.data["multiplicand"]

        print(self.data["multiplier"], self.data["multiplicand"], product)

        self.a1a2_edit.setText(str(product))

rawDescription: Differentiating between signal sources in PySide


rawDescription: How do I search for indices that satisfy condition in numpy?

description: Search for indices that satisfy condition in numpy


rawDescription: I'm looking for a pythonic way to insert a space before capital letters


code:
import numpy as np
import matplotlib.pyplot as plt
from itertools import groupby

import numpy as np
import matplotlib.pyplot as plt
from itertools import groupby

def draw_hist(latitudes,userids):
    min_lat = -90
    max_lat = 90
    binwidth = 1

    bin_range = np.arange(min_lat,max_lat,binwidth)

    all_rows = zip(latitudes,userids)
    binned_latitudes = np.digitize(latitudes,bin_range)
    all_in_bins = zip(binned_latitudes,userids)
    unique_in_bins = list(set(all_in_bins))
    all_in_bins.sort()
    unique_in_bins.sort()

    bin_count_all = []
    for bin, group in groupby(all_in_bins, lambda x: x[0]):
        bin_count_all += [(bin, len([k for k in group]))]

    bin_count_unique = []
    for bin, group in groupby(unique_in_bins, lambda x: x[0]):
        bin_count_unique += [(bin, len([ k for k in group]))]

    # bin_count_all and bin_count_unique now contain the data
    # corresponding to the SQL / pseudocode in your question
    # for each latitude bin

    bin_density = [(bin_range[b-1],a*1.0/u) for ((b,a),(_,u)) in zip(bin_count_all, bin_count_unique)]

    bin_density =  np.array(bin_density).transpose()

    # plot as standard bar - note you can put uneven widths in
    # as an array-like here if necessary
    # the * simply unpacks the x and y values from the density
    plt.bar(*bin_density, width=binwidth)
    plt.show()
    # can save away plot here if desired

latitudes = [-70.5, 5.3, 70.32, 70.43, 5, 32, 80, 80, 87.3]
userids = [1,1,2,2,4,5,1,1,2]

draw_hist(latitudes,userids)

rawDescription: Get density of messages on distinct ID's


rawDescription: Seperate one part list into four part list with Python


code: datetime.strptime(date_string, format)

rawDescription: How do I convert a human-readable date + time to a Unix timestamp in Python?

description: Convert a human-readable date + time to a Unix timestamp in Python


code:
def pod_available(request):
    dat = request['dd']
    return HttpResponse("Hello" + str(dat) + "")

rawDescription: Retrieve date data from browser

description: Retrieve date data from browser


code:
import Tkinter as tk

class WelcomeWindow():

    def __init__(self,master):
        self.master = master
        ##self.frame = tk.Frame(master)  not used
        self.lbl = tk.Label(master, text="Please Login")
        self.lbl.pack()

        self.lbl1 = tk.Label(master, text="Username")
        self.lbl1.pack()
        userName=tk.StringVar(None)
        self.userBox = tk.Entry(master, textvariable=userName)
        self.userBox.pack()

        self.lbl2 = tk.Label(master, text="Password")
        self.lbl2.pack()
        passWord=tk.StringVar(None)
        self.passBox = tk.Entry(master, show="*", textvariable=passWord)
        self.passBox.pack()

        self.logoutbut = tk.Button(master, text="New Window", width=20,
                     command=self.Checkrecord)
        self.logoutbut.pack(padx=15, pady=15)

        self.exitbut = tk.Button(master, text="Exit", width=20, command=self.exitProgram)
        self.exitbut.pack(padx=15, pady=15)

    def Checkrecord(self):
        self.app = Window2(self.master)

    def exitProgram(self):
        self.master.quit()

class Window2():

    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.frame.title="Cinema Booking System"
        self.frame.pack(side="bottom")

        tk.Label(self.frame, text="Inside the new frame", bg="orange").pack()

root = tk.Tk()
root.title("Cinema Booking System")
root.geometry("250x250")
cls = WelcomeWindow(root)
root.mainloop()

rawDescription: having trouble opening and closing windows in tkinter

description: Having trouble opening and closing windows in tkinter


code:
# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
cnt
# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

rawDescription: Finding least common elements in a list

description: Finding least common elements in a list


code: [filter(None, comb) for comb in itertools.product(*[[None] + it for it in list_of_iterables])]

rawDescription: Elegant way to obtain combinations for a list of iterables


code:
siteList = []
path = os.path.dirname(os.path.abspath(__file__))
website = os.path.join(path,"home.html")
if website not in siteList:
    siteList.append(website)
    webbrowser.open(website)

rawDescription: How to check if URL is popuped in python

description: Check if URL is popuped in python


code:
import wx

class Myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.my_choices = ["Board Sports","Ball Sports","Fight Sports"]
        self.my_subchoices = [["Skate boarding","Surfing","Ski boarding"],["Football","Cricket","Rugby","Guess my nationality"],["Boxing","Wrestling","Karate"]]
        pan = wx.Panel(self)
        self.cbx = wx.ComboBox(pan, -1, pos=(10,30), choices=self.my_choices,style=wx.CB_DROPDOWN )
        self.cbx.Bind(wx.EVT_COMBOBOX, self.on_selection)
        self.cbx.SetValue("Choose a sport")

    def on_selection(self, evt):
        Choice = self.cbx.GetSelection()
        msg = ""
        for x in self.my_subchoices[Choice]:
            msg += x+"\n"
        self.cbx.SetToolTipString(msg)

if __name__ == "__main__":
    App = wx.App()
    Myframe().Show()
    App.MainLoop()

rawDescription: Assistance Text For ComboBox Entries

description: Assistance Text For ComboBox Entries


code:
longest = max(len(i) for i in data.values())
data = {key: [0]*(longest-len(value)) + value for key,value in data.items()}
data

rawDescription: Fill missing data in python list

description: Fill missing data in python list


code:
class Registration(CreateView):
    """
    View handles user registration.
    """
    form_class = ExampleForm
    model = Example
    template_name = 'accounts/registration.html'
    success_url = reverse_lazy('accounts:registered')

    def form_valid(self, form):
        example = form.save(commit=False)
        example.extra_field = derive_data(form.cleaned_data)
        example.save()
        return super(Registration, self).form_valid(form)

rawDescription: Handle data from added field in ModelForm via Create View


code:
marker_min = plt.Line2D((0, 0), (0, 0), markeredgecolor=(0.5, 0.0, 0.0), markerfacecolor='none', linestyle='', marker='x', markeredgewidth=2, markersize=5)
marker_max = plt.Line2D((0, 0), (0, 0), markeredgecolor=(0.0, 0.5, 0.0), markerfacecolor='none', linestyle='', marker='o', markeredgewidth=2, markersize=5)
plt.legend([marker_min, marker_max], ['Min Points', 'Max Points'], numpoints=1, loc='center left', bbox_to_anchor=(1, 0.5))

rawDescription: Legend marker transparency - Matplotlit

description: Legend marker transparency - Matplotlit


code:
with open('test.txt', 'r') as text:
    nums = [ast.literal_eval(i) for i in text]
    data = [str(i) + '\n' for i in sorted(nums)]

with open('test.txt', 'w') as text:
    text.writelines(data)

rawDescription: Sort lists inside of a text file in Python


rawDescription: Update list of unique items in a dictionary


code:
l1 = [1,2,3]
l = 2 * max(len(l1), len(l2))  # final length

rawDescription: mix two uneven lists with fill requirements

description: Mix two uneven lists with fill requirements


code:
@app.route('/')
def index():
    rv = cache.get('request:/')
    if rv == None:
        rv = render_template('index.html')
        cachable = make_response(rv).data
        cache.set('request:/', cachable, timeout=5 * 60)
    return rv

rawDescription: nginx with flask and memcached returns some garbled characters

description: Nginx with flask and memcached returns some garbled characters


code:
def update_dict_from_obj(dct, obj):
  dct.update({
    'a': obj.id,
    'b': obj.some_other_value,
    'c': obj.some_other_value2,
  })

for obj in self.objects:
  # Exact values are only numbers (float, int) and or strings
  dct = {}
  update_dict_from_obj(dct, obj)
  some_other_obj.use_dct(dct) # Do something with it
  for obj2 in obj:
    # reuse same dictionary,
    #but regenerate values from another object
    update_dict_from_obj(dct, obj2)
    some_other_obj.use_dct(dct)

rawDescription: Python - reuse same dictionary while only changing object that gives values


code:
def get_queryset(self):
    qs = super(SomeObjectDataTableView, self).get_queryset()
    return qs.select_related().annotate(items_count=Count('items'))

rawDescription: Aggregation with django-eztables

description: Aggregation with django-eztables


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

x = np.random.rand(10,10)
y = np.random.rand(10,10)
z = np.random.rand(10,10)

fig, ax = plt.subplots(1,1)

bxpstats = list()
for dataset, label in zip([x, y, z], ['X', 'Y', 'Z']):
    bxpstats.extend(cbook.boxplot_stats(np.ravel(dataset), labels=[label]))
ax.bxp(bxpstats)
plt.show()

rawDescription: Buildling boxplots incrementally from large datasets


code:
from multiprocessing import Pool
p = Pool(5)  # like in your example, running five separate processes
p.map(do, range(start_i, end_i))

rawDescription: Run several python programs at the same time


code: a.insert(0, a.pop())

rawDescription: How do I move the last item in a list to the front in python?

description: Move the last item in a list to the front in python


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

john_level1 = 10
john_level2 = 2
john_level3 = 18

daniel_level1 = 11
daniel_level2 = 0
daniel_level3 = 6

# plt.subplots_adjust(left=0.35, bottom=0.25)

people = ("John", "Daniel")
y_pos = np.arange(len(people))

level1 = john_level1, daniel_level1
level2 = john_level2, daniel_level2
level3 = john_level3, daniel_level3

fig = plt.figure()
ax = fig.add_subplot(111)

ax.axis([0, 12, -1, 2])

axcolor = 'lightgoldenrodyellow'

ax.barh(y_pos, level1, align='center', alpha=0.5)
ax.set_yticks(y_pos, people)
ax.set_title('Individual Points', fontsize=14, fontweight='bold')

#################
# RADIO BUTTONS # Originally a color-changer from Matplotlib
#################
rax = fig.add_axes([0.015, 0.75, 0.25, 0.25], axisbg=axcolor)
radio = RadioButtons(rax, ('Score at Level 1', 'Score at Level 2', 'Score at Level 3'), active=0)
def raidfunc(label):

    if (label == 'Score at Level 1'):
        ax.clear()
        ax.axis([0, 12, -1, 2])
        ax.barh(y_pos, level1, align='center', alpha=0.5)
        fig.canvas.draw()

    if (label == 'Score at Level 2'):
        ax.clear()
        ax.axis([0, 12, -1, 2])
        ax.barh(y_pos, level2, align='center', alpha=0.5)
        fig.canvas.draw()

    if (label == 'Score at Level 3'):
        ax.clear()
        ax.axis([0, 12, -1, 2])
        ax.barh(y_pos, level3, align='center', alpha=0.5)
        fig.canvas.draw()

radio.on_clicked(raidfunc)

plt.show()

rawDescription: Setting Radiobutton to swich between lists


code:
result = si.query()

if search_terms['province']:
    result = result.query(province=search_terms['province'])
if search_terms['town']:
    result = result.query(town=search_terms['town'])

rawDescription: Sunburnt solr wildcard *:*

description: Sunburnt solr wildcard *:*


code:
import tempfile
import os

def run(mjf_file):
    dir = tempfile.mkdtemp(dir=".")
    os.chdir(dir)

    # rest of function here
    # create mobcal.run in current directory
    # while changing references to other files from "./" to "../"

rawDescription: Python: Using multiprocessing when the function called is dependent on a file


code: df.query('cat1 == dog1 or cat1 == dog2')

rawDescription: Pandas: How do I check for value match between columns in same dataframe?


code:
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))

rawDescription: Avoid a Newline at End of File - Python

description: Avoid a Newline at End of File - Python


code:
import requests

r = requests.get("http://127.0.0.1:8080/store.json")
print(r.status_code)

rawDescription: Testing web server through linux terminal


code:
def change_label(*args):
    label.config(text='') # clear label
    label.config(text='T' + var.get()) # set new label text

root = Tk()

var = StringVar() # make the StringVar()

label = Label(root)
entry = Entry(root, textvariable=var) # set the textvariable to var

var.trace('w', change_label) # trace var to monitor for changes, calling function on change

label.pack()
entry.pack()

root.mainloop()

rawDescription: Linking Tkinter label based on Entry value


rawDescription: Editing the x-axis tick labels of a stacked bar graph in matplotlib


code:
def nested_get(d, *keys):
    for key in keys:
        if d is None:
            break
        d = d.get(key)
    return d

rawDescription: Python get nested dict element

description: Python get nested dict element


code:
import base64

...

data_uri = 'data:...'
image_data = data_uri.partition('base64,')[2]
binary = base64.b64decode(image_data)
return HttpResponse(binary, mimetype='image/png')

rawDescription: Django/Python/toDataURL return a response with the string from toDataURL


code:
def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'

rawDescription: Python function for capping a string to a maximum length


code:
word_dictionary = {} # start with empty dictionary
highest = 0 # and set our counter to 0
sentence = "this is a sentence and is good".split()
compressed = []
for word in sentence:
    if word not in word_dictionary:
        highest += 1 # new word, so we need a new number
    # append the word number, and if it's not in the dictionary,
    # set it, too
    compressed.append(word_dictionary.setdefault(word, highest))

rawDescription: I am trying to compress files in python and seem to be struggling


code:
from matplotlib.path import Path
from matplotlib.patches import PathPatch

def DoubleRect(xy1, width1, height1,
               xy2, width2, height2, **kwargs):
    base = np.array([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])
    verts = np.vstack([xy1 + (width1, height1) * base,
                       xy2 + (width2, height2) * base[::-1],
                       xy1])
    codes = 2 * ([Path.MOVETO] + 4 * [Path.LINETO]) + [Path.CLOSEPOLY]
    return PathPatch(Path(verts, codes), **kwargs)

fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)

# plot the image
im = ax.imshow(imdata, extent=(0, 1, 0, 1), aspect='auto',
               cmap='coolwarm', interpolation='nearest')

# plot the hatched rectangle
patch = plt.Rectangle((0.3, 0.3), 0.4, 0.4, facecolor='none',
                      hatch=r'//')
ax.add_patch(patch)

# add the text
text = ax.text(0.5, 0.5, 'Text', fontsize='xx-large', fontweight='bold',
               color='k', ha='center', va='center')

# create a mask for the hatched rectangle
mask = DoubleRect((0, 0), 1, 1, (0.4, 0.45), 0.2, 0.1,
                  facecolor='none', edgecolor='black')
ax.add_patch(mask)
patch.set_clip_path(mask)

rawDescription: How to nicely plot clipped layered artists in matplotlib?

description: Nicely plot clipped layered artists in matplotlib


code:
hiddenLists = [x.strip() for x in hiddenLists.split(",")]
if i.name() in hiddenLists:
    ...

rawDescription: Python if in Statement Specifics

description: Python if in Statement Specifics


code:
import numpy as np
from itertools import combinations
A = np.array([[1, 2, 3], [4, 5, 6], [10, 20, 30]])
[np.linalg.norm(a-b) for a, b in combinations(A, 2)]

rawDescription: Calculate Euclidean Distance within points in numpy array


code:
#!/usr/bin/env python
# import mks_function .. you won't need this ...

from mks_function import mks_create_sandbox
import os, datetime

# import time, sys .. these aren't used in this snippet
# import os.path .. just refer to os.path, since os is already imported

# get today's date as a datetime type
todaystr = datetime.date.today().isoformat()

# .. use os.path.join()
if not os.path.exists(os.path.join('/home/build/test/sandboxes/', todaystr)):
    os.mkdir(os.path.join('/home/build/test/sandboxes/', todaystr))
# .. 'else: pass' is unnecessary

if not os.path.exists(os.path.join(
    '/home/build/test/sandboxes/', todaystr, '/new_sandbox/project.pj')):

    # i'm not seen, that the sandbox is created in the right directory here
    # maybe you should change the working directory via ..
    # os.chdir(os.path.join('/home/build/test/sandboxes/', todaystr))
    mks_create_sandbox()

if os.path.exists(os.path.join(
    '/home/build/test/sandboxes/', todaystr, '/new_sandbox/Makefile')):

    # .. change to the right directory
    os.chdir(os.path.join(
        '/home/build/test/sandboxes/', todaystr, '/new_sandbox/'))

    os.system("make > make_results.txt 2>&1")

rawDescription: Variables in python os.path

description: Variables in python os.path


code:
class HumanizeTests(TestCase):

    def humanize_tester(self, test_list, result_list, method):
        # Using max below ensures we go through both lists
        # However, if the lists are not equal length, this raises an exception
        for test_content, result in zip(test_list, result_list):
            t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
            rendered = t.render(Context(locals())).strip()
            self.assertEqual(rendered, escape(result),
                         msg="%s test failed, produced '%s', should've produced '%s'" %     (method, rendered, result))

rawDescription: Any ways to add custom/debug message to details of failed test method of python/django unittest.TestCase?


code:
def code_metric(filename):
    line_count = char_count = 0
    with open(filename) as fin:
        stripped = (line.rstrip() for line in fin)
        for line_count, line in enumerate(filter(None, stripped), 1):
            char_count += len(line)
    return line_count, char_count

print(code_metric('cmtest.py'))
# (3, 85)

rawDescription: counting non-empty lines and sum of lengths of those lines in python

description: Counting non-empty lines and sum of lengths of those lines in python


code:
from os import listdir
from os.path import isfile, join
subString = "xyz"
mypath = "/tmp"
onlyGoodfiles = [f for f in listdir(mypath) if isfile(join(mypath, f)) and subString in f]

rawDescription: Finding a file with a particular string as part of its name in a directory


code:
import shutil

shutil.rmtree('_Temp_Dir_')

rawDescription: Python - Is there a way to wait os.unlink() or os.remove() to finish?


code:
def optional_inherit(cls):
    if use_option:
        from package.my_module import OptClass
        class ExampleClassWithOptClass(cls, OptClass):
            pass
        return ExampleClassWithOptClass
    else:
        return cls

...

@optional_inherit
class ExampleClass(base_module.BaseHandler):
    ...

rawDescription: Lazy load / configure a class to inherit from


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection

n = 100

# Get your xy data points, which are the centers of the rectangles.
xy = np.random.rand(n,2)

# Set a fixed height
height = 0.02
# The variable widths of the rectangles
widths = np.random.rand(n)*0.1

# Get a color map and make some colors
cmap = plt.cm.hsv
colors = np.random.rand(n)*10.
# Make a normalized array of colors
colors_norm = colors/colors.max()
# Here's where you have to make a ScalarMappable with the colormap
mappable = plt.cm.ScalarMappable(cmap=cmap)
# Give it your non-normalized color data
mappable.set_array(colors)

rects = []
for p, w in zip(xy, widths):
    xpos = p[0] - w/2 # The x position will be half the width from the center
    ypos = p[1] - height/2 # same for the y position, but with height
    rect = Rectangle( (xpos, ypos), w, height ) # Create a rectangle
    rects.append(rect) # Add the rectangle patch to our list

# Create a collection from the rectangles
col = PatchCollection(rects)
# set the alpha for all rectangles
col.set_alpha(0.3)
# Set the colors using the colormap
col.set_facecolor( cmap(colors_norm) )
# No lines
col.set_linewidth( 0 )
#col.set_edgecolor( 'none' )

# Make a figure and add the collection to the axis.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_collection(col)
# Add your ScalarMappable to a figure colorbar
fig.colorbar(mappable)
plt.show()

rawDescription: Understanding matplotlib verts

description: Understanding matplotlib verts


code:
def setxattr(self, path, name, value, options, position=0):
    # Ignore options
    attrs = self.files[path].setdefault('attrs', {})
    attrs[name] = value

rawDescription: How does setxattr in memory.py change anything?


code:
import xml.dom.minidom as xdm
dom = xdm.parseString('<foo bar="baz"/>')
root = dom.documentElement
atr = root.getAttributeNode('bar')
atr.nodeValue

rawDescription: python xml.dom.minidom.Attr question

description: Python xml.dom.minidom.Attr question


code:
data = job_data.get_parsed_dictionary()

columns = ', '.join(data.keys())
parameters = ', '.join(['%({0})s'.format(k) for k in data.keys()])
query = 'INSERT INTO jobs ({columns}) VALUES ({parameters})'.format(columns=columns, parameters=parameters)

cursor.execute(query, data)

rawDescription: Insert entry into mysqldb with entry values stored as dictionary python


code:
import re
re.findall('a.', 'abacadaeaf')

rawDescription: Match and return a sub-pattern unknown number of times


code:
import random

pool = set(["foo", "bar", "baz", "123", "456", "789"]) # your 240 elements here
slen = len(pool) / 3 # we need 3 subsets
set1 = set(random.sample(pool, slen)) # 1st random subset
pool -= set1
set2 = set(random.sample(pool, slen)) # 2nd random subset
pool -= set2
set3 = pool # 3rd random subset

rawDescription: Divide set into subsets with equal number of elements


code: {{ value|floatformat:2|intcomma }}

rawDescription: How to print number with commas as thousands separator and decimal places in Python/Django

description: Print number with commas as thousands separator and decimal places in Python/Django


code:
if response == "done":
    count = 0
    print("**Treasure entry complete! Here is the treasure**"),
    while count < len(todos):

        print("-",todos[count])
        count = count + 1

rawDescription: How to make a print, only excute once

description: Make a print, only excute once


code:
from pyspark.sql.functions import expr, date_add
new_df = my_df.withColumn('test', expr('date_add(created_at, number*7)'))
filtered = new_df.filter(new_df.test > start_date)
filtered.show()

rawDescription: Date Arithmetic with Multiple Columns in PySpark


code:
import os
import sys
import shutil

for (dir, _, files) in os.walk("C:\\Torrents"):  # note double backslashes
    for f in sorted(files):  # note call to sorted() function
        path = os.path.join(dir, f)
        print(path)
        os.system('python py3createtorrent.py "' +
                  path +
                  '" "udp://tracker.openbittorrent.com:80/announce"')

shutil.rmtree('__pycache__')

rawDescription: How do i sort files into similar directory structures?

description: Sort files into similar directory structures


code:
import os, platform
backup_filename = "output.back.json"
filename = "output.json"

serialised_str = json.dumps(...)
with open(backup_filename, 'wb') as f:
     f.write(serialised_str)
if platform.system() == 'Windows':
     os.unlink(filename)
os.rename(backup_filename, filename)

rawDescription: Keeping in-memory data in sync with a file for long running Python script


code:
class SplitAddressWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = []
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        widgets.append(forms.TextInput(attrs=attrs))
        super(SplitAddressWidget, self).__init__(widgets, attrs)
    ...

class SplitAddressField(forms.MultiValueField):
    widget = SplitAddressWidget
    def __init__(self, *args, **kwargs):
        fields = (
                forms.CharField(required=kwargs['required']),
                forms.CharField(required=0),
                forms.CharField(required=kwargs['required']),
                USStateField(required=kwargs['required']),
                USZipCodeField(required=kwargs['required']),
            )
        super(SplitAddressField, self).__init__(fields, *args, **kwargs)
    ...

rawDescription: Custom address field in Django Model

description: Custom address field in Django Model


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

data = np.array([[1,23,12],[24,12,7],[14,9,4] ])
ny, nx = data.shape

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, interpolation='nearest', extent=[0.5, nx+0.5, ny+0.5, 0.5])

xticks = np.arange(nx)+1
yticks = np.arange(ny)+1

ax.set_xticks(xticks)
ax.set_yticks(yticks)

plt.show()

rawDescription: Matplotlib set coordinate

description: Matplotlib set coordinate


code:
open('hello.dot','w').write("digraph G {Hello->World}")
import subprocess
subprocess.call(["path/to/dot.exe","-Tpng","hello.dot","-o","graph1.png"])
# I think this is right - try it form the command line to debug

rawDescription: Tree plotting in Python

description: Tree plotting in Python


code:
import sys
outfile = 'file path'

with open(outfile, 'r') as f:
    lines = f.readlines()
    for line in lines:
        sys.stdout.write(line)

rawDescription: Convert python codec to text

description: Convert python codec to text


code:
all_pages = Page.objects.all()
revision_ids = [p.revisions.order_by('-created').first().pk for p in all_pages]
page_revisions = PageRevision.objects.filter(pk__in=revision_ids)

rawDescription: Django get multiple latest elements using filter


code:
myvar = 'test'

def myfunction(foo='test'):
    pass

class MyClass(object):
    pass

rawDescription: Is there any way to get python omnicomplete to work with non-system modules in vim?


code:
now = datetime.datetime.now()
now
when = now.replace(hour=0, minute=0, second=0, microsecond=0)
when
when.weekday()
when = when - datetime.timedelta(when.weekday())
when

rawDescription: How do I set a python datetime to something that is (somewhat) relative to now?

description: Set a python datetime to something that is (somewhat) relative to now


code:
import numpy
import lomb
x = numpy.arange(10)
y = numpy.sin(x)
fx,fy, nout, jmax, prob = lomb.fasper(x,y, 6., 6.)

rawDescription: frequency analysis with unevenly spaced data in python

description: Frequency analysis with unevenly spaced data in python


code:
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")

rawDescription: Is there a Python equivalent to the Perl "/x" modifier for regular expressions?


code:
import itertools
a = [1, 2]
b = [3, 4, 5]
list(itertools.product(a, b))

rawDescription: Python generate all n-permutations of n lists


code:
#Rewritten code from /r2/r2/lib/db/_sorts.pyx

from math import sqrt

def confidence(ups, downs):
    n = ups + downs

    if n == 0:
        return 0

    z = 1.0 #1.44 = 85%, 1.96 = 95%
    phat = float(ups) / n
    return ((phat + z*z/(2*n) - z * sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n))

rawDescription: Python implementation of the Wilson Score Interval?


code:
def create_widgets(self):
    """my widgets"""
    spinval = IntVar()

    self.scale = ttk.Scale(self, orient=HORIZONTAL,
                                length=200,
                                from_=1, to=100,
                                variable=spinval,
                                command=self.accept_whole_number_only)
    self.scale.grid(row=3, column=1, sticky=W)

    self.spinbox = Spinbox(self, from_=1, to=100,
                                textvariable=spinval,
                                command=self.update,
                                width=10)
    self.spinbox.grid(row=3,column=3, sticky=W)

def accept_whole_number_only(self, e=None):
    value = self.scale.get()
    if int(value) != value:
        self.scale.set(round(value))

def update(self, e=None):
    """Updates the scale and spinbox"""
    self.scale.set(self.spinbox.get())

rawDescription: Increment by 1 for ttk scale

description: Increment by 1 for ttk scale


code:
import sys

fileTemps = 'temps'

with open(fileTemps, 'rw') as fd:
    temps = fd.readlines()

if temps.__len__() >= 15:
    temps.pop(0)

temps.append(' '.join(sys.argv[1:]) + '\n')

with open(fileTemps, 'w') as fd:
    for l in temps:
        fd.write(l)

rawDescription: Store 15 last values on a file on Python


code:
import xml.etree.ElementTree as ET
import re
xdata = '''
<data>
    <a1>cat</a1>
    <a5>bird</a5>
    <a4>window</a4>
</data>'''
root = ET.fromstring(xdata)

for apptag in root.findall("*"):
    apptag.text = str(len(apptag.text))
    apptag.tag = re.sub(r'^a(.*)',r'r\1',apptag.tag)
root.tag = 'result'
ET.ElementTree(root).write('test.xhtml')

rawDescription: Reading and writing unique XML tags in Python


code:
email =('email')
pwd  = ('pwd')
data = urllib.parse.urlencode({'email': email, 'pwd':pwd, 'service': 'nudge'})
data = data.encode('utf-8')
request = urllib.request.Request("https://jawbone.com/user/signin/login")
# adding charset parameter to the Content-Type header.
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
f = urllib.request.urlopen(request, data)

#print(f.read().decode('utf-8'))
j=(f.read().decode('utf-8'))
b=json.loads(j)

rawDescription: Using OAuth2.o protocol python for social authentication


rawDescription: Python Chosing To Ignore String Value

description: Python Chosing To Ignore String Value


code:
import re

line = "Remind me to pick coffee up at Autostrada at 4:00 PM"

matchObj = re.match( r'Remind me to (.*) at (.*?) at (.*?) .*', line, re.M|re.I|re.M)
matchObj2 = re.match( r'Remind me to (.*) at (.*?) .*', line, re.M|re.I)

if matchObj:
   print("matchObj.group() : ", matchObj.group())
   print("matchObj.group(1) : ", matchObj.group(1))
   print("matchObj.group(2) : ", matchObj.group(2))
   print("matchObj.group(3) :", matchObj.group(3))
elif matchObj2:
   print("matchObj2.group() : ", matchObj2.group())
   print("matchObj2.group(1) : ", matchObj2.group(1))
   print("matchObj2.group(2) : ", matchObj2.group(2))
else:
   print("No match!!")

rawDescription: Python regex: Get only one expression to match


code:
tc = unittest.TestCase('__init__')
tc.assertIsNotNone(a)

rawDescription: Is there a way to use Python unit test assertions outside of a TestCase?


rawDescription: split elements of a list in python

description: Split elements of a list in python


code:
content = (
    "<!DOCTYPE html>\n\n\n  "
    "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"
    "  <title>{0} - {1}</title>\n  "
    "<link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" />\n\n\n"
    "  \n  "
    "\n\n\n"
).format(
    settings["app.name"], ncc, name, settings["dir"]["static.style"],
    settings["lang.style"], settings["dir"]["static.script"],
    settings["lang.script"]
)

rawDescription: What is the most efficient and readable way to pass/format lots of variables to a large string?


rawDescription: Regex to match word and trailing whitespace pairs


code:
d       = defer.Deferred()
d.delay = reactor.callLater(sleepTime, d.callback, None)

d.cancel()

yield d
returnValue(None)

rawDescription: Stop a Twisted Fiber Mid-Execution

description: Stop a Twisted Fiber Mid-Execution


code:
import datetime
import pytz

now = datetime.now(pytz.utc)
# datetime.datetime(2012, 6, 8, 10, 31, 58, 493905, tzinfo=<UTC>)

[tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 9]
# ['Atlantic/Cape_Verde']

[tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 12]
# returns a list of 45 timezones, 'Europe/Oslo' included

rawDescription: pytz: getting all timezones, where now specific time

description: Pytz: getting all timezones, where now specific time


code:
mystring = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness...'''
import textwrap
textwrap.wrap(mystring, width=20)

rawDescription: Add line return to a block of text, but don't break words


code:
client.indices.create(
    index=index,
    body={
      'settings': {
        # just one shard, no replicas for testing
        'number_of_shards': 1,
        'number_of_replicas': 0,

        # custom analyzer for analyzing file paths
        'analysis': {
          'analyzer': {
            'file_path': {
              'type': 'custom',
              'tokenizer': 'path_hierarchy',
              'filter': ['lowercase']
            }
          }
        }
      }
    },
    # Will ignore 400 errors, remove to ensure you're prompted
    ignore=400
)

rawDescription: Elasticsearch Python - Index Analyzer & Search Analyzer


code:
from Tkinter import *
from functools import partial

class LabelTest():
    def __init__(self, master):
        self.master=master
        self.string_vars=[]  ## contains pointers to the label vars
        self.values=[]
        self.start()
        Button(self.master, text="Quit", bg="orange", width=15,
               command=self.master.quit).grid(row=20)
        self.update(1)

    def update(self, ctr):
        """ Change the StringVars to the new values
        """
        if len(self.values) > 9:
            ## full so delete the first one
            del self.values[0]
        self.values.append(ctr)
        ## update the StringVar with the corresponding
        ## value from self.values
        for offset in range(len(self.values)):
            self.string_vars[offset].set(self.values[offset])

        ctr += 1

        if ctr < 20:  ## let's put a limit on this
            self.master.after(1000, partial(self.update, ctr))

    def start(self):
        """ create 10 labels with StringVars that can be changed
            each time a new value is created
        """
        for ctr in range(10):
            var=StringVar()
            lab=Label(self.master, textvariable=var).grid(row=ctr)
            self.string_vars.append(var) ## the variables to be updated
            ## initial variable value
            self.values.append("***")  ## the values

master=Tk()
LabelTest(master)
master.mainloop()

rawDescription: Updating label values using after() method .


code:
#!/usr/bin/python

import array
import math

import cairo
import pygame
import rsvg

WIDTH = 512
HEIGHT = 512

data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)

pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)

screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0))
pygame.display.flip()

clock = pygame.time.Clock()
while True:
    clock.tick(15)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit

rawDescription: SVG rendering in a PyGame application

description: SVG rendering in a PyGame application


code:
from Tkinter import *

root = Tk()

def userChoice():
    row1["text"] = "CLICKED!"

row1 = Button(root, text=" ", command = userChoice)
row1.config(height="6", width="10")
row1.grid(row=0, column=0)

mainloop()

rawDescription: Makes user change Tkinter button if clicked?


code:
#create network and modules
net = FeedForwardNetwork()
inp = LinearLayer(9)
h1 = SigmoidLayer(2)
h2 = TanhLayer(2)
outp = LinearLayer(1)
# add modules
net.addOutputModule(outp)
net.addInputModule(inp)
net.addModule(h1)
net.addModule(h2)
# create connections
net.addConnection(FullConnection(inp, h1, inSliceTo=6))
net.addConnection(FullConnection(inp, h2, inSliceFrom=6))
net.addConnection(FullConnection(h1, h2))
net.addConnection(FullConnection(h2, outp))
# finish up
net.sortModules()

rawDescription: Creating custom connectivity in PyBrain neural networks


code:
def FileWrt(*typos):
    for typo in typos:
        fileWrite.write(typo)

rawDescription: Is there a way for dynamical expand of parameter?


code:
cursor=db.cursor()
cursor.execute('select* from Item Order BY Name ASC')
self.setupHeaderLabels(cursor.description)
for row in cursor:
    self.showOneRow(row)

rawDescription: Easiest way to display data in PyQt from my Sqlite database in a table?