code:
import unicodedata
unicodedata.name(u'\u2028')
unicodedata.name(u'\u202A')

rawDescription: Python unicode.splitlines() triggers at non-EOL character


code: rs['Values']

rawDescription: Python regularise irregular time series with linear interpolation


code:
from datetime import datetime
datetime.strptime('4', '%m').strftime('%b')

rawDescription: Python: Creating a month() function to take 1 - 12 as input and return corresponding month


code: df.x1.values - df.x1.values[:,None]

rawDescription: Creating boolean matrix from one column with pandas


rawDescription: Regex Python not matching, but does on regexpal


code:
while True:
   same_every_time = AClass.objects.all().order_by('-id')[:5]
   sleep(300)

rawDescription: Django ORM queries fail to select new objects


code:
import pysomemodule

foo = pysomemodule.ABC("config.txt") # This will create an instance of ABC

rawDescription: Writing Python bindings for C++ code that use OpenCV


code:
def myfunc(orientation, l, w):
    return { 1: (-w, l), 2: (-l, w), 3: (-w, -l),
             4: (-l, -w), 5: (w, l), 6: (l, w),
             7: (w, -l), 8: (l, -w) }.get(orientation) #This returns `None` if orientation is not found in the dictionary. Use `.get(orientation, defaultval)` for some other default value.

rawDescription: Defining variables efficiently according to a parameter that may take several values


code:
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'IP': ['10.20.30.40',
      '30.50.70.90',
      '10.20.30.41',
      '10.20.30.42',
      '90.80.70.10'],
     'domain': ['example.org',
      'site.com',
      'example.org',
      'example.org',
      'website.com'],
     'subdomain': ['test1', 'something', 'test2', 'test3', 'else']})

B = nx.Graph()
B.add_nodes_from(df['subdomain'], bipartite=0)
B.add_nodes_from(df['domain'], bipartite=1)
B.add_weighted_edges_from(
    [(row['domain'], row['subdomain'], 1) for idx, row in df.iterrows()],
    weight='weight')

print(B.edges(data=True))
# [('test1', 'example.org', {'weight': 1}), ('test3', 'example.org', {'weight': 1}), ('test2', 'example.org', {'weight': 1}), ('website.com', 'else', {'weight': 1}), ('site.com', 'something', {'weight': 1})]

pos = {node:[0, i] for i,node in enumerate(df['domain'])}
pos.update({node:[1, i] for i,node in enumerate(df['subdomain'])})
nx.draw(B, pos, with_labels=False)
for p in pos:  # raise text positions
    pos[p][1] += 0.25
nx.draw_networkx_labels(B, pos)

plt.show()

rawDescription: Construct bipartite graph from columns of python dataframe


rawDescription: How to mix named and unnamed string formatting

description: Mix named and unnamed string formatting


code:
a=SomeObject()
b=a
c=a
d=c

rawDescription: How do I fix the part in __str__ so it would display the name of the instance within the class? Python 2X

description: Fix the part in __str__ so it would display the name of the instance within the class? Python 2X


rawDescription: How to reshape 2D arrays?

description: Reshape 2D arrays


code:
[None, None, None, None, None, None, None, 1, 3, 4]
[None, None, None]

rawDescription: Delete elements in a list and retaining the size of a list in Python?


code:
img = gimp.Image(640, 480, RGB)
pdb.gimp_display_new(img)
parent_group = pdb.gimp_layer_group_new(img)
child_group_1 = pdb.gimp_layer_group_new(img)
child_group_2 = pdb.gimp_layer_group_new(img)
grand_child_group = pdb.gimp_layer_group_new(img)
img.add_layer(parent_group, 0)
pdb.gimp_image_insert_layer(img, child_group_1, parent_group,0)
pdb.gimp_image_insert_layer(img, child_group_2, parent_group,1)
pdb.gimp_image_insert_layer(img, grand_child_group, child_group_1,0)
l1 = gimp.Layer(img, "test", 320,240)
pdb.gimp_image_insert_layer(img,l1, grand_child_group,0)

rawDescription: GIMP Python-fu nested group layers

description: GIMP Python-fu nested group layers


rawDescription: Extract data from within parenthesis in python


code:
variables = []
entries = []
for i in range(x):
    va = StringVar()
    en = Entry(root, textvariable=va)
    en.grid(row=1, column=i+1)
    variables.append(va)
    entries.append(en)

rawDescription: multiple entry labels in tkinter

description: Multiple entry labels in tkinter


rawDescription: Declare python variable that stores a function, but not run it


code:
fruits = ('apple', 'banana', 'orange', 'grape', 'berry')
(5*'%10.10s') % fruits

rawDescription: write fortran-like format to file in python

description: Write fortran-like format to file in python


Conditionally Combining/Reducing key-pairs


code: from __future__ import unicode_literals

rawDescription: python 3 raw unicode strings

description: Python 3 raw unicode strings


code: unrolled = [c for c, count in weighted for _ in range(count)]

rawDescription: Creating multiple copies of list elements


code:
def get_time():
    return datetime.datetime.now() + datetime.timedelta(minutes=15)

# your field would accept function callback
blink = models.DateTimeField(default=get_time)

rawDescription: comparing two DateTime fields in django template

description: Comparing two DateTime fields in django template


code: temp[np.lexsort((temp[:, 1], ))]

rawDescription: Python Matrix sorting via one column

description: Python Matrix sorting via one column


rawDescription: Join list of dict with a dict in python

description: Join list of dict with a dict in python


rawDescription: xaxis numbers not printed on log-scale plot

description: Xaxis numbers not printed on log-scale plot


code:
import sys
import os

# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

rawDescription: SGE script: print to file during execution (not just at the end)?


code:
import io

with io.open('/usr/share/dict/words', encoding='utf-8') as fin, io.open('dataFinal.txt', 'w', encoding='utf-8') as fout:
    fout.writelines(line.partition(':')[0] + '\n' for line in fin)

rawDescription: How to find and replace/remove text after a specified delims with Python?

description: Find and replace/remove text after a specified delims with Python


code:
import numpy as np
@np.vectorize
def foo(a, b):
   return a + b

foo([1,3,5], [2,4,6])
foo(np.arange(9).reshape(3,3), np.arange(9).reshape(3,3))

rawDescription: How do I apply some function to a python meshgrid?

description: Apply some function to a python meshgrid


code: something & something

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
lst = {"cat", "dog", "fish", "god"}
find_anagrams_in_wordlist("odg", lst)
find_anagrams_in_wordlist("cat", lst)
find_anagrams_in_wordlist("shif", lst)
find_anagrams_in_wordlist("birds", lst)

rawDescription: Anagram Function Returning None

description: Anagram Function Returning None


code:
# Filter.py
#...

if __name__ == '__main__':

    # ...

    main(some, args)

rawDescription: Python - Supplying Command Line Arguments - in "from X import A"


code: r = np.exp(np.sqrt(x*x + y*y))

rawDescription: Log scale on radial contour plot with matplotlib


code:
import sys
sys.path.insert(0, '/home/myuser/my_python/lib/python2.5/site-packages')

import numpy

rawDescription: Python web hosting: Numpy, Matplotlib, Scientific Computing


code:
def func_power_3(param, x1, y):
    p1, p2 = param
    res = sum(y_i - (p1*x1_i)**p2 for x1_i, y_i in zip(x1, y))
    return res

rawDescription: Python matplotlib - formatting with meshgrid for user-defined function


code:
def to_bits(contents):
    return ''.join(bin(byte)[2:].zfill(8) for byte in contents)

rawDescription: Binary I/O in Python

description: Binary I/O in Python


rawDescription: How can I slice a list based on the lengths from another list?

description: Slice a list based on the lengths from another list


code: strdata = json.load(f)

rawDescription: Not about to deserialize json kept as string in Python using json.load


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=50, edgecolor='')
plt.show()

rawDescription: How can I make a scatter plot colored by density in matplotlib?

description: Make a scatter plot colored by density in matplotlib


code:
import subprocess

## Do some processing in Python

## Set do-file information
dofile = "/home/roberto/Desktop/pyexample3.do"
cmd = ["stata", "do", dofile, "mpg", "weight", "foreign"]

## Run do-file
subprocess.call(cmd)

rawDescription: Run Stata do file from Python

description: Run Stata do file from Python


code:
from math import *
logsum = 0
n = raw_input('This is a logarithm ratio tester. Which number do you want to test? ')
for x in range(2,n):                            #picks numbers to test
    isprime = True
    for divisor in range(2, 1+int(sqrt(x+1))):
        if x%divisor == 0:                      #checks if x is prime
            isprime = False                                  #computes log of prime
            break
    if isprime:
        logsum += log(x)

rawDescription: Python 2.5.4: how to find sum of logarithm values


rawDescription: Basic Slicing Review

description: Basic Slicing Review


code: indexes = [ind for ind,ele in enumerate(my_list) if ele =="car"]

rawDescription: How to print the index values of two identical items in a list?

description: Print the index values of two identical items in a list


code:
import random
topic = {'Countries': ['Somalia', 'Bermuda'],
         'Cars'     : ['Tesla', 'Lotus']
}
key = random.choice(list(topic.keys()))
value = random.choice(topic[key])
value

rawDescription: access random item in list within dictionaries

description: Access random item in list within dictionaries


code:
X = Xmax * V / Vmax
V = Vmax * X / Xmax

rawDescription: Linear X Logarithmic scale

description: Linear X Logarithmic scale


code:
import re
new_string = re.sub(r'^.*?(\d+\D*)(\..*)', r'\1T\2', orig_string)

rawDescription: Split and append

description: Split and append


code:
u"Tanım"
url = urllib.quote(u"Tanım".encode('utf8'))
urllib.unquote(url).decode('utf8')

rawDescription: How to unquote a urlencoded unicode string in python?

description: Unquote a urlencoded unicode string in python


code:
from myapp.model import MyScopedSession

def setUp(self):
     MyScopedSession.registry.set(MockSession())

     # set up some queries, we can usually use scoped_session's proxying

     MyScopedSession.query(User).filter_by(id=1).first.return_value = User(id=1)

def tearDown(self):
     MyScopedSession.remove()

def some_test(self):
     # to get at mock methods and accessors, call the scoped_session to get at
     # the registry

     #  ... test some thing

     # test a User was added to the session
     self.assertEquals(
            MyScopedSession().add.mock_calls,
            [mock.call(User(name='someuser'))]
     )

rawDescription: What's the correct way to unit test Pyramid views with a SQLAlchemy DBSession?


code:
url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
def some_logic(match):
    s = match.group()  # to get matched string
    return str(len(s) - 1)  # put any login you want here
import re
re.sub('\$\w+', some_logic, url)

rawDescription: How to dynamically parse python string templates?

description: Dynamically parse python string templates


code:
# Inputs
# Set tolerance values for each column
x1,x2

rawDescription: Finding intersection of two matrices in Python within a tolerance?


code:
class GlobeLearningTable(object):
    def __init__(self,mac,port,dpid):
        self.mac = mac
        self.port = port
        self.dpid = dpid

    def __hash__(self):
        return hash((self.mac, self.port, self.dpid))

    def __eq__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.mac == other.mac and self.port == other.port and self.dpid == other.dpid

rawDescription: Creating Set of objects of user defined class in python


code:
import numbers
isinstance(1337, numbers.Integral)
isinstance(1337, numbers.Rational)
issubclass(numbers.Integral, numbers.Rational)

rawDescription: Python: Why do int.numerator and int.denominator exist?


code:
class EasyWidgetUpdater:
     widgets = {}
     def SetValue(self,valueDict):
         for k,v in valueDict.items():
             if k in self.widgets:
                   set_widget_value(self.widgets[k],v)
     def GetValue(self):
         result = {}
         for k,widget in self.widgets:
             result[k] = get_widget_value(widget)
         return result

rawDescription: WxPython Panel Refresh

description: WxPython Panel Refresh


code:
int(binascii.hexlify(x), 16)
int(binascii.hexlify(x), 16) == 0xa313a43bcbda1b1b2c5574deeb32b584e526853b

rawDescription: How to decode raw binary to hex

description: Decode raw binary to hex


rawDescription: most pythonic way to use a value from a list as an index to another list

description: Most pythonic way to use a value from a list as an index to another list


code:
def increment():
    Counter.currentProgress += 1
    time.sleep(random.randint(1,6)) # Artificially delay execution.
    Counter.expectedTime = ((time.time() - Counter.startTime) / Counter.currentProgress)*(Counter.totalTask - Counter.currentProgress)
    print("Progress: "+str(Counter.currentProgress)+" / "+ str(Counter.totalTask) + " : " + str(float(Counter.currentProgress) / float(Counter.totalTask)*100)+"%")
    print("Expected finish in: " + str(Counter.expectedTime/3600.0) + " hrs")

rawDescription: How to write a progress counter/time for concurrency?

description: Write a progress counter/time for concurrency


code:
x.shape
x[:, np.newaxis].shape
y.shape

rawDescription: Difference between every row and column in two DataFrames (Python / Pandas)


rawDescription: Stacked bar plots from two different sources in Pandas


code:
import enchant
d = enchant.Dict("en_US") # or de_DE

def find_words(instring, prefix = ''):
    if not instring:
        return []

    if (not prefix) and (d.check(instring)):
        return [instring]
    prefix, suffix = prefix + instring[0], instring[1:]
    solutions = []
    # Case 1: prefix in solution
    if d.check(prefix):
        try:
            solutions.append([prefix] + find_words(suffix, ''))
        except ValueError:
            pass
    # Case 2: prefix not in solution
    try:
        solutions.append(find_words(suffix, prefix))
    except ValueError:
        pass
    if solutions:
        return sorted(solutions,
                      key = lambda solution: [len(word) for word in solution],
                      reverse = True)[0]

    else:
        raise ValueError('no solution')

inp = "H e l l o   g u y s T h i s i s P a g e 1"
newInp = inp.replace(" ", "")

print(find_words(newInp))

rawDescription: Python fastest way to remove single spaces from spaced out letters in string


code:
arr = np.empty((3, 5))
smallarr = arr[:, :-1]
smallarr[...] = np.arange(12).reshape(3,4)
arr[:, -1] = v
arr

rawDescription: Best way to add a new column to a Numpy array

description: Add a new column to a Numpy array


code:
d = {'x':0, 'z':2, 'w':3}
lst = [""] * (max(d.values()) + 1)
for k, v in d.items():
    lst[v] = k
print(lst)

rawDescription: py3k: mapping dictionary (string->number) into list (of strings)

description: Py3k: mapping dictionary (string->number) into list (of strings)


code: frame = Frame1(None).Show()

rawDescription: How do I load values into a wxPython app when it opens?

description: Load values into a wxPython app when it opens


code:
if suffix == "":
    return True

rawDescription: Why are two empty string slices not acting 'equal'?


code:
from gimpfu import pdb, main, register, PF_STRING
from gimpenums import ORIENTATION_HORIZONTAL

def flip(file):
    image = pdb.gimp_file_load(file, file)
    drawable = pdb.gimp_image_get_active_layer(image)
    pdb.gimp_image_flip(image, ORIENTATION_HORIZONTAL)
    pdb.gimp_file_save(image, drawable, file, file)
    pdb.gimp_image_delete(image)

args = [(PF_STRING, 'file', 'GlobPattern', '*.*')]
register('python-flip', '', '', '', '', '', '', '', args, [], flip)

main()

rawDescription: Writing a GIMP python script

description: Writing a GIMP python script


code: result = sum(e.calculate_result(i).real for i in xrange(10000) for e in element_list)

rawDescription: Container list in Python: standard list vs numpy array


code:
import datetime
datetime.datetime.strptime(row[0], "%Y%m%d%H%M")

rawDescription: Is there a ready solution in matplotlib to plot times?


rawDescription: How to make celery retry using the same worker?

description: Make celery retry using the same worker


code: f.write('Name: {name} || Score: {score}\n'.format(player))

rawDescription: how do i print to a a CSV file from different inputs in python

description: Print to a a CSV file from different inputs in python


code:
class nestedStru(Structure):
    _fields_ = [
      ("One", c_int),
      ("Two", c_int)
    ]

class mainStru(Structure):
    _fields_ = [
      ("First", c_int),
      ("Poniter", POINTER(nestedStru))
    ]

rawDescription: ctypes structure arrays in python

description: Ctypes structure arrays in python


code:
import datetime
import logging

import logaugment

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter("%(time_since_last)s: %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

rawDescription: Python logging module - time since last log


rawDescription: Pythonic way to create empty map of vector of vector of vector


code:
filename = 'data'
data = using_explicit_dtype(filename)
print(data)
# [ (76920, '1995-12-31-00:00', nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 108.0, nan, nan, nan, nan, nan, nan, 14.3, nan, 17.4, nan, nan, nan, nan, 14.3, nan, nan, nan, nan, 1005.8, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 2.6, nan, nan, nan, nan, nan, nan, nan, nan, nan, 7.4, nan, nan, 54.0, 3.2, 5.1, nan, nan, nan, nan, nan, nan, nan, 7.4, nan, nan, 5.7, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 3.7, nan, nan, nan, nan, nan)
#  (76920, '2005-01-01-00:00', 52.0, nan, nan, nan, nan, nan, nan, nan, nan, 0.06, nan, nan, nan, nan, nan, nan, nan, nan, 230.0, nan, nan, nan, nan, nan, nan, 10.1, nan, 12.3, nan, nan, 8.5, nan, nan, nan, nan, nan, nan, 1016.7, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 7.0, nan, 4.7, nan, nan, nan, nan, nan, nan, nan, 7.8, nan, nan, 85.0, 1.5, 2.5, nan, nan, nan, nan, nan, nan, nan, 6.1, 12.8, 8.5, 4.9, nan, nan, nan, nan, nan, nan, 229.0, nan, 10.3, 12.3, nan, 8.6, nan, nan, 1016.8, nan, 7.1, 4.7, nan, nan, nan, 84.0, nan, 2.8, 19.88, 6.8, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1.5, 2.4, 17.4, nan, 12.6, 5.8, 4.9)]

print(data.dtype.descr[:5])
# [('Stno', '<i8'), ('DateHourNMT', '|S16'), ('CD', '<f8'), ('CD147', '<f8'), ('CD15', '<f8')]
print(type(data))
# <class 'numpy.ma.core.MaskedArray'>

rawDescription: Set one specific date type for reading in genfromtxt


code:
def_tagger = nltk.DefaultTagger('NN')
def_tagger.tag(tokens)

rawDescription: NLTK tagger reading from txt

description: NLTK tagger reading from txt


rawDescription: Python - Initializing List variable from List elements


code:
words = [str(cell.value) for cell in Table.col(0)] #list comprehension
abbr = [str(cell.value) for cell in Table.col(1)]
replacements = zip(words, abbr)

rawDescription: Optimizing excel data collection/reduction using xlrd/xlwt and loop iteration


code:
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.decomposition import PCA

class MaskedPCA(BaseEstimator, TransformerMixin):

    def __init__(self, n_components=2, mask=None):
        # mask should contain selected cols. Suppose it is boolean to avoid code overhead
        self.n_components = n_components
        self.mask = mask

    def fit(self, X):
        self.pca = PCA(n_components=self.n_components)
        mask = self.mask
        mask = self.mask if self.mask is not None else slice(None)
        self.pca.fit(X[:, mask])
        return self

    def transform(self, X):
        mask = self.mask if self.mask is not None else slice(None)
        pca_transformed = self.pca.transform(X[:, mask])
        if self.mask is not None:
            remaining_cols = X[:, ~mask]
            return np.hstack([remaining_cols, pca_transformed])
        else:
            return pca_transformed

rawDescription: pipeline with PCA on feature subset only in scikit-learn

description: Pipeline with PCA on feature subset only in scikit-learn


code:
listdict = defaultdict(list)
listdict['Cake'] = ['cheesecake','icecream cake','oreo-cheesecake']

rawDescription: Accessing list values in a defaultdict(list) type


code: computeStats(scipy.stats.mstats.ks_twosamp, sampleA, sampleB, alternative='greater')

rawDescription: Python: pass function as parameter, with options to be set


code: client.images.data(img) # or img.data()

rawDescription: Openstack python API: how to download image from glance using the python api


rawDescription: Matplotlib: draw lines with width given in data coordinates


code:
'the quick brown fox'.split()
'빨른 깨를 있어요'.split()
'el zorro marron rapido'.split()

rawDescription: Regex not splitting text the same way

description: Regex not splitting text the same way


code:
firstline = True
for row in kidfile:
    if firstline:    #skip first line
        firstline = False
        continue
    # parse the line

rawDescription: Python skip First line(field) in loop using CSV file?


code:
import sys, csv

d = {'time_final': 1323494016.8556759,
     'time_init': 1323493818.0042379,
     'time_lapsed': 198.85143804550171
}

d = dict((k, repr(v)) for k, v in d.items())

fieldnames = ('time_init', 'time_final', 'time_lapsed')
myWriter = csv.DictWriter(sys.stdout, fieldnames=fieldnames)
headers = dict( (n,n) for n in fieldnames )
myWriter.writerow(headers)
myWriter.writerow(d)

rawDescription: Python - csv.DictWriter() or writerow() rounding my floats?


code:
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))

rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
import csv
with open('A','rb') as f1, open('B','rb') as f2, open('out.csv','wb') as w:
    writer = csv.writer(w)
    r1,r2 = csv.reader(f1),csv.reader(f2)
    while True:
        try:
            writer.writerow(next(r1)+next(r2))
        except StopIteration:
            break

rawDescription: Combining CSV files column-wise

description: Combining CSV files column-wise


code: result = val

rawDescription: Accessing elements in arbitarily nested structure of lists / dicts


code:
d = defaultdict(int)
for k, v in item_list:  # unwrapping credits to @clemtoy
    d[k] += v
result = [[k, v] for k, v in d.iteritems()]

rawDescription: Best way to remove/merge duplicates in this list?

description: Remove/merge duplicates in this list


code:
def getScreen():
    # Grab image and crop it to the desired window. Find pixel borders manually.
    box = (left, top, right, bottom)
    im = ImageGrab.grab().crop(box)
    #im.save('testcrop.jpg')  # optionally save your crop

    for y in reversed(range(8)):
        for x in reversed(range(8)):
            #sqh,sqw are the height and width of each piece.
            #each pieceim is one of the game piece squares
            piecebox = ( sqw*(x), sqh*(y), sqw*(x+1), sqh*(y+1))
            pieceim = im.crop(piecebox)
            #pieceim.save('piececrop_xy_'+ str(x) + str(y) + '.jpg')

            stats = ImageStat.Stat(pieceim)
            statsmean = stats.mean
            Rows[x][y] = whichpiece(statsmean)

rawDescription: Process image from screenshot - Python

description: Process image from screenshot - Python


code: combined = esh.merge(esm, left_index=True, right_index=True)

rawDescription: Build Back Adjusted Continous Futures contract from Historical Data


code:
class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyFormForm, self).__init__(*args, **kwargs)
        self.fields['title'].widget.attrs['style'] = "width:200px"

rawDescription: Django - Specify width of django.db.models.(???)Field forms


code:
for q_num, q in enumerate(questions, start=1):
    print("{}. {}".format(q_num, q['question']))
    ...

rawDescription: Is there a way to attach a 3rd value in Python dictionaries?


code: sum([a, b], axis=0)

rawDescription: python element wise add in list of list with other list

description: Python element wise add in list of list with other list


code:
import re
import os
import glob
import pprint

candidateDataList = []
for file in glob.glob("*.txt"):
    with open(file, 'r') as f:

        #This pulls the first line of the resume,
        #Which is generally the name.
        first_line_name = f.readline().strip()

        #This pulls the Email from the resume.
        bulkemails = f.read()
        r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)')
        candidateDataList.append({'name':str(first_line_name),
                                  'email':r.findall(bulkemails)})

pprint.pprint(candidateDataList)

rawDescription: running data parser on multiple files in folder? Python

description: Running data parser on multiple files in folder? Python


code: return [i for i in a if -1*i in a]

rawDescription: How to "negate"(?) a list - Python

description: "negate"(?) a list - Python


code:
from django.db.models.signals import post_save
# method for updating latest users
def update_latest_users(sender, instance, created, **kwargs):
     if created:
         lu = LatestUsers.objects.all()[0]
         # Limit to maximally track the latest 6 users
         lu.latest_users = lu.latest_users.order_by('-date_joined')[:5]
         lu.latest_users.add(instance)

# register the signal
post_save.connect(update_latest_users, sender=User, dispatch_uid="update_latest_users")

rawDescription: Fastest way to retrieve newly registered users' instances in Django web app


code:
def is_match(word, match):
    # Test if all the characters in word are also in match.
    return all(c in match for c in word)

def has_any_match(main, match):
    # Test if there is any word in main that matches.
    return any(is_match(word, match) for word in main)

rawDescription: best way to match these string or list?

description: Match these string or list


code: d = numpy.vstack((a, b, c)).T.flatten()

rawDescription: Numpy union arrays in order

description: Numpy union arrays in order


code:
def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False

    return True

rawDescription: isPrime Function for Python Language

description: IsPrime Function for Python Language


code: df1.drop('Join', axis=1, inplace=True)

rawDescription: VLOOKUP Excel analog in pandas python

description: VLOOKUP Excel analog in pandas python


code:
f = file('myfile.txt','w')
f.write(s)
f.close()

rawDescription: Outputting to a file

description: Outputting to a file


code:
class A(object):
    def say(self):
        print('Hello', self.name)

class B(object):
    def rename(self, name):
        self.name = name + name

a = A()
B.rename(a, 'josh')
a.say()

rawDescription: Universally create Derived class from Base in python


rawDescription: Passing a dict of dict with Ajax

description: Passing a dict of dict with Ajax


rawDescription: QGIS: How to run R directly in python console?


code:
from xlrd import open_workbook

book = open_workbook(path_to_file)
sheet = book.sheet_by_index(0)
for i in range(1, sheet.nrows):
    row = sheet.row_values(i)
    variable = row[0]  # Instead zero number of certain column

rawDescription: How to grab the value in a certain column in a certain row using XLRD

description: Grab the value in a certain column in a certain row using XLRD


code: np.count_nonzero(fs >= 0.75)

rawDescription: Want to count the number of values in a column that meet a condition


code: player1.health = min(player1.health, player1.max_health)

rawDescription: Having a Function change variable in Python 3.4?


code:
someSet = set(someList)
someDict.viewkeys() & someSet

rawDescription: Optimize the performance of dictionary membership for a list of Keys


code:
mask = (df['RF'] > 0)
df['mask'] = mask
#      RF   mask
# 0   0.3   True
# 1   1.1   True
# 2   0.2   True
# 3   0.0  False
# 4   0.0  False
# 5   0.0  False
# 6   0.0  False
# 7   0.0  False
# 8   1.1   True
# 9   0.6   True
# ...

rawDescription: How to identify approximately (threshold defined) continuous non null data using pandas?

description: Identify approximately (threshold defined) continuous non null data using pandas


code:
# N.B. 4 hours times 60 minutes in an hour times 60 seconds
# in a minute times 1000 milliseconds in a second
root.after(4*60*60*1000, myCode)

rawDescription: How can I make Tkinter in python to do every code in certain amount of time?

description: Make Tkinter in python to do every code in certain amount of time


code:
class Person(Structure): _fields_ = [("name", c_ubyte * 8), ('age', c_ubyte)]

smith = Person((c_ubyte * 8)(*bytearray('Mr Smith')), 9)
smith.age
cast(smith.name, c_char_p).value

rawDescription: How to print c_ubyte_Array object in Python

description: Print c_ubyte_Array object in Python


code:
def is_number(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

rawDescription: Calculate two values and calculate difference in percentage in Django


rawDescription: Loading a config file from operation system independent place in python


code:
for line in f:
    dict_st=dict()
    for item in line.split():
        k, v = map(int, item.split('-'))
        dict_st.setdefault(k, set()).add(v)

rawDescription: Creating dictionaries in a faster way - Python


code:
recent = my_table.objects.filter(date__lt=datetime.date.today()) \
                         .latest('date')

rawDescription: Django-Getting most recent entry before today


code:
import string
help(string.find)

rawDescription: Is there a difference between -1 and False in Python?


code:
with open('yourfilehere','r') as f:
    s = f.read()
# put the string of both request and response into 'req' and 'res'
# or you need to construct a better re.search if you have multiple requests, responses
req = [re.search(r'<request.*\/request>', s).group()]
res = [re.search(r'<response.*\/response>', s).group()]

req
['<request xmlns="XXX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><transactionheader><username>XXX</username><password>XXX</password><time>31/10/2014 12:27:33</time><clientreferencenumber>123</clientreferencenumber><numberrequests>3</numberrequests><information>Description</information><postbackurl>http://localhost/status</postbackurl></transactionheader><transactiondetails><items><item id="1" client="XXX1" keyword="test"/><item id="2" client="XXX2" keyword="test"/><item id="3" client="XXX3" keyword="test"/></items></transactiondetails></request>']

res
['<response xmlns="XXX" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><serverreferencenumber>XXX123XXX</serverreferencenumber><clientreferencenumber>123</clientreferencenumber><information>Queued for Processing</information><status>OK</status></response>']

rawDescription: How to extract xml from log file to parse in python

description: Extract xml from log file to parse in python


code:
import intf
from scipy import integrate
data = np.load(path)
y = data['arr_1']
t = data['arr_0']

bI2= sp.integrate.cumtrapz(y-y.mean(),x=t)
bI3 = intf.intf(y-y.mean(), fs=500458, f_lo=1, winlen=1e-2, times=1)

rawDescription: Integration in Fourier or time domain

description: Integration in Fourier or time domain


code:
timestr = timestr.replace('a.m.', 'AM')
import datetime
timestamp = datetime.datetime.strptime(timestr, "%d/%m/%Y %I:%M:%S %p")
timestamp

rawDescription: Python putting certain texts into a dictionary from a large string


code:
import numpy as np
import pandas as pd

def h5store(filename, df, **kwargs):
    store = pd.HDFStore(filename)
    store.put('mydata', df)
    store.get_storer('mydata').attrs.metadata = kwargs
    store.close()

def h5load(store):
    data = store['mydata']
    metadata = store.get_storer('mydata').attrs.metadata
    return data, metadata

a = pd.DataFrame(
    data=pd.np.random.randint(0, 100, (10, 5)), columns=list('ABCED'))

filename = '/tmp/data.h5'
metadata = dict(local_tz='US/Eastern')
h5store(filename, a, **metadata)
with pd.HDFStore(filename) as store:
    data, metadata = h5load(store)

print(data)
#     A   B   C   E   D
# 0   9  20  92  43  25
# 1   2  64  54   0  63
# 2  22  42   3  83  81
# 3   3  71  17  64  53
# 4  52  10  41  22  43
# 5  48  85  96  72  88
# 6  10  47   2  10  78
# 7  30  80   3  59  16
# 8  13  52  98  79  65
# 9   6  93  55  40   3

rawDescription: Save additional attributes in Pandas Dataframe


code: np.genfromtxt(('0,'+line for line in open('data.txt')),delimiter=',')

rawDescription: Creating numpy array with empty columns using genfromtxt


code:
MyModel.objects.filter(
                       primaryid=1987
                      ).exclude(
                       timestamp__lt=min_timestamp
                      ).exclude(
                       timestamp__gt=max_timestamp
                      ).values_list('valuefield', flat=True)

rawDescription: Django - SQL Query - Timestamp

description: Django - SQL Query - Timestamp


code:
import numpy as np

def zigzag(seq):
    try:
        if len(seq.shape) == 1:
            return seq[::2], seq[1::2]
    except AttributeError:
        return [zigzag(x) for x in seq]

def main():
    options = _parse_args()

    seq = np.array([1,1,5,1,5,5,1,5,1,1])
    seq2 = (
        np.array([1, 1, 5, 1, 5, 5, 1, 5, 1, 1]),
        np.array([2, 2, 2, 3, 3, 3, 3, 2, 2, 2]),
        np.array([6, 3, 9, 2, 9, 4, 6, 3]),
    )

    print(zigzag(seq))
    print()
    print(zigzag(seq2))

rawDescription: Python : How to vectorize my split function with Numpy


code:
import struct
from collections import namedtuple
data = "1"*24
fmt = "20si"
Rec = namedtuple('Rec', 'text index')
r = Rec._make(struct.unpack_from(fmt, data))
r

rawDescription: Is there an elegant way to use struct and namedtuple instead of this?


code:
dateindex = series.index.get_level_values('date')
# Ensure the dateindex is a DatetimeIndex (as opposed to a plain Index)
dateindex = pd.DatetimeIndex(dateindex)

rawDescription: Pandas: Select from date in MultiIndex

description: Pandas: Select from date in MultiIndex


code:
x = np.array(((range(10), range(10)), (range(10), range(10))))
print(x)

rawDescription: Numpy.cumsum in reverse

description: Numpy.cumsum in reverse


rawDescription: Read/Write a dictionary with values as integer lists in a csv file in python 2.6.x


code:
def max_diff_date(g):
    g = g.sort(columns=['date'])
    return g.col2.ix[(g.date.ix[1: ] - g.date.shift(1)).argmax() - 1]

rawDescription: Calculating the difference in dates in a Pandas GroupBy object


code: assert json.loads(s1) == json.loads(s2)

rawDescription: python: is there a well-known function to normalize JSON representation of data?

description: Python: is there a well-known function to normalize JSON representation of data


code:
from django.db import models
from django.contrib.auth.models import User

class Event(models.Model):
    title = models.CharField(max_length=100)
    datetime = models.DateTimeField()
    num_views = models.IntegerField()

rawDescription: How to get the count of views of a particular event?

description: Get the count of views of a particular event


code:
string = "The boy who cried wolf made many many silly mistakes."
def f(n):
    alpha_chars = filter(lambda char: char.isalpha(), string)
    greater_chars = 0
    for char in list(set(alpha_chars)):
        if string.count(char) > n:
            greater_chars += 1
    return greater_chars

rawDescription: Finding the number of letters that occur more than a specific number of times on python?


code:
def group_by_start(inputlist, n):
    return (list(g) for k, g in groupby(inputlist, key=itemgetter(slice(n))))

rawDescription: Python. How to make list from another list by mark?


code:
od = OrderedDict()
import csv

with open("data.csv") as f, open("new.csv", "w") as out:
    r = csv.DictReader(f,fieldnames=['Location', 'MovieDate', 'Formatted_Address', 'Lat', 'Lng'])
    wr = csv.DictWriter(out, fieldnames=r.fieldnames)
    for row in r:
        od.setdefault(row["Location"], dict(Location=row["Location"], Lat=row["Lat"], Lng=row["Lng"],
                                        MovieDate=[], Formatted_Address=row["Formatted_Address"]))

        od[row["Location"]]["MovieDate"].append(row["MovieDate"])
    for loc, vals in od.items():
        od[loc]["MovieDate"]= ", ".join(od[loc]["MovieDate"])
        wr.writerow(vals)

rawDescription: python ordered dict issue

description: Python ordered dict issue


code:
n, nf = 2, 4
x = [str(i) for i in range(n * nf)]
y = [str(i*2) for i in range(n * nf)]
ID = [str(10*i) for i in range(nf)]
OutputFile = open('output2.txt', 'w')
nx = len(x)
for i in range(0, len(x), nf):
    OutputFile.write(ID[i//nf] + "\t" + x[i] + "\t" + y[i] + "\t" +  x[i+1] + "\t" + y[i+1] + "\t" + x[i+2] + "\t" + y[i+2] + "\t" + x[i+3] + "\t" + y[i+3] + "\n")
OutputFile.close()

rawDescription: writing lines to a txt file python

description: Writing lines to a txt file python


code:
def f(*args):
   args = numpy.asarray(args[0]) if len(args) == 1 else numpy.asarray(args)
   return args

f(7,3,5)
f([1,2,3])
f((2,3,4))
f(numpy.array([1,2,3]))

rawDescription: Python function to accept numpy ndarray or sequence as arguments


code: f = open('/tmp/hippo.txt','w')

rawDescription: Easy way to tell apart python multiprocessing's OS processes


rawDescription: Python: Frequency of occurrences

description: Python: Frequency of occurrences


code: df

rawDescription: Only allow one to one mapping between two columns in pandas dataframe


code:
context = {
    'query': form.cleaned_data['q'],
    'businesslist': businesslist,
    'paginator': paginator,
}

return render_to_response('businesslist.html', context, context_instance=RequestContext(request))

rawDescription: Django display search keyword and count in template


type: Tagged

rawDescription: Convert JSONObject into JSONArray using Python


code: pix.reshape(3, 10).transpose()

rawDescription: How to reshape pixel list into RGB matrix?

description: Reshape pixel list into RGB matrix


code:
now = datetime.datetime.now()
now_frmt = now - datetime.timedelta(microseconds=now.microsecond)

rawDescription: Python: format datetime efficiently whilst leaving it as a datetime object


code:
import datetime
import atexit

def leaving():
   open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())

atexit.register(leaving)

rawDescription: Log the time a python script stopped?

description: Log the time a python script stopped


rawDescription: Remove special chracters from a string in django


code:
inside = ['thing', 'other thing']
inside.append('another thing')
inside

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


rawDescription: Pandas Dataframe splitted into weeks

description: Pandas Dataframe splitted into weeks


code:
# create a NumPy array for use as our data set
import numpy as NP
D = NP.random.randint(0, 10, 40).reshape(8, 5)
# create some generic row and column names to pass to the constructor
row_ids = [ "row{0}".format(c) for c in range(D1.shape[0]) ]
rows = 'rows_id', row_ids
variables = [ "col{0}".format(c) for c in range(D1.shape[1]) ]
cols = 'variable', variables

rawDescription: How do I index n sets of 4 columns to plot multiple plots using matplotlib?

description: Index n sets of 4 columns to plot multiple plots using matplotlib


code:
from itertools import islice
with open(filename, 'r') as infile:
    lines_gen = islice(infile, N)

rawDescription: How to read file N lines at a time in Python?

description: Read file N lines at a time in Python


code:
items = ['aaa','sss','ddd','fff','gggg','hhhh']
indices = [1,3,4]
from operator import itemgetter
import timeit
getter = itemgetter(*indices)
def list_comp(items=items,indices=indices):
    return [items[i] for i in indices]

timeit.timeit('getter(items)','from __main__ import getter,items')
timeit.timeit('list_comp()','from __main__ import list_comp')
getter(items)
list_comp()

rawDescription: python find items in a list given indices

description: Python find items in a list given indices


code:
from scipy.interpolate import interp1d
i = interp1d(a,b)
i(2123)

rawDescription: SciPy interpolation ValueError: x and y arrays must be equal in length along interpolation axis


code:
data = [
    model_to_dict(object).values() + [object.storeID.StoreName]
    for object in objects
]

rawDescription: Django loading dictionary values into JSON


code: Counter((item[0], item[1]) for item in a if len(item) >= 2)

rawDescription: Searching for a word pattern in a Python dataset


code:
z = map(str, x)
z

rawDescription: How To Change Lists of Unicode to ASCII

description: How To Change Lists of Unicode to ASCII


rawDescription: Easy way to test if each element in an numpy array lies between two values?


code:
wlock = _semaphores_rwlock.writer() #this might take a while; it waits for all readers to release
cleanup(_semaphores)
wlock.release()

rawDescription: Dynamically allocating and destroying mutexes?


code:
import sympy
import subprocess
def print_to_file( guy, append=False ):
    flag = 'w'
    if append: flag = 'a'
    outfile = open(r'print.txt', flag)
    outfile.write('\n')
    outfile.write( sympy.pretty(guy, wrap_line=False) )
    outfile.write('\n')
    outfile.close()
    subprocess.Popen( r'notepad.exe print.txt' )

print_to_file( B*g )
print_to_file( ans, append=True )

rawDescription: Differential Operator usable in Matrix form, in Python module Sympy


code: records = []

rawDescription: CSV programming read write

description: CSV programming read write


code: modified

rawDescription: Multiple positional arguments with Python and argparse


code:
g = sns.factorplot("day", col="sex", row="smoker",
               data=tips, margin_titles=True, size=3,
               x_order=top_two_ordered)

rawDescription: seaborn FacetGrid , ranked barplot separated on row and col

description: Seaborn FacetGrid , ranked barplot separated on row and col


rawDescription: Python Pandas - how to apply boolean series to extract rows from dataframe


code: values = [d[key] for key in keys]

rawDescription: Having list of keys, get list/tuple of values from dict


rawDescription: How can I get from 'pyspark.sql.types.Row' all the columns/attributes name?

description: Get from 'pyspark.sql.types.Row' all the columns/attributes name


code:
print("func.__name__:", func.__name__)
print("func2.__name__:", func2.__name__)

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
def substitute_args(arg_sub_dict):
  def my_decorator(fun):
    def wrapper(arg):
      new_arg = arg_sub_dict.get(arg, arg)
      return fun(new_arg)
    # magic to update __name__, etc.
    return wrapper
  return my_decorator

rawDescription: Python Decorator 3.0 and arguments to the decorator


rawDescription: How do i turn `[(1, 'item1'),(2, "item2"),(2, "item3"),(3, "item4"),(2, "item5")]` into a JSON tree and HTML tree in python?

description: Turn `[(1, 'item1'),(2, "item2"),(2, "item3"),(3, "item4"),(2, "item5")]` into a JSON tree and HTML tree in python


code:
def original_app(labeled_array,num_features,thresh):
    big_zones = np.zeros((my_np_array.shape), dtype=np.bool)
    for i in range(1, num_features):
        zone_array = (labeled_array == i)
        zone = np.sum(zone_array)
        if zone > thresh:
            big_zones += zone_array
    return big_zones

def vectorized_app(labeled_array,num_features,thresh):
    matches = np.bincount(labeled_array.ravel())>thresh
    match_feat_ID = np.nonzero(matches)[0]
    valid_match_feat_ID = np.setdiff1d(match_feat_ID,[0,num_features])
    return np.in1d(labeled_array,valid_match_feat_ID).reshape(labeled_array.shape)

rawDescription: Select size filtered elements in a large array (raster)


rawDescription: join corresponding column to dataframe pandas

description: Join corresponding column to dataframe pandas


code:
fig = pyplot.gcf()
fig.set_size_inches([4., 3.])
# Default size: [8., 6.]

rawDescription: What is the difference between 'log' and 'symlog'?


rawDescription: How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?

description: Set the x-axis tick locations for a bar plot created from a pandas DataFrame


code:
def initializePumpThread():
    global pumpedThread
    global app
    if pumpedThread == None:
        app = QtGui.QApplication(sys.argv)
        pumpedThread = threading.Thread(target = pumpQt, args = ())
        pumpedThread.start()

rawDescription: Using external GUI libraries to make user interfaces in Autodesk Maya


code: fav_druds = request.user.favorite_set.values_list('drud', flat=True)

rawDescription: Django, revover a model with multi foreign key


code: words = re.findall("\b\w*")

rawDescription: A regular expression for finding a word within a string exactly "n" times


rawDescription: Python PyQt4 how to open image using QFileDialog


code:
# myproject/account/templatetags/account_admin.py

from django.template import Library

register = Library()

def admin_list_group_filter(cl, spec, groups):
    return {'title': spec.title(), 'choices' : list(spec.choices(cl)), 'groups': groups }
admin_list_group_filter = register.inclusion_tag('admin/auth/group_filter.html')(admin_list_group_filter)

rawDescription: Possible to limit filters ManyToMany/Foreign Key in Django admin for a model where the relationship is defined on the other model?


code: [unicodedata.category(c) for c in a]

rawDescription: Playing around with Devanagari characters


code:
{'Bob Dylan\n': ['1966 Blonde on Blonde',
                 '-Rainy Day Women #12 & 35',
                 '-Pledging My Time',
                 '-Visions of Johanna',
                 '-One of Us Must Know (Sooner or Later)',
                 '-I Want You',
                 '-Stuck Inside of Mobile with the Memphis Blues Again',
                 '-Leopard-Skin Pill-Box Hat',
                 '-Just Like a Woman',
                 "-Most Likely You Go Your Way (And I'll Go Mine)",
                 '-Temporary Like Achilles',
                 '-Absolutely Sweet Marie',
                 '-4th Time Around',
                 '-Obviously 5 Believers',
                 '-Sad Eyed Lady of the Lowlands'],
 'Led Zeppelin\n': ['1979 In Through the Outdoor',
                    '-In the Evening',
                    '-South Bound Saurez',
                    '-Fool in the Rain',
                    '-Hot Dog',
                    '-Carouselambra',
                    '-All My Love',
                    "-I'm Gonna Crawl",
                    '1969 II',
                    '-Whole Lotta Love',
                    '-What Is and What Should Never Be',
                    '-The Lemon Song',
                    '-Thank You',
                    '-Heartbreaker',
                    "-Living Loving Maid (She's Just a Woman)",
                    '-Ramble On',
                    '-Moby Dick',
                    '-Bring It on Home']}

rawDescription: Append items to dictionary Python

description: Append items to dictionary Python


rawDescription: Python's .format() minilanguage and Unicode


code:
import json

password_for_key = {'password': 'myPassword'}
authentication_token = {'auth_token': 'passwordlesstokenphg'}

requests.put('https://build.phonegap.com/api/v1/keys/ios/193686',
             data={'data': json.dumps(password_for_key)},
             params=authentication_token)

rawDescription: Python Requests Put not working with build.phonegap.com


code:
def diagnosis_major(line):
    return line[0:3]

def diagnosis_minor(line):
    return line[3:5]

def age(line):
    return int(line[5:7])

def sex(line):
    return line[7]

counter = HierarchicCounter(
    diagnosis_major, {diagnosis_minor: {sex: {}}, age: {}})

rawDescription: Python parsing large text files and capturing multi-level data


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import boto.sqs
from boto.sqs.message import RawMessage
import sys                               #  <== added this line

reload(sys)                              #  <== added this line
sys.setdefaultencoding('utf-8')          #  <== added this line

# print boto.Version
sqs_conn = boto.sqs.connect_to_region(
    'my_region',
    aws_access_key_id='my_kye',
    aws_secret_access_key='my_secret_ky')
queue = sqs_conn.get_queue('my_queue')
queue.set_message_class(RawMessage)

msg = RawMessage()

body = '1 café, 2 cafés, 3 cafés ...'
msg.set_body(body)
queue.write(msg)

rawDescription: (python/boto sqs) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)


code:
print
from __future__ import print_function
print

rawDescription: What is __future__ in Python used for and how/when to use it, and how it works


code:
class PostEditForm(forms.ModelForm):
    class Meta:
         model = Post

rawDescription: Django: How to create forms for each element on the page?


rawDescription: How to get euclidean distance on a 3x3x3 array in numpy

description: Get euclidean distance on a 3x3x3 array in numpy


code:
maximum = current = sum(a[:50000])
current

rawDescription: Python sum of N consecutive digits of a large number


rawDescription: How do I check the methods that an object has, in Python?

description: Check the methods that an object has, in Python


code:
discountValues['UpperLimit1'] = int(firstLine[2]) # int() converts string to int
discountValues['PercentDiscount1'] = int(firstLine[4])

rawDescription: Converting dictionary value to integer

description: Converting dictionary value to integer


rawDescription: For Loop Count Single Word String Not Work?


rawDescription: Python: Ordering partial elements in List for Genetic Algorithm


code:
class MyArray:

    def __init__(self, arr):
        self.arr = arr

rawDescription: In python 3, how can I convert a function into an attribute


code:
for i in range(3):
    capture = cv.CaptureFromCAM(i)
    if capture: break

rawDescription: Displaying a webcam feed using OpenCV and Python


code:
def testFlyCode(FlyessInput, Fly):
    for line in FlyessInput:
        if any(e in line for e in Fly):
            print('FlyMatchedOutput', line)
        else:
            print('FlyNotMatchedOutput', line)

FlyessInput = [[1, 2, 3], [2, 3, 4]]
Fly = [1, 2]
testFlyCode(FlyessInput, Fly)

Fly = [1, 12]
testFlyCode(FlyessInput, Fly)

rawDescription: Python - If any element in list is in line


code: ''.join(x for x in your_string if x.isdecimal())

rawDescription: How to remove all non-integer values in python

description: Remove all non-integer values in python


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
ax = plt.gca() # get axis handle
line = ax.lines[0] # get the first line, there might be more
line.get_xdata()
line.get_ydata()
line.get_xydata()

rawDescription: Retrieve XY data from matplotlib figure

description: Retrieve XY data from matplotlib figure


code:
def calc_polygons_new(startx, starty, endx, endy, radius):
    sl = (2 * radius) * math.tan(math.pi / 6)

    # calculate coordinates of the hexagon points
    p = sl * 0.5
    b = sl * math.cos(math.radians(30))
    w = b * 2
    h = 2 * sl

    # offsets for moving along and up rows
    xoffset = b
    yoffset = 3 * p

    row = 1

    shifted_xs = []
    straight_xs = []
    shifted_ys = []
    straight_ys = []

    while startx < endx:
        xs = [startx, startx, startx + b, startx + w, startx + w, startx + b, startx]
        straight_xs.append(xs)
        shifted_xs.append([xoffset + x for x in xs])
        startx += w

    while starty < endy:
        ys = [starty + p, starty + (3 * p), starty + h, starty + (3 * p), starty + p, starty, starty + p]
        (straight_ys if row % 2 else shifted_ys).append(ys)
        starty += yoffset
        row += 1

    polygons = [zip(xs, ys) for xs in shifted_xs for ys in shifted_ys] + [zip(xs, ys) for xs in straight_xs for ys in straight_ys]
    return polygons

rawDescription: Faster way to calculate hexagon grid coordinates


code: ips = [dic[k][1] for k in dic.keys()]

rawDescription: Scanning thorugh lists inside a dictionary of selected groups


code:
* EFFECTIVE_URL
* HTTP_CODE
* TOTAL_TIME
* NAMELOOKUP_TIME
* CONNECT_TIME
* PRETRANSFER_TIME
* REDIRECT_TIME
* REDIRECT_COUNT
* SIZE_UPLOAD
* SIZE_DOWNLOAD
* SPEED_UPLOAD
* HEADER_SIZE
* REQUEST_SIZE
* CONTENT_LENGTH_DOWNLOAD
* CONTENT_LENGTH_UPLOAD
* CONTENT_TYPE
* RESPONSE_CODE
* SPEED_DOWNLOAD
* SSL_VERIFYRESULT
* INFO_FILETIME
* STARTTRANSFER_TIME
* REDIRECT_TIME
* REDIRECT_COUNT
* HTTP_CONNECTCODE
* HTTPAUTH_AVAIL
* PROXYAUTH_AVAIL
* OS_ERRNO
* NUM_CONNECTS
* SSL_ENGINES
* INFO_COOKIELIST
* LASTSOCKET
* FTP_ENTRY_PATH

rawDescription: Getting DNS resolution time and response time with Python


code: df.merge(reduce(pd.DataFrame.combine_first, [pd.ewma(df[['PX_LAST']].resample(w), span=10) for w in lista4]), left_index=True, right_index=True)

rawDescription: Ewma in pandas but over rolling weekly data.


code: fp = file_with_pos(sys.stdin)

rawDescription: How to get byte offset in a file in python

description: Get byte offset in a file in python


code:
import numpy as np
blank = np.empty([4,4])

rawDescription: How to reshape 2D arrays?

description: Reshape 2D arrays


rawDescription: mongo - find items who at least match an array of values

description: Mongo - find items who at least match an array of values


code:
t = open(meno_suboru)
# open a file to read in
j = 0
# initialise line counter
self.pole = []
# create list to hold things
self.dvere = {}
# create dictionary to hold other things
while True:
# loop until condition met
    riadok = t.readline().strip()
    # get the next line from t and strip the newline character, whitespace etc
    if newLine == '':
    # if we've reached a blank line
        break
        # we're done
    for i in range(len(riadok)):
    # count through the characters in the new line
        if riadok[i] == 'v':
        # if current character is a 'v'
            self.vajce = Vajce(i*40+20, j*40+20)
            # create a new Vjace object and set to self.vajce
            raidok = riadok.replace('v','.')
            # replace all 'v's in the line with '.'s to prevent further matches
            # so we only ever have one self.vjace
        if newLine[i] == 'z':
        # if current character is a 'z'
            self.dvere[j,i] = Dvere(i*40, j*40)
            # same as before, but self.dvere is a dictionary so we
            # keep any previous Dvere objects too - dictionary key
            # is a tuple (j, i)
    self.pole.append(list(riadok))
    # turn the line into a list of characters and add to the self.pole list
    j += 1
    # increment the line counter

rawDescription: Two dimensional array from file

description: Two dimensional array from file


code:
if last_key != key:
    k = key.split('|')
    v_id = k[0]
if v_id == 'a':
    if tot_cnt > 1:
        sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))
else:
    sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))

rawDescription: How to get the Reducer to emit according to key type

description: Get the Reducer to emit according to key type


code:
table.transpose()
table.where('9')

rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


code:
from subprocess import call
call("pip install your_dependency_name",shell=True)

rawDescription: install dependency in Bitnami Odoo Stack

description: Install dependency in Bitnami Odoo Stack


code: i, = np.where( a==value )

rawDescription: Index of element in Numpy array

description: Index of element in Numpy array


rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
import os.path
os.path.split(path)

rawDescription: Python: Get URL path sections

description: Python: Get URL path sections


code:
import re
text = '''this \sum 1,2 \end is three and \sum 2,3,4 \end is nine'''
def add(numbers):
    return sum(map(lambda x:int(x), numbers.split(",")))

re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)

rawDescription: Replace all occurrences of a regexp group after processing the strng in the group


rawDescription: Python add to a list that is a value of a key


code:
import json
import pandas

data = json.load(open('input.json', 'r'))

flightdata = []
for flight_position in data['flightPositions']:
    flight_id = flight_position['flightId']
    for position in flight_position['positions']:
        position['flightId'] = flight_id
        series = pandas.Series(position)
        flightdata.append(series)

df = pandas.DataFrame(flightdata)
print(df)

rawDescription: Properly extract data from JSON string

description: Properly extract data from JSON string


rawDescription: Permute 5 (or 6) lists

description: Permute 5 (or 6) lists


rawDescription: Merge three csv files with same headers in Python


code:
from collections import defaultdict
myNewDict = defaultdict(list)
for staff_id, names in myDict.items():
    for name in names:
        myNewDict[name].append(staff_id)

rawDescription: Extend dict from key/values pair to key/value pair in Python


rawDescription: Normalizing rows of a matrix python

description: Normalizing rows of a matrix python


code:
from Tkinter import *
import time

class Box:
    def __init__(self, canvas, type):
        self.canvas = canvas
        if type == "1":
            self.rect = canvas.create_rectangle(0, 0, 50, 50, fill="red")
        elif type == "2":
            self.rect = canvas.create_rectangle(50, 50, 100, 100, fill="blue")
        self.coords = canvas.coords(canvas, self.rect)

    def hide(self):
        # remember where this object was
        self.coords = canvas.coords(self.rect)
        # move it to an invisible part of the canvas
        self.canvas.move(self.rect, -1000, -1000)
    def unhide(self):
        # restore it to where it was
        self.canvas.coords(self.rect, *self.coords)

root = Tk()
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, width=500, height=200)
canvas.pack()

a = Box(canvas, type="1")
b = Box(canvas, type="2")

root.after(1000, a.hide)
root.after(2000, a.unhide)
root.after(3000, b.hide)
root.after(4000, b.unhide)

root.mainloop()

rawDescription: Getting Tkinter pack_forget to work only on unique objects


code: labels = dict( ((i, j), i + (N-1-j) * 10 ) for i, j in G.nodes() )

rawDescription: Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph


code:
dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday"]  # This is the array for the days.
consumedArray = [2600, 2400, 3500, 3200, 2700, 3300,
                 3000]  # This is the array for the calories consumed.
burnedArray = [150, 100, 200, 180, 250, 100,
               50]  # This is the array for the calories burned.

def main():  # This is the main module.
    calories = 0  #This is the variable for the calories.
    day = ""  #This is the variable for the day.
    letter = ""  #This is the variable for the letter.
    totals = 0  #This is the variable for the totals.
    difference = 0  #This is the variable for the differences.
    average = 0.0  #This is the variable for the average.
    max1 = 0  #This is the variable for the max.
    min1 = 0  #This is the variable for the min.
    flag = False  #This is the variable for the flag.
    counter = 1  #This is the variable for the counter.
    index = 1  #This is the variable for the index.
    intro()
    decisions()

def intro():  # This is the intro module.
    print(
        "Welcome to the program!! Enjoy!!")  #This is the message to welcome you to the program.
    print("*" * 60)  #Prints 60 stars.

def decisions():  # This is the decisions module.
    print("What do you want to do? ")  #This is asking you what you want to do.
    print("T = Get Totals")  #This is if you type in "T" you will get totals.
    print("D = Find Differences")  #This is if you type in "D" you will find differences.
    print("A = Find Averages")  #This is if you type in "A" you will find the averages.
    print("H = Find Highest")  #This is if you type in "H" you will find the highest.
    print("L = Find Lowest")  #This is if you type in "L" you will find the lowest.
    print('*' * 60)  #Prints 60 stars.
    flag = False
    while flag != True:  #This is the loop for letter doesnt equals E
        letter = str(input("What do you want to do? "))  #This is asking you what you want to do.
        print("You entered: ", letter)  #This is telling you what letter you have entered.
        if letter == "T":  #This is if letter is equal to T.
            print("like anything")
            totals()
            print("like anything")
        elif letter == "D":  #This is if letter is equal to D.
            differences()
        elif letter == "A":  #This is if letter is equal to A.
            averages()
        elif letter == "H":  #This is if letter is equal to H.
            max1()
        elif letter == "L":  #This is if letter is equal to L.
            min1()
        elif letter == "E":
            break

        else:
            print("restart and try again")  #Anything else end program
            break
            #when while loop ends end the program
    end1()

def differences():  # This is the differences module.
    print('*' * 60)  #Prints 60 stars.
    print(
        'Day          Calories Consumed          Calories Burned')  #This is the output for the column names.
    print('*' * 60)  #Prints 60 stars.
    for i in range(7):  #This is saying i is in the range of 7.
        x = consumedArray[i] - burnedArray[i]  #This is the formula for the differences.
        print("{0:10s} {1:12d}".format(dayArray[i],
                                       x))  #This is the output for the days and the differences.
    print('*' * 60)  #Prints 60 stars.
    print()
    # decisions()  #run decisions to restart the main content of the program

def totals():  # This is the totals module.
    print('*' * 60)  #Prints 60 stars.
    print(
        'Day          Calories Consumed          Calories Burned')  #This is the output for the column names.
    print('*' * 60)  #Prints 60 stars.
    for i in range(7):  #This is saying i is in the range of 7.
        print("{0:10s} {1:12d} {2:25d}".format(dayArray[i], consumedArray[i], burnedArray[
            i]))  #This is the output for the totals of days, consumed, and burned.
    print('*' * 60)  #Prints 60 stars.
    print()
    # decisions()  #run decisions to restart the main content of the program

def averages():  # This is the averages module.
    print('*' * 60)  #Prints 60 stars.
    average1 = sum(consumedArray) / len(
        consumedArray)  #This is the formula for the Average Calories Consumed.
    average2 = sum(burnedArray) / len(
        burnedArray)  #This is the formula for th Average Calories Burned.
    print(
        "Average Calories Consumed %.2f" % average1)  #This is the output for the Average Calories Consumed at 2 decimal places as a float.
    print(
        "Average Calories Burned %.2f" % average2)  #This is the output for the Average Calories Burned at 2 decimal places as a float.
    print('*' * 60)  #Prints 60 stars.
    print()
    # decisions()  #run decisions to restart the main content of the program

def max1():  # This the max1 module.
    print('*' * 60)  #Prints 60 stars.
    maxconsumed = max(
        consumedArray)  #This is finding the highest amount of calories consumed.
    maxburned = max(burnedArray)  #This is finding the highest amount of calories burned.
    i = consumedArray.index(
        maxconsumed)  #This is setting the highest amount of calories consumed in the index.
    j = burnedArray.index(
        maxburned)  #This is setting the highest amount of calories burned in the index.
    print("Highest Calories Consumed {0:10s} {1:2d}".format(dayArray[i],
                                                            maxconsumed))  #This is the output for the highest calories consumed.
    print("Highest Calories Burned {0:10s} {1:2d}".format(dayArray[i],
                                                          maxburned))  #This is the output for the highest calories burned.
    print('*' * 60)  #Prints 60 stars.
    print()
    # decisions()  #run decisions to restart the main content of the program

def min1():  # This is the min1 module.
    print('*' * 60)  #Prints 60 stars.
    minconsumed = min(
        consumedArray)  #This is finding the lowest amount of calories consumed.
    minburned = min(burnedArray)  #This is finding the lowest amount of calories burned.
    i = consumedArray.index(
        minconsumed)  #This is setting the lowest amount of calories consumed in the index.
    j = burnedArray.index(
        minburned)  #This is setting the lowest amount of calories burned in the index.
    print("Lowest Calories Consumed {0:10s} {1:2d}".format(dayArray[i],
                                                           minconsumed))  #This is the output for the lowest calories consumed.
    print("Lowest Calories Burned {0:10s} {1:2d}".format(dayArray[i],
                                                         minburned))  #This is the output for the lowest calories burned.
    print('*' * 60)  #Prints 60 stars.
    print()
    # decisions()  #run decisions to restart the main content of the program

def end1():  # This is the end module.
    print(
        "You have finished the program!!")  #This is telling you that you have finished the program.

main()  #This is telling the program to run all of the modules.

rawDescription: Python while loop logic

description: Python while loop logic


rawDescription: How to convert EST/EDT to GMT?

description: Convert EST/EDT to GMT


code: eval(repr(object)) == object

rawDescription: PHP equivalent for Python's repr()

description: PHP equivalent for Python's repr()


rawDescription: How does multiple function calls works in python 2.7


code: mystring = b'my cp1251 byte array'.decode('cp1251')

rawDescription: Changing encoding python 3

description: Changing encoding python 3


code: [x[1:-1] for x in '[abc] [def] [zzz]'.split()]

rawDescription: String split on specific characters

description: String split on specific characters


code:
if __name__ == '__main__':
    from twisted.internet import reactor
    reactor.listenTCP(1025, factory)
    reactor.run()
else:
    application = service.Application("chatserver")
    internet.TCPServer(1025, factory).setServiceParent(application)

rawDescription: How do you you run a Twisted application via Python (instead of via Twisted)?

description: You run a Twisted application via Python (instead of via Twisted)


code:
import turtle

def create_track(n, side=80, change=20):
    race = turtle.Turtle()
    for cnt in range(n+1):
        race.forward(side)
        race.circle(side,180)
        race.forward(side)
        race.circle(side,180)
        side = side + change
        race.penup()
        race.right(90)
        race.forward(change)
        race.right(-90)
        race.backward(change/2)
        race.pendown()

def main():
    n = int(input("How many lanes do would you want?\n"))
    create_track(n)

if __name__ == "__main__":
    main()

rawDescription: python use turtle draw a track n field race track

description: Python use turtle draw a track n field race track


code:
def countWords(s):
    words = s.split()
    count = 0
    for word in words:
        if len(word) >= 2:
            count += 1
    return count

rawDescription: Retrieving total number of words with 2 or more letters in a document using python


code: df[(df['emld'] == 'aol.com') & (df['bounce_type'] == 'hard')][['source_ip', 'tids']]

rawDescription: How to split pandas data frame by many criteria

description: Split pandas data frame by many criteria


rawDescription: pandas how to convert a dataframe into a dictionary of tuples tuple using 1 col as key and the rest as a tuple of form (col2:col3)

description: Pandas how to convert a dataframe into a dictionary of tuples tuple using 1 col as key and the rest as a tuple of form (col2:col3)


code:
from django.conf.urls import url, include
from yourapp import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'articles', views.ArticleViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]

rawDescription: Django REST Framework: difference between views and viewsets?


code:
match = True
for A, B in zip(a, b):
    if not same_structure(A, B):
        match = False
        break
return match

rawDescription: How to properly use recursion in this (simple) python procedure?

description: Properly use recursion in this (simple) python procedure


rawDescription: In Python is there a history of the function that i ran?


code:
result = session.query(Table1.field1, Table1.field2, field1_count).filter(
    Table1.user_id == self.user_id).filter(Table1.timestamp > self.from_ts).group_by(
    Table1.field1, Travelog.field2).order_by(desc('c')).first()

rawDescription: how use alias in sqlachemy

description: How use alias in sqlachemy


code: df = pd.concat(dataList.values(), axis=1, keys=dataList.keys())

rawDescription: Resampling and merging data frame with python


rawDescription: Parse wget log file in python

description: Parse wget log file in python


code:
from pprint import pprint

binary2ascii = {}
for i in range(65, 70):
    bits = format(i, "08b")
    char = chr(i)
    binary2ascii[bits] = char
    binary2ascii[char] = bits

pprint(binary2ascii)

rawDescription: Using a loop to make a dictionary

description: Using a loop to make a dictionary


code:
from django.db.models import Q
values = ['1.01', '1.02']
query = Q()
for value in values:
    query |= Q(name__startswith=value)
Inventary.objects.filter(query)

rawDescription: Filtering in Django by a set of String

description: Filtering in Django by a set of String


rawDescription: Change a text between two strings in Python with Regex


rawDescription: multiprocessing.Pool with maxtasksperchild produces equal PIDs

description: Multiprocessing.Pool with maxtasksperchild produces equal PIDs


code:
test = log.set_index('EventType', append=True)
test = test.groupby(level=[0,1])['EventID'].count('EventID')
test.unstack().fillna(0)

rawDescription: Pandas DataFrame.groupby including index


rawDescription: Data transformation for machine learning


code: result = np.where(np.isnan(a), 0, a * b)

rawDescription: Numpy: multiplying with NaN values without using nan_to_num


code:
sql = 'SELECT neighborhood, income, risk_factor FROM aprtable WHERE apr < ?'
args = [0.10]
cursor.execute(sql, args)
for neighborhood, income, risk_factor in cursor:
    print(neighborhood, income, risk_factor)

rawDescription: Dynamically fill a python dictionary

description: Dynamically fill a python dictionary


rawDescription: Python list rearranging

description: Python list rearranging


code:
d1 = numpy.arange(R.shape[0])[:,None]
d2 = indices[numpy.arange(R.shape[0])][:,None]
d3 = numpy.arange(R.shape[2])[None,:]
ri = R[d1,d2,d3]

bestepsilons = numpy.zeros(R.shape[0])+numpy.nan
d0 = numpy.nanmin(ri, axis=1) # places where the best index is not a nan
bestepsilons[~numpy.isnan(d0)] = epsilon[numpy.nanargmin(ri[~numpy.isnan(d0),:], axis=1)]

rawDescription: push for-loop to numpy

description: Push for-loop to numpy


code: values = [[func(val) for func,val in zip(f, X)] for f in itertools.product(funcs, repeat=len(funcs))]

rawDescription: Get all combinations of list multiple arrays


code:
# app_settings.py
from django.conf import settings

MY_SETTING = getattr(settings, 'APP_NAME_MY_SETTING', 'the_default_value')

rawDescription: add variables in settings to be used in views - Django

description: Add variables in settings to be used in views - Django


code:
def _remove_leading_zero(value, string):
    if 1 > value > -1:
        string = string.replace('0', '', 1)
    return string

class MyFloat(float):
    def __str__(self):
        string = super().__str__()
        return _remove_leading_zero(self, string)

    def __format__(self, format_string):
        string = super().__format__(format_string)
        return _remove_leading_zero(self, string)

rawDescription: Print floating point values without leading zero


rawDescription: Using variable content as part of file name of my output file


code:
def __bootstrap__():
  global __bootstrap__, __loader__, __file__
  import sys, pkg_resources, imp
  __file__ = pkg_resources.resource_filename(__name__, 'foo.so')
  __loader__ = None; del __bootstrap__, __loader__
  imp.load_dynamic(__name__,__file__)
__bootstrap__()

rawDescription: Sphinx autodoc functionality on Python-C-Extension


code:
arg_map = {1 : 'JOHN', 4 : 'SMITH', 8 : 'BEN'}
translated_result = map(arg_map.get, result_list)

rawDescription: Python: Best way to translate constants?

description: Python: Best way to translate constants


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

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z += 0.1*np.random.random(Z.shape)

rawDescription: Plotting contours over pcolormesh data

description: Plotting contours over pcolormesh data


rawDescription: How to save and load an array of complex numbers using numpy.savetxt?

description: Save and load an array of complex numbers using numpy.savetxt


code:
class MySurface:
    def __init__(api_surface):
        self.api_surface = api_surface

    width = surface_property('Width','Get and set the width.')
    height = surface_property('height', 'Get and set the height.')

rawDescription: Python property factory or descriptor class for wrapping an external library


code:
localpick = int(input('This is a list of locals, type the number of the local you want to talk to [1-5] \n'))
localx(localpick)  # We're now passing the value as a parameter.

rawDescription: Passing a variable between functions

description: Passing a variable between functions


code:
for line in file:
    for each_item in line:
        print(each_item[0]*each_item[1], end='')
    print()

rawDescription: Python Challenge - Level 5 , almost there


code: ~mask

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


rawDescription: pandas - find maximum of multilevel dataframe

description: Pandas - find maximum of multilevel dataframe


code:
n = 100000

a1 = np.random.uniform(0, 100, size=(n, 3))
a2 = a1[np.random.permutation(np.arange(n))] + np.random.normal(0, 1e-8, size=(n, 3))
from scipy import spatial
tree = spatial.cKDTree(a2)
dist, idx = tree.query(a1)
np.allclose(a1, a2[idx])

rawDescription: Order of elements in a numpy array

description: Order of elements in a numpy array


code:
P = np.eye(3)
for i, p in enumerate(piv):
    Q = np.eye(3,3)
    q = Q[i,:].copy()
    Q[i,:] = Q[p,:]
    Q[p,:] = q
    P = np.dot(P, Q)

rawDescription: How to understand the pivot matrix of scipy.linalg.lu_factor?

description: Understand the pivot matrix of scipy.linalg.lu_factor


code:
df.columns.map(lambda x: int(x[1:]))
df.columns = df.columns.map(lambda x: int(x[1:]))
df

rawDescription: Renaming columns in pandas dataframe using regular expressions


code:
import Tkinter as tk
import ttk
from page1 import Page1
from page2 import Page2

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill="both", expand=True)

        page1 = Page1(self.notebook)
        page2 = Page2(self.notebook)
        self.notebook.add(page1, text="Page 1")
        self.notebook.add(page2, text="Page 2")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: TTK Notebook Share data between imported tabs


code:
def for_loop_v2(A):
    n2 = A.shape[0]
    for i in range(n2):
        A[i] -= np.einsum('ij->j',B[y==i]) # OR (B[y==i]).sum(0)
    return A

rawDescription: Vectorize addition into array indexed by another array


code:
num = ['1', '2', '', '6']
L = [int(n) for n in num if n]
ave = sum(L)/float(len(L)) if L else '-'

rawDescription: Average of a list of numbers, stored as strings in a Python list


code:
from sklearn.cross_validation import KFold
threefold = KFold(n=10, n_folds=3)
for train, test in threefold:
   print("train: %r" % train)
   print("test:  %r" % test)

rawDescription: Is there an option to prevent the cross validation (and gridsearchCV) to randomize the rows of the dataset?


code: [x.as_integer_ratio() for x in arange(1,1.1,0.02)]

rawDescription: Dealing with floating points: With numpy python in particular


code:
def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

rawDescription: how to call stdout.write from subprocess.Popen?

description: Call stdout.write from subprocess.Popen


code:
B,C=[i for i in A if i<0 ],[j for j in A if j>0]
B
C

rawDescription: Python - Split a list of integers into positive and negative


code:
import csv

with open('Results.csv', 'rb') as inf, open('SSF1.txt', 'wb') as outf:
    site_id = inf.next().rstrip()  # read past site id on first line
    HBVout = csv.DictReader(inf, skipinitialspace=True)  # will read header line
    ssf = csv.writer(outf, delimiter='\t')

    for data in HBVout:
        date = data['Date']  # convert date from YYYYMMDD to MM/DD/YYYY
        date = '/'.join((date[4:6], date[6:8], date[0:4]))
        ssf.writerow([site_id, date, '00:00:00', data['Qsim']])

rawDescription: Converting a CSV file for Hydrologic Model


rawDescription: What's the best way to generate random strings of a specific length in Python?


rawDescription: How do I access embedded json objects in a Pandas DataFrame?

description: Access embedded json objects in a Pandas DataFrame


rawDescription: Apache spark taking average by key with python


rawDescription: PyQt or PySide: QTextEdit deselect all

description: PyQt or PySide: QTextEdit deselect all


code: list(list(x[1]) for x in itertools.groupby(lst, operator.itemgetter(1)))

rawDescription: Group same elements in list python

description: Group same elements in list python


code: commentCounter = 0

rawDescription: Write text at the 8th line in file

description: Write text at the 8th line in file


code:
column = 0
for item in iter_tree_widget(tree):
    print('State: %s, Text: "%s"' % (
          item.checkState(column), item.text(column)))

rawDescription: Qt treewidget python; iterate columns

description: Qt treewidget python; iterate columns


code:
class Person:
  def woot(self,data):
    print("Woot! ",data)

  def test(self,boss,data):
    x = "def callback():\n  self.woot(data)\nboss.registerCallback(callback)"
    exec(x, locals())

rawDescription: Closure lost during callback defined in exec()


code:
arr = numpy.array([1,23,4,6,7,8])
[(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]

rawDescription: Python first and last element from array


code:
uniques, X = np.unique(['foo', 'baz', 'bar', 'foo', 'baz', 'bar'], return_inverse=True)
X

rawDescription: scatter plots with string arrays in matplotlib

description: Scatter plots with string arrays in matplotlib


code:
fig, ax = plt.subplots()

for name, group in df.set_index('Date').groupby(['Code', 'ID']):
    group['Sum'].resample('M', 'sum').plot(ax=ax, label=name)

rawDescription: calculate total events in month using pandas

description: Calculate total events in month using pandas


rawDescription: Sum a nested list of a nested list of a nested list of integers


code:
words = nltk.corpus.brown.words()
k = 5
for ngram in nltk.ngrams(words, 2*k+1, pad_left=True, pad_right=True, pad_symbol=" "):
    if ngram[k+1].lower() == "settle":
        print(" ".join(ngram))

rawDescription: NLTK: Find contexts of size 2k for a word


rawDescription: Submitting web form from python and saving results


code:
with open('file.dat', 'rb') as infile:
    data = infile.read()

xml, sep, binary_data = data.partition(SEP)

rawDescription: Splitting binary file content in two parts using single byte separator in python


code:
out = open("outfile.dat", "w")
for line in unwrap_data("input_file.dat"):
    out.write("\t".join(line) + "\n")

rawDescription: Python-Cannot convert string to float...manipulating a text file


code:
f
f.func_closure

rawDescription: How to debug dynamically defined functions in Python?

description: Debug dynamically defined functions in Python


code:
class Configuration(db.Model):
  CACHE_TIME = datetime.timedelta(minutes=5)

  _INSTANCE = None
  _INSTANCE_AGE = None

  @classmethod
  def get_instance(cls):
    now = datetime.datetime.now()
    if not cls._INSTANCE or cls._INSTANCE_AGE + cls.CACHE_TIME < now:
      cls._INSTANCE = cls.get_or_insert('config')
      cls._INSTANCE_AGE = now
    return cls._INSTANCE

rawDescription: What is a good place to store configuration in Google AppEngine (python)


rawDescription: Modifying multidimensional numpy subarrays indexed by lists


code:
import urllib2
import lxml.html
import re
re_dollars = '\$?\s*(\d+\.\d{2})'

def urlExtractData(url, defs):
    """
    Get html from url, parse according to defs, return as dictionary

    defs is a list of tuples ("name", "xpath", "regex", fn )
      name becomes the key in the returned dictionary
      xpath is used to extract a string from the page
      regex further processes the string (skipped if None)
      fn casts the string to the desired type (skipped if None)
    """

    page = urllib2.urlopen(url) # can modify this to include your cookies
    tree = lxml.html.parse(page)

    res = {}
    for name,path,reg,fn in defs:
        txt = tree.xpath(path)[0]

        if reg != None:
            match = re.search(reg,txt)
            txt = match.group(1)

        if fn != None:
            txt = fn(txt)

        res[name] = txt

    return res

def getStockData(code):
    url = 'https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=' + code
    defs = [
        ("stock_name", '//span[@class="header1"]/text()', None, str),
        ("stock_symbol", '//span[@class="header2"]/text()', None, str),
        ("last_price", '//span[@class="neu"]/text()', re_dollars, float)
        # etc
    ]
    return urlExtractData(url, defs)

rawDescription: Download prices with python

description: Download prices with python


rawDescription: Remove outer list from list of list in python


rawDescription: Splitting a string and adding the digits inside of the string


code:
class Foo():
    def __str__(self):
        return 'plain foo'
    def pretty_version(self):
        return 'pretty foo'
    def __format__(self, spec):
        if spec.endswith('pretty'):
            prettified = self.pretty_version()
            return prettified.__format__(spec[:-6])
        return str(self).__format__(spec)

f = Foo()
print(f)
print(format(f))
print(format(f, 'pretty'))
print(format(f, '>20pretty'))
print('This object is pretty: {:^20pretty}!'.format(f))

rawDescription: what is the Pythonic way to implement a __str__ method with different format options?

description: What is the Pythonic way to implement a __str__ method with different format options


code:
import numpy
machar = numpy.MachAr(float_conv=numpy.float32)
machar.eps

rawDescription: numpy float32 truncating decimal

description: Numpy float32 truncating decimal


code:
class CreateEventForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        is_authenticated = kwargs.pop('is_authenticated', False)
        super(CreateEventForm, self).__init__(*args, **kwargs)
        if is_authenticated:
            self.fields['owner_email'] = forms.EmailField(required=True)

rawDescription: not show field in form if user is authenticated

description: Not show field in form if user is authenticated


code:
DOWNLOAD_HANDLERS = {
    'http': 'crawler.http.TorProxyDownloadHandler'
}

rawDescription: How to write a DownloadHandler for scrapy that makes requests through socksipy?

description: Write a DownloadHandler for scrapy that makes requests through socksipy


code:
df.rdd.map(lambda row:
    Row(row.__fields__ + ["day"])(row + (row.date_time.day, ))
)

rawDescription: PySpark add a column to a DataFrame from a TimeStampType column


code: list(enumerate(lsts, 1))

rawDescription: Spark: Using iterator lambda function in RDD map()


code:
my_string="""
What is the reason
ذَلِكَ الْكِتَابُ لَا رَيْبَ فِيهِ هُدًى لِلْمُتَّقِينَ
behind this?
ذَلِكَ الْكِتَابُ لَا رَيْبَ فِيهِ هُدًى لِلْمُتَّقِينَ
"""
print(re.sub(r'[a-zA-Z?]', '', my_string).strip())

rawDescription: How to retrieve only arabic texts from a string using regular expression?

description: Retrieve only arabic texts from a string using regular expression


code:
class DownloadImage(webapp.RequestHandler):
    def get(self):
        photo= db.get(self.request.get("photo_id"))
        if photo:
            self.response.headers['Content-Type'] = "image/jpeg"
            self.response.out.write(photo.imageblob)
        else:
            self.response.out.write("Image not available")

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


code:
string_list = ['NaT', 'nan', 'NaN', 'None']

def remove_wrong_nulls(x):
    for r in range(len(x)):
        for i,e in enumerate(tuples):
            for j,k in enumerate(e):
                if k == x[r]:
                    temp=list(tuples[i])
                    temp[j]=None
                    tuples[i]=tuple(temp)

remove_wrong_nulls(string_list)

rawDescription: how to transform pandas dataframe for insertion via executemany() statement?

description: Transform pandas dataframe for insertion via executemany() statement


code:
for index, field in enumerate(fields):
    def get(self,index=index):
        return list.__getitem__(self, index)
    def set(self, v,index=index):
        list.__setitem__(self, index, v)
    attrs[field] = property(get, set, None, 'Property "%s" mapped to item %d' % (field, index))

rawDescription: Improving my `namedlist` class inspired by `namedtuple`


code: self.frames = list(frames)

rawDescription: How to append to a custom python Sequence?

description: Append to a custom python Sequence


rawDescription: How to compare list in Python?

description: Compare list in Python


code: pictures = game.picture_set.all()

rawDescription: Pull a list of objects with foreign key in python


rawDescription: How to add (sum) the two values in a python dictionary based on another value?

description: Add (sum) the two values in a python dictionary based on another value


code:
import requests
from requests_ntlm import HttpNtlmAuth

requests.get("http://ntlm_protected_site.com",auth=HttpNtlmAuth('domain\\username','password'))

rawDescription: Handling windows authentication while accessing url using requests


rawDescription: grep a string after pattern match in python

description: Grep a string after pattern match in python


rawDescription: How to convert pandas dataframe so that index is the unique set of values and data is the count of each value?

description: Convert pandas dataframe so that index is the unique set of values and data is the count of each value


code:
from email.mime.multipart import MIMEMultipart

msgRoot = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')
...

# image file
msgText = MIMEText('<img src="cid:image" alt="Smiley" title="title">', 'html')
msgAlternative.attach(msgText)

# In-line Image
with open('/Users/john/Desktop/2015-04-21_13.35.38.png', 'rb') as fp:
    msgImage = MIMEImage(fp.read())
msgImage.add_header('Content-ID', '<image>')
msgImage.add_header('Content-Disposition', 'inline', filename='filename')
msgRoot.attach(msgImage)

...
server.sendmail(sender, recipients, msgRoot.as_string())

rawDescription: Naming inline images when sending HTML mails with Python's email.mime.multipart


rawDescription: How to create a function that loops through both the key and item of a dictionary using variables in Python?

description: Create a function that loops through both the key and item of a dictionary using variables in Python


code:
import numpy as np
import cv2

img = cv2.imread("../images/opencv_logo.png", 0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
cv2.imshow("grayscale", cimg)
cv2.waitKey(0)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                                    param1=50,param2=30,minRadius=0,maxRadius=0)
print (circles)

rawDescription: Python OpenCV Hough Circles returns None


code:
def show_args(*args, **kwargs):
    print(args, kwargs)

show_args(*(1, 2, 3), **{4: True, 5: False})

rawDescription: add parameters dynamically in python

description: Add parameters dynamically in python


code:
ymax = round(max(y), -1) + 20
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)
ax.set_yticks(range(int(ymin), int(ymax) + 1, 10))
ax.plot(x,y)

rawDescription: How to set the ticks on a logarithmic axis in matplotlib

description: Set the ticks on a logarithmic axis in matplotlib


code: APIVERSION = r'^api/v1'

rawDescription: django how to place variable in a raw string,such as for URL router

description: Django how to place variable in a raw string,such as for URL router


rawDescription: Is it possible to include mutiple equations in a lambda function


code:
text = self.canvas.create_text(30, 10, text="Welcome", tags="text")
# The canvas.bbox method returns the corner coordinates of the provided item id.
rect = self.canvas.create_rectangle(self.canvas.bbox(text), fill='red')
# Then you need to reposition the rectangle so that it is behind the text.
self.canvas.lower(rect, text)

rawDescription: Python - Moving an object\label\button and changing it's attribute


code:
# well-known name for our program
ECHO_BUS_NAME = 'com.stackoverflow.question_21793826.EchoService'

# interfaces implemented by some objects in our program
ECHO_INTERFACE = 'com.stackoverflow.question_21793826.EchoInterface'
QUIT_INTERFACE = 'com.stackoverflow.question_21793826.QuitInterface'

# paths to some objects in our program
ECHO_OBJECT_PATH = '/EchoServerObject'

rawDescription: SImple (but specific) listener and sender Python 3 DBus example


code: [key for key, values in rev_multidict.items() if len(values) > 1]

rawDescription: Find dictionary keys with duplicate values


code:
replacement = "test"
original_string = "(cats && dogs) || (cows && chickens)"
new_string = re.sub(r'[a-z]+', replacement, original_string)

rawDescription: Replace Section of String Rather than Character Python


code: wordlist1 = [word for word in wordslist1 if word not in filterlist]

rawDescription: Exclude list of words when reading a file


code: dict3 = dict(dict2, **dict1)

rawDescription: check two dictionaries that have similar keys but different values

description: Check two dictionaries that have similar keys but different values


rawDescription: list of lists to either autovivify or recursive data structure

description: List of lists to either autovivify or recursive data structure


code: subprocess.call('exit | theprogram %s' % arg1, shell=True)

rawDescription: Using pipes with the python "subprocess" module


code:
from collections import namedtuple
ReadElement = namedtuple('ReadElement', 'address value')
LookupElement = namedtuple('LookupElement', ReadElement._fields + ('lookups',))
LookupElement._fields
LookupElement('addr', 'val', 'lookup')

rawDescription: Python: Extending a predefined named tuple


code:
s = slice(0,len(L), 14)
L[s]

rawDescription: Array generation from a list in python

description: Array generation from a list in python


code:
def index():
    form = RegisteredCoursesForm()
    return render_template('main.html', title='Main', form=form)

rawDescription: Form with multiple identical lines

description: Form with multiple identical lines


code:
dists, indices = k.query(xyCenters)
myra = np.take(ra, indices)
mydec = np.take(dec, indices)

rawDescription: Finding the correspondence of data from one data set in the other


code:
if args.path:
    # user specify a value for path
    # using -p
    pass
elif cfg.path:
    # user provided a path in the configuration value
    args.path = cfg.path
else:
    # no value was specified, use some sort of default value
    args.path = DEFAULT_PATH

rawDescription: Can I check if a value was supplied by the default or by the user?

description: Check if a value was supplied by the default or by the user


rawDescription: Split a Pandas 'findall' result list into multiple items, to group by uniques


code: [ret[key] for key in sorted(ret)]

rawDescription: convert list of dict into list of list of dict

description: Convert list of dict into list of list of dict


rawDescription: stats.scipy.chi2 returns value of 0.0

description: Stats.scipy.chi2 returns value of 0.0


code:
l = ['c:\\3536 OK-LKF.txt', 'c:\\2532 PK-HHY.txt', 'c:\\1256 OK-ASR.txt', 'c:\\521 OL-MRA.txt', 'c:\\2514 LP-GRW.txt']

ll = ['c:\\aa.txt', 'c:\\bb.txt', 'c:\\cc.txt', 'c:\\dd.txt', 'c:\\ee.txt']
for a in l:
    for b in ll:
        print('renaming {} to {}'.format(a,b))

rawDescription: Python basic - renaming files

description: Python basic - renaming files


code:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

rawDescription: Is it possible to order a Django Model using the active language?


code: date

rawDescription: How to convert integer timestamp to Python datetime

description: Convert integer timestamp to Python datetime


code:
while True:      # Loop continuously
    a = func(x)  # Assign a
    if not a:    # Check if a is True
        break    # Break if not
    # use a

rawDescription: Assignments in conditions

description: Assignments in conditions


code:
for List in tableau:
      print()  # Right here
      print ("Row", Row, ":", end="")

      Row += 1
      for x in List:
          print (x, end="")

rawDescription: How to print on the same line in a loop?

description: Print on the same line in a loop


code:
def halved(n):
    while n:
        yield n
        n >>= 1

rawDescription: List comprehension to return the sum of n/2...?


code:
users_dict['admin']['passwd'] = 345

with open(FILE_PATH, 'w') as f:
   yaml.dump(users_dict, f)

rawDescription: Variables from txt file

description: Variables from txt file


code:
df = data('iris')
df.describe()

rawDescription: Are there any example data sets for Python?


code:
# Keep column headers. Convert numbers to numbers. Empty strings into None (empty "set")

def get_col(col):
    if col:
        try:
            return int(col)
        except:
            return col
    else:
        return None

rows = [row.split (',') for row in data.split ('\n')]
# Convert empty columns into None and
rows = [[get_col(col) for col in cols] for cols in rows]

rawDescription: Read array string of variable length in Python


code: pattern = re.compile('(%s)' % '|'.join(sterm), re.IGNORECASE)

rawDescription: replace multiple words - python

description: Replace multiple words - python


code:
def blsimpv_(row):
    blsimpv(row['spot'], row['strike'], row['rf'], row['dy'], row['T'], row['price'], row['w'])

rawDescription: Spreadsheet like functions in pandas

description: Spreadsheet like functions in pandas


rawDescription: Sampling from MultiIndex DataFrame

description: Sampling from MultiIndex DataFrame


code:
df['Cat2']=0
for i in range(2,len(df)):
   if df['Category'].iloc[i]==df['Category'][i-1]:
     df['Cat2'].iloc[i]=df['Cat2'].iloc[i-1]
   else:
     df['Cat2'].iloc[i]=df['Cat2'].iloc[i-1]+1

rawDescription: establish begin/end dates via groupby

description: Establish begin/end dates via groupby


code:
class Title(models.Model):
    title = models.CharField("Title", max_length=200, unique=True)

    def __unicode__(self):
        return self.title

rawDescription: ForeignKey returns id when editing the form


code:
import re
line = 'DATA(VALUE1|VALUE2||VALUE4)'
re.split(r'[(|)]', line)

rawDescription: Python: splitting a complex string including parentheses and |


code:
reg = re.compile(r'''
     (?xs)               # no need for i, but for s (dot matches newlines)
     (\b\w\.\s*)         # e.g. A. or b. (word boundary to restrict to 1 letter)
     ((?:(?!\b\w\.).)+)  # everything until the next A. or b.
     ''')

rawDescription: Negating previously matched word group

description: Negating previously matched word group


rawDescription: How to make my code more Pythonic?

description: Make my code more Pythonic


code: _ = simple_method(printit=True)

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
with self.lock:
    self.queue.put(result)

rawDescription: How to work around the Queue corruption when using Process.Terminate()

description: Work around the Queue corruption when using Process.Terminate()


rawDescription: Get often occuring string patterns from column in R or Python


code:
from django.shortcuts import get_list_or_404
from django.core import serializers

def ajax_category_type(request):
    id = request.GET.get('id')
    categories = get_list_or_404(Category, id=id)
    data = serializers.serialize('json', categories, fields=('type',))
    return HttpResponse(data, mimetype='application/json')

rawDescription: Django: change inlines based on select option


code:
import binascii

def int_from_bytes(b):
    x = int(binascii.hexlify(b), 16)
    mask = 1 << (len(b) << 3) - 1
    if x & mask:
        x -= mask << 1
    return x

rawDescription: Translating Array Manipulation in C++ to Python