code:
import json

df_json = df.to_json(orient='values') # JSON

py_data = json.loads( df_json ) # Python data

result['extra_data'] = py_data # merge data

json_all = json.dumps( result ) # JSON again

rawDescription: Combine DataFrame as JSON with additional data


code:
class OrderProduct(BaseModel):
    order = models.ForeignKey(Order)
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()

rawDescription: Django, m2m with same model

description: Django, m2m with same model


rawDescription: change multiple lines in file python using regex

description: Change multiple lines in file python using regex


code:
def findCarryIn(x, y, c_out, bit):
    s = 0
    for i,j in zip(x, reversed(y)):
        s += i & j
    return (2 * c_out + bit - s)

rawDescription: Optimizing python one-liner

description: Optimizing python one-liner


code:
import example
x = range(2)
x
example.set(x)
example.display()
x[:] = range(7, 10)
example.display()

rawDescription: boost::python passing reference of python::list

description: Boost::python passing reference of python::list


code:
all[0].content_type
all[0].object_id

rawDescription: Django Releationship between multiple fields


rawDescription: Python data frames - how to select all columns that have a specific substring in their name


code:
df.loc[:,"value1":"value3"] = df.loc[:,"value1":"value3"].div(df["sum"], axis=0)
df

rawDescription: Pandas sum across columns and divide each cell from that value


code:
data=item.find('Datas')
new=ET.SubElement(data,'Data')
new.text='FOUR'
new=ET.SubElement(data,'Data')
new.text='FIVE'

rawDescription: python elementtree xml append

description: Python elementtree xml append


code: 1,a,"the big bad, string"

rawDescription: How to escape comma in string Python 2.7 in a .csv file

description: Escape comma in string Python 2.7 in a .csv file


code: references = dict(zip(modules, map(__import__, modules)))

rawDescription: Dynamic module loading in python

description: Dynamic module loading in python


rawDescription: Which regex is more efficient?

description: Which regex is more efficient


code:
int_columns = [1, 3, 5]
for i in range(sh.nrows):
    row = sh.row_values(i)
    for col in int_columns:
        row[col] = int(new_row[col])
    writetab.writerow(row)

rawDescription: Convert Float to Integer During xcel to Tab Delimited File Conversion


code: a = x if x else y

rawDescription: What is the most Pythonic way to provide a fall-back value in an assignment?


code:
import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
        # ('id', 0, <type 'int'>)
        # ('rb', '', <type 'str'>)
        # ('person', 'name', <type 'str'>)
print(parser.items('section'))
# [('id', '000'), ('rb', ''), ('person', 'name')]

rawDescription: How to handle empty values in config files with ConfigParser?

description: Handle empty values in config files with ConfigParser


code:
[i for i, v in set(enumerate(new)).symmetric_difference(enumerate(old))
                                                     if i not in ignore]

rawDescription: Optimise comparison between two lists, giving indices that differ


code:
x =  ['apples', 'oranges', 'bananas']
x = [a.replace("app", "spam") for a in x ]
x

rawDescription: How can I replace parts of strings in a list?

description: Replace parts of strings in a list


code: cursor.execute('INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s,   ...)' % ','.join(fieldlist), valuelist)

rawDescription: MySQL Dynamic Query Statement in Python

description: MySQL Dynamic Query Statement in Python


code:
class Person(models.Model):
    # your existing code goes here

    @property
    def is_employee(self):
         try:
              self.employee # try to get the associated Employee object
              return True
         except Employee.DoesNotExist:
              return False

class PersonSearchIndex(SearchIndex):
    # your existing code goes here
    is_employee = BooleanField(model_attr='is_employee')

rawDescription: django haystack inheritance problems

description: Django haystack inheritance problems


rawDescription: Working with unicode in python

description: Working with unicode in python


code:
for i in Object.vars:
    list_of_objects.append(getattr(Object, 'attribute_' + i))

rawDescription: Jinja2 dynamic variable building

description: Jinja2 dynamic variable building


code:
import zipfile
import StringIO

zipped_file = StringIO.StringIO()
with zipfile.ZipFile(zipped_file, 'w') as zip:
    for i, file in enumerate(files):
        file.seek(0)
        zip.writestr("{}.csv".format(i), file.read())

zipped_file.seek(0)

rawDescription: Sending multiple .CSV files to .ZIP without storing to disk in Python


code:
# arr=np.zeros((row,column), dtype=np.int8)  # no use
img1 = np.zeros(img.shape, dtype=float)  # to allow float multiplication
img1[:,:,0]=img[:,:,0]*.114  # a fast i,j iteration
img1[:,:,1]=img[:,:,1]*.587  # another fast i,j
img1[:,:,2]=img[:,:,2]*.299   # yet another
arr=img1[:,:,0]+img1[:,:,1]+img1[:,:,2]  # and yet another :)

rawDescription: Why do the following codes take different times for execution (What is actually going on inside numpy arrays)?


code:
for key, value in filestocopy.iteritems():
        #dest_path+key is the destination path, as the key is the relative path
        #and the dest_path is the top level folder
        copy(value['fullpath'], dest_path+key, **kwargs)

rawDescription: Is there a better way to feed different parameters into a function with if-statements?


code:
def __eq__(self,other):
    return self.name == other.name

rawDescription: How do I make a class in Python behave with Sets?

description: Make a class in Python behave with Sets


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

    links = relationship(
        'Links', tagslinks_assoc,
        collection_class=set,  # use a set to hold the collection
        backref=backref('tags', collection_class=set)
    )

    def __hash__(self):
        return hash((self.__class__, self.tag))  # any Tag with the same name hashes equal

class Links(Base):
    # ...

    def __hash__(self):
        return hash((self.__class__, self.link))

rawDescription: database for tags - updating many-to-many tables with unique columns

description: Database for tags - updating many-to-many tables with unique columns


code: from ..pkg1 import util

rawDescription: Basic Python imports question

description: Basic Python imports question


code: Canvas.create_rectangle(x0, y0, x1, y1, option, ...)

rawDescription: Help Creating Python Class with Tkinter

description: Help Creating Python Class with Tkinter


code:
from myapp.models import MenuItem
def menu(request):
    return {'menu': MenuItem.objects.all() }

rawDescription: Site menu using django

description: Site menu using django


code: SCOPES = 'https://mail.google.com/'

rawDescription: Where do I get the Authorized Gmail API service instance? (python, gmail api)


code:
import re
re.split('([\s.,;()]+)', text)

rawDescription: Split strings on whitespaces, but do not remove them


code:
if st.find("e") < st.find("t"):
    st.replace("e","i",1)

rawDescription: Replace character in a string conditional on appearance of another character in the string Python


rawDescription: Efficient Way to Recursively Multiply

description: Efficient Way to Recursively Multiply


code: [x for x,y in groupby(L) if sum(1 for i in y)<2]

rawDescription: Removing elements that have consecutive dupes


code: [x for tup in zip(a, b) for x in tup]

rawDescription: Python two list lists shuffle

description: Python two list lists shuffle


code:
a = "I am an apple"
reg = re.compile(r'I am (\w+).*?$')
print('How long have you been {}'.format(*reg.findall(a)))

rawDescription: Grabbing a part of a string using regex in python 3.x


code:
# establish data set in the format of [node_id, name, parent_node_id]
tree_info = [
    ['1', 'Grandparent', 'root'],
    ['2', 'Parent 1', '1'],
    ['3', 'Parent 2', '1'],
    ['4', 'Child 1', '3'],
    ['5', 'Child 2', '3']
]

generation = {'root': 0}

for node in tree_info:
    node_id, name, parent_id = node
    indent = generation[parent_id]
    generation[node_id] = indent + 1
    print(indent * ' ' + name)

rawDescription: print out an indented node tree in python from a list of list

description: Print out an indented node tree in python from a list of list


code: [list(t) for t in zip(a,b)]

rawDescription: Python: combine list with lists of list while preserving lists elements


code: sensors = pd.merge(sensor1, sensor2, how="inner", on=["ObservationID"])

rawDescription: Append data in pandas

description: Append data in pandas


code:
Food
Person
Person
Food
Vehicle
Food

rawDescription: Python - reading complex lines of text into dictionary


rawDescription: I want to use Python to list a directory, then sort the filenames by size


code:
#In your model
head = models.BooleanField(default=True)

#As a signal plugin:
def check_head(sender, **kwargs):
    message = kwargs['instance']
    if hasattr(message,'no_check_head') and message.no_check_head:
        return
    previous_message = Message.objects.filter(time__lt=message.time).order_by('-time')[0]
    if message.source == previous_message.source:
        message.head = False
    next_message = Message.objects.filter(time__gt=message.time).order_by('time')[0]
    if message.source == next_message.source:
        next_message.head = False
        next_message.no_check_head
        next_message.save()

rawDescription: Paging depending on grouping of items in Django


code:
from collections import defaultdict, Counter

data = '''-,-,1970,John,-
-,-,1970,John,-
-,-,1970,Paul,-
-,-,2014,Bob,-
-,-,2014,Mary,-
-,-,2014,Mary,-'''

temp = defaultdict(list)

for record in (line.split(',') for line in data.splitlines()):
  y = record[2]
  n = record[3]
  temp[y].append(n)

results = [(k, Counter(v).most_common(1)) for k,v in temp.items()]

rawDescription: Reading text file and returning most popular name for that year


code:
packedButton = Button(btn_f, text="Button Packed")
packedButton.pack(pady=100,padx=100)

rawDescription: expand within notebook does not work as expected

description: Expand within notebook does not work as expected


code: response.delimiters = ['{%', '%}']

rawDescription: Processing ember.js tagged html with python


code:
v.vendorName
cast(v.vendorName, c_char_p)
cast(v.vendorName, c_char_p).value

rawDescription: Print a C string in Python

description: Print a C string in Python


code:
with settings( host_string="ec2-user@%s" % instance.ip_address,
    key_filename=os.path.join( os.getenv( "HOME" ),
    ".ssh", "%s.pem" % ami.sshkey.name ),
    connection_attempts=5, timeout=60 ):

    ...
    sudo( "yum -y install mysql mysql-devel" )
    ...

rawDescription: How can I write a python script that can start new EC2 instances?

description: Write a python script that can start new EC2 instances


code:
import numpy as np
np.random.randn(5)
np.set_printoptions(precision=3)
np.random.randn(5)

rawDescription: Apply round off setting to whole notebook


code:
def prepped_compare(obj1, obj2):
    li_field = getattr(obj1, "li_field", None)
    if li_field  is None:
        #grab the list from the compare object, but this assumes a
        #fixed fieldlist per run.
        #mind you getattr(obj,non-existentfield) blows up anyway
        #so y'all making that assumption already
        li_field = [f for f in vars(obj1) if f.startswith('field')]
        obj1.__class__.li_field = li_field

    for field in li_field:
        if getattr(obj1, field) != getattr(obj2, field):
            return False
    return True

rawDescription: Selective comparison of class objects

description: Selective comparison of class objects


code: conv = np.round(alt / 500.).astype(int)

rawDescription: Python numpy grid transformation using universal functions


code:
def returncolor():
    pButton.config(image=PlayUp)
def playButton():
    pButton.config(image=PlayDown)
    pButton.after(200,returncolor)

rawDescription: Python Change Button Image and change it back


rawDescription: updating a numpy array efficiently when the conditions are two

description: Updating a numpy array efficiently when the conditions are two


rawDescription: Circular moving average on a tuple in Python


rawDescription: Making my NumPy array shared across processes


code:
SEND
SEND

rawDescription: How to access a class variable from another class in python?

description: Access a class variable from another class in python


code:
from flask import Flask, Blueprint

mod = Blueprint('app', __name__)

@mod.route('/')
def index():
    return "hello world"

rawDescription: Error while a Flask project turning into a package


rawDescription: Method to get two separate lists after parsing output


code:
PyMyStatus_SET_MSTATUS(self, mStatus)
PyMyStatus_GET_MSTATUS(self)
PyMyStatus_SET_mErrorString(self, mErrorString)
PyMyStatus_GET_mErrorString(self)

rawDescription: Using a new type in Python C Extension

description: Using a new type in Python C Extension


code:
html = '''
<head>
    <meta content="all" name="audience"/>
    <meta content="2006-2013 webrazzi.com." name="copyright"/>
    <title> This is title</title>
    <link href=".../style.css" media="screen" rel="stylesheet" type="text/css"/>
</head>
'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print('name={} value={}'.format('title', soup.title.text))  # <----
print('name={} value={}'.format('link', soup.link['href'])) # <----

rawDescription: Python HTML parse, gettting tag name with its value


code:
idx
df

rawDescription: Pandas Dataframe drop items where index condition is true


code:
for line in input_lines:
    m = re.match(r'''
        ^\(                  # at the beginning of the line look for a (
        [A-Z]+               # then a group of upper-case letters, i.e. OUTPUT
        \)                   # followed by a )
        \s*                  # some space
        \*                   # a literal *
        \s*                  # more space
        (?P<tag>[A-Z0-9]+)   # create a named group (tag) that matches HDMI1, ie. upper case letters or numbers
        \s*                  # more space
        (?P<nums>[\d\.]+)    # followed by a sequence of numbers and .
        $                    # before reaching the end of the line
        ''', line, re.VERBOSE)
    if m:
        break
else:  # note: this else goes with the for-loop
    raise ValueError("Couldn't find a match")
# we get here if we hit the break statement
tag = m.groupdict()['tag']    # HDMI1
nums = m.groupdict()['nums']  # 124.124.124

rawDescription: Command output parsing in Python2.7

description: Command output parsing in Python2.7


code:
hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
type(hashlib.md5("foo").hexdigest())

rawDescription: Compare result from hexdigest() to a string


code:
with open('random_text.txt', 'w') as f:
    f.write('{0:6}{1:6}{2:4}'.format('Atom','word','next'))

rawDescription: Python- Adding a specified width to strings


code:
import generic_stuff
from customer_module import ThisCustomerData, other_feature, yet_more

rawDescription: Where to put rules for creating a map between two data sets?


code:
lat = request.args.get('lat')
long = request.args.get('long')

rawDescription: Send Google Maps marker position to Flask whe dragged


rawDescription: How to generate simple polygons with equal area but varying edge

description: Generate simple polygons with equal area but varying edge


code:
"""
This script:
    1) prompts the user to enter a string
    2) performs modifications to the entered string
    3) stores the modified string into a file
"""
def get_input():
    # get user input
    user_entry = raw_input('Enter a string: ')

    # perform modifications to the input
    modified_data = user_entry + '...'

    # store the modified input into a file
    f = open('output_from_1_script.txt', 'w')
    f.write(modified_data)
    f.close()

rawDescription: How to automate the execution of several inter-dependent Python scripts

description: Automate the execution of several inter-dependent Python scripts


code:
dirs = []
for d in os.listdir('.'):
    if os.path.isdir(d):
        dirs.append(d)

rawDescription: How to get the newest directory in Python

description: Get the newest directory in Python


code:
mytuple = (1,2,3,4,5)
len(mytuple)

rawDescription: Getting the length of an array in Python


code:
import pandas as pd
import numpy as np
from scipy import optimize
from scipy import interpolate
import matplotlib.pyplot as plt

def find_intersections(x1, y1, x2, y2):
    x1 = np.asarray(x1)
    y1 = np.asarray(y1)
    x2 = np.asarray(x2)
    y2 = np.asarray(y2)
    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 x_guess in x_mid:
        root, infodict, ier, mesg = optimize.fsolve(
            pdiff, x_guess, full_output=True)
        # ier==1 indicates a root has been found
        if ier == 1 and x_min < root < x_max:
            roots.add(root[0])
    x_roots = np.array(list(roots))
    y_roots = p1(x_roots)
    return x_roots, y_roots

df = pd.DataFrame({
    'SomeNumber': [0.85, 0.98, 1.06, 1.1, 1.13, 1.2, 1.22, 1.23, 1.31, 1.43],
    'Events': [24, 39, 20, 28, 20, 24, 26, 29, 30, 24],
    'Amount': [35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78]},
                  columns=['Amount', 'Events', 'SomeNumber'])

df = df.sort('SomeNumber')

x = df['SomeNumber']
y = df['Amount']/df['SomeNumber']

df_below = df[df['Events'] < y]
df_above = df[df['Events'] >= y]

x_coords = [df_below['SomeNumber'].min(), df_above['SomeNumber'].min()]
y_coords = [df_below.ix[df_below['SomeNumber'].idxmin(), 'Events'],
            df_above.ix[df_above['SomeNumber'].idxmin(), 'Events']]

x_roots, y_roots = find_intersections(x, y, x_coords, y_coords)

plt.plot(x, y, label='Potential Events')
plt.scatter(x, df['Events'], label='Actual Events')
plt.plot(x_coords, y_coords)
plt.scatter(x_roots, y_roots, s=50, c='red')
plt.xlabel('Some Number')
plt.ylabel('Events')
plt.legend(loc='upper right')
plt.show()

rawDescription: Python Pandas MatPlotLib Find The Intersection Of Two Lines (One Curved, One Straight)


code: return fib(n-1) + fib(n-2)

rawDescription: Memoization python function

description: Memoization python function


rawDescription: Plotting mathematica data with python

description: Plotting mathematica data with python


rawDescription: Handling attributes of a class within a numpy array


code:
components = {0:4, 0:5, 0:4}
components

rawDescription: dictionary not storing multiple values for same key

description: Dictionary not storing multiple values for same key


code: [[False]*N for _ in range(N)]

rawDescription: Modify element [0][0] in a Python 2D list


code:
def big_keys(dictionary, value):
  return [k for k, v in dictionary.iteritems() if v > value]

rawDescription: hints and stepping stone on how to tackle this

description: Hints and stepping stone on how to tackle this


rawDescription: Finding the top 10 and converting it from centimeters to inches - Python


code:
for pair in itertools.combinations(d['people'], 2):
    first, second = pair
    if first[0] == second[0]:
        g.connectThem(first, second)

rawDescription: Python: Comparison between list items that isn't redundant


code:
a.sort(key=lambda s: datetime.strptime(s[:10], '%m/%d/%Y'))
a

rawDescription: sorting a list containing dates as a substring

description: Sorting a list containing dates as a substring


rawDescription: Output issue calculating moving average

description: Output issue calculating moving average


code:
with open("numbers.txt") as f:
    odd,even = 0, 0
    for num in f:
        num = int(num)
        if num % 2:
            odd += 1
        else:
            even += 1

print("Total amount of even numbers: {}".format(even))
print("Total amount of odd numbers: {}".format(odd))

rawDescription: How do I determine how many odd and even numbers are in a text file?

description: Determine how many odd and even numbers are in a text file


rawDescription: Convert SQL into json in Python

description: Convert SQL into json in Python


code:
my_array_1 = create_list_and_fix_max_and_min(10)
my_array_2 = create_list_and_fix_max_and_min(20)
the_smart_way(my_array_1)

rawDescription: Python Alternatives to Global Variables

description: Python Alternatives to Global Variables


code:
for element in itertools.product(*d.values()):
    sortedList = sorted(list(element))

rawDescription: Remove outer list from list of list in python


code:
from pyramid.view import view_config

class MyObject(object):
    def __init__(self, x):
        self.x = x

    def __json__(self, request):
        return {'x':self.x}

@view_config(renderer='json')
def object(request):
    request.response.location = "http://LocationToRedirectTo.com"
    return MyObject(1)

# the JSON value returned by ``object`` will be:
#    {"x": 1}

rawDescription: Why isn't HTTPFound redirecting the page


rawDescription: Python list of dictionaries issue

description: Python list of dictionaries issue


code:
from selenium.webdriver.support import expected_conditions as EC

class wait_for_display(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            element = EC._find_element(driver, self.locator)
            return element.value_of_css_property("display") == "inline-block"
        except StaleElementReferenceException:
            return False

rawDescription: make selenium driver wait until elements style attribute has changed

description: Make selenium driver wait until elements style attribute has changed


rawDescription: Matplotlib: Pcolor creates huge images

description: Matplotlib: Pcolor creates huge images


code: myLang = 'en' if lang == 'en' else ('de' if lang == 'ger' else 'fa')

rawDescription: Using conditions in variable assignments in Python


code:
from collections import defaultdict

seen = set()
drepr = lambda d: tuple(sorted(d.items()))

output = defaultdict(list)

for el in input:
    if drepr(el) not in seen:
        output[el['id']].append(el)
        seen.add(drepr(el))

rawDescription: Fastest way to create dict from a large list of Dict


code: list_of_sets = [set() for i in range(domain_number)]

rawDescription: comparing dynamic number of lists (non-equal length) for common entries in Python

description: Comparing dynamic number of lists (non-equal length) for common entries in Python


code:
subkeys = []
while key:
    subkeys.append(key & 0xffffffff)
    key >>= 32

if not subkeys: subkeys = [0] # Handle 0 case
subkeys.reverse() # Use same order as before (BUT SEE BELOW)

rawDescription: Refactor this block cipher keying function


code:
from collections import defaultdict

grouped = defaultdict(list)

for person in inputlist:
    grouped[person['person_id']].append(person)

grouped = grouped.values()

rawDescription: Group list of dictionaries to list of list of dictionaries with same property value


code: id, amount, *p_values = [int(i) for i in s.split()]

rawDescription: Unpack strip into combination of integer and list


code:
context = decimal.Context(prec=1000)

with decimal.localcontext(context):
    # here decimal uses 1000 digits for computations
    pass

# here the default context is restored.

rawDescription: How to define a decimal class holding 1000 digits in python?

description: Define a decimal class holding 1000 digits in python


code: issubclass(type(other), Vec)

rawDescription: using isinstance () gives me True , using type() gives me False in Python

description: Using isinstance () gives me True , using type() gives me False in Python


code: string.split(pattern, 1)[0]

rawDescription: Slice a string after a certain phrase?

description: Slice a string after a certain phrase


code:
df['rkGood'] = 0
df.loc[df.rank.between(20, 40, inclusive=True), 'rkGood'] = 1

rawDescription: Pandas and dataframe: How to transform a ordinal variable in a binary variable?


code:
def check(s):
    odd_counts = (count for count in Counter(s).itervalues() if count % 2 == 1)
    try:
        next(odd_counts)  # Fails if there is no odd count
        next(odd_counts)  # Fails if there is one odd count
    except StopIteration:
        return True
    else:
        return False

rawDescription: Fast and pythonic way to find out if an anagram is a palindrome?


code:
s = "cat goose  mouse horse pig cat cow"
re.sub(r'^((?:(?!cat).)*cat(?:(?!cat).)*)cat', r'\1Bull', s)

rawDescription: How to find and replace nth occurence of word in a sentence using python regular expression?

description: Find and replace nth occurence of word in a sentence using python regular expression


code:
from itertools import product
help(product)

rawDescription: How to optimize the memory and time usage of the following algorithm in python

description: Optimize the memory and time usage of the following algorithm in python


rawDescription: Removing spaces from astring within a CSV in python


rawDescription: easy way of getting number of bits from a numpy type?

description: Easy way of getting number of bits from a numpy type


code: list(itertools.chain(bs, jn))

rawDescription: lambda - 'QuerySet' object has no attribute 'xxx'

description: Lambda - 'QuerySet' object has no attribute 'xxx'


code:
from struct import pack,unpack

def modswap(num):
    tmp=bytearray(pack("f",num))
    tmp[0],tmp[1],tmp[2],tmp[3] = tmp[2],tmp[3],tmp[0],tmp[1]
    return unpack('f',tmp)

rawDescription: How do I rearrange bytes in a bytearray in Python?

description: Rearrange bytes in a bytearray in Python


code:
def rec(currentObject, joiner=", ".join):
    if isinstance(currentObject, list):
        return joiner([rec(item) for item in currentObject])
    elif isinstance(currentObject, dict):
        return joiner([rec(item) for item in currentObject.values()])
    elif isinstance(currentObject, str) or isinstance(currentObject, unicode):
        return currentObject
    else:
        raise TypeError("Unexpected type : {}".format(type(currentObject)))

rawDescription: Python:How to recursively store all the value of hash of hash into a string ?


code:
session.query(Shots) \
    .filter_by(event_id=event_id) \
    .count()

rawDescription: How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?

description: Model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)


code:
import glob

file_list = glob.glob('./texts' + '/*.txt')

# create document list:
documents = []
for filename in file_list:
    with open(filename, 'r') as f:
        documents.append(f.read()) # option 1, to get a direct string
        # documents.append(f.readlines()) # option 2, to get a list of lines
        # documents.append([item.strip() for item in f.readlines()]) # option 3, to get a list of lines with no linefeeds
        # documents.append(f.read().replace('\n', ' ') # option 4, to get a direct string, linefeeds replaced with spaces

rawDescription: Python: How to read a directory of texts into a list


code:
def temptask(n):
    header=list(tempsubtask.si(i) for i in range(n))
    callback=templink.si('printed at last?')
    r = celery.Progresschord(celery.group(header))(callback)
    return r

rawDescription: How to track the progress of individual tasks inside a group which forms the header to a chord in celery?

description: Track the progress of individual tasks inside a group which forms the header to a chord in celery


rawDescription: Python- best way to pass variable arguments to subprocess.call


rawDescription: How can I make a method takes the value(s) from another method from within the same class in Python

description: Make a method takes the value(s) from another method from within the same class in Python


code:
import csv

with open("class_a.txt") as file:
    csv_reader = csv.reader(file)
    sorted_list = sorted(csv_reader, key=lambda row: int(row[1]), reverse=True)

for name, score in sorted_list:
    print("{0}'s Score = {1}".format(name, score))

rawDescription: Sorting numerical data from text file high to low (Python)


code:
def toplevel(func):
  """A sync tasklet that sets a fresh default Context.

  Use this for toplevel view functions such as
  webapp.RequestHandler.get() or Django view functions.
  """

rawDescription: Using @ndb.tasklet or @ndb.synctasklet in Google App Engine


rawDescription: How can I compress a folder and email the compressed file in Python?

description: Compress a folder and email the compressed file in Python


code:
for tool in find_tools():
    def __tool(*arg):
        validate_args(tool, args)
        return execute_tool(tool, args)
    __tool.__name__ = tool.name
    __tool.__doc__ = compile_docstring(tool)
    setattr(module, tool.name, __tool)

rawDescription: Dynamic function docstring

description: Dynamic function docstring


code:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

x=np.linspace(30,390,288)
y = np.linspace(-90, 90, 234)
xg, yg = np.meshgrid(x, y)

fig = plt.figure()

for j in xrange(0,3):
        a = fig.add_subplot(3,2,j+1)
        m = Basemap(projection='mill', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=30,urcrnrlon=390, resolution='c', ax=a)
        m.drawcoastlines() # Just put something on the map - doesn't need to be your complex contour plot
        x, y = m(xg,yg)

        #You can see the problem with using hard-coded 30,390 if you print this
        #x=30 and x=390 are both in the lowest 0.001% of the x axis
        #print x

        xlab=np.concatenate([np.arange(30,181,30),np.arange(-150,31,30)])
        plt.xticks(np.linspace(30,390,13),xlab)

        #Working version commented below
        #plt.xticks(np.linspace(min(x[0]),max(x[0]), len(xlab)),xlab)
        plt.tick_params(labelsize=8)

plt.show()

rawDescription: Python: xticks and labels stuck on one side of the subplot


code:
def from_bytes (data, big_endian = False):
    if isinstance(data, str):
        data = bytearray(data)
    if big_endian:
        data = reversed(data)
    num = 0
    for offset, byte in enumerate(data):
        num += byte << (offset * 8)
    return num

rawDescription: Unable convert to int from bytes

description: Unable convert to int from bytes


code: d = {tup[tup[0]]: tup for tup in list_o_tuples}

rawDescription: Initialising a large dict with unknown keys? Is there a better way than this?


code:
class BuyFilterView(PaginationMixin, MultipleObjectMixin, TemplateView):
    template_name = "buy_filter.html"
    paginate_by = 50

    def get_context_data(self, **kwargs):
        context = super(BuyFilterView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        context['goods'] = ProductFilter(request.GET,
                                         queryset=Goods.objects.exclude(price=''))
        return context

rawDescription: How to pass queryset with exclude param in django-filter extension

description: Pass queryset with exclude param in django-filter extension


code: idx = np.vstack(np.triu_indices(n, 1)).T

rawDescription: Combinations of features using Python NumPy


code:
def blacklistServer(self, menuitem, *ignore):
    # you have to modify *get_selected_ids* so it returns the values you need for
    # blacklisting.
    values = self.get_selected_ids()
    blacklist = set(values)
    self.saveBlacklist(blacklist)

rawDescription: Sending treeview information from button_press_event in pygtk


code:
r=requests.post('https://api.openfigi.com/v1/mapping',
                headers={"Content-Type": "text/json"},
                json=data)

rawDescription: convert curl to python

description: Convert curl to python


code:
cl = (ser.notnull() & (ser != 0))
cl

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


code:
import numpy as np
y = np.zeros(4,dtype=('a4,int32,float64'))
y = np.append(y, np.array([("0",7,24.5)], dtype=y.dtype))

rawDescription: Adding records to a numpy record array

description: Adding records to a numpy record array


code:
s = b"Can you count to three or sing 'ABC?'"
str(buffer(s, 10))

rawDescription: Is there a way to use a memoryview with regexes in Python 2?


code:
foo = FileClass('foo.txt')
type(foo)
foo = FileClass('foo.rtf')
type(foo)

rawDescription: How to create a hidden factory?

description: Create a hidden factory


code:
import time

def g(x): # destroy function
    del model
    time.sleep(1) # to ensure, this worker does not pick too many
    return None

rawDescription: Initializing and destorying Python multiprocessing workers


code: df.groupby(['a', 'b', 'c']).agg(lambda col: ','.join(col))

rawDescription: Python Pandas: concatenate rows with unique values


rawDescription: How to compare two arrays in python with 1s for hits and 0s for non-hits?

description: Compare two arrays in python with 1s for hits and 0s for non-hits


code:
while True:
   if temperature > 30:
      output = 1
   else:
      output = 0
   #update database or file with output

rawDescription: HTML interface for a python program running in loop


rawDescription: Aliased name of a Function in Python

description: Aliased name of a Function in Python


code:
urlpatterns = patterns('',
    url(r'^custom_search$', CustomSearchView.as_view(), name='custom_search'),
)

rawDescription: How to display search results(django+haystack+elasticsearch) on the SAME page?

description: Display search results(django+haystack+elasticsearch) on the SAME page


code:
import csv

with open('sample.csv') as f:
    with open('new_file.txt', 'w') as w:
        c = [r for r in csv.reader(f, delimiter=',')]
        data = [
            item[0] * 14 + item[1] for item in
                [map(int, row[2].split('-', 1)) for row in c]
        ]
        for line, d in zip(c, data):
            for l in line:
                w.writelines(str(l) + ',')
            w.writelines(str(d))
            w.writelines('\n')

rawDescription: How to convert hyphenated weights to pounds in csv

description: Convert hyphenated weights to pounds in csv


code:
import datetime
def get_most_recent(data):
    lst = data[jobs]
    newlst = sorted(lst,key=lambda x:datetime.datetime.strptime(x['startTime'],'%a %d %b %Y %H:%M:%S %Z'),reverse=True)
    recentdate = None
    nowd = datetime.datetime.now()
    retlist = []
    for i in newlst:
        d = datetime.datetime.strptime(i['startTime'],'%a %d %b %Y %H:%M:%S %Z')
        if recentdate is not None:
             if d == recentdate:
                 retlist.append(i)
             else:
                 break;
        elif d < nowd:
            recentdate = d
            retlist.append(i)
    return retlist

rawDescription: How do I get the recent json object based on datetime value?

description: Get the recent json object based on datetime value


rawDescription: Regex. Match words that contain special characters or 'http://'


code:
def get_attrs_list(self):
    return self.__dict__.values()

rawDescription: returning a list from an objects elements?

description: Returning a list from an objects elements


code: colormap[categories]

rawDescription: Using multiple colors in matplotlib plot


code:
def substrings(s, min_length=1):
   for length in range(min_length, len(s)+1):
     for start in range(len(s) - min_length + 1):
        yield s[start:start+length]

rawDescription: Given a list of words, identify all identical substrings of length 4 or greater


code:
data[year] = {}
data[year][month] = [day]

rawDescription: Which data structure to use in Python to store data like this?


rawDescription: Inside a range how can I internally count up to 3?


rawDescription: How do I remove hex values in a python string with regular expressions?

description: Remove hex values in a python string with regular expressions


code:
def genfield():
    for line in open('data.txt'):
        yield '0,' + line

rawDescription: Creating numpy array with empty columns using genfromtxt


code:
class LocalSettings(Settings):
    def __init__(self, foo=None, bar=None):             # in Python 3,
        super(LocalSettings, self).__init__(foo, bar)   # super().__... works
        self.foo = foo if foo is not None else True

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


code: float(b - a) / n

rawDescription: divide by zero encountered in double_scalars for derivative calculations

description: Divide by zero encountered in double_scalars for derivative calculations


code:
index = 0
for data, curr_color in zip(datasets, colors):
    ax.scatter(np.log2(data[:, 0]), np.log2(data[:, 1]),
                   np.log2(data[:, 2]), 'o', c=curr_color, label=my_labels[index])
    ax.plot([], [], 'o', c = curr_color, label=my_labels[index])
    index += 1

rawDescription: plotting 3d scatter in matplotlib

description: Plotting 3d scatter in matplotlib


rawDescription: How to split a string by multiple characters and keep the split chars in return value?

description: Split a string by multiple characters and keep the split chars in return value


code:
class Task(object):
    def run(self):
        # before
        self.do_run()
        # after

class MyTask(Task):
    def do_run(self):
        ...

task = MyTask()
task.run()

rawDescription: Python: Decorating a class method that is intended to be overwritten when inherited


code: my_new_list = [m for m in my_list if 'blahblah' in m]

rawDescription: Python: Having difficulty filtering out strings containing certain substrings


code:
A
X
Y

rawDescription: Build array from other array and table of values (Python)


code:
def get_X_of_Y (x, y):
    return filter(lambda item: item[1]==x and item[2]==y, people)

rawDescription: Efficiently find objects satisfying relationship


code:
def manual(arr):
    out = []
    count = 0
    for x in arr:
        if x == 1:
            count += 1
        if x == 0:
            count = 0
        out.append(count)
    return out

def test():
    for w in [1, 2, 10, 10**4]:
        for trial in range(100):
            for vals in [0,1],[0,1,2]:
                b = np.random.choice(vals, size=w)
                assert (rcount(b) == manual(b)).all()
    print("hooray!")

rawDescription: Cumulative counts in NumPy without iteration


code:
def spamify(message):
    print(message % spam)

rawDescription: How to set the global value of % in python

description: Set the global value of % in python


code:
def test1(t_arg=None, t_arg2=None):
    return t_arg + sum(t_arg2)

def test2(t_arg=None):
    return t_arg

res = test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])
print(res)  # 6

test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = call_dict(test_dict)
print(res)  # 6

rawDescription: Read python dict or yaml and call as python function with arguments and objects


code:
from datetime import datetime

d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S.%f')

rawDescription: Convert email (rfc 2822) date string to another format (ISO 8601 timestamp) in Python 2.7


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

# generation of a dictionary of (title, images)
number_of_im = 6
figures = {'im'+str(i): np.random.randn(100, 100) for i in range(number_of_im)}

# plot of the images in a figure, with 2 rows and 3 columns
plot_figures(figures, 2, 3)

rawDescription: Multiple figures in a single window

description: Multiple figures in a single window


rawDescription: How can I use OpenCV (Python) to read a video file WITHOUT looping (Mac OS)?

description: Use OpenCV (Python) to read a video file WITHOUT looping (Mac OS)


code:
folder_counter = sum([len(folder) for r, d, folder in os.walk(path)])
                        # ^ here          # ^ and here
file_counter = sum([len(files) for r, d, files in os.walk(path)])
                      # ^ vs. here     # ^ and here

rawDescription: Count the number of folders in a directory and subdirectories


code:
def item_copy(request, id):
    new_item = get_object_or_404(MyModel, pk = id)
    new_item.pk = None #autogen a new pk (item_id)
    new_item.name = "Copy of " + new_item.name #need to change uniques

    form =  MyForm(request.POST or None, instance = new_item)

    if form.is_valid():
        form.save()
        return redirect('my_view')

    context = {
        "form": form,
        #other context
    }

    return render(request, "form.html", context)

rawDescription: Django: copy a model object using views and forms


code:
import time
import progressbar
import threading

def crawl_data(data):
    # sleep for 10 seconds
    time.sleep(10)
# end of def crawl_data

def main():
    data = 'some data'
    widgets = ['Working: ', progressbar.AnimatedMarker(), ' ',
                   progressbar.Timer()]
    pbar = progressbar.ProgressBar(widgets=widgets)
    # creating thread to run crawl_data()
    thread = threading.Thread(target=crawl_data,
                              args=(data,))
    thread.daemon = True
    # starting thread and progress bar
    thread.start()
    pbar.start()
    i = 1
    # continuous loop until crawl_data thread is not alive
    while True:
        # update every second
        time.sleep(1)
        pbar.update(i)
        if not thread.is_alive():
            pbar.finish()
            break
        # end of if thread is not alive
        i += 1
    # end of continuous loop until crawl_data thread is not alive
    # prints a new line
    print
# end of def main

# run main
main()

rawDescription: Use of python progress bar in script

description: Use of python progress bar in script


code:
def mysub(seq, acc=None):
    seq = iter(seq)
    if acc is None:
        item = next(seq, None)
        if item is None:
            return acc
        acc = item

    item = next(seq, None)
    if item is None:
        return acc
    return mysub(seq, acc - item)

rawDescription: Subtraction(list) recursively in Python 3


code:
def main():
    data = [...]
    pool = ThreadPool(45)
    stop_flag = Event()
    RepeatTimer(60,display_status,stop_flag).start()
    results = pool.map(make_job, data)
    pool.close()
    pool.join()
    stop_flag.set()

rawDescription: Is it possible to execute function every x seconds in python, when it is performing pool.map?


code:
from PySide import QtGui
from PySide import QtCore

def launch_window():
    global window
    # Creates a new window
    window=QtGui.QWidget()
    window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    window.setWindowTitle('Window 1')
    # Creates a layout for the window and populates it with a Qlabel
    window.grid=QtGui.QGridLayout()
    window.label=QtGui.QLabel("Hello")
    window.grid.addWidget(window.label,0,0)
    # Sets the layout to the window and sets the size of the window
    window.setLayout(window.grid)
    window.setFixedSize(window.sizeHint())
    # Starts the thread
    myThread.start()

class running_operation(QtCore.QObject):

    # Creates a QtCore Signal for when the operation is over (if you want something to happen when the function ends processing)
    finish_operation=QtCore.Signal()
    # Wraps the function to run inside a QtCore Slot (MANDATORY !)
    @QtCore.Slot()
    # Function I wanted to run in a separate thread ! NOW IT RUNS !
    def run_operation(self):
        global counter
        counter=0
        # Setting a timer that fires every second and calling at the same time the function print_counter()
        global timer
        timer=QtCore.QTimer(self)
        timer.timeout.connect(self.print_counter)
        timer.start(1000)

    def print_counter(self):
        global counter
        global timer
        # A random function to execute just for testing purposes, the counter keeps counting up every second.
        if counter <= 3 :
            counter += 1
            print(counter)
        elif counter == 4 :
        # At seconds, we emit the finish_operation signal.
            counter += 1
            self.finish_operation.emit()
        # At 5 seconds and more, the counter keeps counting up again every second (just to check if the thread actually exited)
        else:
            counter += 1
            print(counter)

# Creates a new thread
myThread=QtCore.QThread()
# Creates the object "operations"
operations = running_operation()
# Moves the object to the thread
operations.moveToThread(myThread)
# Connects the QThread.started signal function to the run_operation() function.
myThread.started.connect(operations.run_operation)
# Connects the finish_operation signal to quitting the thread.
operations.finish_operation.connect(myThread.quit)

rawDescription: What is the correct way to use QThreads?

description: What is the correct way to use QThreads


code:
from StringIO import StringIO
import pandas
datastring = StringIO("""\
time_period    total_cost    total_revenue
7days          150           250
14days         350           600
30days         900           750
7days          180           400
14days         430           620
""")

data = pandas.read_table(datastring, sep='\s\s+')

data['total_cost_avg'] = data.apply(
    lambda row: row['total_cost'] / float(row['time_period'][:-4]),
    axis=1
)

rawDescription: Conditionally perform calculation on pandas dataframe


code: expr = 2*x - 7*y

rawDescription: SymPy express variable in terms of another


rawDescription: np.mean for rows with specific values across multiple columns

description: Np.mean for rows with specific values across multiple columns


code:
# this works because the ID does exist
p = Jpiece.objects.get(pk=3)
p.save()

rawDescription: Django autocategorize in m2m field

description: Django autocategorize in m2m field


code: cost = (random.random() * spread + min(accuracy, (1-spread))) * user_specified_value

rawDescription: Generate random values based on a variable in Python


code:
...
import mytestmodule

def btnCallback():
    #extract the textbox variable
    var = stringadacercare.get()

    progressbar.start()

    #call the main function from the test module
    mytestmodule.main(var)

    progressbar.stop()

...

rawDescription: I would like to pass the value entered into the textbox to a python program


code:
def gettextbyxpath(tree, xpath):
    node = tree.xpath(xpath)[0]
    try:
        text = etree.tostring(node, method="text", encoding='UTF-8').strip()
        text = '\n'.join(line.strip() for line in text.split('\n') if line.strip())
    except:
        text = 'ERROR'
    return text

rawDescription: Python: re.sub changes nothing

description: Python: re.sub changes nothing


code:
patt = re.compile(r'STR:(\w+)')
patt.findall(s)

rawDescription: Extracting a variable from a function call in Python


code:
Ctypes
import ctypes

lib = ctypes.CDLL("lib.so")

class foo(ctypes.Structure):
  _fields_ = [('data', ctypes.POINTER(ctypes.c_uint32))]

bar = lib.bar
bar.argtypes = [ctypes.POINTER(foo)]

# Call the function with the argument:

arg = foo()

with open('input.dat', 'rb') as f:
  arg.data = ctypes.cast(ctypes.create_string_buffer(f.read()), ctypes.POINTER(ctypes.c_uint32))

bar(ctypes.byref(arg))

rawDescription: Store file contents in a buffer and assign it to a pointer in Python


rawDescription: What is the pythonic way to this dict to list conversion?


code:
embossed = objectify.Element('embossed')
embossed.append(objectify.Element('line'))
embossed.line[-1] = 'Test Line'
embossed.append(objectify.Element('line'))
embossed.line[-1] = 'Test Line 2'

rawDescription: How to create the same XML element 3 times with Python LXML Objectify

description: Create the same XML element 3 times with Python LXML Objectify


code:
import re
s = "RENAME_JAVASCRIPT(18), RENAME_IMAGE(7), MINIFY_JAVASCRIPT(26), (1), JAVASCRIPT_HTML5_CACHE(19), EMBED_JAVASCRIPT(1), RENAME_CSS(3), (1), IMAGE_COMPRESSION(7), RESPONSIVE_IMAGES(6), ASYNC_JAVASCRIPT(2);TextTransApplied:RENAME_JAVASCRIPT(18), RENAME_IMAGE(7), MINIFY_JAVASCRIPT(26), (1), JAVASCRIPT_HTML5_CACHE(19), EMBED_JAVASCRIPT(1), RENAME_CSS(3), (1), IMAGE_COMPRESSION(7), RESPONSIVE_IMAGES(6), ASYNC_JAVASCRIPT(2);TagTransAttempted:(8), ASYNC_JAVASCRIPT(61);TagTransFailed:ASYNC_JAVASCRIPT(42);TagTransApplied:(8), ASYNC_JAVASCRIPT(19);"
for i in re.findall(r'[A-Z]+(?:_[A-Z\d]+)+\(\d+\)', s):
    print(i)

rawDescription: Regex to match the following patterns

description: Regex to match the following patterns


code:
#models.py
class Dialog(Model):
    info1 = models.TextField()
    info2 = models.TextField()

#forms.py
class DialogFormSetHelper(FormHelper):
 def __init__(self, *args, **kwargs):
    super(DialogFormSetHelper, self).__init__(*args, **kwargs)
    self.form_tag = False    # This line removes the '<form>' tag
    self.disable_csrf = True # No need to insert the CSRF string with each inlineform
    self.layout = Layout(
        Field('info1', rows='3'), # make sure the name of the field matches the names defined in the corresponding model
        Field('info2', rows='3')
    )

rawDescription: Django remove inline formset record in UpdateView


rawDescription: Pandas groupby date

description: Pandas groupby date


code:
import tempfile
import cherrypy as cp

class App:

    @cp.expose
    def index(self):
        return """

Upload a file

            <form action="upload" method="post" enctype="multipart/form-data">
            filename: <input type="file" name="my_file" />

            <input type="submit" />
            </form>

        """

    @cp.expose
    def upload(self, my_file):
        return "The path is %s" % my_file.file.name

class CustomPart(cp._cpreqbody.Part):
    """
    Custom entity part that it will alway create a named
    temporary file for the entities.
    """
    maxrambytes = 0 # to ensure that it doesn't store it in memory

    def make_file(self):
        return tempfile.NamedTemporaryFile()

if __name__ == '__main__':
    cp.quickstart(App(), config={
        '/': {
            'request.body.part_class': CustomPart
        }
    })

rawDescription: CherryPy get uploaded file's temporary location


code:
import base64

class ModuledString(object):
    def __init__(self, string):
        self.string = string

    def __getattr__(self, attrname):
        def func(*args, **kwargs):
            result = getattr(self.module, attrname)(self.string, *args, **kwargs)
            self.string = result
            return result
        return func

    def __str__(self):
        return str(self.string)

rawDescription: How to add abilities to strings in Python

description: Add abilities to strings in Python


code:
def float_range(start=0, stop=None, step=1):
    while start <= stop:
        yield start
        start += step

rawDescription: Creating lists from data file

description: Creating lists from data file


code:
import re
...
eof = re.compile(r'\s*\{\s*"diag":.*,\s*"status":.*\}') # compile the regex
...

rawDescription: Read until an only partially known line - Python


code:
for row in range(1, row+1):
    for col in range(1,columns+1):
        print("{: >3}".format(row * col), end="")
    print()

rawDescription: Allignment of multiplication table in Python


code:
import numpy as np
a = np.loadtxt(filename, delimiter=',',usecols=(1,2,3,4),
               skiprows=1, dtype=float)

rawDescription: Recomended way to create a matrix containing strings in python


code:
class MultiSourceField(serializers.Field):
    """
    A custom field to use when you want to
    join multiple sources into a single field.
    Example :
        my_field = MultiSourceField(source=["attr1.subattr", "attr2.subattr"])
    It can also handle serializers, a small example :
        rel_field = MultiSourceField(source=[Serializer(source="rel"), "attr2"])
    """

    def field_to_native(self, obj, field_name):
        if obj is None:
            return self.empty

        sources = self.source
        value = []
        for source in sources:
            if isinstance(source, serializers.BaseSerializer):
                value += source.field_to_native(obj, "")
            else:
                #setting self.source to source in order to use the parent method
                self.source = source
                value.append(super(MultiSourceField, self).field_to_native(obj,
                    field_name))
                #reverting self.source after the parent method call
                self.source = sources
        return value

rawDescription: django REST framework multi source field

description: Django REST framework multi source field


code:
while play:
    # Checks if window exit button pressed
    for event in pygame.event.get():
         ...

    camera.update(ship)
    # Update
    ship.update()

    # Print Background/Sprites
    screen.fill(WHITE)

    backgroundGroup.draw(screen)
    shipGroup.draw(screen)

    # Limits frames per iteration of while loop
    ...

rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
import re
string = """
for i in x:
    for y in z[i]:
        print y
"""
s2 = "for"
[match.start() for match in re.finditer(re.escape(s2), string)]

rawDescription: Given 2 strings find the indexes where one string occurs in another


code:
def wrapper(instance, command, *args, **kwargs):
            original_value = func(instance, command) #call func here
            return "%s, %s! %s!\n%s, %s!" % (
                self.greeting,
                instance.name,
                original_value,
                self.farewell,
                instance.name
            )

rawDescription: Python class decorators with arguments, but decorated function is not being run


code:
class CharacterRange(object):
    def __init__(self, chars, size):
        self.chars, self.size = chars, size

    def __len__(self):
        return len(self.chars) ** self.size

    def __getitem__(self, item):
        if item < 0:
            item = len(self) + item
        if not 0 <= item <= len(self):
            raise IndexError('Index out of range')

        result = []
        for i in range(self.size):
            item, index = divmod(item, len(self.chars))
            result.append(self.chars[index])
        return ''.join(result[::-1])

rawDescription: Generate 2 Unique but random Elements in a List


code:
import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent

# Set up a tap, with type of tap, location, options and event mask
tap = Quartz.CGEventTapCreate(
    Quartz.kCGSessionEventTap, # Session level is enough for our needs
    Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter
    Quartz.kCGEventTapOptionListenOnly, # Listening is enough
    Quartz.CGEventMaskBit(NSSystemDefined), # NSSystemDefined for media keys
    keyboardTapCallback,
    None
)

runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
    Quartz.CFRunLoopGetCurrent(),
    runLoopSource,
    Quartz.kCFRunLoopDefaultMode
)
# Enable the tap
Quartz.CGEventTapEnable(tap, True)
# and run! This won't return until we exit or are terminated.
Quartz.CFRunLoopRun()

rawDescription: system wide shortcut for Mac OS X

description: System wide shortcut for Mac OS X


code:
def _eval_power(self, expt):
    if expt.is_positive:
        return self
    ...

rawDescription: Sympy classes Zero, One and NegativeOne, why they exist?


code:
df = pd.read_csv('sample.csv', dtype={'uid':str})
df.set_index('uid', inplace=True)

rawDescription: How to read index data as string with Python pandas?

description: Read index data as string with Python pandas


code:
with open('a.txt') as f:
   for line in f:
      if '\xce\xb5' in line:
          print(line)

rawDescription: Reading ε using python

description: Reading ε using python


code:
def populateCBs(self, instance):
    print(instance)
    if instance:
        for key, item in instance.items():
            if item:
                getattr(self, key).setCheckState(QtCore.Qt.Checked)

rawDescription: Pyside restore checkbox state from dict

description: Pyside restore checkbox state from dict


code:
s="""
First Rank Title Score
A      1    foo   100
A      2    bar   90
A      3    lime  80
A      4    lame  70
B      1    foo   400
B      2    lime  300
B      3    lame  200
B      4    dime  100
"""
df = pd.read_csv(StringIO(s),
                 sep='\s+',
                 index_col=["First", "Rank"])

rawDescription: Python Pandas slice multiindex by second level index (or any other level)


rawDescription: How to list latest modification time of contents of some directories?

description: List latest modification time of contents of some directories


code: get_static_path(request, 'static')

rawDescription: How to get file path of a add_static_view() in Pyramid

description: Get file path of a add_static_view() in Pyramid


rawDescription: Regex in python seems to be not working with some hyphen


code:
# right after connect
db.row_factory = sqlite3.Row

def find():
    cursor = db.cursor()
    searchname = str(input('Enter name of product: '))
    sql = "SELECT * FROM items WHERE name = '%s';" % searchname.strip()
    cursor.execute(sql)
    a = cursor.fetchall()
    for row in a:
        print(row['ID'])

rawDescription: split database record into variables

description: Split database record into variables


rawDescription: D3 vs Scipy (Voronoi diagram implementation)


code:
# -*- mode: python -*-

# <<< START ADDED PART
from PyInstaller.building.build_main import Analysis, PYZ, EXE, COLLECT, BUNDLE, TOC

def collect_pkg_data(package, include_py_files=False, subdir=None):
    import os
    from PyInstaller.utils.hooks import get_package_paths, remove_prefix, PY_IGNORE_EXTENSIONS

    # Accept only strings as packages.
    if type(package) is not str:
        raise ValueError

    pkg_base, pkg_dir = get_package_paths(package)
    if subdir:
        pkg_dir = os.path.join(pkg_dir, subdir)
    # Walk through all file in the given package, looking for data files.
    data_toc = TOC()
    for dir_path, dir_names, files in os.walk(pkg_dir):
        for f in files:
            extension = os.path.splitext(f)[1]
            if include_py_files or (extension not in PY_IGNORE_EXTENSIONS):
                source_file = os.path.join(dir_path, f)
                dest_folder = remove_prefix(dir_path, os.path.dirname(pkg_base) + os.sep)
                dest_file = os.path.join(dest_folder, f)
                data_toc.append((dest_file, source_file, 'DATA'))

    return data_toc

pkg_data = collect_pkg_data('<yourapplication>')  # <<< Put the name of your package here
# <<< END ADDED PART

block_cipher = None

a = Analysis(['..\\CommerceApp_withPyInstaller\\run.py'],
             pathex=['D:\\PythonProjects\\CommerceAppExe'],
             binaries=None,
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='SupplyTracker',
          debug=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               pkg_data,  # <<< Add here the collected files
               strip=False,
               upx=True,
               name='SupplyTracker')

rawDescription: Pyinstaller Jinja2 TemplateNotFound

description: Pyinstaller Jinja2 TemplateNotFound


rawDescription: Does Python have a relational join operator?


code:
from abc import ABCMeta, abstractmethod
class A(object):
    __metaclass__ = ABCMeta
    @abstractmethod
    def do_some_cool_stuff():
        ''' To override '''
        pass
    def do_some_boring_stuff():
        return 2 + 2

class B(A):
    def do_stuff():
        return 4

B()

rawDescription: Is it possible in Python to declare that method must be overriden?


code:
#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user

survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")

#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")

# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
    guessed_items = raw_input("Please choose:")
    guessed_inventory_list.append(guessed_items)

print ("You have chosen the following:", guessed_inventory_list)

# Enumerate is one of the built-in Python functions.
# It returns an enumerate object.
# In this case that object is a list of tuples (immutable lists),
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
    #the "in" is a membership test operator which will test whether
    #individual_items is in list guessed_inventory_list
    if individual_items in guessed_inventory_list:
       #finally the print statements below advise the user if they guessed an item and which position it's in.
       print("You have chosen wisely", individual_items)
       print("It's in position", t, "on the survival list")

rawDescription: comparing a list to a tuple, python 3.x - having problems getting the correct position to print

description: Comparing a list to a tuple, python 3.x - having problems getting the correct position to print


code:
import pandas as pd
data = pd.read_csv("data.csv", names=["t", "p"], parse_dates=[0])
data.to_dict()

rawDescription: Why isn't read_csv() parsing my dates?

description: Why isn't read_csv() parsing my dates


code: sum(1 for ch in u'A\u0332\u0305BC' if unicodedata.combining(ch) == 0)

rawDescription: How do I get the "visible" length of a combining Unicode string in Python?

description: Get the "visible" length of a combining Unicode string in Python


rawDescription: python for loop

description: Python for loop


code:
t = numpy.arange(81.).reshape((9,9))
numpy.lib.stride_tricks.as_strided(t, shape=(3,3,3,3), strides=(216,24,72,8))

rawDescription: Creating a 4D view on 2D array to divide it into cells of fixed size


code:
for bucket in result:
    print(bucket)

rawDescription: Merge list of timestamps in Python

description: Merge list of timestamps in Python


code:
fetched = [(1, u'01', u'Data push button1'),
    (2, u'01', u'Data push button2'),
    (3, u'01', u'Data push button3')]

rawDescription: Get component from Array sqlite

description: Get component from Array sqlite


code:
def add(a, b, c):
    print(a, b, c)

x = (1, 2, 3)
add(*x)

rawDescription: How to extract parameters from a list and pass them to a function call

description: Extract parameters from a list and pass them to a function call


code: self.crumb = self._breadcrumb(father)

rawDescription: How can I handle dynamic calculated attributes in a model in Django?

description: Handle dynamic calculated attributes in a model in Django


rawDescription: Python sort strings by count of appearances of the strings in the list


rawDescription: groupby multiple value columns

description: Groupby multiple value columns


code:
[li.xpath('string(.)').extract()[0]
 for li in sel.xpath('//*[@id="tab_description"]/ul/li')]

rawDescription: Scrapy, receive just the text from an unordered list, including text between other html tags


code:
my_list = ['a1', 'a2', 'b1', 'b2', 'a3', 'a4']
[list(group) for key, group in itertools.groupby(my_list)]

rawDescription: Python: New list grouping repeated elements from existing list


code:
@jit(nopython=True)
def dot(mat1, mat2):
    s = 0
    mat = np.empty(shape=(mat1.shape[1], mat2.shape[0]), dtype=mat1.dtype)
    for r1 in range(mat1.shape[0]):
        for c2 in range(mat2.shape[1]):
            s = 0
            for j in range(mat2.shape[0]):
                s += mat1[r1,j] * mat2[j,c2]
            mat[r1,c2] = s
    return mat

rawDescription: optimal numba implementations for matrix multiplication depends significantly on matrix size

description: Optimal numba implementations for matrix multiplication depends significantly on matrix size


rawDescription: Obtaining the label of the control of a form in Mechanize


code: product_df['month_num'] = product_df.groupby('product_desc').cumcount() + 1

rawDescription: How to increment a row count in groupby in DataFrame

description: Increment a row count in groupby in DataFrame


code:
from django.contrib.gis import models

class Example(models.Model):
    point = models.PointField()
    objects = models.GeoManager()

rawDescription: Finding models inside a set of Polygons in GeoDjango


code: labels == row

rawDescription: Boolean indexing of 2D ndarray based on row comparison


code:
import sys
sys.modules['inspect'] = None
sys._getframe = None

rawDescription: Access parent namespace in python

description: Access parent namespace in python


rawDescription: Convert variable-sized byte array to a integer/long


code:
np.column_stack((R_match[2],C_match[2]))  # Third point
np.column_stack((grps_R[2],grps_C[2]))    # Its three neighbors

rawDescription: Find a nodes 8 neighbors on a 2D grid

description: Find a nodes 8 neighbors on a 2D grid


code:
from settings import *
ROOT_URLCONF='management_urls.py'

rawDescription: Django - per-domain URLConf?

description: Django - per-domain URLConf


code:
# make sure to change the app name
ALLOWED_RELATIONSHIPS = models.Q(app_label = 'app_name', model = 'team') | models.Q(app_label = 'app_name', model = 'teammember')
class TeamFormNote(models.Model):
    content_type = models.ForeignKey(ContentType, limit_choices_to=ALLOWED_RELATIONSHIPS)
    relation_id = models.PositiveIntegerField()
    relation = generic.GenericForeignKey('content_type', 'relation_id')

rawDescription: How do you force only one relationship in django when multiple are possible?

description: Force only one relationship in django when multiple are possible


code:
aa = {"Fruit":[u'Apple',u'Banana',u'lemon'],
      "Student":[ u'pen',u'book',u'chair' ],
      "Family":[u'father',u'mother']}

obj = u'pen hahhah'
for key in aa:
    for item in aa[key]:
        if obj.startswith(item):
            print(obj + ' is in ' + key)

rawDescription: Python how to compare string in a list with dict


code: list(map(lambda x: [x[0]] + [ y[1]*y[2] for y in x[1:] ], orders))

rawDescription: How can I rewrite this map() example using list comprehension?

description: Rewrite this map() example using list comprehension


code:
from collections import deque

def tail(iterable,n=None):
    """Return an iterator over the last n items, if n is none return a iterator over all elemens
       in iterable save the first

       tail('ABCDEFG',3) --> E F G
       tail('ABCDEFG')   --> B C D E F G """
    if n is None:
        resul = iter(iterable)
        next(resul,None)
        return resul
    return iter(deque(iterable, maxlen=n))

rawDescription: how to read the lines from line 7 to line 265 in python?

description: Read the lines from line 7 to line 265 in python


code:
numpy_array = numpy.arange(9).reshape((3, 3))
confused_array = numpy.arange(9).reshape((3, 3)) % 2
mask = numpy.in1d(numpy_array, repeat_set).reshape(numpy_array.shape)
mask
~mask
numpy_array == 0
numpy_array != 0
confused_array[mask] = 1
confused_array[~mask & (numpy_array == 0)] = 0
confused_array[~mask & (numpy_array != 0)] = 2
confused_array

rawDescription: Check if values in a set are in a numpy array in python


rawDescription: Python range function: defining the length of sequence instead of the step size


rawDescription: deleting semicolons in a column of csv in python

description: Deleting semicolons in a column of csv in python


code:
f = anobj.amethod
for x in whatever():
    f(x)

rawDescription: Python performance characteristics

description: Python performance characteristics


rawDescription: python dask DataFrame, support for (trivially parallelizable) row apply?

description: Python dask DataFrame, support for (trivially parallelizable) row apply


code: sortedList=sorted(reader, key=lambda t: int( t[1] ))

rawDescription: Sorting a csv file in Python with sorted() returns values in programmer DESC order, not time DESC order


rawDescription: What is the correct way to reassign a list in Python?


rawDescription: Scrape input value from html

description: Scrape input value from html


code: sum('LL' in "".join(i) for i in permutations('AAAAAA'+'LL'))

rawDescription: Permutations of a string with two distinct characters (60 of one value and 20 of another)


rawDescription: Efficient way of appending / extracting list elements


code: spot0_list = set(zip(l1,l2,l3)[0])

rawDescription: predict the outcome numbers using a list

description: Predict the outcome numbers using a list


code:
from test import *
import App.main

# do the tests

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

rawDescription: Python - organising code and test suite

description: Python - organising code and test suite


code: weekly = [ sum(visitors[x:x+7]) for x in range(0, len(daily), 7)]

rawDescription: Find the sum of subsets of a list in python


code:
import maptlotlib.pyplot as plt
plt.triplot(points[:,0], points[:,1], triangles)
plt.plot(points[:,0], points[:,1], 'ko ')

rawDescription: Speeding up selecting sets of 3 nodes that form triangles with given min and max side length


code:
import re
re.findall('\b', 'test') # the backslash gets consumed by the python string interpreter
re.findall('\\b', 'test') # backslash is explicitly escaped and is passed through to re module
re.findall(r'\b', 'test') # often this syntax is easier

rawDescription: What does the "r" in pythons re.compile(r' pattern flags') mean?


code:
def downloadFile(filename, folder):
    #login
    ftp = FTP(myhost,myuser,passw)
    ftp.set_debuglevel(2)
    ftp.voidcmd('TYPE I')
    sock = ftp.transfercmd('RETR ' + filename)
    f = open(folder + filename, 'wb')
    while True:
        block = sock.recv(1024*1024)
        if not block:
            break
        ftp.voidcmd('NOOP')
        f.write(block)
    sock.close()

rawDescription: python ftplib transfercmd() BINARY Mode

description: Python ftplib transfercmd() BINARY Mode


code: whiskey

rawDescription: Dictionary python trouble

description: Dictionary python trouble


code:
def main():
    oldperson = Person()
    ModifyPersonToBeFriendly()
    p = Person()
    p.hello()
    # works!  But:
    oldperson.hello()
    # does not

rawDescription: How to dynamically change base class of instances at runtime?

description: Dynamically change base class of instances at runtime


code: langs.append({u'code': u'xx', u'name': u'UNKNOWN'})

rawDescription: Python: Add row to list with two columns?


code: custname.trace("w", changeLabel)

rawDescription: need assistance with Entry Tkinter in Python 2.5

description: Need assistance with Entry Tkinter in Python 2.5


code:
import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy

fig = plt.figure()
ax = plt.axes()
txt = plt.text(0.1,0.5,"My text", transform = ax.transAxes)

fig.canvas.draw()

text_bbox = txt.get_window_extent()
transform_for_second_text = offset_copy(ax.transAxes, fig,
                                        x=text_bbox.width,
                                        units="dots")

plt.text(0.1,0.5, "Second text", transform=transform_for_second_text, color="r")

plt.show()

rawDescription: Python fig.text() - retrieve the height of the text for alignment purposes


code:
next = Resource.objects.filter(date__gt=now()).order_by('date')[:1]
archive = Resource.objects.filter(date__lt=now())
qs = list(chain(archive, next))

rawDescription: Django QuerySet: filter by date, then select one more


code:
def main(*args, **kwargs):
    if "some_admin_name" in session:
        return predecorator_main_function(*args, **kwargs)
    else:
        flash("\"You shall not pass!\" - Gandalf")
        return redirect(url_for("login"))

rawDescription: What is a self-written decorator (like @login_required) actually doing?


rawDescription: Python convert String to Tuple for REST API


code:
from operator import itemgetter

sorted(tuples, key=itemgetter(-1))

rawDescription: Sorting Tuples in a descending order based on the last item given in the tuple


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

x = linspace(0.1, 2*pi, 10)
markerline, stemlines, baseline = stem(x, cos(x), '-.')
setp(markerline, 'markerfacecolor', 'b')
setp(baseline, 'color','r', 'linewidth', 2)

show()

rawDescription: Stem plot in matplotlib?

description: Stem plot in matplotlib


rawDescription: Start index at 1 when writing Pandas DataFrame to CSV


rawDescription: Get record from master table if alteast one record exists in slave/child tables using django api


code:
ax = df.plot.scatter(x=2005, y=2015)
df.set_index(2005, inplace=True)
df.trendline.sort_index(ascending=False).plot(ax=ax)
plt.gca().invert_xaxis()

rawDescription: How to add a line of best fit to scatter plot

description: Add a line of best fit to scatter plot


code:
b, a = scipy.signal.butter(N, Wn, 'low')
output_signal = scipy.signal.filtfilt(b, a, input_signal)

rawDescription: How To apply a filter to a signal in python


code:
class base(object):
    name = ""

    def __init__(self, name):
        self.user =user

    def context(self, value):
        return [value]

class override(base):
    name = "override"

    def context(self, value):
        base_context = super(override, self).context(value)
        a = ["hello", "a"] + base_context

    def description(self):
        return "override description"

rawDescription: How to return a value computed by overriding method from a subclass to it's base class method in python

description: Return a value computed by overriding method from a subclass to it's base class method in python


code:
class DTreeBuilder(object):
    def __init__(self):
        self.sigma = [[]]

    def buildDTree(self, sofar, todo):
        sal = []
        if len(todo) == 0:
            return binaryTree(sofar)
        else:
            withelt = buildDTree(sofar + [todo[0]], todo[1:])
            withoutelt = buildDTree(sofar, todo[1:])
            here = binaryTree(sofar)
            here.setLeftBranch(withelt)
            here.setRightBranch(withoutelt)
            sal += here.getLeftBranch().getValue()
            self.sigma += [sal]
            return here

rawDescription: Python: Substituting for global variables


code: elem in b2a

rawDescription: Data structure for many-many

description: Data structure for many-many


code: filter(lambda n: n is not None, (0,1,2,3,4,5,None,None,None,None,None))

rawDescription: Python Optimize Grouper Function to avoid None elements


code:
contig1
contig102

rawDescription: Sorting names containing numbers

description: Sorting names containing numbers


code:
fig, axes = plt.subplots(2)

plt.subplot2grid((1,5), (0,0), colspan=3)
# here plot something

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

plt.show()

rawDescription: Creating a subplot instead of separate plots


code:
from PyQt4 import QtGui
QtGui.QImageReader.supportedImageFormats()

rawDescription: PyQt4 jpeg/jpg unsupported image format

description: PyQt4 jpeg/jpg unsupported image format


rawDescription: Finding Great circle distances from points in dictionary


code:
d.nonzero()
z,x,y = d.nonzero()

rawDescription: Creating a 3D plot from a 3D numpy array


rawDescription: Referencing values using foreign key on flask sql-alchemy


code:
l = [1, 2, 3, 4, 5]
e = enumerate(l)
e
list(e)
list(e)

rawDescription: Enumerate function

description: Enumerate function


code: X[afield] = ma.resize(X[afield], (len(Y),) )

rawDescription: reassigning expanded recarray field

description: Reassigning expanded recarray field


code:
def test(phrase, filename):
    phrase = phrase.strip()
    with open(filename, 'r') as f:
        for line in f:
            if phrase in line:
                return 'Y'
        return 'N'

rawDescription: Python3: Finding a phrase (string) in a file


code: DS.blit(catImg, catImgRectObj.center)

rawDescription: get_rect() over an image gets shifted in pygame

description: Get_rect() over an image gets shifted in pygame


rawDescription: Converting list of tuples in functional way


code:
x = 1
import pkg.b

rawDescription: Importing package in Python

description: Importing package in Python


rawDescription: Problem in printing array of char pointer passing from Python


code:
class MetaFoo(type):
    def __iter__(self):
        for attr in dir(Foo):
            if not attr.startswith("__"):
                yield attr

class Foo(metaclass=MetaFoo):
    bar = "bar"
    baz = 1

rawDescription: Python: Is it possible to make a class iterable using the standard syntax?


code:
atb_mat = atbvec.copy()
atb_mat.resize(dim, nb)

rawDescription: Python equivalent code to MATLABs vec2mat


rawDescription: flask-login: Chrome ignoring cookie expiration?

description: Flask-login: Chrome ignoring cookie expiration


code:
"""Replaces template placeholder with values.

:param timestamp: formatted date to display
:param priority: priority number
:param priority_name: priority name
:param message: message to display
:returns: formatted string
"""

rawDescription: Using javadoc for Python documentation

description: Using javadoc for Python documentation


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

for spine in ['left', 'bottom']:
    ax.spines[spine].set_position('zero')

# Hide the other spines...
for spine in ['right', 'top']:
    ax.spines[spine].set_color('none')

ax.axis([-4, 10, -4, 10])
ax.grid()

plt.show()

rawDescription: how to move axes labels to near the arrows in matplotlib

description: Move axes labels to near the arrows in matplotlib


code:
set1 = set(array1)
array2 = [e for e in array2 if e not in set1]

rawDescription: Using arrays with other arrays in Python


rawDescription: Python - Updating dictionary in a for loop


rawDescription: numpy ndarray indexing - retrieving indexes from tuple

description: Numpy ndarray indexing - retrieving indexes from tuple


code:
if any(s in attrs["show"] for s in ("aa", "bb", "cc", "dd", "ee", "ff")):
    self.xx = xxxx

rawDescription: if command in python

description: If command in python


code:
@http_safe
def cloudflare_add_zone(ctx, url, jumpstart, organization):
    if organization:
        ctx.create_zone(url, jumpstart, organization)
    else:
        ctx.create_zone(url, jumpstart)
    click.echo('Zone successfully created: %s' % url)

rawDescription: How can I organize my code so that repeating try except clauses only exist once?

description: Organize my code so that repeating try except clauses only exist once


code:
def error_handler(msg):
    print (msg)

def execDetails(msg):
    print('ID',msg.execution.m_execId,'PRICE',msg.execution.m_price)

def commReport(msg):
    print('ID',msg.commissionReport.m_execId,'COM',msg.commissionReport.m_commission)

tws = Connection.create(port = 4001, clientId=123)
tws.register(execDetails, message.execDetails)
tws.register(commReport, message.commissionReport)
tws.register(error_handler, 'Error')
tws.connect()

rawDescription: How to get the trading price and commission in Interactive Brokers (IBPY) after placing an order?

description: Get the trading price and commission in Interactive Brokers (IBPY) after placing an order


code:
from __future__ import division
import numpy as np

# Create a sample data set
c1, c2 = 10, 5
idx1, idx2 = np.arange(c1), np.arange(c2)
idx1, idx2 = np.repeat(idx1, c2), np.tile(idx2, c1)

items = 1000
i = np.random.randint(c1*c2, size=(items - 2*c1*c2,))
d = np.random.rand(items+5)

dataset = np.empty((items+5,), [('idx1', np.int), ('idx2', np.int),
                             ('data', np.float)])
dataset['idx1'][:2*c1*c2] =  np.tile(idx1, 2)
dataset['idx1'][2*c1*c2:-5] = idx1[i]
dataset['idx2'][:2*c1*c2] = np.tile(idx2, 2)
dataset['idx2'][2*c1*c2:-5] = idx2[i]
dataset['data'] = d
# Add blocks with only 2 and only 3 elements to test corner case
dataset['idx1'][-5:] = -1
dataset['idx2'][-5:] = [0] * 2 + [1]*3

rawDescription: stratified sampling in numpy

description: Stratified sampling in numpy


code: ans = str(Decimal(a).sqrt()).replace('.', '')[:100]

rawDescription: Correctly compute square root digital expansions


code:
from nltk import pos_tag
from inspect import getargspec
getargspec(pos_tag)
getargspec(pos_tag).args

rawDescription: Probing a python function

description: Probing a python function


code:
A = [500, 300, 400, 200, 100]
index = { k:i for i,k in enumerate(A, 1) }
random_list = [200, 100, 50]
[i for i,x in enumerate(random_list) if x in index]
map(index.get, random_list)
filter(None, map(index.get, random_list))

rawDescription: Python: Fast mapping and lookup between two lists


rawDescription: django SimpleListFilter

description: Django SimpleListFilter


code:
with open('new_file.csv', 'wb') as toWrite:
    writer = csv.writer(toWrite) # if the delimiter is ',', you don't need to specify

    for row in result_edited:
        writer.writerow(row)

rawDescription: Re-writing a CSV file using csv

description: Re-writing a CSV file using csv


code:
MEMBERSHIP_QUERY = '''
    SELECT gm.group, mc.memberscount = %(len)s AS type
      FROM groupmembers gm
      JOIN (SELECT "group", COUNT(DISTINCT members) as memberscount
              FROM groupmembers
             GROUP BY "group") mc
      ON gm.group = mc.group
    WHERE gm.members IN %(set)s
    GROUP BY gm.group, mc.memberscount
    HAVING COUNT(DISTINCT gm.members) = %(len)s;
'''

def membership(members):
    # obtain a cursor
    for row in cursor.execute(MEMBERSHIP_QUERY, dict(len=len(members), set=members)):
        yield dict(group=row[0], type=row[1])

rawDescription: How do I create a one-column SQL table from an input list/array?

description: Create a one-column SQL table from an input list/array


code:
values, inv = np.unique(items, return_inverse=True)
counts = np.bincount(inv)
values
counts
idx = np.argsort(counts)[::-1]
values[idx]
counts[idx]

rawDescription: Sorting a scipy.stats.itemfreq result containing strings


rawDescription: Python Pandas business day range bdate_range doesn't take 1min freq?


rawDescription: Django development - Accessing results from a model


rawDescription: Selenium Python: How to click on a <a> tag based on "onclick" text


code:
infinidict = lambda: collections.defaultdict(infinidict)
result = infinidict()
for keys, value in values:
    last = reduce(operator.getitem, keys[:-1], result)
    last[keys[-1]] = value

rawDescription: Python list to nested keys

description: Python list to nested keys


code:
def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)

rawDescription: How do I build a tree dynamically in Python

description: Build a tree dynamically in Python


rawDescription: find self index for nested Python object

description: Find self index for nested Python object


rawDescription: Sort list of dictionaries by multiple keys with different ordering


rawDescription: Save for loop result in variable

description: Save for loop result in variable


code:
import re
p = re.compile(r'(?<=\d)\.0+\b')
test_str = "15.0+abc-3"
subst = ""

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

rawDescription: Python: Replace "wrong" floats by integers inside string


code:
import re
s = """SOME OF THE STRINGS COULD BE HERE

SOME STRINGS COULD ALSO BE HERE

"""
m = re.findall(r'(.+?)	|
(.+?)
', s)
m
[s for s in x if s for x in m]

rawDescription: Combining two REGEX in Python for compiling


code:
class X(object):
    def __init__(self):
        self.count = 5
        self.y = Y(self) #create a y passing in the current instance of x
    def add2(self):
        self.count += 2

class Y(object):
    def __init__(self,parent):
        self.parent = parent #set the parent attribute to a reference to the X which has it
    def modify(self):
        self.parent.add2()

rawDescription: Composition - Reference to another class in Python


code:
rdd = sc.parallelize(["aDSd", "CDd", "aCVED"])

rdd.flatMap(lambda line: my_method(line)).collect()
## ['adsd', 'acved']

rawDescription: How can I return an empty (null?) item back from a map method in PySpark?

description: Return an empty (null?) item back from a map method in PySpark


code:
A = [86, 2,4 ,5, 6122, 87]
def selectionSort(a):
    # Go through all positions except the last one
    # (that one will automatically be correct)
    for index in range(len(a)-1):
        value = a[index]
        # enumerate all (index, value) pairs from the rest of the list
        # and take the pair with the smallest value
        min_subindex, min_value = min(enumerate(a[index+1:]), key=lambda x: x[1])
        if min_value < value:
            a[index] = min_value
            a[min_subindex + index + 1] = value

selectionSort(A)
print(A) # [2, 4, 5, 86, 87, 6122]

rawDescription: Python: Selection Sort

description: Python: Selection Sort


rawDescription: How to remove a value but keep the corresponding key in a dictionary?

description: Remove a value but keep the corresponding key in a dictionary


code:
app = QtGui.QApplication([])
win = QtGui.QWidget(None)
win.show()
put_ipy(win)

rawDescription: embedding ipython qtconsole and passing objects

description: Embedding ipython qtconsole and passing objects


code:
import operator
class ReversedOrder:
    def __init__(self, value):
        self.value = value
for x in ['__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__']:
    op = getattr(operator, x)
    setattr(ReversedOrder, x, lambda self, other, op=op: op(other.value, self.value))

rawDescription: How to write Python sort key functions for descending values

description: Write Python sort key functions for descending values


code:
inp = open("text.txt", "r")
output = open("out.txt", "w")

for line in inp:
    l = line.strip()
    if l.endswith("dev"):
       output.write("%s <- He's a developer\n" % l)
    if l.endswith("supp"):
       output.write("%s <- He's a support guy\n" % l)

inp.close()
output.close()

rawDescription: Append a text in a file where the pattern matches


rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


code:
if __name__ == '__main__':
    import dispy
    f = functools.partial(setup,"file.dat")
    cluster = dispy.JobCluster(compute, depends=['file.dat'], setup=f, cleanup=cleanup)

rawDescription: Is there a way to pass a variable to setup() in dispy?


code: line = line.rstrip('\r\n')

rawDescription: Stripping \r\n from a line

description: Stripping \r\n from a line


code:
df2.rename(columns={'Country':'Country_Name'}, inplace=True)
merged = df1.merge(df2, on='Country_Name', how='left')

# you can either use merged dataframe or assign it to df1:
df1 = merged

rawDescription: Add a category column to a pandas dataframe from an existing list of categories


rawDescription: Split a list with consecutive block items but discontinued blocks into sub-lists


code:
def cans(layers):
    if layers < 1:
        return 0
    return (layers ** 2) + cans(layers-1)

def lager(layers=5, volume=0.407150407905):
    return cans(layers) * volume

rawDescription: Recursive function not returning what I want


code: x = 'scatter -n', n

rawDescription: outputting a string to terminal and otherwise in a correct format

description: Outputting a string to terminal and otherwise in a correct format


code:
from xml.etree import cElementTree as etree

xml = """

Bill

John

Joe

"""
root = etree.fromstring("<root>%s</root>" % xml)
for div in root.getiterator('div'):
    if "John" in div.text:
       print(etree.tostring(div))

rawDescription: Equivelant of contains() selector in BeautifulSoup/Python


code:
a = [[0, 2, 2], [2, 0, 0], [2, 0, 1]]
b = [[1, 0, 0], [0, 2, 3], [0, 1, 0]]
s = [sum(i) for i in b]
l = [sum(v != 0 for v in i) for i in a]
l
[[0 if not v else v + (float(sumb) / count) for v in i]
 for i, sumb, count in zip(a, s, l)]

rawDescription: Sum and length of lists of list

description: Sum and length of lists of list


code:
pay_dict = {"get_name": "foo","get_pay_rate" : 50,"get_the_hours": 40}

with open('Emp schedule.txt','a') as schedule:
   schedule.write("{get_name}\n{get_pay_rate}\n{get_the_hours}\n".format(**pay_dict))

rawDescription: How to write text to an output file in a structured, organize manner

description: Write text to an output file in a structured, organize manner


code:
s.unique()
'a' in s.unique()

rawDescription: How to determine whether a Pandas Column contains a particular value

description: Determine whether a Pandas Column contains a particular value


code: re.findall(r"mxy\s*(.*?)\s*jpg", 'test:"<no-cjar> mxy 3044 jpg fasst_st')

rawDescription: python parse output and return certain value

description: Python parse output and return certain value


code:
new_dict = {}
for key, values in Dict.iteritems():
    counts = Counter()
    for color, _, count in values:
        counts[color] += count
    new_dict[key] = counts.items()

new_dict

rawDescription: Sum Values in a Dictionary w/ respect to the Key - Python 2.7


code:
import numpy as np

def gen_log_space(limit, n):
    result = [1]
    if n>1:  # just a check to avoid ZeroDivisionError
        ratio = (float(limit)/result[-1]) ** (1.0/(n-len(result)))
    while len(result)<n:
        next_value = result[-1]*ratio
        if next_value - result[-1] >= 1:
            # safe zone. next_value will be a different integer
            result.append(next_value)
        else:
            # problem! same integer. we need to find next_value by artificially incrementing previous value
            result.append(result[-1]+1)
            # recalculate the ratio so that the remaining values will scale correctly
            ratio = (float(limit)/result[-1]) ** (1.0/(n-len(result)))
    # round, re-adjust to 0 indexing (i.e. minus 1) and return np.uint64 array
    return np.array(map(lambda x: round(x)-1, result), dtype=np.uint64)

rawDescription: logarithmically spaced integers

description: Logarithmically spaced integers


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

with open('input', 'rb', 0) as input_file, \
     open('output', 'wb', 0) as output_file:
    check_call(["perl", "script.pl", "/path/to/file1/"],
               stdin=input_file, stdout=output_file)

rawDescription: Process a perl script within a python script


code:
a = [ [0], [0], [0] ]
fmt = '< {} >'.format
from itertools import chain
fmt(' '.join(map(str, chain.from_iterable(a))))

rawDescription: manipulate python lists into string type i want

description: Manipulate python lists into string type i want


code:
import datetime
now = datetime.datetime.now()
datetime.datetime.strftime(now, '%m/%d/%Y')
datetime.datetime.strftime(now, '%H:%M:%S')
datetime.datetime.strftime(now, '%I:%M:%S')

rawDescription: Formatting datetime in python

description: Formatting datetime in python


code:
files = (
    r'..\..\data\User\level1\level2\sun.png',
    r'..\..\data\User\level1\level2\description.txt'
)

rawDescription: Convert single backslash to double backslash


code: primes = range(2, 20)

rawDescription: Finding Primes with Modulo in Python

description: Finding Primes with Modulo in Python


code: form = AccountForm(request.POST, request.FILES) # A form bound to the POST data

rawDescription: Editing the Form in Django creates new instance


code: lst = [str(i) for i in lst]

rawDescription: List of numbers

description: List of numbers


code:
output_dict = {}
for val,item in enumerate(input_set):
    output_dict[item] = val

rawDescription: how to convert a set in python into a dictionary

description: Convert a set in python into a dictionary


rawDescription: Python and Selenium - PHPSESSID cookie is logging me in


code:
import numpy as np
bool(any(x < 3 for x in [10,20,30]))
from numpy import *
bool(any(x < 3 for x in [10,20,30]))

rawDescription: What is the formal way to load numpy package?


code:
import collections

MyCustomType = collections.namedtuple('MyCustomType', 'a, b')

rawDescription: namedTuples definition across multiple chained functions

description: NamedTuples definition across multiple chained functions


code:
import pygame
from pygame.locals import *
...
resolution = TIMER_RESOLUTION

rawDescription: Importing a module and using its methods


code: LINK_MODEL = 'someproject.somemodel'

rawDescription: How to Model a Foreign Key in a Reusable Django App?


code:
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)

ERROR_NOT_ALL_ASSIGNED = 0x0514
SE_PRIVILEGE_ENABLED = 0x00000002
TOKEN_ALL_ACCESS = 0x000F0000 | 0x01FF

class LUID(ctypes.Structure):
    _fields_ = (('LowPart',  wintypes.DWORD),
                ('HighPart', wintypes.LONG))

class LUID_AND_ATTRIBUTES(ctypes.Structure):
    _fields_ = (('Luid',       LUID),
                ('Attributes', wintypes.DWORD))

class TOKEN_PRIVILEGES(ctypes.Structure):
    _fields_ = (('PrivilegeCount', wintypes.DWORD),
                ('Privileges', LUID_AND_ATTRIBUTES * 1))
    def __init__(self, PrivilegeCount=1, *args):
        super(TOKEN_PRIVILEGES, self).__init__(PrivilegeCount, *args)

PDWORD = ctypes.POINTER(wintypes.DWORD)
PHANDLE = ctypes.POINTER(wintypes.HANDLE)
PLUID = ctypes.POINTER(LUID)
PTOKEN_PRIVILEGES = ctypes.POINTER(TOKEN_PRIVILEGES)

def errcheck_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)

kernel32.GetCurrentProcess.errcheck = errcheck_bool
kernel32.GetCurrentProcess.restype = wintypes.HANDLE

# https://msdn.microsoft.com/en-us/library/aa379295
advapi32.OpenProcessToken.errcheck = errcheck_bool
advapi32.OpenProcessToken.argtypes = (
    wintypes.HANDLE,  # _In_  ProcessHandle
    wintypes.DWORD,   # _In_  DesiredAccess
    PHANDLE)          # _Out_ TokenHandle

# https://msdn.microsoft.com/en-us/library/aa379180
advapi32.LookupPrivilegeValueW.errcheck = errcheck_bool
advapi32.LookupPrivilegeValueW.argtypes = (
    wintypes.LPCWSTR, # _In_opt_ lpSystemName
    wintypes.LPCWSTR, # _In_     lpName
    PLUID)            # _Out_    lpLuid

# https://msdn.microsoft.com/en-us/library/aa375202
advapi32.AdjustTokenPrivileges.errcheck = errcheck_bool
advapi32.AdjustTokenPrivileges.argtypes = (
    wintypes.HANDLE,   # _In_      TokenHandle
    wintypes.BOOL,     # _In_      DisableAllPrivileges
    PTOKEN_PRIVILEGES, # _In_opt_  NewState
    wintypes.DWORD,    # _In_      BufferLength
    PTOKEN_PRIVILEGES, # _Out_opt_ PreviousState
    PDWORD)            # _Out_opt_ ReturnLength

def enable_privilege(privilege):
    hToken = wintypes.HANDLE()
    luid = LUID()
    tp = TOKEN_PRIVILEGES()
    advapi32.LookupPrivilegeValueW(None, privilege, ctypes.byref(luid))
    tp.Privileges[0].Luid = luid
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
    advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
                              TOKEN_ALL_ACCESS,
                              ctypes.byref(hToken))
    try:
        advapi32.AdjustTokenPrivileges(hToken, False,
                                       ctypes.byref(tp),
                                       ctypes.sizeof(tp),
                                       None, None)
        if ctypes.get_last_error() == ERROR_NOT_ALL_ASSIGNED:
            raise ctypes.WinError(ERROR_NOT_ALL_ASSIGNED)
    finally:
        kernel32.CloseHandle(hToken)

def disable_privilege(privilege):
    hToken = wintypes.HANDLE()
    luid = LUID()
    tp = TOKEN_PRIVILEGES()
    advapi32.LookupPrivilegeValueW(None, privilege, ctypes.byref(luid))
    tp.Privileges[0].Luid = luid
    tp.Privileges[0].Attributes = 0
    advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
                              TOKEN_ALL_ACCESS,
                              ctypes.byref(hToken))
    try:
        advapi32.AdjustTokenPrivileges(hToken, False,
                                       ctypes.byref(tp),
                                       ctypes.sizeof(tp),
                                       None, None)
        if ctypes.get_last_error() == ERROR_NOT_ALL_ASSIGNED:
            raise ctypes.WinError(ERROR_NOT_ALL_ASSIGNED)
    finally:
        kernel32.CloseHandle(hToken)

rawDescription: Python - Get windows folder ACL permissions


code:
import operator

l = [[1,4,3], [2,2,4], [3,1,5]]
print(sorted(l, key=operator.itemgetter(1)))

rawDescription: Nested list sort python 3

description: Nested list sort python 3


code:
master = create_engine("some DB")
slave = create_engine("some other DB")
Session = scoped_session(sessionmaker(bind=master))

def with_slave(fn):
    def go(*arg, **kw):
        s = Session(bind=slave)
        return fn(*arg, **kw)
    return go

rawDescription: read slave , read-write master setup

description: Read slave , read-write master setup


rawDescription: Inheriting a tuple as a list

description: Inheriting a tuple as a list


code: string

rawDescription: Is there a clean way to write multi-lines strings in Python?


code:
s = 'First sentenceSecond sentence'
soup = BeautifulSoup(s)
soup.find_all("a")
[a.get_text() for a in soup.find_all("a")]

rawDescription: Want to get part of string using regular expression


code:
import mypath

my_path= mypath.path()

rawDescription: How can I create folder in importing process [python]

description: Create folder in importing process [python]


code:
expr = "members.filter(gender='Male')"
evaluate(ast.parse(expr), referenceObject)

rawDescription: Python getattr callable function

description: Python getattr callable function


rawDescription: Depth Traversing a graph in Python

description: Depth Traversing a graph in Python