code:
from django.core.cache import cache

def save_viewer_tab(active, session_key, tab):
    cache.set(session_key + ":" + str(tab), int(active))

def get_viewer_tab(session_key, tab, default=0):
    return cache.get(session_key + ":" + str(tab), default)

@csrf_exempt
def update_active_tab_request(request):
    """
    Stores the active tab for a given tab item
    """
    session_key = request.session._session_key
    for tab, active in request.GET.iteritems():
        save_viewer_tab(active, session_key, tab)

    return HttpResponse("OK", status=200)

rawDescription: Django session values occasionally not persisted


code:
from scipy import ndimage

stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
x = linspace(-10, 10, 100)
y = linspace(-10, 10, 100)
xx, yy = meshgrid(x, y)
image = exp(-xx**2-yy**2)  # Standard deviation in x or y: 1/sqrt(2)

laplaced = ndimage.convolve(image, stencil)/(x[1]-x[0])**2  # stencil from original post
expected_result = -4*image + 8*(xx**2+yy**2)*image  # Very close to laplaced, in most points!

rawDescription: How to compute laplacian of a field?

description: Compute laplacian of a field


code:
#!/usr/bin/env python

import StringIO
import zipfile
from google.appengine.api import files
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import util

def zipit():
    zipstream = StringIO.StringIO()
    zfile = zipfile.ZipFile(file=zipstream, mode='w')
    bytes = "lorem ipsum dolor sit amet"
    zfile.writestr('loremipsum', bytes, compress_type=zipfile.ZIP_STORED)
    zfile.close()
    zipstream.seek(0)
    return zipstream.getvalue()

class MainHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self):
        k = self.request.get('key')
        if k:
            self.send_blob(k)
            return

        zip_file = files.blobstore.create(mime_type='application/zip')
        zip_data = zipit()

        with files.open(zip_file, 'a') as f:
            f.write(zip_data)
        files.finalize(zip_file)
        blob_key = files.blobstore.get_blob_key(zip_file)

        self.response.out.write('get zip' % blob_key)

application = webapp.WSGIApplication([('/getzip', MainHandler)])

def main():
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

rawDescription: Generate Zip Files and Store in GAE BlobStore


code:
import numpy as np
import dask.array as da
x = da.random.normal(10, 0.1, size=(10000, 10000), chunks=(1000, 1000))
type(x)
import dask
dask.__version__

rawDescription: Installation/use of dask.array on python3


code:
for i in range(num_rows):
    for j in range(i, num_cols):
        matrix[j][i] = matrix[i][j]

rawDescription: Copy upper triangle to lower triangle in a python matrix


code:
def primeNumbers(limit):
    primeList = [2]
    for i in nextPrime(primeList):
        if i > limit:
            break
        primeList.append(i)
    return primeList

rawDescription: Am I overusing variables with this generator function?


code:
df.loc[df.c2pos==0,'c2len'] = 0
df.loc[df.c1pos==0,'c1len'] = 0
df

rawDescription: Updating Pandas DataFrame column conditionally using other columns


code:
from twisted.internet.protocol import Protocol
from twisted.internet.threads import deferToThread

class Send(Protocol):
    def connectionMade(self):
        self.qget()

    def qget(self, data=None):
        if data is not None:
            self.transport.write(data)
        deferToThread(queue.get).addCallback(self.qget)

rawDescription: Send from Twisted client to Twisted server, only this one way


code:
e = Entry(root1,textvariable=x1)
e.pack();
Button(root1,text="try me",command=(lambda :hello (e.get()))).pack()

rawDescription: tkinter argument passing between two functions

description: Tkinter argument passing between two functions


code:
import itertools
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

rawDescription: Iterate a list as pair (current, next) in Python


code:
email_accounts = EmailAccount.objects.filter(user__user=self.request.user)
form.fields['account'].queryset = email_accounts

rawDescription: How to filter special characters in django template

description: Filter special characters in django template


code: import pdb; pdb.set_trace()

rawDescription: drop into python interpreter while executing function

description: Drop into python interpreter while executing function


code:
import itertools
word = 'toy'
[''.join(w) for w in itertools.product(*zip(word.lower(), word.upper()))]

rawDescription: Iterate to get case alternatives in python


code:
#!/usr/bin/python

from pylab import *
import matplotlib
import matplotlib.ticker as ticker

# Setting minor ticker size to 0, globally.
# Useful for our example, but may not be what
# you want, always
matplotlib.rcParams['xtick.minor.size'] = 0

# Create a figure with just one subplot.
# 111 means "1 row, 1 column, 1st subplot"
fig = figure()
ax = fig.add_subplot(111)
# Set both X and Y limits so that matplotlib
# don't determine it's own limits using the data
ax.set_xlim(0, 800)

# Fixes the major ticks to the places we want (one every hundred units)
# and removes the labels for the majors: we're not using them!
ax.xaxis.set_major_locator(ticker.FixedLocator(range(0, 801, 100)))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
# Add minor tickers AND labels for them
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(['AB%d' % x for x in range(1, 9)]))

ax.set_ylim(-2000,6500, auto = False)
# And set the grid!
ax.grid(True, linestyle='-')

# common attributes for the bar plots
bcommon = dict(
    height = [8500],  # Height = 6500 - (-2000)
    bottom = -2000,   # Where to put the bottom of the plot (in Y)
    width = 100)      # This is the width of each bar, itself
                      # determined by the distance between X ticks

# Now, we create one separate bar plot pear colored column
# Each bar is a rectangle specified by its bottom left corner
# (left and bottom parameters), a width and a height. Also, in
# your case, the color. Three of those parameters are fixed: height,
# bottom and width; and we set them in the "bcommon" dictionary.
# So, we call bar with those two parameters, plus an expansion of
# the dictionary.

# Note that both "left" and "height" are lists, not single values.
# That's because each barplot could (potentially) have a number of
# bars, each one with a left starting point, along with its height.
# In this case, there's only one pair left-height per barplot.
bars = [[600, 'blue'],
        [700, 'orange']]
for left, clr in bars:
    bar([left], color=clr, **bcommon)

show()

rawDescription: How do I create this kind of grid table using matplotlib

description: Create this kind of grid table using matplotlib


code:
import scipy
import numpy as np
a = np.array([[3,2,0],[1,-1,0],[0,5,1]])
b = np.array([2,4,-1])
x = linalg.solve(a,b)
x

rawDescription: How to solve a equation set in python?

description: Solve a equation set in python


code:
def in_fragment(phrase, fragments):
    return any(x in phrase for x in fragments)

rawDescription: Compare a string to a list of fragments in Python


code:
for i in range(1,len(word)+1):
    print(word[:i])

for i in range(len(word)-1,0,-1): #the third argument of range is step, and -1 causes range to step backwards
    print(word[:i])

rawDescription: Replacing a single character when there are duplicates


code:
from string import maketrans
table = maketrans("GCTA", "CGAT")
f = open("filename.txt", "r")
input = f.read()
print(input.translate(table))
print(input.count('GCAA'))

rawDescription: Attempting to count a certain string and how many times it repeats. Also, replacing characters with other characters. All from a file read


code: ax = [fig.add_subplot(1, 3, x+1, projection = '3d') for x in range(3)]

rawDescription: Generate list of subplots in same order as they will be plotted.


code:
import socket
def iptoint(ip):
    return int(socket.inet_aton(ip).encode('hex'), 16)

iptoint('127.0.0.200')
iptoint('127.0.1.10') - iptoint('127.0.0.200')
def ipdistance(ip1, ip2):
    return abs(iptoint(ip1) - iptoint(ip2)) + 1

ipdistance('127.0.1.10', '127.0.0.200')

rawDescription: Is there an easy way of calculating number of IPs from 2 given IP addresses?


code:
def unique_list(l):
    ulist = []
    [ulist.append(x) for x in l if x not in ulist]
    return ulist

a="calvin klein design dress calvin klein"
a=' '.join(unique_list(a.split()))

rawDescription: How can I remove duplicate words in a string with Python?

description: Remove duplicate words in a string with Python


code:
def getnewestfile(NetworkPath):
    DestFolder = os.getcwd()
    os.chdir(NetworkPath)
    filelist = os.listdir(os.getcwd())
    filelist = filter(lambda x: not os.path.isdir(x), filelist)
    newest = max(filelist, key=lambda x: os.stat(x).st_mtime)
    os.chdir(DestFolder)
    return newest

rawDescription: Checking a file modification date/time against one stored in memory?


code:
data = {
    'delay_time': [],
    'step_size': [1,1,1,1,1],
    'first_uncorrectable': [],
    'second_uncorrectable': [],
    'erasure_decode': [],
    'ecc_hibit': [],
    'bits_corrected': [],
    'bits_read': [],
    'avg_rber': [],
    'avg_rber_ed': [],
    'ed_success': []
}

for data_set in data:
    for each_item in data[data_set]:
        current_cell_iteration = '%s%d'%(xlsx_cols[current_letter], column_iterator) #STARTING AT CURRENT CELL OF
        overall_stats_sheet[current_cell_iteration] = each_item
        current_letter += 1
    current_letter = 1
    column_iterator += 1

rawDescription: Developing a more efficient array and for loop script in Python


code: sparse_grid = {(r1, c1): value1, (r2, c2):value2 }

rawDescription: For Python 3.4: Is there a grid-like container that doesn’t store values for empty cells?


code:
from itertools import groupby
L = [0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]
# Or (k, len(list(g))), but that creates an intermediate list
grouped_L

rawDescription: What's the most Pythonic way to identify consecutive duplicates in a list?


code:
for j in range(10):
    jstart = jstarts[j]
    jend = jends[j]
    tmp = np.sum(data[...,jstart:jend]*vol[jstart:jend], axis=1)/np.sum(vol[jstart:jend])
    data_new[..., jstart:jend] = tmp

rawDescription: Python method for array with variable dimensions


rawDescription: django - Foreign key models, view that inherts 3 models deep

description: Django - Foreign key models, view that inherts 3 models deep


code:
max(enumerate(dq), key=lambda x: (x[1][1], -x[1][0]))
idx, maxval = max(enumerate(dq), key=lambda x: (x[1][1], -x[1][0]))
idx

rawDescription: How to find a corner in a list of coordinates?

description: Find a corner in a list of coordinates


code:
print >>f, "Hello world"           # Python 2.x

print("Hello world", file=f)       # Python 3.x

rawDescription: Meaning of >> in print statement

description: Meaning of >> in print statement


code:
import numpy as np
from scipy.interpolate import spline, UnivariateSpline, Akima1DInterpolator, PchipInterpolator
import matplotlib.pyplot as plt

x_data = np.array([1, 1.2371, 1.6809, 2.89151, 5.13304, 9.23238])

y_data = np.array([0.0688824, 0.0490012, 0.0332843, 0.0235889, 0.0222304, 0.0245952])

x_data_smooth = np.linspace(min(x_data), max(x_data), 1000)
fig, ax = plt.subplots(1,1)

spl = UnivariateSpline(x_data, y_data, s=0, k=2)
y_data_smooth = spl(x_data_smooth)
ax.plot(x_data_smooth, y_data_smooth, 'b')

bi = Akima1DInterpolator(x_data, y_data)
y_data_smooth = bi(x_data_smooth)
ax.plot(x_data_smooth, y_data_smooth, 'g')

bi = PchipInterpolator(x_data, y_data)
y_data_smooth = bi(x_data_smooth)
ax.plot(x_data_smooth, y_data_smooth, 'k')

ax.plot(x_data_smooth, y_data_smooth)
ax.scatter(x_data, y_data)

plt.show()

rawDescription: Intuitive interpolation between unevenly spaced points


code: df2 = df1.drop(df1.columns[df1.sum() >= 100], axis=1)

rawDescription: Subsetting a dataframe using column sum in Python


rawDescription: How does a Python genius iterate over a single value in a Python tuple?


code:
import unittest

from redis import Redis

class RedisTest(unittest.TestCase):

    def setUp(self):
        self.redis = Redis()

    def test_zrangebyscore(self):
        r = self.redis
        name = 'myset'
        r.zadd(name, 'one', 1)
        r.zadd(name, 'two', 2)
        r.zadd(name, 'three', 3)
        r.zadd(name, 'four', 4)

        self.assertTrue(r.zrangebyscore(name, '-inf', '+inf') == ['one', 'two', 'three', 'four'])
        self.assertTrue(r.zrangebyscore(name, 1, 1) == ['one'])
        self.assertTrue(r.zrangebyscore(name, 1, 2) == ['one', 'two'])
        self.assertTrue(r.zrangebyscore(name, 2, 3) == ['two', 'three'])
        self.assertTrue(r.zrangebyscore(name, '(1', '(2') == [])
        self.assertTrue(r.zrangebyscore(name, '(1', '(3') == ['two'])

rawDescription: how can I pass infinity to redis from python?

description: Pass infinity to redis from python


code:
job = group([
    single_test.s(1, 1),
    single_test.s(1, 2),
    single_test.s(1, 3),
])
result = job.apply_async()
result.save()

from celery.result import GroupResult
saved_result = GroupResult.restore(result.id)

rawDescription: Retrieving GroupResult from taskset_id in Celery?


code:
import re
re.sub(r"(\w+) (\w+)", r"john \2", "Isaac Newton, physicist")

rawDescription: editing using regular expressions

description: Editing using regular expressions


code:
for file in files:
    mod = __import__(file)
    mod.report()

rawDescription: How to call a function if the function's file name is known and is a string?

description: Call a function if the function's file name is known and is a string


code:
from datetime import datetime
datetime.strptime(s, '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')

rawDescription: Display given datetime in reverse order in python


code:
from numpy import sqrt

vol = .30
lag = 30
df = pd.DataFrame(np.random.randn(1000) * sqrt(vol) * sqrt(1 / 252.)).cumsum()
pd.rolling_mean(df, lag).plot()

rawDescription: Simulate a smooth timeseries in Python

description: Simulate a smooth timeseries in Python


code:
# on_rtd is whether we are on readthedocs.org
import os
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# otherwise, readthedocs.org uses their theme by default, so no need to specify it

rawDescription: What is an easy way to do a local sphinx build with the static assets readthedocs.org uses?


code:
import itertools

def intersperse(x, numzeroes):
    for indices in itertools.combinations(range(len(x) + numzeroes), numzeroes):
        y = x[:]
        for i in indices:
            y.insert(0, i)
        yield y

x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2]]
list(intersperse(x, 3))

rawDescription: Generate all permutations with sort constraint


code:
# The _artists method can be used from any other method
def _artists(self, action, artist_id):
    artists = session.query(model.Artist).all()
    return dict(artists=artists)

@expose("json")
#@identity.require(identity.non_anonymous())
# error handlers, etc.
def artists(self, action="view", artist_id=None):
    return self._artists(action=action, artist_id=artist_id)

rawDescription: How to create a controller method in Turbogears that can be called from within the controller, or rendered with a template

description: Create a controller method in Turbogears that can be called from within the controller, or rendered with a template


code:
import os
import sys

import gst

def get_frame(path, offset=5, caps=gst.Caps('image/png')):
    pipeline = gst.parse_launch('playbin2')
    pipeline.props.uri = 'file://' + os.path.abspath(path)
    pipeline.props.audio_sink = gst.element_factory_make('fakesink')
    pipeline.props.video_sink = gst.element_factory_make('fakesink')
    pipeline.set_state(gst.STATE_PAUSED)
    # Wait for state change to finish.
    pipeline.get_state()
    assert pipeline.seek_simple(
        gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH, offset * gst.SECOND)
    # Wait for seek to finish.
    pipeline.get_state()
    buffer = pipeline.emit('convert-frame', caps)
    pipeline.set_state(gst.STATE_NULL)
    return buffer

def main():
    buf = get_frame(sys.argv[1])

    with file('frame.png', 'w') as fh:
        fh.write(str(buf))

if __name__ == '__main__':
    main()

rawDescription: How to create video thumbnails with Python and Gstreamer

description: Create video thumbnails with Python and Gstreamer


code:
class MyStr(str):pass

mydict = dict()
mydict['thiskey'] = MyStr('myvalue')
mydict['thiskey'].tag = 1

rawDescription: tagging dictionary data

description: Tagging dictionary data


code:
import inspect, collections
def checkif_paramcomboexists(numpeople, numreviews, prophunters,
                             utility_funcform, goods):

    ...

    temp = inspect.getargvalues(inspect.currentframe())
    args = temp[0]
    valuedict = temp[-1]
    ordered_args_dict = collections.OrderedDict(sorted(valuedict.items(), key=lambda x: args.index(x[0])))
    paramvalues = ordered_args_dict.values()

    ...

rawDescription: Programming practice: dependency of one function on another


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

x1=np.linspace(0,1,1000)
x2=np.linspace(0,1,1000)[:,None]

#f1=x1*(x2-1)
#f2=x1**2+x2**2

inds=(x2<=x1) & (x1<=4*x2)

x1new=(x1+np.zeros(x2.shape))[inds]
x2new=(x2+np.zeros(x1.shape))[inds]
#f1new=f1[inds]
#f2new=f2[inds]
f1new=x1new*(x2new-1)
f2new=x1new**2+x2new**2

plt.figure()
plt.scatter(x1new,x2new)
plt.xlabel(r"$x_1$")
plt.ylabel(r"$x_2$")

plt.figure()
plt.scatter(f1new,f2new)
plt.xlabel(r"$f_1$")
plt.ylabel(r"$f_2$")

plt.show()

rawDescription: Plotting several Y values vs X

description: Plotting several Y values vs X


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

fig, ax = plt.subplots()
fig.set_facecolor('white')

yticks = np.arange(1,3,0.2)

x = [1,2,3]
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.xticks()
plt.yticks(yticks)
ax.yaxis.set_minor_locator(MultipleLocator(5))
plt.show()

rawDescription: Set Python to custom-set y-axis minor tick mark frequency


code:
param = range(10)
var = 'abcdefghij'
locals().update({'{}_true'.format(k): v for k, v in zip(var, param)})
c_true
f_true

rawDescription: Creating variables in loop and initialize them in Python


code: result = ''.join(map(''.join, zip(*strings)))

rawDescription: create new string by adding characters of smaller strings one after another

description: Create new string by adding characters of smaller strings one after another


code: from PIL import ImageTk

rawDescription: Mac 10.9.4 Python ImageTK module import not working "no module named ImageTK"


code:
f=my_opener.open(url)
f.fp._sock.fp._sock._sslobj # here's the ssl object holding the 'issuer' (CA) and 'server' (CN) attributes.

rawDescription: Python requests library - get SSL certificate information


code:
import os, sys
if __name__ == '__main__':
    # Setup environ
    sys.path.append(os.getcwd())
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

    # Setup django
    import django
    django.setup()

    # now you can import your ORM models

rawDescription: Using django for CLI tool

description: Using django for CLI tool


code:
sub_dict = subset(data_dict, 'b', 'a', greater_than, 10)
fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
plt.ylim(0,250)
plt.xlim(0,100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()

rawDescription: figure/subplot confusion with regard to x/y limits

description: Figure/subplot confusion with regard to x/y limits


code: fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')

rawDescription: How to make inline plots in Jupyter Notebook larger?

description: Make inline plots in Jupyter Notebook larger


code:
with open("sample.txt") as infile:
    matrix  = [line.split() for line in infile.readlines()]

    header_list  = [row[0] for row in matrix]
    seq_list = [str(row[1]) for row in matrix]
    disorder_list = [str(row[2]) for row in matrix]

f = open('new_sample.txt', 'a')

for i in range(len(header_list)):
    header = header_list[i]
    seq = seq_list[i]
    disorder = disorder_list[i]

    # count sequence length and total residue of missing coordinates
    sequence_length = len(seq)

    # get total number of missing coordinates
    num_missing = disorder.count('X')

    # get the range of these missing coordinates
    first_X_pos = disorder.find('X')
    last_X_pos = disorder.rfind('X')
    range_missing = '-'.join([str(first_X_pos), str(last_X_pos)])

    reformat_seq=" ".join([header, str(num_missing), range_missing, str(sequence_length), seq, '\n'])
    f.write(reformat_seq)

f.close()

rawDescription: How to create a dataset using sequence file in python

description: Create a dataset using sequence file in python


code:
from StyleFrame import StyleFrame, colors

excel_writer = StyleFrame.ExcelWriter('example.xlsx')
sf = StyleFrame({'a': [1, 2, 3], 'b': [1, 1, 1], 'c': [2, 3, 4]})
sf.apply_column_style(cols_to_style=['a', 'c'], protection=True, style_header=True)
sf.apply_style_by_indexes(indexes_to_style=2, cols_to_style='b', bg_color=colors.yellow, protection=True)
sf.to_excel(excel_writer=excel_writer, row_to_add_filters=0, columns_and_rows_to_freeze='B2', allow_protection=True)
excel_writer.save()

rawDescription: excel file with the ability to filter columns

description: Excel file with the ability to filter columns


code:
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(12,12))

rows = 40
cols = 19
gs = gridspec.GridSpec(rows, cols, wspace=0.0, hspace=0.0)

for i in range(rows):
    for j in range(cols):
        ax = plt.subplot(gs[i, j])
        ax.set_xticks([])
        ax.set_yticks([])

    # label y
    if ax.is_first_col():
        ax.set_ylabel(i, fontsize = 9)

    # label x
    if ax.is_last_row():
        ax.set_xlabel(j, fontsize = 9)

plt.show()

rawDescription: Matplotlib Gridspec "Cell" labels

description: Matplotlib Gridspec "Cell" labels


code:
def wrap(*args, **kwargs):
    return helloworld(*args, **kwargs)

ui.pushButton.clicked.connect(wrap)

rawDescription: python pyqt interactive usuage

description: Python pyqt interactive usuage


code:
while True:
    with open("test.avi") as fh:
        get_last_frame()
    wait_or_do_whatever_you_want()

rawDescription: Read from video .avi file as it is being written


code:
for i in reversed(range(12)):
    I = actualrgn >= 2**i
    actualrgnexpand[i,I] = 1
    actualrgn[I] -= 2**i

rawDescription: Is it possible to vectorize this Python code containing 1D and 2D numpy arrays?


code:
def pytest_generate_tests(metafunc):
    if 'file_name' in metafunc.fixturenames:
        files = []
        if metafunc.config.option.all_files:
            files = list_all_files()
        fn = metafunc.config.option.file_name
        if fn:
            files.append(fn)
        metafunc.parametrize('file_name', all_files, scope='module')

rawDescription: Problems with pytest's addoptions and dynamically parametrizing test fixtures


code:
def get_form_kwargs(self):
    kwargs = super(CampaignLoginView, self).get_form_kwargs()
    kwargs['initial']['email'] = self.request.user.email
    return kwargs

rawDescription: Django How to pre-populate a form field with a argument form context


code:
fixed_list = [x.items() for x in list]
keys,values = zip(*fixed_list)

rawDescription: split dictionary into two lists , one list is for key, another list is for value

description: Split dictionary into two lists , one list is for key, another list is for value


code:
next_page_number = '1'
print(next_page_number, type(next_page_number))  #output: 1, <class 'str'>
# set str explicit or call int(next_page_number)
if next_page_number == '1':
    print('yes')
else:
    print('no')

rawDescription: Select text in href

description: Select text in href


code:
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
# ...

EXTRA_PATHS = [
  DIR_PATH,
  os.path.join(DIR_PATH, 'lib', 'antlr3'),
  os.path.join(DIR_PATH, 'lib', 'django'),
  os.path.join(DIR_PATH, 'lib', 'fancy_urllib'),
  os.path.join(DIR_PATH, 'lib', 'ipaddr'),
  os.path.join(DIR_PATH, 'lib', 'webob'),
  os.path.join(DIR_PATH, 'lib', 'yaml', 'lib'),
]
# ...
sys.path = EXTRA_PATHS + sys.path

rawDescription: Testing Google App Engine app from terminal (python cli)


code:
path = '/some/directory'
for filename in os.listdir(path):
    if not filename.endswith('.txt'):
        continue
    filename = os.path.join(path, filename)
    with open(filename, 'r') as fh:
        for line in fh:
            if re.search('Unique description', line):
                print(line, end='')

rawDescription: Reading directory including txt files

description: Reading directory including txt files


code:
p = Parent()
p.user_ptr = user
p.contact_means = ...
p.save()

rawDescription: user inheritance in django

description: User inheritance in django


code:
for tablename in cur.execute('SELECT name FROM sqlite_master WHERE type="table";'):
    if tablename[0].startswith('conn_'):
        execute_some_query_using_this_table()

rawDescription: Python SQLite3 How to extract specific tables only


code:
def load(filename):
    features = []
    with codecs.open(filename, 'rb',  'utf-8') as f:
        return f.readlines()

rawDescription: Python : how to speed up this file loading


rawDescription: Mongoengine query set to list conversion


code:
import sys
# Assume path to module is
# /path/to/recent/version/of/module.py
sys.path.insert(0,"/path/to/recent/version/of")
import module

rawDescription: python search paths order on Debian

description: Python search paths order on Debian


code:
s = 'abcdefgh'
[s[i:i+2] for i in range(0, len(s), 2)]

rawDescription: Splitting strings in python based on index


code:
import wx.animate

class TestFrame2( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Testing!", pos = wx.DefaultPosition, size = ( 300,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER )
        self.m_animCtrl1 = wx.animate.AnimationCtrl( self, wx.ID_ANY, wx.animate.NullAnimation, ( 40,40 ), ( -1,-1 ), wx.animate.AC_DEFAULT_STYLE )
        self.m_animCtrl1.LoadFile( u"img.GIF" )
        self.m_animCtrl1.Play()
        self.Layout()
        self.Show()
        self.Centre( wx.BOTH )

if __name__ == "__main__":
    App = wx.App()
    TestFrame2(None)
    App.MainLoop()

rawDescription: Can't play animation in wxPython

description: Can't play animation in wxPython


code:
import pickle
try:
    with open("curl-output.txt", "rb") as myfile:
        num = pickle.load(myfile)
except FileNotFoundError:
    num = 0

if num < 5:
    do_curl_stuff()
    num += 1
    with open("curl-output.txt", "wb") as myfile:
        pickle.dump(num, myfile)

rawDescription: Python conditional statement based on text file string


code:
for listing in listings:
    this_value = {
        'bedrooms': listing.findtext('bedrooms'),
        'bathrooms': listing.findtext('bathrooms'),
        'agency': listing.xpath('agency/name/text()')[0]
    }
    listings_info.append(this_value)

rawDescription: How can I use XPATH to add data of subtree to main tree  in Python/Django

description: Use XPATH to add data of subtree to main tree  in Python/Django


code:
x = int(input("What would you like x to be? "))
while x<0:
    print("Sorry, x must be positive. Please try again.")
    x = int(input("What would you like x to be? "))
y = int(input("What would you like y to be? "))
while y<0:
    print("Sorry, y must be positive. Please try again.")
    y = int(input("What would you like y to be? "))
z = int(input("What would you like z to be? "))
while z<0:
    print("Sorry, z must be positive. Please try again. ")
    z = int(input("What would you like z to be? "))

rawDescription: How to allow inputs above a certain number in python

description: Allow inputs above a certain number in python


code:
import numpy as np

with open(file1, "w") as f:
    f.write('2\n')
    np.savetxt(f, datafile, fmt)

rawDescription: How do I combine two files without overwriting any data in python?

description: Combine two files without overwriting any data in python


code:
def annotate(gen):
    prev_i, prev_val = 0, gen.next()
    for i, val in enumerate(gen, start=1):
        yield prev_i, prev_val
        prev_i, prev_val = i, val
    yield '-1', prev_val

rawDescription: Detect last iteration over dictionary.iteritems() in python


rawDescription: Pyserial read from serial port and write to C program


code:
import foo
foo.bar.append('baz')

rawDescription: Editing a global dictionary in python

description: Editing a global dictionary in python


code:
import os
os.environ.get('VIRTUAL_ENV')

rawDescription: Python: Is there any way how I can know under which virtualenv script is running?


code:
f.get.__closure__[0].cell_contents.value
f.get.__closure__[0].cell_contents.value = "some new value"

rawDescription: Strategy for Private Fields in Python

description: Strategy for Private Fields in Python


rawDescription: Sorting Items by Multiple Criteria

description: Sorting Items by Multiple Criteria


code:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
sample = 20
x=np.arange(sample)
y=10*np.sin(2*np.pi*x/20)

ax.plot(x,y)
ax.set_yticks(np.arange(min(y), max(y)+1, 1.0)) # setting the ticks
ax.set_xlabel('x')
ax.set_ylabel('y')
fig.show()

rawDescription: Set scale of axis in plot using matplotlib


code:
import argparse
import sys
import copy
import os

def split_list(lst,condition):
    current=[]
    out=[current]
    for arg in lst:
        current.append(arg)
        if(condition(arg)):
            current=[]
            out.append(current)

    return out

parser=argparse.ArgumentParser()
parser.add_argument('-m',action='store')
parser.add_argument('-r',default='0',action='store')
#pieces=split_list(sys.argv[1:],os.path.isfile)
pieces=split_list(sys.argv[1:],lambda x: x in ('foo','bar','baz','quux'))
options={} #use collections.OrderedDict if order matters -- or some more suitable data structure.
default=argparse.Namespace()
for args in pieces:
    if(not args):
        continue
    ns=copy.deepcopy(default)
    default=parser.parse_args(args[:-1],namespace=ns)
    options[args[-1]]=default

print (options)

rawDescription: Can argparse associate positional arguments with named arguments?


code:
import os
winpath = os.environ['WINDIR'] + "\\System\\"
inifile = open(winpath + filename)

rawDescription: Get windows/system folder location in Python


code:
def censor(fileName):
    output_content = ""
    with open(fileName, "r") as input_file:
        with open("censored.txt", "w") as output_file:
            output_content = ""
            for line in input_file:
                output_content += ' '.join([word if len(word) != 4 else "****" for word in line.split(" ")])
            output_file.write(output_content)

rawDescription: How to open a file to write to, write new information, and then close the file?

description: Open a file to write to, write new information, and then close the file


code:
def validateFirstname(firstname):
    def validchar(c):
        return c.isalpha() or c.isspace() or (c in "'-")
    total = sum(1 for c in firstname if validchar(c))
    return 3 <= total <= 20 and total == len(firstname)

rawDescription: Evaluating requirements in python using string.isalpha, return always True


code:
#app1/routing.py

from channels.routing import route
from . import consumers

post_websocket = [
    route("websocket.connect", consumers.websocket_connect),
    route("websocket.disconnect", consumers.websocket_disconnect)
]

vote_websocket = [
    route("websocket.connect", consumers.websocket_voteconnect),
    route("websocket.receive", consumers.ws_updatevotes),
    route("websocket.disconnect", consumers.websocket_votedisconnect)
]

# myproject/routing.py
from channels import include

channel_routing = [
    include("app1.routing.post_websocket", path=r"^/app1/post/notification"),
    include("app1.routing.vote_websocket", path=r"^/app1/vote/notification"),
]

rawDescription: Multiple websocket.receive in django channels


code:
class MyModelForm(ModelForm):
    def is_valid(self):
        # Call super's is_valid to populate cleaned_data and do basic field validation
        valid = super(MyModelForm, self).is_valid()
        if not valid:
            return False

        serializer = MyModelSerializer(data=self.cleaned_data)
        return serializer.is_valid()

rawDescription: django rest framework serializers and django forms

description: Django rest framework serializers and django forms


code:
def get_feature_infos(file_path, feature_name):
    technical_name = []
    possible_variables = []
    possible_names = []
    data = []
    with open(file_path, "r") as commands_library:
        for line in commands_library:
            if feature_name in line:
                technical_name.append((line.split(",")[0]).split(":")[1])

            data = (line.split(","))
            data.pop(0)

            for shortData in data:
                possible_variables.append(shortData.split(":")[0])
                possible_names.append(shortData.split(":")[1])

        print ("   Technical name: ", technical_name[0])
        print ("   Possible variables: ", possible_variables)
        print ("   Possible names: ", possible_names)

rawDescription: spliting string from a line and appending in a list in python 3

description: Spliting string from a line and appending in a list in python 3


rawDescription: Python splitting string by parentheses

description: Python splitting string by parentheses


code:
doubles = ( Pizza
     .objects
     .annotate(num_toppings=Count('toppings'))
     .filter(num_toppings=2)
    )

rawDescription: Django filter by group count

description: Django filter by group count


code:
@property
def in_progress(self):
    return self.expiration_date > timezone.now()

rawDescription: django check post expiry function

description: Django check post expiry function


code:
class StaticGetter(object):
    def __init__(self, attr):
        self.attr = attr
    def __get__(self, instance, owner):
        # owner is the class, your getter code here
        return getattr(owner, attr)

class Test(object):
    __staticField = 0
    staticField = StaticGetter('_Test__staticField')

rawDescription: how to define IronPython static property?

description: Define IronPython static property


rawDescription: Differentiating a sympy function with an unknown number of variables


code:
h.Granule[0].soma.push()
h.psection()

rawDescription: Easy way to list NEURON section properties/information?


code:
for r1,r2 in zip(p1,p2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    plt.text(r1.get_x()+r1.get_width()/2., h1+h2, '%s'% (h1+h2), ha = 'center', va='bottom')

rawDescription: Displaying totals above stacked bars in barchart: matplotlib.pyplot


rawDescription: The fastest way to structure data in JSON for python


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.rootPanel = wx.Panel(self)

        innerPanel = wx.Panel(self.rootPanel,-1, size=(150,150), style=wx.ALIGN_CENTER)
        innerPanel.SetBackgroundColour('WHITE')
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        innerBox = wx.BoxSizer(wx.VERTICAL)

        # I want this line visible in the CENTRE of the inner panel
        txt = wx.StaticText(innerPanel, id=-1, label="TEXT HERE",style=wx.ALIGN_CENTER, name="")
        innerBox.AddSpacer((150,75))
        innerBox.Add(txt, 0, wx.CENTER)
        innerBox.AddSpacer((150,75))
        innerPanel.SetSizer(innerBox)

        hbox.Add(innerPanel, 0, wx.ALL|wx.ALIGN_CENTER)
        vbox.Add(hbox, 1, wx.ALL|wx.ALIGN_CENTER, 5)

        self.rootPanel.SetSizer(vbox)
        vbox.Fit(self)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'wxBoxSizer.py')
        frame.Show(True)
        frame.Center()
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: wxpython: centering text within a panel within a sizer

description: Wxpython: centering text within a panel within a sizer


code:
from collections import namedtuple
Array = namedtuple('Array', ['data', 'description'])
A = Array(np.array([[1,2,3],[4,5,6]]), "Holds all the data from experiment 1. Each row contains an intensity measurement with the following columns: time [s], intensity [W/m^2], error [%].")
A.data
A.description

rawDescription: Add a description string to a numpy array


code:
#!/usr/bin/env python

import re

# This is the input from your question
INPUT_TEXT = '''\
    rep_origin      607..1720
                    /label=Rep
    Region          2643..5020
                    /label="region"
                    extra_info and stuff'''

# A regular expression that matches the start of a section. A section
# start is a line that has 4 spaces before the first non-space
# character.
match_section_start = re.compile(r'^    [^ ]').match

def parse(text):
    sections = []
    section_lines = None

    def append_section_if_lines():
        if section_lines:
            sections.append(section_lines)

    for line in text.split('\n'):
        if match_section_start(line):
            # We've found the start of a new section. Unless this is
            # the first section, save the previous section.
            append_section_if_lines()
            section_lines = []
        section_lines.append(line.strip())

    # Save the last section.
    append_section_if_lines()

    return sections

sections = parse(INPUT_TEXT)
print(sections)

rawDescription: fuzzy string split in Python 2.x

description: Fuzzy string split in Python 2.x


rawDescription: When removing an item from a list in a list of objects, that item is also removed from the other objects' list


code:
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash

class GameResource(ModelResource):
    class Meta:
         queryset = Game.objects.all()
         resource_name = 'store'

    def prepend_urls(self):
        """ Add the following array of urls to the GameResource base urls """
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/start%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('start'), name="api_game_start"),
        ]

    def start(self, request, **kwargs):
         """ proxy for the game.start method """

         # you can do a method check to avoid bad requests
         self.method_check(request, allowed=['get'])

         # create a basic bundle object for self.get_cached_obj_get.
         basic_bundle = self.build_bundle(request=request)

         # using the primary key defined in the url, obtain the game
         game = self.cached_obj_get(
             bundle=basic_bundle,
             **self.remove_api_resource_names(kwargs))

         # Return what the method output, tastypie will handle the serialization
         return self.create_response(request, game.start())

rawDescription: Exposing model method with Tastypie

description: Exposing model method with Tastypie


code:
corr_val=0.01
df2 = df1.corr().unstack().reset_index()
df2[df2[0]>corr_val]

rawDescription: what is the best method to extract highly correlated vaiables within the given threshold

description: What is the best method to extract highly correlated vaiables within the given threshold


code:
[easy_install]
allow_hosts = local.mirror

rawDescription: Getting setuptools to ignore PyPI repository


code:
view.run_command("insert_snippet", {"name": "Packages/etc/my.sublime-snippet"})
view.run_command("insert", {"characters": "field 1"})
view.run_command("next_field")
view.run_command("insert", {"characters": "field 2"})
view.run_command("next_field")
view.run_command("insert", {"characters": "field 3"})

rawDescription: Populate snippets from a list of values in Sublime Text 2


code:
def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        return inventedfunction(list2)
    else:
        return list2

rawDescription: python tail recursive function doesn't return

description: Python tail recursive function doesn't return


code:
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
   # MY PROFILE
   url(r'^$',
       login_required(MyProfileDetailView.as_view()),
       name="my_profile"
   )
)

rawDescription: Django allauth allowed urls

description: Django allauth allowed urls


code:
from collections import namedtuple
namedtuple('foo', 'bar baz', verbose=True)

description: Python collections.namedtuple() confusion


code:
from multiprocessing import Process, Manager
import random

class MyProc(Process):
    def __init__(self, B, length):
        Process.__init__(self)
        self.B = B
        self.length = length

    def run(self):
        i = random.randint(0, self.length-1)
        self.B.append(i)

if __name__ == '__main__':
    procs = []
    M = Manager()
    a = range(15)
    b = M.list()
    print('A: {0}'.format(a))
    print('sum(A) = {0}'.format(sum(a)))

    for i in range(100):
        procs.append(MyProc(b, len(a)))

    map(lambda x: x.start(), procs)
    map(lambda x: x.join(), procs)

    for i in b:
        a[i] = a[i] + 1

    print('A: {0}'.format(a))
    print('sum(A) = {0}'.format(sum(a)))

rawDescription: python multiprocessing.Process.Manager not producing consistent results?

description: Python multiprocessing.Process.Manager not producing consistent results


code: lines = [i for i in open(file_path) if i[:-1]]

rawDescription: one liner for removing blank lines from a file in python?

description: One liner for removing blank lines from a file in python


code:
__doc__ = """
>>> L = []
>>> if True:
...    append_to(L) # doctest: +IGNORE_RESULT
>>> L
[1]
""".replace('+IGNORE_RESULT', '+ELLIPSIS\n<...>')

def append_to(L):
    L.append(1)
    class A(object):
        pass
    return A()

rawDescription: Doctests: How to suppress/ignore output?

description: Doctests: How to suppress/ignore output


code:
import urllib2
r = urllib2.urlopen("https://howsmyssl.com/").read()
self.response.write(r)

rawDescription: Does appengine urllib use SSLv3? TLS?

description: Does appengine urllib use SSLv3? TLS


rawDescription: Jython: How to remove '\n' from the end of a string being read in


code: from wsgiref.simple_server import make_server

rawDescription: ImportError: No module named wsgi.simple_server


code:
import re
s = "galley/files/tew/tewt/tweqt/"
m = re.sub(r'^.+/+([^/]+/$)', r'\1', s)
m

rawDescription: RE match fail in python, confuse with the result on regex101


code:
class ChildFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, evt):
        process_whatever_you_want()
        self.Destroy()

rawDescription: wxPython equivalent to Tkinter's protocol attribute?

description: WxPython equivalent to Tkinter's protocol attribute


code:
from intervaltree import IntervalTree

tree = IntervalTree.from_tuples(zip(A['from_timestamp'], A['to_timestamp'] + 0.1))
B['corrupted_flag'] = B['actual_timestamp'].map(lambda x: tree.overlaps(x))

rawDescription: How to flag the most efficient way a column of a dataframe by values of another dataframe's in python/pandas?

description: Flag the most efficient way a column of a dataframe by values of another dataframe's in python/pandas


code:
def second_smallest(lst):
    first = second = float("inf")
    for num in lst:
        if num < first:
            second, first = first, num
        elif first < num < second:
            second = num
    return second

rawDescription: Finding the second smallest number using loops in python


rawDescription: Making a query for all objects that don't have `None` for a certain field


code:
# Original values
oldnames = ["apple", "banana", "sheep"]

# Conversion table
translate = {
    "apple": "monkey",
    "banana": "monkey",
    "sheep": "lion",
}

# For each oldname, get the translated value
newnames = [translate.get(x) for x in oldnames]

rawDescription: pythonic way of changing old names by new names

description: Pythonic way of changing old names by new names


code:
with tempfile.NamedTemporaryFile() as f:
    # file gone now from the filesystem
    # but f still holds a reference so it still exists and uses space (see /prof<pid>/fd)
    # open it again (will not work on windows)
    x = np.memmap(f.name, dtype=np.float64, mode='w+', shape=(3,4))
# f reference is gone now but x still has a reference
del x
# now all references are gone and the file is properly deleted

rawDescription: In Python, is it possible to overload Numpy's memmap to delete itself when the memmap object is no longer referenced?


code:
import sys
from queue import Queue, Empty

class QueuedFile:
   def __init__(self, queue):
       self.queue = queue
   def write(self, text):
       self.queue.put(text)
   def flush(self):
       pass # noop

q = Queue()
sys.stdout = sys.stderr = QueuedFile(q)

# print from multiple threads while accepting input...

# print queued output
while True:
    try:
        sys.__stdout__.write(q.get(block=False))
    except Empty:
        break # no more output

rawDescription: Python: Print Lines without Input Being broken up


code:
CACHES = {
    'default': {
        'BACKEND': 'redis_cache.RedisCache',
        'LOCATION': '/var/run/redis/redis.sock',
    },
}

rawDescription: Redis cache not working with django

description: Redis cache not working with django


code:
import sys

def myMethod():
    i = 0
    while (i<1000000):
        i = i+1
        output_str = str(i) + "\n"
        sys.stdout.write(output_str)  # same as print
        sys.stdout.flush()

rawDescription: How can I print to console while the program is running in python?

description: Print to console while the program is running in python


rawDescription: Python unicode normalization: is it correct to translate u'\xb4' to u' \u0301'


code:
a = range(4)
b = a
id(a)
id(b)
a=1
b=a
id(a)
id(b)
b=2
id(a)
id(b)

rawDescription: Difference between assignment of a variable to a number and lists of numbers in Python


code:
area_func = {'triangle': triangle, 'square': square, 'rectangle': rectangle,
             'paralelogram': paralelogram, 'circle': circle, 'trapezoid': trapezoid,
             'sphere': sphere}

while True:
    shape = input('What shape do you want to calculate the area of ("stop" to end)?')
    if shape == 'stop':
        break
    try:
        area_func[shape]()
    except KeyError:
        print("I don't recognise that shape.")
        continue

rawDescription: Asking the user what kind of function they want


code:
county_tax_rate = 0.02
state_tax_rate = 0.04
tax_rate = county_tax_rate + state_tax_rate

item_price = float(input("Please enter the price of your item: "))
item_price = int(100 * item_price) # Item price in cents
total_price = item_price * (1 + tax_rate) # Total price in cents

print("Your Total Sales Cost is ${:0.2f}".format(total_price / 100.0))
print("Your Purchase Amount was ${:0.2f}".format(item_price / 100.0))
print("Your County Tax Rate was {}%".format(int(county_tax_rate * 100)))
print("Your State Tax Rate was {}%".format(int(state_tax_rate * 100)))
print("Your Total Tax Rate was {}%".format(int(tax_rate * 100)))

rawDescription: Python Sales Tax Program with 2 Decimal Places, Money


code:
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

rawDescription: How to sort a list of objects in Python, based on an attribute of the objects?

description: Sort a list of objects in Python, based on an attribute of the objects


code:
class read_conf_values(object):
    def __init__(self):
        parser = ConfigParser.ConfigParser()
        parser.read('configuration.conf')
        self.a = parser.get('asection', 'a')

rawDescription: Refreshing or re-running a class in Python 2.7


code:
def spawnSugar(spawnPoint) :
    global sugarList,mapDict
    mapDict[spawnPoint] = 1
    sugarList.append(spawnPoint)

def moveAll() :
    global mapDict,sugarList
    sugarListTmp = sugarList
    sugarList = []
    for sugarX,sugarY in sugarListTmp :
            # m stands for the vertical movement (1 for down, 0 for staying still)
            # k stands for horizontal movement (-1 for left, +1 for right)
            m = 1
            if mapDict[( sugarX , (sugarY+1)%mapSizeY )]==0:
            # checks whether the coordinate below this particle is empty
                k = randint( -(mapDict[((sugarX-1)%mapSizeX , (sugarY+1)%mapSizeY)]==0) , mapDict[((sugarX+1)%mapSizeX , (sugarY+1)%mapSizeY)]==0 )
                # If it is empty; randomly chooses 1 of the 3 coordinates below the particle (1 of them is just below and the other 2 are diagonally below)
            elif mapDict[((sugarX-1)%mapSizeX,(sugarY+1)%mapSizeY)]==0 and mapDict[((sugarX-1)%mapSizeX,(sugarY)%mapSizeY)]==0 and mapDict[((sugarX+1)%mapSizeX,(sugarY+1)%mapSizeY)]==0 and mapDict[((sugarX+1)%mapSizeX,(sugarY)%mapSizeY)]==0:
            # If the coordinate below the particle is not empty but other 2 diagonals are empty
                k = -1 if randint(0,1) else 1 #chooses 1 of them randomly

            else : # If at most 1 of these 2 diagonal coordinates are empty
                k = (mapDict[((sugarX+1)%mapSizeX,(sugarY+1)%mapSizeY)]==0 and mapDict[((sugarX+1)%mapSizeX,(sugarY)%mapSizeY)]==0) or -(mapDict[((sugarX-1)%mapSizeX,(sugarY+1)%mapSizeY)]==0 and mapDict[((sugarX-1)%mapSizeX,(sugarY)%mapSizeY)]==0)
                if not k: # If none of them are empty
                    m = 0
            mapDict[(sugarX,sugarY)] = 0
            mapDict[((sugarX+k)%mapSizeX,(sugarY+m)%mapSizeY)] = 1
            sugarList.append(((sugarX+k)%mapSizeX,(sugarY+m)%mapSizeY))

# Values to assign before entering the main loop
mapDict = {}
sugarList = []
for x in range(mapSizeX):
    for y in range(mapSizeY):
        mapDict[(x,y)] = 0

rawDescription: Fluid-like characteristics with Pygame

description: Fluid-like characteristics with Pygame


code:
import pylab as plt
a=[0,1]
b=[0,1]
plt.plot(a,b,'g',linewidth=3.5, label = 'a')
plt.rc('text', usetex=True)
plt.legend(labelspacing = 1.0,loc=1,prop={'size':40})

plt.text(0.45,-0.08,'a',fontsize=50)
plt.text(0.53,-0.08, 'N',fontsize = 20)

rawDescription: Multiple fontsize in same label Matplotlib


code:
from django.dispatch import receiver
from django.db.models.signals import pre_save

@receiver(pre_save, sender=Item)
def iter_pre_save_handler(sender, instance, **kwargs):
    if not instance.pk:
        instance.slug = slugify(instance.name)

rawDescription: Django: Slugify Post Data

description: Django: Slugify Post Data


rawDescription: PYTHON: Converting list of tuples into a dictionary


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

data = np.genfromtxt('beta_tracking.csv', delimiter=' ')

f=data[:,0]
x=data[:,1]
y=data[:,2]
z=data[:,3]

k=range(1,11)
for j in k:
    g=list(compress(x, (abs(i)==j for i in f)))
    h=list(compress(y, (abs(i)==j for i in f)))
    FigList = [ ]
    FigList.append(plt.figure())
    ax = FigList[-1].add_subplot(1,1,1)
    ax.plot(g,h,',')
    for i in plt.get_fignums():
          plt.figure(i)
          plt.savefig('plots/figure%d.png' % i)

rawDescription: plot from a large data set into several figures

description: Plot from a large data set into several figures


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

cos = np.cos
pi = np.pi

# This is not necessary if `text.usetex : True` is already set in `matplotlibrc`.
mpl.rc('text', usetex = True)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
t = np.linspace(0.0, 2*pi, 100)
s = cos(t)
plt.plot(t, s)

plt.xticks([0, pi/2, pi, 3*pi/2, 2*pi],
           ['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
plt.show()

rawDescription: Mark ticks in latex in matplotlib

description: Mark ticks in latex in matplotlib


code:
d = {}
with open('adat.txt') as f:
    for line in f:
        words = line.split()
        try:
            price = int(words[-1])
            name = ' '.join(words[:-1])
            d[name] = price
        except (ValueError, IndexError):
            # line doesn't end in price (int() raised ValueError)
            # or is empty (words[-1] raised IndexError)
            pass

for key, value in d.items():
    print(key)
    print(value)

rawDescription: python - auction script (input from file to dictionary)

description: Python - auction script (input from file to dictionary)


rawDescription: Manipulating json files python

description: Manipulating json files python


code:
try:
    profile = request.user.get_profile()
except UserProfile.DoesNotExist:
    # If DoesNotExists, Create an empty one
    profile = UserProfile(user=request.user)
    profile.save()

rawDescription: Set and use flags against a users profile model in Django


code: import someapp

rawDescription: django problem - install the xxx package by putting it on your python path?

description: Django problem - install the xxx package by putting it on your python path


code:
a = np.arange(27)  # some 1-D numpy array
a.reshape(-1, 3)

rawDescription: Python : simple array manipulation with Numpy


code:
def changeToUpperCase(text):
    new_text = ""
    for i in text:
        i = ord(i) - 32
        new_text = new_text + chr(i)
    return new_text

rawDescription: Changing to uppercase letters using ASCII


rawDescription: Making the `nosetests` script select folder by Python version


code:
import numpy as np

# create example file
np.arange(256).astype('uint8').tofile('uint8_file.bin')

# read example file and convert to uint16
u1 = np.fromfile('uint8_file.bin', 'uint8')
u2 = u1.astype('uint16')
u2 *= 257  # scale to full 16 bit range
u2.tofile('uint16_file.bin')

rawDescription: convert raw binary 8 bit unsigned file to 16 bit unsigned with the python imaging library

description: Convert raw binary 8 bit unsigned file to 16 bit unsigned with the python imaging library


code:
import datetime
path = r'C:\soa11g\New\abc_%s.zip' % datetime.datetime.now().strftime('%d%m%Y')
connect('weblogic','welcome','t3://localhost:7001')
exportMetadata(application='soa-infra', server='AdminServer',toLocation=path, docs='/**')
exit()

rawDescription: How to set file name as date in command prompt

description: Set file name as date in command prompt


code:
from string import Formatter
[i[1] for i in Formatter().parse('Hello {1} {foo}')]

rawDescription: Get keys from template

description: Get keys from template


code:
import re
s = "key1: value | key2: value"
re.findall(r'([^\s|:]+):\s*([^\s|:]+)', s)

rawDescription: Regex pattern to retrieve key and value

description: Regex pattern to retrieve key and value


code:
from django.db.models import F

low_wallets = Wallet.objects.filter(
    low_credits_threshold__gt=F('packaged_credits')+F('purchased_credits')
)

rawDescription: How do i compare the sum of two fields to another field on the same model in Django

description: Compare the sum of two fields to another field on the same model in Django


code: datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(-3739996800000/1000))

rawDescription: how to create datetime from a negative epoch in Python

description: Create datetime from a negative epoch in Python


code:
def arePermsEqualParity(perm0, perm1):
    """Check if 2 permutations are of equal parity.

    Assume that both permutation lists are of equal length
    and have the same elements. No need to check for these
    conditions.
    """
    perm1 = perm1[:] ## copy this list so we don't mutate the original

    transCount = 0
    for loc in range(len(perm0) - 1):                         # Do (len - 1) transpositions
        p0 = perm0[loc]
        p1 = perm1[loc]
        if p0 != p1:
            sloc = perm1[loc:].index(p0)+loc          # Find position in perm1
            perm1[loc], perm1[sloc] = p0, p1          # Swap in perm1
            transCount += 1

    # Even number of transpositions means equal parity
    if (transCount % 2) == 0:
        return True
    else:
        return False

rawDescription: How to check if permutations have equal parity?

description: Check if permutations have equal parity


code:
as_integer = getattr(conn.r, 'as.integer')
conn.r.sapply(conn.ref.List, as_integer)
Out[8]: array([1, 2, 3], dtype=int32)

rawDescription: How to call an R function with a dot in its name by pyRserve?

description: Call an R function with a dot in its name by pyRserve


code:
rng = Range('A1').vertical.last_cell
...
Range((rng.row + 1, rng.column)).value = participant_list

rawDescription: Xlwings - Referencing saved range and appending additional values


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

data = np.random.randn(82)
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray')

# Set the ticks to be at the edges of the bins.
ax.set_xticks(bins)
# Set the xaxis's tick labels to be formatted with 1 decimal place...
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

# Change the colors of bars at the edges...
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
    if rightside < twentyfifth:
        patch.set_facecolor('green')
    elif leftside > seventyfifth:
        patch.set_facecolor('red')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -18), textcoords='offset points', va='top', ha='center')

    # Label the percentages
    percent = '%0.0f%%' % (100 * float(count) / counts.sum())
    ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.15)
plt.show()

rawDescription: Matplotlib - label each bin

description: Matplotlib - label each bin


rawDescription: Python Error : 'RPCProxy' object is not iterable


code:
i=0
new_list=[]
while i<len(data_list):
  new_list.append(data_list[i:i+3])
  i+=3

rawDescription: Turning a list into nested lists in python


code:
set(['stackoverflow', 'serverfault']).issubset(sites) # ==> True

set(['stackoverflow', 'google']).issubset(sites) # ==> False

rawDescription: How do you check the presence of many keys in a Python dictinary?

description: Check the presence of many keys in a Python dictinary


code:
from django.db.models.signals import post_save

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text='Some help.')
    entity = models.ForeignKey(CancellationEntity)

    @classmethod
    def cancellation_occurred (sender, instance, created, raw):
        # grab the current instance of Activity
        self = instance.activity_set.all()[0]
        # do something
    ...

class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

post_save.connect(Activity.cancellation_occurred, sender=Cancellation)

rawDescription: In Django how do I notify a parent when a child is saved in a foreign key relationship?


code:
def write_bmp_to_dc_rotated( dc, bitmap, angle ):
    '''
    Rotate a bitmap and write it to the supplied device context.
    '''
    img = bitmap.ConvertToImage()
    img_centre = wx.Point( img.GetWidth()/2, img.GetHeight()/2 )
    img = img.Rotate( angle, img_centre )
    dc.WriteBitmap( img.ConvertToBitmap(), 0, 0 )

rawDescription: How can I draw a bitmap rotated in wxPython?

description: Draw a bitmap rotated in wxPython


code:
from Queue import Queue
import threading

class workingthread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._queue = Queue()

    def run(self):
        while True:

            item = self._queue.get(block=True)
            if item is None:
                return

            name, message = item
            chat = skype.CreateChatWith(name)
            chat.SendMessage(message)

    def processOne(self, data):
        self._queue.put_nowait(data)

    def stop(self):
        self._queue.put(None)

rawDescription: Multithreading vs Multiprocessing

description: Multithreading vs Multiprocessing


code:
map(max, abs(a[2]-a) )
np.abs(a[2] - a).max(axis=1)

rawDescription: Need faster python code for calculating sample entropy


code:
import re
...
pattern = re.compile("|".join(searchlist))
with open("your_file") as f:
    for line in f:
         if not re.search(pattern, line):
                print(line)

rawDescription: FIlter a csv file with a list of search terms


code:
import re
s = "abc('abt')"
regex = re.compile("\('(.*)'\)")
m = re.search(regex, s)
m.group(1)

rawDescription: reg to extract content from parenthese

description: Reg to extract content from parenthese


code: [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]

rawDescription: How to list only top level directories in Python?

description: List only top level directories in Python


code:
import sympy

M = sympy.Matrix(3, 2, lambda i,j:sympy.var('M_%d%d' % (i+1,j+1)))

rawDescription: Automatically populating matrix elements in SymPy


code:
a
b
c = a & b
c

rawDescription: Finding the overlap of numpy images

description: Finding the overlap of numpy images


code:
td = Threaded_worker()
td.setDaemon(True)  # Shouldn't do that.
td.start()

rawDescription: Consuming rabbitmq queue from inside python threads


code:
from suds.client      import Client
from suds.sax.element import Element

client = Client("http://example.com/example.wsdl")

# <tns:h xmlns:tns="http://example2.com/example2/">v</tns:h>
tns = ("tns", "http://example2.com/example2/")
h = Element('h', ns=tns).setText('v')
client.set_options(soapheaders=h)
#
s = client.service.Op(data)

rawDescription: python soappy add header

description: Python soappy add header


code:
np.random.seed(0)
s = np.random.randn(10)
s
np.random.seed(0)
s

rawDescription: numpy random not working with seed

description: Numpy random not working with seed


code:
df = pd.read_fwf(StringIO(data),widths=[5,12,8,8,6],header=0,names=['idx','date','time','datetime','year'])
df['date'] = df['date'].fillna('')
df
df.loc[df.date=='','date'] = np.nan
df
df['date']  = df['date'].ffill()
df

rawDescription: Python Pandas - Fill down text value in column where following cells are blank


code:
import math
def format_percentage(x, precision=3):
    return ("%%.%df%%%%" % (precision - min(0,math.log10(100-x)))) % x

rawDescription: Percentage with variable precision

description: Percentage with variable precision


code:
def interpolate_pixels_along_line(x0, y0, x1, y1):
    """Uses Xiaolin Wu's line algorithm to interpolate all of the pixels along a
    straight line, given two points (x0, y0) and (x1, y1)

    Wikipedia article containing pseudo code that function was based off of:
        http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
    """
    pixels = []
    steep = abs(y1 - y0) > abs(x1 - x0)

    # Ensure that the path to be interpolated is shallow and from left to right
    if steep:
        t = x0
        x0 = y0
        y0 = t

        t = x1
        x1 = y1
        y1 = t

    if x0 > x1:
        t = x0
        x0 = x1
        x1 = t

        t = y0
        y0 = y1
        y1 = t

    dx = x1 - x0
    dy = y1 - y0
    gradient = dy / dx  # slope

    # Get the first given coordinate and add it to the return list
    x_end = round(x0)
    y_end = y0 + (gradient * (x_end - x0))
    xpxl0 = x_end
    ypxl0 = round(y_end)
    if steep:
        pixels.extend([(ypxl0, xpxl0), (ypxl0 + 1, xpxl0)])
    else:
        pixels.extend([(xpxl0, ypxl0), (xpxl0, ypxl0 + 1)])

    interpolated_y = y_end + gradient

    # Get the second given coordinate to give the main loop a range
    x_end = round(x1)
    y_end = y1 + (gradient * (x_end - x1))
    xpxl1 = x_end
    ypxl1 = round(y_end)

    # Loop between the first x coordinate and the second x coordinate, interpolating the y coordinates
    for x in range(xpxl0 + 1, xpxl1):
        if steep:
            pixels.extend([(math.floor(interpolated_y), x), (math.floor(interpolated_y) + 1, x)])

        else:
            pixels.extend([(x, math.floor(interpolated_y)), (x, math.floor(interpolated_y) + 1)])

        interpolated_y += gradient

    # Add the second given coordinate to the given list
    if steep:
        pixels.extend([(ypxl1, xpxl1), (ypxl1 + 1, xpxl1)])
    else:
        pixels.extend([(xpxl1, ypxl1), (xpxl1, ypxl1 + 1)])

    return pixels

rawDescription: Python3 Pillow Get all pixels on a line

description: Python3 Pillow Get all pixels on a line


code:
data = open(...).readlines()
dct = {line.split(":")[0]:line.split(":")[1] for line in data}

rawDescription: read text file (colon separated words) and get a dictionary using python

description: Read text file (colon separated words) and get a dictionary using python


rawDescription: Copy list and append an element in one line


code:
class Foo(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = accuracy(value)

foo = Foo()

f = 1.5
foo.x = f     # set foo._x to accuracy(f)
print(foo.x)  # prints foo._x

rawDescription: redefine behaviour of float

description: Redefine behaviour of float


rawDescription: How to avoiding skipped months in Python pivot table when all entires in table are 0

description: Avoiding skipped months in Python pivot table when all entires in table are 0


code:
import itertools

[ ''.join(x) for x in itertools.product(['a','b'],repeat=3) ]

['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']

rawDescription: python list of all possible lists given multiple variables

description: Python list of all possible lists given multiple variables


code:
for x in 'bcdef':
    t = array.array('B', map( operator.xor, mydict['a'], mydict[x] ) )
    f1 = open(''.join('a',x),'wb')
    t.tofile(f1)
    f1.close()

rawDescription: get an array variable in python

description: Get an array variable in python


code:
class Foo(object):
    def ff(self):
        self.var_1, self.var_2, self.var_3 = ff()
    def sf(self):
        self.var_4, self.var_5 = sf(self.var_1, self.var_2)
    def tf(self):
        self.var_6, self.var_7, self.var_8, self.var_9 = tf(self.var_2, self.var_4, self.var_5)
    def plot(self):
        mp(self.var_1, self.var_2, self.var_3,
           self.var_5, self.var_6, self.var_7, self.var_8, self.var_9)

foo = Foo()
foo.ff()
foo.sf()
foo.tf()
foo.plot()

rawDescription: Pass variables between functions vs global variables


code:
max_int64 = 0xFFFFFFFFFFFFFFFF
packed    = struct.pack('>QQ', (u.int >> 64) & max_int64, u.int & max_int64)
# unpack
a, b     = struct.unpack('>QQ', packed)
unpacked = (a << 64) | b

assert u.int == unpacked

rawDescription: How to pack a UUID into a struct in Python?

description: Pack a UUID into a struct in Python


code:
def foo(x):
    return x*100

a = {'key1': 'value1', 'key2': 42, 'key3': lambda: foo(20)}
a
{k: v() if callable(v) else v for k,v in a.iteritems()}

rawDescription: How can I process a python dictionary with callables?

description: Process a python dictionary with callables


code:
#!/usr/bin/python
#
# Description: it works like the input -thing in Tex,
# you can fetch outside executable code, data or anything you like.
# Sorry I don't know precisely how input(things) works, maybe misusing terms
# or exaggerating.
#
# The reason why I wanted input -style thing is because I wanted to use more
# Python to write my lab-reports. Now, I don't need to mess data with
# executions and evalutions and data can be in clean files.

#TRIAL 1: Execution and Evaluation not from a file

executeMe="print('hello'); a = 'If you see me, it works'";

exec( executeMe )
print(a);

#TRIAL 2: printing file content
#
# and now with files
#
# $ cat IwillPrint007fromFile
# 007

f = open('./IwillPrint007fromFile', 'r');
msg = f.read()

print("If 007 == " + msg + " it works!");

# TRIAL 3: Evaluation from a file
#
# $cat IwillEvaluateSthing.py
# #!/usr/bin/python
# #
# # Description:
#
#
# evaluateMe = "If you see me again, you are breaking the rules of Sky."

f = open('./IwillEvaluateSthing.py', 'r');
exec(f.read());
print(evaluateMe);

rawDescription: Python: how to input python-code part like \input in Tex?


code:
#!/usr/bin/env python
from subprocess import check_call

check_call(['mocha-phantomjs', 'static/js/tests/headless.html'])

rawDescription: mocha-phantomjs output not shown when run with Python subprocess.check_output

description: Mocha-phantomjs output not shown when run with Python subprocess.check_output


code:
from logging import getLogger
loggers = [app.logger, getLogger('sqlalchemy'),
           getLogger('otherlibrary')]
for logger in loggers:
    logger.addHandler(mail_handler)
    logger.addHandler(file_handler)

rawDescription: How to see the debug messages included in third-party modules of flask?

description: See the debug messages included in third-party modules of flask


code:
from suds.plugin import MessagePlugin

class LogPlugin(MessagePlugin):
  def sending(self, context):
    print(str(context.envelope))
  def received(self, context):
    print(str(context.reply))

client = Client("http://localhost/wsdl.wsdl", plugins=[LogPlugin()])

rawDescription: How can I inspect what SUDs is generating/receiving in "sudo 0.4.1 jurko 5" and newer?

description: Inspect what SUDs is generating/receiving in "sudo 0.4.1 jurko 5" and newer


code:
def update_docs(resource, request, payload):
    """ do your stuff here """
    pass
app = Eve()
app.on_post_POST += udpate_docs
app.run()

rawDescription: python-eve hook after document is inserted

description: Python-eve hook after document is inserted


code:
from pgmagick import Image

img = Image('CB_TM432.jp2') # Input Image
img.write('CB_TM432.jpeg')  # Output Image

rawDescription: How to convert a JPEG2000 to JPEG in Python?

description: Convert a JPEG2000 to JPEG in Python


code:
import gtk

win = gtk.Window()
win.connect("destroy", gtk.main_quit)

btn = gtk.Button("test")

#make a gdk.color for red
map = btn.get_colormap()
color = map.alloc_color("red")

#copy the current style and replace the background
style = btn.get_style().copy()
style.bg[gtk.STATE_NORMAL] = color

#set the button's style to the one you created
btn.set_style(style)

win.add(btn)
win.show_all()

gtk.main()

rawDescription: GTK: create a colored regular button

description: GTK: create a colored regular button


code:
from nose_parameterized import parameterized
import urllib2

urls = ['http://www.google.com', 'http://www.yahoo.com']

@parameterized(urls)
def test_add(url):
    a = urllib2.urlopen(url).read()

    b = 2 + urls.index(url)
    c = 3 + urls.index(url)
    assert a+str(b) == str(c)

rawDescription: multithreaded urllib2 freezes on nose framework

description: Multithreaded urllib2 freezes on nose framework


code:
import subprocess
subprocess.Popen("./Do_Regr.sh -i Testlist_Regression.in -m 135.24.237.167 -g",shell=True)

rawDescription: Bash script in Python os.system

description: Bash script in Python os.system


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

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

# Plot some random data
values = np.random.rand(4,1);
graph_1, = ax.plot(values, label='original curve')
graph_2, = ax.plot([], marker='o')

# Keep track of x/y coordinates
xcoords = []
ycoords = []

def onclick(event):
    xcoords.append(event.xdata)
    ycoords.append(event.ydata)

    # Update plotted coordinates
    graph_2.set_xdata(xcoords)
    graph_2.set_ydata(ycoords)

    # Refresh the plot
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

rawDescription: matplotlib onclick event repeating

description: Matplotlib onclick event repeating


code:
import plotly.plotly as py
url = py.plot(fig, filename='stacked-bar')

rawDescription: plot.ly python graph url

description: Plot.ly python graph url


rawDescription: How to align QLabel text to label's right edge

description: Align QLabel text to label's right edge


code:
def test1_test2(*args):
    test1(*args)
    test2(*args)

cmds.button('greetings', label='Menu', command=test1_test2)

rawDescription: Running Multiple functions in python Maya


code:
from django.views.generic import TemplateView

...
url(r'^$', TemplateView.as_view(template_name='index.html'))

rawDescription: Serving static index.html in django

description: Serving static index.html in django


rawDescription: Hoy can I pass "whole" cli arguments to a function in python


code:
def list_length(L):
    if L:
        return 1 + list_length(L[1:])
    return 0

list_length(myarray)
list_length([])
list_length([1]*4)

rawDescription: calculate length of list recursively

description: Calculate length of list recursively


code: plt.yticks(sharey) #where sharey is your list of values

rawDescription: Matplotlib : Consistent Y-Axis across 4 Separate Line Plots


code:
l = [1, 2, 20, 5, 10]
list(dict.fromkeys(l).keys())
list(collections.OrderedDict.fromkeys(l).keys())

rawDescription: Disable automatic dict sorting with dict.fromkeys( )?


code:
from ast import literal_eval

literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")

rawDescription: Convert String back to List

description: Convert String back to List


code:
for line in f:
    items = line.split()
    key, values = int(items[0]), items[1:]
    my_dict.setdefault(key, []).extend(values)

rawDescription: Converting a file into a dictionary with one key and multiple values


code: x=foo[index]

rawDescription: Extracting the a value from a tuple when the other values are unused


rawDescription: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine?

description: Filter based on dict contents in a DictField on a model using the Django-MongoDB Engine


code: return Response(my_date, mimetype, {'Content-Disposition':'attachment'})

rawDescription: How to convert a string in .ics file and then download it in Flask?

description: Convert a string in .ics file and then download it in Flask


code:
import sys
from PyQt4 import QtCore, QtGui

class QCsMainWindow (QtGui.QMainWindow):
    def __init__ (self):
        super(QCsMainWindow, self).__init__()
        self.isDirectlyClose = False
        QtCore.QTimer.singleShot(5 * 1000, self.close) # For simulate test direct close

    def close (self):
        for childQWidget in self.findChildren(QtGui.QWidget):
            childQWidget.close()
        self.isDirectlyClose = True
        return QtGui.QMainWindow.close(self)

    def closeEvent (self, eventQCloseEvent):
        if self.isDirectlyClose:
            eventQCloseEvent.accept()
        else:
            answer = QtGui.QMessageBox.question (
                self,
                'Are you sure you want to quit ?',
                'Task is in progress !',
                QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            if (answer == QtGui.QMessageBox.Yes) or (self.isDirectlyClose == True):
                eventQCloseEvent.accept()
            else:
                eventQCloseEvent.ignore()

appQApplication = QtGui.QApplication(sys.argv)
mainQWidget = QCsMainWindow()
mainQWidget.show()
sys.exit(appQApplication.exec_())

rawDescription: closing pyqt messageBox with closeevent of the parent window

description: Closing pyqt messageBox with closeevent of the parent window


rawDescription: How to ensure get label for zero counts in python pandas pd.cut

description: Ensure get label for zero counts in python pandas pd.cut


code:
import threading

#1
lock = threading.Lock() # use this line if theadsafety for _cache is important

def memorize(key, period):
    """
    Memorizing decorator. Returning cached data
    if its validity period is not expired
    """
    #2
    lock = threading.Lock() # use this line if theadsafety for a key is important
    def _decoration_wrapper(func):
        #3
        lock = threading.Lock() # use this line if theadsafety for  the function is important
        def _caching_wrapper(*args, **kwargs):
            cache_key = key
            now = time.time()

            if _timestamps.get(cache_key, now) > now:
                return _cache[cache_key]
            with lock:
                if _timestamps.get(cache_key, now) > now:
                    return _cache[cache_key]
                ret = func(*args, **kwargs)
                _cache[cache_key] = ret
                _timestamps[cache_key] = now + period
                return ret
        return _caching_wrapper
    return _decoration_wrapper

rawDescription: Python cache/memorize and thread locking


code:
#!/usr/bin/python3
# License: MIT
import svgwrite

progname = 'example_filter_on_group'

def create_svg(name):

    svg_size_w = 900
    svg_size_h = 1500
    title_size = 20
    y = 0
    title = name + ': example of filter on a group'
    dwg = svgwrite.Drawing(name, (svg_size_w, svg_size_h), debug=True)
    # background will be white.
    dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), fill='white'))

    # create simple filter to blur rectangle
    blur6_filter = dwg.defs.add(dwg.filter())
    blur6_filter.feGaussianBlur(in_='SourceGraphic', stdDeviation=6)

    # group with filter
    g_f = dwg.add(dwg.g(filter=blur6_filter.get_funciri()))
    g_f.add( dwg.rect(insert=(50, 50), size=(50, 50), fill='aqua'))

    dwg.save()

if __name__ == '__main__':
    create_svg(progname + '.svg')

rawDescription: How to apply SVG Filter to Group using svgwrite with Python?

description: Apply SVG Filter to Group using svgwrite with Python


code:
import numpy as np

def array_to_complete_graph(vertexarray):

    vertcoords = np.transpose(np.where(vertexarray == True))

    cg_array = np.eye(len(vertcoords))

    for idx, vals in enumerate(vertcoords):
        x_val_1, y_val_1 = vals
        for jdx, wals in enumerate(vertcoords):
            x_diff = wals[0] - vals[0]
            y_diff = wals[1] - vals[1]
            cg_array[idx,jdx] = np.sqrt(x_diff**2 + y_diff**2)
    return cg_array

arr = np.random.rand(10, 20) > 0.75

from scipy.spatial.distance import cdist
y, x = np.where(arr)
p = np.c_[x, y]
dist = cdist(p, p)
np.allclose(array_to_complete_graph(arr), dist)

rawDescription: Vectorize compressed sparse matrix from array in Python


code:
#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split('/')
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

rawDescription: Using os.walk() to recursively traverse directories in Python


code:
from collections import OrderedDict
OrderedDict(sorted(d.items(), key=lambda item: len(item[1])))

rawDescription: Sorting Python dictionary based on number of items in list


code:
f = open('tabledefinition.sql')
full_sql = f.read()
sql_commands = full_sql.split(';')

for sql_command in sql_commands:
    curs.execute(sql_command)

rawDescription: execute a sql script file from cx_oracle?

description: Execute a sql script file from cx_oracle


code:
def adder(dict, source, dest, weight):
   if not source in dict:
     dict[source] = {}
   if not dest in dict:
     dict[dest] = {}
   dict[source][dest] = weight

rawDescription: Python Dictionary of Dictionary with condition


code:
def split_up(funds, people):
    share = funds / people
    return "each person (of %d) gets $%.2f as their share" % (people, share)

rawDescription: Function for Splitting up

description: Function for Splitting up


code:
pattern = "\s(\w*?(?P<ext>\w)(?P=ext){2,}\w*?)\W"
s1 = "Bob is the bessssst."
s2 = "Bob is the bessssst ."
ext_re = re.compile(pattern)
m = ext_re.search(s1)
m.groups()
m = ext_re.search(s2)
m.groups()

rawDescription: How do I find extensions and replace them in python?

description: Find extensions and replace them in python


code:
import numpy as np
from mayavi import mlab

x = np.linspace(0,10,50)
y = np.linspace(0,15,50)
z = np.linspace(0,8,50)

X, Y, Z = np.meshgrid(x, y, z)

s = np.cos(X) + np.sin(Y) + Z**0.5
b1 = np.percentile(s, 20)
b2 = np.percentile(s, 80)
mlab.pipeline.volume(mlab.pipeline.scalar_field(s), vmin=b1, vmax=b2)
mlab.axes()
mlab.show()

rawDescription: Plotting function of 3 dimensions over given domain with matplotlib


code:
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))

rawDescription: Convert File to HEX String Python

description: Convert File to HEX String Python


code:
def login_user(request):
    if request.POST:
        sform = LoginForm(request.POST)
        rform = UserForm()
        if sform.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username = username,password = password)
            if user is not None:
                if user.is_active:
                    login(request,user)
                    return redirect(request.path)
                else:
                    state = "Your account is not active."
                    #or first set the user to is active and then log in
                    return redirect(req.session['after_login_url'],user = user)
                return render_to_response('home.html',{'state':state,'user':user},context_instance = RequestContext(request))
            else:
                state = "Incorrect Username or Password"
                #sform = LoginForm()
                form = LoginForm()
                return render_to_response('register.html',{'state':state,'sform':sform,'rform':rform,'form':form},context_instance = RequestContext(request))
        else:
            state = "Invalid form"
            dLoginForm = LoginForm()
            rform = PartialSignupForm()
            return render_to_response('register.html',{'sform':sform,'rform':rform,'form':form},context_instance = RequestContext(request))
    else:
        dLoginForm = LoginForm()
        rform = PartialSignupForm()
        req.session['after_login_url'] = req.META.get('HTTP_REFERER')
        return render_to_response('category.html',{'dLoginForm':dLoginForm,'rform':rform},context_instance = RequestContext(request))

rawDescription: redirect to the same url from which request is sent

description: Redirect to the same url from which request is sent


rawDescription: Strange behavior of QProgressBar with PyQt4


code: files = next(os.walk('somedir'))[2]

rawDescription: How to list only regular files (excluding directories) under a directory in Python

description: List only regular files (excluding directories) under a directory in Python


code: sequences = [part for part in mystring.split("\\") if not part.isdigit()]

rawDescription: Extract a particular field in '\xxx\xxx\xxx\xxx\xxx\' format in python?


code:
from itertools import izip
zipped = [(xx, yy) for xx, yy in izip(x, y) if yy]

rawDescription: How can I skip creating tuples with certain values, when using the zip function in Python?

description: Skip creating tuples with certain values, when using the zip function in Python


rawDescription: How to change color of a 3D mesh in Kivy?

description: Change color of a 3D mesh in Kivy


code:
def prepend_urls(self):
    params = (self._meta.resource_name, trailing_slash())
    return [
        url(r"^(?P<resource_name>%s)/delete%s$" % params, self.wrap_view('foo_delete'), name="api_foo_delete")
    ]

    ## (?P<resource_name>%s)  will be /api/foo  if your resource name is foo

def foo_delete(self, request, **kwargs):
    """
    Get pks to delete from post .
    pks = request.POST.getlist('pks[]')
    you can use split if you are sending pks by comma separated .
    pks = (request.POST.get('pks')).split(',')
    """
    self.method_check(request, allowed=['post'])
    self.is_authenticated(request)
    if request.user and request.user.is_authenticated():
        ### perform delete operation of pk .
        return self.create_response(request, { 'success': True })
    else:
        return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })

rawDescription: Deleting a queryset using tastypie

description: Deleting a queryset using tastypie


rawDescription: Get count of values across columns-Pandas DataFrame


code:
def __getitem__(self, index):
  return self.list[index-1]

def __setitem__(self, index, value):
  self.list[index-1] = value

rawDescription: make array index 1 instead of index 0 based

description: Make array index 1 instead of index 0 based


rawDescription: Selecting values from python dictionaries and string into new dicts


code:
CHOICES=(
    (1,"1"),
    (2,"2"),
    (3,"3"),
    (4,"4"),
    (5,"5")
)
satisfaction = forms.ChoiceField(
    choices=CHOICES,
    widget=forms.RadioSelect()
)

rawDescription: Django single checkbox questionaire

description: Django single checkbox questionaire


code:
def do_something(fname):
    with open(fname,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"):#find dbname =PFAM
            # Make slightly more robust
            try:
                start = int(lcn.get("start"))#if it is PFAM then look for start value
                end = int(lcn.get("end"))#if it is PFAM then also look for end value
                yield start, end
            except (TypeError , ValueError) as e:
                pass # start/end aren't usable as numbers decide what to do here...

for start, end in do_something():
    do_something_else(start, end)

rawDescription: how to make a function return every possible values

description: Make a function return every possible values


code:
import pylab as plt
import pandas as pd
np = pd.np

df = pd.DataFrame( {'age':np.random.normal( 50,10,300).astype(int),
                    'counts':1000*np.random.random(300)} ) # test data
#df.head()
#   age      counts
#0   38  797.174450
#1   36  402.171434
#2   49  894.218420
#3   66  841.786623
#4   51  597.040259

df.hist('age',weights=df['counts'] )
plt.ylabel('counts')
plt.show()

rawDescription: Histogram of one field wrt another in pandas python


code:
x = ...
y = ...
v = ...

xmin = x[0]
xmax = x[-1]
ymin = y[0]
ymax = y[-1]

nx = len(x.unique())
ny = len(y.unique())

img = np.zero((nx, ny))
for ix in range(0, nx):
    for iy in range(0, ny):
        v_idx = ix*ny + iy
        img[ix, iy] = v[v_idx]

plt.imshow(img, extent=[xmin, xmax, ymin, ymax], cmap=plt.cm.Reds, interpolation='none')
plt.xscale('log')
plt.yscale('log')

plt.show()

rawDescription: Function to plot a data source (probably not regularized) in format x,y,value using python matplotlib


code:
from django import template
import binascii

register = template.Library()

@register.filter
def hex_decode(value):
    return binascii.unhexlify(value)

rawDescription: unhexlify value within a Django template

description: Unhexlify value within a Django template


code:
from django.db.models import Q

class PromotionQuerySet(models.QuerySet):
    def for_user(self, user):
        return self.filter(Q(user=user) | Q(user__isnull=True))

class Promotion(models.Model):
    user = models.ForeignKey(User, null=True)

    objects = PromotionQuerySet.as_manager()

# and later in your code, say, in the view:
active_promos = Promotion.objects.for_user(request.user)

rawDescription: Django related objects and null foreign key


code:
from kivy.lang import Builder

Builder.load_string('''
<Slider>:
    canvas:
        Color:
            rgb: 0, 0, 0
        BorderImage:
            border: (0, 18, 0, 18) if self.orientation == 'horizontal' else (18,
 0, 18, 0)
            pos: (self.x + self.padding, self.center_y - sp(18)) if self.orienta
tion == 'horizontal' else (self.center_x - 18, self.y + self.padding)
            size: (max(self.value_pos[0] - self.padding * 2 - sp(16), 0), sp(36)
) if self.orientation == 'horizontal' else (sp(36), max(self.value_pos[1] - self
.padding * 2 - sp(16), 0))
            source: 'atlas://data/images/defaulttheme/slider{}_background{}'.format(self.orientation[0], '_disabled' if self.disabled else '')
''')

rawDescription: Change Kivy Slider Color

description: Change Kivy Slider Color


code:
import functools

class MyType(collections.MutableMapping):

    keys = functools.partialmethod(collections.KeysView)

rawDescription: Create bound method from class constructor


code:
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "teacher":
            kwargs["queryset"] = User.objects.filter(groups__name='Teacher')
        if db_field.name == "students":
            kwargs["queryset"] = User.objects.filter(groups__name='Student')
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Django auth group model m2m

description: Django auth group model m2m


rawDescription: Python: How to create an array of arrays based on a variable?


code:
import time
time.clock()
time.clock()
time.clock()
for x in xrange(100000000): pass

time.clock()
time.clock()
time.clock()

rawDescription: Python clock function on FreeBSD

description: Python clock function on FreeBSD


code:
from win32api import *
from win32gui import *
import win32con
import sys, os
import struct
import time

class WindowsBalloonTip:
    def __init__(self, title, msg):
        message_map = {
                win32con.WM_DESTROY: self.OnDestroy,
        }
        # Register the Window class.
        wc = WNDCLASS()
        hinst = wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbar"
        wc.lpfnWndProc = message_map # could also specify a wndproc.
        classAtom = RegisterClass(wc)
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = CreateWindow( classAtom, "Taskbar", style, \
                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
                0, 0, hinst, None)
        UpdateWindow(self.hwnd)
        iconPathName = os.path.abspath(os.path.join( sys.path[0], "balloontip.ico" ))
        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
        try:
           hicon = LoadImage(hinst, iconPathName, \
                    win32con.IMAGE_ICON, 0, 0, icon_flags)
        except:
          hicon = LoadIcon(0, win32con.IDI_APPLICATION)
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "tooltip")
        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(NIM_MODIFY, \
                         (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
                          hicon, "Balloon  tooltip",msg,200,title))
        # self.show_balloon(title, msg)
        time.sleep(10)
        DestroyWindow(self.hwnd)
    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        Shell_NotifyIcon(NIM_DELETE, nid)
        PostQuitMessage(0) # Terminate the app.

def balloon_tip(title, msg):
    w=WindowsBalloonTip(title, msg)

if __name__ == '__main__':
    balloon_tip("Title for popup", "This is the popup's message")

rawDescription: How to create a system tray popup message with python? (Windows)

description: Create a system tray popup message with python? (Windows)


code:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)

rawDescription: Django Serving a Download File

description: Django Serving a Download File


code:
import xlwings as xw
pic = xw.Picture(1, 'picture_name')  # To manipulate an existing picture
pic = xw.Picture.add('path/to/picture.jpg', sheet=1)  # add a new one

rawDescription: Insert image in Excel using xlwings

description: Insert image in Excel using xlwings


code:
try:
    import userdefined
except ImportError:
    pass

rawDescription: Best way to include functions defined by arbitrary user?

description: Include functions defined by arbitrary user


code:
import copy

x = copy.copy(y)        # make a shallow copy of y
x = copy.deepcopy(y)    # make a deep copy of y

rawDescription: Copy constructor in python

description: Copy constructor in python


code:
with open('fin.txt') as fin, open('fout.txt', 'w') as fout:
    for i, item in enumerate(fin, 1):
        if i == 7:
            item = "string\n"
        fout.write(item)

rawDescription: Python replace line by index number

description: Python replace line by index number


rawDescription: How can I find the number of arguments of a Python function?

description: Find the number of arguments of a Python function


code:
for missing_name in set(skill_names) - set(Skill.objects.filter(name__in=skill_list).values_list('name',flat=True) ):
    _ = Skill.objects.get_or_create(name=missing_name)

rawDescription: Auto creating records across a ManyToMany Field in Django upon save


code:
chunk = stream.read(chunk_size)  # here stream is your PyAudio Stream
mx = audioop.max(chunk, 2)       # 2 is the width, here corresponding to paInt16

rawDescription: Using pyaudio to convert volume to string


code:
def returnNotMatches(a, b):
    return [[x for x in a if x not in b], [x for x in b if x not in a]]

rawDescription: How can I compare two lists in python and return not matches

description: Compare two lists in python and return not matches


code:
#!/usr/bin/env python
from pylab import *

def f(t):
    s1 = cos(2*pi*t)
    e1 = exp(-t)
    return multiply(s1,e1)

t1 = arange(0.0, 5.0, 0.1)
t2 = arange(0.0, 5.0, 0.02)
t3 = arange(0.0, 2.0, 0.01)

figure(figsize=(4, 4))
sub1 = subplot(211)
l = plot(t1, f(t1), 'bo', t2, f(t2), 'k--', markerfacecolor='green')
grid(True)
title('A tale of 2 subplots')
ylabel('Damped oscillation')

## I ADDED THIS
autoAxis = sub1.axis()
rec = Rectangle((autoAxis[0]-0.7,autoAxis[2]-0.2),(autoAxis[1]-autoAxis[0])+1,(autoAxis[3]-autoAxis[2])+0.4,fill=False,lw=2)
rec = sub1.add_patch(rec)
rec.set_clip_on(False)

subplot(212)
plot(t3, cos(2*pi*t3), 'r.')
grid(True)
xlabel('time (s)')
ylabel('Undamped')

savefig('test.png')

rawDescription: draw a border around subplots in matplotlib

description: Draw a border around subplots in matplotlib


code:
def logged_in(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('logged_in') is not None:
            return f(*args, **kwargs)
        else:
            flash('Please log in first...', 'error')
            next_url = get_current_url() # However you do this in Flask
            login_url = '%s?next=%s' % (url_for('login'), next_url)
            return redirect(login_url)
    return decorated_function

rawDescription: Flask/Werkzeug, how to return previous page after login


code:
import urllib2

page = urllib2.urlopen('http://stackoverflow.com')

page_content = page.read()

with open('page_content.html', 'w') as fid:
    fid.write(page_content)

rawDescription: Inherent Python way to save web page source


code:
import numpy
np = numpy
del numpy

rawDescription: Obfuscate 'import numpy as np'

description: Obfuscate 'import numpy as np'


code:
parser = argparse.ArgumentParser(description="Test")
parser.add_argument('command')

parameters = parser.parse_args()
cmd = parameters.command

rawDescription: Some python argparse usage questions: retrieving arguments


code: ndf.reset_index(drop = True)

rawDescription: Reserializing row index after row selection in pandas data frame


code:
from sys import argv
from itertools import cycle
from pprint import pprint

from twisted.names import client
from twisted.internet.task import react
from twisted.internet.defer import gatherResults, inlineCallbacks

def query(reactor, server, name):
    # Create a new resolver that uses the given DNS server
    resolver = client.Resolver(
        resolv="/dev/null", servers=[(server, 53)], reactor=reactor)
    # Use it to do an A request for the name
    return resolver.lookupAddress(name)

@inlineCallbacks
def main(reactor, *names):
    # Here's some random DNS servers to which to issue requests.
    servers = ["4.2.2.1", "8.8.8.8"]

    # Handy trick to cycle through those servers forever
    next_server = cycle(servers).next

    # Issue queries for all the names given, alternating between servers.
    results = []
    for n in names:
        results.append(query(reactor, next_server(), n))
    # Wait for all the results
    results = yield gatherResults(results)
    # And report them
    pprint(zip(names, results))

if __name__ == '__main__':
    # Run the main program with the reactor going and pass names
    # from the command line arguments to be resolved
    react(main, argv[1:])

rawDescription: Asynchronous DNS resolver testing

description: Asynchronous DNS resolver testing


code: total = 0

rawDescription: python elementtree - getting average

description: Python elementtree - getting average


code:
def func(n):
    x, y = n
    ...

rawDescription: What is an exotic function signature in Python?