rawDescription: Replacing item values in a data frame on certain condition in other columns


code: n_grams = CountVectorizer(ngram_range=(1, 5))

rawDescription: Python List of Ngrams with frequencies

description: Python List of Ngrams with frequencies


code:
Base = declarative_base()

def TableCreator(tablename):
  class MyTable(Base):
    __tablename__ = tablename
    row_id = Column(INT, primary_key=True)
    another_column = Column(CHAR(10))
  return MyTable

rawDescription: dynamically creating a set of SQLAlchemy tables

description: Dynamically creating a set of SQLAlchemy tables


code:
from multiprocessing import Pool
from time import sleep

def square(x):
    return x * x

def cube(y):
    return y * y * y

pool = Pool(processes=20)

result_squares = pool.map_async(f, range(10))
result_cubes = pool.map_async(g, range(10))

rawDescription: Mulitprocess Pools with different functions


code:
def total_results(params):
    # create all workers
    workers = [Worker(p) for p in params]

    # start all workers
    [w.start() for w in workers]

    # wait for all of them to finish
    [w.join() for w in workers]

    #get the result
    return Worker.results

rawDescription: parallel writing to list in python

description: Parallel writing to list in python


code:
with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile, delimiter='\t')
    writer = csv.writer(outfile, delimiter='\t')

    row = None

    try:
        next(reader)  # skip the `A   B` headers.

        line = next(reader)  # prime our loop
        while True:
            while not line[0]:
                # advance to the first line with a column 0 value
                line = next(reader)

            row = line  # start off with the first number and column
            line = next(reader)  # prime the subsequent lines loop

            while line and not line[0]:
                # process subsequent lines until we find one with a value in col 0 again
                cell = line[1]
                if cell == 'foo':    # detect column d
                    row.append('')   # and insert empty value
                row.append(cell)
                line = next(reader)

            # consolidate, write
            if len(row) < 5:
                # make row at least 5 columns long
                row.extend([''] * (5 - len(row)))
            if len(row) > 5:
                # merge any excess columns into the 5th column
                row[4] = ','.join(row[4:])
                del row[5:]

            writer.writerow(row)
            row = None
    except StopIteration:
        # reader is done, no more lines to come
        # process the last row if there was one
        if row is not None:
            # consolidate, write
            if len(row) < 5:
                # make row at least 5 columns long
                row.extend([''] * (5 - len(row)))
            if len(row) > 5:
                # merge any excess columns into the 5th column
                row[4] = ','.join(row[4:])
                del row[5:]

            writer.writerow(row)

rawDescription: Adjusting CSV data: appending cells to previous row, merge cells containing certain string


code: foobar = Derived()

rawDescription: How to call a data member of the base class if it is being overwritten as a property in the derived class?

description: Call a data member of the base class if it is being overwritten as a property in the derived class


code:
# settings.py

from oscar import get_core_apps
# ...
INSTALLED_APPS = [
    # all your non-Oscar apps
] + get_core_apps(['myproject.partner'])

rawDescription: How to alter Fields in Django and Oscar

description: Alter Fields in Django and Oscar


code:
d = { 'a': 'Chief Manager', 'b': 'Assistant General Manager', 'c': 'General Manager', 'D': 'CTO', 'E': 'CEO' }
user = 'a'
print(d[user])
# Chief Manager

rawDescription: How do I read data from a file using Python?

description: Read data from a file using Python


code:
s = pd.Series(np.random.uniform(0, 110, 100))
s
s = pd.Series(np.random.uniform(0, 110, 100))
s
cuts = np.arange(0, 101, 10)
pd.cut(s, cuts)

rawDescription: Converting float into range in Python

description: Converting float into range in Python


code: yield tuple(combination)

rawDescription: Generating non-consecutive combinations

description: Generating non-consecutive combinations


code:
c = C()
c.add_tweet_r(('Mike', "Hi"))
c.add_tweet_r(('Joe', "Like Mike said, Hi."))
c.add_tweet_r(('Mike', "I'd gladly say it again, Hi"))
c.add_tweet_r(('Nancy', "Hip-hop extravaganza tonight 9pm at The Firetrap!"))
c.add_tweet_r(('Clem', "Yo."))

rawDescription: How do I search a list that is located in a class?

description: Search a list that is located in a class


code:
dicts = sc.parallelize([{"foo": 1, "bar": 2}, {"foo": 3, "baz": -1, "bar": 5}])
dicts.flatMap(lambda x: x.items())

rawDescription: Extracting a dictionary from an RDD in Pyspark


code:
#Insert BINS column
RRData['BINS'] = pd.cut(RRData.COUNTS,sortBins, labels = binLabels)

rawDescription: How to bin groupeby counts in pandas?

description: Bin groupeby counts in pandas


code:
def writeText(df):
    for row in df.text.reset_index().values:
        with open(str(row[0])+'.txt', 'w+') as f:
            f.write(str(row[1]))

writeText(df)

rawDescription: How to call the index value of the data frame as an arg in apply function with python-pandas?

description: Call the index value of the data frame as an arg in apply function with python-pandas


code:
total = ...
digits = []
while total > 0:
    digits = [(total % 40 + 1)] + digits
    total = total / 40

rawDescription: How to convert a random number to another base format?

description: Convert a random number to another base format


code:
photos = [
    {
        _id: ObjectId(...),
        title: "...",
        date_uploaded: Date(...),
        albums: [
            ObjectId(...),
            ...
        ]
    },
    ...
]

albums = [
    {
        _id: ObjectId(...),
        title: "..."
    }
]

rawDescription: Proper NoSQL data schema for web photo gallery


code: foo|"bar|baz"|spam

rawDescription: Pipe delimiter file, but no pipe inside data


code:
import xml.etree.ElementTree as ET

tree = ET.parse("in.xml")

def getkey(elem):
    # Used for sorting elements by @LIN.
    # returns a tuple of ints from the exploded @LIN value
    # '1.0' -> (1,0)
    # '1.0.1' -> (1,0,1)
    return float(elem.get('LIN'))

container = tree.find("PurchaseOrder/LineItems")

container[:] = sorted(container, key=getkey)

tree.write("new.xml")

rawDescription: Sorting child elements with lxml based on attribute value


code:
def setdoc(docstring):
    def decor(func):
        func.__doc__ = docstring
        return func
    return decor

@setdoc('Here I am.')
def load_this(dt):
    pass

rawDescription: Python docstring repeated param text

description: Python docstring repeated param text


code: return list({element for element in itertools.product(*somelists)})

rawDescription: Python: return unique only cartesian product of a list containing lists?


code: wordlist = [" ".join(x) for x in product(rowa, rowb)]

rawDescription: Trying to convert a list of tuples to a list of lists


rawDescription: How to slice memmap efficiently?

description: Slice memmap efficiently


code: inputlist[max(0, index - 2):index + 3]

rawDescription: Elegant way to access last two and next two elements in a list?


rawDescription: open file and read sentence

description: Open file and read sentence


rawDescription: Count equal tuple-elements of a list in Python3


code:
rgb_image = np.random.rand(2*4*3).reshape(2,4,3)
transformation_matrix = np.random.rand(9).reshape(3,3)
z = np.empty_like(rgb_image)
for x in range(rgb_image.shape[0]):
    for y in range(rgb_image.shape[1]):
        z[x,y] = np.dot(transformation_matrix, rgb_image[x,y,:])
np.allclose(z, np.einsum('kl,ijl->ijk', transformation_matrix, rgb_image))

rawDescription: Numpy 3d array map operation

description: Numpy 3d array map operation


code:
name
unicode(name, 'latin-1')

rawDescription: How do convert unicode escape sequences to unicode characters in a python string


code:
besseli_vec = np.frompyfunc(mp.besseli, 2, 1)
besseli_vec(0, A)

rawDescription: How to mpf an array?

description: Mpf an array


code:
with open('parsed.txt', 'r') as f:
    data = [line.strip() for line in f if line.strip()]

index = dict()
for i in range(len(data)):
    line = data[i]
    first_letter = line[0].lower()
    if first_letter not in index:
        index[first_letter] = i

rawDescription: reading strings from large file faster

description: Reading strings from large file faster


code:
lis_A = [[], [], []]
vals = [1,2,3]
[x.append(y) for x, y in zip(lis_A, vals)]
lis_A

rawDescription: Append to several lists inside list

description: Append to several lists inside list


code:
df = pd.melt(df, id_vars=["Date"])
df = df.rename(columns={'variable': 'hour'})
df

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


code:
import pandas
df = pandas.DataFrame({'Values': randn(10), 'Categories': list('AABABBABAB')}, index=range(10))
df.set_index('Categories', append=True).unstack().interpolate().plot(subplots=True)

rawDescription: Plot a pandas dataframe grouped by column


code:
import sys
from time import sleep

for c in "Hello":
    sys.stdout.write(c)
    sys.stdout.flush()
    sleep(0.1)
sys.stdout.write('\n')
sys.stdout.flush()

rawDescription: Python code, Time delay on console text

description: Python code, Time delay on console text


code:
s = ssh.Connection('example.com', 'warrior', password = 'lennalenna')
s.put('/home/warrior/hello.txt', '/home/zombie/textfiles/report.txt')
s.get('/var/log/strange.log', '/home/warrior/serverlog.txt')
s.execute('ls -l')
s.close()

rawDescription: python libraries for ssh handling

description: Python libraries for ssh handling


code: Session.query(...).filter(..., schema.Term.id < term_alias.id).distinct()

rawDescription: SQLAlchemy - Get all Rows which have matching set of Columns


code: ls_5min.insert(x1[i]+ l, 10)

rawDescription: Extra index in list

description: Extra index in list


code:
"""Line one
Line two"""

rawDescription: Python string notation

description: Python string notation


code:
def stop(self):
    self.terminate()

rawDescription: PyQt5 opening and closing windows

description: PyQt5 opening and closing windows


code:
def find_dupe(lists):
    seen = set()
    for lst in lists:
        for item in lst:
            if item in seen:
                yield item
            seen.add(item)

rawDescription: Find duplicate element in a list of lists


code:
hubs = sorted(g.items())
for node, vertices in hubs:
    for vertice, weight in reversed(sorted(vertices.items())):
        if vertice >= node:
            matrix[vertice][node] = weight
            matrix[node][vertice] = weight
        else: # do only care about vertices that haven't been saved before,
            break # continue with next node when the current one won't introduce any more vertices

rawDescription: Creating Adjacency Lists from Dicts in Python


rawDescription: Sorting dictionary by value and key length


code:
# settings.py

import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DATABASE_URL = ''
DATABASE_USER = ''
DATABSE_PASSWORD = ''

rawDescription: "real" global variables in Python for programwide settings


code:
class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)

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


code:
class Trk(object):
    """Track some values and compute a function if any change"""
    def __init__(self, name, fn, **objects_to_track):
        def _trk_fn(self):
            if any(self.__dict__[x] != self.original_objects[x] for x in self.original_objects):
                self.value = self.saved_fn(self.__dict___)
                # now that self.value is updated, also update self.original_objects
                for x in self.original_objects:
                    self.original_objects[x] = self.__dict__[x]
            return self.value

        self.original_objects = objects_to_track  # make reference copy
        self.__dict__.update(objects_to_track)
        self.name = name
        self.saved_fn = fn
        self.fn = self._trk_fn()
        self.value = self.fn()

rawDescription: In Python, can I bind a variable to a function/expression so that it automatically updates?


code:
from flask import Flask, request
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/')
def root():
    return app.send_static_file('index.html')

rawDescription: How to serve static files in Flask

description: Serve static files in Flask


code:
import json
import re
import urllib.request
from urllib.parse import quote_plus

baseurl = "https://en.wiktionary.org/w/api.php?action=query&titles={}&prop=revisions&rvprop=content&format=json"

def getIPAen(word):
    url = baseurl.format(quote_plus(word))
    jsondata = urllib.request.urlopen(url).read().decode('utf8')
    data = json.loads(jsondata)
    for page in data['query']['pages'].values():
        for revision in page['revisions']:
            if 'IPA' in revision['*']:
                ipa = re.search(r"{IPA\|/(.*?)/\|", revision['*']).group(1)
                print(ipa)

rawDescription: Python: print unicode string stored as a variable


code:
import re
line = 'Specified, if char, else 10 (default).'
words = re.split(r'\)?[, .]\(?', line)
# words = ['Specified', '', 'if', 'char', '', 'else', '10', 'default', '']
separators = re.findall(r'\)?[, .]\(?', line)
# separators = [',', ' ', ' ', ',', ' ', ' ', ' (', ').']

rawDescription: Python: Splitting a string into words, saving separators


code:
import itertools

chars = 'abc'
tags = itertools.cycle(chars)
words = ['We', 'HELLO', 'want', 'you', 'WOHO', 'self', 'Maybe', 'APIL', 'sort']

for word, tag in zip(words, tags):
    print("<{0}>{1}</{0}>".format(tag, word))

rawDescription: Add characters to specific elements in a list


code:
A = A.tocsr()
# May also need
# B = B.tocsr()
A = A.multiply(B)

rawDescription: Scipy sparse matrices element wise multiplication


code: res = add.chunks(zip(range(10), range(10)), 2)()

rawDescription: What is the right way to invoke celery.task.chunks?


rawDescription: Wrong output in Python - as per my logic


code:
key = "somerediskey"
data = redis_connection.hdel(key, *dict1.keys())

rawDescription: delete multiple fields for a key in Redis

description: Delete multiple fields for a key in Redis


rawDescription: Custom sort on a dictionary in Python?

description: Custom sort on a dictionary in Python


code:
def make_cylinder(radius, length, nlength, alpha, nalpha, center, orientation):

    #Create the length array
    I = np.linspace(0, length, nlength)

    #Create alpha array avoid duplication of endpoints
    #Conditional should be changed to meet your requirements
    if int(alpha) == 360:
        A = np.linspace(0, alpha, num=nalpha, endpoint=False)/180*np.pi
    else:
        A = np.linspace(0, alpha, num=nalpha)/180*np.pi

    #Calculate X and Y
    X = radius * np.cos(A)
    Y = radius * np.sin(A)

    #Tile/repeat indices so all unique pairs are present
    pz = np.tile(I, nalpha)
    px = np.repeat(X, nlength)
    py = np.repeat(Y, nlength)

    points = np.vstack(( pz, px, py )).T

    #Shift to center
    shift = np.array(center) - np.mean(points, axis=0)
    points += shift

    #Orient tube to new vector

    #Grabbed from an old unutbu answer
    def rotation_matrix(axis,theta):
        a = np.cos(theta/2)
        b,c,d = -axis*np.sin(theta/2)
        return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
                         [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
                         [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])

    ovec = orientation / np.linalg.norm(orientation)
    cylvec = np.array([1,0,0])

    if np.allclose(cylvec, ovec):
        return points

    #Get orthogonal axis and rotation
    oaxis = np.cross(ovec, cylvec)
    rot = np.arccos(np.dot(ovec, cylvec))

    R = rotation_matrix(oaxis, rot)
    return points.dot(R)

rawDescription: How to generate regular points on cylindrical surface

description: Generate regular points on cylindrical surface


code:
import re

def do_thing(LS, SS):
    if re.match("^%s" % SS, LS, re.I):
        action_on_match(LS[len(SS):])
    else:
        action_on_no_match()

rawDescription: How should I remove one string from the start of another given that I know the longer string matches case-insensitively?


code:
modules = df['Associate Modules'].apply(Series)
modules.index = df['Address']
modules

rawDescription: Transpose Multidimensional Table

description: Transpose Multidimensional Table


code:
def key(branch):
    id, flows = branch
    return ordered_branches.index(id)

rawDescription: Sorting the contents of one list via the contents of another (Python)


code: pd.merge(acc_df, pol_df, on=['EID','PCODE'], how='inner',suffixes=('_Acc','_Po'))

rawDescription: Pandas - GroupBy and then Merge on original table


rawDescription: issue in executing scikit-learn linear regression model

description: Issue in executing scikit-learn linear regression model


code: these_args = [context[arg_name] for arg_name in self.arg_names]

rawDescription: django: resolve variables in custom template

description: Django: resolve variables in custom template


code: user = request.user

rawDescription: Improving Python/django view code

description: Improving Python/django view code


code:
class MyTuple(tuple):
    def __lt__(self, other):
        return all(a < b for a, b in zip(self, other))
    def __eq__(self, other):
        return (len(self) == len(other)
                and all(a == b for a, b in zip(self, other)))
    def __gt__(self, other):
        return not (self < other or self == other)
    def __le__(self, other):
        return self < other or self == other
    def __ge__(self, other):
        return not self < other

A = [MyTuple((1,100,2))]
B = [MyTuple((2,0,0))]
print(list(heapq.merge(A,B)))
# [(2, 0, 0), (1, 100, 2)]

rawDescription: merging tuples in heap module in python

description: Merging tuples in heap module in python


code:
from werkzeug.routing import BaseConverter

class DictionaryConverter(BaseConverter):
    """Convert python dictionary to URL query string and back."""

    def to_python(self, value):
        d = {}
        for item in value.split('&'):
            k, v = item.split('=')
            if k != 'csrf_token':
                d[k] = v
        return d

    def to_url(self, values):
        pairs = []
        for k in values:
            #don't expose the csrf token in the query string
            if k != 'csrf_token':
                pairs.append('{}={}'.format(k, values[k]))
        return '&'.join(BaseConverter.to_url(self, value=pair) for pair in pairs)

rawDescription: redirect data to the next view in Flask

description: Redirect data to the next view in Flask


code:
diff_abs = np.abs(img1-img2)
cnt = (diff_abs > threshold).sum()

rawDescription: Python Opencv img.item() performance too slow


code: users[users > 0]

rawDescription: Remove rows of zeros from a Pandas series


rawDescription: Adding lambda functions with the same operator in python


code:
import pandas as pd
import numpy as np
np.random.seed(1001)
df = pd.DataFrame(np.random.randn(10, 2), columns=['A', 'B'])
df
q = pd.qcut(df["A"], 5)
q
q.labels

rawDescription: Convert data to the quantile bin

description: Convert data to the quantile bin


code:
s = """This is the text

I am interested in splitting,

but I want to remove blank lines!"""
lines = [l for l in s.split("\n") if l]
lines

rawDescription: Splitting <textarea> post on empty line(s)


code: grouped = df.groupby('OPTION')

rawDescription: Accessing data from a count method in Pandas


rawDescription: Longest increasing subsequence in Python (For vs While loop)


code: import aaa

rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


rawDescription: Numpy: vector of indices and value

description: Numpy: vector of indices and value


code:
inputlist = [(0.2, 'Item1'), (0.25, 'Item2'), (0.23, 'Item3')]
[t[1] for t in inputlist]
from operator import itemgetter
map(itemgetter(1), inputlist)
[t[-1] for t in inputlist]
[item for ratio, item in inputlist]
zip(*inputlist)[-1]

rawDescription: Python values out of list

description: Python values out of list


code: annos

rawDescription: Improving code design of DNA alignment degapping


code:
from mythread import *
thread.stop() # omit this line to continue the thread

rawDescription: Exit an imported module without exiting the main program - Python


code:
class MyModel(models.Model):
    my_field = models.Charfield(max_length=100)

rawDescription: Is it possible getting all parameters of a field


code:
import gmpy2

def generate(x):
    if x == gmpy2.gcd(x, gmpy2.fib(x-1)):
        return True
    if x == gmpy2.gcd(x, gmpy2.fib(x+1)):
        return True
    return False

for x in range(7, 2000):
    if generate(x):
        print(x)

rawDescription: Prime number generation using Fibonacci possible?


code:
import configparser
filename = r'C:\directory\sub_directory\FILE.INI'
config = configparser.ConfigParser()
config.read(filename)
config['device.label'] = config['device.name']
modified_name = str(config['device.name']) + '_' + filename.split['\\'][2]
config['device.name'] = modified_name

with open(filename, 'w') as configfile:
    config.write(configfile)

rawDescription: scripting tool to modify configuration files

description: Scripting tool to modify configuration files


rawDescription: Python Pandas, Resampling data with pct_change function


code:
b = [[] for i in range(5)]
b[0].append('abc')
b

rawDescription: Why does 'append' mutates all elements in a list?


code:
def replace_value(s, new):
    content, sep1, comment = s.partition('#')
    key, sep2, value = content.partition('=')
    if sep2: content = key + sep2 + new
    return content + sep1 + comment

assert replace_value('log_File = b', ' Hello') == 'log_File = Hello'
assert replace_value('#log_File = b', ' Hello') == '#log_File = b'
assert replace_value('#This is comment', ' Hello') == '#This is comment'
assert replace_value('log_File = b # hello', ' Hello') == 'log_File = Hello# hello'

rawDescription: Ask for a regx for re.sub in python

description: Ask for a regx for re.sub in python


rawDescription: How to get a subset of rows from a NumPy Matrix based on a condition?

description: Get a subset of rows from a NumPy Matrix based on a condition


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

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


code:
mylist = ["all dogs go", "why does one", "fell down so hard I"]
mylist = [x + " moo" for x in mylist]
mylist

rawDescription: Add a word at the end of elements of a list


code:
from scipy.cluster.vq import kmeans, vq
codebook, distortion = kmeans(X, 3)
code, dist = vq(X, codebook)
code

rawDescription: k-means in python: Determine which data are associated with each centroid

description: K-means in python: Determine which data are associated with each centroid


code:
import sys

sys.stderr.write('prompt> ')
value = raw_input()
print('value was: ', value)

rawDescription: Save a Python script's output with > in bash while using raw_input()


code:
class sub_test_data(object):

    def __init__(self, *test_data):
        self.test_data = test_data

    def __call__(self, func):
        func.sub_test_data = self.test_data
        func.has_sub_tests = True
        return func

def create_test_driver(func, *args):
    def test_driver(self):
        try:
            func(self, *args)
        except AssertionError as e:
            e.args += ({"test_args": args},)
            raise
    return test_driver

def create_sub_tests(cls):
    for attr_name, func in list(vars(cls).items()):
        if getattr(func, "has_sub_tests", False):
            for i, value in enumerate(func.sub_test_data):
                test_name = 'test_{}_subtest{}'.format(attr_name, i)
                setattr(cls, test_name, create_test_driver(func, value))
    return cls

@create_sub_tests
class NumbersTest(unittest.TestCase):
    tickets = [0, 1, 2, 3, 4, 5]

    @sub_test_data(*tickets)
    def even(self, t):
        self.assertEqual(t % 2, 0)

rawDescription: Adding test methods dynamically using decorator


code:
def plane_ride_cost(city):
    if city =="Charlotte":
        return 183
    elif city == "Tampa":
        return 220
    elif city =="Pittsburgh":
        return 222
    elif city =="Los Angeles":
        return 475
    else:
        raise ValueError("No Vacation")

def hotel_cost(days):
    return 140*days

def rental_car_cost(days):
    return 30*days

def trip_cost(city, days):
    total_cost = 0.0
    total_cost += hotel_cost(days)
    total_cost += plane_ride_cost(city)
    total_cost += rental_car_cost(days)
    return total_cost

city=raw_input("Enter your destination")
days=int(raw_input("Enter the duration of your stay in number of days"))
print("Your %s day trip in %s is %0.2f dollars"%(days, city, trip_cost(city, days)))

rawDescription: How to give return value of a function to print in Python

description: Give return value of a function to print in Python


code: framename.columnconfigure(0, weight = 1)

rawDescription: Creating GUI using Tkinter

description: Creating GUI using Tkinter


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

num = 1000
x = np.linspace(0, 10, num)
y = np.exp(x)

# Add some non-stationary noise that's hard to see without de-trending
noise = 100 * np.exp(0.2 * x) * np.random.normal(0, 1, num)
y += noise

fig, ax = plt.subplots()
ax.plot(x, y, 'ro')
plt.show()

rawDescription: Detrend Flux Time Series with Non-Linear Trend


code:
def delta_value(direction):
    diff = cmp(value2, value1)   # -1 for <, 0 for ==, 1 for >
    if direction == "increase": diff = -dif
    return diff

rawDescription: Dynamically increment/decrement the value of a variable?


code: player.items.filter(slot__name='off_hand')[0].item    # Could be None

rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
class Point3D:
    """Representation of a point in 3D space."""
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __add__(self, other):
        """Add two points.

        >>> Point3D(1, 2, 3) + Point3D(100, 200, 300)
        Point3D(101, 202, 303)
        """
        x = self.x + other.x
        y = self.y + other.y
        z = self.z + other.z
        return Point3D(x, y, z)

    def __mul__(self, a):
        """Multiply a point with a number.

        >>> Point3D(1, 2, 3) * 2
        Point3D(2, 4, 6)
        """
        x = self.x * a
        y = self.y * a
        z = self.z * a
        return Point3D(x, y, z)

    def __rmul__(self, a):
        """Multiply a number with a point.

        >>> 2 * Point3D(1, 2, 3)
        Point3D(2, 4, 6)
        """
        return self.__mul__(a)

    def __repr__(self):
        return 'Point3D({p.x}, {p.y}, {p.z})'.format(p=self)

rawDescription: Break down cubes into 8 smaller cubes recursively (when the cubes are defined by a mid point and size)


code:
root = ET.parse('file.xml')
tree = root.getroot()
...

rawDescription: How to extract part of xml file

description: Extract part of xml file


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

class A(object):
    b = Property()

A.__dict__['b']
type(A.__dict__['b'])
class Property(object):
    _value = None
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self._value
    def __set__(self, instance, value):
        self._value = value * 2

class A(object):
    b = Property()

A.b

rawDescription: determine a class attribute is Property?

description: Determine a class attribute is Property


code:
if wx.MessageBox("Are You Sure?","Checking",wx.YES_NO) == wx.YES:
   print ("User Clicked Yes")
else:
   print ("User did not click yes (clicked No or closed)")

rawDescription: wxPython wait for dialog response before continuing

description: WxPython wait for dialog response before continuing


code: z_msg = [item['z_msg'] for item in top_30]

rawDescription: For a list containing dictionary objects, how do I filter the list based on the value of a key?


code:
for i, item in enumerate(reversed(somelist), -len(somelist)+1):
    do_some_stuff(item)
    if delete_element(item):
        del somelist[-i]

rawDescription: Python idiom for iterating over changing list


code:
import datetime
datetime.date.today()
datetime.datetime.now()
datetime.datetime.now() == datetime.date.today()
datetime.datetime.now().date() == datetime.date.today()

rawDescription: Equating python datetimes

description: Equating python datetimes


code:
timeit('from __main__ import np, pd, a, b; pd.Series(np.concatenate([a,b]))', number = 10000)
timeit('from __main__ import np, pd, a, b; pd.concat([a, b], ignore_index=True)', number = 10000)
timeit('from __main__ import np, pd, a, b; a.append(b).reset_index(drop=True)', number = 10000)

rawDescription: Simple way to append a pandas series with same index


rawDescription: Creating 2D dictionary in Python

description: Creating 2D dictionary in Python


code:
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

rawDescription: Include labels for each data point in pandas plotting


code:
MIME_STATE_HEADER = 1
MIME_STATE_BODY = 2

def read_lines(text):
    if isinstance(text, list):
        return text
    return re.split(r'\r?\n', text)

def parse_mime(text):
    header_line = re.compile(r'^([A-Za-z\-]+): (.*)$')
    state = MIME_STATE_HEADER
    header = {}
    body = []
    for line in read_lines(text):
        if state == MIME_STATE_HEADER:
            if line == '':
                state = MIME_STATE_BODY
                continue
            m = header_line.match(line)
            if not m:
                raise Exception('Invalid header section: %s' % line)
            header[ m.group(1).lower() ] = m.group(2)
        elif state == MIME_STATE_BODY:
            body.append(line)
    return header, body

def mime(text):
    header, body = parse_mime(text)
    content_type = re.compile(r'multipart/.*; boundary="(.*)"')
    m = content_type.match(header['content-type'])
    if m:
        boundary = re.escape(m.group(1))
        matcher = re.compile(r'\r?\n--%s(--)?\r?\n' % boundary)
        parts = [ mime(part) for part in matcher.split('\n'.join(body))[1:-2] if part ]
        return header, parts
    return header, '\n'.join(body)

rawDescription: How to extract line 1 to line 3 which are in the middle of the document?

description: Extract line 1 to line 3 which are in the middle of the document


code:
value = "0110100001100101011011000110110001101111"*10**5

def using_fromarray():
    carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
    data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
    img = Image.fromarray(data, 'RGB')
    return img

def using_putdata():
    cmap = {'0': (255,255,255),
            '1': (0,0,0)}

    data = [cmap[letter] for letter in value]
    img = Image.new('RGB', (8, len(value)//8), "white")
    img.putdata(data)
    return img

rawDescription: Turning binary string into an image with PIL


code:
list_of_lists = [list1,list2,list3,...]
{z[0]:list(z[1:]) for z in zip(*list_of_lists)}

rawDescription: How to map multiple lists to one dictionary?

description: Map multiple lists to one dictionary


code:
Lead.objects.extra(tables=['appname_userdemographic'],
                   where=['appname_userdemographic.user_id=appname_lead.user_id',
                          'appname_userdemographic.site_id=appname_lead.site_id'],
                   select={'country': 'appname_userdemographic.country'})

rawDescription: In Django, how do I join a table with a composite primary key to another table?


code:
s = u'\xe0'
import json
json.dumps(s)

rawDescription: Convert u'\xe0' to '\u00E0' in Python 2.x?


rawDescription: Web.py SQL queries giving odd data

description: Web.py SQL queries giving odd data


code:
df1.loc[(df1['size'] > 0.3) & (df1['size'] < 0.5), 'Flower.Type'] = 'Setosa'
print(df1)

rawDescription: Merging two data frames and doing calculation


rawDescription: How to generate numbers based on a pattern in python

description: Generate numbers based on a pattern in python


rawDescription: How to store 'yield' generator result in a list in Python 2.7?

description: Store 'yield' generator result in a list in Python 2.7


rawDescription: How do I format a list of dictionaries with itertools.groupby?

description: Format a list of dictionaries with itertools.groupby


rawDescription: Concatenate strings by groups python

description: Concatenate strings by groups python


code: df.sort(axis=1, ascending=False)

rawDescription: Fastest way to sort each row in a pandas dataframe


code:
df = DataFrame(1.,index=list('abcdefghij'),columns=[0,1,2])
df2 = DataFrame(0,index=list('afg'),columns=[1,2])
needed_columns = df.columns-df2.columns
df2[needed_columns] = df.reindex(index=df2.index,columns=needed_columns)
df2
df3 = DataFrame(0,index=list('cji'),columns=[1,2])
needed_columns = df.columns-df3.columns
df3[needed_columns] = df.reindex(index=df3.index,columns=needed_columns)
df3

rawDescription: Fastest way to copy columns from one DataFrame to another using pandas?


code:
s = f.readline()
x = int(s)
y = x * 5  # etc.

rawDescription: Text file number to Python number how?

description: Text file number to Python number how


code:
from pprint import pprint
body=['Study: Study 1', 'Date:  Friday, March 28, 2014 3:15 PM - 4:00 PM',
      'Location: Some Place','Participant: John Doe','Study: Study 1',
      'Date: Friday, March 28, 2014 4:00 PM - 4:40 PM',
      'Location: Some Place','Participant: Mary Smith']
[elem
 for line in body
 for elem in (line.split()[1:] if line.startswith('Participant:') else (line,))]
pprint(_)

rawDescription: Split, edit, and replace values in list

description: Split, edit, and replace values in list


code:
#!python3

import re
import xml.etree.ElementTree as ET

rex = re.compile(r'''(?P<title>Longitude
                       |Latitude
                       |date&time
                       |gsm\s+cell\s+id
                       |Neighboring\s+List-\s+Lac\s+:\s+Cid\s+:\s+RSSI
                     )
                     \s*:?\s*
                     (?P<value>.*)
                     ''', re.VERBOSE)

root = ET.Element('root')
root.text = '\n'    # newline before the celldata element

with open('cell.txt') as f:
    celldata = ET.SubElement(root, 'celldata')
    celldata.text = '\n'    # newline before the collected element
    celldata.tail = '\n\n'  # empty line after the celldata element
    status = 0              # init status of the finite automaton
    for line in f:
        if status == 0:     # lines of the heading expected
            # If the line contains the wanted data, process it.
            m = rex.search(line)
            if m:
                # Fix some problems with the title as it will be used
                # as the tag name.
                title = m.group('title')
                title = title.replace('&', '')
                title = title.replace(' ', '')

                if line.startswith('Neighboring'):
                    neighbours = ET.SubElement(celldata, 'neighbours')
                    neighbours.text = '\n'
                    neighbours.tail = '\n'
                    status = 1  # empty line and then list of neighbours expected
                else:
                    e = ET.SubElement(celldata, title.lower())
                    e.text = m.group('value')
                    e.tail = '\n'
                    # keep the same status

        elif status == 1:   # empty line expected
            if line.isspace():
                status = 2  # list of neighbours must follow
            else:
                raise RuntimeError('Empty line expected. (status == {})'.format(status))
                status = 999 # error status

        elif status == 2:   # neighbour or the empty line as final separator

            if line.isspace():
                celldata = ET.SubElement(root, 'celldata')
                celldata.text = '\n'
                celldata.tail = '\n\n'
                status = 0  # go to the initial status
            else:
                # This is the neighbour item. Split it by colon,
                # and set the attributes of the item element.
                item = ET.SubElement(neighbours, 'item')
                item.tail = '\n'

                lac, cid, rssi = (a.strip() for a in line.split(':'))
                item.attrib['lac'] = lac
                item.attrib['cid'] = cid
                item.attrib['rssi'] = rssi.split()[0] # dBm removed
                # keep the same status

        elif status == 999: # error status -- break the loop
            break

        else:
            raise LogicError('Unexpected status {}.'.format(status))
            break

# Display for debugging
ET.dump(root)

# Include the root element to the tree and write the tree
# to the file.
tree = ET.ElementTree(root)
tree.write('cell.xml', encoding='utf-8', xml_declaration=True)

rawDescription: How to convert .txt file into xml file using python?

description: Convert .txt file into xml file using python


rawDescription: How to move a Tkinter button?

description: Move a Tkinter button


code:
product_keys = set(Product.all(keys_only=True).fetch(1000))
product_list = ProductList.get_by_id(product_list_id)
missing_products = product_keys - set(product_list.products)

rawDescription: Google app engine - Users, Lists and Products a Join question on effiency


rawDescription: How to separate the first and last part of a string in a list

description: Separate the first and last part of a string in a list


code:
from pprint import pprint as pp

pp(data)
{1: {'NO_USERS': '3', 'Name': 'IMPULSE', 'id_info': '1021055'},
 2: {'NO_USERS': '1', 'Name': 'PASSION', 'id_info': '324356'},
 3: {'NO_USERS': '5', 'Name': 'VICTOR', 'id_info': '324356'},
 'num_blocks': 3}

rawDescription: How to read a file block-wise in python

description: Read a file block-wise in python


code: picturetag.type = 3

rawDescription: Change embedded image type in APIC ID3 tag via Mutagen


code:
from itertools import chain
def makeMap(d):
    nodes = set([x for x in chain.from_iterable(d.values())])
    return dict([[x, [y for y in d.keys() if x in d[y]]] for x in nodes ])

rawDescription: Acess the dictionary being created inside dictionary comprehension


code:
import numpy as np
import itertools as it

def row_product(*arrays):
    lengths = np.array([x.shape[0] for x in arrays])
    positions = np.cumsum(lengths)

    ranges = np.arange(positions[-1])
    ranges = np.split(ranges,positions[:-1])

    total = np.concatenate((arrays),axis=0)

    inds = np.fromiter(it.chain.from_iterable(it.product(*ranges)), np.int)
    inds = inds.reshape(-1, len(arrays))

    return np.take(total, inds, axis=0)

rawDescription: The set of all combinations of vectors in Python


code:
def remove_n_smallest(lst, n):
    for _ in range(n):
        m = min(lst)
        lst[:] = (x for x in lst if x != m)

rawDescription: Removing the lowest numbers from a list

description: Removing the lowest numbers from a list


rawDescription: How to convert int to Enum in python?

description: Convert int to Enum in python


rawDescription: Django - filtering by a portion of the key within a list


rawDescription: How would I create a text-based board for a scrabble game in python?


rawDescription: Python - check if file/webpage exists

description: Python - check if file/webpage exists


rawDescription: Splitting a GPS Point into Latitude and Longitude Regular


code:
import csv
import sqlite3
from itertools import islice

conn = sqlite3.connect('/tmp/ipaddresses.db')
conn.execute('CREATE TABLE IF NOT EXISTS ipaddress (domain, ip)')
conn.execute('''\
    CREATE UNIQUE INDEX IF NOT EXISTS domain_ip_idx
    ON ipaddress(domain, ip)''')

for filename in files:
    print(filename)
    with open(filename, 'rb') as f:
        reader = csv.reader(f, delimiter='|')
        cursor = conn.cursor()
        while True:
            with conn:
                batch = list(islice(reader, 10000))
                if not batch:
                    break
                cursor.executemany(
                    'INSERT OR IGNORE INTO ipaddress VALUES(?, ?)',
                    batch)

conn.execute('CREATE INDEX IF NOT EXISTS ip_idx ON ipaddress(ip)')
with open(outputfile, 'wb') as outfh:
    writer = csv.writer(outfh, delimiter='|')
    cursor = conn.cursor()
    cursor.execute('SELECT ip, domain from ipaddress order by ip')
    writer.writerows(cursor)

rawDescription: How to parse files larger than 100GB in Python?

description: Parse files larger than 100GB in Python


code: players = sorted(d.values())

rawDescription: Is there a way to pair dictionary items?

description: Is there a way to pair dictionary items


code:
seen = set()
ans = []
for item in lis:
    tup = tuple(item)
    if tup not in seen:
        ans.append(item + [1])
        seen.add(tup)

ans

rawDescription: How to count elements in a list of lists of strings

description: Count elements in a list of lists of strings


rawDescription: Check if an element exists

description: Check if an element exists


code:
def index(self, **kw):
    if kw.get('reset') == '{password}':
        cherrypy.engine.restart()
        ip = cherrypy.request.headers["X-Forwarded-For"] #get_client_ip
        return 'CherryPy RESETTING for duty, sir! requested by '+str(ip)

rawDescription: Restart Python.py when it stops working

description: Restart Python.py when it stops working


code:
# assuming items is a reference to the list of item instances you gave
# in the example
cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%s, %s, %s, %s)", items)

rawDescription: Python: adding named tuples to MySQL in a for loop


code:
vector_a
vector_b

rawDescription: Append input to list as integers

description: Append input to list as integers


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

plt.ion()
mu, sigma = 100, 15
for i in range(50):
    x = mu + sigma*np.random.randn(10000)
    n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
    plt.draw()
    plt.clf()

rawDescription: How do I display real-time graphs in a simple UI for a python program?

description: Display real-time graphs in a simple UI for a python program


code:
i = iter(list_of_strings)
for line in i:
    if line.startswith('$'):
        while line.endswith('#'):
            line = i.next()
        # do work on 'line' which begins with $ and doesn't end with #

rawDescription: for loops in python

description: For loops in python


code: list(sorted(sd_dict.items(), key=lambda x: x[1]['std']))

rawDescription: Sorting nested python dictionary by label


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

def main():
    fig, ax = plt.subplots()
    dual_half_circle(radius=0.1, angle=90, ax=ax)
    ax.axis('equal')
    plt.show()

def dual_half_circle(radius, angle=0, ax=None, colors=('w','k'), **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) at the lower
    left corner of the axes with the specified facecolors *colors* rotated at
    *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    kwargs.update(transform=ax.transAxes, clip_on=False)
    center = (0, 0)
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

main()

rawDescription: Matplotlib half black and half white circle


code:
class YourAbstractFactory(object):
    @classmethod
    def get_factory(cls, condition):
        cond_map = {
            'impl1': Impl1,
            'impl2': Impl2
        }

        impl = cond_map.get(condition)

        return impl() if impl else None

    def f1(self):
        pass

    def f2(self):
        pass

rawDescription: Advantages to two modules with same interface or two classes with the same interface?


code:
#!usr/bin/env python

import wx

class TestFrame(wx.Frame):
    def __init__(self, parent, *args, **kwargs):
        wx.Frame.__init__(self, parent, *args, **kwargs)
        framesizer = wx.BoxSizer(wx.VERTICAL)
        mainpanel = MainPanel(self, wx.ID_ANY)
        self.subpanel = SubPanel(self, wx.ID_ANY)
        self.subpanel.Hide()
        framesizer.Add(mainpanel, 1, wx.EXPAND)
        framesizer.Add(self.subpanel, 1, wx.EXPAND)
        self.SetSizerAndFit(framesizer)

class MainPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        panelsizer = wx.BoxSizer(wx.VERTICAL)
        but = wx.Button(self, wx.ID_ANY, "Add")
        self.Bind(wx.EVT_BUTTON, self.OnAdd, but)
        self.panel_shown = False
        panelsizer.Add(but, 0)
        self.SetSizer(panelsizer)

    def OnAdd(self, evt):
        if not self.panel_shown:
            self.GetParent().subpanel.Show()
            self.GetParent().Fit()
            self.GetParent().Layout()
            self.panel_shown = True
        else:
            self.GetParent().subpanel.Hide()
            self.GetParent().Fit()
            self.GetParent().Layout()
            self.panel_shown = False

class SubPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        spsizer = wx.BoxSizer(wx.VERTICAL)
        text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel')
        spsizer.Add(text, 1, wx.EXPAND)
        self.SetSizer(spsizer)

if __name__ == '__main__':
    app = wx.App()
    frame = TestFrame(None, wx.ID_ANY, "Test Frame")
    frame.Show()
    app.MainLoop()

rawDescription: How do I Create an instance of a class in another class in Python


code: pd.concat([df, target], axis=1)

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code:
'tt:Device'.split(':')[-1]  # with namespace
'Device'.split(':')[-1]  # without namespace

rawDescription: How to get node name without namespace if it exists?

description: Get node name without namespace if it exists


code:
import csv
with open('somepath/file.txt', 'wb+') as outfile:
  w = csv.writer(outfile)
  w.writerow(['header1', 'header2'])
  for i in you_data_structure: # eg list or dictionary i'm assuming a list structure
    w.writerow([
      i[0],
      i[1],
    ])

rawDescription: Output from function to text/CSV file?

description: Output from function to text/CSV file


code:
for f in self.subdirArray1:
    if f.replace(self.rootDir1,self.rootDir2) not in self.subdirArray2:
        self.statusText.SetValue("This file: " + f + " does not correspond to any file in parallel.")
        self.blocker = True
        self.statusText.SetForegroundColour(wx.RED)
        return False
for f in self.subdirArray2:
    if f.replace(self.rootDir2,self.rootDir1) not in self.subdirArray1:
        self.statusText.SetValue("This file: " + f + " does not correspond to any file in parallel.")
        self.blocker = True
        self.statusText.SetForegroundColour(wx.RED)
        return False

rawDescription: Image Saving I/O Using Python Efficiency & Speed


code:
result = data.read()

prefix = 'oo.visualization.Query.setResponse('
suffix = ');'

if result.startswith(prefix) and result.endswith(suffix):
    result = result[len(prefix):-len(suffix)]

rawDescription: Extracting data from a URL result with special formating


code:
def apply_all(functions, item):
    for f in functions:
        yield f(item)

rawDescription: How do you apply a list of lambda functions to a single element using an iterator?

description: Apply a list of lambda functions to a single element using an iterator


code: drawImage(image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c')

rawDescription: Insert multiple images in a single PDF according to image.coordinates - Python


code:
numberPrimes = 0
startNumber = 0
currentNumber = startNumber
isPrime = 0
while numberPrimes < 1000:
    if currentNumber == 1:
        currentNumber = currentNumber + 1
    else:
        for primeCheck in range (int(2), int(currentNumber)):
            if int(currentNumber)%primeCheck == 0:
                isPrime = 1
                break
            else:
                isPrime = 0
        if isPrime == 0:
            print(currentNumber, 'is prime')
            numberPrimes = numberPrimes + 1
            currentNumber == currentNumber + 1
        else:
            currentNumber == currentNumber + 1

rawDescription: Python and Prime Numbers

description: Python and Prime Numbers


code:
['assign (resid 42 and name H ) (resid 55 and name H ) 2.5 2.5 2.5 ! note '
 'string 3',
 'assign (resid 16 and name H ) (resid 5 and name H ) 2.5 2.5 2.5 ! note '
 'string 2',
 'assign (resid 3 and name H ) (resid 18 and name H ) 2.5 2.5 2.5 ! note '
 'string 1',
 'assign (resid 44 and name H ) (resid 53 and name H ) 2.5 2.5 2.5 ! note '
 'string 4']

rawDescription: Python Find Duplicate with Note String Preservation


code:
items = [{'num': 3, 'obj': 'books'}, {'num': 1, 'obj': 'pen'}, {'num': 2, 'obj': 'cellphones'}]
objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
"There are {} on the table".format(objects)

rawDescription: Building up a string using a list of values


code:
import MySQLdb as m

if __name__ == '__main__':
    db = m.connect(user='root',db='test')
    c = db.cursor()
    c.callproc("per5min")
    print(c.fetchall())
    c.close()
    db.close()

rawDescription: python : mysql : Return 0 when no rows found

description: Python : mysql : Return 0 when no rows found


code:
try:
    from itertools import zip_longest
except ImportError:
    # Python 2
    from itertools import izip_longest as zip_longest

def alternate(list1, list2):
    return [v for v in sum(zip_longest(list1, list2), ()) if v is not None]

rawDescription: Combine numerous lists of different length in python in an alternating order


code: p1 = Task1(queue, done)

rawDescription: Python Process completion

description: Python Process completion


rawDescription: Python: How to convert a rgb or hex value to single color values


code:
@app.route('/flip', methods=['POST'])
def flip():
    ticket = Ticket.query.filter_by(id=request.form["flip"]).first_or_404()
    ticket.status = 0
    db.session.commit()
    return redirect(url_for('index'))

rawDescription: Flask - Submit Button Actioning Database Update


code: from a import add

rawDescription: Call python function from other py file what goes in __init__.py


code:
Lastname0:Password0
Lastname1:Password1
Lastname2:Password2
Lastname3:Password3

rawDescription: Python - Writing to a new file from another file


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

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

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


code:
for s in dizv:
    for kk in dizv[s]:
        dnew[kk] = set([s])

rawDescription: Assign "ID" to a string in a "post"

description: Assign "ID" to a string in a "post"


code:
def trav(dir_1, dir_2):
    data_0 = []
    data_1 = []
    for dir in [dir_1, dir_2]:
        current_dir = dir
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                      if current_dir == dir_1:
                          data_0.append(line)
                      else:
                          data_1.append(line)

rawDescription: Python, appending to different lists while looping


code:
...
def import_plugin(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

...
feed_parser = import_plugin('parsers.%s' % feed['format'])
data = feed_parser(...)
...

rawDescription: Template driven feed parsing

description: Template driven feed parsing


rawDescription: Read several lists from the text file properly python


code:
from bs4 import BeautifulSoup
import requests

def getPhoneStats(url):
    try:
        request= requests.get(url)
        if request.status_code == 200:
            soup = BeautifulSoup(request.content,"html.parser")

            for table in soup.findAll("table"):
                header = table.th.get_text()
                for row in table.findAll("tr"):
                    out_row = [ header ]
                    for col in row.findAll("td"):
                        out_row.append(col.get_text())
                    print(out_row)
        else:
            print('unable to connect ')
    except requests.HTTPError as e:
        print('Unable to open url',e)

if __name__ == "__main__":
    getPhoneStats('''http://www.gsmarena.com/lenovo_k3_note-7147.php''')

rawDescription: Scrap all tables from div using BeautifulSoup


code:
class Monster:
    def __init__ (self, name, age):
        self.name = name
        self.age = age

    def greet (self):
        print ("Hello, I'm", self.name, "of age", self.age, ".")

person = Monster("Monster",340)
person.greet() #prints Hello, I'm Monster of age 340 .

person.name = "John"
person.greet() #prints Hello, I'm John of age 340 .

person.name = "Mary"
person.age = 60
person.greet() #prints Hello, I'm Mary of age 60 .

rawDescription: When a class is created in Python, and an object referencing it is used, how would you use the name of the object in the class?


code:
class dictholder():
    def __init__(self):
        self.dict = {}

    def add(self, name, time):
        if name in self.dict:
            if (abs(time) - abs(self.dict[name][0]) < 2):
                self.dict[name][1] += 1
                self.dict[name][0] = time
                if self.dict[name][1] == 3:
                    del self.dict[name]
        else:
            self.dict[name] = [time, 1]
        for item in self.dict:
            if (abs(time) - abs(self.dict[item][0]) > 2):
                self.dict[item][1] = 1

    def get(self):
        return self.dict

rawDescription: specific implementation of dictionary

description: Specific implementation of dictionary


code:
process = subprocess.Popen('echo $(pwd)', stdout=subprocess.PIPE, shell=True)
out, err = process.communicate()
out

rawDescription: Using back-ticks in Python subprocess

description: Using back-ticks in Python subprocess


code:
trends1 = api.trends_place(1) # from the end of your code
# trends1 is a list with only one element in it, which is a
# dict which we'll put in data.
data = trends1[0]
# grab the trends
trends = data['trends']
# grab the name from each trend
names = [trend['name'] for trend in trends]
# put all the names together with a ' ' separating them
trendsName = ' '.join(names)
print(trendsName)

rawDescription: Python: Get Twitter Trends in tweepy, and parse JSON


code: Z = hierarchy.linkage(points, method="average")

rawDescription: Triangle vs. Square distance matrix for Hierarchical Clustering Python?


code:
class Score(object):
    def __init__(self, points):
        self.points = points
    def __repr__(self):
        return 'Score({})'.format(self.points)

scores = [Score(i) for i in [99.1, 78.3, ...]]
for s in scores:
    s.points += 5  # adds 5 points to each score

rawDescription: How to change variables fed into a for loop in list form

description: Change variables fed into a for loop in list form


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

# Generate data
nrows, ncols = 20, 5
x = np.exp(np.random.normal(0, 0.8, (nrows, ncols)))
y = np.exp(np.random.normal(0, 1, (nrows, ncols)))

# Make data for display
mask = np.array(nrows * [ncols * [False, True]], dtype=bool)
red = np.ma.masked_where(mask, np.repeat(x, 2, axis=1))

mask = np.array(nrows * [ncols * [True, False]], dtype=bool)
blue = np.ma.masked_where(mask, np.repeat(y, 2, axis=1))

# Make a side-by-side plot
fig, ax = plt.subplots()
redmesh = ax.pcolormesh(red, cmap='Reds')
bluemesh = ax.pcolormesh(blue, cmap='Blues')

# Make things a touch fancier
ax.set(xticks=np.arange(1, 2 * ncols, 2),
       yticks=np.arange(nrows) + 0.5,
       xticklabels=['Column ' + letter for letter in 'ABCDE'],
       yticklabels=['Row {}'.format(i+1) for i in range(nrows)])

ax.set_title('Side-by-Side Plot', y=1.07)
ax.xaxis.tick_top()
ax.yaxis.tick_left()
ax.tick_params(direction='out')

# Add dual colorbars
fig.subplots_adjust(bottom=0.05, right=0.78, top=0.88)
cbar = fig.colorbar(redmesh, cax=fig.add_axes([0.81, 0.05, 0.04, 0.83]))
cbar.ax.text(0.55, 0.1, 'Variable 1', rotation=90, ha='center', va='center',
             transform=cbar.ax.transAxes, color='gray')
cbar = fig.colorbar(bluemesh, cax=fig.add_axes([0.9, 0.05, 0.04, 0.83]))
cbar.ax.text(0.55, 0.1, 'Variable 2', rotation=90, ha='center', va='center',
             transform=cbar.ax.transAxes, color='gray')

# Make the grouping clearer
ax.set_xticks(np.arange(0, 2 * ncols, 2), minor=True)
ax.grid(axis='x', ls='-', color='gray', which='minor')
ax.grid(axis='y', ls=':', color='gray')

plt.show()

rawDescription: Creating a matplotlib heatmap with two different coloured data sets


rawDescription: Merge Columns within a DataFrame that have the Same Name


code: r.json()['unis'].keys() # gives me the following error

rawDescription: Parsing large JSON - Python

description: Parsing large JSON - Python


rawDescription: explanation for groupby() in Pandas dataframe object behaviour

description: Explanation for groupby() in Pandas dataframe object behaviour


code:
self.Bands = []
self.Bands.append(Band(self.Meta, 1))
self.Bands.append(Band(self.Meta, 2))
self.Bands.append(Band(self.Meta, 3))

rawDescription: Can an attribute access another attribute?


code:
z=np.empty((10,5))
for i in range(10):
   for j in range(5):
      z[i,j] = x[i]**2 + y[j]**2

rawDescription: Reshaping numpy array without using two for loops


rawDescription: Dealing with data inside TFIDF Sparevector or saving it to Dataframe or external file


code: dir(list)

rawDescription: What's the equivalent of PHP's "$my_array[]" in Python?


code:
s = Series(date_range('1/1/2001', periods=5, freq='D'))
s.values

rawDescription: Is there a dedicated milli-sec precision timestamp data structure in python pandas?


code: prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]

rawDescription: index of a letter in string - python 2.7

description: Index of a letter in string - python 2.7


code:
def overlap( r1, r2 ):
    left =  max(r1[0], r2[0])
    right = min(r1[1], r2[1])
    over = right - left
    return (left, right, over) if over>0 else None

rawDescription: Python: optimizing pairwise overlaps between intervals


rawDescription: How to create dynamic link between list variables

description: Create dynamic link between list variables


code:
if input_a not in dictionary.values():
        print('Sorry, try again')

rawDescription: How can I select all keys in a python dictionary?

description: Select all keys in a python dictionary


code:
from bs4 import BeautifulSoup
import urllib2
url = 'http://www.soccerstats.com/team.asp?league=england&teamid=24'
soup = BeautifulSoup(urllib2.urlopen(url).read(), 'lxml')
all_stats = soup.find('div', id='team-matches-and stats')
left_column, right_column = [x for x in all_stats.table.tr.children if x.name == 'td']
table1, table2 = [x for x in right_column.children if x.name == 'table']  # the two tables at the top right
[x['title'] for x in right_column.find_all('div', class_='tabbertab')]

rawDescription: Python beautiful soup how to get deep nested elements


code:
say=lambda x:lambda y:print(x+" "+y)
say('Hello')('World')

rawDescription: Interesting "Hello World" Interview

description: Interesting "Hello World" Interview


code:
loop = asyncio.get_event_loop()
coro = hello_world(loop)
loop.run_until_complete(coro)

rawDescription: Execute coroutine from `call_soon` callback function


code:
import numpy as np

# add one additional value so that the arrays have the same length
myArray = np.array([1, 3, 4, 5, 15, 14, 16, 13, 17])

# choose the starting index rather than the element
n = 2

myAverage = np.array([2, 3.5, 4.5, 10, 14.5, 15, 14.5])

diffAr = myArray[n:] - myAverage

rawDescription: Function which is similar to numpy's diff


rawDescription: common elements in two lists where elements are the same

description: Common elements in two lists where elements are the same


rawDescription: Concatenate all rows of a numpy matrix in python


code: botmsg = botdata.split(':')[2]

rawDescription: Identify sending user, Python IRC

description: Identify sending user, Python IRC


code:
with io.open('test_file.txt', 'w') as f:
    f.write(text)

df = read_email_headers('test_file.txt')
print(df.to_string())  # Same output as before.

rawDescription: Read data from text format into Python Pandas dataframe


code:
mouse_clicks = set()

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit

        if event.type == MOUSEBUTTONDOWN:
            mouse_clicks.add(pygame.mouse.get_pos())

        elif event.type == KEYDOWN and event.unicode == 'c':
            # clear the circle when pressing the 'c' key
            mouse_clicks.clear()

    screen.blit(background,(0,0))
    x,y = pygame.mouse.get_pos()
    x -= mousec.get_width()/2
    y -= mousec.get_height()/2

    screen.blit(mousec, (x,y))

    for pos in mouse_clicks:
        color = (100,100,100)
        posx,posy = pos
        pygame.draw.circle(screen, color, (posx,posy), 50)

    pygame.display.update()

rawDescription: Why won't pygame draw a circle?

description: Why won't pygame draw a circle


code:
import boto

sg_string_list = ['sg-xxxx1234', 'sg-xxxx5678']

conn = boto.connect_ec2()
conn.modify_network_interface_attribute(interface_id=eni_id,
                                        attr='groupSet',
                                        value=sg_string_list)

rawDescription: How do I add or remove security groups from ENIs using Boto?

description: Add or remove security groups from ENIs using Boto


code:
from google.appengine.api import urlfetch

rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, "http://www.google.com/")

# ... do other things ... << YOUR CODE HERE

rpc.wait()

rawDescription: Asynchronous fetch request with Google App Engine


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import scipy.spatial as spatial

def fmt(x, y):
    return 'x: {x:0.2f}\ny: {y:0.2f}'.format(x=x, y=y)

class FollowDotCursor(object):
    """Display the x,y location of the nearest data point.
    http://stackoverflow.com/a/4674445/190597 (Joe Kington)
    http://stackoverflow.com/a/20637433/190597 (unutbu)
    """
    def __init__(self, ax, x, y, formatter=fmt, offsets=(-20, 20)):
        try:
            x = np.asarray(x, dtype='float')
        except (TypeError, ValueError):
            x = np.asarray(mdates.date2num(x), dtype='float')
        y = np.asarray(y, dtype='float')
        mask = ~(np.isnan(x) | np.isnan(y))
        x = x[mask]
        y = y[mask]
        self._points = np.column_stack((x, y))
        self.offsets = offsets
        y = y[np.abs(y - y.mean()) <= 3 * y.std()]
        self.scale = x.ptp()
        self.scale = y.ptp() / self.scale if self.scale else 1
        self.tree = spatial.cKDTree(self.scaled(self._points))
        self.formatter = formatter
        self.ax = ax
        self.fig = ax.figure
        self.ax.xaxis.set_label_position('top')
        self.dot = ax.scatter(
            [x.min()], [y.min()], s=130, color='green', alpha=0.7)
        self.annotation = self.setup_annotation()
        plt.connect('motion_notify_event', self)

    def scaled(self, points):
        points = np.asarray(points)
        return points * (self.scale, 1)

    def __call__(self, event):
        ax = self.ax
        # event.inaxes is always the current axis. If you use twinx, ax could be
        # a different axis.
        if event.inaxes == ax:
            x, y = event.xdata, event.ydata
        elif event.inaxes is None:
            return
        else:
            inv = ax.transData.inverted()
            x, y = inv.transform([(event.x, event.y)]).ravel()
        annotation = self.annotation
        x, y = self.snap(x, y)
        annotation.xy = x, y
        annotation.set_text(self.formatter(x, y))
        self.dot.set_offsets((x, y))
        event.canvas.draw()

    def setup_annotation(self):
        """Draw and hide the annotation box."""
        annotation = self.ax.annotate(
            '', xy=(0, 0), ha = 'right',
            xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
            bbox = dict(
                boxstyle='round,pad=0.5', fc='yellow', alpha=0.75),
            arrowprops = dict(
                arrowstyle='->', connectionstyle='arc3,rad=0'))
        return annotation

    def snap(self, x, y):
        """Return the value in self.tree closest to x, y."""
        dist, idx = self.tree.query(self.scaled((x, y)), k=1, p=1)
        try:
            return self._points[idx]
        except IndexError:
            # IndexError: index out of bounds
            return self._points[0]

np.random.seed(6)
numdata = 100
t = np.linspace(0.05, 0.11, numdata)
y1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
y2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(t, y1, 'r-', label='y1')
ax2.plot(t, y2, 'g-', label='y2')

cursor1 = FollowDotCursor(ax1, t, y1)
cursor2 = FollowDotCursor(ax2, t, y2)
plt.show()

rawDescription: Matplotlib cursor value with two axes

description: Matplotlib cursor value with two axes


code:
t = ('Let', 'Us', 'Test')
type(t)

rawDescription: Python print() output discrepancy

description: Python print() output discrepancy


code: reduce(lambda d,k: d.setdefault(k, {}), keys, dict_nested)[newkey] = newvalue

rawDescription: Python: Change values in dict of nested dicts using items in a list


code:
'haveRev'
'rev'
'clientFile'
'client'
'user'
'action'
'type'
'depotFile'
'change'

rawDescription: How to get the type of change in P4Python

description: Get the type of change in P4Python


rawDescription: Python what does abs do? I have tried looking at different pages for help, however i cannot understand the jargon


code:
def __init__(self,spam,eggs,swallow,coconut='Migrated.'):
        self.spam = spam
        self.eggs = eggs
        self.swallow = swallow
        self.coconut = coconut

rawDescription: Initializing object variables - a Java approach, a Python approach?


code:
def teaching_results(x):
    num_rows = x.passed.iloc[0] + x.failed.iloc[0]
    passed = x.passed.iloc[0] * [1] + x.failed.iloc[0] * [0]
    extra_teaching = num_rows * [x.extra_teaching.iloc[0]]
    class_code = x['class'].iloc[0]
    return pd.DataFrame({'pass': passed, 'extra_teaching': extra_teaching, 'class': class_code})

df.groupby('class', as_index=False).apply(lambda x: teaching_results(x))

rawDescription: How to 'unravel' a dataframe using the values of the rows?


rawDescription: Uninstall python.org version of python2.7 in favor of default OS X python2.7


code:
s = 'AAAKBBBBRAAA'
re.findall(r'[^KR]+[KR]?', s)

rawDescription: Translate perl split to python split

description: Translate perl split to python split


code: [tuple(k for (k,v) in d.items() if v == w) for w in l]

rawDescription: Combining Keys in Dictionary into tuples in a list


rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


code:
import numpy as np
from skimage.io._plugins import freeimage_plugin as fi
image = np.zeros((32, 256, 256), 'uint16')
fi.write_multipage(image, 'multipage.tif')

rawDescription: Create a multiframe .tif file

description: Create a multiframe .tif file


rawDescription: Counting occurrence of a word in a column of a tsv file using python


code: df.groupby("Letters")["Bool"].sum() # select Bool, sum it

rawDescription: Summing values in a group of a groupby object?


code:
obj = {}
for i in range(1, 21):
    obj['l'+str(i)] = []

obj

rawDescription: Python : creating multiple lists

description: Python : creating multiple lists


code: names = list(map(lambda x: x[0], cursor.description))

rawDescription: Is there a way to get a list of column names in sqlite?


code:
class A(object):
    def __init__(self, words):
        self.words = words

    def get_words(self):
        return self.words

a = A("I am a")
b = A("I am b")

def make_meth(inst, _cls, meth, lm):
    inst.__class__ = type(_cls.__name__, (_cls,), {meth: lm})

make_meth(a, A, "__len__", lambda self: 12)
make_meth(b, A, "__len__", lambda self: 44)

print(len(b))
print(len(a))
print(a.get_words())
print(b.get_words())

rawDescription: Making len() work with instance methods

description: Making len() work with instance methods


code:
import networkx as nx

# Sample graph
G = nx.Graph()
G.add_edge(0,1)
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(1,3)

labels = {(0,1):'foo', (2,3):'bar'}

pos=nx.spring_layout(G)

nx.draw(G, pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels,font_size=30)

import pylab as plt
plt.show()

rawDescription: graph-tool: Draw text on edges

description: Graph-tool: Draw text on edges


code:
import re
stuff = ["$x$y0123", "$", "", "  \t", "$x      @hi"]

p1 = re.compile(r'(?:\$[A-Z_]\w*|\s)*$', re.IGNORECASE)
p2 = re.compile(r'\$[A-Z_]\w*|\s+', re.IGNORECASE)

for thing in stuff:
    if p1.match(thing):
        print(p2.findall(thing))

rawDescription: python regular expression $[a-zA-Z ][0-9a-zA-Z ]* with forbidding

description: Python regular expression $[a-zA-Z ][0-9a-zA-Z ]* with forbidding


code:
class Product(models.Model):
    name = models.CharField()
    image = models.ImageField(blank=True, null=True)
    weight = models.DecimalField(blank=True, null=True)

rawDescription: How do you implement multiple data types for an object in Django?

description: Implement multiple data types for an object in Django


code:
with open("in.txt") as f:
    import re
    r = re.compile(r'(^DATE/USER:\s+\d+/\d+/\d+\s+(\w+$))')
    for line in f:
        match = r.search(line)
        if match:
           print(match.group(2))

rawDescription: Python: How to skip lines that have extra characters while using Regular Expressions?


code:
def isdigit(s):
    """Better isdigit that handles strings like "-32"."""
    try:
        int(s)
    except ValueError:
        return False
    else:
        return True

rawDescription: Hi I was wondering if there was a data type in Python that only allows letters to be inputed and not numbers


rawDescription: Python append dictionary item to array in dictionary


code:
for match in pattern.finditer(mailbody):
    print(tuple(match.groups()))

rawDescription: Different behavior between re.finditer and re.findall


code:
def purify(numbers):
    for item in reversed(numbers):
        if item % 2:
            numbers.remove(item)
    return numbers

rawDescription: Python remove element in for loop

description: Python remove element in for loop


code:
import numpy as np
from sklearn.preprocessing import PolynomialFeatures

X = np.random.rand(1000, 3)

poly = PolynomialFeatures(4)
Y = poly.fit_transform(X)

features = ['X1','X2','X3']

print(poly.powers_)

for entry in poly.powers_:
    newFeature = []
    for feat, coef in zip(features, entry):
        if coef > 0:
            newFeature.append(feat+'**'+str(coef))
    if not newFeature:
        print(1) # If all powers are 0
    else:
        print(' + '.join(newFeature))

rawDescription: How can I see the effect of sklearn.preprocessing.PolynomialFeatures?

description: See the effect of sklearn.preprocessing.PolynomialFeatures


rawDescription: Python Filtering 2 Lists

description: Python Filtering 2 Lists


code: List = [s[1:] for s in List]

rawDescription: Delete Extra Space from Values In List

description: Delete Extra Space from Values In List


code:
try:
    input = raw_input
except NameError:
    pass

rawDescription: How should I wait for a keypress in both Python 2 and Python 3?


rawDescription: find unique first top and bottom lines of fastq file from fasta file

description: Find unique first top and bottom lines of fastq file from fasta file


code: countedQuestions = Counter([question for q in answers for question in q])

rawDescription: Search in a python list

description: Search in a python list


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

axes_lst = []
#Prepares the data
x = np.arange(5)
y = np.exp(x)

#plot fig1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
axes_lst.append(ax1)

#plot fig2
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
axes_lst.append(ax2)

for ax in axes_lst:
    ax.plot(x, y)

plt.show()

rawDescription: Matplotlib: Plotting the same graph in two different figures without writting the "plot(x,y)" line twice


code:
@conditional('matplotlib' in sys.modules, 'Please install matplotlib')
def foo(self, bar):
    pass

rawDescription: Deactivate function with decorator

description: Deactivate function with decorator


code:
import gtk
pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png')

rawDescription: Scale an image in GTK

description: Scale an image in GTK


code:
#!/usr/bin/env python
import argparse, csv
if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='merge csv files on field', version='%(prog)s 1.0')
    parser.add_argument('infile', nargs='+', type=str, help='list of input files')
    parser.add_argument('--out', type=str, default='temp.csv', help='name of output file')
    args = parser.parse_args()
    data = {}
    fields = []

    for fname in args.infile:
        with open(fname, 'rb') as df:
            reader = csv.DictReader(df)
            for line in reader:
                # assuming the field is called ID
                if line['ID'] not in data:
                    data[line['ID']] = line
                else:
                    for k,v in line.iteritems():
                        if k not in data[line['ID']]:
                            data[line['ID']][k] = v
                for k in line.iterkeys():
                    if k not in fields:
                        fields.append(k)
            del reader

    writer = csv.DictWriter(open(args.out, "wb"), fields, dialect='excel')
    # write the header at the top of the file
    writer.writeheader()
    writer.writerows(data)
    del writer

rawDescription: Merge multiple *.csv, *.txt, or *.ascii files based on a common field using python


code:
import re
print (re.sub(r"(?![\d_])\w","X","dfäg"))
# => XXXX

rawDescription: Can the [a-zA-Z] Python regex pattern be made to match and replace non-ASCII Unicode characters?


rawDescription: Python - get subset from 2nd, to last element


code:
import util

class MyObj:
    def func():
        util.get_content()

rawDescription: mocking functions using python mock

description: Mocking functions using python mock


code:
argspec = getargspec(my_function)
keyword_args = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
positional_args = [None] * (len(argspec.args) - len(argspec.defaults))  # set all positionals to None
my_function(*positional_args, **keyword_args)

rawDescription: python variable value to trigger parameter default

description: Python variable value to trigger parameter default


code:
class CObjectsEncoder(json.JSONEncoder):
    def iterencode(self, o, _one_shot=False):
        o = map_intenum(o)
        return super(CObjectsEncoder, self).iterencode(o, _one_shot)
    def default(self, o):
        if isinstance(o, Enum):
            return {'__class__': o.__class__.__name__,
                    '__value__': (o.value,)}
        return super(CObjectsEncoder, self).default(o)

rawDescription: How do I serialize IntEnum from enum34 to json in python?

description: Serialize IntEnum from enum34 to json in python


code:
import gtk
import subprocess
import threading

gtk.gdk.threads_init()

class FollowProcess(threading.Thread):
    def __init__(self, cmd, text_buffer):
        self.tb = text_buffer
        self.child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        super(FollowProcess, self).__init__()

    def run(self):
        while not self.child.poll():
            out = self.child.stdout.read(1)
            if out != '':
                gtk.gdk.threads_enter()
                self.tb.insert_at_cursor(out)
                gtk.gdk.threads_leave()

def destroy(w, cmd):
    cmd.child.terminate()
    gtk.main_quit()

i = 0
def click_count(btn):
    global i
    message.set_text('Calling button %d' %i)
    i += 1

other_command = 'python extranger.py'

w = gtk.Window()
w.resize(400, 400)

message = gtk.Label('Nothing')
tb = gtk.TextBuffer()
tv = gtk.TextView(tb)
scroll = gtk.ScrolledWindow()
scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scroll.add(tv)

box = gtk.VBox()
button = gtk.Button('Active button')

cmd = FollowProcess('python extranger.py', tb)

button.connect('clicked', click_count )

w.connect('destroy', destroy, cmd)
box.pack_start(button, False)
box.pack_start(message, False)
box.pack_start(scroll)

w.add(box)
w.show_all()
cmd.start()
gtk.main()

rawDescription: Regarding running a script from another

description: Regarding running a script from another


code: super(SchoolHouse, self).build(*args)

rawDescription: Multiple Inheritance with same Base Classes in Python


code:
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
eng = create_engine("mssql+pyodbc://", poolclass=StaticPool, creator=lambda: my_odbc_connection)

rawDescription: In SQLAlchemy, can I create an Engine from an existing ODBC connection?


rawDescription: Pandas - bucketing events close to each other


code:
import matplotlib.pyplot as plt

a = trace['alpha']
b = trace['beta']
x = np.linspace(0,1,N)

fig = plt.figure(figsize=(12,4))

ax = fig.add_subplot(1,2,1)
plt.scatter(X,Y, color='g', alpha=0.3)
for i in xrange(500):
  y = a[i] + b[i] * x
  plt.plot(x, y, 'b', alpha=0.02)

ax = fig.add_subplot(1,2,2)
for i in xrange(500):
  y = a[i] + b[i] * x
  plt.plot(x, y, 'b', alpha=0.02)
plt.show()

rawDescription: Linear regression with pymc3 and belief

description: Linear regression with pymc3 and belief


code:
def some_callback(a, b, c=None):
    print(a,b,c)

Button(text="Do not press",
    command=lambda: some_callback(1, 2, 3))

rawDescription: Function to make functions callable doesn't work properly


rawDescription: python threading blocks

description: Python threading blocks


rawDescription: Numpy does treat float('nan') and float differently - convert to None


code:
with open("A.txt") as infile, open("C.txt", "w") as outfile:
    for line in infile:
        start, end = line.strip().rsplit(None, 1)
        outfile.write("{0} {1}\n".format(start, B[end]))

rawDescription: How to replace a particular value of a field (column) in a file with a value from another file in shell scripting?

description: Replace a particular value of a field (column) in a file with a value from another file in shell scripting


code:
test_str = "ask and asked, ask are different ask. ask"
word = "ask"
def finder(s,w):
  return re.findall(r'\b{}\b'.format(w),s,re.U)

finder(text_str,word)

rawDescription: Python - Check If string Is In bigger String


code: {'foo': None, 'bar': None}

rawDescription: How to present a class as a function?

description: Present a class as a function


rawDescription: converting binary to utf-8 in python

description: Converting binary to utf-8 in python


code:
list_of_folders = [
    u'Magazines/testfolder1',
    u'Magazines/testfolder1/folder1/folder2/folder3',
    u'Magazines/testfolder1/folder1/',
    u'Magazines/testfolder1/folder1/folder2/',
    u'Magazines/testfolder2',
    u'Magazines/testfolder2/folder1/folder2/folder3',
    u'Magazines/testfolder2/folder1/',
    u'Magazines/testfolder2/folder1/folder2/',
    u'Magazines/testfolder3',
    u'Magazines/testfolder3/folder1/folder2/folder3',
    u'Magazines/testfolder3/folder1/',
    u'Magazines/testfolder3/folder1/folder2/',
]
result = set()
for folder in list_of_folders:
    for parent in result:
        if folder.startswith(parent):
            break
    else:
        result.add(folder)

result

rawDescription: Find parent folders in list of paths

description: Find parent folders in list of paths


rawDescription: How to partition dataframe rows into bins with calculations

description: Partition dataframe rows into bins with calculations


rawDescription: Convert a numpy array to an array of numpy arrays


code:
from __future__ import print_function
from collections import defaultdict

d=defaultdict(list)

with open('/tmp/cols.txt') as f:
    for line in f:
        line_data=line.strip().split()
        d['\t'.join(line_data[0:5])].append(line_data[5])

for k in sorted(d.keys(),
                key=lambda s: (s.split()[0], tuple(map(int, s.split()[1:])))):
    print(k, '\t',', '.join(d[k]))

rawDescription: eliminating rows and combining from a file

description: Eliminating rows and combining from a file


code:
CLOSESPIDER_ITEMCOUNT = 0
USER_AGENT = u'Scrapy/1.0.3 (+http://scrapy.org)'
HTTPCACHE_DIR = 'httpcache'
MEMUSAGE_REPORT = False
...

rawDescription: How do I log Scrapy settings?

description: Log Scrapy settings


rawDescription: Python string similarity with probability


code:
v.press_keycode(66)    # turns capslock on
v.release_keycode(66)
v.press_keycode(66)    # turns capslock off
v.release_keycode(66)

rawDescription: Anybody know how to toggle caps lock on/off in Python?


code:
upload_handlers = request.upload_handlers
content_type   = str(request.META.get('CONTENT_TYPE', ""))
content_length = int(request.META.get('CONTENT_LENGTH', 0))

if content_type == "":
    return HttpResponse(status=400)
if content_length == 0:
    # both returned 0
    return HttpResponse(status=400)

content_type = content_type.split(";")[0].strip()
try:
    charset = content_type.split(";")[1].strip()
except IndexError:
    charset = ""

# we can get the file name via the path, we don't actually
file_name = path.split("/")[-1:][0]
field_name = file_name

rawDescription: How do I handle file upload via PUT request in Django?

description: Handle file upload via PUT request in Django


rawDescription: How to recognize which mathematical function generated a curve given by X and Y arrays in sympy

description: Recognize which mathematical function generated a curve given by X and Y arrays in sympy


code:
models.py
class PresetList(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

rawDescription: HTML tags for choicefield in Django

description: HTML tags for choicefield in Django


code: construct_idx = 0

rawDescription: Processing a sub-list of variable size within a larger list


code:
def your_view(request):
    if request.is_ajax(): return updateRevFromS3(request)
    elif request.POST.get("my-hidden-input-name") == "this-is-the-update-form":
        return updateRevFromS3(request)
    return normal_processing()

rawDescription: How can I run a Django function on a button press which doesn't render content?

description: Run a Django function on a button press which doesn't render content


code:
# __init__.py:

from common_settings import *

# A check for environment variable, hostname, etc:
# Example for checking hostname:
from platform import node
if node() in ['dev1', 'dev2']:
    from local import *
elif node() in ['prod1', 'prod2']:
    from production import *

rawDescription: Active Django settings file from Celery worker


code:
import datetime, pytz

testing = False # set to True/False

if testing:
    now = datetime.datetime(2011, 1, 1, 12, 23, 34, tzinfo=pytz.utc)
    # testing with any time
else:
    now = datetime.datetime.now(pytz.utc)
    # normal usage with current time

if (now.hour == 12):
    ...

rawDescription: test time-based scripts

description: Test time-based scripts


code:
self.child1=childclassname()
self.child1.childfunction1()
a1 = self.child1.childvariable1

rawDescription: How could I make a good application architecture in Python with PyQt?


code:
import csv
import StringIO
line = 'a, b, "c, z",,,d,e,f'
file_like = StringIO.StringIO(line)
csvreader = csv.reader(file_like, delimiter=',', quotechar='"', skipinitialspace=True)
list(csvreader)

rawDescription: Preserve consecutive whitespace with shlex


code: list(map(list, input_file))

rawDescription: Is there a more efficient way to create this 2D list?


rawDescription: Create an offset list python

description: Create an offset list python


code: sorted(string.split('\n'), key=lambda x: x.split()[5])

rawDescription: Using sorted and key parameter on list of strings


code:
url = "http://creepypasta.wikia.com/api.php?%20action=query&prop=revisions&titles=Main_Page&rvprop=content&indexpageids=1&format=json"
j = json.load(urllib2.urlopen(url))
value = j['query']['pages']['22491']['revisions'][0]['*']

rawDescription: Getting Page Content via Json

description: Getting Page Content via Json


code:
def match_loop(seq, other):
    count = 0
    for this, that in zip(seq, other):
        if this != that:
            return count
        count += 1
    return count

rawDescription: Find the 1 based position to which two lists are the same


code:
def multirange_original(counts):
    ranges = np.concatenate([np.arange(count) for count in counts])
    return ranges

rawDescription: How to efficiently concatenate many arange calls in numpy?

description: Efficiently concatenate many arange calls in numpy


code: url(r'^set/(?P<the_city>\w+)/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'),

rawDescription: Django url parameter and reverse URL

description: Django url parameter and reverse URL


rawDescription: Python- how do I use re to match a whole string


code:
def iterate_with(iterable):
    for element in iterable:
        with element:
            yield element

rawDescription: Looping over resource in python

description: Looping over resource in python


code:
f = figure()
ax = f.add_subplot(111)
scatter([3,5,2,6,8],[5,3,2,1,5])
text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)

rawDescription: Putting text in top left corner of matplotlib plot


code:
class Greeting(db.Model):
    author = db.UserProperty()
    author_nickname = db.StringProperty() # denormalization (copy of author.nickname)
    content = db.StringProperty(multiline = True)
    date = db.DateTimeProperty(auto_now_add=True)

rawDescription: Cannot access members of UserProperty in code


rawDescription: select from list B k distinct elements that are not in list A in python?

description: Select from list B k distinct elements that are not in list A in python


code:
import random
[random.sample(s, 1)[0] for _ in range(10)]

rawDescription: How to get an arbitrary element from a frozenset?

description: Get an arbitrary element from a frozenset


code:
test = {1, 2, 3}
list(powerset(test))
list(product(test, test))

rawDescription: Power set and Cartesian Product of a set python


code: dic={'a':[''.join(per) for per in permutations('AGUCN')]}

rawDescription: Look ahead without itertools

description: Look ahead without itertools


code:
D1
D2
D3
D1
D2
D3

rawDescription: Writing files to directories in a round robin pattern


code: subprocess.Popen(['C:\Program Files\Mozilla Firefox\\firefox.exe', '-new-tab'])

rawDescription: How to open external programs in Python

description: Open external programs in Python


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

rawDescription: the most pythonic matrix transposition

description: The most pythonic matrix transposition


rawDescription: Converting Eastern Arabic numbers to Western Arabic numbers


code:
import sys
sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=32, cols=100))

rawDescription: Resize the terminal with Python?

description: Resize the terminal with Python


code:
def create_mapping(filename):
    with open(filename, 'r') as infile:
        data = infile.readlines()
        mapping = {int(k): (i,d) for k,i,d in
                   (x.strip().split('|') for x in data)}
    # Your mapping now looks like
    # { 312: ('cheeseburger', 'Denmark'),
    #   621: ('chesscake', 'USA') }
    return mapping

rawDescription: Replacing data in files with new inputs

description: Replacing data in files with new inputs


code:
VertexNb = cmds.polyEvaluate(Mesh, v=1) - 1
weight = cmds.getAttr('{0}.weightList[0].weights[0:{1}]'.format(deformerNode, VertexNb))

rawDescription: How to change the weights of a deformer from a script in Maya?

description: Change the weights of a deformer from a script in Maya


code:
import pyproj
from shapely.geometry import Point
from shapely.ops import transform
from functools import partial

WGS84 = pyproj.Proj(init='epsg:4326')

def latlonbuffer(lat, lon, radius_m):
    proj4str = '+proj=aeqd +lat_0=%s +lon_0=%s +x_0=0 +y_0=0' % (lat, lon)
    AEQD = pyproj.Proj(proj4str)
    project = partial(pyproj.transform, AEQD, WGS84)
    return transform(project, Point(0, 0).buffer(radius_m))

A = latlonbuffer(48.180759, 11.518950, 19.0)
B = latlonbuffer(47.180759, 10.518950, 10.0)
print(A.intersects(B))  # False

rawDescription: Find the intersection between two geographical data points


code:
res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]

print(res)
[100, 17, 1000]

rawDescription: Python: how to retrieve some values from the elements of a list?


code: lambda x: group(0).replace(',', '')

rawDescription: Replace a string located between

description: Replace a string located between


code:
import numpy as np
from scipy.signal import lfilter, lfiltic
import matplotlib.pyplot as plt

# Parameters
c1 = 0.2
c2 = 1.1
c3 = -0.5
k = 1

# Create an array of signals for the demonstration.
np.random.seed(123)
nsamples = 50
nsignals = 4
s = np.random.randn(nsamples, nsignals)

# Coefficients of the filter's transfer function.
b = c1 * np.array([0.5, 0.5])
a = np.array([1, -c2, -c3])

# Create the initial condition of the filter for each signal
# such that
#     y[:2] == [0, k]
# We need a loop here, because lfiltic is not vectorized.
zi = np.empty((2, nsignals))
for i in range(nsignals):
    zi[:, i] = lfiltic(b, a, [k, 0], x=s[1::-1, i])

# Create the filtered signals.
y = np.empty_like(s)
y[:2, :] = np.array([0, k]).reshape(-1, 1)
y[2:, :], zo = lfilter(b, a, s[2:], zi=zi, axis=0)

# Plot the filtered signals.
plt.plot(y, linewidth=2, alpha=0.6)
ptp = y.ptp()
plt.ylim(y.min() - 0.05*ptp, y.max() + 0.05*ptp)
plt.grid(True)
plt.show()

rawDescription: python recursive vectorization with timeseries

description: Python recursive vectorization with timeseries


code:
print([list(getter(item)) for item in data])
# [['a', '1'], ['b', '2']]

rawDescription: How can I convert list of dictionaries to list of lists?

description: Convert list of dictionaries to list of lists


rawDescription: Convert/Reshape 3D Matrix to a 2D Matrix


rawDescription: Losing timezone-awareness when saving hyerarchical pandas DatetimeIndex to hdf5 in Python


code:
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))

while True:
    rand = random.randint(0, 10)
    message, address = serverSocket.recvfrom(1024)
    message = message.upper()
    if rand >= 4:
        serverSocket.sendto(message, address)

rawDescription: UDP Client/Server Socket in Python

description: UDP Client/Server Socket in Python


code:
from unittest.mock import MagicMock as mm
mm1 = mm()
mm2 = mm()
type(mm1)
type(mm2)
type(mm1) == type(mm2)
id(type(mm1))
id(type(mm2))
type(mm1) is mm1.__class__
mm
id(mm)

rawDescription: Why does type(mock.MagicMock()) == mock.MagicMock returns False?


rawDescription: How to write Default dictionary values to a file with new line?

description: Write Default dictionary values to a file with new line


code:
B[np.in1d(B, bads).reshape(3, 3)] = 0
B

rawDescription: Converting Specified Elements of a NumPy Array by a New Value


code:
s = """1, First Street, City, X13
1, First Street             First Street, City,          X13
1                           1, First Street, City, X13  X13"""

lines = s.split('\n')

splitted_lines = [line.split(',') for line in lines]

rawDescription: Python - Merging two strings that overlap


code:
def chooseletter():
    playerletter = ''

    # use a tuple of letters in condition instead of splitting
    while playerletter not in ('X', 'O'):
        playerletter = input("What letter would you like to be? X or O? \n").upper()

    # move the setting of computerletter outside the loop
    # use the X if Z else Y construction for simplicity
    computerletter = 'O' if playerletter == 'X' else 'X'

    # instead of returning 2 values in a list, return a tuple
    return playerletter, computerletter

rawDescription: Variable won't be assigned to input in Python


code:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

rawDescription: How to iterate through list in Python/Jython (like with HashMaps)?

description: Iterate through list in Python/Jython (like with HashMaps)


rawDescription: Using Python, how would I take in an integer argument?


code:
def handle_connect_event(self):
    self.is_connected = True

rawDescription: Python - Asyncore (client) socket - Can not determaine connection status


code: "stuff and things"

rawDescription: Calling previously defined functions within other functions(Python)


code:
import subprocess
import shlex
proc = subprocess.Popen(shlex.split('fdisk -l'))
proc.communicate()
proc = subprocess.Popen(shlex.split('fdisk -l'))
proc.communicate()

rawDescription: Repeatedly using one subprocess.Popen instance in python


code:
def do_work(filename):

    d = Reader(filename)

    # if you want to use 'asdot+' or 'asdot' for AS numbers,
    # comment out either line below.
    # default is 'asplain'.
    #
    # as_repr(AS_REPR['asdot+'])
    # as_repr(AS_REPR['asdot'])
    for m in d:
        m = m.mrt
        print('---------------------------------------------------')
        if m.err == MRT_ERR_C['MRT Header Error']:
            prerror(m)
            continue
        print_mrt(m)

        if m.err == MRT_ERR_C['MRT Data Error']:
            prerror(m)
            continue
        if m.type == MRT_T['TABLE_DUMP']:
            print_td(m)
        elif m.type == MRT_T['TABLE_DUMP_V2']:
            print_td_v2(m)
        elif ( m.type == MRT_T['BGP4MP']
            or m.type == MRT_T['BGP4MP_ET']):
            print_bgp4mp(m)

rawDescription: Python - How to call the main fuction of a module in another module?


code:
import concurrent.futures
import marshal
from cProfile import Profile
from pstats import Stats
import sys

progname = 'myscript.py'
with concurrent.futures.ProcessPoolExecutor() as executor:
    future = executor.submit(_run, progname)
    stats = Stats()
    stats.stats = marshal.loads(future.result())
    stats.get_top_level_stats()

def _run(progname):
    sys.path.insert(0, os.path.dirname(progname))

    with open(progname, 'rb') as fp:
        code = compile(fp.read(), progname, 'exec')
    globs = {
        '__file__': progname,
        '__name__': '__main__',
        '__package__': None,
    }
    prof = Profile()
    prof.runctx(code, globs, None)
    prof.create_stats()
    return marshal.dumps(prof.stats)

rawDescription: Why is number of function calls different on second time?


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

def main():
    x = np.linspace(0, 6 * np.pi, 100)

    fig1, (ax1, ax2) = plt.subplots(nrows=2)
    plot(x, np.sin(x), ax1)
    plot(x, np.random.random(100), ax2)

    fig2 = plt.figure()
    plot(x, np.cos(x))

    plt.show()

def plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    line, = ax.plot(x, y, 'go')
    ax.set_ylabel('Yabba dabba do!')
    return line

if __name__ == '__main__':
    main()

rawDescription: matplotlib: can I create AxesSubplot objects, then add them to a Figure instance?

description: Matplotlib: can I create AxesSubplot objects, then add them to a Figure instance


code:
eggs: 2
onions: 1
omelette: 11.0
pileofomelettes: 60

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 collections
Credential = collections.namedtuple('Credential', 'username, password', verbose=True)

class Credential(tuple):
    'Credential(username, password)'

    __slots__ = ()

    _fields = ('username', 'password')

    def __new__(_cls, username, password):
        return _tuple.__new__(_cls, (username, password))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Credential object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        return 'Credential(username=%r, password=%r)' % self

    def _asdict(t):
        'Return a new dict which maps field names to their values'
        return {'username': t[0], 'password': t[1]}

    def _replace(_self, **kwds):
        'Return a new Credential object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('username', 'password'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        return tuple(self)

    username = _property(_itemgetter(0))
    password = _property(_itemgetter(1))

rawDescription: Structure accessible by attribute name or index options


code:
_control = None

def is_enabled():
    global _control
    if (_control is None) or _control.is_stale():
        _control = TaskControl.objects.get(pk=1)
        # There's probably a better way to set `retrieved`,
        # maybe with a signal or a `Model` override,
        # but this should work.
        _control.retrieved = datetime.utcnow()
    return _control.some_status

rawDescription: Turn Off Celery Tasks

description: Turn Off Celery Tasks


code: is_critical = (type_code & 0x20) == 0

rawDescription: PNG Chunk type-code Bit #5

description: PNG Chunk type-code Bit #5


rawDescription: NumPy vectorised method for computing covariance with population means (for survey data)