code: {k: list(set(d1.get(k, [])) | set(d2.get(k, []))) for k in d1.viewkeys() | d2}

rawDescription: Merge two dictionaries in python with lists as values


code: tempdict[charactername]

rawDescription: Python. Import specific characters from a .txt file


code:
service_args = [
    '--proxy=127.0.0.1:9999',
    '--proxy-type=socks5',
]
driver = webdriver.PhantomJS(service_args=service_args)
# ...............

rawDescription: Selenium PhantomJS custom headers in Python


code:
import datetime
datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()

rawDescription: convert string to date type python

description: Convert string to date type python


code:
import re
text = 'Here is a phone number: 1 (123) 123-4567'
phonePattern = re.compile("\d?(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4})", re.S)
phonePattern.sub(lambda m: re.sub('\d', 'X', m.group(1)), text)

rawDescription: How to replace phone number with Xs?

description: Replace phone number with Xs


code:
pressed_keys = set()

def keyPressEvent(self, event):
    pressed_keys.add(event.key())

def keyReleaseEvent(self, event):
    pressed_keys.remove(event.key())

rawDescription: How to process short keypress in the same time long keypress is performed?

description: Process short keypress in the same time long keypress is performed


code: evt = Quartz.CGEventCreateKeyboardEvent(None, vkey, True)

rawDescription: How to use CGEventCreateKeyboardEvent in Python on Mac?

description: Use CGEventCreateKeyboardEvent in Python on Mac


code:
split_at_idx(string.ascii_letters, [3, 10, 12, 40])
split_at_idx(string.ascii_letters, [])
split_at_idx(string.ascii_letters, [13, 26, 39])

rawDescription: Efficiently partition a string at arbitrary index


code:
def isSorted(self):
    return self.a == self.b

rawDescription: Class and while loop?

description: Class and while loop


code: guessfoo = int(input('Guess my number: '))

rawDescription: Guessing a number, true or false? Python


rawDescription: Python set sequence of numbers to add or subtract for certain result


code:
from collections import defaultdict
def sortbit(n):
    d = defaultdict(list)
    max_val = 2**n
    for x in range(0,max_val):
       d[bin(x).count("1")].append("{0:0{1}b}".format(x,n))
    return d

rawDescription: appending values to list and adding to dictionary

description: Appending values to list and adding to dictionary


code:
list_x = [[66,76],
          [25,26,27],
          [65,66,67,68],
          [40,41,42,43,44],
          [11,21,31,41,51,61]]
flat = [y for x in list_x for y in x]
flat # Just to demonstrate
len(flat) != len(set(flat)) # True because there are duplicates
# This list has no duplicates...
list_x = [[1, 2],
          [3, 4, 5],
          [6, 7, 8, 9],
          [10, 11, 12, 13],
          [14, 15, 16, 17, 18]]
flat = [y for x in list_x for y in x]
len(flat) != len(set(flat)) # ...so this is False

rawDescription: How to find out if there are any duplicates in list of lists

description: Find out if there are any duplicates in list of lists


code:
idx = np.where(cond)[0]
label[idx[arr[idx].argmin()]] = 3

rawDescription: Replacing minimum element in a numpy array subject to a condition


code:
from django import forms
from app_name.models import Upload

class UploadForm(forms.ModelForm):
    class Meta:
        model = Upload

rawDescription: Uploading csv file from url using django forms


code:
ind2=np.where((A.data>0.0)&(A.data<=1.0))
A.indices[ind2]
A.indptr[ind2]
A.data[ind2]
B.data[ind2]=(3.0-B.data[ind2])**5-6.0*(2.0-B.data[ind2])**5
B.data[ind2]

rawDescription: numpy.where equivalent for csr_matrix python

description: Numpy.where equivalent for csr_matrix python


code:
df
grouped = df.groupby(['GENE', 'DESC'])
grouped.agg(np.sum) # agg is a shortcut for aggregate

rawDescription: Python pandas to partially collapse 2d matrix


rawDescription: zip function help with tuples

description: Zip function help with tuples


code:
import math

for i in range(1, N + 1):
    angle = (i - 1) * math.pi * 2 / N
    x_coord = radius * math.cos(angle)
    y_coord = radius * math.sin(angle)
    z_coord = 0
    cube = place_cube(x_coord, y_coord, z_coord)
    cube.rotate_around_z(angle)

rawDescription: I need help forming a circle with cubes, useing blender 2.69 with python engine


code:
def getreads(length, table, genome):
        genome_len = len(genome)

        arr = numpy.frombuffer(mp_arr.get_obj())
        counts = arr.reshape(10,101)

        for start in range(0,genome_len):
                gc = gc_count(genome[start:start+length])
                l = table[ (length, gc) ]
                l.append( (start) )
                table[ (length, gc) ] = l
                counts[length,gc] +=1

if __name__ == "__main__":
    g = 'ACTACGACTACGACTACGCATCAGCACATACGCATACGCATCAACGACTACGCATACGACCATCAGATCACGACATCAGCATCAGCATCACAGCATCAGCATCAGCACTACAGCATCAGCATCAGCATCAG'
    genome_len = len(g)

    mgr = MyManager()
    mgr.start()
    m = mgr.defaultdict(list)
    mp_arr = multiprocessing.Array(c.c_double, 10*101)
    arr = numpy.frombuffer(mp_arr.get_obj())
    count = arr.reshape(10,101)

    pool = multiprocessing.Pool(9)
    partial_getreads = partial(getreads, table=m, genome=g)

    pool.map(partial_getreads, range(1, 10))
    pool.close()
    pool.join()

    arr = numpy.frombuffer(mp_arr.get_obj())
    count = arr.reshape(10,101)

rawDescription: Python multiprocessing: losing counts after pool.join()?


code:
from collections import Iterable
if isinstance(e, Iterable):
   ...

rawDescription: Python, best way to write a sum of two for loops


code:
p1 = session.query(Parent).get('A1234')
print(p1)
print(p1.children)

c1 = session.query(Child).get(1234)
print(c1)
print(c1.parent)

rawDescription: relationship with a sliced and casted value of the column in SQLAlchemy

description: Relationship with a sliced and casted value of the column in SQLAlchemy


code:
BACKENDS = {
    'facebook': CustomFacebookAuth,
}

rawDescription: How to show user a form to set username when using django with django-social-auth

description: Show user a form to set username when using django with django-social-auth


code:
def highestNumber(l):
    return sorted(l)[-1]

rawDescription: Python: Function returning highest value in list without max()?


rawDescription: How to discard pyparsing parseResults during parsing?

description: Discard pyparsing parseResults during parsing


code:
dictionary = {
    "+": operator.iadd,
    "-": operator.isub,
    "*": operator.imul,
    "/": operator.itruediv,
    "^": operator.ipow
}

answer = dictionary[symbol](answer, number)

rawDescription: How do I access a mathematical operation within a dictionary based on user input?

description: Access a mathematical operation within a dictionary based on user input


code:
t is s
g is s

rawDescription: Why use Inbuilt copy() function for sets in python when we can simply assign it?


code:
class Showing(Base):
    __tablename__   = "showings"

    time            = Column(DateTime, primary_key=True)
    link            = Column(String)
    film_id         = Column(Integer, ForeignKey('films.id'), primary_key=True)
    cinema_id       = Column(Integer, ForeignKey('cinemas.id'), primary_key=True)

rawDescription: Fastest way to insert object if it doesn't exist with SQLAlchemy


code:
True == 1
False == 0
'ab'[True]
'ab'[False]

rawDescription: Please explain (python): example_list[a < b]


code:
indices = ([0, 1], [0, 1])
np.add.at(m, indices, 2)

rawDescription: Using ufunc.at on matrix

description: Using ufunc.at on matrix


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

    segments = relationship(Segment)

    @property
    def visible_items(self):
        return [item for segment in self.segments
                     for item in segment.items
                     if segment.visible and item.visible]

class Segment(Base):
    # ...

    items = relationship(Item)

rawDescription: SQLAlchemy - Filtering children in One-To-Many relationships


code:
class Bar (Base):
    def get_message_impl (self):
        raise Exception ("Bar.get_message_impl always fails!")

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


code:
cursor.execute("SELECT * FROM my_table WHERE id IN (%s)",
    (','.join(a_long_list_of_ids),)
)
do_something(cursor.fetchall())

rawDescription: difference between SELECT queries embedded in for loop vs WHERE id IN syntax

description: Difference between SELECT queries embedded in for loop vs WHERE id IN syntax


rawDescription: How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation?

description: Force matplotlib to write out the full form of the x-axis label, avoiding scientific notation


code:
target_seq = "567"
input_file = "1234567890"

target_seq.read(5) # reads 12345, doesn't contain 567
target_seq.read(5) # reads 67890, doesn't contain 567

rawDescription: Removing a sequence of characters from a large binary file using python


code:
class AddressAdmin(admin.ModelAdmin):
    model = Address
    list_filter = ['memberaddress_set__member__user']

rawDescription: Enabling Django Admin Filters on Many-to-Many Fields


code: f['Adj Close'].loc[:, 'AAPL']

rawDescription: how to pick out individual columns of numerical values from Datareader pandas?

description: Pick out individual columns of numerical values from Datareader pandas


code: np.genfromtxt('abc.txt', delimiter=',', dtype=None, names=True)

rawDescription: Query about np.loadtext() function

description: Query about np.loadtext() function


code:
def enumerate2(xs, start=0, step=1):
    for x in xs:
        yield (start, x)
        start += step

rawDescription: Python enumerate downwards or with a custom step


code: assert abs(x-y) < 0.0001

rawDescription: pytest: assert almost equal

description: Pytest: assert almost equal


code:
1% done
2% done
3% done
4% done
5% done
6% done
7% done
8% done
9% done
10% done
11% done
12% done
13% done
14% done
15% done
16% done
17% done
18% done
19% done
20% done
21% done
22% done
23% done
24% done
25% done
26% done
27% done
28% done
29% done
30% done
31% done
32% done
33% done
34% done
35% done
36% done
37% done
38% done
39% done
40% done
41% done
42% done
43% done
44% done
45% done
46% done
47% done
48% done
49% done
50% done
51% done
52% done
53% done
54% done
55% done
56% done
57% done
58% done
59% done
60% done
61% done
62% done
63% done
64% done
65% done
66% done
67% done
68% done
69% done
70% done
71% done
72% done
73% done
74% done
75% done
76% done
77% done
78% done
79% done
80% done
81% done
82% done
83% done
84% done
85% done
86% done
87% done
88% done
89% done
90% done
91% done
92% done
93% done
94% done
95% done
96% done
97% done
98% done
99% done
100% done
b114ecaab65bc5b02f5a129bd29d1864

rawDescription: Getting percentage complete of an md5 checksum


rawDescription: Search with employee_id in openerp?

description: Search with employee_id in openerp


code: [i for i in x if i in y]

rawDescription: First common element from two lists

description: First common element from two lists


code: newstring = "".join(s1[i] for i in lst)

rawDescription: How to construct a string by joining characters efficiently?

description: Construct a string by joining characters efficiently


code:
a, b = [1, 2], [2, 3]

def func():
    a, b = b, a

import dis
dis.dis(func)

rawDescription: Python swapping lists

description: Python swapping lists


rawDescription: h5py: Correct way to slice array datasets

description: H5py: Correct way to slice array datasets


code:
if ~(np.all(l == new,1)).any():
    l = np.append(l, new).reshape(-1, 3)

rawDescription: Check existence of a list in a 2d array

description: Check existence of a list in a 2d array


code:
items = get_items(db_connection)
template = Template(file='OptionsPage.html')
print(template.render(items=items, a_variable=42))

rawDescription: Printing data from MySql in HTML using Python


code: locations = [l for l in (self.room, self.floor, self.building) if l is not None]

rawDescription: Python: a better way to write a if-then block with join?


code:
response = s.post(url, data=payload)
print(response.text)

rawDescription: POST to .jsp website with Python requests library


code: mystring="".join(line[:2] for line in data)

rawDescription: Find amount of times that the chosen letters appear


rawDescription: What is a "Manager" in django?

description: What is a "Manager" in django


rawDescription: Decimal precision in python without decimal module


code:
a = Pokemon('charmander', 'fire')
a.weakness("passing in the poketype argument here")

rawDescription: Error with a simple program, printing error (python)


code:
import re

def ReplaceThreeOrMore(s):
    # pattern to look for three or more repetitions of any character, including
    # newlines.
    pattern = re.compile(r"(.)\1{2,}", re.DOTALL)
    return pattern.sub(r"\1\1", s)

rawDescription: Python: how to cut off sequences of more than 2 equal characters in a string


rawDescription: Numpy or SciPy Derivative function for non-uniform spacing?


code:
def mymode(s):
    try:
        return s.mode().iloc[0]
    except IndexError:
        # just pick the first element, even though it occurs only once, even if it's NaN
        return s.iloc[0] if len(s) >= 1 else np.nan

rawDescription: backfilling data from one column into another

description: Backfilling data from one column into another


code: new_list = old_list[:]  # the slicing at the end just takes the whole list

rawDescription: How do I change an element in a list, and keep a copy of the original list?

description: Change an element in a list, and keep a copy of the original list


code:
def line2cipher(amp,seed,line):
    acc=''
    for i in line[1:]:
        res=logMap(amp,seed)
        offset=int(96*res)
        acc+= cipherChr(i,offset)
    print(acc,res)

rawDescription: Making for loop ignore something first time through


code:
class A:
    d = {}
    @classmethod
    def c(cls):
        print (cls.d)

class B(A):
    d = A.d.copy()
    d.update({0:1})

B.c()
A.c()

rawDescription: Class attribute overriding: keep parent class changes


code:
# Return whether a path is absolute.
# Trivial in Posix, harder on Windows.
# For Windows it is absolute if it starts with a slash or backslash (current
# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
# starts with a slash or backslash.

def isabs(s):
    """Test whether a path is absolute"""
    s = splitdrive(s)[1]
    return len(s) > 0 and s[0] in _get_bothseps(s)

rawDescription: How does abspath determine if a path is relative?


code:
res = {}
for ix in xrange(len(b)):
    cur_b = b[ix] # grab the next number in b
    cur_a = a[ix] # grab the corresponding number in a
    try: # if we've seen cur_b before then we can add cur_a to it
        res[cur_b] += cur_a
    except KeyError: # otherwise we've never seen cur_b before so we set it to cur_a
        res[cur_b] = cur_a

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

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


code: y

rawDescription: Restricting a sparse matrix to a subspace in scipy


code:
bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

rawDescription: binning data in python with scipy/numpy

description: Binning data in python with scipy/numpy


code: import numpy as np

rawDescription: write a loop to represent each polynomial from an array for n polynomials

description: Write a loop to represent each polynomial from an array for n polynomials


code:
listwidget1 = QListWidget(self)
listwidget2 - QListWidget(self)
listwidget1.itemSelectionChanged.connect(function_that_updates_listwidget2)

rawDescription: How to updated ListView 2 based on Item clicked on ListView 1

description: Updated ListView 2 based on Item clicked on ListView 1


code:
b = ['AC', '3H', 'TD', '9C', 'KD', '7H', '5S']
suits = [s for _, s in b]
max(suits.count(s) for s in suits) >= 5

rawDescription: Check string in list for multiple occurrence


code:
def draw (self, context):
    layout = self.layout
    row = layout.row()
    row.operator("foo.bar", text="Whatever you want")

rawDescription: How to change Operator's label in Blender 2.63 depending on the context?

description: Change Operator's label in Blender 2.63 depending on the context


rawDescription: Python List of tuples positionally

description: Python List of tuples positionally


code:
from django.template.defaultfilters import slugify
def get_nickname(self):
    nick = self.name
    vowels = ('a','e','i','o','u')
    first_letter = nick[:1]
    nick = nick[1:]

    for vowel in vowels: nick = nick.replace(vowel,'')
    nick = first_letter + nick
    if len(nick) > 8:
        nick = nick[:7]
    return nick

def save(self, force_insert=False, force_update=False, using=None):
    if not self.nickname:
        self.nickname = self.get_nickname() if len(self.name)>8 else self.name
    self.slug = slugify(self.nickname)
    slug_test = SomeModel.objects.filter(slug=self.slug, id=self.id) # corrected to use a generic model name
    if slug_test:
        count = slug_test.count
        self.slug = "{}{}".format(self.slug[:len(self.slug)-1], count)

    super(SomeModel, self).save()

rawDescription: Best practice: prepopulate SlugField in Django (without Admin module)


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


code:
import Image
import ImageDraw
img = Image.open(...).convert('RGBA')

x = ['10', '30', '70']
y = ['15', '45', '90']

# convert values to ints
x = map(int, x)
y = map(int, y)

img2 = img.copy()
draw = ImageDraw.Draw(img2)
draw.polygon(zip(x,y), fill = "wheat")

img3 = Image.blend(img, img2, 0.5)
img3.save('/tmp/out.png')

rawDescription: Overlay polygon on top of image in Python


code:
# Most pythonic
person.cars.exists()

# or
person.cars.count() == 0

rawDescription: Check if user has chosen a value from many to many field


code:
def main():
      session = requests.Session()

      # Get the source page that contain the auth_key
      r = requests.get("http://fans.heat.nba.com/community/index.php?app=core&module=global&section=login")
      # Parse it
      auth_key = re.findall("auth_key' value='(.*?)'",r.text)[0]

      # This is the form data that the page sends when logging in
      login_data = {
           'ips_username': 'username',
           'ips_password': 'password',
           'auth_key' : auth_key

      }

rawDescription: Logging into a forum using Python Requests


code:
from Tkinter import *
root = Tk()
canvas = Canvas(root, width =1224,height=1000)
logo=PhotoImage(file="myimage.jpg")
canvas.create_image(0, 0, image=logo) #Change 0, 0 to whichever coordinates you need
root.mainloop()

rawDescription: Simple example of displaying an image fullscreen in Python


rawDescription: Scrapy Post Request with payload

description: Scrapy Post Request with payload


code:
def foo():
   if x:
       return y, None
   else:
       return y, z

rawDescription: Is it possible to detect the number of return values of a function in python?


code:
def graph(formula, x_range):
    x = np.array(x_range)
    y = [formula(xx) for xx in x]
    y = np.array(y)
    plt.plot(x, y)
    plt.show()

rawDescription: How to get current value of ndarray in function?

description: Get current value of ndarray in function


code: regExpression = "FPS([^./]+)\\."

rawDescription: Python Regex, word in between two words matches correctly, but not with dot


code:
from itertools import count, groupby

def make_login_key():
    counter = count()
    current_key = None
    def key(line):
        nonlocal current_key
        if line.startswith('login'):
            # we found the start of a new step, so change key
            current_key = next(counter)
        return current_key
    return key

def find_steps(fobj):
    for _, group in groupby(fobj, key=make_login_key()):
        step = []
        for line in group:
            step.extend(line.split()[1:])
        yield step

def format_steps(steps, fobj):
    for i, step in enumerate(steps):
        for part in step:
            fobj.write('step{}.{}={}\n'.format(i, *part.split('=')))

rawDescription: Split multiple nested key,values and extract to text file


code:
key = lambda sl: (sl.count('YES') + sl.count('MAYBE'), -sl.count('NO'))
mylist.sort(lambda p, q: -cmp(key(p), key(q)))

rawDescription: Sorting a list of lists by item frequency in Python 2.3


code:
[q.user.userdata.access_token for q in Question.objects.all()]
[q.user.userdata.access_token for q in Question.objects.all().select_related()]
[q.user.userdata.access_token for q in Question.objects.all().select_related('user__userdata')]

rawDescription: Django - Indirect Join Query

description: Django - Indirect Join Query


rawDescription: Element to Element addition of two lists in python


code:
def get_all_values(list_o_dicts):
    return [value for a_dict in list_o_dicts for value in a_dict.values()]

rawDescription: generate list using a particular key from a list of objects

description: Generate list using a particular key from a list of objects


rawDescription: Python: How to convert a string containing hex bytes to a hex string


code:
from itertools import combinations

l = [2, 3, 5]

result = []
for i in range(1, len(l) + 1):
    result += list(combinations(l, i))

multiplied_result = [reduce(lambda x, y: x*y, lst) for lst in result]

rawDescription: Find product of any subset of elements from a list


code:
category = BadgeCategory(name='foo')
category.save()
badge = Badge(category=category, name='bar', description='test badge')
badge.save()

rawDescription: django post_save call from within sending Model?

description: Django post_save call from within sending Model


code:
def leaves(root):
    for node in dfs(root):
        if node.branches is None:
            yield node

rawDescription: Mapping a list of inputs to the lowest level of nested lists


code:
def myfunc(root):
    label=Label(root,text="cow")
    label.pack()
    return label

#This is the callback we want...
#  Q: but how do we pass S?
#  A: we need to wrap this call in another -- a perfect use for lambda functions!
def change_label(label,S):
    label.config(text=S)

root=Tk()
lbl=myfunc(root)
lbl.bind("<Enter>",lambda e: change_label("Horse"))
lbl.bind("<Leave>",lambda e: change_label("Cow"))

rawDescription: Python 2.7 : Tkinter, How to use the bind method?


code:
fields_2_get = [u'salePrice',u'name',u'modelNumber']
data = response.json()
for item in data[u'items']:
   for field_name in fields_2_get:
      print(field + ": " + str(item.get(field_name, None)))

rawDescription: Python Json Parseing for output

description: Python Json Parseing for output


code: globals()[ "Laptop" ]

rawDescription: Referring to class names through strings?


rawDescription: Subsetting DataFrame using ix in Python

description: Subsetting DataFrame using ix in Python


rawDescription: Changing a list with a twist: whats going on behind the scenes


code:
lis = s.rstrip().split(', ')
lis

rawDescription: Output file formatting and rearrangement


code:
from Foundation import *
a = NSArray.arrayWithObjects_("a", "b", "c", None)
a
a[1]
a.objectAtIndex_(1)
type(a)

rawDescription: Calling Python from Objective-C

description: Calling Python from Objective-C


code:
for _, category in itertools.groupby(dictList, key=lambda item:item['type']):
    processingMethod(list(category))

rawDescription: How to categorize list of dictionaries based on the value of a key in python efficiently?

description: Categorize list of dictionaries based on the value of a key in python efficiently


code: print (mydate.strftime('%m'))

rawDescription: datetime objects format

description: Datetime objects format


code: [name for name in iterable if condition]

rawDescription: Is there a `let` or `as` keyword for Python generators?


code:
import matplotlib.pyplot as plt
circle1=plt.Circle((0,0),.2,color='r')
circle2=plt.Circle((.5,.5),.2,color='b')
circle3=plt.Circle((1,1),.2,color='g',clip_on=False)
fig = plt.gcf()
fig.gca().add_artist(circle1)
fig.gca().add_artist(circle2)
fig.gca().add_artist(circle3)
fig.savefig('plotcircles.png')

rawDescription: plot a circle with pyplot

description: Plot a circle with pyplot


code: [first for first,second in a]

rawDescription: Creating a Python list from a list of tuples


code: back.pack(fill="none", expand=True)

rawDescription: Place objects in the middle of a frame in tkinter python


code: np.triu_indices(n, 1)

rawDescription: Nested python loop revisited

description: Nested python loop revisited


code:
from itertools import islice
with open('afile') as f:
    lines = list(islice(f, 4003, 4005))
do_something_with(lines)

rawDescription: Python fastest access to line in file

description: Python fastest access to line in file


code:
import pickle

class ABC(object):
    pass

# Load:
d1 = pickle.load(open('filename.pkl', 'rb'))

print(d1)

rawDescription: unpickling python 2.6 object in python 3.1.1

description: Unpickling python 2.6 object in python 3.1.1


code: table.where('9')   # this should work equally well for '9C'

rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


rawDescription: Print tree without recursion

description: Print tree without recursion


code:
for row in rows:
       row = dict(zip(columns, row))
       # REMOVED
       result.append(row)

json_response=json.dumps(result)
response=Response(json_response,content_type='application/json; charset=utf-8')
response.headers.add('content-length',len(json_response))
response.status_code=200
return response

rawDescription: getting json response using requests object flask

description: Getting json response using requests object flask


code:
import numpy as np

def gaussian_probability(x,mean,standard_dev):
    termA = 1.0 / (standard_dev*np.sqrt(2.0*np.pi))
    termB = np.exp(-((x - mean)**2.0)/(2.0*(standard_dev**2.0)))
    return termA * termB

class EM(object):
    def __init__(self, N=5):
        self.image_matrix = np.random.rand(20, 20)
        self.num_components = N
        self.mixing_coefficients = 1 + np.random.rand(N)
        self.means = 10 * np.random.rand(N)
        self.variances = np.ones(N)

    def sum_of_gaussians(self, x):
        return sum([self.mixing_coefficients[i] *
                    gaussian_probability(x, self.means[i], self.variances[i]**0.5)
                    for i in range(self.num_components)])

    def expectation(self):
        dim = self.image_matrix.shape
        rows, cols = dim[0], dim[1]
        responsibilities = []
        for i in range(self.num_components):
            gamma_k = np.zeros([rows, cols])
            for j in range(rows):
                for k in range(cols):
                    p = (self.mixing_coefficients[i] *
                         gaussian_probability(self.image_matrix[j,k],
                                              self.means[i],
                                              self.variances[i]**0.5))
                    gamma_k[j,k] = p / self.sum_of_gaussians(self.image_matrix[j,k])
            responsibilities.append(gamma_k)
        return responsibilities

    def expectation_fast(self):
        responsibilities = (self.mixing_coefficients[:, None, None] *
                            gaussian_probability(self.image_matrix,
                                                 self.means[:, None, None],
                                                 self.variances[:, None, None] ** 0.5))
        return responsibilities / responsibilities.sum(0)

rawDescription: Speeding up guassian EM algorithm

description: Speeding up guassian EM algorithm


code:
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    if user.is_anonymous():
        return False
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

rawDescription: Restricting User access to different apps in Django


code:
find_slice(a, b)
find_slice(a, b2)
find_slice(a, np.array([[5,6], [5,8]]))

rawDescription: Searching a sub-array inside a 2D array (image recognition)


code:
subreddit_name = (c.subreddit.display_name
                  if hasattr(c.subreddit, 'display_name')
                  else c.subreddit)

rawDescription: Seeking a better way to check an instance property and assign value depending on property type


code:
cat,14
dog,2

rawDescription: Paste list to an Excel file

description: Paste list to an Excel file


code:
#!/usr/bin/jython
import java.util.HashMap

channelList = java.util.HashMap()
channelList.put("Hello", "World")
it = channelList.entrySet().iterator()
while (it.hasNext()):
    e = it.next()
    print("key = " + e.getKey())
    print("value = " + e.getValue())

rawDescription: How to split next entryset iterator?

description: Split next entryset iterator


code:
def call_a():
    a()

def a():
    pass

call_a()

rawDescription: Python: Name resolution; order of function def's


code: parser.add_argument('-i', '--input_list', nargs="+", action='append', dest='input_list', default=[], help='Input list of cell names')

rawDescription: Error with argparse

description: Error with argparse


code:
import pandas as pd

a = datetime.datetime(2015, 10, 1)
b = datetime.datetime(2015, 10, 29)

diff_calendar_days = pd.date_range(a, b).size
diff_business_days = pd.bdate_range(a, b).size

rawDescription: Find day difference between two datetimes (excluding weekend days) in Python?


code:
import re
p = re.compile(r';[^;.]*;')
test_str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget eros\nlibero. Duis ac diam pretium velit volutpat facilisis in vel nibh. In lacinia ; neque \nmassa, in consectetur lectus ; faucibus vel. Maecenas ; dapibus leo nec ; elit sagittis \nconvallis. Sed at lacus consectetur, eleifend urna tristique, consequat orci. Nullam \nac orci quis elit pellentesque consectetur quis ac libero. Duis lorem sem, sodales ; ut \nmassa sed, porta facilisis ex. Aliquam cursus accumsan ante sed maximus. "
subst = ""

result = re.sub(p, subst, test_str)

rawDescription: Regex delete string semi colon delimeter


rawDescription: Some nudges for a first-time scraper

description: Some nudges for a first-time scraper


code: randomNames = random.sample(nameLines, random.randint(1, 2))

rawDescription: Python - Print random number of lines from file


code:
labelbottom='off'
labeltop='off'
labelleft='off'
labelright='off'

rawDescription: Turning off ticks in matplotlib for all plots (using rc)


code:
def findWord(word,l):
    words = []
    lists = []
    for entry in l:
        if isinstance(entry,list):
            lists.append(entry)
        else:
            words.append(entry)

    for w in words:
        if w == word:
            return True

    for ls in lists:
        if findWord(word,ls) == True:
            return True

    return False

if findWord(userInput,VOCABULARY) == True:
    print("YES")
else:
    print("I don't know that word")

rawDescription: How do you search in triple nested lists?

description: Search in triple nested lists


code: [ l.event_set.order_by( start_date ).all()[0] for l in Location.objects.select_related().all() ]

rawDescription: Problem writing a database query

description: Problem writing a database query


code:
if type(Fnum) is float:
                Fnum = str(Fnum)
                Fnum = Fnum.replace('.0','')

rawDescription: Trouble comparing 2 excel sheets in Python using nested for loop


code: df = df[[col for col in df.columns if col != 'a.1']]

rawDescription: how to delete a duplicate column read from excel in pandas

description: Delete a duplicate column read from excel in pandas


rawDescription: Getting totals from list of lists and apply it to a dictionary


code:
def format_link(text_widget,tag,command):
    text_widget.tag_config(tag,foreground="blue",underline=1)
    text_widget.tag_bind(tag,"<Button-1>",command)#remember that the command will need to take an event argument

rawDescription: Converting a string automatically into a link to a pdf document


code:
np.random.seed(1)
df = pd.DataFrame(np.random.randint(10,size=(20,3)))
df.columns = ['Product Id','group','price']
df
df['percentil'] = df.groupby(['group'])['price'].transform(lambda x: x.quantile(.6))

rawDescription: Calculating percentile for specific groups


rawDescription: Python FTP Upload Multiple Files at Once


code:
value = 'www.123.com'
containsdigit = any(c.isdigit() for c in value)
if containsdigit:
    print("1")
else:
    print("0")

rawDescription: Python Detect numbers in string by a list of sample


code: data = {dict_key: value}

rawDescription: python dictionary keys

description: Python dictionary keys


code:
import csv
from operator import itemgetter
from tempfile import NamedTemporaryFile
from shutil import move

def keep_columns(csv_f, keep_cols, **kwargs):
    with open(csv_f) as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
        csv.writer(tmp, **kwargs).writerows(itemgetter(*keep_cols)(row)
                                            for row in csv.reader(f, **kwargs))
    move(tmp.name, csv_f)

keep_columns("edsa_data.csv", (3, 4, 7, 9))

rawDescription: fast, accurate, reliable way to remove undesirable values from a csv file

description: Fast, accurate, reliable way to remove undesirable values from a csv file


code:
from ctypes import *

class File(Structure):
 _fields_ = [("fileSize", c_uint),
            ("fileName", c_byte * 32)]

f = File()
f.fileSize = 2
print(f.fileSize)
p = pointer(f)
print(p.contents.fileSize)

rawDescription: Python: ctypes and Pointer to Structure

description: Python: ctypes and Pointer to Structure


code:
import pandas as pd
import numpy as np
import string
from itertools import permutations

rawDescription: What is the best way to store and use information between two objects in python?


rawDescription: Speeding up timestamp operations

description: Speeding up timestamp operations


code:
import tables
import numpy as np

def store(filename, name, data):
    with tables.openFile(filename, 'w') as store:
        store.createGroup('/', name)
        for i, item in enumerate(data):
            store.createArray('/%s' % name, 'item_%s' % i, item)

def read(filename, name):
    with tables.openFile(filename, 'r') as store:
        nodes = store.listNodes('/%s' % name)
        data = [0] * len(nodes)
        for node in nodes:
            pos = int(node.name.split('_')[-1])
            data[pos] = node.read()
        return data

rawDescription: Storing large unstructured list in Python


code:
unique_l, counts_l = np.unique(kmeans.labels_, return_counts=True)
sort_ix = np.argsort(counts_l)
sort_ix = sort_ix[::-1]

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

for cluster_center in kmeans.cluster_centers_[sort_ix]:
    ax.add_patch(patches.Rectangle( (x_from, 0.05), 0.29, 0.9, alpha=None,
                                    facecolor='#%02x%02x%02x' % (cluster_center[2], cluster_center[1], cluster_center[0] ) ) )
    x_from = x_from + 0.31

plt.show()

rawDescription: Color detection of object in Image

description: Color detection of object in Image


code:
w = df[['minor','major']].abs().idxmax(axis=1)
w

rawDescription: Pandas: optimizing some python code by getting rid of DataFrame.apply()


code:
import time
start_time = time.time()
finish_time = time.time() - start_time

rawDescription: Python: Add Processing Time to Output CSV File


code: result = [parent for parent, ds, fs in os.walk(dirname) if 'foo.txt' in fs]

rawDescription: collect all directories matching criteria from directory tree in python

description: Collect all directories matching criteria from directory tree in python


code:
class C:
    def __init__(self):
        self.a = None
        self.A = None
        self.aA = None
        self.Aa = None
        self.AAA = None
        self.aAa = None

rawDescription: Python dict.keys to list results in duplicates


code: any("Financial Assets:" in line2 for line2 in searchlines[m-5:m+5])

rawDescription: How can I search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python?

description: Search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python


code: super().save(*args, **kwargs)

rawDescription: How to pass django model field value as an argument to callable which is default of field in the same model?

description: Pass django model field value as an argument to callable which is default of field in the same model


code:
area = {i: [] for i in range(1, 37)}        # Python 2.7+
area = dict((i, []) for i in range(1, 37))  # Python 2.6 or earlier

rawDescription: List of named lists

description: List of named lists


code:
def timeit_decorator(the_func):

    @functools.wraps(the_func)
    def my_timeit(*args, **kwargs):
        output_container = []
        def wrapper():
            output_container.append(the_func(*args, **kwargs))
        timer = Timer(wrapper)
        delta = timer.timeit(1)
        my_timeit.last_execution_time = delta
        return output_container.pop()

    return my_timeit

rawDescription: timeit eats return value

description: Timeit eats return value


code: set(item) - set(z)

rawDescription: Finding elements not in a list

description: Finding elements not in a list


code:
iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM),
                             35099, struct.pack('256s', iface))[20:24])

rawDescription: Get network address and network mask in Python


code:
df.index = pd.to_datetime(df.pop('date'))
df

rawDescription: computing an EWMA of a DataFrame by time

description: Computing an EWMA of a DataFrame by time


code:
with open('data.json') as datafile:
    raw_data = datafile.read()
    data = json.loads(raw_data)

rawDescription: diagnosing when I'm being limited by disk i/o

description: Diagnosing when I'm being limited by disk i/o


code:
print("Downloading...",end="")
#your code here
print("Done!")

rawDescription: How can I replace a printed line with a new printed line?

description: Replace a printed line with a new printed line


rawDescription: how do I parse a specific string in python

description: Parse a specific string in python


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2)

plt.subplot2grid((1,5), (0,0), colspan=3)
plt.plot([1,2,3]) # plot something

plt.subplot2grid((1,5), (0,3), colspan=2)
plt.plot([1,2,1]) # plot something

plt.show()

rawDescription: Creating a subplot instead of separate plots


rawDescription: "scripting" vim using python with greater granularity


code:
jumble += word[position] # adding value of the index `position` to jumble
word[:position] # items from the beginning through position-1
word[(position + 1):]   # items position+1 through the rest of the array

rawDescription: I do not understand this piece of tutorial code?


code:
class prepend_two_arguments:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __call__(self, f):
        def wrapped_function(*args, **kwargs):
            return f(self.a, self.b, *args, **kwargs)
        return wrapped_function

@prepend_two_arguments(1,2)
def f(a, b, c):
    return a+b+c
print(f(3)) # 6

rawDescription: Python decorators theory

description: Python decorators theory


code:
def compute():
    value = var.get()
    result = square(value)
    list_of_results.append(result)

button = Tk.Button(root, text='click', command = compute)
...

rawDescription: Python - returning from a Tkinter callback


code: peoples_names = [input('Enter your name:') for _ in range(3)]

rawDescription: Using a while loop in python until the list is full


code:
A = np.array([ [ 'a', 'b', 'c'], [ 'd', 'e', 'f'] ])
ones = np.ones(A.shape)
np.vstack(np.where(ones) + (A.ravel(),)).transpose()

rawDescription: Convert n-dimensional numpy array to 2-dimensional index array


code:
all_allowable = df3['Bid'].isin(['E', 'A', 'N'])
counts = df3[all_allowable]['Bid'].value_counts(normalize=True)

rawDescription: Pandas calcuating percentage in data summary


code:
abc=3
def foo():
  from some_module import abc #import inside foo avoids you from naming conflicts
  abc(...) #call the function, nothing to do with the variable "abc" outside "foo"

rawDescription: import module_name Vs __import__('module_name')

description: Import module_name Vs __import__('module_name')


code:
def mock_func(*args):
    if args == (1, 2):
        return 'foo'
    else:
        return 'bar'
my_mock.side_effect = mock_func
my_mock(1, 2)
my_mock()

rawDescription: How to setup return_value for a function call with specific signature?

description: Setup return_value for a function call with specific signature


code:
from hashlib import sha256
import json
import struct
import binascii

def getId(publicKey):
 publicKeyHash = sha256(publicKey)
 p = publicKeyHash.digest()
 b = bytearray(p[:8])
 b.reverse()
 bigInt = 0
 for byte in b:
  bigInt <<= 8
  bigInt |= byte
  #print bigInt
 return(bigInt)

rawDescription: Rewriting Java BigInteger function in python


code:
stripped = (x.strip() for x in data)
stations = [x for x in stripped if x]

rawDescription: Pythonic list comprehension possible with this loop?


code:
a
b
b[:,None] == a

rawDescription: How to generate a bool 2D arrays from two 1D arrays using numpy

description: Generate a bool 2D arrays from two 1D arrays using numpy


code:
def biggest_even_number(xs):
    return max(i for i in xs if i % 2 == 0)

rawDescription: Largest even number in a list using fold


rawDescription: how to make undo in backtracking? I'm having problems with the recursively backtracking method

description: Make undo in backtracking? I'm having problems with the recursively backtracking method


code:
indices = []
next = -1
while True:
    try:
        next = besedilo.index(next + 1)
        indices.append(next)
    except ValueError:
        break

rawDescription: Find indexes for a certain character in string


code: data = np.genfromtxt(rf)

rawDescription: Loading .txt data into 10x256 3d numpy array


code:
import datetime
days = 10
# a bit of a hack to get the current date without any time stuff.
endDate = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time())
queryset = [datetime.datetime(2015,12,15), datetime.datetime(2015,12,11), datetime.datetime(2015,12,10), datetime.datetime(2015,12,9), datetime.datetime(2015,12,8)]
date_ranges = set([endDate - datetime.timedelta(x) for x in xrange(days)])
output = sorted(list(date_ranges - set(queryset)))
print([x.strftime('%Y-%m-%d') for x in output])

rawDescription: Return a list of missing values?

description: Return a list of missing values


code:
@app.route("/posts/<int:post_id>/background")
def generate_image(post_id):
    # Assume that if we got here the image does not yet exist
    dimensions = int(request.args.get("s", 800), 10)

    image_data = generate_image(post_id, dimensions)

    image_name = "{}_{}.png".format(post_id, dimensions)
    image_path = os.path.join("/cache", image_name)

    with open(image_path, "wb") as image:
        image.write(image_data)

    return Response(image_data, content_type="image/png")

rawDescription: Device Detection Using CSS Media Queries and Flask/Jinja


rawDescription: Iterate over all disjoint pairs of pairs


code:
Python
from ctypes import *

class data_t(Structure):
    _fields_ = [
        ("foo", c_int),
        ("bar", c_wchar_p),
        ("baz", c_char_p)]

dll = CDLL('test')

@CFUNCTYPE(None,c_int)
def callback(n):
    p = cast(n,POINTER(data_t)).contents
    print(p.foo,p.bar,p.baz)

@CFUNCTYPE(None,POINTER(data_t))
def callback2(n):
    p = n.contents
    print(p.foo,p.bar,p.baz)

dll.set_callback(callback)
dll.call_callback()

dll.set_callback(callback2)
dll.call_callback()

rawDescription: Hard typecasts in ctypes possible? int -> "pointer to struct" for example


code:
import requests
from bs4 import BeautifulSoup
import csv
import sys

postdata = {
    'grouping_type': "wells",
    'FromYear': '2012',
    'ToYear': '2014',
    'maxrec': '5000'
}

r = requests.post('http://cogcc.state.co.us/cogis/ProductionSearch2.asp',
                  data=postdata, timeout=3600.0)

if r.status_code != 200:
    print("Got status code {}, cannot proceed".format(r.status_code))
    sys.exit(1)

soup = BeautifulSoup(r.text)
trlist = soup.findAll('table')[1].findAll("tr")
header = trlist[1]
data = trlist[2:]

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow([row.get_text() for row in header.find_all("th")])

    for entry in data:
        csvwriter.writerow([' '.join(item.get_text().split())
                            for item in entry.findAll("td")])

rawDescription: python post web form and contents retrieval

description: Python post web form and contents retrieval


code:
from collections import Counter

def dice(trials, numbers):
    results = Counter()
    for throw in range(trials):
        results[randint(1, numbers)] += 1
    return results

rawDescription: Performing sum of dice and generating the percentage with histogram


code:
for i in xrange(0, 10, 1):
    pass

rawDescription: Why are there no control structures for python FOR loop?


rawDescription: Python does not recognize the type of a namedtuple


code:
from collections import OrderedDict
d = OrderedDict
for x in data:
    d.setdefault(x['author'], []).append(x)

rawDescription: How to initialize an a priori unknown number of list

description: Initialize an a priori unknown number of list


code:
from jinja2 import Template

d = {'e34': ['120'], 'e24': ['50']}

s = """{% set result = 'default' %}
{% for item, value in test_dict.items() %}
   {% if 'e2' in item %}
      {% set result = item %}
      {{ result }}
   {% endif %}
{% endfor %}"""

template = Template(s)
print(template.render(test_dict=d))

rawDescription: Iterate over jinja array

description: Iterate over jinja array


rawDescription: How to draw a list of sprites in Pygame

description: Draw a list of sprites in Pygame


code:
def foo(i, l):
    l.append(10)
foo(i, l)
print(l)

rawDescription: Why are there immutable objects in Python?


code:
import json
import urllib
from datetime import datetime

data = urllib.urlopen('https://dl.dropboxusercontent.com/u/2684973/data_A.txt').read()
data = json.loads(data)

tweets = data['statuses']

def parse_created(timestamp):
    _, m, d, t, _, y = timestamp.split(' ')
    return datetime.strptime('%s %s %s %s' % (m, d, t, y), '%b %d %H:%M:%S %Y')

tweets_data = [(x['user']['name'], x['text'], parse_created(x['created_at']))
               for x in tweets]

rawDescription: How to save and handle tweets saved as JSON in Python

description: Save and handle tweets saved as JSON in Python


code:
def product_of_permutations(n, k):
    return product(permutations(range(k)), repeat=n)

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

description: Generate all possible combinations from all permutations


code:
class DoStuffWithObject(object):
    def __init__(self,obj):
        self.obj = obj
        self.changeObj()
        self.writeObj()

    def changeObj(self):
        self.obj['values'] = 100.134;
        self.obj['length'] = 12;
        self.obj['anotherVariable'] = 15;
        self.obj['someString'] = "spam";

    def writeObj(self):
        ''' write back to file '''
        with open('anObject.json', 'w') as f:
            json.dump(self.obj, f)

    def someOtherMethod(self, s):
       ''' do something else '''
       print('hello {}'.format(s))

import json
with open('anObject.json','r') as f:
    obj = json.loads(f.read())
# print out obj['values'] obj['someBool'] ...
for key in obj:
    print(key, obj[key])

aThing = DoStuffWithObject(obj)
aThing.someOtherMethod('there')

rawDescription: Passing java object to python

description: Passing java object to python


rawDescription: Benefits of panda's multiindex?

description: Benefits of panda's multiindex


code:
from itertools import groupby
from operator import itemgetter
lis = [[10, 0], [30, 0], [40, 2], [20, 2], [90, 0], [80, 0]]
[list(g) for k,g in groupby(lis, key=itemgetter(1))]

rawDescription: In python, how to group elements together, based on a key (group adjacent)?


rawDescription: Python QuickSort returning original input


code: shlex.split("this 'is a string' with 5 parts") # ['this', 'is a string', 'with', '5', 'parts]

rawDescription: process.call and cmd.exe

description: Process.call and cmd.exe


code:
myTuple = namedtuple("Test", ['a', 'b', 'c', 'd'])
records = [myTuple(3, 2, 1, 4), myTuple(5, 6, 7, 8)]
[[record.a, record.b] for record in records if record.c == 1]

rawDescription: indexing and finding values in list of namedtuples

description: Indexing and finding values in list of namedtuples


rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


rawDescription: Find numbers in string, modify and re-join


rawDescription: Reducing the complexity of dictionary brute force in python


code:
#-*- coding: UTF-8 -*-
from gi.repository import Gtk

class App(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title='ComboBox Test')

        model = Gtk.ListStore(int, str)
        for i in [[1, 'One'], [2, 'Two'], [3, 'Three'], [4, 'Four']]:
            model.append(i)

        combo = Gtk.ComboBox.new_with_model(model)
        renderer = Gtk.CellRendererText()

        combo.set_active(0)
        combo.pack_start(renderer, True)
        combo.add_attribute(renderer, 'text', 1)
        combo.connect('changed', self._changed_cb)

        self.add(combo)

        # Variables
        self.combo = combo
        self.model = model

    def _changed_cb(self, widget, param=None):
        comboiter = self.combo.get_active_iter()
        if comboiter:
            print("Changed to {}".format(
                     self.model.get_value(comboiter, 0)
            ))
        else:
            print("Nothing selected!")

win = App()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Show drop-down list without entry by using PyGObject ComboBox


rawDescription: How to sort a dictionary by descending order numerically

description: Sort a dictionary by descending order numerically


code:
slow = TestSuite()
slow.addTests( TestSlowAnother )
slow.addTests( TestSlowSomeMore )

rawDescription: Python unittest: how to run only part of a test file?


code:
import os
os.environ['IP']

rawDescription: How to use a bash variable in python

description: Use a bash variable in python


code: myvar = request.args.get("myvar")

rawDescription: How to obtain values of request variables using Python and Flask

description: Obtain values of request variables using Python and Flask


code:
class ListView(list):
  def __init__(self, raw_list, raw2new, new2raw):
    self._data = raw_list
    self.converters = {'raw2new': raw2new,
        'new2raw': new2raw}

  def __repr__(self):
    repr_list = [self.converters['raw2new'](item) for item in self._data]
    repr_str = "["
    for element in repr_list:
      repr_str += element.__repr__() + ",\n "
    repr_str = repr_str[:-3] + "]"
    return repr_str

  def append(self, item):
    self._data.append(self.converters['new2raw'](item))

  def pop(self, index):
    self._data.pop(index)

  def __getitem__(self, index):
    return self.converters['raw2new'](self._data[index])

  def __setitem__(self, key, value):
    self._data.__setitem__(key, self.converters['new2raw'](value))

  def __delitem__(self, key):
    return self._data.__delitem__(key)

  def __getslice__(self, i, j):
    return ListView(self._data.__getslice__(i,j), **self.converters)

  def __contains__(self, item):
    return self._data.__contains__(self.converters['new2raw'](item))

  def __add__(self, other_list_view):
    assert self.converters == other_list_view.converters
    return ListView(
        self._data + other_list_view._data,
        **self.converters
        )

  def __len__(self):
    return len(self._data)

  def __eq__(self, other):
    return self._data == other._data

  def __iter__(self):
    return iter([self.converters['raw2new'](item) for item in self._data])

rawDescription: How can I change in Python the return/input type of a list that is implemented as an class attribute?

description: Change in Python the return/input type of a list that is implemented as an class attribute


code:
import concurrent.futures

with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
    ans = executor.map(your_func, [your_arguments] * n_trials)

rawDescription: Multiprocessing Python Sampling Distribution Simulation (no interdependence between function calls)


rawDescription: Split tests into even time slaves

description: Split tests into even time slaves


code:
import itertools
#Should return False, returns False
board1 = [
    [1, 0, 1],
    [1, 0, 1],
    [0, 0, 1]
]

#Should return True, returns False
board2 = [
    [1, 0, 1],
    [1, 0, 1],
    [0, 1, 0]
]

#Should return True, returns True
board3 = [
    [1, 0, 1],
    [1, 1, 1],
    [0, 1, 0]
]

#Should return True, returns False
board4 = [
    [1, 0, 0, 1],
    [0, 1, 1, 0],
    [0, 0, 1, 0],
    [0, 1, 0, 0],
]

class Matrix(object):
    def __init__(self, m):
        self.m = m

    @property
    def numrows(self): return len(self.m)

    @property
    def numcols(self): return len(self.m[0])

    def get(self, r, c):
        return self.m[r][c]

    def set(self, r, c, v):
        self.m[r][c] = v

    def is_valid(self, r, c):
        return (0 <= r < self.numrows) and (0 <= c < self.numcols)

    def neighbors(self, r, c):
        #offsets =
        #    (0,1), (0,-1), (1,0), (-1,0),
        #    (-1,-1), (-1,1), (1,-1), (1,1),
        #]
        offsets = itertools.product([-1,0,1],[-1,0,1])
        neighbors = []
        for (dr,dc) in offsets:
            if (dr,dc) == (0,0): continue
            rr = r + dr
            cc = c + dc
            if self.is_valid(rr, cc): neighbors.append((rr,cc))
        return neighbors

    def find_nonzero(self):
        for (r,c) in self.iter():
            if self.get(r,c) == 1: return (r,c)
        return None

    def iter(self):
        return itertools.product(xrange(self.numrows), xrange(self.numcols))

    def show(self):
        for row in self.m: print(row)

def grow(m, r, c):
    m.set(r, c, 0)
    for (rr,cc) in m.neighbors(r, c):
        if m.get(rr,cc): grow(m, rr, cc)

def check(board):
    m = Matrix(board)

    # Find any non-zero element
    (r,c) = m.find_nonzero()
    print("Found non-zero element at ({},{})".format(r,c))

    # Call grow, a recursive function that "unsets" the neighbors of (r,c) and recurses
    grow(m, r, c)

    m.show()

    # Check if any are still set
    return (m.find_nonzero() is None)

rawDescription: Determine if all the elements of a matrix are connected in Python


code:
a = Population()
a.kill_random(3)
a.miners
a.workers
a.farmers
a.loggers

rawDescription: accessing a variable reference with a list

description: Accessing a variable reference with a list


code:
class Counter:
    counter = 0

    def increment(self):
        self.counter += 1
    def set_to_zero(self):
        self.counter = 0

rawDescription: 2D forloop counter django template

description: 2D forloop counter django template


code:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

rawDescription: Python looping: idiomatically comparing successive items in a list


rawDescription: pythonic format for indices

description: Pythonic format for indices


code: out = log(sum(exp(threshold if a - a_max < threshold else a - a_max), axis = 0))

rawDescription: Conditional calculation in python

description: Conditional calculation in python


code:
my_arr['number']
array([ 2.2  ,  3.777,  0.   ])
my_arr['user']
array(['User1', 'User2', 'User3'],
      dtype='|S10')

rawDescription: Make single column of numpy array another datatype


code:
FIN = 0x01
SYN = 0x02
RST = 0x04
PSH = 0x08
ACK = 0x10
URG = 0x20
ECE = 0x40
CWR = 0x80

rawDescription: Get TCP Flags with Scapy

description: Get TCP Flags with Scapy


code: combination[p:] = range(combination[p]+1, combination[p] + 2*(r-p), 2)

rawDescription: Generating non-consecutive combinations

description: Generating non-consecutive combinations


code:
import binascii
'0x' + binascii.hexlify('\xFF\xFF\xFF')
'0x' + binascii.hexlify('\x00\x00\xFF')

rawDescription: Convert a string of escaped hex to a hex number in Python


code: options = CharField(_("Options"), max_length=200)

rawDescription: How to break the item name and size in Django Cartridge cart page?

description: Break the item name and size in Django Cartridge cart page


code:
import numpy as np
np.arange(0,1,0.1)

rawDescription: Python decimal range() step value

description: Python decimal range() step value


code:
line = rb'mj\195\164ger'
regex = re.compile(rb"\\(\d{1,3})")
def replace(match):
    return int(match.group(1)).to_bytes(1, byteorder="big")
new = regex.sub(replace, line)
new
print(new.decode("utf-8"))

rawDescription: Process decimal escape in string

description: Process decimal escape in string


code:
text = '''
OR 125
BA  48
Pr 12
ba 4
Cherry 147
Ba   10
Or 7
OR 6
Orange 2
AP 9
PR          3
Banana 101
or 22
pR 13
'''

rawDescription: Capturing the replaced text using re.sub in python


code:
from django.db.models import F

next_raid = models.RaidSession.objects \
    .filter(scheduled__gte=now() - F('duration')) \
    .order_by('scheduled') \
    .first()

rawDescription: Next upcoming date model object ignoring past dates


rawDescription: Combining lists and performing a check

description: Combining lists and performing a check


code:
reobj = re.compile("(auto|allow-|iface)\s*((?:(?!(?:auto|allow-|iface)).)*)(?<!\s)", re.DOTALL)
result = [tuple(match.groups()) for match in reobj.finditer(subject)]
result

rawDescription: Divide string containing some keywords into list using Python


code: cv2.imshow('image %d' % (i,), roi[i])

rawDescription: Changing title of image to display many images simultaneously using open cv and python


code:
engine = sa.create_engine('postgresql:///somedb')
pandas_sql = pd.io.sql.pandasSQL_builder(engine, schema=None, flavor=None)

rawDescription: Python Pandas to_sql, how to create a table with a primary key?


code:
B = tuple(A.tolist()[0])
B

rawDescription: Convert a matrix to a list

description: Convert a matrix to a list


code:
def fill_cell(cell, corner, rad):
    m, n = cell.shape
    ctr = corner[0]+m/2, corner[1]+n/2
    x = np.arange(m) - ctr[0]
    y = np.arange(n) - ctr[1]
    X,Y = np.meshgrid(x, y, order='ij')  # could try order='xy'
    Z = ((X**2 + Y**2)<= rad**2).astype(cell.dtype)
    return Z
empty_lattice[:] = fill_cell(empty_lattice, (x,y),side/2)

rawDescription: Python: how to create a submatrix discretizing a circle?


code:
# `fmt` can be a string with multiple insertion points or a
# list of formats.  E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')

rawDescription: What are the possible numpy value format strings?


code:
with open('/tmp/scores.txt', 'r') as f, open('/tmp/mod_scores.txt', 'w') as fout:
    for line in f:
        if line.startswith('jill'):
            li=line.split()
            line=' '.join([li[0]]+li[-3:])
        fout.write(line.strip()+"\n")

rawDescription: Replacing a line within a text file

description: Replacing a line within a text file


code:
## in ex17.py

if __name__ == '__main__':
    print_two("Gaurav","Pareek")
    print_two_again("Gaurav","Pareek")
    print_one("First!")
    print_none()

rawDescription: how import statement executes in python?

description: How import statement executes in python


code:
def bounding_box(coords):

  min_x = 100000 # start with something much higher than expected min
  min_y = 100000
  max_x = -100000 # start with something much lower than expected max
  max_y = -100000

  for item in coords:
    if item[0] < min_x:
      min_x = item[0]

    if item[0] > max_x:
      max_x = item[0]

    if item[1] < min_y:
      min_y = item[1]

    if item[1] > max_y:
      max_y = item[1]

  return [(min_x,min_y),(max_x,min_y),(max_x,max_y),(min_x,max_y)]

rawDescription: Python: Defining a minimum bounding rectangle


code: final_result = dict(((A, B, C), [x, y, z]) for A, B, C, x, y, z in result)

rawDescription: AMPL vs. Python - Importing tables (multi-dimensional dictionaries?)


code: sorted(list_of_objects, key=lambda obj: obj._variable_name)

rawDescription: sort list of objects by return of object method

description: Sort list of objects by return of object method


code:
query = '//span[@class="summary-view-icon"][i/@class="icon-day"]/text()[normalize-space()]'
dates = root.xpath(query)
result = [date.strip() for date in dates]

rawDescription: Extracting date and other data from scraped items


rawDescription: Python: Dictionary within dictionary?

description: Python: Dictionary within dictionary


code: ['hi', 'hello', 'hey']

rawDescription: Making a new list from an existing list

description: Making a new list from an existing list


code: data['hello'] = [(1 if 'hello' in item else 0) for item in data['state']]

rawDescription: Binomial classification using a list comprehension python


code:
import lxml.etree as ET
import io

class Settings(object):
    def __init__(self,text):
        root=ET.parse(io.BytesIO(text)).getroot()
        self.settings=dict((elt.tag,elt.text) for elt in root.xpath('/Settings/*'))
    def update(self,other):
        self.settings.update(other.settings)

text='''\
<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathA>/Some/path/to/directory</PathA>
    <PathB>/Another/path</PathB>
</Settings>'''

text2='''\
<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathB>/Change/this/path</PathB>
</Settings>'''

s=Settings(text)
s2=Settings(text2)
s.update(s2)
print(s.settings)

rawDescription: Combine XML files similar to ConfigParser's multiple file support


code:
import pandas as pd

df = pd.read_table('data', sep='\s+')
count = df.groupby(['index'])['col1'].transform('count') > 1
mask = (df['col1'] == '-') | (df['col2'] == '-')
mask = mask & count
result = df.loc[~mask]
print(result)

rawDescription: drop rows that have duplicated indices

description: Drop rows that have duplicated indices


code: a = {k: v / total for total in (sum(a.values()),) for k, v in a.items()}

rawDescription: Divide each python dictionary value by total value


code:
import argparse
parser = argparse.ArgumentParser(description='Demo')
subparsers = parser.add_subparsers(dest='action', help='do this')
parser_act_one = subparsers.add_parser('actone')
parser_act_one.add_argument('function', type=str)
parser_act_two = subparsers.add_parser('acttwo')
parser_act_two.add_argument('function', type=str)
parser.print_help()
parser_act_one.print_help()
parser.parse_args(['actone', 'some_filename.txt'])

rawDescription: Python Argsparser add a single argument to subparser without a name


rawDescription: Why is StringVar().set(LocalScript) receiving a function id instead of a return value


rawDescription: Group a list of points/tuples

description: Group a list of points/tuples


code:
[[i for i, t in enumerate(zip(*pair), 1) if t[0]!=t[1]] for pair in
    [(tuple1, tuple2), (tuple1, tuple3), (tuple2, tuple3)]]

rawDescription: Element by element comparison in tuple to return set of sets - python


code:
import time

for x in range(10):
    time.sleep(1)
    print("a", end="", flush=True)

rawDescription: Sleeping and printing without newline?

description: Sleeping and printing without newline


code:
import pandas as pd
import sqlalchemy as SA
import config

df = pd.DataFrame({'SEC1':['IBM','CSCO','MSFT','AMZN' ], 'SEC2':['GOOG', 'INTC', 'ABX', 'CREE'], 'HOUR':[10 ,10 ,15, 12], 'Size':[100 ,200 ,50 ,500],'Price':[300 ,25 ,150, 80] })
df = df[['SEC1', 'SEC2', 'HOUR', 'Size', 'Price']]

engine = SA.create_engine('mysql+oursql://{u}:{p}@{h}/{d}'.format(
    u=config.USER, p=config.PASS, h=config.HOST, d='test'))
tablename = 'Table-A'
df.to_sql(tablename, engine, if_exists='replace')

sql = '''select * from  Table-A a
         left join Table-B b
         on (a.sec1 = b.sec1)
         where DATE_SUB(CURDATE(),INTERVAL 12 MONTH) <= dt
         group by 1,2,3,4,5,6,7'''

result = pd.read_sql(sql, engine)

rawDescription: pass pandas dataframe as parameter in mysql query

description: Pass pandas dataframe as parameter in mysql query


rawDescription: Returning specific content

description: Returning specific content


code: assert threading.current_thread() == threading.main_thread()

rawDescription: Check if current thread is main thread, in Python


code:
def beat_main(self, argv=None):
    return instantiate(
        'celery.bin.beat:beat',
        app=self).execute_from_commandline(argv)

rawDescription: Run celery worker and celery beat as thread


code: self.processFile(root, open(os.path.abspath(f)), age, inString)

rawDescription: Mental block with os.walk - want to process a file not the filename string


code: console.log("Hello World");

rawDescription: Save Javascript variable value and read it in python


rawDescription: Getting the first item item in a many-to-many relation in Django


code:
investments = Investment.objects.all().filter(plan = p).order_by('financial_institution')
cur_inv = investments.filter(maturity_date__year = current_year)
nxt_inv = investments.filter(maturity_date__year = next_yr)
thr_inv = investments.filter(maturity_date__year = thr_yr)
fr_inv = investments.filter(maturity_date__year = fr_yr)
fv_inv = investments.filter(maturity_date__year = fv_yr)

rawDescription: Using annotate on list

description: Using annotate on list


rawDescription: (Django) Trim whitespaces from charField


code:
def create_footer(sheet, suma_cell, starting_row, flag):
    """
    Function to creade footer of listok
    flag = 0 / 1 / 2 (data sheet where to write header)
    """
    sheet.write(row, 4, 'Test')

rawDescription: Using "object" of mainfile, in function saved in other file


code:
def foo():
    ...

foo = decorator(foo)

rawDescription: Understanding the difference between these two decorators


code:
if os.environ['WORKING_ENVIRONMENT'] == 'HEROKU':
    pass
else:
    pass

rawDescription: How to run different code in django based on heroku deployment

description: Run different code in django based on heroku deployment


rawDescription: Draw an image into another one in imagemagick?


code:
["{}{}{}".format(a,b,c) for a in range(3) for b in range(3)
                                              for c in range(3) if a!=b and b!=c]

rawDescription: Equality in Python's list-comprehension

description: Equality in Python's list-comprehension


code:
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        output=[]
        with open(file, 'r') as inF:
            for line in inF:
                output.append(line)
                if 'criteria' in line: break
        f=open(file, 'a')
        Lorem_list=['Lorem Ipsum','Lorem Ipsum','Lorem Ipsum']
        #The '\n' may look strange, but I am using your previous syntax.
        #This also will result in a blank line. I would suggest revising the
        #way you place text to follow the (x+'\n') format.
        [f.write(x) for x in output]
        [f.write('\n      '+x) for x in Lorem_list]
        f.close()

rawDescription: Remove multiple lines from a text file after a specific string, then replace with new text


code:
import re
sorted(records,key=lambda x:int(re.split(r'[-/]',x)[1].strip()))

rawDescription: Complicated sorting in Python

description: Complicated sorting in Python


code:
def wait_for_either(e1, e2):
    OrEvent(e1, e2).wait()

rawDescription: Python threading: can I sleep on two threading.Event()s simultaneously?


code:
class DependentIntegerField(models.IntegerField):

    def pre_save(self, model_instance, add):
        if not add: # set the default only while adding model
            return super(self, DependentIntegerField).pre_save(model_instance, add)

        return model_instance.number*50

rawDescription: Simple multiplication in model's attribute django?


code:
Final_List = [[server] + environments + [account]
              for (server, account), environments in sorted(grouped.items())]

rawDescription: Grouping of list of list for elments of inner list in python


code:
def main():
    url = 'http://www.reddit.com/images/logo.png'
    if download_image(url):
        print('script successful!')
    else:
        print('download failed...')

rawDescription: Different statements depending on exit status of code


code:
def plot_tree( P, pos=None ):
    icoord = scipy.array( P['icoord'] )
    dcoord = scipy.array( P['dcoord'] )
    color_list = scipy.array( P['color_list'] )
    xmin, xmax = icoord.min(), icoord.max()
    ymin, ymax = dcoord.min(), dcoord.max()
    if pos:
        icoord = icoord[pos]
        dcoord = dcoord[pos]
        color_list = color_list[pos]
    for xs, ys, color in zip(icoord, dcoord, color_list):
        plt.plot(xs, ys,  color)
    plt.xlim( xmin-10, xmax + 0.1*abs(xmax) )
    plt.ylim( ymin, ymax + 0.1*abs(ymax) )
    plt.show()

rawDescription: how do I get the subtrees of dendrogram made by scipy.cluster.hierarchy

description: Get the subtrees of dendrogram made by scipy.cluster.hierarchy


code:
locs = range(0, N, 5)
ax.set(xticks=locs, xlabels=...)

rawDescription: Python How to set axes for a matplotlib plot


code:
PK: {'name': None, 'constrained_columns': [u'login']}
UNIQUE: [{'column_names': [u'email'], 'name': None}, {'column_names': [u'login'], 'name': None}]

rawDescription: SQLAlchemy Determine If Unique Constraint Exists


code:
entering
exiting
foo
entering
exiting
('foo', 'bar')

rawDescription: Wrapping a function imported with import *?


code:
def scrape_table(url, linewriter):
    # do scraping to get data
    linewriter.writerow(data)

rawDescription: Scraping tables and writing rows to CSV

description: Scraping tables and writing rows to CSV


code: fOWOO(num1, fOWOO(num2, num3, op2), op1)  # num1 `op1` (num2 `op2` num3)

rawDescription: Python: Dealing with a second operator in calculator


code:
import logging

def get_logger(
        LOG_FORMAT     = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        LOG_NAME       = '',
        LOG_FILE_INFO  = 'file.log',
        LOG_FILE_ERROR = 'file.err'):

    log           = logging.getLogger(LOG_NAME)
    log_formatter = logging.Formatter(LOG_FORMAT)

    # comment this to suppress console output
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(log_formatter)
    log.addHandler(stream_handler)

    file_handler_info = logging.FileHandler(LOG_FILE_INFO, mode='w')
    file_handler_info.setFormatter(log_formatter)
    file_handler_info.setLevel(logging.INFO)
    log.addHandler(file_handler_info)

    file_handler_error = logging.FileHandler(LOG_FILE_ERROR, mode='w')
    file_handler_error.setFormatter(log_formatter)
    file_handler_error.setLevel(logging.ERROR)
    log.addHandler(file_handler_error)

    log.setLevel(logging.INFO)

    return log

def main():

    my_logger = get_logger()

    my_logger.info('This is an INFO message')
    my_logger.warning('This is a WARNING message')
    my_logger.error('This is an ERROR message')

if __name__ == '__main__':
    main()

rawDescription: Using python logging module to info messages to one file and err to another file


code:
from django.db.models import Count

question_list = Question.objects.distinct() \
                        .filter(category=category, is_approved=1,
                                answer__is_approved=1) \
                        .annotate(answer_cnt=Count('answer')) \
                        .filter(answer_cnt=2) \
                        .prefetch_related('answer_set')[:10]

rawDescription: How do we filter results from two tables using prefetch_related function in Django


code: element = browser.find_element_by_xpath("//div[@style='visibility: visible; display: block;']/iframe[1]")

rawDescription: Best way to locate this element in selenium?

description: Locate this element in selenium


code:
import re

with open('input.txt','r') as fp:
    for x in xrange(7):
        next(fp)

    rx = "\w+"
    for line in fp:
        data = re.findall(u"\w+", line, re.DOTALL)
        if data:
            print(', '.join(data[0:-1]))

rawDescription: Python Reading a file and printing

description: Python Reading a file and printing


code:
n = mlab.normpdf(a, np.mean(a), np.std(a))
ind = np.argsort(a)
a = a[ind]
n = n[ind]
plt.plot(a,n)
plt.show()

rawDescription: Smoothening a normal/gaussian plot in matplotlib


code:
from operator import itemgetter

map(itemgetter(1), inputlist)

rawDescription: Python values out of list

description: Python values out of list


rawDescription: Add multiple rows into google spreadsheet using API


code:
def triplet(s):
    extra_zeros = (3 - len(s)) % 3
    s += '0' * extra_zeros
    return (s[::3], s[1::3], s[2::3])

rawDescription: Txt Parsing in Python

description: Txt Parsing in Python


rawDescription: No handler found for library with logging configured


rawDescription: Summing over lists in python - is there a better way?


code:
def paintGL(self):
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(0.0, 0.0, 1.0)
    glRectf(-5, -5, 5, 5)
    glColor3f(1.0, 0.0, 0.0)
    glBegin(GL_LINES)
    glVertex3f(0, 0, 0)
    glVertex3f(20, 20, 0)
    glEnd()

rawDescription: Unable to clear OpenGL viewport

description: Unable to clear OpenGL viewport


code:
import matplotlib as mpl
mpl.rcParams['legend.handlelength'] = 0

rawDescription: Python plot legend : markers appear twice


code:
teststr
unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')

rawDescription: Character reading from file in Python

description: Character reading from file in Python


code:
user1 = Info_model.get_or_insert('Bill',
                                 username='Bill',
                                 phone=1231231234,
                                 active=False)

user2_key = ndb.Key('Info_model', 'Bill')
user2 = user2_key.get()

assert user1.key == user2.key

rawDescription: Retrieving Datastore Object With Key

description: Retrieving Datastore Object With Key


code:
def getExpandoValues(self):
   return dict((name, getattr(self, name)) for name, impl_class in self.dynamic_properties())

rawDescription: Iterating through Expando's Dynamic properties in Django Templates


rawDescription: Modify default registration form in Django-registration-redux


rawDescription: Building a numpy array (matrix) from several dataframes


rawDescription: Why won't my for loop work? (Python)

description: Why won't my for loop work? (Python)


code:
str = 'name: phil age : 23 range: 33, 45 address: "main ave US" abcd : xyz'
re.findall(r'\w+\s*:\s*(?:"[^"]*"|.*?(?=\w+\s*:\s*|$))', str)

rawDescription: Split on space but not if there is a colon followed by space or if there is a space in quotes


code: A = PI * MA * ma

rawDescription: How to find the area of an ellipse obtained using cv.fitEllipse(contour)?

description: Find the area of an ellipse obtained using cv.fitEllipse(contour)


code:
header[0].header['opp'] = "34:04:32.04"
print (sum(float(x) for x in header[0].header['opp'].split(":")))

rawDescription: python pyfits, reading header information and using in caculation

description: Python pyfits, reading header information and using in caculation


rawDescription: Finding an average but ignoring any zero in a list [Python]


code: print("\rLoading...", end="")

rawDescription: Loading animation in python

description: Loading animation in python


code: df1.to_excel(writer, sheet_name='PnL', na_rep=0, index=False, header=False)

rawDescription: Handle Nan when using Pandas ExcelWriter in python


code:
if somecondition:
    import pdb; pdb.set_trace()

rawDescription: how to load a module within python debugger

description: Load a module within python debugger


rawDescription: BoxSizer issue: Not expanding to fit contents of StaticText


code:
abc = [1, 2, 3] # Read more about lists
rownum = 0

rawDescription: convert string to existing variable

description: Convert string to existing variable


code:
crdscl.pop(0)
crdscl.append(tomove)

rawDescription: list[i] in "for" statement does not return the right values

description: List[i] in "for" statement does not return the right values


code:
import json

string = json.loads(data.decode('utf8'))

rawDescription: Python: Cyrllic handling

description: Python: Cyrllic handling


code:
class SongInline(admin.TabularInline):
    #list_display = ('title','artist','song_1','song_2','song_3','song_4','song_5','song_6')
    #prepopulated_fields = { 'slug': ['title'] }
    model = Song

class AlbumAdmin(admin.ModelAdmin):
    inlines = [
            SongInline,
            ]
class ArtistAdmin(admin.ModelAdmin):
    pass

rawDescription: Related to model( each song need each artist)


code:
plist_slots = [
    'main_hand', 'off_hand', 'head', 'neck', 'shoulder',
    'back', 'chest', 'wrist', 'hands', 'waist', 'legs',
    'feet', 'ring1', 'ring2', 'trinket1', 'trinket2'
]

Slot.objects.bulk_create([
    Slot(name=slot) for slot in plist_slots
])

plist = ProtectionList.objects.all().select_related(
    *list(['player'] + plist_slots)
)

for p in plist:
    PlayerSlot.objects.bulk_create([
        PlayerSlot(
            player=p.player,
            item=getattr(p, slot),
            slot=Slot.objects.get(name=slot)
        ) for slot in plist_slots
    ])

rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
def remove_cruft(s):
    return s[4:-4]

sites=['www.hattrick.com', 'www.google.com', 'www.wampum.net', 'www.newcom.com']
[remove_cruft(s) for s in sites]

rawDescription: removing first four and last four characters of strings in list, OR removing specific character patterns

description: Removing first four and last four characters of strings in list, OR removing specific character patterns


code:
from django.db.models import get_model
from django.contrib.auth.models import User
from hashlib import sha1

class MyUserAuthBackend(object):

    def check_legacy_password(self, db_password, supplied_password):
        return constant_time_compare(sha1(supplied_password).hexdigest(), db_password)

    def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = User.objects.get(email=username)

            if '$' not in user.password:
                if self.check_legacy_password(user.password, password):
                    user.set_password(password)
                    user.save()
                    return user
                else:
                    return None

            else:
                if user.check_password(password):
                    return user

        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        """ Get a User object from the user_id. """
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

rawDescription: Migrating a password field to Django

description: Migrating a password field to Django


code:
class UITest(LiveServerTestCase):

    fixtures = ['initial_test_data.json']
    selenium = None

    @classmethod
    def setUpClass(self):
        cls.drivers = WebDriverList(
            webdriver.Chrome(),
            webdriver.Firefox(),
            webdriver.PhantomJS
        )
        super(UITest, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        for driver in cls.drivers:
            driver.quit()
        super(UITest, cls).tearDownClass()

    @run_through_drivers()
    def test_example(self):
        ...

rawDescription: How to run selenium tests using LiveServerTestCase in different browsers?

description: Run selenium tests using LiveServerTestCase in different browsers


code: soup.find(lambda elm: elm.name == "h2" and "Content Logical Definition" in elm.text)

rawDescription: using bs4 to find a html tag (h2) having text

description: Using bs4 to find a html tag (h2) having text


rawDescription: Comparing a numpy array object to multiple conditions


code:
date1 = datetime.datetime.strptime('01/03/2010', '%d/%m/%Y').date()
date2 = datetime.datetime.strptime('04/03/2010', '%d/%m/%Y').date()

rawDescription: Compute number of dates between two string dates and return an integer


code:
import threading
import time
import random

class Worker(threading.Thread):
    def __init__(self, srcfile, printlock,**kwargs):
        super(Worker,self).__init__(**kwargs)
        self.srcfile = srcfile
        self.lock = printlock # so threads don't step on each other's prints

    def run(self):
        with self.lock:
            print("starting %s on %s" % (self.ident,self.srcfile))
        # do whatever you need to, return when done
        # example, sleep for a random interval up to 10 seconds
        time.sleep(random.random()*10)
        with self.lock:
            print("%s done" % self.ident)

def threadme(srcfiles):
    printlock = threading.Lock()
    threadpool = []
    for file in srcfiles:
        threadpool.append(Worker(file,printlock))

    for thr in threadpool:
        thr.start()

    # this loop will block until all threads are done
    # (however it won't necessarily first join those that are done first)
    for thr in threadpool:
        thr.join()

    print("all threads are done")

if __name__ == "__main__":
    threadme(["abc","def","ghi"])

rawDescription: Python - Using threads or a queue to iterate over a for loop that calls a function


code:
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit

X = np.random.randn(100, 4)     # independent variables
m = np.random.randn(4)          # known coefficients
y = X.dot(m)                    # dependent variable

df = pd.DataFrame(np.hstack((X, y[:, None])),
                  columns=['A', 'B', 'C', 'D', 'Z_real'])

def func(X, *params):
    return np.hstack(params).dot(X)

popt, pcov = curve_fit(func, df[['A', 'B', 'C', 'D']].T, df['Z_real'],
                       p0=np.random.randn(4))

print(np.allclose(popt, m))
# True

rawDescription: Pass Pandas DataFrame to Scipy.optimize.curve_fit


code:
def func(x): return bool(x)
lis = [ 1, [], 3, 4 ]
min(lis, key=func) # bool([]) evaluated to False, ie 0
max(lis, key=func)

rawDescription: max() function: how to get the item being iterated and pass to key=func()

description: Max() function: how to get the item being iterated and pass to key=func()


code:
def foo(bar=None, baz=None, qux=None, haz=None):
    return {k:v for k,v in locals().items() if v}

rawDescription: Basic Python metaprogramming: populating dictionaries?


code: for d in ( depth[i][j] for i in range(rows) for j in range(columns) ): ...

rawDescription: Iterating within bounds of a 2D list (matrix) in python


code:
import itertools
def arrangements(arr):
    p = itertools.permutations(arr)
    return set(item for item in p if all(x!=y for x,y in zip(item,arr)))

rawDescription: Find the number of ways a sequence can be rearranged


code:
from itertools import combinations, product, chain

x = [['222', '219'], ['221'], ['220', '218', '216']]
combos = list(chain.from_iterable( [list(product(a,b)) for (a,b) in combinations(x,2)]))

rawDescription: Python: 2-item combinations from list of lists containing 1 or more items


code:
from subprocess import Popen, PIPE

p = Popen(['external-program', 'arg1', 'arg2'],
                stdin=PIPE, stdout=PIPE, stderr=PIPE)

rawDescription: Running external program using pipes and passing arguments in python


code: raise ImportError()

rawDescription: Is it possible to simulate the unavailability of modules in Python tests?


DC_Volt: FUNC:VOLT DC

DC_Curr: FUNC:CURR DC

AC_Volt: FUNC:VOLT AC

rawDescription: How do I dump text file contents into dictionary

description: Dump text file contents into dictionary


code:
def forms_valid(self, forms, form_name):
    session = self.request.session
    session['invite_key'] = self.get_invite().key
    return super(ResourceInviteAcceptanceView, self).forms_valid(forms, form_name)

rawDescription: How to implement an invite flow using django allauth for signup/signin?

description: Implement an invite flow using django allauth for signup/signin


code:
s='what a nice day'

print ("".join(set(s.replace(" ",""))))
acedihntwy

rawDescription: How to list the used chars in a text in Python?

description: List the used chars in a text in Python


code:
class Organism(object):
    def reproduce(self):
        #use self here to customize the new organism ...
        return Organism()

rawDescription: Create new class instance from class method


code:
for wine in wines:
    glass=wine #Lets pour your wine in a glass
    for stop in stop_words:
        if stop in glass: #Is stop in your glass?
            #Replace stop in glass and pour it in the glass again
            glass = glass.replace(stop, "")
    result.append(glass) #Finally pour the content from your glass to result

result
[' Chardonnay', 'Cabernet Sauvignon ', 'Bordeaux  ']

rawDescription: Using Python's replace() method to implement stopword functionality


code:
x = np.eye(3)
x
np.nonzero(x)

rawDescription: Convert an image to a 2D array of coordinates in Python for two point correlation


code: D

rawDescription: How to cross check a python list of dictionaries against a csr matrix

description: Cross check a python list of dictionaries against a csr matrix


code:
class AnimalForm(ModelForm):
    class Meta:
        model = Animal
        exclude = ('publisher',)

rawDescription: Using request.user with Django ModelForm


code: pandas.factorize(data.id, sort=True)[0]

rawDescription: Unique zero-based id for values in pandas


rawDescription: passing a dictionary by reference instead of using eval / how to pass a variable number of arguments

description: Passing a dictionary by reference instead of using eval / how to pass a variable number of arguments


rawDescription: Why are slices in Python 3 still copies and not views?


rawDescription: Python | Access the sole element of a set


code: counts = Counter(fname[:2] for fname in os.listdir(path) if os.path.isfile(os.path.join(path, fname)))

rawDescription: Count Files based on the first two letters


code:
ds = ts.resample('5min', how=func)
ds

rawDescription: Downsize series containing boolean data with resample


rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code: list(enumerate(s))

rawDescription: pandas row specific apply

description: Pandas row specific apply


code:
import socket
import struct

username = "username_value"
verification_key = "verification_key"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # boilerplate
s.connect(("example.com", 1234))  # adjust accordingly

# now for the packet
# note that the String type is specified as having a length of 64, we'll pad that

packet = ""

packet += struct.pack("B", 1)  # packet type
packet += struct.pack("B", 7)  # protocol version
packet += "%-64s" % username  # magic!
packet += "%-64s" % verification_key
packet += struct.pack("B", 0)  # that unused byte, assuming a NULL byte here

# send what we've crafted
s.send(packet)

rawDescription: How to Send Packets to a Remote Minecraft Classic Server in Python?


code:
# Longer function, but satisfies the requirements of using True/False and return
def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False

rawDescription: Adding True/False Boolean expression into program. (Python)


code:
import numpy as np
from scipy.optimize import fsolve

def lw(x):
    """Lambert W function, for real x >= 0."""

    def func(w, x):
        return np.log(x) - np.log(w) - w

    if x == 0:
        return 0
    if x > 2.5:
        lnx = np.log(x)
        w0 = lnx - np.log(lnx)
    elif x > 0.25:
        w0 = 0.8 * np.log(x + 1)
    else:
        w0 = x * (1.0 - x)

    return fsolve(func, w0, args=(x,))[0]

rawDescription: NaN value when using Lambert Function in Python - in Enthought Canopy


code:
def HandleAuthAndReturnResult(self, methodName, arg):
    mc = xmlrpclib.MultiCall(self.wiki)
    if self.token:
        mc.applyAuthToken(self.token)

    try:
        methodToCall = getattr(mc, methodName)
    except AttributeError:
        return None

    methodToCall(arg)
    return mc()[-1]

def fooMethod(self, x):
    HandleAuthAndReturnResult('fooMethod', x)

rawDescription: pythonic way to wrap xmlrpclib calls in similar multicalls

description: Pythonic way to wrap xmlrpclib calls in similar multicalls


code:
ps = soup.findAll('p', {'class': 'i'})
ps

rawDescription: Parsing web page in python using Beautiful Soup


code:
numlist, alist, blist = [], [], []
nappend = numlist.append, aappend = alist.append, bappend = blist.append
for item in mixlist:
    if item == "a":
        aappend(item)
    elif item == "b":
        bappend(item)
    else:
        nappend(item)

rawDescription: Split a list in sublists by a logic criterion


code:
with open("words.txt", 'w') as f:    # Open file for writing
    f.write('\n'.join(new_wordlist))

rawDescription: how to assign a word from a text file to a variable in python

description: Assign a word from a text file to a variable in python


code:
test = 'Today it is Tuesday'
removeText = 'pqrst'
test.translate(dict.fromkeys(ord(elem) for elem in removeText+removeText.upper()))

rawDescription: Removing certain letters from a string

description: Removing certain letters from a string


code: avg = [int(i) for i in avg]

rawDescription: Quick way to remove largest values in big list in Python?


rawDescription: Input html form data from python script

description: Input html form data from python script


code:
pvt = pd.pivot_table(df, index=df.index, columns='cmte_id',
                     values='amount', aggfunc='sum', fill_value=0)

rawDescription: Pandas: transposing one column in a multiple column df


code:
['Sir Lancelot of Camelot', 'To seek the Holy Grail', 'blue']
['Sir Galahad of Camelot', 'I seek the Grail', 'blue... no yellow!']

rawDescription: Python CSV reading ascii delimited text?

description: Python CSV reading ascii delimited text


rawDescription: How do I get Python2.x `map` functionality in Python3.x?

description: Get Python2.x `map` functionality in Python3.x


code:
import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)

rawDescription: Convert strange date format to standard date format


code:
from subprocess import *
p = Popen(['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE)
output, errors = p.communicate()
p.wait() # wait for process to terminate

rawDescription: Running a batch file with parameters in python OR F#


code: df2.agg({'Surveys' : 'sum', 'Question1' : 'mean'})

rawDescription: Groupby or pivot in pandas?

description: Groupby or pivot in pandas


rawDescription: Return the file path of the file, not the current directory


code:
url_template = 'http://somewhere.com/relatedqueries?limit={limit}&query={seedterm}'
url = url_template.format(limit=2, seedterm='seedterm')

rawDescription: Extracting data from a URL result with special formating


rawDescription: How do you use pandas.DataFrame columns as index, columns, and values?

description: Use pandas.DataFrame columns as index, columns, and values


code:
total = 0
for org in orgs:
    orders = orgs[org]
    subtotal = sum(order['qty']*order['price'] for order in orders)
    total += subtotal
    orgs[org] = {'orders': orders, 'subtotal': subtotal}

rawDescription: Totals/Subtotals in Django template

description: Totals/Subtotals in Django template


code: setattr(self, 'combo%d' % index, combo)

rawDescription: dynamically generating unique combo box and filling them with two different sources

description: Dynamically generating unique combo box and filling them with two different sources


rawDescription: effectively preprocessing record array from genfromtxt

description: Effectively preprocessing record array from genfromtxt


code:
from pyb import USB_VCP
usb_vcp = USB_VCP()

rawDescription: Micropython updating board V 1.0

description: Micropython updating board V 1.0


rawDescription: Summing values of numpy array based on indices in other array


code:
from flask import Flask
from flask.ext.bcrypt import Bcrypt

app = Flask(__name__)
bcrypt = Bcrypt(app)

# Your code here...

users_doc = {
    "username": "james",
    "password": bcrypt.generate_password_hash(password)
}

rawDescription: save password as salted hash in mongodb in users collection using python - bcrypt

description: Save password as salted hash in mongodb in users collection using python - bcrypt


code:
d
(d.A + d.B) / d.C
d.A > d.C

rawDescription: Adding calculated column(s) to a dataframe in pandas


code:
class BindableHTTPHandler(urllib2.HTTPHandler):
    def http_open(self, req):
        return self.do_open(BindableHTTPConnectionFactory('10.91.56.4'), req)

rawDescription: How to send HTTP request using virtual IP address in Linux?

description: Send HTTP request using virtual IP address in Linux


code:
with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {}
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

rawDescription: Writing header with DictWriter from Python's csv module


rawDescription: What char can be used to seperate binary data in a python 2.7 string?


code:
class OrderNewForm(forms.ModelForm):

   client = forms.ModelChoiceField(
       required=False,
       queryset=Client.objects.all(),
       widget=RelatedFieldWidgetCanAdd(Client, related_url="so_client_add")
                                )
   class Meta:
       model = Order
       fields = ('code', 'client')

rawDescription: Django: adding an "Add new" button for a ForeignKey in a ModelForm


code:
import random

def gen():
    for _ in range(10):
        i=random.randint(0,100)
        if i%2:
            yield True, str(i)
        else:
            yield False, str(i)

def test():
    for j, i in gen():
        if j:
            process1()
        else:
            process2()

rawDescription: better treatment for 2 kind of generator results in python

description: Better treatment for 2 kind of generator results in python


code: contents = ftp.retrlines('LIST')  # List CWD contents securely.

rawDescription: Get all filenames inside a directory on FTP [Python]


code:
return_path(1)
return_path(12)
return_path(123)
return_path(1234)
return_path(12345)
return_path(123456)
return_path(1234567)
return_path(12345678)

rawDescription: splitting and merging the string in python

description: Splitting and merging the string in python


code:
def sub_combinations(segment):
  if len(segment) == 1:
    yield (segment,)
  else:
    for j in sub_combinations(segment[1:]):
      yield (segment[0],)+j
      for k in range(len(j)):
        yield (segment[0]+j[k],)+j[:k]+j[k+1:]

rawDescription: Yielding sub combinations

description: Yielding sub combinations


code: [[x+'/'+y for y in 'ab'] for x in '012']

rawDescription: What's wrong with this nested list comprehension?


code:
mx = np.arange(60).reshape((10, 6))
mx

rawDescription: accessing columns within an array within a for loop

description: Accessing columns within an array within a for loop


code: {{ form.priority }}

rawDescription: Django - Convert value get from HTML select in POST request back to number before validate ModelForm


code:
from urllib import quote
from django.shortcuts import render

class UserPhoneNumberView(FormView):
    form_class = UserPhoneNumberForm
    template_name = "get_user_phonenumber.html"

    def form_valid(self, form):
        phonenumber = self.request.POST.get("mobile_number")
        unique = self.request.POST.get("unique")
        url = "http://example.com/"+unique
        body = quote("See this url: "+url)
        nonhttp_url = "sms:"+phonenumber+"?body="+body
        context = {'url': nonhttp_url}
        return render(request, 'theTemplate.html', context)

rawDescription: Calling a special (non-HTTP) URL from the form_valid method of a Django class-based view


code:
@reverse_sentence
def printer(s):
    print(s)

printer("hello world")

rawDescription: Can we design any function using a decorator?


code:
with ListStream() as x:
    for i in range(2):
        print ('i = ', i)

print(x.data)

rawDescription: Redirect print to string list?

description: Redirect print to string list


code:
class Add(int):
    def __call__(self, val):
        return type(self)(self + val)

rawDescription: Python:Can lambda works with *args as it's parameter?


code:
bigList = []
for group in g:
    rowList = []
    rowList.append(group[0])
    for c in group[1].C.iteritems():
        rowList.append(c[1])
    bigList.append( rowList )

rawDescription: writing pandas dataframe columns to csv rows staggered

description: Writing pandas dataframe columns to csv rows staggered


rawDescription: Can I create an RPG-esque save & quit, and then reload progress?

description: Create an RPG-esque save & quit, and then reload progress


code:
import random
class Randomizer():
    def __init__(self):
        # Generates a list of random values
        self.x = []
        self.rng = 10
        for i in range(1,self.rng+1):
            self.x.append(random.random())

        # Need to call once to make sure all vars defined
        self.func_A()

    # pick a random value from a list
    def func_A(self):
        self.recent = self.x[random.randint(0,self.rng-1)]
        return self.recent

    # Do something with random value picked by A
    def func_B(self):
        return self.recent*self.recent

rawDescription: Randomizer function/global variables trouble in python?


code: pd.concat([df2, df2], axis=1, keys=['tier1', 'tier2'])

rawDescription: How can I generalize my pandas data grouping to more than 3 dimensions?

description: Generalize my pandas data grouping to more than 3 dimensions


code:
class MyListThingy(object):
    def __init__(self, data):
        self.data = data
    def __eq__(self, other):
        return self.data[0]==other.data[0] and self.data[1]==other.data[1]

rawDescription: Removing duplicates from list based on custom definition of duplicate