code: cluster_entries = [[0]*28]

rawDescription: Python list of list selective insertion

description: Python list of list selective insertion


code:
from Tkinter import *
variable = 1
def makeSomething(value):
    global variable
    variable = value
root = Tk()
Button(root, text='Set value to four',command=lambda *args: makeSomething(4)).pack()
Button(root, text='Set value to eight',command=lambda *args: makeSomething(8)).pack()
Button(root, text='Set value to fifteen',command=lambda *args: makeSomething(15)).pack()
#...etc

rawDescription: Change the value of a variable with a button (Tkinter)


code:
from itertools import zip_longest
def chunks(iterable, size):
    "chunks(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g', 0, 0)"
    return zip_longest(*[iter(iterable)]*size, fillvalue=0)

def flatten(data):
    """Convert a list of N x M matrices into a flat iterator"""
    return ( v for matrix in data for row in matrix for v in row )

def unflatten(data, n, m):
    """Convert a flat sequence (of ints) into a list of `n` by `m` matrices"""
    msize = n * m
    for chunk in chunks(data, msize):
        yield [ chunk[i:i+m] for i in range(0, msize, m) ]

rawDescription: Python: Serializing/de-serializing huge amount of data


rawDescription: What is the appropriate Python data structure to hold its items and a combined list of its items?


code: rc = call("start cmd /K " + cmdline, cwd=dir, shell=True)

rawDescription: How to open a program with cmd.exe from Python?

description: Open a program with cmd.exe from Python


code:
def capture (self,length):
    capture.video_count+=1
    self.camera.start_recording(str(video_count) + '.h264')
    self.camera.wait_recording(length)
    self.camera.stop_recording()
capture.video_count = 0

rawDescription: Assigning incremental filenames within a cycle


code: df['data_prime'] = df['data'] * 3

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
from urllib.parse import urlparse
url = 'http://example.com/random/folder/path.html'
parse_object = urlparse(url)
parse_object.netloc
parse_object.path
parse_object.scheme

rawDescription: Django: check if an image exists at some particular url


code:
L = np.linalg.cholesky(S)
y = scipy.linalg.solve_triangular(L, (X - mu[np.newaxis]).T, lower=True)
d = np.einsum('ij,ij->j', y, y)

rawDescription: Vectorizing code to calculate (squared) Mahalanobis Distiance


code:
b = iter(a)
[[next(b) for _ in range(x)] for x in l]

rawDescription: Split a list into chunks of varying length


code:
def calculate_df_stats(dfs):
    mask_ = list(dfs['mask'])
    mean = np.ma.array(list(dfs['values']), mask=mask_).mean()
    return mean

result['Z'] = grouped.apply(calculate_df_stats)

result

rawDescription: pandas dataframe groupby like mysql, yet into new column

description: Pandas dataframe groupby like mysql, yet into new column


rawDescription: Grep numbers from a string

description: Grep numbers from a string


code:
df['Payment_Date']
df['Order_Date']

rawDescription: Finding the closest date given a date in a groupby dataframe (Python)


rawDescription: Does ply.lex Parse The Same Token Once?

description: Does ply.lex Parse The Same Token Once


code:
class User(object):

    def __init__(self, id_code, name, surname):
        self.id_code = id_code
        self.name = name
        self.surname = surname

class Worker(User):

    def __init__(self, id_code, name, surname, username, password, worker_type): # changed
        super(Worker, self).__init__(id_code, name, surname) # changed
        self.username = username
        self.password = password
        self.worker_type = worker_type

rawDescription: How to call constuctor from superclass

description: Call constuctor from superclass


rawDescription: Adding a item into a a dictionary in Python


code:
try:
    region = [r for r in feed['config']['regions'] if region['region'] == region_name][0]
    instance_type = [t for t in region['instanceTypes'] if i['type'] == instance_type_name][0]
    # ...
    return decimal.Decimal(prices['USD'])
except IndexError:
    raise Exception("Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" %
                (region_name, instance_type_name, instance_size_name, platform_name))

rawDescription: How can i improve the readablility of nested if and for statements

description: Improve the readablility of nested if and for statements


code:
df = pd.DataFrame(np.random.randint(0, 10, (9, 5)))
df
df.groupby(np.arange(len(df))//3).mean()

rawDescription: PYTHON : abbreviate big data in DataFrame


code:
from calendar import monthrange
monthrange(2012, 2)

rawDescription: How do we determine the number of days for a given month in python


code:
def Collection_is_cheap(C, price):
    result = set()
    for rest in C:
        for dish in rest.menu:
            if dish.price <= price:
                result.add(rest)
    return list(result)

print(Collection_is_cheap(collection, 28))

rawDescription: Iterating over list of namedtuples, selecting restaurants


code:
for n, attributes in line:
    ...
    attributes['foo'] = 'bar'

rawDescription: Python - how to store lines of numerical values?


code: df.iloc[:, 0]

rawDescription: Call column in dataframe by column index instead of column name - pandas


rawDescription: sum value of two different dictionaries which is having same key

description: Sum value of two different dictionaries which is having same key


code: r = requests.get ('https://www.dropbox.com/s/7uhheam5lqppzis/singlelineTest.csv?dl=1')

rawDescription: Download "csv-like" text data file and convert it to CSV in python


code:
tolerance = 0.000001
abs(a - b) < tolerance

rawDescription: Python .1 - .1 = extremely small number w/negative exponent?


code:
import urllib2
urllib2.urlopen('http://www.google.com')

f = urllib2.urlopen('http://www.google.com')
f

rawDescription: python urllib2 urlopen response

description: Python urllib2 urlopen response


code:
class QuarterCode(object):
    """docstring for QuarterCode"""

    @property
    def value(self):
        return self.__value;

    @value.setter
    def value(self, value):
        assert 1 <= value%10 <=4, "Number of quarters differs from {1,2,3,4}"
        self.__value = value

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

    def code_sum(self, n):
        q_code_year, q_code_quarter = self.value // 10, self.value % 10
        n_year, n_quarter = (n // 4), (n % 4 - 1)
        quarters = q_code_quarter + n_quarter
        years = q_code_year + n_year + quarters // 4
        self.value = years * 10 + quarters % 4 + 1

rawDescription: Python: using a custom number class or type


rawDescription: Save a function definition in ipython

description: Save a function definition in ipython


code:
def preprocess(lst):
    """
    process an iterable into 2 lists.
    The second list contains the portion bracketed by '--cmdname' and '--cmdname--'
    whereas the first portion contains the rest of it.
    """
    try:
        i1 = lst.index('--cmdname')
        i2 = lst.index('--cmdname--')
        argv1 = lst[i1+1:i2]
        argv2 = lst[:i1]+lst[i2+1:]
    except ValueError:
        argv1 = lst
        argv2 = []

    return argv1,argv2

rawDescription: How do I parse argparse arguments into a list of strings, stopping on a predefined flag argument?

description: Parse argparse arguments into a list of strings, stopping on a predefined flag argument


rawDescription: return an array instead of a tuple from a NumPy function

description: Return an array instead of a tuple from a NumPy function


code:
list3 = set(range(0,11) + range(25,36) + range(100,111) + range(75,86))
[x in list3 for x in list1]

rawDescription: fast way to compare whether the number is in the list of ranges in python

description: Fast way to compare whether the number is in the list of ranges in python


code:
last_line_location = True
first_time_through = True

rawDescription: Python: How to loop through blocks of lines and copy specific text within lines


code:
defined_args = {k:v for k,v in args._get_kwargs() if v is not None}
foo = Foo(**defined_args)

rawDescription: Using argparse arguments as keyword arguments


code:
# 'clip' will map all negative values a very small positive one
pyplot.xscale('log', nonposx='clip')

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


rawDescription: returns the preorder list of a tree in python

description: Returns the preorder list of a tree in python


code:
params = []
for idx, param in enumerate(functionNode):
   # parse XML and assign local variables type, name & description
   params.append({'name': name, 'type': type, 'description': description})

rawDescription: Dynamically building an "array of strcuts" in Python


code:
import json
import re
contents = r'[{"": "", "User ID": "913fd663bc66a452", "Description": "", "Timestamp": "Jul 09, 2014 10:33 PM", "Session Index": "2", "Platform": "Android", "Version": "0.2.9", "Params": "{ email : soleimaniarmin@yahoo.com;  comments : 09337845621;  stars : 4.0;  name : ari}", "Device": "Samsung Galaxy S4", "Event": "feedback"},{"": "", "User ID": "6e35346f9754b787", "Description": "", "Timestamp": "Jul 09, 2014 04:36 PM", "Session Index": "6", "Platform": "Android", "Version": "0.3.0", "Params": "{ email : eddgrow89@hotmail.com;  comments : i love My live ;  stars : 5.0;  name : eddy}", "Device": "Alcatel  One Touch 6033A", "Event": "feedback"},]'
json.loads(contents)
contents = re.sub(r',\s*(?=])', '', contents)
json.loads(contents)

rawDescription: Format of a .json file to be loaded in python


rawDescription: Spline of curve (python)

description: Spline of curve (python)


code:
class MyModel(models.Model):
    ...
    @property
    def priority(self):
        return (1 + (date.today() - self.reset_date) / self.days_to_expiration) * self.importance

rawDescription: Dynamic field calculations in Django

description: Dynamic field calculations in Django


rawDescription: Replace a string dynamically in Python

description: Replace a string dynamically in Python


rawDescription: performing outer addition with numpy

description: Performing outer addition with numpy


code:
for i, item in enumerate(dic):
    if (inp == item) :
        print("Thanks, found the key.")
        break
    if i == len(dic) - 1:
        print('This is the last key in the loop')

rawDescription: How to get the last item of the dictionary when looping

description: Get the last item of the dictionary when looping


code: zip(L, fL)

rawDescription: Given an iterable, how to apply a function in every possible combination?


code:
for data in soup.find_all('td', class_="yfnc_tabledata1")[0:6]:
    print (data.text)

rawDescription: Python webscrape text inside of multiple tags


code:
def __unicode__(self):
    return u'Country: %s  Model: %s' % (self.country, self.model)

rawDescription: How to __repr__ type unicode from database model


code: keep = [ele for ele in s.split() if ele.endswith("=whatever") ]

rawDescription: Pythonic way of getting a value from a list


code:
[list(x) for x in zip(*lis)]
map(list, zip(*lis))

rawDescription: Transpose a matrix in Python

description: Transpose a matrix in Python


code:
parser = ArgumentParser()
subparsers = parser.add_subparsers()
...
parser_quit = subparsers.add_parser('quit')
parser_quit.set_defaults(func=do_quit)
...
args = parser.parse_args()
args.func(args)

rawDescription: python argparse - add action to subparser with no arguments?

description: Python argparse - add action to subparser with no arguments


rawDescription: How to turn a list/tuple into a space separated string in python using a single line?

description: Turn a list/tuple into a space separated string in python using a single line


code:
import re
string1 = 'bob1: The ceo of the company {"salary": 100000}'
string2 = 'bob1: The ceo of the company ["10001", "10002"]'

re.search(r"\s([{\[].*?[}\]])$", string1).group(1)
re.search(r"\s([{\[].*?[}\]])$", string2).group(1)

rawDescription: Parse valid JSON object or array from a string


code:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('create table test (id int, value int)')
conn.execute('insert into test select 1, 1 union all select 2, 2')
df = pd.read_sql('select t1.id, t2.id, t1.value * t2.value from test as t1 cross join test as t2', conn)
df
df.columns = ['id1','id2','value']
df.pivot(index='id1', columns='id2')

rawDescription: SQL query 1 col & 1000 rows to pandas dataframe 10 cols&100 rows


code:
if samplemat[i,j] == nodatacode:
   classifiedmat[i,j] == nodatacode

rawDescription: Vectorized element assignment involving comparisons between matrices in Numpy


rawDescription: Finding multiple minimums and adding new column in pandas


code:
c = [item for group in zip(x, y, vx, vy) for item in group]
print(c)  # -> [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11]

rawDescription: Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc


rawDescription: python check if bit in sequence is true or false

description: Python check if bit in sequence is true or false


code:
c = (2 * frame['b']).where(frame['a'].shift().fillna(False), frame['b'])
c

rawDescription: doing calculations in pandas dataframe based on trailing row

description: Doing calculations in pandas dataframe based on trailing row


rawDescription: Specifying the keys in a JSON object with Python


code:
from facebook import Facebook

api_key = 'Your App API Key'
secret  = 'Your App Secret Key'

session_key = 'your infinite Session key of user'

fb = Facebook(api_key, secret)
fb.session_key = session_key

# now use the fb object for playing around

rawDescription: Facebook API and Python

description: Facebook API and Python


code:
while True:
    drivefiles  = drive.ListFile().GetList()
    self.User.GoogleFile = None
    for f in drivefiles:
        if f['title'] == 'Hello.txt':
            self.User.GoogleFile = f
            break
        if self.User.GoogleFile!=None:
            self.Message=json.loads(self.User.GoogleFile.GetContentString())
    raw_input("Press Enter to continue...")

rawDescription: Access shared file with PyDrive

description: Access shared file with PyDrive


code:
f = open('myfile.csv','w')
header = ''
for key in pairs.keys():
    if header == '':
        header = '%s' %pairs[key]
    else:
        header = '%s, %s' % (header, pairs[key])
f.write('%s\n' % header)

for i in range(4):
    line = ''
    for value in pairs.values():
        if line == '':
            line = '%s' %pairs[value][i]
        else:
            header = '%s, %s' % (header, pairs[value][i])
    f.write('%s\n' % line)
f.close()

rawDescription: Matrix creation

description: Matrix creation


rawDescription: Django: Unicode Filenames with ASCII headers?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

class MidpointNormalize(Normalize):
    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))

data = np.random.random((10,10))
data = 10 * (data - 0.8)

fig, ax = plt.subplots()
norm = MidpointNormalize(midpoint=0)
im = ax.imshow(data, norm=norm, cmap=plt.cm.seismic, interpolation='none')
fig.colorbar(im)
plt.show()

rawDescription: Shifted colorbar matplotlib

description: Shifted colorbar matplotlib


code: total_items_in_stock = [item for item in storage_items if item.in_stock()]

rawDescription: Django query: Want to count an empty value


code:
@count_check
def foo():
    return 42

print(foo(), foo(), foo())

@count_check
def bar():
    return 23

print(bar(), bar(), bar())
print(foo(), foo(), foo())

rawDescription: Python - Count number of times function passes through decorator


code: df = df[(~df['column2'].str.contains("foo")) & (~df['column2'].str.contains("bird")) & (~df['column2'].str.contains("cat"))]

rawDescription: Pandas: Efficiently subset DataFrame based on strings containing certain values


code:
import re
p = re.compile(r'\[(\d+)\|([^][]*)]')
test_str = "Text [123|Foo bar] text"
print (p.findall(test_str))

rawDescription: python - Mentions parse regex

description: Python - Mentions parse regex


rawDescription: Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?


code:
params = urllib.urlencode({'key': '8TU6AC31T81MV52N'})
f = urllib.urlopen("https://api.thingspeak.com/update?field1=hello", data=params)

rawDescription: How to POST - API in thingspeak.comusing urllib in Python


code:
li = [u'ansible-1.1.tar.gz', u'ansible-1.2.1.tar.gz', u'ansible-1.2.2.tar.gz', u'ansible-1.2.3.tar.gz',
      u'ansible-1.2.tar.gz', u'ansible-1.3.0.tar.gz', u'ansible-1.3.1.tar.gz', u'ansible-1.3.2.tar.gz',
      u'ansible-1.3.3.tar.gz', u'ansible-1.3.4.tar.gz', u'ansible-1.4.1.tar.gz', u'ansible-1.4.2.tar.gz',
      u'ansible-1.4.3.tar.gz', u'ansible-1.4.4.tar.gz', u'ansible-1.4.tar.gz']
import re
def get_version(fn):
    return list(map(int, re.findall(r'\d+', fn)))
get_version(u'ansible-1.4.4.tar.gz')
max(li, key=get_version)

rawDescription: python max function with mixed strings and numbers

description: Python max function with mixed strings and numbers


code:
def find_files(root, extensions = ('mel', 'py')):
    def clean_path(*p):
        return "/".join(p).replace('\\', '/')

    for root, _, files in os.walk(root):
        used = [f for f in files if f.split(".")[-1] in extensions]
        for u in used:
            yield clean_path(root, u)

def relativize(abs, roots):
    low_roots = map (str.lower, roots) # all lower for comparison
    for root, low_root in zip(roots,low_roots):
        if abs.lower().startswith(low_root):
            return root, abs[len(root):]
    return ("", abs)

relative_paths = find_files('c:/users/scripts')

root_dict = {}
for item in relative_paths :
    folder, file = relativize(item, ('C:/users/scripts/Python/', 'C:/users/scripts/Mel/', 'C:/users/scripts/'))
    if not folder in root_dict:
        root_dict[folder] = []
    root_dict[folder].append(file)

rawDescription: Multiple Paths Traversed and Displayed Filed type in Maya Menu with Python


code:
import importlib
my_module = importlib.import_module('4-1')

rawDescription: Import .py files with punctuation before extension


rawDescription: For loops over a list

description: For loops over a list


rawDescription: operation in arrays

description: Operation in arrays


code:
number = int(input('What number do you want to start with? '))

while number > 9:
    decompose_helper, number = number, 0
    while decompose_helper: # != 0 is implied
        decompose_helper, remainder = divmod(decompose_helper, 10)
        number += remainder

print('Result is', number)

rawDescription: How to add numbers in an integer

description: Add numbers in an integer


code:
def parseline(l):
    sp = l.split('=')
    return int(sp[1]) if len(sp) > 1 and sp[1].strip() != '' else None

rawDescription: Extracting specific variables of a line with linecache


code:
from selenium.selenium import selenium
import unittest, time, re
import BRConfig
from BRTestCase import BRTestCase

class Signin(BRTestCase):
    def test_signin(self):
        sel = self.selenium
        sel.open("/signout")
        sel.open("/")
        sel.open("signin")
        sel.type("email", "test@test.com")
        sel.type("password", "test")
        sel.click("//div[@id='signInControl']/form/input[@type='submit']")
        sel.wait_for_page_to_load("30000")
        self.assertEqual(BRConfig.WEBROOT, sel.get_location())

if __name__ == "__main__":
    unittest.main()

rawDescription: keeping firefox profile persistent in multiple selenium tests without specifying a profile

description: Keeping firefox profile persistent in multiple selenium tests without specifying a profile


code:
for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        PointsOfInterest[k][1] = PointsOfInterest[k][1] + 1

rawDescription: Python incrementing a Dictionary value entry held within a list


code:
import csv

def get_distinct_values(filename, column):
    with open(filename, "rb") as fp:
        reader = csv.reader(fp)
        return set(line[column] for line in reader)

rawDescription: reading a csv with python and handling blanks

description: Reading a csv with python and handling blanks


code:
x = " %s "%x # Add the spaces
for depth in range(z):
    # depth will be 0 on the first iteration, then 1
    print("|"*depth+"+"+"-"*(len(x)+2*(z-depth-1))+"+"+"|"*depth)
for repeat in range(y):
    print("|"*z+x+"|"*z)
for depth in reversed(range(z)):
    # reverse the depth values to start from the inner frame
    print("|"*depth+"+"+"-"*(len(x)+2*(z-depth-1))+"+"+"|"*depth)

rawDescription: Python: How to print a message within a "frame", using if,for and while control statements? Really confused


code: largestKey, largestNum = max(myHash.items(), key=itemgetter(1))

rawDescription: Python printing single key/value pairs from a dict


rawDescription: Python: How do you convert n-bits to base 64?


code:
class Crawler(models.Model):
    name = models.CharField(max_length=25)
    Id = models.CharField(max_length=25, primary_key=True)
    total_news_crawled= models.IntegerField(default=0)
    active = models.BooleanField(True)

    def __unicode__(self):  # Python 3: def __str__(self):
        return self.name

    def update_total_news_crawled( self ):
        self.total_news_crawled = New.objects.filter( source = 'xyz' ).count()

rawDescription: Getting field value counts and pushing values to other field of other model


code:
def only1(l):
    true_found = False
    for v in l:
        if v:
            # a True was found!
            if true_found:
                # found too many True's
                return False
            else:
                # found the first True
                true_found = True
    # found zero or one True value
    return true_found

rawDescription: How can I check that a list has one and only one truthy value?

description: Check that a list has one and only one truthy value


code:
from functools import partial
for a in range(2):
  def get(t,x): return x
  rules[a] = partial(get,x=a)

rules[0](0)
rules[0](1)
rules[1](0)
rules[1](1)

rawDescription: Python for loop initialization of reference to function


code: {'properties': ['sleep 200', '[sh, -xc, "echo $test\'  test\' >> /etc/hosts"]']}

rawDescription: escape characters and strings

description: Escape characters and strings


code:
import openpyxl
wb1 = openpyxl.load_workbook('workbook1.xlsx')

rawDescription: Adding cell values from multiple sheets in Excel workbook via Python


code:
from itertools import groupby

grouped = [list(g) for k, g in groupby(L, lambda s: s.partition('_')[0])]

rawDescription: Split list into sublist based on part of value


code:
from my_standard_package import *

(MY_DSL_FOO_FUNCTION, params, (ANOTHER_DSL_FUNCTION, ), expression_in_python, more_expressions_in_python)

rawDescription: When a DSL gets 'lispy'

description: When a DSL gets 'lispy'


rawDescription: Combination items of List in Python

description: Combination items of List in Python


code:
def check(g,s):
    for keys, value in g.items():
        for w, val in enumerate(g[keys]):
            print(s, g[keys][w], w)
            if(s==g[keys][w]):
                return 1
    return 0

rawDescription: Code not iterating over whole dictionary


code:
import subprocess
with open('foobar.txt', 'w') as f:
  p=subprocess.Popen(['look','data'], stdout=f)
  p.wait()

rawDescription: How do I write to a file using a terminal command in python?

description: Write to a file using a terminal command in python


code:
import numpy as np
np.dot(row(A,0), col(B,0))

rawDescription: How to multiply each row in a matrix by each column in the second matrix in Python?

description: Multiply each row in a matrix by each column in the second matrix in Python


code: norm_arr = np.full((max_height, max_width), fill_value=255)

rawDescription: Better image normalization with numpy

description: Better image normalization with numpy


rawDescription: Iterate across arbitrary dimension in numpy


code:
class Property(object):
    _value = None
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self._value
    def __set__(self, instance, value):
        self._value = value * 2

rawDescription: determine a class attribute is Property?

description: Determine a class attribute is Property


code: atom_list = [atom for atom in structure.get_atoms() if atom.name == 'CA']

rawDescription: Get all neighbors of a set of Residues

description: Get all neighbors of a set of Residues


code:
def linspace(start, stop, num=50, endpoint=True, retstep=False):
    ...
    if endpoint:
        if num == 1:
            return array([float(start)])
        step = (stop-start)/float((num-1))
        y = _nx.arange(0, num) * step + start   #<-- the first point is `start`
        y[-1] = stop   # <-- the last point is `stop`
    ...
    return y

rawDescription: for floating point x, is x==numpy.linspace(x,y,n)[0] always True?

description: For floating point x, is x==numpy.linspace(x,y,n)[0] always True


code:
def lone_sum(*L):
  nums = set()
  all_nums = set()
  for num in L:
    if num in nums:
      nums.remove(num)
    elif num not in all_nums:
      all_nums.add(num)
      nums.add(num)
  return sum(nums)

rawDescription: Python sum of non duplicate int

description: Python sum of non duplicate int


code:
lst = [[0]*5]*5
[id(sublst) for sublst in lst]

rawDescription: How to multiply lists and set a single variable?

description: Multiply lists and set a single variable


code:
import copy

grid = copy.deepcopy(initial)

rawDescription: Python continuously updating array

description: Python continuously updating array


code:
import MyLibrary

foo = MyLibrary.Foo()
foo.pushBack(10);
foo.pushBack(20);
foo.pushBack(30);
print(foo.getInt(0)) # 10
print(foo.getInt(1)) # 20
print(foo.getInt(2)) # 30

bar = foo.getBar()
print(bar.getValue()) # 42
bar.setValue(17)
print(foo.getBar().getValue()) #17

print(MyLibrary.compute()) # 18.3

rawDescription: Calling C++ class functions from Ruby/Python


code:
widget = QtGui.QWidget()
vbox = QtGui.QVBoxLayout(widget)
self.setCentralWidget(widget)

rawDescription: PyQt QVBoxLayout and missing widgets?

description: PyQt QVBoxLayout and missing widgets


code:
new_set_name = 'buffalo'
globals()[new_set_name] = set()

rawDescription: How to access the string stored in the variable? (Python)

description: Access the string stored in the variable? (Python)


code:
wparameters = [w]
update = [(wparam,
           wparam + tr_rate * (pos_associations-neg_associations)) for wparam in wparameters]

rawDescription: How to write update in theano function

description: Write update in theano function


code:
with open('file_name', 'w+') as my_file:
    lines = my_file.readlines()
    # set the file pointer at the beginning of the file
    my_file.seek(0, 0)
    # now, rewrite the data
    for line in lines:
        my_file.write(line.title())

rawDescription: Python code not writing into file

description: Python code not writing into file


code: sorted(v for key in yourdict for v in key)

rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


rawDescription: Python list not printing as desired

description: Python list not printing as desired


Why 10 // .01 = 999.0


rawDescription: `struct.unpack_from` doesn't work with `bytearray`?


code:
with open("test.csv", encoding="utf-8") as f, open("file_out.csv", "w") as out:
    from collections import Counter
    from csv import reader, writer
    wr = writer(out)
    header = next(f) # get header
    # get count of each first/last name pair lowering each string
    counts = Counter((a.lower(), b.lower()) for a, b, *_ in reader(f))
    f.seek(0) # reset counter
    out.write(next(f))  # write header ?
    # iterate over the file again, only keeping rows which have
    # unique first and second names
    wr.writerows(row for row in reader(f)
                   if counts[row[0].lower(),row[1].lower()] == 1)

rawDescription: Remove duplicate rows in CSV comparing data in only two columns with Python


code:
from pyevolve import GAllele
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Crossovers
from pyevolve import Initializators
from pyevolve import Mutators
from pyevolve import Scaling

# data values are the [min, max] for each parameter
data=[ [0,99], [1,10], [1,10], [90,110], [1,10],
[1,10], [1,10], [1,10], [1,10], [1,10],
[1,10], [5,10], [1,10], [1,10], [50,100],
[50,100], [50,100], [50,100], [50,100], [7,77] ]

def Grid_Constructor(a=data):
    alleles = GAllele.GAlleles()
    for i in range(0, 20):
        alleles.add(GAllele.GAlleleRange(a[i][0], a[i][1], real=True))
    return alleles

# set the params, initializator and mutator
genome = G1DList.G1DList(20)
genome.setParams(allele=Grid_Constructor())
genome.initializator.set(Initializators.G1DListInitializatorAllele)
genome.mutator.set(Mutators.G1DListMutatorAllele)
ga = GSimpleGA.GSimpleGA(genome)
print(Grid_Constructor())
#ga.evolve(freq_stats=10)

rawDescription: How to set different parameter ranges within a real valued chromosome using Pyevolve?

description: Set different parameter ranges within a real valued chromosome using Pyevolve


code:
from __future__ import division
#cython: wraparound=False
#cython: boundscheck=False
#cython: nonecheck=False
#cython: profile=False
#cython: cdivision=True

rawDescription: Cython header directive and __future__

description: Cython header directive and __future__


code:
while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            relx, rely = event.rel
            if relx != 0:  # x movement
                angle += 10

rawDescription: Pygame: Mouse Specific Axis Detection

description: Pygame: Mouse Specific Axis Detection


code: im = Image.fromstring(image['mode'], image['size'], image['pixels'])

rawDescription: Pickleable Image Object

description: Pickleable Image Object


rawDescription: Automate Input Into Python Prompts

description: Automate Input Into Python Prompts


code:
from random import shuffle
import numpy as np

a = ['a','b','c','d']
b = a[:]
c = ['w','x','y','z']
d = c[:]
shuffle(c)
shuffle(d)
# print a,b,c,d
print (a,b,c,d)
ac = np.array(a + c)
bd = np.array(b + d)
indices = list(range(len(ac)))
shuffle(indices)
ac = ac[indices]
bd = bd[indices]
#print ac, bd
print (ac, bd)

rawDescription: Shuffling two lists separately in Python


code:
infiles = (infile for infile in infiles if infile.endswith(".pdb"))
for infile, outfile in zip(infiles, rename_files):
    os.rename(infile, outfile + ".pdb")

rawDescription: Rename files based on an input list Python


code:
try_parse('123')
try_parse('12n3')
try_parse('')
try_parse('4.13n3')

rawDescription: saving the number into the variable in every run of cycle python

description: Saving the number into the variable in every run of cycle python


code:
class MyWidget(ModelSelect2Widget):
    search_fields = ['name__icontains', 'genus__name__icontains']

rawDescription: Django with Select2 remote data example

description: Django with Select2 remote data example


code:
from operator import itemgetter
min(gen,key=itemgetter(1))

rawDescription: minimum of list of lists

description: Minimum of list of lists


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
            ],
        },
    },
]

rawDescription: django view render to template from another app

description: Django view render to template from another app


code:
import functools

class MyDB(object):

    submodule_classes = []

    def __init__(self):
        for c in self.submodule_classes:
            self.__dict__[c.__name__] = c(self)

        self.db_stuff = "test"

rawDescription: Access parent object from submodule

description: Access parent object from submodule


rawDescription: Help on Regular Expression problem

description: Help on Regular Expression problem


rawDescription: Django reverse url to onetoonefield on success


code:
def weekdays_consecutive(days):
    indexes = [day_indexes[d] for d in days]
    return all(indexes[i + 1] % 7 == (indexes[i] + 1) % 7
               for i in range(len(indexes) - 1))

rawDescription: Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday'


code:
rng = pd.date_range('1/10/2011', periods=3, freq='D')
rng.to_pydatetime()

rawDescription: Converting between datetime and Pandas Timestamp objects


rawDescription: Combination of combinations that cut of with the sum of 4


code:
from collections import OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
od['third'] = 3
od.values()

rawDescription: Dictionary values are not ordered python


code:
data
indices
indptr
M=sparse.csr_matrix((data,indices,indptr),shape=(3,4))

rawDescription: How do I get a scipy.csr sparse-matrix as a normal dense matrix without toDense()?

description: Get a scipy.csr sparse-matrix as a normal dense matrix without toDense()


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

latexTickSize = 18; latexLabelSize = 26
mpl.rcParams['axes.labelpad'] = -5 # default is 5
plt.xlabel('$t$', fontsize=latexLabelSize)
plt.xticks(np.linspace(-np.pi, np.pi, 5),\
['$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$'], fontsize=latexTickSize)
plt.xlim([-np.pi, np.pi])
plt.ylabel('$x(t)$', fontsize=latexLabelSize)
plt.yticks(np.linspace(-1, 1, 5), fontsize=18)
plt.ylim(-1.25, 1.25)

t = np.linspace(-np.pi, np.pi, 100)
plt.plot(t, np.cos(t))

rawDescription: Getting the axis labels in matplotlib not to go over the boundaries


code: func = lambda x,keyword='bar':(x,keyword)

rawDescription: Python functions within lists

description: Python functions within lists


code:
y.flags
x.flags

rawDescription: When will numpy copy the array when using reshape()


rawDescription: Some python date manipulation

description: Some python date manipulation


code:
headers = ['Host: www.perdu.com', 'Connection: keep-alive', 'Cache-Control: max-age=0', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36', 'DNT: 1', 'Accept-Encoding: gzip,deflate,sdch', 'Accept-Language: en-US,en;q=0.8,es;q=0.6,fr;q=0.4', '']
headers = [tuple(i.split(': ')) for i in headers]

rawDescription: Split list with colon seperated items into list of tuples


rawDescription: re.match (regular expression) in python: matching issue

description: Re.match (regular expression) in python: matching issue


rawDescription: Is there an efficient way of generating numbers with repeated digits in Python?


code:
def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

rawDescription: Reusable library to get human readable version of file size?


code:
import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.xossip.com/showthread.php?t=1384077&page=' + str(page)
        sourcecode= requests.get(url)
        plaintext = sourcecode.text
        soup = BeautifulSoup(plaintext)

        for tag in soup.findAll('img'):
            print(tag.get('src'))   # use `tag.get('src')` in this case

        page += 1
spider(1)

rawDescription: How do I scrap specific images (excluding thumbnails,icons,etc.) from forums using Beautiful soup

description: Scrap specific images (excluding thumbnails,icons,etc.) from forums using Beautiful soup


code:
lst = range(1, 4)
id(lst)
lst = [1, 2, 3]
id(lst)  # different; you pointed lst at a new object
lst[:] = range(1, 4)
id(lst)  # the same, you iterated over the list returned by range
lst = xrange(1, 4)
lst
id(lst)   # and different
lst = [1, 2, 3]
id(lst)    # again different
lst[:] = xrange(1, 4) # this gets read temporarily into a tuple
id(lst)   # the same, because you iterated over the xrange
lst    # and still a list

rawDescription: List assignment with [:]

description: List assignment with [:]


code: pat = re.compile(r'reg')

rawDescription: Ignore special characters when creating a regular expression in python


code:
def help():
    print("help!")

rawDescription: Can I call a function by inputting a string?

description: Call a function by inputting a string


code: x = func(*[a, b, c])

rawDescription: get slice from multi-dimensions in python

description: Get slice from multi-dimensions in python


code:
letters = 'imtryingtocreateacaesarcypherdecoder'
c = collections.Counter(letters)

rawDescription: Python Caesar cypher using the most common letter to decode a message


rawDescription: Find maximum # of connections between 2 people


code:
def insert_description(element):
    '''Inserts the Title as a Description if Desscription not present.'''
    for sub_e in element:
        if sub_e.find('Description') is None:
            title = sub_e.find('Title').text
            new_desc = ET.Element('Description')
            new_desc.text = title
            sub_e.insert(2, new_desc)

rawDescription: Add new Element to xml using Elementtree


code:
class AngularJSTextInput(TextInput):
    def __call__(self, field, **kwargs):
        for key in list(kwargs):
            if key.startswith('ng_'):
                kwargs['ng-' + key[3:]] = kwargs.pop(key)
        return super(AngularJSTextInput, self).__call__(field, **kwargs)

rawDescription: Custom attributes for Flask WTForms

description: Custom attributes for Flask WTForms


code:
# (assumes you already created an instance of FTP
#  as "ftp", and already logged in)
f = open(fn, 'r')
ftp.storbinary("STOR remote_filename.png", f)

rawDescription: PIL.Image.save() to an FTP server

description: PIL.Image.save() to an FTP server


code: my_dict2 = {'group_a':my_array[0:1], 'group_b':my_array[1:]}

rawDescription: Numpy - retaining the pointer when referencing a single element


rawDescription: How to move values in a list one by one?

description: Move values in a list one by one


code: sum( [ int(x) for x in mystr ] )

rawDescription: How to manipulate digits within an integer/string?

description: Manipulate digits within an integer/string


code:
thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2

thechan = Score.objects.filter(content=44)[0:1]
thechan[0].save() # saves an unmodified object back to the DB, no effective change

rawDescription: Why can't I save an object in Django?

description: Why can't I save an object in Django


code:
df = df.groupby(['type','group']).sum().transpose().stack(0).reset_index()
df

rawDescription: Trouble pivoting / reshaping a pandas dataframe


code:
data1 = np.array(tupleli[0], dtype=dt)
data1.shape
data1['start date']
data1['n']

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code:
m = getTranslatedMessage("d", "this may work", 17)
print(m)
brute(m)

rawDescription: Check a generated string against a preset string in python


code:
def func(group):
    sum_ = group.qty.sum()
    es = (group.csv / group.qty).sum()
    return pd.Series([sum_, es], index=['qty', 'es'])

trades.groupby('ordrefno').apply(func)

rawDescription: How do I use pandas groupby function to apply a formula based on the groupby value

description: Use pandas groupby function to apply a formula based on the groupby value


rawDescription: Index for the end of a numpy array

description: Index for the end of a numpy array


code:
magnitude = np.sqrt(sobel_X**2 + sobel_Y**2)
Y, X = np.ogrid[0:angle.shape[0], 0:angle.shape[1]]
hog[Y, X, angle] += magnitude

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

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


rawDescription: How to convert unicode string into list using pandas python?

description: Convert unicode string into list using pandas python


rawDescription: python3 How do I identify / handle unwanted unicode from scraped web page?

description: Python3 How do I identify / handle unwanted unicode from scraped web page


code:
lst = [[1,2,3],[4,5,6],[3,2,1]]
seen = set()
[x for x in lst if frozenset(x) not in seen and not seen.add(frozenset(x))]

rawDescription: How to remove duplicate lists that contain elements in different order?

description: Remove duplicate lists that contain elements in different order


rawDescription: Making a list with every possible combination of 0's and 1's in Python


code:
class X:
    b = 4

getattr(x, a)

print(getattr(x, "b"))

rawDescription: Passing which member to lookup dynamically


code:
basecells = np.where(cellrecord[:,2]==firstcelltype)[0]
xlocs = cellrecord[basecells, 0]
ylocs = cellrecord[basecells, 1]
xedgedists = xbound - xloc
yedgedists = ybound - yloc
whichcells = np.where((xlocs>excludedist) & (xedgedists>excludedist) & (ylocs>excludedist) & (yedgedists>excludedist))[0]
selectedcells = basecells[whichcells]
comparecells = np.where(cellrecord[:,2]==secondcelltype)[0]
xcomplocs = cellrecords[comparecells,0]
ycomplocs = cellrecords[comparecells,1]
analysisdist2 = analysisdist**2
for basecell in selectedcells:
    dists = np.round((xcomplocs-xlocs[basecell])**2 + (ycomplocs-ylocs[basecell])**2)
    whichcells = np.where((dists >= 1) & (dists <= analysisdist2))[0]
    arraytargets = np.round(dists[whichcells]*analysisdist/intervalnumber) - 1
    for target in arraytargets:
        spatialraw[target] += 1

rawDescription: Numpy/Python performing terribly vs. Matlab


code:
import urllib2

response = urllib2.urlopen('http://example.com/some/path/?myvar=myvalue')

rawDescription: in need of a simple example that shows serverside python program passing data to webserver

description: In need of a simple example that shows serverside python program passing data to webserver


rawDescription: Pandas: Compress Column Names to Cell Values where True


code: findall(name + ".*", info)[0]

rawDescription: python 2.2 find string after linebreak

description: Python 2.2 find string after linebreak


code:
import fakemodule, sys

sys.modules["package.module"] = fakemodule

rawDescription: Can I "fake" a package ( or at least a module ) in python for testing purposes?


rawDescription: mapping in SD in python

description: Mapping in SD in python


rawDescription: Numpy extract values along a dimension for a given point


code: sorted( seurch2('stardict',wordlist) )

rawDescription: Finding out exact match in python

description: Finding out exact match in python


code:
from django.template import RequestContext

def start_here(request):
    return render_to_response("profile.html", {},
        context_instance=RequestContext(request))

rawDescription: User authentication in Django

description: User authentication in Django


rawDescription: Why this regular expression pattern matches even an extra character in string?


code: iList1, iList2 = [list(group) for key, group in itertools.groupby(iList, operator.itemgetter(0))]

rawDescription: How should I break a list of tuples so that it forms lists with same keys?


code:
plt.figure()
length_plot = sns.barplot(x='sepal_length', y='species', data=iris)
plt.savefig('ex1.pdf')
plt.figure()
width_plot = sns.barplot(x='sepal_width', y='species', data=iris)
plt.savefig('ex2.pdf')

rawDescription: Stop seaborn plotting multiple figures on top of one another


code:
for name, email in pairs:
    data.setdefault(email, []).append(name)

rawDescription: Python3 Uniquify list of tuples based on only one of the values of the index


code:
for letter in word:
    i = word.find(letter)
    while i in indeces:
        i = word.find(letter, i+1)
    indeces.append(i)

rawDescription: Lists, conditionals and loops don't give the result expected


code:
df = pd.DataFrame([['blah', 1, 2], ['some_string', 3, 4], ['foo', 5, 6]])
df
df[0].isin(['some_string']).argmax()  # assuming it's found

rawDescription: Pandas advanced read_excel or ExcelFile.parse


code: sorted(list_of_objects, key=lambda o: min(p.z for p in o.point_array))

rawDescription: Python, sort a list of objects by lowest sub-object attribute


code:
from itertools import compress
reason = [', '.join(compress(tups, x)) for x in zip(*tups.values())]

rawDescription: Filter a tuple with another tuple in Python


code:
env.roledefs = {
    #static roles
}
# add dynamic role from file "hosts"
with open("./hosts") as f:
    env.roledefs['tmp'] = f.readlines()

rawDescription: How to specify hosts list or roledefs in text file (instead of code)?

description: Specify hosts list or roledefs in text file (instead of code)


rawDescription: Numpy.unique - getting output with consistent depth


rawDescription: Disable cursor in TextCtrl - wxPython

description: Disable cursor in TextCtrl - wxPython


code:
packRegister(255, 8)
packRegister(1023, 16)
packRegister(324353, 24)
packRegister(324353, 8)

rawDescription: python conversion int into arbitrary number of bytes

description: Python conversion int into arbitrary number of bytes


code:
import datetime

def pubdate(tag):
    return '<{tag}>{date}</{tag}>'.format(
        date = datetime.date.today().strftime("%d %B %Y"),
        tag = tag
    )

rawDescription: Generating a British date/time pubDate for an RSS in Python


code: print("\n".join(("{:>4}"*10).format(*(i*j if i*j else i+j if i+j else "" for j in range(10))) for i in range(10)))

rawDescription: How to print multiplication table using nested for loops

description: Print multiplication table using nested for loops


code:
import subprocess
import shlex
import os

PASSPHRASE='...'

in_fd,out_fd=os.pipe()
os.write(out_fd,PASSPHRASE)
os.close(out_fd)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=in_fd)
with open('filename.txt','r') as stdin_fh:
    with open('filename.gpg','w') as stdout_fh:
        proc=subprocess.Popen(shlex.split(cmd),
                              stdin=stdin_fh,
                              stdout=stdout_fh )
        proc.communicate()
os.close(in_fd)

rawDescription: Write to file descriptor 3 of a Python subprocess.Popen object


code:
nfs = cgi.FieldStorage()
for k in fs:
  nfs[ tr[k] ] = fs[k]

rawDescription: Transform Python HTML Inputs

description: Transform Python HTML Inputs


code: sorted(dictionary.items(), key=lambda x: x[1])

rawDescription: How do I iterate over a Python dictionary, ordered by values?

description: Iterate over a Python dictionary, ordered by values


rawDescription: Filtering pandas data frame by a list of id's


code: perc = lambda i, t: (i * t) / 100

rawDescription: Getting indices for certain percent of a length of a list


code:
rabbit = next(b for b in blobs if abs(750 - b.area()) < 60)
rabbit.draw()
binarized.show()
rabbit

rawDescription: How do I locate the rabbit?

description: Locate the rabbit


rawDescription: Replace values of a group with group aggregate in numpy/pandas


code:
y1 = main_func(x)
y2 = calculate_secant(x, y1, p1, p2)
y2[y2 < y1] = np.nan
plot(x, y1, y2)

rawDescription: secant line too long, trying not to use y limits

description: Secant line too long, trying not to use y limits


code:
class BootstrapCheckboxSelectMultiple(CheckboxSelectMultiple):
    """Form widget that supports Bootstrap's markup requirements"""
    def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = []
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices,
            choices)):

            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.

            # Should be able to pass in additional widget attributes to
            # the checkbox renderer here...
            if has_id:
                final_attrs = dict(final_attrs, id='{}_{}'.format(attrs['id'], i))
                label_for = u' for="{}"'.format(final_attrs['id'])
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs,
                check_test=lambda value: value in str_values)

            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append(u'<label{} class="checkbox">{} {}</label>'.format(
                label_for, rendered_cb, option_label))
        return mark_safe(u'\n'.join(output))

rawDescription: Add css class from database to manytomany field


code:
class Foo(object):
    def __init__(self, c):
        self.bar=c

objects = [Foo(x) for x in 'ab..$111$x.z$222']

rawDescription: Short way to extract sublist from list in python by given conditions


code: df.sort_clean = lambda sort_cols, x=df: sort_clean(x, sort_cols)

rawDescription: attach functions to pandas

description: Attach functions to pandas


code:
import pandas as pd

# generating random DF
num_rows = 100

locs = list('abcdefghijklmno')

df = pd.DataFrame(
        {'id': np.random.randint(1, 100, num_rows),
         'location': np.random.choice(locs, num_rows),
         'year': np.random.randint(2005, 2007, num_rows)})

df.sort_values('id', inplace=True)

print('**** sorted DF (first 10 rows) ****')
print(df.head(10))

# chopping DF into chunks ...
chunk_size = 5

chunks = [i for i in df.id.unique()[::chunk_size]]

chunk_margins = [(chunks[i-1],chunks[i]) for i in range(1, len(chunks))]

df_chunks = [df.ix[(df.id >= x[0]) & (df.id < x[1])] for x in chunk_margins]

print('**** first chunk ****')
print(df_chunks[0])

rawDescription: How to cut up my dataframe in chunks, but keeping groups together

description: Cut up my dataframe in chunks, but keeping groups together


code:
def __str__(self):
    if self.solution is None:
        self.solveIt()
    return '{}\n{}'.format(len(self.seq),
                           ','.join(map(str, self.solution)))

rawDescription: Turning my function into a class

description: Turning my function into a class


code: g_tree[obj_id]['name'] = obj_name

rawDescription: Unable to generate network data in tree format while retaining node attributes


code: ['Detroit Tigers', 'Washington Nationals', 'Kansas City Royals', 'New York Yankees', 'Oakland Athletics', 'Boston Red Sox', 'Pittsburgh Pirates', 'Cincinnati Reds', 'Milwaukee Brewers', 'Miami Marlins', 'Chicago White Sox', 'Texas Rangers', 'San Diego Padres', 'Chicago Cubs', 'Baltimore Orioles', 'Minnesota Twins', 'Cleveland Indians', 'Houston Astros', 'Arizona Diamondbacks', 'Colorado Rockies', 'Tampa Bay Rays', 'Seattle Mariners', 'New York Mets', 'Los Angeles Dodgers', 'Toronto Blue Jays', 'San Francisco Giants']

rawDescription: How to get a specific tag attribute text in Python with BeautifulSoup?

description: Get a specific tag attribute text in Python with BeautifulSoup


code:
try: from BigPackage.SmallSubset import TheOnlyFunctionIReallyNeed
except ImportError: from BigPackageSmallSubset import TheOnlyFunctionIReallyNeed

rawDescription: py2exe: excluding parts of a package that wants to import all its parts

description: Py2exe: excluding parts of a package that wants to import all its parts


code:
def num_double_letters(astr):
    if astr == "" or len(astr) == 1:
        return 0
    elif len(astr) == 2:
        if astr[0] == astr[1]:
            return 1
        else:
            return 0
    elif astr[0] != astr[1]:
        return 0 + num_double_letters(astr[1:])
    elif astr[0] == astr[1]:
        return 1 + num_double_letters(astr[2:])

print(num_double_letters('hmm'))
print(num_double_letters('hmmm'))
print(num_double_letters('hmmmm'))

rawDescription: Python Recursion Double letters

description: Python Recursion Double letters


code:
def add_wrap_overflow(x,y):
    return (x+y) % 12

rawDescription: Subtracting 12 when the sum of two variables is greater or equal to 12


code:
import xml.etree.ElementTree as E
e = E.parse("test.xml")
print(e.find("type").text)

rawDescription: Accessing child nodein an xml in python

description: Accessing child nodein an xml in python


rawDescription: Strings, ints and leading zeros

description: Strings, ints and leading zeros


code:
class Example (object):
    pass

example = Example()
setattr(Example, '__getitem__', lambda x, y: 1)
example['something']

rawDescription: Setting special methods using setattr()

description: Setting special methods using setattr()


code:
def getHashValue(fName,Hash):
   f = open(fName,'rb')
   hashvalue = Hash(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)

rawDescription: Unable to pass a variable to function

description: Unable to pass a variable to function


code:
move_func = directions[direction.replace(" ","")]
move_func(steps)

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


code: sortedlist = sorted(list(data)[2:-2], key=lambda x:int(x[0]))

rawDescription: Sort a file according to values in first column


code:
lons = val_pivot_df.columns.values
lats = val_pivot_df.index.values

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

m = Basemap(projection='merc',
        llcrnrlat=val_df.dropna().min().lat-5
        , urcrnrlat=val_df.dropna().max().lat+5
        , llcrnrlon=val_df.dropna().min().lon-5
        , urcrnrlon=val_df.dropna().max().lon+5
        , resolution='i', area_thresh=10000
        )

m.drawcoastlines()
m.drawstates()
m.drawcountries()
m.fillcontinents(color='gray', lake_color='white')#, zorder=0)
m.drawmapboundary(fill_color='0.3')

x, y = np.meshgrid(lons,lats)
px,py = m(x,y)

data_values = val_pivot_df.values
masked_data = np.ma.masked_invalid(data_values)

cmap = plt.cm.viridis

m.pcolormesh(px, py, masked_data, cmap=cmap, vmin=0, vmax=2, shading='flat')

m.colorbar()

rawDescription: restructuring pandas dataframe into meshgrid for basemap

description: Restructuring pandas dataframe into meshgrid for basemap


code:
class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = forms.CharField(label=_("Username"), max_length=30)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

    def __init__(self, request=None, *args, **kwargs):
        """
        If request is passed in, the form will validate that cookies are
        enabled. Note that the request (a HttpRequest object) must have set a
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
        running this validation.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
            elif not self.user_cache.is_active:
                raise forms.ValidationError(_("This account is inactive."))

        # TODO: determine whether this should move to its own method.
        if self.request:
            if not self.request.session.test_cookie_worked():
                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))

        return self.cleaned_data

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache

rawDescription: Separately validating username and password during Django authentication


code:
from collections import UserList
from functools import partial

def objectitemcaller(key):
    def inner(*args, **kwargs):
        try:
            return getattr(object, key)(*args, **kwargs)
        except AttributeError:
            return NotImplemented
    return inner

class Listable(UserList):
    def __init__(self, iterator):
        self.iterator = iterator
        self.iterated = False

    def __iter__(self):
        return self

    def __next__(self):
        self.iterated = True
        return next(self.iterator)

    def _to_list_hack(self):
        self.data = list(self)
        del self.iterated
        del self.iterator
        self.__class__ = UserList

for key in UserList.__dict__.keys() - Listable.__dict__.keys():
    if key not in ["__class__", "__dict__", "__module__", "__subclasshook__"]:
        setattr(Listable, key, objectitemcaller(key))

def metagen():
    def innergen():
        yield 1
        yield 2
        yield 3

    for i in range(3):
        r = Listable(innergen())
        yield r

        if not r.iterated:
            r._to_list_hack()

        else:
            for item in r: pass

for item in metagen():
    print(item)
    print(list(item))
#>>> <Listable object at 0x7f46e4a4b850>
#>>> [1, 2, 3]
#>>> <Listable object at 0x7f46e4a4b950>
#>>> [1, 2, 3]
#>>> <Listable object at 0x7f46e4a4b990>
#>>> [1, 2, 3]

list(metagen())
#>>> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

rawDescription: python generator of generators?

description: Python generator of generators


code:
from io import BytesIO

with open('file.txt', 'rb') as f:
    output = BytesIO()
    output.write(f.read())

for i in range(1, 101):
    fname = 'file' + str(i) + '.txt'
    output.seek(0)
    ftp.storbinary('STOR ' + fname, fp)

rawDescription: Python read file into memory for repeated FTP copy


rawDescription: Appending to a line

description: Appending to a line


code:
lis[:] = [x for x in lis if not is_float(x)]
lis

rawDescription: How to check float string?

description: Check float string


code:
import numpy as np
a = np.array([["John", "Smith"], ["Jane", "Jones"]])
a = a.astype(object)
a[:,0] += " " + a[:,1]
a = a[:,:1]
a

rawDescription: How can we join two columns of a numpy array into a single column, separating the values by a space?


code:
while True:
    vari1=input("please enter your choice.")
    if vari1.lower() not in ['o','p']:
        print("please enter a appropriate choice")
    else:
        # do your stuff
        break

rawDescription: how many logical operator can we use in a statement in python?

description: How many logical operator can we use in a statement in python


rawDescription: convert (nx2) array of floats into (nx1) array of 2-tuples

description: Convert (nx2) array of floats into (nx1) array of 2-tuples


code:
def extract_elem_v2(elem_name):
    def key_extractor(obj):
        dct = obj if isinstance(obj, dict) else obj.__dict__
        return dct[elem_name]
    return key_extractor

rawDescription: Sorting a heterogeneous list of objects in Python


rawDescription: how to delete a record by using a class method?

description: Delete a record by using a class method


code:
def foobar():
    local('/pathto/foo.sh')

rawDescription: How to automate django dumpdata?

description: Automate django dumpdata


code:
import numpy as np
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit ... consequat."
# assume s continues after the "..."
v = list("aeiou")
cumVowels = [0,] + np.cumsum([l in v for l in s])
v_dict = {}
max_win_size = 100
if max_win_size > len(s): max_win_size = len(s)

for i in range(1, max_win_size):
    v_dict[i] = [0,] * (i+1)
    for pos in range(0, len(s)-i):
        v_dict[i][cumVowels[pos + i] - cumVowels[pos]] += 1

rawDescription: Reduce repeated string search from quadratic to faster


rawDescription: theano (python): elementwise gradient

description: Theano (python): elementwise gradient


code:
db.letter.opening.widget = suggest_widget(db.receiver.opening, id_field=db.i2l_receiver_profile.id,
                                          limitby=(0,10), min_length=1, db=db(db.i2l_receiver_profile.user_id==auth.user_id))

rawDescription: web2py Autofilling/autocomplete returns id

description: Web2py Autofilling/autocomplete returns id


code: df['new_col'] = df.colA.map(new_dict)

rawDescription: New pandas dataframe column using values from python dictionary


code:
import requests
from bs4 import BeautifulSoup

url = "http://www.expatistan.com/cost-of-living/comparison/phoenix/new-york-city"
page  = requests.get(url).text
soup_expatistan = BeautifulSoup(page)

expatistan_table = soup_expatistan.find("table", class_="comparison")
expatistan_titles = expatistan_table.find_all("tr", class_="expandable")

for expatistan_title in expatistan_titles:
    published_date = expatistan_title.find("th", class_="percent")
    print(published_date.span.string)

rawDescription: Python - Web Scraping - BeautifulSoup

description: Python - Web Scraping - BeautifulSoup


code:
def sort_list(lst):
    sort_order = ['red', 'blue', 'green', 'alpha']
    lst.sort(key=lambda x: sort_order.index(x.split(".")[1]))
    return lst

rawDescription: Custom order list python

description: Custom order list python


code:
self.citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
# some code
self.panel = citPanel(self, -1)

rawDescription: Cannot understand how to get data from checklistbox in wxpython


code:
import sys
import sdl2.ext

sdl2.ext.init()

window = sdl2.ext.Window("Hello World!", size=(640, 480), flags=sdl2.SDL_WINDOW_BORDERLESS)
window.show()

processor = sdl2.ext.TestEventProcessor()
processor.run(window)

rawDescription: PySDL2: Creating a borderless window

description: PySDL2: Creating a borderless window


rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


code:
# python3 source code
from tkinter import *
from tkinter.ttk import *
import threading
import time
import queue

root = Tk()
msg = StringVar()
Label(root, textvariable=msg).pack()

# This is our own event queue, each element should be in this form:
# (function_to_be_called_from_gui_thread, function_arguments)
# In python, functions are objects and can be put in a queue.
my_event_queue = queue.Queue()

def worker():
    """
    This is a time consuming worker, it takes 1 second for each task.
    If you put such a worker in the GUI thread, the GUI will be blocked.
    """
    task_counter = 0
    while True:
        time.sleep(1)  # simulate a time consuming task

        # show how many tasks finished in the Label. We put this action in my_event_queue instead of handle
        # it from this worker thread which is not safe. This action will be handled by my_event_handler which is
        # called from GUI thread.
        my_event_queue.put((msg.set, '{} tasks finished.'.format(task_counter)))
        task_counter += 1

def my_event_handler():
    """
    Query my_event_queue, and handle one event per time.
    """
    try:
        func, *args = my_event_queue.get(block=False)
    except queue.Empty:
        pass
    else:
        func(*args)

    # At last schedule handling for next time.
    # Every 100 ms, my_event_handler will be called
    root.after(100, my_event_handler)

threading.Thread(target=worker, daemon=True).start()  # start worker in new thread

my_event_handler()  # start handler, after root.mainloop(), this method will be called every 100ms. Or you can use root.after(100, my_event_handler)

root.mainloop()

rawDescription: How should I get my Tkinter IRC client to continuously read data from the IRC server?


code:
import Bio.PDB
path = '/path/to/PDB/file' # your file path here
p = Bio.PDB.PDBParser()
structure = p.get_structure('myStructureName', path)

rawDescription: Extract Columns from a Protein Data Bank (PDB) Text File


code:
class PickalableSWIG:

    def __setstate__(self, state):
        self.__init__(*state['args'])

    def __getstate__(self):
        return {'args': self.args}

rawDescription: How to make my SWIG extension module work with Pickle?

description: Make my SWIG extension module work with Pickle


code:
self.fig.canvas.mpl_connect('key_press_event', self.on_key_press)
self.fig.canvas.mpl_connect('key_release_event', self.on_key_release)

...

def on_key_press(self, event):
   if event.key == 'shift':
       self.shift_is_held = True

def on_key_release(self, event):
   if event.key == 'shift':
       self.shift_is_held = False

rawDescription: matplotlib: How to pick up shift click on figure?

description: Matplotlib: How to pick up shift click on figure


rawDescription: python multiprocessing peculiar memory management

description: Python multiprocessing peculiar memory management


code:
np.random.choice(np.arange(10), 10, True)
# 10 choices from the range with replacement

rawDescription: How to randomly change positions of non-zero entries of an array where certain rows are excluded

description: Randomly change positions of non-zero entries of an array where certain rows are excluded


rawDescription: Numpy: Get random set of rows from 2D array


code:
from itertools import zip_longest

with open('File1', 'rb') as f1, \
    open('File2', 'rb') as f2, \
    open('File3', 'wb') as f3:

    output = bytearray()

    for v1, v2 in zip_longest(f1.read(), f2.read()):
        output.append(v2 if v2 else v1)

    f3.write(output)

rawDescription: Reading binary file in Python and writing it into another patching by nonzero bytes from the third file


code:
f = lambdify(x, integrate(x**2+2,x))
f(2)

rawDescription: Evaluate integral from sympy as lambda function


code:
from MySQLdb.constants import FIELD_TYPE
conv = { FIELD_TYPE.VARCHAR: str }

rawDescription: force MySQLdb to treat all MySQL data as strings

description: Force MySQLdb to treat all MySQL data as strings


code:
d = dict()
for key, val in values:
    if key in d:
        d[key] += val
    else:
        d[key] = val

valuesNew = [(k,v) for k,v in d.iteritems()]

rawDescription: Add values in a list of tuples if one element is repeated


rawDescription: Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?


code:
def without_none_values(d):
  return {k:d[k] for k in d if d[k] is not None}

rawDescription: How to quickly convert from items in a list of lists to list of dictionaries in python?

description: Quickly convert from items in a list of lists to list of dictionaries in python


code:
wildcard = "Python source (*.spectrum)|*.spectrum|" \
           "All files (*.*)|*.*"

rawDescription: Set extension type for open and save dialogs


code:
from bs4 import BeautifulSoup

data = '''

Idag, by Karl (100)

 Sample text1

 18 comments

 Sample text2

 18 comments

 Sample text3

 18 comments

2014-01-14, byPerson  (50)

 Sample text4

 18 comments

'''
soup = BeautifulSoup(data)

result = []
tag = soup.find_all('div', {'class': 'day'})[0]
while True:
    tag = tag.next_sibling
    if hasattr(tag, 'class') and 'day' in tag['class']:
        break
    result.append(tag)
for e in result:
    print(e)

rawDescription: python 3.3 Beautifulsoup text between 2 sets of classes

description: Python 3.3 Beautifulsoup text between 2 sets of classes


code:
from binascii import unhexlify
import sqlite3

data = unhexlify('''\
6d73 7373 652e 6578 4e7c 4f74 6570 4b6e
7965 337c 3430 347c 347c 307c 5c7c 5200
6500 6700 6900 7300 7400 7200 7900 5c00
4d00 6100 6300 6800 6900 6e00 6500 5c00
5300 7900 7300 7400 6500 6d00 5c00 4300
7500 7200 7200 6500 6e00 7400 4300 6f00
6e00 7400 7200 6f00 6c00 5300 6500 7400
5c00 4300 6f00 6e00 7400 7200 6f00 6c00
5c00 5300 6500 7300 7300 6900 6f00 6e00
2000 4d00 6100 6e00 6100 6700 6500 7200'''.replace(' ','').replace('\n',''))

# OP's data dump must have been decoded from the original data
# as little-endian words, and is missing a final 0x00 byte.
# Byte-swapping and adding missing zero byte to get back what
# was likely the original binary data.
data = ''.join(a+b for a,b in zip(data[1::2],data[::2])) + '\x00'

with open('data.db','wb') as f:
    f.write(data)

def parsecreate(filename):
    with open(filename,'rb') as sourcefile:
        with sqlite3.connect("sqlite.db") as cx:
            cu = cx.cursor()
            cu.execute("create table data(id integer primary key,command text, ntfunc text, pid text, ppid text, handle text, roothandle text, genevalue text)")
            eachline = []
            for line in sourcefile:
                eachline = line.split('|')
                eachline[-1] = eachline[-1].decode('utf-16le')
                cu.execute("insert into data(command,ntfunc,pid,ppid,handle,roothandle,genevalue) values(?,?,?,?,?,?,?)",(eachline[0],eachline[1],eachline[2],eachline[3],eachline[4],eachline[5],eachline[-1]) )

parsecreate('data.db')

rawDescription: unicode string in file contain different

description: Unicode string in file contain different


code:
abspath = os.path.abspath
dirname = os.path.dirname
# 15 lines of heavy usage of those functions
a = abspath(somepath)
d = dirname(somepath)
...
del abspath, dirname

rawDescription: Can I define a scope anywhere in Python?

description: Define a scope anywhere in Python


code: list(range(1, 4+1))

rawDescription: Function to calculate the difference between sum of squares and square of sums


code: MyScore=float(input("enter my score"))

rawDescription: This python code calls a function that returns a value but user input is asked twice


code:
data = numpy.arange(0, 1000000, 128);
shiftData = numpy.arange(128, 1000000, 128);
result = (1-alpha)*data[:-1] + shiftdata;

rawDescription: optimizing low pass filter smoothing code for activity recognition

description: Optimizing low pass filter smoothing code for activity recognition


rawDescription: Am I supposed to create a file use .env or os.py to store my secret key


code:
from random import randrange
N = 365
ns = []
for _ in range(10000):
    n = 0
    seen = set()
    while True:
        b = randrange(N)
        n += 1
        if b in seen:
            break
        seen.add(b)
    ns.append(n)
print(sum(ns) / float(len(ns)))

rawDescription: How many samples needed for a collision (birthday paradox)


code: while not s[0].isalnum(): s = s[1:]

rawDescription: Most Pythonic was to strip all non-alphanumeric leading characters from string


rawDescription: Factoring polys in sympy

description: Factoring polys in sympy


rawDescription: empty key while using dictread

description: Empty key while using dictread


rawDescription: For loop in Scrapy returns full response multiple times


code:
def add(a, b):
    return a + b

rawDescription: how do I get a function to take two arguments?

description: Get a function to take two arguments


code: list_of_tuples = [tuple(k) for k in list_of_lists]

rawDescription: Fastest way to remove all multiple occurrence items from a list?


code:
import math

func_dict = {'square': lambda x: x**2,
             'cube': lambda x: x**3,
             'log': math.log}

def transform(value, transformation_list):
    for func_name in transformation_list:
        value = func_dict[func_name](value)
    return value

rawDescription: preserving order of function implementation

description: Preserving order of function implementation


rawDescription: Python regex - do not match word when it is in html tag


code:
def handleCommandLine():
    p = argparse.ArgumentParser()
    p.add_argument('--backend', '-b', default=None, help='Specify plotting backend')
    args = p.parse_args()

    if args.backend != None:
        matplotlib.use(args.backend)  #Must occur before importing pyplot

    global plt  #Style choice: Can also be placed at the top of the function
    import matplotlib.pyplot as plt  #Must occur after setting backend
    return args

rawDescription: How can I import a module into main() from a sub function?

description: Import a module into main() from a sub function


code:
from PyQt4 import QtGui, QtCore

class MyFrame(QtGui.QGraphicsView):
    def __init__( self, parent = None ):
        super(MyFrame, self).__init__(parent)

        scene = QtGui.QGraphicsScene()
        self.setScene(scene)

        # add some items
        x = 0
        y = 0
        w = 45
        h = 45
        pen   = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
        brush = QtGui.QBrush(pen.color().darker(150))

        item = scene.addEllipse(x, y, w, h, pen, brush)
        item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)

        # create an open path
        path = QtGui.QPainterPath()
        path.moveTo(-w, -h)
        path.lineTo(-w, h)
        path.lineTo(w, h)
        path.lineTo(w, -h)

        clr   = QtGui.QColor('blue')
        clr.setAlpha(120)
        brush = QtGui.QBrush(clr)
        pen   = QtGui.QPen(QtCore.Qt.NoPen)
        fill_item = scene.addRect(-w, y, w*2, h, pen, brush)
        path_item = scene.addPath(path)

if ( __name__ == '__main__' ):
    app = QtGui.QApplication([])
    f = MyFrame()
    f.show()
    app.exec_()

rawDescription: Python PyQt: How can I move my widgets on the window with mouse?


code:
from datetime import datetime

def str_to_date(string):
    pattern = '%m/%d/%Y' if len(string) > 8 else '%m/%d/%y'
    try:
        return datetime.strptime(string, pattern).date()
    except ValueError:
        raise  # TODO: handle invalid input

rawDescription: Python: Parse String as Date with Formatting


code:
with ExifTool() as e:
    metadata = e.get_metadata(*filenames)

rawDescription: Call exiftool from a python script?

description: Call exiftool from a python script


rawDescription: Pretty printing a list of list of floats?


code:
#TODO: respect naming convention
class sprite_to_place(pygame.sprite.Sprite):
    # you can use a single parameter instead of two
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("a_picture.png")
        # you can pass the position directly to get_rect to set it's position
        self.rect = self.image.get_rect(topleft=pos)
        # I don't know if you actually need this
        self.start_pos = pos

rawDescription: Pygame- Sprite set position with mouseclick


code:
while len(od) > 3:
    od.popitem()

od

rawDescription: How do you get the first 3 elements in Python OrderedDict?

description: Get the first 3 elements in Python OrderedDict


code:
Klass
instance

rawDescription: Python overriding class (not instance) special methods


code:
def transpose(rows):
    return list(zip(*rows))

rawDescription: Does anyone have a better solution for 'iteratively' applying zip in Python?


code:
@ensure_even(1)  #2nd argument must be even
def test(arg1, arg2):
  print(arg2)

test(1,2) #succeeds
test(1,3) #fails

rawDescription: How to pass a specific argument to a decorator in python

description: Pass a specific argument to a decorator in python


rawDescription: NumPy: create bool array like "repeat" but in multiple dimensions


rawDescription: Add utc time to filename python

description: Add utc time to filename python


code:
def split_input(string, chunk_size):
    num_chunks = len(string)/chunk_size
    if (len(string) % chunk_size != 0):
        num_chunks += 1
    output = []
    for i in range(0, num_chunks):
        output.append(string[chunk_size*i:chunk_size*(i+1)])
    return output

rawDescription: How would one limit characters per line when printing a raw_input to a text file?


code:
import itertools
import collections
element_counts = collections.Counter(itertools.chain.from_iterable(allsets))

rawDescription: Subtraction over a list of sets

description: Subtraction over a list of sets


code:
# It doesn't matter which `with` block is the outermost.
with open('resultfile', 'w') as wFile:
    with open('versions.txt', 'r') as verFile:
        for line in verFile:
            if 'VERSION_2_' in line:
                # Split the line from the right on underscores and
                # take the last part of the resulting list.
                wFile.write(line.rpartition('_')[-1])

rawDescription: Search for specific string, only copy part of string into another textfile


rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


code: x not in seen

rawDescription: Remove following duplicates in a tuple

description: Remove following duplicates in a tuple


code: timeit.timeit('1+1', number=1000000)

rawDescription: Two very different but very consistent results from Python timeit


code:
import multiprocessing

class Test(object) :

    def __init__(self):
       self.some_list = []  # Normal list

    def method(self):
        self.some_list.append(123)  # This change gets lost

if __name__ == "__main__":
    t1 = Test()
    t2 = Test()
    pr1 = multiprocessing.Process(target=t1.method)
    pr2 = multiprocessing.Process(target=t2.method)
    pr1.start()
    pr2.start()
    pr1.join()
    pr2.join()
    print(t1.some_list)
    print(t2.some_list)

rawDescription: Parallel execution of class methods

description: Parallel execution of class methods


code:
{5}
Hello

rawDescription: Parsing IMAP Email BODYSTRUCTURE for Attachment Names


code:
# Calculation of A.dot(X_r[:,:,n,s])
p1 = np.einsum('i,ijkl->jkl',A,X_r)

# Calculation of B.dot(X_u[:,:,n,s])
p2 = np.einsum('i,ijkl->jkl',B,X_u)

# Include .dot(k) part to get the final output
out = np.einsum('ijk,i->kj',p1*p2,k)

rawDescription: Fastest way to use Numpy - multi-dimensional sums and products


rawDescription: How to create a custom manager for related objects?

description: Create a custom manager for related objects


code:
import itertools

def exponent_partitions(exponents, min_exponents):
    """Generate all vector partitions of 'exponents', each of whose
    entries is lexicographically at least 'min_exponents'."""
    if all(exponent == 0 for exponent in exponents):
        yield []
    else:
        for vector in itertools.product(*(range(v+1) for v in exponents)):
            if vector >= min_exponents:
                remainder = tuple(x - y for x, y in zip(exponents, vector))
                for partition in exponent_partitions(remainder, vector):
                    yield partition + [vector]

def divisor_from_exponents(primes, exponent_vector):
    """Reconstruct divisor from the list of exponents."""
    divisor = 1
    for p, e in zip(primes, exponent_vector):
        divisor *= p**e
    return divisor

def multiplicative_partitions(primes, exponents):
    """Generate all multiplication partitions of
    product(p**e for p, e in zip(primes, exponents))"""
    if len(exponents) == 0:
        # Corner case for partitions of 1.
        yield []
    else:
        initial_vector = (0,) * (len(exponents) - 1) + (1,)
        for partition in exponent_partitions(exponents, initial_vector):
            yield [divisor_from_exponents(primes, vector) for vector in partition]

rawDescription: How can I generate all possible divisor products for a number?

description: Generate all possible divisor products for a number


code: del self.population[:]

rawDescription: updating a list in python

description: Updating a list in python


code:
a1  = gca().annotate('',xy=(1e-1,1e-3),xycoords='data',xytext =(1e-1,1e1),textcoords = 'data',arrowprops=opt,size=20)
a2  = gca().annotate('',xy=(1e2,1e-3), xycoords='data',xytext =(1e1,1e-3),textcoords = 'data',arrowprops=opt,size=20)
show()

rawDescription: Matplotlib arrow head in log-log plot

description: Matplotlib arrow head in log-log plot


code:
each_block = ("\n".join(map(str,seq)) for seq in stuff if seq)
print("\n\n".join(each_block))

rawDescription: Print a new line in between a list in python


code:
def parseName():
    type, firstName = Lexer.next_token()
    if type != Lexer.STRING: raise ParseError()
    type, lastName = Lexer.next_token()
    if type == Lexer.STRING: # first-name last-name
        return firstName + ' ' + lastName
    else:
        Lexer.keep(type, lastName)
        return firstName

rawDescription: lexical analyse or series of regular expressions to parse unstructured text into structured form

description: Lexical analyse or series of regular expressions to parse unstructured text into structured form


code: s.index = pd.DatetimeIndex(s.index)

rawDescription: Pandas : how do I merge minute data rows in a timeseries


code:
@view_config(route_name='home', renderer='dashboard.jinja2')
def home_view(request):
    if request.authenticated_userid is None:
        # most people would probably opt to redirect to the login url
        # here instead of rendering a response, but you asked
        return render_to_response('login.jinja2', {}, request=request)
    # user is logged in, so use the dashboard renderer
    return {}

rawDescription: python pyramid, render user dashboard at root url when logged in

description: Python pyramid, render user dashboard at root url when logged in


code:
def command_handler():
    return sum1.num_press(0)  # or without the return

bttn_0["command"] = command_handler

rawDescription: Need help rewriting a Python function without using lambda


code: year = column_property(extract('year', date))

rawDescription: SA: can I have a 'year' column_property for a Date column?


rawDescription: Referring to the first element of all tuples in a list of tuples


code:
p = re.compile(r'<img.*?title=(".*?")/>')
p.sub(lambda match: match.group(1), test2)

rawDescription: Relace emotion html tags with emotion names using Python


code:
import re

discussions = []
for input_file_name in ['Output2.txt', 'Output2012.txt']:
    with open(input_file_name) as f:
        doc = f.read()

    item7 = r"Item 7\.*\s*Management.s Discussion and Analysis of Financial Condition and Results of Operations"
    discussion_text = r"[\S\s]*"
    item8 = r"Item 8\.*\s*Financial Statements"

    discussion_pattern = item7 + discussion_text + item8
    results = re.findall(discussion_pattern, doc)

    # Some input files have table of contents and others don't
    # just keep the last match
    discussion = results[len(results)-1]

    discussions.append((input_file_name, discussion))

rawDescription: Python: Using regex to find the last pair of occurence


code: p = User(name="Fred", email="fred@example.com")

rawDescription: Writing a __init__ function to be used in django model


code:
N = 2 # Parameter to decide how many duplicates are allowed

sortidx = a.argsort()
idx = np.searchsorted(a,m,sorter=sortidx)[:,None] + np.arange(N)
lim_counts = (a[:,None] == m).sum(0).clip(max=N)
idx_clipped = idx[lim_counts[:,None] > np.arange(N)]
out = np.in1d(np.arange(a.size),idx_clipped)[sortidx.argsort()]

rawDescription: numpy mask array limiting the frequency of masked values

description: Numpy mask array limiting the frequency of masked values


rawDescription: How to change colours of nodes and edges of bipartite graph in networkX?

description: Change colours of nodes and edges of bipartite graph in networkX


code:
def readObs(dir, file):
    df = pd.DataFrame()
    #Grab header
    header = ''
    with open(dir + file) as handler:
        for i, line in enumerate(handler):
            header += line
            if 'END OF HEADER' in line:
                break
    #Grab Data
    with open(dir + file) as handler:
        for i, line in enumerate(handler):
            #Check for a Timestamp lable
            if '> ' in line:
                #Grab Timestamp
                links = line.split()
                index = datetime.strptime(' '.join(links[1:7]), '%Y %m %d %H %M %S.%f0')
                #Identify number of satellites
                satNum = int(links[8])
                #For every sat
                for j in range(satNum):
                    #just save the data as a string for now
                    satData = handler.readline()
                    #Fix the names
                    satdId = satData.replace("G ", "G0").split()[0]
                    #Make a dummy dataframe
                    dff = pd.DataFrame([[index,satdId,satData]], columns=['%_GPST','satID','satData'])
                    #Tack it on the end
                    df = df.append(dff)
    return df, header

rawDescription: Reading GPS RINEX data with Pandas

description: Reading GPS RINEX data with Pandas


code:
for line in x:
    if not line.startswith("?"):
        DO_STUFF

rawDescription: What is the easiest way to get all strings that do not start with a character?


code: f(*args,**kwargs)

rawDescription: Python multiprocessing.Pool: when to use apply, apply_async or map?


code:
import numpy as np

#generate dummy data
nrows=6
ncols=11
nframes=3
threshold=0.3
data=np.random.rand(nrows,ncols,nframes)

CM_tilde = np.mean(data, axis=1)
N = data.shape[1]

all_CMs2 = np.mean(np.where(data < (CM_tilde[:,None,:]+threshold),data,CM_tilde[:,None,:]),axis=1)
data_cm2 = data - all_CMs2[:,None,:]

rawDescription: python numpy operation instead of for loops

description: Python numpy operation instead of for loops


rawDescription: javascript comparison operators

description: Javascript comparison operators


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)

fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=100, 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


rawDescription: Multiply ticklabel values in colorbar when plotting matrix with imshow


code:
settings = wx.Dialog()
result = settings.ShowModal()
... # Save new settings based on result
settings.Destroy()

rawDescription: wxPython, efficient way to create a settings dialog

description: WxPython, efficient way to create a settings dialog


code:
@app.route('/images/<cropzonekey>')
def images(cropzonekey):
    return render_template("images.html", title=cropzonekey)

@app.route('/fig/<cropzonekey>')
def fig(cropzonekey):
    fig = draw_polygons(cropzonekey)
    img = StringIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')

rawDescription: Passing a matplotlib figure to HTML (flask)


code:
import time

value = None

def setup():
    global value
    value = 1

def test_one():
    time.sleep(2)
    assert value == 1

rawDescription: How to benchmark unit tests in Python without adding any code

description: Benchmark unit tests in Python without adding any code


code:
def helper():
    bar = get_some_value()
    yield bar
    save(bar)

def foo():
  do_something()
  for x in helper(): yield x
  do_something_else()
  # more code in between
  for x in helper(): yield x
  # finishing up

rawDescription: Code duplication in generator functions in Python


code:
import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Firefox()
url = 'http://reverb.echo.nasa.gov/reverb/'
browser.get(url)

for i in range(10):
    try:
        browser.find_element_by_xpath(
            ".//*[contains(text(), '15 Minute Stream Flow Data: USGS (FIFE)')]"
        ).click()
        break
    except NoSuchElementException as e:
        print('retry in 1s.')
        time.sleep(1)
else:
    raise e

rawDescription: Select check box using Selenium Python

description: Select check box using Selenium Python


code:
def grpavg(ws):
    i = df1['word'].isin(ws)
    return df1.loc[i, 'score'].sum() / len(ws)

df3['avg-score'] = df3['words'].str.split().map(grpavg)
df3

rawDescription: Python Pandas Lookup/Cross Referencing

description: Python Pandas Lookup/Cross Referencing


code:
v1
v1
v1
v2
v2
v3
v1

rawDescription: Count lines in a file

description: Count lines in a file


code:
def megasplit(pattern, string):
    splits = list((m.start(), m.end()) for m in re.finditer(pattern, string))
    starts = [0] + [i[1] for i in splits]
    ends = [i[0] for i in splits] + [len(string)]
    return [string[start:end] for start, end in zip(starts, ends)]

print(megasplit(r'(?<!foo)(?=bar)', 'foobarbarbazbar'))
print(megasplit(r'o', 'foobarbarbazbar'))

rawDescription: Python regex: splitting on pattern match that is an empty string


code: map(sum, np.roll(arra, arra.shape[2]))

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


code: 1 if index in l else 0

rawDescription: Populating a sparse list with random 1's


code:
class Settings(object):
    def __getattr__(self, attr):
        return load_plugin(attr)

settings = Settings()

rawDescription: Accessing classes from arbitrary modules inside of package directly


code: any_curr("EUR250", ["USD", "GBP", "EUR"])

rawDescription: Determine if the string contains any currency sign?


code:
import re
import urllib
s = b'https\u00253A\u00255C\u00252F\u00255C\u00252Ffbcdn-video'
re.sub(r'\\(.)', r'\1', urllib.unquote_plus(s.decode('unicode_escape')))

rawDescription: convert unicode of form "\uxxxxxx" to string or text

description: Convert unicode of form "\uxxxxxx" to string or text


code:
class MyHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('name')

rawDescription: Get form data using get method in python webapp2


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

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t, s)

# Retrieve the limits of the x and y axis.
xlims = ax.get_xlim()
ylims = ax.get_ylim()

# Create two FixedLocator objects. FixedLocator objects take a sequence
# which then is translated into the tick-positions. In this case I have
# simply given the x/y limits as the sequence.
xmajorlocator = FixedLocator(xlims)
ymajorlocator = FixedLocator(ylims)

ax.xaxis.set_major_locator(xmajorlocator)
ax.yaxis.set_major_locator(ymajorlocator)

# Create two LinearLocator objects for use in the minor ticks.
# LinearLocator objects take the number of ticks as an argument
# and automagically calculate the appropriate tick positions.
xminorlocator = LinearLocator(10)
yminorlocator = LinearLocator(10)

ax.xaxis.set_minor_locator(xminorlocator)
ax.yaxis.set_minor_locator(yminorlocator)

# Create two FormatStrFormatters to format the major ticks.
# I've added this simply to complete the example, you can set
# a fmt string using Python syntax to control how your ticks
# look. In this example I've formatted them as floats with
# 3 and 2 decimal places respectively.
xmajorformatter = FormatStrFormatter('%.3f')
ymajorformatter = FormatStrFormatter('%.2f')

ax.xaxis.set_major_formatter(xmajorformatter)
ax.yaxis.set_major_formatter(ymajorformatter)

plt.show()

rawDescription: Placing ticks on specific values

description: Placing ticks on specific values


rawDescription: Python graphics module

description: Python graphics module


code: getQuote("GS", what=yahooQF())

rawDescription: Is there a way to automatically get general info of many stocks like P/E ratio, Yield, and so on?


code:
def AddBits2(byte_offset, bit_offset, bits, value):
    global Bit_Offset
    global Array

    # precompute offsets
    bit_offset += Bit_Offset
    byte_offset += bit_offset / 8
    Bit_Offset += bits

    # Mask out any extra bits in value and adjust value to align to byte
    value = (((1 << bits) - 1) & value) << (bit_offset % 8)

    # go through bytes and OR them in one byte at a time
    for i in range((bits + 7) / 8) :
        Array[byte_offset + i] |= (value & 0xff)
        value >>=8

rawDescription: Understanding bit-manipulation function in Python


rawDescription: How to check version of python package if no __version__ variable is set

description: Check version of python package if no __version__ variable is set


code:
class DummyObj(object):

    ...

    def __hash__(self):
        return (hash(self.myTuple) ^
                hash(tuple(self.myList)) ^
                hash(tuple(self.myDictionary.items())))

rawDescription: How to implement __eq__ for set inclusion test?

description: Implement __eq__ for set inclusion test


rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


code:
from  availableDates import avDates
printTest = avDates()
print ("These are the dates - ")
for pt in printTest:
    print (pt)

rawDescription: Having some problems printing out an array in Python3


code:
@app.route('/<slug>')
def feature(slug):
    if slug_in_database(slug):
        return "feature: " + slug
    return catch(slug)

@app.route('/<path:url>')
def catch(url):
    return "catch: " + url

rawDescription: Skip/pass over view function so the next can execute in Flask


code:
@receiver((post_save,), sender='User')
def create_user_folders(sender, instance, created, **kwargs):
   if not created: return
   # generate MessageFolder && UserFolder

rawDescription: How can I create initial values for a model in django?

description: Create initial values for a model in django


code:
import csv

fnumbers = r'casnum.txt'
fnames = r'casname.txt'
foutput = r'CAS-S.csv'
#Take the text file with Source CAS Numbers and make it into a list
sourcecas = []
file = open(fnumbers, 'r')
sourcecas = file.readlines()
sourcecas[:] = [line.rstrip('\n') for line in sourcecas]
file.close() # Here's the fix

#Take the text file with Source CAS Names and make it into a list
sourcecasnames = []
file = open(fnames, 'r')
sourcecasnames = file.readlines()
sourcecasnames[:] = [line.rstrip('\n') for line in sourcecasnames]
file.close() # Make sure to close your file when you're done with it

#Zip the source cas numbers and names into a CSV file
zip(sourcecas, sourcecasnames)
with open(foutput, 'w') as f: # note that with open() closes itself
    writer = csv.writer(f, delimiter=',')
    writer.writerows(zip(sourcecas, sourcecasnames))

rawDescription: Zip two lists into text file

description: Zip two lists into text file


code:
#!python3
import threading
from queue import Queue
import time

# lock to serialize console output
lock = threading.Lock()

def do_work(item):
    time.sleep(.1) # pretend to do some lengthy work.
    # Make sure the whole print completes or threads can mix up output in one line.
    with lock:
        print(threading.current_thread().name,item)

# The worker thread pulls an item from the queue and processes it
def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

# Create the queue and thread pool.
q = Queue()
for i in range(4):
     t = threading.Thread(target=worker)
     t.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
     t.start()

# stuff work items on the queue (in this case, just a number).
start = time.perf_counter()
for item in range(20):
    q.put(item)

q.join()       # block until all tasks are done

# "Work" took .1 seconds per task.
# 20 tasks serially would be 2 seconds.
# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
print('time:',time.perf_counter() - start)

rawDescription: Python 3.3 Simple threading event example.


code:
import numpy as np
from multiprocessing import Pool

def process(chunk):
    max_ = np.zeros((4000, 4000))
    for im in chunk:
        im_array = np.array(Image.open(im))
        max_ = np.maximum(max_, im_array)
    return max_

if __name__ == "__main__":
    p = Pool(8)

    chunksize = 500 #4000/8 = 500, might have less overhead
    chunks = [files[i:i+chunksize]
              for i in range(0, len(files), chunksize)]

    # this returns an array of (len(files)/chunksize, 4000, 4000)
    max_arrays = np.array(p.map(process, chunks))
    maxi = np.amax(max_array, axis=0) #finds maximum along first axis
    img = Image.fromarray(maxi) #should be of shape (4000, 4000)

rawDescription: Find the maximum x,y value fromn a series of images


code:
def panelCreation():
    dd = {}
    for i in range(1,3):
        name = 'X' + str(i)
        dd[name] = createNewDf(i)
    return Panel(dd)

rawDescription: adding dataFrame to panel in python pandas

description: Adding dataFrame to panel in python pandas


code: 'male'

rawDescription: TypeError: 'WordListCorpusReader' object has no attribute '__getitem__' while using nltk.classify.apply_features


code:
def Addzero(value):
    return [0] * (8-len(value)) + value

rawDescription: Prepending zeros to a list

description: Prepending zeros to a list


code: pieces = s.split()

rawDescription: Python replace every odd occurrence of space with "_"


code:
def wfsc_pod1(self):
    return "%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0])

rawDescription: Python - List and Loop in one def

description: Python - List and Loop in one def


code: birthday[month] = format(birthday[month], '>02')

rawDescription: Python: How could this be written in a less verbose form?


code:
try:
    from itertools import izip as zip #python 2
except:
    pass #python 3 already has zip

#decorator
def attribute_tuple(cls):

    if not hasattr(attribute_tuple,'initialized'):
        attribute_tuple.initialized=True
        def get(self,keys):
            keys = keys.split(',')
            return tuple(getattr(self, attr) for attr in keys)
        attribute_tuple.get = get
        def set(self,keys,values):
            keys = keys.split(',')
            if len(keys) != len(values):
                raise ValueError('too many values to unpack (expected %d)'%len(keys))
            for attr,val in zip(keys, values):
                setattr(self, attr, val)
        attribute_tuple.set = set
        def delete(self,keys):
            keys = keys.split(',')
            for attr in keys:
                delattr(self, attr)
        attribute_tuple.delete = delete

    cls.__getitem__ = attribute_tuple.get
    cls.__setitem__ = attribute_tuple.set
    cls.__delitem__ = attribute_tuple.delete

    return cls

@attribute_tuple
class myclass:
    pass

rawDescription: A member tuple (as opposed to member variable) of a class?