code: no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}

rawDescription: Python Get Access to locals() Back In 2.7 to Prevent Duplicates


code:
def get_overlap(keys):
    # create map: prefix -> set(keys with that prefix)
    prefixes = defaultdict(set)
    for key in keys:
        for prefix in [key[:i] for i in range(len(key))]:
            prefixes[prefix].add(key)
    # get keys with matching prefixes for all suffixes
    overlap = set()
    for key in keys:
        for suffix in [key[i:] for i in range(len(key))]:
            overlap.update([(key, other) for other in prefixes[suffix]
                                                      if other != key])
    return overlap

rawDescription: Getting all keys in a dict that overlap with other keys in the same dict


code:
def extend_lst(foo):
    v = 1
    foo.extend([v,v])

def extend_tup(foo):
    v = 1
    foo.extend((v,v))

rawDescription: Python - append VS extend efficiency

description: Python - append VS extend efficiency


code: [i + j for i, j in zip(list_of_urls, string.lowercase[:14])]

rawDescription: Python: how to print range a-z?

description: Python: how to print range a-z


code: property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]

rawDescription: Python: Select subset from list based on index set


code:
from numpy import *
from pyhdf.SD import SD
sd = SD('data.hdf', SDC.READ)
sd.datasets()

rawDescription: Dump HDF4 arrays to ascii with full precision of the source file


code:
def create_query(**kwargs):
    parameters = (('WhoId', 'who_id'),
                  ('Subject','subject'),
                  ('Description', 'description'))
    query_string = ','.join(r"'{}':'{{{}}}'".format(name, kwargs[id])
                            for name, id in parameters
                            if id in kwargs)
    print(query_string)

create_query(who_id=123, description="he's bossy",
             will_be_ignored="really?")

rawDescription: Auto format arguments to string

description: Auto format arguments to string


code:
import numpy as np

k= np.array(
    [[1, 2, 3, 4, 5],
     [5, 6, 7, 8, 9],
     [2, 5, 4, 7, 3],
     [4, 7, 6, 8, 2],
     [1, 2, 4, 3, 6],
     [7, 8, 9, 5, 4]])

cols=[2,4]
others = [c for c in range(k.shape[1]) if c not in cols]
groups = [k[:,[o, c]] for c in cols for o in others]
for g in groups:
    print(g)
    print('')

rawDescription: Grouping column indices of an array based on max value of another list in python


code:
import itertools as IT
result = ({k:v} for k, v in IT.izip(keys, values))

rawDescription: create a list of dictionaries with randomised elements from two lists - python

description: Create a list of dictionaries with randomised elements from two lists - python


rawDescription: Difference between lists in Python

description: Difference between lists in Python


code:
tim, c = User.objects.get_or_create(username='tim')
chris, c = User.objects.get_or_create(username='chris')
tim.userprofile.follows.add(chris.userprofile) # chris follows tim
tim.userprofile.follows.all() # list of userprofiles of users that tim follows
chris.userprofile.followed_by.all() # list of userprofiles of users that follow chris

rawDescription: Following users like twitter in Django, how would you do it?


code:
import cherrypy

@cherrypy.popargs('name')
class Band(object):
    def __init__(self):
        self.albums = Album()

    @cherrypy.expose
    def index(self, name):
        return 'About %s...' % name

@cherrypy.popargs('title')
class Album(object):
    @cherrypy.expose
    def index(self, name, title):
        return 'About %s by %s...' % (title, name)

if __name__ == '__main__':
    cherrypy.quickstart(Band())

rawDescription: Friendly URL for a REST WebService with CherryPy


rawDescription: how to crawl a javascript page whose content name is defined by a reference?

description: Crawl a javascript page whose content name is defined by a reference


code:
import inspect
[n for n, v in inspect.getmembers(x, inspect.ismethod)]

rawDescription: list of methods for python shell?

description: List of methods for python shell


code:
bad_fn() is bad
good_fn() is good

rawDescription: Python is not recognizing my variables, but instead replacing them with zero


code: {{ create_date|date:"N j, Y" }}

rawDescription: Creating a resuable template in Django

description: Creating a resuable template in Django


code:
dt = yaml.load("dt: !!python/object/apply:time.gmtime []")
dt = yaml.load("dt: !!python/object/apply:time.time []")

rawDescription: How to create a datetime object with PyYAML

description: Create a datetime object with PyYAML


code:
import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f

rawDescription: Redirecting stdout to "nothing" in python


code:
start = mouse.isPressedIn(polygon, buttons=[0])

if start==True:
    thisExp.addData('starttime',core.getTime())
    x, y = mouse.getPos()
    mouse.x.append(x)
    mouse.y.append(y)
    checkstart=True;

if checkstart==True:
    if y>10 or y <-10:
        thisExp.addData('penalty',1)

finish = mouse.isPressedIn(polygon2, buttons=[0])

if finish==True:
    thisExp.addData('stoptime',core.getTime())
    continueRoutine=False

rawDescription: psychopy event based on mouse position

description: Psychopy event based on mouse position


code:
popt_1,pcov_1 = curve_fit(fitfunc,logx,logn,p0=(10.0,1.0),maxfev=2000)

p1_1 = popt_1[0]
p1_2 = popt_1[1]

sigma1 = [np.sqrt(pcov_1[0,0]),np.sqrt(pcov_1[1,1])] #THE 1 SIGMA CONFIDENCE INTERVALS
residuals1 = (logy) - fitfunc((logx),p1_1,p1_2)
xi_sq_1 = sum(residuals1**2) #THE CHI-SQUARE OF THE FIT

curve_y_1 = fitfunc((logx),p1_1,p1_2)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(logx,logy,c='r',label='$0.0<z<0.5$')
ax1.plot(logx,curve_y_1,'y')
ax1.plot(logx,fitfunc(logx,p1_1+sigma1[0],p1_2+sigma1[1]),'m',label='68% conf limits')
ax1.plot(logx,fitfunc(logx,p1_1-sigma1[0],p1_2-sigma1[1]),'m')

rawDescription: Confidence regions of 1sigma for a 2D plot


code:
class POI(db.Model):
    __tablename__ = 'zo_poi'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text())
    tags = db.Column(HSTORE())
    src = db.Column(db.Text())
    way = db.Column(Geometry('point', srid=4326))
    intern = db.Column(db.BOOLEAN())

rawDescription: AdminModelConvertor for Geometry Field (LON/LAT)


rawDescription: Python variable value reset out of loop

description: Python variable value reset out of loop


rawDescription: Find difference between two multi dimensional lists


rawDescription: Convert python-igraph graph to networkx

description: Convert python-igraph graph to networkx


code: [x for s in reversed(list(zip(*[iter(lst)]*3))) for x in s]

rawDescription: Manipulating a list by slicing in Python3.x


code: from django.http import JsonResponse

rawDescription: Django list of json objects

description: Django list of json objects


rawDescription: Django ForeignKey _set on an inherited model


code:
b = a[np.argsort(a[:, 0])]
grps, idx = np.unique(b[:, 0], return_index=True)
counts = np.add.reduceat(b[:, 1:], idx)
np.column_stack((grps, counts))

rawDescription: Consolidate duplicate rows of an array

description: Consolidate duplicate rows of an array


rawDescription: Split based by a-z character in an alphanumeric string in python


code:
def test_root_route(self):
    with self.client.session_transaction() as session:
        session['accountId'] = 'test'
    resp = self.client.get('/')
    self.assert_template_used('index.html')

rawDescription: Flask-Testing: issues with session management with unittests


code:
templist = [
    { 'GameCode': 'A', 'PASS': '1' },
    { 'GameCode': 'A', 'RUN': '2' },
    { 'GameCode': 'B', 'PASS': '3' },
    { 'GameCode': 'B', 'RUN': '4' },
]

merged = None
output_list = []

for t in templist:
    if merged is None:
        merged = t
    elif merged['GameCode'] == t['GameCode']:
        merged.update(t)
    else:
        output_list.append(merged)
        merged = t

rawDescription: Merging values in different columns into one in python list


code:
np.asarray([(1,2)],dtype=object)
np.asarray([(1,[2])],dtype=object)
np.asarray([([1],[2])],dtype=object)
_.shape

rawDescription: scipy.sparse.hstack(([1], [2])) -> "ValueError: blocks must be 2-D". Why?

description: Scipy.sparse.hstack(([1], [2])) -> "ValueError: blocks must be 2-D". Why


code:
columns = ['total_2013', 'total_2014', 'total_2015']
df[columns].replace(0, None)

rawDescription: Calculating mean of each row, ignoring 0 values in python


code: strippedString = yourString.strip()

rawDescription: How to check if text is "empty" (spaces, tabs, newlines) in Python?

description: Check if text is "empty" (spaces, tabs, newlines) in Python


code:
from collections import defaultdict

data = {'dog':['milo','otis','laurel','hardy'],'cat':['bob','joe'],'milo':['otis','laurel','hardy','dog'],'hardy':['dog'],'bob':['joe','cat']}

# create symmetric version of data
d = defaultdict(list)
for key, values in data.items():
    for value in values:
        d[key].append(value)
        d[value].append(key)

visited = set()
def connected(key):
    visited.add(key)
    yield key
    for value in d[key]:
        if key not in visited:
            yield from connected(value)

print([list(connected(key)) for key in d if key not in visited])

rawDescription: How to check if a key/value is repeated elsewhere in a dictionary using Python

description: Check if a key/value is repeated elsewhere in a dictionary using Python


code:
@register.filter
def labeled(value, label):
    if value:
        return label + value
    else:
        return ""

rawDescription: Django Template Headings

description: Django Template Headings


code:
values = []
for x in lst:
    values.append(x.value)

rawDescription: Plotting python object attribute and objects are stored in list


code:
def mousePressEvent(self, event):
    ''' You will have to implement the contain algorithm yourself'''
    if sel.fo(even.pos()):
        self.myMethod()

rawDescription: How to detect mouse click on ellipse drawn in pyside?

description: Detect mouse click on ellipse drawn in pyside


code:
def dct2 (block):
  return dct(dct(block.T, norm = 'ortho').T, norm = 'ortho')

rawDescription: In scipy why doesn't idct(dct(a)) equal to a?


code:
#read in large chunks - fastest in my test
chunksize = 2**16
with open(fn,'r') as f:
    chunk = f.read(chunksize)
    while chunk:
        chunk = f.read(chunksize)
#1 loop, best of 3: 4.48 s per loop

#read whole file in one go - slowest in my test
with open(fn,'r') as f:
    chunk = f.read()
#1 loop, best of 3: 11.7 s per loop

#read file using iterator over each line - most practical for most cases
with open(fn,'r') as f:
    for line in f:
        s = line
#1 loop, best of 3: 6.74 s per loop

rawDescription: Does it takes RAM to save a readlines array?


code:
with open('wards.json', 'r') as f:
    json_obj = json.load(f)

# assume the structure above is used for the JSON
# don't do any validation (because that would require more work with something
# like a JSON schema, and I'm too lazy for that)

# convert the object to a list of tuples, and convert codes from strings to ints
code_list = []
for (code, data) in json_obj.items():
    code_list.append((int(code), data))

# sorting tuples does a dictionary-order sorting, so this will sort on keys,
# then on the data components of the tuples (which presumably don't have
# meaningful ordering)
return sorted(code_list)

rawDescription: Split dictionary by keys in Python

description: Split dictionary by keys in Python


code:
def find_windows(d, min_elements=3,upper_length=20,max_value=70):
    G = sorted(d.items())
    for start_index in range(len(G)):
        for width in range(min_elements, len(G)-start_index+1):
            window = G[start_index:start_index+width]
            if not all(v <= max_value for k,v in window):
                break
            if not window[-1][0] - window[0][0] < upper_length:
                break
            yield window

rawDescription: Determine High Frequency Intervals

description: Determine High Frequency Intervals


code:
##import it if not already imported
#import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.HourLocator())

rawDescription: Using datetime as ticks in Matplotlib

description: Using datetime as ticks in Matplotlib


code: [i for k, v in sorted(d.iteritems()) for i in (k, v)]

rawDescription: Generator-expression, getting the same results of using append or extend in a for-loop


code:
MAGICSTRING = '1234'
value = '\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))

rawDescription: Python String to Escaped Hex

description: Python String to Escaped Hex


code:
class Point(object):
    def init(self, x, y):
        self.x = x
        self.y = y
        return self

p = Point().init(x, y)

rawDescription: Can someone help me understand special methods vs normal methods?


rawDescription: Prevent outer double quotes in my list

description: Prevent outer double quotes in my list


code:
from contextlib import closing

def computeStuff(arguments, globalData, concurrent=True):
    with closing(multiprocessing.Pool(initializer=initWorker, initargs=(globalData,))) as pool:
        return pool.map(workerFunction, enumerate(arguments))

rawDescription: Why won't Python Multiprocessing Workers die?


code:
__add__ = add
__concat__ = concat

rawDescription: What is the difference between Python's __add__ and __concat__?


code:
class Trie(object):
    def __init__(self):
        self.children = {}

    def add_child(self, letter):
        if letter in self.children:
            return self.children[letter]
        else:
            child = Trie()
            self.children[letter] = child
            return child

    def traverse(self, letter):
        return self.children.get(letter, None)

rawDescription: find and remove common substring with python

description: Find and remove common substring with python


code:
from collections import OrderedDict

def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
    root = dct._OrderedDict__root
    first = root[1]

    if key in dct:
        link = dct._OrderedDict__map[key]
        link_prev, link_next, _ = link
        link_prev[1] = link_next
        link_next[0] = link_prev
        link[0] = root
        link[1] = first
        root[1] = first[0] = link
    else:
        root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
        dict_setitem(dct, key, value)

rawDescription: How can I add an element at the top of an OrderedDict in python?

description: Add an element at the top of an OrderedDict in python


rawDescription: How to split a string to sequences of odd numbers?

description: Split a string to sequences of odd numbers


code:
for state in states:
    score += scores_per_state[state]

rawDescription: Python Ternary Style: Is this good or bad style?


code: out_csv(my_data, 'my_name.csv')

rawDescription: how do I export my lists into an excel compatible file?

description: Export my lists into an excel compatible file


code: foo_vars = {id(instance): instance.foo for instance in A.instances}

rawDescription: Keep track of instances in python

description: Keep track of instances in python


code: ids = [value.split('-') for value in request.POST.getlist('selection')]

rawDescription: Passing a Tuple of Values through a Checkbox


rawDescription: Pythonic way to select elements of an array based on values?


code:
intp = Interpreter()
intp.compile("""
    4
    def(c|-1;x0;p;c)
    c
    p
""")

rawDescription: Interpreter written in Python not working properly


rawDescription: Python - can text file data be stored in code?


code: BAILOUT = False

rawDescription: Running unit tests in Python with a caching decorator


code:
while True:
    ...
    for event in pygame.event.get():
        if event.type == QUIT:
            save(player, blocklist)
            exit()

rawDescription: Save a list of objects on exit of pygame game


code:
def show_magicians(names):
    for name in names:
        print(name)

def make_great(magicians_names):
    return [ name + ' The Great' for name in magicians_names ]

magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']

magicians_names = make_great(magicians_names)
show_magicians(magicians_names)

rawDescription: Passing a list to a function to be modified


rawDescription: How do I slice a Multindex timeseries dataframe on Pandas?

description: Slice a Multindex timeseries dataframe on Pandas


code: {{ post|linkify }}

rawDescription: How to make a filter to check if someone has tagged a user with @?

description: Make a filter to check if someone has tagged a user with @


code:
with open('/path/to/file') as infile:
    for line in infile:
        if some_condition(line):
            continue
        do_stuff(line)

rawDescription: Python Skip one or more lines in a text file


code:
for blog in blogs:
    self.menu_blogs.add_command(label=blog[1],
                                command=partial(self.load_blog, blog[0]))

rawDescription: How to effectively turn a variable into a hardcoded value

description: Effectively turn a variable into a hardcoded value


code:
# I'm using a very simple "catch-all" regex
# you are probably using a regex to extract
# that specific "O'Connor Park" string
selector.xpath('//div/script/text()').re_first('.+')

# .re() on the element itself, one needs to handle newlines
selector.xpath('//div/script').re_first('.+')
import re
selector.xpath('//div/script').re_first(re.compile('.+', re.DOTALL))

rawDescription: How to extract raw html from a Scrapy selector?

description: Extract raw html from a Scrapy selector


code:
# the following coordinates need to be determined with experimentation
# put them at a location and move them around if they are in
# the way of the graph
x = 5
y = 10
plt.text(x,y, "Your comment")

rawDescription: editing plot - python

description: Editing plot - python


code:
mixed = lambda s: "".join((str.upper,str.lower)[i%2](ch) for i,ch in enumerate(s))
mixed("whatchathink?")

rawDescription: How would I capitalize every other letter in a str?


rawDescription: Python compare list and store in new variable


code: V4 = np.column_stack([g.ravel() for g in grid_bc] + [Z.ravel()])

rawDescription: Correspondence between a "ij" meshgrid and a long meshgrid


code:
NA = object()  # Will compare different to everything in interesting_vals
result = [dictB[5] for dictB in listB if dictB.get(5, NA) in interesting_vals]

rawDescription: Python: How to iterate lists of dictionaries Fast


code:
from collections import Counter

count = Counter(map(tuple, my_content))

rawDescription: Count occurrences of each permutation of bits in lists from CSV


code:
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

rawDescription: How to get predicted class labels in TensorFlow's MNIST example?

description: Get predicted class labels in TensorFlow's MNIST example


code:
def myFunction(x):
    print("called for: " + str(x))
    return x * x

originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
limit = 10
result =   [C2 for C2 in ((myFunction(C), C) for C in originalList) if C2[0] < limit]
# result = [C2 for C2 in [(myFunction(C), C) for C in originalList] if C2[0] < limit]

rawDescription: List Comprehensions in Python : efficient selection in a list


rawDescription: How to format a number with spanish thousand grouping in python?

description: Format a number with spanish thousand grouping in python


rawDescription: Difference between every pair of columns of two numpy arrays (how to do it more efficiently)?


code:
def can_access(func):
    return auth.can_access(app.view_functions[func])

rawDescription: Hiding inaccessible links in Jinja2 templates


code: c.setName("Utku", "Onur")

rawDescription: Best way to apply function to element or to list of elements in python

description: Apply function to element or to list of elements in python


code:
ACCC
CCGA
GATT
TTT

rawDescription: How to extract short sequence using window with specific step size?

description: Extract short sequence using window with specific step size


code:
post = driver.find_element_by_css_selector('input.postbtn')
post.click()

rawDescription: Selenium using python

description: Selenium using python


code:
item = stats.get(field) or very_expensive_initializer(field)
item.add(value)

rawDescription: How do I initialize values in a dictionary?

description: Initialize values in a dictionary


code:
x, y = 7, 3
range(x, y, x < y or -1)

rawDescription: python for loop increasing or decreasing

description: Python for loop increasing or decreasing


code:
import json
from collections import OrderedDict
result = json.loads(request.text,
                    object_parir_hook=OrderedDict)

rawDescription: requests module return json with items unordered

description: Requests module return json with items unordered


code:
text = """kAewtloYgcFQaJNhHVGxXDiQmzjfcpYbzxlWrVcqsmUbCunkfxZWDZjUZMiGqhRRiUvGmYmvnJ"""

for i, _ in enumerate(text[:-6]): #loop through index of each char (not including last 6)
    sevenCharacters = text[i:i+7] #create chunk of seven characters
    shouldBeCapital = sevenCharacters[0:3] + sevenCharacters[4:7] #combine all the chars that should be cap into list

    if (all(char.isupper() for char in shouldBeCapital)): #make sure all those characters are indeeed capital
        if(sevenCharacters[3].islower()): #make sure middle character is lowercase
            print(sevenCharacters)

rawDescription: Python Challenge #3: Loop stops way too early


code:
l = ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0']
filter(bool, l) # remove empty values
map(float, filter(bool, l)) # remove empty values and convert the rest to floats

rawDescription: Best strategy for dealing with incomplete lines of data from a file


code: n in range(10, 100)

rawDescription: Computing persistence number of an integer


code:
def count():
    with open("xxx.txt","r") as file:
        return len(re.findall('[a-zA-Z]', file.read()))

rawDescription: acount total number of letter ONLY alphabet

description: Acount total number of letter ONLY alphabet


code:
s
s.most_common()[0][0]

rawDescription: Extract greatest index from an array using python


code:
print(Y.shape)
# (2, 2)

rawDescription: storing record arrays in object arrays

description: Storing record arrays in object arrays


code:
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf'
prop = font_manager.FontProperties(fname=path)
fig, ax = plt.subplots()
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.show()

rawDescription: How to load .ttf file in matplotlib using mpl.rcParams?

description: Load .ttf file in matplotlib using mpl.rcParams


code:
# classes ALWAYS start with a capital letter in Python
class Student(models.Model):
    user_id =  models.OneToOneField(User,unique=True)
    ...

class StudentForm(ModelForm):
    class Meta:
        model = student

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(StudentForm, self).__init__(*args, **kwargs)
        self.fields['user'] = user

# views.py
from django.core.urlresolvers import reverse

def profile_creation(request):
    # Assumes the user is authenticated, otherwise request.user
    # will be an AnonymousUser instance...
    student_form = StudentForm(request.POST or None, user=request.user)
    if request.method == 'POST':
        if student_form.is_valid():
            student_form.save()
            # don't hard-code urls - use reverse lookups
            return HttpResponseRedirect(reverse('about'))

    return render(request, 'profile_registration.html',
        {'student_form': student_form})

rawDescription: Model Form wont validate with OneToOneField(User)


code:
def get_counts(sequence):
    counts = {}
    for x in sequence:
        if x in counts:
            counts[x] += 1
        else:
            counts[x] = 1 # it is run every iteration if x not in counts
    return counts

rawDescription: Example from "Python for Data Analysis", Chapter 2


code:
# Get the colour palette
palette = im.getpalette()

# Determine the total number of colours
num_colours = len(palette)/3

# Determine maximum value of the image data type
max_val = float(np.iinfo(indexed.dtype).max)

# Create a colour map matrix
map = np.array(palette).reshape(num_colours, 3) / max_val

rawDescription: Read in an indexed color image in Python


code:
from itertools import count

def longest_substr(input_string):
    maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)
    for start in range(len(input_string)): # O(n)
        for end in count(start + len(maxsubstr) + 1): # O(m)
            substr = input_string[start:end] # O(m)
            if len(set(substr)) != (end - start): # found duplicates or EOS
                break
            if (ord(max(substr)) - ord(min(substr)) + 1) == len(substr):
                maxsubstr = substr
    return maxsubstr

rawDescription: Find the longest substring with contiguous characters, where the string may be jumbled


code: sales_dict[int(j[6])] = 1

rawDescription: re reading a csv file in python without loading it again

description: Re reading a csv file in python without loading it again


code: month.lower() == 'march'

rawDescription: Why doesn't if, elif or else work with .lower() in Python?


rawDescription: Numpy matrix row/column memory layout

description: Numpy matrix row/column memory layout


code:
df1 = pd.DataFrame([[1, 'foo'], [np.nan, 'bar'], [3, 'meh'], [np.nan, 'baz']], columns = ['A', 'B'])
df2 = pd.DataFrame([[3], [np.nan]], columns = ['A'])
df1[~df1['A'].isin(df2['A'])]

rawDescription: Set differences on columns between dataframes


rawDescription: How do you get a list of annual compound returns in numpy (or other library)?

description: Get a list of annual compound returns in numpy (or other library)


code:
def merge_dicts(d1, d2):
    try:
        # Python 2
        intersection = d1.viewkeys() & d2
    except AttributeError:
        intersection = d1.keys() & d2

    if any(d1[shared] != d2[shared] for shared in intersection):
        return {}  # empty result if there are conflicts

    # leave the rest to C code, execute a fast merge using dict()
    return dict(d1, **d2)

rawDescription: Merging two dicts in python with no duplication permitted


code:
_abdlfla_
sldjlfds_
_adlfdls
_132jdlfjflds_

rawDescription: Regular expression in Python for matching strings in a CSV file


code:
idx = np.searchsorted(t1, t2) - 1
mask = idx >= 0

df = pd.DataFrame({"t1":t1[idx][mask], "t2":t2[mask]})

rawDescription: pandas.merge: match the nearest time stamp >= the series of timestamps

description: Pandas.merge: match the nearest time stamp >= the series of timestamps


code:
import csv

results = []
with open('ratings.txt', 'rb') as f:
    reader = csv.reader(f, delimiter='|')
    for row in reader:
        results.append(row)

rawDescription: Trying to read information in a file into two lists in Python


code:
class Hive(models.Model):
    name = models.CharField(max_length=100)
    marker = models.BooleanField(default=False)

class Bee(models.Model):
    hive = models.ForeignKey(Hive)
    name = models.CharField(max_length=100)

rawDescription: Extending Django Admin tabular.html custom checkbox action


code:
def find_ip(in_file,sub_s):
    with open(in_file) as f:
        lines = reversed(f.readlines())
        for line in lines:
            if sub_s in line:
                return next(lines).rsplit(":", 1)[-1]

rawDescription: python search a text file for a string and add the value to a variable

description: Python search a text file for a string and add the value to a variable


code:
if exit_status:
    self.output = stderr.readlines()
else:
    self.output =  stdout.readlines()
    del self.output[0]
    del self.output[-1]

rawDescription: Python Class For Reading List Element ,__str__ and class questions


code:
files = BetterDefaultDict(lambda key: open(key, 'w'))
files['/tmp/test.py']

rawDescription: is it possible to use a lambda as a dictionary default?

description: Is it possible to use a lambda as a dictionary default


code:
test = [[(u'hello',), (u'hello',)], [(u'hello',)]]
for i, part_i in enumerate(test):
    for j, part_j in enumerate(part_i):
        test[i][j] = str(part_j[0])

rawDescription: How to change this list tuple into list only in Python?

description: Change this list tuple into list only in Python


rawDescription: Nested object listing with conditions

description: Nested object listing with conditions


rawDescription: Regex - Replacing a matching subgroup

description: Regex - Replacing a matching subgroup


code:
if f[1] == 0:
    continue

rawDescription: Python: split a list based on a condition?


code:
X.data[:] = np.sqrt(X.data)
X.A

rawDescription: How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?

description: Operate elementwise on a matrix of type scipy.sparse.csr_matrix


code:
x = []
y = []
for row in plot:
    x.append(int(row[0]))
    y.append(int(row[1]))

rawDescription: Why is this python list showing empty in this certain case?


code:
import pandas as pd
df = pd.read_table('data', sep='\s{2,}').set_index('observation_date')
df.index = pd.DatetimeIndex(df.index)
df.index = df.index + pd.DateOffset(year=2013)
print(df)

rawDescription: How to change a DateTimeIndex in a pandas dataframe to all the same year?

description: Change a DateTimeIndex in a pandas dataframe to all the same year


code:
def weeks():
    d = ["week1", "week2", "week3"]
    total_weight_lost = 0
    for k in d:
        total_weight_lost += int(input(" How much weight did you lose in", d, "?:"))
    return total_weight_lost,

rawDescription: How to get user inputted values for keys in dictionary with for loop?

description: Get user inputted values for keys in dictionary with for loop


code:
import statsmodels.api as sm
a = np.array([1,2,3,4,5,6,7,8,9])
b = 2. * np.array([1,2,9,4,5,6,7,13,9])
model = sm.RLM(b, a, M=sm.robust.norms.HuberT()).fit()
model.params

rawDescription: Python statsmodels return values missing


code: words = re.findall('\w+', string)

rawDescription: Find duplicates in string, and return single result for only duplicates


code:
counts = collections.defaultdict(int)
for word in words:
    counts[word] += 1

rawDescription: Python Duplicate words

description: Python Duplicate words


code:
minId = volumes.index(min(volumes))
maxId = volumes.index(max(volumes))

rawDescription: How to colour maixum and minimun of each bar in bar graph in python?

description: Colour maixum and minimun of each bar in bar graph in python


code:
myDict = {}
JohnDoe = Person("John Doe", "jdoe@email.com")
BobbyMcfry = Person("Bobby Mcfry", "bmcfry@email.com")
WardWilkens = Person("Ward Wilkens", "wwilkens@email.com")
for person in [JohnDoe, BobbyMcfry, WardWilkens]:
    myDict[person.name] = person

x = input("Who to check for? ")
person = myDict.get(x)
if person:
    print("Name: {0}\nEmail: {1}".format(person.name, person.email))
else:
    print("{0} is not on the manifest.".format(x))

rawDescription: How to check if instance object's attribute within a list is equal to a value

description: Check if instance object's attribute within a list is equal to a value


rawDescription: del function not working properly

description: Del function not working properly


code:
from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
                     builtin_str, getproxies, proxy_bypass, urlunparse,
                     basestring)

rawDescription: Python requests urlencode without sending any request


rawDescription: Choosing random items from a Spark GroupedData Object


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

class DrawDragPoints(object):
    """
    Demonstrates a basic example of the "scaffolding" you need to efficiently
    blit drawable/draggable/deleteable artists on top of a background.
    """
    def __init__(self):
        self.fig, self.ax = self.setup_axes()
        self.xy = []
        self.tolerance = 10
        self._num_clicks = 0

        # The artist we'll be modifying...
        self.points = self.ax.scatter([], [], s=200, color='red',
                                      picker=self.tolerance, animated=True)

        connect = self.fig.canvas.mpl_connect
        connect('button_press_event', self.on_click)
        self.draw_cid = connect('draw_event', self.grab_background)

    def setup_axes(self):
        """Setup the figure/axes and plot any background artists."""
        fig, ax = plt.subplots()

        # imshow would be _much_ faster in this case, but let's deliberately
        # use something slow...
        ax.pcolormesh(np.random.random((1000, 1000)), cmap='gray')

        ax.set_title('Left click to add/drag a point\nRight-click to delete')
        return fig, ax

    def on_click(self, event):
        """Decide whether to add, delete, or drag a point."""
        # If we're using a tool on the toolbar, don't add/draw a point...
        if self.fig.canvas.toolbar._active is not None:
            return

        contains, info = self.points.contains(event)
        if contains:
            i = info['ind'][0]
            if event.button == 1:
                self.start_drag(i)
            elif event.button == 3:
                self.delete_point(i)
        else:
            self.add_point(event)

    def update(self):
        """Update the artist for any changes to self.xy."""
        self.points.set_offsets(self.xy)
        self.blit()

    def add_point(self, event):
        self.xy.append([event.xdata, event.ydata])
        self.update()

    def delete_point(self, i):
        self.xy.pop(i)
        self.update()

    def start_drag(self, i):
        """Bind mouse motion to updating a particular point."""
        self.drag_i = i
        connect = self.fig.canvas.mpl_connect
        cid1 = connect('motion_notify_event', self.drag_update)
        cid2 = connect('button_release_event', self.end_drag)
        self.drag_cids = [cid1, cid2]

    def drag_update(self, event):
        """Update a point that's being moved interactively."""
        self.xy[self.drag_i] = [event.xdata, event.ydata]
        self.update()

    def end_drag(self, event):
        """End the binding of mouse motion to a particular point."""
        for cid in self.drag_cids:
            self.fig.canvas.mpl_disconnect(cid)

    def safe_draw(self):
        """Temporarily disconnect the draw_event callback to avoid recursion"""
        canvas = self.fig.canvas
        canvas.mpl_disconnect(self.draw_cid)
        canvas.draw()
        self.draw_cid = canvas.mpl_connect('draw_event', self.grab_background)

    def grab_background(self, event=None):
        """
        When the figure is resized, hide the points, draw everything,
        and update the background.
        """
        self.points.set_visible(False)
        self.safe_draw()

        # With most backends (e.g. TkAgg), we could grab (and refresh, in
        # self.blit) self.ax.bbox instead of self.fig.bbox, but Qt4Agg, and
        # some others, requires us to update the _full_ canvas, instead.
        self.background = self.fig.canvas.copy_from_bbox(self.fig.bbox)

        self.points.set_visible(True)
        self.blit()

    def blit(self):
        """
        Efficiently update the figure, without needing to redraw the
        "background" artists.
        """
        self.fig.canvas.restore_region(self.background)
        self.ax.draw_artist(self.points)
        self.fig.canvas.blit(self.fig.bbox)

    def show(self):
        plt.show()

DrawDragPoints().show()

rawDescription: Efficient Matplotlib Redrawing

description: Efficient Matplotlib Redrawing


rawDescription: splitting an array into two smaller arrays in python

description: Splitting an array into two smaller arrays in python


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

def func(x, *params):
    y = np.zeros_like(x)
    for i in range(0, len(params), 3):
        ctr = params[i]
        amp = params[i+1]
        wid = params[i+2]
        y = y + amp * np.exp( -((x - ctr)/wid)**2)
    return y

rawDescription: fit multiple gaussians to the data in python

description: Fit multiple gaussians to the data in python


rawDescription: extracting data from .txt file using python

description: Extracting data from .txt file using python


code:
jobid = request.get('id')
cmd = request.get('cmd')
sock = socket.socket(socket.AF_UNIX)
sock.connect('/tmp/script-foo/control/%s.socket' % jobid)
sock.sendall(cmd)
sock.close()

rawDescription: Python - User input to CGI via. Threading and reading file


code:
def intersect(a, b):
    sb = set(b)
    return [x for x in a if x in sb]

rawDescription: Intersecting lists in python won't work

description: Intersecting lists in python won't work


code:
similarities = {}

def set_sim(players, sim):
    similarities[tuple(sorted(players))] = sim

def get_sim(players):
    return similarities.get(tuple(sorted(players)))

rawDescription: How to make array of array of dictionaries in python

description: Make array of array of dictionaries in python


code:
size = 30
features = np.random.rand(50)
transitiveParams = np.random.rand(size, size)
featureParams = np.random.rand(size, size)

rawDescription: How to eliminate for-loop and use list comprehension when using numpy array?

description: Eliminate for-loop and use list comprehension when using numpy array


code:
ax = (
    df.set_index('E', append=True)  # set E as part of the index
      .stack()                      # pull A - D into rows
      .to_frame()                   # convert to a dataframe
      .reset_index()                # make the index into reg. columns
      .rename(columns={'level_2': 'quantity', 0: 'value'})  # rename columns
      .drop('level_0', axis='columns')   # drop junk columns
      .pipe((seaborn.boxplot, 'data'), x='quantity', y='value', hue='E', hue_order=[1, 2])
)
seaborn.despine(trim=True)

rawDescription: Python Side-by-side box plots on same figure


code: for i in rubikstring("RL2R'F2LD'"): i

rawDescription: Most efficient way of splitting strings like rubik's cube notations in python?


code:
def findnth(haystack, needle, n):
    parts= haystack.split(needle, n+1)
    if len(parts)<=n+1:
        return -1
    return len(haystack)-len(parts[-1])-len(needle)

rawDescription: Find the nth occurrence of substring in a string


code: m = [row for row in l if 'a' == row[0]]

rawDescription: Filter array to show rows with a specific value in a specific column


code:
print ("Pig Latin") #welcoming message for the program.
word = input("Input a word in English ") #user input defined variable

rawDescription: Why does my function not run once I run the module and input?


code:
class Meta:
    fields = ('custom_field', 'all_other_fields_you_need')

rawDescription: Django REST framework serializing model combinations


code:
def getDifference(x,y):
    symDiff = set(i[0] for i in x) ^ set(i[0] for i in y)
    return [i for i in x if i[0] in symDiff] + [i for i in y if i[0] in symDiff]

rawDescription: How can the symmetric difference between two lists of two-element sublists be obtained?


code:
for line in f:
    copy.write(line)

rawDescription: Copy a file line by line in python

description: Copy a file line by line in python


code:
instance = Test()
dict((p, getattr(instance, p))
     for p in dir(instance)
     if p not in dir(Test) or isinstance(getattr(Test, p), property))

rawDescription: Python: retrieve  all properties of a class instance that uses the @property annotation


code:
import sys
sys.path

rawDescription: Defining PYTHONPATH automatically in virtualenvs


code:
datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 0, 4) #no need for that.

rawDescription: Understanding timedelta

description: Understanding timedelta


code:
def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h # center player

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top

    return Rect(l, t, w, h)

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


code:
import collections
ordered_dict=collections.OrderedDict()
ordered_dict['foo'] = 1
ordered_dict['bar'] = 2
ordered_dict['baz'] = 3
sorted_dict = collections.OrderedDict(sorted(ordered_dict.items(),
                                             key=lambda t: t[0]))

rawDescription: Ordered Dictionary is not sorting

description: Ordered Dictionary is not sorting


code:
image = gtk.Image.new_from_file("filename")
button = gtk.Button()
button.add(image)

inner_box = gtk.VBox()
inner_box.pack_start(gtk.Alignment(), True, True, 0)
inner_box.pack_start(button, False, False, 0)
inner_box.pack_start(gtk.Alignment(), True, True, 0)

outer_box = gtk.HBox()
outer_box.pack_start(gtk.Label("some widget"), True, True, 0)
outer_box.pack_start(inner_box, False, False, 0)

rawDescription: How to fill a button with image in python gtk

description: Fill a button with image in python gtk


code:
class Boundary:
    pass
x = Boundary()
isinstance(x, Boundary)

rawDescription: Determine the type of a (not built in) class in python


code:
indexes = concatenate((arange(n - shift, n), arange(n - shift)))
res = a.take(indexes, axis)

rawDescription: Operations on 'N' dimensional numpy arrays


rawDescription: How to find the index value of a variable in SPSS Python

description: Find the index value of a variable in SPSS Python


rawDescription: Pandas: Create New Column using Values in Subgroup of Other Columns


rawDescription: Python split equally

description: Python split equally


code:
a = raw_input("Enter number:")
type(a)
b = int(a)
type(b)

rawDescription: Input to list and operate on it

description: Input to list and operate on it


code:
land_cover = df.groupby('Allotment')['Land_Cover'].apply(lambda x: pd.DataFrame(x.unique()).T).reset_index(level=1, drop=True)
land_cover.columns = ['Land_Cover{}'.format(c) for c in land_cover.columns]

rawDescription: Pivoting based on unique values

description: Pivoting based on unique values


code: string.capwords("john's    school", " ")

rawDescription: Python title() with apostrophes

description: Python title() with apostrophes


rawDescription: Counting qualitative values based on the date range in Pandas


code:
wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))

# if you don't call rewind, next readframes() call
# will return nothing and audioop will fail

wav.rewind()
print(audioop.max(wav.readframes(wav.getnframes()), wav.getsampwidth()))

rawDescription: What type of file is the "sound fragment" parameter for audioop?


rawDescription: What do * and ** before a variable name mean in a function signature?


code:
import urllib2
img = urllib2.urlopen("http://example.com/image.jpg").read()

rawDescription: How do I copy a remote image in python?

description: Copy a remote image in python


rawDescription: Remove part of an element in python

description: Remove part of an element in python


code:
@property
def id(self):
    return self._id

@id.setter
def id(self, newid):
    self._id = newid

rawDescription: Are accessors in Python ever justified?

description: Are accessors in Python ever justified


code:
with open('myfile.txt', 'r') as myfile:
    print([item.strip() for item in myfile.read().split('< NEW DOCUMENT>') if item])

rawDescription: How to count the articles and place each in a list

description: Count the articles and place each in a list


rawDescription: Update dictionary in xml from csv file in python


code: D1 = S1.to_frame().reset_index().T

rawDescription: Pandas How to convert from series to a data frame


code:
def wear(hat):
    try:
        import bandana
    except ImportError:
        raise NotImplementedError("You need the bandana package to wear hats")
    else:
        bandana.check(hat)
        ...

rawDescription: Python: Define a function only if package exists


code:
import math

FMT = "{:>8} {:>8} {:>8}".format

def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            value = int(raw_input(prompt))
            if (lo is None or lo <= value) and (hi is None or value <= hi):
                return value
        except ValueError:   # could not parse input as int
            pass             # try again

def max_x(max_y):
    # y = 90*x**2 + 2*x
    # 0 = 90*x**2 + 2*x - y
    # Using the quadratic formula,
    # x = (-2 +/- sqrt(4 + 360*y)) / 180
    # We are only interested in the +ve solution:
    discr_rt = math.sqrt(4 + 360 * max_y)
    x = (discr_rt - 2.) / 180.
    # and we want to round down to an int
    return int(math.floor(x))

def max_n(x, max_z):
    a = 90*x + 1
    y = (90*x + 2)*x
    nf = float(max_z - y) / a
    return int(math.floor(nf))

def z(x, n):
    a = 90*x + 1
    y = (90*x + 2)*x
    return a*n + y

def main():
    max_z = get_int("Please enter int value for max_z: ", 1, 10000)
    max_y = max_z
    max_x_val = max_x(max_y)

    for x in xrange(1, max_x_val + 1):
        max_n_val = max_n(x, max_z)
        if max_n_val < 1:
            break
        y = (90*x + 2)*x
        print(FMT("(nonn)", "(nonn)", y))
        for n in xrange(1, max_n_val + 1):
            z_val = z(x, n)
            print(FMT(z_val, z_val, ""))

if __name__=="__main__":
    main()

rawDescription: How to set a global numerical limit for several sequences in Python?

description: Set a global numerical limit for several sequences in Python


code: r, *x = color()

rawDescription: Is there some kind of tuple wildcart in Python?


code:
...

from blog.sitemap import BlogSitemap
from fooapp.sitemap import FooSitemap
from barapp.sitemap import BarSitemap

sitemaps = {
    'blog':BlogSitemap,
    'foo':FooSitemap,
    'bar':BarSitemap,
}

rawDescription: Django 1.6: What should be the location of the sitemap.py file?


rawDescription: How to convert string of the form '1,1' into float (1,1)?

description: Convert string of the form '1,1' into float (1,1)


code:
class ComplexStructure():
    def add_records(self,record):
        self.listofrecords.append(record)

    def get_value(self,position):
        listnum,posinlist = ... # formula to figure out which list and where in
                                # list element of complex structure is
        return self.listofrecords[listnum][record]

    def set_value(self,position,value):
        listnum,posinlist = ... # formula to figure out which list and where in
                                # list element of complex structure is
        self.listofrecords[listnum][record] = value

rawDescription: How to create a memoryview for a non-contiguous memory location?

description: Create a memoryview for a non-contiguous memory location


code:
def scatter_plot_with_correlation_line(x, y, graph_filepath):
    plt.scatter(x, y)
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)

    # Store reference to correlation line. note the comma after corr_line
    corr_line, = plt.plot(X_plot, m*X_plot + b, '-')
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

    # remove the correlation line after saving the figure, ready for the next iteration
    corr_line.remove()

rawDescription: Python matplotlib keeps the previous line after plotting new one


rawDescription: match the pattern at the end of a string?

description: Match the pattern at the end of a string


code:
# processing
# ===========================================
def func(group):
    return (group.prec != 0).astype(int).cumsum()[group.prec == 0].value_counts().iloc[0]

rawDescription: how to count continuous numbers of events in a long time series data

description: Count continuous numbers of events in a long time series data


rawDescription: Loop through dictionary with django

description: Loop through dictionary with django


code:
a = "This is an example"
a.split()        # gives ['This', 'is', 'an', 'example']  -> same as a.split(' ')

rawDescription: Capitalization of the first letters of words in a sentence using python code


rawDescription: Parsing Python Dictionary Keys

description: Parsing Python Dictionary Keys


code:
my_dict = {}
my_dict['value1'] = ['new value 1']
my_dict['value1'] += ['new value 2', 'new value 3']

rawDescription: transform php code to python - append new values to the same key in dict

description: Transform php code to python - append new values to the same key in dict


code:
i = 0
while i <= length:
    u[:,i] = u[:,i] - u_val
    y[:,i] = y[:,i] - y_val
    i = i + 1

rawDescription: Python Changing Array Values in While Loop


code: filter(f, L)

rawDescription: What is a better pythonic version of this conditional deleting?


code:
with open(file, 'r') as f:
    lines = [x for x in unuuencode(f)]

rawDescription: Python - delete uuencoding lines

description: Python - delete uuencoding lines


code: ''' I use this module to check for newer versions of ETE '''

rawDescription: ETE2 .phonehome() Is it an Easter Egg?

description: ETE2 .phonehome() Is it an Easter Egg


code:
def negate(number, bits = 32):
    return format(~number & 2 ** bits - 1, "0{}b".format(bits))

print(negate(1))
# 11111111111111111111111111111110
print(negate(1, bits = 4))
# 1110

rawDescription: How to create Python fixed length bits?

description: Create Python fixed length bits


code:
t1.class_attr = []
t1.class_attr is t2.class_attr

rawDescription: Static class variable in Python that isn't copied for each instance


code:
zeros = [20 - bin(n).count('1') for n in range(1<<20)]
ones = [bin(n).count('1') for n in range(1<<20)]

rawDescription: Get the the number of zeros and ones of a binary number in Python


code:
class YourModel(models.Model):
    name = models.CharField(max_length=100)

class YourModelUpdateHistory(models.Model):
    your_model = models.ForeignKey('YourModel')
    updated = models.DateTimeField()

rawDescription: django multiple update dates in one field

description: Django multiple update dates in one field


code: data.append( (int(myinput[0]), int(myinput[1])) )

rawDescription: python add elements in a tuple

description: Python add elements in a tuple


rawDescription: Read multiple bytes in Hexadecimal file using python


code:
from itertools import izip_longest

summed = [a + b for a, b in izip_longest(v1, v2, fillvalue=0)]

rawDescription: Add sum of values of two lists into new one


code:
from fabric.api import task, run, hide, execute, runs_once
env.hosts['h1', 'h2', 'h3']

@task
def collect_info():
    with hide('everything'):
        info = run("who | tail -n 1")
        return info

@task
@runs_once
def info():
    collected_output = execute(collect_info)
    for host, info in collected_output.iteritems():
        print("On host {0} last user was {1}".format(host, info))

rawDescription: How can I collect fabric task output and print a summary for multiple hosts?

description: Collect fabric task output and print a summary for multiple hosts


code:
import re
result = re.sub("\D", "", a['onclick'])

rawDescription: Python - Parse String

description: Python - Parse String


code:
inputlowf = line1.get()
inputhighf = line2.get()
inputstep = line3.get()

rawDescription: Tkinter get() function not saving values as float or int variables


code:
for i in range(len(array)):
   [row1, row2, row3] = np.loadtxt(list.list[i],unpack=True,skiprows=1)

rawDescription: Python: np.loadtxt, read multiple files

description: Python: np.loadtxt, read multiple files


code:
def readfile():
    with open(file) as fil:     # open file
        scores = fil.read().splitlines() # split file contents by lines

    count = 0
    for score in scores:        # loop through all lines
        if count == 0:          # skip first line
            count = count + 1
            continue
        data = score.split()    # split line by space
        print ("%s\t%s" % (data[0], data[1])) # print name and score

rawDescription: Write dictionary data to file

description: Write dictionary data to file


code: [{'playing': ['volley ball', 'basket ball', 'hockey', 'cricket'], 'name': 'kishore'}, {'playing': ['cricket'], 'name': 'xyz'}]

rawDescription: Merging list of dictionary in python

description: Merging list of dictionary in python


code:
f_in = 'foreman_cif.yuv'
f_out = 'py_10bpp.yuv'

def convert(chunk):
    data = bytearray() # 1.6 -> 1.5 seconds for preallocated data
    for b in bytearray(chunk):
        data.append((b << 2) & 0xff)
        data.append((b >> 6) & 0xff)
    return data

with open(f_in, 'rb') as fd_in, open(f_out, 'wb') as fd_out:
    while True:
        chunk = fd_in.read(8192)
        if not chunk:
            break
        fd_out.write(convert(chunk))

rawDescription: python performance dealing with binary files

description: Python performance dealing with binary files


code:
for _ in range(3):
    result = pool.apply_async(ImageData.shepard_interpolation, args=[ImageData()])
    results.append(result.get())

rawDescription: Can't pickle static method - Multiprocessing - Python


code: reduce(lambda agg,x: agg.__setitem__(x,agg.get(x,0)+1) or agg, colSequence, {})

rawDescription: Python Filtering lists? - Lambda function


code:
class C:
    _x = None

    @property
    def x(self):
        return self._x

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

rawDescription: Using @property versus accessing variables directly


code:
def rec_list(l):
    if not l: return # empty list case
    # process l[0]
    return rec_list(l[1:])

rawDescription: How do I convert a for loop to a recursive method?

description: Convert a for loop to a recursive method


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

kv = '''
#:import Label kivy.uix.label.Label

<TestWidget>
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: 'add before'
            on_press: root.add_widget(Label(text="before"), index=len(root.children))
        Button:
            text: 'add after'
            on_press: root.add_widget(Label(text="after"))
'''
Builder.load_string(kv)

class TestWidget(BoxLayout):
    pass

class TestApp(App):
    def build(self):
        return TestWidget()

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

rawDescription: How to .put() data in the first item in a JsonStore() in Python Kivy


code:
def foo(s):
    return id(s)
x = 'blah'
id(x) == foo(x)

rawDescription: Python: How do I pass a string by reference?


code: process_names = [proc.name() for proc in psutil.process_iter()]

rawDescription: Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows


code: a.reshape(50, 40) > np.percentile(a.reshape(50, 40), 99, axis=0)

rawDescription: Calculate percentile per set interval in python array


code:
while True:
    key = prefix + "".join(random.choice(string.letters+string.digits) for _ in range(KEYLEN))
    if not key in key_list:
        key_list.append(key)
        break

rawDescription: Generate randon and uniques ids in django


code: desired_list = [[value]+list(tup) for tup in tuple_list]

rawDescription: How to append one value to every tuple within a list?

description: Append one value to every tuple within a list


code:
class SideEffect():
    def __init__(self, n):
        self.values = iter(range(n))
        self.return_value = None

    def __call__(self):
        self.return_value = next(self.values)
        return self.return_value

a = Mock()
se = SideEffect(10)
a.side_effect = se

for x in range(10):
    v = a()
    assert v == se.return_value
    print("a()={}  return_value={}".format(v, se.return_value))

rawDescription: Is it possible to query a Python mock object for the return values of its calls?


code:
b'Why is this twice'

done

rawDescription: Python subprocess input is read twice

description: Python subprocess input is read twice


code:
def get(self):
  return self._s
def set(self, value):
  self._s = value

rawDescription: How to implement property() with dynamic name (in python)

description: Implement property() with dynamic name (in python)


code: df.sort_values(['a', 'b'], ascending=[True, False])

rawDescription: How to sort a dataFrame in python pandas by two or more columns?

description: Sort a dataFrame in python pandas by two or more columns


code: rapport.append(Paragraph('  Toto is a naugthy boy ', styles['Left']))

rawDescription: Defining our own colors (RGB ?) for Intra-paragraph markup color in reportlab


code:
for person,details in dct.items():
    thing, number = details
    new_num = number * 2
    dct[person][1] = new_num

rawDescription: spliting list and adding values

description: Spliting list and adding values


code:
locators = ((getAttr(locator+'.localScaleY'), locator) for locator in pm.ls('locator*'))
yMaxValue, locator = max(locators)

rawDescription: Compare and grab items attributes

description: Compare and grab items attributes


code:
from grades import test

# then invoke it
test()

rawDescription: Python Multiple file program

description: Python Multiple file program


code:
anchor = line.find('div', {'class':'torrentname'}).find('a')
d['name'] = ''.join(anchor.findAll(text=True))

rawDescription: Removing Tags from HTML Parsed with BeautifulSoup


code:
for i,fname in enumerate(('inputFile.csv','lat.csv','lon.csv')):
    with open(fname) as f:
        data = np.fromfile(f,sep=',')
        a[:,i] = data.ravel()

rawDescription: Translating a gridded csv file with numpy


code: main()

rawDescription: Problem with multiprocessing python 2.6

description: Problem with multiprocessing python 2.6


code:
def trunc_div(a, b):
    return int(a / b)

rawDescription: Truncating division in Python 3.2

description: Truncating division in Python 3.2


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


code:
new_dict = {}
for row in data_dict['epoch']:
    if new_dict.get(row[0]):
        new_dict[row[0]].update({row[1]:row[2]})
    else:
        new_dict[row[0]] = {row[1]:row[2]}
return_data = {'epoch':new_dict}

rawDescription: Converting a list of lists into a multi-dimensional list in python


code:
find = Selection.Find
find.Text = "test"
find.Replacement.Text = "test2"

rawDescription: Can I use Win32 COM to replace text inside a word document?

description: Use Win32 COM to replace text inside a word document


rawDescription: How can I convert a dictionary to a tuple in python?

description: Convert a dictionary to a tuple in python


code: myOldIntValue|string

rawDescription: Convert integer to string Jinja

description: Convert integer to string Jinja


code:
zones = []
cur_zone = ''
f = open(bind_file).readlines()
for line in f:
    if line[0:2] == '//':
        zones.append(cur_zone)
        cur_zone = ''
    else:
        cur_zone = cur_zone + line
zones.pop(0) # Drop the first list item, it's empty

rawDescription: Extracting BIND parameters to build a JSON query


rawDescription: Break the sentence into words using the space character as a delimiter in Python


code:
f = open('data')
list(IT.groupby(f, key=header_func))

rawDescription: Most pythonic way to break up highly branched parser


code: self.myButton.clicked.connect(lambda self=self: setattr(self, 'someVariable', None))

rawDescription: PyQt signal: set variable

description: PyQt signal: set variable


code:
_artist_name = ['artist {}'.format(i + 1) for i in range(30)]
_artist_title = ['title {}'.format(i + 1) for i in range(30)]
_xl = ['xl image {}'.format(i + 1) for i in range(30)]
_l = ['l image {}'.format(i + 1) for i in range(30)]
_m = ['m image {}'.format(i + 1) for i in range(30)]
_s = ['s image {}'.format(i + 1) for i in range(30)]

from pprint import pprint
track_keys = ("artist", "title", "image_xl", "image_l", "image_m", "image_s")
zipped = zip(_artist_name, _artist_title, _xl, _l, _m, _s)
pprint([dict(zip(track_keys, values)) for values in zipped])

rawDescription: Putting a zipped object into a dictionary


code:
def writerows(self, rows):
    for row in rows:
        self.writerow(row)

rawDescription: csv: writer.writerows() splitting my string inputs

description: Csv: writer.writerows() splitting my string inputs


code:
mButton = Button(mGui, text = "CON", command = assign("CON")).pack()
mButton = Button(mGui, text = "MS", command = assign("MS")).pack()
mButton = Button(mGui, text = "DRN", command = assign("DRN")).pack()

rawDescription: Using tkinter to assign a global variable and destroy the gui


code:
start_year = 2005
end_year = 2007
start_month = 3
end_month = 2
yymm = [(yy, mm) for yy in range(start_year, end_year + 1) for mm in range(1, 13)
        if (start_year, start_month) <= (yy, mm) <= (end_year, end_month)]

rawDescription: Python: Generating YYMM string between two dates


rawDescription: How does Python take in an expression as a parameter to a function?


code: foo | groupby('a') | map(attribute='list') | map('sum', attribute='b')

rawDescription: Applying a jinja filter after using groupby filter


code: dictionary1, dictionary2 = decoded

rawDescription: How to convert a JSON string into a Python data structure

description: Convert a JSON string into a Python data structure


code:
def remove_sensitive(data,key):
    if key in data:
         data[key] = "Not Stored!"
    return data

rawDescription: Python remove or replace key

description: Python remove or replace key


rawDescription: Simplify this dictionary of lists into a single list containing all/only unique values


code:
import base64

with open("image.png", "rb") as image:
    encoded_string = base64.b64encode(image.read())

rawDescription: Python display a server-side image in a html


code:
def main(dataset, n_h, n_y, batch_size, dev_split, n_epochs):
    input_to_state = Linear(name='input_to_state',
                            input_dim=seq_u.shape[-1],
                            output_dim=n_h)
    RNN = SimpleRecurrent(activation=Tanh(),
                          dim=n_h, name="RNN")
    return input_to_state, RNN

def predict(dev_X, input_to_state, RNN):
    dev_transform = input_to_state.apply(dev_X)
    dev_h = RNN.apply(dev_transform)

if __name__ == "__main__":
    input_to_state, RNN = main(args)
    predict(dev_X, input_to_state, RNN)

rawDescription: In Python, can I call the variable from main function - use global variable?


rawDescription: Matplotlib colorbar ticks on left/opposite side


code: 'the first paragraph of'

rawDescription: how to change index value in python lists

description: Change index value in python lists


code:
text = 'b,a,b'
','.join(set(text.split(',')))

rawDescription: How to get rid of duplicate entries in a comma separated string

description: Get rid of duplicate entries in a comma separated string


code:
import numpy as np

def iterative_test(rng, fn, goal):
    return min(rng, key=lambda x: abs(goal - fn(x)))

rng  = np.arange(1.01, 1.20, 0.01)
fn   = lambda x: 11. * (1. - x**8) / (1. - x)
goal = 126.
sol  = iterative_test(rng, fn, goal)

print('Solution: {} -> {}'.format(sol, fn(sol)))

rawDescription: solving for a compound interest between PV and "summation" FV?

description: Solving for a compound interest between PV and "summation" FV


code:
def parse(filename, services):
    services = set(services)
    with open(filename, 'r', encoding='koi8-r') as f:
        for log_line in f:
            words = set(log_line.split())
            services -= words

    return list(servicesset)

rawDescription: More pythonic way to write this function


code:
a = np.arange(3)
a
a[:, None]
b = np.arange(4,1,-1)
b
a[:, None] * b

rawDescription: How to vectorize multiple levels of recursion?

description: Vectorize multiple levels of recursion


rawDescription: Difference between dictionary and ordereddict in python


code:
for i in range(10):  # xrange in Python 2
    for j in range(i, 10):
        calc_something(x[i], x[j])

rawDescription: Calculate all unique permutations using nested loops in Python


code:
FList = set(["Mary Smith", "Kevin Bacon"])
JG = [[3928, "Mary Smith"], [2920, "Jacob Francis"], [7777, "Kevin Bacon"]]
ultralist = [row for row in JG if row[1] in FList]
ultralist

rawDescription: Iterating over two lists, the first list is only going through the first value


rawDescription: CRC-CCITT 16-bit Python Manual Calculation


code:
new_lst = [(False, 'category123'), (True, 'cat@123'), (False, 'cat')]
sorted(new_lst, reverse=True)

rawDescription: Sort: How to treat special character greater than alphabetical in Python 2?


code:
score=int(raw_input("Enter a number: "))
name=raw_input("What is your name?: ")

if name in class_1:
    class_1[name]+=score
else:
    class_1[name]=score

rawDescription: How to add a value to a key in dictionary in Python

description: Add a value to a key in dictionary in Python


code:
[[[b_n, b_p, b_s[-4:]], change, [a_n, a_p, a_s[:4]]]
 for (b_n, b_p, b_s), change, (a_n, a_p, a_s) in results]

rawDescription: Python: slicing elements of lists in lists in lists differently depending on sublist


code: [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ]

rawDescription: Find the indices of elements greater than x


rawDescription: Efficient way to create term density matrix from pandas DataFrame


code:
from pika.adapters.twisted_connection import TwistedProtocolConnection
from pika.connection import ConnectionParameters
from twisted.internet import protocol, reactor, task
from twisted.python import log

class Consumer(object):
    def on_connected(self, connection):
        d = connection.channel()
        d.addCallback(self.got_channel)
        d.addCallback(self.queue_declared)
        d.addCallback(self.queue_bound)
        d.addCallback(self.handle_deliveries)
        d.addErrback(log.err)

    def got_channel(self, channel):
        self.channel = channel

        return self.channel.queue_declare(exclusive=True)

    def queue_declared(self, queue):
        self._queue_name = queue.method.queue

        self.channel.queue_bind(queue=self._queue_name,
                                exchange="my-exchange",
                                routing_key="*.*.*.*.*")

    def queue_bound(self, ignored):
        return self.channel.basic_consume(queue=self._queue_name)

    def handle_deliveries(self, queue_and_consumer_tag):
        queue, consumer_tag = queue_and_consumer_tag
        self.looping_call = task.LoopingCall(self.consume_from_queue, queue)

        return self.looping_call.start(0)

    def consume_from_queue(self, queue):
        d = queue.get()

        return d.addCallback(lambda result: self.handle_payload(*result))

    def handle_payload(self, channel, method, properties, body):
        print(body)

if __name__ == "__main__":
    consumer1 = Consumer()
    consumer2 = Consumer()

    parameters = ConnectionParameters()
    cc = protocol.ClientCreator(reactor,
                                TwistedProtocolConnection,
                                parameters)
    d1 = cc.connectTCP("host1", 5672)
    d1.addCallback(lambda protocol: protocol.ready)
    d1.addCallback(consumer1.on_connected)
    d1.addErrback(log.err)

    d2 = cc.connectTCP("host2", 5672)
    d2.addCallback(lambda protocol: protocol.ready)
    d2.addCallback(consumer2.on_connected)
    d2.addErrback(log.err)

    reactor.run()

rawDescription: Python and RabbitMQ - Best way to listen to consume events from multiple channels?


code:
b
i[b]

rawDescription: Vectorized search of element indeces

description: Vectorized search of element indeces


code:
import scipy.interpolate as interpolate
import scipy.optimize as optimize
import numpy as np

x1=np.array([1.4,2.1,3,5.9,8,9,23])
y1=np.array([2.3,3.1,1,3.9,8,9,11])
x2=np.array([1,2,3,4,6,8,9])
y2=np.array([4,12,7,1,6.3,8.5,12])

p1=interpolate.PiecewisePolynomial(x1,y1[:,np.newaxis])
p2=interpolate.PiecewisePolynomial(x2,y2[:,np.newaxis])

def pdiff(x):
    return p1(x)-p2(x)

xs=np.r_[x1,x2]
xs.sort()
x_min=xs.min()
x_max=xs.max()
x_mid=xs[:-1]+np.diff(xs)/2
roots=set()
for val in x_mid:
    root,infodict,ier,mesg = optimize.fsolve(pdiff,val,full_output=True)
    # ier==1 indicates a root has been found
    if ier==1 and x_min<root<x_max:
        roots.add(root[0])
roots=list(roots)
print(np.column_stack((roots,p1(roots),p2(roots))))

rawDescription: Python - matplotlib: find intersection of lineplots


code: re.search("is", String).start()

rawDescription: Python - Locating the position of a regex match in a string?


code:
try:
    item = test['store']
except KeyError:
    item = run()

rawDescription: Callable as the default argument to dict.get without it being called if the key exists


code: parser = Parser()

rawDescription: Dynamically import and create class instance


rawDescription: Scrapy not collecting data

description: Scrapy not collecting data


code: m = [float(x) for x in m]

rawDescription: extracting numbers from a string in a list via regex

description: Extracting numbers from a string in a list via regex


code:
from matplotlib import rcParams
rcParams['text.usetex'] = True

rawDescription: Python: Matplotlib: how to print ONE text with different sizes in it?


code: grad = theano.grad(loss, l_hid.W_hid_to_hid)

rawDescription: Lasagne / Theano gradient values

description: Lasagne / Theano gradient values


code:
import pandas as pd

data = pd.read_csv('data_file.csv')
grouped_measured_power = data.groupby([' Rate', ' Frequency'])[' Measured_Power']
min_measured_power_by_rate_and_freq = grouped_measured_power.min()
max_measured_power_by_rate_and_freq = grouped_measured_power.max()
average_measured_power_by_rate_and_freq = grouped_measured_power.mean()

rawDescription: Find min,max in csv file in python

description: Find min,max in csv file in python


rawDescription: Fill zero values of 1d numpy array with last non-zero values


code:
class AsciiInput(TextInput):

    def insert_text(self, string, from_undo=False):
        string = string.decode("ascii", errors='ignore')
        return super(AsciiInput, self).insert_text(string, from_undo=from_undo)

rawDescription: Restrict kivy's TextInput to only ascii characters


code:
N = 5
dotps
R,C = np.triu_indices(N,1)
out

rawDescription: Processing upper triangular elements only with NumPy einsum


code: (item1, item2, item3, count)

rawDescription: Sorting by element on data structure in python


code:
parser.add_argument('-i', type=int, metavar='input', choices=range(1,65), help='set input.')
parser.add_argument('-o', type=int, metavar='output', choices=range(1,5), help='set output.')

rawDescription: python-argparse: assign a choice to each argument

description: Python-argparse: assign a choice to each argument


code:
def is_not_digit(s):
    return not s.isdigit()
filter(is_not_digit, 'h3ll0')

rawDescription: How to remove numeric character in my input text?

description: Remove numeric character in my input text


code:
test = [['ma', 'e', 'wa', 'ka'], ['ma', 'haa', 'laa'], ['ma', 'ka', 'm', 'haa', 'laa', 'ca', 'j', 'ra'], ['ma', 'ra'], 'ma']
test = sorted(test, key=lambda x: len(x) if type(x)==list else 1)
test

rawDescription: Sort order of lists in multidimensional array in Python


code:
[int(x) for x in li]  # create the full list directly
(int(n) for n in li)  # create a generator (note parentheses instead of brackets)

rawDescription: how to change the type of items in the list?

description: Change the type of items in the list


code: v = A[position : position + length]

rawDescription: combining two slicing operations

description: Combining two slicing operations


rawDescription: Python - Removing overlapping lists

description: Python - Removing overlapping lists


code:
indexed_sentence = []
for x in Sentence:
    for count in range(len(Sentence)):
        if x == Sentence[count]:
            indexed_sentence.append(count + 1)
            break

rawDescription: Replace the words in a list with the position of each word


code:
def onclick(self):
    ...
    g.canvas.draw()
refresh=f.canvas.mpl_connect('button_release_event', onclick)

rawDescription: Python, Pyplot - How to move two plots at the same time?


code:
headers = ["part"]
for i, ASM in enumerate(ASM_list):
    headers.append("ASM%d" % (i+1))
print(", ".join(headers))

for i, part_colors in enumerate(zip(*parts_list)):
    part_name = part_names[i]
    print(part_name + ", " + ", ".join(part_colors))

rawDescription: Python extract properties from list of listed objects


rawDescription: How to find index of a character after space in python

description: Find index of a character after space in python


code:
hhh = [clf_nb, clf_dt]

g = pd.DataFrame()

i = clf_nb

while i in hhh: # if `clf_nb` is still on the list `hhh` then ...
    g.append( crossV(i) ) # append `clf_nb` to the `g`

rawDescription: How to use a for loop to append the data frame generated from a function in python

description: Use a for loop to append the data frame generated from a function in python


rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


code:
from itertools import izip_longest

print(list(izip_longest(a,b, fillvalue="")))
[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

rawDescription: Combining two lists into a list of lists


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

# Your "list of 600 values"...
x = np.linspace(0, 10, 600)

coeffs = [-1.3, 10, 3, 10]

# Evaluate a polynomial at each location in `x`
y = np.polyval(coeffs, x)

# Calculate the derivative
der_coeffs = np.polyder(coeffs)

# Evaluate the derivative on the same points...
y_prime = np.polyval(der_coeffs, x)

# Plot the two...
fig, (ax1, ax2) = plt.subplots(nrows=2)

ax1.plot(x, y)
ax1.set_title('Original Function')

ax2.plot(x, y_prime)
ax2.set_title('Deriviative')

plt.show()

rawDescription: Transform polynomial graph - Multiply by a list of values


code:
import a_standard
import b_standard

import a_third_party
import b_third_party

from a_soc import f
from a_soc import g
from b_soc import d

rawDescription: What's the correct way to sort Python `import x` and `from x import y` statements?


code:
import copy
def fill(shape,value):
    result=value
    for i in reversed(shape):
        result=[copy.deepcopy(result) for j in range(i)]
    return result

rawDescription: Initialize arbitrarily shaped nested list


code: ('20:33:02', 'user', 'random message here')

rawDescription: Python regex not matching full capture group


label: Anonymous lifestyle App cflw`2B2[h1s`lNzF@sPC1FtaCiK0VF@

rawDescription: Python: remove ^A in a string

description: Python: remove ^A in a string


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2015)

N = 5
x, y = np.random.randint(100, size=(2,N))

fig, axs = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
colors = np.linspace(0, 1, N)
axs[0,0].scatter(x,y, s=200, c=colors)
for i, ax in enumerate(axs.ravel()[1:]):
    ax.scatter(x[i], y[i], s=200, c=colors[i], vmin=0, vmax=1)
plt.show()

rawDescription: With MatPlotLib, how do I apply autoscaled axes from one graph to a separate graph?


rawDescription: Fill out login information with selenium


code:
import threading
import wsgiref.simple_server
remote_server = wsgire.simple_server('localhost', 8000, app)
POOL_SIZE = 10 # or some other value.
pool = [threading.Thread(target=remote_server.serve_forever) for dummy in xrange(POOL_SIZE)]
for thread in pool:
    thread.daemon = True
    thread.start()

while True:
    pass # normal experiment processing here; don't handle requests in this thread.

rawDescription: Building an HTTP API for continuously running python process


code: elem = doc.createElement('your_elem')

rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code: f = fs['failas'].file

rawDescription: How does cgi.FieldStorage store files?

description: How does cgi.FieldStorage store files


code: [pair[1] for pairlist in dict1.values() for pair in pairlist]

rawDescription: Generating a list from complex dictionary


code: count_weekday(date_from, date_to)

rawDescription: Number of times each weekday occurs between two dates


code:
from itertools import chain
max_val = max(chain.from_iterable(lst))
lst = [[1,2,3], [1,3,3], [1,1,1]]
[(i, j) for i, x in enumerate(lst) for j, y in enumerate(x) if y == max_val]

rawDescription: getting all the tiles with the maximum value in a 2d grid (a multidimensional list)

description: Getting all the tiles with the maximum value in a 2d grid (a multidimensional list)


code:
import timeit
timeit.timeit("[int(digit) for digit in bin(123)[2:]]")
timeit.timeit("[123 >> i & 1 for i in range(7,-1,-1)]")
timeit.timeit("[1 if digit=='1' else 0 for digit in bin(123)[2:]]")

rawDescription: Integer to bitfield as a list

description: Integer to bitfield as a list


rawDescription: Convert list-of-dicts into tree

description: Convert list-of-dicts into tree


code:
import random

my_win = 0
my_loss = 0
my_tie = 0

def rock(rand):

    global my_tie, my_loss, my_win
    if rand == (1):
        print("Tie Game!")
        my_tie += 1
    elif rand == (2):
        print("Your rock got covered by opponent's paper. You Lose!")
        my_loss += 1
    elif rand == (3):
        print("You crushed the opponent's scissors with your rock! You Win!")
        print("Good game!")
        my_win += 1

def paper(rand):

    if rand == (1):
        print("You covered opponent's rock with your paper. You Win!")
        print("Good game!")
        my_win += 1
    elif rand == (2):
        print("Tie Game!")
        my_tie += 1
    elif rand == (3):
        print("Your opponent cut your paper with its scissors. You Lose!")
        my_loss += 1

def scissors(rand):

    if rand == (1):
        print("Your opponent's rock crushed your scissors. You Lose!")
        my_loss += 1
    elif rand == (2):
        print("Your scissors cut opponent's paper. You Win!")
        print("Good game!")
        my_win += 1
    elif rand == (3):
        print("Tie Game!")
        my_tie += 1

def main():

    name = input("What is your name? ")

    print("Hello, " + name + "! I'm a rock paper scissors game.")

    while True:
        choice = input("Would you like to play? (yes/no) ").upper()[0]
        if choice == "N":
            print("Let's play later!")
            break
        elif choice == "Y":
            print("Ok, lets play!")
            print("Rules: Rock breaks Scissors, Scissors cuts Paper, Paper covers Rock. ")
            raw = input("Choose rock, paper, or scissors ").upper()
            try:
                answer = raw[0]
            except:
                print("Illegal input! Exiting.")
                break

            rand = random.randint(1, 3)  # 1 = rock, 2 =Paper 3 = Scissors
            if answer == "S":
                scissors(rand)
            elif answer == "P":
                paper(rand)
            elif answer == "R":
                rock(rand)
            else:
                print("Enter a valid answer!")
    print ("You win %d times!" % my_win)
    print ("You lose %d times!" % my_loss)
    print ("You tie %d times!" % my_tie)
main()

rawDescription: python rock paper scissors counter

description: Python rock paper scissors counter


code:
import csv
import sys

with open('csv1.txt') as fp:
    reader = csv.reader(fp, skipinitialspace=True)
    writer = csv.writer(sys.stdout)
    writer.writerows(row for row in reader if row[2] == '1944')

rawDescription: How do I search for a specific field in a csv file then print the entire row in Python

description: Search for a specific field in a csv file then print the entire row in Python


code:
private = RSA.generate(1024)
public  = private.publickey()
private.exportKey()
public.exportKey()

rawDescription: Using RSA in Python

description: Using RSA in Python


code:
def build_addin(pres, path):
    """
    This procedure does the following:
        1. adds all of the VBComponents to the working PPTM file
        2. adds required project references
    The .PPTM file is used for local development & debugging and
    is only usually packaged as a PPAM for Testing and Distribution
    """

    version = str(int(float(pres.Application.version)))

    # import the VB Components
    for fn in [fn for fn in os.listdir(path) if not(fn.endswith(".frx"))]:
        pres.VBProject.VBComponents.Import(path + "\\" + fn)

    # add the required project references
    pres.VBProject.References.AddFromFile(r'C:\Program Files (x86)\Microsoft Office\Office'+version+'\EXCEL.EXE')
    # MSForms TreeView Control
    pres.VBProject.References.AddFromFile(r'C:\Windows\SysWOW64\MSCOMCTL.OCX')
    # MSXML2
    pres.VBProject.References.AddFromFile(r'C:\Windows\System32\msxml6.dll')
    # ADODB
    pres.VBProject.References.AddFromFile(r'C:\Program Files (x86)\Common Files\System\ado\msado15.dll')
    # VBE Extensibility

rawDescription: Python Build Script for VBA Add-In file

description: Python Build Script for VBA Add-In file


code:
class CarManufacturers(enum.Enum):
    BMW, Mercedes = range(2)

mfcChanged = pyqtSignal()

@pyqtProperty('QStringList', constant=True)
def carmanufacturers(self):
    return [mfc.name for mfc in CarManufacturers]

@pyqtProperty('QString', notify=mfcChanged)
def mfc(self):
    return str(CarManufacturers[self._mfc].value)

@modus.setter
def mfc(self, mfc):
    print('mfc changed to %s' % mfc)
    if self._mfc != CarManufacturers(int(mfc)).name:
        self._mfc = CarManufacturers(int(mfc)).name
        self.mfcChanged.emit()

rawDescription: I want to set a Qt QML Combobox to a PyQt5 object property


code:
import wx
import wx.lib.newevent

import logging

# create event type
wxLogEvent, EVT_WX_LOG_EVENT = wx.lib.newevent.NewEvent()

class wxLogHandler(logging.Handler):
    """
    A handler class which sends log strings to a wx object
    """
    def __init__(self, wxDest=None):
        """
        Initialize the handler
        @param wxDest: the destination object to post the event to
        @type wxDest: wx.Window
        """
        logging.Handler.__init__(self)
        self.wxDest = wxDest
        self.level = logging.DEBUG

    def flush(self):
        """
        does nothing for this handler
        """

    def emit(self, record):
        """
        Emit a record.

        """
        try:
            msg = self.format(record)
            evt = wxLogEvent(message=msg,levelname=record.levelname)
            wx.PostEvent(self.wxDest,evt)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

rawDescription: How can I redirect the logger to a wxPython textCtrl using a custom logging handler?

description: Redirect the logger to a wxPython textCtrl using a custom logging handler


rawDescription: Adding many scrolledpanels to one scrolledPanel in wxPython


code:
from visual import *
myell = ellipsoid(pos=(x0,y0,z0), length=L, height=H, width=W)

rawDescription: Making Random 3-D Shapes in Python

description: Making Random 3-D Shapes in Python


rawDescription: izip_longest on a list of lists

description: Izip_longest on a list of lists


code:
import pandas as pd
from numpy import arange
from scipy import random
index = pd.MultiIndex.from_product([arange(0,3), arange(10,15)], names=['A', 'B'])
df = pd.DataFrame(columns=['test'], index=index)
someValues = random.randint(0, 10, size=5)
df.loc[0,'test'] = someValues
df

rawDescription: Set values of a column with numpy array

description: Set values of a column with numpy array


code:
import re
scanner = re.Scanner([
    (r"[\\]", r'\\textbackslash{}'),
    (r"[{]", r'\\{{}'),
    (r"[}]", r'\\}{}'),
    (r".", lambda s, t: t)
])

tokens, remainder = scanner.scan("\\foo\\{bar}")
print(''.join(tokens))

rawDescription: quote string for TeX input

description: Quote string for TeX input


code:
import pyparsing
s = r'''"this is an \"example\" of what I want to parse" '''
pyparsing.QuotedString('"').parseString(s)
pyparsing.QuotedString('"', escChar='\\').parseString(s)

rawDescription: Using escChar and escQuote in pyparsing

description: Using escChar and escQuote in pyparsing


code:
def start_fun(self):
    res = self.foo(500) # use self.

def foo(self, m):
    for i in xrange(m):
        i * 2
        self.pbar_det.step(1)
        self.update()
        time.sleep(0.1)
    return i

rawDescription: how to embed a Tkinter progressbar in a function in Python

description: Embed a Tkinter progressbar in a function in Python


code:
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django_tables2.utils import AttributeDict

class CustomBooleanColumn(BooleanColumn):
    def render(self, value):
        value = bool(value)
        text = self.yesno[int(not value)]
        html = '<span %s>%s</span>'

        class_name = 'some_class_false'
        if value:
            class_name = 'some_class_true'
        attrs = {'class': 'class_name'}

        attrs.update(self.attrs.get('span', {}))

        return mark_safe(html % (AttributeDict(attrs).as_html(), escape(text)))

rawDescription: django-tables2 edit yesno parameter for all BooleanColumn

description: Django-tables2 edit yesno parameter for all BooleanColumn


code:
class NoteSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username') # Make sure owner is associated with the User model in your models.py

rawDescription: Django rest framework auto-populate filed with user.id


rawDescription: Python library to extract 'epub' information


code:
def main():
    """To print a names numeric value"""
    name = input("Enter your full name here: ")
    return sum(ord(character) - 96 for character in name.lower() if character != " ")

rawDescription: Numerical value of a name

description: Numerical value of a name


rawDescription: how to set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs?

description: Set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs


rawDescription: Set properties for specific patch in matplotlib.collections.PathCollection


code:
import example
spam = example.Spam(42)
spam = example.Spam([42])

rawDescription: Boost Python iterable convertible masking non-iterable constructor


rawDescription: Python - Convert a matrix to edge list/long form


code: ppf(q, loc=0, scale=1)  # Percent point function (inverse of cdf — percentiles)

rawDescription: python equivalent of qnorm, qf and qchi2 of R

description: Python equivalent of qnorm, qf and qchi2 of R


code: my_dic = {key: [] for key in my_dic}

rawDescription: clearing a dictionary but keeping the keys

description: Clearing a dictionary but keeping the keys


code: from urllib.parse import urlparse, parse_qs

rawDescription: Beautifulsoup extract string partially

description: Beautifulsoup extract string partially


code:
def primes(count):
    """
    Returns a list with the first `count` prime numbers.

    An advice: If you will be using this functiona a lot it's better
    for performance if you precalculate cribe.
    """

    # Calculate primes up to 50, you can change this to your preference.
    MAX = 50

    sieve = [1] * MAX
    for i in range(2, int(MAX ** 0.5) + 2 ):
        for j in range(i + i, MAX, i):
            sieve[j] = 0

    # Finally primes are indexes in the list that still has 0.
    result = []
    for index, elem in enumerate(sieve):
        if elem == 1: result.append(index)

    return result[1:count + 1]

rawDescription: List not being written to a text file

description: List not being written to a text file


code: re.split(r'[A-Z ]+',tr)

rawDescription: Python: how to split a string by multiple strings


rawDescription: numpy beginner array plain python vs. numpy vectors: faulty results

description: Numpy beginner array plain python vs. numpy vectors: faulty results


code:
out = A.T + A
idx = np.arange(A.shape[0])
out[idx,idx] = A[idx,idx]

rawDescription: Convert triangle matrix to square (Python | NumPy)?


code:
for team in league.iterkeys():
    runs_scored, runs_allowed = map(float, league[team])

rawDescription: Iterating Over Dictionary Key Values Corresponding to List in Python


code: match = re.search(r'ac.*?\.([\d]*)\b', i)

rawDescription: Is there any better way to solve this regular expression in Python?


code:
from django.core import cache
from proj.celery import app

class SomeModel(models.Model):
    # ...
    def get_crunched_numbers(self):
        cache_key = 'foo:{}'.format(self.id)
        res = cache.get(cache_key)
        if not res:
            gen_crunched_numbers.delay(cache_key)
            return 'crunching... come back later'
        else:
            return res

@app.task
def gen_crunched_numbers(cache_key):
    res = do_heavy_lifting()
    cache.set(cache_key, res)
    return res

rawDescription: Celery task best practices in Django/Python


code:
def runner(f, callable):
  def inner():
    for i in xrange(1000):
      f(*callable())
  return inner

runner(f, lambda: (random.randint(1, 1000),))()

rawDescription: Run python function multiple times with different arguments


rawDescription: Python: can 2.X be patched so as to totally ignore *.pyc files?


code:
fig = plt.figure(figsize=(8.0,6.0))
ax1 = fig.add_subplot(221)

vmax=30
levels_max=100
vmin=0
levels = np.arange(vmin,levels_max,.1)

z_contourR = ax1.contourf(xlist,ylist,z_matrixR,levels=levels,vmax=vmax,vmin=vmin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('real')
cbarR = plt.colorbar(z_contourR)

ax2 = fig.add_subplot(222)
z_contourI = ax2.contourf(xlist,ylist,z_matrixI,levels=levels,vmax=vmax,vmin=vmin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('imaginary')
cbarI = plt.colorbar(z_contourI)

plt.tight_layout()
plt.show()

rawDescription: Python same colorbar for subplots of real / imaginary contour plots of function


code:
def func(a,b,c,d):
    pass

func(a=1, *(1, 2, 3))

rawDescription: Mixing *vargs and **kargs arguments in function call


code:
class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    html = db.Column(db.String)

    @property
    def slugified_title():
        return slugify(self.title, separator="_", to_lower=True)

    @permalink
    def url(self):
        # where 'post' is the title of your route that displays the post
        return 'post', {'post_id': self.id, 'slug':self.slugified_title}

rawDescription: add slugified title to url

description: Add slugified title to url


code: dict_of_balls = {ball.name: ball for ball in list_of_balls}

rawDescription: python getting a specific attribute from a list of objects

description: Python getting a specific attribute from a list of objects


code:
strings = []
for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    strings.append(filterString)

my_query_set = MyModel.objects.filter(arn__in=strings)

rawDescription: Is it possible to concatenate QuerySets?

description: Is it possible to concatenate QuerySets


code: t_df.index = t_df.index.map(str)

rawDescription: Python Pandas: What is the fastest way to create a datetime index?


rawDescription: Splitting longer patterns using regex without losing characters Python 3+


code:
import itertools
import os

# Will raise StopIteration if you don't have 1000 files
file1000 = next(itertools.islice(os.scandir(somedir), 999, None)).path

rawDescription: fastest way to get the filename of a specific file from a directory with python

description: Fastest way to get the filename of a specific file from a directory with python


code: df = pd.read_csv('sticks.csv', names=["xstk", "stk"])

rawDescription: How do I turn this json object into a panda dataframe?

description: Turn this json object into a panda dataframe


code:
from pyspark import SparkFiles

class EnvVariables:
    attributes = {}
    allTags = ["UNK"]
    similarityDicts = []
    mergeThreshold = 0.5

with open(SparkFiles.get("config")) as fr:
    EnvVariables.attributes.update({"a": 1})
    EnvVariables.allTags.append("b")

rawDescription: Python Spark, Accessing Class Static Variables from Executor


rawDescription: Only extracting text from this element, not its children


code: start_time = datetime.datetime.strptime(data, "%Y%m%d%H%M%S")

rawDescription: How to exchange time between C and Python

description: Exchange time between C and Python


code: (klass.__dict__['x'] for klass in ChildA.__mro__ if 'x' in klass.__dict__)

rawDescription: Python: Class attribute which defaults to parent's value and is collectible for entire hierarchy


code:
def twoNumValues(myList):
    return len(myList) == 2 and all(type(i) in [float, int] for i in myList)

rawDescription: How to make sure if parameter is a list of numbers? (python)

description: Make sure if parameter is a list of numbers? (python)


code:
def mul(x, y):
    assert isinstance(x, DenseVector)
    assert isinstance(y, SparseVector)
    assert x.size == y.size
    return SparseVector(y.size, y.indices, x[y.indices] * y.values)

aRDD.join(bRDD).mapValues(lambda xy: mul(*xy))

rawDescription: Multiply SparseVectors element-wise

description: Multiply SparseVectors element-wise


code:
os.path.relpath('/Folder/OtherFolder/AnotherFolder/file.txt', '/Folder/OtherFolder')
# returns 'AnotherFolder/file.txt'

rel_path.split(os.path.sep)
# returns ['AnotherFolder', 'file.txt']

rawDescription: Get parents directories of a file, up to a point


code:
def flatten(current, key, result):
    if isinstance(current, dict):
        for k in current:
            new_key = "{0}.{1}".format(key, k) if len(key) > 0 else k
            flatten(current[k], new_key, result)
    else:
        result[key] = current
    return result

result = flatten(my_dict, '', {})

rawDescription: How would I flatten a nested dictionary in Python 3?


code: ivd = {v: k for (k, v) in a.items()}

rawDescription: Reverse the one-to-one mapped dictionary


code:
import numpy as np
import matplotlib.pyplot as plt
#import math  #use np.* if you have it already imported

epsilon=0.0038*1.60217662*10**-19
k = 1.38*10**-23
T = np.arange(1,2000,0.1)
beta = 1.0/(k*T) #changed to 1.0 for safe measure; redundant

#partitionfunction
svec=np.arange(1,31,2)
p=np.zeros(max(svec)) #added pre-allocation
Zodd=np.zeros(len(T)) #added pre-allocation
for i in np.arange(len(T)): #changed to index Zodd from 0
    for s in svec:  #changed to avoid magic numbers
        p[s-1] = 3*(2*s+1)*np.exp(-(s**2+s)*epsilon*beta[i])   #changed to index p from 0; changed beta(i) to beta[i]; changed to np.exp
    Zodd[i] = sum(p)

#energy
ln_Zodd = np.log(Zodd)  #changed to np.log

Epara=np.zeros(len(T)-2)  #added pre-allocation
for i in np.arange(len(T) - 2): #changed to index Epara from 0
    Epara[i]=- (ln_Zodd[i + 1] - ln_Zodd[i]) / (beta[i + 1] - beta[i])   #changed bunch of () to []

#heat capacity
Cpara=np.zeros(len(T)-3)  #added pre-allocation
for i in np.arange(len(T) - 3): #changed to index Cpara from 0
    Cpara[i]=(Epara[i + 1] - Epara[i]) / (T[i + 1] - T[i])

#plot
x = k*T/epsilon
plt.plot(x[:6000],Cpara[:6000] / k,'r')  #fixed and simplified array indices
plt.axis([0, 7, 0, 1.5])
plt.ylabel('C_v/k')
plt.xlabel('kT/eps')
plt.show()

rawDescription: Suggestions on matlab/python conversion

description: Suggestions on matlab/python conversion


code:
p = Profile.objects.get(...)
isinstance(p.settings, Settings)

rawDescription: Automatically creating a OneToOneField when accessed


code:
d={"a":5, "bf": 55, "asf": 55}

search_key = lambda in_d, val: (k for k,v in in_d.items() if v == val)

for k in search_key(d, 55):
    print(k)

# since the lambda returns generator expression you can simply print
# the keys as follows:

print(list(search_key(d, 55)))
# or get the key list
key_list = list(search_key(d, 55))

rawDescription: Python - Opposite of dictionary search

description: Python - Opposite of dictionary search


code:
from datetime import datetime, timedelta
from collections import OrderedDict
dates = ["2014-10-10", "2016-01-07"]
start, end = [datetime.strptime(_, "%Y-%m-%d") for _ in dates]
OrderedDict(((start + timedelta(_)).strftime(r"%b-%y"), None) for _ in xrange((end - start).days)).keys()

rawDescription: Generate list of months between interval in python


code:
import wmi
cur=wmi.WMI()
wireless_devices=cur.query("select * from Win32_NetworkAdapter WHERE NetConnectionID = 'Wireless Network Connection'")
for device in wireless_devices:
    device.Disable()

rawDescription: put interface down in windows with python?

description: Put interface down in windows with python


rawDescription: how to get a descendant from parent entity

description: Get a descendant from parent entity


rawDescription: Shortest code for depleting a generator in code golfing


code: ndb.gql("SELECT * FROM MyModel WHERE foo != :1", my_key)

rawDescription: How to order an ndb query by a repeated field that can be empty

description: Order an ndb query by a repeated field that can be empty


code:
with open('output.txt', 'w') as f:
    for tr in soup.find_all('tr')[2:]:
        tds = tr.find_all('td')
        f.write("Nome: %s, Cognome: %s, Email: %s\n" % \
              (tds[0].text, tds[1].text, tds[2].text))

rawDescription: Python BeautifulSoup scrape tables

description: Python BeautifulSoup scrape tables


rawDescription: How do I get another field from a Pandas Group By?

description: Get another field from a Pandas Group By


rawDescription: python, zip:Discard extra elements

description: Python, zip:Discard extra elements


code:
@np.vectorize
def values(i):
    try:
        return next(idx for idx, value in enumerate(A[i+1:]) if value > A[i]) + i + 1
    except StopIteration:
        return -1 # no valid values found
return values(np.arange(len(A)))

rawDescription: Numpy vectorization algorithms to find first future element greater than current element


rawDescription: How to avoid hanging Xvfb processes [while using PyVirtualDisplay]?

description: Avoid hanging Xvfb processes [while using PyVirtualDisplay]