code:
#!/usr/bin/env python3
import sys
import time
from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE

messages = 'This is Console1', 'This is Console2'

# open new consoles
processes = [Popen([sys.executable, "-c", """import sys
for line in sys.stdin: # poor man's `cat`
    sys.stdout.write(line)
    sys.stdout.flush()
"""],
    stdin=PIPE, bufsize=1, universal_newlines=True,
    # assume the parent script is started from a console itself e.g.,
    # this code is _not_ run as a *.pyw file
    creationflags=CREATE_NEW_CONSOLE)
             for _ in range(len(messages))]

# display messages
for proc, msg in zip(processes, messages):
    proc.stdin.write(msg + "\n")
    proc.stdin.flush()

time.sleep(10) # keep the windows open for a while

# close windows
for proc in processes:
    proc.communicate("bye\n")

rawDescription: How can I open two consoles from a single script

description: Open two consoles from a single script


code:
list_of_games = session.query(Game_Table).all()
list_of_games.filter(name=="stuff").all()

rawDescription: SQLAlchemy Query Possible?

description: SQLAlchemy Query Possible


code:
def by_three(n): return False if n % 3 else cube(n)

def cube(n): return n**3

by_three(11)
by_three(12)
by_three(13)

rawDescription: Strange multiple return values in Python


code:
a.flags
a.dtype
a.itemsize
a.shape

rawDescription: Difference between numpy.array shape (R, 1) and (R,)


rawDescription: Escape sequence in python

description: Escape sequence in python


code:
import csv

lol = [[1,2,3],[4,5,6],[7,8,9]]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

rawDescription: Python, transposing a list and writing to a CSV file


code: [(m.group(0)[0], len(m.group(0))) for m in re.finditer(r'((\w)\2*)', s)]

rawDescription: Splitting a string into consecutive counts?


rawDescription: Rounding a number in python but keeping ending zeros


code:
result = []
for item in a:
    if item > 3:
        result.append(item)
    else:
        result.append(3)

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


code:
df.dtypes
merged.dtypes
df.SICcode.unique()
merged.SICcode.head(10).unique()

rawDescription: Pandas: dataframes won't merge

description: Pandas: dataframes won't merge


code:
from __future__ import division

import numpy as np
from scipy.stats.contingency import margins

def residuals(observed, expected):
    return (observed - expected) / np.sqrt(expected)

def stdres(observed, expected):
    n = observed.sum()
    rsum, csum = margins(observed)
    v = csum * rsum * (n - rsum) * (n - csum) / n**3
    return (observed - expected) / np.sqrt(v)

rawDescription: What is the equivalent of R data.chisq$residuals in python?


code:
format(110, '05d')
'Formatted String : {0:05d}'.format(12)

rawDescription: Python format Integer into fixed length strings


code:
for last, i in tag_last(xrange(4)):
    print(last, i)

for last, i in tag_last(xrange(1)):
    print(last, i)

for last, i in tag_last(xrange(0)):
    print(last, i)

rawDescription: How to check if an item is the last one of iteration in python

description: Check if an item is the last one of iteration in python


code:
def addparams():
    global param1
    global param2
    ...

rawDescription: Updating empty variables outside a function


code:
root_hypernyms_of_nouns = Counter(chain(*[ss.root_hypernyms() for ss in wn.all_synsets(pos='n')]))
len(root_hypernyms_of_nouns)
root_hypernyms_of_nouns.items()

rawDescription: NLTK WordNet verb hierarchy

description: NLTK WordNet verb hierarchy


code:
def append_children(parent, iterable):
    last = None
    for i in iterable:
        if hasattr(i, '__iter__'):
            append_children(last, i)
        else:
            parent.children.append(i)
            last = i

def magic(lst):
    result = []
    for i in lst:
        if hasattr(i, '__iter__'):
            append_children(result[-1], i)
        else:
            result.append(i)
    return result

rawDescription: Nesting lists in python

description: Nesting lists in python


code:
M,N,R = A.shape
X,Y,Z = np.ix_(np.arange(M),np.arange(N),np.arange(R))
out = A/(w*((X/Lx) + (Y/Ly) + (Z/Lz)))

rawDescription: Applying function that cares about index to every element of numpy array


code:
utype = UserType.objects.get(...)
utype.profiles.all()

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


code:
# Calling a soup or tag is the same as find_all

[e.get_text() for panda in soup('div', {'class': 'panda'})
              for e in panda('span', {'class': 'cheese'})]

rawDescription: How can I use BeautifulSoup to get deeply nested div values?

description: Use BeautifulSoup to get deeply nested div values


code:
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, DateTime, ForeignKey, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import Session, relationship, aliased

engine = create_engine('sqlite:///', echo=True)
session = Session(bind=engine)
Base = declarative_base(bind=engine)

class Project(Base):
    __tablename__ = 'project'

    id = Column(Integer, primary_key=True)

class Followup(Base):
    __tablename__ = 'followup'

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey(Project.id))
    ts = Column(DateTime, nullable=False)

    project = relationship(Project, backref='followups')

    @hybrid_property
    def previous_count(self):
        # the python property, queries the database and returns a count
        cls = self.__class__
        return session.query(func.count(cls.id)).filter(cls.project == self.project, cls.ts < self.ts).scalar()

    @previous_count.expression
    def previous_count(cls):
        # the sql property, constructs a scalar subquery with an alias
        other = aliased(cls)
        return session.query(func.count(other.id)).filter(other.project_id == cls.project_id, other.ts < cls.ts).as_scalar()

Base.metadata.create_all()

p1 = Project()
p2 = Project()

f1 = Followup(project=p1, ts=datetime(2014, 1, 1))
f2 = Followup(project=p1, ts=datetime(2014, 2, 1))
f3 = Followup(project=p1, ts=datetime(2014, 3, 1))
f4 = Followup(project=p1, ts=datetime(2014, 4, 1))
f5 = Followup(project=p2, ts=datetime(2014, 5, 1))

session.add_all((p1, p2))
session.commit()

print(session.query(Followup.id, Followup.previous_count).all())

rawDescription: Using HybridProperty to count previous sibblings


code:
df = pd.DataFrame(np.random.randn(5,2), columns=['A', 'B'])
df
df.to_clipboard(float_format='{:n}'.format)

rawDescription: Pandas(Python) to_clipboard with comma decimal parameter


code: index = path.get_indices()[0]

rawDescription: Getting the row number of Gtk TreeView

description: Getting the row number of Gtk TreeView


code:
def parse(self, response):
    for link in response.xpath("//a"):
        item = SocialMediaItem()
        item['title'] = link.xpath('text()').extract()
        item['link'] = link.xpath('@href').extract()
        yield item

rawDescription: How to loop over a response element in Scrapy?

description: Loop over a response element in Scrapy


code: dict((k, int(v) if v.isdigit() else v) for k, v in json.loads(inputstring))

rawDescription: Python string to dict

description: Python string to dict


code:
import pytz
import datetime as DT

text = '07/20-10:38:04.360700'
tz = pytz.timezone('US/Eastern')
date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
# interpret the date as coming from US/Eastern
date_tz = tz.localize(date)

epoch = DT.datetime(1970,1,1, tzinfo=pytz.utc)
timestamp = (date_tz - epoch).total_seconds()
print(repr(timestamp))
# 1405867084.3607

rawDescription: DateTime Conversion to Epoch Time

description: DateTime Conversion to Epoch Time


code: s.set("timeout", 60000)

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

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


code:
for item in items:
    def item_command(name):
        def new_command():
            print(name)
        return new_command

    map[item] = item_command(item)

rawDescription: Dynamically creating a menu in Tkinter. (lambda expressions?)


code: op, value = add, 0

rawDescription: How to go back to a specific line

description: Go back to a specific line


code: printlist.append(text['data'] if 'data' in text else '')

rawDescription: How to combine try/except in python into a pretty one liner?

description: Combine try/except in python into a pretty one liner


code:
@app.after_request
def after_request_callback(response):
    # Do something with the response (invalidate cache, alter response object, etc)
    return response

rawDescription: How to execute a block of code only once in flask?

description: Execute a block of code only once in flask


code: '{0}@{1}'.format(user, host)

rawDescription: Python .join or string concatenation

description: Python .join or string concatenation


code: df["decision"] = decision.astype(int)

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


rawDescription: Using regular expressions to manipulate strings


rawDescription: Python Type Conversion

description: Python Type Conversion


rawDescription: Python 2.7: "import time" Where is python importing this time module from?


rawDescription: Pandas - Get first row value of a given column


rawDescription: How would I run numbers through a list in python?


code: self.opener.urlopen(url, data)

rawDescription: How to store cookie jar to be used between functions inside class?

description: Store cookie jar to be used between functions inside class


code:
import httplib
class Z(object): pass

class Y(Z, httplib.HTTPConnection): pass

Y.mro()
class X(Z, httplib.HTTPConnection, object): pass

X.mro()

rawDescription: Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection


code:
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos, node_color=node_colors)
nx.draw_networkx_edges(G, pos=pos)

rawDescription: NetworkX color the nodes in path

description: NetworkX color the nodes in path


code:
[el for lst in [set(L) for L in list4] for el in lst].count('apples')
[el for lst in [set(L) for L in list4] for el in lst].count('oranges')

rawDescription: Counting the number of lists that contain an element in Python


code:
soup = BeautifulSoup(
    urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html')
    .read()
    .replace('<![CDATA[', '').replace('<!]]>', ''))

rawDescription: I cannot scrape anything with BeautifulSoup


code:
return HttpResponse(json.dumps(dataset, ensure_ascii="False"), content_type="application/json; encoding=utf-8")
#                                                    ^^^^^^^ to False

rawDescription: Output utf-8 characters in django as json


code: print("Randy's phone # is {Randy[phone]}".format(**people))

rawDescription: Accessing nested dictionary items in Python


code:
from collections import Counter

data = '''\
ashwin programmer india
amith programmer india'''

c = Counter()
for line in data.splitlines():
    c.update(line.split())
print(c)

rawDescription: python - find the occurrence of the word in a file

description: Python - find the occurrence of the word in a file


code: df.iloc[0, -1]    #row 0, last cell in row

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


code:
def initialized_bytearray_test_opt():
    tStart = time.clock()
    L = len(MSG)
    ba = bytearray(L*COUNT)
    ofs = 0
    for i in range(COUNT):
        ba[ofs : ofs+L] = MSG
        ofs += L
    print('initialized array opt time:', time.clock() - tStart)

rawDescription: Python bytearray verses list of bytes

description: Python bytearray verses list of bytes


code:
for row1, row2, row3 in zip(u[0::,:],u[1::,:],u[2::,:]):
    print(row1, row2, row3)
    print("\n")
    # or write them to one file, or files.

rawDescription: Saving numpy arrays as txt file [Beginner]


code:
import random
parameters = [[1,3,2], [4,5,6]]
random.triangular(*parameters[0])

rawDescription: Entering Parameters in Python

description: Entering Parameters in Python


code:
from ctypes import create_string_buffer, c_char_p, c_int, CDLL

libtest = CDLL("./libtest.so")

_putAll = libtest.putAll
_putAll.restype = None
_putAll.argtypes = [c_int, c_char_p]

def putAll(values):
    """Expects a bytes object, bytearray, or a list of ints."""
    char_buffer = create_string_buffer(bytes(values))
    _putAll(len(char_buffer), char_buffer)

getAll = libtest.getAll
getAll.restype = c_char_p
getAll.argtypes = None

rawDescription: How to pass Python list to C function using Cython

description: Pass Python list to C function using Cython


rawDescription: Are there standard rules and practices for Date serialization between two languages or frameworks?


code:
import statsmodels.api as sm

dta = sm.datasets.co2.load_pandas().data
# deal with missing values. see issue
dta.co2.interpolate(inplace=True)

res = sm.tsa.seasonal_decompose(dta.co2)
resplot = res.plot()

rawDescription: Seasonal Decomposition of Time Series by Loess with Python


code:
time.tzset()
sec = -time.timezone

rawDescription: Time issues in Python

description: Time issues in Python


code:
import pandas as pd
import io

content = '''\
1    2    3    4   mean
NaN  NaN  NaN  NaN      NaN
5.9  5.4  2.4  3.2    4.225
0.6  0.7  0.7  0.7    0.675
2.5  1.6  1.5  1.2    1.700
0.4  0.4  0.4  0.4    0.400'''

df = pd.read_table(io.BytesIO(content), sep='\s+')
df.to_csv('/tmp/test.csv', float_format='%g', index=False)

rawDescription: Wrong decimal calculations with pandas

description: Wrong decimal calculations with pandas


rawDescription: How To Use NDB Query Without Knowing Class Name


code: Y = simulate(ymodel,500,'X',X);

rawDescription: Create a multivariate AR model in MATLAB


code: app.route(path='/', method='GET', callback=func, apply=[auth, mako_view('index.html')])

rawDescription: Set Mako as the default template renderer in Bottle.py


code:
import struct
rand_int = struct.unpack('I', rnd_string)[0]

rawDescription: Best seed for parallel process

description: Best seed for parallel process


code:
def foo ():
    for i in range (10):
        i = i * i

from timeit import Timer
max_iter = 10000
t = Timer ("foo()", "from __main__ import foo")
print ("foo(%i): %f seconds" %(max_iter, t.timeit(max_iter)))

rawDescription: python 3.3 ,2.7 and 2.6 - benchmark inconsistent results. how fix that?

description: Python 3.3 ,2.7 and 2.6 - benchmark inconsistent results. how fix that


code: rmin, rmax

rawDescription: working with tiff files in python

description: Working with tiff files in python


code: contents = read_sheet.cell(row_index, col_index).value

rawDescription: How to collapse rows in excel using python?

description: Collapse rows in excel using python


code:
import numpy as np

ncol = 10  # 10 in your case
nrow = 500  # 500 in your case
# just creating some test data:
x = np.arange(ncol*nrow).reshape(nrow,ncol)
y = (ncol * np.random.random_sample((nrow, 1))).astype(int)

print(x)
print(y)
print(x[np.arange(nrow),y.T].T)

rawDescription: Multi-dimensional array indexing using a single dimensional array in Python


code:
def findNeighbors(grid, x, y):
    if 0 < x < len(grid) - 1:
        xi = (0, -1, 1)   # this isn't first or last row, so we can look above and below
    elif x > 0:
        xi = (0, -1)      # this is the last row, so we can only look above
    else:
        xi = (0, 1)       # this is the first row, so we can only look below
    # the following line accomplishes the same thing as the above code but for columns
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    for a in xi:
        for b in yi:
            if a == b == 0:  # this value is skipped using islice in the original code
                continue
            yield grid[x + a][y + b]

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

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


rawDescription: How to use the same widget twice in pygtk?

description: Use the same widget twice in pygtk


code:
SNPs = {}
for r in reader:
    for n in CHR:
        if r[1]==n:
            SNPs.setdefault(n, []).append(r[2])        #append values into empty list SNP
for n in CHR:
    SNP = SNPs[n]
    # I didn't change anything below here..
    SNP = [try_int(x) for x in SNP] #convert to integers
    max_val=max(SNP)                #find the maximum value
    chr_max.append((n, max_val))    #append this maximum to a new list

rawDescription: How do I clear this list at the end of every loop?

description: Clear this list at the end of every loop


code:
def get_number_count(lucky_number):
    """ Returns the number of times the lucky_number
        appears in the database """

    c.execute('SELECT COUNT(*) FROM myTable WHERE number_column = %s', (lucky_number,))
    result = c.fetchone()
    return result[0]

def get_input_number():
    """ Get the number to be searched in the database """
    lookup_num = raw_input('Lucky number: ')
    return get_number_count(lookup_num)

rawDescription: find all ocurrences inside a list

description: Find all ocurrences inside a list


code: idx = coords / scaling[(slice(None),) + (None,)*(coords.ndim-1)]

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


code:
from config import configs
import os

evn = os.environ.get('MY_FLASK_APP_ENV', 'default')

create_app(config=configs[evn])

rawDescription: How to serve different config settings in flask app to uwsgi using create_app?

description: Serve different config settings in flask app to uwsgi using create_app


code:
import csv
import urllib.request

downloaded_data  = urllib.request.urlopen('http://...')
csv_data = csv.reader(downloaded_data)

for row in csv_data:
    print(row)

rawDescription: get csv data from a website

description: Get csv data from a website


code:
columns = [['key_header'] + sorted(inputlist[0].keys())]  # first column

for i, entry in enumerate(inputlist):
    columns.append([i] + [entry[k] for k in columns[0][1:]])

with open(outputfilename, 'wb') as output:
    writer = csv.writer(output)
    writer.writerows(zip(*columns))

rawDescription: Writing a CSV horizontally

description: Writing a CSV horizontally


code:
for factors in itertools.product(range(1,3), repeat=10):
    product = reduce(lambda x, y: x*y, factors)

rawDescription: Simplify Python iterations

description: Simplify Python iterations


code:
import numpy as np

a = np.array([2, 4])
b = np.array([3, 5])
c = np.outer(a, b)

print(c)
# [[ 6 10]
#  [12 20]]

rawDescription: Vector-vector multiplication to create a matrix


code: data = form.cleaned_data['data']

rawDescription: Django form based view GET response

description: Django form based view GET response


code:
def get_parsed_attribute(self, result, field_name):
    try:
        return reduce(self.smart_getattr, field_name.split("__"), result)
    except (AttributeError, IndexError):
        return None  # We can assume that either the value is missing, or
                     # that key doesn't exist.  Either way, there's no harm.

@staticmethod
def smart_getattr(obj, key):
    if isinstance(obj, list):
        return list.__getitem__(obj, int(key))
    if isinstance(obj, dict):
        return dict.__getitem__(obj, key)
    return getattr(obj, key)

rawDescription: How to use a string to (safely) access deep Python properties?

description: Use a string to (safely) access deep Python properties


code:
class User(db.Model):
    name = db.StringProperty()
    softwares = db.ListProperty(db.Key)

class Software(db.Model):
    name = db.StringProperty()
    description = db.TextProperty()

    @property
    def users(self):
        return User.all().filter('softwares', self.key())

rawDescription: Querying on multiple tables using google apps engine (Python)


code:
isinstance(pp,Point)
isinstance(pp,P)

rawDescription: Use of class typenames in python

description: Use of class typenames in python


rawDescription: Perform calculation on one list depending on value of second list


code:
from collections import defaultdict
output = defaultdict(lambda: defaultdict(int))
for d in (dict1, dict2):
    for key, values_dict in d.items():
        for date, integer in values_dict.items():
            output[key][date] += integer

rawDescription: Merge two dictionaries with nested dictionaries into new one, summing same keys and keeping unaltered ones in Python


code:
import re
foo, bar, _irrelevant = re.split(r"\s{2,}",  line)

rawDescription: String parsing in Python, regular expression?


code:
df = read_csv(StringIO(data),sep='\s+',header=None,parse_dates=[[0,1],[2,3],[4,5],[6,7]])
df.columns = ['date1','date2','date3','date4']
df

rawDescription: getting time delta from pandas data frame

description: Getting time delta from pandas data frame


code:
def delete_item(listboxInventory, event = None):
    answer = messagebox.askquestion("Delete", "Are You Sure?", icon='warning')
    if answer == 'yes':
        listboxInventory.delete(listboxInventory.curselection())

rawDescription: Python 3.4.2, Using listbox for an inventory


code:
from Bio import Seq
from itertools import product

def extend_ambiguous_dna(seq):
   """return list of all possible sequences given an ambiguous DNA input"""
   d = Seq.IUPAC.IUPACData.ambiguous_dna_values
   return [ list(map("".join, product(*map(d.get, seq)))) ]

rawDescription: how to extend ambiguous dna sequence

description: Extend ambiguous dna sequence


code: a + b + c

rawDescription: Join many lists using list comprehension


code:
with contextlib.closing(sqlite3.connect('test.db.temp')) as db:
    db.executescript('CREATE TABLE foo (bar);')
os.rename('test.db.temp', 'test.db')

rawDescription: WindowsError moving sqlite3 database after closing


code:
varInt = 12

print(
    "Integer : " +
    "{:07.3f}".format(varInt)
)

rawDescription: Python integer formatting

description: Python integer formatting


code:
class SecondModelForm(FirstModelForm):
    class Meta:
        model = TheModel
        fields = ('title', 'description')

rawDescription: How can I update only certain fields in a Django model form?

description: Update only certain fields in a Django model form


code:
def construct_task_graph(deps, tasks):
    required = set(tasks)
    strong_subgraph = extract_strong_subgraph(deps)
    for task in tasks:
        ancestors = nx.ancestors(strong_subgraph, task)
        required.update(ancestors)

    return nx.subgraph(deps, required)

def extract_strong_subgraph(deps):
    strong_deps = nx.DiGraph()
    strong_deps.add_nodes_from(deps)

    strong_edges = (e for e in deps.edges_iter(data=True) if e[2]["is_strong"])
    strong_deps.add_edges_from(strong_edges)

    return strong_deps

rawDescription: How can I implement "weak" edges with NetworkX?

description: Implement "weak" edges with NetworkX


code: scatter(cost, rating, c=brandcolors)

rawDescription: How do I assign different dots different colors in a scatter plot made with MatPlotLib?

description: Assign different dots different colors in a scatter plot made with MatPlotLib


code:
...

conn = engine.connect()
@sa.event.listens_for(engine, "begin")
def do_begin(conn):
    conn.connection.create_function('regexp', 2, re_fn)

db = orm.scoped_session(orm.sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

...

rawDescription: How to use regexp function in sqlite with sqlalchemy?

description: Use regexp function in sqlite with sqlalchemy


code:
from distutils.core import setup
import py2exe

setup(console = ['main.py'])

rawDescription: How to compile multiple scripts with py2exe?

description: Compile multiple scripts with py2exe


code:
class Person(object):

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

rawDescription: Best way to make 'n' objects with each with unique data contents?

description: Make 'n' objects with each with unique data contents


code:
for label in network_labels.unique():
    g.ax_col_dendrogram.bar(0, 0, color=network_lut[label],
                            label=label, linewidth=0)
g.ax_col_dendrogram.legend(loc="center", ncol=6)

rawDescription: How to express classes on the axis of a heatmap in Seaborn

description: Express classes on the axis of a heatmap in Seaborn


rawDescription: Resizing small images in Python (numpy) to a multiple of the original size, accurately


code: from . import json

rawDescription: Fully Qualified name of a python module

description: Fully Qualified name of a python module


code:
...
line = yield from loop.run_in_executor(io_pool_exc, f.readline)
...

rawDescription: Read file line by line with asyncio

description: Read file line by line with asyncio


code:
class UserThings(Document):
    # you can look this document up by username
    username = StringField()

    # you can store whatever you want here
    things = DictField()

dcrosta_things = UserThings(username='dcrosta')
dcrosta_things.things['foo'] = 'bar'
dcrosta_things.things['bad'] = 'quack'
dcrosta_things.save()

rawDescription: using key as value in Mongoengine

description: Using key as value in Mongoengine


code:
import app.models

get_object_or_404(getattr(app.model, object_type), uuid=uuid_from_request)

rawDescription: Django and python - use variable value as model's name


code:
def mod_inv (a, b):
    return pow(a, b - 2, b)

mod_val=10**9+7

hi = 5000
for lo in range(0, hi-1):

    # Code 1
    num_prod=1
    den_prod=1
    for each in xrange(1,lo+1):
        den_prod = (den_prod*each) % mod_val
        num_prod = (num_prod*(hi+each)) % mod_val

    output = (num_prod * mod_inv(den_prod, mod_val)) % mod_val
    # print output

rawDescription: Placing of modulo operation in code

description: Placing of modulo operation in code


code:
list(pseudosplit(lambda x: x is None, ()))
list(pseudosplit(lambda x: x is None, [1,2,3]))
list(pseudosplit(lambda x: x is None, [None]*3))
list(pseudosplit(lambda x: x is None, [3, 1, 4, 1, 5, 9, None, 2, 6, 5, 3, 5, None, 8, 9, 7, 9, 3, None]))

rawDescription: Analog of str.split for iterables?

description: Analog of str.split for iterables


code:
from operator import itemgetter

G = [(1, 2, 3), ('a', 'b', 'c'), ('you', 'and', 'me')]

def f1():
   return tuple(x[0] for x in G)

def f2():
   return tuple(map(itemgetter(0), G))

def f3():
    return tuple(x for x, y, z in G)

def f4():
    return tuple(list(zip(*G))[0])

def f5():
    t0,*the_rest=zip(*G)
    return t0

def f6():
    t0,t1,t2=zip(*G)
    return t0

cmpthese.cmpthese([f1,f2,f3,f4,f5,f6],c=100000)

rawDescription: Best way to get the nth element of each tuple from a list of tuples in Python

description: Get the nth element of each tuple from a list of tuples in Python


code: masterSet = set().union(*iterable)

rawDescription: Quick way to extend a set if we know elements are unique


rawDescription: Extracting Info From Webpage using urllib2


code:
import fileinput
import sys

def keep_three(fle):
    name = input("Please enter your name")
    with open(fle, 'r+') as f:
        indexes = [ind for ind, line in enumerate(f) if line.strip() == name]
        if len(indexes) < 3:
            f.write("{}\n".format(name))
            return
        elif len(indexes) == 3:
            return
        remove = set(indexes[:len(indexes)-3])
        for ind, line in enumerate(fileinput.input(fle,inplace=True)):
            if ind not in remove:
                sys.stdout.write(line)

rawDescription: How to delete a line from a file if it contains certain data

description: Delete a line from a file if it contains certain data


code:
for a, b in pairwise(gen):
    func(b[1], a[1])
    func(b[1], a[2])

rawDescription: Refactor the first iteration for generator in python


code:
import lxml.etree as le

with open('doc.xml','r') as f:
    doc=le.parse(f)
    for elem in doc.xpath('//*[attribute::lang]'):
        if elem.attrib['lang']=='en':
            elem.attrib.pop('lang')
        else:
            parent=elem.getparent()
            parent.remove(elem)
    print(le.tostring(doc))

rawDescription: How to remove elements from XML using Python

description: Remove elements from XML using Python


code:
t= 1
for hehe in range (t):
    n, e= 10, 6

    g= Graph()
    # ...
    # ...
    s= 3
    print('g.verts[s-1] is ', g.verts[s-1].getname())
    print('g.verts[s-1] neigh ', g.verts[s-1].getneigh()[0].getname())
    print('g.verts[s-1] neigh[0] -> neigh', g.verts[s-1].getneigh()[0].getneigh())
    print('------------')

    #s is the start node of the graph
    c=bfs(g,s)
    # ...

rawDescription: Object details don't get passed into another object pointer [Python 3]


code: np.tensordot(X,tensor, axes=([1],[0]))

rawDescription: Numpy tensor: Tensordot over frontal slices of tensor


code:
xml = """<main>
<object1 attr="name">content</object1>
<object1 attr="foo">contenbar</object1>
<test>me</test>
</main>"""
from lxml import objectify
main = objectify.fromstring(xml)
main.object1[0]
main.object1[1]
main.object1[0].get("attr")
main.test

rawDescription: How to convert XML to objects?

description: Convert XML to objects


code:
def unify2(raw_data):
    dtype = np.dtype((np.void, (raw_data.shape[1] * raw_data.dtype.itemsize)))
    uniq, inv = np.unique(raw_data.view(dtype), return_inverse=True)
    uniq = uniq.view(raw_data.dtype).reshape(-1, raw_data.shape[1])
    return uniq, inv

rawDescription: Python/Numpy: Build 2D array without adding duplicate rows (for triangular mesh)


code:
d = { 'vars': "variables", 'example': "example" }
s = "This is an {example} with {vars}"
s.format(**d)

rawDescription: Python multiline string - $ for variables


code:
# Create a market open flag.
df['market_open'] = False
mask = (df.Datetime.dt.time > dt.time(15)) | (df.Datetime.dt.time < dt.time(13, 15))
df.loc[mask, 'market_open'] = True

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


code:
id = ind_x*3 + ind_y
np.bincount(id,values,minlength=9).reshape(3,3)
np.bincount(id,minlength=9).reshape(3,3)

rawDescription: Grid distribution with numpy

description: Grid distribution with numpy


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

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


code: isinstance(True,int)

rawDescription: Counting positive elements in a list with Python list comprehensions


code:
class User(db.Model):
    name = db.Column()

class UserSerializer(Serializer):
    class Meta:
        fields = ('id', 'name')

class FooSerializer(Serializer):
    author_name = fields.Nested('UserSerializer')

    class Meta:
        fields = ('id', 'author_name')

rawDescription: Sqlalchemy - Foreign Value

description: Sqlalchemy - Foreign Value


code:
import glob
images = glob.glob("image_[0-9]*")

rawDescription: How to list an image sequence in an efficient way? Numercial sequence comparison in Python

description: List an image sequence in an efficient way? Numercial sequence comparison in Python


code: from myproj import settings

rawDescription: Using the correct settings constant in Django view


code:
def __recvall(self, bytes):
    """__recvall(bytes) -> data
    Receive EXACTLY the number of bytes requested from the socket.
    Blocks until the required number of bytes have been received.
    """
    data = ""
    while len(data) < bytes:
       data = data + self.recv(bytes-len(data))
    return data

rawDescription: How to set timeout for urllib2.OpenDirector open() method

description: Set timeout for urllib2.OpenDirector open() method


rawDescription: What is the format of the .tar.gz file for setting up firefox preference from selenium python?


code:
from bs4 import BeautifulSoup
data = """
<parent>
   <child>
        text1
        <subchild>text2 </subchild>
        text3
   </child>
</parent>
"""
soup = BeautifulSoup(data, "xml")
print(soup.child.get_text())

rawDescription: python xml minidom get the full content of childnode that contains both child and text

description: Python xml minidom get the full content of childnode that contains both child and text


code: np.append(n, np.zeros(20) + np.nan)

rawDescription: Add "nan" to numpy array 20 times without loop


code:
tags_and_filters.py
import copy

from django import template

register = template.Library()

@register.filter(name='remove_filter')
def remove_filter(category, slugs):
    copied_slugs = copy.copy(slugs)
    slug = category.slug
    if slug in copied_slugs:
        copied_slugs.remove(slug)
    return '/'.join(copied_slugs)

rawDescription: get_full_path in django model method

description: Get_full_path in django model method


code:
filter(lambda x: x[1] == "Plot", l)
filter(lambda x: x[1] == "unPlot", l)

rawDescription: How to separate a Python list into two lists, according to some aspect of the elements

description: Separate a Python list into two lists, according to some aspect of the elements


code:
myArray = ['file' + str(i) for i in range(1,101)]
myArray

rawDescription: Array of strings using a range

description: Array of strings using a range


code:
blacklisted = 'foo.com'
email = 'x@foo.com'
email.endswith('foo.com')
email = 'x@subdomain.foo.com'
email.endswith('foo.com')

rawDescription: Best way to filter out emails and domains in python

description: Filter out emails and domains in python


code:
from kivy.app import App
from kivy.uix.button import Button

class MyButton(Button):
    pass

class MyApp(App):
    def dostuff(self, *args):
        print(args)

    def build(self):
        return MyButton()

MyApp().run()

rawDescription: Can someone tell me where I'm going wrong with this structure?


code:
outcome_cat = pd.Categorical(
    first_df['outcome'],
    categories=['L', 'W', 'D'], ordered=False
)

rawDescription: setting levels apriori when using factorize in Pandas to cover missing cases

description: Setting levels apriori when using factorize in Pandas to cover missing cases


code: json.dumps(a_list,sort_keys=True, indent=2, cls =JSONDateTimeEncoder)

rawDescription: Consolidating row data from DB into a list of dicts


code:
import os
import json
import requests
from flask import Flask

app = Flask(__name__)

app.config.update(
    DEBUG=True,
)

@app.route('/')
def welcome():
    return 'Welcome to flask and Cloudant on Bluemix.'

@app.route('/createdb/<db>')
def create_db(db):
    try:
        vcap = json.loads(os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB']

        cl_username = vcap[0]['credentials']['username']
        cl_password = vcap[0]['credentials']['password']

        url         = vcap[0]['credentials']['url']
        auth        = ( cl_username, cl_password )

    except:
        return 'A Cloudant service is not bound to the application.  Please bind a Cloudant service and try again.'

    requests.put( url + '/' + db, auth=auth )
    return 'Database %s created.' % db

port = os.getenv('VCAP_APP_PORT', '5000')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=int(port))

rawDescription: How can I connect to Cloudant from a Flask App running in Bluemix?

description: Connect to Cloudant from a Flask App running in Bluemix


code: odeint(dX_dt, [1,2], np.linspace(0, 1, 5))

rawDescription: SymPy/SciPy: solving a system of ordinary differential equations with different variables


code:
def compare(list_a,list_b):
    for a in list_a:
        try:
            b_index=list_b.index(a)
        except ValueError:
            return False
        return compare(list_a[1:],b[b_index:])

rawDescription: Comparing 2 txt files in Python

description: Comparing 2 txt files in Python


code:
header = soup.find("b", text="Payable")
table = header.find_parent("table")

rawDescription: Python+BeautifulSoup: scraping a particular table from a webpage


rawDescription: How to subtract a day from datetime format in python?

description: Subtract a day from datetime format in python


code: newList = [ str(t) for t in mylist ]

rawDescription: django , list of models to list of string

description: Django , list of models to list of string


code:
import itertools
it = itertools.chain(range(15, 30, 3), [0])

rawDescription: Extend Python list "inline"

description: Extend Python list "inline"


code:
ev = np.array(ev)
idx = np.searchsorted(time, t1, side='right')-1
ev[idx]

rawDescription: Resampling an array using predefined indices in Python


code:
c = list(set(b) - set(a))
# c is now a list of everything in b that is not in a

rawDescription: Compare with each other, items inside two lists, in a for loop?


code:
'''\

        some indentation here

lorum ipsum

'''.strip('\n')

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

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


code:
@register.filter
def difference(value, arg):
    try:
        result_num = (float(arg) - float(value)) / (float(arg) * 0.01)
        if result_num > 0:
            result = '%s%%' % result_num
        elif result_num < 0:
            result = '%s%%' % result_num
    except (TypeError, ZeroDivisionError):
        return None
    return result

rawDescription: Calculate two values and calculate difference in percentage in Django


code:
if x > self.location[0] and not self.location[0]>=x:
    ratio = distance_x/distance_y
    speed_x = ratio * speed
    self.speed_x=speed_x
    prints.append(block.speed_x) #temp print

elif x < self.location[0] and not self.location[0]<=x:
    print('X')
    ratio = distance_x/distance_y
    speed_x = ratio * speed
    self.speed_x=speed_x*-1
    prints.append(block.speed_x) #temp print

else: self.speed_x=0

if y > self.location[1] and not self.location[1]>=y:
    ratio = distance_y/distance_x
    speed_y = ratio * speed
    self.speed_y=speed_y

elif y < self.location[1] and not self.location[1]<=y:
    ratio = distance_y/distance_x
    speed_y = ratio * speed
    self.speed_y=speed_y *-1

else: self.speed_y=0

rawDescription: how does this variable get set to 0?

description: How does this variable get set to 0


code:
# Python 2
from collections import Counter

with open("corpus.txt") as inf:
    wordcount = Counter(line.decode("latin_1").rstrip() for line in inf)

with open("lexic.txt", "w") as outf:
    outf.write('Palabra\tTag\tApariciones\n'.encode("utf-8"))
    for word,count in wordcount.iteritems():
        outf.write("{}\t{}\n".format(word, count).encode("utf-8"))

rawDescription: Bad output format in .txt file

description: Bad output format in .txt file


code:
blues = plt.get_cmap('Blues')  # this returns a colormap
color = blues(1 - float(i)/(len(raw)-1)) # blues(x) returns a color for each x between 0.0 and 1.0

rawDescription: how to make colors in line graph fade in matplotlib and python

description: Make colors in line graph fade in matplotlib and python


code:
b
Out[65]: array([False, False,  True,  True, False, False, False, False], dtype=bool)

c
Out[64]: array([False, False, False, False,  True, False,  True, False], dtype=bool)

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


rawDescription: Python - Write list values in xlwt

description: Python - Write list values in xlwt


code:
from math import sqrt

def stat(lst):
    """Calculate mean and std deviation from the input list."""
    n = float(len(lst))
    mean = sum(lst) / n
    stdev = sqrt((sum(x*x for x in lst) / n) - (mean * mean))
    return mean, stdev

def parse(lst, n):
    cluster = []
    for i in lst:
        if len(cluster) <= 1:    # the first two values are going directly in
            cluster.append(i)
            continue

        mean,stdev = stat(cluster)
        if abs(mean - i) > n * stdev:    # check the "distance"
            yield cluster
            cluster[:] = []    # reset cluster to the empty list

        cluster.append(i)
    yield cluster           # yield the last cluster

rawDescription: How would you group/cluster these three areas in arrays in python?


code:
def functioncaller(*args, **kwargs):
    return lambda fun:fun(*args, **kwargs)

rawDescription: Apply multiple functions to the same argument in functional Python


rawDescription: PyQt4 + matplotlib in a QScrollWidget

description: PyQt4 + matplotlib in a QScrollWidget


code:
template_response = super(ExtendedUserAdmin, self).render_change_form(
    *args, **kwargs)

rawDescription: How to wrap long super() call to be compliant with PEP-8?

description: Wrap long super() call to be compliant with PEP-8


code:
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

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

description: Split a list into evenly sized chunks in Python


code:
line = line.strip()
columns = line.split()

rawDescription: read files with empty entries for certain columns

description: Read files with empty entries for certain columns


code: (t.hour * 3600) + (t.minute * 60) + t.second + (t.microsecond / 1000000.0)

rawDescription: How do I convert a timestamp to seconds-since-midnight?

description: Convert a timestamp to seconds-since-midnight


code:
def find_sequences(sequences, events):
    i = 0
    events_len = len(events)
    sequences_len = len(sequences)
    while i < sequences_len:
            if sequences[i:i+events_len] == events:
                yield True
            i = i + 1

list(find_sequences(lst, events))
sum(find_sequences(['AB', 'A', 'BA', 'A', 'BA'], ['A', 'BA']))

rawDescription: How to find defined sequence in the list?

description: Find defined sequence in the list


code:
class MyHandler(tornado.web.RequestHandler):

    @asynchronous
    @gen.engine
    def get(self):
        response = yield gen.Task(self.dosomething, 'argument')

rawDescription: Tornado async call to a function

description: Tornado async call to a function


code:
import pandas as pd

df = pd.DataFrame(dict(a=[1,1,2,2,2],
                       b=['car', 'train', 'boot', 'computer', 'lipstick']))
# Using a loop
dt = {}
for g, d in df.groupby('a'):
    dt[g] = d['b'].values

# Using dictionary comprehension
dt2 = {g: d['b'].values for g, d in df.groupby('a')}

rawDescription: long-format pandas dataframe to dictionary

description: Long-format pandas dataframe to dictionary


code:
def download_from_file(filename):
    if os.path.exists(filename):
        links = [line.strip() for line in open(filename)]

        for link in links:
            p = Process(target=standard_download, args=(link,))
            p.start()
            yield p

processes = list(download_from_file(filename))
# later, when we need to wait until we're done with all the downloads
for process in processes:
    process.join()

rawDescription: Running two methods (with arguments) simultaneously?


code:
import re

pattern = re.compile(r'\b(?:' + '|'.join(re.escape(s) for s in seed) + r')\b')
pattern.findall(line)

rawDescription: Substring search for multiword strings - Python


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

description: Set up and solve simultaneous equations in python


code: from IPython.zmq.blockingkernelmanager import BlockingKernelManager

rawDescription: Sending data from a web app to an ipython notebook


code:
if do == "n":
    print(1)
else:
    print("2")
return

rawDescription: Python: Do I have to use else statements (unless mandated by code)?


code: valmap['b']

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

description: Access a list containing specific item in a dictionary


code:
parts = [int(s) for s in '198.124.252.130'.split('.')]
parts2 = [int(s) for s in '198.124.252.101'.split('.')]
from operator import sub
diff = sum(d * 10**(3-pos) for pos,d in enumerate(map(sub, parts, parts2)))
diff

rawDescription: How does the python difflib.get_close_matches() function work?


code:
bookmark_par_parent = bookmark_par.getparent()
index = bookmark_par_parent.index(bookmark_par) + 1
for child in tmp_doc_body:
    bookmark_par_parent.insert(index, child)
    index = index + 1
bookmark_par_parent.remove(bookmark_par)

rawDescription: python-docx insertion point

description: Python-docx insertion point


code:
...
newTime = np.linspace(3,25,accuracy)
...

rawDescription: Python scipy Curve fit for quadratic function stopping early


code:
#!/usr/bin/python3

from numpy import arange

import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap

# ======
## data:

N = 10000
data = arange(N +1)

# =================
## custom colormap:

# red-green colormap:
cdict = {'red':   [(0.0, 1.0, 1.0),  # red decreases
                   (1.0, 0.0, 0.0)],

         'green': [(0.0, 0.0, 0.0),  # green increases
                   (1.0, 1.0, 1.0)],

         'blue':  [(0.0, 0.0, 0.0),  # no blue at all
                   (1.0, 0.0, 0.0)] }

red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)

# ======
## plot:

colors = cm.get_cmap(red_green_cm, N)

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

# each line is of its own color:
for i, x in enumerate(data):
    ax.plot(data, data*x, color=colors(i))

# make space for colorbar:
fig.tight_layout(rect=[0, 0, 0.85, 1])

# adding colorbar:
ax_cb = fig.add_axes([0.85, 0.10, 0.05, 0.8])
norm = mpl.colors.Normalize(vmin=data[0], vmax=data[-1])
cb = mpl.colorbar.ColorbarBase(ax_cb, cmap=red_green_cm, norm=norm, orientation='vertical')

fig.savefig("red-green-cm.png")

rawDescription: Mapping range of integer values to colors in python


code:
from itertools import combinations, product

def pairs(*lists):
    for t in combinations(lists, 2):
        for pair in product(*t):
            yield pair

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8]

for pair in pairs(a, b, c):
    print(pair)

rawDescription: Python getting unique pairs from multiple lists of different lengths


rawDescription: Why does the order of dimensions change with boolean indexing?


code:
import Tkinter

mycolor = '#%02x%02x%02x' % (64, 204, 208)  # set your favourite rgb color
mycolor2 = '#40E0D0'  # or use hex if you prefer
root = Tkinter.Tk()
root.configure(bg=mycolor)
Tkinter.Button(root, text="Press me!", bg=mycolor, fg='black',
               activebackground='black', activeforeground=mycolor2).pack()
root.mainloop()

rawDescription: Default window colour Tkinter and hex colour codes


code:
proc = psutil.Process(process.pid)
procs = proc.children(recursive=True)
procs.append(proc)

for proc in procs:
    proc.terminate()

gone, alive = psutil.wait_procs(procs, timeout=1)
for p in alive:
    p.kill()

rawDescription: Kill a chain of sub processes on KeyboardInterrupt


rawDescription: Transform list of instances into list of instance attributes


rawDescription: Converting list of lists of lists into dictionary of dictionaries (Python)


rawDescription: How to sort two-dimensional array in python

description: Sort two-dimensional array in python


rawDescription: WTForms-How to prepopulate a textarea field?


code:
func.min()
func.max()
func.avg()

rawDescription: sqlalchemy: get max/min/avg values from a table

description: Sqlalchemy: get max/min/avg values from a table


code:
_sentinel = object()

class A(object):
    def __init__(self):
        self._defaultReportText = "hello world"

    def report(self, text=_sentinel):
        if text is _sentinel:
            text = self._defaultReportText
        return text

rawDescription: How should data attributes of a class be used as default arguments in methods of the class?


code:
from random import randint
from operator import itemgetter

first = itemgetter(0)
second = itemgetter(1)

sa = [(str(randint(0, 1000000)), str(randint(0, 1000000))) for _ in range(300000)]
f_sorted = sorted(sa, key=first)
s_sorted = sa
s_sorted.sort(key=second)
max_length = max(len(s) for _,s in sa)

# See: bisect module from stdlib
def bisect_right(seq, element, key):
    lo = 0
    hi = len(seq)
    element = element.ljust(max_length, '9')
    while lo < hi:
        mid = (lo+hi)//2
        if element < key(seq[mid]):
            hi = mid
        else:
            lo = mid + 1
    return lo

def bisect_left(seq, element, key):
    lo = 0
    hi = len(seq)
    while lo < hi:
        mid = (lo+hi)//2
        if key(seq[mid]) < element:
            lo = mid + 1
        else:
            hi = mid
    return lo

def lookup_set(x_appr, y_appr):
    x_left = bisect_left(f_sorted, x_appr, key=first)
    x_right = bisect_right(f_sorted, x_appr, key=first)
    x_candidates = f_sorted[x_left:x_right + 1]
    y_left = bisect_left(s_sorted, y_appr, key=second)
    y_right = bisect_right(s_sorted, y_appr, key=second)
    y_candidates = s_sorted[y_left:y_right + 1]
    return set(x_candidates).intersection(y_candidates)

rawDescription: Python: how to search for a substring in a set the fast way?


code: g = df.groupby(0).max()

rawDescription: Split time series to find annual maximum from a data frame in Pandas


code:
mask = a != 0
a[mask] += 2
#some more code ...
a[mask] *= 3
#more code ...

rawDescription: Selective Numpy array manipulation (dependent on value)


rawDescription: Update pandas DataFrame in stored in a Pytable with another pandas DataFrame


code:
import bzr_version
d = bzr_version.version_info
build = d.get('revno','<unknown revno>')
date  = d.get('build_date','<unknown build date>')

rawDescription: Have program report bazaar revision number when run


code:
def on_pre_delete(self):
  for record in ClusteringRecord.related_set(self):
    record.cluster_comment = None
    record.save()

rawDescription: Iterating through all foreign key related children of an abstract django model


code:
class SavedForm(Model):
    user = ForeignKey(User)
    postdata = TextField()

rawDescription: Using FormWizard and saving the forms data in between before the completion of the whole process?


code:
d = {1: ['Ma','Ant','Man','io'], 2: ['Sc','Alb','Man'], 3: ['Sc','Alb','Sch','bre']}
df = pd.DataFrame.from_dict(d, orient='index')
df = pd.get_dummies(df, prefix='', prefix_sep='').astype(int)

rawDescription: Python: Multidimensionnal dictionnary to array


rawDescription: Iterating through python numpy array when used with scipy.optimize.curve_fit


rawDescription: Sorting dictionary keys by values in a list?


code: print(*range(5), sep=", ")

rawDescription: I don't know how to strip the end of this line


rawDescription: Sorting a complex datastructure

description: Sorting a complex datastructure


code:
l.sort(key=itemgetter(0))
l

rawDescription: How to Sort 2 Element Tuple of Strings in Mixed Order Using key Parameter (Not cmp)


code: factors += [-item for item in factors]

rawDescription: add a character in front of every element in a list

description: Add a character in front of every element in a list


rawDescription: Find common numbers in Python

description: Find common numbers in Python


rawDescription: Scipy label erosion

description: Scipy label erosion


code:
def flatten(li):
    for el in li:
        try:    # if strings can be in list, would have to check here
            for sub in flatten(el):
                yield sub
        except TypeError:
            yield el

def find(abc):
    abc = list(flatten(abc))

    def _smallest2(abc):
        # basically your implementation for finding the smallest two values
        if len(abc) <= 2:
            return tuple(sorted(abc, reverse=True))
        current = abc[0]
        second, first = _smallest2(abc[1:])
        if (second < current):
            re = (second, first)
        elif (current > first) and (second >= current):
            re = (current, first)
        else:
            re = (first, current)
        return re

    return _smallest2(abc)

rawDescription: Finding the second smallest int in list of list in Python 3 with recursion


code:
class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        listy = [] # where the needed output is put in
        splitName = name.split(" ")
        listy ="Name",splitName[0],"Name",splitName[1],"Surname",splitName[2]

        return listy

nr = NameParser()

print(nr.getName("ali opcode goren"))

# output: name: ali, name: opcode, surname: goren

rawDescription: How to return two values in Python

description: Return two values in Python


code:
#!/usr/bin/env python
import sys
import tarfile

with tarfile.open(sys.argv[1]) as archive:
    for member in archive:
        if member.isdir() and member.name.count('/') < 2:
            print(member.name)

rawDescription: Navigating a large tar.gz file in python without extracting it first


code:
def zip (filenames):
    buffer= StringIO.StringIO()
    z= zipfile.ZipFile( buffer, "w" )
    [z.writestr(f) for f in filenames]
    z.close()
    # generate the file
    response = HttpResponse(FileWrapper(z), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=z.zip'
    return response

rawDescription: python django dynamic zipping and download

description: Python django dynamic zipping and download


rawDescription: Add a column to the end of csv using pandas or in general python


code:
import re
def solve(s):
    return re.sub(r'(\d)(st|nd|rd|th)', r'\1', s)

rawDescription: python format date days that contains st nd ..or th

description: Python format date days that contains st nd ..or th


code:
with open('data.xml', 'w') as f:
    f.write(r.text)

rawDescription: Save XML response from GET call using Python


code:
# Compute v
v = [item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500]
if len(v) == 1:
    row1[1]=v[0][1]
    row1[2]=v[0][2]
else:
    # If v fails, compute k
    k = [item for item in custadd if item[0]==row1[4]]
    if len(k) == 1:
        row1[1]=k[0][1]
        row1[2]=k[0][2]
    else:
        # If k fails, compute m
        m = [item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group()]
        if len(m) == 1:
            row1[1]=m[0][1]
            row1[2]=m[0][2]

rawDescription: Assign variable name to list in if statement python


code:
import re
# Regex: VERBOSE, commented version.
reLong = r"""
    # Match "val=dd" where dd has two or more digits (but is not 13).
    \bval\s*=\s*  # "val=" literal with optional ws.
    (?!           # Begin negative lookahead assertion.
      [+\-]?      # Number may have optional sign.
      13          # This is the number we don't match
      \b          # which ends on a word boundary.
    )             # The number is not 13, +13 or -13.
    (             # $1: Two digit number.
      [+\-]?      # Allow optional sign.
      \d+         # One or more digits.
    )             # End $1: containing 2 digit number
    """
# Regex: short, uncommented version.
reShort = r"\bval\s*=\s*(?![+\-]?13\b)([+\-]?\d{2}\b)"

# Compile a regex object we can use over and over.
reObj = re.compile(reLong, re.IGNORECASE | re.VERBOSE)

# Test data strings. Positive and negative. With/without whitespace.
input = [
    # String with positive numbers. No whitespace.
    "val=1 val=13, val=133, val=12, otherval=1",
    # String with positive numbers. With whitespace.
    "val = 1 val = 13, val = 133, val = 12, otherval = 1",
    # String with negative numbers. No whitespace.
    "val=-1 val=-13, val=-133, val=-12, otherval=-1",
    # String with negative numbers. With whitespace.
    "val = -1 val = -13, val = -133, val = -12, otherval = -1",
    ]

# Parse all test data strings and print matches.
for str in input:
    matches = reObj.findall(str)
    if matches:
        print(matches)

rawDescription: Python regex: Reject one two-digit number and accept other two-digit numbers


code:
import sqlite3
import numpy as np
import pandas as pd

filename = '/tmp/test.sqlite'
with sqlite3.connect(filename) as conn:
    cursor = conn.cursor()
    cursor.execute('DROP TABLE IF EXISTS C')
    cursor.execute('CREATE TABLE C (CTR float)')
    sql = 'INSERT INTO C VALUES (?)'
    args = [(x, ) for x in np.random.random(5)] + [('',)]
    cursor.executemany(sql, args)
    df = pd.read_sql(sql="SELECT * FROM C",
                     con=conn, coerce_float=True)
    print(df)
    #           CTR
    # 0   0.1205763
    # 1   0.5859016
    # 2   0.9511995
    # 3  0.08459435
    # 4   0.8094845
    # 5
    print(df.dtypes)

rawDescription: Why the datatypes in Pandas are different from those in SQL


code:
with open('first_group.csv', 'wb') as test_file:
    csv_writer = csv.writer(test_file)
    csv_writer.writerow(["image1"] + ["image2"])

    step_size = 7 # set step size here
    seen = set() # here we remember images we've already seen
    for x in range(0, len(rows)-step_size):
        img1 = rows[x][1]
        img2 = rows[x+step_size][1]
        if not (img1 in seen or img2 in seen):
            csv_writer.writerow([img1, img2])
            seen.add(img1)
            seen.add(img2)

rawDescription: Selecting rows in cvs file and write them in another csv file


rawDescription: cleaning big data using python

description: Cleaning big data using python


code:
import os
import imp
import runpy

package = 'classes'

_, path, _ = imp.find_module(package)
for m in os.listdir(path):
    if m.endswith('.py'):
        runpy.run_module(
            package + '.' + os.path.splitext(m)[0],
            run_name="Mix_Meld"
        )

rawDescription: Executing python class code located in folders


code:
import cv2
import numpy as np

# original image
image = cv2.imread('image.png')

# mask (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array(points, dtype=np.int32) #pointsOf the polygon Like [[(10,10), (300,300), (10,300)]]
white = (255, 255, 255)
cv2.fillPoly(mask, roi_corners, white)

# apply the mask
masked_image = cv2.bitwise_and(image, mask)

# display your handywork
cv2.imshow('masked image', masked_image)
cv2.waitKey()
cv2.destroyAllWindows()

rawDescription: openCV python, get the region from closed curve

description: OpenCV python, get the region from closed curve


code:
def fun(x, y, param1=10, param2=None):
    if param2 is None:
        param2 = param1/3
    # do something

rawDescription: Function with dependent preset arguments


code: html_sidebars = { '**': ['globaltoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'], }

rawDescription: How to include the toctree in the sidebar of each page

description: Include the toctree in the sidebar of each page


code: doSomething();

rawDescription: How to ask user for loop amount

description: Ask user for loop amount


code:
import csv

with open('file1', 'rb') as file1:
    file1_data = dict(line.split(None, 2)[1::-1] for line in file1 if line.strip())

with open('file2', 'rb') as file2, open('output', 'wb') as outputfile:
    output = csv.writer(outputfile, delimiter='|')
    for line in file2:
        if line[:1] == '?':
            row = line.strip().split('|')
            key = row[0][1:]
            if key in file1_data:
                 output.writerow(row + [file1_data[key]])

rawDescription: Matching different columns and combine them using python


code:
IV = base64.b64decode(IV)
newIV = base64.b64encode(IV[:-1] + chr(ord(IV[-1]) ^ x))

rawDescription: Altering the Last Byte of a String

description: Altering the Last Byte of a String


code:
def isgeneratorfunction(object):
    """Return true if the object is a user-defined generator function.

    Generator function objects provides same attributes as functions.

    See help(isfunction) for attributes listing."""
    return bool((isfunction(object) or ismethod(object)) and
                object.func_code.co_flags & CO_GENERATOR)

rawDescription: How python interpret a function as a generator


rawDescription: Getting top n edges in a graph networkx

description: Getting top n edges in a graph networkx


code:
class NamespaceReference(object):
    def __init__(self, namespace, name):
        self.namespace, self.name = namespace, name
    def get(self):
        return getattr(self.namespace, self.name)
    def set(self, value):
        setattr(self.namespace, self.name, value)

ref_dict = {'field1': GlobalReference('a'), 'field2': NamespaceReference('myobj', 'b')}

rawDescription: python reference to a float, int, etc

description: Python reference to a float, int, etc


code:
expl_var = 'Av_Temp'
cname = 'Tot_Precip'
df[expl_var+'_Deciles'] = pandas.qcut(df[expl_var], 2)

ax = df.boxplot(by='Av_Temp_Deciles', column='Tot_Precip')
ax.set_yscale('log')

rawDescription: Overlapping boxplots in python

description: Overlapping boxplots in python


rawDescription: Regex finds just once

description: Regex finds just once


code:
import numpy as np
from scipy.interpolate import spline

fpr =[0,0.1,0.4,0.9,1]
tpr =[0,0.3,0.4,0.5,1]

n = 20
x_interp = np.linspace(0,1,n+1)
y_interp = spline(fpr, tpr, x_interp, order=0)

rawDescription: How can i resample "roc_curve" (fpr,tpr )?

description: Resample "roc_curve" (fpr,tpr )


code:
def on_keyPressHook(self, event):
    if event.keyCode == wx.WXK_RETURN:
        self.handle_return()
    else:
        event.Skip()

rawDescription: PythonCard not getting 'enter' KeyEvent in Windows


code: wave_date = sampling_rate * (wave_data[1:] - wave_data[:-1])

rawDescription: Mapping a numpy array pairwise

description: Mapping a numpy array pairwise


rawDescription: Python command line argument for an existing process


code:
class docstring_str(str):
    def __new__(cls, v, __doc__=''):
        s = super(docstring_str, cls).__new__(cls, v)
        s.__doc__ = __doc__
        return s

rawDescription: Implementing a class property that preserves the docstring


code:
def get_seed(self, word):
    #Set the acceptable distance
    LIMIT = 2
    #Have we seen this word before?
    seed = self.cache.get(word,None)
    if seed is not None:
        #YES. Return from the cache
        return seed
    for seed in self.seeds:
        #NO. For each pre-existing seed, find the distance of this word from that seed
        if self.distance(seed, word) <= LIMIT:
            #This word is similar to the seed
            self.cache[word] = seed
            #We found this word's seed, cache it and return
            return seed
    #No we couldn't find a matching word in seeds. This is a new seed
    self.seeds.add(word)
    #Cache this word for future
    self.cache[word] = word
    #And return the seed (=word)
    return word

rawDescription: improve my code to group same words in a large list python and comparison to other code

description: Improve my code to group same words in a large list python and comparison to other code


code:
dx = ndimage.sobel(your3Dmatrix, 0)  # x derivative
dy = ndimage.sobel(your3Dmatrix, 1)  # y derivative
dz = ndimage.sobel(your3Dmatrix, 2)  # z derivative

rawDescription: 3d sobel algorithm in python?

description: 3d sobel algorithm in python


rawDescription: Read a CSV file and Append to dictionary


code: m.title = exif.get('Xmp.dc.subject') or exif.get('Xmp.dc.title') or original_filename_noextension

rawDescription: Efficiently select the best string from keys in a dict


code:
message = unicode(message).replace('\r\n','
').replace('\n','
')

rawDescription: How to turn a Flask Markup string into a normal string

description: Turn a Flask Markup string into a normal string


rawDescription: Adding a Method to an Existing Object Instance


code:
list_of_tuples = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'), ('Frenchy', 'HelloMrGumby'), ('INTENSE', 'Frenchy'), ('INTENSE', 'ComputerScienceFTW'), ('INTENSE', 'HelloMrGumby'), ('ComputerScienceFTW', 'Frenchy'), ('ComputerScienceFTW', 'INTENSE'), ('ComputerScienceFTW', 'HelloMrGumby'), ('HelloMrGumby', 'Frenchy'), ('HelloMrGumby', 'INTENSE'), ('HelloMrGumby', 'ComputerScienceFTW')]
[''.join(t) for t in list_of_tuples]
[a + b for a, b in list_of_tuples]

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


code:
def hyperbola(x, a, b, c, d, e):
    """ hyperbola(x) with parameters
        a/b = asymptotic slope
         c  = curvature at vertex
         d  = offset to vertex
         e  = vertical offset
    """
    return a*np.sqrt((b*c)**2 + (x-d)**2)/b + e

def rot_hyperbola(x, a, b, c, d, e, th):
    pars = a, b, c, 0, 0 # do the shifting after rotation
    xd = x - d
    hsin = hyperbola(xd, *pars)*np.sin(th)
    xcos = xd*np.cos(th)
    return e + hyperbola(xcos - hsin, *pars)*np.cos(th) + xcos - hsin

rawDescription: Fit a curve for data made up of two distinct regimes


rawDescription: Unix base64 encoding mismatch

description: Unix base64 encoding mismatch


code:
from numpy import linspace
xs = linspace(-1, 1, num=1000) * sigma_overlap_fit * 6 + mu_overlap_fit
ax.plot(xs, gaussian(xs, mu_overlap_fit, sigma_overlap_fit), color="orange", lw=2)

xs = linspace(-1, 1, num=1000) * sigma_curve_fit * 6 + mu_curve_fit
ax.plot(xs, gaussian(xs, mu_curve_fit, sigma_curve_fit), color="purple", lw=2)

pyplot.show()

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


code:
def put_ticket_on_dynamodb(self, item):
    # Write record to dynamoDB
    try:
        dynamodb = boto3.resource('dynamodb')
        table = dynamodb.Table(settings.ENV[self.stage]["TABLE_NAME"])
        table.put_item(Item=item)
    except Exception as e:
        logger.error("Fail to put item on DynamoDB: {0}".format(str(e)))
        raise
    logger.info("Item successfully written to DynamoDB")
    return item

rawDescription: Using different settings on a aws lambda function coded in python


rawDescription: set very low values to zero in numpy

description: Set very low values to zero in numpy


code: True

rawDescription: Check if part of text is in tuple

description: Check if part of text is in tuple


rawDescription: django convert .values_list('datetimefield') to date

description: Django convert .values_list('datetimefield') to date


code:
import cv2
import numpy as np

img = cv2.imread('zzzyj.jpg')
h = np.zeros((300,256,3))

bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]

for ch, col in enumerate(color):
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
    cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
    hist=np.int32(np.around(hist_item))
    pts = np.column_stack((bins,hist))
    cv2.polylines(h,[pts],False,col)

h=np.flipud(h)

cv2.imshow('colorhist',h)
cv2.waitKey(0)

rawDescription: Drawing Histogram in OpenCV-Python

description: Drawing Histogram in OpenCV-Python


code:
from collections import Counter
mystr = "AaAaaEeEiOoouuu"
Counter(c for c in mystr.lower() if c in "aeiou")
# Get the top three most common
Counter(c for c in mystr.lower() if c in "aeiou").most_common(3)
# Get the most common
Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)
Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
a
b

rawDescription: Count specific vowels in a sentence

description: Count specific vowels in a sentence


code:
import wx
messages = ["Hello","World","Python"]
a = wx.App(redirect=False)
f = wx.Dialog(None,-1,"Changing Text!")
te = wx.StaticText(f,-1,"Changes!")
btn = wx.Button(f,-1,"Change The Text",pos=(10,25))
btn.Bind(wx.EVT_BUTTON,lambda evt:te.SetLabel(messages.pop(0)) or messages.append(te.GetLabel()))
f.ShowModal()

rawDescription: How to update wxStatic Text in wxpython?

description: Update wxStatic Text in wxpython


code: find_all(master, namecount)

rawDescription: How to replace different blocks of text in all combinations using awk?

description: Replace different blocks of text in all combinations using awk


rawDescription: Login form for custom users in django

description: Login form for custom users in django


code:
def subfoldernames( root ):
    for folder in os.listdir(root):
        path = os.path.join(root, folder)
        if os.path.isdir(path):
            yield folder # just the name, not the path

# same, just shorter:
def subfoldernames( root ):
    # this returns a generator, written as a generator expression
    return ( folder for folder in os.listdir( root )
                    if os.path.isdir(os.path.join( root, folder )) )

def GetSteamAccts():
        Steamapp_Folders = ("C:\\Program Files (x86)\\Steam\\steamapps\\",
                                             "C:\\Program Files\\Steam\\steamapps\\")
        for folder in Steamapp_Folders:
            if os.path.isdir(folder):
                # only the subfolders of the first path that exists are returned
                return list(subfoldernames( folder ))

rawDescription: Cleaning up nested for loops in python

description: Cleaning up nested for loops in python


rawDescription: Parsing Text with Python RegEx re.findall


code:
number_1 = int(raw_input("Input first number:"))
number_2 = int(raw_input("Input second number:"))

rawDescription: Print user inputted number with commas and the numbers in between


code:
def create_random(i):
    return random() * i

curs.execute("select gid, number from t;")
data = curs.fetchall()

results = []
for i in data:
    results.append((create_random(i[1]), i[0]))

curs.execute("""
    update t
    set
        rnd = s.rnd,
        result = number * s.rnd
    from unnest(%s) s(rnd numeric, gid integer)
    where t.gid = s.gid;
""", (results,))

con.commit()

rawDescription: How to efficiently UPDATE a column in a large PostgreSQL table using Python / psycopg2?

description: Efficiently UPDATE a column in a large PostgreSQL table using Python / psycopg2


code:
print ("hello", "world")
print ("hello world",)

rawDescription: Python 2.7: What print() does to the string inside of it


rawDescription: [Python EVE]: Reading the request parameters values in Python EVE


code:
class EqMixin(object):
  def __eq__(self, other):
    return same(cont1, cont2, value_same)

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
import unittest
from unittest.mock import patch
from module_a import A

class MyTestCase(unittest.TestCase):

    #patch B class in a_module by a MagicMock instance mock_b_costructor passed to test method
    @patch("module_a.B")
    def test_a(self, mock_b_costructor):
        #B() return value will be the B() instance assigned to a.b property
        mock_b = mock_b_costructor.return_value
        # Now start test:
        a = A()
        #ok! b is our mock...
        self.assertIs(a.b, mock_b)
        #not authorized
        self.assertFalse(a.is_authorized())
        mock_b.get_name.return_value = 'admin'
        #Yeah!!! we are admin
        self.assertTrue(a.is_authorized())
        #sanity check
        mock_b.get_name.return_value = 'guest'
        self.assertFalse(a.is_authorized())

rawDescription: How do I mock a class in a Python unit test?

description: Mock a class in a Python unit test


code:
source = inspect.getsource(foo)
with open('newfoo.py', 'wb') as f:
    f.write(source)
    f.write('spam = Spam(3)\neggs = Eggs(spam)\n')

rawDescription: Exporting a python module (to string or py file)


code:
class Course(db.Model):
    name = CharField()

class Activity(db.Model):
    # Note that we have added a backreference
    # to activities on the `Course` model with
    # the `related_name` argument
    # so we can do course.activites
    course = ForeignKeyField(Course, related_name='activities')
    name = CharField()

results = Course.select(Course, Activity).join(Activity)
# results is now a collection of courses, each course
# with all of its activities and it all should have been
# pulled out with one SQL query

rawDescription: Generate select with optgroup in Peewee

description: Generate select with optgroup in Peewee


code: d = dict(map(str.split, open(filename)))

rawDescription: How to read from file, turn into a dictionary and write to the same file

description: Read from file, turn into a dictionary and write to the same file


code:
for sublist in data:
    for i, val in enumerate(sublist):
        if isinstance(v, basestring):
            sublist[i] = v.strip('%')

rawDescription: Find and Replace Percent Signs - Python

description: Find and Replace Percent Signs - Python


code:
REDIS_HOST = "localhost"
REDIS_PASSWORD = "password"
REDIS_PORT = 6379

rawDescription: Flask: How to Authenticate with Flask-Redis and Redis


code:
X = np.random.randint(2, size=(nSamples,nFeatures)).astype(np.int8)
X.nbytes / 10 ** 6
Out[12]: 60.0

rawDescription: Practical limits to data size for sklearn.naive_bayes.BernoulliNB


code:
lis = ['abcd','efgh','ijkl','mnop']
[ x[1:3] for x in lis]

rawDescription: Create new list of substrings from list of strings


code: return style.saveResultToString(html)

rawDescription: Python - convert <type 'instance'> to <type 'str'>?


code:
df
df.groupby('VID').count()
countdf = df.groupby('VID').count()
df.loc[df['VID'].isin(countdf[countdf['value'] > 3].index)]

rawDescription: Keeping rows in Pandas where the same ID appears more than n times and convert to list per ID


code:
def cumsum(it):
    total = 0
    for x in it:
        total += x
        yield total

rawDescription: Elegant pythonic cumsum

description: Elegant pythonic cumsum


rawDescription: Output data from all columns in a dataframe in pandas


code: l = ax1.plot(x,y)

rawDescription: How do I target a list element of a MatPlotLib object that "returns a list"?

description: Target a list element of a MatPlotLib object that "returns a list"


code:
for d in result:
    if "is_diabetic" in d:
        if d["is_diabetic"] == 1:
            d["is_diabetic"] = "Yes"
        else:
            d["is_diabetic"] = "No"
    if "is_inpatient" in d:
        if d["is_inpatient"] == 1:
            d["is_inpatient"] = "Yes"
        else:
            d["is_diabetic"] = "No"

rawDescription: Updating values for only certain keys in a list of dicts in python


rawDescription: List conversion

description: List conversion


code:
import subprocess
subprocess.check_call(["python", "user_script.py", "c"])

rawDescription: Have command line argument as a default function argument


code:
#!/usr/bin/env python
from glob import glob
from multiprocessing.pool import ThreadPool
from subprocess import call
try:
    from threading import get_ident # Python 3.3+
except ImportError: # Python 2
    from thread import get_ident

cmd = 'java -cp stanford-ner.jar edu.stanford.nlp.process.PTBTokenizer'.split()
def run_command(files):
    with open('output%d.txt' % get_ident(), 'ab', 0) as file:
        return files, call(cmd + files, stdout=file)

all_files = glob('*.txt')
file_groups = (all_files[i:i+100] for i in range(0, len(all_files), 100))
for _ in ThreadPool(10).imap_unordered(run_command, file_groups):
   pass

rawDescription: python or bash script to pass all files in a folder to java command line

description: Python or bash script to pass all files in a folder to java command line


code:
import numpy as np
import scipy.stats
data = np.random.uniform(0, 100, 10**5)
data.mean(), data.std()

rawDescription: How should the values of a list be scaled such that they meet standard deviation and mean requirements?


rawDescription: Python - Uniquely determining which text file an element originated from


code:
df.groupby('id').apply(lambda x: list(set(x['colours'])))
df.groupby('id').apply(lambda x: list(x['colours']))

rawDescription: Grouping data in a dataframe to produce lists against unique ids in Pandas/Python


code: import utils_pandas

rawDescription: Is there a pandas function to display the first/last n columns, as in .head() & .tail()?


code:
formatter = argparse.HelpFormatter('prog')
formatter._max_help_position = 45

rawDescription: How to change the format of subparser with argparse

description: Change the format of subparser with argparse


rawDescription: Is it possible to cross reference bash and python variables in python script


rawDescription: Reassigning a value to a list with a function


code:
from string import punctuation
r = re.compile(r'[{}]+'.format(re.escape(punctuation)))
r.sub('', a)

rawDescription: replace punctuation with nothing

description: Replace punctuation with nothing


rawDescription: Pandas select and write rows that contain certain text


code:
lst = [ [i]*j for i, j in zip( df3.index.tolist(), df3['ones'].tolist() ) ]
arr = np.array( [item for sublist in lst for item in sublist] )
np.hstack( [arr,-1*arr] )

rawDescription: How to return all opposite pairs in a Pandas DataFrame?

description: Return all opposite pairs in a Pandas DataFrame


code:
hdr = {'Accept': 'text/html,application/xhtml+xml,*/*',"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"}
req=urllib2.Request(url,headers=hdr)
html = urllib2.urlopen(req).read()

rawDescription: HTTP Error 403: Forbidden urlib2 Python 2.7


code:
T1 = timeit.Timer('maker(3)(4)', 'from __main__ import maker')
T1.timeit()
T2 = timeit.Timer('clsmaker(3)(4)', 'from __main__ import clsmaker')
T2.timeit()

rawDescription: python factory functions compared to class

description: Python factory functions compared to class


code:
@classmethod
def function_b(cls, df):
    if df.empty:
        return df
    df.rename(columns={'_id':'release_id'}, inplace=True)
    df.set_index("release_id", drop=True, inplace=True)
    return df.sort_index()

rawDescription: How can I reduce the duplicated use of if and else

description: Reduce the duplicated use of if and else


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code: city_re = re.compile(r'\b('+ '|'.join(c.strip() for c in cities.readlines()) + r')\b')

rawDescription: Faster Approach of Double for loop when iterating large list (18,895 elements)


rawDescription: Python 3 string formatting with filler more than one character long


code:
### Indices to marginals arguments:

NGRAM = 0
"""Marginals index for the ngram count"""

UNIGRAMS = -2
"""Marginals index for a tuple of each unigram count"""

TOTAL = -1
"""Marginals index for the number of words in the data"""

def student_t(cls, *marginals):
      """Scores ngrams using Student's t test with independence hypothesis
      for unigrams, as in Manning and Schutze 5.3.1.
      """
      return ((marginals[NGRAM] -
                _product(marginals[UNIGRAMS]) /
                float(marginals[TOTAL] ** (cls._n - 1))) /
              (marginals[NGRAM] + _SMALL) ** .5)

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?


code:
for (key, val) in d.items():
    if val < sl:
          d[key] = (val,'Yes')
    else:
          d[key] = (val,'No')

rawDescription: Adding multiple values to a key in python dictionaries


code: "doc" and "pdf" and "xls" and "jpg"

rawDescription: Python Logic in searching String

description: Python Logic in searching String


code:
from itertools import chain

def get_lines(f, n=1):
    return [f.next() for i in xrange(n)]

class BlockReader(object):
    def __init__(self, f, n=1):
        self.f = f
        self.n = n
    def __iter__(self):
        return self
    def next(self):
        return [self.f.next() for i in xrange(self.n)]

fmt = "{:<12}" + "{:<16}"*6 + "\n"
cols = [
    "Time",
    "Head(Depth=0)",
    "Head(Depth=-1)",
    "Head(Depth=-2)",
    "Moisture(Depth=0)",
    "Moisture(Depth=-1)",
    "Moisture(Depth=-2)"
]

def main():
    with open("simulation.txt") as inf, open("result.txt","w") as outf:
        # throw away input header
        get_lines(inf, 5)
        # write output header
        outf.write(fmt.format(*cols))

        # read input file in ten-line chunks
        for block in BlockReader(inf, 10):
            # grab time value
            time = float(block[1].split()[1])

            # grab head and moisture columns
            data = (line.split()[2:4] for line in block[6:9])
            values = (map(float,dat) for dat in data)
            h,m = zip(*values)

            # write data to output file
            outf.write(fmt.format(*chain([time],h,m)))

if __name__=="__main__":
    main()

rawDescription: Read, Slice and Re-structure data file block-by-block in Python


code:
def Popen(*args, testmode=False, **kw):
    if testmode:
        return DummyPopen(*args, **kw)
    return subprocess.Popen(*args, **kw)

rawDescription: extending subprocess.Popen through inheritence

description: Extending subprocess.Popen through inheritence


rawDescription: Subset of an ndarray based on another array


code:
def plot_histogram(data, edge_bins, **kwargs):
    bins = edge_bins[:-1] + edge_bins[1:]
    plt.step(bins, data, **kwargs)

plot_histogram(xhist, xbins, c='b')
plot_histogram(yhist, ybins, c='g')

rawDescription: Normalize a multiple data histogram

description: Normalize a multiple data histogram


code:
with open('data.txt') as f:
    data = f.readlines()
print (data[1])

rawDescription: What is best way to access variables from different python modules?


code:
best = max(map(lambda p: p.best, self.players))
bestPlayers = filter(lambda p: p.best == best, self.players)

rawDescription: Using a for loop instead of if,elif?

description: Using a for loop instead of if,elif


code:
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    url = db.Column(db.String(120))
    body = db.Column(db.Text)
    create_date = db.Column(db.DateTime)
    pub_date = db.Column(db.DateTime)
    pub_status = db.Column(db.Text(80))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User',
                             backref=db.backref('posts', lazy='dynamic'))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.category = category
        self.pub_date = pub_date

    def __repr__(self):
        return '<Post %r>' % self.title

class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    description = db.Column(db.String(250))

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

    def __repr__(self):
        return self.name

rawDescription: A Complete Many-to-One Example Using Flask, WTForm, SQLAlchemy, and Jinja2


code:
if bareWords[0] == 'from' and bareWords[2] == 'run':
        atPrompt.autoRun = ['from ' + bareWords[1] + ' import ' + bareWords[3].split('(')[0],
                            ' '.join(bareWords[3:])]
        return

rawDescription: Bare words / new keywords in Python

description: Bare words / new keywords in Python


rawDescription: Python: Dictionary with 3 items

description: Python: Dictionary with 3 items


code:
x = "abcde"
x = x.replace(x[0], x[2])    # == replace("a", "c")
x
x = x.replace(x[2], x[4])    # == replace("c", "e")
x

rawDescription: python replace records in variable

description: Python replace records in variable


code: [(y+"@company.com") for y in x.split()]

rawDescription: Python regex - extend string

description: Python regex - extend string


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

# Generate some interesting-looking random data...
num = 200
grid = np.random.normal(0, 1, (20, num)).cumsum(axis=1).cumsum(axis=0)
x = np.linspace(0, 360, num)
y1 = np.random.normal(0, 1, num).cumsum()
y2 = np.random.normal(0, 1, num).cumsum()

# Plot on three seperate axes
fig, axes = plt.subplots(nrows=3, sharex=True)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
im = axes[2].imshow(grid, extent=[0, 360, 0, 20], aspect='auto')
fig.colorbar(im, orientation='horizontal')

plt.show()

rawDescription: Matplotlib mixed subplots with plot and pcolor(mesh) to have the same x axis length when colorbar is on


code: ['Wonderland', 'ALice', 'in']

rawDescription: Enumerate Keys in a dictionary?

description: Enumerate Keys in a dictionary


code:
import file1

class A(file1.A):
    def __init__(self):
        file1.A(self)
        self.thing = other_thing

file1.A = A

rawDescription: Python inheritance and scoping question

description: Python inheritance and scoping question


rawDescription: How to replace non-alphabetic AND numeric characters in a string in python

description: Replace non-alphabetic AND numeric characters in a string in python


code:
from multiprocessing import Pool
import time
import random

SOME_LIST = []

def myfunc():
    a = random.randint(0,3)
    time.sleep(a)
    return a

def cb(retval):
    SOME_LIST.append(retval)

print("Starting...")

p = Pool(processes=8)
for _ in range(p._processes):
    p.apply_async(myfunc, callback=cb)
p.close()
p.join()

print("Stopping...")
print(SOME_LIST)

rawDescription: Managing Processes from Python multiprocessing module


code:
from Bio.Blast import NCBIXM
blast_records = NCBIXML.parse(result_handle)

save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w')

for blast_record in blast_records:
  for alignment in blast_record.alignments:
      for hsp in alignment.hsps:
            save_file.write('>%s\n' % (alignment.title,))
  #here possibly to output something to file, between each blast_record
save_file.close()

rawDescription: BioPython: extracting sequence IDs from a Blast output file


code: #!/usr/bin/env python3

rawDescription: terminal only running 2.7, even after changing alias

description: Terminal only running 2.7, even after changing alias


code: line1, line2 = ('foo', 'bar') # unpack a 2-tuple

rawDescription: Mystical comma in a Python expression

description: Mystical comma in a Python expression


code:
from Mudules.module1 import *
from Widgets.widget1 import *

rawDescription: PYTHONPATH set when loading Idle in virtual environment


code:
x = 5
a = {}
b = dict(enumerate('ABCDEFGHIJKLM'))

while x > 0:
    try:
        key, value = b.popitem()
    except KeyError:
        break
    else:
        a[key] = value
        x -= 1

print(a)
print(b)

rawDescription: Copy 'N' key value pairs from one python dictionary to another


code:
import csv
import itertools

d = {
    'key_1':['item_1','item_2','item_3'],
    'key_2':['2_item_1','2_item_2','2_item_3', '2_item_4'],
}

with open('output.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(itertools.izip_longest(*d.values()))

rawDescription: Save a dict with lists as csv file

description: Save a dict with lists as csv file


code:
def add_visibility_fields(iface):
    fields = {}
    for name, attr in iface.namesAndDescriptions():
        fields[name] = attr
        if isinstance(attr, schema.Field):
            fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

    return InterfaceClass(iface.__name__, iface.__bases__, fields)

rawDescription: How to dynamically add attributes to an interface

description: Dynamically add attributes to an interface


code:
with open('bsxlength.txt' , 'r') as string:
    result = []
    while True:
        chunk = string.readline(513)
        if chunk:
            result.append(chunk)
        else:
            break

rawDescription: Chunk long string into 513 character chunks | Python 3.3


code:
import functools

def iterate(update):
    @functools.wraps(update)
    def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1):
        M, N = X.shape
        O = matrix(ones([M, N]))
        if A is None:
            A = matrix(rand(M, K))
        if S is None:
            S = matrix(rand(K, N))
        for iter in range(maxiter):
            A, S = update(X, A, S, K, maxiter, c)
            for k in range(K):
                na = norm(A[:,k])
                A[:,k] /= na
                S[k,:] *= na
        return A, S
    return inner

rawDescription: Potential use of Python decorator or other refactorization: iterative optimization


code: {{ yes_count }}

rawDescription: Django: How to reverse lookup with filter and count


code:
def save_session(self, app, session, response):
    domain = '.' + request.headers['Host']
    path = self.get_cookie_path(app)

    # the rest of the method is intact

rawDescription: How to configure a single flask application to handle multiple domains?

description: Configure a single flask application to handle multiple domains


code:
my_list = MyModel.objects.all()
smaller_list = my_list[100:200]

rawDescription: Django pagination. What if I have 1 million of rows?


rawDescription: How to remove the last repeating letters of a word

description: Remove the last repeating letters of a word


code:
x = 1    # int
x = 1.0  # float

rawDescription: I am trying to add r'' to a variable and tried below but its not working


code:
getFoos()
generateFoos()
yieldFoos()
allFoos()

rawDescription: Name of a function returning a generator


code: textinput = TextInput(focus=True)

rawDescription: How to set cursor position in TextInput in Kivy

description: Set cursor position in TextInput in Kivy


rawDescription: How to aggregate matching pairs into "connected components" in Python

description: Aggregate matching pairs into "connected components" in Python


rawDescription: Split Series by string length

description: Split Series by string length


code: map(hex, map(ord, x))

rawDescription: Extracting strings from struct.pack

description: Extracting strings from struct.pack


code:
import numpy as np

x = np.random.randint(0, 3200, (1000, 1000))
z = x.astype('<u2').tostring()

rawDescription: struct.pack is much slower in python 2.6 when working with numpy arrays

description: Struct.pack is much slower in python 2.6 when working with numpy arrays


code:
max = ws.max_row
for row, entry in enumerate(data1,start=1):
   st.cell(row=row+max, column=1, value=entry)

rawDescription: how to append data using openpyxl python to excel file from a specified row?

description: Append data using openpyxl python to excel file from a specified row


rawDescription: How to elegantly send/receive a large C struct using Python?

description: Elegantly send/receive a large C struct using Python


code:
row['ADDLINE2'] = row['LOCATION']['ADDLINE2']
row['ADDLINE3'] = row['LOCATION']['ADDLINE3']
row['PIN '] = row['LOCATION']['PIN ']

rawDescription: selective flattening in python nested dictionary and finding keys

description: Selective flattening in python nested dictionary and finding keys


code:
import datetime
from django.shortcuts import render_to_response
from myapp.models import Film

def search(request):
    # Suppose we support these params -> ('director', 'fromdate', 'todate')
    request_params = request.GET.copy()
    fromdate = datetime.datetime.strptime(request_params['fromdate'], 'some-string-format')
    todate = datetime.datetime.strptime(request_params['todate'], 'some-string-format')
    # Our query is ready to take off.
    film_results = Film.objects.filter(
        director__name=request_params['director'],
        created_at__range=(fromdate, todate)
    )
    return render_to_response('search_results.html', {'results':film_results})

rawDescription: DJANGO: how to create a web query form?

description: DJANGO: how to create a web query form


code:
suits = ["h","c", "d", "s"]
noclubs = list(suits)
noclubs.remove("c")
noclubs

rawDescription: python: a quick way to return list without a specific element

description: Python: a quick way to return list without a specific element


code: OrderedDict( (k, int(v)) for k, v in (el.split(':') for el in your_list))

rawDescription: Python: Parse list of 'key:value' elements to dictionary of 'key': value pairs


code:
def get_category_choices():
    all_categories = DBSession.query(Category).all()
    return [(str(c.id), c.name) for c in all_categories]

categories = get_category_choices()

class ProductForm(colander.Schema):
    """ The class which constructs a ProductForm form for add/edit pages. """

    name = colander.SchemaNode(colander.String(), title = "Name",
                               validator=colander.Length(max=80),
                              )

    description = colander.SchemaNode(colander.String(), title="Description",
                                  validator=colander.Length(max=2000),
                                  widget=deform.widget.TextAreaWidget(rows=10, cols=60),
                                 )

    categories = colander.SchemaNode(
                colander.Set(),
                widget=deform.widget.SelectWidget(
                    values=categories,
                    multiple=True,
                ),
                validator=colander.Length(min=1),
                )

rawDescription: Working with Many to Many Relationships in Deform/Colander HTML Select Field


rawDescription: Indexing ndarray of variable number of dimensions


code:
def OnLstStrategyDClick(self,e):
  index=e.GetSelection()
  self.txtStrategyID.SetValue(self.StrategyList[index][0])
  self.txtDescription.SetValue(self.StrategyList[index][1])
  #print self.StrategyList[index][2]

  out = StringIO()
  handler = wx.richtext.RichTextXMLHandler()
  buffer = self.txtBidStrategy.GetBuffer()
  buffer.AddHandler(handler)
  out.write(self.StrategyList[index][2])
  out.seek(0)
  handler.LoadStream(buffer, out)
  self.txtBidStrategy.Refresh()

  self.txtBidStrategy.SetValue(self.StrategyList[index][2])

rawDescription: text from RichTextCtrl

description: Text from RichTextCtrl


code: bindices_zero = (array == 0)

rawDescription: Getting indices of both zero and nonzero elements in array


code: [len(word) for word in sentence.split()]

rawDescription: Change code to use list comprehension

description: Change code to use list comprehension


code:
import tkinter as tk

root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()

rawDescription: Setting the window to a fixed size with Tkinter


rawDescription: Python dict using dot notation and chaining


code: ZTASKD_URL = 'ipc:///tmp/%s_ztask.sock' % SITE_NAME

rawDescription: Django and SaaS. How to use separate database for each Django site?


code:
parser.add_argument('--infile',
                    help="The file to be imported",
                    type=argparse.FileType('r'),
                    default=sys.stdin
)

parser.add_argument('--carpark',
                    nargs='+',
                    dest='CarparkID',
                    type=int, default=[],
                    help="One or many carpark IDs"
)

rawDescription: Argparse nargs="+" is eating positional argument


code:
import multiprocessing, itertools

def stringForInt(args):
    num, charset, length = args ## hack hack hack
    setlen = len(charset)
    s = []
    s.append(charset[num % setlen])
    for n in xrange(1, length):
        num //= setlen
        s.append(charset[num % setlen])
    return ''.join(s)

def bruteforce(charset, length, mapper, raw=False):
    if not raw:
        charset = sorted(set(charset))
    return mapper(stringForInt, ((n,charset,length) for n in xrange(len(charset)**length)))

if __name__ == '__main__':
    import time, sys
    if len(sys.argv) == 1 or sys.argv[1] == 'map':
        mapper = map
    else:
        p = multiprocessing.Pool()
        pfunc = {'pmap':p.map,
                 'imap':p.imap,
                 'imapu':p.imap_unordered}[sys.argv[1]]
        mapper = lambda f, i: pfunc(f, i, chunksize=5)
    o = bruteforce('abcdefghijk',6,mapper)
    if not isinstance(o, list):
        list(o)

rawDescription: Implementing Multicore Threading on this algorithm


code:
import urllib2  # the lib that handles the url stuff

data = urllib2.urlopen(target_url) # it's a file like object and works just like a file

rawDescription: web scrape a .txt file using python

description: Web scrape a .txt file using python


code:
from collections import defaultdict
reverselookup = defaultdict(list)
for testdict in test_data:
    reverselookup[testdict['value']].append(testdict)

rawDescription: How do I compare multiple key values from a list of dictionaries?

description: Compare multiple key values from a list of dictionaries


code:
import re
line = '{2}*{3}^2'
factorseq_dict = [('2', 'NAME1'), ('3', 'NAME2')]
dict_ = dict(factorseq_dict)
re.sub(r'\{(\d+)\}', lambda m: '{' + dict_[m.group(1)] + '}', line)

rawDescription: Compare and replace items in a string

description: Compare and replace items in a string


code: pd.PeriodIndex([ pd.Period(year=year,month=month,freq='M') for year, month in df.index ])

rawDescription: How to change a groupby DF to a monthly datetime series in Python Pandas

description: Change a groupby DF to a monthly datetime series in Python Pandas


code:
def test():   #python 2 and 3
    output = False
    locals()['output'] = True
    print(output)

test()

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


code:
def distance(point, segment):
    """Distance from a point to a line formed by a segment"""
    ...

rawDescription: Python List of Paired Points, How to Find Points Along Line


code:
from itertools import cycle
from operator import methodcaller
methods = cycle((methodcaller('upper'), methodcaller('lower')))
''.join([next(methods)(c) if c.isalpha() else c for c in sample])

rawDescription: Having trouble with whitespace and strings in a function


code: l == ['cheesecake', 13]

rawDescription: How to select only integers in a list of strings/integers?

description: Select only integers in a list of strings/integers


code:
from __future__ import print_function
debug = print

rawDescription: Alias a function in Python

description: Alias a function in Python


code:
css_panel = driver.find_element_by_id("panel_css")

code_mirror_element = css_panel.find_element_by_css_selector(".CodeMirror")
driver.execute_script("arguments[0].CodeMirror.setValue(arguments[1]);",
                      code_mirror_element,
                      "test")

rawDescription: ElementNotVisibleException: Message: Element is not currently visible... selenium (python)


code:
response = requests.get(url, params=params)
results = response.json()

rawDescription: Exception Value: list indices must be integers, not str


code:
l = zip(*data)    # swap rows and columns - it's easier to work this way
from pprint import pprint
pprint(l)
result = []
for row in l[1:]:
    result.append({row[0] : [{l[0][i] : row[i]} for i in range(1, len(row))]})
pprint(result)

rawDescription: How can I match values from first row of array with values from first column to create a json?

description: Match values from first row of array with values from first column to create a json


code: cv.HoughCircles(processed, storage, cv.CV_HOUGH_GRADIENT, 2, 100.0, 30, 150,100,140)

rawDescription: What are the correct usage/parameter values for HoughCircles in OpenCV for Iris detection?