rawDescription: fillplots module in Python

description: Fillplots module in Python


code:
def f1(a, s):
    if s in a["contents"]:
        a["phrase"] = s
    for b in a["descendent"]:
        f(b, s)

rawDescription: How to look through a phrase in a dictionary?

description: Look through a phrase in a dictionary


code: io.savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as='row')

rawDescription: Can someone explain mdict in python (scipy.io), for example in scipy.io.savemat()?


code:
def update(func):
    def wrapper(*args):
        cls = func(*args)
        cls.params.update({'d': 4, 'e': 5})
        return cls
    return wrapper

class myclass(object):
    @update
    def function(self):
        class localclass(object):
            params = {'a':1, 'b': 2}
        return localclass

rawDescription: How can I extend a local class in a function?

description: Extend a local class in a function


code: var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

rawDescription: Output formatting in Python: replacing several %s with the same variable


code:
def get_text_blocks(filename):
    import re
    seperator = re.compile('^-- -.*', re.M)
    with open(filename,'r') as f:
        return re.split(seperator, f.read())

rawDescription: How to check for EOF in Python?

description: Check for EOF in Python


code:
import urllib2
response = urllib2.urlopen('http://httpbin.org/status/404')
urllib2.urlopen('http://httpbin.org/status/404')

rawDescription: Do python functions care whether or not you use their output?


code:
[build_ext]
#define=
#include_dirs=/usr/local/include
#library_dirs=/usr/local/lib
libraries=sqlite3
# define=SQLITE_OMIT_LOAD_EXTENSION

rawDescription: Python: The pysqlite library does not support C extension loading


code:
arr1 = np.array([100, 200, 255],dtype=np.uint8)
arr2 = np.array([180, 210, 100],dtype=np.uint8)
_arr2 = arr2.astype(np.int16)
sub_arr = np.subtract(arr1, _arr2)

sub_arr[sub_arr < 0] = 0
sub_arr = sub_arr.astype(np.uint8)
print(sub_arr)

rawDescription: Python array subtraction loops back to high number instead of giving negative value


code:
from django.core.management import setup_environ
import mysite.settings
setup_environ(mysite.settings)

rawDescription: python django automated data addition

description: Python django automated data addition


code:
def fmt(msg, obj):
    return msg.format(**obj.__dict__)

rawDescription: Using instance variables as named format substitutions


code:
[
    'https://www.webaddress.com/url/urls.do?filename=swc.jpg&filetype=l',
    'https://www.webaddress.com/url/urls.do?filename=SWC.JPG&filetype=l'
]

rawDescription: How do you split in beautiful soup based on two parameters - python

description: Split in beautiful soup based on two parameters - python


code:
import re
import sys

def section(scanner, token):
    return "SECTION", scanner.match.group(1)

def some_line(scanner, token):
    return "SOME LINE", token

def garbage(scanner, token):
    sys.exit('Found garbage: {}'.format(token))

# scanner will attempt to match these patterns in the order listed.
# If there is a match, the second argument is called.
scanner = re.Scanner([
    (r"section (\d+)$$", section),
    (r"some line$", some_line),
    (r"\s+", None),  # skip whitespace
    (r".+", garbage), # if you get here it's garbage
    ], flags=re.MULTILINE)

tokens, remainder = scanner.scan('''\

section 1

some line
''')
for token in tokens:
    print(token)

rawDescription: How do I tokenize a file with Python as a sequence of regular expressions?

description: Tokenize a file with Python as a sequence of regular expressions


code: self.counter += 1

rawDescription: Are class variables in the scope of instance methods or class methods?


code: cur.execute("CREATE TABLE C(Id INTEGER PRIMARY KEY)");

rawDescription: Make sqlite3 column update faster

description: Make sqlite3 column update faster


code:
from datetime import date, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr, min(curr + delta, end)
        curr += delta

rawDescription: How to create Python Generator that iterates through date range giving me 3 day segments?

description: Create Python Generator that iterates through date range giving me 3 day segments


rawDescription: Stomp Broadcast with Rabbitmq and Python


code:
LANGUAGES = (
    ('nl-be', ugettext_lazy('Dutch (Belgium)')),
    ('nl-fr', ugettext_lazy('French (Belgium)')),
    ('nl-de', ugettext_lazy('German (Belgium)')),
)

rawDescription: django country from request

description: Django country from request


rawDescription: Get all "grand"-Children of a given Model


code:
calendar_daily_ts[:4]
calendar_daily_ts.resample(rule='B', closed='left').first()[:4]
calendar_daily_ts.resample(rule='B', closed='right').first()[:4]

rawDescription: Pandas, unexpected behavior of .resample('B')


code:
day1[0,50,50]
day1 = np.squeeze(day1)
day1.shape
day1[50,50]

rawDescription: How to merge multiple arrays in python?

description: Merge multiple arrays in python


code:
strMonth = []
counter = 0
strMonth[counter]

rawDescription: What's wrong with my def function? how to fix it?


code:
from multiprocessing import dummy as multithreading

class SomeClass(object):
    def doSomething(self):
        pass
    def doSomethingElse(self):
        pass

someClass = SomeClass()
pool = multithreading.Pool(1)
pool.apply(someClass.doSomething)
pool.apply(someClass.doSomethingElse)
pool.apply(someClass.doSomething)
pool.close()
pool.join()

rawDescription: How to call a function on a running Python thread

description: Call a function on a running Python thread


code:
item = QStandardItem('my_item_text')
item.setEditable(False)

rawDescription: PyQT -- How can you make a QTreeview uneditable but also selectable?


code: fixed_data = COMPILED_REGEX.sub(replace_callback, YOUR_DATA)

rawDescription: How to substitute specific patterns in python

description: Substitute specific patterns in python


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

class DummyPlot(object):
    def __init__(self):
        self.imsize = (10, 10)
        self.data = np.random.random(self.imsize)
        self.fig, self.ax = plt.subplots()

        dummy_data = np.zeros(self.imsize)
        self.im = self.ax.imshow(dummy_data)
        self.im.set_visible(False)

        buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075])
        self.button = Button(buttonax, 'Update')
        self.button.on_clicked(self.update)

    def update(self, event):
        self.im.set_visible(True)
        self.data += np.random.random(self.imsize) - 0.5
        self.im.set_data(self.data)
        self.im.set_clim([self.data.min(), self.data.max()])
        self.fig.canvas.draw()

    def show(self):
        plt.show()

p = DummyPlot()
p.show()

rawDescription: Preserve zoom settings in interactive navigation of matplotlib figure


code:
f = open('e:\\text.txt','rt',encoding='utf-8')
f.read()

rawDescription: How to print non-ascii characters to file in Python 2.7

description: Print non-ascii characters to file in Python 2.7


rawDescription: How can I efficiently load this kind of ASCII files with python?

description: Efficiently load this kind of ASCII files with python


code: query = query.filter(PrimateToMetricBlock.primate_id == primate_id)

rawDescription: SQLAlchemy: One-Way Relationship, Correlated Subquery


code: l = [x for y in range(7) for x in list(permutations('1397', y))]

rawDescription: Multi-variable List Comprehension

description: Multi-variable List Comprehension


code: Wizard['Create Shortcut on Desktop'].Wait('enabled').CheckByClick()

rawDescription: Python - Control window with pywinauto while the window is minimized or hidden


code: A

rawDescription: how to set on zero 3d numpy array?

description: Set on zero 3d numpy array


code:
def minus(a, b):
    return a - b

minus1 = lambda x: minus(x, 1)
minus1(3)

rawDescription: Python callback function placeholders?

description: Python callback function placeholders


rawDescription: How do i call a method by a string name using python?

description: Call a method by a string name using python


code:
def F():
    a,b = 0,1
    yield a
    yield b
    while True:
        a, b = b, a + b
        yield b

rawDescription: How to write the Fibonacci Sequence in Python

description: Write the Fibonacci Sequence in Python


code: my_dict = { k : [] for k in keys }

rawDescription: Add items to a dictionary of lists

description: Add items to a dictionary of lists


code:
p_area_id = f.lag("area_id").over(w) # Previous area

ind =  f.sum((
    p_area_id.isNull() | # No previous observation
    (p_area_id != f.col("area_id")) # Area changed
).cast("integer")).over(w)

rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


rawDescription: consensus score and WSP score in python

description: Consensus score and WSP score in python


code: l, = v

rawDescription: An unusual Python syntax element frequently used in Matplotlib


title: Mamer

title: Champhol

title: Station Palais

rawDescription: Using Python's csv.dictreader to search for specific key to then print its value


code: np.unique(df[['Col1', 'Col2']])

rawDescription: pandas unique values multiple columns

description: Pandas unique values multiple columns


code: res

rawDescription: PYTHON 2.7 - Modifying List of Lists and Re-Assembling Without Mutating


code:
series.name = 'Value'
df = series.reset_index()
print(df.head())

rawDescription: How can I use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place?

description: Use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place


code:
import psutil
excelPids = []
for proc in psutil.process_iter():
  if proc.name == "EXCEL.EXE": excelPids.append(proc.pid)

rawDescription: Get name of active Excel workbook from Python


code:
{"doc_type_name": "CONDEMNATION PROCEEDINGS ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERTIFICATE OF REDUCTION ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "COLLATERAL MORTGAGE ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERTIFIED COPY OF WILL ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CONFIRMATORY DEED ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERT NONATTCHMENT FED TAX LIEN ", "borough": "Borough", "block": "Block"}
...

rawDescription: Python data scraping with Scrapy

description: Python data scraping with Scrapy


rawDescription: Optimizing py2neo's cypher insertion

description: Optimizing py2neo's cypher insertion


code:
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi

angles = 2*pi*np.random.randint(0,864000,100)/86400
ax = plt.subplot(111, polar=True)
ax.scatter(angles, np.ones(100)*1)

# suppress the radial labels
plt.setp(ax.get_yticklabels(), visible=False)

# set the circumference labels
ax.set_xticks(np.linspace(0, 2*pi, 24, endpoint=False))
ax.set_xticklabels(range(24))

# make the labels go clockwise
ax.set_theta_direction(-1)

# place 0 at the top
ax.set_theta_offset(pi/2.0)

# plt.grid('off')

# put the points on the circumference
plt.ylim(0,1)

plt.show()

rawDescription: How to plot points on a clock

description: Plot points on a clock


code: lst[:] = ['lst%s' % item for item in lst]

rawDescription: Python, Appending string on each item on the list


code:
class B(object):
  def __getattribute__(self, method):
    try:
      return getattr(self, method)
    except:
      return getattr(self.get_connection(key), method)

rawDescription: Python class interface design

description: Python class interface design


code:
import pycountry

code = 'en-GB'

# ISO 639-1 codes are always 2-letter codes, so you have to take
# the first two characters of the code

# This is a safer way to extract the country code from something
# like en-GB (thanks ivan_pozdeev)
lang_code = code[:code.index('-')] if '-' in code else code

lang = pycountry.languages.get(iso639_1_code=lang_code)
print("ISO 639-1 code: " + lang.iso639_1_code)
print("ISO 639-2 code: " + lang.iso639_2T_code)
print("ISO 639-3 code: " + lang.iso639_3_code)

rawDescription: Convert ISO 639-1 to ISO 639-2

description: Convert ISO 639-1 to ISO 639-2


code:
strs="I am a string"
lis=['this', 'is', 'a', 'regex', 'test']
any(x in strs for x in lis)

rawDescription: Multi-condition regex in Python

description: Multi-condition regex in Python


rawDescription: get cluster labels in mllib kmeans pyspark

description: Get cluster labels in mllib kmeans pyspark


code:
ax = df1.plot()
df2.plot(ax=ax)

rawDescription: Plotting multiple dataframes using pandas functionality


code:
import multiprocessing
import Queue

def timed_function(return_queue):
    do_other_stuff()
    return_queue.put(True)
    return

def main():

    return_queue = multiprocessing.Manager().Queue()

    proc = multiprocessing.Process(target=timed_function, args=(return_queue,))
    proc.start()

    try:

        # wait for 60 seconds for the function to return a value
        return_queue.get(timeout=60)

    except Queue.Empty:
        # timeout expired
        proc.terminate() # kill the subprocess
        # other cleanup

rawDescription: Limit function execution in Python

description: Limit function execution in Python


code:
def run_expression(self):
    return eval(self.expression, vars(self))

rawDescription: python class with user defined expressions executed at runtime

description: Python class with user defined expressions executed at runtime


code:
# myapp/context_processors.py

def notifications(request):
    "Context processor for adding notifications to the context."
    return {
        'unseen_notifications': Notification.objects.filter(
            body__user=request.user).filter(viewed=False),
        'seen_notifications': Notification.objects.filter(
            body__user=request.user).filter(viewed=True),
    }

rawDescription: django display context data in template without calling view through url

description: Django display context data in template without calling view through url


code:
# first, remove track from playlist.tracks

client.put(playlist.uri, playlist={
    'tracks': newTracks # where newTracks is playlist.tracks from above with the specified track removed
})

rawDescription: Remove track from playlist with soundcloud Python


code:
class Cheese():
    def __init__(self, num_holes = None):
        if num_holes is None:
            ...

rawDescription: What is a clean, pythonic way to have multiple constructors in Python?


rawDescription: Django - Where to write code for easy-thumnails custom THUMBNAIL_NAMER?


code:
Xnp
Xsp
np.allclose(Xnp, Xsp)

rawDescription: What is the difference between cholesky in numpy and scipy?


code:
def __init__(self):
    self.created = datetime.now()

rawDescription: Python class with datetime.now() when instantiated


code:
lis = ['A', 'Quick', 'brown', 'fox', 'jump', 'over', 'the', 'lazy']
print(' '.join(lis))

rawDescription: How to print all strings in a list on one line?

description: Print all strings in a list on one line


code:
array([ ('Strings strings', 'Error', '")  Thread Name:  Extended Properties:"', 'SunDSrvc.exe', 'C:\\Program Files\\SunDSrvc.exe', '5DAA9377 ', 'Client'),
       ('Strings strings', 'Error', '")  Thread Name:  Extended Properties:"', 'SunDSrvc.exe', 'C:\\Program Files\\SunDSrvc.exe', '5DAA9377 ', 'Client'),
       ('Strings strings', 'Error', '")  Thread Name:  Extended Properties:"', 'SunDSrvc.exe', 'C:\\Program Files\\SunDSrvc.exe', '5DAA9377 ', 'Client')],
      dtype=[('name', 'S15'), ('severity', 'S5'), ('Message', 'S39'), ('AppDomainName', 'S12'), ('ProcessName', 'S29'), ('clientid', 'S9'), ('type', 'S6')])

rawDescription: genfromtxt returning NaN rows

description: Genfromtxt returning NaN rows


code:
server = []
for i in grouplist : servers+=getServers(i)

rawDescription: My first python program: can you tell me what I'm doing wrong?


code:
from difflib import Differ

delta = 0

for d in Differ().compare(text_1, text_2):
    status = d[0]

    if status == "+":
        delta += 1

    elif status == "-":
        delta -= 1

print(delta)

rawDescription: Delta words between two TXT files

description: Delta words between two TXT files


code:
# Tested with spyne.__version__=='2.10.9'
class warwarukDocument(JsonDocument):
    """An implementation of the json protocol
       with the method name stored in the URL,
       not the document."""

    def create_in_document(self, ctx, in_string_encoding=None):
        """ Sets ``ctx.in_document`` using ``ctx.in_string``."""
        assert ctx.transport.type.endswith('http'), \
               "This protocol requires an http transport, not %r (in %r)" \
                   % (ctx.transport.type, ctx.transport)

        super(warwarukDocument, self).create_in_document(ctx, in_string_encoding)
        # Not 100% sure where to find the URL path
        try:
            # Works for twisted
            uri = ctx.transport.req.uri
        except AttributeError:
            # Works for WSGI
            uri = ctx.transport.req['PATH_INFO']
        uri = re.sub(r'.*/', '', uri)
        ctx.in_document = { uri : ctx.in_document }

application = Application([HelloWorldService],
    tns='spyne.examples.hello',
    in_protocol=warwarukDocument(validator='soft'),
    out_protocol=JsonDocument()
)

rawDescription: JsonDocument as input protocol but method name taken from URL


code:
import time
def timing_function(some_function):
    """Outputs the time a function takes to execute."""
    def wrapper(*args, **kw):
        t1 = time.time()
        some_function(*args, **kw)
        time.sleep(1)
        t2 = time.time()
        return "Time it took to run the function " + some_function.__name__ + " is " + str((t2-t1)) + "\n"
    return wrapper

def tags(tag_name):
    def tags_decorator(my_func):
        """Adds tags to a string."""
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, my_func(name))
        return func_wrapper
    return tags_decorator

@timing_function
@tags("p")
def get_text(name):
    return "Hello "+name

get_text('World')

rawDescription: Using decorators with and without arguments simultaneously


code:
from subprocess import Popen, PIPE
p = Popen('svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname',
          stdout=PIPE)
stdout, stderr = p.communicate()

rawDescription: How do I poll the subversion history/log remotely from python?

description: Poll the subversion history/log remotely from python


code:
t = np.linspace(0, 2*np.pi, 100)
x = np.sin(t)
f = np.fft.rfft(x)
np.round(np.abs(f), 0)

rawDescription: How to Make Sense of Fourier Transform Results in Audio Frequency Analysis


code:
c = 1 + 2j
c.real
c.imag

rawDescription: Numbers ending with j

description: Numbers ending with j


code:
"""
we want to plot multiple data columns on one plot, so we use the layout
manager subplots().  if we wanted to break out individual plots for each
data source we could use subplots(n, m, o) where n,m,o are ints defining
the layout.
figure is the window our plot will reside in
ax is used for nearly everything else: plot itself, labels, ticks,
ticklabels, title(s)"""

fig, ax = plt.subplots()
# plot 'ABC' column, using red (r) line and label 'ABC' which is used in the legend
ax.plot(data['ABC'],'r-',label='ABC')
ax.plot(data['DEF'],'b-',label='DEF')
# set the number of ticks on x-axis to be a list [0, ... ,R]
# R is the number of rows in the data (i.e. len(dates))
# this ensures ticklabels align with the corresponding data point
ax.set_xticks(np.arange(len(dates)))
ax.set_xticklabels(dates)     # set the ticklabels to the list of datetimes
ax.legend(loc=4, fontsize=10) # make a legend and place in bottom-right (loc=4)
plt.xticks(rotation=30)       # rotate the xticklabels by 30 deg
plt.show()

rawDescription: Matplotlib - adjusting date spacing on the x-axis


code:
import datetime
s = datetime.date(2012,1,1)
e = datetime.date(2013,1,1)
u =  make_url('csco',s,e)

rawDescription: Get data for specific date range from yahoo finance api via python


rawDescription: stdout from python to stdin java

description: Stdout from python to stdin java


code:
def create_obj(klass, dictionary):
    obj = klass()

    # set regular fields
    for field, value in dictionary.iteritems():
        if not isinstance(value, list):
            setattr(obj, field, value)

    obj.save()

    # set M2M fields
    for field, value in dictionary.iteritems():
        if isinstance(value, list):
            setattr(obj, field, value)

    return obj

book = create_obj(Book, dictionary)

rawDescription: django how to create an object with the dictionary with m2m data

description: Django how to create an object with the dictionary with m2m data


code: re.findall(r'{([\w\d-]+)}', inputtext)

rawDescription: Python regex parsing string containing braced items


code:
csvList = [item for suffix in ('US-CIR', 'US-PIR', 'DS-PIR')
           for item in glob.glob(filepath + '\\*{}.csv'.format(suffix))[:1]]

rawDescription: custom ordering list using glob.glob in python

description: Custom ordering list using glob.glob in python


rawDescription: Re-shaping pandas data frame using shape or pivot_table (stack each row)


rawDescription: iterate through unicode strings and compare with unicode in python dictionary

description: Iterate through unicode strings and compare with unicode in python dictionary


code:
DF2['inDF2'] = 1
DF3 = pd.merge(DF1, DF2, how='left', left_on=['A', 'B'], right_on=['K', 'L'])

rawDescription: Find common rows of 2 dataframe for 2 columns


rawDescription: Parse Excel Report

description: Parse Excel Report


code:
find_neigbours('A', 1)
find_neigbours('A', 2)
find_neigbours('A', 3)

rawDescription: Most Efficient Method of Searching Neighbour Data for Nth Neighbour


code:
from itertools import groupby
from operator import itemgetter

key = itemgetter(0)  # sort by name
{name: sum(v[1] for v in group)
 for name, group in groupby(sorted(a_list, key=key), key)}

rawDescription: Adding and combining values with dictionary comprehensions?


code: fig, axes = pyplot.subplots(nrows=3, ncols=4, sharex=True, sharey=True)

rawDescription: make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels

description: Make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels


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

indices = np.random.randint(0, 512**2, size=(50**4))
E_initial = np.bincount(indices).reshape((512, 512))

fig = plt.figure()
ax = fig.add_subplot(111)
plt.imshow(E_initial)
cbar = plt.colorbar(orientation='vertical')
cbar.set_label('# of contacts', rotation=270, labelpad=10)
plt.show()

rawDescription: How do I use Python multiprocessing to get rid of nested while loops

description: Use Python multiprocessing to get rid of nested while loops


code: sorted(d, key=lambda x: x[::-1] + ',')

rawDescription: Advanced List sorting Python

description: Advanced List sorting Python


code:
def dictionary_tuples(key, values):
    return [(key, item) for item in values]

rawDescription: Python Build tuples from a dictionary with key and multiple values


code: return object1, object2, object3

rawDescription: How to call an object created in a module

description: Call an object created in a module


code:
import MySQLdb
conn = MySQLdb.connect(host, user, passwd, db)
cursor = conn.cursor()
cursor.executemany('INSERT INTO numbers (value, name) VALUES (%, %)',
                   [['1', 'one'], ['2', 'two'], ['3', 'three']])

cursor.commit()

rawDescription: python program for accessing values from csv files and storing it into a database using wamp

description: Python program for accessing values from csv files and storing it into a database using wamp


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)
        investmentChoice = ''
        while investmentChoice 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")
            investmentChoice = input("Please enter your investment option 1, 2, or 3:")
            if investmentChoice 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:
def get_comments(posts):
    postids = []
    for post in posts:
        postids.append(post.key().id())
    comments = {}
    for i in postids:
        comments[i] = Comment.all().ancestor(Blogpost.get_by_id(i))
    return comments

rawDescription: Fetch a GAE entity from Jinja with a Key


code:
a = {'Letters': ['Alpha', 'Beta', 'Theta'], 'Animals': ['Dog', 'Cat', 'Ox']}
zip(a["Letters"], a["Animals"])

rawDescription: How can I compare corresponding items in a python dictionary?

description: Compare corresponding items in a python dictionary


code:
def some_function(arg1,arg2="defaultValue"):
    myval = arg2

rawDescription: Most idiomatic way to provide default value in python?


rawDescription: How to check which arguments a function/method takes?

description: Check which arguments a function/method takes


rawDescription: numpy selecting every other n entries

description: Numpy selecting every other n entries


rawDescription: Python: Find dict in array based on value of key


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: How do I turn a tuple into a tuple of tuples?

description: Turn a tuple into a tuple of tuples


code:
with open('filename.txt', 'r') as file:  # replace filename.txt with your filename
    data = file.read().split()
    data = [int(x) for x in data]  # this will convert all of the numbers to integers

print(data)

rawDescription: Sorting file contents into a list in Python


rawDescription: Split a list of tuples into sub-lists of the same tuple field


rawDescription: Mocking function argument names to work with inspect.getargspec


code:
final_matrix = 1j * tmp2
final_matrix += tmp1

rawDescription: How to split a matrix in two in python in a memory effecient way?

description: Split a matrix in two in python in a memory effecient way


code:
for yoffset in range(yscale):
    for xoffset in range(xscale):
        newImage.setPixel(yscale*r + yoffset, xscale*c + xoffset, pixel)

rawDescription: Rescale an Image using Python3.2

description: Rescale an Image using Python3.2


code:
class SSEHandler(sse.Handler):

    #...

    @classmethod
    def abort(cls):
        for instance, future in cls._instances.items():
            future.set_result(None)
        cls._instances = {}

class Telnet(asyncio.Protocol):

    #...

    def connection_lost(self, esc):
        print("Connection lost!")
        SSEHandler.abort()
        telnet_server.close()

rawDescription: Python - Communicate between asyncio protocol/servers


rawDescription: Python regex for detecting additions

description: Python regex for detecting additions


code:
f = Foo(2)
g = Foo(1)
f + g

rawDescription: Dynamic Operator Overloading on dict classes in Python


rawDescription: Python regular expression to change date formatting


code:
class MyClass(object):
    __metaclass__ = MyMeta

rawDescription: How do I run code when a Python class is evaluated

description: Run code when a Python class is evaluated


code:
from random import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image

class MyBackground(Widget):
    def __init__(self, **kwargs):
        super(MyBackground, self).__init__(**kwargs)
        with self.canvas:
            self.bg = Rectangle(source='water.png', pos=self.pos, size=self.size)

        self.bind(pos=self.update_bg)
        self.bind(size=self.update_bg)

    def update_bg(self, *args):
        self.bg.pos = self.pos
        self.bg.size = self.size

class MyPaintWidget(Widget):
    def on_touch_down(self, touch):
        color = (random(), random(), random())
        with self.canvas:
            Color(*color)
            d = 30.
            touch.ud['line'] = Line(points=(touch.x, touch.y))

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):
    def build(self):
        parent = MyBackground()
        painter = MyPaintWidget()
        parent.add_widget(painter)
        return parent

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

rawDescription: How to fill canvas with an image in kivy?

description: Fill canvas with an image in kivy


code:
import Tkinter as Tk

class App(object):
    def __init__(self):
        self.root = Tk.Tk()
        self.root.wm_title("Fibonacci Calculator")
        #self.root.wm_iconbitmap("@icon2.xbm")
        self.label = Tk.Label(self.root, text="Set the digit number you want.")
        self.label.pack()
        self.digits = Tk.StringVar()
        Tk.Entry(self.root, textvariable=self.digits).pack()

        self.buttontext = Tk.StringVar()
        self.buttontext.set("Calculate")
        Tk.Button(self.root,
                  textvariable=self.buttontext,
                  command=self.clicked1).pack()

        self.label = Tk.Label(self.root, text=" ")
        self.label.pack()

        self.root.mainloop()

    def fibonacci(self, idx):
        # Your function here
        # Make sure this function accepts as its only argument the index
        return idx ** 2

    def clicked1(self):
        idx = int(self.digits.get())
        out = self.fibonacci(idx)
        self.label['text'] = out

    def button_click(self, e):
        pass

App()

rawDescription: Taking input from user and returning an answer in TKinter


code:
class SomeNonTrivialClass(object):
    # ...

    foo = autoproperty('_foo', can_get=True, can_set=True, allow_null=False, default_value=0)

rawDescription: Create a class level decorator to automatically add a property


rawDescription: How to set the content type header in response for a particular file type in Pyramid web framework

description: Set the content type header in response for a particular file type in Pyramid web framework


code:
np.all(np.identity(5) == np.identity(5)+np.ones([5,5]))
np.all(np.identity(5) == np.identity(5))

rawDescription: Comparing two dictionaries with numpy matrices as values


rawDescription: How to set User-Agent in Python MozEmbed?

description: Set User-Agent in Python MozEmbed


code:
from ctypes import *

file = CDLL('file.dll')

# do stuff here

handle = file._handle # obtain the DLL handle

windll.kernel32.FreeLibrary(handle)

rawDescription: Can I explicitly close a ctypes CDLL?

description: Explicitly close a ctypes CDLL


code: onestep = onestep.next

rawDescription: Tail-Loop Puzzle with a Linked list - My Python solution is Failing when tail is longer than loop


rawDescription: Extracting (interval) values from multiple dictionaries inside one large list, and combining these with corresponding lists inside another large list


rawDescription: Numpy/Python: Array iteration without for-loop


code:
format_string = "{};{};{}"
print(format_string.format(list[0], list[1], list[2]))

rawDescription: Writing Python lists into file, items seperated by semicolon


code:
from io import StringIO
import pandas

def defragment(x):
    values = x.dropna().values
    return pandas.Series(values, index=df.columns[:len(values)])

datastring = StringIO("""\
Name    h1    h2    h3    h4
A       1     nan   2     3
B       nan   nan   1     3
C       1     3     2     nan""")

df = pandas.read_table(datastring, sep='\s+').set_index('Name')
long_index = pandas.MultiIndex.from_product([df.index, df.columns])

print(
    df.stack()
      .groupby(level='Name')
      .apply(defragment)
      .reindex(long_index)
      .unstack()
)

rawDescription: Move non-empty cells to the left in pandas DataFrame


code:
import ast
from collections import namedtuple

Import = namedtuple("Import", ["module", "name", "alias"])

def get_imports(path):
    with open(path) as fh:
       root = ast.parse(fh.read(), path)

    for node in ast.iter_child_nodes(root):
        if isinstance(node, ast.Import):
            module = []
        elif isinstance(node, ast.ImportFrom):
            module = node.module.split('.')
        else:
            continue

        for n in node.names:
            yield Import(module, n.name.split('.'), n.asname)

rawDescription: Python easy way to read all import statements from py module


code:
import numpy as np
boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
boolarr
np.sum(boolarr)

rawDescription: Python Numpy: how to count the number of true elements in a bool array


code:
#!/usr/bin/env python
import os
import shutil
import tempfile
from multiprocessing import Pool

def init(topdir='.'):
    dir = tempfile.mkdtemp(dir=topdir) # parent is responsible for deleting it
    os.chdir(dir)

def child(n):
    return os.getcwd(), n*n

if __name__ == "__main__":
   pool = Pool(initializer=init)
   results = pool.map(child, [1,2,3])
   pool.close()
   pool.join()
   for dirname, _ in results:
       try:
           shutil.rmtree(dirname)
       except EnvironmentError:
           pass # ignore errors

rawDescription: Python subprocess.Popen : sys.stdout vs .txt file vs Cpickle.dump


code: [labels[x] for x in np.array(duplicates)]

rawDescription: Access 1D array with array of lists or arrays


code: name = friend.user.name

rawDescription: sqlalchemy foreign key relationship attributes

description: Sqlalchemy foreign key relationship attributes


code:
def function(numbers):
    ...
function([1, 2, 3])

rawDescription: How to take any number of inputs in python without defining any limit?

description: Take any number of inputs in python without defining any limit


code:
import re

codepoint = re.compile(r'(\\u[0-9a-fA-F]{4})')
def replace(match):
    return unichr(int(match.group(1)[2:], 16))

codepoint.sub(replace, text).encode('utf8')

rawDescription: Unescape unicode-escapes, but not carriage returns and line feeds, in Python


code:
import datetime

now = datetime.datetime.now()

today = now.date()

midnight = datetime.time(hour=0)
midday = datetime.time(hour=12)

last_midnight = datetime.datetime.combine(today, midnight)
if now.time() < midday:
    yesterday = today - datetime.timedelta(days=1)
    last_midday = datetime.datetime.combine(yesterday, midday)
else:
    last_midday = datetime.datetime.combine(today, midday)

rawDescription: get time in past from current time

description: Get time in past from current time


code:
class Person:
   def setName(self, name):
      self.name = name
      return self   ## this is what makes this work

   def setAge(self, age):
      self.age = age;
      return self;

   def setSSN(self, ssn):
      self.ssn = ssn
      return self

rawDescription: Calling chains methods with intermediate results


code:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(some_data)

rawDescription: How can I access data sent in a post request in Django?

description: Access data sent in a post request in Django


code: df = pd.read_csv("filename.csv", parse_dates = [["DATE", "TIME"]], index_col=0)

rawDescription: 5 minute data only python, pandas

description: 5 minute data only python, pandas


code:
data = [1,2,3]
output = ((lambda x: x + x)
          (data[2]))

rawDescription: binding local variables in python

description: Binding local variables in python


code:
a = np.array([(3, 2), (6, 2), (3, 6), (3, 4), (5, 3)])
dt = [('col1', a.dtype),('col2', a.dtype)]
assert a.flags['C_CONTIGUOUS']
b = a.ravel().view(dt)
b.sort(order=['col1','col2'])

rawDescription: Sorting a 2D numpy array by multiple axes


rawDescription: Numpy: Affect diagonal elements of matrix prior to 1.10


code:
from datetime import *
today = date.today()
print(today.strftime('%Y-%m-%d'))

rawDescription: Python- Parser the today's date out of Dateutil


code: frame = inspect.currentframe().f_back

rawDescription: pass all current variables to function in python

description: Pass all current variables to function in python


code:
"""
Adds a tweet to the twitter account in settings.

Login to dev.twitter.com and add a desktop application
Add the keys and secrets for the added application to the settings file

Requires tweepy to be installed
https://github.com/joshthecoder/tweepy

"""
from django.conf import settings
from tweepy import *

class TwitterManager:
    def __get_api_handle(self):
        #Create OAuth object
        auth = OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)

        #Set access tokens
        auth.set_access_token(settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)

        #Create API handle
        api = API(auth)

        return api

    def update_twitter_status(self, message):

        api = self.__get_api_handle()

        #Send update
        api.update_status(message)

rawDescription: Django Tweepy File

description: Django Tweepy File


code:
with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", 'w') as outfile2:
    lineList = sorted(infile.readlines())
    for lines in lineList:
        lines = lines.replace('\n', '').split(',')
        studentScores = lines[1:-1]
        studentsList = [int(i) for i in studentScores]
        result = "%s: %s,max score = %d" % (lines[0].capitalize(),
                                            str(studentsList),
                                            max(studentsList))
        print(result)
        print(result, file = outfile)
        outfile2.write(result + "\n")

rawDescription: Writing Lines to a Different File

description: Writing Lines to a Different File


rawDescription: How to rearrange a date in python

description: Rearrange a date in python


code:
with open(master_file_path) as master_file:
    with open(search_results_path, 'w') as search_results:
        for line in master_file:
            if set(line.split()[:-1]) & keywords:
                search_results.write(line)

rawDescription: Use a file to search lines in another file in Python


code:
seen = set()
{k: v for k, v in yourdict.iteritems()
    if v['name'] not in seen and (seen.add(v['name']) or True)}

rawDescription: How to remove dictionaries with duplicate values from a nested dictionary

description: Remove dictionaries with duplicate values from a nested dictionary


code:
dx = bin_edges[1]-bin_edges[0]
cdf = np.cumsum(counts*dx)

rawDescription: How to get cumulative distribution function correctly for my data in python?

description: Get cumulative distribution function correctly for my data in python


code: timeit.timeit('l = filter(None, l)', 'l = range(0,10000000)', number=1)

rawDescription: Control the value returned by a spawned process


code:
import collections

# build an adjacency list representation of your input
graph = collections.defaultdict(set)
for l in ListA:
    for first, second in l:
        graph[first].add(second)
        graph[second].add(first)

# breadth-first search the graph to produce the output
output = []
marked = set() # a set of all nodes whose connected component is known
for node in graph:
    if node not in marked:
        # this node is not in any previously seen connected component
        # run a breadth-first search to determine its connected component
        frontier = set([node])
        connected_component = []
        while frontier:
            marked |= frontier
            connected_component.extend(frontier)

            # find all unmarked nodes directly connected to frontier nodes
            # they will form the new frontier
            new_frontier = set()
            for node in frontier:
                new_frontier |= graph[node] - marked
            frontier = new_frontier
        output.append(tuple(connected_component))

rawDescription: Find duplicate items within a list of list of tuples Python


code: mynewstr = unicode(mystr)

rawDescription: How to pass a variable to unicode/raw (ur"") conversion function

description: Pass a variable to unicode/raw (ur"") conversion function


code:
from unittest import TestCase, main

class TestOdd:
    def runTest(self):
        """Assert that the item is odd"""
        self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")

class TestOdd1(TestOdd, TestCase):
    NUMBER=1
class TestOdd2(TestOdd, TestCase):
    NUMBER=2

if __name__ == '__main__':
    main()

rawDescription: Instantiate Python unittest.TestCase with arguments


code:
import struct
struct.unpack('>f', '\x3f\x9a\xec\xb5')[0]

rawDescription: python 32 bit float conversion

description: Python 32 bit float conversion


code:
class A:
    def __init__(self, f):
        print(repr(self), "received", object.__repr__(f))
        self.f = f

class B:
    def __init__(self, f):
        print(repr(self), "received", object.__repr__(f))
        self.a = A(f)

with open(LARGE_FILE, 'rb') as f:
    text = f.read()

print("passing", object.__repr__(f), "into B()")
x = B(text)

rawDescription: python memory question

description: Python memory question


rawDescription: List type conversion python

description: List type conversion python


code: {'Words': ['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye']}

rawDescription: how to repeatedly append a string?

description: Repeatedly append a string


code: whos

rawDescription: multiply numpy ndarray with 1d array along a given axis

description: Multiply numpy ndarray with 1d array along a given axis


code: whatever.__name__ = "add"

rawDescription: Python: Dynamically adding function to a class, whose name is contained in a string


rawDescription: String Mirror Function

description: String Mirror Function


code:
import numpy as np
res=np.array(vals).reshape((9,9))

rawDescription: How to read a text file into a 9x9 matrix?

description: Read a text file into a 9x9 matrix


code:
import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi

shell = IPShell(argv=[''])

def set_trace():
    ip = ipapi.get()
    def_colors = ip.options.colors
    Pdb(def_colors).set_trace(sys._getframe().f_back)

rawDescription: Is it possible to go into ipython from code?


code: reduce(operator.add, s, ())

rawDescription: Python list comprehensions: Is it possible to specify the inclusion of two elements at a time?


code:
from itertools import product

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    rows = list(csv_input)  # Load all rows in
    block_count = len([x for x in rows[0] if x.find('Movement') != -1])
    row_count = len(rows)
    col_count = len(rows[0]) / block_count

    for block, row in product(range(block_count), range(row_count)):
        csv_output.writerow(rows[row][block * col_count : block * col_count + col_count])

rawDescription: How can I sort my CSV data from going into from rows into columns based on the header titles

description: Sort my CSV data from going into from rows into columns based on the header titles


code:
with open("a.txt") as a:
    with open("b.txt") as b:
        with open("c.txt", "w") as c:
            b_lines = set(b)
            c.write("".join(line for line in a if not line in b_lines))

rawDescription: What's the fastest way to find unique lines from huge file A as compared to huge file B using python?


code: tuple('SUP E P I C'.replace(" ",""))

rawDescription: Convert a string list to a tuple in Python


code:
def parseData(input):
    data = input.split('_')
    d = {}
    d['sku'] = data[0]
    d['country'] = data[1].capitalize()
    d['material'] = data[2].capitalize()
    d['size'] = data[3]
    d['retail_price'] = data[4]
    d['sale_price'] = data[5]
    return d

myData = parseData(input)
print(myData['sku'])
print(myData['country'])

rawDescription: Referencing a variable after seperating it from a list


code:
def parse(self, response):
        jsonresponse = json.loads(response.body_as_unicode())

#for each television show extract the url to get the seasons
        for sel in jsonresponse["tv"]:

            request = Request(sel['url'], callback = self.parse_season_details)
            request.meta['tv_name'] = sel['title']
            request.meta['tv_url'] = sel['url']
            yield request

rawDescription: scrapy crawling multiple pages [3 levels] but scraped data not linking properly

description: Scrapy crawling multiple pages [3 levels] but scraped data not linking properly


code: (np.arange(10) == 4).astype(int)

rawDescription: How to create in one line a null vector of size 10 but the fifth value being 1 using numpy

description: Create in one line a null vector of size 10 but the fifth value being 1 using numpy


code:
from app.views import my_view

urlpatterns = patterns('',
    url(r'^$', my_view()),
)

rawDescription: Could as_view() (for class-based views) be implemented in a decorator?


rawDescription: In-place type conversion of a NumPy array


code:
s = 'foo foo bar bar'
re.sub(r'\b(.+)\s+\1\b', r'\1', s)
s = 'foo bar foo bar foo bar'
re.sub(r'\b(.+)\s+\1\b', r'\1', s)

rawDescription: Is there a way to remove duplicate and continuous words/phrases in a string?


rawDescription: Updating a 2D database (CSV) with other databases in Python?


code:
import numpy as np
def random_pick(choices, probs):
    '''
    >>> a = ['Hit', 'Out']
    >>> b = [.3, .7]
    >>> random_pick(a,b)
    '''
    cutoffs = np.cumsum(probs)
    idx = cutoffs.searchsorted(np.random.uniform(0, cutoffs[-1]))
    return choices[idx]

rawDescription: draw random element in numpy

description: Draw random element in numpy


code:
def sum_previous(text):
    _iterator = iter(text.split())
    previous_word = next(_iterator)
    # set first k/v pairing with the first word
    # if  "total_lengths" is 0 at the end we know there
    # was only one match at the very start
    avg_dict = {previous_word: {"count": 1.0, "total_lengths": 0.0}}
    for current_word in _iterator:
        # if key does not exist, it creates a new key/value pairing
        avg_dict.setdefault(current_word, {"count": 0.0, "total_lengths": 0.0})
        # update value adding word length and increasing the count
        avg_dict[current_word]["total_lengths"] += len(previous_word)
        avg_dict[current_word]["count"] += 1
        previous_word = current_word
    # return the dict so we can use it outside the function.
    return avg_dict

def match_previous_generator(*args):
    # create our dict mapping words to sum of all lengths of their preceding words.
    d = sum_previous(text)
    # for every word we pass to the function.
    for word in args:
        # use dict.get with a default of an empty dict.
        #  to catch when a word is not in out text.
        count = d.get(word, {}).get("count")
        # yield each word and it's avg or False for non existing words.
        yield (word, d[word]["total_lengths"] / count if count else False)

rawDescription: Preceding Word Length

description: Preceding Word Length


code: print("The value is %d" % d["key%d" % x])

rawDescription: Printing a formatted dictionary key

description: Printing a formatted dictionary key


code: returncode = Popen(*args, **kwargs).wait()

rawDescription: What's the difference between subprocess Popen and call (how can I use them)?


code: self.SetMinSize((self.WIDTH, -1))

rawDescription: wxPython align widgets and fitting

description: WxPython align widgets and fitting


code: d[Idx] += Val

rawDescription: add items to dictionary of list

description: Add items to dictionary of list


code:
import sys
for i in xrange(10,0,-1):
    time.sleep(1)
    sys.stdout.write(str(i)+' ')
    sys.stdout.flush()

rawDescription: Display a countdown for the python sleep function


code:
from itertools import groupby
this_array = np.array([9999, 4, 1, 9999, 9999, 9999, -5, -4, 9999])
for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
    if k:
        indices = list(g)
        prev_i, next_i = indices[0]-1, indices[-1]+1
        before = this_array[prev_i] if prev_i != -1 else this_array[next_i]
        after = this_array[next_i] if next_i != len(this_array) else before
        this_array[indices[0]:next_i].fill((before + after) / 2)
this_array

rawDescription: Python: Replacing values in an array

description: Python: Replacing values in an array


code:
def function(*args, bob, sally):
    print(args, bob, sally)

values = [1, 2, 3, 4]

function(bob="Hi bob", sally="Hello sally", *values)
function(*values, bob="Hi bob", sally="Hello sally")
function(bob="Hi bob", *values, sally="Hello sally")

rawDescription: In python, can you pass variadic arguments after named parameters?


code:
lookup = {'name1': 'xxx-xxx-xxxx',
          'name2': 'yyy-yyy-yyyy'}

with open('data.csv') as data_file, open('out.csv', 'w') as out_file:
    for row in data_file:
        if any(num in row for num in lookup.values()):
            out_file.write(row)

rawDescription: How do I get python to search a csv file for items in a dictionary then print out the entire excel row...Thanks

description: Get python to search a csv file for items in a dictionary then print out the entire excel row...Thanks


rawDescription: Finding if a string exists in a nested tuple in Python


code:
import sys
import urllib2

from PyQt4 import QtCore, QtGui

class DownloadThread(QtCore.QThread):
    def __init__(self, url, list_widget):
        QtCore.QThread.__init__(self)
        self.url = url
        self.list_widget = list_widget

    def run(self):
        info = urllib2.urlopen(self.url).info()
        self.list_widget.addItem('%s\n%s' % (self.url, info))

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.list_widget = QtGui.QListWidget()
        self.button = QtGui.QPushButton("Start")
        self.button.clicked.connect(self.start_download)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.list_widget)
        self.setLayout(layout)

    def start_download(self):
        urls = ['http://google.com', 'http://twitter.com', 'http://yandex.ru',
                'http://stackoverflow.com/', 'http://www.youtube.com/']
        self.threads = []
        for url in urls:
            downloader = DownloadThread(url, self.list_widget)
            self.threads.append(downloader)
            downloader.start()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: Updating GUI elements in MultiThreaded PyQT


code:
class UserForm(forms.ModelForm):
    # ... as before
    def __init__(self, user, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        if user.language == 'en':
            self.fields['field_name'].widget = forms.HiddenInput()
    # ... as before

rawDescription: Pass parameters to Django class meta

description: Pass parameters to Django class meta


code: stats = [{'Population' : population1.text} for i in range(18)]

rawDescription: Creating numbered dictionaries with a For loop [python]


code:
def process_with_manual_measuring(self):
    self._start = time.time()
    next = self._start + 1
    self._k = 0
    while self._k < 100000000:
        self._k = self._k+1
        if time.time() > next:
            print (round((self._k / 1000000), 5))
            next = time.time() + 1

    print("duration:")
    print (time.time() - self._start)

rawDescription: Python, calculating the status of computation slows down the computation itself


rawDescription: Count of specific case per row in matrix


code:
class GeneratorSort():
    def __init__(self, *args):
        self.values = [(arg.next(), i) for i, arg in enumerate(args)]
        self.generators = args
    def generate(self):
        while any(self.values):
            r, index = min(v for v in self.values if v)
            try:
                self.values[index] = (self.generators[index].next(), index)
            except StopIteration:
                self.values[index] = None
            yield r

l1 = [2, 5, 6, 8]
l2 = [1, 4, 5, 7]
l3 = [0, 3, 9, 10]
a = GeneratorSort(iter(l1), iter(l2), iter(l3))
list(a.generate())

rawDescription: Sort generated numbers using another python generator


code: attrDict = {'init': functools.partial(Parent.__init__, first='A')}

rawDescription: How to pass parameters to parent class with type() in python?

description: Pass parameters to parent class with type() in python


code:
class SubClass(EntityResource):
    A=1
    B=2

rawDescription: Is there a way to create subclasses on-the-fly?


code: StartTime = re.findall(r"StartTime (\d\.\d{2})", text)

rawDescription: Python regular expression: get result without the search string used


code:
with io.StringIO() as query_str:
    query_str.write('INSERT INTO ')
    query_str.write(table_name)
    query_str.write(' VALUES ')
    for row in data_frame.iterrows():
        raw_row = row[1].values
        query_str.write(str(tuple(raw_row)))
    # Use query_str.getvalue(), as it will be deleted
    # when the 'with' scope is finished.

rawDescription: How to get mutable string?

description: Get mutable string


code: l4 = map(sum, l3)

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
l3 = []
for li in l1:
    if li in l2:
        l3.append(li)
    else:
        l3.append(None)

rawDescription: Sorting a list and adding None values in the right positions


code: ('{}.{}.{}.{}'.format(*x) for x in itertools.product(primes, repeat=4))

rawDescription: Python script to collect all hostnames of ip addresses with only prime entities


code:
print(h)
# y + 4*x

rawDescription: Mathematical function, unassigned variables?


rawDescription: Efficiently page query results

description: Efficiently page query results


rawDescription: matplotlib close does not close the window

description: Matplotlib close does not close the window


code:
def foo(listOfInputs):
    return all(map(str.isnumeric,listOfInputs))

rawDescription: Is there a function in python that returns true if all members of an iterable are true?


code:
class BuildingViewset(viewsets.ModelViewSet):
    def get_serializer_class(self):
        if self.action == 'list':
            return serializers.BuildingSerializer
        if self.action == 'retrieve':
            return serializers.BuildingDetailSerializer

rawDescription: only show a certain serializer field in a sub-level (newbie)

description: Only show a certain serializer field in a sub-level (newbie)


rawDescription: Select only one index of multiindex frame


code:
class Foo(object):
    @class_or_instance_method
    def details(cls_or_self, id=None):
        if isinstance(cls_or_self, type):
            return 'Class method with id {}'.format(id)
        else:
            return 'Instance method with id {}'.format(cls_or_self.id)

Foo.details(42)
f = Foo()
f.id = 42
f.details()

rawDescription: Python method available for both instantiated/uninstantiated class


code:
class X:
    @classmethod
    def id(cls):
        return cls.__name__

X.id()
X().id()

rawDescription: Same name for classmethod and instancemethod?


code: sum_l1 = map(lambda x: x/num_rows, sum_l)

rawDescription: Add only the first value in my list of arrays


code:
foo = PaddedStaticText(...)
foo.text.SetFont(...)

rawDescription: Implementing a proxy object

description: Implementing a proxy object


code: [i.start() for i in re.finditer('ga', seq)]

rawDescription: Finding a string pattern and printing the following characters for multiple occurrences in Python 3


code:
def neighbors2(pattern, d):
    return sum([neighbors(pattern, d2) for d2 in range(d + 1)], [])

rawDescription: Implement Neighbors to find the d-neighborhood of a string in Python


code:
# app/templatetags/getattribute.py

import re
from django import template
from django.conf import settings

numeric_test = re.compile("^\d+$")
register = template.Library()

def getattribute(value, arg):
	"""Gets an attribute of an object dynamically from a string name"""

	if hasattr(value, str(arg)):
		return getattr(value, arg)
	elif hasattr(value, 'has_key') and value.has_key(arg):
		return value[arg]
	elif numeric_test.match(str(arg)) and len(value) > int(arg):
		return value[int(arg)]
	else:
		return settings.TEMPLATE_STRING_IF_INVALID

register.filter('getattribute', getattribute)

rawDescription: Performing a getattr() style lookup in a django template


code:
import os.path, time
INDEX_DATE = time.ctime(os.path.getmtime(path/to/the/index.html))

rawDescription: Print the last modification of a jinja2 template in pelican


rawDescription: Extracting data with Headless Selenium browser with Python


rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results


code:
post_indices = dict((tuple(v),k) for k,v in post.iteritems())
pre_indices = dict((tuple(v),k) for k,v in pre.iteritems())

rawDescription: fast data comparison in python

description: Fast data comparison in python


code:
num = 332000000
colorarray = np.empty((2 * num, 4), dtype=float)
colorarray[::2, :3] = np.random.random_sample((num, 3))
colorarray[::2, -1] = 0.6
colorarray[1::2] = colorarray[::2]

rawDescription: Python - Fastest way to generate list of random colours with fixed alpha


code:
import re
re.findall('\d+|\D+', s)
re.split('(\d+)', s)  # note that you may have to filter out the empty
re.split('(\D+)', s)

rawDescription: Splitting letters from numbers within a string


rawDescription: Reading python ttk Styles from configuration file


code:
color = [(0,0,0),(255,255,255)]
for colorcode, pixelloc in zip(outputAfterLearning, blocked(10, 10, 5, 5)):
   if 0 <= colorcode < len(color):
   # ^ omit this if outputAfterLearning[i] is always valid
     image.putpixel(pixelloc, color[colorcode])

rawDescription: How to write this in a simpler way

description: Write this in a simpler way


code:
import re
url = "http://example.com/boards/recentnews.aspx?page=9"
re.search('page=(\d+)', url).group(1)
url = "http://example.com/boards/recentnews.aspx?page=10"
re.search('page=(\d+)', url).group(1)

rawDescription: Scrapy SgmlLinkExtractor Stop after 10 Pages


code:
class SplitpointUnsignedTest(unittest.TestCase):
    def testBestApproximation(self):
        self.assertEquals(1, splitpoint(numpy.array([5, 5, 4, 5], dtype=numpy.uint32)))

rawDescription: Find the equilibrium point in a numpy array


code:
from profilestats import profile

@profile
def my_function(args, etc):
    pass

rawDescription: What is the reliable method to find most time consuming part of the code?


code:
import pytz
import datetime as DT
utcnow = DT.datetime.utcnow()

canonical = dict()
for name in pytz.all_timezones:
    tzone = pytz.timezone(name)
    try:
        dstoffset = tzone.dst(utcnow, is_dst=False)
    except TypeError:
        # pytz.utc.dst does not have a is_dst keyword argument
        dstoffset = tzone.dst(utcnow)
    if dstoffset == DT.timedelta(0):
        # utcnow happens to be in a non-DST period
        canonical[name] = tzone.localize(utcnow, is_dst=False).strftime('%z')
    else:
        # step through the transition times until we find a non-DST datetime
        for transition in tzone._utc_transition_times[::-1]:
            dstoffset = tzone.dst(transition, is_dst=False)
            if dstoffset == DT.timedelta(0):
                canonical[name] = (tzone.localize(transition, is_dst=False)
                                   .strftime('%z'))
                break

for name, utcoffset in canonical.iteritems():
    print('{} --> {}'.format(name, utcoffset))

# All timezones have been accounted for
assert len(canonical) == len(pytz.all_timezones)

rawDescription: "Canonical" offset from UTC using pytz?

description: "Canonical" offset from UTC using pytz


code:
import Tkinter
c = Tkinter.Canvas()
lineId = c.create_line(1,1,2,2)

rawDescription: Python 2.7 - Draw on Tkinter Canvas from Different Functions


code:
sql = "SELECT STR_TO_DATE(CONCAT(y,':',w,':1'), '%x:%v:%w') as date, d FROM test.t"
df = pd.read_sql(sql, engine)

rawDescription: pandas.read_sql and interpreting dates specified as weeks

description: Pandas.read_sql and interpreting dates specified as weeks


code: inst1.i = 4

rawDescription: Python : How to create a dynamic list of class values


code:
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calculator")
calculator.geometry("317x145")

menubar = Menu(calculator)

class Calculator(Frame):
    def __init__(self):
        Frame.__init__(self)
        display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
        buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
        display.grid(column=0, row=0, padx=0, pady=0)
        buttons.grid(column=0, row=1, padx=1)
        numbers = StringVar()
        self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
        self.results.pack()
        self.results.grid(column=0, row=0)

        def showup(x):
            return lambda: self.results.insert(END, x)

        numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
        for i in range(9):
            n=numbers[i]
            Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)

        Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
        Clear.grid(padx=2, pady=2, column=3, row=0)
        Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
        Equals.grid(padx=2, pady=2, column=4, row=3)
        All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
        All_clear.grid(padx=2, pady=2, column=4, row=0)
        Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
        Bracket_one.grid(padx=2, pady=2, column=2, row=3)
        Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
        Bracket_two.grid(padx=2, pady=2, column=3, row=3)
        Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
        Zero.grid(padx=2, pady=2, column=0, row=3)
        Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
        Decimal_point.grid(padx=2, pady=2, column=1, row=3)
        Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
        Multiplication.grid(padx=2, pady=2, column=3, row=1)
        Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
        Division.grid(padx=2, pady=2, column=4, row=1)
        Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
        Addition.grid(padx=2, pady=2, column=3, row=2)
        Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
        Subtraction.grid(padx=2, pady=2, column=4, row=2)
        self.menubar = Menu(self)
        def about():
            messagebox.showinfo(title = "About", message = "Author")
            return
        self.helpMenu = Menu(self.menubar)
        self.menubar.add_cascade(label="Help",menu=self.helpMenu)
        self.helpMenu.add_command(label = "About", command=about)
        calculator.config(menu=self.menubar)

    def equals(self):
        try:
            result = eval(self.results.get())
        except:
            result = "Invalid input"
        self.all_clear()
        self.results.insert(0, result)
    def zero(self):
        self.results.insert(END, "0")
    def bracket_one(self):
        self.results.insert(END, "(")
    def bracket_two(self):
        self.results.insert(END, ")")
    def all_clear(self):
        self.results.delete(0, END)
    def clear(self):
        self.results.delete(-1)
    def multiplication(self):
        self.results.insert(END, "*")
    def division(self):
        self.results.insert(END, "/")
    def addition(self):
        self.results.insert(END, "+")
    def subtraction(self):
        self.results.insert(END, "-")
    def decimal_point(self):
        self.results.insert(END, ".")

if __name__ == '__main__':
    Calculator().mainloop()
    calculator.config(menu=menubar)
    calculator.mainloop()

rawDescription: Messagebox not working

description: Messagebox not working


code: db = build_db("path/to/your/file.txt")

rawDescription: Python Not finding phrase on any line other than first (new)


code:
def merge_dicts(*dict_args):
    return dict(chain.from_iterable(d.iteritems() for d in dict_args[::-1]))
# If you provide 0 or 1 dict,
# this will return an empty dict or the single dict (a copy thereof) itself

rawDescription: Pythonic way to get the union of dictionaries


rawDescription: How to delete all occurances of an item from a dictionary of dictionary?

description: Delete all occurances of an item from a dictionary of dictionary


rawDescription: Efficient way to convert a list to dictionary


rawDescription: Floating point conversion

description: Floating point conversion


code:
def shift(s, n):
    return s[n:] + s[:n]

rawDescription: Get the indices of capital letters in a string


code:
mass = 1.2
density = 2.3
masslog = math.log(mass * density)
map(sum, (masslog/(i+1) for i in range(10000)))

rawDescription: Python3, map-function

description: Python3, map-function


code:
ndf = df.groupby(level=0).count()
ndf[ndf == 1] = 'Y'
ndf[ndf == 0] = np.nan
ndf

rawDescription: Pandas dataframe merge

description: Pandas dataframe merge


code:
action = {
    'newChannel': lambda ok: newChannel(cName(ok)),
    'newNetwork': lambda ok: newNetwork(hName(ok)),
    'loginError': lambda ok: loginError(nName(ok))
     }

ok = parse_qsl(urlparse(u).query, keep_blank_values=True)

handler = action.get(eventType(ok))
handler(ok)

rawDescription: Dispatch dictionary but pass different parameters to functions


code:
states_dictionary={
     CT:["alex","harry"],
     AK:["liza","alex"],
     TX:["fred", "harry"]
};

rawDescription: are there dictionaries in javascript like python?

description: Are there dictionaries in javascript like python


rawDescription: Verifying that a string does not contain curly brackets other than those used for formatting


code:
import pandas as pd
import re

A = pd.read_csv('FileA', delimiter = r'\s+')
A = A.set_index(['ProbeID'])

BFiles = ['FileB1', 'FileB2', 'FileB3']
for i, bfile in enumerate(BFiles):
    B = pd.read_csv('FileB', delimiter = r'\s+')
    B = B.set_index(['ProbeID'])
    C = pd.concat([A,B], axis = 1)

    idx = C['call'] == 0
    C['alleleB'][idx]  = C['alleleA'][idx]
    idx = C['call'] == 2
    C['alleleA'][idx]  = C['alleleB'][idx]
    cfile = 'FileC{i}'.format(i = i)
    with open(cfile, 'w') as f:
        f.write(C[['call', 'alleleA', 'alleleB']])

rawDescription: compare text in two files and append text in a field

description: Compare text in two files and append text in a field


rawDescription: How to convert the following string to python date?

description: Convert the following string to python date


rawDescription: Distributing points for lottery.py

description: Distributing points for lottery.py


code:
def findpaths(fname):
  with open(fname, 'rb') as f:
    m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    for match in re.finditer(':path,([0-9]+)', m):
      yield m[match.end():match.end()+int(match.group(1))]

rawDescription: seek to regex in a large file using python

description: Seek to regex in a large file using python


code:
important_list = []
for i in otp:
    important_list.append(base_dict[i])

rawDescription: Trying to place values of dictionary into a list, but it prints values individually


code:
id(p._actions[1])
id(p1._actions[1])

rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code: albums = Album.query().fetch(100)

rawDescription: How to create a JSON file from a NDB database using Python

description: Create a JSON file from a NDB database using Python


code:
acids = frozenset(('A', 'T', 'G', 'C'))
final1 = [i for i in words if i in acids]

rawDescription: How do I loop through a list?

description: Loop through a list


code:
@app.route('/route_name')
def script_output():
    output = execute('./script')
    return render_template('template_name.html',output=output)

rawDescription: Write the output of a script in a html page using flask


code: menu.Append(self.popupID2, "Two\t&T")

rawDescription: PopupMenu in wxPython with key press activated context menu items


code:
my_django_shutdown_signal = django.dispatch.Signal()

def _forward_to_django_shutdown_signal(signal, frame):
    my_django_shutdown_signal.send('system')
    sys.exit(0)   # So runserver does try to exit
signal.signal(signal.SIGINT, _forward_to_django_shutdown_signal)

rawDescription: Django Framework - Is there a shutdown event that can be subscribed to?


code:
with open('file') as f:
    array = [ [int(s) for s in line.split()] for line in f ]
for line in array:
    print('{:08.0f} {:3.1f} {:3.0f} {:3.0f}'.format(line[0], sum(line[1:])/len(line[1:]), min(line[1:]), max(line[1:])))

rawDescription: Need to read from a file and add the elements and get avg in python 3.4


code:
ns19:AuditFeesExpenses
1,850
ns19:AuditFeesExpenses
2,400

rawDescription: Code transformation from BS4 to lxml parser


code:
class MyClass():

    model_func = {'A' : funca, 'B' : funcb}

    def __init__(self, model):
        self.func = self.model_func[model]

    def funca():
        pass

    def funcb():
        pass

a = MyClass('A')
a.func()

b = MyClass('B')
b.func()

rawDescription: Pythonic way to create dynamic class methods


code:
import numpy as np
from random import random

# generate fake data
num_files = 5
N = 20
my_array = []
for f in range(num_files):  # simulate multiple files
    for n in range(N):  # simulate multiple samples per file
        # fake data
        my_array.append([10 ** n / N, random() + f, 10 + f + random()])
my_array = np.asarray(my_array)

rawDescription: save and plot multiple datasets using python

description: Save and plot multiple datasets using python


rawDescription: Getting values live from a logfile into a string for caculations using Python


code:
idx = sorted(random.sample(range(len(lst)), 30))

j = 0
for i,num in enumerate(lst):
    if j <= len(idx) and i == idx[j]:
        msg = 'line {} in sample'
        j += 1
    else:
        msg = 'line {} not in sample'

    print(msg.format(num))   # out.write() or whatever

rawDescription: Write out from random sample

description: Write out from random sample


code:
df
df.duplicated()

rawDescription: pandas selects a set of columns from a dataframe

description: Pandas selects a set of columns from a dataframe


code:
filenames = 'QLD2010.csv QLD2011.csv QLD2012.csv QLD2013.csv QLD2014.csv'.split()
filenames
[fn[3:7] for fn in filenames]

rawDescription: Python csv processing

description: Python csv processing


rawDescription: How to get data sent by cloud telephony service using django url?

description: Get data sent by cloud telephony service using django url


code:
df = df.set_index('id1')
dfReplace = dfReplace.set_index('id2').rename( columns={'value2':'value1'} )
dfReplace.combine_first(df)

rawDescription: Elegant way to replace values in pandas.DataFrame from another DataFrame


code:
def outer(arg, timeout=None):
    t = Timeout(timeout)
    # some operation:
    time.sleep(1)
    if t.is_timeout: return None
    # use time left as subfunction's timeout:
    return inner(arg, timeout=t.time_left)

rawDescription: Nestable timeout decorator? (i.e. timeout decorated func calling timeout decorated func)


code:
transform = lambda x: x.id
results = self.db.query(schema.allPostsUuid).execute(timeout=20)
condition = lambda x: x.deleted is not False and ... and ...
[transform(x) for x in results if condition(x)]

rawDescription: How to indent Python list-comprehensions?

description: Indent Python list-comprehensions


code:
import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title='BoxSizer demo (resize the frame)')
        self.SetBackgroundColour(wx.WHITE)
        layout = wx.StaticBoxSizer(wx.StaticBox(self,label="wx.BoxSizer(wx.HORIZONTAL)"),wx.HORIZONTAL)
        # proportion=1
        layout.Add( wx.StaticText(self,label='proportion=1', style=wx.BORDER_DOUBLE ), 1, wx.ALL, 10 )
        # proportion=0, expand
        layout.Add( wx.StaticText(self,label='wx.EXPAND', style=wx.BORDER_DOUBLE ), 0, wx.EXPAND|wx.ALL, 10 )
        # proportion=0, align bottom
        layout.Add( wx.StaticText(self,label='wx.ALIGN_BOTTOM', style=wx.BORDER_DOUBLE ), 0, wx.ALIGN_BOTTOM|wx.ALL, 10 )
        # proportion=2, expand
        layout.Add( wx.StaticText(self,label='proportion=2 + wx.EXPAND', style=wx.BORDER_DOUBLE ), 2, wx.EXPAND|wx.ALL, 10 )
        self.SetSizerAndFit(layout)

app = wx.App(False)
Frame().Show()
app.MainLoop()

rawDescription: wxpython flag=wx.EXPAND vs propotion=number

description: Wxpython flag=wx.EXPAND vs propotion=number


code:
import re

def explode(s, keywords):
    for k in keywords:
        m = re.search(r'(%s~[^~]*)(?:~|$)' % (re.escape(k),), s)
        yield m and m.group(1)

for row in lst:
    row[1:2] = explode(row[1], "Mega Mid Micro".split())

rawDescription: Split String In List While Preserving Original List Order


code: makeArchive(dirEntries(folder, True), zipname, folder)

rawDescription: Python zip a sub folder and not the entire folder path


code:
import code

console = code.InteractiveConsole()

more_input = False
with open('example.py') as source:
    for line in source:
        if not more_input:
            print('>>> ' + line.rstrip())
        else:
            print('... ' + line.rstrip())

        more_input = console.push(line)

rawDescription: How to generate documentation from python code looking like "python shell output"

description: Generate documentation from python code looking like "python shell output"


code:
def get_list_of_vowel_count(name_list):
    return [len([c for c in name if c in "aeiouAEIOU"])
                for name in name_list]

rawDescription: Counting vowels using nested loop in python


rawDescription: How do I write a float list of lists to file in Python

description: Write a float list of lists to file in Python


code:
import psutil
import subprocess
doc = subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True)
doc.poll()
psutil.Process(doc.pid).get_children()[0].kill()
doc.poll()

rawDescription: How do I launch a file in its default program, and then close it when the script finishes?

description: Launch a file in its default program, and then close it when the script finishes


code:
a
a.A
x
a.multiply(x)

rawDescription: Element-wise multiplication for sparse matrices in python


rawDescription: Datetime conversions to timestamp

description: Datetime conversions to timestamp


code: newdate = datetime.datetime(*values)

rawDescription: Python create datetime object from list of values


code:
RRA.txt
CZM.txt
DUN.txt
# etc

rawDescription: how to read the content of .txt file using python?

description: Read the content of .txt file using python


code:
import pandas as pd
from datetime import datetime
data = pd.DataFrame({"year": ["01/01/1880 12:00:00 AM"]})
data
a = data["year"]
[datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]

rawDescription: how to get year from a file, column contaning datetime

description: Get year from a file, column contaning datetime


code:
import re

for value in ['abc', 'abc1']:
    if re.search(r'\d', value):
        print(value, 'contains at least one digit')
    else:
        print(value, 'contains no digit')

rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


code:
t5.join()
t1.join()

rawDescription: Multi threading script favors .start() which is first and doesn't run the others at all python


code:
import numpy as np
from scipy.sparse import coo_matrix

shape = (100000, 100000)
rows = np.int_(np.round_(shape[0]*np.random.random(1000)))
cols = np.int_(np.round_(shape[1]*np.random.random(1000)))
vals = np.ones_like(rows)

m = coo_matrix((vals, (rows, cols)), shape=shape)
ax = plot_coo_matrix(m)
ax.figure.show()

rawDescription: python matplotlib plot sparse matrix pattern

description: Python matplotlib plot sparse matrix pattern


code: "this is field 0" "this is field 1" "this is field 2"

rawDescription: TAB break for line split in a dictionary in Python


code:
def planPath(self, creature, goal, board):
        print("in the path")
        path = [board[creature.x][creature.y]]
        while goal not in path and len(path) < self.boardSize ** 2:
            print("path length")
            print(len(path))
            nextPossible = {}
            for neighbor in path[-1].neighbors:
                if type(neighbor) is not Land.Water:
                    nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)
            path.append(min(nextPossible, key=nextPossible.get))
        return path

rawDescription: endless while loop confusion

description: Endless while loop confusion


code:
result = pd.to_datetime(d.Initial_Date.astype(str), dayfirst=True, errors='coerce')

result.ix[result.isnull()] = pd.to_datetime(d.Initial_Date.astype(str), format='%d%m%Y', dayfirst=True, errors='coerce')
#format is set to %d%m%Y

rawDescription: Convert content of Object datatype to Date datatype in Python


code:
import socket
import socks
import requests

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050, True, 'socks5_user','socks_pass')
socket.socket = socks.socksocket
print(requests.get('http://ifconfig.me/ip').text)

rawDescription: How do I make a requesocks request with socks5 username and password?

description: Make a requesocks request with socks5 username and password


code:
import string
class baseRange:
    def __init__(self, low, high, base):
        digs = string.digits + string.letters
        self.current = low
        self.high = high
        self.base = base
    def __iter__(self):
        return self
    def next(self):  # Python 3 requires this to be __next__
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.int2base(self.current - 1, self.base)
    def int2base(self, x, base):
        if x < 0: sign = -1
        elif x == 0: return digs[0]
        else: sign = 1
        x *= sign
        digits = []
        while x:
            digits.append(digs[x % base])
            x /= base
        if sign < 0:
            digits.append('-')
            digits.reverse()
        return ''.join(digits)

rawDescription: Count upward in python with variable base


code: [[s, d, v] for d in data for f in data[d] for vals in data[d][f] for s, v in zip(state, vals) if f == 'go']

rawDescription: Manipulating fields and values in dict and transforming into tuples in Python


rawDescription: Adjacency List and Adjacency Matrix in Python


code:
for j in range(i, len(Array)+1):
  current_sum += Array[j]

rawDescription: Understanding/implementing this enumeration solution for maximum subarray


code:
def send(self):
    return buffer(self)[:]

rawDescription: How to pack and unpack using ctypes (Structure <-> str)

description: Pack and unpack using ctypes (Structure <-> str)


code:
import heapq

class FilenameQueue(object):
    def __init__(self, times_sizes_names, maxsize):
        self.maxsize = maxsize
        self.size = sum(s for t, s, n in times_sizes_names)
        self.files = list(times_sizes_names)
        heapq.heapify(self.files)
        while self.size > self.maxsize:
            self.get()
    def __len__(self):
        return len(self.files)
    def put(self, time_size_name):
        self.size += time_size_name[1]
        if self.size < self.maxsize:
            heapq.heappush(self.files, time_size_name)
        else:
            time_size_name = heapq.heappushpop(self.files, time_size_name)
            self.size -= time_size_name[1]
    def get(self):
        time_size_name = heapq.heappop(self.files)
        self.size -= time_size_name[1]
        return time_size_name

rawDescription: can collections.deque be extended to build a "file buffer"?

description: Can collections.deque be extended to build a "file buffer"


code:
def parse_shot_success(string):
    words = [
        # (word, return value)
        ('scores', 'scores'),
        ('blocks', 'misses'),
        ('misses', 'misses'),
    ]

    for word, result in words:
        if word in string:
            return result

    return 'not a shot'

rawDescription: Searching fro string and converting it to another string python


rawDescription: if "it is a date" then "do what I say" -

description: If "it is a date" then "do what I say" -


code:
q = [2]
for num in range(3, 101, 2):
    if num > 1:
        if all(num % i != 0 for i in range(3, int(num ** 0.5 + 1), 2)):
            q.append(num)

rawDescription: Change starting index of list in python?

description: Change starting index of list in python


code:
def _select_nextval(cr, seq_name):
    cr.execute("SELECT nextval('%s')" % seq_name)
    return cr.fetchone()

rawDescription: Why the sequence of a field changes when saved in Odoo?


code:
def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent(self.hWaitStop)
    web.httpserver.server.interrupt = KeyboardInterrupt()

rawDescription: How to stop web.py server which run as windows service

description: Stop web.py server which run as windows service


code:
import shelve
import itertools
s = shelve.open('final.db', flag='c', protocol=-1, writeback=False)
s1 = shelve.open('file1.db', flag='r')
s2 = shelve.open('file2.db', flag='r')
for key, val in itertools.chain(s1.iteritems(), s2.iteritems()):
    d = s.get(key, {})
    d.update(val)
    s[key] = d # force write
s.close()

rawDescription: Joining large dictionaries by identical keys


rawDescription: Generating sub-lists of a string containing keywords in python


code: {'kwarg1': 'FOO', 'kwarg2': 'BAR', 'kwarg3': 'BAZ'}

rawDescription: What is the use of __kwdefaults__ which is a function object attribute?


code:
from itertools import product

c = list(product(a, b))

rawDescription: Generate array of number pairs from 2 numpy vectors


rawDescription: python xmpp wokkel JID escaping

description: Python xmpp wokkel JID escaping


code:
TYPES = { 'ParentClass': ParentClass,
          'ChildClass': ChildClass }

class CustomTypeEncoder(json.JSONEncoder):
    """A custom JSONEncoder class that knows how to encode core custom
    objects.

    Custom objects are encoded as JSON object literals (ie, dicts) with
    one key, '__TypeName__' where 'TypeName' is the actual name of the
    type to which the object belongs.  That single key maps to another
    object literal which is just the __dict__ of the object encoded."""

    def default(self, obj):
        if isinstance(obj, TYPES.values()):
            key = '__%s__' % obj.__class__.__name__
            return { key: obj.__dict__ }
        return json.JSONEncoder.default(self, obj)

def CustomTypeDecoder(dct):
    if len(dct) == 1:
        type_name, value = dct.items()[0]
        type_name = type_name.strip('_')
        if type_name in TYPES:
            return TYPES[type_name].from_dict(value)
    return dct

rawDescription: Easiest way to serialize a simple class object with simplejson?


rawDescription: Finding the intersection between two series in Pandas using index


rawDescription: Creating a spiral structure in Python, using hyperbolic tangent


code:
from collections import defaultdict

def parse_go(mapping_list, go_file):
    go_dict = defaultdict(set)

    with open(go_file) as f:                    # Better garbage handling using 'with'
        for line in f:
            (value_id, go_term) = line.split()  # Feel free to change the split behaviour
                                                # work better for you.
            for map_dict in mapping_list:
                if value_id in map_dict:
                    go_dict[map_dict[value_id]].add(go_term)

    return go_dict

rawDescription: Adding items to sets in a dictionary

description: Adding items to sets in a dictionary


code:
import numpy as np
import pandas as pd
def using_transform(s):
    return s[s.groupby(level=0).transform(lambda x: x == x.max()).astype(bool)]

N = 10**5
id1 = np.random.randint(100, size=N)
id2 = np.random.choice(list('abcd'), size=N)
index = pd.MultiIndex.from_arrays([id1, id2])
ss = pd.Series(np.random.randint(100, size=N), index=index)
ss.index.names = ['id1', 'id2']
ss.name = 's'

rawDescription: Multiindex pandas groupby + aggregate, keep full index


code:
isprintable(u'Hello World!')
isprintable(u'Jeg \u00f8ve mit Norsk.')

rawDescription: Check printable for Unicode

description: Check printable for Unicode


code:
DATETIME_FORMAT = '%d-%m-%Y %H:%M:S'
USE_L10N = False
USE_TZ = False # if you plan to disable timezone support

rawDescription: Django model DateTimeField set auto_now_add format or modify the serializer


rawDescription: How to import specific data from an XML file and process it using python 3.5?

description: Import specific data from an XML file and process it using python 3.5


code:
transtab = maketrans(inchars, outchars, deletechars)
return s.translate(*transtab).rstrip().split(':')

rawDescription: Transparently doing .translate with str and unicode objects


code:
# Assume cursor object
statement = 'INSERT INTO Names (FirstName, LastName) VALUES (?, ?)'
cursor.executemany(statement, (
    ('John', 'Doe'),
    ('Mary', 'Smith'),
    # ...
    )
)

rawDescription: SQL INSERT with multiple rows of values using Jython and zxJDBC


code:
[item[1:] for item in your_list]  # probably the best
zip(*zip(*your_list)[1:])  # tricky and probably slow one

rawDescription: Deleting the first item of every element in a string in Python


code:
def random_string():
    return str(random.randint(10000, 99999))

rawDescription: How to set a random integer as the default value for a Django CharField?

description: Set a random integer as the default value for a Django CharField


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

    def __eq__(self, other):
        return isinstance(other, Panel) and other.id == self.id

rawDescription: Unit tests for Query in SQLAlchemy

description: Unit tests for Query in SQLAlchemy


code:
import string, win32ui, win32con
from Tkinter import *

def decaption(event):
    w = event.widget
    frame = win32ui.CreateWindowFromHandle(string.atoi(w.wm_frame(), 0))
    frame.ModifyStyle(win32con.WS_CAPTION, 0, win32con.SWP_FRAMECHANGED)
    w.bind("<Map>", None)

root = Tk()
root.bind("<Map>", decaption)
root.mainloop()

rawDescription: Using TCL extensions to set native window style in Tkinter


code:
import subprocess
import glob
for f in glob.glob('*-C_'):
    subprocess.call(['xRITDecompress',f])

rawDescription: apply command to list of files in python

description: Apply command to list of files in python


rawDescription: How to mathematically subtract two lists in python?

description: Mathematically subtract two lists in python


rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


rawDescription: if statement vs. expression

description: If statement vs. expression


code:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Dependency(models.Model):
    dependent_contenttype = models.ForeignKey(ContentType)
    dependent_id = models.PositiveIntegerField()
    dependent = GenericForeignKey('dependent_contenttype', 'dependent_id')

    prerequisite_contenttype = models.ForeignKey(ContentType)
    prerequisite_id = models.PositiveIntegerField()
    prerequisite = GenericForeignKey('prerequisite_contenttype',
                                     'prerequisite_id')

rawDescription: Data models dependencies, can I simplify these objects?


code:
data = []
with open("999A.txt") as f:
    for line in f:
        line = line.strip()
        if line.startswith("|"):
            cols = line.split("|")[1:-1] # remove outside empty strings
            cols = list(map(str.strip, cols)) # strip the remaining strings
            if len(cols) == 16 and not all(x == '' for x in cols):
                # keep rows with 16 columns and no empty strings
                data.append(cols)

for row in data:
    # do something
    print(row)

rawDescription: grabbing info from a table with loops (python)

description: Grabbing info from a table with loops (python)


rawDescription: How can I dynamically generate class instances with single attributes read from flat file in Python?

description: Dynamically generate class instances with single attributes read from flat file in Python


rawDescription: Why is numpy vectorized function apparently called an extra time?


rawDescription: Resample withing a specified interval in Pandas?


code:
results = []
# ranging from 1 to 3 digits
for l in range(1, 4):
    # all combinations of l digits out of 8 and 9
    for digits in product('89', repeat=l):
        # put the digits together into one string, convert to an integer
        value = int(''.join(digits))
        results.append(value)

rawDescription: How do I create a lambda function to print numbers containing x and y in Python?

description: Create a lambda function to print numbers containing x and y in Python


rawDescription: Order mapping - more efficient Python solution for sorting?


rawDescription: Python split a list into smaller lists depending on original list length


code: [dct[i] for i in index]

rawDescription: Convert a 3D array to 2D array based on dictionary


code: col_idx = bool_array.argmax(1)

rawDescription: How to obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row

description: Obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row


rawDescription: Removing empty Counter() objects from a list


code:
for elem in list_im:
  for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
  new_im.save('new_' + elem + '.jpg')

rawDescription: Combine several images horizontally with Python


code:
from rx.observable import Observable, ObservableMeta
from rx.anonymousobservable import AnonymousObservable
from rx.concurrency import current_thread_scheduler

class ObservableFile(Observable, metaclass=ObservableMeta):

    @classmethod
    def from_file(cls, readableFile, scheduler=None):
        scheduler = scheduler or current_thread_scheduler

        def subscribe(observer):
            def action(action1, state=None):
                try:
                    observer.on_next(readableFile.next())
                    action1(action)

                except StopIteration: # EOF
                    observer.on_completed()

            return scheduler.schedule_recursive(action)
        return AnonymousObservable(subscribe)

rawDescription: How can I make an rx.py Observable from a stream such as stdin?

description: Make an rx.py Observable from a stream such as stdin


code:
class Bank(object):
    def __init__(self, name):
       self.name = name
       self.accounts = []  # Note - this is at the instance level
                           # so multiple banks don't share each other's accounts

    def add_account(self, account):
       self.accounts.append(account)

    def delete_account(self, account):
       try:
           self.accounts.remove(account)
       except ValueError:
           print('{} is already deleted.'.format(account))

    def transfer(self, from_acct, to_acct, amount):
       if amount < from_account.get_balance():
           print('{} is less than the balance of the from account'.format(amount))
       to_account.credit(amount)
       from_account.debit(amount)

rawDescription: Class Level Variables python

description: Class Level Variables python


code:
import matplotlib.pyplot as plt
plt.plot(hours,degs)

rawDescription: Python: Read text file with time in hour, minutes and seconds; and angle in degree, arc minutes and arc seconds


code:
import numpy as np
def func(a,k):
    b=np.empty(a.shape)
    for i in range(a.flatten().size):
        ind=np.unravel_index(i,a.shape)
        if ind[0:3]==ind[3:6]:
            b[ind]=a[ind]*ind[0:3][k]**2
        else:
            b[ind]=a[ind]*(ind[0:3][k]**2-ind[3:6][k]**2)
    return b

def func2(a,k):
    b = np.empty(a.shape)
    ind = np.indices(a.shape).reshape(6, -1)
    mask = np.all(ind[:3] == ind[3:6], axis=0)
    ar = a.ravel()
    br = b.ravel()
    br[mask] = ar[mask]*ind[k, mask]**2
    mask = ~mask
    br[mask] = ar[mask]*(ind[k, mask]**2 - ind[3+k, mask]**2)
    return b

a = np.arange(729).reshape((3,3,3,3,3,3))
b1 = func(a, 2)
b2 = func2(a, 2)
np.allclose(b1, b2)

rawDescription: Vectorized manipulation of an array, based on a function of indices


code: waves = [(frequency, amplitude)] * wave_count

rawDescription: Python 3.2: Can I multiply a tuple in a list without concatenating the individual tuples into one tuple?


code:
import pandas as pd
df = pd.read_table('data', sep='\s+')
df['month'] = pd.to_datetime(df['month'], format='%Y-%m')
df = df.pivot(index='month', columns='ticker')

start_date = df.index.min() - pd.DateOffset(day=1)
end_date = df.index.max() + pd.DateOffset(day=31)
dates = pd.date_range(start_date, end_date, freq='D')
dates.name = 'date'
df = df.reindex(dates, method='ffill')

df = df.stack('ticker')
df = df.sortlevel(level=1)
df = df.reset_index()

rawDescription: Converting PANDAS dataframe from monthly to daily


code:
with np.errstate(invalid='ignore'):
    y1 = (x/2.) + np.sqrt(np.power(x/2.,2) + a)
    y2 = (x/2.) - np.sqrt(np.power(x/2.,2) + a)

rawDescription: Matplotlib challenge - smart way to plot only in the existence range


code:
import csv

results = {}
with open('psc.csv', newline='') as pscfile:
    reader = csv.DictReader(pscfile)
    for row in reader:
        results[row['cellname']] = row['scrambling']

rawDescription: how to read a csv into a dictionary in python?

description: Read a csv into a dictionary in python


rawDescription: How to repeat Pandas data frame?

description: Repeat Pandas data frame


code:
class Course:
    def __init__(self, date, title, instructor, ID, description, instructorDescription, *args):
        self.date = date
        self.title = title
        self.instructor = instructor
        self.ID = ID
        self.description = description
        self.instructorDescription = instructorDescription
        self.misc = args

    def matches_term(self, term):
        if term in self.date.lower():
            return True
        # etc
        return False

rawDescription: Are python list comprehensions always a good programming practice?


rawDescription: clean summation involving index of numpy arrays

description: Clean summation involving index of numpy arrays


code:
class Species:
    '''This structure contains all the information needed for all genes.
    One specie have several genes, one gene several proteins'''

    def __init__(self, name):
        self.name = name #name of the GENE
        self.genes = {}

    def addProtein(self, gene, protname, len):
        #Converting a line from the input file into a protein and/or an exon
        if gene not in self.genes:
            self.genes[gene] = Gene(gene)
        self.genes[gene].proteins[protname] = Protein(protname, len)

    @property
    def ngenes(self):
        return len(self.genes)

class Protein:
    #The class protein contains information about the length of the protein and a list with it's exons (with it's own attributes)
    def __init__(self, name, len):
        self.name = name
        self.len = len

class Gene:
    #The class gene contains information about the gene and a dict with it's proteins (with it's own attributes)
    def __init__(self, name):
        self.name = name
        self.proteins = {}

    @property
    def nproteins(self):
        return len(self.proteins)

rawDescription: optimize python key-searching in hierarchichal dictionary

description: Optimize python key-searching in hierarchichal dictionary


code:
i, j = pr[0]
df.loc[i:j]

rawDescription: Delimiting contiguous regions with values above a certain threshold in Pandas DataFrame


code:
import ctypes
X11 = ctypes.CDLL("libX11.so")

rawDescription: How can I use python xlib to generate a single keypress?

description: Use python xlib to generate a single keypress


rawDescription: Remove boilerplate content from HTML page


code:
class Gallery(models.Model):
    # SQL columns

    @property
    def thumb(self):
        return self.latest(limit=1, public=True)

rawDescription: Django adding two objects to view

description: Django adding two objects to view


code:
case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

rawDescription: Adding item to Dictionary within loop

description: Adding item to Dictionary within loop


code: [datetime.strptime(dt, '%d/%m/%Y').toordinal() for dt in x]

rawDescription: Python - Altering a list that is being iterated. Out of Scope