code:
reader = csv.reader(self.request.get('file').file)

self.response.headers['Content-Type'] = 'text/plain'
for row in reader:
    self.response.out.write(str(row) + "\n")

rawDescription: CSV parsing of uploaded file

description: CSV parsing of uploaded file


code:
statement = "cypher query above ^"
parameters = {}
response = graph.cypher.post(statement, parameters)

rawDescription: How to perform an atomic update on relationship properties with Py2neo

description: Perform an atomic update on relationship properties with Py2neo


code:
from collections import namedtuple
import csv

Person = namedtuple('Person', ('name', 'gender', 'occurences')) # create our type

def main():
    filename = 'yob' + input('Enter year: ') + '.txt'
    with open(filename, newlines="") as f: # parameters differ a bit in Python 2
        reader = csv.reader(f) # the reader handles splitting the lines for you
        lst = [Person(*row) for row in reader]

rawDescription: Objects/classes/lists Python

description: Objects/classes/lists Python


rawDescription: How to use multiprocessing for grid search (parameter optimization) in Python

description: Use multiprocessing for grid search (parameter optimization) in Python


code: print(u'\N{COPYRIGHT SIGN} \N{TRADE MARK SIGN} \N{REGISTERED SIGN}')

rawDescription: Python Regex and the Copyright Symbol

description: Python Regex and the Copyright Symbol


rawDescription: Simple Django queryset __icontains search that will find most specific elements first


code: commands = {}

rawDescription: Automatically registering "commands" for a command line program in python


code:
from collections import defaultdict

class UnionFind:
    def __init__(self):
        self.leaders = defaultdict(lambda: None)

    def find(self, x):
        l = self.leaders[x]
        if l is not None:
            l = self.find(l)
            self.leaders[x] = l
            return l
        return x

    def union(self, x, y):
        lx, ly = self.find(x), self.find(y)
        if lx != ly:
            self.leaders[lx] = ly

    def get_groups(self):
        groups = defaultdict(set)
        for x in self.leaders:
            groups[self.find(x)].add(x)
        return groups

rawDescription: Python list comparison to create trees

description: Python list comparison to create trees


code:
a = "A01     5729384 5730870 Bra1000071      117     -       5729384 5730870 255,0,0 4       281,252,145,229 0,380,1030,1257"
a = a.split()
add_num = list(map(int,a[-1].split(',')[1:]))   #split with whitespace and taken last element, removed 0 and using map to convert them to int
for i in range(len(add_num)):
    print(" ".join([b[0]] + [str(int(b[1])+sum(add_num[:i+1]))] + b[2:]))

rawDescription: how to add a specific value to a column iteratively in python

description: Add a specific value to a column iteratively in python


code: list(fcn())

rawDescription: Is there a simpler construct for Python map(None, fcn())?


rawDescription: Converting dictionaries to list sorted by values, with multiple values per item


rawDescription: How to read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python

description: Read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python


code:
from datetime import datetime
dt = datetime(2015, 2, 11)
dt
dt.replace(month=dt.day, day=dt.month)

rawDescription: Convert a datetame object to the correct date (MM-DD-YYYY to DD-MM-YYYY)


code:
def my_view(request):
    if 'user' in request.GET:
        user = request.GET['user']
    if 'comment' in request.GET:
        comment = request.GET['comment']

rawDescription: handling multiple query parameters in tastypie

description: Handling multiple query parameters in tastypie


code: datetime.date(year=d.year, month=((d.month % 3) + 1) * 3 + 1, day=1) - datetime.timedelta(days=1)

rawDescription: Getting the date of the last day of this [week/month/quarter/year]


rawDescription: Django: Download Image from URL, Resize it, append "small" to the end of the filename


code:
def __init__(self, number):
    self.number = number
    self.current = 1

rawDescription: Using an iterator in python?

description: Using an iterator in python


rawDescription: Fastet way to create 2D list from two 1D list in Python


code:
df1 = pd.DataFrame(np.random.normal(size=8).reshape(4,2),index=[1,2,3,4],columns=['a','b'])
df2 = pd.DataFrame(np.random.normal(size=8).reshape(2,4),index=['c','d'],columns=[5,6,7,8])
df1.join(df2.T.set_index(df1.index))

rawDescription: Dataframe columns from Dataframe rows in Pandas


code: [word for word in text.split() if not word.startswith("<") and not word.endswith(">")]

rawDescription: Match words that are not inside the characters < > using regular expressions


code:
from extension1 import Main

#define screen somehow
ext1 = Main(screen, ...)
ext1.Draw()

rawDescription: How to make the "screen" variable accessible to all scripts in python/pygame

description: Make the "screen" variable accessible to all scripts in python/pygame


code:
def transform(n):
    return lambda x: x + n
f = transform(3)
f(4) # is 7

rawDescription: Why are Python lambdas useful?

description: Why are Python lambdas useful


code:
def secondlat(lat1, arc):
    degrees_to_radians = math.pi/180.0
    lat2 = (arc-((90-lat1)*degrees_to_radians))*(1./degrees_to_radians)+90
    return lat2

rawDescription: Automatically center matplotlib basemap onto data


rawDescription: Python's pandas gives wrong weekday index for DatetimeIndex


code:
def __init__(self, start, end, foo, volume, high=foo, low=foo, last=foo):
    self.start = start
    self.end = end
    self.open = foo
    self.high = high
    self.low = low
    self.last = last
    self.volume = int(volume)

rawDescription: How to use the value of a non-default argument as the default value for a default argument in Python?

description: Use the value of a non-default argument as the default value for a default argument in Python


code:
import datetime
a = ('[19:49:40:680]', '[19:49:49:128]')
start = datetime.datetime.strptime(a[0][:-1]+"000", "[%H:%M:%S:%f")
end = datetime.datetime.strptime(a[1][:-1]+"000", "[%H:%M:%S:%f")
delta = end-start
ms = delta.seconds*1000 + delta.microseconds/1000
ms

rawDescription: Print Difference Between Time in Ms

description: Print Difference Between Time in Ms


code:
loop = asyncio.get_event_loop()
queue = asyncio.Queue()
# Connection coroutine
factory = lambda: StreamProtocol(loop, queue)
connection = loop.create_connection(factory, '127.0.0.1', '42')
# Consumer task
consumer = asyncio.ensure_future(consume(queue))
# Set up connection
loop.run_until_complete(connection)
# Wait until the connection is closed
loop.run_forever()
# Wait until the queue is empty
loop.run_until_complete(queue.join())
# Cancel the consumer
consumer.cancel()
# Let the consumer terminate
loop.run_until_complete(consumer)
# Close the loop
loop.close()

rawDescription: asyncio queue consumer coroutine

description: Asyncio queue consumer coroutine


rawDescription: Issue? selecting data between_time from DataFrame in pandas 0.17.1


code:
with open('text.txt', 'rU') as inputfile:
    thelist = [x.rstrip() for x in inputfile]

rawDescription: Stripping line edings before appending to a list?


rawDescription: How do I convert date to Day/Month/Year (20/Jan/2012) in python

description: Convert date to Day/Month/Year (20/Jan/2012) in python


code:
import json

customers_file = "customers.json"

customers_dict = {}

def load_customers(filename=customers_file):
    """ you hand this function a filename and it returns a dictionary of all customers """
    with open(filename, "r") as customers_json:
        return json.loads(customers_json.read())

def save_customers(customers_dict, filename=customers_file):
    """ you hand this function a dictionary and a filename to save the customers """
    with open(filename, "w") as customers_json:
        customers_json.write(json.dumps(customers_dict))

def add_customer():
    """ pretty much your existing code - just return a dictionary instead """
    print("by maing an account in our bank your sure to lose all you money\n")
    print("plss enter your name\n")
    newname = input("\n")
    print("plss enter an insecure 4 digit code that can be hacked by any one \n")
    newpin = int(input("\n"))
    print("pls enter the amount you want to loss i mean deposit\n")
    newamount = int(input("\n"))
    # return the values, so they can be used outside the function
    customer_dict = {"name":newname, "pin":newpin, "balance":newamount}
    return customer_dict

def get_customer_details(customers):
    import pprint
    customer_name = input("Get details for which customer?")
    pprint.pprint(customers[customer_name])

# load existing
customers_dict = load_customers()
# add new
new_customer = add_customer()
# add single customer to "master" dictionary
customers_dict[new_customer["name"]] = new_customer
# save all
save_customers(customers_dict)
# get customer details by name
get_customer_details(customers_dict)

rawDescription: How to store a user input permanently in python

description: Store a user input permanently in python


rawDescription: Strip common indentation from the beginning of each line similar to what pydoc help does with docstrings


code:
def uniq(fn):
    uniq_elems = OrderedDict()
    def handler(*args, **kwargs):
        uniq_elems.update(uniq_elems.fromkeys(fn(*args, **kwargs)))
        return uniq_elems.keys()
    return handler

rawDescription: Remove strings containing words from list, without duplicate strings


code:
import pyqtgraph as pg
pg.ScatterPlotItem

rawDescription: Python 3.3 pyqtgraph can't plot points

description: Python 3.3 pyqtgraph can't plot points


code:
def foo(arg1, arg2, src, dst=None):
    dst = dst if dst else src

rawDescription: Python - how to set default parameter equal to another parameter


code:
import pretty_csv
pretty_csv.pretty_file("test.csv", header=False, border=False, delimiter="|")

rawDescription: How to Pretty Print a CSV file in Python

description: Pretty Print a CSV file in Python


rawDescription: Using zip() to rotate a list

description: Using zip() to rotate a list


code: self.data[x*height + y]

rawDescription: In which format does PIL's putdata need the data to be?


code: data = [[float(f) for f in p.split()] for p in pnts]

rawDescription: Breaking an XML string into three floats


code:
url(r'^login/$',
    auth_views.login,
    {'template_name': 'registration/login.html',
     'redirect_field_name': 'next'},
    name='auth_login'),

rawDescription: Dynamic login/logout URLs in Django

description: Dynamic login/logout URLs in Django


code:
from py4j.protocol import Py4JError

try:
    sqlContext.dropTempTable("df")
except Py4JError:
    pass

rawDescription: How to release a dataframe in spark?

description: Release a dataframe in spark


code:
import xml.etree.ElementTree as ET

tree = ET.parse('file1.xml')

root = tree.getroot()

with open('ac4.vhd', 'w+') as fd:
    fd.write('Registers\n')
    for node in root:
        if node.tag == 'Module':
            for sub_node in node:
                fd.write('{0}\n'.format(sub_node.get('name')))
                for child in sub_node:
                    fd.write('\t{0}\n'.format(child.get('name')))

rawDescription: How can I display the child element of a node from an xml file, in python?

description: Display the child element of a node from an xml file, in python


code:
td = soup.find("td")
td.get_text()

rawDescription: How can I remove all different script tags in BeautifulSoup?

description: Remove all different script tags in BeautifulSoup


code:
import serial.tools.list_ports_windows
devices = serial.tools.list_ports_windows.comports()

rawDescription: how to find all serial devices ? (COM*)

description: Find all serial devices ? (COM*)


code:
def script_running(self, script):
    """Return True if the script is running, False otherwise."""

rawDescription: Docstrings - one line vs multiple line

description: Docstrings - one line vs multiple line


code:
import pickle
f = open('my_classifier.pickle', 'wb')
pickle.dump(classifier, f)
f.close()

rawDescription: Save Naive Bayes Trained Classifier in NLTK


code:
def on_radiobutton(var, index):
    value = var.get()
    color = {"in": "green", "out": "red", "unassigned": "yellow"}
    self.canvas.itemconfigure(index, fill=color[value])

rawDescription: Python - arrays of tkinter widgets changing with radiobutton clicks


rawDescription: What is the difference between `super(...)` and `return super(...)`?


rawDescription: Xpath query 'like' substitution

description: Xpath query 'like' substitution


code: query = """SELECT element FROM table2 WHERE id IN (%s) """ % ",".join(['%s'] * len(results))

rawDescription: Retrieving and selecting binary values from Mysql with Python 3


code:
from foo import a,b
a
b

rawDescription: How do I use a python file I created in the interpretor?

description: Use a python file I created in the interpretor


code:
keys = ['a', 'b', 'c']
lst = [10, 5, 50]
collections.OrderedDict(zip(keys, lst))

rawDescription: Inserting value in orderedict by index?

description: Inserting value in orderedict by index


rawDescription: Getting Ipython QtConsole's current config infomation in it's interactive shell


code:
df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')
df

rawDescription: Nested List to Pandas Dataframe with headers


rawDescription: Coverting Hex array to Decimal in Python


code:
d = my_row.asDict()
d["value"] = [Row(value=x.value) for x in  my_row.value]
Row(**d)

## Row(id=1, value=[Row(value='value1'), Row(value='value2')])

rawDescription: Iterating List of SQL.Row with PySpark

description: Iterating List of SQL.Row with PySpark


rawDescription: Print single word from Parsed Json text

description: Print single word from Parsed Json text


code:
a = SomeAbstractClass()
c = ConcreteSubclass()
c.this_method_must_be_overridden()

rawDescription: Python abstract classes - how to discourage instantiation?


code:
class MyDelegate(QtGui.QItemDelegate):

    def createEditor(self, parent, option, index):
        return QtGui.QSpinBox(parent)

delegate = MyDelegate()
table.setItemDelegate(delegate)

rawDescription: How validate a cell in QTableWidget?

description: How validate a cell in QTableWidget


code: uncertainty[..., :3] = numpy.uint8(data_property * 255)[..., np.newaxis]

rawDescription: Assign same value to different ndarray indices - Python


code:
def MetadataMixin(cls_name):
    """Mixin class that provides metadata-fields and methods"""
    person_role_cls_name = 'Person%sRole' % cls_name
    person_role_cls = Base._decl_class_registry[person_role_cls_name]

    class Mixin(object):
        # ...
        persons = association_proxy('persons_roles', 'person',
                                    creator=person_role_cls)
    return Mixin

rawDescription: SQLAlchemy: Multiple Inheritance with dynamic 'association_proxy' creator function


code:
mkdir("c:/users/me/desktop/new_dir")  # for Windows
mkdir("/home/users/me/Desktop/new_dir") # for Linux

rawDescription: How to create directory in specified path?

description: Create directory in specified path


rawDescription: Efficiently parsing text file for datetimes


code:
B=plt.boxplot(data)
[item.get_ydata() for item in B['whiskers']]

rawDescription: Obtaining values used in boxplot, using python and matplotlib


code:
example_dictionary = {}
for item in root_values:
    example_dictionary.setdefault(item['name'], []).append(item['value'])

rawDescription: Initialize List to a variable in a Dictionary inside a loop


code:
self.m = MessagesUpdateThread()
QtCore.QObject.connect(self.m, QtCore.SIGNAL("updateMessages()"), self.updateMessages)
self.m.start()

rawDescription: Message displaying in QListWidget/View on boolean condition


code: iprint = logging.warning

rawDescription: What's an easy way to implement a --quiet option in a python script


code:
def increment(x):
    return x+1

map(increment,[1,2,3]) # python2 `map`, for brevity
Out[3]: [2, 3, 4]

rawDescription: Treating function as an object in Python


code:
from sklearn import preprocessing
le = preprocessing.LabelEncoder()

# training data
train_x = [0,1,2,6,'true','false']
le.fit_transform(train_x)
# array([0, 1, 1, 2, 4, 3])

# transform some new data
new_x = [0,0,0,2,2,2,'false']
le.transform(new_x)
# array([0, 0, 0, 1, 1, 1, 3])

# transform data with a new feature
bad_x = [0,2,6,'new_word']
le.transform(bad_x)
# ValueError: y contains new labels: ['0' 'new_word']

rawDescription: How to pre-process new instances for classification, so that the feature encoding is the same as the model with Scikit-learn?

description: Pre-process new instances for classification, so that the feature encoding is the same as the model with Scikit-learn


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

# Sample data. You can get yours with np.genfromtxt('/path/to/performance.dat')
data1 = np.random.rand(20,20)*2
data2 = np.random.rand(20,20)*2
data3 = np.random.rand(20,20)*2

fig = plt.figure(figsize=(9,3))

bottom,top,left,right = 0.2,0.9,0.1,0.85
fig.subplots_adjust(bottom=bottom,left=left,right=right,top=top)

# fancy new colormap, just because...
plt.viridis()

# Add the 3 subplots
ax1 = fig.add_subplot(131)
ax2 = fig.add_subplot(132)
ax3 = fig.add_subplot(133)

# Plot the data
for ax,data in zip(fig.axes,[data1,data2,data3]):
    p=ax.pcolor(data,vmin=0,vmax=2)
    # xlabel on all subplots
    ax.set_xlabel(r"$\log \, \sigma_1$", size=28)

# ylabel only on the left
ax1.set_ylabel(r"$\log \, \sigma_2$", size=28)

# add_axes takes (left,bottom,width,height)
# height is just top-bottom
cax = fig.add_axes([right+0.05,bottom,0.03,top-bottom])
fig.colorbar(p,cax=cax)

plt.show()

rawDescription: Creating a heatmap without a colorbar in matplotlib


code: Optional('alpha') & Optional('beta') & Optional('gamma')

rawDescription: pyparsing matching any combination of specified Literals

description: Pyparsing matching any combination of specified Literals


rawDescription: Scraping data from a dynamic web database with Python


code:
{'group': '<group_name>',
 'name': '<filename>',
 'links': '1',
 'date': '<modified_date>',
 'time': '<modified_time>',
 'owner': '<user_name>',
 'permissions': '-rw-rw-r--',
 'size': '<size>'}

rawDescription: python subprocess output to list or file

description: Python subprocess output to list or file


rawDescription: Detect int32 overflow using 0xFFFFFFFF masking in Python?


code:
n_rings = 20
n_angles = 20
base_points = .9
increase_per_level = 1.1

rawDescription: Method to uniformly randomly populate a disk with points in python


code:
import numpy as np

def func2a(x, y):
    return np.where(x>y,x+y,x-y)

def func2b(x, y):
    ind=x>y
    z=np.empty(ind.shape,dtype=x.dtype)
    z[ind]=(x+y)[ind]
    z[~ind]=(x-y)[~ind]
    return z

def func2c(x, y):
    # x, y= x[:, None], y[None, :]
    A, L= x+ y, x<= y
    A[L]= (x- y)[L]
    return A

N=40
x = np.random.random(N)
y = np.random.random(N)

xx = x[:, np.newaxis]
yy = y[np.newaxis, :]

rawDescription: Broadcasting a python function on to numpy arrays


code:
df['match'] = df.apply(lambda x: len(set(x)) == 1, axis=1).astype(int)
df

rawDescription: Checking column values in python panda

description: Checking column values in python panda


code:
import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array[my_array > 255] = 255

rawDescription: How to truncate the values of a 2D numpy array

description: Truncate the values of a 2D numpy array


code: df = df.drop('ID', axis=1)

rawDescription: Python pandas dataframe- remove columns from header


code:
import re
with open("FirstMondayArticle.html") as f, open("twoVoweledWordList.txt", "w") as out:
    two_vowels = re.compile(r".*[aeiou].*[aeiou].*", re.I)
    non_word = re.compile(r"\W+", re.U)
    for line in f:
        for word in non_word.split(line):
            if two_vowels.match(word):
                print(word)
                out.write("{}\n".format(word.rstrip()))

rawDescription: trying to print to a text file with words that only have two or more occurring vowels

description: Trying to print to a text file with words that only have two or more occurring vowels


code:
l3 = ['a'] + [''] * 999
timeit(lambda:l3.count('') == len(l3))
timeit(lambda:l3 == l2)

rawDescription: in python which would be the fastest way to compare / test with an lists

description: In python which would be the fastest way to compare / test with an lists


code:
re.split(r'\s*,\s*', string)
#          ^- zero or more whitespace incl. tabs and newlines
# the r'' syntax preserves the backslash from being interpreted
# as escape sequence

rawDescription: Splitting a string via regex problems

description: Splitting a string via regex problems


code:
import shutil
shutil.copyfile(src, dst)

rawDescription: How to ensure a file is closed for writing in Python?

description: Ensure a file is closed for writing in Python


code: import d

rawDescription: Confused by python package scoping

description: Confused by python package scoping


rawDescription: Pygame screen width

description: Pygame screen width


code:
df = df.sort("timestamp")
cluster = (df["timestamp"].diff() > pd.Timedelta(minutes=30)).cumsum()
dfs = [v for k,v in df.groupby(cluster)]
for clust in dfs:
    print(clust)

rawDescription: How to Partition Pandas DataFrame using DateTime


code:
def modFact(k,n):
    #computes k! mod n
    p = 1
    for i in range(1,k+1):
        p = (p*i) % n
    return p

def isPrime(n):
    return n == 1+ modFact(n-1,n)

rawDescription: How can I work out how long a factorial will take in Python?

description: Work out how long a factorial will take in Python


rawDescription: Custom dictionary lookup in Python

description: Custom dictionary lookup in Python


code:
import pandas as pd
index=pd.date_range('2011-1-1 00:00:03', '2011-12-31 23:50:03', freq='10min')
df=pd.DataFrame(np.random.rand(len(index),3),index=index)
df2 = df.groupby(lambda x: x.month)
for key, group in df2:
    group.plot()

rawDescription: Plot groupby data by month

description: Plot groupby data by month


code:
if screen_width == 400:
    width = 18

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code:
u = u'\u6211'      # Unicode for 我
u.encode('big5hkscs')

rawDescription: Generate character images with a font whose name cannot be correctly decoded


code:
for k, v in d.items():
    if v: # will be False for any empty list
        print(k.split(".")[0])
        print([s.split(".")[0] for s in v])
7
['8']
4
['3', '6']

rawDescription: How to save JSON string into CSV or TXT in Python?

description: Save JSON string into CSV or TXT in Python


rawDescription: How to use distinct with pipeline in mongodb using python

description: Use distinct with pipeline in mongodb using python


code:
with open("y.txt") as inf:
    y = pickle.load(inf)

rawDescription: Python - write symbolic expression (sympy) to txt file


rawDescription: Check if multple variables greater than zero in python


code:
query = (models.MyModel.objects.all()
                   .extra(select={'order_me': """CASE WHEN month*31+day < %s*31+%s
                                                    THEN (12+month)*31+day
                                                    ELSE (month)*31+day
                                               END""" % (start_month, start_day) })
                   .extra(order_by=['order_me'])
                   .extra(where=['order_me < (12 + %s) * 31 + %s' % (end_month,
                                                                     end_day)]))

rawDescription: Applying an arbitrary sort to Django ORM querysets


code: pd.concat([df, dummies[['cc_US', 'cc_UK']]], axis=1)

rawDescription: How to generate dummy variables for only specific values in a column?

description: Generate dummy variables for only specific values in a column


rawDescription: Merge 2 lists at every x position

description: Merge 2 lists at every x position


code:
it1 = iter(string1)
it2 = iter(string2)
count_diffs = 0
c1 = next(it1, None)
c2 = next(it2, None)
while True:
    if c1 != c2:
        if count_diffs: return False
        count_diffs = 1
        c1 = next(it1)
    else:
        try:
            c1 = next(it1)
            c2 = next(it2)
        except StopIteration: return True

rawDescription: Returns True if the two strings only differ by one character


code:
"|{:>22}|".format("Niki Lauda")
"|{:^22}|".format("Niki Lauda")

rawDescription: Tabbing in Python?

description: Tabbing in Python


code: result = [{'event':p, 'i':i, 'j':j} for p,(i,j) in zip(pargs, indices)]

rawDescription: Building up a list of dictionaries from a few lists in Python


code:
y = 1
f = lambda x, y=y: x + y
f(1)
y = 2
f(1)

rawDescription: Assign variable to local scope of function in Python


code:
#input-encoding: utf-8
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
  name = "ABC",
  packages = ["ABC"],
  package_dir = { "ABC" : "." },
  ext_package = "ABC",
  cmdclass = {'build_ext': build_ext},
  package_data = { ".": [ "C.dll"] },
  ext_modules = [ Extension("B", sources="B.pyx", libraries="C" ) ]
)

rawDescription: Install mixture of extension module. pure python module and shared libraries with distutils


rawDescription: NumPy: 2D array from a list of arrays and scalars


rawDescription: Python - how to parse this with regex correctly? its parsing all the E.164 but except the local format


code:
import re
a=['from src1 to dest2','from src3 to dest4','from src5 to dest6']
b=[['destb','dest2'],['destd','loc4'],['destf','dest6'],['desth','dest8']]
result = []
for x in a:
    result.append(x)
    for i,j in b:
            if j in result[-1]:
                    result[-1] = re.sub(j,i,result[-1])
result

rawDescription: Python: Compare list of strings to list of tuples, and create a new list based on match or no match


rawDescription: Pickle versus shelve storing large dictionaries in Python


rawDescription: Adding one element from a list to next,after that to next etc


code:
sub_app = db.session.query(db.func.count(Instance.id).label('app')
).filter(db.not_(db.or_(Instance.name == 'erf', Instance.tiername == 'wer')), Instance.type == 'app'
).subquery()

sub_adc = db.session.query(db.func.count(Instance.id).label('adc')
).filter(db.not_(db.or_(Instance2.name == 'visq', Instance2.name == 'werf')), Instance2.type == 'adc'
).subquery()

out = db.session.query(sub_app.c.app, sub_adc.c.adc).all()

rawDescription: Convert SQL to SQL alchemy

description: Convert SQL to SQL alchemy


code:
def recursive_bin(i):
    if i == 0:
        return ''
    elif i < 0:
        return '-' + recursive_bin(-i)
    else:
        return recursive_bin(i>>1) + str(i&1)

rawDescription: Python: Recursively convert int to binary string


code:
from configuration import app
from core.expense.models import user # added my model here

alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = app.config['SQLALCHEMY_DATABASE_URI']
engine = engine_from_config(
    alembic_config,
    prefix='sqlalchemy.',
    poolclass=pool.NullPool)

rawDescription: Alembic --autogenerate producing empty migration


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                horizontalalignment='right', verticalalignment='bottom')
plt.show()

rawDescription: Python/Matplotlib - How to put text in the corner of equal aspect figure


code:
for k, v in t_dict.viewitems():
    v.difference_update(values_to_remove.get(k, ()))

rawDescription: Remove values from lists of values in a dictionary


code:
import pdb
import sqlite3
con = sqlite3.connect(':memory:')
cur = con.cursor()
cur.execute('create table abc (id int, sal int)')
cur.execute('insert into abc values(1,1)')
cur.execute('select * from abc')
data = cur.fetchone()
print (data)
pdb.set_trace()
x = "y"

rawDescription: How to browse an in memory sqlite database in python

description: Browse an in memory sqlite database in python


code: (some_function(i) for i in seq)

rawDescription: When does using list comprehension in Python become inefficient?


code:
information = [['U1', 'b1', 12], ['U1', 'b2', 15], ['U1', 'b3', 1], ['U2', 'b1', 6], ['U2', 'b2', 7], ['U2', 'b3', 43]]
key = itemgetter(0)
{tuple(best[:2]): best[2]
              for key, group in groupby(sorted(information, key=key), key=key)
              for best in (max(group, key=itemgetter(2)),)}

rawDescription: Get the max value for given keys in a dictionary?


code:
def run_fabric_tasks(self, path_to_conf_file):
        cmd = 'fab update_workers copy_conf_to_worker:%s -H %s' % (path_to_conf_file, ",".join(self.hosts))
        result = local(cmd)
        deploy_workers(path_to_conf_file)
        return result

rawDescription: Fabric, @parallel and dynamically changing hosts


code:
from lxml import etree

def register_xpath_namespaces():
    fns = {
            'date':'http://exslt.org/dates-and-times',
            'dyn':'http://exslt.org/dynamic',
            'exsl':'http://exslt.org/common',
            'func':'http://exslt.org/functions',
            'math':'http://exslt.org/math',
            'random':'http://exslt.org/random',
            're':'http://exslt.org/regular-expressions',  # FOR REGEXP
            'set':'http://exslt.org/sets',
            'str':'http://exslt.org/strings'
    }
    for k,v in fns.iteritems():
        etree.FunctionNamespace(v).prefix = k

register_xpath_namespaces()

rawDescription: Can we add regular expression in scrapy .xpath()


code:
ax = fig.gca(projection = '3d')
ax.pbaspect = [2.0, 0.6, 0.25]

rawDescription: Setting aspect ratio of 3D plot

description: Setting aspect ratio of 3D plot


rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code:
proc = subprocess.Popen(['python', 'write_to_stdin.py'],  stdin=subprocess.PIPE)
proc.communicate('Hello?')

rawDescription: How do I make a python program give a command to a command shell?

description: Make a python program give a command to a command shell


code:
import dateutil.parser
first = dateutil.parser.parse(first)

rawDescription: How to read head and tail of CSV file with python

description: Read head and tail of CSV file with python


code: return (yield from whatever)

rawDescription: Pros and cons of using return (yield from some_function())


code:
class SomeDetailView(...):
     def get_queryset(self):
         queryset = super(SomeDetailView, self).get_queryset()
         # grab all named URL keyword arguments and
         # transform them into field lookup patterns.
         # Leave out slug and primary key keywords, though.
         filter_args = {
              k: v for k, v in self.kwargs.iteritems()
              if k not in (self.slug_url_kwarg, self.pk_url_kwarg)
         }
         if filter_args:
             queryset = queryset.filter(**filter_args)
         return queryset

rawDescription: Django url pattern for DetailView

description: Django url pattern for DetailView


code:
subscriptions = filters.get(word)
if subscriptions is not None:
    pass # TODO do something with subscriptions

rawDescription: Fastest way of checking for word in huge list of keywords - Python performance


rawDescription: cumcout groupby --- how to list by groups

description: Cumcout groupby --- how to list by groups


code:
[ln.split('=') for ln in txt.splitlines()]
vars = [ln.split('=') for ln in txt.splitlines()]

rawDescription: Parse a config-file with Python having more then one variable with the same name


code:
import datetime
date_string = '20151227135000'
date = datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S')
date.strftime('%H:%M')

rawDescription: how to convert long date into time

description: Convert long date into time


rawDescription: How to add a character to the end of every string in a list?

description: Add a character to the end of every string in a list


code:
# get all attributes of class C
vars = [classVar for classVar in dir(C) if not classVar.startswith('__')]

# iterate through all bases:
for base in C.__bases__:
    for attr in vars:
        if attr in base.__dict__:
            print("Attribute: '{}' defined in {}".format(attr, base))

rawDescription: How would I find where a function originates in source code?


code:
a = np.asarray(a)
b = np.asarray(b).squeeze()
b.shape

rawDescription: SciPy interpolation ValueError: x and y arrays must be equal in length along interpolation axis


code:
binom_test = np.vectorize(stats.binom_test)
result = binom_test(x, x+y)

rawDescription: Given two numpy arrays of same size, how to apply a function two each pair of elements at identical position?


code:
import sys
print('ERROR!!!!!', file=sys.stderr)

rawDescription: Practical difference between keyword "print" and function "print" in Python


code:
F
LFRRFL
LLFRRFLRRLFRRFLL
LLLFRRFLRRLFRRFLLRRLLFRRFLRRLFRRFLLL

rawDescription: Trying to understand the Levy Curve (fractal)


code:
import csv

with open("table.csv", "rU") as f:
    reader = csv.reader(f)
    next(reader)
    output = sorted(row[7] for row in reader)

rawDescription: Getting a column into an array from excel in python


rawDescription: Removing one or multiple keys from a dictionary


code:
from statistics import mean

with open('test.txt') as f:
    data = [float(line.split()[-1]) for line in f if line.strip().startswith('X-DSPAM-Confidence:')]
    print(mean(data))

rawDescription: slicing and dicing of a text file in python

description: Slicing and dicing of a text file in python


rawDescription: Pull a list of objects with foreign key in python


code:
l = [1, 2, 3, 'foo', 'bar', 4, 8, -10, 'baz']
import numbers
sorted(l, key=lambda x: (isinstance(x, numbers.Number), x))

rawDescription: Sorting hybrid lists in Python

description: Sorting hybrid lists in Python


rawDescription: one liner for conditionally replacing dictionary values

description: One liner for conditionally replacing dictionary values


code: f.close() # Notice the parenthesis

rawDescription: f.readline() != '0' even if reading a line containing only 0

description: F.readline() != '0' even if reading a line containing only 0


code:
import random
sorted(l, key=lambda *args: random.random())

rawDescription: Shuffle in Python

description: Shuffle in Python


code:
s = '\xc1\x58\xa8\x54'
import struct
struct.unpack('>i', s)

rawDescription: Two's complement of Hex number in Python


code:
def get_val(n, last):
    if n < 5:
        for k in range(-1, 1+1, 1):
            yield from get_val(n+1, last+[k])
    else:
        yield last

get_val(0, [])

rawDescription: Simple recursion with yield?

description: Simple recursion with yield


rawDescription: Serialize an already serialized json string?


code: {{ message | safe }}

rawDescription: Warning message should contain a LINK to a next page


rawDescription: Read multiple lines in a single excel cell using python


code: Foo.immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


code:
def decompress(compressed):
    return ''.join(decompress_gen(compressed))

def decompress_gen(compressed):
    start = 0
    i = 0
    while i < len(compressed):
        curr = compressed[i]
        i += 1
        if not(curr in string.digits):
            num = 1 if start + 1 == i else int(compressed[start:i-1])
            yield "".join(curr * num)
            start = i

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


code:
import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('screenshot.jpg', 'jpg')

rawDescription: Is there any better way to capture the screen than PIL.ImageGrab.grab()?


code: ['bar', 'world']

rawDescription: Trying to pull useful info blocks from text file


code:
import base64
import json
import urlfetch

base64string = base64.encodestring('%s:%s' % (key, secret_ley))[:-1]
http_headers = {'Authorization' : 'Basic %s' % base64string}

response = urlfetch.fetch(url='https://api.picloud.com/servers/list/',
      payload={},  #POST DATA if method was urlfetch.POST
      method=urlfetch.GET,
      headers=http_headers)
data = json.loads(response.content)    #{"servers": ["https://api.picloud.com/"]}

rawDescription: Call a library uploaded in PiCloud from GAE?


code: my_list2, my_list1 = zip(*my_list)

rawDescription: Splitting a nested list into two lists

description: Splitting a nested list into two lists


code:
import mymodule
import atexit

# call mymodule.unload('param1', 'param2') when the interpreter exits:
atexit.register(mymodule.unload, 'param1', 'param2')

rawDescription: Detect when a Python module unloads

description: Detect when a Python module unloads


code:
feed = RssFeed(url='http://url/for/feed')
session.add(feed)

rawDescription: Using list as a data type in a column (SQLAlchemy)


rawDescription: Django Model DateField to_python

description: Django Model DateField to_python


code:
#list of tuples in python3.x.
zzz = list(zip(xxx,yyy)) #equivalent to zip(xxx,yyy) in python2.x
                         #will work in python2.x, but will make an extra copy.
                         # which will be available for garbage collection
                         # immediately

rawDescription: Convert lists into 'transposed' list

description: Convert lists into 'transposed' list


rawDescription: Convert pandas freq string to timedelta

description: Convert pandas freq string to timedelta


rawDescription: python: Using the choice box to get data besides getString()

description: Python: Using the choice box to get data besides getString()


rawDescription: If dictionaries aren't ordered, why do two dictionaries with the same key names return values in the same order?


code:
stack
over
flow

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


code: someobject.lastUpdate = datetime.now

rawDescription: Fix "unsupported date format" when marshaling data from rest endpoint


code:
parser.def_mapping(foo={"A":CONST_A, "B":CONST_B},
                   conv={"int":int,"float":float})

rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


code:
coords = np.ogrid[0:2, 0:3]
checkerboard = (coords[0] + coords[1]) % 2 == 0
checkerboard

rawDescription: Slicing Pandas DataFrame with a Checkerboard Pattern


rawDescription: Filtering a subgraph in graph-tool

description: Filtering a subgraph in graph-tool


rawDescription: how to make a function that checks a list of 20 digits

description: Make a function that checks a list of 20 digits


rawDescription: simple regex for following string

description: Simple regex for following string


code:
import codecs
import numpy as np

fh = open('utf_16_le_with_bom.csv', 'rb')
efh = codecs.EncodedFile(fh, data_encoding='ascii', file_encoding='utf-16')
a = np.genfromtxt(efh, delimiter=',')
fh.close()

print("a:")
print(a)

rawDescription: numpy.genfromtxt csv file with null characters

description: Numpy.genfromtxt csv file with null characters


code: pixel = im.getpixel(0,0)

rawDescription: Python: Serial Transmission

description: Python: Serial Transmission


rawDescription: How can I keep this Pandas column type as datetime when using MultiIndex?

description: Keep this Pandas column type as datetime when using MultiIndex


code:
def load_results(base):
    """try to unpickle and return data from file if it exists and is not
    corrupted

    return an empty dictionary if it doesn't exists
    """
    data_file = get_pdata_path(base, 1)
    try:
        with open(data_file, _PICK_LOAD) as stream:
            return pickle.load(stream)
    except:
        return {}

rawDescription: How does pylint remember scores from previous runs?


code:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)

        self.button_layout = QtGui.QHBoxLayout()
        self.button_layout.addStretch()
        self.button_layout.addWidget(self.button)
        self.button_layout.addStretch()

        self.grid = QtGui.QGridLayout(self)

        self.grid.addLayout(self.button_layout, 0, 0)
        self.grid.addWidget(self.lineEdit, 1, 0)
        self.grid.addWidget(self.textEdit, 2, 0)

        # Alternative using QVBoxLayout:
        #self.layout = QtGui.QVBoxLayout(self)
        #self.layout.addLayout(self.button_layout)
        #self.layout.addWidget(self.line_edit)
        #self.layout.addWidget(self.text_edit)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: Can't change size within layout

description: Can't change size within layout


code:
import itertools as it

d = [k+1 for k, L in
         ((k, len(list(g))) for k, g in it.groupby(data,key=lambda x:x//10))
     if L>=3]

rawDescription: Python: create a distribution from a list based on number of items that fall within certain ranges


code: [format(i + 1, '03d') for i in range(300)]

rawDescription: Creating list of defined number pattern

description: Creating list of defined number pattern


code:
def integrate(func, lo_x, hi_x):
    #... Stuff to perform the integral, which will need to evaluate
    # the passed function for various values of x, like this
    y = func(x)
    #... more stuff
    return value

rawDescription: Python: How to integrate a math function using only math module?


code:
A_sorted
B_sorted

rawDescription: sorting the elements in the list

description: Sorting the elements in the list


rawDescription: Check whether each row of a matrix is in another matrix [Python]


code:
d1 = datetime.now()
d2 = datetime.now()
delta = d2 - d1
delta
delta.seconds
delta.microseconds

rawDescription: Paradoxical time intervals in Python

description: Paradoxical time intervals in Python


code:
def application(environ):
    return (status,
            headers,
            ['content block 1',
             'content block 2',
             'content block 3'])

rawDescription: WSGI: what's the purpose of start_response function


code:
if right[0]<replace.last_index:
    for i in range(replace.last_index-right[0]):
        yield placeholder

rawDescription: Generator which leaves a placeholder at the beginning and at the end of the input iterator intact


rawDescription: python alexa result parsing with lxml.etree

description: Python alexa result parsing with lxml.etree


rawDescription: Extending dictionary list values in a certain way


code:
mySound.setLoop(True)
mySound.play()

rawDescription: How to keep playing a sound at a given frequency and volume in Python?

description: Keep playing a sound at a given frequency and volume in Python


code:
class A(object):
    def __get__(self, cls, instance):
        print(cls, instance)
        return self

class B(object):
    a = A()

b = B()
c = b.a

rawDescription: callable object as method of a class - Can I get `self` to be the class that owns the method?

description: Callable object as method of a class - Can I get `self` to be the class that owns the method


code:
target = defaultdict(list)
for key, values in original.items():
    for value in values:
        target[value].append(key)

rawDescription: What is the pythonic way to reverse a defaultdict(list)?


code:
class TestingRoutes(WebTestCase, unittest.TestCase):

    APPLICATION = application()

    def tearDown(self):
        os.environ['USER_EMAIL'] = ''
        os.environ['USER_IS_ADMIN'] = ''

    #AdminIndex .....
    def test_adminindex_no_user(self):
        #No user: redirect to login form
        response = app.get( url_map['adminindex'] )
        self.assertRedirects(response)

    def test_adminindex_user(self):
        os.environ['USER_EMAIL'] = 'info@example.com'
        response = app.get( url_map['adminindex'] )
        self.assertForbidden(response)

    def test_adminindex_admin(self):
        os.environ['USER_EMAIL'] = 'info@example.com'
        os.environ['USER_IS_ADMIN'] = '1'
        response = app.get( url_map['adminindex'] )
        self.assertOK(response)

rawDescription: Google App Engine: Webtest simulating logged in user and administrator


code:
from numpy import arange, array, ones, r_, zeros
from numpy.random import randint

def gen_tst(m, n):
    a= randint(1, n, m)
    b, c= arange(a.sum()), ones((m, n), dtype= int)* 999
    return a, b, c

def basic_1(a, b, c):
    # some assumed basic iteration based
    n= 0
    for k in xrange(len(a)):
        m= a[k]
        c[k, :m], n= b[n: n+ m], n+ m

def advanced_1(a, b, c):
    # based on Svens answer
    cum_a= r_[0, a.cumsum()]
    i= arange(len(a)).repeat(a)
    j= arange(cum_a[-1])- cum_a[:-1].repeat(a)
    c[i, j]= b

def advanced_2(a, b, c):
    # other loopless version
    c[arange(c.shape[1])+ zeros((len(a), 1), dtype= int)< a[:, None]]= b

rawDescription: fastest way to arrange data in python numpy based on list

description: Fastest way to arrange data in python numpy based on list


rawDescription: How can I speed up an iteration in python?

description: Speed up an iteration in python


code:
with open("your_file_name", "w") as dumpfile:
    dumpfile.write(str(RSEM))

rawDescription: Replace dict key by value of other dict

description: Replace dict key by value of other dict


code: con.execute("insert into person(firstname) values (?)", ("Joe",))

rawDescription: Protecting against SQL injection in python


code: db.unwind.save({field:['A','B']} )

rawDescription: $unwind with group and count

description: $unwind with group and count


rawDescription: save dataframe to excel when each value is a dict

description: Save dataframe to excel when each value is a dict


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

rawDescription: Renaming a django model class-name and corresponding foreign keys with south, without loosing the data


code:
translation = range(26)
random.shuffle(translation)  # ②
random_string = ''.join(chr(
  translation[random.randint(0, random.randint(1, 25))] + ord('a'))  # ①
  for _dummy in range(1000))

rawDescription: Deterministic and non uniform long string generation from seed


code:
if 'postVenue' in request.POST:
    form = NewVenueForm(request.POST)
    required = 'postVenue' in request.POST
    form.fields['title'].required = required
    form.fields['category'].required = required
    # do this for every form field

elif 'mainForm' in request.POST:
    form = NewVenueForm(request.POST)

rawDescription: Django form with two submit buttons . . . one requires fields and one doesn't


code:
import itertools

def HammingDistance(string_1, string_2):
    assert len(string_1) == len(string_2)
    return sum(c1 != c2 for c1, c2 in zip(string_1, string_2))

def MotifCount(string1, substring, d):
    for i in range(len(string1) - len(substring) + 1):
        if HammingDistance(string1[i:i+len(substring)], substring) <= d:
            print(i)

MotifCount("CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT", "ATTCTGGA", 3)

rawDescription: How to optimize a python script which runs for 4**k times?

description: Optimize a python script which runs for 4**k times


code: #!/usr/bin/env python

rawDescription: Turn an application or script into a shell command


code: df.asfreq("D", method='bfill')

rawDescription: pandas's resample with fill_method: Need to know data from which row was copied?

description: Pandas's resample with fill_method: Need to know data from which row was copied


code:
class ElementRemovingTestCase(unittest.TestCase):
    def tearDown(self):
        self.removeElements()
        self.additionalTearDown()

class MyTestCase(ElementRemovingTestCase):
    def additionalTearDown(self):
        print('Tearing down {}'.format(self))

rawDescription: Calling a function after or before tearDown of each unit testcase


code:
html_sidebars = {
        '**': [
                 'localtoc.html',
                 'relations.html',
                 'searchbox.html',
                 # located at _templates/
                 'foo.html',
            ]

        }

rawDescription: How to edit Sidebar under Sphinx Alabaster theme

description: Edit Sidebar under Sphinx Alabaster theme


code:
import autocomplete_light
from django.forms import ModelForm, IntegerField

from error_tracking.models import Incident

autocomplete_light.register(Incident, search_fields=['incident_id'])

class IncidentForm(autocomplete_light.ModelForm):
    class Meta:
        model = Incident
        fields = ['incident_id', 'user_id', 'equipment_id', 'incident_category', 'incident_date_time_reported', 'incident_date_time_occurred', 'description']
    incident_id = IntegerField()

class Incident(models.Model):
       incident_id = models.IntegerField(primary_key=True)
       incident_date_time_reported = models.DateTimeField('incident reported', default=timezone.now)
       user_id = models.ForeignKey(User)
       incident_date_time_occurred = models.DateTimeField('incident occurred', default=timezone.now)
       clinical_sample = models.BooleanField(default=True)
       number_of_clinical_samples = models.IntegerField(default=0)
       sample_id_numbers = models.TextField(max_length=1000)
       equipment_id = models.ForeignKey(Equipment)
       incident_category = models.ForeignKey(Incident_Category)
       technician = models.TextField(max_length=1000)
       description = models.TextField(max_length=1000)
       action_taken = models.TextField(max_length=1000)
       open = models.BooleanField(default=True)

       def __str__(self):
               return self.incident_id

       class Meta:
               verbose_name_plural="Incident"

rawDescription: Created a modelform in django, primary key is missing


code: re.findall(r'(?<=@)\w+', inputtext)

rawDescription: extracting multiple instances regex python

description: Extracting multiple instances regex python


rawDescription: Python Open File path that changes dynamically


rawDescription: Optimize runtime of calling 'in' many times on same string


code: cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

rawDescription: Python: tf-idf-cosine: to find document similarity


rawDescription: How to map a function in pandas which compares each record in a column to previous and next records

description: Map a function in pandas which compares each record in a column to previous and next records


code:
import numpy as np
x = np.arange(25).reshape(5, 5)
y = np.arange(5) + 1000

rawDescription: Load data from file and normalize

description: Load data from file and normalize


code:
import re

with open('input.txt') as f:
    lines = f.read()

mat = re.sub(r'=([^"]\w*(?:(?:\\ )\w*)*)', r'="\1"', lines)  # Quote unquoted values
mat = mat.replace("\\ "," ").replace("\\\n","")              # Replace escaped spaces
mat = re.findall(r'(\w*)="(.*?)"', mat)                      # Extract pairs
for (k,v) in mat:                                            # Print pairs
    print('{} = "{}"'.format(k, v))

rawDescription: PyParsing: shell style space escape using backslash


code:
params = urllib.urlencode({"curpage": NUMBER})
urllib2.urlopen(YOUR_PAGE, params)

rawDescription: Parsing through multiple result pages using python


code:
def numberList(items):
     indexeditems = []
     number = 1
     for item in items:
         indexeditems.append(str((number, item)))
         number = number + 1
     return indexeditems

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

rawDescription: Python: Return list result problem in a function


code:
import re
header="Year    JAN    FEB    MAR    APR    MAY    JUN    JUL    AUG    SEP    OCT    NOV    DEC     WIN    SPR    SUM    AUT     ANN"
cols=re.findall("\s*[^\s]+",header)
delimiter=tuple([len(c) for c in cols])

rawDescription: Handling empty space in reading table from text file python


code:
instances = [{'a': 5, 'b': 3}, {'a': 7, 'b': 8},  {'a': -1, 'b': 19}]
primary_keys = ['a', 'b']
kw = {'a': 7, 'b': 8}
next(inst for inst in instances
          if all(inst[pkey] == kw[pkey] for pkey in primary_keys))

rawDescription: Find object in a list with multiple primary keys in Python


code:
person1 = PersonClient.objects.create(first_name='Person', last_name='One', gender='M')
person2 = PersonClient.objects.create(first_name='Person', last_name='Two', gender='F')
company = CompanyClient.objects.create(name='FastCompany', tax_no='4220')
company_ct = ContentType.objects.get_for_model(CompanyClient)
person_ct = ContentType.objects.get_for_model(person1) # works for instances too.
msg = Message.objects.create(sender_content_type=person_ct, sender_id=person1.pk, msg_body='Hey, did any of you move my cheese?')
MessageRecipient.objects.create(message=msg, recipient_content_type=person_ct, recipient_id=person2.pk)
MessageRecipient.objects.create(message=msg, recipient_content_type=company_ct, recipient_id=company.pk)
MessageRecipient.objects.count()

rawDescription: Generic many-to-many relationships

description: Generic many-to-many relationships


rawDescription: Type Unicode code points into Python CLI


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from kivy.config import Config
Config.set('graphics', 'fullscreen', '0')

from kivy.app import App

class TestApp(App):
    pass

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

rawDescription: How do I turn off fullscreen in Kivy?

description: Turn off fullscreen in Kivy


code:
# module.py

address_dict = {'address1':{'username':'abc', 'password':'123'}, 'address2':{'username':'xyz', 'password':'456'}}

# main.py

import module
print(module.address_dict)

rawDescription: Can I make a dictionary available to multiple python scripts?

description: Make a dictionary available to multiple python scripts


code: hosts = importlines()

rawDescription: Importing file data to a list from a function


code:
import numpy

def detect_twopeak_event(measurements, template):
    data = numpy.asarray(measurements) # convert to numpy array
    activations = numpy.convolve(
        data[:, 1],  # convolve over all "value" elements
        template)
    return activations.argmax()

rawDescription: Detecting regions in (x, y) data

description: Detecting regions in (x, y) data


code:
import pandas as pd
import random
import matplotlib.pyplot as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T #T for transpose

df.columns=['a','b']

df.plot(kind='line')

plt.legend(loc='upper left')

plt.show()

rawDescription: Use dataframe column names as labels in pylab.plot


code:
for name in sorted(user_scores):
    # get the highest score in the list
    average = sum(user_scores[name]) /float(len(user_scores[name]))
    print(name, "'s average from the last 3 scores is", average)

rawDescription: Using more than the last 3 scores to analyse data; also repeating analysis?


code:
import glob
import multiprocessing
from functools import partial
from threading import Thread

list_files = glob.glob("Protein/*.txt")

def Some_func(out_q, some_file):
    with open(some_file) as some:
        for lines in Some:
            #Do Something
            #edited_lines = func(lines)

            out_q.put(edited_lines)

def write_lines(q):
   with open(file_output) as output:
       for line in iter(q.get, None): # This will end when None is received
           output.write(line)

pool = multiprocessing.Pool(10) # Desired number of threads = 10
m = multiprocessing.Manager()
q = m.Queue()
t = Thread(target=write_lines, args=(q,))
t.start()
pool.map(partial(Some_func, q), list_files)
pool.close()
pool.join()
q.put(None)  # Shut down the writer thread
t.join()

rawDescription: Writing Errors in Multiprocessing Python


code:
Inserting
c = Character(character_description='c')
c2 = Character(character_description='c2')
m = Movie(movie_type ='action')

# link characters to movie
m.characters.append(c)
m.characters.append(c2)
# or
m.characters.extend([c,c2])

db.session.add(m)
# add characters
db.session.add(c)
db.session.add(c2)
# or
db.session.add_all([c,c2])
# commit
db.session.commit()

rawDescription: One-to-many Flask | SQLAlchemy

description: One-to-many Flask | SQLAlchemy


code:
df1['date2'] = pd.DatetimeIndex(df1['date1']).normalize()
pd.merge(df1, df2).head()

rawDescription: Joining dataframes with different datetime frequencies


code:
dout.values[np.triu_indices_from(dout)] = 0
dout

rawDescription: Transform dataframe to get co-author relationships


code:
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)

rawDescription: command CHOICE in DOS batch replacement/reproduction in python

description: Command CHOICE in DOS batch replacement/reproduction in python


rawDescription: How to get SGDClassifier to reflect uncertainty

description: Get SGDClassifier to reflect uncertainty


code:
class Foo(models.Model):
    # fields...

    def my_task_init(self):
        return mark_safe("") % self.id
    my_task_init.allow_tags = True
    my_task_init.short_description = _(u"Execute Task")

rawDescription: Django: How to call management custom command execution from admin interface?


code:
from parse import parse
def zero_or_more_string(text):
    return text

zero_or_more_string.pattern = r".*"
parse('hi "{:z}"', 'hi ""', { "z": zero_or_more_string })

rawDescription: Python parse empty string

description: Python parse empty string


code:
my_list = [['a'], ['a'], ['b'], ['c']]
remove_extras_and_sort(my_list)

rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code:
satisfiable(x ^ y)
satisfiable((x ^ y) & ~(x & ~y))

rawDescription: Solving Symbolic Boolean variables in Python


code:
from itertools import combinations

def partitions(s, r):
    """
    Generate partitions of the iterable `s` into subsets of size `r`.

    >>> list(partitions(set(range(4)), 2))
    [((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]
    """
    s = set(s)
    assert(len(s) % r == 0)
    if len(s) == 0:
        yield ()
        return
    first = next(iter(s))
    rest = s.difference((first,))
    for c in combinations(rest, r - 1):
        first_subset = (first,) + c
        for p in partitions(rest.difference(c), r):
            yield (first_subset,) + p

def partitions_with_remainder(s, r):
    """
    Generate partitions of the iterable `s` into subsets of size
    `r` plus a remainder.

    >>> list(partitions_with_remainder(range(4), 2))
    [((0, 1, 2, 3),), ((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]
    >>> list(partitions_with_remainder(range(3), 2))
    [((0, 1, 2),), ((1, 2), (0,)), ((0, 2), (1,)), ((0, 1), (2,))]
    """
    s = set(s)
    for n in xrange(len(s), -1, -r): # n is size of remainder.
        if n == 0:
            for p in partitions(s, r):
                yield p
        elif n != r:
            for remainder in combinations(s, n):
                for p in partitions(s.difference(remainder), r):
                    yield p + (remainder,)

rawDescription: Producing all groups of fixed-length combinations


code:
import sys
from PyQt4 import QtGui

class QCheckerDialog (QtGui.QDialog):
    def __init__ (self, parent = None) :
        super(QCheckerDialog, self).__init__(parent)

        checkBoxQGridLayout = QtGui.QGridLayout()
        for y in range(13):
            for x in range(9):
                currentQCheckBox = QtGui.QCheckBox('%d, %d' % (x, y))
                currentQCheckBox.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum))
                checkBoxQGridLayout.addWidget(currentQCheckBox, x, y)

        buttonQHBoxLayout  = QtGui.QHBoxLayout()
        applyQPushButton = QtGui.QPushButton('Apply')
        closeQPushButton = QtGui.QPushButton('Close')
        buttonQHBoxLayout.addWidget(applyQPushButton)
        buttonQHBoxLayout.addWidget(closeQPushButton)

        allQVBoxLayout = QtGui.QVBoxLayout()
        allQVBoxLayout.insertLayout(1, buttonQHBoxLayout)
        allQVBoxLayout.insertLayout(0, checkBoxQGridLayout)
        self.setLayout(allQVBoxLayout)

myQApplication = QtGui.QApplication(sys.argv)
myQQCheckerDialog = QCheckerDialog()
myQQCheckerDialog.show()
sys.exit(myQApplication.exec_())

rawDescription: Nested Layouts ... Drawn stacked not layered


code:
import cherrypy as cp
from cherrypy.wsgiserver import CherryPyWSGIServer
from cherrypy.process.servers import ServerAdapter

from bottle import Bottle

app = Bottle()

@app.get('/stuff')
def do_stuff():
    '''
    Method that does stuff.
    '''
    stuff = {'data': 'some dataX'}
    return stuff

def run_decoupled(app, host='0.0.0.0', port=8080, **config):
    server = CherryPyWSGIServer((host, port), app, **config)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

def run_in_cp_tree(app, host='0.0.0.0', port=8080, **config):
    cp.tree.graft(app, '/')
    cp.config.update(config)
    cp.config.update({
        'server.socket_port': port,
        'server.socket_host': host
    })
    cp.engine.signals.subscribe() # optional
    cp.engine.start()
    cp.engine.block()

def run_with_adapter(app, host='0.0.0.0', port=8080, config=None, **kwargs):
    cp.server.unsubscribe()
    bind_addr = (host, port)
    cp.server = ServerAdapter(cp.engine,
                              CherryPyWSGIServer(bind_addr, app, **kwargs),
                              bind_addr).subscribe()
    if config:
        cp.config.update(config)
    cp.engine.signals.subscribe() # optional
    cp.engine.start()
    cp.engine.block()

rawDescription: How to launch a Bottle application over a CherryPy standalone web server?

description: Launch a Bottle application over a CherryPy standalone web server


rawDescription: Why is SymPy's solver returning only one, trivial solution?


code:
with open('RawDataeDataTest.csv', 'rb') as csvf:
    data = list(csv.reader(csvf))
data.sort(key=lambda row: (row[3], row[7]))
print(u'\n'.join(u','.join(row) for row in data))

rawDescription: Sorting data by class for each date

description: Sorting data by class for each date


code:
def some_view(request, param):
    my_queryset = SomeModel.objects.filter(...).select_related(...)
    list_data = [x.some_related_field for x in my_queryset]
    return JsonResponse(list_data, safe=False)

rawDescription: Django - json response allowing for json[i][j] reference rather than json[0].field.field_name


code: re.split("\s+", str1)

rawDescription: python split string based on regular expression

description: Python split string based on regular expression


code:
from django.db.models import Count
qs = UserType.objects.annotate(Count('userlike'))

rawDescription: Django, getting related objects in a loop of objects


code: p.sub('gray \\1', s)

rawDescription: How to use python regex to replace using captured group?

description: Use python regex to replace using captured group


code:
d =  [(u'Code', u'US'), (u'Country', u'United States'), (u'Name', u'Bill')]
type(d)
type(d[0])

rawDescription: How to access value in list of dictionaries

description: Access value in list of dictionaries


code: print ("%s" * len(vars)) % tuple(vars)

rawDescription: How can I create python strings with placeholders with arbitrary number of elements

description: Create python strings with placeholders with arbitrary number of elements


code:
a=2
f = (lambda a: lambda x: x**a)(a)
f(3)
a=4
f(3)

rawDescription: Python lambda expression

description: Python lambda expression


code: zip(it, it, it)

rawDescription: Convert List to a list of tuples python

description: Convert List to a list of tuples python


code:
class Settings:

    # default settings
    name = 'John'
    surname = 'Doe'
    age = 45
    gender = 'Male'

rawDescription: Storing application settings in Python

description: Storing application settings in Python


code:
def isHappy(n):
    s = lambda n: sum(int(d)**2 for d in str(n))
    m = s(n)
    while m != n:
        n, m = s(n), s(s(m))
    return n == 1

rawDescription: Why doesn't this code work (Leetcode in Python)?


code: reader = csv.reader(csvfile)

rawDescription: How to parse of a simple csv file?

description: Parse of a simple csv file


code:
def extract_date(entity):
    'extracts the starting date from an entity'
    return entity.start_time.date()

rawDescription: Django model group by datetime's date

description: Django model group by datetime's date


code: load_sums = {k:sum(i[0] for i in d[k]) for k in d}

rawDescription: Stumped - In Python obtaining unique keys with multiple associated values from a list of ditionaries


code:
from collections import Counter
counter = Counter(s for v in d.itervalues() for s in v if isinstance(s, str))

rawDescription: Python how to print separate counters from a loop/add them together?


code:
def double(filename):
    seen = set()
    with open(filename, 'r') as infile:
        return any(word in seen or seen.add(word) for line in l for word in line.split())

rawDescription: How to determine if word in string is a double word?

description: Determine if word in string is a double word


code:
import win32security
import ntsecuritycon as con

FILENAME = r'D:\tmp\acc_test'

sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()

ace_count = dacl.GetAceCount()
print('Ace count:', ace_count)

for i in range(0, ace_count):
    rev, access, usersid = dacl.GetAce(i)
    user, group, type  = win32security.LookupAccountSid('', usersid)
    print('User: {}/{}'.format(group, user), rev, access)

rawDescription: How to authorize/deny write access to a directory on Windows using Python?

description: Authorize/deny write access to a directory on Windows using Python


code:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

rawDescription: Python : Soap using requests

description: Python : Soap using requests


code:
"chdir /".split(" ")
"chdir  /".split(" ")
"chdir  /".split()

rawDescription: Python split data from socket

description: Python split data from socket


code:
def getNGramBeginsWords(nGram, length):
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    for line in wlist:
        stripline = line.strip().upper() # you keep doing this
        # you can merge these two ifs
        # also this renders the comparison of ngram and stripline lengths redundant
        if (len(stripline) == length) and stripline.endswith(nGram):
            words.append(stripline)
    return words

rawDescription: Passing in Global Variables in Python

description: Passing in Global Variables in Python


code:
if not(some_strng in countries):
    code_country.append( ['NOT FOUND'])

rawDescription: need to iterate through dictionary to find slice of string

description: Need to iterate through dictionary to find slice of string


code: data = dict((k, filter(bool, v)) for k, v in data.iteritems())

rawDescription: How to remove empty entries from a list in a dictionary using python

description: Remove empty entries from a list in a dictionary using python


rawDescription: How to get folder name, in which given file resides, from pathlib.path?

description: Get folder name, in which given file resides, from pathlib.path


code:
class ExampleExtension(WrapExtension):
    tags = set(['example'])
    template = 'example.html.j2'

rawDescription: How do you parse and inject additional nodes in a Jinja extension?

description: Parse and inject additional nodes in a Jinja extension


code:
from collections import defaultdict

def merge(*d):
    newdicts = defaultdict(set)  # Define a defaultdict
    for each_dict in d:

        # dict.items() returns a list of (k, v) tuple.
        # So, you can directly unpack the tuple in two loop variables.
        for k, v in each_dict.items():
            newdicts[k].add(v)

    # And if you want the exact representation that you have shown
    # You can build a normal dict out of your newly built dict.
    unique = {key: list(value) for key, value in newdicts.items()}
    return unique

rawDescription: Python remove duplicate value in a combined dictionary's list


code:
class User(Base):
    __tablename__ = 't_users'
    id = Column(Integer, primary_key=True)
    MAUorALL = Column(String)
    User_Type = Column(String)
    Country = Column(String)
    Month_ID = Column(Integer)
    Objects_Created = Column(Integer)

rawDescription: SQLalchemy: quantiles for all permutations of column value combinations


code:
class PrettyEnum(Enum):
    def __str__(self):
       return self.__class__.__name__ + ': ' + self.name

rawDescription: Python 2.7, enum34 and user friendly unicode representation of enum properties


rawDescription: How to make a function return nothing?

description: Make a function return nothing


code:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from ..items import BotItem
from scrapy.linkextractors import LinkExtractor

class UlsterSpider(CrawlSpider):
    name = "ulster"
    allowed_domains = ["ulster.ac.uk"]
    start_urls = (
        'http://www.ulster.ac.uk/courses/course-finder?query=&f.Year_of_entry|E=2015/16&f.Type|D=Undergraduate',
    )

    rules = (
        Rule(
            LinkExtractor(restrict_xpaths='//div[@class="pagination"]/ul/li[position() = last()]'),
            follow=True,
            callback='parse_start_url'),
    )

    def parse_start_url(self, response):
        item = BotItem()

        for title in response.xpath('//*[@id="course_list"]/div/h2/a'):
            item['name'] = title.xpath('text()')[0].extract().strip()
            yield item

rawDescription: Crawl spider not crawling ~ Rule Issue

description: Crawl spider not crawling ~ Rule Issue


code:
#!python

from _winreg import *
from sys import executable
from os import path

subkey  = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
script  = 'C:\\Path\\To\\SetDesktopBackground.py'
pythonw = path.join(path.dirname(executable), 'pythonw.exe')

hKey = OpenKey(HKEY_CURRENT_USER, subkey, 0, KEY_SET_VALUE)

SetValueEx(hKey, 'MyApp', 0, REG_SZ, '"{0}" "{1}"'.format(pythonw, script))

CloseKey(hKey)

rawDescription: Change wallpaper in Python for user while being system


rawDescription: Is there a wx.EVT_CHAR or event.GetKeyCode() equivalent for wxPython( Phoenix )?


code:
from BeautifulSoup import BeautifulSoup as BSHTML
BS = BSHTML("""
<font face="ARIAL,HELVETICA" size="-2">
JUL 28         </font>"""
)
BS.font.contents[0].strip()

rawDescription: Python string operation, extract text between html tags


code:
from copy import deepcopy

def remove_pass(v):
    if isinstance(v, dict):
        if "password" in v:
            del v["password"]
        for ele in v.values():
            remove_pass(ele)
    elif isinstance(v, Iterable) and not isinstance(v, basestring):
        for ele in v:
            remove_pass(ele)

from pprint import pprint as pp
d = deepcopy(d)
for v in d.values():
   remove_pass(v)

rawDescription: How to scrub a dynamic python dictionary of specific keys?

description: Scrub a dynamic python dictionary of specific keys


code:
m = re.search(r'(T)P-(L)INK.+(WA\w+)', re1)
''.join(m.groups())

rawDescription: How to use regex to search in a string

description: Use regex to search in a string


code:
import numba

@numba.autojit
def inner_loop(row, col, values, number, amount):
    for i in range(len(row)):
        r = row[i]
        c = col[i]
        v = values[i]
        amount[r, c] += v
        number[r, c] += 1

def numba_assign(row, col, values):
    number = np.zeros([2,2], np.float)
    amount = np.zeros([2,2], np.float)
    inner_loop(row, col, values, number, amount)
    return amount, number

rawDescription: Sum array values into a matrix in python in a quick way


code:
chain_sizes = {}
chain_sizes[13] = 10
chain_sizes[40] = 9
chain_sizes[40]   # => 9
20 in chain_sizes # => False

rawDescription: How can I improve my code for euler 14?

description: Improve my code for euler 14


code:
data += sock.recv(65535)
if not data: # if empty
    break

rawDescription: recv() keep returning the same data

description: Recv() keep returning the same data


code:
Nickname
Car

rawDescription: How could I delete certain columns then write wanted columns into csv python


rawDescription: Efficiently comparing data across rows in a Pandas Dataframe


code:
import multiprocessing as mp

def mkproc(func):
    parent_conn, child_conn = mp.Pipe()
    p = mp.Process(func, args=(child_conn,))
    p.start()
    return (p, parent_conn)

rawDescription: python multiprocessing dynamically created processes and pipes

description: Python multiprocessing dynamically created processes and pipes


code:
from itertools import product, chain
from string import punctuation

list1 = ['abra', 'hello', 'cfre']
list2 = ['dacc', 'ex', 'you', 'fboaf']
list3 = ['ihhio', 'oih', 'oihoihoo']

l = [list1, list2, list3]

def test(l, tt):
    counts = {word.strip(punctuation):0 for word in tt.split()}
    for word in chain(*product(*l)):
        if word in counts:
            counts[word] += 1
        if sum(v > 1 for v in counts.values())  > 1:
            return False
    return True

rawDescription: find only one word of multiple lists in a string

description: Find only one word of multiple lists in a string


code:
def transform(li):
    new_li = []
    prev_tag = None
    for word, tag in li:
        if word.endswith('ing') and prev_tag == 'NN':
            tag = 'VBG'
        new_li += [(word, tag)]
        prev_tag = tag
    return new_li

rawDescription: lookbehind in a for loop

description: Lookbehind in a for loop


code:
not_matched_in_df1 = set(df1['data_id1']) - set(merged_cross_join['data_id1'])
final = pd.concat([merged_cross_join,df1[df1['data_id1'].isin(not_matched_in_df1)]],axis=0)

rawDescription: Left outer Join Pandas Data Frame using contains


code: [('BIG Problem Line', 'blah GPS INFO: 238490'), ('BIG Problem Line2', 'GPS INFO: 12343')]

rawDescription: Using Python to run nested string searches


rawDescription: DFT gives different results if iterated

description: DFT gives different results if iterated


code:
import glob
with ('out.csv', 'w') as fout:
    for fname in glob.glob('*.txt'):
        with open(fname, 'r') as fin:
            fout.write(fin.read())

rawDescription: Python automating text data files into csv


code:
from django.core import urlresolvers
from myapp import myview
urlresolvers.get_resolver (None).reverse_dict
v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]
reverse(v1)
v1 is myview
v1.__module__
myview.__module__

rawDescription: How do I successfully pass a function reference to Django’s reverse() function?

description: Successfully pass a function reference to Django’s reverse() function


code:
from collections import OrderedDict
d = OrderedDict([(3, 'c'), (2, 'b'), (1, 'a')])
d

rawDescription: Can I trust the order of a dict to remain the same each time it is iterated over?

description: Trust the order of a dict to remain the same each time it is iterated over


code:
class GradeInline(admin.TabularInline):
    model = Grade
    extra = 1

rawDescription: Is it possible to filter choices on a foreign key in Django Admin panel?


code:
import pipes
p = os.popen("/usr/bin/passwd " + pipes.quote(username), 'w')

rawDescription: Safe way to execute commands on linux server when part of command is from a user input


code:
for y in xrange( 70, 131, 30):
  for x in xrange( 80, 741, 110):
    print (x, y)

rawDescription: sequence-pattern based algorithm with numbers

description: Sequence-pattern based algorithm with numbers


code:
from django.utils.safestring import mark_safe

...

render_to_response('a.html', {'taggeddoc': mark_safe(tdoc)})

rawDescription: django render_to_response how to send special characters

description: Django render_to_response how to send special characters


code: form = RecipeForm(request.POST, user=request.user) #user would be passed in as a kwarg to the form class.

rawDescription: How to filter model choice field options based on user in django?

description: Filter model choice field options based on user in django


code:
price = itertools.cycle(price or [None])
mypart['rrp'], mypart['price'] = next(price), next(price)

rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


rawDescription: How to retrieve the list of supported file formats for Matplotlib savefig() function?

description: Retrieve the list of supported file formats for Matplotlib savefig() function


rawDescription: Index of multidimensional array

description: Index of multidimensional array


code:
tmp = []
i = j = 0
while i < len(primes) and j < len(removable):
    if primes[i] < removable[j]:
        tmp.append(primes[i])
        i += 1
    elif primes[i] == removable[j]:
        i += 1
    else:
        j += 1
primes[:i] = tmp
del tmp

rawDescription: What's a fast and pythonic/clean way of removing a sorted list from another sorted list in python?


code:
def get_creation_time(path):
    return os.stat(path).st_birthtime

rawDescription: Get file creation time with Python on Mac


code: P /= P.sum(axis=1).reshape((-1, 1))

rawDescription: Python SKLearn: Logistic Regression Probabilities


code:
class Temp_entry(models.Model):
    dateTime = models.IntegerField(db_index=True) #datetime
    sensor = models.IntegerField(db_index=True)   # id of sensor
    temp = models.IntegerField()     # temp as temp in Kelvin * 100

rawDescription: Improving performance of django DB query


code:
g1 = df.groupby(['col1', 'col2', 'session_number'])  # I think there is a slightly neater way, but I forget..
df1['session'] = g1.apply(lambda x: 1).cumsum()  # could -1 here if it matters
df1

rawDescription: Pandas Dataframe split in to sessions

description: Pandas Dataframe split in to sessions


code: itertools.product((0,1), repeat=4)

rawDescription: Is there a way to delist a list in python?


code:
#MAIN VIEW FUNCTION
def view(request):
    #Do stuff, get data as string

    #Get data into needed formats
    jsonData  = jsonToJsonFile(dataString, fileName)

    #Set values to external view ****NEW PART****
    returnJSON.jsonData = jsonData

    #Render main template
    return render_to_response('mainTemplate.html', {'someForm'    : aForm,
                                                    'regularData' : dataString})

#SECONDARY VIEW TO RETURN JSON DATA TO USER ****NEW PART****
def returnJSON(request):
    #Simply return the response
    return returnJSON.jsonData

rawDescription: Django : provide dynamically generated data as attachment on button press


code:
def to_inch(cm):
    return float(cm) / 2.54

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


code:
def get_upload_file(instance, filename):
   today_date = datetime.datetime.today().date()
   directory = 'Data/'+ str(today_date)+'/'+instance.reqObj.user.username
   if not os.path.exists(directory):
       os.makedirs(directory)
   full_path = str(directory)+"/%s" %(filename)
   return full_path

rawDescription: Django dynamic file upload path

description: Django dynamic file upload path


code: Button(wind, text = 'Left', command=lambda: can.coords(oval1, *(moveLeft() + addThirty(moveLeft()))))

rawDescription: Passing function returns as method parameters in Python


code:
parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-v', '--version', action='version',
                    version='%(prog)s 1.0', help="Show program's version number and exit.")
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
                    help='Show this help message and exit.')

rawDescription: Customize argparse help message

description: Customize argparse help message


rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code:
EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
                 ('AIR', 'Airnz', 5.60),
                 ('AMP', 'Amp',3.22),
                 ('ANZ', 'Anzbankgrp', 26.25),
                 ('ARG', 'Argosy', 12.22),
                 ('CEN', 'Contact', 11.22),
                 ('CNU', 'Chorus',3.01),
                 ('DIL', 'Diligent', 5.3),
                 ('DNZ', 'Dnz Property', 2.33),
                 ('EBO', 'Ebos', 1.1)]
inp = "AIA,AIR,AMP"     # could come from input()
exchange_dict = {i[0]:i for i in EXCHANGE_DATA}
[exchange_dict[x] for x in inp.split(',')]

rawDescription: Input points to certain elements in a list of tuples


code: tree.find('{{{0}}}Item/{{{0}}}UniqueID'.format(NS))  # Tags are prefixed with NS

rawDescription: Using ElementTree to parse an XML string with a namespace


code:
results = [(code, a[0])
           for id, number, code in first_list
           for a in second_set
           if code.startswith(a[0])]

rawDescription: Python: nested list comprehension

description: Python: nested list comprehension


code: ip, outcome = queue.get()

rawDescription: Identifying queue returns from Python script that uses threading and queue modules


rawDescription: Slicing a DataFrame

description: Slicing a DataFrame


code: args_raw = '[{}]'.format(', '.join(js_args))

rawDescription: Scrapy hxs.select() not selecting all results


code:
def format_time_with_milliseconds(time):
    fmt = "{time.year:04}-{time.month:02}-{time.day:02}T{time.hour:02}:{time.minute:02}:{time.second:02}.{millisecond:03}{tz}"
    return fmt.format(time=time, millisecond=int(round(time.microsecond/1000)), tz=time.strftime("%z"))

rawDescription: How to convert date string to ISO8601 standard?

description: Convert date string to ISO8601 standard


code:
def posNumAvg(values):
    pos = [v for v in values if v > 0]
    return sum(pos) / len(pos)

rawDescription: Trying to learn how to python have, I am curious about appeand and dictionaries...am i doing this correctly?


code:
from shutil import copyfile
copyfile(filenamefrom, filenameto)

rawDescription: Python - Trying to truncate, write to and then copy the written-to file to another file


code:
class a: ## Using this class just to explain
    def __init__(self,y,m,d,t):
        self.y=y
        self.m=m
        self.d=d
        self.t=t

o1 = a(2000,12,18,9) ## Just assuming integers here. you can choose immutable objects here
o2 = a(2000,12,19,13)
o3 = a(2001,11,18,9)
o4 = a(2000,11,18,6)
o5 = a(2000,12,6,7)

l=[o1,o2,o3,o4,o5]

d={}

for o in l:
    if o.y not in d:
        d[o.y] = {}
    # print d
    if o.m not in d[o.y]:
        d[o.y][o.m]={}
    if o.d not in d[o.y][o.m]:
        d[o.y][o.m][o.d]={}
    if o.t not in d[o.y][o.m][o.d]:
        d[o.y][o.m][o.d][o.t]=o

rawDescription: GAE Python - 'Clamp' dates together into a 'tree' structure


code:
#Supposing you check for an attribute
def check_for_property(array, property_name, property_state):
   #property_name: str (The name of the property you want to check(
   #property_state: anything (Check if the property_name property of all elements matches this one)
   #The returns act as a shortcut so that the for loop is stopped after the first mismatch.
   #It only returns True if the complete for loop was passed.
   for i in np.nditer(array):
       if hasattr(i, property_name):
          if getattr(i, property_name) != property_state:
              return False #Property has not the same value assigned
       else:
          return False # If this element hasn't got this property return False
   return True #All elements have the property and all are equal 'property_state'

rawDescription: List of objects: how to extract attributes from a particular region or slice?


code: print(self.class_1_instance.x) # prints 1

rawDescription: Class management in python

description: Class management in python


code: print('\n'.join(' '.join(p) for p in matrix))

rawDescription: Removing brackets and quotes from matrix in python


code: pd.Series( [' foo','foo','foo '] ).value_counts()

rawDescription: Leading or trailing whitespace and pandas value_counts vs boolean selection


code:
from collections import namedtuple
Flight = namedtuple('Flight',['id','start','end'])

rawDescription: Find first and last list within a list with a matching property


rawDescription: extracting items using regular expression in python

description: Extracting items using regular expression in python


code:
def addState (self, parentState, newState) :
    "add state if it's new. Remember its parent"

    # Let's augment this by adding a breakpoint
    import pdb; pdb.set_trace()

    if self.seen.has_key(str(newState)) : return
    self.seen[str(newState)] = str(parentState)
    self.queue.append (newState)
    #print '--- Adding ', newState

rawDescription: How can I figure out which parameters map to which variables?

description: Figure out which parameters map to which variables


code:
example = 0x1234   # Hexadecimal example; 2 bytes, 4660 decimal.
bin(example)       # Show as binary digits
example & 31       # Grab 5 most significant bits
bin(example & 31)  # Same, now represented as binary digits
(example >> 5) & 31 # Grab the next 5 bits (shift right 5 times first)
bin(example >> 5 & 31)

rawDescription: Interpreting 5bit subsets within Packed Binary Data Python


code:
df = pd.melt(df.reset_index(), id_vars=['index']).sort(['index'])
df.columns = ['Product Category', 'Ship Cycle', 'Multiplier']
df.head()

rawDescription: Python - Unpivot data

description: Python - Unpivot data


code:
def rule(f):
    f.rule = True
    return f

def getRules(cls):
    cls.rules = {}
    for attr, value in cls.__dict__.iteritems():
        if getattr(value, 'rule', False):
            cls.rules[attr] = value
    return cls

@getRules
class RuleClass:
    @rule
    def foo(self):
        pass

rawDescription: python decorator to modify variable in current scope

description: Python decorator to modify variable in current scope


code:
import csv

with open('d_file.csv', 'r') as first_file:
    reader = csv.reader(first_file)
    first_header = next(reader, None)
    column0=  {}
    column1 = {}
    for row in reader:
        if row[0]:
            column0[row[0].strip()] = row[2]
        if row[1]:
            column1[row[1].strip()] = row[2]

with open('data_file.csv', 'r') as second_file:
    with open('final_results.csv', 'w', newline='') as outfile:
        reader = csv.reader(second_file)
        second_header = next(reader, None)
        description = len(second_header)-1
        writer = csv.writer(outfile)
        # use there first_header[2:] is incorrect - you will save 'Column 3', while you want 'Column 7'
        writer.writerow(second_header[:6] + ['Column 7'])

        for row in reader:
            if row[0].strip() in column0:
                writer.writerow(row[0:] + [column0[row[0].strip()]] )
            elif row[1].strip() in column1:
                writer.writerow(row[0:] + [column1[row[1].strip()]] )
            else:
                writer.writerow(row[0:])

rawDescription: Python 3.5 combine two CSV by matching multiple columns


code:
for k in my_list:
    ccDict[k] = [str(len(k)), "N/A", "N/A", "N/A", "No"]

rawDescription: Update value in Dictionary with multiple values per key


code:
def some_remote_task():
    # Run a remote task silently
    with _mute():
        output = remote("uname -a")

rawDescription: What's the pythonic way to wrap several functions in the same with statements


code: m = m.multiply(m >= 10)

rawDescription: Filter values from a scipy sparse matrix


code: [item for item in l if item['username'] != 'bob']

rawDescription: How to remove an object from a list in python?

description: Remove an object from a list in python


code:
    #!/usr/bin/python
from gi.repository import Gtk, Pango, PangoCairo
import cairo

text = '''
Text.
I have some information (a list of participants to an event) which I
want to print out easily.
No need for fancy layout,
just a table with several columns,
and if possible a drawn line in between the lines of
 text for better readability.
'''

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World Printing")
        self.button = Gtk.Button(label="Print A Rectangle")
        self.button.connect("clicked", self.on_button_clicked)
        self.add(self.button)

    def on_button_clicked(self, widget):
        ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
        st = Gtk.PrintSettings()
        s = Gtk.PageSetup()
        s.set_paper_size(ps)
        s.set_bottom_margin(4.3, Gtk.Unit.MM)
        s.set_left_margin(4.3, Gtk.Unit.MM)
        s.set_right_margin(4.3, Gtk.Unit.MM)
        s.set_top_margin(4.3, Gtk.Unit.MM)
        s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
        # ret =  Gtk.print_run_page_setup_dialog(self, s, st)
        pd = Gtk.PrintOperation()
        pd.set_n_pages(1)
        pd.set_default_page_setup(s)
        pd.connect("begin_print", self.bg)
        pd.connect("draw_page", self.draw_page)
        # print(ret, s, st)
        pd.set_export_filename("test.pdf")
        result = pd.run(Gtk.PrintOperationAction.EXPORT, None)
        print (result)  # handle errors etc.
        # Gtk.PaperSize.free(ps)

    def bg(self, op, cx):
        w = cx.get_width()
        h = cx.get_height()
        self.layout = cx.create_pango_layout()
        self.layout.set_width(int(w / 4 * Pango.SCALE))
        self.layout.set_text(text, len(text))
        num_lines = self.layout.get_line_count()
        page_height = 0
        self.layout.set_font_description(Pango.FontDescription("Georgia Bold 12"))
        k = 0
        for line in range(num_lines):
            if k == 4:
                self.layout.set_font_description(Pango.FontDescription("Georgia 10"))
            layout_line = self.layout.get_line(line)
            ink_rect, logical_rect = layout_line.get_extents()
            # print(logical_rect, ink_rect)
            # x_bearing, y_bearing, lwidth, lheight = logical_rect
            lheight = 1200
            line_height = lheight / 1024.0  # 1024.0 is float(pango.SCALE)
            page_height += line_height
            # page_height is the current location on a page.
            # It adds the the line height on each pass through the loop
            # Once it is greater then the height supplied by context.get_height
            # it marks the line and sets the current page height back to 0
            k += 1
            print ("page_height ", page_height)

    def box(self, w, h, x, y, cx):
        w, h = int(w), int(h)
        cx.set_font_size(100)
        cx.set_source_rgb(0, 0, 0)
        cx.rectangle(x, y, w, h)
        cx.stroke()
        yy = 120
        cx.select_font_face("Times", 0, 1)
        ex = cx.text_extents("TEGOLA ROMÂNIA SRL")[2]
        cx.move_to(w / 2 - ex / 2 + x, 105 + y)
        cx.show_text("TEGOLA ROMÂNIA SRL")
        ex = cx.text_extents("Str. Plevnei, nr. 5, Buzău")[2]
        cx.move_to(w / 2 - ex / 2 + x, 210 + y)
        cx.show_text("Str. Plevnei, nr. 5, Buzău")
        ex = cx.text_extents("Tel.: 0238/710.280")[2]
        cx.move_to(w / 2 - ex / 2 + x, 320 + y)
        cx.show_text("Tel.: 0238/710.280")
        ex = cx.text_extents("Fax : 0238/710021")[2]
        cx.move_to(w / 2 - ex / 2 + x, 415 + y)
        cx.show_text("Fax : 0238/710021")
        cx.set_font_size(90)
        cx.move_to(x + 120, 520 + y)
        ex = cx.text_extents("Compoziție:")[2]
        cx.show_text("Compoziție:")
        cx.select_font_face("Times", 0, 0)
        cx.move_to(x + 125 + ex, 520 + y)
        cx.show_text("Polimer bituminos, liant și")
        cx.move_to(x + 5, 620 + y)
        cx.show_text("material de umplutură de înaltă calitate.")
        cx.move_to(x + 5, 720 + y)
        cx.show_text("Nu conține gudron.")
        cx.move_to(x + 5, 800 + y)
        cx.select_font_face("Times", 0, 1)
        ex = cx.text_extents("Instrucțiuni de utilizare:")[2]
        cx.show_text("Instrucțiuni de utilizare:")
        cx.select_font_face("Times", 0, 0)
        cx.move_to(x + 10 + ex, 800 + y)
        cx.show_text("Suprafețele se")

    def draw_page1(self, operation, context, page_nr=None):
        ctx = context.get_cairo_context()
        w = context.get_width()
        h = context.get_height()
        ww, hh = int(w / 4), int(h / 2)
        self.k = 0
        for x in range(2):
            for y in range(4):
                self.box(ww, hh, y * ww, x * hh, ctx)
                self.k += 1
        print(ctx.get_font_matrix())

    def draw_page (self, operation, context, page_number):
        end = self.layout.get_line_count()
        cr = context.get_cairo_context()
        cr.set_source_rgb(0, 0, 0)
        i = 0
        start = 0
        start_pos = 0
        iter = self.layout.get_iter()
        while 1:
            if i >= start:
                line = iter.get_line()
                print(line)
                _, logical_rect = iter.get_line_extents()
                # x_bearing, y_bearing, lwidth, lheight = logical_rect
                baseline = iter.get_baseline()
                if i == start:
                    start_pos = 12000 / 1024.0  # 1024.0 is float(pango.SCALE)
                cr.move_to(0 / 1024.0, baseline / 1024.0 - start_pos)
                PangoCairo.show_layout_line(cr, line)
            i += 1
            if not (i < end and iter.next_line()):
                break

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Creating print job in gtk3/python

description: Creating print job in gtk3/python


code:
import msvcrt
import time

t0 = time.time()
while time.time() - t0 < 600:
    if msvcrt.kbhit():
        if msvcrt.getch() == '\r': # not '\n'
            break
    time.sleep(0.1)

rawDescription: Python: wait for user input, and if no input after 10 minutes, continue with program


rawDescription: Matplotilb bar chart: diagonal tick labels


code:
class Table2(Base):
    # ...
    table1 = relationship(Table1, backref="table2s")

rawDescription: How to execute "left outer join" in SqlAlchemy

description: Execute "left outer join" in SqlAlchemy


code:
plt.plot(arange(0,100,10) + 1000, arange(0,100,10))
ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt.draw()

rawDescription: How to prevent numbers being changed to exponential form in Python matplotlib figure

description: Prevent numbers being changed to exponential form in Python matplotlib figure


rawDescription: Why can't Python understand integers in word form?


code:
from StringIO import StringIO
import numpy as np

txt_data = """
1\t2\t3
4\t\t6
7t\8t\9"""

infile = StringIO(txt_data)
data = np.genfromtxt(infile, usemask=True, delimiter='\t')

rawDescription: creating a masked array from text fields

description: Creating a masked array from text fields


code:
from random import Random
import unittest

random = Random()

def gen_age():
    # generate integer between 15 and 99
    return random.randint(15, 99)

class AgeTest(unittest.TestCase):

    def setUp(self):
        global random
        random = Random(666)

    def test_gen_age(self):
        self.assertEqual(gen_age(), 53)

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

rawDescription: How to validate a unit test with random values

description: Validate a unit test with random values


code:
import re

addresses = set()
pattern = re.compile(r'[-=]> +(\w{1,}@\w{1,}\.\w{2,3})')

with open('test.txt', 'r') as f:
    for line in f:
        match = pattern.search(line)
        if match:
            addresses.add(match.groups()[0])

for address in sorted(addresses):
    print(address)

rawDescription: Sorting the unique values from regex match in python


code:
import os
def ps(self, command):
  os.system(command + " & disown")

ps("/var/tmp/KernelbootRun.sh")
ps("ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9")

rawDescription: How can i let the BASH script run as process? So that even the Python script is killed the BASH script runs forever?

description: Let the BASH script run as process? So that even the Python script is killed the BASH script runs forever


code:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
    writer = csv.writer(cache)
    for tweet in datares['results']:
        writer.writerow([tweet['text'], tweet['area'], tweet['date'], tweet['id']])

rawDescription: Formatting data returned from twitter api utilizing python in a csv file?


code: first, last = MyModel.allocate_ids(100, parent=q)

rawDescription: How to guarantee the uniqueness of gae datastore Name/ID?

description: Guarantee the uniqueness of gae datastore Name/ID


code:
with open('wordlist.txt') as wlist:
    words = [w.strip() for w in wlist]
with open('output.txt', 'w') as output:
    for word in random.sample(words, 12):
        output.write(word + '\n')

rawDescription: Python: compare two text files for same random lines


rawDescription: sum squared values in FreqDist, python

description: Sum squared values in FreqDist, python


code:
import re
m = re.sub(r'(?<=\S)%(?= |$)', r'PCT', 'foo%bar foo% bar%')
m

rawDescription: Python - string replacement, re.match and re.sub in a single operation (replace a char if at end of a string)


code:
tgt=[]
for root, dirs, files in os.walk(exportLocation):
    for file in files:
        if 'SystemIndex_0A' in file:
            tgt.append(os.path.join(root, file))

rawDescription: Python: filter on a list returning empty list


code:
def test_something(self):
    spud = Potato()
    with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
        forty_two = spud.foo(n=40)
        mock.assert_called_once_with(n=40)
    self.assertEqual(forty_two, 42)

rawDescription: python mock - patching a method without obstructing implementation

description: Python mock - patching a method without obstructing implementation


code:
pairs = []
for line in data():
    line = line.strip()
    pairs.append(line.split(', '))

print([s for s, t in pairs if t == "animal"])

rawDescription: Print out indexes of same values in file/list


code:
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

rawDescription: Populating list with images in PYQT

description: Populating list with images in PYQT