code:
from math import sin, cos, pi

# The core function of the Bessel integral
def f(m, x, t):
    return cos(m * t - x * sin(t))

#The number of steps used in the Simpson's integral approximation
N = 1000

def J(m, x):
    ''' Approximate Bessel function Jm(x) for integer m '''

    # lower & upper limits of the integral
    a = 0.0
    b = pi

    # step size
    h = (b - a) / N

    # Sum the values for Simpson's integration
    s = f(m, x, a) + f(m, x, b)
    for i in range(1, N):
        t = a + i * h
        if i % 2 == 1:
            s += 4.0 * f(m, x, t)
        else:
            s += 2.0 * f(m, x, t)

    # multiply by h/3 to get the integral
    # and divide by pi to get the Bessel function.
    return s * h / (3.0 * pi)

for x in range(21):
    print(x, J(0, x), J(1, x), J(2, x))

rawDescription: Python numerical integration with Simson's rule


code:
offset -= 3
blob_size_bin = data[offset:offset+3]
blob_size_hex = binascii.b2a_hex(blob_size_bin)
blob_size_dec = int(blob_size_hex, 16)
offset = magic_number_offset - 72
blob = data[offset:offset+blob_size_dec]

rawDescription: Find previous byte that isn't equal to unwanted byte in Python


code:
z = np.sin(.8*xy[:, 1])      # the original z
zw = vq.whiten(z)            # save it under a different name
zn = z / z.std()             # make another 'normalized' array
map(np.std, [z, zw, zn])     # standard deviations of the three arrays
np.allclose(zw, zn)          # whitened is the same as normalized

rawDescription: Using scipy's kmeans2 function in python


rawDescription: Using df.apply() with a Pandas MuliIndex / carrying out operations on hierarchical index rows?


code:
import foo as _foo

SANITIZE = "value2"

class _FooWrapper(object):
    def __getattribute__(self, attr):
        self.change_vars()
        original_function = getattr(_foo, attr)
        if callable(original):
            def wrapper(func):
                def new_func(*args, **kw):
                    res = func(*args, **kw)
                    self.restore_vars()
                    return res
                return new_func
            return wrapper(original)
        return original

    def change_vars(self):
        self.original_sanitize = _foo.SANITIZE
        _foo.SANITIZE = SANITIZE
    def restore_vars(self):
        __foo.SANITIZE = self.original_sanitize

foo = _FooWrapper()

rawDescription: Alter module variables in one module while it doesn't change in the original


code:
with open(fn, 'r') as fin:
    data=[line.split() for line in fin]

rawDescription: How to read in a file with a mixture of different delimiters using Python csv module?

description: Read in a file with a mixture of different delimiters using Python csv module


code:
from itertools import groupby
from csv import  reader
from operator import itemgetter

with open("in.txt") as f:
    print([list(map(itemgetter(1), v))
           for k, v in groupby(reader(f,delimiter=" "), key=itemgetter(0))])

rawDescription: splitting a list into two lists based on a unique value python

description: Splitting a list into two lists based on a unique value python


rawDescription: Matplotlib boxplot without outliers

description: Matplotlib boxplot without outliers


code:
# Get non-empty lines from input file:
relevant_lines = [line for line in open(file_name).readlines() if line.strip()]
# Count them:
num_lines = len(relevant_lines)

import defaultdict
# If a key does not exist in a defaultdict when adding a value for it,
# it will be added with a default value for the given data type
# (0 in case of int):
d = defaultdict(int)

# Iterate through lines; get first character of line
# and increment counter for this character by one in defaultdict:
for line in relevant_lines:
    d[line[0]] += 1

# Print results:
for key, value in d.items():
    print(k + ' appears ' + value + ' times in file.')

rawDescription: How to count the number of times a digit appears at the beginning of each number in a file? (python)

description: Count the number of times a digit appears at the beginning of each number in a file? (python)


code:
class TestB():
    def __init__(self, attr=1):
        self.attr = attr

a = TestB()
b = TestB()
a.attr = 2
a.attr
b.attr

rawDescription: How should I declare default values for instance variables in Python?


code:
answer = (
    'Ten for that? You must be mad!' if does_not_haggle(brian)
    else "It's worth ten if it's worth a shekel.")

rawDescription: How to make a line break on the Python ternary operator?

description: Make a line break on the Python ternary operator


code:
class baseSprite(pyglet.sprite.Sprite):
    def __init__(self, texture, x, y, batch, subgroup):
        self.texture = texture

        super(baseSprite, self).__init__(self.texture, batch=batch, group=subgroup)
        self.x = x + global_settings['player position'][0]#X
        self.y = y + global_settings['player position'][1]#Y

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
class CategoryResource(RestResource):
      def prepare_data(self, obj, data):
            data["subcategories"] = []
            for item in obj.subcategories:
                data["subcategories"].append({"name" : item.name})
            return data

rawDescription: How to Reverse Foreign key in python Flask-peewee


code:
df
df.set_index(['date', 'Country', 'Type']).unstack('Type').reset_index()

rawDescription: Pandas DataFrame: transforming frame using unique values of a column


code:
underscores = ('_', '__')
xx = "text__"
xxx = "text_"
xx.endswith(underscores)
xxx.endswith(underscores)

rawDescription: Python: How to check characters occurrence in string in one line


code:
class Info(QtGui.QWidget):
    def __init__(self,  parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.initUI()
        nuke.addOnScriptSave(self.updateInfo)
        if nuke.root().name() == 'Root' and not nuke.modified():
            # No reason to add a scriptLoad callback if opening a
            # script would spawn a new Nuke process.
            nuke.addOnScriptLoad(self.updateInfo)

    # Rest of the class definition omitted for brevity

rawDescription: refresh(update) widget in Nuke (vfx soft)

description: Refresh(update) widget in Nuke (vfx soft)


code:
import requests
from bs4 import BeautifulSoup

query = 'Thomas Jefferson'

query = query.replace (" ", "+")
#replaces whitespace with a plus sign for Google compatibility purposes

r = requests.get('https://www.google.com/search?q=site:wikipedia.com+{}&gbv=1&sei=YwHNVpHLOYiWmQHk3K24Cw'.format(query))
soup = BeautifulSoup(r.text, "html.parser")
#creates soup and opens URL for Google. Begins search with site:wikipedia.com so only wikipedia
#links show up. Uses html parser.

links = []
for item in soup.find_all('h3', attrs={'class' : 'r'}):
    links.append(item.a['href'][7:]) # [7:] strips the /url?q= prefix
#Guides BS to h3 class "r" where green Wikipedia URLs are located, then prints URLs
#Limiter code to only pull top 5 results

rawDescription: Pull Data/Links from Google Searches using Beautiful Soup


code:
import numpy as np
def identify_pareto_observations(fitness_observations):
    np_array_fitness_observations = np.array(fitness_observations)
    np_array_fitness_observations = np_array_fitness_observations[np.lexnp_array_fitness_observations[:,0].argsort()]
    np_pareto_frontier = np_array_fitness_observations[[0],:]
    for row in np_array_fitness_observations[1:,:]:
        dominated = False
        for nondom in np_pareto_frontier:
            if all([row[x] > nondom[x] for x in range(len(row))]):
                dominated = True
                break
        if not dominated:
            np_pareto_frontier = np.concatenate((np_pareto_frontier, [row]))
    return np_pareto_frontier

rawDescription: unable to correctly identify Pareto observations in 4-dimensional solution space

description: Unable to correctly identify Pareto observations in 4-dimensional solution space


code:
from datetime import datetime, date, time
from django.utils import timezone

date = date(2016, 12, 25)
time = time(12, 0, 0, tzinfo=timezone.get_current_timezone())
aware_datetime = datetime.combine(date, time)

rawDescription: In python, how do I create a timezone aware datetime from a date and time?


code:
query = "LK936033.1 Babesia assembly 454hybrid_PBjelly scaffold Contig1323  7"
seeds = ["assembly","454","scaffold","contig"]
' '.join([i for i in query.split() if not any(w in i.lower() for w in seeds)])

rawDescription: python, remove words in a string from a list

description: Python, remove words in a string from a list


code: return jsonify(my_list_of_eqtls)

rawDescription: Flask jsonify a list of objects

description: Flask jsonify a list of objects


code:
title = tree.xpath('/Title')[0]
genres = title.xpath('Genre')

for element in genres:
    if element.tag == "Genre" and element != title.xpath("Genre[1]")[0]:
        element.getparent().remove(element)

rawDescription: Python ElementTree XML Modifying Elements with Multiple Values


rawDescription: How to access JSON translation from Google Translate API with Python

description: Access JSON translation from Google Translate API with Python


code:
def tups_to_dicts(kv_pairs):
    # split into dictionaries
    ds = []
    for key, val in kv_pairs:
        if not ds or key in ds[-1]:
            ds.append({})
        ds[-1][key] = val
    # pad the empty values
    all_seen_keys = set().union(*ds)
    ds = [{key: d.get(key, '') for key in all_seen_keys} for d in ds]
    return ds

rawDescription: function generates list of dictionaires

description: Function generates list of dictionaires


code: df['inc_index'] = df.mn_earn_wne_p6 // bucket_width

rawDescription: Python/Pandas - Best way to group by criteria?


rawDescription: Using Python with a set of not regular point X,Y,Z in order to create a regular grid where each pixel is the minimum value of the point


rawDescription: XML conversion fails to JSON return object


rawDescription: return pandas DF column with the number of days elapsed between index and today's date

description: Return pandas DF column with the number of days elapsed between index and today's date


rawDescription: Remove NaN and convert to float32 in Python Pandas


code:
sortmap = {x: i for i, x in enumerate("abdcfe")}
sorted('abcdef', key=sortmap.get)

rawDescription: Inheriting from "str" class

description: Inheriting from "str" class


code:
def intToDelim( ba, delim ):
    i=ba.find( delim )
    return int(str(ba[0:i]))

rawDescription: How can I convert a byte array to an integer more elegantly in Python

description: Convert a byte array to an integer more elegantly in Python


code:
Foo.objects.filter(
    Q(m_number__icontains=(request.GET['term']))
).filter(
    co_id = co_id,
    is_active=1
).extra(
    select={
        'int_m_number': 'cast(m_number AS UNSIGNED)',
        'pk': 'pk' ,
        'm_number': 'm_number'
    }
).extra(
    order_by=['int_m_number']
)

rawDescription: Fetch data order by whole numbers instead of order by each digit of a number


code: ['test']

rawDescription: Finding All Defined Functions in Python Environment


rawDescription: Handle Multiple Checkboxes with a Single Serverside Variable


code:
if token in self.commands:
    operator = self.commands[token]
    operator()
    self.stack = []

rawDescription: Adding a string with spaces to a stack

description: Adding a string with spaces to a stack


rawDescription: is there a way to get the index for multiple lists python?

description: Is there a way to get the index for multiple lists python


code: [x*10**pow for pow in xrange(6) for x in xrange(3,10,3)]

rawDescription: how to generate the following list with few words in python?

description: Generate the following list with few words in python


code:
records = self.browse(cr, uid, ids)
totals = [rec.total for rec in records]
average = sum(totals)/len(totals)

rawDescription: How can I loop and access values of fields in OpenERP?

description: Loop and access values of fields in OpenERP


code: passes['Pele'] = ['Messi']

rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


code:
class read_log:
    def __init__(self, exit_status, stdin, stdout, stderr):
        self.exit_status = exit_status
        self.tuple_list = (stdin, stdout, stderr)

rawDescription: Python Class For Reading List Element ,__str__ and class questions


code: from some_module_name import *

rawDescription: Help with PyEPL logging

description: Help with PyEPL logging


code: ['This is D']

rawDescription: Find Node value in xml using etree

description: Find Node value in xml using etree


rawDescription: Parsing string containing Unicode character names


code:
df['percent salary'] = df.groupby(['account'])['salary'].transform(
                           lambda x: x/x.sum())

rawDescription: apply sum calculated using pandas group by to all elements of group

description: Apply sum calculated using pandas group by to all elements of group


code:
zip([1, 2, 3], ['spam', 'ham', 'eggs'])
all(i < 5 for i in range(5))
all(i < 5 for i in range(10))

rawDescription: Varying number of conditions

description: Varying number of conditions


code:
import numpy as np

# 1 Dimension
a = np.ones(2)
b = np.ones(5)
offset = [3]
pad(a, b, offset)

# 3 Dimensions

a = np.ones((3,3,3))
b = np.ones((5,4,3))
offset = [1,0,0]
pad(a, b, offset)

rawDescription: python how to pad numpy array with zeros

description: Python how to pad numpy array with zeros


code:
from google.appengine.ext import ndb

class Story(ndb.Model):
    title = ndb.StringProperty(required=True)
    vote_count = ndb.IntegerProperty(default = 0)

rawDescription: How to use AJAX with Google App Engine (Python)

description: Use AJAX with Google App Engine (Python)


rawDescription: improving a function in python

description: Improving a function in python


code:
import wpf

from System import Uri
from System.IO import Path
from System.Windows import Window
from System.Windows.Media import FontFamily

class MainWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'MainWindow.xaml')
        self.addFont()

    def addFont(self):
        fontDirectory = Path.GetFullPath(".\\Fonts\\")
        uri = Uri(fontDirectory)

        fontFamily = FontFamily(uri, "./#Foo")
        self.textbox.FontFamily = fontFamily

    def get_textbox(self):
        return self._textbox

    def set_textbox(self, value):
        self._textbox = value

    textbox = property(get_textbox, set_textbox)

rawDescription: How to access an embedded font from xaml in Iron Python

description: Access an embedded font from xaml in Iron Python


rawDescription: How to use the variable from the python in rpy2?

description: Use the variable from the python in rpy2


code:
def shoplist(request):
    categories = request.GET.getlist('category')
    if categories:
       products = ShopProduct.objects.filter(shop_product_category_id__in=categories)

rawDescription: Multiple request filtr from url Djjango

description: Multiple request filtr from url Djjango


code:
from apps.app2.models import model1
model1.objects.all()

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code:
locale.setlocale(locale.LC_ALL, 'FR')
locale.format('%.2f', 1.2333333)

rawDescription: How do I change my float into a two decimal number with a comma as a decimal point separator in python?

description: Change my float into a two decimal number with a comma as a decimal point separator in python


code:
from django.utils.thread_support import currentThread
currentThread()

rawDescription: django.utils.thread_support in django 1.5

description: Django.utils.thread_support in django 1.5


code:
def removeTuplesWithOne(lst):
    return (x for x in lst if x[0] != 1)

rawDescription: Removing specific tuples from List

description: Removing specific tuples from List


code:
df
copy = df.copy()
df.ix[0,'a'] = 100
df
copy

rawDescription: Assigning to parent DataFrame affects child DataFrame?


code:
s = sum(my_list)
for my_element in my_list:
    avg_of_others = (s - my_element) / float(len(my_list) - 1)
    ...

rawDescription: Python split list by one element

description: Python split list by one element


code:
def sql_decorator(func):
    def decorated(user, limit):
        table = compute_the_table_somehow(user)
        return func(table, user, limit)
    return decorated

@sql_decorator
def user_records(table, user, limit):
    "sql to select records from %s with user=%s limit %s" % (table, user, limit)

data = user_records('joe', 100)

rawDescription: Python Decorator with extraneous arguments


code:
import numpy as np
from numpy import ma
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from matplotlib.ticker import FixedFormatter, FixedLocator

class CloseToOne(mscale.ScaleBase):
    name = 'close_to_one'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)
        self.nines = kwargs.get('nines', 5)

    def get_transform(self):
        return self.Transform(self.nines)

    def set_default_locators_and_formatters(self, axis):
        axis.set_major_locator(FixedLocator(
                np.array([1-10**(-k) for k in range(1+self.nines)])))
        axis.set_major_formatter(FixedFormatter(
                [str(1-10**(-k)) for k in range(1+self.nines)]))

    def limit_range_for_scale(self, vmin, vmax, minpos):
        return vmin, min(1 - 10**(-self.nines), vmax)

    class Transform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, nines):
            mtransforms.Transform.__init__(self)
            self.nines = nines

        def transform_non_affine(self, a):
            masked = ma.masked_where(a > 1-10**(-1-self.nines), a)
            if masked.mask.any():
                return -ma.log10(1-a)
            else:
                return -np.log10(1-a)

        def inverted(self):
            return CloseToOne.InvertedTransform(self.nines)

    class InvertedTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, nines):
            mtransforms.Transform.__init__(self)
            self.nines = nines

        def transform_non_affine(self, a):
            return 1. - 10**(-a)

        def inverted(self):
            return CloseToOne.Transform(self.nines)

mscale.register_scale(CloseToOne)

if __name__ == '__main__':
    import pylab
    pylab.figure(figsize=(20, 9))
    t = np.arange(-0.5, 1, 0.00001)
    pylab.subplot(121)
    pylab.plot(t)
    pylab.subplot(122)
    pylab.plot(t)
    pylab.yscale('close_to_one')

    pylab.grid(True)
    pylab.show()

rawDescription: Logarithmic plot of a cumulative distribution function in matplotlib


code:
Example.objects.extra(select={'value': 'column1 + column2 + column3'},
                      where=['(column1 + column2 + column3) >= %s'],
                      params=[100])

rawDescription: Django annotation based on multiple columns


code: MONGO_QUERY_BLACKLIST = ['$where']

rawDescription: How to create a Case-Insensitive regex in eve rest framework

description: Create a Case-Insensitive regex in eve rest framework


code:
import re
s = """key: value
key: 'value'"""
m = re.findall(r"key:\s*'?([^'\n]*)'?", s, re.M)
m

rawDescription: How can i find the string inside single quotes in python regex

description: Find the string inside single quotes in python regex


code:
date_in_chicago = date_in_utc.astimezone(chicago)
print(date_in_chicago)
# 2012-08-12 09:00:00-05:00

date_in_newyork2 = date_in_utc.astimezone(newyork)
print(date_in_newyork2)
# 2012-08-12 10:00:00-04:00

rawDescription: What is the local timezone

description: What is the local timezone


code:
if Product.objects.all().products.distinct('price').count() == 1:
    pass

rawDescription: how to check whether all the values of a database field are same using django queries

description: Check whether all the values of a database field are same using django queries


code: mylist = list(reader)

rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


rawDescription: How to add dictionaries to tuple

description: Add dictionaries to tuple


code:
class monster(baseSprite):
    def __init__(self, monster_image, main_batch, background):
        super(monster, self).__init__(imgage=monster_image, x=0, y=0, batch=main_batch, group=background)
    def update(self):
        self.x = x + global_settings['player position'][0]#X
        self.y = y + global_settings['player position'][1]#Y

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


rawDescription: Immutable dictionary in Python 3: how to make keys(), items(), and values() dictionary views immutable


code: values = insert(values, [0], (1,2,3))

rawDescription: Create new numpy array-scalar of flexible dtype


code:
{u'Ptr<AdjusterAdapter>': (u'OpenCV',
  u'2.4',
  u'http://docs.opencv.org/2.4/detectorType)',
  u'ocv:function 1 modules/features2d/doc/common_interfaces_of_feature_detectors.html#$ -')}

rawDescription: How to properly write coss-references to external documentation with intersphinx?

description: Properly write coss-references to external documentation with intersphinx


rawDescription: Can someone explain to me what python is doing here?


rawDescription: How to convert a Python datetime.datetime.utctime() to an Obj-C NSDate, and back again?

description: Convert a Python datetime.datetime.utctime() to an Obj-C NSDate, and back again


code:
from urllib import urlencode
data = {"do": "http://webpage.com/?secondary=parameter"}
encoded_data = urlencode(data)
url = "http://myserver.appspot.com/?" + encoded_data

rawDescription: Sending a URL in a GET request to a Python server on Google App Engine


code:
from collections import defaultdict

customers = defaultdict(list)

rawDescription: Populating a Python dictionary

description: Populating a Python dictionary


code:
def keep_count(f):
    @functools.wraps(f)
    def wrapped_f(*args, **kwargs):
        f(*args, **kwargs)
        wrapped_f.count += 1
    wrapped_f.count = 0
    return wrapped_f

rawDescription: Change an attribute of a function inside its own body?


code:
def grouper(sequence):
    result = []  # will hold (members, group) tuples

    for item in sequence:
        for members, group in result:
            if members.intersection(item):  # overlap
                members.update(item)
                group.append(item)
                break
        else:  # no group found, add new
            result.append((set(item), [item]))

    return [group for members, group in result]

rawDescription: Group Python list of lists into groups based on overlapping items


code: Q(name__contains=list[0]) | Q(name__contains=list[1]) | ... | Q(name__contains=list[-1])

rawDescription: How to Query model where name contains any word in python list?


rawDescription: Creating 2 arrays from one array in python


code:
from django.db.models import Count
class Screening(generic.DetailView):
    model = Job
    template_name = 'dashboard/screening.html'

    def get_context_data(self, **kwargs):
        context = super(Screening, self).get_context_data(**kwargs)

        # Fetch the sender_id for each unread message.
        # Count the number of times that the sender_id was included.
        # Then convert the list of tuples into a dictionary for quick lookup.
        sent_messages = dict(self.request.user.received_messages.filter(
            read_at__isnull=True
        ).values('sender_id').annotate(
            messages_sent=Count('user_id')
        ).values_list('sender_id', 'messages_sent'))

        candidates = []
        for candidate in self.object.applied_to.all().order_by('candidate'):
            candidate.messages_sent = sent_messages.get(candidate.id, 0)
            candidates.append(candidate)
        context['candidate_list'] = candidates
        return context

rawDescription: Issue in Django count string in a template


rawDescription: Distance between two points including elevation


code:
class Foo(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer = UserSerializer

rawDescription: Django Rest Framework: turn on pagination on a ViewSet (like ModelViewSet pagination)


code:
from pprintpp import pprint

data = ... # your dict here

pprint(data)

rawDescription: PrettyPrint indent/line break each level


code: dictionary = json.loads(s)

rawDescription: how I should proceed to extract the value id for keys from the .json file in python using the keys

description: How I should proceed to extract the value id for keys from the .json file in python using the keys


code:
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
    for chunk in iter(lambda: old.read(1024), b""):
        new.write(chunk)

rawDescription: How to prepend data to the binary file?

description: Prepend data to the binary file


code:
divs = x.xpath("//div[@class='content'][preceding-sibling::p]")
[d.xpath("string((preceding-sibling::p)[last()])")
 for d in divs]

rawDescription: xpath for preceding sibling

description: Xpath for preceding sibling


code:
person[ADDRESS][PHONES][x] # Phone numbers associated with that address
person[PHONES][x] # Phone numbers associated with the person

rawDescription: Json organization

description: Json organization


code:
for i in range(len(content2)):
    if content2[i] == 0.0:
        content2[i] = None

rawDescription: python changing integers/ floats to None in list

description: Python changing integers/ floats to None in list


code: a[:len(bbins)] += bbins

rawDescription: Increment Numpy array with repeated indices


code:
text = soup.find_all('p')[0].get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)

rawDescription: Python: print/get first sentence of each paragraph


code: myDict["Objective A"]()

rawDescription: How can I associate dictionary keys with functions?

description: Associate dictionary keys with functions


code: [{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


code: snapshot_delay = 1000 # time in ms

rawDescription: take snapshots every second using artist animation

description: Take snapshots every second using artist animation


rawDescription: How to split a matrix into 4 blocks using numpy?

description: Split a matrix into 4 blocks using numpy


code:
#    fruit  item
#0  mango     1
#1  apple     2

rawDescription: Python Subset dataframe with another dataframe


rawDescription: How can I use pyparsing to parse nested expressions that have mutiple opener/closer types?

description: Use pyparsing to parse nested expressions that have mutiple opener/closer types


code:
# Add this line to the top of your script file
from __future__ import print_function

rawDescription: Is there anything like a "void lambda" in Python?


code:
j = 0
s = len(l)
for i in range(0, s):
    l_i = l[i]
    l_i2 = l_i<<1
    while l[j] < l_i2:
        j += 1
        if j == s:
            return -1
    if l[j] == l_i2:
        return i

rawDescription: How to quickly find first multiple of 2 of list element in list of large integers?

description: Quickly find first multiple of 2 of list element in list of large integers


rawDescription: scikit-learn how to know documents in the cluster?

description: Scikit-learn how to know documents in the cluster


rawDescription: python matplotlib save plot

description: Python matplotlib save plot


code:
import re
word = ['roaming','overseas','samsung']
s =  "Contacted vodafone about going overseas and asked about roaming charges. The customer support officer says there isn't a charge but while checking my usage overseas."
pattern = r'|'.join(map(re.escape, word))
re.findall(pattern, s)
' '.join(_)

rawDescription: Text clean up in Python

description: Text clean up in Python


code:
df2 = pd.concat([df,df1])
df2.groupby('x').mean()

rawDescription: How do I merge together two columns from two dataframes in Python

description: Merge together two columns from two dataframes in Python


code: from __future__ import division # unnecessary on Py 3

rawDescription: Python - 'tuple' object does not support item assignment


code: ax1 = fig.add_subplot(111, projection='3d')

rawDescription: matplotlib correct colors/colorbar for plot with multiple surfaces each of a different color

description: Matplotlib correct colors/colorbar for plot with multiple surfaces each of a different color


code:
for x in range(251):
    print(bin(x))

rawDescription: Printing Binary in Python

description: Printing Binary in Python


rawDescription: New colum in pandas, based on another colums last value


code:
lst1 = ['abc', 'abc', 'cde', 'cde']
set(lst1)

rawDescription: Accessing the List Being Generated by List Comprehension


code:
daily.index = pandas.MultiIndex.from_tuples(daily.index, names=['W', 'D'])
daily

rawDescription: Pandas: how to plot yearly data on top of each other


rawDescription: Escaped string of bytes to bytestring

description: Escaped string of bytes to bytestring


code:
from multiprocessing.dummy import Pool # use threads

def compute_y(i):
    np.add.reduce(no * np.sin(np.radians(impar * x[i])) / impar, out=y[i])

step = 10**8 // n
Pool().map(compute_y, (slice(j, j + step) for j in range(0, len(x), step)))

rawDescription: Python multiprocessing pylab Fourier

description: Python multiprocessing pylab Fourier


code:
def comp(el):
    if type(el) == str:
        return ['not', el]
    else:
        return el[1]

listA = ['P', 'Q', ['not', 'R'], ['not', 'S']]
comp(['not', 'P']) in listA  # True
comp('S') in listA  # True

rawDescription: Python: Check if list item has a complement


rawDescription: Displaying one Django database object on a page at a time


code:
counts, bins, bars = plt.hist(...)
plt.xticks(bins)

rawDescription: Bar heights and widths in histogram plot of several data


code:
ignore = {"a","of","the","an"}

from collections import Counter
cnt = Counter(word for line in text.lower()
              for word in line.split() if word not in ignore)

rawDescription: get some words sorted by occurrence and some words should be ignored from a string

description: Get some words sorted by occurrence and some words should be ignored from a string


code:
def connectionLost(self, reason):
    Factory.clients.remove(self)

rawDescription: how to kill twisted protocol instances python

description: Kill twisted protocol instances python


rawDescription: Best way to aggregate a simple dict in Python

description: Aggregate a simple dict in Python


code:
import operator
list(map(operator.itemgetter(1), f))

rawDescription: List a specific position in each list within a list (python)


code:
#!/usr/bin/python3

def _spawn_background_interpreter(*args,**kwargs):
    from threading import Thread
    def _open_interp(locs):
        import code
        code.interact(local=locs)
    locs = args[0] if args else None
    t = Thread(target=_open_interp, args=(locs,))
    t.setDaemon(True) #pre-3.3 API
    t.start()

rawDescription: Python live coding/debugging

description: Python live coding/debugging


code:
import requests
from pyquery import PyQuery as pq

url = 'http://wireless.walmart.com/content/getRatePlanInfo'
payload = {'carrierID':68, 'conditionToType':1, 'cssPrepend':'wm20'}
r = requests.post(url, data=payload)
d = pq(r.text)

rawDescription: How do I send a POST request to the page after it has been opened using Python?

description: Send a POST request to the page after it has been opened using Python


code: tuple(map(tuple, df1.values))

rawDescription: Memoize a costly computation of a data frame


code:
import foo
dir(foo)

rawDescription: Find what is in a PYC file

description: Find what is in a PYC file


code:
from sklearn.externals import joblib
joblib.dump(model, 'saved_model.pkl')

rawDescription: moving classification to production environment

description: Moving classification to production environment


code:
tax_allyears
lienyears = tax_allyears.loc[tax_allyears['type'] == 'Lien','tax_year'].unique().tolist()
lienendorsementyears = tax_allyears.loc[tax_allyears['type'] == 'Lien Endorsement','tax_year'].unique().tolist()
by_year_lien_interest = tax_allyears[(tax_allyears['type'] == 'Lien Interest') & tax_allyears['tax_year'].isin(lienyears)].groupby('tax_year')['amount'].sum()
by_year_lien_endorsement_interest = tax_allyears[(tax_allyears['type'] == 'Lien Interest') & tax_allyears['tax_year'].isin(lienendorsementyears)].groupby('tax_year')['amount'].sum()
by_year_lien_interest
by_year_lien_endorsement_interest

rawDescription: Pandas groupby sum if value in group

description: Pandas groupby sum if value in group


code:
from datetime import datetime
time_list = []
time_list.append(datetime.now().timestamp())

rawDescription: Python list and time

description: Python list and time


code:
values = "10,20,30"
sum(int(x) for x in values.split(','))

rawDescription: Python: Reducing a set of strings

description: Python: Reducing a set of strings


rawDescription: How to sort a pandas dataframe by columns and a part of multi index simultaneously without modifying the dataframe

description: Sort a pandas dataframe by columns and a part of multi index simultaneously without modifying the dataframe


rawDescription: sort list of floating-point numbers in groups

description: Sort list of floating-point numbers in groups


code:
fields = ('name', 'email', 'company', 'address', 'brochure',)

widgets = {'brochure': forms.CheckboxSelectMultiple()}

rawDescription: Rendering and customising a django form in the template


rawDescription: Fit data to curve using polyfit with multiple variables in python using numpy polyfit


code:
import numpy as np
a1 = np.array([-10,1,2])
a2 = np.array([1,2,3])
a1 > 0
a2 > 0
np.all(a1 > 0)
np.all(a2 > 0)

rawDescription: All command in Python

description: All command in Python


rawDescription: Get coordinates from a wikipedia page

description: Get coordinates from a wikipedia page


rawDescription: allow a shelve object to be pickled in python, pypar and mpich2

description: Allow a shelve object to be pickled in python, pypar and mpich2


code:
from datetime import datetime, time, timedelta
import random

now = datetime.now()
midnight = datetime.combine(now.date(), time.min)
delta = int((now - midnight).total_seconds())
random_dt = midnight + timedelta(seconds=random.randrange(delta))

rawDescription: Get Random Time Between Midnight to Current Time


code:
self.worker_queue = Queue() # queue for messages to workers
self.server_queue = Queue() # queue for messages to ampq server

rawDescription: Can eventlet manage an AMQP connection with messages passing asynchronously both in and out?


code:
def callback(hwnd, hwnds):
    if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        hwnds[win32gui.GetClassName(hwnd)] = hwnd
    return True

hwnds = {}
win32gui.EnumChildWindows(whndl, callback, hwnds)

rawDescription: Python win32api SendMesage

description: Python win32api SendMesage


code: arrs = [ l.rstrip().split(",\t") for l in open(filename) ]

rawDescription: spliting a list into [ ]

description: Spliting a list into [ ]


code:
myFunction2(['a','bc','f'], min, max)          # ('a', 'f')
myFunction2(['a','bc','f'], min, max, key=len) # ('a', 'bc')

rawDescription: Refactor a couple of functions into one by accepting sets and returning sets


code:
import __builtin__

__builtin__.open

rawDescription: Undo Overwrite of Python Built-In

description: Undo Overwrite of Python Built-In


rawDescription: How to alter a part of an array

description: Alter a part of an array


rawDescription: Swap characters in string

description: Swap characters in string


code:
import os
import rpy2
import rpy2.robjects as ro
from rpy2.robjects.packages import importr

# CURRENT DIRECTORY OF SCRIPT
cd = os.path.dirname(os.path.abspath(__file__))

# READ IN DATA
allelefreqshort_py = ro.r['read.table'](os.path.join(cd, "allelefreqs.txt"), header=False)

# PASSING PYTHON DF TO R DF
ro.globalenv['allelefreqshort'] = allelefreqshort_py

# OUTPUT PLOT
grdevices = importr('grDevices')
grdevices.png(file="alleleFreq.png", width=800, height=500)
p = ro.r('hist(log10(allelefreqshort$AlleleFreq), xlim = c(-15,0), breaks=20)')
grdevices.dev_off()

rawDescription: Converting R to ryp2

description: Converting R to ryp2


code:
from decimal import Decimal

def plus(n):
    return n + Decimal('10') ** n.as_tuple().exponent

rawDescription: How to plus one at the tail to a float number in Python?

description: Plus one at the tail to a float number in Python


code:
from app.tests.models import *
from app.tests.views import *

rawDescription: Nose: test all modules in a given package


code: ','.join(value for value in d.itervalues() if value)

rawDescription: remove unnecessary comma from python dict

description: Remove unnecessary comma from python dict


code:
# Insert test data
rooms = [Room(name=name) for name in 'ABCDEFGHI']
session.add_all(rooms)

A, B, C, D, E, F, G, H, I = rooms

A.entries = {'NW': B, 'NE': C, 'S': F}
B.entries = {'SE': A}
C.entries = {'E': D, 'SW': A}
D.entries = {'W': C, 'NE': E}
E.entries = {'SW': D}
F.entries = {'N': A, 'SW': G, 'SE': H}
G.entries = {'NE': F}
H.entries = {'NW': F, 'SE': I}

if True:  # add cycle, in which case we get duplicates in the results
    B.entries['E'] = C
    C.entries['W'] = B

session.commit()

rawDescription: Recursively select (with limited depth) relationships in SQLAlchemy using ORM, declarative style, and Association objects


code:
numAndSize = re.compile(r'\d+[xX]\d+(?:\.\d+)?')
numAndSize.findall("Product:A,2x3.5gallonbottles")

rawDescription: Odd behavior with Python regular expressions - findall only finds the "()?" portion


code:
from itertools import izip_longest

listA = [1, 2, 3, 4]
listB = [1, 2, '--']

records = izip_longest(listA, listB)
# will return [(1, 1), (2, 2), (3, '--'), (4, None)]

rawDescription: Organize table data by columns

description: Organize table data by columns


code:
from __future__ import print_function

import datetime
import itertools

def iter_len(iterable):
    return sum(1 for __ in iterable)

def by_hour(item):  # Hour key
    timestamp = item[1]
    return '{}-{}'.format(timestamp.hour, (timestamp.hour+1) % 24)

def by_half_hour(item):  # Half-hour key
    timestamp = item[1]
    half_hour = timestamp.hour + (0.5 * (timestamp.minute // 30))
    return '{:.1f}-{:.1f}'.format(half_hour, (half_hour+0.5) % 24)

def get_results(data, key):  # Name this more appropriately
    data = sorted(data, key=key)
    for key, grouper in itertools.groupby(data, key):
        yield (key, iter_len(grouper))

data = [
    ('172.18.74.146', datetime.time(11, 28, 58)),
    ('10.227.211.244', datetime.time(11, 54, 19)),
    ('10.227.215.68', datetime.time(11, 54, 34)),
    ('10.227.209.139', datetime.time(12, 14, 47)),
    ('10.227.147.98', datetime.time(14, 47, 25)),
    ]

print('By Hour')
print(list(get_results(data, by_hour)))
print()
print("By Half Hour")
print(list(get_results(data, by_half_hour)))

rawDescription: Sort tuples by time interval? Python

description: Sort tuples by time interval? Python


code:
with open('out2', 'r+') as f:
    content = f.read()
    content = re.sub('HI', 'hi', content)
    content = re.sub('HELLO', 'hello', content)
    f.seek(0)  # Reset file position to the beginning of the file
    f.write(content)
    f.truncate()  # <---- If the replacement string is shorter than the original one,
                  #       You need this. Otherwise, there will be remaining of
                  #         content before the replacement.

rawDescription: replace certain strings in a file

description: Replace certain strings in a file


code:
mis, frequentItems = {1: 3.4, 5: 3.14, 3: 7.5}, [1, 3, 5]
frequentItems.sort(key = mis.get)
print(frequentItems)  # [5, 1, 3]

rawDescription: Sort List of string based on value in Dict


rawDescription: list assignment index out of range (creating a minesweeper board)

description: List assignment index out of range (creating a minesweeper board)


rawDescription: Why isn't this even function's FFT real?

description: Why isn't this even function's FFT real


code:
#! /usr/bin/python3

class Node:
    def __init__(self, payload, left = None, right = None):
        self.payload = payload
        self.left = left
        self.right = right

    def __repr__(self):
        return self.payload

class Tree:
    def __init__(self, root):
        self.root = root

    def levels(self):
        levels = [[self.root]]
        while levels[-1]:
            nextLevel = []
            for node in levels[-1]:
                nextLevel.extend([node for node in (node.left, node.right) if node])
            levels.append(nextLevel)
        return levels[:-1]

t = Tree(Node('41', Node('7', Node('1'), Node('19')), Node('53', Node('47'))))

print(t.levels())

rawDescription: Print Levels Of A Binary Tree by Level Iteratively


code:
def compute_values(a,b,c):
    return (a+b, c)

def func_one(a,b,c):
    some_function(*(compute_values(a,b,c) + (1,)))

def func_two(a,b,c):
    some_function(*(compute_values(a,b,c) + (2,)))

func_one(1,2,3)
func_two(1,2,3)

rawDescription: A way to automatically pass parameters to a function?


code:
class TagCounter:
   tag = db.ReferenceProperty(Tag)
   counter = db.IntegerProperty(default=0)

rawDescription: Choose between many-to-many techniques in App Engine DB


rawDescription: Making a dictionary from multiple items in lists


code: [[None for x in range(20)] for y in range(20)]

rawDescription: Making a 2d list of objects (Python 2.7)


code: output

rawDescription: Python numpy indexing does not work

description: Python numpy indexing does not work


code: del somelist[2:]

rawDescription: list.__delslice__ python 3

description: List.__delslice__ python 3


code:
def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target), args).send(item[0])
    else:
        for item in source:
            FullOutput(WriteFlatFile(target)).send(item[0])

rawDescription: Whats the pythonic way to handle empty *args when creating a set?


code:
while True:
    # check time
    # check currently running processes :: workerX.still_running()
    #   -> if some are past their timeout, kill them workerX.kill()
    # start new subprocesses according to your scheduling logic
    sleep(1)

rawDescription: Custom Scheduler to have sequential + semi-sequential scripts with timeouts/kill switches?


code:
import requests

bibtex_id = '10.1007/s00425-007-0544-9'

url = "http://www.doi2bib.org/#/doi/{id}".format(id=bibtex_id)
xhr_url = 'http://www.doi2bib.org/doi2bib'

with requests.Session() as session:
    session.get(url)

    response = session.get(xhr_url, params={'id': bibtex_id})
    print(response.content)

rawDescription: Python web scraping for javascript generated content


rawDescription: python [:] notation and range

description: Python [:] notation and range


code:
pd.__version__
import tables
tables.__version__
np.__version__

rawDescription: Speed up writing billions of rows to HDF5


code:
No,name,lastname,hobby
1,jhon,g,fishing
2,mike,a,boxing
3,tom,v,sking

rawDescription: Excel parsing in python and forming dictionary


code:
def print_func(x, y):
    print("{}, {}".format(x, y))

rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
def update(self, move, blocks):

    # check if we can jump
    if move.up and self.on_ground:
        self.yvel -= self.jump_speed

    # simple left/right movement
    if move.left: self.xvel = -self.move_speed
    if move.right: self.xvel = self.move_speed

    # if in the air, fall down
    if not self.on_ground:
        self.yvel += 0.3
        # but not too fast
        if self.yvel > max_gravity: self.yvel = max_gravity

    # if no left/right movement, x speed is 0, of course
    if not (move.left or move.right):
        self.xvel = 0

    # move horizontal, and check for horizontal collisions
    self.rect.left += self.xvel
    self.collide(self.xvel, 0, blocks)

    # move vertically, and check for vertical collisions
    self.rect.top += self.yvel
    self.on_ground = False;
    self.collide(0, self.yvel, blocks)

rawDescription: Add collision detection to a plattformer in pygame


code:
import functools

def my_partialmethod(func, *args1, **kwargs1):
    @functools.wraps(func)  # copy attributes to start, they can be overwritten later
    def method(self, *args2, **kwargs2):
        return func(self, *args1, *args2, **kwargs1, **kwargs2)
    return method

rawDescription: Documentation of functions defined with functools partialmethod


code: ['Stoker', 'Laundryboy', 'Receptionist', 'Mr Z', 'Mr J', 'The S Family', 'The M Family', 'Mr Rich']

rawDescription: Python - I need a collection with negative indices


code:
from django.db.models import signals

def encode_upload(sender, instance=None, created=None, **kwargs):
   # your custom stuff here, this is the file path, change "upload_field_name"
   # by your actual FileField name
   instance.upload_field_name.path

# change YourModelClass by the name of your actual model class
signals.pre_save.connect(encode_upload, sender=YourModelClass)

rawDescription: Django custom admin methods on uploaded file


code: p is q

rawDescription: Why is the value of p[1] is '0' immediately after entering the for loop?


code:
from django.db import models

class Grade(models.Model):
    pass  # Whatever you need here...

class Student(models.Model):
    name = models.CharField(max_length=20)
    grade = models.ForeignKey(Grade)

class Rank(models.Model):

    class Meta(object):
        unique_together = (("date", "student"), )

    date = models.DateField(db_index=True)
    student = models.ForeignKey(Student)
    value = models.IntegerField()

rawDescription: How do I record daily rankings for a model in Django?

description: Record daily rankings for a model in Django


code:
from string import maketrans
with open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
    # separate A -> # ...
    a, b = zip(*(list(line.rstrip()) for line in f))
    # create table where # maps to A, * -> M and % -> N
    tbl = maketrans("".join(b), "".join(a))
    for line in f2:
        # translate each string using our mapping table
        print(line.translate(tbl).rstrip())

rawDescription: Replace character(s) in list a with character from list b


code:
def verification():
    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "python.exe" and len(p.cmdline()) > 1 and "Pinger.py" in p.cmdline()[1]:
            print ("running")

rawDescription: Checking if program is running

description: Checking if program is running


code:
import scipy.stats as st
st.norm.ppf(.95)
st.norm.cdf(1.64)

rawDescription: Probability to z-score and vice versa in python


code:
a = Animal.objects.all().first() #let's assume this is a cat
a.speak()
a.downcast().speak()

rawDescription: Access child methods in Python Django

description: Access child methods in Python Django


code:
AlexaAndGoogleTrainData = p.read_table('train.tsv', header=0)[["AlexaRank", "GooglePageRank"]]
AlexaAndGoogleTestData = p.read_table('test.tsv', header=0)[["AlexaRank", "GooglePageRank"]]
AllAlexaAndGoogleInfo = AlexaAndGoogleTestData.append(AlexaAndGoogleTrainData)

rawDescription: Using ranking data in Logistic Regression


code:
data = {}
data['number_of_faces'] = len(faces)
data['faces'] = []
for (x,y,w,h) in faces:
    data['faces'].append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w})
with open(json_path+folder+'/'+file_name, "w") as outfile:
    json.dump(data, outfile)

rawDescription: Nested json in python

description: Nested json in python


rawDescription: How to split numbers in string?

description: Split numbers in string


code:
import lxml

xml = """
<brochures>
    <brochure>
        <onlinePath>http://EEE</onlinePath>
        <downloadPath>http://YYY</downloadPath>
        <Name>ABC</Name>
        <AAA>

JPG

            <Q>JPG</Q>
        </AAA>
    </brochure>
    <brochure>
        <onlinePath>http://EKK</onlinePath>
        <downloadPath>http://XXX</downloadPath>
        <Name>DEF</Name>
        <AAA>

JPG

            <Q>JPG</Q>
        </AAA>
    </brochure>
</brochures>
"""

root = lxml.etree.fromstring(xml)
mylist = root.xpath('//brochure/onlinePath/text()')

rawDescription: Data from XML to Python list

description: Data from XML to Python list


code:
index   | name       | user
1       | Matthew    | James
2       | Matthew    | Sandy
3       | Matthew    | May

rawDescription: How to properly store a list of data in SQL?

description: Properly store a list of data in SQL


code:
title = title.decode("unicode-escape")
subprocess.Popen([command, title], stdout=subprocess.PIPE)

rawDescription: Unicode and subprocess.Popen

description: Unicode and subprocess.Popen


code:
# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    if not data: break
    print(data) # Paging Python!
    # do whatever you need to do with the data
conn.close()
# optionally put a loop here so that you start
# listening again after the connection closes

rawDescription: Communicate between a processing sketch and a python program?


code:
x = []
while n:
    x.append(n % 256)
    n //= 256
s = ''.join(r'\x{:02x}'.format(b) for b in reversed(x))

rawDescription: Pythonic way to convert an integer into a hex-escaped string


code:
alist[2] = alist
alist
alist[1] = alist
alist

rawDescription: What does Python mean by printing "[...]" for an object reference?


code: sortedLst = sorted(strLst, key=str.lower)

rawDescription: How to alphabetize a column?

description: Alphabetize a column


code:
import ctypes as c
import numpy as np
import multiprocessing as mp

n, m = 2, 3
mp_arr = mp.Array(c.c_double, n*m) # shared, can be used from multiple processes
# then in each new process create a new numpy array using:
arr = np.frombuffer(mp_arr.get_obj()) # mp_arr and arr share the same memory
# make it two-dimensional
b = arr.reshape((n,m)) # b and arr share the same memory

rawDescription: Can I create a shared multiarray or lists of lists object in python for multiprocessing?

description: Create a shared multiarray or lists of lists object in python for multiprocessing


rawDescription: How to return a "Tuple type" in a UDF in PySpark?

description: Return a "Tuple type" in a UDF in PySpark


rawDescription: Programmatically get current Ipython notebook cell output?


code:
t_pos = posVec
t_dir = dirVec

rawDescription: Numpy array values changed without being aksed?


code: [t for x in range(0,20,5) for t in [-x,x+1] ]

rawDescription: Map Python list element to multiple elements, avoiding nested lists


code:
import re

with open("old_text.txt") as f:
   txt = f.read()
   new_txt=re.sub(r'(\bCourtney\b.*?)(\s*\Courtney\b\s*)','\1',txt,re.S)

rawDescription: Deleting every second occurence of a word in a txt file (Python)


code:
if 'test' in sys.argv:
     TEST_RUNNER = '<?>.ExistingDBTestRunner'
     # alternative db settings?

rawDescription: Run Unittest On Main Django Database

description: Run Unittest On Main Django Database


code:
import sys
sys.stdout.encoding

rawDescription: setting default encoding in a python.py

description: Setting default encoding in a python.py


rawDescription: finding out absolute path to a file from python

description: Finding out absolute path to a file from python


code:
text=b'Hello World'
hexi=b'\12\34\45\EF\CD\AB'
xors=[ord(t)^ord(x) for t,x in zip(text,hexi)]
xors

rawDescription: How to xor in python using hex

description: Xor in python using hex


code:
g = [[1,1,1,0],
     [1,0,0,0],
     [1,0,0,0],
     [1,0,1,0],
     [1,1,1,1]]

width = len(g[0])
height = len(g)

for i in range(height):
    for j in range(width):
        if g[i][j] != 0:
            continue
        around = [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
        walls = 0
        for (x,y) in around:
            if x < 0 or x >= height or y < 0 or y >= width:
                #Outside, count as wall
                walls += 1
            elif g[x][y] == 1:
                walls += 1
        if walls in [2,3]: # 4 would be inaccessible
            g[i][j] = 2

rawDescription: Finding corners in a 2d map with walls

description: Finding corners in a 2d map with walls


code:
class ConfirmationViewMixin(object):
    confirmation_template = '_confirm.html'

    def get_confirmation_context(self):
        # implement this in your view class
        raise NotImplementedError()

    def post(self):
        if request.args.get('confirm') == '1':
            return super(ConfirmationViewMixin, self).post()

        return render_template(
            self.confirmation_template, **self.get_confirmation_context())

rawDescription: Flask Confirm Action

description: Flask Confirm Action


code:
x()
x.y

rawDescription: How to autodoc a function inside a method in Sphinx

description: Autodoc a function inside a method in Sphinx


rawDescription: Loading .RData files into Python

description: Loading .RData files into Python


code:
def has_integer_cube_root(n):
    floatroot = (n ** (1.0 / 3.0))
    introot = int(round(floatroot))
    return floateq(floatroot, introot)

rawDescription: How do I get a whole number as a result for a cube root?

description: Get a whole number as a result for a cube root


code: ''.join(char for char in word if char not in set('aeiouAEIOU'))

rawDescription: string replace vowels in python?

description: String replace vowels in python


rawDescription: Python 2D NumPy array comprehension

description: Python 2D NumPy array comprehension


code: 'target' in source.func_code.co_names

rawDescription: In Python, determine if a function calls another function


code:
with open("numberGood.txt") as f:
    print(sum(float(line) for line in f))

rawDescription: Python - sum variables from a text file

description: Python - sum variables from a text file


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

rawDescription: "Less/greater than" comparison of N-dimensional and (N-k)-dimensional numpy arrays


rawDescription: How to assign equal scaling on the x-axis in Matplotlib?

description: Assign equal scaling on the x-axis in Matplotlib


code:
level="""one
two
three"""

rawDescription: How to count lines in multi lined strings

description: Count lines in multi lined strings


code:
dummytuple = collision_list[numbers[tiles[int(tile)]]]
collision_list[numbers[tiles[int(tile)]]] = dummytuple + (tiles[int(tile)].rect,)

rawDescription: Add object to existing value in dictionary


code: any(idx for idx in range(len(a)) if (b*2)[idx:idx+len(a)] == a)

rawDescription: Compare Sequences Python

description: Compare Sequences Python


rawDescription: Get information out of sub-lists in main list elegantly


rawDescription: How can I split a string with no delimiters but with fixed number of decimal places - python

description: Split a string with no delimiters but with fixed number of decimal places - python


code:
env = Environment()
env.Program(target = 'foo', source = 'foo.c')

SConscript('sub/SConscript')

rawDescription: Creating a Hierarchical Build with SCons


code:
import pandas as pd
import csv

test = pd.read_csv("output/Emails.csv", quoting=csv.QUOTE_NONE,  sep=',', error_bad_lines=False, header=None,
    names=["Id","DocNumber","MetadataSubject","MetadataTo","MetadataFrom","SenderPersonId","MetadataDateSent","MetadataDateReleased","MetadataPdfLink","MetadataCaseNumber","MetadataDocumentClass","ExtractedSubject","ExtractedTo","ExtractedFrom","ExtractedCc","ExtractedDateSent","ExtractedCaseNumber","ExtractedDocNumber","ExtractedDateReleased","ExtractedReleaseInPartOrFull","ExtractedBodyText","RawText"])

print (test.shape)

#delete row with NaN in column MetadataFrom
test = test.dropna(subset=['MetadataFrom'])
#delete headers in data
test = test[test.MetadataFrom != 'MetadataFrom']

rawDescription: Not reading all rows while importing csv into pandas dataframe


rawDescription: How group by sum and average column in python?


code:
import builtins
builtins
import sys
sys

rawDescription: Where is builtins module located?

description: Where is builtins module located


code: codes_from_file = [a.decode("windows-1250").encode("utf-8") for a in codes_from_file]

rawDescription: python 2.7 encoding decoding

description: Python 2.7 encoding decoding


code: a += a * b

rawDescription: How to perform arithmetic on the same line as a augmented assignment in Python 3.x.x?

description: Perform arithmetic on the same line as a augmented assignment in Python 3.x.x


code:
class DynServe(blobstore_handlers.BlobstoreDownloadHandler):

    def get(self, resource):

        (blob_key, extension) = resource.rpartition('.')[::2]
        blob_info = blobstore.BlobInfo.get(blob_key)
        if not blob_info:
            logging.error('Blob NOT FOUND %s' % resource)
            self.abort(404)

        self.response.headers[b'Content-Type'] = mimetypes.guess_type(blob_info.filename)
        self.send_blob(blob_key, save_as=blob_info.filename)

rawDescription: Python App Engine serving files with Google Cloud Storage


code: make_password(pwd, None, 'md5')

rawDescription: Django make_password too slow for creating large list of users programatically


code:
cmap.set_under('w') # will use white for values under vmin
cmap.set_over('k') # will use black for values over vmax

rawDescription: Custom colormap and change user range to plot 2D function not defined on the whole range


code: list(gen())

rawDescription: Set partition with constraints in Python


code:
if text == 'help':
            reply(img=urllib2.urlopen('img url').read())

rawDescription: How to send an image from a telegram bot

description: Send an image from a telegram bot


code:
from social.exceptions import AuthForbidden

def email_check(strategy, details, *args, **kwargs):
    if not is_valid_email(details.get(email)):
        raise AuthForbidden(strategy.backend)

rawDescription: Filtering or restricting Google-Oauth2 login to a set of users in Django using Python Social Auth


code:
import numpy as np
from numpy import ctypeslib

# ...code to load the shared library as `lib` not shown...

# Declare the argument types of lib.foo:
lib.foo.argtypes = [ctypeslib.ndpointer(np.complex64, ndim=1, flags='C'), c_int]

rawDescription: How to interface a NumPy complex array with C function using ctypes?

description: Interface a NumPy complex array with C function using ctypes


code: sh.git('archive', '--format', 'tar')

rawDescription: How to handle commands containing "-" in python sh module?

description: Handle commands containing "-" in python sh module


code:
i = np.arange(start_x, end_x)
plasmaFreq[start_x:end_x, start_y: end_y] = plasmaFreq_0 *(np.tanh((i - 50)/10) - np.tanh((i - (nx - 50))/10))/2.0

rawDescription: Vectorizing a nested for-loop in python for index-dependent function


code:
import random
a=0
q = 1
while a < 5:
    i=0
    x=[]
    while i < q:
        s=random.randint(10, 20)
        i+=1
        x.append(s)
    print(x)
    q+=1
    a+=1

rawDescription: print out a randint and append it to a list, then loop over and print a totaly different list

description: Print out a randint and append it to a list, then loop over and print a totaly different list


code:
if moduleName == '-1':
    break

rawDescription: Loop to obtain two pieces of user input and save to a global list


code:
m = re.search('<(".+")>', 'Tags=<"traffic""apple""sample">')
tags = [x for x in m.group(1).split('"') if x]

rawDescription: How to write Regex for extracting tags?

description: Write Regex for extracting tags


code: yield Request(link.link, callback=self.crawl_recursive, meta={'present_depth': 0, 'depth_limit': link.depth_limit})

rawDescription: How to set different depth limits for different websites when crawling in python scrapy?

description: Set different depth limits for different websites when crawling in python scrapy


code:
pkt_bytes = [0x02, 0x07, 0xff, 0xff, 0x00, 0x03]
myint = 123
pkt_bytes[3:5] = [ord(b) for b in struct.pack("H",myint)]
pkt_bytes

rawDescription: Python inserting a short integer into a list of bytes


code:
import re
import urllib2

data = urllib2.urlopen("http://python-data.dr-chuck.net/regex_sum_179860.txt")
r = re.compile("\d+")
l = []
for line in data:
    l.extend(map(int,r.findall(line)))

rawDescription: Find all occurrences of integer within text in Python


code:
df
rdf = df.stack(['First', 'Third'])
rdf['new'] = rdf.foo + rdf.bar
rdf
rdf.unstack(['First', 'Third'])

rawDescription: Add a column with a groupby on a hierarchical dataframe


rawDescription: Export message that encrypted with python-rsa


code:
class Dashboard(webapp.RequestHandler):
    def some_function(self):
        if data['user'].new_user and not self.request.path == '/main/new':
            self.redirect('/main/new')
            return True
        else:
            return False
    def get(self):
        if not self.some_function():
            self.response.out.write('Some output here')

rawDescription: How can I kill off a Python web app on GAE early following a redirect?

description: Kill off a Python web app on GAE early following a redirect


code:
with open("data.csv") as f, open("new.csv", "w") as out:
    r = csv.reader(f)
    wr = csv.writer(out)
    header = next(r)
    for row in r:
        loc, mov, form, lat, long = row
        od.setdefault((loc, lat, long), []).append("{} {}".format(mov, form))
    wr.writerow(header)
    for loc, vals in od.items():
        wr.writerow([loc[0]] + vals + list(loc[1:]))

rawDescription: python ordered dict issue

description: Python ordered dict issue


code:
def triwise(iterable):
    a, b = tee(iterable)
    a, c = tee(iterable)
    next(b, None)
    next(c, None)
    next(c, None)
    return izip(a, b, c)

rawDescription: Python: how to extend pairwise to triwise?


code:
import os, sys
os.isatty(sys.stdout.fileno())

rawDescription: How to recognize whether a script is running on a tty?

description: Recognize whether a script is running on a tty


code: dict1.update((k, dict2[k]) for k in dict1.keys() & dict2.keys())

rawDescription: Update dict without adding new keys?

description: Update dict without adding new keys


code:
where = '%(year)s >= YEAR(date_from) AND %(month)s >= MONTH(date_from) \
        AND %(year)s <= YEAR(date_to) AND %(month)s <= MONTH(date_to)' % \
        {'year': year, 'month': month}
Departure_Date.objects.extra(where=[where])

rawDescription: Django, filter by specified month and year in date range


code:
def openSlot(self):
    # This function is called when the user clicks File->Open.
    filename = QtGui.QFileDialog.getOpenFileName()
    print(filename)
    # Do your pixmap stuff here.

rawDescription: Python PyQt4 how to open image using QFileDialog


rawDescription: filtering array with conditional control variables in python to create numpy matrix

description: Filtering array with conditional control variables in python to create numpy matrix


code: c = [item for item in b if item in a]

rawDescription: Compare unequal lists

description: Compare unequal lists


code:
from dis import dis
dis(lambda: {})

rawDescription: Why is dict definition faster in Python 2.7 than in Python 3.x?


code:
1234,asd
dsa
qwerty
567,

rawDescription: How to split string at a specific char(set of chars, actually), but with specified length

description: Split string at a specific char(set of chars, actually), but with specified length


code:
name = data['name']
entity = Object.get_or_insert(name)

rawDescription: How to check the existance of single Entity? Google App Engine, Python

description: Check the existance of single Entity? Google App Engine, Python


code: return any(isinstance(v, dict) for v in dictObj.itervalues())

rawDescription: How can I check if a dictionary contains a dictionary?

description: Check if a dictionary contains a dictionary


code: a = x if x is not None else y

rawDescription: What is the most Pythonic way to provide a fall-back value in an assignment?


code:
global counter
whosturn = "Green" if counter%2 else "Red"
turnLbl = tk.Label(gameframe,text=color+"'s Turn")
turnLbl.grid(row=11,column = 0,columnspan = 10)

rawDescription: Python board game with tkinter

description: Python board game with tkinter


code:
def preProcess(s):
    return s.upper()

rawDescription: How can I pass a preprocessor to TfidfVectorizer? - sklearn - python

description: Pass a preprocessor to TfidfVectorizer? - sklearn - python


rawDescription: calculate diff() in python on subsets of data within a dataframe

description: Calculate diff() in python on subsets of data within a dataframe


code:
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)

class SystemAdmin(Base):
    __tablename__ = 'system_admin'
    user_id = Column(ForeignKey(User.id), primary_key=True)

rawDescription: SQLAlchemy mapping joined tables' columns to one object


code:
import pandas as pd
df = pd.DataFrame(["BEAR ESTOX X12 S", "BEAR ESTOX X15 S", "BEAR AXP UN 3X VON", "BULL AXP UN x5 VON"], columns=["name"])

sg = {"S":"SEG", "SG":"SEG", "SEG":"www.societegenerale.com"}
vontobel = {"VON":"Vontobel","Vontobel":"www.vontobel.com"}

issuer = sg.copy()
issuer.update(vontobel) #Combine both to one dictionary

#Split last word in string to new column
df["issuer_spl"] = df.name.str.split().str.get(-1)

df['issuer'] = df['issuer_spl'].map(issuer)
df['website'] = df['issuer'].map(issuer)

print(df)

rawDescription: Key to Value to Key in Python Dictionary


code: a

rawDescription: Finding duplicate matrices in Python?

description: Finding duplicate matrices in Python


rawDescription: Terminate a sockert.recv in a thread in Python


code:
['CAT']
['DOG SILVER FOX']
['KING KONG']
["P'OT THEN"]
['FOO-BAR', 'FISH']
['YELLOW', 'BLUE']

rawDescription: Need help to find right Regex match pattern


rawDescription: Pandas, Python. How to filter out days depending on number of observations?


code:
#Handler Connection.#
handlers = {
"on_blasterbot_mainwindow_destroy": gtk.main_quit,
"on_tool_deploy_button_clicked": bot_thread
}
builder.connect_signals(handlers)

#Stuff I know I need but don't know what is for.#
gtk.main()

rawDescription: Making a irc bot with a gui. Dificulties with desconecting on toggle button toggle


code:
from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

rawDescription: Python + Django page redirect

description: Python + Django page redirect


code:
import collections
def top5_words(text):
    counts = collections.Counter(text.lower().split())
    return [elem for elem, _ in sorted(counts.most_common(),key=lambda x:(-x[1], x[0]))[:5]]

rawDescription: Python - Return top 5 words with highest frequency


code:
s = "a descriptor 23 fd"
s.split("23", 1)[0]
s.split("fdasfdsafdsa", 1)[0]

rawDescription: Slice a string after a certain phrase?

description: Slice a string after a certain phrase


rawDescription: Spelling Correction in a Dataframe Object , Python


rawDescription: specific handling of list of list in python... itertools?

description: Specific handling of list of list in python... itertools


code: df = pd.concat([df,pd.DataFrame(columns = col_add)])

rawDescription: Pandas append list to list of column names


code:
expr = sympify("x & y | z")
expr

rawDescription: Truth tables in python using sympy

description: Truth tables in python using sympy


code:
now = datetime.now()
results = MyTable.objects.filter(datetime_field__year=now.year, datetime_field__month=now.month, datetime_field__day=now.day)

rawDescription: Add custom SQL into WHERE clause in Django, without using .raw()


code:
import pygame,time
from VideoCapture import Device
from pygame.locals import *
pygame.init()
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=550)
cam = Device()
screen=pygame.display.set_mode((200,200))
pygame.display.set_caption('Casting...')
while True:
    for e in pygame.event.get():
        if e.type==QUIT:
            exit()
    try:
        time.sleep(4)
        cam.saveSnapshot('image.jpg')
    except:
        pass

rawDescription: Python or Html live camera stream?

description: Python or Html live camera stream


code:
import bisect
n = bisect.bisect_left(lst, mx)

rawDescription: Efficient way of counting number of elements smaller (larger) than cutoff in a sorted list


code:
import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

rawDescription: How could I use requests in asyncio?

description: How could I use requests in asyncio


code:
[theme]
inherit = default
stylesheet = style.css
pygments_style = pygments.css

rawDescription: Customize sphinxdoc theme

description: Customize sphinxdoc theme


code:
def parse(data):
    nodes = set()
    links = set()

    for line in data.split('\n'):
        fields = line.split()

        id1, id2 = map(int, fields[:2])
        value = float(fields[2])

        nodes.update((id1, id2))
        links.add((id1, id2, value))

    return {
        'nodes': [{
            'name': node
        } for node in nodes],
        'links': [{
            'source': link[0],
            'target': link[1],
            'value': link[2]
        } for link in links]
    }

rawDescription: Formatting a string in required format in Python


code:
import argparse
import os

class EnvDefault(argparse.Action):
    def __init__(self, envvar, required=True, default=None, **kwargs):
        if not default and envvar:
            if envvar in os.environ:
                default = os.environ[envvar]
        if required and default:
            required = False
        super(EnvDefault, self).__init__(default=default, required=required,
                                         **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)

rawDescription: Setting options from environment variables when using argparse


code:
to_remove = []
for f1 in lst:
    # because lst is not being modified, we have to manually skip
    # elements which we will remove later
    # the performance difference is negligible on small lists
    if f1 in to_remove:
        continue
    for f2 in lst:
        # also skip f2s which we removed
        if f2 in to_remove:
            continue
        # note that I collapsed two of your conditions here for brevity
        # this is functionally the same as what you wrote, but looks neater
        if f1 != f2 and f1.intersect(f2):
            if f1.score >= f2.score:
                to_remove.append(f2)
            else:
                to_remove.append(f1)
lst = [x for x in lst if x not in to_remove]

rawDescription: Python 2.7 delete items form list while looping


rawDescription: It is possible to round up integers using format?


rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code:
np.set_printoptions(threshold='nan')
s = StringIO()
df.to_csv(s)
s.getvalue()  # no ellipsis (it's all there)

rawDescription: Pandas to_csv always substitute long numpy.ndarray with ellipsis


rawDescription: Can't select an option

description: Can't select an option


code:
int(ascending)
int(descending)

rawDescription: How to sort digits in a number?

description: Sort digits in a number


code: str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]

rawDescription: in Python, how to convert list of float numbers to string with certain format?

description: In Python, how to convert list of float numbers to string with certain format


code:
import csv

with open('state.csv', 'rb') as f:
    id2name = dict(csv.reader(f))

with open('csv_file.csv', 'rb') as ifile, open('output.', 'wb') as ofile:
    reader = csv.reader(ifile)
    writer = csv.writer(ofile)

    for state_id, year, value in reader:
        state = id2name[state_id]
        writer.writerow([state, year, value])

rawDescription: How to map state code from one csv file to state name in another csv file in python?

description: Map state code from one csv file to state name in another csv file in python


code:
from .mixin import ComparableMixin
class Orderable(ComparableMixin):
    def __init__(self, firstname, lastname):
        self.first = firstname
        self.last = lastname
    def _cmpkey(self):
        return (self.last, self.first)
    def __repr__(self):
        return "%s %s" % (self.first, self.last)
sorted([Orderable('Donald', 'Duck'),
        Orderable('Paul', 'Anka')])

rawDescription: Comparable classes in Python 3

description: Comparable classes in Python 3


code:
import pyodbc
cnxn = pyodbc.connect("DSN=myDb_SQLEXPRESS")
crsr = cnxn.cursor()
sql = """\
CREATE TABLE #numbered (rownum INT PRIMARY KEY, AccountNo VARCHAR(10))
"""
crsr.execute(sql)
cnxn.commit()
sql = """\
INSERT INTO #numbered (rownum, AccountNo)
SELECT
    ROW_NUMBER() OVER (ORDER BY Accountno) AS rownum,
    AccountNo
FROM casa4
"""
crsr.execute(sql)
cnxn.commit()
sql = "SELECT AccountNo FROM #numbered WHERE rownum BETWEEN ? AND ? ORDER BY rownum"
batchsize = 1000
ctr = 1
while True:
    crsr.execute(sql, [ctr, ctr + batchsize - 1])
    rows = crsr.fetchall()
    if len(rows) == 0:
        break
    print("-----")
    for row in rows:
        print(row)
    ctr += batchsize
cnxn.close()

rawDescription: Select nth to nth row while table still have values unselected with python and pyodbc


code:
import numpy as np
from scipy.spatial import distance
Y = distance.cdist(X, X, 'sqeuclidean')

rawDescription: Can I do (x_i-x_j)^T(x_i-x_j) for x_i, x_j are rows in a X matrix with numpy native function instead of loop

description: Do (x_i-x_j)^T(x_i-x_j) for x_i, x_j are rows in a X matrix with numpy native function instead of loop


code:
class C():
  def demo(): pass

C.demo.im_func                  # Retrieve it from the unbound method
C.__dict__["demo"]              # Retrieve it directly from the class dict

rawDescription: How to decorate (monkeypatch...) a Python class with methods from another class?

description: Decorate (monkeypatch...) a Python class with methods from another class


code:
queue_dtype = np.int32
queue_capacity = 2
values_queue = tf.FIFOQueue(capacity=queue_capacity, dtypes=queue_dtype)
size_op = values_queue.size()
value_placeholder = tf.placeholder(dtype=queue_dtype)
enqueue_op = values_queue.enqueue(value_placeholder)
dequeue_op = values_queue.dequeue()
close_op = values_queue.close()

sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())

# add two elements onto the queue
sess.run([enqueue_op], {value_placeholder:2})
sess.run([enqueue_op], {value_placeholder:3})
# if you uncomment the next line, you'll hang because queue is full
# sess.run([enqueue_op], {value_placeholder:4})

# close the queue. This means 3rd read will throw OutOfRangeError instead of
# hanging until queue is replenished
sess.run([close_op])
print('queue has %d/%d entries' % (sess.run([size_op])[0], queue_capacity))

# take two elements off the queue
fancy_computation = tf.square(dequeue_op)
print('Computation result %d' %(sess.run([fancy_computation])[0]))
print('queue has %d/%d entries' % (sess.run([size_op])[0], queue_capacity))
print('Computation result %d' %(sess.run([fancy_computation])[0]))
print('queue has %d/%d entries' % (sess.run([size_op])[0], queue_capacity))
print('Computation result %d' %(sess.run([fancy_computation])[0]))
print('queue has %d/%d entries' % (sess.run([size_op])[0], queue_capacity))

rawDescription: How can read_cifar10() routine return anything other than first object in TensorFlow tutorial?


rawDescription: Creating a table out of data in python

description: Creating a table out of data in python


code:
originalString = "from:\t[name:\tString\nid:\tSequenceofNumber]"
fixedString = ",\t".join(originalString.split("\n"))

rawDescription: Regex matching certain character in string pattern


code: Widget.objects.extra(select={'year': "EXTRACT(year FROM sold)", 'month': "EXTRACT(month from sold)"}).values('year', 'month').annotate(Sum('price'))

rawDescription: Calculate the total value of the Widgets sold each month for a particular year


code:
def check(self):
    print(self.weapon)
    print(self.dictionary[self.weapon].ammo)

rawDescription: Why cant I access a property of an instance from another class?


code:
h1 = Holder(10)
h2 = Holder(20)
h1.value = h2.value # h1.value and h2.value point to the same int.
h1.increment() # Change observed in h2.value.  The semantics may be unexpected
               # by Python developers.

rawDescription: How to export a shared_ptr of a fundamental type to python

description: Export a shared_ptr of a fundamental type to python


code: df

rawDescription: How to rank values in different columns based on a criteria in Python (transferring Excel calculations to Python)?

description: Rank values in different columns based on a criteria in Python (transferring Excel calculations to Python)


code: numpy.savez('file.npz', **arrs)

rawDescription: How to save big (not huge) dictonaries in Python?

description: Save big (not huge) dictonaries in Python


code: re.search(r'%s$' % re.escape(name1), name2, re.IGNORECASE)

rawDescription: re.search() exact comparison at end of string

description: Re.search() exact comparison at end of string


code:
blaster_file = open("/dev/pi-blaster", "a")
for i in range(100, 0, step):
    blaster_file.write(...)
blaster_file.close()

rawDescription: LED fade in python - implementing multithreading


rawDescription: Python - Safe Indexing with boolean

description: Python - Safe Indexing with boolean


code: 'b' in input_list

rawDescription: Checking if a str is in a list of str?

description: Checking if a str is in a list of str


code:
try:
  int(val)
  is_int = True
except ValueError:
  is_int = False

rawDescription: python regular expression to validate types of strings

description: Python regular expression to validate types of strings


code: foo = [a + 42 for a in foo]

rawDescription: Change value of currently iterated element in list in python


code:
from numpy import genfromtxt
rdata = genfromtxt('AllcorrR.csv', skip_header=1)[:,1:]
Pdata = genfromtxt('AllcorrP.csv', skip_header=1)[:,1:]

rawDescription: comparing/extracting data from matrices using python (2.6.1)

description: Comparing/extracting data from matrices using python (2.6.1)


code: result = dictionary(fin)

rawDescription: pulling a dictionary out of the function that created it (python)

description: Pulling a dictionary out of the function that created it (python)


code: df.groupby(pd.cut(df.index, np.arange(20, 60, 10))).sum()

rawDescription: Pandas binning column values according to the index


code: exp_as_func = eval('lambda v: ' + expression)

rawDescription: Python: Way to speed up a repeatedly executed eval statement?


code: slice(None)

rawDescription: represent numpy ellipsis

description: Represent numpy ellipsis


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

# Plot
fig_object = plt.figure()
x = np.linspace(0,3*np.pi)
y = np.sin(x)
plt.plot(x,y)
# Save to disk
pickle.dump(fig_object,file('sinus.pickle','w'))

rawDescription: Matplotlib save file to be reedited later in ipython


code:
import re

texts = (
    'text',
    '"text"',
    'text\ntext',
    '"text\ntext"',
    'text"text\ntext"text',
    'text"text\n"\ntext"text"',
    '"\n"\ntext"text"',
    '"\n"\n"\n"\n\n\n""\n"\n"'
)

line_matcher = re.compile('(?:"[^"]*"|.)+')

for text in texts:
    print("{:>27} → {}".format(
        text.replace("\n", "\\n"),
        " [LINE] ".join(line_matcher.findall(text)).replace("\n", "\\n")
    ))

#>>>                        text → text
#>>>                      "text" → "text"
#>>>                  text\ntext → text [LINE] text
#>>>                "text\ntext" → "text\ntext"
#>>>        text"text\ntext"text → text"text\ntext"text
#>>>    text"text\n"\ntext"text" → text"text\n" [LINE] text"text"
#>>>            "\n"\ntext"text" → "\n" [LINE] text"text"
#>>>    "\n"\n"\n"\n\n\n""\n"\n" → "\n" [LINE] "\n" [LINE] "" [LINE] "\n"

rawDescription: parsing a string in python: how to split newlines while ignoring newline inside quotes

description: Parsing a string in python: how to split newlines while ignoring newline inside quotes


code:
import types

def patch_it(info, key):
    def get_it(info):
        return info.data[key]

    info.get_it = types.MethodType(get_it, info)

rawDescription: Passing unique dictionary addresses to class instances


code:
from sqlalchemy import event
from sqlalchemy.engine import Engine

@event.listens_for(Engine, "connect")
def connect(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("SET DateStyle='somestring'")
    cursor.close()

rawDescription: How to specify the PostgreSQL DateStyle property with SQLAlchemy ORM

description: Specify the PostgreSQL DateStyle property with SQLAlchemy ORM


code:
chunks = (
    (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')),
    (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')),
    (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')),
    (60 * 60 * 24, ungettext_lazy('%d day', '%d days')),
    (60 * 60, ungettext_lazy('%d hour', '%d hours')),
    (60, ungettext_lazy('%d minute', '%d minutes'))
)

rawDescription: Django - Timeuntil Tag output abbreviation


code:
class Bird(pygame.sprite.Sprite):
    def __init__(self):
       pygame.sprite.Sprite.__init__(self)

       self.image = pygame.image.load("bird.png").convert_alpha()

       # Fetch the rectangle object that has the dimensions of the image
       # Update the position of this object by setting the values of rect.x and rect.y
       self.rect = self.image.get_rect()

rawDescription: Pygame collision detect with object and rect


code:
from functools import partial

parse_requests_for_map = partial(parse_requests, user_agent_vals=user_agent_vals)

rawDescription: Is it better to use globals or pass in arguments to map functions?


code:
a = 1.0/x
inf_ind = np.isinf(a)
a[inf_ind] = your_value

rawDescription: numpy: concise conditional syntax for array division

description: Numpy: concise conditional syntax for array division


code:
from copy import deepcopy
class IncomeVerification(object):

        data = {'IncomeYears': []}
        def __init__(self, income_years):
            for year in income_years:
                new_year = deepcopy(IncomeYear(year).data)

rawDescription: Nested dictionaries in classes

description: Nested dictionaries in classes


code:
from __future__ import division
from nltk.corpus import inaugural
total_lens = 0
for i, sent in enumerate(inaugural.sents()):
    total_lens += len(sent)

total_lens
i
avg_sent_len = total_lens / i
avg_sent_len
avg_sent_len = total_lens / (i+1)
avg_sent_len

rawDescription: Average sentence length for every text in corpus (python3 & nltk)


code:
patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(',')))
patt.parseString(test).asList()

rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


rawDescription: How to patch an attribute in an object

description: Patch an attribute in an object


rawDescription: Store python requests session in persistent storage


code:
class A:   # Python 3
    pass

a = A()
a.new_attr = 10

rawDescription: More memory efficient way to define many objects of the same type


code:
#!/usr/bin/env python3

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.dropdown import DropDown
from kivy.uix.spinner import Spinner
from kivy.properties import ListProperty, ObjectProperty,\
        StringProperty, BooleanProperty, NumericProperty
#from kivy.uix.actionbar import ActionBar, ActionView, ActionGroup, ActionButton

class MenuItem(Widget):
    '''Background color, in the format (r, g, b, a).'''
    background_color_normal = ListProperty([0.2, 0.2, 0.2, 1])
    background_color_down = ListProperty([0.3, 0.3, 0.3, 1])
    background_color = ListProperty([])
    separator_color = ListProperty([0.8, 0.8, 0.8, 1])
    text_color = ListProperty([1,1,1,1])
    inside_group = BooleanProperty(False)
    pass

class MenuSubmenu(MenuItem, Spinner):
    triangle = ListProperty()

    def __init__(self, **kwargs):
        self.list_menu_item = []
        super().__init__(**kwargs)
        self.dropdown_cls = MenuDropDown

    def add_widget(self, item):
        self.list_menu_item.append(item)
        self.show_submenu()

    def show_submenu(self):
        self.clear_widgets()
        for item in self.list_menu_item:
            item.inside_group = True
            self._dropdown.add_widget(item)

    def _build_dropdown(self, *largs):
        if self._dropdown:
            self._dropdown.unbind(on_dismiss=self._toggle_dropdown)
            self._dropdown.dismiss()
            self._dropdown = None
        self._dropdown = self.dropdown_cls()
        self._dropdown.bind(on_dismiss=self._toggle_dropdown)

    def _update_dropdown(self, *largs):
        pass

    def _toggle_dropdown(self, *largs):
        self.is_open = not self.is_open
        ddn = self._dropdown
        ddn.size_hint_x = None
        if not ddn.container:
            return
        children = ddn.container.children
        if children:
            ddn.width = max(self.width, max(c.width for c in children))
        else:
            ddn.width = self.width
        for item in children:
            item.size_hint_y = None
            item.height = max([self.height, 48])

    def clear_widgets(self):
        self._dropdown.clear_widgets()

class MenuDropDown(DropDown):
        pass

class MenuButton(MenuItem,Button):
    icon = StringProperty(None, allownone=True)
    pass

class MenuEmptySpace(MenuItem):
    pass

class MenuBar(BoxLayout):

    '''Background color, in the format (r, g, b, a).'''
    background_color = ListProperty([0.2, 0.2, 0.2, 1])
    separator_color = ListProperty([0.8, 0.8, 0.8, 1])

    def __init__(self, **kwargs):
        self.itemsList = []
        super().__init__(**kwargs)

    def add_widget(self, item, index=0):
        if not isinstance(item, MenuItem):
            raise TypeError("MenuBar accepts only MenuItem widgets")
        super().add_widget(item, index)
        if index == 0:
            index = len(self.itemsList)
        self.itemsList.insert(index, item)

if __name__ == '__main__':

    class MenuApp(App):
        def button(self, nb):
            print("Button", nb, "triggered")

    MenuApp().run()

rawDescription: Dropdown partially visible in Kivy (Python)


code:
'no quotes'
'one quote: \''

rawDescription: double quotes in string representation

description: Double quotes in string representation


rawDescription: Extract Values from CSV file to then multiply with values from other CSV? Python


code:
def rect(T):
    """create a centered rectangular pulse of width $T"""
    return lambda t: (-T/2 <= t) & (t < T/2)

def pulse_train(t, at, shape):
    """create a train of pulses over $t at times $at and shape $shape"""
    return np.sum(shape(t - at[:,np.newaxis]), axis=0)

sig = pulse_train(
    t=np.arange(100),              # time domain
    at=np.array([0, 10, 40, 80]),  # times of pulses
    shape=rect(10)                 # shape of pulse
)

rawDescription: rectangular pulse train in python

description: Rectangular pulse train in python


code:
from matplotlib.cbook import flatten

data = [BSL_20, BSL_40, BSL_100, BSL_100CC, BSL_200]
max_area = max(map(sum, data))

def set_venn_scale(ax, true_area, reference_area=max_area):
    s = np.sqrt(float(reference_area)/true_area)
    ax.set_xlim(-s, s)
    ax.set_ylim(-s, s)

for a, d in zip(flatten(axes), data):
    set_venn_scale(a, sum(d))

rawDescription: Matplotlib_Venn, Multiple Venn diagrams same scale


code:
import numpy as np

A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5])
k = 3

idx = np.argpartition(A, k)
print(idx)
# [4 0 7 3 1 2 6 5]

rawDescription: Find the k smallest values of a numpy array


code: print(' '.join(map(str, attrlist)))

rawDescription: Printing an List without brackets, without quotations, without commas and additional spacing


code:
def populate_form_choices(registration_form):
    """
    Pulls choices from the database to populate our select fields.
    """
    states = State.query.all()
    countries = Country.query.all()
    state_names = []
    for state in states:
        state_names.append(state.state_name)
    #choices need to come in the form of a list comprised of enumerated lists
    #example [('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')]
    state_choices = list(enumerate(state_names))
    country_names = []
    for country in countries:
        country_names.append(country.country_name)
    country_choices = list(enumerate(country_names))
    #now that we've built our choices, we need to set them.
    registration_form.state_select_field.choices = state_choices
    registration_form.country_select_field.choices = country_choices

@app.route('/', methods=['GET', 'POST'])
def demonstration():
    """
    This will render a template that displays all of the form objects if it's
    a Get request. If the use is attempting to Post then this view will push
    the data to the database.
    """
    #this parts a little hard to understand. flask-wtforms does an implicit
    #call each time you create a form object. It attempts to see if there's a
    #request.form object in this session and if there is it adds the data from
    #the request to the form object.
    registration_form = RegistrationForm()
    #Before we attempt to validate our form data we have to set our select
    #field choices. This is just something you need to do if you're going to
    #use WTForms, even if it seems silly.
    populate_form_choices(registration_form)
    #This means that if we're not sending a post request then this if statement
    #will always fail. So then we just move on to render the template normally.
    if flask.request.method == 'POST' and registration_form.validate():
        #If we're making a post request and we passed all the validators then
        #create a registered user model and push that model to the database.
        registered_user = RegisteredUser(
            first_name=registration_form.data['first_name_field'],
            last_name=registration_form.data['last_name_field'],
            address_line_one=registration_form.data['address_line_one_field'],
            address_line_two=registration_form.data['address_line_two_field'],
            city=registration_form.data['city_field'],
            state_id=registration_form.data['state_select_field'],
            country_id=registration_form.data['country_select_field'],)
        db.session.add(registered_user)
        db.session.commit()
        return flask.render_template(
            template_name_or_list='success.html',
            registration_form=registration_form,)
    return flask.render_template(
            template_name_or_list='registration.html',
            registration_form=registration_form,)

rawDescription: Creating flask form with selects from more than one table


code:
aeval = Interpreter()
time_start = time.time()
expr = aeval.parse(userinput_function)
x = numpy.array([item['x'] for item in database_xy])
aeval.symtable['x'] = x
y = aeval.run(expr)
time_end = time.time()

rawDescription: Evaluating a mathematical expression (function) for a large number of input values fast


code:
for b in submodel_generator(newpat, current+1, maxn):
    yield b

rawDescription: Python: how to make a recursive generator function


rawDescription: How to group identical collections together

description: Group identical collections together


code:
#!/usr/bin/env python
import sys
from itertools import groupby

file = sys.stdin
next(file) # skip header line

lines = (line.split() for line in file if line.strip())
for id, same_id in groupby(lines, key=lambda x: x[0]): # by id
    max_time, max_count = None, 0
    for time, same_time in groupby(same_id, key=lambda x: x[1]): # by time
        count = sum(int(c) for _, _, c in same_time)
        if count > max_count:
            max_time, max_count = time, count
    print("{} {} {}".format(id, max_time, max_count))

rawDescription: How to find the most common occurring timestamp and its frequency from a file having multiple entries for a user and time in python?

description: Find the most common occurring timestamp and its frequency from a file having multiple entries for a user and time in python


code:
import urlparse
import urllib
url = 'http://example.com/dynamic?t=MD5-YOUR-OAUTH-TOKEN&p=11111111'
parsed = urlparse.urlparse(url)
parsed
qs = urlparse.parse_qs(parsed.query)
qs

rawDescription: Updating Query In URL With Urlib In Python


rawDescription: Insert value in Incremental List not working


code:
import ctypes

libc = ctypes.CDLL(None)
environ = ctypes.POINTER(ctypes.c_char_p).in_dll(libc, 'environ')

rawDescription: python: getting actual environment variables to modify and pass to subprocess

description: Python: getting actual environment variables to modify and pass to subprocess


code:
# \u2013 represents a long dash, long minus or so called en-dash
s = u'hello – world'
s
import re
re.split(u"\u2013", s)

rawDescription: How to split line at non-printing ascii character in Python

description: Split line at non-printing ascii character in Python


code: stdin, stdout, stderr = ssh.exec_command('print os.path.isfile("r/a/etc/portal/db/secrets/db.shared")')

rawDescription: Not able get the return value of command print os.path.isfile(filename) from with in paramiko connection


code: dict(zip(found[::2], found[1::2]))

rawDescription: Python parsing list of string

description: Python parsing list of string


code:
for node in tree.in_order():
    do_something_with(node.value)

rawDescription: Python in order traversal to a flat list