code:
from __future__ import print_function, absolute_import
from IPython.nbconvert.preprocessors.base import Preprocessor

class MyLatexPreprocessor(Preprocessor):

    def preprocess(self, nb, resources):
        # Generate Pygments definitions for Latex
        from pygments.formatters import LatexFormatter

        resources["latex"]["pygments_definitions"] = LatexFormatter(style='emacs').get_style_defs()
        return nb, resources

rawDescription: IPython nbconvert to latex - syntax colouring


code:
import networkx as nx
G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted at 0
[n for n,d in G.in_degree().items() if d==0]

rawDescription: Getting the root (head) of a DiGraph in networkx (Python)


code:
import sys
print(sys.hexversion)

rawDescription: Dealing with multiple python versions when python files have to use #!/bin/env python


rawDescription: Remove items from a list in Python based on previous items in the same list


code:
class MyFramework(object):
    """A bare MyFramework, I only hold a person's name
    """
    _addons= {}
    @staticmethod
    def addAddon(name, addon):
        MyFramework._addons[name]= addon

    def __init__(self, person):
        self.person= person
        for name, addon in MyFramework._addons.items():
            setattr(self, name, addon(self))

rawDescription: Putting separate python packages into same namespace?


code: a, b = b, a

rawDescription: Shuffling a list

description: Shuffling a list


code:
if pygame.MOUSEBUTTONDOWN in [event.type for event in pygame.event.get()]:
    run_your_animation()

rawDescription: How use mouse control with pygame?

description: How use mouse control with pygame


code: list(split_sequence(range(7), 4))

rawDescription: Yield sub combinations with constraint on lenght of output list


rawDescription: getattr on class objects

description: Getattr on class objects


code:
query = [{'x': 1}]
if checkbox == 'checked':
    query.append({'y': 2})

results = db.collection.find({'$or': query})

rawDescription: Dynamically building queries in pymongo

description: Dynamically building queries in pymongo


rawDescription: Pandas: top N rows, top N rows per group, equivalent for ROW_NUMBER OVER(PARTITION BY ... ORDER BY ...)


code: lowui = user_input.lower() # Actually call the lower function

rawDescription: Python if with many or in a contracted form


code:
def getProductElement(m1, m2, i, j):
    # some calculations
    return element

rawDescription: How do I make processes able to write in an array of the main program?

description: Make processes able to write in an array of the main program


code:
from copy import deepcopy as dc
a = [[1 ,4],[2, 5],[3, 6, 9]]
f = [[dc(x) for _ in xrange(y)] for x,y in zip(a,b)]
[[id(z) for z in x] for x in f]

rawDescription: Creating list of individual list items multiplied n times


code:
import struct
xx = '\x03\xff'
struct.pack('<H', *struct.unpack('>H', xx))

rawDescription: Difference between different hex types/representations in Python


code: used = reduce(lambda used, obj: used.union(obj.callSomeFunc(used)), objs, set())

rawDescription: Idiomatic way to build list with successive function calls on that list


code:
s = ''
for bla in bli:
  s += bla
s = 'it works ' + s

rawDescription: python concat before

description: Python concat before


code:
class Blah(object):
    @copy_argspec(bar)
    def foo(self, *args, **kwargs):
        """ a docstr """
        result = bar(*args, **kwargs)
        result = result**2 # just so it's clear we're doing something extra here...
        return result

rawDescription: How can I programmatically change the argspec of a function *not* in a python decorator?

description: Programmatically change the argspec of a function *not* in a python decorator


code: sorted(zip(*l))

rawDescription: Sorting a list of lists in python alphabetically by "column"


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

rawDescription: Again, regular expression matching in python


rawDescription: Selecting row based on column value in duplicated entries on different column in PySpark


code: sorted(d, key=lambda x: (-d[x], x.lower()))[:2]

rawDescription: What is an alternative to sorted() in this situation? Or can this be managed?


code:
import sys
inFile = sys.argv[1]
outFile = sys.argv[2]

rawDescription: How to take input file from terminal for python script?

description: Take input file from terminal for python script


rawDescription: An efficient way of making a large random bytearray


code:
#First, I get the length of the first line -- if you already know it, skip this block
f=open('test.dat','r')
l=f.readline()
linelen=len(l)-1
f.close()

#apparently mode='a+' doesn't work on all systems :( so I use 'r+' instead
f=open('test.dat','r+')
f.seek(0)
f.write('a'*linelen+'\n') #'a'*linelen = 'aaaaaaaaa...'
f.close()

rawDescription: Reading lines in text files using python


code:
sample.seek(0)
open('/tmp/test.csv', 'wb').write(sample.read())
f = open('/tmp/test.csv', 'rbU')
f.readline()
f = open('/tmp/test.csv', 'rb')
f.readline()

rawDescription: python tab separated file parsing problems

description: Python tab separated file parsing problems


rawDescription: Search in a python list

description: Search in a python list


code:
for line in infile:
    instance, ts, data, *rest = line.rstrip().split(',')
    print ("instance = %s, date = %s, ts = %d" %(instance, date, ts))

rawDescription: How to read multiple values from a line in python when the # of values could change

description: Read multiple values from a line in python when the # of values could change


code:
class PinochleDeck(Deck):

    def __init__(self):
        list.__init__(self)

        for i in range(2):
            for suit_ind in range(4):
                for card_ind in range(7, 13):
                    self.append(Card(suit_ind*card_ind))

rawDescription: Creating two copies of objects in a list


code: r = [v for v in secondlst if v not in lst]

rawDescription: Python Filtering 2 Lists

description: Python Filtering 2 Lists


code:
def flatten(d):
    for key in d.keys():
        if isinstance(d[key], list):
            value = d.pop(key)
            for i, v in enumerate(value):
                d.update(flatten({'%s__%s' % (key, i): v}))
        elif isinstance(d[key], dict):
            value = d.pop(key)
            d.update([('%s__%s' % (key, sub), v) for (sub, v) in flatten(value).items()])
    return d

rawDescription: Manipulate Pandas DataFrame containing dictionaries from Twitter API


code:
one
three
two

rawDescription: Calling unspecified function from another file and another class


rawDescription: Assigning a column for a modified dataframe back to original dataframe in pandas


code: prime = not(any(n % m == 0 for m in range(2, n)))

rawDescription: Prime generator in python returns multiple composites instead of primes


code:
[['University of Georgia', 'Anne   Greene', 'ba'],
 ['University of Georgia', 'Sara Dean', 'ms'],
 ['University of Georgia', 'Beth Johnson', 'bs'],
 ['University of Michigan', 'James Jones', 'phd'],
 ['University of Michigan', 'Frank Kimball', 'ma'],
 ['University of Florida', 'Nate Franklin', 'ms']]

rawDescription: Python: How to sort a list of lists by the most common first element?


code:
Animal.__init__(self, name)
super(Dog, self).__init__(name)
super(self.__class__, self).__init__(name) # self.__class__ is the class of self or its type.

rawDescription: Understanding Class Inheritance in Python from learningPythonthehardway


code:
def recurrence_relation(seed,func):
    seed = list(seed)
    que = deque(seed,len(seed))
    for x in seed:
        yield seed
    while True:
        out = func(que)
        yield out
        queue.append(out)

rawDescription: Formula to Generate List of Specific Numbers


code:
import lldb

def myobject_summary(valueObject, dictionary):

    return 'MyCustomDescription'

def __lldb_init_module(debugger, dict):

    debugger.HandleCommand('type summary add MyObject -F CustomSummaries.myobject_summary')

rawDescription: When is __lldb_init_module called?

description: When is __lldb_init_module called


rawDescription: Using Deque.popleft as args for function


code:
class DemoClass(object):
    ...

def isinstance(obj, cls):
    if __builtins__.isinstance(obj, DemoClass) and issubclass(int, cls):
        return True
    else:
        return __builtins__.isinstance(obj, cls)

rawDescription: Create/imitate mutable subclass of immutable built-in type


code:
class b(models.Model):
    a = models.ForeignKey(a, unique=True, related_name="profile")
    age = models.IntegerField(null=True, blank=True)

rawDescription: Django REST combining Meta. models

description: Django REST combining Meta. models


code:
model_profit_tr = pd.ols(y=df_closed['Profit cum (%)'],
                         x=df_closed['Order'],
                         intercept=False)

rawDescription: Linear regression - reduce degrees of freedom


code:
import peewee as pw
from BaseModel import BaseModel

class Spaghetti(BaseModel):
    has_meatballs = pw.BooleanField()

rawDescription: Modularizing peewee

description: Modularizing peewee


code:
cookie["varname"] = 'value'
cookie["varname"]["expires"] = "formatted date"
cookie["varname"]["othercookieproperty"] =  "othercookieproperty"

rawDescription: Python Setting and Recalling Cookies

description: Python Setting and Recalling Cookies


code: import sys

rawDescription: Python import and module scoping (specifically sys.ps1)


code:
mu   = xs.dot(prob)               # mean value
mom2 = np.power(xs, 2).dot(prob)  # 2nd moment
var  = mom2 - mu**2               # variance
np.sqrt(var)                      # standard deviation

rawDescription: Calculate the standard deviation of a gaussian


code:
data = open(path).read()
if data[0:4] == '\xca\xfe\xba\xbe':
    minetype = 'application/x-java-applet'

rawDescription: How can I find the mimetype of a file without extension that is sent to me inside a zip file?

description: Find the mimetype of a file without extension that is sent to me inside a zip file


code:
from collections import deque

def ngrams(it, n=2):
    it = iter(it)
    deq = deque(it, maxlen=n)
    yield tuple(deq)
    for p in it:
        deq.append(p)
        yield tuple(deq)

rawDescription: Getting next variable in a for loop

description: Getting next variable in a for loop


code:
hand = ['1D', '5S', '10H']
hand2 = [i[:-1] for i in hand]
hand2

rawDescription: Taking Elements From a List

description: Taking Elements From a List


rawDescription: python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix

description: Python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix


rawDescription: pattern match list a with list b

description: Pattern match list a with list b


rawDescription: How to change the template engine in Pyramid?

description: Change the template engine in Pyramid


code:
def upload_to_id_image(instance, filename):
    extension = splitext(filename)[1].lower()
    salt, hashed = generate_sha1(instance.id)
    path = 'profiles/%(id)s_%(date_now)s_' % {
                                         'id': instance.user.id,
                                         'date_now': get_datetime_now().date().strftime("%Y%m%d")}
    return '%(path)s%(hash)s%(extension)s' % {'path': path,
                                          'hash': hashed[:16],
                                          'extension': extension}

rawDescription: Django ImageKit: How to rename uploaded images?


code: walkDict( myDict, filterFor )

rawDescription: How to do this - python dictionary traverse and search

description: Do this - python dictionary traverse and search


code:
from nltk import word_tokenize, pos_tag
text = "Let the sizes be denoted by $s(n)$ and $t(n)$ respectively."
tagged_text = pos_tag(word_tokenize(text))
tagged_text

rawDescription: chunk NP and VP using nltk

description: Chunk NP and VP using nltk


code:
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.can = Canvas(self.master, width=500, height=250)
        self.can.grid(row=2, column=1)
        self.can.create_line(0,0,500,200)

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

rawDescription: just a canvas in a tkinter window

description: Just a canvas in a tkinter window


code:
random.seed(100)
randreplace("This is an awesome string","a","@",1) # "This is @n awesome string"
randreplace("This is an awesome string","a","@",1) # "This is an @wesome string"
randreplace("This is an awesome string","a","@",2) # "This is @n @wesome string"
randreplace("This is an awesome string","a","@")   # "This is @n @wesome string"

rawDescription: Conditionally format a string - Python

description: Conditionally format a string - Python


code:
import random
import time
choices = list(range(0,11))
choices[3] = "3 was number 3!" #override the third indice
x = 1
ran = None #previous value before you start, needs to be defined for rule 1 to work
while True:
    last = ran
    while ran == last:
        ran = random.choice(choices)
    print ('Random :', ran)
    x += 1
    time.sleep(1)

rawDescription: block repeat of random only for certain step through the random value

description: Block repeat of random only for certain step through the random value


code:
{'drinks': '[{"breakfast": "milk", "lunch": "beer"}, {"breakfast": "milk", "lunch": "beer"}]',
'famili': 'ivanov',
'name': 'georgi'}

rawDescription: Change json.dumps dictionary values in python


code:
class Test(models.Model):
    student = models.ForeignKey(Student)
    date_added = models.DateField(default=datetime.datetime.now)
    test_name = models.CharField(max_length=200,default='',blank=False)
    section_1 = models.CharField(max_length=100,default='')
    section_2 = models.CharField(max_length=100,default='')

    def __str__(self):
        return self.test_name

rawDescription: Consuming api from django rest framework


rawDescription: Python list of sets to dictionary

description: Python list of sets to dictionary


code:
list(xrange(3))
list(xrange(1, 3))

rawDescription: list of random integers without zero Python

description: List of random integers without zero Python


code: zip(score, name)

rawDescription: How do I index the 3 highest values in a list?

description: Index the 3 highest values in a list


rawDescription: transparent widgets inside transparent frame pyqt5

description: Transparent widgets inside transparent frame pyqt5


code:
import json

data = [1, 2, 3]

with open('data.json', 'w') as jsonfile:
    json.dump(data, jsonfile)

rawDescription: Feeding a Python array into a Perl script


rawDescription: Python get clustered data-Hierachical Clustering


rawDescription: Toggle between two commands with one key at a time


rawDescription: sorting the list in Python without .sorted()

description: Sorting the list in Python without .sorted()


code:
from django.db import connection
cursor = connection.cursor()
connection.introspection.get_table_list(cursor)

[u'auth_group', u'auth_group_permissions', u'auth_message', u'auth_permission', u'auth_user', u'auth_user_groups', u'auth_user_user_permissions', u'django_content_type', u'django_session', u'django_site', u'testapp_book', u'testapp_userbook', u'testapp_userbook_purchasedBooks']

rawDescription: Django manage.py sqlclear omit some tables


code:
3 in even_numbers
4 in even_numbers

rawDescription: Translating a callable test into a collection membership test


rawDescription: DRF relate single field from model

description: DRF relate single field from model


code:
import example
spams = []
example.append_to_list(spams)
assert(type(spams[0]) is example.Spam)
del spams

rawDescription: Append C++ created object to python list and make it managed by python


rawDescription: Python using higher order functions

description: Python using higher order functions


code:
# this retrieves the pivot table for 2012
data_dict['2012']

rawDescription: Python Summarizing data efficiently using loops in pandas


code:
s = np.sign(df - 1)
(s == -s.shift()).sum()

rawDescription: Python : How to find in set of rows, one element is less than 1 and other is greater than 1?


code:
sim_matrix
sim_matrix[sim_matrix < 2] = 0 # apply your threshold
sim_matrix

rawDescription: optimizing code for traversing a matrix in python

description: Optimizing code for traversing a matrix in python


code:
lower = int(input("Enter Lower: "))
upper = int(input("Enter Upper: "))

for num in range(lower, upper + 1):
    # prime numbers are greater than 1
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            if is_unique(num):
                print(num)

rawDescription: Finding prime numbers between any range and how to pick out non repeat numbers in python


code:
db.collection.aggregate([
    { "$group": {
        "_id": { "message": "$message.message", "from": "$headers.from" },
        "message_id": { "$first": "$_id" },
        "headers": { "$first": "$headers" },
        "message": { "$first": "$message" }
    }},
    { "$project": {
        "_id": "$message_id",
        "headers": 1,
        "message": 1
    }}
])

rawDescription: MongoDB Collection with Non-repeated field value


code:
sentence = input("Enter a sentence: ").split()

count = 0
for w in sentence:
    if palindrome(w):
        count += 1
        print("{} is a palindrome.")
    else:
        print("{}  is not a palindrome.")
print(" There are {} palindromes in your sentence\n.".format(count))

rawDescription: Python Palindrome Help: Count palindromes in a sentence


code: a = [item if item > 3 else 3 for item in a]

rawDescription: Check if all values of a list are less than a certain number, if not set it to that number


rawDescription: Removing all duplicates from the list - keeping no instance of a duplicate item


code:
Problem #2: Check if there's an empty header item:
blank = re.compile(r'\s*')
for i in csv[0]:
    if blank.match(i).end() == len(i):
        print("found an empty header item")

rawDescription: Python- Check in the CSV file the Header value and data value is equal


code:
root = tk.Tk()
tk.Label()
tk.Button()

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code: examples = example.pp1_lookup.get(30.0, [])

rawDescription: How to invoke an instance by its property in Python?

description: Invoke an instance by its property in Python


code:
def createURL():
    param1 = ''
    param2 = ''
    typeans = ['parameter 1', 'param 1']
    typeansa = ['parameter 2', 'param 2']
    while True:
        again = raw_input('Would you like to add another parameter? Enter y/n: ')
        if again == "n":
            break
        if again == "y":
            additionalparams = raw_input("Would you like to add any other parameters? (Parameter 1, Parameter 2): ")
            if additionalparams.lower() in typeans:
                param1 = raw_input('Please enter the first search criteria: ')
                param1 = param1+"one"
            elif additionalparams.lower() in typeansa:
                param2 = raw_input('Please enter the second search criteria: ')
                param2 = param2+"two"
    return 'www.website.com/'+param1+param2

url = createURL()

rawDescription: Updating empty variables outside a function


code:
x = np.linspace(0,1,11)
y = np.linspace(1,0,11)
u = v = np.zeros((11,11))
u[5,5] = 0.2

plt.axis('equal')
plt.quiver(x, y, u, v, scale=1, units='xy')

rawDescription: How does Python's matplotlib.pyplot.quiver exactly work?


code:
pd.to_timedelta(s_nano, unit='ns')
pd.to_timedelta(s_nano, unit='ns').values

rawDescription: How to create a pandas.Timestamp from datetime.datetime object and nanoseconds value

description: Create a pandas.Timestamp from datetime.datetime object and nanoseconds value


code:
import numpy as np

class sdarray(object):
    def __init__(self, *args, **kwargs):
        self.recarray =  np.recarray( *args, **kwargs)

    def __getattr__(self,attr):
        if hasattr( self.recarray, attr ):
            return getattr( self.recarray, attr )
        else:
            return getattr( self, attr )

    def __len__(self):
        return self.recarray.__len__()

    def __add__(self,other):
        return self.recarray.__add__(other)

    def __sub__(self,other):
        return self.recarray.__sub__(other)

    def __mul__(self,other):
        return self.recarray.__mul__(other)

    def __rmul__(self,other):
        return self.recarray.__rmul__(other)

    def __getitem__(self,i):
        return self.recarray.__getitem__(i)

    def __str__(self):
        return self.recarray.__str__()

    def __repr__(self):
        return self.recarray.__repr__()

    def __setitem__(self, i, x):
        keys = []
        formats = []
        if i in self.dtype.names:
            self.recarray.__setitem__(i,x)
        else:
            for name, t in self.dtype.fields.iteritems():
                keys.append(name)
                formats.append(t[0])
            keys.append( i )
            formats.append( formats[-1] )
            new = np.recarray( shape = self.shape,
                              dtype = {'names'  : keys,
                                       'formats': formats} )
            for k in keys[:-1]:
                new[k] = self[k]
            new[i] = x
            self.recarray = new

rawDescription: Add new items to some structured array in a dictionary-like way


rawDescription: Hamming distance between two binary strings not working


code:
class Service(Model):
    name = models.CharField(max_length=32)

class Person(Model):
    services = models.ManyToManyField('self', through='PersonServiceRel', null=True, related_name='friends', symmetrical=False)

class PersonServiceRel(Model):
    provider = models.ForeignKey(Person, related_name='provided_services')
    consumer = models.ForeignKey(Person, related_name='consumed_services')
    service = models.ForeignKey(Service)

rawDescription: What are the character limitations to Django model's related_name in a relationship?


code:
s = sympy.parsing.sympy_parser.parse_expr('3*x*y - y*x - 2*x*y', evaluate=False)
s.atoms(sympy.Symbol)

rawDescription: Non-commutative sympify (or simplify)

description: Non-commutative sympify (or simplify)


code:
from collections import defaultdict

def leaders(xs, top=10):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]

rawDescription: Python: how to get sorted count of items in a list?


code: df.groupby("L1", as_index=False).apply(lambda x : pd.expanding_sum(x.sort("L3", ascending=False)["L3"])/x["L3"].sum())

rawDescription: New cumulative value col derived from existing col in a Pandas dataframe


rawDescription: z3 pseudo-randomly hangs while parsing through a SAT Model

description: Z3 pseudo-randomly hangs while parsing through a SAT Model


code:
class Room(object):
    lookup = {}
    def __init__(self,name,exits):
        self.name = name
        self.exits = exits
        Room.lookup[name] = self

rawDescription: Relationships between variables

description: Relationships between variables


code: df

rawDescription: Applying function to each row of pandas data frame - with speed


code:
import unittest

class BaseTest(unittest.TestCase):
    def initialisation_script_stuff(blah,etc):
        foo

    def setUp(self):
        common_setup_stuff()

    def tearDown(self):
        whatever

rawDescription: boilerplateless tests

description: Boilerplateless tests


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Getting two characters from string in python


rawDescription: Sorting all rows in numpy matrix by target-column


code:
import pandas, numpy as np
df = pandas.io.parsers.read_csv("baseline.csv")
df["month"] = df["time2"].map(lambda x: int(x.split('-')[1]))
df.groupby(["license","month"]).apply(len)

rawDescription: statistics with "group by" or "uniq"

description: Statistics with "group by" or "uniq"


code:
text= "I say what I mean. I mean what I say. i do."
sentences = text.lower().split('.')
dic = {}
for i, sen in enumerate(sentences):
    for word in sen.split():
        if word not in dic:
            dic[word] = [i]
        elif dic[word][-1] != i:     # this prevents duplicate entries
            dic[word].append(i)

dic

rawDescription: word/pair list using dictionaries and strings

description: Word/pair list using dictionaries and strings


code:
b = '{:0{width}b}'.format(n, width=width)
int(b[::-1], 2)

rawDescription: Reversing bits of Python integer

description: Reversing bits of Python integer


code:
import argparse

parser = argparse.ArgumentParser(description=("Program desciption"))

parser.add_argument("-g", "--full-name-of-g", action='append',
                    help="what is g option for")

args = vars(parser.parse_args())

print(args['full_name_of_g'])

rawDescription: How to parse same argument twice or more than once to python script?

description: Parse same argument twice or more than once to python script


code:
import itertools

dct = {
    'bk1': {
        'k11': ['a1', 'b1', 'c1'],
        'k12': ['a2', 'b2', 'c2']
    },
    'bk2':{
        'k21': ['d1', 'e1'],
        'k22': ['d2', 'e2'],
        'k23': ['d3', 'e3']
    },
    'bk3': {
        'k31': ['f1', 'g1', 'h1'],
        'k32': ['f2', 'g2', 'h2']
    }
}

big_keys = dct.keys()
small_keys = (dct[big_key].keys() for big_key in big_keys)

res = {}
for keys_from_each in itertools.product(*small_keys):
    key = "_".join(keys_from_each)

    value = []
    for big_key, small_key in zip(big_keys, keys_from_each):
        value.extend(dct[big_key][small_key])

    res[key] = value

rawDescription: Concatenation of a variant number of keys of a dictionary Python (recursion?)


code: df.loc['row_name', 'column_name']

rawDescription: Using print to access individual cells of pandas dataframe after groupby


code:
try:
    dict(ENROLLMENT_STATUS)[self.enrollment_status]
except ValueError:
    raise # or whatever

rawDescription: Translating choices in Django without using loops?


code:
text = 'my name is ryan'
sum(len(w) == 2 for w in text.split())

rawDescription: how do i find the number of times a word is of len n in python?

description: Find the number of times a word is of len n in python


code:
eggs: 5
onions: 1
omelette: 26.0
pileofomelettes: 156.0

rawDescription: How do I replace lines in a file using data contained elsewhere in the same file?

description: Replace lines in a file using data contained elsewhere in the same file


code:
import html.entities
import re

def to_entitydef(match):
    n = ord(match.group())
    name = html.entities.codepoint2name.get(n)
    if name is None:
        return '&#{};'.format(n)
    return '&{};'.format(name)

def escape(text):
    return re.sub('.', to_entitydef, text)

rawDescription: Python html alphabet

description: Python html alphabet


code:
s = '0xDB52 Message 0x124A orderid 1504505254 for number 0xae45'
re.findall(r'0x[0-9A-F]+', s, re.I)

rawDescription: Extract hexadecimal number from string

description: Extract hexadecimal number from string


code:
import os

from django.core.management import call_command
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Description of your command.'

    def handle(self, *args, **options):
        if not os.environ.get('RUN_MAIN'):
            call_command('initialize_some_stuff', *args, **options)
        call_command('runserver', *args, **options)

rawDescription: Django app initialization process

description: Django app initialization process


code:
class Foo(object):
   a = []
   b = 2

rawDescription: New instance of Python class with a non-None class attribute


code:
import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
a=tree.find('parent')          # Get parent node from EXISTING tree
b=ET.SubElement(a,"child")
b.text="Jay/Doctor"
tree.write("test.xml")

rawDescription: Modify a XML using ElementTree

description: Modify a XML using ElementTree


code:
mytz = pytz.timezone('America/Los_Angeles')
now = datetime.datetime.now(tz=mytz)
now

rawDescription: Time issues in Python

description: Time issues in Python


code:
import Tkinter as tk
kybrd_list = ['q','w','e','r','t','y','...']
def onclick(k):
    def click():
        print(k)
    return click

class SimpleGridApp(object):
    def __init__(self, master, **kwargs):
        self.keyboardButtons = []
        for i, k in enumerate(kybrd_list):
            button = tk.Button(root, text=k, width=5, relief='raised',
                               command=onclick(k), state=tk.DISABLED)
            button.grid(row=i, column=0)
            self.keyboardButtons.append(button)

        self.enterCountryBtn = tk.Button(
            root, width=30, text="enter Country", command=self.countryCommand)
        self.enterCountryBtn.grid(row=7, column=0)
    def countryCommand(self):
        for button in self.keyboardButtons:
            button['state']=tk.NORMAL

root = tk.Tk()
app = SimpleGridApp(root, title='Hello, world')
root.mainloop()

rawDescription: tkinter enabling a list of buttons, but only one(the last one) responds

description: Tkinter enabling a list of buttons, but only one(the last one) responds


code:
np.arange(7, 8+eps)
np.arange(7, 8+eps, 0.3)
np.arange(7, 8+eps, 0.2)

rawDescription: Matlab range in Python

description: Matlab range in Python


code:
import magic
mime = magic.Magic(mime=True)
mime.from_file("result.tsv")

rawDescription: How to emulate Firefox "Save File" -> OK in Python

description: Emulate Firefox "Save File" -> OK in Python


code:
a_tags  = xml.xpath("//*[@id='yfncsumtab']//ul[position() < 7]//a")

paired = dict((a.xpath("./text()")[0].strip(), a.xpath("./@href")[0]) for a in a_tags)
from pprint import pprint as pp
pp(paired)

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code:
def handle(self, *args, **options):
    arguments = self._argv[1:]
    for arg in arguments:
        if arg in ('-', '--'):
            i = arguments.index(arg)
            new_arg = ''.join((arguments[i], arguments[i+1]))
            del arguments[i:i+2]
            arguments.insert(i, new_arg)

    from scrapy.cmdline import execute
    execute(arguments)

rawDescription: Django custom management command running Scrapy: How to include Scrapy's options?


code:
grid = [[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]]
list(findNeighbors(grid, 2, 1))   # find neighbors of 9
list(findNeighbors(grid, 3, 3))   # find neighbors of 15

rawDescription: Python, finding neighbors in a 2-d list

description: Python, finding neighbors in a 2-d list


code: df.drop('A', axis = 1) * z

rawDescription: python: multiplication of array to pandas dataframe

description: Python: multiplication of array to pandas dataframe


code:
result = {}
for obj in json_obj:
    result[obj['case_id']] = result.get(obj['case_id'], 0) + (obj['type'] == 'email_response')

result

rawDescription: How do you find the number of occurrence within a list of dictionaries

description: Find the number of occurrence within a list of dictionaries


code:
def logsumexp_csr_rows(X):
    result = np.empty(X.shape[0])
    for i in range(X.shape[0]):
        data = X.data[X.indptr[i]:X.indptr[i+1]]
        # fill in from logsumexp_csr_row
        result[i] = mx + np.log(r + k * np.exp(-mx))
    return result

rawDescription: Log-sum-exp trick on a sparse matrix in scipy


code: scaling = np.array([dx, dy, dz])

rawDescription: Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z


code:
import re
pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
s = 'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre http://t.co/Ad2oWDNd4u'
pattern.sub('', s)

rawDescription: How to remove words containing a substring in a python string?

description: Remove words containing a substring in a python string


code: result = foo(bar, baz, **quux)

rawDescription: Passing as kwargs, reading as args - a special or temporary feature?


code:
items = '- //components/rel/bt.wcnss/2.4/wcnss_proc/bt/platform/rom/inc/oi_sbc_tables-generated.h#1 - branch change 700801 (text)'
answer = items.rsplit('-',1);
k.append(answer[0].strip() + '\n')
# print answer[0].strip()

rawDescription: split based on the first "-" from the last in a line

description: Split based on the first "-" from the last in a line


rawDescription: broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array

description: Broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array


code:
d = FooMeta.__prepare__('Foo', ())
d['Foo'] = 123
def a(self):
    pass
d['a'] = a
Foo = FooMeta('Foo', (), d)

rawDescription: Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?


code:
from dateutil.relativedelta import relativedelta
adate + relativedelta(months=1)

rawDescription: How can I "change" a python struct_time object?

description: "change" a python struct_time object


code:
with open('csvbooks_out.csv', 'wt') as f:
    wtr = csv.writer(f)
    wtr.writerows(booklist)

rawDescription: Saving lists as a csv in python

description: Saving lists as a csv in python


code:
writer = csv.writer(open('dict.csv', 'wb'))
for key, value in mydict.items():
   writer.writerow([key, value])

rawDescription: Python: Writing a dictionary to a csv file with one line for every 'key: value'


code:
max_letter = w[0]
min_letter = w[0]

rawDescription: Program that counts most and least common non-space characters


code:
import os
def directory_paths(root):
    isdir = os.path.isdir
    for entry in os.listdir(root):
        new_root = os.path.join(root, entry)
        if isdir(new_root):
            yield new_root
            for path in directory_paths(new_root):
                yield path

rawDescription: List all branches of subfolders in directory with python


code: len(set(map(lambda x: x['age'], a)))

rawDescription: how to find the number of dictionaries with a particular value in an array of dictionaries?

description: Find the number of dictionaries with a particular value in an array of dictionaries


rawDescription: making multi-index in pandas dataframes in Python?

description: Making multi-index in pandas dataframes in Python


code:
def function(l, n=0, test=-1):
    if not l:
        return n == test
    else:
        n += l[0]
        return function(l[1:], n, test)

In [2]: function([1,2,3],test=6)
Out[2]: True

In [3]: function([1,2,3],test=5)
Out[3]: False

In [4]: function([1,2,3])
Out[4]: False

In [5]: function([])
Out[5]: False

rawDescription: How to compare a return value of a recursive function with an integer (actual parameter of function)

description: Compare a return value of a recursive function with an integer (actual parameter of function)


code:
import ROOT
# create an array of bytes (chars) and reserve the last byte for null
# termination (last byte remains zero)
char_array = bytearray(21)
# all bytes of char_array are zeroed by default here (all b'\x00')

# create the tree
tree = ROOT.TTree('tree', 'tree')
# add a branch for char_array
tree.Branch('char_array', char_array, 'char_array[21]/C')
# set the first 20 bytes to characters of a string of length 20
char_array[:21] = 'a' * 20
# important to keep the last byte zeroed for null termination!
tree.Fill()
tree.Scan('', '', 'colsize=21')

rawDescription: Python array of strings in a ROOT TTree

description: Python array of strings in a ROOT TTree


code: df

rawDescription: how to use groupby to avoid loop in python

description: Use groupby to avoid loop in python


code:
root2 = Tk()
root2.title("Result")
root2.style = Style()
root2.style.theme_use("clam")

rawDescription: Python Tkinter. Cant apply theme for second window of program


code:
class Pokemon(object):
    def __init__(self, default_accuracy=0):
        self._default_accuracy = default_accuracy
        self._accuracy = default_accuracy
        self._boosted_turns = 0
        self._hp = 100

    def boost(self, turns=3, boost=100):
        self._boosted_turns = turns
        self._accuracy = boost

    def _spend_boost(self):
        self._boosted_turns -= 1

    def _reset_accuracy(self):
        self._accuracy = self._default_accuracy

    def get_damaged(self, damage):
        self._hp = (self._hp - damage > 0 and self._hp - damage) or 0

    def perform_attack(self, Pokemon, attack):
        if attack == 'boost accuracy':
            self.boost()
        if self._boost_turns:
            self._spend_boost()
        else:
            self._reset_accuracy()
        # specify attack behaviour

rawDescription: Python: change variable for specific number of iterations in a loop


code: os.rename(inputfile + ".out", 'w')

rawDescription: Loop through multiple csv files, copying only certain columns to new files


code: mat_C = [[a+b for a,b in zip(row_A, row_B)] for row_A, row_B in zip(mat_A, mat_B)]

rawDescription: How can I add two elements of same indices of two 2D arrays in python?

description: Add two elements of same indices of two 2D arrays in python


code:
from urlparse import urljoin
base_url = 'https://www.website.com/'
urljoin(base_url, '/first/page')

rawDescription: Beautifulsoup, add attribute information (resource id) to url


rawDescription: Python: Index in a list of lists

description: Python: Index in a list of lists


code:
import matplotlib.pyplot as plt
H, xedges, yedges =np.histogram2d(x_axis, y_axis, bins=10, weights=z_axis)
extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]
plt.imshow(H, extent=extent, interpolation='nearest')
plt.colorbar()
plt.show()

rawDescription: numpy histogram with 3 variables

description: Numpy histogram with 3 variables


code:
import re

for title in [
        "a.bad.title.asdf.1975",
        "another bad title asdf.com 1975",
        "a really.bad title[1975]"]:
   print(" ".join(map(str.title, re.findall(r"\w+", title))))

rawDescription: Suggestions on Word Parsing

description: Suggestions on Word Parsing


rawDescription: Creating Network Graphs

description: Creating Network Graphs


code:
L = list(itertools.repeat("a", 20)) # 20 copies of "a"

L = list(itertools.repeat(10, 20))  # 20 copies of 10

L = list(itertools.repeat(['x','y'], 20)) # 20 copies of ['x','y']

rawDescription: Creating a list in Python with multiple copies of a given object in a single line


rawDescription: How to test for the second parameter of a mocked method?

description: Test for the second parameter of a mocked method


rawDescription: difference in csv.reader and pandas - python

description: Difference in csv.reader and pandas - python


code:
rounded_a = [round(elem, 2) for elem in a]
type(rounded_a[0]), type(rounded_b[0])

rawDescription: Rounding numbers - What's wrong here?

description: Rounding numbers - What's wrong here


code: output_help_to_file(r'test.txt', 're')

rawDescription: How do I export the output of Python's built-in help() function

description: Export the output of Python's built-in help() function


rawDescription: How to check if file already exists, if not, download on Python?

description: Check if file already exists, if not, download on Python


code:
class NodeClass(Base):
    __tablename__ = 'nodes_table'
    node_id = Column(Integer, primary_key=True)

    left_id = Column(Integer, ForeignKey('nodes_table.node_id'))
    left = relationship('NodeClass', remote_side=[node_id],
            primaryjoin=('NodeClass.left_id==NodeClass.node_id'),
            backref=backref("right", uselist=False),
            #lazy="joined", join_depth=9,
            )

rawDescription: Using SQLAlchemy with multiple self-referential foreign keys


rawDescription: Terminating generator expression

description: Terminating generator expression


rawDescription: Detect duplicates and create summarised rows


code:
def __mul__(self,other):
    dot=sum(p*q for p,q in zip(self.vector, other.vector))
    return (dot)

rawDescription: Python second class initialization

description: Python second class initialization


rawDescription: How to crawl a specific value out of a HTML page with python HTMLParser

description: Crawl a specific value out of a HTML page with python HTMLParser


code:
import numpy as np
a = np.matrix([[1, 2], [3, 4]])
b = np.matrix([[2, 2], [2, 2]])
a+b

rawDescription: Add two matrices in python

description: Add two matrices in python


code:
np.random.seed(0)
idx = pd.date_range('2015-1-1', '2016-1-1', freq='5min')
df = pd.DataFrame(np.random.randn(len(idx), 6),
                  columns=['Open', 'High', 'Low', 'Close', 'Up', 'Down'])
df['Datetime'] = idx

rawDescription: Select CONSECUTIVE rows from a DataFrame based on values in a column in Pandas with Groupby


code:
import scipy.signal as signal

# First, design the Buterworth filter
N  = 3    # Filter order
Wn = 0.1 # Cutoff frequency
B, A = signal.butter(N, Wn, output='ba')
smooth_data = signal.filtfilt(B,A, rawdata[0:500])
plt.plot(rawdata[0:500],'r-')
plt.plot(smooth_data[0:500],'b-')
plt.show()

rawDescription: How to average a signal to remove noise with Python

description: Average a signal to remove noise with Python


code:
import csv

with open('inputfile', newline='') as inputfile:
    reader = csv.reader(inputfile, delimiter='|')
    for row in reader:
        if len(row) > 5 and row[5].lower().startswith('command'):
            print(row[1], row[5])

rawDescription: python extracting second number in a line if meets a criteria

description: Python extracting second number in a line if meets a criteria


code:
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = ('author',)

rawDescription: Django edit form based on add form?

description: Django edit form based on add form


code:
def draw_grid(self, box):
    for element in self.map_layout.all_map_objects:
        collidepoint = box.area.collidepoint(element.checkpoint)
        if element not in self.build_grid and collidepoint:
            self.build_grid.append(element)
        elif not collidepoint:
            if element in self.build_grid:
                self.build_grid.remove(element)

rawDescription: How can I speed up this function?

description: Speed up this function


rawDescription: Filter Pyspark dataframe column with None value


code:
like_with_hive_udf.explain()

## TungstenProject [document_id#2L,keyword#4]
##  Filter document_text#3 LIKE concat(%,keyword#4,%)
##   CartesianProduct
##    Scan PhysicalRDD[document_id#2L,document_text#3]
##    Scan PhysicalRDD[keyword#4]

like_with_python_udf.explain()

## TungstenProject [document_id#2L,keyword#4]
##  Filter pythonUDF#13
##   !BatchPythonEvaluation PythonUDF#<lambda>(document_text#3,keyword#4), ...
##    CartesianProduct
##     Scan PhysicalRDD[document_id#2L,document_text#3]
##     Scan PhysicalRDD[keyword#4]

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code: buf.raw + sdata.tobytes()

rawDescription: python concatenate ctype struct and array

description: Python concatenate ctype struct and array


code:
d = {k:[] for k in  'abcdef'}
[id(x) for x in d.values()]

rawDescription: How to update values for specific keys in dict in Python

description: Update values for specific keys in dict in Python


code:
from operator import itemgetter

a = [{"id":1,"data":{"age":16,"name":"a"}},
     {"id":3,"data":{"age":35,"name":"b"}},
     {"id":2,"data":{"age":9,"name":"c"}}]

l=sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )

print (l)

rawDescription: Sort dict list with itemgetter

description: Sort dict list with itemgetter


code:
Pago.objects.filter(
    created__range=(self.inicio, self.fin)
).values(
    'tipo__nombre'
).annotate(
    monto=Sum('monto')
).order_by(
    'tipo__nombre'
)

rawDescription: Django adds extra columns to group by

description: Django adds extra columns to group by


code:
line = "<pattern number=1 theme=pseudo>"
import re
re.findall("theme=pseudo", line)

rawDescription: re.findall() doesn't matches with it's finding

description: Re.findall() doesn't matches with it's finding


code:
dicts = [dict1, dict2]
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), []))])

rawDescription: Updating or adding keys to dicts

description: Updating or adding keys to dicts


code:
if not dircheck.endswith(os.sep):
    homedir = dircheck + os.sep
else:
    dircheck = homedir

rawDescription: Checking if path ends in separation

description: Checking if path ends in separation


code:
mindexes = map(lambda x: x.argmin(), s)  #finding the minima
shifts = mindexes - min(mindexes)

def shifted(shift, x, s):
    if shift == 0:   #x[:-0] was not what I wanted.
        return x, s
    else:
        return x[:-1*shift], s[shift:]

for i in (0,1,2):
    px, py = shifted(shifts[i], x, s[i])
    plt.plot(px, py)
plt.show()

rawDescription: align three time series in python

description: Align three time series in python


code:
form = ExampleForm(request.POST or None,
                   instance=instance_variable,
                   some_variable=2015)

rawDescription: Pass values into Django form before form is made


code:
list1 = list2
list2 = [0]*len(list2)

rawDescription: Swap two lists in python

description: Swap two lists in python


code:
listWords = ['foo', 'bar', 'foobar', 'foo', 'bar']
indices_per_word = {}
for index, word in enumerate(listWords):
    indices_per_word.setdefault(word, []).append(index)

indices_per_word
for word, indices in indices_per_word.items():
    print(word, indices)

rawDescription: Find positon of words in list

description: Find positon of words in list


code:
for path, value in objwalk(element):
    if isinstance(value, int):
        parent = element
        for step in path[:-1]:
            parent = parent[step]
        parent[path[-1]] = hex(value)

rawDescription: Iterate over nested lists and dictionaries


code:
def max_temp(data):
    maximum = float('-inf')
    times = []
    for entry in data:
        time, temp = entry[:2]
        if temp == maximum:
            times.append(time)
        elif temp > maximum:
            maximum = temp
            times = [time]
    return maximum, times

rawDescription: All instances of maximum

description: All instances of maximum


code:
from datetime import datetime, timedelta

max_td = timedelta(days=30)
now = datetime.now()

# Remove events that are too far into the future
filtered_events = filter(lambda e: e[0] - now <= max_td, all_events)

# Sort events in ascending order of start time
filtered_events.sort()

rawDescription: How to set a date restriction for returned events in Google Calendar and put them in order - Python

description: Set a date restriction for returned events in Google Calendar and put them in order - Python


code:
def special_search(my_dict, pos, min, max):
    result = {}
    for item, tuples in my_dict.items():
        matches = []
        for i, t in enumerate(tuples):
            if min <= t[pos] <= max:
                matches.append(i)
        if matches:
            result[item] = tuple(matches)
    return result

rawDescription: How can I search a nested dictionary with specific constraints in mind

description: Search a nested dictionary with specific constraints in mind


code:
"""Wrap a single paragraph of text, returning a list of wrapped lines.

    Reformat the single paragraph in 'text' so it fits in lines of no
    more than 'width' columns, and return a list of wrapped lines.  By
    default, tabs in 'text' are expanded with string.expandtabs(), and
    all other whitespace characters (including newline) are converted to
    space.  See TextWrapper class for available keyword args to customize
    wrapping behaviour.
    """

rawDescription: Split a string into N equal parts?

description: Split a string into N equal parts


code:
def rotated(l, n):
    return l[n:] + l[:n]

def canonicalize(l):
    m = min(l)
    where = l.index(m)
    return rotated(l, where)

rawDescription: Removing similar, but not identical, lists from a list of lists in python


code:
def globFolder(path):
    output_1 = glob.glob(path + '\*.shp')

path1 = "C:\folder\data1"
path2 = "C:\folder\data2"

rawDescription: Python - Can glob be used multiple times?


code:
with open(filename) as f_in:
    lines = list(line for line in (l.strip() for l in f_in) if line)

rawDescription: Python: Easiest way to ignore blank lines when reading a file


code: d.scan_once(my_string, 6)

rawDescription: In python, is there a way to extract a embedded json string?


code:
key = "root.secondary.user2"
reduce(dict.get, key.split("."), my_dict)

rawDescription: Accessing python dict with multiple key lookup string


code:
c = Counter(dict((x.split()[0], float(x.split()[1])) for x in inp))
d = Counter(dict((x.split()[0], float(x.split()[1])) for x in inp2))

rawDescription: iterating through folder for files and add up values within the columned file in Python

description: Iterating through folder for files and add up values within the columned file in Python


code: XStrLenField("rand", "", length_from=lambda x: x.len)

rawDescription: Working with LenFields in ScaPy

description: Working with LenFields in ScaPy


code:
from matplotlib.transforms import  Transform

class LogPolarTransform(PolarAxes.PolarTransform):
    input_dims = 2
    output_dims = 2
    is_separable = False

    def __init__(self, axis=None, use_rmin=True):
        Transform.__init__(self)
        self._axis = axis
        self._use_rmin = use_rmin
    def transform_non_affine(self, tr):
        xy = np.empty(tr.shape, np.float_)
        if self._axis is not None:
            if self._use_rmin:
                rmin = self._axis.viewLim.ymin
            else:
                rmin = 0
            theta_offset = self._axis.get_theta_offset()
            theta_direction = self._axis.get_theta_direction()
        else:
            rmin = 0
            theta_offset = 0
            theta_direction = 1

        t = tr[:, 0:1]
        r = tr[:, 1:2]
        x = xy[:, 0:1]
        y = xy[:, 1:2]

        t *= theta_direction
        t += theta_offset

        r = r - rmin
        mask = r < 0
        x[:] = np.where(mask, np.nan, np.log(r) * np.cos(t))
        y[:] = np.where(mask, np.nan, np.log(r) * np.sin(t))

        return xy

    def inverted(self):
        return InvertedLogPolarTransform(self._axis, self._use_rmin)
    inverted.__doc__ = Transform.inverted.__doc__

class InvertedLogPolarTransform(Transform):
    """
    The inverse of the polar transform, mapping Cartesian
    coordinate space *x* and *y* back to *theta* and *r*.
    """
    input_dims = 2
    output_dims = 2
    is_separable = False

    def __init__(self, axis=None, use_rmin=True):
        Transform.__init__(self)
        self._axis = axis
        self._use_rmin = use_rmin

    def transform_non_affine(self, xy):
        if self._axis is not None:
            if self._use_rmin:
                rmin = self._axis.viewLim.ymin
            else:
                rmin = 0
            theta_offset = self._axis.get_theta_offset()
            theta_direction = self._axis.get_theta_direction()
        else:
            rmin = 0
            theta_offset = 0
            theta_direction = 1

        x = xy[:, 0:1]
        y = xy[:, 1:]
        r = np.exp(np.sqrt(x*x + y*y))
        with np.errstate(invalid='ignore'):
            # At x=y=r=0 this will raise an
            # invalid value warning when doing 0/0
            # Divide by zero warnings are only raised when
            # the numerator is different from 0. That
            # should not happen here.
            theta = np.arccos(x / r)
        theta = np.where(y < 0, 2 * np.pi - theta, theta)

        theta -= theta_offset
        theta *= theta_direction
        theta %= 2 * np.pi

        r += rmin

        return np.concatenate((theta, r), 1)

    def inverted(self):
        return PolarAxes.LogPolarTransform(self._axis, self._use_rmin)

rawDescription: Log scale on radial contour plot with matplotlib


code:
isinstance([1, 2, 3], collections.Sized)
isinstance(np.arange(10), collections.Sized)
isinstance(1, collections.Sized)

rawDescription: What is the most pythonic way to use len on a scalar?


code:
#!/usr/bin/env python
def mm_to_inches(mm):
    """Convert *mm* to inches."""
    return mm * 0.039370

with open('rainfalls.txt') as input_file, \
     open('rainfallInInches.txt', 'w') as output_file:
    for line in input_file:
        if line.strip(): # non-blank
            city, rainfall_mm = line.split() # no comments
            output_file.write("{city} {rainfall:.2f}\n".format(city=city,
                rainfall=mm_to_inches(float(rainfall_mm))))

rawDescription: Python File Writing Format Issue

description: Python File Writing Format Issue


code:
set_l = set(l)
mutual_followers = [x for x in set_l if x[::-1] in set_l]

rawDescription: Algorithm to find follow relationship like Twitter


code:
class sqlTableModel(QSqlTableModel):
    def __init__(self, parent=None):
        super(sqlTableModel, self).__init__(parent)

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            value = value.strip() if type(value) == str else value

        return super(sqlTableModel, self).setData(index, value, role)

    def flags(self, index):
        itemFlags = super(sqlTableModel, self).flags(index)

        if index.column() != 0:
            return itemFlags | Qt.ItemIsEditable

        return itemFlags ^ Qt.ItemIsEditable #  First column not editable

rawDescription: PyQt - QTableView doesn't respond dataChanged signal?


code:
# here are the parts that stay the same...

jibarTermStructure = ql.RelinkableYieldTermStructureHandle()
jindex = ql.Jibar(ql.Period(3,ql.Months), jibarTermStructure)
jindex.addFixings(dtes, fixings)
discountStructure = ql.RelinkableYieldTermStructureHandle()

bond = ql.FloatingRateBond(settlementDays = 0,
                          faceAmount = 100,
                          schedule = schedule,
                          index = jindex,
                          paymentDayCounter = ql.Actual365Fixed(),
                          spreads=[0.02])

bondengine = ql.DiscountingBondEngine(discountStructure)
bond.setPricingEngine(bondengine)

# ...here is the pricing function...

def price_floater(myqlvalDate,jibar_curve,discount_curve):
    ql.Settings.instance().evaluationDate = myqlvalDate
    jibarTermStructure.linkTo(jibar_curve)
    discountStructure.linkTo(discount_curve)
    return [bond.NPV() ,bond.cleanPrice()]

# ...and here are the remaining varying parts:

df_ad=pd.DataFrame(all_dates,columns=['valDate'])
df_ad['qlvalDate']=df_ad.valDate.map(lambda x:ql.DateParser.parseISO(x.strftime('%Y-%m-%d')))
df_ad['flatCurve'] = df_ad.apply(lambda r: ql.FlatForward(r['qlvalDate'],0.1,ql.Actual365Fixed(),compounding,compoundingFrequency),axis=1)
df_ad['discount_curve']= df_ad.apply(lambda x:ql.ZeroSpreadedTermStructure(jibarTermStructure,ql.QuoteHandle(ql.SimpleQuote(math.log(1+0.02)))),axis=1)
df_ad['all_in_price']=df_ad.apply(lambda r:price_floater(r['qlvalDate'],r['flatCurve'],r['discount_curve'])[0],axis=1)
df_ad['clean_price']=df_ad.apply(lambda r:price_floater(r['qlvalDate'],r['flatCurve'],r['discount_curve'])[0],axis=1)
df_plt=df_ad[['valDate','all_in_price','clean_price']]
df_plt=df_plt.set_index('valDate')

rawDescription: Daily Pricing of a Bond with QuantLib using Python


code:
from datetime import timedelta
d = timedelta(microseconds=-1)
(d.days, d.seconds, d.microseconds) (-1, 86399, 999999)

rawDescription: Why does datetime.datetime.now() - datetime.datetime.now() equal to datetime.timedelta(-1, 86399, 999974)?


rawDescription: How can i return maximum number in range in Python

description: Return maximum number in range in Python


code:
# step 1: create the index
idx = (D.category_code== 'B') | (D.category_code == 'C')
# then filter the data against that index:
D.ix[idx]

rawDescription: Filter numpy ndarray (matrix) according to column values


code:
import re
zone_def = re.split('zone', st, re.DOTALL)
big_dict = {}
for zone in zone_def:
    if len(zone) > 0:
        zone_name = re.search('(".*?")', zone)
        sub_dicts = re.finditer('([\w]+) ({.*?})', zone, re.DOTALL)
        big_dict[zone_name.group(1)] = {}
        for sub_dict in sub_dicts:
            big_dict[zone_name.group(1)][sub_dict.group(1)] = sub_dict.group(2).replace(' ', '')
        sub_types = re.finditer('([\w]+) (.*?);', zone)
        for sub_type in sub_types:
            big_dict[zone_name.group(1)][sub_type.group(1)] = sub_type.group(2)

rawDescription: python parse bind configuration with nested curly braces

description: Python parse bind configuration with nested curly braces


rawDescription: Dice generator, Picking number of sides in PYTHON 3.3.4


code:
class Maintenance(webapp2.RequestHandler):
    def get(self):
        self.response.write (
            "My app is down for maintenance and should be back up shortly.")
    def post(self):
        self.response.write (
            "My app is down for maintenance and should be back up shortly.")

rawDescription: GAE/P - schedule downtime for maintenance


code:
import re
re.findall(r'(?:X[0-9]+)+', 'YYYX4X5Z3X2')

rawDescription: Matching sequentially repeated brackets with Python Regex


rawDescription: Python Regex: Optional White Space Around Matching Group


code:
input= """\
href="http://www.sciencedirect.com/science/article/pii/S0167923609002097" onmousedown="return scife_clk(this.href,'','res','2')">Using text mining and sentiment analysis for online forums hotspot detection and forecast

N Li, How to link ontologies and protein–protein interactions to literature: text-mining approaches and the BioCreative experience

[HTML] from nih.govnih.gov (.*)',line)
    if m:
        print(m.group(1))

rawDescription: extracting string using regular expression

description: Extracting string using regular expression


code:
points_1 = (19.114315,72.911174)
points_2 = (19.112398,72.912743)
threshold_km = 0.5

distance_km = haversine(points_1[0], points_1[1], points_2[0], points_2[1])
if distance_km < threshold_km:
    print('within range')
else:
    print('outside range')

rawDescription: how to find user location within 500 meters from given lat and long in python

description: Find user location within 500 meters from given lat and long in python


code:
from nltk.tree import Tree
tree = Tree('S', [Tree('Clause', [Tree('Process-dependencies', [Tree('Participant', [('This', 'DT')]), Tree('Verbal-group', [('is', 'VBZ')]), Tree('Participant', [('a', 'DT'), ('representation', 'NN')]), Tree('Circumstance', [('of', 'IN'), ('the', 'DT'), ('grammar', 'NN')])])]), ('.', '.')])
standoff(tree)

rawDescription: Converting NLTK phrase structure trees to BRAT .ann standoff


code:
strip_empty_lines('''\

        some indentation here

lorem ipsum

''')
strip_empty_lines('''\
\t  \t
    \n
        some indentation here

lorem ipsum

''')

rawDescription: python - remove empty lines from end and beginning of string

description: Python - remove empty lines from end and beginning of string


code: element = webdriver.find_element_by_xpath("//td[contains(., '8')]")

rawDescription: Python Selenium return HTML location

description: Python Selenium return HTML location


rawDescription: Regex pattern problem in python

description: Regex pattern problem in python


code:
u = zip(*zs)
u

rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


code: xtickNames = plt.setp(ax, xticklabels=[str(v) for v in values])

rawDescription: matplotlib: setting xticklabels returned some "help" output

description: Matplotlib: setting xticklabels returned some "help" output


code:
b = np.zeros(a.shape,dtype=bool)
c = np.zeros(a.shape,dtype=bool)
c[cutoff:] = a[cutoff:]
b[:cutoff] = a[:cutoff]

rawDescription: What is best way to find first half of True's in boolean numpy array?


code:
class MyClass(BaseClass):

    def my_method():
        for item in self.my_collection:
            if item.numeric_property % 2:
                self.my_property = item.other_property + item.age * self.my_coefficient
        self.do_other_stuff()

rawDescription: Should I use camelCase to abide by pep-8 line length?


code:
s1 = LineString((0, 0), (1, 1), (1, 2), (0, 1))
s1.convex_hull
s1.convex_hull.coords
m1=MultiLineString(s1)
m1.convex_hull
m1.convex_hull.coords

rawDescription: How to convert a GEOS MultiLineString to Polygon using Python?

description: Convert a GEOS MultiLineString to Polygon using Python


code:
names = ["gymnastics_school", "participant_name", "all_around_points_earned"]
Data = collections.namedtuple("Data", names)
d = Data('school', 'name', '50.0')
d.gymnastics_school
d.participant_name
d.all_around_points_earned

rawDescription: opening txt file and creating list and getting basic stats

description: Opening txt file and creating list and getting basic stats


rawDescription: Python ElementTree find() not matching within kml file


rawDescription: Scrape a Google Chart script with Scraperwiki (Python)


rawDescription: Bokeh Plotting: Enable tooltips for only some glyphs


code: subprocess.check_call( ["./test.sh %s" % loop], shell=True)

rawDescription: Passing variable from python script to bash script


rawDescription: How do you split a list into evenly sized chunks in Python?

description: Split a list into evenly sized chunks in Python


code:
def am_able_to(tagged):
    return any(['am', 'able', 'to', 'VB'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][0], tagged[i+3][1]] for i in xrange(len(tagged) - 3))

rawDescription: detecting POS tag pattern along with specified words

description: Detecting POS tag pattern along with specified words


code:
class User(object):
    def __eq__(self,other):
       return self.userID == other
   #other methods here

rawDescription: Python if Statement not finding value

description: Python if Statement not finding value


code:
#from django.shortcuts import render <- delete this line
from myutils import myrender as render
def index(request):
    return render(request, 'app/index.html', { 'foo': 'bar', })

rawDescription: Get template name in template tag ( Django )


code:
cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
result = cmds.render('persp', x=512, y=512)

rawDescription: how to save multi images by MEL command

description: Save multi images by MEL command


code:
def calc(x):
    return eval(name)

rawDescription: how to set .__name__ in python?

description: Set .__name__ in python


rawDescription: Getting a N-element vector of values evenly spaced from -X to X


code:
func(positional_args, keyword_args,
                     *tuple_grp_nonkw_args, **dict_grp_kw_args)

rawDescription: Assign variables to the list elements, without knowing it's length


code:
@task
def provision():
    execute(stuff_to_do_on_all_hosts)
    execute(stuff_to_do_on_mongo_primaries)

@task
def stuff_to_do_on_all_hosts():
    do_stuff()

@task
@roles('mongo')
def stuff_to_do_on_mongo_primaries():
    if not is_primary():
        return
    add_user()
    do_other_stuff()

rawDescription: Can a fabric task execute other tasks and respect decorators such as runs_once?


code:
from scipy.sparse import spdiags, lil_matrix, vstack, hstack
from scipy.sparse.linalg import spsolve
import numpy as np

def solve(n):
    nrange = np.arange(n)
    diag = np.ones(n-1)

    # upper left block
    n_to_M = spdiags(-2. * diag, 0, n-1, n-1)

    # lower left block
    n_to_N = spdiags([n * diag, -nrange[-1:0:-1]], [0, 1], n-1, n-1)

    # upper right block
    m_to_M = lil_matrix(n_to_N)
    m_to_M[1:, 0] = -nrange[1:-1].reshape((n-2, 1))

    # lower right block
    m_to_N = lil_matrix((n-1, n-1))
    m_to_N[:, 0] = -nrange[1:].reshape((n-1, 1))

    # build A, combine all blocks
    coeff_mat = hstack(
                       (vstack((n_to_M, n_to_N)),
                        vstack((m_to_M, m_to_N))))

    # const vector, right side of eq.
    const = n * np.ones((2 * (n-1),1))

    return spsolve(coeff_mat.tocsr(), const).reshape((-1,1))

rawDescription: How to set up and solve simultaneous equations in python

description: Set up and solve simultaneous equations in python


code:
L1 = L[:]       #make a copy of L
L1.append(i1)

rawDescription: python: list manipulation

description: Python: list manipulation


code:
from functools import partial
def _header_footer(canvas, doc, custom_data):
    ...

# Usage:
doc.build(elements, onFirstPage=partial(_header_footer, custom_data=my_custom_data))

rawDescription: Parameter to reportlab header using Django


code: key = next(lst for lst in d.values() if 'b' in lst)

rawDescription: How to access a list containing specific item in a dictionary?

description: Access a list containing specific item in a dictionary


rawDescription: Switching from SQLite to MySQL with Flask SQLAlchemy


code: sys.stdout.write("\b ")

rawDescription: Clearing old data from sys.stdout in Python


code:
from scrapy import log
from scrapy.item import Item
from scrapy.http import Request
from scrapy.contrib.spiders import XMLFeedSpider

def NextURL():
    urllist =[]
    with open("URLFilename") as f:
        for line in f:
            urllist.append(line)

class YourScrapingSpider(XMLFeedSpider):

    name = "imagespider"

    allowed_domains = []

    url = NextURL()

    start_urls = []

    def start_requests(self):

        start_url = self.url.next()

        request = Request(start_url, dont_filter=True)

        yield request

    def parse(self, response, node):

        scraped_item = Item()
        yield scraped_item
        next_url = self.url.next()
        yield Request(next_url)

rawDescription: Parsing txt file, to web scrape an image from each link on each line, with python


rawDescription: How reverse query OnetoOne Django

description: How reverse query OnetoOne Django


code:
def find_ip(s, f):
    with open(f) as f:
        for line in f:
            if line.startswith("lease "):
                ip = line.rstrip().split()[1]
                for n_line in f:
                    if n_line.find(s) != -1:
                        return ip.rstrip("{")
                    if n_line.startswith("}"):
                        break
    return "No match"

rawDescription: Extract Information From a File

description: Extract Information From a File


code:
zero_data = data.fillna(0)
distance = lambda column1, column2: scipy.stats.pearsonr(column1, column2)[0]
result = zero_data.apply(lambda col1: zero_data.apply(lambda col2: distance(col1, col2)))
result.head()

rawDescription: Distance matrix for rows in pandas dataframe


code:
def _get_AF(self):
    return self._AF

rawDescription: How to set functions for a property()?

description: Set functions for a property()


code:
csv_file = 'file.csv'
with open(csv_file, 'wb') as fd:
    writer = csv.writer(fd, delimiter=',')

    keys = sorted(dictionary)
    # Format headers for aesthetics
    headers = [' {} '.format(key) for key in keys]
    writer.writerow(headers)

    # Format data to create convenient csv format
    csv_data = itertools.izip_longest(*(dictionary[key] for key in keys),
                                      fillvalue='     ')
    writer.writerows(csv_data)

rawDescription: How to sort uneven dictionary by key and create CSV

description: Sort uneven dictionary by key and create CSV


code:
def computer_guess(num):
    low = 1
    high = 100
    guess = 50
    while guess != num:
        guess = (low+high)//2
        print("The computer takes a guess...", guess)
        if guess > num:
            high = guess
        elif guess < num:
            low = guess + 1

    print("The computer guessed", guess, "and it was correct!")

def main():
    num = int(input("Enter a number: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

if __name__ == '__main__':
    main()

rawDescription: Guess the number game optimization (user creates number, computer guesses)


code: SearchList = search.all()

rawDescription: Can I dynamically change order_by attributes in my query call?

description: Dynamically change order_by attributes in my query call


code:
import re
# escape meta characters
invalid = u''.join(combined).replace('-', r'\-').replace(']', r'\]')
invalid = re.compile(u'([^{}])'.format(invalid))

rawDescription: In python replacing characters from multiple char maps


code:
df
df['s'] = df.groupby('cluster_id').cumsum()
df

rawDescription: Pandas dataframe - running sum within cluster


code:
def with_coo(x,y):
    x=x.tocoo()
    y=y.tocoo()
    d = np.concatenate((x.data, y.data))
    r = np.concatenate((x.row, y.row))
    c = np.concatenate((x.col, y.col))
    C = sparse.coo_matrix((d,(r,c)))
    return C

rawDescription: Adding two `csc` sparse matrices of different shapes in python


code:
from collections import Counter

def change(amount):
    money = ()

    for coin in [200, 100, 50, 20, 10, 5, 1, 0.5]:
        num = int(amount/coin)
        money += (coin,) * num
        amount -= coin * num

    return Counter(money)

rawDescription: Work out correct money denominations for change


code: fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )

rawDescription: how do I make a single legend for many subplots with matplotlib?

description: Make a single legend for many subplots with matplotlib


code:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Status(models.Model):
    request_type = models.ForeignKey(ContentType)
    request_id = models.PositiveIntegerField()
    request = GenericForeignKey('request_type', 'request_id')

rawDescription: Django model one foreign key to many tables


code:
import itertools
import pandas as pd
import lxml.etree as et
import numpy as np
import sys
import multiprocessing as mp
import logging
logger = mp.log_to_stderr(logging.INFO)

def make_toys(df):
    result = []
    for index, row in df.iterrows():
        toys = [Toy(row) for _ in range(row['number'])]
        result += [x for x in toys if x is not None]
    return result

class Toy(object):
    def __new__(cls, *args, **kwargs):
        x = np.random.uniform() <= 0.97
        if x:
            return super(Toy, cls).__new__(cls, *args, **kwargs)
        logger.info('Returning None')

    def __init__(self, row):
        self.id = None
        self.type = row['type']

    def set_id(self, x):
        self.id = x

    def write(self, tree):
        et.SubElement(tree, "toy", attrib={'id': str(self.id), 'type': self.type})

if __name__ == "__main__":
    table = pd.DataFrame({
        'type': ['a', 'b', 'c', 'd'],
        'number': [5, 4, 3, 10]})

    n_cores = 2
    split_df = np.array_split(table, n_cores)

    p = mp.Pool(n_cores)
    pool_results = p.map(make_toys, split_df)
    p.close()
    p.join()
    l = [a for L in pool_results for a in L]

    box = et.Element("box")
    box_file = et.ElementTree(box)

    for i, toy in itertools.izip(range(len(l)), l):
        toy.set_id(i)

    for x in l:
        x.write(box)

    box_file.write(sys.stdout, pretty_print=True)

rawDescription: Parallel and conditional: NoneType object has no attribute '__dict__'


code:
from itertools import product

out = np.zeros((N**3,4),dtype=int)
out[:,:3] = list(product(np.arange(N), repeat=3))

rawDescription: Python List of Lists vs numpy

description: Python List of Lists vs numpy


rawDescription: ply concatenating strings on grammar

description: Ply concatenating strings on grammar


code:
a_nums = [int(n) for n in a.split(',')]
b_nums = [int(n) for n in b.split(',')]

rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


rawDescription: Pythonic way to manipulate same dictionary


code:
@valid_range(10, 20)
def f(x):
    pass

rawDescription: Passing arguments to a decorator using the decorator module


code: results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", "")))

rawDescription: How to convert dictionary values to int in Python?

description: Convert dictionary values to int in Python


code:
mask = a.astype(bool)
a[mask] += 2

rawDescription: Selective Numpy array manipulation (dependent on value)


rawDescription: Getting positions of specific values of a 2D NumPy array with mask


code:
import csv

with open("infile1.txt", 'r') as infile1,\
     open('infile2.txt', 'r') as infile2,\
     open('outfile.txt', 'w') as outfile:
    trans_dict = dict(csv.reader(infile1, delimiter="\t"))

    for line in infile2:
        outfile.write(trans_dict.get(line.strip(),line.strip()) + "\n")

rawDescription: search contents of one file with contents of a second file using python

description: Search contents of one file with contents of a second file using python


code:
vals_col1 = Set(Set(Couplet('col1', 'foo')))
vals_col3 = Set(Set(Couplet('col3', 'baz1')), Set(Couplet('col3', 'baz2')))
vals_col4 = Set(Set(Couplet('col4', 'nurf1')), Set(Couplet('col4', 'nurf2')))
pred_as_clan = clans.cross_union(vals_col1, clans.cross_union(vals_col3, vals_col4))
answer = clans.superstrict(data_clan, pred_as_clan)
answer = sets.restrict(answer, lambda rel: rel('col5') < Atom(date(2015, 4, 1)) < rel('col6'))

rawDescription: Writing complex query using algebraixlib


rawDescription: puzzled on how to slice a numpy array

description: Puzzled on how to slice a numpy array


code:
features = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation",
            "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country"]
input_text = """38   Private    215646   HS-grad    9    Divorced    Handlers-cleaners   Not-in-family   White   Male   0   0   40   United-States   <=50K
53   Private    234721   11th   7    Married-civ-spouse  Handlers-cleaners   Husband     Black   Male   0   0   40   United-States   <=50K
30   State-gov  141297   Bachelors  13   Married-civ-spouse  Prof-specialty  Husband     Asian-Pac-Islander  Male   0   0   40   India   >50K
"""

rawDescription: handling too many categorical features using scikit-learn

description: Handling too many categorical features using scikit-learn


code:
df['USRECQ NEXT'] = df['USRECQ'].shift(-1)
df

rawDescription: Boolean Check in a Pandas DataFrame based on Criteria at different Index values


rawDescription: Using Sikuli to take automated screenshots of a window?


code:
print([d["NODE"] for d in node.values()])
['CLOUDY', 'RAIN', 'SPRINKLER', 'WETGRASS']

rawDescription: Grab Values Within a Dictionary in a Dictionary


code:
a = np.arange(25, dtype=float).reshape(5, 5)
a

rawDescription: convert 2d numpy array to string

description: Convert 2d numpy array to string


code:
class Contacts:
    all_contacts = []

    def __init__(self, name, email):
       self.name = name
       self.email = email
       Contacts.all_contacts.append(self)

    def __str__(self):
       return '%s, <%s>' % (self.name, self.email)

    def __repr__(self):
        return str(self)

rawDescription: How do I print this class variable?

description: Print this class variable


rawDescription: How to save pictures with lower resolution in python?

description: Save pictures with lower resolution in python


code:
print(set(nee))
# set(['A', 'A2'])

print(set(nejsou.ASS.tolist()))
# set(['A', 'AF2', 'AF'])

rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results


code:
query = "SELECT * FROM `table` AS t WHERE t.`categoryID`={}".format(category_id)
if record_id:
    query += " AND t.`recordID`={}".format(record_id)

rawDescription: Best way of gluing strings in Python to compose SQL query


code: var = subprocess.check_call(['awk', '-F|', '{print $2}', file])

rawDescription: python subprocess awk with -F option and using variable for input file

description: Python subprocess awk with -F option and using variable for input file


code: cursor = coll.find({"place.bounding_box.type" : "Polygon"}, {"place.bounding_box.coordinates" : 1})

rawDescription: Extracting data from a mongo collection

description: Extracting data from a mongo collection


code:
tempBoard = list(genBoard)
tempBoard = genBoard[:]
tempBoard = copy.copy(genBoard)

rawDescription: Generate list of possible moves Python Tic-Tac-Toe


rawDescription: Scipy label erosion

description: Scipy label erosion


code:
_result = a['vector_2']  # via a.__getitem__('vector_2')
_result[0, 1, 2]         # via _result.__getitem__((0, 1, 2))

rawDescription: __getitem__ for a list vs a dict

description: __getitem__ for a list vs a dict


code: df.index = ['/'.join(i) for i in df.index]

rawDescription: Pandas: transforming the DataFrameGroupBy object to desired format


code: filename, regex = line.split(' ', 2)[1:]

rawDescription: Python/Regex splitting a specifically formatted return string


code:
from operator import attgetter

used, free = attrgetter('used', 'free')(psutil.swap_memory())

rawDescription: When calling a function from a module can you say what is returned? (Python)


rawDescription: pandas split string into columns

description: Pandas split string into columns


code:
def autoargs(l):
    self = l.pop('self')
    for k,v in l.items():
        setattr(self, k, v)

class Base(object):
    def __init__(self, a, b, c):
        autoargs(locals())

rawDescription: A Common constructor in Python

description: A Common constructor in Python


code:
from timeit import timeit
import numpy as np
myList = list(np.random.rand(100))
so = np.argsort(myList) #converts list to NumPy internally
timeit(lambda: [myList2[i] for i in so])
myArray = np.random.rand(100)
so = np.argsort(myList)
timeit(lambda: a[o])

rawDescription: How to sort a list based on the output of numpy's argsort function

description: Sort a list based on the output of numpy's argsort function


code:
with open('file1.txt') as f1,open('file2.txt','w') as f2:
 for line in f1:
   x=line.split()   #now x is ['AlphaforBravo007', '102000000010170000000001', 'SusanaForCharlie', '1000', 'end']
   f2.write('\n'.join((x[1],x[3]))+'\n')

rawDescription: Copying some data of a file and pasting it to another file in python


code:
def fix_json(string_):
    if string_[0] == string_[-1] == "'":
        return '"' + string_[1:-1] +'"'
    return string_

rawDescription: Proper way to deal with string which looks like json object but it is wrapped with single quote


code:
import clr
clr.CompileModules(dllname, module1.py, module2.py,...)

rawDescription: how to deploy a C# application that calls numpy through IronPython

description: Deploy a C# application that calls numpy through IronPython


code:
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

rawDescription: TastyPie Authentication from the same server


rawDescription: Tkinter - what's the Index of selected value in spinbox?


code: arduino.write('%d' % (5,))

rawDescription: PySerial communication with variables

description: PySerial communication with variables


rawDescription: Pandas: Splitting and editing file based on dictionary


code:
@my_decorator(5)
def function():
    return 5

rawDescription: Why are Python decorators with arguments syntactically different from those without?


code:
import os

filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
    filesList = files
    break
print(filesList)

rawDescription: not listing entire directory

description: Not listing entire directory


rawDescription: Update dictionary in xml from csv file in python


code:
from bs4 import BeautifulSoup
import requests
from urlparse import urljoin # python 3 -> from urllib.parse import urljoin

def get_links():
    # cretate all css selectors
    ytlink = 'https://www.youtube.com/channel/UCUvoulvwzCnUVk7yoduI_Gw/videos'
    ajax_css = "button[data-uix-load-more-href]"
    link_css = "a.yt-uix-sessionlink.yt-uix-tile-link.spf-link.yt-ui-ellipsis.yt-ui-ellipsis-2"
    base = "https://www.youtube.com/"

    r = requests.get(ytlink).content
    soup = BeautifulSoup(r, "lxml")

    # yield first visible links
    for link in soup.select(link_css):
        yield urljoin(base, link["href"])

    # Load more button
    ajax = soup.select(ajax_css)[0]["data-uix-load-more-href"]

    while True:
        print(ajax)
        r = requests.get(urljoin('https://www.youtube.com/', ajax))

        # next html is stored in the json.values()
        soup = BeautifulSoup("".join(r.json().values()), "lxml")
        for link in soup.select(link_css):
            yield urljoin(base, link["href"])

        ajax = soup.select(ajax_css)
        # if empty "Load more" button would be gone
        if not ajax:
            break
        ajax = ajax[0]["data-uix-load-more-href"]

rawDescription: Python expanding YouTube uploads

description: Python expanding YouTube uploads


rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code:
bb = B([A(i) for i in range(10)])
print(list(bb.a))

rawDescription: Get attribute of all items in container python


code:
import re
tst=u'\'\'\'Joseph Michael "Joe" Acaba\'\'\' (born May 17, 1967) is an [[Teacher|educator]], [[Hydrogeology|hydrogeologist]], and [[NASA]] [[astronaut]].<ref name="bio">{{Cite web|url=http://www.jsc.nasa.gov/Bios/htmlbios/acaba-jm.html|title=Astronaut Bio: Joseph Acaba|month=February | year=2006|publisher=[[NASA|National Aeronautics and Space Administration]]|author=NASA|accessdate=November 26, 2006}}</ref><ref name="bio2">{{Cite web|url=http://oeop.larc.nasa.gov/hep/hep-astronauts.html|title=NASA Hispanic Astronauts\n|publisher=National Aeronautics and Space Administration|author=NASA|accessdate=November 26, 2006}}</ref> In May 2004 he became the first person'
ref = re.compile(u'<ref.*?ref>', re.DOTALL)
ref.sub(u'', tst)

rawDescription: How can I remove a substring, given a start and end token, in python?

description: Remove a substring, given a start and end token, in python


rawDescription: Computing future value of an account, when the user enters in the present value, interest rate, and number of years


code:
import itertools
[''.join(x) for x in itertools.izip_longest(*[iter(a)]*3, fillvalue=' ')]

rawDescription: Python - How to add space on each 3 characters?


code:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(211)
ax1.scatter(x1, y1, c = 'r', alpha = 0.3)

ax2 = fig.add_subplot(212)
ax2.scatter(x2, y2, c = 'k', alpha = 0.7)

plt.show()

rawDescription: creating and referencing separate matplotlib plots

description: Creating and referencing separate matplotlib plots


code:
import time
import os

start = time.time()

os.system("tar -cvf name.tar /path/to/directory")
os.system("gzip name.tar")

end = time.time()
print("Elapsed time: %s"%(end - start,))

rawDescription: Faster way to compress folder in python

description: Faster way to compress folder in python


code:
import sys

from PyQt5 import QtCore, QtWebSockets, QtNetwork
from PyQt5.QtCore import QUrl, QCoreApplication, QTimer
from PyQt5.QtWidgets import QApplication

class Client(QtCore.QObject):
    def __init__(self, parent):
        super().__init__(parent)

        self.client =  QtWebSockets.QWebSocket("",QtWebSockets.QWebSocketProtocol.Version13,None)
        self.client.error.connect(self.error)

        self.client.open(QUrl("ws://127.0.0.1:1302"))
        self.client.pong.connect(self.onPong)

    def do_ping(self):
        print("client: do_ping")
        self.client.ping(b"foo")

    def send_message(self):
        print("client: send_message")
        self.client.sendTextMessage("asd")

    def onPong(self, elapsedTime, payload):
        print("onPong - time: {} ; payload: {}".format(elapsedTime, payload))

    def error(self, error_code):
        print("error code: {}".format(error_code))
        print(self.client.errorString())

    def close(self):
        self.client.close()

def quit_app():
    print("timer timeout - exiting")
    QCoreApplication.quit()

def ping():
    client.do_ping()

def send_message():
    client.send_message()

if __name__ == '__main__':
    global client
    app = QApplication(sys.argv)

    QTimer.singleShot(2000, ping)
    QTimer.singleShot(3000, send_message)
    QTimer.singleShot(5000, quit_app)

    client = Client(app)

    app.exec_()

rawDescription: How to create a websocket client by using QWebSocket in PyQt5

description: Create a websocket client by using QWebSocket in PyQt5


code:
import sys
sys.stdout = open('file.txt', 'w')

rawDescription: putting python output to text file using cron-job

description: Putting python output to text file using cron-job


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

    @staticmethod
    def lineFromPoints(point1, point2):
        deltaX = point2[0] - point1[0]
        deltaY = point2[1] - point1[1]
        if deltaX == 0:
            return line(point1[0], 0, True)
        else:
            a = deltaY / deltaX
            b = point1[1] - a * point1[0]
            return line(a, b, False)

    @staticmethod
    def lineFromVector(vector, point):
        if vector[0] == 0:
            return line(point1[0], 0, True)
        else:
            a = vector[1] / vector[0]
            b = point1[1] - a * point1[0]
            return line(a, b, False)

# Create instance of class
myLine = line.lineFromPoints((0,0), (1,1))

rawDescription: Best practice to implement multiple contructors in python


code:
def translator(s):
    for original, replacement in bad_chars.iteritems():
        s = s.replace(original, replacement)
    return s

rawDescription: implementing multiple string replace() using lambda function

description: Implementing multiple string replace() using lambda function


code:
import webapp2

class MyHandler(webapp2.RequestHandler):
    def get(self):
        foo = self.app.config.get('foo')
        self.response.write('foo value is %s' % foo)

rawDescription: Passing parameters to a webapp2.RequestHandler object in python


code:
def sort_dns(l):

    to_return = []
    # Get top-level domains: the domains that contain the less amount of dots.
    count_list = [i.count('.') for i in l]
    min_dots = min(count_list)
    top_domains = [i for i in l if i.count('.') == min_dots]
    # Now for each domain, we find it subdomains.
    for domain in top_domains:
        sub_domains = [i for i in l if domain in i and i is not domain]
        #And untill we aren't at the deepest level, we continue looking for sub domains and repeat the structure
        sub_sub_domains = sort_dns(sub_domains) if not len(sub_domains) == 0 else None
        if sub_sub_domains:
            to_return.append({'name' : domain, 'childrens' : sub_sub_domains})
        else:
            to_return.append({'name' : domain})

    return to_return

rawDescription: Sorting and organizing DNS records

description: Sorting and organizing DNS records


code:
yest = now - datetime.timedelta(days=1)
yest
now

rawDescription: time series in python up to microseconds

description: Time series in python up to microseconds


code: process = subprocess.Popen(['./cpulimit', '-p', '2112', '-l', '50'], stdin=subprocess.PIPE)

rawDescription: Python command line argument for an existing process


code:
class MetaClass(type):
    @property
    def test(cls):
        "docstring"
        return "Test"

class A(object):
    __metaclass__ = MetaClass

rawDescription: Implementing a class property that preserves the docstring


code:
from threading import Thread,Event
from subprocess import call

class Controller(object):
    def __init__(self):
        self.thread1 = None
        self.thread2 = None
        self.stop_threads = Event()

    def loop1(self):
        while not self.stop_threads.is_set():
            call (["raspivid -n -op 150 -w 640 -h 480 -b 2666666.67 -t 5000 -o test.mp4"],shell=True)
            call (["raspivid -n -op 150 -w 640 -h 480 -b 2666666.67 -t 5000 -o test1.mp4"],shell=True)

    def loop2(self):
        while not self.stop_threads.is_set():
            call (["arecord -D plughw:1 --duration=5 -f cd -vv rectest.wav"],shell=True)
            call (["arecord -D plughw:1 --duration=5 -f cd -vv rectest1.wav"],shell=True)

    def combine(self):
        self.stop_threads.clear()
        self.thread1 = Thread(target = self.loop1)
        self.thread2 = Thread(target = self.loop2)
        self.thread1.start()
        self.thread2.start()

    def stop(self):
        self.stop_threads.set()
        self.thread1.join()
        self.thread2.join()
        self.thread1 = None
        self.thread2 = None

rawDescription: Terminate the Thread by using buttion in Tkinter


rawDescription: Subsetting DataFrame using ix in Python

description: Subsetting DataFrame using ix in Python


code:
s = '\n'
s = s.encode('unicode-escape').decode()
print(s)
# -> \n

rawDescription: Unescaping escaped characters in a string using Python 3.2


code: [a + b for a, b in list_of_tuples]

rawDescription: Extract a 2-element tuple and convert it to String


code:
def something():
    foo = 'bar'
    return foo

rawDescription: Python within python

description: Python within python


code: pc = pcap.pcap()

rawDescription: 'module' object has no attribute 'pcapObject'


code:
#We need to *maximise* the overlap integral
from scipy.integrate import quad as integrate
def overlap(func1, func2, limits, func1_args=[], func2_args=[]):

  def product_func(x):
    return min(func1(x, *func1_args),func2(x, *func2_args))

  return integrate(product_func, *limits)[0] # we only care about the absolute result for now.

limits = hist_data.min(), hist_data.max()
def gaussian_overlap(args):
  mu, sigma = args
  return -overlap(kde_func, gaussian, limits, func2_args=[mu, sigma])

rawDescription: Python: Overlap between two functions (PDF of kde and normal)


rawDescription: How can I convert a binary value to text or ascii in python 3?

description: Convert a binary value to text or ascii in python 3


code: ["%.2d" % i for i in range(16)]

rawDescription: Generate list of numbers in specific format


code:
from math import sin, cos, acos
from unittest import assertAlmostEqual

def assertAlmostEqualAngles(x, y, **kwargs):
    c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
    angle_diff = acos((2.0 - c2)/2.0) # a = b = 1
    assertAlmostEqual(angle_diff, 0.0, **kwargs)

rawDescription: Python unittesting: Test whether two angles are almost equal


code: doc.xpath(u'.//th[div[text()="Cash & Short Term Investments"]]/following-sibling::td/text()')

rawDescription: Python/lxml/Xpath: How do I find the row containing certain text?


code: config = [Player(line.split(',')) for line in open("config")]

rawDescription: Python: Best way to dynamically instantiate Player class in a loop?


code:
index = Index("my_index_name", MyModel.c.data['my_key'].astext)
index.create(engine)

rawDescription: Using sqlalchemy to create an index on a json key (expression index)


code: ax.bar(0, 5, 2*np.pi, bottom=0.0, facecolor='None') #need to modified the edge lines or won't look right

rawDescription: matplotlib: how to plot concentric circles at a given set of radii

description: Matplotlib: how to plot concentric circles at a given set of radii


rawDescription: print a tensor variable

description: Print a tensor variable


rawDescription: Python float decimal places

description: Python float decimal places


code: xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])

rawDescription: python area chart with gradient color between the line and y=0

description: Python area chart with gradient color between the line and y=0


code:
def giveMeSomeRows(group):
    return random.uniform(low=group.low, high=group.high, size=N)

N = 3
df = pd.DataFrame(arange(0,8).reshape(4,2), columns=['low', 'high'])
df['farm'] = 'a'
df['fruit'] = arange(0,4)
results = df.groupby(['farm', 'fruit']).apply(giveMeSomeRows)

rawDescription: How do I convert a row from a pandas DataFrame from a Series back to a DataFrame?

description: Convert a row from a pandas DataFrame from a Series back to a DataFrame


rawDescription: Keeping some of the elements in a list

description: Keeping some of the elements in a list


code: x = EqM_list(someiter)

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
from scipy import ndimage

outVariance = ndimage.generic_filter(data, np.var, size=3)

rawDescription: Variance image in python using gdal and a running window approach


code:
filename = line[2]
foldername = line[5]

for letter in bad_characters:
    filename = filename.replace(letter, "_")
    foldername = foldername.replace(letter, "_")

rawDescription: Python string.replace() not replacing characters


code:
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(metadata, parser)
root = tree.getroot()
namespaces = {'ns':'http://apple.com/itunes/importer'}
items = iter(root.xpath('//ns:provider/text()|//ns:actor/@name',
                       namespaces=namespaces))
for provider, actor in zip(*[items]*2):
    print(provider, actor)

rawDescription: xmlns namespace breaking lxml

description: Xmlns namespace breaking lxml


code:
from pyramid.renderers import render

@view_config(...) # no renderer needed
def new_model(self):
    raw_html = render('new_model.mako', request, {...})
    html = htmlfill(raw_html, ...)
    resp = request.response
    resp.body = html
    return resp

rawDescription: Using HTMLFill with Pyramid's @view_config


code:
import ctypes

libc = ctypes.cdll.LoadLibrary("msvcrt")
# or on linux
# import ctypes.util
# libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))

strchr = libc.strchr

strchr.argtypes = (ctypes.c_char_p, ctypes.c_char)
strchr.restype = ctypes.c_char_p

result = strchr(b"abcde", b"c")
assert result == b"cde"

rawDescription: Calling C++ 64bit shared library from Python


code:
for client in (client for client in all_clients if client.attrspam == barfoo):
    client.send(data)

rawDescription: How can i send a packet to some users in python?

description: Send a packet to some users in python


rawDescription: Slice pandas DataFrame where column's value exists in another array


code:
user = User.all().filter('name =', name).filter('password =', password).get()
if user:
    user.delete()

rawDescription: Google App Engine Datastore delete entity by properties


code:
env = Environment()

# Set the include paths
env.Append(CPPPATH = ['src1', 'src2'])

# Notice the source files are referred to in the build dir
# If you dont do this, the compiled objects will be in the src dirs
src1Sources = ['build/lib1/class1.cc']
src2Sources = ['build/lib2/class2.cc']
mainSources = ['build/mainApp/main.cc']

env.VariantDir(variant_dir = 'build/lib1', src_dir = 'src1', duplicate = 0)
env.VariantDir(variant_dir = 'build/lib2', src_dir = 'src2', duplicate = 0)
env.VariantDir(variant_dir = 'build/mainApp', src_dir = 'srcMain', duplicate = 0)

lib1 = env.Library(target = 'build/lib1/src1', source = src1Sources)
lib2 = env.Library(target = 'build/lib1/src2', source = src2Sources)
env.Program(target = 'build/mainApp/main', source = [mainSources, lib1, lib2])

rawDescription: Do we need sconscript file in every source directory


code:
a = t1.test(self.lst)
a.size

rawDescription: Adding an attribute to a list

description: Adding an attribute to a list


code:
for i in range(1,5):
    self.canvas.itemconfig(getattr(self, 'lamp_%s' % i),
                           fill=self.color_blink)

rawDescription: substring variable name python

description: Substring variable name python


code:
import sys
print(sys.argv)

rawDescription: what is a commandline argument?

description: What is a commandline argument


code: df.sort_values(["ID", "time"]) # different df

rawDescription: Sort grouped dataframe based on the time variable colum


code:
from sqlalchemy import Column, Integer, String
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
    def __repr__(self):
       return "<User(name='%s', fullname='%s', password='%s')>" % (
                            self.name, self.fullname, self.password)

rawDescription: How To Store Changing Data For 20,000 Items In A Database


rawDescription: Using "google-like" colon-search operator with Haystack


code:
for line in lines:
    l = line.split(":")
    if l[0] in targets:
        results[l[0]] = l[1]

rawDescription: Extract data from a site using python

description: Extract data from a site using python


code:
input1 = input("Enter word: ")
input2 = "goodbye"
# make input1 at least as long as input2
while len(input1) <= len(input2):
    input1 += input1
for x, y in zip(input1, input2):
    total = ord(x) + ord(y)
    print(total)

rawDescription: Adding 2 ascii converted characters using nested loops in Python 3.2


code: A.ravel()[np.random.choice(A.size, c, replace=False)] = np.nan

rawDescription: Create sample numpy array with randomly placed NaNs


code:
d = {'NONANE':9, 'OCTANE':8, 'HEPTANE':7, 'HEXANE':6}
df['num'] = df['solvent'].map(d)

rawDescription: Setting column equal to value depending on another column pandas


code: any(myCoord in x for x in (someCoords1, someCoords2))

rawDescription: identify x,y coordinate pair in a python x,y array

description: Identify x,y coordinate pair in a python x,y array


code:
import datetime

def iso_year_start(iso_year):
    "The gregorian calendar date of the first day of the given ISO year"
    fourth_jan = datetime.date(iso_year, 1, 4)
    delta = datetime.timedelta(fourth_jan.isoweekday()-1)
    return fourth_jan - delta

def iso_to_gregorian(iso_year, iso_week, iso_day):
    "Gregorian calendar date for the given ISO year, week and day"
    year_start = iso_year_start(iso_year)
    return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)

def week_start_end(date):
    year = date.isocalendar()[0]
    week = date.isocalendar()[1]
    d1 = iso_to_gregorian(year, week, 0)
    d2 = iso_to_gregorian(year, week, 6)
    d3 = datetime.datetime(d1.year, d1.month, d1.day, 0,0,0,0)
    d4 = datetime.datetime(d2.year, d2.month, d2.day, 23,59,59,999999)
    return (d3,d4)

rawDescription: tuple of datetime objects in Python

description: Tuple of datetime objects in Python


rawDescription: Python: Split numpy array

description: Python: Split numpy array