code:
import datetime as DT
import io
import numpy as np
import pandas as pd

pd.options.mode.chained_assignment = 'warn'

content = '''     ssno        lname         fname    pos_title             ser  gender  dob
0    23456789    PLILEY     JODY        BUDG ANAL             0560  F      031871
1    987654321   NOEL       HEATHER     PRTG SRVCS SPECLST    1654  F      120852
2    234567891   SONJU      LAURIE      SUPVY CONTR SPECLST   1102  F      010999
3    345678912   MANNING    CYNTHIA     SOC SCNTST            0101  F      081692
4    456789123   NAUERTZ    ELIZABETH   OFF AUTOMATION ASST   0326  F      031387'''

df = pd.read_table(io.BytesIO(content), sep='\s{2,}')
df['dob'] = df['dob'].apply('{:06}'.format)

now = pd.Timestamp(DT.datetime.now())
df['dob'] = pd.to_datetime(df['dob'], format='%m%d%y')    # 1
df['dob'] = df['dob'].where(df['dob'] < now, df['dob'] -  np.timedelta64(100, 'Y'))   # 2
df['age'] = (now - df['dob']).astype('<m8[Y]')    # 3
print(df)

rawDescription: Pandas get the age from a date (example: date of birth)


code:
import pandas as pd
gbl = globals()
for i in range(2008, 2015):
    gbl['df_'+str(i)] = pd.DataFrame(df[str(i)])

rawDescription: How to create series of pandas dataframe by iteration

description: Create series of pandas dataframe by iteration


code: hog[Y[i,j], X[i,j], angle[i,j]]

rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


code:
for key, value in request.files.iteritems():
    uploaded_image = request.files[key]
    name, ext = os.path.splitext(uploaded_image.filename)
    if ext not in ('.png','.jpg','.jpeg','.JPG','.gif'):
        return "File extension not allowed."
    if uploaded_image and uploaded_image.file:
        raw = uploaded_image.file.read()
        filename = uploaded_image.filename
        dbname = 'grid_files'
        db = connection[dbname]
        fs = gridfs.GridFS(db)
        fs.put(raw,filename=filename, user_email = user_email)

rawDescription: How to handle multiple file uploads where the name and number of inputs is dynamic?

description: Handle multiple file uploads where the name and number of inputs is dynamic


code:
def changecs(instances):

    # The following line is equivalent to
    # cs_id = unzip(ifile, instances)
    # for c in cs_id:
    for c in unzip(ifile, instances):

        cspath = cs_id + '/abc/myfile.txt'

rawDescription: How to use a list in other function?

description: Use a list in other function


code:
sort_spec = (True, False, False, True)
for index, reverse_value in list(enumerate(sort_spec))[::-1]:
    list_of_tuples.sort(key = lambda x: x[index], reverse=reverse_value)

rawDescription: sort list of tuples with multiple criteria

description: Sort list of tuples with multiple criteria


rawDescription: Is it possible to represent non-ASCII characters?


code:
import datetime
datetime.datetime.now()

rawDescription: Python record the time of typing

description: Python record the time of typing


rawDescription: Ordereddict Merge by Month, and Week python


code:
import matplotlib.animation as animation

anim = animation.FuncAnimation(fig, ...)

FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib',
                comment='Movie support!')

# Change the video bitrate as you like and add some metadata.
writer = FFMpegWriter(fps=15, bitrate=1000, metadata=metadata)

rawDescription: Pixelated animations in Matplotlib

description: Pixelated animations in Matplotlib


code: pip --version

rawDescription: how to run pip for python 3 and python 2

description: Run pip for python 3 and python 2


code: data = BeautifulSoup(urllib2.urlopen(value), 'html.parser')

rawDescription: BeautifulSoup Cannot Find Tag

description: BeautifulSoup Cannot Find Tag


code:
import Tkinter
from Tkinter import Tk, Frame, Menu
from Tkinter import IntVar, BOTH
class App(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Test")
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        menubar.add_cascade(label="Discrepancy", menu=fileMenu)
        fileMenu.add_command(label="View current case", command=self.view)
        fileMenu.add_command(label="OK Process", command=self.OK)

        self.var = IntVar()

        self.frame_view = Frame(self)
        self.view_label1 = Tkinter.Label(self.frame_view, text="RMA", relief=Tkinter.RIDGE)
        self.view_label2 = Tkinter.Label(self.frame_view, text="SN", relief=Tkinter.RIDGE)
        self.view_label1.grid(row=0, column=0, sticky=Tkinter.W)
        self.view_label2.grid(row=0, column=1, sticky=Tkinter.W)
        #self.frame_view.pack(fill=BOTH, expand=1)

        self.frame_ok = Frame(self)
        self.ok_label1 = Tkinter.Label(self.frame_ok, text="RMA")
        self.ok_label2 = Tkinter.Label(self.frame_ok, text="SN")
        self.ok_entry1 = Tkinter.Entry(self.frame_ok, width=50)
        self.ok_entry2 = Tkinter.Entry(self.frame_ok, width=50)
        self.ok_label1.grid(row=0)
        self.ok_label2.grid(row=1)
        self.ok_entry1.grid(row=0, column=1, pady=4)
        self.ok_entry2.grid(row=1, column=1, pady=4)
        #self.frame_ok.pack(fill=BOTH, expand=1)

        self.pack(fill=BOTH, expand=1)

    def view(self):
        self.frame_ok.grid_forget()

        self.frame_view.grid()

    def OK(self):
        self.frame_view.grid_forget()

        self.frame_ok.grid()

def main():

    root = Tk()
    root.geometry("1280x720")
    app = App(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Avoid screen overlap in Tkinter

description: Avoid screen overlap in Tkinter


code:
uniques = np.array(list(string.ascii_letters))
len(uniques)

rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
class sine:
    def __init__(self, freq):
        self.freq = freq
        self.phase = 0.0

    def __iter__(self):
        return self

    def __next__(self):
        v = math.sin(self.phase)
        self.phase += samplerate/freq
        return v
        # for this infinite gen we never raise StopIteration()

rawDescription: Efficiency of python generators

description: Efficiency of python generators


code:
import urllib2
response = urllib2.urlopen(request.to_url())
response_body = response.read()    # in case you need it

rawDescription: python-oauth2 - issue Request objects

description: Python-oauth2 - issue Request objects


code: d

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


code:
s = df.loc[:, ['x_axis', 'y_axis']].stack().astype('category')
s

rawDescription: Replacing string elements of a pandas DataFrame with integers


code:
nodes = [Node() for _ in range(10)]
nodes[0].children = nodes[1:6]
nodes[1].children = [nodes[6]]
nodes[2].children = [nodes[7]]
nodes[3].children = [nodes[8]]
nodes[4].children = [nodes[9]]

rawDescription: Chaining of Python generators to traverse a nested data structure; best practices


code:
from operator import mul
dict_a = dict(Counter("".join(mul(*b) for b in a)))

rawDescription: How to merge value of key when I have a list-tuple object

description: Merge value of key when I have a list-tuple object


code:
def parse_video_page(self, response):
    loader = response.meta['loader']
    sel = Selector(response)
    loader.selector = sel

    loader.add_xpath(
        'original_description',
        '//*[@id="videoInfo"]//td[@class="desc"]/h2/text()'
    )
    # ...

rawDescription: How to change selector for ItemLoader

description: Change selector for ItemLoader


code:
if current_location >= 1 or fail_event.isSet():
    break

rawDescription: Python module for playing sound data with progress bar?


code:
file = models.FileField(upload_to=get_file_path,
                        null=True,
                        blank=True,
                        verbose_name=_(u'Contact list'))

rawDescription: Enforce unique upload file names using django?


rawDescription: Python, split array by gradient of dataset


code:
import time
import datetime as dt
import pytz

utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%d %H:%M:%S %Z%z'

text='''\
10/1/2010   0:0:0
10/1/2010   0:6:0
10/1/2010   23:54:0
10/3/2010   0:0:0
3/13/2011   1:55:0
3/13/2011   3:00:0
'''
for datestring in text.splitlines():
    date=dt.datetime.strptime(datestring,"%m/%d/%Y %H:%M:%S")
    date_est=eastern.localize(date,is_dst=None)
    date_utc=date_est.astimezone(utc)
    date_utc2=dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
    print('{d} --> {d_utc}    {d_utc2}'.format(
        d=date.strftime(fmt),
        d_utc=date_utc.strftime(fmt),
        d_utc2=date_utc2.strftime(fmt),
        ))
    assert date_utc.hour == date_utc2.hour

rawDescription: How to convert EST/EDT to GMT?

description: Convert EST/EDT to GMT


code: map(sum, arra_mod)

rawDescription: Choosing and iterating specific sub-arrays in multidimensional arrays in Python


rawDescription: python, add lists to csv by columns, with list extracted dynamically from other data

description: Python, add lists to csv by columns, with list extracted dynamically from other data


code:
def dependent(meth):
    def depmeth(self, *args, **kwargs):
        if self.other_instance:
            return meth(self, *args, **kwargs)
        else:
            return None
    return depmeth

rawDescription: Python: how to code methods all of which require the same condition


code:
cur = collection.aggregate([
    {"$match": {"Booked Date": {"$in": date_list}}},
    {"$project": {
        "Room No": 1,
        "available_date": {
            "$setDifference": [date_list, "$Booked Date"]
        }
    }},
    {'$unwind': '$available_date'},
    {'$sort': {'avalable_date': 1}},
    {'$group': {
        '_id': '$Room No',
        'available_date': {'$first': '$available_date'}
    }}
])
# pretty print the result
pprint(list(cur))

rawDescription: Find values from MongDB from an array for only one date


code:
A
B
mask = (D[:,None,:] == A).all(-1)
out

rawDescription: Numpy Vectorization While Indexing Two Arrays


rawDescription: How can I select values along an axis of an nD array with an (n-1)D array of indices of that axis?

description: Select values along an axis of an nD array with an (n-1)D array of indices of that axis


rawDescription: Python matplotlib change color of specified value in contourf plot using colormap


code: newlist = [(item[0], item[2]) for item in List]

rawDescription: Sorting a List of Tuples (Python)

description: Sorting a List of Tuples (Python)


rawDescription: Populating a list with elements from different lists in Python


code: from MyStuff import my_module1

rawDescription: Class Modules in Far-Off Places

description: Class Modules in Far-Off Places


code:
res = df.sort('transaction_date', ascending=False).groupby('login').agg({'transaction_id': ['size', 'first']})
res.columns = ['transaction_count', 'last_transaction_id']
res

rawDescription: pandas: find newest value against index in time series data

description: Pandas: find newest value against index in time series data


code:
class CronJobExpire(BaseHandler):
    def get(self):
        jobs = Job.query(Job.published == "on").fetch()
        now = datetime.datetime.now()
        for job in jobs:
            if job.expire <= now:
                job.published = "off"
                job.put()

rawDescription: Google App Engine: Using cron to expire (or 'unpublish') entities


rawDescription: Different parts of regex matching same text depending on what comes afterwards


code:
from tkinter import *
from PIL import Image,ImageTk
import urllib.request
import io

url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urllib.request.urlopen(url1).read()
imagedata = io.BytesIO(imagebytes)
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()

rawDescription: Tkinter being fickle with pictures, some are blank, others are not


code:
names = mylist[0::3]
ages = mylist[1::3]
nationalities = mylist[2::3]

rawDescription: Custom Iteration over a list item in Python


code: dict(('contains(%s)' % w, True) for w in words)

rawDescription: Creating a feature dictionary for Python machine learning (naive bayes) algorithm


code:
0    # Initial global value
10   # Now we've set it to 10 in `main_function()`
15   # Now we've added 5 in `other_function()`

rawDescription: Python - How to make a local variable (inside a function) global


rawDescription: How to join links in Python to get a cycle?

description: Join links in Python to get a cycle


code:
import cgi
form = cgi.FieldStorage()

try:
    test = form['name'].value
except KeyError:
    print('not found')
else:
    print(test)

rawDescription: python if $_GET is empty do something & url path

description: Python if $_GET is empty do something & url path


code:
elements = ['|L |'] + L
text = ''.join(elements)

rawDescription: How can I count the length of the output of print in Python?

description: Count the length of the output of print in Python


code:
payload_write(payloadRecon, '####TCP PAYLOAD STREAM RECONSTRUCTION. Segment ' + str(segmentCount) + '######' '\n\n\n\n')
assert segmentCount == 1

rawDescription: Python Increasing counter by 1 every time something is written to a file


code: np.loadtxt('column.txt', ndmin=2)

rawDescription: Problems on how to transpose single column data in python


code: ln._verts3d = new_x,new_y,new_z

rawDescription: How to plot a queue of points?

description: Plot a queue of points


code:
from datetime import datetime
from dateutil import relativedelta

orig_start = datetime.now()
orig_end = datetime.now() + relativedelta.relativedelta(months=1)

print(orig_start)
print(orig_end)

mod_start = datetime(year=orig_start.year,
                     month=orig_start.month,
                     day=orig_start.day,
                     hour=0, minute=0, second=0)

mod_end = datetime(year=orig_end.year,
                   month=orig_end.month,
                   day=orig_end.day,
                   hour=23, minute=59, second=59)

# or even better as suggested in the comments:
mod_end = orig_end.replace(hour=23, minute=59, second=59, microsecond=0)

print(mod_start)
print(mod_end)

rawDescription: Customizing time of the datetime object in python


code:
def needs_privilege(privilege, project=None):
    def validate(func):
        def new_func(self, *args, **kwargs):
            try:
                check(self.user, privilege, project)
            except AccessDenied:
                return abort(status_code=401)
            else:
                return func(self, *args, **kwargs)
        new_func.privilege = privilege
        return new_func
    return validate

rawDescription: Getting local variables of function

description: Getting local variables of function


code: df

rawDescription: Pandas comparison with variable number of columns


code:
dict(d3)
d3.to_dict()

rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


rawDescription: How to get all grandchildren of a directory in python with only one OS call

description: Get all grandchildren of a directory in python with only one OS call


code: fluidPage(..., htmlOutput("json"), ...)

rawDescription: Place a chart in plotly popup

description: Place a chart in plotly popup


code: list3 = map(sum, zip(list1, list2))

rawDescription: Python: joining 2 lists of the same size


code:
def __call__(self, X, alpha=None, bytes=False):
    """
    *X* is either a scalar or an array (of any dimension).
    If scalar, a tuple of rgba values is returned, otherwise
    an array with the new shape = oldshape+(4,). If the X-values
    are integers, then they are used as indices into the array.
    If they are floating point, then they must be in the
    interval (0.0, 1.0).
    Alpha must be a scalar between 0 and 1, or None.
    If bytes is False, the rgba values will be floats on a
    0-1 scale; if True, they will be uint8, 0-255.
    """

rawDescription: Converting a grayscale image to an RGB heatmap image with matplotlib


code:
test = '8743-12083-15'
lst_int = [int(x) for x in test.split("-")]

rawDescription: Efficient way to convert strings from split function to ints in Python


code:
import sys
import matplotlib as mpl
mpl.use('TkAgg')  # do this before importing pyplot
import matplotlib.pyplot as plt
import numpy as np
import timeit

clock = timeit.default_timer

fig, ax = plt.subplots()

alphab = ['A', 'B', 'C', 'D', 'E', 'F']
frequencies = [1, 44, 12, 11, 2, 10]

pos = np.arange(len(alphab))
width = 1.0     # gives histogram aspect to the bar diagram
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(alphab)

def animate():
    start = clock()
    rects = plt.bar(pos, frequencies, width, color='r')
    for frameno, bin_idx in enumerate(np.linspace(0,1000000,100000000), 2):
        #Here we just change the first bin, so it increases through the animation.
        frequencies[0] = bin_idx
        # rects = plt.bar(pos, frequencies, width, color='r')
        for rect, f in zip(rects, frequencies):
            rect.set_height(f)
        fig.canvas.draw()
        print("FPS: {:.2f}".format(frameno / (clock() - start)))

win = fig.canvas.manager.window
win.after(1, animate)
plt.show()

rawDescription: Animate a Histogram in Python

description: Animate a Histogram in Python


code:
...
from scipy.sparse.linalg import spsolve
...

def inv(A):
    """
    Some comments...
    """
    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv

rawDescription: Is it possible to compute an inverse of sparse matrix in Python as fast as in Matlab?


rawDescription: Effectively generate slot machine outcome


code:
import collections
isinstance('ciao', collections.Iterable)
isinstance(23, collections.Iterable)
isinstance(xrange(23), collections.Iterable)

rawDescription: How can I check if an object is an iterator in Python?

description: Check if an object is an iterator in Python


code:
d = {}
for word, lineno in document:
    d.setdefault(word, [lineno, 0])[1] += 1 # works whether or not word was in d before

rawDescription: Use 'in' in an array of arrays

description: Use 'in' in an array of arrays


rawDescription: how to use numpy.lexsort without cycles

description: Use numpy.lexsort without cycles


code:
import os, shutil, glob

source_dir = "F:\CS\PyA"
dest_dir = "F:\CS\PyB"

for root, dirnames, filenames in os.walk(source_dir):
    for file in filenames:
        (shortname, extension) = os.path.splitext(file)
        if extension == ".txt" :
            shutil.copy2(os.path.join(root,file), os.path.join(dest_dir,
                         os.path.relpath(os.path.join(root,file),source_dir)))

rawDescription: How to copy files of a certain type in python

description: Copy files of a certain type in python


code:
current_time = datetime.datetime.now()
type(current_time.hour)

rawDescription: Alarm will not be triggered in Python 2.7 program


code:
def skip_to(fle, line,**kwargs):
    if os.stat(fle).st_size == 0:
        raise ValueError("File is empty")
    with open(fle) as f:
        pos = 0
        cur_line = f.readline()
        while not cur_line.startswith(line):
            pos = f.tell()
            cur_line = f.readline()
        f.seek(pos)
        return pd.read_csv(f, **kwargs)

rawDescription: skipping unknown number of lines to read the header python pandas

description: Skipping unknown number of lines to read the header python pandas


code: new_dc_files = [dc for dc in dc_files if 'NoCover' not in dc]

rawDescription: Python Remove Item from list

description: Python Remove Item from list


rawDescription: pandas complicated stacked barplot

description: Pandas complicated stacked barplot


code:
user = raw_input("Enter your GMail username --> ")
pwd = getpass.getpass("Enter your password --> ")

rawDescription: Extract information from Gmail with Python


code:
U = np.array([4, 3, 8])
M=rot(U,V)
dot(M,U)
W=cross(U,V)
allclose(W,dot(M,W))

rawDescription: Create a rotation matrix from 2 normals

description: Create a rotation matrix from 2 normals


code:
def add_helpfunc(obj):
    def helpfunc(self):
        """Nice readable docstring"""
        #code

    obj.helpfunc = helpfunc

rawDescription: Attribute added with setattr not showing up in help()


code: sum(1 for _ in next(groupby(lst), ('ignored', ()))[1])

rawDescription: Finding the amount of equal elements in the beginning of a list


code: total += abs(x[movie]-y[movie])

rawDescription: Manhattan Distance Recommending system Python


rawDescription: How to Transpose Column Values to Row Values in Python


code: [row[2:5] for row in LoL[1:4]]

rawDescription: Sub matrix of a list of lists (without numpy)


rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
GTK_THEME_DEFAULT = os.path.join("share", "themes", "Default")
GTK_THEME_WINDOWS = os.path.join("share", "themes", "MS-Windows")
GTK_GTKRC_DIR = os.path.join("etc", "gtk-2.0")
GTK_GTKRC = "gtkrc"
GTK_WIMP_DIR = os.path.join("lib", "gtk-2.0", "2.10.0", "engines")
GTK_WIMP_DLL = "libwimp.dll"

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


code:
def stdstring_args(elem):
    if elem.argstring == '[]':
        return False
    return 'std::string' in null2string(elem.vartype)

memberdef_list = [elem for elem in from_cache(classname, 'memberdefs')
                  if stdstring_args(elem)]

rawDescription: Pythonic Style for Multiline List Comprehension


code:
[uwsgi]
master = false

rawDescription: Python3 threading with uWSGI

description: Python3 threading with uWSGI


code:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

current_time = datetime.now(pytz.timezone('Asia/Shanghai'))
print(current_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> 2015-08-19 19:03:22 CST+0800

rawDescription: Time Zones in python for program

description: Time Zones in python for program


code:
for ligne in fichier:
    ligne_niveau = []
    #On parcourt les sprites (lettres) contenus dans le fichier
    for sprite in ligne.split(): # note split here
        ligne_niveau.append(sprite) # no need to check for line end
    #On ajoute la ligne Ã  la liste du niveau
    structure_niveau.append(ligne_niveau)

rawDescription: How to correctly parse a tiled map in a text file?

description: Correctly parse a tiled map in a text file


rawDescription: What is difference between {:.4e} and {:2.4} in Python scientific notation


rawDescription: Handling attributes of a class within a numpy array


code:
speech, new = Speech.objects.get_or_create(
    location=my_location_string,
    date=my_datetime_variable,
)

if new:
    speech.speaker = my_speaker_string
    speech.save()

rawDescription: django save data in database only when certain conditions are met

description: Django save data in database only when certain conditions are met


code:
class RandomResponder(object):
    choices = [A, B, C]

    def __getattr__(self, attr):
        # we define a function that actually gets called
        # which takes up the first positional argument,
        # the rest are left to args and kwargs
        def doCall(which, *args, **kwargs):
            # get the attribute of the appropriate one, call with passed args
            return getattr(self.choices[which], attr)(*args, **kwargs)
        return doCall

rawDescription: Need to route instance calls inside a python class


code:
df[0]
df[0].replace(to_replace="\(", value="", regex=True)

rawDescription: How to read a tuple with python pandas and How Series.replace function works

description: Read a tuple with python pandas and How Series.replace function works


rawDescription: getting the average rgb value of an image in wand

description: Getting the average rgb value of an image in wand


code:
template = '{{0:<{bw}}} {{1:>{aw}}}'.format(bw=bookwidth, aw=authorwidth)
for book, author in bookdict.items():
    print( template.format(book, author) )

rawDescription: Equally separating words in Python

description: Equally separating words in Python


code: gotAny.printMsg("We are the knights who say ni");

rawDescription: Class instance calling a member function: C++ Vs Python syntax


code:
x = patricia()
x.addWord('abcabc')
x._d
x.addWord('abcdef')
x._d
x.addWord('abc')

rawDescription: Implementing a Patricia Trie for use as a dictionary


rawDescription: Binary string in Python issues

description: Binary string in Python issues


code:
directories = [os.path.abspath(name)
               for name in os.listdir(".") if os.path.isdir(name)]

rawDescription: Capture subdirectory names as variable

description: Capture subdirectory names as variable


code:
def updateCounter():
   while True:
       wood.next()
       # wood += 1
       time.sleep(60)

rawDescription: How to make an action happen every minute in Python

description: Make an action happen every minute in Python


code:
def naive_map(input_list, do_something):
   result = []
   for i in input_list:
     result.append(do_something(i))
   return result

rawDescription: is synchronization needed with multiprocessor in python?

description: Is synchronization needed with multiprocessor in python


rawDescription: Python statement: sometimes True, sometimes False. Why?


code: prices.asof(amounts.index) * amounts

rawDescription: What representation should I use in Pandas for data valid throughout an interval?


code: import lib.someLibrary

rawDescription: Relative import from current file

description: Relative import from current file


code:
class Foo(object):
    def __init__(self, dictionary):
        for k, v in dictionary.iteritems():
            setattr(self, k, v)
    def __iter__(self):
        return iter(vars(self))

rawDescription: Iterate over unknown object attributes in Python


code:
import urlib.parse, json
cookie_data = urllib.parse.quote(json.dumps(mydict))

rawDescription: How to encode a python dictionary and decode in jquery? (via a cookie)

description: Encode a python dictionary and decode in jquery? (via a cookie)


code:
import bs4, requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
}

from bs4 import BeautifulSoup

with requests.Session() as s:
    s.headers = headers
    r = s.get('https://kindle.amazon.com/login')
    soup = BeautifulSoup(r.content, "html.parser")
    signin_data = {s["name"]: s["value"]
                   for s in soup.select("form[name=signIn]")[0].select("input[name]")
                   if s.has_attr("value")}

    signin_data[u'email'] = 'your_em'
    signin_data[u'password'] = 'pass'

    response = s.post('https://www.amazon.com/ap/signin', data=signin_data)
    soup = bs4.BeautifulSoup(response.text, "html.parser")
    warning = soup.find('div', {'id': 'message_warning'})
    if warning:
        print('Failed to login: {0}'.format(warning.text))
    print(response.content)

rawDescription: Unable to log in to Amazon using Python

description: Unable to log in to Amazon using Python


code:
import mechanize
from BeautifulSoup import BeautifulSoup
br = mechanize.Browser()
resp = br.open('your_url')
soup = BeautifulSoup(resp.get_data())
second_select = soup.findAll('select', name="mv_searchspec")[1]
# now use BeautifulSoup API to get the data you want

rawDescription: differentiating between html form SELECT items with the same name

description: Differentiating between html form SELECT items with the same name


rawDescription: How to compare two lists of dicts in Python?

description: Compare two lists of dicts in Python


code:
def make_downloadable_link(object_id):

    # get object from object_id
    object = ObjectModel.objects.get(id=object_id)
    mypath = object.path

    #prepare to serve the file
    wrapper      = FileWrapper(open(mypath))
    response     = HttpResponse(wrapper,'application/pdf')
    response['Content-Length']      = os.path.getsize(mypath)
    fname = mypath.split('/')[-1]
    response['Content-Disposition'] = 'attachment; filename= fname'
    return response

rawDescription: How can i make the common function/view for servinf downloadble files in django python

description: Make the common function/view for servinf downloadble files in django python


code:
"""
This script retrieves a hardware information for an specific hardware object.
It is only necessary to specify the hostname from the server.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
http://sldn.softlayer.com/article/object-filters

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
# So we can talk to the SoftLayer API:
import SoftLayer.API

# For nice debug output:
from pprint import pprint as pp

# Your SoftLayer username and api key
API_USERNAME = 'set me'
API_KEY = 'set me'
# Define the hostname from the hardware object
hostname = 'hostnametest'

# Declare an object filter to get an specific hardware object
filterHardware = {
    'hardware': {
        'hostname': {
            'operation': hostname
        }
    }
}

# Creates a new connection to the API service.
client = SoftLayer.API.Client(username=API_USERNAME,api_key=API_KEY)

try:
    hardwareObjects = client['SoftLayer_Account'].getHardware(filter=filterHardware)
    pp(hardwareObjects)

except SoftLayer.SoftLayerAPIError as e:
        pp('Unable to get the hardware object faultCode=%s, faultString=%s'
            % (e.faultCode, e.faultString))

rawDescription: Softlayer Server_ID

description: Softlayer Server_ID


rawDescription: How to remove items from lista comparing with another list listb

description: Remove items from lista comparing with another list listb


rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


code:
l = sorted(d.items(), key=lambda x:x[1], reverse=True)
l

rawDescription: convert a dict to sorted dict in python

description: Convert a dict to sorted dict in python


code:
with open('output.txt', 'w+') as new_file:
    for item in txt_list:
        new_file.write(item)

rawDescription: How do I save the output I have to a new text file?

description: Save the output I have to a new text file


rawDescription: Best way of removing single newlines but keeping multiple newlines


code:
def make_new_yu(yu, i):
    return lambda x: i + yu(x)

rawDescription: Python: Lambda in a sum

description: Python: Lambda in a sum


code:
import time

now = time.time()
future = now + 10
while time.time() < future:
    # do stuff
    pass

rawDescription: Stopwatch In Python

description: Stopwatch In Python


rawDescription: How to get the resource for a given security group using python boto?

description: Get the resource for a given security group using python boto


code:
prefix, _, sprint = version.rpartition('.')
newversion = '{}.{}'.format(prefix, int(sprint) + 1)

rawDescription: increment a variable like */2.4.7 via python

description: Increment a variable like */2.4.7 via python


code:
from rest_framework import permissions

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.user == request.user

rawDescription: Use request.user for model deserialization in django rest framework


rawDescription: Django filter on TimeField

description: Django filter on TimeField


code:
settings.beginGroup('layouts')
settings.beginGroup('layoutname1')
# set various layout values...
settings.endGroup()
settings.beginGroup('layoutname2')
# set various layout values...
settings.endGroup()
settings.endGroup()

rawDescription: Is it possible to pickle a QSettings object?


code:
import pkg_resources
data_stream = pkg_resources.resource_stream('myapp', 'relative/path/filename')
data = data_stream.read()

rawDescription: Python - Accessing Application Resources without Filepath Dependancy


code:
Traceback(filename='/Users/raymond/Documents/tmp3.py',
          lineno=11,
          function='multiply_then_trace',
          code_context=['    Z = multiply(X, Y)\n'],
          index=0)

rawDescription: Cleanest way to compute less in a function by implicitly knowing what the callback / caller function is in Python?


code:
mask = np.ones(a.shape, dtype=bool)
np.fill_diagonal(mask, 0)
max_value = a[mask].max()

rawDescription: Minimum of Numpy Array Ignoring Diagonal


code: df['A'] = df['A'].map(addOne)

rawDescription: pandas DataFrame, how to apply function to a specific column?

description: Pandas DataFrame, how to apply function to a specific column


rawDescription: Pandas: break categorical column to multiple columns


rawDescription: Matching up differing timestamp conventions across device data


code: result = {}

rawDescription: A dictionary mapping words to lists of objects


code: from script1 import getCities

rawDescription: Writing a method that I can call in a separate script in python


code: Foo = 1

rawDescription: Python 3 NOT updating variables in a nested package (”recursive” relative imports used)


code:
L = [{'color':'yellow','fruit':'banana'},{'firstname':'Jack','lastname':'Black'}]
[d for d in L if 'firstname' in d and 'lastname' in d]

rawDescription: Get to nested dictionary in list

description: Get to nested dictionary in list


code:
class MyUser(User):

    class Meta:
        proxy = True

    @property
    def keywords(self):
        return u','.join(self.get_full_name().split())

def proxy_access_fn(self):
    return MyUser.objects.get(id=self.id)

setattr(User, 'my_proxy', property(proxy_access_fn))

rawDescription: Getting Proxied user object in django templates


code: input_list[:] = [x for x in (s.strip() for s in input_list) if x]

rawDescription: Python - list comprehension in this case is efficient?


code:
def memoryviewbuffer (source, start, end = -1):
    return source[start:end]

PYTHON_3 = sys.version_info >= (3, )
if PYTHON_3:
    b = memoryviewbuffer
    s = memoryview(s)
else:
    b = buffer

print(timeit.timeit("r.search(b(s, 10))", setup='from __main__ import r, s, b'))

rawDescription: Is there a way to use a memoryview with regexes in Python 2?


code:
IncompleteList=['00:00:00', '00:00:01', '00:00:03','23:59:59']
IncompleteSet = set(IncompleteList)
MyList=['22', '33', '25','13']
CompleteList=['00:00:00', '00:00:01', '00:00:02', '00:00:03','23:59:59']
MyListIt = iter(MyList)
[next(MyListIt) if cl_elem in IncompleteSet else '' for cl_elem in CompleteList]

rawDescription: Include empty values in a list according to specific positions (Python)


rawDescription: find index of similar values

description: Find index of similar values


code:
def foo():
    if conditional():
        logger.info("<Conditional's meaning> happened, so we're not "
                    "setting up the interface.")

rawDescription: How to cleanly keep below 80-char width with long strings?

description: Cleanly keep below 80-char width with long strings


code:
result = {}
for name, count in a_list:
    result[name] = result.get(name, 0) + count

rawDescription: Adding and combining values with dictionary comprehensions?


code: allRanges = rangesForFile0 + rangesForFile1 + ...

rawDescription: Python Compare overlap of multiple dictionaries of ranges


code:
from PyQt4.QtGui import QDialog
from Ui_LoginDialog import Ui_login_dialog

class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_login_dialog()
        self.ui.setupUi(self)

    def get_username(self):
        return self.ui.username_LE.text()

    def get_password(self):
        return self.ui.password_LE.text()

    def is_valid(self):
        # determine if username and password combination are valid
        return True

rawDescription: How to close a login dialog and show the main window (PyQt4)

description: Close a login dialog and show the main window (PyQt4)


code: M_selection = M[i_min:i_max, j_min:j_max, k_min:k_max]

rawDescription: How to extract a sub-array in numpy efficiently?

description: Extract a sub-array in numpy efficiently


code:
def change_Title(self, title, *args):
    self.main.change_curr_title(title)

rawDescription: Kivy - Why Label does not update?

description: Kivy - Why Label does not update


code:
def update_activity(self):
    self.last_active_at = now()

rawDescription: Django Models: Keep track of activity through related models?


code:
data_sets_a = [
    d.groupby(
        ['col_a', 'col_b', 'col_c']
    ).agg(funcs, inplace=True).reset_index() for d in data_sets_a
]

rawDescription: How do I apply transformations to list of pandas dataframes?

description: Apply transformations to list of pandas dataframes


code: kvdict = {}

rawDescription: Python : text replacemnt in two files using a keyword?


code:
def deleteButton():
    b = layout.takeAt(2)
    buttons.pop(2)
    w = b.widget()
    w.setParent(None)

rawDescription: PySide: Removing a widget from a layout

description: PySide: Removing a widget from a layout


code:
def makeS(N):
    values = np.array([v(x) for x in x_range])
    values_doubled = 2 * values
    result = np.eye(N, k=1) * values[0]
    result[:, 0] = values[1:]
    for i in xrange(N - 1):
        result[i + 1, 1:i + 2] = values_doubled[1:i + 2][::-1]
    return result

rawDescription: Efficient way to create a dense matrix from diagonal vectors in Python?


rawDescription: How to print from a loop onto a single line

description: Print from a loop onto a single line


code:
# settings.py
default_settings = {'foo': True, 'bar': False}
my_settings = {'foo': False}
current_settings = default_settings.copy()
current_settings.update(my_settings)

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


code: custom_cv = zip(train_indices, test_indices)

rawDescription: How to customize sklearn cross validation iterator by indices?

description: Customize sklearn cross validation iterator by indices


code: [(i,j) for i in t1 for j in t2]

rawDescription: Remove particular combinations from itertools.combinations


code:
name = 'xml.etree.ElementTree.ElementTree'
parts = name.rsplit('.', 1)
ElementTree = getattr(__import__(parts[0], fromlist=['']), parts[1])
tree = ElementTree()

rawDescription: How do you map a fully qualified class name to its class object in Python?

description: Map a fully qualified class name to its class object in Python


code:
lck = threading.Lock()

def dir_change_callback(dwErrorCode,dwNumberOfBytesTransfered,p):
     print("dir_change_callback! PID:" + str(os.getpid()))
     print("CALLBACK THREAD: " + str(threading.currentThread()))

...
...
...

lck.acquire()
print("Waiting!")
docall()
lck.acquire()

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
cmd.extend(connect_cmd)
cmd.extend(remote_cmd)
try:
    remote = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    local = subprocess.Popen(local_cmd, stdin=remote.stdout)
    remote.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
    local.communicate()
except KeyboardInterrupt:
    exit(0)

rawDescription: script will not save locally over ssh

description: Script will not save locally over ssh


code:
class Country(db.Model):
    name = db.StringProperty()
    count = db.IntegerProperty()

rawDescription: Ran out of "Datastore Small Operations" quota unexpectedly


code:
selection = ''
while selection.lower() not in ("r","t"):
    print("This program can operate in random mode (fluctuations will randomly occur) or it can operate in test mode (fluctuations are fixed).")
    print("(r)andom mode")
    print("(t)est mode")
    selection = input("Mode of operation:")
    if selection.lower() not in ("r","t"):
         print("\nPlease select 'r' or 't' for mode selection\n")
    elif (selection.lower() == "r"):
        print("Random mode enabled")
        n = random.randrange(1,101)
        selection = '' # redefined here
        while selection not in ("1","2","3"):
            print("\tInvestment options:")
            print("(1)Fly-By-Night Investments (FBN): high risk, high potential returns")
            print("(2)Blue Chips INC. (BCI): moderate risk, good potential yearly returns")
            print("(3)Slow-And-Steady-Corp. (SNS), mature industry stock: no risk but low returns")
            selection = input("Please enter your investment option 1, 2, or 3:")
            if selection not in ("1","2","3"):
                print("\nPlease enter an investment option from the menu using 1, 2, or 3 as valid selections:\n")

rawDescription: Trouble closing loops or creating a prompt to progress


code:
import dis
def foo():
    return [x for x in y]

dis.dis(foo)

rawDescription: Why does locals() return a strange self referential list?


code:
@jit(nopython=True)
def numba_get_pos_neg_bitwise(df, mask):
    pos = np.zeros(df.shape[0])
    neg = np.zeros(df.shape[0])
    vandmask = np.bitwise_and(df[:, 1:], mask)

    for idx in range(df.shape[0]):

        # numba fail with # if np.all(vandmask == mask):
        vandm_equal_m = 1
        for i in xrange(vandmask.shape[1]):
            if vandmask[idx,i] != mask[i]:
                vandm_equal_m = 0
                break
        if vandm_equal_m == 1:
            if df[idx, 0] == 1:
                pos[idx] = 1
            else:
                neg[idx] = 1
    pos = np.nonzero(pos)[0]
    neg = np.nonzero(neg)[0]
    return pos, neg

rawDescription: Numba 3x slower than numpy

description: Numba 3x slower than numpy


code: d1 = {(i, j): {} for i in range(4) for j in range(4)}

rawDescription: Dictionary assignment to tuple-keys in other dictionary with map() function


code:
import itertools
outrow = (['H:\\Test\\Test_Data\\New Layer.lyr'], [], ['H:\\Test\\Test_Data\\New_Shapefile.dbf', 'H:\\Test\\Test_Data\\New_Shapefile.shp'], [], [], [], [], [], [], ['H:\\Test\\Test_Data\\New_dBASE_Table.dbf'], [])
w.writerows(itertools.izip_longest(*outrow, fillvalue=""))

rawDescription: Write each list as a column in csv table


code:
import csv
for row in csv.reader(open('allnamesallyearsn.csv')):
    c.execute(sql, row)

rawDescription: Incorrect number of bindings supplied for CSV Sqlite Python script


code: A.T * A

rawDescription: How to convert co-occurrence matrix to sparse matrix

description: Convert co-occurrence matrix to sparse matrix


code:
import csv

with open ('filename.cv','wb') as file:
   writer=csv.writer(file)
   for row in course_list:
      writer.writerow(row)

rawDescription: writing and saving CSV file from scraping data using python and Beautifulsoup4

description: Writing and saving CSV file from scraping data using python and Beautifulsoup4


rawDescription: How to move data in numpy array from column/row to another based on value in third column

description: Move data in numpy array from column/row to another based on value in third column


code:
from collections import Counter
lis1 = [['a', 2], ['b',1]]
lis2 = [['b', 2], ['c', 1]]
c = Counter(dict(lis1)) + Counter(dict(lis2))
c.most_common()

description: Any pythonic way to do "[['a', 2], ['b',1]] + [['b', 2], ['c', 1]] = [['b', 3], ['a', 2], ['c', 1]]"


code:
list = []
list.append(user.first_name.lower()) # to have lowercase strings

rawDescription: Find the Common first_name from Django Auth user Model


code: noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

rawDescription: No Primes list Comprehension

description: No Primes list Comprehension


code: df.groupby('User')['X'].filter(lambda x: x.sum() == 0)

rawDescription: How to subset a data frame using Pandas based on a group criteria?

description: Subset a data frame using Pandas based on a group criteria


code:
test = b'hello\x00world'
test
test_without_nulls = bytes(filter(lambda x: x != b'\x00', test))
test_without_nulls

rawDescription: How to consistently ignore one byte from a string

description: Consistently ignore one byte from a string


code:
def group_runs(li,tolerance=2):
    out = []
    last = li[0]
    for x in li:
        if x-last > tolerance:
            yield out
            out = []
        out.append(x)
        last = x
    yield out

rawDescription: Group consecutive integers and tolerate gaps of 1


code:
def courses_display(request, category=None):
    ctx = {}
    if category:
        ctx.update({category: 'in'})
    return render_to_response('display/basic.html', ctx,    context_instance=RequestContext(request))

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


code:
channel_obj = db.TVChannel().get_id(channel_id) #load a channel's infos into an object
channel     = ChannelForm(request.form, obj=channel_obj) #load channel form
channel.CITY1adapt.process_data(channel_obj.streams['City1']['adapt'])
#and others links

rawDescription: Flask-WTF: how pass structered object to form


code:
def factorial(X):
    if X == 0:
        return 1
    else:
        return factorial_recurrence(factorial(X - 1), X)

rawDescription: Issues with Recursion using Python 3

description: Issues with Recursion using Python 3


code:
import random
random_a = { k: [1000.0*random.random() for i in xrange(50)] for k in xrange(1000)}
timeit('f(a.copy())', 'from __main__ import a, original as f', number=100000)
timeit('f(a.copy())', 'from __main__ import a, zip_and_max as f', number=100000)

rawDescription: normalise list data in range (0.0, 1.0)

description: Normalise list data in range (0.0, 1.0)


code:
from django.views.decorators.cache import cache_page

def cache_on_auth(timeout):
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            return cache_page(timeout, key_prefix="_auth_%s_" % request.user.is_authenticated())(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return decorator

rawDescription: Django Caching for Authenticated Users Only


code:
fig, ax = subplots(1, 1)
plot(randn(100));

rawDescription: Redisplaying modified plot in subsequent IPython notebook cells


code:
def group_by_month(items):
    month = []
    for day, flag in items:
        if month and month[-1][0] > day:
            # new month starting
            yield month
            month = []
        month.append((day, flag))
    if month:
        yield month

rawDescription: How to group items in array?

description: Group items in array


rawDescription: python text files

description: Python text files


rawDescription: Python: Cell arrays comparison using minus function


code:
from pprint import pprint

# make some simple data structures
dct = {k: v for k, v in zip('abcdefghijklmnopqrstuvwxyz', range(26))}

# define a filename
filename = '/tmp/foo.txt'

# write them to some log
pprint(dct, open(filename, 'w'))

# open them back out of that log and use the readlines() function
# to let python split on the new lines for us
with open(filename, 'r') as f:
    obj = eval(f.read())

print(type(obj))
print(obj)

rawDescription: Reading in a pprinted file in Python

description: Reading in a pprinted file in Python


code:
def vig_2(row, col):
    return string.ascii_uppercase[(ord(row) + ord(col)) % 26]

rawDescription: For Kasiski Test,How to implement 26x26 table in Python


code:
timeit.timeit('abs(np.diff(mat, axis=0))', 'from __main__ import np, mat')
timeit.timeit('abs(mat[1:,:] - mat[:-1,:])', 'from __main__ import np, mat')

rawDescription: Column wise subtraction in numpy

description: Column wise subtraction in numpy


code:
with open("output.bed", "w+b") as f:
    for m in all_matches:
        f.write('%s\t%i\t%i\n' % m)

rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


rawDescription: Structure representing time without date in Python


code:
nr = '01{:%Y%m%d%H%M}{:04}\n'.format(d, int(p * 0.2))
outfile.write(nr)

rawDescription: Print strings with line break Python

description: Print strings with line break Python


code:
from collections import defaultdict
name_entries = defaultdict(list)
for row in data:
    name_entries[row[col_name]].append(row)

rawDescription: Disturbing odd behavior/bug in Python itertools groupby?


code:
ModelX.objects.filter(category__in = ('catA','catB'), row_number__lte = 30)
ModelX.objects.filter(row_number = 29)
...

rawDescription: Limit queryset results based on model field, are there better ways?


code:
#!/usr/bin/python

from Tkinter import *

class Application:
    def __init__(self, master):
        self.master = master
        self.master.title("Main Page")
        self.label = Label(master, text="Decem Rationes Computerum Programmandorum")
        self.label.grid(row=1, column=2)
        self.button = Button(master, text="Decem Rationes", command=self.openWindowReasons)
        self.button.grid(row=3, column=3)
        self.button_1= Button(master, text="Pleasant Alternative", command=self.openWindowAlt)
        self.button_1.grid(row=3, column=1)

    def openWindowAlt(self):
        newWin_1 = Toplevel()
        label_2 = Label(newWin_1, text="Magister Bartoloma tam sapiens ut Minerva, quae dea sapientae est, eum admiretur.")
        label_2.pack()

    def openWindowReasons(self):
        self.toplevel = Toplevel()
        self.buttonMaker("I", 1, 1, " I) Programmo computeres ne meus animus deceat ignavus." )
        self.buttonMaker("II", 2, 1, " II) Programmo computeres ut relaxem post scholam et gaudeam scholam esse perfectam.")
        self.buttonMaker("III", 3, 1, " III) Meo amico programmato programmo ut certem cum eo.")
        self.buttonMaker("IV", 4, 1, " IV) Alii homines qui boni porgrammi programmant ut facian pecuniam.")
        self.buttonMaker("V", 5, 1, " V) Alii homines scribunt tantam codem ut alii cogitent eos esse optimos.")
        self.buttonMaker("VI", 1, 3, " VI) Programmare est tam iocus ut sperem me programmaturum esse saepius.")
        self.buttonMaker("VII", 2, 3, " VII) Multi homines programmant tam ut non habent tempus faciendorum pensorum quod sunt quam insulso.")
        self.buttonMaker("VIII", 3, 3, " VIII) Programmo ut possim loqui de eo cum meis amicis.")
        self.buttonMaker("IX", 4, 3, " IX) Me inspirato ab caeteris programmo ut sim similaris eis.")
        self.buttonMaker("X", 5, 3, " X) Saepe programmo ne habeam audire mea matri quae dictit quam multa.")
        label_1 = Label(self.toplevel, text="RATIONES")
        label_1.grid(row=3, column=2)

    def buttonMaker(self, a, b, c, d):
        f = Button(self.toplevel, text="button" + a, command=lambda d=d: self.openWindowR(str(d)))
        f.grid(row=int(b), column=int(c))

    def openWindowR(self, d):
        newWin = Toplevel()
        newWin.title(str(d))
        g = Label(newWin, text="label" + d)
        g.grid()

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

rawDescription: Opening windows from other windows in tkinter


code:
ma.masked_where( ((z<sorted[sorted.size/2-5]) |
                  (z>sorted[sorted.size/2+4])) &
                 ((z>sorted[10]) & (z<sorted[-10])),z)

rawDescription: Maximun and mininum values numpy Array

description: Maximun and mininum values numpy Array


code:
a = dict((x, x) for x in range(10))
a

rawDescription: How to construct a dictionary which contain keys which are invalid keyword arguments, not using {}

description: Construct a dictionary which contain keys which are invalid keyword arguments, not using {}


code:
col1 = ['a', 'b', 'c']
col2 = [[1,2], [4,3,2], []]
col2_lens = map(len, col2)

# flatten col2
s2 = Series([eli for el in col2 for eli in (el or [nan])])

# replicate elements of col1 col2[i] times
s1 = Series(list(''.join(el * (col2_len or 1) for el, col2_len in zip(col1, col2_lens))))
concat([s1, s2], axis=1)

rawDescription: Import python dict with variable-length list items into pandas


code:
strength = float(raw_input("Input Strength Stat:"))
str_mod = round(strength/2)

rawDescription: Rounding positive/negative numbers to nearest "whole" number in python


code:
bincount = np.zeros(9)
for i in range(1000):
    a = np.random.random_integers(0 , 8, 1000)
    bincount += np.histogram(a, bins)[0]

bincount

rawDescription: Counts in bins using loop

description: Counts in bins using loop


code:
def OnClicked(textbox1, event=None):
    text = textbox1.get()

    stepwindow.delete(0,END)
    vehicle=str(txtEntrXpression.get())

    if text == "Arrival":
        Arrival(vehicle)
    elif text == "Departure":
        Departure(vehicle)

rawDescription: bind two commands for one button

description: Bind two commands for one button


code:
def sweep_non_sym(a, k):
    a = np.asarray(a)
    n = a.shape[0]
    if a.shape != (n, n):
        raise ValueError('Not a square array')
    if k >= n:
        raise ValueError('Not a valid row number')
    #  Fill with the general formula
    b = a - np.outer(a[:, k], a[k, :]) / a[k, k]
    # b = a - a[:, k:k+1] * a[k, :] / a[k, k]
    # Modify the k-th row and column
    b[k, :] = a[k, :] / a[k, k]
    b[:, k] = -a[:, k] / a[k, k]
    # Modify the pivot
    b[k, k] = 1 / a[k, k]
    return b

rawDescription: Python implementation of statistical Sweep operator


code:
soup.find_all("a", href=re.compile(r"/markets/NZSX/securities/"))
soup.find_all("a", href=lambda href: href and "/markets/NZSX/securities/" in href)
soup.select('a[href*="/markets/NZSX/securities/"]')

rawDescription: Finding partial matches in an href tag

description: Finding partial matches in an href tag


rawDescription: Python permutations of both sequence and subsequences


code:
def fix_window(self):
        set = False
        while set == False:
            try:
                window = myXwindow.Window(self.parent().winId())
                if window != None:
                    height = self.parent().height()
                    window.reserve_space(0, 0, height, 0)
                    set = True
                else:
                    self.sleep(1)
            except:
                raise

rawDescription: Python: tell X to reserve screen space for application


code:
import time

def do_something():
    with open("/tmp/current_time.txt", "w") as f:
        f.write("The time is now " + time.ctime())

def run():
    while True:
        time.sleep(60)
        do_something()

if __name__ == "__main__":
    run()

rawDescription: Efficient Python Daemon

description: Efficient Python Daemon


code:
import git
import tempfile

tmpdir = tempfile.TemporaryDirectory(suffix='.git')
repo = git.Repo.init(tmpdir.name, shared=True, bare=True)
repo.daemon_export = True

gd = git.Git().daemon(tmpdir.name,
                      enable='receive-pack',
                      listen='127.0.0.1',
                      port=9418,
                      as_process=True,
                      verbose=True
)
gd.proc.wait()

rawDescription: Serve repository using git daemon with GitPython


rawDescription: Count binary ones and find intersections in Pandas DataFrame


rawDescription: How to make Python Interactive Shell print cyrillic symbols?

description: Make Python Interactive Shell print cyrillic symbols


code: from asterisk import *

rawDescription: Multiple Database Config in Django 1.2

description: Multiple Database Config in Django 1.2


code: list1 == list2

rawDescription: How to check if two lists have the same objects in the same order?

description: Check if two lists have the same objects in the same order


code:
def collide_top(a, b):
    return a.top == b.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_bottom(a, b):
    return a.bottom == b.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_left(a, b):
    return a.left == b.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)
def collide_right(a, b):
    return a.right == b.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)

rawDescription: How to assign and test for attributes on a rect in Pygame

description: Assign and test for attributes on a rect in Pygame


rawDescription: Can some one explain me what does np.log do?


code: [d for d in range(1,31) if is_business_day(datetime.date(2017,5,d))]

rawDescription: How would you get the xth weekday of a given month in python?


rawDescription: Slicing a python string with intervals?

description: Slicing a python string with intervals


code:
def party_generator(size=1, chars=string.ascii_uppercase):
    return ['Party {}'.format(party) for party in random.sample(CharacterRange(chars, size))]

rawDescription: Generate 2 Unique but random Elements in a List


code:
import json
import time

datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")
    else:
        def add_data(users):
            for i in range(users):
                datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")})
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry["name"])
        print("Email:  "+entry["mail"])
        print("DOB:  "+entry["dob"])
        print("\n")

def search_function(value):
  for eachperson in datastore:
    for i in eachperson.keys():
        if value in eachperson[i]:
            print_resource(eachperson)

while menuon == 1:
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0

rawDescription: How can I save the array to a text file and import it back?

description: Save the array to a text file and import it back


code:
level_lookup_order = ['PRIORITY_1', 'PRIORITY_2', ...]
for key in level_lookup_order:
    if key in level_lookup:
        do_stuff(level_lookup[key])

rawDescription: How to iterate over a Python dictionary in defined order?

description: Iterate over a Python dictionary in defined order


code: foundFilesFixed = [str(value for value in file if value) for file in foundFiles]

rawDescription: Getting rid of empty strings in a tuple

description: Getting rid of empty strings in a tuple


code: cols = pd.read_csv(io.StringIO(t), nrows=1).columns.tolist()

rawDescription: How to read index data as string with Python pandas?

description: Read index data as string with Python pandas


code:
libncursesw5-dev
libssl-dev
libgdbm-dev
libsqlite3-dev
tk-dev

rawDescription: Python install not behaving like native python


code:
def compose(func1, func2):
    def composed(*args, **kw):
        return func2(func1(*args, **kw))
    return composed

class addable(object):
    def __init__(self, func):
        self.func = func
    def __add__(self, other):
        if callable(other):
            return addable(compose(self.func, other))
        raise TypeError
    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

@addable
def mysum(a, b):
    return a + b

@addable
def dup(a):
    return a * 2

rawDescription: Weird function/class casting in Python. Why do we have it?


code:
df
s
df.join(s)

rawDescription: How to get a combined look at two different DataFrames

description: Get a combined look at two different DataFrames


code:
import json
with open('myfile', 'r') as f:
    data = json.load(f)

rawDescription: Overwrite flags in a file python

description: Overwrite flags in a file python


code:
from datetime import datetime, timedelta

def genDatePeriods(startDate, endDate, format='%Y-%m-%d'):
    curr = datetime.strptime(startDate, format).date()
    end = datetime.strptime(endDate, format).date()

    while curr <= end:
        # first day of the next month, using modular arithmetic
        next_month = curr.replace(
            month=curr.month % 12 + 1, year=curr.year + curr.month // 12,
            day=1)
        curr_formatted = curr.strftime(format)
        # end date is next month's first day, minus one day,
        # or the given endDate, whichever comes first
        end_formatted = min(next_month - timedelta(days=1), end).strftime(format)
        yield [curr_formatted, end_formatted]
        curr = next_month

rawDescription: Generate date ranges broken by month for a given period


code:
user = {}
mbox('starting in 1 second...', t=1)
user['name'] = mbox('name?', entry=True)
if user['name']:
    user['sex'] = mbox('male or female?', ('male', 'm'), ('female', 'f'))
    mbox(user, frame=False)

rawDescription: Correct way to implement a custom popup tkinter dialog box


code:
class _MethodDecoratorAdaptor(object):
    def __init__(self, decorator, func):
        self.decorator = decorator
        self.func = func
    def __call__(self, *args, **kwargs):
        return self.decorator(self.func)(*args, **kwargs)
    def __get__(self, instance, owner):
        return self.decorator(self.func.__get__(instance, owner))

def auto_adapt_to_methods(decorator):
    """Allows you to use the same decorator on methods and functions,
    hiding the self argument from the decorator."""
    def adapt(func):
        return _MethodDecoratorAdaptor(decorator, func)
    return adapt

rawDescription: Using the same decorator (with arguments) with functions and methods


code: {{ request.session.temp_data }}

rawDescription: Send form data from views to template

description: Send form data from views to template


rawDescription: Find sum of right and left hand of list element in python


code:
import numpy as np
a = np.ma.zeros((500, 500))
a.dump('test')

rawDescription: How to save numpy masked array to file

description: Save numpy masked array to file


code:
wanted_arr = np.vstack((map(np.array,wanted)))
out = z[((wanted_arr[:,None] == z).all(2)).any(0)]

rawDescription: Find rows of numpy array that are members of a set


code: result = functools.reduce(merge, dfs)

rawDescription: Pandas: merge multiple dataframes and control column names?


rawDescription: Get the latest entries django

description: Get the latest entries django


rawDescription: Verifying arithmetic sequence python

description: Verifying arithmetic sequence python


rawDescription: Python non-greedy regex match with pattern in between


code:
with open("out.html", "w") as f:
       f.write(dr.page_source)

rawDescription: How to retrieve the exact HTML as in a browser

description: Retrieve the exact HTML as in a browser


rawDescription: How to map a function to every item in every sublist of a list

description: Map a function to every item in every sublist of a list


code: ops[op](first,second)

rawDescription: python random arithmetic game

description: Python random arithmetic game


code:
import lxml.etree as ET
import lxml.builder
import glob

dbchangelog = 'http://www.host.org/xml/ns/dbchangelog'
xsi = 'http://www.host.org/2001/XMLSchema-instance'
E = lxml.builder.ElementMaker(
    nsmap={
        None: dbchangelog,
        'xsi': xsi})

ROOT = E.databaseChangeLog
DOC = E.include

# grab all the xml files
files = [DOC(file=f) for f in glob.glob("*.xml")]

the_doc = ROOT(*files)
the_doc.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'www.host.org/xml/ns/dbchangelog'

print(ET.tostring(the_doc,
                  pretty_print=True, xml_declaration=True, encoding='utf-8'))

rawDescription: Python: adding xml schema attributes with lxml


code: [d['ParentGuardianID'] for d in list_of_dicts]

rawDescription: Obtaining a value from a list of dictionaries


code: img.setTo(Scalar(b, g, r));

rawDescription: the equivalent of python's [:] in c++

description: The equivalent of python's [:] in c++


rawDescription: how to import module from other directory in python?

description: Import module from other directory in python


code: union_set = set.union(*l)

rawDescription: Taking the union of sets

description: Taking the union of sets


code: dict(zip(i,zip(*j)))

rawDescription: How to add two lists into dictionary?

description: Add two lists into dictionary


code:
class A:
    def __init__(self):
        self.d = {}
    def c(self):
        print (self.d)

class B(A):
    def __init__(self):
        A.__init__(self)
        self.d.update({0:1})

# create instances of each class
a = A()
b1 = B()
b2 = B()

# call each instance's c method
b1.c()
b2.c()
a.c()

# you can even update on the fly without affecting the other!
a.d.update({2:3})
b1.d.update({4:5})
b2.d.update({7:8})
b1.c()
b2.c()
a.c()

rawDescription: Class attribute overriding: keep parent class changes


rawDescription: How to sum elements of a list corresponding to elements of another list in python

description: Sum elements of a list corresponding to elements of another list in python


code: y[np.ix_(mask, mask)] = other

rawDescription: Restricting a sparse matrix to a subspace in scipy


code:
import socket
import re

class MessageError(Exception): pass

class MessageReader(object):
    def __init__(self,sock):
        self.sock = sock
        self.buffer = b''

    def get_until(self,what):
        while what not in self.buffer:
            if not self._fill():
                return b''
        offset = self.buffer.find(what) + len(what)
        data,self.buffer = self.buffer[:offset],self.buffer[offset:]
        return data

    def get_bytes(self,size):
        while len(self.buffer) < size:
            if not self._fill():
                return b''
        data,self.buffer = self.buffer[:size],self.buffer[size:]
        return data

    def _fill(self):
        data = self.sock.recv(1024)
        if not data:
            if self.buffer:
                raise MessageError('socket closed with incomplete message')
            return False
        self.buffer += data
        return True

remote_host = 'www.google.com'
remote_port = 80

remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((remote_host, remote_port))
remote_socket.sendall(b'GET http://www.google.com/images/logos/ps_logo2a_cp.png HTTP/1.1\r\nHost: www.google.com\r\nCache-Control: max-age=0\r\nPragma: no-cache\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.794.0 Safari/535.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n\r\n')
mr = MessageReader(remote_socket)
header = mr.get_until(b'\r\n\r\n')
print(header.decode('ascii'))
m = re.search(b'Content-Length: (\d+)',header)
if m:
    length = int(m.group(1))
    data = mr.get_bytes(length)
    print(data)
remote_socket.close()

rawDescription: Why doesn't Python socket receive a final blank value during recv loop of HTTP socket?


code:
import networkx as nx

G = nx.complete_graph(10)
G.node[0]['ColorNode'] = True  # right-hand side value is irrelevant for the lookup
G.node[1]['ColorNode'] = True
G.node[2]['ShapeNode'] = True
G.node[3]['ShapeNode'] = True

shape_nodes = nx.get_node_attributes(G, 'ShapeNode').keys()
color_nodes = nx.get_node_attributes(G, 'ColorNode').keys()

print('Shape node ids: {}'.format(shape_nodes))
print('Color node ids: {}'.format(color_nodes))

rawDescription: Get nodes of specific type in Networkx

description: Get nodes of specific type in Networkx


code: struct.pack("!Bbh", 0, 1, 7)

rawDescription: How to send packets in a Minecraft Classic server written in Python

description: Send packets in a Minecraft Classic server written in Python


code:
def f1(a, b) :
    a, b = 2 * a, 3 * b
    return ne.evaluate('2*a + 3*b + c',
                       local_dict={'c' : np.arange(30, 40)})
f1(a, b)
2*a + 3 * b + np.arange(30, 40)

rawDescription: Numexpr: How to use "local_dict" and "global_dict"?


rawDescription: python re.search (regex) to search words who have pattern like {{world}} only

description: Python re.search (regex) to search words who have pattern like {{world}} only


code:
import csv

with open("input.csv", "r") as f_input, open("output.csv", "wb") as f_output:
    csv_input = csv.reader(f_input, delimiter=" ")
    csv_output = csv.writer(f_output, delimiter=" ")
    headings = csv_input.next()     # skip the header row

    for row in csv_input:
        for col in row[1:]:
            csv_output.writerow([row[0], col])

rawDescription: Column values distributed to adjacent columns


code: Z_conj_reverse = [ w.conjugate() for w in reversed( Z ) ]

rawDescription: Python: convert frequency response to impulse response


code:
from tkinter import *

# ---------------- code for class: curry [BEGIN] ----------------
class curry:
    """from Scott David Daniels'recipe
    "curry -- associating parameters with a function"
    in the "Python Cookbook"
    http://aspn.activestate.com/ASPN/Python/Cookbook/
    """

    def __init__(self, fun, *args, **kwargs):
        self.fun = fun
        self.pending = args[:]
        self.kwargs = kwargs.copy()

    def __call__(self, *args, **kwargs):
        if kwargs and self.kwargs:
            kw = self.kwargs.copy()
            kw.update(kwargs)
        else:
            kw = kwargs or self.kwargs
        return self.fun(*(self.pending + args), **kw)
# ---------------- code for class: curry [END] ------------------

class SampleApp:
    def __init__(self, parent):

        self.textfield = None

        self.myParent = parent
        self.Container = Frame(parent)
        self.Container.pack()

        self.textfield = Entry(self.Container, bg="red")
        self.textfield.pack()

        self.button = Button(self.Container, text="Get", command=curry(self.TestFunction, self.on_button))
        self.button.pack()

    def on_button(self):
        return self.textfield.get()

    def TestFunction(self, var):
        print(var())

root = Tk()
myapp = SampleApp(root)
root.mainloop()

rawDescription: Python 3.4.4 settin argument in Tkinter?

description: Python 3.4.4 settin argument in Tkinter


rawDescription: run command with paramiko for a certain amount of time

description: Run command with paramiko for a certain amount of time


code:
while then < now:
    then += timedelta(days=1)
minutes = (then - now) // timedelta(minutes=1)

rawDescription: How to subtract datenow from time string?

description: Subtract datenow from time string


rawDescription: Adding items to dictionary

description: Adding items to dictionary


code:
class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

rawDescription: Python, creating objects

description: Python, creating objects


code:
p1="/root/d1/d2/d1/d2"
p2="d2/d1/d2/file.txt"
p1+'/'+'/'.join([i for i in p2.split('/') if i not in p1.split('/')])

rawDescription: Is there any smart way to combine overlapping paths in python?


code:
with open("file1") as f, open("file2") as f2:
    st = set(map(str.rstrip,f))
    for line in f2:
        spl = line.split(None, 1)[0]
        if spl in st:
            print(line.rstrip())

rawDescription: Printing out matching lines between two .txt files in Python


code:
def dijkway2(dijkpredmat, i, j):
    wayarr = []
    while (i != j) & (j >= 0):
        wayarr.append(j)
        j = dijkpredmat.item(i,j)
    return wayarr

def jumpvec2(pmat,node):
    jumps = np.zeros(len(pmat))
    jumps[node] = -999
    todo = set()
    for i in range(len(pmat)):
        if i != node:
            todo.add(i)

    indexs = np.arange(len(pmat), 0, -1)
    while todo:
        r = todo.pop()
        dway = dijkway2(pmat, node, r)
        jumps[dway] = indexs[-len(dway):]
        todo -= set(dway)
    return jumps

rawDescription: Calculate number of jumps in Dijkstra's algorithm?


code: t.daemon = True

rawDescription: Python chatserver - Unable to close server because of blocking call


code:
tbl = str.maketrans({ord("?"):"",ord(" "):""})
while True:
    secret_word = input("Please enter a word to be guessedthat does not contain ? or white space: ")
    if len(secret_word.translate(tbl)) == len(secret_word):
        break
    else:
        print("Invalid input")

rawDescription: How do I keep asking the user to input the valid characters?

description: Keep asking the user to input the valid characters


code: H = inv(T) * R * T

rawDescription: 3d rotation on image

description: 3d rotation on image


code:
import boto3
from botocore.client import Config

# Create a client with the s3v2 signer
resource = boto3.resource('s3', config=Config(signature_version='s3'))
gcs_bucket = resource.Bucket('phjordon-test-bucket')
s3_bucket = resource.Bucket('phjordon-test-bucket-tokyo')
for obj in gcs_bucket.objects.all():
    s3_bucket.Object(obj.key).copy_from(
        CopySource=obj.bucket_name + "/" + obj.key)

rawDescription: copy file from gcs to s3 in boto3

description: Copy file from gcs to s3 in boto3


code:
class Foo(object):

    def __init__(self):
        self.fsm = Fysom(TABLE)

    def my_method(self):
        self.fsm.onload()

rawDescription: python FSM Fysom callbacks on the other way

description: Python FSM Fysom callbacks on the other way


code: unstacked = gpm.unstack(['Bracket', 'Win'])

rawDescription: How to use groupby in Pandas to compute columns

description: Use groupby in Pandas to compute columns


code:
class MarketIndexer( djapian.Indexer ):

    fields = [ 'name', 'description', 'tags_string', 'state']
    tags = [('state', 'state'),]

rawDescription: Djapian - filtering results

description: Djapian - filtering results


code:
def my_reader(feed=sys.stdin):
    while True:
        line = feed.readline()
        if not line:
            break
        parse(line)

rawDescription: How to mock a buffered file handle for unit testing

description: Mock a buffered file handle for unit testing


code:
import os
import sys

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

rawDescription: How do I send stdout in real time from nodejs to angularjs?

description: Send stdout in real time from nodejs to angularjs


code:
rules=(
    Rule(SgmlLinkExtractor(allow=(),
                           attrs=('onclick',),
                           process_value=process_onclick),
         callback='parse_item'),
)

rawDescription: How can i use scrapy to parse links in JS?

description: Use scrapy to parse links in JS


code:
with open('latin.txt', 'rb') as fdin, open('utf.txt', 'wb') as fdout:
    for line in fdin:
        fdout.write(line.decode('latin1').encode('utf8'))

rawDescription: Python 3.4 / Notepad++ 6.5 Hex Characters Replacement


code: res = cur.fetchall()

rawDescription: DictCursor doesn't seem to work under psycopg2


code:
sentence = 'Hello, This is string.'
sentence = sentence.replace('i', '', 1) # Replace the first occurence of `i`
sentence = sentence[::-1].replace('i', '', 1)[::-1] # reverse/replace/reverse
sentence.swapcase()

rawDescription: Actions with strings, python

description: Actions with strings, python


rawDescription: Nested options with argparse

description: Nested options with argparse


code:
for x in ascii_lowercase:
    return x,(dic[x]/n)*100

rawDescription: Determing relative letter frequency

description: Determing relative letter frequency


code: [[item + 1 for item in list] for list in list_of_lists]

rawDescription: Adding a value to a list of lists

description: Adding a value to a list of lists


code:
import multiprocessing
import other_package

def worker_process(sub_job):
    other_package.run_job(sub_job)

_manager = None

def get_manager(): # Note that you don't have to use a singleton here
    global _manager
    if not _manager:
        _manager = Manager()
    return _manager

class Manager(object):
    def __init__(self):
        self._pool = multiprocessing.Pool()

    def runProcesses(self, jobs):
        self._pool.map_async(worker_process, jobs)

rawDescription: Python - Asynch Multiprocessing from RabbitMQ Consumer


code:
def dupli(the_list):
    count = the_list.count # this optimization added courtesy of Sven's comment
    result = [(item, count(item)) for item in set(the_list)]
    result.sort()
    return result

rawDescription: how to optimally count elements in a python list

description: Optimally count elements in a python list


code: np.sum((p == 1).values)

rawDescription: Search for value in a panel

description: Search for value in a panel


code:
def invoice_generator(request):
    data = {}
    data['invform'] = InvoiceForm()
    data['itmform'] = ItemForm()
    return render(request, 'invoiceapp/invoice_generator.html', data)

rawDescription: Using field of a related model in a django template


code: clean_string = filter(lambda c: c.isalnum() or c.isspace(), s)

rawDescription: delete characters that are not letters, numbers, whitespace?

description: Delete characters that are not letters, numbers, whitespace


code:
settings = QtCore.QSettings(org_name, app_name)
is_floating = main_win._ui.dockWin.isFloating()
settings.setValue('dockWin/isFloating', is_floating)
main_win._ui.dockWin.setFloating(True)
settings.setValue('geometry', main_win.saveGeometry())
settings.setValue('state', main_win.saveState())

rawDescription: Qt - Pyside - .saveGeom() .saveState() (again)


rawDescription: Adding elements of RGB array in Python

description: Adding elements of RGB array in Python


code: df = pd.concat([df[:1], df[1:].sample(frac=1)]).reset_index(drop=True)

rawDescription: Shuffle DataFrame rows except the first row


code:
no_none = [t for t in my_list if None not in t]
some_none = [t for t in my_list if t != (None, None)]

rawDescription: Filtering a list of tuples filled with None in python


code:
def layerContainer(self):
    self.layerContainer = dict(zip(self.keyFields, self.layerData))
    return self.layerContainer

rawDescription: Saving instances when created by an iterator - Python


code:
def login_required(function_to_wrap):
    @wraps(function_to_wrap)
    def wrap(*args, **kwargs):
        if "some_admin_name" in session:
            return function_to_wrap(*args, **kwargs)
        else:
            flash("\"You shall not pass!\" - Gandalf")
            return redirect(url_for("login"))
    return wrap

rawDescription: What is a self-written decorator (like @login_required) actually doing?


code:
@fab.task
def testrole():
    if 'prod' in fab.env.roles:
        do_production_stuff()
    elif 'staging' in fab.env.roles:
        do_staging_stuff()
    else:
        raise ValueError('No valid role specified!')

rawDescription: How to discover current role in Python Fabric

description: Discover current role in Python Fabric


code:
def encode_b(obj):
    if isinstance(obj, B):
        return obj.__dict__
    return obj

json.dumps(a, default=encode_b)

rawDescription: Python serialize objects list to JSON

description: Python serialize objects list to JSON


code: {1: 'Operation not permitted', 2: 'No such file or directory', 3: 'No such process', 4: 'Interrupted system call', 5: 'Input/output error', 6: 'Device not configured', 7: 'Argument list too long', 8: 'Exec format error', 9: 'Bad file descriptor', 10: 'No child processes', 11: 'Resource deadlock avoided', 12: 'Cannot allocate memory', 13: 'Permission denied', 14: 'Bad address', 15: 'Block device required', 16: 'Resource busy', 17: 'File exists', 18: 'Cross-device link', 19: 'Operation not supported by device', 20: 'Not a directory', 21: 'Is a directory', 22: 'Invalid argument', 23: 'Too many open files in system', 24: 'Too many open files', 25: 'Inappropriate ioctl for device', 26: 'Text file busy', 27: 'File too large', 28: 'No space left on device', 29: 'Illegal seek', 30: 'Read-only file system', 31: 'Too many links', 32: 'Broken pipe', 33: 'Numerical argument out of domain', 34: 'Result too large', 35: 'Resource temporarily unavailable', 36: 'Operation now in progress', 37: 'Operation already in progress', 38: 'Socket operation on non-socket', 39: 'Destination address required', 40: 'Message too long', 41: 'Protocol wrong type for socket', 42: 'Protocol not available', 43: 'Protocol not supported', 44: 'Socket type not supported', 46: 'Protocol family not supported', 47: 'Address family not supported by protocol family', 48: 'Address already in use', 49: "Can't assign requested address", 50: 'Network is down', 51: 'Network is unreachable', 52: 'Network dropped connection on reset', 53: 'Software caused connection abort', 54: 'Connection reset by peer', 55: 'No buffer space available', 56: 'Socket is already connected', 57: 'Socket is not connected', 58: "Can't send after socket shutdown", 59: "Too many references: can't splice", 60: 'Operation timed out', 61: 'Connection refused', 62: 'Too many levels of symbolic links', 63: 'File name too long', 64: 'Host is down', 65: 'No route to host', 66: 'Directory not empty', 68: 'Too many users', 69: 'Disc quota exceeded', 70: 'Stale NFS file handle', 71: 'Too many levels of remote in path', 77: 'No locks available', 78: 'Function not implemented', 84: 'Value too large to be stored in data type', 90: 'Identifier removed', 91: 'No message of desired type', 92: 'Illegal byte sequence', 94: 'Bad message', 95: 'EMULTIHOP (Reserved)', 96: 'No message available on STREAM', 97: 'ENOLINK (Reserved)', 98: 'No STREAM resources', 99: 'Not a STREAM', 100: 'Protocol error', 101: 'STREAM ioctl timeout', 102: 'Operation not supported on socket'}

rawDescription: How to get the list of error numbers (Errno) for an Exception type in python?

description: Get the list of error numbers (Errno) for an Exception type in python


code: X * coeffs[:, np.newaxis, np.newaxis]

rawDescription: Multiply (a x a) square matrix by (a x c x d) matrix


rawDescription: python BeautifulSoup parsing table

description: Python BeautifulSoup parsing table


rawDescription: How can I write a method within a Django model to retrieve related objects?

description: Write a method within a Django model to retrieve related objects


code:
{OneVsRestClassifier(SVC(C=1, kernel="poly", degree=1)),
 OneVsRestClassifier(SVC(C=1, kernel="poly", degree=2)),
 ...,
 OneVsRestClassifier(SVC(C=8, kernel="rbf", degree=3)),
 OneVsRestClassifier(SVC(C=8, kernel="rbf", degree=4))}

rawDescription: Sklearn: Evaluate performance of each classifier of OneVsRestClassifier inside GridSearchCV


code:
def calc_iso_surface_2(my_array, my_value, zs):
    '''Takes the average of the two closest zs
    '''
    from numpy import argsort, take
    dist = (my_array - my_value)**2
    arg = argsort(dist,axis=2)
    z0 = take(zs, arg[:,:,0])
    z1 = take(zs, arg[:,:,1])
    z = (z0+z1)/2
    return z

rawDescription: Using numpy/scipy to calculate iso-surface from 3D array


code:
def shrink(s):
    for i in range(len(s)):
        yield s[i:]

rawDescription: how can I generate a fragment library from a protein sequence file?

description: Generate a fragment library from a protein sequence file


rawDescription: Django store regular expression in DB which then gets evaluated on page


code:
col_1 = np.vstack([knight, knight]) # Simply put the images in the list
                                    # I've put 2 knights as example

rawDescription: How to best create a new image out of existing images in openCV

description: Best create a new image out of existing images in openCV


code: from collections import Counter

rawDescription: Sort data to present barchart highest to lowest in python


code:
X_projected = pca.inverse_transform(X_train_pca)
X_projected2 = X_train_pca.dot(pca.components_) + pca.mean_

assert_array_almost_equal(X_projected, X_projected2)

rawDescription: PCA projecting and reconstruction in Scikit


code: r = subprocess.Popen(['dir', '/A'])

rawDescription: Python --- How to execute command prompt and get the output from it?


code: finalDict = dict(((k['id'], k['sigla']) for k in myDictList))

rawDescription: From List of Dictionary To Dictionary

description: From List of Dictionary To Dictionary


code:
def seno(x,n):
    result = 0
    sign = 1 # Sign starts out positive
    for i in range(1, n+1, 2):
        result += x**i/math.factorial(i)
        sign *= -1 # use negative sign on odd terms
    return result

rawDescription: Programming a math function in python

description: Programming a math function in python


rawDescription: How to perform a $and search with Python and MongoDB

description: Perform a $and search with Python and MongoDB


code:
for w in range(x):
    s="s"+str(w)
    self.s.deleteLater()

rawDescription: Dynamically deleting QLineEdit in PyQT4

description: Dynamically deleting QLineEdit in PyQT4


code: default_data['item3'] = 3

rawDescription: Python add new item to dictionary

description: Python add new item to dictionary


code: from google.appengine.api.mail import AdminEmailMessage

rawDescription: Who is treated as administrator of GAE application?


code:
from itertools import tee

def partition(lst, pred):
    l1, l2 = tee((pred(e), e) for e in lst)
    return (x for cond, x in l1 if cond), (x for cond, x in l2 if not cond)

rawDescription: filtered and non-filtered elements in a single pass

description: Filtered and non-filtered elements in a single pass


code:
d = dict((i['id'], i) for i in b)
[d[key] for key in filter]

rawDescription: Sorting a list of dicts in python, using another list as a "filter"?


code:
from io import StringIO
sample = '''\
Shop: someshop
Schedule: from 8:00 to 18:00
Day: 11:11:2011
Items Sold: 456
List of purchases:
(product, 123, 12:30)
(product, 123, 12:30)
(product, 123, 12:30)
'''
d = {}
with StringIO(sample) as f:
    for line in f:
        if line.startswith('List of purchases'):
            purchases = d['List of purchases'] = []
            for line in f:
                info = line.strip('()\n').split(', ')
                purchases.append(info)
            break
        key, val = line.split(': ')
        d[key] = val.rstrip('\n')

d
from pprint import pprint
pprint(d)

rawDescription: Python - Reading text file into dict

description: Python - Reading text file into dict


code: items.sort(key=lambda e: e.find(attrs={"class": "mgioAutonymEnglish"}).string)

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code:
from django import template
register = template.Library()

@register.simple_tag
def attributeLookup(the_object, attribute_name):
   # Try to fetch from the object, and if it's not found return None.
   return getattr(the_object, attribute_name, None)

rawDescription: How do I access dictionary keys that contain hyphens from within a Django template?

description: Access dictionary keys that contain hyphens from within a Django template


code: OneOrMore(leaf)

rawDescription: Convert BNF grammar to pyparsing

description: Convert BNF grammar to pyparsing


code:
def primecheck_all(x):
    return all(prime(n) for n in x)

rawDescription: Iterate Function through List

description: Iterate Function through List


code:
from urllib.request import urlopen,Request
url = 'http://httpbin.org/get'
url1 = urlopen(Request(url,  headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}))
print(url1.read().decode('utf8'))

rawDescription: Testing for user agent spoofing in python


code:
for i in np.ndindex(3,4):
    e[i]=arr[i]

rawDescription: Method for generating row-column arrays with other arrays


code:
#I presume your tweet is saved in the variable text
txt = []
if "'" in text:
    for item in text:
        if not item=="'":
            txt.append(item)
        else:
            txt.append("''")
    text = ''.join(txt)

rawDescription: Extracting hashtags using Tweepy to go into MySQLdb


rawDescription: Make every numeric value in a pandas DataFrame negative


rawDescription: Python: pass a function call's list index as its own argument


code: isinstance(Bat(), Mammal) == True

rawDescription: get the name of the class and wrap it in an if statement

description: Get the name of the class and wrap it in an if statement


code: from IPython.kernel import BlockingKernelClient

rawDescription: Sending data from a web app to an ipython notebook


code:
#!/usr/bin/python
import threading
from time import sleep

exitCondition = threading.Event()

def inputActivity():
    while True:
        exitConditionReached = exitCondition.wait(.1) #<-critical
        print(exitConditionReached)
        if exitConditionReached: #exitCondition reached -> shutdown
            return
        else: #exitCondition not reached -> do work
            sleep(.1)

inThread = threading.Thread(target = inputActivity)
inThread.start()

sleep(.2) #<-critical

exitCondition.set()
print("exitCondition set")

inThread.join()

description: Threading.Condition.wait(timeout) ignores threading.Condition.notify()


code:
def solve(self):
    v = set()

    q = [(0, self.matrix)]
    i = 0
    while True:
        dist, matrix = q[i]
        i += 1

        for mask in self.masks:
            t = matrix ^ mask

            if t not in v:
                if t == 0:
                    return dist + 1
                v.add(t)
                q.append((dist + 1, t))

rawDescription: Avoid a deepcopy when doing a BFS

description: Avoid a deepcopy when doing a BFS


rawDescription: delete items from a set while iterating over it

description: Delete items from a set while iterating over it


rawDescription: Difference between super() and calling directly


code: original[0], original[9] = original[9], original[0]

rawDescription: Switching positions of two strings within a list


code: [0 if i not in orig else orig[i] for i in range(100)]

rawDescription: Python Tuple & List Manipulation (As an input to the SVM model in scikit-learn)


code:
total_lines = total_words = total_characters = 0

def cfunc(folder, *arg):
    global total_lines, total_words, total_chars

    for x in arg:
        ...
        print(x, lines, words, chars)
        total_lines += lines
        total_words += words
        total_chars += chars

rawDescription: Python: counter in a function with multiple args


rawDescription: add column to csv when exporting numpy ndarray

description: Add column to csv when exporting numpy ndarray


code:
url = 'http://losangeles.craigslist.org/wst/sof/4869468306.html';
soup = BeautifulSoup(urllib2.urlopen(url).read());
reply = soup.findAll('a', attrs = {"id": "replylink"});
if reply:
   url = 'http://losangeles.craigslist.org' + reply[0].get('href');
   soup = BeautifulSoup(urllib2.urlopen(url).read());
   reply = soup.findAll(['div', 'a'], attrs = {"class": re.compile(r'anonemail|mailapp')});
   if reply:
      reply[0].getText()

rawDescription: Parsing HTML within Javascript button elements with BeautifulSoup


code:
for k, v in inventory.iteritems():
    v[1] += 1

rawDescription: modifying list element in Python dictionary

description: Modifying list element in Python dictionary


code:
def do_after(func):
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        call_my_extra_function()
    return wrapper

rawDescription: Is there a way in python to trigger an action upon exiting a function


code:
orders = {}
orders[code] = number

rawDescription: python multiplication {how to do it with a dic ?}

description: Python multiplication {how to do it with a dic ?}


rawDescription: Save app data in Weather App

description: Save app data in Weather App


code:
# same result as `method1()`
def method3():
    np.random.seed(123)
    x = np.zeros(size, dtype=float)
    for i  in range(size[0]):
        x[i,:] = np.random.normal(0, 1, size[1])
    return x

rawDescription: numpy random usage validity

description: Numpy random usage validity


code:
def get_image_name(instance, filename):
    fn = 'mealsOne/static/meal_photos/%s.jpg' % instance.id
    return fn

rawDescription: how to rename django image as id.jpg

description: Rename django image as id.jpg


code:
def get_lines(self,data):
    if data['form']['export_format'] == 'xls':
        for row in self.result_temp:
            for key in ('name', 'name1'):
                if key not in row:
                    continue
                row[key] = cgi.escape(row[key])
    return self.result_temp

rawDescription: xml excape form a python dictionary

description: Xml excape form a python dictionary


code:
df1
df2

rawDescription: Pandas adding two Multiindex Dataframes

description: Pandas adding two Multiindex Dataframes


code:
import collections
Point = collections.namedtuple('Point', 'x y')
x, y = Point(0, 1)
p = Point(x, y)
x, y, p
p.x, p.y, p[0], p[1]
for i in p:
  print(i)

rawDescription: Is it pythonic for a function to return multiple values?


code:
streetno={"1":"Sachin Tendulkar","2":"Sehawag","3":"Dravid","4":"Dhoni","5":"Kohli"}
streetno.update([(v, k) for k, v in streetno.items()])

rawDescription: Retrieving Key and Values from Dictionary


code:
sort_orders = {
   "-created_at": -MyModel.created_at,
   "some_other_order": SomeModel.some_property

}

def get_order(input):
    return sort_orders.get(input)

rawDescription: Appengine - Upgrading from DB to NDB - Order


code:
class IntPoly(object):
    def __init__(self, poly1, poly2):
        self.poly1 = poly1
        self.poly2 = poly2

    def multiply():
        """Here you would do your proper conversion and parsing
        given the representation of the polynomials.
        But pretending that they are just numbers, you would do the following:"""
        return self.poly1 * self.poly2

rawDescription: How do variables get passed in and out of methods in Python?


code:
df['C'] = df.apply(f, axis=1)
df

rawDescription: Creating a new column based on if-elif-else condition


code:
def d(fun, num):
    return fun(num)

def e(x):
    return x**2

d(lambda x: x**2, 7) # Returns 49
d(e) # Also returns 49

rawDescription: function as constructor parameter in python

description: Function as constructor parameter in python


code:
def knightofni(obj):
    obj.number = 1
    obj.who = "We've encountered Knight of Ni."

rawDescription: Change object's variable from different file


rawDescription: How to generate all possible combinations from all permutations?

description: Generate all possible combinations from all permutations


code:
import os
sis = os.path.join('nohup ~/mycodes/code > {}'.format(j), 'out{}.dat'.format(i))

rawDescription: python multiprocessing sleep between executions

description: Python multiprocessing sleep between executions


code:
def modify_inplace(X):
    np.exp(X, out=X)
    X += 8.
    np.power(X, -1, out=X)
    X *= 2

rawDescription: How to modify a numpy array inplace without hidden additional memory allocation?

description: Modify a numpy array inplace without hidden additional memory allocation


code:
aggregated = data.groupByKey().mapValues(lambda vs: (list(vs), len(vs)))
aggregated.collect()
## [('a', (['u', 'v'], 2)), ('b', (['w', 'x', 'x'], 3))]

rawDescription: Apache Spark CombineByKey with list of elements in Python


code:
from functools import partial

def key(num, x):
  return int(x[num])

def sort(a, num):
  return sorted(a, reverse=True, key=partial(key, num))

rawDescription: Understanding lambda functions in python


rawDescription: How should I check more than 10 columns for nan values and select those rows having nan values, ie keepna() instead of dropna()


code:
import fnmatch
import os
my_match = []

for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
        my_match.append(file)       # append insert the value at end of list
# do stuff with my_match list

rawDescription: how can I save the output of a search for files matching *.txt to a variable?

description: Save the output of a search for files matching *.txt to a variable


code:
alist = ['an', 'am', 'apple', 'cool', 'why']
for _ in range(20):
    print(normal_choice(alist))

rawDescription: Select one element from a list using python following the normal distribution


rawDescription: Using same function as instance and classmethod in python


code:
from datetime import datetime
year=int(input("What year?"))
month=int(input("What month?"))
day=int(input("What day?"))
hour=int(input("What hour?"))
minute=int(input("What minute?"))
second=int(input("What second?"))
then = datetime(year,month,day,hour,minute,second)
now = datetime.now()
diff = then - now
print(diff)

print(diff.total_seconds())

rawDescription: Can you do sums with a datetime in Python?

description: Do sums with a datetime in Python


code:
for i in range(3):
    if i == 5:
        print(i)
    else:
        print('Not 5')

rawDescription: Python Programming for Absolute Beginner Chapter 5 Challenge 4


code:
import modules
from modules import some_module
import modules.some_module

rawDescription: Navigating file locations

description: Navigating file locations


code:
list_1 = [1,2,3]
list_2 = [1,3,5]
list_3 = [2,4,6]
zip(list_1, list_2, list_3)  # To make 1st items pair, 2nd items pairs, ...
[sorted(xs)[1] for xs in zip(list_1, list_2, list_3)]

rawDescription: Python: Iterating through multiple lists to get median of each item of same index


code: names = [i.text.strip() for i in soup.find_all('td', {'class': 'views-field views-field-field-faculty-name-last-value active'})]

rawDescription: Trying to parse the names (and phD degrees) from a faculty university site. Having trouble getting only that


code: bool(" ".strip())

rawDescription: getting rid of some elements that contain just white space in a list

description: Getting rid of some elements that contain just white space in a list


code:
# from statistics import mean will work for python 3.4

for k,v in d.items():
       print("Scores total for {} is {}".format(k,sum(v)))
       print("Scores average for {} is {}".format(k,sum(v)/len(v))) # mean(v) for python 3,4
       print("Highest score  for {} is {}".format(k, max(v)))

rawDescription: How to sort integers in a variable?

description: Sort integers in a variable