code:
def block(str):
    regex = re.compile(r'''
               (?:\d{1,2}\s)(block\s\w*) # rule 1
                 |   # or
               (?:(phase|apartment|building).*?)(block\s\w+) # rule 2
                 ''', re.X)
    match = regex.search(str)
    if not match:
        return ''
    else:
        return match.group(1) or match.group(3) or ''

rawDescription: Conditioning on Regex

description: Conditioning on Regex


rawDescription: Some Basic Python Questions

description: Some Basic Python Questions


code:
import cPickle
from collections import namedtuple
ChanVal= namedtuple( 'ChanVal', ['eventTime','eventTimeExact', 'other_clock', ... ] )
while True:
    item = cPickle.load( sys.stdin )
    # processing
    cPickle.dump( sys.stdout )

rawDescription: Getting fast translation of string data transmitted via a socket into objects in Python


code: nw, n, ne, w, _, e, sw, s, se = (self.board[column-1:column+2, row-1:row+2]).ravel()

rawDescription: Set none if numpy array index does not exist


code:
## This class is used to replicate QuerySet methods into a manager.
## This way:  Partyline.objects.for_user(foo) works the same as
## Partyline.objects.filter(date=today).for_user(foo)
class CustomQuerySetManager(models.Manager):
    def get_query_set(self):
        return self.model.QuerySet(self.model)
    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)

class Partyline(models.Model):
    ## Define fields, blah blah.
    objects = CustomQuerySetManager()
    class QuerySet(QuerySet):
        def sort_for_request(self, request):
            sort_field = request.REQUEST.get('sortby', 'did').strip()
            reverse_order = False
            if sort_field.startswith('-'):
                search = sort_field[1:]
            else:
                search = sort_field
                reverse_order = True

            # Check to see if the sort term is valid.
            if not (search in Partyline._meta.get_all_field_names()):
                sort_field = 'did'

            partylines = self.all().order_by(sort_field)
            if reverse_order:
                partylines.reverse()
            return partylines
        def for_user(self, user):
            if is_user_type(request.user, ['admin']):
                return self.all()
            else:
                ## Code from get_my_partylines goes here.
                return self.all() ## Temporary.

rawDescription: Does Django Have a Way to Auto-Sort Model Fields?


code:
forms.py
from django.forms import ModelForm

class EventForm(ModelForm):

    def __init__(self, user, **kwargs):
        self.user = user
        super(EventForm, self).__init__(**kwargs)

    class Meta:
        model = Event

    def save(self, commit=True):
        event = super(EventForm, self).save(commit=False)
        event.user = self.user
        if commit:
            event.save()

rawDescription: Best practices on saving in a view, based on example code


code:
'__subclasses__' in dir(object)
'__subclasses__' in dir(type)

rawDescription: Calling class method as part of initialization


code: func(1, 2, kwonly=3, kw=4)

rawDescription: Python inspect module: keyword only args


code:
dfrm
100*np.round(dfrm, 2)

rawDescription: Rounding entries in a Pandas DafaFrame

description: Rounding entries in a Pandas DafaFrame


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

fig1 = plt.figure() # create a figure with the default size

im1 = np.random.rand(5,5)
ax1 = fig1.add_subplot(2,2,1)
ax1.imshow(im1, interpolation='none')
ax1.set_title('5 X 5')

im2 = np.random.rand(100,100)
ax2 = fig1.add_subplot(2,2,2)
ax2.imshow(im2, interpolation='none')
ax2.set_title('100 X 100')

fig1.savefig('example.png', dpi = 1000) # change the resolution of the saved image

rawDescription: Change resolution of imshow in ipython

description: Change resolution of imshow in ipython


rawDescription: Most Pythonic way to iteratively build up a list?


rawDescription: XPath: Assessing an Error in this Line of Code?


code:
sigreq =request.POST.get('signed_request', None)
user_id,access_token = load_signed_request(sigreq)

rawDescription: How to redirect the url after logging into Facebook?

description: Redirect the url after logging into Facebook


code:
ordered = sorted(first, key = lambda k: (first[k], k[1], k[0]))
ordered

rawDescription: Dictionary value sorting

description: Dictionary value sorting


rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code: contentjoined.translate(None,''.join([i for i in contentjoined if i not in aminoacids]))

rawDescription: Remove character from string if its not in a list...?


code:
class User(db.Entity):
    username = Required(str, unique=True)
    ...
    @classmethod
    def name_starts_with(cls, prefix):
        return cls.select(lambda user: not user.disabled
                                       and user.name.startswith(prefix))

...
users = User.name_starts_with('A').order_by(desc(User.last_visit))[:10]

rawDescription: Writing select functions for customized Pony


code: dict((key, [val[i] for i in filter_ind]) for key, val in db.iteritems())

rawDescription: Filter dict by certain values

description: Filter dict by certain values


rawDescription: Python - Convert epoch time with nanoseconds to human-readable?


code:
import lxml.etree as ET
tree = ET.parse(filename)

rawDescription: Faithfully Preserve Comments in Parsed XML (Python 2.7)


code:
class MyFormatter(argparse.HelpFormatter):
    def __init__(self,prog):
        super(MyFormatter,self).__init__(prog,max_help_position=55)
parser=argparse.ArgumentParser(formatter_class=MyFormatter)

rawDescription: How to change the format of subparser with argparse

description: Change the format of subparser with argparse


code:
import operator
sorted(lst, key=operator.itemgetter('name'))

rawDescription: Sort dictionary elements in list

description: Sort dictionary elements in list


code:
def match(a, b, L):
    try:
        return L.index(a) < L.index(b)
    except ValueError:
        return False

selection = [L for L in lists if match(x1, x2, L)]

rawDescription: Fast way to find lists contains two particular items?


code: [x.a for x in X]

rawDescription: Selecting all objects in the list of objects (in Python)


rawDescription: Python: In an xml, How to delete nodes within a parent node


code:
def log_deleted_question(sender, instance, using, **kwargs):
    d = Deleted()
    d.question = instance.id
    d.dt = datetime.datetime.now() # consider using auto_now=True in your Deleted definition
    # not sure how you'd get the user via a signal,
    # since it can happen from a number of places (like the command line)
    d.save()

rawDescription: Using Pre_delete Signal in django

description: Using Pre_delete Signal in django


code: filter(lambda k: 'ab' in k, lst)

rawDescription: Filtering a list of strings based on contents


code:
import requests
import pandas as pd
import json

def load_data(country='', start_date='2014-08-09', end_date='2014-11-1'):
    base = "http://www.apptrace.com/api/app/389801252/rankings/country/"
    extra = "?country={0}&start_date={1}&end_date={2}&device=iphone&list_type=normal&chart_subtype=iphone"
    addr = base + extra.format(country, start_date, end_date)

    page = requests.get(addr)
    json_data = page.json() #gets the json data from the page
    ranks = json_data['rankings'][0]['ranks']
    ranks = json.dumps(ranks)  #Ensures it has valid json format
    df = pd.read_json(ranks, orient='records')
    return df

rawDescription: scraping data from a dynamic graph using python+beautifulSoup4

description: Scraping data from a dynamic graph using python+beautifulSoup4


code:
priorities = {'xyz' : 1, 'cde' : 3, 'abc' : 4, 'pqr' : 2}

arr = ['abc', 'cde', 'pqr', 'xyz', 'cde', 'abc']

arr.sort(key = lambda s : priorities[s])

print(arr)

rawDescription: Python: Arguments to sorting function

description: Python: Arguments to sorting function


code:
import functools
df.sort_clean = functools.partial(sort_clean, df)

rawDescription: attach functions to pandas

description: Attach functions to pandas


code:
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.node[1]['ipaddress'] = '8.8.8.8'
G.node[1]['longitude'] = 37
G.node[1]['latitude'] = 50
G.node[1]
G.node[1]['ipaddress']

rawDescription: how do I make a cutomised object as a node for networkx and how do I look it up?

description: Make a cutomised object as a node for networkx and how do I look it up


rawDescription: From a python dictionary to list of settings


code:
for name in (line.rstrip("\r\n") for line in sys.stdin):
    ...

rawDescription: Python iterate over stdin line by line using input()


code:
import re
def add_letter_to_vowels(word, letter):
  return re.sub(r"([aeiou])",r"%s\g<1>"%letter, word)

rawDescription: insert letter before vowel in word

description: Insert letter before vowel in word


code: item.extend(d[k].get(key, '') for key in ('v1', 'v2', 'e', 'x'))

rawDescription: How to convert some values in a dict into a list in a clean style in Python?

description: Convert some values in a dict into a list in a clean style in Python


code:
import jinja2
template_dir = '/path/to/templates'
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.Environment(loader=loader)

rawDescription: Does the Jinja2 templating language have the concept of 'here' (current directory)?


code:
for each_div in soup.find_all('div',{'class':'username'}):
    each_div = each_div.split(">")[1]  # everything after the first ">"
    each_div = each_div.split("<")[0]  # everything before the other "<"
    f.write(str(each_div) + "\n")

rawDescription: Python How to remove characters from a string inside a list


rawDescription: Setting path in Python

description: Setting path in Python


code: L = re.findall(r'https?://[^/"]+/', site_str)

rawDescription: Python regex alternation

description: Python regex alternation


code:
@cache
def get_url_src(url):
    return urllib.urlopen(url).read()

rawDescription: Caching in urllib2?

description: Caching in urllib2


code:
import sys
from math import floor

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QEvent
from PyQt4.QtGui import QTableView, QAbstractItemView

from modeltest import TestModel

DEFAULT_ROW_HEIGHT = 30

class App(QtGui.QApplication):
    """Main application class"""

    def __init__(self, sys_argv):
        """Constructor for App"""
        super(App, self).__init__(sys_argv)

        self.tableView = QTableView()
        self.tableView.resize(500, 400)
        self.tableView.setAttribute(QtCore.Qt.WA_DeleteOnClose)  # Fix QObject::startTimer error message.
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setAlternatingRowColors(True)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.tableView.installEventFilter(self)

        self.model = TestModel()
        self.tableView.setModel(self.model)

        self.tableView.show()

    def setScrollBarVisibility(self, emptyRowCount):
        if emptyRowCount > 0:
            self.tableView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        else:
            self.tableView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)

    def eventFilter(self, source, event):
        if event.type() == QEvent.Resize and source is self.tableView:
            totalRowNumber = (self.tableView.height()) / DEFAULT_ROW_HEIGHT
            self.model.updateRows(floor(totalRowNumber))
            self.setScrollBarVisibility(self.model.emptyRowCount())
        if event.type() == QEvent.KeyPress:
            if event.key() == QtCore.Qt.Key_Return:
                self.model.addRow()
                self.setScrollBarVisibility(self.model.emptyRowCount())
            elif event.key() == QtCore.Qt.Key_Delete:
                self.model.delRow()
                self.setScrollBarVisibility(self.model.emptyRowCount())

        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    app = App(sys.argv)
    sys.exit(app.exec_())

rawDescription: Fill in QtableView's bottom space with empty rows


code:
with open("data1.txt", "r") as f1, open("data2.txt", "r") as f2:
    lines = set(f1) # efficient 0(1) lookups using a set
    for line in f2: # single pass over large file
        if line in lines:
            print(line)

rawDescription: Match lines in two text files

description: Match lines in two text files


code:
paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)")

def getParens(s):
  return paren_pattern.findall(s)

rawDescription: Match series of (non-nested) balanced parentheses at end of string


code:
carIndex = next((index for index, car in enumerate(cars)
if any(x in car.name for x in ("VW","Poodles"))), -1)

rawDescription: Python: How to re-use list comprehensions after they are created in an expression


code:
sel = [(x, 1-y) for x,y in sel]
sel

rawDescription: python, rebuilding lists

description: Python, rebuilding lists


code:
def run_logistic(xn,r,iterates):
    iteration = 1
    xn_list = []
    while iteration <= iterates:
        xn1 = logistic_map(xn,r)
        iteration = iteration + 1
        xn = xn1
        xn_list.append(xn)
    return xn_list # Put return outside while-loop to get full list of values

rawDescription: While loop executes once during return, runs fine during print [python]


code:
(u'Houston', u'Houst')           (u'Alabama', u'Alab')
(u'Florida State', u'FlaSt')     (u'North Carolina State', u'NCSt')
(u'Penn State', u'PnSt')         (u'Iowa', u'Iowa')
(u'Oklahoma', u'Okla')           (u'Texas', u'Texas')
(u'Florida Atlantic', u'FlAtl')   (u'South Florida', u'SFla')
(u'Georgia', u'Geo')             (u'Tennessee', u'Tenn')
(u'San Jose State', u'SJSU')     (u'Idaho', u'UI')
(u'Washington State', u'WshSt')   (u'Arizona State', u'ArzSt')
(u'Fresno State', u'FrsSt')      (u'Nevada', u'Nevad')
(u'Oregon State', u'OSU')        (u'Arizona', u'ARIZ')
(u'Clemson', u'Clem')            (u'Virginia Tech', u'VTech')
(u'Chattanooga', u'UTC')         (u'Arkansas', u'AR')
(u'USC', u'USC')                 (u'Stanford', u'Stanf')
(u'Baylor', u'BU')               (u'Colorado', u'CU')
(u'North Texas', u'NoTex')       (u'Louisiana-Lafayette', u'LaLaf')
(u'Tulane', u'TLN')              (u'Army', u'ARMY')
(u'Troy', u'TROY')               (u'Florida International', u'FIU')
(u'Louisiana-Monroe', u'ULM')    (u'Arkansas State', u'ASU')
(u'Texas Tech', u'TT')           (u'Iowa State', u'ISU')
(u'Akron', u'AKRON')             (u'Western Michigan', u'WMU')
(u'Liberty', u'LIBERTY')         (u'Toledo', u'TOLEDO')
(u'Virginia', u'Virg')           (u'Middle Tennessee', u'MTnSt')
(u'Oklahoma State', u'OKSt')     (u'Texas A&M', u'TexAM')
(u'Notre Dame', u'NDame')        (u'UCLA', u'UCLA')
(u'Rutgers', u'Rutgr')           (u'Cincinnati', u'Cincy')
(u'Ohio State', u'OhSt')         (u'Purdue', u'Prdue')
(u'LSU', u'LSU')                 (u'Florida', u'Fla')
(u'Air Force', u'AFA')           (u'UNLV', u'UNLV')
(u'Nebraska', u'Neb')            (u'Missouri', u'Misso')
(u'New Mexico State', u'NMxSt')   (u'Boise State', u'BoiSt')
(u'Pittsburgh', u'Pitt')         (u'Navy', u'Navy')
(u'Wake Forest', u'WFrst')       (u'Florida State', u'FlaSt')
(u'San Jose State', u'SJSt')     (u'Hawaii', u'Hawa')
(u'UCF', u'UCF')                 (u'South Florida', u'SFla')

rawDescription: Pythonic Name Matching

description: Pythonic Name Matching


code:
positions = {j:i for i, j in enumerate(ids)}
result = sorted(Record.objects.filter(id__in=ids), key=lambda r:positions[r.id])

rawDescription: Python how to sort list of objects based on their attribute according to another list


code:
with open("test.txt") as f:
    keys = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
    d = dict.fromkeys(keys, 0)
    for flt in map(float, f):
        k = round(flt + .05, 1) if flt > .05 else .1
        if flt not in d:
            d[k] += 1
        else:
            d[flt] += 1

rawDescription: to clustter the floating point data into suitable buckets in python

description: To clustter the floating point data into suitable buckets in python


code:
import numpy
a = numpy.zeros((6,6), dtype=numpy.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1

from scipy.ndimage import convolve

kernel = np.ones((3, 3))
kernel[1, 1] = 0
b = convolve(a, kernel, mode="constant")
b[a != 0].sum()

rawDescription: Calculate number of equal neighbouring cells within a numpy array


code:
pattern = r"""(?x)   # turn on verbose mode (ignores whitespace and comments)
    \[       # match a literal open bracket '['
    [^\]]*   # match zero or more characters, as long as they are not ']'
    \]       # match a literal close bracket ']'
        |        # alternation, match either the section above or the section below
    \S+      # match one or more non-space characters
    """

values = re.findall(pattern, line) # findall returns a list with all matches it finds

rawDescription: Space delimited, except inside braces in a log file - Python


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

from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline

x = np.array([0., 4., 9., 12., 16., 20., 24., 27.])
y = np.array([[2.9, 4.3, 66.7, 91.4, 109.2, 114.8, 135.5, 134.2],
              [0.9, 17.3, 69.7, 81.4, 119.2, 124.8, 155.5, 144.2]])

x_all = np.ravel(x + np.zeros_like(y))
y_all = np.ravel(y)

plt.scatter(x, y[0], label="training points 1", c='r')
plt.scatter(x, y[1], label="training points 2", c='b')

x_plot = np.linspace(0, max(x), 100)

for degree in np.arange(4, 5, 1):
    model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=3, fit_intercept=False))
    model.fit(x_all[:, None], y_all)
    y_plot = model.predict(x_plot[:, None])
    plt.plot(x_plot, y_plot, label="degree %d" % degree)

    ridge = model.named_steps['ridge']
    print(degree, ridge.coef_)

plt.legend(loc='best')

rawDescription: How to obtain only one parameter set for a polynomial fit when several data sets are taken into account?

description: Obtain only one parameter set for a polynomial fit when several data sets are taken into account


code:
# Get sorted "rows"
sorted_rows = rows[np.argsort(rows[:,0])]

# Get count of elements for each ID
_,count = np.unique(sorted_rows[:,0],return_counts=True)

# Form mask to fill elements from X-column
N1 = count.max()
N2 = len(count)
mask = np.arange(N1) < count[:,None]

# Form a 2D matrix of ID's with each row for each unique ID
ID_2Darray = np.empty((N2,N1))
ID_2Darray.fill(-np.Inf)
ID_2Darray[mask] = sorted_rows[:,1]

# Get ID based max indices
grp_max_idx = np.argmax(ID_2Darray,axis=1) + np.append([0],count.cumsum()[:-1])

# Finally, get the "maxed"-X rows
out = sorted_rows[grp_max_idx]

rawDescription: How to get rows from numpy 2d where column value is maximum from group by other column?

description: Get rows from numpy 2d where column value is maximum from group by other column


code:
def download(self, file, dest_path=None, dest_filename=None, callback=None):
    """
    Download a file by it's file object
    """
    self.download_file(None, None, file=file[1], dest_path=dest_path, dest_filename=dest_filename, is_public=False, callback=callback)

rawDescription: Parsing print in python

description: Parsing print in python


code:
['" A lot of important text"']
['"A lot of important text"']
['"1. List of text pertaining to Title3 "', '"2. List of items for Title 3"', '"3. the number of listed items is variable for every page"', '"4. Sometimes no list at all"']
[]

rawDescription: HTML parsing with lxml, python, .tail being broken up by <br> tags


code:
class escaped:
  def __init__(self, property_to_wrap):
    # we wrap the property object created by the other decorator
    self.property = property_to_wrap

  def __get__(self, instance, objtype=None):
    # delegate to the original property
    original_value = self.property_to_wrap.__get__(instance, objtype)
    # ... change the data however you like
    return frotz(original_value)

  def __set__(self, instance, new_value):
    actual_value = frob(new_value)
    self.property.__set__(instance, actual_value)

  ...

rawDescription: How to automatically escape properties when they are being set/retrieved?

description: Automatically escape properties when they are being set/retrieved


code:
from subprocess import call
call(["python ./dir1/script1 -o &"], shell=True)
call(["python ./dir2/script2 -o &"], shell=True)

rawDescription: How to submit 2 jobs (to run 2 python scripts in parallel located in 2 different directories) in linux?

description: Submit 2 jobs (to run 2 python scripts in parallel located in 2 different directories) in linux


code:
class DatabaseCacheExtended(DatabaseCache):
    def get_where(self, query, default=None, version=None):
        db = router.db_for_read(self.cache_model_class)
        table = connections[db].ops.quote_name(self._table)

        with connections[db].cursor() as cursor:
            cursor.execute("SELECT cache_key, value, expires FROM %s "
                           "WHERE cache_key LIKE %%s" % table, [query])
            rows = cursor.fetchall()
        if len(rows) < 1:
            return {}
        return_d ={}
        for row in rows:
            value = connections[db].ops.process_clob(row[1])
            return_d[row[0]] = pickle.loads(base64.b64decode(force_bytes(value)))
        return return_d

rawDescription: Enumerating keys in Django Database Cache


rawDescription: Setting a variable equal to a returned value from a for loop in Python


code:
def add_child(self, node, parent):
    if self.data == parent:
        self.children.append(node)
        return
    for child in self.children:
        child.add_child(node, parent)

rawDescription: How to add a grandchild to a python tree?

description: Add a grandchild to a python tree


code:
w, h = freqz(b, a, worN=1000)
plot(w/np.pi, np.abs(h))

rawDescription: Filter gain issue when using scipy.signal in Python


code: encoded_message = bytes('{:0>5d}{:1}'.format(len(msg), msg), 'utf-8')

rawDescription: Byte formatting in python 3

description: Byte formatting in python 3


code:
import csv
f = open('myclone.csv', 'rb')
reader = csv.reader(f)
headers = reader.next()
headers
column = {}
for h in headers:
   column[h] = []
column
for row in reader:
  for h, v in zip(headers, row):
    column[h].append(v)
column
column['workers']
column['constant']
column['age']

rawDescription: How to import a csv file using python with headers intact, where first column is a non-numerical

description: Import a csv file using python with headers intact, where first column is a non-numerical


code:
comma_separated = ','.join(some_list)
return redirect(url_for('show_list', some_list=comma_separated))
# returns something like 'http://localhost/show_list?some_list=a,b,c,d'

rawDescription: How can I "redirect" to another URL and pass a list object using Flask


code:
import matplotlib.pyplot as plt

f = plt.figure()
arrow = plt.arrow(0, 0, 0.5, 0.6, 'dummy',label='My label')
plt.legend([arrow,], ['My label',])

rawDescription: Matplotlib legend for an arrow

description: Matplotlib legend for an arrow


code: subprocess.call(["activate", value])

rawDescription: How do you activate an Anaconda environment within a Python Script?

description: Activate an Anaconda environment within a Python Script


code:
dumped = pickle.dumps(mydict, 0)
timeit.timeit('pickle.loads(dumped)', 'from __main__ import pickle, dumped', number=10000)
dumped = pickle.dumps(mydict, 1)
timeit.timeit('pickle.loads(dumped)', 'from __main__ import pickle, dumped', number=10000)
dumped = pickle.dumps(mydict, 2)
timeit.timeit('pickle.loads(dumped)', 'from __main__ import pickle, dumped', number=10000)

rawDescription: Why does it take longer to dump and load with pickle.HIGHEST_PROTOCOL?


rawDescription: pandas dataframe selecting the nan indexes

description: Pandas dataframe selecting the nan indexes


code:
dialogue = 'Ooh! French Vanilla!'
self.Coffee = self.fontType.render(dialogue, 0, (0,0,0))

rawDescription: Pygame - Is There A Way To Get The String From fontType.render?


code:
import re
re.sub('\s+', '', sample_html_string)

rawDescription: Replace paragraph mark in string

description: Replace paragraph mark in string


code: False

rawDescription: Distinguishing large integers from near integers in python


code:
import itertools

# from itertools recipes in the docs
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def shouldbesimple(originalfile):
    with open(originalfile) as inputfile, open('finaloutput.txt', "w") as outputfile:
        client = next(inputfile).rstrip()
        count = int(next(inputfile).rstrip())
        groups = grouper(inputfile, 4)

        Header = "stuff at beginning of each record in output"
        Insertclient = "NEEDED {1} CHANGES"
        Line1 = "THINGS I {0} MUST ADD"
        Footer = "stuff at end of each record in output"
        thingstoadd = [Header, Line1, Insertclient, Footer]

        for _ in range(count):
            for fmt, line in zip(thingstoadd, next(groups)):
                outputfile.write(fmt.format(line.rstrip(), Client) + '\n')

rawDescription: string formatting issue within an iterative loop

description: String formatting issue within an iterative loop


code:
from django import forms

class FormA(forms.ModelForm):
    [...]

class FormB(forms.ModelForm):
    [...]

rawDescription: Django forms question

description: Django forms question


code:
def sorted_triples(L):
    # Transform [a, b, c, d, e, f, ...] into [(a, b, c), (d, e, f), ...]
    triples = [L[i:i+3] for i in range(0, len(L), 3)]

    # Sort each triple by float value of second element in reverse order
    triples.sort(key=lambda t: float(t[1]), reverse=True)

    # Flatten list of triples
    return [x for t in triples for x in t]

rawDescription: Sorting list nested in tuples

description: Sorting list nested in tuples


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
  return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: I want to use matplotlib to make a 3d plot given a z function


code:
import Tkinter as tk

root = tk.Tk()
frame = tk.Frame(root)
frame.grid(row=0,column=0)
buttons = [tk.Button(frame,text=str(i)) for i in range(6)]
for i,b in enumerate(buttons):
    b.grid(row=i,column=0)

textbox = tk.Text(root)
textbox.grid(row=0,column=1)

root.mainloop()

rawDescription: Python Tkinter Layout Problems

description: Python Tkinter Layout Problems


code:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst[1::2]  # Remember that Python indexes start at 0

rawDescription: Understanding a line of code

description: Understanding a line of code


code:
class Demo(object):
    def __init__(self, value=None):
        self._value = value

    @chached_property_if_None
    def value(self):
        # some calculations to get value
        return value

rawDescription: How to have a decorator return a (cached) property iff it was previously None?

description: Have a decorator return a (cached) property iff it was previously None


code: ' '.join(s.split())

rawDescription: How to remove extra spaces in a string?

description: Remove extra spaces in a string


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

fig, axes = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True)

for ax in axes.flat:
    ax.bar(range(5), np.random.random(5), color=np.random.random((5,3)))

for ax, col in zip(axes[0,:], ['A', 'B', 'C']):
    ax.set_title(col, size=20)
for ax, row in zip(axes[:,0], ['D', 'E', 'F']):
    ax.set_ylabel(row, size=20)

plt.show()

rawDescription: How to label rows/cols of a matrix of plots?

description: Label rows/cols of a matrix of plots


code:
names_and_nums = [x.split() for x in (bob, james, longname)]
longest_length = max(len(name) for (name, num) in names_and_nums)
format_str = "{: <" + str(longest_length) + "}{}"
for name, num in names_and_nums:
    print(format_str.format(name,  num))

rawDescription: Replace integer with number of spaces

description: Replace integer with number of spaces


rawDescription: count how many of an object type there are in a list Python

description: Count how many of an object type there are in a list Python


code:
from threading import Thread
from Queue import Queue
import sys
import time

class Performer():
    def __init__(self):
        self.active = False
        self.queue = Queue()

    def action(self, line):
        pass # your code should be here

    def operate(self, text_file, threads=5):
        with open(text_file) as f:
            for line in f:
                self.queue.put(line)

        self.active = True
        thread_pool = []
        for i in range(threads):
            t = Thread(target=self.__thread, name=('worker-%d' % i))
            t.daemon = True
            t.start()
            thread_pool.append(t)

        while self.active:
            try:
                if self.queue.empty():
                    break
            except KeyboardInterrupt:
                self.active = False
                sys.exit('user + keyboard = byebye')
            else:
                time.sleep(1)

    def __thread(self):
        while self.active:
            if not self.queue.empty():
                try:
                    self.action(self.queue.get())
                except Exception:
                    pass # do something here

rawDescription: How to interrupt a program while it's running?

description: Interrupt a program while it's running


rawDescription: numpy.ma.cov - pairwise correlations for with missing values?

description: Numpy.ma.cov - pairwise correlations for with missing values


rawDescription: Python Requests - Use navigate site by servers IP


code:
fig1 = figure(figsize=(4, 4), facecolor='white')
ax = fig1.add_subplot(111)
ax.contour(X, Y, Z)

rawDescription: How can I attach a pyplot function to a figure instance?

description: Attach a pyplot function to a figure instance


code:
p = poly.Polynomial(poly.polyfit(x, a, x.size-1))
plot(x, np.sin(x), '-', x, a, 'o', x, p(x), ':')

rawDescription: python cross section curve fitting

description: Python cross section curve fitting


code:
def update(char1, laser_list): # fewer parameters
    # key reading stuff, as before, which sets the local variable `facing`

    for laser in laser_list:       # loop over all lasers in the list
        if laser.firedir == "up":  # check an attribute of the laser for its direction
            laser.rect.y -= 4
        elif laser.firedir == "down":
            laser.rect.y += 4
        elif laser.firedir == "left":
            laser.rect.x -= 4
        elif laser.firedir == "right":
            laser.rect.x += 4

    return facing  # the returned facing will be used for lasers fired in the next frame!

rawDescription: How can I change the location of a projectile in pygame without changing its facing every loop?

description: Change the location of a projectile in pygame without changing its facing every loop


code:
def get_integral(tt):
    intarray = np.zeros_like(tt)
    step_size = tt[1] -tt[0]
    for i,t in enumerate(tt):
        intarray[i] = intarray[i-1] + g(t)*step_size
    return intarray

rawDescription: python - scipy.integrate.odeint returning wrong results

description: Python - scipy.integrate.odeint returning wrong results


code:
#models.py

CAPRICORN = 'Capricorn'
AQUARIUS = 'Aquarius'
PISCES = 'Pisces'
ARIES = 'Aries'
TAURUS = 'Taurus'
GEMINI = 'Gemini'
CANCER = 'Cancer'
LEO = 'Leo'
VIRGO = 'Virgo'
LIBRA = 'Libra'
SCORPIO = 'Scorpio'
SAGITTARIUS  = 'Sagittarius'

SIGN_CHOICES = (
    (1, CAPRICORN,
     2, AQUARIUS,
     3, PISCES,
     4, ARIES,
     5, TAURUS,
     6, GEMINI,
     7, CANCER,
     8, LEO,
     9, VIRGO,
     10, LIBRA,
     11, SCORPIO,
     12, SAGITTARIUS)
  )

class Sign(models.Model):
    signtype = models.CharField(choice=SIGN_CHOICES)
    astro_date = models.DateField()
    headline = models.CharField(max_length=255)
    headcontent = models.TextField()
    rating = RatingField()
    love_rate = models.CharField(max_length=255)

rawDescription: django - get_or_create() is not saving to sqlite db

description: Django - get_or_create() is not saving to sqlite db


code:
def cut_line_at_points(line, points):

    # First coords of line (start + end)
    coords = [line.coords[0], line.coords[-1]]

    # Add the coords from the points
    coords += [list(p.coords)[0] for p in points]

    # Calculate the distance along the line for each point
    dists = [line.project(Point(p)) for p in coords]

    # sort the coords based on the distances
    # see http://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list
    coords = [p for (d, p) in sorted(zip(dists, coords))]

    # generate the Lines
    lines = [LineString([coords[i], coords[i+1]]) for i in range(len(coords)-1)]

    return lines

rawDescription: Shapely Split LineStrings at Intersections with other LineStrings


code:
a
b

rawDescription: Python numba.jit types

description: Python numba.jit types


rawDescription: OpenCV get centers of multiple objects

description: OpenCV get centers of multiple objects


code:
results=[]
while idqueue.qsize()<nbprocess:
   pass
while resultqueue.qsize()>0:
   results.append(resultqueue.get())

rawDescription: python multiprocessing - pool allocation

description: Python multiprocessing - pool allocation


code:
for times in range(50):
    start = time.time()
    #do some stuff
    stop = time.time()
    duration = stop-start
    print(duration)

rawDescription: How do I get the time execution for each iteration? Python

description: Get the time execution for each iteration? Python


code:
l = re.split('Overview of (\w+) study', text)[1:]
l = [l[i:i+2] for i in range(0, len(l), 2)]

# or just `final_list = l` if it doesn't matter
final_list = []

for i in [[(i, k) for k in re.findall('\(.+?\)', j)] for i, j in l]:
    final_list.extend(i)

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


code:
#!/usr/bin/env python
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.
"""
This module provides code for doing k-nearest-neighbors classification.

k Nearest Neighbors is a supervised learning algorithm that classifies
a new observation based the classes in its surrounding neighborhood.

Glossary:
distance   The distance between two points in the feature space.
weight     The importance given to each point for classification.

Classes:
kNN           Holds information for a nearest neighbors classifier.

Functions:
train        Train a new kNN classifier.
calculate    Calculate the probabilities of each class, given an observation.
classify     Classify an observation into a class.

    Weighting Functions:
equal_weight    Every example is given a weight of 1.

"""

import numpy

class kNN:
    """Holds information necessary to do nearest neighbors classification.

    Members:
    classes  Set of the possible classes.
    xs       List of the neighbors.
    ys       List of the classes that the neighbors belong to.
    k        Number of neighbors to look at.

    """
    def __init__(self):
        """kNN()"""
        self.classes = set()
        self.xs = []
        self.ys = []
        self.k = None

def equal_weight(x, y):
    """equal_weight(x, y) -> 1"""
    # everything gets 1 vote
    return 1

def train(xs, ys, k, typecode=None):
    """train(xs, ys, k) -> kNN

    Train a k nearest neighbors classifier on a training set.  xs is a
    list of observations and ys is a list of the class assignments.
    Thus, xs and ys should contain the same number of elements.  k is
    the number of neighbors that should be examined when doing the
    classification.

    """
    knn = kNN()
    knn.classes = set(ys)
    knn.xs = numpy.asarray(xs, typecode)
    knn.ys = ys
    knn.k = k
    return knn

def calculate(knn, x, weight_fn=equal_weight, distance_fn=None):
    """calculate(knn, x[, weight_fn][, distance_fn]) -> weight dict

    Calculate the probability for each class.  knn is a kNN object.  x
    is the observed data.  weight_fn is an optional function that
    takes x and a training example, and returns a weight.  distance_fn
    is an optional function that takes two points and returns the
    distance between them.  If distance_fn is None (the default), the
    Euclidean distance is used.  Returns a dictionary of the class to
    the weight given to the class.

    """
    x = numpy.asarray(x)

    order = []  # list of (distance, index)
    if distance_fn:
        for i in range(len(knn.xs)):
            dist = distance_fn(x, knn.xs[i])
            order.append((dist, i))
    else:
        # Default: Use a fast implementation of the Euclidean distance
        temp = numpy.zeros(len(x))
        # Predefining temp allows reuse of this array, making this
        # function about twice as fast.
        for i in range(len(knn.xs)):
            temp[:] = x - knn.xs[i]
            dist = numpy.sqrt(numpy.dot(temp,temp))
            order.append((dist, i))
    order.sort()

    # first 'k' are the ones I want.
    weights = {}  # class -> number of votes
    for k in knn.classes:
        weights[k] = 0.0
    for dist, i in order[:knn.k]:
        klass = knn.ys[i]
        weights[klass] = weights[klass] + weight_fn(x, knn.xs[i])

    return weights

def classify(knn, x, weight_fn=equal_weight, distance_fn=None):
    """classify(knn, x[, weight_fn][, distance_fn]) -> class

    Classify an observation into a class.  If not specified, weight_fn will
    give all neighbors equal weight.  distance_fn is an optional function
    that takes two points and returns the distance between them.  If
    distance_fn is None (the default), the Euclidean distance is used.
    """
    weights = calculate(
        knn, x, weight_fn=weight_fn, distance_fn=distance_fn)

    most_class = None
    most_weight = None
    for klass, weight in weights.items():
        if most_class is None or weight > most_weight:
            most_class = klass
            most_weight = weight
    return most_class

rawDescription: Finding k-nearest neighbors for a given vector?


code:
urlpatterns = patterns('',
  url(r'^', include('stock_app.urls')),
)

rawDescription: How to restrict one url to only one view in django urls

description: Restrict one url to only one view in django urls


code: dir(str)

rawDescription: Regarding dir()

description: Regarding dir()


code:
from itertools import product ,permutations
p=list(permutations(['2','3','4']))
l=[('-'+i,'-'+j,'-'+k) for i,j,k in permutations(['2','3','4'])]
new=zip(l,p)
new
list(list(product(*zip(j,i))) for i,j in new)

rawDescription: How can I generate a list like this with python

description: Generate a list like this with python


code: wcscpy(command, _PyOS_optarg);

rawDescription: How to get python interpreter full argv command line options?

description: Get python interpreter full argv command line options


code:
applicationURLs (
    "file:///Applications/calibre.app/",
    "file:///Applications/Archiver.app/",
    "file:///Applications/Pacifist.app/",
    "file:///System/Library/CoreServices/Archive%20Utility.app/"
)

rawDescription: OSX: programmatically get list of applications for a file


code: sorted(l)

rawDescription: How to sort a dictionary by a value passed through a function?

description: Sort a dictionary by a value passed through a function


code:
def unique_chars_set(s):
    return len(s) == len(set(s))

def unique_chars_frozenset(s):
    return len(s) == len(frozenset(s))

def unique_chars_counter(s):
    return Counter(s).most_common(1)[0][1] > 1

def unique_chars_sort(s):
    ss = ''.join(sorted(s))
    prev = ''
    for c in ss:
        if c == prev:
            return False
        prev = c
    return True

def unique_chars_bucket(s):
    buckets = 255 * [False]
    for c in s:
        o = ord(c)
        if buckets[o]:
            return False
        buckets[o] = True
    return True

rawDescription: What is the fastest way to check if a string contains repeating characters in Python 3?


code:
import tables
import numpy as np

filename = 'outarray.h5'
ROW_SIZE = 100
NUM_COLUMNS = 200

f = tables.open_file(filename, mode='w')
atom = tables.Float64Atom()

array_c = f.create_earray(f.root, 'data', atom, (0, ROW_SIZE))

for idx in range(NUM_COLUMNS):
    x = np.random.rand(1, ROW_SIZE)
    array_c.append(x)
f.close()

rawDescription: save numpy array in append mode

description: Save numpy array in append mode


rawDescription: Custom pipeline for Cordova social auth

description: Custom pipeline for Cordova social auth


code: setattr(x, 'minutes', 40)

rawDescription: Map variables to dictionary values, and call with reference to key?


code:
def FirstTransaction(c):
    if c == "2013" :
        return  ('wow')
    elif c == "2010" :
        return  ('yeaaaa')

rawDescription: Timestamp url with function

description: Timestamp url with function


code: objects = objects.order_by('priority')

rawDescription: How can i find next highest value in django query

description: Find next highest value in django query


code:
class Card(object):
    # has self.value and self.suit

    def __str__(self):
        return (str(self.value) + self.suit)

rawDescription: Python - __str__ returning elements of a list


code:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    return render_template('login.html',
                           title='Sign In')

rawDescription: Using Google OAuth2 with Flask

description: Using Google OAuth2 with Flask


code:
[['GR', 'Hellas', 'Greece'],
 ['SE', 'Sverige', 'Sweden'],
 ['NO', 'Norge', 'Norway']]

rawDescription: Python: Compare lists and combine in common fields


code:
Animals = [[d['animal'] for d in sub] for sub in MyList]
Colors = [[d['color'] for d in sub] for sub in MyList]

rawDescription: Making a list comprehension for a dict within a list within a list


rawDescription: How can I capture a value from a string and then remove it?

description: Capture a value from a string and then remove it


code:
ROOT_DIR = '/some/path/to/array/files/'
array_files = glob.glob(os.path.join(ROOT_DIR, '*.corr.npy'))

rawDescription: Plot arrays same extension Matlotlib

description: Plot arrays same extension Matlotlib


code:
import pandas as pd
import os
import sys

class RedirectStdStreams(object):
    def __init__(self, stdout=None, stderr=None):
        self._stdout = stdout or sys.stdout
        self._stderr = stderr or sys.stderr

    def __enter__(self):
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush(); self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, exc_type, exc_value, traceback):
        self._stdout.flush(); self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

if __name__ == '__main__':

    devnull = open('log.txt', 'w')

    #replaces sys.stdout, sys.stderr, see http://stackoverflow.com/a/6796752/2901002
    with RedirectStdStreams(stdout=devnull, stderr=devnull):
        df = pd.read_csv('data.csv', warn_bad_lines=True, error_bad_lines=False)

rawDescription: Pandas Bad Lines Warning Capture

description: Pandas Bad Lines Warning Capture


code:
def sorted_uniq(your_list):
    table = {}
    for s in your_list:
        table[s] = None
    k = table.keys()
    k.sort()
    return k

rawDescription: Dedupe and sort a list in Python 2.2

description: Dedupe and sort a list in Python 2.2


code:
import requests
from pprint import pprint
params = {'name': ['val1', 'val2', 'val3', 'val4']}
url = 'http://httpbin.org/get'
response = requests.get(url, params=params)
pprint(response.json())
url = 'http://httpbin.org/post'
response = requests.post(url, data=params)
pprint(response.json())

rawDescription: Post request with many params in Python

description: Post request with many params in Python


code:
# We use our mixin
class MyTestCase(FileAssertions, TestCase):
    def test_some_paths(self):
        # Test all permissions
        self.assertFileMode('/foo/bar', user='rwx', group='rx', others='')

        # Only test user permissions
        self.assertFileMode('/foo/bar', user='rwx')

        # We support the suid/sgid bits as well
        self.assertFileMode('/foo/bar', user='rwxs', group='rxs', others='rx')

rawDescription: Better assertEqual() for os.stat(myfile).st_mode


code:
list1 = [[ 2, '+', 4 ], [ 4, '-', 6 ], [ 8, '+', 2 ]]
list2 = [[ 2, '-', 4 ], [ 4, '-', 2], [ 8, '+', 2 ]]
expressions = {}
for left, op, right in list1 + list2:
    expressions.setdefault((left, op), []).append(right)

[[left, op] + [sum(rights) // len(rights)] for (left, op), rights in expressions.items()]

rawDescription: Combining lists in python with unique elements but changing the third


code:
def translate_from_dict(original_text,dictionary_of_translations):
    out = original_text
    for target in dictionary_of_translations:
        trans = str.maketrans(target,dictionary_of_translations[target])
        out = out.translate(trans)
    return out

trans = {"abc":"cda"}
out = translate_from_dict("abcabc",trans)
print(out)

rawDescription: String translate using dict

description: String translate using dict


code: out[i, j] == array[idxs[j, i], j]

rawDescription: Numpy advanced indexing using a 2D array of row indices without broadcasting the output


code:
class MyInt(int):
    def __iadd__(self, other):
        return self.__class__(self - other)

rawDescription: Is it possible to be a virtual subclass of a built in type?


code:
from string import maketrans
t = maketrans(''.join(key.keys()) , ''.join(key.values()))
"ABCDEFGZYXW".translate(t)

rawDescription: Replace multiple characters atomicaly

description: Replace multiple characters atomicaly


code:
# method that is recursively applied to set the next one
def recursive_trial(first, depth, maxdepth):
    # all ones are placed: check the grid
    if depth == maxdepth:
        return checkgrid()
    # enumerate possible grid positions as idx == 5 * r + c
    for idx in xrange(first, 25 - (maxdepth - depth + 1)):
        # get row and column idx
        r = idx / 5
        c = idx % 5
        # skip the middle
        if grid[r,c] == 1:
            continue
        # set entry to one
        grid[r,c] = 1
        # call method recursively to place missing ones until 7 in the remainder of the array
        if recursive_trial(idx + 1, depth + 1, maxdepth):
            return True
        # set entry back to zero
        grid[r,c] = 0
    # at this point, we failed with the current configuration.
    return False

rawDescription: 5*5 grid, in every 3*3 square of the grid must be 4 "lights"


rawDescription: Nested List of Lists to Single List of tuples


rawDescription: d3 - how to select specific element from g and transform it

description: D3 - how to select specific element from g and transform it


code: User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name))

rawDescription: Django - User full name as unicode

description: Django - User full name as unicode


code:
if __name__ == '__main__':
    p = Thread(target=login, args=(name,pwd))
    p.start()
    p.join()

rawDescription: should I use multiprocessing in all function call from the start function?

description: Should I use multiprocessing in all function call from the start function


code:
import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]

new_a = np.delete(a, index)

print(new_a) #Prints `[1, 2, 5, 6, 8, 9]`

rawDescription: How to remove specific elements in a numpy array

description: Remove specific elements in a numpy array


code:
integers = set()
while len(integers) < 10:
    integers.add(input("Enter an integer: "))

rawDescription: how to reject duplicate values

description: Reject duplicate values


code:
# choose needs a sequence of length 20, so move last axis to front
In [22]: aa = np.rollaxis(a, -1)

In [23]: c = np.choose(b, aa)

In [24]: all(c[i, j] == a[i, j, b[i, j]] for i in range(10) for j in range(10))
Out[24]: True

rawDescription: Index numpy nd array along last dimension


code:
import timeit
trials = 1000000
print("Integer exponent:")
print("pow(2, 100)")
print(timeit.timeit(stmt="pow(2, 100)", number=trials))
print("math.pow(2, 100)")
print(timeit.timeit(stmt="m_pow(2, 100)", setup='import math; m_pow=math.pow', number=trials))
print("2 ** 100")
print(timeit.timeit(stmt="2 ** i", setup='i=100', number=trials))
print("2.0 ** 100")
print(timeit.timeit(stmt="2.0 ** i", setup='i=100', number=trials))
print("Float exponent:")
print("pow(2.0, 100.0)")
print(timeit.timeit(stmt="pow(2.0, 100.0)", number=trials))
print("math.pow(2, 100.0)")
print(timeit.timeit(stmt="m_pow(2, 100.0)", setup='import math; m_pow=math.pow', number=trials))
print("2.0 ** 100.0")
print(timeit.timeit(stmt="2.0 ** i", setup='i=100.0', number=trials))
print("2.01 ** 100.01")
print(timeit.timeit(stmt="2.01 ** i", setup='i=100.01', number=trials))

rawDescription: Why is 2**100 so much faster than math.pow(2,100)?


code:
def main():
    # Initial balance
    balance = input ('Wallet balance: ')

# This constructs the infinite loop
while True:

    # Initial balance
    balance = input('Wallet balance: ')

    # Withdraw amount from wallet balance
    withdraw= input('Withdraw amount: ')

    #If there is no balance to withdraw from
    if balance < 1:
        print('You have no funds to withdraw.')

    # Withdraw process and new balance display
    if balance > 0:
        new = balance - withdraw
        print('Your new balance: ' + str(new))
main()

rawDescription: What am i doing wrong in this attempt at an infinite loop?


code:
# read the file into a list of lines
with open('data.csv','r') as f:
    lines = f.read().split("\n")

print("Number of lines is {}".format(len(lines)))

word = 'someword' # dummy word. you take it from input

# iterate over lines, and print out line numbers which contain
# the word of interest.
for i,line in enumerate(lines):
    if word in line: # or word in line.split() to search for full words
        print("Word \"{}\" found in line {}".format(word, i+1))

rawDescription: How to find on which line a specific word is. [python]

description: Find on which line a specific word is. [python]


code:
from collections import Counter
def isAnagram(str1, str2):
    return Counter(str1) == Counter(str2)

def find_anagrams_in_word_list(str1, str_list):
    return [word for word in str_list if isAnagram(str1, word)]

rawDescription: Comparing a string with a list of strings to find anagrams in Python


code:
from sympy import symbols
from numpy import linspace
from sympy import lambdify
import matplotlib.pyplot as mpl

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)
lam_x = lambdify(t, x, modules=['numpy'])

x_vals = linspace(0, 10, 100)
y_vals = lam_x(x_vals)

mpl.plot(x_vals, y_vals)
mpl.ylabel("Speed")
mpl.show()

rawDescription: Python - Using Sympy Equations for Plotting


code: lambda letter: lalala

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
)

rawDescription: Django: Redirect to previous page after login


rawDescription: How do i find the percentage of the most common element in a list?

description: Find the percentage of the most common element in a list


code: Board = [el for el in startBoard]

rawDescription: (Python) adding a list to another without the brackets


rawDescription: Ordinal numbers replacement

description: Ordinal numbers replacement


code:
# File: factories.py
from .models import Book
import factory

starting_seq_num = 0

class BookFactory(factory.Factory):
  FACTORY_FOR = BookModel
  title = factory.Sequence(lambda n: u'Title #{}'.format(n))

  @classmethod
  def _setup_next_sequence(cls):
      # Instead of defaulting to starting with 0, start with starting_seq_num.
      return starting_seq_num

# File: make_data.py
import factories

factories.starting_seq_num = 100
factories.BookFactory().create()

rawDescription: How to pass in a starting sequence number to a Django factory_boy factory?

description: Pass in a starting sequence number to a Django factory_boy factory


rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


code: fichier = open(repertoire+"C:/Program Files/EasyPHP-DevServer-14.1VC9/data/localweb/projects/Administration/bonsDeCommandes" + nom_fichier, "No13");

rawDescription: Calling Python file from within PHP

description: Calling Python file from within PHP


code:
def set_fonts(axis):
    axis.set_title(axis.get_title(), **titleFont)
    axis.set_ylabel(axis.get_ylabel(), **axesFont)
    axis.set_xlabel(axis.get_xlabel(), **axesFont)
    return axis

rawDescription: Matplotlib: set label font without setting label


code:
import time, datetime

# this is how your time object was constructed before
tm_isdst = 0
t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst))
print("Old conversion: {0}".format(datetime.datetime.fromtimestamp(t)))

# this is what happens if you let mktime "divine" a time zone
tm_isdst = -1
t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst))
print("New conversion: {0}".format(datetime.datetime.fromtimestamp(t)))

rawDescription: Python datetime.datetime from time.structtime difference


rawDescription: Passing Python Data to JavaScript via Django


rawDescription: Django ORM and templates, how do I view all of the variables available for a given QuerySet?


code: ax.xaxis.labelpad = 8

rawDescription: Python subplots leaving space for common axis labels


rawDescription: How to implement this Depth-First-Search in a Sudoku Solver

description: Implement this Depth-First-Search in a Sudoku Solver


code:
from datetime import datetime, timedelta
t1 = datetime.utcnow()
t2 = t1 + timedelta(milliseconds=500)

rawDescription: How to get real three digits of microseconds in Python?

description: Get real three digits of microseconds in Python


code:
class Books():
    def __init__(self):
        self._referTable = 1

    @property
    def referTable(self):
        return self._referTable if self._referTable else 2

rawDescription: Built-in non-data version of property?

description: Built-in non-data version of property


code:
checkerboard=arr[idx].reshape(w,h//2)
print(checkerboard)
print(checkerboard.shape)
# [[ 1  3]
#  [ 4  6]
#  [ 9 11]
#  [12 14]
#  [17 19]
#  [20 22]]
# (6, 2)

rawDescription: getting pixels value in a checkerboard pattern in python

description: Getting pixels value in a checkerboard pattern in python


code: Button (root, text="+", command=add_line(N)).grid(row=N, column=2, padx=3)

rawDescription: Tkinter: How to dynamically change layout


code:
if __name__ == '__main__':
    t = tk.Tk()
    t.iconbitmap('icon.ico')

    b = tk.Button(text='test', command=exit)
    b.grid(row=0)

    t.mainloop()

rawDescription: Tkinter locks python when Icon loaded and tk.mainloop in a thread


code:
import pymc

def testit(passed, test_p = 0.8, alpha = 5, beta = 2):
    Pi = pymc.Beta( 'Pi', alpha=alpha, beta=beta)
    Tj = pymc.Bernoulli( 'Tj', p=test_p)

    @pymc.deterministic
    def flipper( Pi=Pi, Tj=Tj):
            return Pi if Tj else (1-Pi)
            # Pij = Pi if Tj else (1-Pi)
            # return pymc.Bernoulli( 'Rij', Pij)

    Rij = pymc.Bernoulli( 'Rij', p=flipper, value=passed, observed=True)

    return locals()

vars = testit(1.)
model = pymc.MCMC(vars)
model.sample(iter=10000, burn=1000, thin=10)

rawDescription: How do I get parameters from a posterior distribution in PyMC?

description: Get parameters from a posterior distribution in PyMC


rawDescription: list of list concept in python

description: List of list concept in python


rawDescription: How to get different colors in python turtle

description: Get different colors in python turtle


code: df.column.fillna('0',inplace = True)

rawDescription: Pandas: how to fill null values matching the right types of that column?


code:
def sequences(l):
    x2 = cycle(l)
    next(x2)
    grps = groupby(l, key=lambda j: j + 1 == next(x2))
    for k, v in grps:
        if k:
            t = tuple(v) + (next(next(grps)[1]),)
            yield t, len(t)

def sequences(l):
    x2 = cycle(l)
    next(x2)
    grps = groupby(l, lambda j: j + 1 == next(x2))
    yield from ((t, len(t)) for t in (tuple(v) + (next(next(grps)[1]),)
                                      for k, v in grps if k))

def sequences(x):
        it = iter(x)
        prev, temp = next(it), []
        while prev is not None:
            start = next(it, None)
            if prev + 1 == start:
                temp.append(prev)
            elif temp:
                yield tuple(temp + [prev]), len(temp) + 1
                temp = []
            prev = start

rawDescription: Finding groups of increasing numbers in a list


code: only_some_values = [[x[2]] for x in alist]

rawDescription: Iterate over a list of list, not returning all item from sub-list


code: ('This_DT', 'is_VBZ', 'POS_NNP', 'example_NN')

rawDescription: python: How to use POS (part of speech) features in scikit learn classfiers (SVM) etc

description: Python: How to use POS (part of speech) features in scikit learn classfiers (SVM) etc


code:
rect1 = self.hAA.create_rectangle(..., tags=("special",))
rect2 = self.hAA.create_rectangle(..., tags=("special",))
...
self.hAA.itemconfigure("special", ...)

rawDescription: Python+Tkinter: Redrawing a rectangle in a canvas based on some % value


code:
x = np.array([1,2,2,3])
y, inverse = np.unique(x, return_inverse=True)
y
inverse
np.bincount(inverse)
np.column_stack((y,np.bincount(inverse)))

rawDescription: Grouping repetitions in an array?

description: Grouping repetitions in an array


code:
a = A()
a.hello()
a = B(a)
a.hello()

rawDescription: Cast an object to a derived type in Python


code:
def createClickableSubclass(parent):
    class ClickableSubclass(parent):
        clicked_ = QtCore.Signal(QtGui.QMouseEvent)

        def __init__(self, *args, **kwargs):
            super(ClickableSubclass, self).__init__(*args, **kwargs)

        def mousePressEvent(self, event):
            self.clicked_.emit(event)

    return ClickableSubclass

MyLabel = createClickableSubclass(QtGui.QLabel)
MyToolBar = createClickableSubclass(QtGui.QToolBar)

rawDescription: Implement event handlers for QWidget and derived classes and avoid code duplication


rawDescription: Packing 4 Integers as ONE BYTE?

description: Packing 4 Integers as ONE BYTE


code: df1.join(df2, how='outer', rsuffix='_')

rawDescription: In Pandas, merge two dataframs with complex multi-indexing


code:
fig = df.value.value_counts().sort_index().plot(kind="bar")
plt.savefig("figure.png")

rawDescription: Plotting a histogram in Pandas with very heavy-tailed data


rawDescription: How to split a string by a string except when the string is in quotes in python?

description: Split a string by a string except when the string is in quotes in python


code:
template = """My {pet} {}ate my {object}.
This is a float: {number:0.2f}.
{integer:10d} is an integer on a newline.
Here is another 'fixed' input: {}"""
out_string = template.format('spot ', 7, **d)
print(out_string)

rawDescription: Reversing C-style format strings in Python (`%`)


rawDescription: Store NumPy Row and Column Headers

description: Store NumPy Row and Column Headers


code: dict((k,v) for k,v in my_dict.items() if k[0] == 'Peter')

rawDescription: Extracting key/value pair from dictionary


code:
if request.user in project.project_collaborators.all():
    nodes = project.node_set.all()
else:
    nodes = project.node_set.filter(collaborators=request.user)

rawDescription: Select all of django foreign key model if condition or part if another condition


code:
b_flat = pd.DataFrame([[i, x]
              for i, y in input['B'].apply(list).iteritems()
                   for x in y], columns=list('IB'))
b_flat = b_flat.set_index('I')

rawDescription: Flatten a column with value of type list while duplicating the other column's value accordingly in Pandas


code:
from bs4 import BeautifulSoup
s = """
Google

Google12

Google13
"""
soup = BeautifulSoup(s,'html.parser')
for i in soup.select("h2.hello-word > a"):
    print(i.text)

rawDescription: How do I get the value of a soup.select?

description: Get the value of a soup.select


code:
from itertools import combinations

for group in by_name.items():
    for pair in combinations(group, 2):
        yield pair  # list(pair) if you need lists

rawDescription: finding unique combinations of elements in a list of lists

description: Finding unique combinations of elements in a list of lists


code:
n = 17**987273 # 1.2 million digits number
digits = int(math.log10(n))
k = digits - 24 # i.e. first 24 digits
n / (10 ** k)

rawDescription: Accessing the highest digits of large numbers from Python long


code:
def compare_two_lists(list1,list2):
    lRet = []                         #a
    for i in range(len(list2)):       #b
        j= i%2                        #c
        sublist1 = list1[j]
        sublist2 = list2[i]
        lRet.append([x for x in sublist1 if x in sublist2])
    return lRet

compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])

rawDescription: python matching list of lists

description: Python matching list of lists


code:
k = int(input())
numbers = list(range(k+1))
numbers

rawDescription: python: how can i create a list of integers,to a number?

description: Python: how can i create a list of integers,to a number


code:
example = 'The quick brown fox jumps over the lazy dog!'.encode('base64')
remove_tail(example + '*This is a tail').decode('base64')

rawDescription: How to extract valid string from beginning to the first no base64 valid character?

description: Extract valid string from beginning to the first no base64 valid character


code:
def force_ctrl(iv, ev): ev.state |= gtk.gdk.CONTROL_MASK
iconview.connect('key-press-event', force_ctrl)
iconview.connect('button-press-event', force_ctrl)

rawDescription: Gtk IconView select multiple without Ctrl?


code:
from sys import exit
from Tkinter import *
from subprocess import Popen, PIPE
from time import sleep
from os.path import exists
import os, time, sys, ttk

#Initialize Tkinter by creating Tk root widget, which is a window with a
Root = Tk()
Root.title("VIZ TOOL")

class Command:
    def __init__(self, func, *args, **kw):
        self.func = func
        self.args = args
        self.kw = kw
    def __call__(self, *args, **kw):
        args = self.args+args
        kw.update(self.kw)
        self.func(*args, **kw)

 #Script definitions#

def quitter():
    exit(0)

#Button organization and layout#

Sub0 = Frame(Root)
Sub = Frame(Sub0)

#X mesh node
Label(Sub, text = "Create x mesh nodes").grid(columnspan=3)

#x min text box area
v1=StringVar()
#Create entry widge to get user input, in this case a text string for the x

Entry(Sub, textvariable=v1).grid(row=1, column=0)
Label(Sub, text = "min").grid(row=2, column=0)

#x max text box area
v2=StringVar()
Entry(Sub, textvariable=v2).grid(row=1, column=1)
Label(Sub, text = "max").grid(row=2, column=1)
#x step text box area
v3=StringVar()
Entry(Sub, textvariable=v3).grid(row=1, column=2)
Label(Sub, text = "step increment").grid(row=2, column=2)

Sub.pack(side = TOP)
Frame(Sub0,height=1, relief = GROOVE, bg="black").pack(side = TOP, fill =
BOTH, pady= 5)

#GUI Organization#

Sub0.pack(side = TOP, padx = 10)

Button(Root, text = "Quit", command = quitter).pack(side = TOP, pady = 5)

#The window will not appear until we enter the Tkinter event loop. Script

Root.mainloop()

rawDescription: set Tkinter label widget below entry widget

description: Set Tkinter label widget below entry widget


rawDescription: Finding letters in a string

description: Finding letters in a string


code:
totals = {}
for k,v in original_list:
  totals[k] = totals.get(k,0) + v

# totals = {'a': 2, 'c': 2, 'b': 7}

rawDescription: finding duplicates in a list of lists

description: Finding duplicates in a list of lists


code:
from celery import Celery

app = Celery('tasks', backend='amqp', broker='amqp://')

@app.task
def add(x, y):
    return x + y

rawDescription: Celery - Activate a task via command line or HTTP requests


code:
import string
import random
data = string.ascii_lowercase + string.digits
x = ''.join(random.choice(data) for n in range(20))

rawDescription: How to write alphanumeric codes to a file in Python?

description: Write alphanumeric codes to a file in Python


code:
add(
    age, (height - (weight * (iq / 2)))
)

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


code:
df['Diff'] = pd.to_timedelta((df['End_Time'] == '00:00:00').astype(int), unit='d')
# 0   1 days
# Name: End_Time, dtype: timedelta64[ns]

rawDescription: How to convert the time from 00:00 to 24:00 in python

description: Convert the time from 00:00 to 24:00 in python


code:
try:
    with open("Vowels.txt","r") as in_file:
        txt = in_file.read()
        count = {x:sum([1 for char in txt if char==x])for x in 'aeiouy'}
        print(count)
except IOError:
        print("The text file is not found")
        sys.exit(1)

rawDescription: Vowel counter in a text file

description: Vowel counter in a text file


code:
'abc' in d
'def' in d

rawDescription: Find index in a list of dictionaries

description: Find index in a list of dictionaries


code:
@app.route('/test/<command>/<path:path>')
def test(command, path):
    args = path.split('/')
    return " ".join(args)

rawDescription: Flask route rule as function args

description: Flask route rule as function args


code: print("Thanks {} for participating in the quiz.".format(StudentName))

rawDescription: Text after variable print command

description: Text after variable print command


code: output

rawDescription: How to find reoccuring string groups (order does not matter) in a dictionary of lists?

description: Find reoccuring string groups (order does not matter) in a dictionary of lists


rawDescription: Python 3.5 csv parsing with special characters


code: df

rawDescription: How to sum over all values between 2 repeating values in pandas?

description: Sum over all values between 2 repeating values in pandas


rawDescription: Pandas: replicating SASs proc means by attribute out=agg


code:
class Foo:
    def __init__(self):
        self.active = False

    def isActive(self):
        return self.active

    def doThing(self):
        if not self.isActive(): return
        print("Just a Foo here, boss")

class Bar(Foo):
    def __init__(self):
        super().__init__()

    def doThing(self):
        if not self.isActive(): return
        print("I shouldn't be showing unless I'm active!")

rawDescription: Python class method merge

description: Python class method merge


code: Counter(x for sublist in my_list for x in sublist)

rawDescription: counting element occurences in nested lists

description: Counting element occurences in nested lists


code:
from collections import Counter
Counter( ['a','b','a','c','b','a','c'] )

rawDescription: count each element in list without .count

description: Count each element in list without .count


code:
from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

rawDescription: Python : List of dict, if exists increment a dict value, if not append a new dict


code:
def makelist(filename, keys):
    result = []
    with open('%s.txt' % filename) as f:
        for line in f:
            result.append(dict(zip(keys, line.split('|'))))
    return result

rawDescription: How to make a list of dictionaries for unknown number of keys in dictionary?

description: Make a list of dictionaries for unknown number of keys in dictionary


code: EOF

rawDescription: Can Gnuplot take different arguments at run time? maybe with Python?


code:
x
inv

rawDescription: How to write this numpy code in vectorized form?

description: Write this numpy code in vectorized form


rawDescription: Extract sub-lists recursively from main list


code:
def mega_calculator(fn, repeat=1000):
    def helper(*args):
        total = 0
        for _ in range(repeat):
            total += fn(*args)
        return total / repeat
    return helper

def add(a, b):
    return a + b

repeated = mega_calculator(add, 10)
repeated(5, 6)

rawDescription: how to access *args input from parent function?

description: Access *args input from parent function


code:
import subprocess
subprocess.call(['ssh pi@theraspberrypi ./myscript'], shell=True)

rawDescription: How to run a bash script from another computer?

description: Run a bash script from another computer


code: sprintf(zarray, "%f\n", z_angle);

rawDescription: Passing char array from c++ (client) to python(server) winsock


rawDescription: Create a table of permutation data python


code:
def decode_with_string(codes):
    number_of_cols = max(ceil(math.log(v, 100)) for v in codes)
    str_format = '{:0%dd}'%(2*number_of_cols) # prepare to format numbers as string
    return [[int(str_format.format(int(code))[2*i:2*i+2]) # extract the wanted digits
             for i in range(number_of_cols)] # for all columns
            for code in codes] # for all rows

rawDescription: Converting an array to a float, how to reverse the process?


code:
class Pita( object ):
    __slots__ = ('pocket',)
    marker = object()
    def __init__(self, v=marker):
        if v is not self.marker:
            self.pocket = v
    def __call__(self, v=marker):
        if v is not self.marker:
            self.pocket = v
        return self.pocket

rawDescription: Most Pythonic way equivalent for: while ((x = next()) != END)


code:
with open('my_file.py', 'r') as f:
    lines = [line for line in f if line.strip()[0] != '#']

with open('my_file.py', 'w') as f:
    f.writelines(lines)

rawDescription: as removing a line commented python file?

description: As removing a line commented python file


rawDescription: How to decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python?

description: Decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python


rawDescription: python regexp remove last numbers from string

description: Python regexp remove last numbers from string


rawDescription: Adding Python to Windows environmental variables


code:
def gen_data(levels, size):
    choices = 'abcdefghijklmnopqrstuvwxyz'
    levels = np.asarray([l for l in choices[:nlevels]])
    index = np.random.random_integers(0, levels.size - 1, size)
    b = levels[index]
    x = np.arange(1, size + 1)
    return x, b

rawDescription: Applying a function by bins on a vector in Numpy


code:
['value1', 'value2']
['yyy']

rawDescription: How to ConfigParse a file keeping multiple values for identical keys?


code:
s = requests.Session()
s.auth = (username, password)

response = s.get('http://wiki.company.com/wiki_page')
print(response.text)

rawDescription: Unable to retain login credentials across pages while using requests


code:
c = np.array([[0,1,1],[2,1,0]])  # note that this data has dupes for max in row 1
d = np.array([[0,10,10],[20,10,0]]) # data to be chaged
c_argmax = np.argmax(c,axis=1)[:,np.newaxis]
b_map1 = c_argmax == np.arange(c.shape[1])
# now use the bool map as you described
d[b_map1] += 1
d
[out]
array([[ 0, 11, 10],
       [21, 10,  0]])

rawDescription: Mask One 2D Numpy Array By Argmax Along Axis Of Another Array


code:
import heapq
h = []
heapq.heappush(h, 4)
heapq.heappush(h, 3)
heapq.heappush(h, 9)
heapq.heappush(h, 5)
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))

rawDescription: python queue using embedded list

description: Python queue using embedded list


code:
words = ["jam", "honey", "choc"]
condition = " or ".join("contains(@href, '%s')" % word for word in words)
links = browser.find_elements_by_xpath("//a[%s]" % condition)

rawDescription: Python SeleniumExtract href containing specific strings


rawDescription: "Best" pythonic way to retreive an item from a list based on two criteria


code:
...
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
...

rawDescription: Tkinter, Canvas refuses to expand or contract when window resized


code:
from bs4 import BeautifulSoup

data = """

                    AGFA ACCUSET, 1994 (46965)

                    Equipements :
AGFA 9800

WITH RIP VIPER N°2

FILM PROCESSOR GLUNZ AND JENSEN ML35 n°26498

(LAIZE 450/600mm)

Spectraset 2200

                    Availability : IMMEDIATE

"""

soup = BeautifulSoup(data)
print(soup.tr.td.get_text())

rawDescription: Get Text outside of tags as well

description: Get Text outside of tags as well


code: Freshman['ADMIT_DATE'] = pd.to_datetime(Freshman['ADMIT_DATE'].astype(str), format='%Y%m')

rawDescription: How to convert a column of type integer to type datetime in python?

description: Convert a column of type integer to type datetime in python


code:
TYPE_CODE = "8700"
REMAINDER = "00000000fe80000000000000026097fffe0769ea01010000860580da"
icmpv6_chunk = build_icmpv6_chunk(TYPE_CODE, REMAINDER)

rawDescription: Computing 16-bit checksum of ICMPv6 header


rawDescription: Python Help: Creating a dict of {str:list of str} from csv file


code:
def add_mean_value(mgrp):
    mgrp['meanvalue'] = mgrp[mgrp['Name'] == 'Print buffer']['value'].mean()
    return mgrp
data = data.groupby(['Block', 'Concentration', 'Name']).apply(add_mean_value)

def max_sum_value(mgrp):
    mgrp['meanvalue'] = mgrp['meanvalue'].max()
    return mgrp
data = data.groupby(['Block']).apply(max_sum_value)

data['newvalue'] = data['value'] - data['meanvalue']
print(data)

rawDescription: looping through dataframe add rows to column pandas python

description: Looping through dataframe add rows to column pandas python


rawDescription: numpy histogram cumulative density does not sum to 1

description: Numpy histogram cumulative density does not sum to 1


rawDescription: Finding minimum value element-wise in three 2d submatrices


rawDescription: Find Indices Of Columns Having Some Nonzero Element In A 2d array


code:
import os
import os.path

new_list = []

for each in texture_filename_list:
    file_name = os.path.basename(each)
    new_list.append(file_name)

rawDescription: extracting only texture filenames being used in maya file from the list of filename paths

description: Extracting only texture filenames being used in maya file from the list of filename paths


rawDescription: Coverting a string to an array in python


code:
index = pd.date_range("2011-01-01", periods=5, freq="80d")
df = pd.DataFrame({"temp": np.random.random(5)}, index=index)
df

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


rawDescription: How can I sort a list numerically rather than alphabetically?

description: Sort a list numerically rather than alphabetically


code:
class BaseParser(object):
    ...

class CSVParser(BaseParser):
    ...
register_feed_parser(CSVParser, ['text/plain', 'text/csv'])
...

parsers = get_registered_feed_parsers(feed['mime_type'])
data = None
for parser in parsers:
    try:
        data = parser(feed['data'])
        if data is not None: break
    except ParsingError:
        pass
...

rawDescription: Template driven feed parsing

description: Template driven feed parsing


code:
def __matrix_fib__(n, k):
    if n == 1:
        return [0, 1]
    else:
        f = __matrix_fib__(n / 2, k)
        c = k * f[0] * f[0] + f[1] * f[1]
        d = f[1] * (f[1] + 2 * k * f[0])
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, k * c + d]

def fib(n, k=1):
    assert (n >= 0)
    if n == 0:
        return n
    else:
        return __matrix_fib__(n, k)[1]

rawDescription: Dynamically changing the recursion limit for a fibonnacci program python


code: (s if s in good_characters else ' ' for s in country)

rawDescription: Use an External file to replace special characters?


rawDescription: Matrix multiplication gives unsual result in Python (SciPy/PyLab)


code:
med
values

rawDescription: python if elif different result

description: Python if elif different result


code:
from heapq import heappush
test = [[]] * 4
heappush(test[2],6)
heappush(test[2],7)
test

rawDescription: How to use a array of heaps in python

description: Use a array of heaps in python


code:
def __init__(self, objfile):
    self.config = ConfigParser.ConfigParser(allow_no_value=True)
    self.config.readfp(objfile)
    #and i do my stuffs

rawDescription: Python fabric calling scrip "remote path"


rawDescription: Restricting function to unique dates - Multi-Index


code: int(value)

rawDescription: Parsing or Splitting pysnmp output to update into database


code: '--bass_cut_off=0 --out=something.wav'

rawDescription: How to replace a words near the specific word in a text file using python

description: Replace a words near the specific word in a text file using python


rawDescription: python proper way to decode raw udp packet

description: Python proper way to decode raw udp packet


code:
res, c = [], 1
for x in num_words:
    c += x
    res.append(c)
res

rawDescription: Do math of list - python

description: Do math of list - python


rawDescription: How to cast object in Python

description: Cast object in Python


rawDescription: Python, fastest way to iterate over regular expressions but stop on first match


code: print([re.findall(r'(\w+_\w+)', line) for line in i.split('\n')])

rawDescription: Extract variable names from file

description: Extract variable names from file


code:
file1_common_words = dict(Counter(all_words_in_file1).most_common(50))
file2_common_words = dict(Counter(all_words_in_file2).most_common(50))

rawDescription: How to compare most common words in on text file to other text file

description: Compare most common words in on text file to other text file


code:
from lxml import etree

data = [['SEC.12.0', '\\\\DATA\\LOC', '\\\\ftp\\location'], ['SEC.13.0', '\\\\DATA\\LOC2', '\\\\ftp\\location2']]

COMBO = """<combo>
    {0}
</combo>"""

ITEM = """
    <pro>{0}</pro>
    <dataloc>{1}</dataloc>
    <ftploc>{2}</ftploc>
"""

output = COMBO.format("".join([ITEM.format(*line) for line in data]))

with open('data.xml', 'w') as f:
    f.write(output)

rawDescription: Creating xml file using ElementTree or lxml


code:
set(ListOne) - set(ListZero)
Excess = list(set(ListOne)-set(ListZero))

rawDescription: Can I give the user an option to chose an element from the list based on its position in the list using python?

description: Give the user an option to chose an element from the list based on its position in the list using python


rawDescription: How to calculate the sum of all columns of a 2D numpy array (efficiently)

description: Calculate the sum of all columns of a 2D numpy array (efficiently)


code:
pig_words = []

for word in sentence.split():
    if word[0] in VOWELS:
        pig_latin = word + "ay"
    else:
        pig_latin = word[1:] + word[0] + "ay"
    pig_words.append(pig_latin)

return pig_words

rawDescription: Python Simple Loop in function

description: Python Simple Loop in function


rawDescription: How to do this GROUP BY query in Django's ORM with annotate and aggregate

description: Do this GROUP BY query in Django's ORM with annotate and aggregate


code:
def convert_decimal(json_data):
    stack = [json_data]
    while stack:
        json_data = stack.pop()
        for k, v in get_items(json_data):
            if isinstance(v, Decimal):
                json_data[k] = str(v)
            else:
                stack.append(v)

rawDescription: Convert python decimal to string in deeply nested and unpredictable list


code:
n = 1000
x = np.random.rand(n)
y = np.random.rand(2*n)

rawDescription: finding nearest items across two lists/arrays in Python

description: Finding nearest items across two lists/arrays in Python


code:
import itertools

# collect all the names involved
names = itertools.chain.from_iterables(f.values() for f in friendships)
query = 'SELECT name, id FROM People WHERE name in (%s)' \
             % ','.join(mysql_escape(n) for n in names)

rawDescription: Python/MySQL get data from table based on values in a dictionary


code:
def getEpisodeTuple(iterable):
    episodeTuple = [episodeChunk(chunk)
        for chunk in iterable
        if episodeChunk(chunk)]
    if episodeTuple:
        assert len(episodeTuple) == 1
        return episodeTuple[0]
    else:
        return None

rawDescription: My first Python program! Anyone care to review it an help me improve?


code:
from __future__ import print_function

def row(seq):
    result = []
    for i in range(1, len(seq)):
        start = seq[:i]
        end = seq[i:]
        startsum = sum(start)
        endsum = sum(end)
        diff = abs(startsum - endsum)
        print(start, end, startsum, endsum, diff)
        result.append((diff, i))

    t = min(result)
    print('min', t)
    i = t[1]
    return seq[:i], seq[i:]

a = [-11, 15, 14, 12, 12]

print(a)
print(row(a))

rawDescription: How can i make a general coding from my function?

description: Make a general coding from my function


code:
while True:
  gdb.execute("step")
  sp = gdb.parse_and_eval("$sp")
  # Do something with sp.

rawDescription: How to step through code line-by-line with python and examine the stack

description: Step through code line-by-line with python and examine the stack


code:
subbedlines = []

with open('sample','r') as textreader:
    lines = textreader.read().split('\n')

for line in lines:
    subbedlines.append(re.sub('.*#= min, max\s', "HOLA", line))

rawDescription: Replacing 'match' object with string, Python


code:
print(good)
print(bad)

rawDescription: Prevent terminal character set switch on data printing


code:
if __name__=='__main__':
    try:
        func = sys.argv[1]
    except:
        func = None

functions = {
              "function1": function1,
              "function2": function2
              }

if func in functions:
    functions[func]()

rawDescription: python calling custom function from bash shell

description: Python calling custom function from bash shell


code:
unorderedPosts = Post.objects.all()
if request.user.is_authenticated():
    preferences=request.user.categorypreference_set.filter(on=False)
    for preference in preferences: #filter by category preference
        unorderedPosts=unorderedPosts.exclude(category_name=preference.category_name)
latest_post_datetime = unorderedPosts.aggregate(Max('created'))['created__max']

original_start_time = datetime.datetime.now() - datetime.timedelta(hours=startHours)
latest_post_day_start_time = datetime.datetime.combine(latest_post_datetime.date(), original_start_time.time())
# a timedelta guaranteed to be less than 24 hours
time_shift = latest_post_day_start_time - latest_post_datetime
timewindow = datetime.timedelta(hours=4)
if time_shift.days >= 0:
    extra_windows_needed = time_shift.seconds / timewindow.seconds
else:
    # negative timedeltas store negative days, then positive seconds; negate
    extra_windows_needed = -(abs(time_shift).seconds) / timewindow.seconds
start_time = latest_post_day_start_time - (timewindow * (extra_windows_needed + 1))
posts = unorderedPosts.filter(created__gte=start_time).order_by('-upVote')
return posts

rawDescription: How to optimize this function for returning posts in a feed. Django

description: Optimize this function for returning posts in a feed. Django


code:
import matplotlib.pyplot as plt
plt.imshow(data)
plt.show()

rawDescription: Python 2D Gaussian Fit with NaN Values in Data


code:
first_tuple_list = [tuple(lst) for lst in first_list]
secnd_tuple_list = [tuple(lst) for lst in secnd_list]

rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


code: clean(' 32v2 g #Gmw845h$W b53wi ')

rawDescription: how do I convert a string to a valid variable name in python?

description: Convert a string to a valid variable name in python


code:
user = UserProfile(user=request.user)
user.weekOne.squats += 5
user.weekOne.save()
user.save()

rawDescription: Properly Defining Relationships in Django DB


code:
for row in zip(*contents):
    print(row)

rawDescription: Printing row and columns in reverse

description: Printing row and columns in reverse


code: lambda x: x['id'] in list1

rawDescription: iterate list and compare it's values with dict

description: Iterate list and compare it's values with dict


rawDescription: Is it possible to directly rename pandas dataframe's columns stored in hdf5 file?


code:
lst = [{'score': 93, 'numrep': 0}, {'score': 32, 'numrep': 0}, {'score': 39, 'numrep': 0}, {'score': 81, 'numrep': 0}, {'score': 82, 'numrep': 0}]
[{k: v - 1 if k == 'score' else v for k, v in d.iteritems()} for d in lst]

rawDescription: List of dictionaries - subtract a constant from each dictionary value


rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code:
root.text = "hello"
lxml.etree.tostring(root)

rawDescription: Replace text with HTML tag in LXML text element


code:
from json import JSONEncoder

class LogEncoder(JSONEncoder):
    def default(self, obj):
        try:
            return obj.__dict__ ['records']
        except:
            return obj.__dict__

rawDescription: Serialize LogRecords in Python

description: Serialize LogRecords in Python


rawDescription: Selenium and Python 3 – unable to find element


code: f(**arg_dict('a, b, c, d, e'))

rawDescription: Passing keyword arguments to a function when local variable names are same as function parameter names


code:
import re

numbers = re.compile('\d+(?:\.\d+)?')
numbers.findall("It took 2.3 seconds")

rawDescription: Python: Strip Everything but Numbers

description: Python: Strip Everything but Numbers


code: os.system('xdg-open "%s"' % foldername)

rawDescription: Python Directory Display in Finder, Explorer, Dolphin, etc... (Cross-Platform)


code:
for sourceIP, otherHeader in testDictionary.items():
    if otherHeader[0] == destinationIP:
        testDictionary[sourceIP][-1] += 1

rawDescription: Store and lookup IP Packet header fields in Python


code:
test_cols = data[['a1', 'a4']]
test_vals = np.array(('a1v1', 'a4v1'), test_cols.dtype)

rawDescription: Create a new array from numpy array based on the conditions from a list


code:
from scipy.spatial import cKDTree
import numpy as np
points_ref = np.array([(1, 1), (3, 3), (4, 4), (5, 4), (6, 6)])
tree = cKDTree(points_ref)

rawDescription: Scipy cKDTree nearest neighbor including zeros distance


code:
import random

def randparts(l):
    n = len(l)
    s = random.randint(0, n-1) + 1
    if s >= 2 and n - s >= 2: # the split makes two valid parts
        yield l[:s]
        for p in randparts(l[s:]):
            yield p
    else: # the split would make a single cycle
        yield l

def shuffle_n(s, n):
    idx = range(len(s))
    random.shuffle(idx)
    mapping = dict((x[i], x[i-1])
        for i in range(len(x))
        for x in randparts(idx[:n]))
    return ''.join(s[mapping.get(x,x)] for x in range(len(s)))

rawDescription: How to make a random but partial shuffle in Python?

description: Make a random but partial shuffle in Python


code:
timedelta = sla_list[1] - sla_list[2]
timedelta = '%02d:%02d' % divmod(timedelta.total_seconds(), 60)

rawDescription: Django View Nested Tuple Calculation

description: Django View Nested Tuple Calculation


code:
call_cacheK = {}

def callTest(n, k):
    if (n, k) in call_cacheK:
        return call_cacheK[(n, k)]
    if k == 0:
        return 1
    elif k == n:
        return 1
    elif (1 <= k) and (k <= (n-1)):
        result = ((callTest(n-1, k) + callTest(n-1, k-1)))
        call_cacheK[(n, k)] = result
    print(result)
    return result

rawDescription: Memoization Usage/Cache Storing

description: Memoization Usage/Cache Storing


code:
df = DataFrame(dict(event = randint(10,100,(100)), yes = ['foo','bar']*50))
df.loc[[2,3,5,10,15],'yes'] = np.nan
df.head(10)
mini = df[:20]
mini
Series(mini.yes.values,mini.event).iloc[:10]

rawDescription: Pandas - series creation results in NaN when index is passed in?


rawDescription: How to arrange three lists in such a way that the sum of corresponding elements if greater then appear first?

description: Arrange three lists in such a way that the sum of corresponding elements if greater then appear first


code:
def index(request):
    ctx = {'project_list': Project.objects.all()}
    return render(request, 'construction/index.html', ctx)

rawDescription: django parent child summation in view and pass to a template

description: Django parent child summation in view and pass to a template


code:
class User(object):
   first_name = models.CharField(max_length=255)

   def get_username(self):
       return self.username

class Employee(User, models.Model):
   title = models.CharField(max_length=255)

rawDescription: django abstract models versus regular inheritance

description: Django abstract models versus regular inheritance


code:
args=parser.parse_args('-p one -q two -r three'.split())
args
args_dict = vars(args)
args_dict

rawDescription: Using Argparse and Json together

description: Using Argparse and Json together


code:
directory = 'bin'
if not os.path.exists(directory):
    os.makedirs(directory)

subprocess.call(['make', '-C', 'src'])

rawDescription: Python setup.py call makefile don't include binaries


code:
from unidecode import unidecode
unidecode(mystr)
"doesn't" in unidecode(mystr)

rawDescription: python convert unicode into it's "print" form

description: Python convert unicode into it's "print" form


code: sum(float(close[4]) for close in tickers[30:40])

rawDescription: How do I sum the first value in a set of lists within a tuple?

description: Sum the first value in a set of lists within a tuple


code:
if start:
    slices.append(lst[start:])
    yield slices

rawDescription: Python: breaking a list into all possible sublists


code:
# create G as a copy of A, otherwise you might change A by changing G
G = A.copy()

# getting the mask for all columns except the last one
m = (B[:,0][:,None] != np.arange(d2-1)[None,:]) & (B[:,1]==0)[:,None]

# getting a matrix with those elements of A which fulfills the conditions
C = np.where(m,A[:,:d2-1],0).astype(np.float)

# get the 'modified' average you use
avg = np.sum(C,axis=0)/np.sum(m.astype(np.int),axis=0)

# change the appropriate elements in all the columns except the last one
G[:,:-1] = np.where(m,avg,A[:,:d2-1])

rawDescription: numpy array slicing to avoid for loop

description: Numpy array slicing to avoid for loop


code:
result = df.groupby(np.arange(len(df))//2).sum()
result.index = df.loc[1::2, 'Idx']
print(result)
#             A  B  C
# Idx
# 2004-04-02  2  2  0
# 2004-05-02  0  0  0

# [2 rows x 3 columns]

rawDescription: Pandas Python: Merging every two rows in one dataframe


code:
ONE

TWO

THREE

1

2

3

rawDescription: Python (2.7) dictionary Jinja confusion

description: Python (2.7) dictionary Jinja confusion


code:
import pandas as pd
df = pd.read_csv("group.csv", names=["ID", "category"])
df

rawDescription: fast sorting of a csv file in python

description: Fast sorting of a csv file in python


code:
a = [None, 0, None, None, 0, None, None, None, 0, None, None, None, None, None, 0]
b = [7, 1, 4, 8, 2, 1, 1, 1, 1, 6, 1]
b_iter = iter(b)
[next(b_iter) if i is None else i for i in a]

rawDescription: minimize memory consumption when dealing with python list assignment

description: Minimize memory consumption when dealing with python list assignment


rawDescription: Best way to Convert pairs of base 10 integers to ascii characters in python


code:
from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
    pdf.add_page()
    pdf.image(image,x,y,w,h)
pdf.output("yourfile.pdf", "F")

rawDescription: Create PDF from a list of images

description: Create PDF from a list of images


code:
import numpy as np
arr = np.arange(12).reshape(2,6)

def ndindex_values(arr):
    for idx, value in np.ndenumerate(arr):
        for coord in idx:
            yield coord
        yield value

result = np.fromiter(
    ndindex_values(arr),
    count=arr.size*(len(arr.shape)+1),
    dtype=arr.dtype).reshape(arr.size, -1)

rawDescription: Vector (positionx,positiony,value) of a matrix python


code:
def parse_lemmas(leema_lines):
    for line in lemmas_lines:
        target, from_words_str = line.split(' -> ')
        from_words = from_words_str.split(',')
        for word in from_words:
            yield (word, target)

with open('lemmas.txt', 'r') as lemmas_file:
    lemmas = dict(parse_lemmas(lemma_line.strip() for lemma_line in lemmas_file))

# The dictionary lemmas now has all the lemmas in the lemmas file

rawDescription: How to use lemas list on python

description: Use lemas list on python


code:
from time import sleep
last_sold_stock_time = 0
wait_time = 1

while True:

     # <Condition Code goes here>

    # This is in seconds
    sleep(wait_time)
    # Keep track of how much time has passed.
    last_sold_stock_time += wait_time

rawDescription: condition parameter adjustment

description: Condition parameter adjustment


code: np.savetxt('temp2.txt', x, fmt='%f')

rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code: [sum([x[1] for x in i]) for i in data]

rawDescription: Summing 2nd list items in a list of lists of lists


code:
dist = classifier.prob_classify(features)
for label in dist.samples():
    print("%s: %f" % (label, dist.prob(label)))

rawDescription: python nltk naive bayes probabilities

description: Python nltk naive bayes probabilities


rawDescription: add parameters dynamically in python

description: Add parameters dynamically in python


code:
def __cmp__(self, other):
    if isinstance(other, UUID):
        return cmp(self.int, other.int)
    return NotImplemented

rawDescription: Sorting a list of UUID v1 in python

description: Sorting a list of UUID v1 in python


code:
form_class = None
http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
initial = {}
model = None

rawDescription: How can i access the variables passed in as_view in django

description: Access the variables passed in as_view in django


code:
def getSubdigits(n, a, b):
    n %= 10 ** a
    n //= 10 ** b
    return n

rawDescription: Is using `str` the correct idiom for working with digits in Python


code:
from Crypto.Util import asn1
seq = asn1.DerSequence()
seq.decode(decrypted)
obj = asn1.DerObject()
obj.decode(seq[1])
# now this is the original message digest that was signed
original_message_md = obj.payload

rawDescription: How to get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)

description: Get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)


code:
import win32com.client as win32
import os

excel = win32.gencache.EnsureDispatch('Excel.Application')

for dirpath, dirnames, filenames in os.walk(r'c:\excel_files_folder'):
    for filename in filenames:
        name, ext = os.path.splitext(filename)
        if ext == '.xlsx':
            wb = excel.Workbooks.Open(os.path.join(dirpath, filename))
            wb.DoNotPromptForConvert = True
            wb.CheckCompatibility = False
            excel.DisplayAlerts = False
            wb.SaveAs(os.path.join(dirpath, name + '.xls'), FileFormat=56, ConflictResolution=2)

excel.Application.Quit()

rawDescription: convert xlsx files to xls inside folders and subfolders in Excel VBA or Python

description: Convert xlsx files to xls inside folders and subfolders in Excel VBA or Python


code:
# Define inputs
maskcenters = np.array([
   [1, 1],
   [7, 2],
   [2, 8]])

out_shp = (10,10) # Output array shape
r = 2 # Radius of circles

# Get a disk kernel
X,Y = [np.arange(-r,r+1)]*2
disk_mask = X[:,None]**2 + Y**2 <= r*r

# Initialize output array and set the maskcenters as 1s
out = np.zeros(out_shp,dtype=bool)
out[maskcenters[:,0],maskcenters[:,1]] = 1

# Use binary dilation to get the desired output
out = binary_dilation(out,disk_mask)

rawDescription: Applying a disc shaped mask to several locations in a NumPy array


rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


code:
dsums = divisorSums(MAXNUM)
def memo_s(n):
    if n <= MAXNUM:
        return dsums[n]
    return s(n)

rawDescription: How would I go about improving/making this run faster?


rawDescription: Python: Find monotonic sequences in a list


code:
dis.dis(f)
dis.dis(g)

rawDescription: How do you implement "#ifdef" in python?

description: Implement "#ifdef" in python


code:
import subprocess
import shlex

LS="/bin/ls -l"
FILENAME="inventory.txt"

cmd = '{} {}'.format(LS, FILENAME)
ps = subprocess.Popen(shlex.split(cmd),
                      stdout = subprocess.PIPE,
                      stderr = subprocess.STDOUT)
output, err = ps.communicate()
print(output)

rawDescription: python command substitution for linux commands

description: Python command substitution for linux commands


code:
{'baz_zip': 'zap', 'bam_fie': 'foo', 'foo': 'bar', 'bam_zip_mep': 'mop',
 'baz_fie': 'foo', 'bam_zip_zap': 'zup'}

rawDescription: Transforming deeply nested dictionary to 1D dictionary with Python


code:
x  = []
x.append('{:04b}'.format(10))
print(x)
x.append('{:04b}'.format(2))
print(x)

rawDescription: Inserting binary notation of numbers in python list


code:
set_of_all_items = set(list_of_all_items)
purple_count = len(set(list_of_purple_items).difference(list_of_all_items))
brown_count = len(set(list_of_brown_items).difference(list_of_all_items))
blue_count = len(set(list_of_blue_items).difference(list_of_all_items))

rawDescription: Most efficient way to loop finding items not in a list in python