code:
import datetime

from yourapp.models import Event

class SingleEventView(DetailView):
    model = Event
    template_name = 'single-event.html'

    def get_context_data(self, *args, **kwargs):
       # Get the existing context dictionary, then add
       # your custom object to it before returning it
       ctx = super(SingleEventView, self).get_context_data(*args, **kwargs)
       ctx['approaching'] = Event.objects.exclude(event_date__lt=datetime.date.today())[:5]
       return ctx

rawDescription: Showing a list of objects alongside a Django DetailView


code:
#!/usr/bin/python2.6
import subprocess
from flask import Flask, render_template

app = Flask(__name__)

def get_data():
    """
    Return a string that is the output from subprocess
    """

    # There is a link above on how to do this, but here's my attempt
    # I think this will work for your Python 2.6

    p = subprocess.Popen(["tree", "/your/path"], stdout=subprocess.PIPE)
    out, err = p.communicate()

    return out

@app.route('/')
def index():
    return render_template('subprocess.html', subprocess_output=get_data())

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Run Python script with HTML embedded

description: Run Python script with HTML embedded


rawDescription: Python run code every 100th loop item

description: Python run code every 100th loop item


code:
import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

rawDescription: How to import a module given the full path?

description: Import a module given the full path


rawDescription: Check if list item contains items from another list


code: lfunctionHashes = set()

rawDescription: Can I restore a function whose closure contains cycles in Python?

description: Restore a function whose closure contains cycles in Python


rawDescription: How can I convert a hex ASCII string to a signed integer

description: Convert a hex ASCII string to a signed integer


rawDescription: How to convert flat items/list to Pandas dataframe

description: Convert flat items/list to Pandas dataframe


rawDescription: add an element N times between elements in list

description: Add an element N times between elements in list


rawDescription: pandas - apply replace function with condition row-wise

description: Pandas - apply replace function with condition row-wise


code:
import re
twikiattribs = 'author="PersonsName" date="1183050420" format="1.1" version="1.2"'
re.findall(r'(\w+)="([^"]+)"', twikiattribs)
dict(re.findall(r'(\w+)="([^"]+)"', twikiattribs))

rawDescription: turn key="value" string into a dict

description: Turn key="value" string into a dict


code:
import bisect
import datetime
def generate_last(dts):
    current = dts[0].replace(microsecond=0)
    end = dts[-1]
    pos = 0
    while current < end:
        current += datetime.timedelta(seconds=1)
        pos = bisect.bisect(dts, current, lo=pos)
        yield dts[pos - 1]

dts = [datetime.datetime(2014, 8, 15, 13, 1, 41, 658749),
       datetime.datetime(2014, 8, 15, 13, 1, 42, 158749),
       datetime.datetime(2014, 8, 15, 13, 1, 42, 258749),
       datetime.datetime(2014, 8, 15, 13, 1, 43, 658749),
       datetime.datetime(2014, 8, 15, 13, 1, 45, 658749)]
pprint(list(generate_last(dts)))

rawDescription: Extracting latest datetime from a list "every second"


code:
if geometry is not None:
    w.show()
    w.setGeometry(*geometry)
else:
    w.showMaximized()

rawDescription: Pyforms - Form appears always maximized

description: Pyforms - Form appears always maximized


code:
from math import isnan
c = dict((k, v) for k, v in d.items() if not (type(k) == float and isnan(k)))
c

rawDescription: Filtering null values from keys of dictionary- Python


code:
def my_ignore(dir, files):
    if dir == '/full_path_to':
        return {"exclude.file"}

rawDescription: The Ignore callback for python shutil.copytree() does not accept full path


code:
mysourceaddrlong = r"\x00\x13\xa2\x00@\n!\x1c"
"\\".join([(i[0]+i[1:].upper()) for i in mysourceaddrlong.split('\\') if i])

rawDescription: Convert all letters to uppercase except those following a backslash


code:
# Extract row and column information
rowIDs = df['row']
colIDs = df['col']

# Setup image array and set values into it from "grumpiness" column
A = np.zeros((rowIDs.max()+1,colIDs.max()+1))
A[rowIDs,colIDs] = df['grumpiness']

rawDescription: Create 2D array from Pandas dataframe

description: Create 2D array from Pandas dataframe


code:
# connect, keepalive and disconnect
def ws_foo(message):
    pass

rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


rawDescription: Downsampling irregular time series in pandas


code: sorted(scrambled, key=word.index)

rawDescription: Sorting string into identical words

description: Sorting string into identical words


code:
while a <= c:
    b = randrange(1, 200)
    if b in my:
        print('Duplicate random value generated')
    my.add(b)
    a = a + 1

rawDescription: comparing values in a set

description: Comparing values in a set


code:
# There are five possible values for the "formatter" argument passed in
# to methods like encode() and prettify():
#
# "html" - All Unicode characters with corresponding HTML entities
#   are converted to those entities on output.
# "minimal" - Bare ampersands and angle brackets are converted to
#   XML entities: & < >
# None - The null formatter. Unicode characters are never
#   converted to entities.  This is not recommended, but it's
#   faster than "minimal".

rawDescription: How to insert a blank space(&nbsp) into a Beautifulsoup tag?

description: Insert a blank space(&nbsp) into a Beautifulsoup tag


code:
def test_generate_tests(metafunc):
    rows = read_csvrows()
    if 'row' in metafunc.fixturenames:
        metafunc.parametrize('row', rows)
    if 'col' in metafunc.fixturenames:
        metafunc.parametrize('col', list(itertools.chain(*rows)))

rawDescription: pytest parameterize - row from CSV as a testcase

description: Pytest parameterize - row from CSV as a testcase


rawDescription: Getting the first three bytes of an IP address


rawDescription: Animate quadratic grid changes (matshow)


code:
import itertools

with open(filename, 'r') as f:
    lines_gen =  itertools.islice(f, 1, num_lines) # start from 1,  read num_lines
    l = [int(line) for line in lines_gen]

rawDescription: Save data from a text file into an array in Python


rawDescription: Replacing a unicode character in a string in Python 3


code:
def a(a,b,c):
    kwargs = {'a':a , 'b':b , 'c':c}
    d(**kwargs)
def d(**kwargs):
    print(kwargs)
a(1,2,3)

rawDescription: Python: put all function arguments into **kwargs automatically


rawDescription: Fastest Way to Round to the Nearest 5/100ths


code:
class Baz(object):
    _foo = 'spam'
    @property
    def foo(self):
        return self._foo
    echo = with_descriptor_defaults(foo)(mk_foobar)

baz = Baz()
baz_echo = baz.echo
baz._foo = 'ham'
baz_echo()

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
from csvkit import convert
convert.convert(open('test.xlsx', 'rb'), 'xlsx')

rawDescription: Why does csvkit's in2csv convert dates to integers?


code:
string = input("Enter a string: ")

if all(x.isalpha() or x.isspace() for x in string):
    print("Only alphabetical letters and spaces: yes")
else:
    print("Only alphabetical letters and spaces: no")

rawDescription: Checking if string is only letters and spaces - Python


code: [lst[i:i+leng] for leng in range(len(lst), 0, -1) for i in range(len(lst)-leng+1)]

rawDescription: python connected combinations of list items

description: Python connected combinations of list items


code: response = reply_xml.find('.//SOAP:Body/dummy:Server_Reply',namespaces = {'SOAP':'http://www.w3.org/2003/05/soap-envelope', 'dummy':'some_url'})

rawDescription: Find element with function find in lxml

description: Find element with function find in lxml


code:
import grequests
import pprint

urls = [
    'http://httpbin.org/user-agent',
    'http://httpbin.org/headers',
    'http://httpbin.org/ip',
]

requests = (grequests.get(u) for u in urls)
responses = grequests.map(requests)

json = [response.json() for response in responses]
pprint.pprint(json)

text = '\n'.join(response.text for response in responses)
print(text)

rawDescription: Python: How can i send multiple HTTP requests and receive the response?


code:
import string

def clean_up(s):
    # I'm assuming you REQUIRE this function as per your assignment
    # otherwise, just substitute str.strip(string.punctuation) anywhere
    # you'd otherwise call clean_up(str)
    return s.strip(string.punctuation)

def average_word_length(text):
    total_length = sum(len(clean_up(word)) for sentence in text for word in sentence.split())
    num_words = sum(len(sentence.split()) for sentence in text)
    return total_length/num_words

rawDescription: average number of characters per word in a list

description: Average number of characters per word in a list


code:
from binascii import hexlify
hexVals = hexlify(f.read())

rawDescription: Add leading zero to hex values in python


rawDescription: re.search with multiple matched keyword

description: Re.search with multiple matched keyword


code:
df.boxplot(column='B', by='A')
plt.twinx()
plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'],
        align='center', alpha=0.3)

rawDescription: Python pandas plotting shift x-axis if twinx two y-axes


rawDescription: Python: A4 size for a plot

description: Python: A4 size for a plot


rawDescription: regex/beautifulsoup how to extract the all values of column from html table?

description: Regex/beautifulsoup how to extract the all values of column from html table


code:
{'comment': 'words words', 'name': 'test1'}
{'comment': 'more words', 'name': 'test2'}
{'comment': '690512810, other words', 'name': 'rex'}

rawDescription: Parsing a JSON file in Python

description: Parsing a JSON file in Python


code:
# convert df to rdd
rdd = df.rdd

def extract(row, key):
    """Takes dictionary and key, returns tuple of (dict w/o key, dict[key])."""
    _dict = row.asDict()
    _list = _dict[key]
    del _dict[key]
    return (_dict, _list)

def add_to_dict(_dict, key, value):
    _dict[key] = value
    return _dict

# preserve rest of values in key, put list to flatten in value
rdd = rdd.map(lambda x: extract(x, 'sBus'))
# make a row for each item in value
rdd = rdd.flatMapValues(lambda x: x)
# add flattened value back into dictionary
rdd = rdd.map(lambda x: add_to_dict(x[0], 'sBus', x[1]))
# convert back to dataframe
df = sqlContext.createDataFrame(rdd)

df.show()

rawDescription: How do I flattern a pySpark dataframe by one array column?

description: Flattern a pySpark dataframe by one array column


rawDescription: Comparing Pandas Dataframe Rows & Dropping rows with overlapping dates


code:
HISTORICAL_URLS_MAPPING = {
    '33': '/this-is-a-page-about-programming',
    '34': '/this-is-a-page-about-premature-optimization'
}

def historical_node_id_view(node_id):
    return HTTPFound(HISTORICAL_URLS_MAPPING[node_id])

rawDescription: How to mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)?

description: Mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)


code:
import numpy as np
import tables

# Generate some data
x = np.random.random((100,100,100))

# Store "x" in a chunked array with level 5 BLOSC compression...
f = tables.openFile('test.hdf', 'w')
atom = tables.Atom.from_dtype(x.dtype)
filters = tables.Filters(complib='blosc', complevel=5)
ds = f.createCArray(f.root, 'somename', atom, x.shape, filters=filters)
ds[:] = x
f.close()

rawDescription: Python: how to store a numpy multidimensional array in PyTables?


code:
@prints_invocation
def add(x, y):
    return x + y
add(1, 2)

rawDescription: print arguments on function invocation

description: Print arguments on function invocation


rawDescription: create a dictionary for a certain range in Python

description: Create a dictionary for a certain range in Python


code:
registers[0]=('register_1', '1', '5', regfield)
registers

rawDescription: Placing a numpy record array inside another record array python


code:
import re
s = """fooblahblahbar
fooblahbazbar"""
m = re.findall(r'foo(?:(?!baz).)*bar', s, re.M)
m

rawDescription: what is the regular expression that matches from one substring to a second one, without another one in between?

description: What is the regular expression that matches from one substring to a second one, without another one in between


code:
class Supplier(object):
    def __init__(self):
        self.projects = []  #winning projects
        self.bids = []      #how much this supplier bid, winning bid.

rawDescription: search large number of text files python

description: Search large number of text files python


rawDescription: How can I include null values in arithmetic query in django

description: Include null values in arithmetic query in django


rawDescription: Many independent pseudorandom graphs each with same arbitrary y for any input x


code: list(combine('AB?D?', ['ABC', 'DEF']))

rawDescription: Generate combinations from an input in python


code:
from functools import reduce

reduce(lambda counts, bc: (counts[0] + bool(bc[0]), counts[1] + bool(bc[1])),
       bullsandcows(given, number), (0, 0))

rawDescription: Reduce list of tuples

description: Reduce list of tuples


code:
[section1]
Name1=Url_1
Name2=Url_2

[Section2]
Name3=Url_3
Name4=Url_4

rawDescription: Printing contents in particular section of configuration file in Python


code:
f = open("output.csv", 'wt')
for item in group:
    custom_serialization = ', _ ,'.join(item.split('_'))
    f.write(custom_serialization + '\n')
f.close()

rawDescription: CSV Python Delimiting Underscore

description: CSV Python Delimiting Underscore


code:
SUDO_USER
SUDO_UID

rawDescription: Python: drop root privileges for certain operations


code:
class StaffInLine(admin.TabularInline):
    model = Staff
    formset = StaffInlineFormSet
    def get_max_num(self, request, obj=None, **kwargs):
        return 10
    def get_min_num(self, request, obj=None, **kwargs):
        return 1

rawDescription: Django-admin validation on Foreign object


code:
def __cmp__(self, a):
    return cmp(self.code, a.code)

rawDescription: Huffman encoding issue

description: Huffman encoding issue


code:
do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
do.strftime("%H:%M:%S")

rawDescription: Change Date Format In Python

description: Change Date Format In Python


rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'program.py'],
             pathex=['C:\\Your\\User\\Path\\To\\pyinstaller'])
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=1,
          name=os.path.join('build\\pyi.win32\\App Name', 'App Name.exe'),
          debug=False,
          strip=False,
          upx=True,
          console=False , icon='youricon.ico')
coll = COLLECT( exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name=os.path.join('dist', 'Hey Mang!'))
app = BUNDLE(coll,
             name=os.path.join('dist', 'Hey Mang!.app'))

rawDescription: PyInstaller won't load the PyQt's images to the GUI


code: FactoryClass()

rawDescription: Only creating object through factory class in Python - factory class related


code:
y=25
all(y%p>0 for p in q)
y=29
all(y%p>0 for p in q)

rawDescription: To test a condition on all values in a list before proceeding to the next line


code: df = pd.read_csv('File.txt', sep='\t', header=None)

rawDescription: Pandas sort() ignoring negative sign

description: Pandas sort() ignoring negative sign


rawDescription: Avoid updating nested lists in for loop

description: Avoid updating nested lists in for loop


code:
def my_view(request, name=None):
    # get a model instance
    animal = animals.objects.get(name=name)

rawDescription: Capturing objects in Django Url

description: Capturing objects in Django Url


code:
from __future__ import print_function
print("hi there", file=f)

rawDescription: Correct way to write line to file in Python


rawDescription: Python (numpy) sort character order?

description: Python (numpy) sort character order


rawDescription: Converting pairwise to list with varying number of rows based on value


code:
set(['apple', '16', 'gb', '6', 'silver', 'iphone'])
set(['apple', 'mobile', 'phone', '64', 'gb', '6', 'gsm', 'silver', 'iphone'])
False

rawDescription: How to perform pattern matching between two strings?

description: Perform pattern matching between two strings


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


code:
class MovieCategoryAdmin(admin.ModelAdmin):
    """
    Admin Class for 'Movie Category'.
    """
    fieldsets = [
        ('Category',      {'fields': ['category']}),
        ('Movie',         {'fields': ['movie']}),
        ('Prefix',        {'fields': ['prefix']}),
        ('Number',        {'fields': ['number']}),
    ]
    list_display = ('category', 'movie', 'prefix', 'number')
    search_fields = ['category__category_name', 'movie__title', 'prefix__prefix']
    form = MovieCategoryForm

rawDescription: Django ForeignKey limit_choices_to a different ForeignKey id


code: a=array.array('i',(0 for i in range(N)))

rawDescription: Python Typed Array of a Certain Size

description: Python Typed Array of a Certain Size


code: #pylint: disable-all

rawDescription: Pylint disable all warnings for a file

description: Pylint disable all warnings for a file


code: [x for x in chain(A, B, C) if x[0] in common]

rawDescription: Efficiently find overlap of a lists of tuples


code: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

rawDescription: Pandas left outer join multiple dataframes on multiple columns


code:
ms = fb.MyStruct()
ret =  fb.MYSTRUCT_Func1(ms, 123)

rawDescription: SWIG interfacing C library to Python (SWIG generated classes are cumbersome to use)


rawDescription: Merging 2 Lists In Multiple Ways - Python


rawDescription: I have need the N minimum (index) values in a numpy array


code:
import linecache
linecache.getline('testfile.txt', 2)

rawDescription: Reading a specific line in a file

description: Reading a specific line in a file


code: connSqlServer = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=192.106.0.102,1443;DATABASE=master;UID=sql2008;PWD=password123')

rawDescription: python pyodbc : how to connect to a specific instance

description: Python pyodbc : how to connect to a specific instance


rawDescription: Merge two lists of tuples with timestamps and queue lengths


code:
from PIL import Image
from pyscreenshot import grab

img = grab(bbox=(100, 200, 300, 400))

# to keep the aspect ratio
w = 300
h = 400
maxheight = 600
maxwidth = 800
ratio = min(maxwidth/width, maxheight/height)
# correct image size is not #oldsize * ratio#

# img.resize(...) returns a resized image and does not effect img unless
# you assign the return value
img = img.resize((h * ratio, width * ratio), Image.ANTIALIAS)

rawDescription: How to do a screenshot of a tkinter application?

description: Do a screenshot of a tkinter application


code: map(*[None] + result)

rawDescription: How do I convert apply(map, args) to map(function, iterable) in this case?

description: Convert apply(map, args) to map(function, iterable) in this case


rawDescription: Parsing or Splitting pysnmp output to update into database


code: cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%sw' ) AS UNSIGNED);", ['%'])

rawDescription: Calling DATE_FORMAT() in MySQL from Django fails


code: tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5)))

rawDescription: Python : Get many list from a list

description: Python : Get many list from a list


rawDescription: How to display only a left and bottom box border in matplotlib?

description: Display only a left and bottom box border in matplotlib


rawDescription: Why does setattr work differently for attributes and methods?


code:
@numba.jit(nopython=True)
def generate_values(mins, maxs, vals):
    N = len(vals)
    ans = np.empty(N)

    for i in range(N):
        for j in range(i, N):
            if vals[j] < mins[i] or vals[j] > maxs[i]:
                ans[i] = vals[j]
                break
        else:
            ans[i] = np.nan
    return ans

rawDescription: Optimizing time series generation

description: Optimizing time series generation


rawDescription: urls.py and redirecting urls

description: Urls.py and redirecting urls


code:
from itertools import combinations, product

def pairs(*lists):
    for t in combinations(lists, 2):
        for pair in product(*t):
            #Don't output pairs containing duplicated elements
            if pair[0] != pair[1]:
                yield pair

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

#Feed the output of `pairs` into a set to eliminate duplicate tuples
output = set(pairs(a, b, c))
for pair in sorted(output):
    print(pair)

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


code: result = freq.stack().reset_index()

rawDescription: Pandas: calculate overlapping with pivot_table or crosstab


code:
table = {i: unicode(chr(i)) if 32 <= i < 128 else u'\\%o' % i for i in range(256)}
u'\xb0ABD\260'.translate(table)

rawDescription: How to replace r'\xb0' with r'\260'

description: Replace r'\xb0' with r'\260'


code: y

rawDescription: Rank each number by position in a list of arrays - Python


code:
# Read all lines into lines list, each element is a dictionary
lines = []
with open("save_file.txt") as f:
    for line in f:
        s = {}
        (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = line.split(";")
        lines.append(s)

# Print first line
s = lines[0]
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])

# Print second line
s = lines[1]
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])

# Or with a Function
def print_line(lines, num):
    s = lines[num]
    print(s['name'])
    print(s['race'])
    print(s['class'])
    print(s['FOR'])
    print(s['INT'])
    print(s['DES'])

# Print third line
print_line(lines, 2)

rawDescription: How to stop print lines?

description: Stop print lines


code:
from django.template.loader import render_to_string
content = render_to_string(template_name, dictionary, context_instance)

rawDescription: Include a view in a template

description: Include a view in a template


code:
buf = np.zeros(3, dtype=np.int8) # 3 byte buffer
arr = buf.view(dtype=np.int16) # Error! Needs a buffer with multiples of 2 bytes
two_byte_slice = buf[:2]
arr = two_byte_slice.view(dtype=np.int16) # Succeeds
arr[0] = 1
assert buf[0] == 1 # shows that two_byte_slice and arr are not copies of buf

rawDescription: Define Ctypes array that overlaps in memory for numpy array and multiprocessing


code:
i, j = 0, 0
with open("wordlist") as fin:
    for line in fin:
        i += 1
        for word in line.split():
            if "e" not in word.lower():
                j += 1

rawDescription: python condition in function without_E not doing what is suppose to

description: Python condition in function without_E not doing what is suppose to


rawDescription: Read contents of <script> with BeautifulSoup


code:
wiki = """
=Title=

Description.

{| class="wikitable sortable"
|-
! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment
|-
| ION || 1.8 || 0.067 || 27 ||  || 16 || poclbm;  power consumption incl. CPU
|-
| 8200 mGPU || 1.2 || || || 1200 || 16 || 128 MB shared memory, "poclbm -w 128 -f 0"
|-
| 8400 GS || 2.3 || || || || || "poclbm -w 128"
|-
|}

{| class="wikitable sortable"
|-
! A !! B !! C
|-
| 0
| 1
| 2
|-
| 3
| 4
| 5
|}
"""

rawDescription: How to convert Wikipedia wikitable to Python Pandas DataFrame?

description: Convert Wikipedia wikitable to Python Pandas DataFrame


code:
mylist = []

for f in files:
    new = f.attribute
    mylist.append(new)

rawDescription: Python iterating over a list to add items to another list?


code:
from django.db.models import Max

# with this method the total_price can be filtered on
SomeModel.objects.annotate(
    total_price=Max('base_price', field='base_price + commission')
).filter(total_price__lt=20)

rawDescription: How to calculate the total of two fields for each item in the queryset

description: Calculate the total of two fields for each item in the queryset


code: data = np.loadtxt('file.txt', [('x',float), ('y',float), ('value',float)])

rawDescription: Nx3 column data to 2d matrix for image processing


code:
def insert(list1, list2, index):
    return  list1[:index]+list2+list1[index:]

rawDescription: Whats the best way to remove print brackets from a python list?


code:
source = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']
source[::4]
source[1::4]
def slice_per(source, step):
    return [source[i::step] for i in range(step)]

slice_per(source, 4)
slice_per(source, 3)

rawDescription: How to Split Python list every Nth element

description: Split Python list every Nth element


code:
user_score += len(input_set & set_1)
user_score += len(input_set & set_2) * 2
# etc.

rawDescription: Finding the intersection between sets and awarding points


rawDescription: Adding DataFrame groups as data columns

description: Adding DataFrame groups as data columns


code:
@app.route('/double/<int:number>')
def double(number):
    return '%d' % (number * 2)

rawDescription: Flask multiple URL handlers process URLs partially


code: migrate_table("...long sql query...", "...", check_customer_name)

rawDescription: Python functions - pass a full if condition as a parameter


rawDescription: Python longest/average 'losing' run in a sequence of binary digits in a string


code:
from StringIO import StringIO
timeit(lambda: truncate(StringIO()))
timeit(lambda: new(StringIO()))

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
import xml.etree.ElementTree as ET
from collections import defaultdict

strings = ["Sweden, Västmanland, Västerås",
"Sweden, Dalarna, Leksand",
"Ireland, Cork, Cobh",
"Ireland, Clare, Boston",
"Ireland, Cork, Baltimore",
"Sweden, Dalarna, Mora"]

dd = defaultdict(lambda: defaultdict(list))

for s in strings:
    a, b, c = s.split(', ')
    dd[a][b].append(c)

root = ET.Element('data')

for c, regions in dd.items():
    country = ET.SubElement(root,  'country', {'name': c})
    for r, settlements in regions.items():
        region = ET.SubElement(country, 'region', {'name': r})
        for s in settlements:
            settlement = ET.SubElement(region, 'settlement', {'name': s})

import xml.dom.minidom # just to pretty print for this example
print(xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml())

rawDescription: Convert strings to nested XML data

description: Convert strings to nested XML data


code:
import re
re.findall(r'\w+',s)

rawDescription: Python List comprehension: Single string to list


code:
from __future__ import print_function
import decimal
import sys

if sys.version_info.major<3:
    ic=long
else:
    ic=int

def ri(i, places=6):
    with decimal.localcontext() as lct:
        lct.prec=places
        n=ic(decimal.Decimal(i,)+decimal.Decimal('0'))
    return format(n,',')

print(ri(2**99, 4))
# 633,800,000,000,000,000,000,000,000,000
print(ri(12349159111, 7))
# 12,349,160,000
print(ri(12349111111, 3))
# 12,300,000,000

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


code: angleInDegrees = atan2(deltaY, deltaX) * 180 / PI

rawDescription: How to calculate the angle between a line and the horizontal axis?

description: Calculate the angle between a line and the horizontal axis


code:
import io
txt = "foo\nbar\nbaz"
stream = io.TextIOWrapper(io.BytesIO(txt))
stream.read(5)

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


rawDescription: Using Regular Expressions With Python to Get Value Buried in HTML5


code:
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop

class Part(ndb.Model):
    alpha = msgprop.EnumProperty(Alpha, required=True)
    ...

rawDescription: Pass enum to ndb.Model field in python

description: Pass enum to ndb.Model field in python


code:
t = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'untill to twenty']
for i, x in enumerate(t):
     obj = Button(root1, text=x, command=lambda name=x: btn_click(name), width=27)
     obj.grid(row=i, column=0, sticky=W, padx=15, pady=15)

rawDescription: Is it possible to know the button name through function


code:
import re
[x.start() for x in re.finditer('foo', 'foo foo foo foo')]

rawDescription: How to find all occurrences of a pattern and their indices in Python

description: Find all occurrences of a pattern and their indices in Python


code:
import pandas as pd

df = pd.DataFrame({
    'one.txt': [1, 0, 1, 0, 0, 1, 1, 2, 0],
    'third.txt': [1, 0, 1, 0, 1, 0, 1, 0, 0],
    'two.txt': [0, 1, 1, 1, 0, 0, 1, 0, 1]},
    index=['a', 'i', 'is', 'no', 'not', 'really', 'sentence', 'short', 'think'])

order = df.sum(axis=1).sort(inplace=False, ascending=False)
print(df.loc[order.index])

rawDescription: custom sorting pandas dataframe

description: Custom sorting pandas dataframe


code:
import re

pat = re.compile(r'\[(.*?)\](.*)')

settings = {}

with open('your_file') as fd:
    for line in fd:
        m = pat.match(line)
        if m is None: continue
        settings[m.group(1)] = m.group(2).strip()

rawDescription: Reading Tags in text File Python

description: Reading Tags in text File Python


code:
import cloudstorage
from google.appengine.api import app_identity

bucketName = app_identity.get_default_gcs_bucket_name()
fileName = "/" + bucketName + "/somedir/somefile.txt"

with cloudstorage.open(fileName, "w") as gcsFile:
            gcsFile.write("text")

rawDescription: Writing to text file with python running on GAE


code:
from collections import deque

def comparisons(seq):
    return [abs(a-b) for a, b in zip(seq, seq[1:])]

def best_order(seq):
    pool = deque(sorted(seq))
    temp = deque([pool.popleft(), pool.pop()])
    try:
        while pool:
            if temp[0] < temp[-1]:
                temp.append(pool.popleft())
                temp.appendleft(pool.pop())
            else:
                temp.append(pool.pop())
                temp.appendleft(pool.popleft())
    except IndexError:
        pass
    return list(temp)

i = [0, 1, 2, 3, 4, 5, 6, 0, 0, 1, 1, 2, 2]
print("Algorithmic:", best_order(i), comparisons(best_order(i)), sum(comparisons(best_order(i))))
for n in range(2, 6):
    i = list(range(n))
    print("Algorithmic:", best_order(i), comparisons(best_order(i)), sum(comparisons(best_order(i))))

rawDescription: Comparison between adjacent elements in sequences


code:
def setUp(self):
    p = Person.objects.create(name="Alex")

    for i in range(self.num_entries):
        Entry.objects.create(author=p, title="Entry with number %s" % i, text="foobar " * i)

    Entry.indexer.update()

rawDescription: How to make django test framework read from live database?

description: Make django test framework read from live database


code:
t="""date,val
12/05/1984,sadas
1/11/1980,sadas
2/4/1945,sadas
22/10/1921,sadas"""
df = pd.read_csv(io.StringIO(t), parse_dates=[0])
df.to_csv(r'c:\data\date.csv', date_format='%Y-%m-%d')

rawDescription: How to specify date format when using pandas.to_csv to YYYY-MM-DD?

description: Specify date format when using pandas.to_csv to YYYY-MM-DD


code:
class MyHashTable:
    def __init__(self, capacity):
        self.capacity = capacity
        self.slots = [None] * self.capacity
        self.count = 0

    def __str__(self):
        return str(self.slots)

    def __contains__(self, item):
        return self.search(item) != -1

    def __len__(self):
        return self.count

    def hash_function(self, key):
        return hash(key) % self.capacity

    def find_slot(self, key):
        slot = self.hash_function(key)
        while self.slots[slot] is not None and self.slots[slot] != key:
            slot = (slot + 1) % self.capacity
        return slot

    def insert(self, key):
        slot = self.find_slot(key)
        if self.slots[slot] != key:
            self.slots[slot] = key
            self.count += 1

    def search(self, key):
        i = self.find_slot(key)
        if self.slots[i] is not None:
            return i
        return -1

rawDescription: Python MyHashTable class: search method with linear probing


rawDescription: Python pickle load doesn't work when program is run again


rawDescription: Finding out names from Regular Expression using Python


code:
tkinter.after(10, change_one_pixel)

def change_one_pixel():
     change_next_pixel() # if you change more pixels you get faster animation
     create_new_image()
     update_label()
     if any_pixel_left:
        tkinter.after(10, change_one_pixel)

rawDescription: How do I get my program to update this tkinter label in my nested loop so that it shows the grayscale process?

description: Get my program to update this tkinter label in my nested loop so that it shows the grayscale process


code:
initialize
('doing things', 1)
('doing things', [2, 3])

rawDescription: Changing a function implementation in Python


code: key=lambda x: (x[0], -int(rankednames[x]))

rawDescription: More complex sorting: How to cateorize data and sort the data within categories? (Python)


code:
s = 'is this is'
counter = len(s.split(word))-1
counter

rawDescription: Python - Find words in string

description: Python - Find words in string


code: df['YearMonth'] = df['ArrivalDate'].map(lambda x: 1000*x.year + x.month)

rawDescription: Extracting just Month and Year from Pandas Datetime column (Python)


code:
@checkpoint
def step1():
    return do_stuff_here()

def intermediate_step():
    return some_operation(step1())

@checkpoint
def step2():
    return do_stuff_with(intermediate_step())

# ... and so on

rawDescription: Formatting if try except else code blocks


code:
list_a = [e['a'] for e in a_list]
set_b = {e['b'] for e in a_list}

rawDescription: Python: How should I reformat this short code block?


code:
t.textLines('''Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book.''')

rawDescription: Reportlab new line in a long line

description: Reportlab new line in a long line


code:
# -*- coding : utf-8 -*-
from __future__ import absolute_import

from celery import Celery

app = Celery('mymodule',
             broker='amqp://',
             backend='amqp://',
             include=['mymodule.tasks'])

if __name__ == '__main__':
    app.start()

rawDescription: Can i use celery without django

description: Use celery without django


code:
s = u"[u'967208', u'411600', u'460273']"

import csv
import re
with open("out.csv","w") as out:
    wr = csv.writer(out,delimiter="\n")
    r = re.compile("\d+")
    wr.writerow(r.findall(s))

rawDescription: Remove unicode [u']

description: Remove unicode [u']


code:
t1 = threading.Thread(target=winsound.PlaySound, args=("C:/Interactive Program/LIP Source Files/skyisup.wav", 2))
t2 = threading.Thread(target=lipgui.msgbox, args=("The sky is up.",))

rawDescription: How to run 2 different processes at once in Python

description: Run 2 different processes at once in Python


code:
nodes
weight

rawDescription: Replacing Names with Index From Separate File using Pandas


code:
#!/usr/bin/env python3
from subprocess import check_output

cmd = '''py -3 -c "print('no newline in the input', end='')"'''
cat = '''py -3 -c "import os; os.write(1, os.read(0, 512))"'''  # pass as is
piped = check_output(['powershell', '-C', '{cmd} | {cat}'.format(**vars())])
no_pipe = check_output(['powershell', '-C', '{cmd}'.format(**vars())])
print('piped:   {piped}\nno pipe: {no_pipe}'.format(**vars()))

rawDescription: Decode poweshell output possibly containing non-ascii unicode characters into a python string


code:
import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network"])

rawDescription: List All Wireless Networks Python for PC


code:
object1.value_changed.connect(lambda val: store_var('var1', val))
object2.value_changed.connect(lambda val: store_var('var2', val))

rawDescription: PyQt, Python 3: Lambda slot assigning signal argument to a variable?


rawDescription: Cumulative addition whilst looping over a list


rawDescription: Next level of abstraction up from a for loop?


rawDescription: How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link?

description: Scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link


rawDescription: grouping a list in individual lists in a base list or completely individual in maya python

description: Grouping a list in individual lists in a base list or completely individual in maya python


rawDescription: Replace values in an 2d array according to neighboring values


code:
def bisect_right(rows, country, lo=0, hi=None):
    if hi is None:
        hi = len(rows)
    while lo < hi:
        mid = (lo + hi) // 2
        if country < rows[mid][0]:
            hi = mid
        else:
            lo = mid + 1
    return lo

def bisect_left(rows, country, lo=0, hi=None):
    if hi is None:
        hi = len(rows)
    while lo < hi:
        mid = (lo + hi) // 2
        if rows[mid][0] < country:
            lo = mid + 1
        else:
            hi = mid
    return lo

rawDescription: python binary search and file i/o

description: Python binary search and file i/o


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


code: vertices = sorted(vertices, key = lambda x: (x.co.y, x.co.x), reverse = True)

rawDescription: Multisort Python

description: Multisort Python


code:
##################################################
# file: EchoServer_server.py
#
# skeleton generated by
#  "ZSI.generate.wsdl2dispatch.ServiceModuleWriter"
#
##################################################

from ZSI.schema import GED, GTD
from ZSI.TCcompound import ComplexType, Struct
from EchoServer_types import *
from ZSI.ServiceContainer import ServiceSOAPBinding

# Messages
EchoRequest = GED("urn:ZSI", "Echo").pyclass

EchoResponse = GED("urn:ZSI", "Echo").pyclass

# Service Skeletons
class EchoServer(ServiceSOAPBinding):
    soapAction = {}
    root = {}

    def __init__(self, post='', **kw):
        ServiceSOAPBinding.__init__(self, post)

    def soap_Echo(self, ps, **kw):
        request = ps.Parse(EchoRequest.typecode)
        return request,EchoResponse()

    soapAction['Echo'] = 'soap_Echo'
    root[(EchoRequest.typecode.nspname,EchoRequest.typecode.pname)] = \
        'soap_Echo'

rawDescription: Are there any working examples of Zolera SOAP Infrastructure (ZSI)?


code: db = SQLAlchemy(app)

rawDescription: How to create (in Flask using flask-SA etc.) an SQLite DB file with metadata.create_all(..)

description: Create (in Flask using flask-SA etc.) an SQLite DB file with metadata.create_all(..)


code: lines = open("inputfilex.txt", "r").readlines()

rawDescription: taking a character input in python from a file?

description: Taking a character input in python from a file


code:
class NumberEntry(gtk.Entry):
    def __init__(self):
        gtk.Entry.__init__(self)
        self.connect('changed', self.on_changed)

    def on_changed(self, *args):
        text = self.get_text().strip()
        self.set_text(''.join([i for i in text if i in '0123456789']))

rawDescription: Creating a pygtk text field that only accepts number


code:
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(5)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(1)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)

rawDescription: Minor ticks with only major tick labels are shown


rawDescription: how to check DEBUG true/false in django template - exactly in layout.html

description: Check DEBUG true/false in django template - exactly in layout.html


rawDescription: i was solving a sequence of large numbers, but python shell stop responding

description: I was solving a sequence of large numbers, but python shell stop responding


code: [i for i in range(20) if re.search(r'^(A{2,})\1+$', 'A' * i)]

rawDescription: Composite number of occurrences of letter with regex


code:
with open('/path/to/csv-file.csv') as f:
    reader = csv.reader(f, delimiter='"')
    header = [column.replace("'", "") for column in header]

rawDescription: using python extract string from a list of string

description: Using python extract string from a list of string


code:
class ShadingInfoDecoder(json.JSONDecoder):
    def decode(self, obj):
        obj = super(ShadingInfoDecoder,self).decode(s)
        if isinstance(obj, dict):
            decoders = [("_set",self.setDecode),
                        ("_NodeInfo", self.nodeInfoDecode),
                        ("_ShapeInfo", self.shapeInfoDecode),
                        ("_ShaderInfo", self.shaderInfoDecode)]
            for placeholder, decoder in decoders:
                if placeholder in obj:
                    return decoder(obj[placeholder])
                else:
                    for k in obj:
                        obj[k] = self.recursiveDecode(obj[k])
        elif isinstance(obj, list):
            for x in range(len(obj)):
                obj[x] = self.recursiveDecode(obj[x])

        return obj

    def setDecode(self, v):
        return set(v)

    def nodeInfoDecode(self, v):
        o = NodeInfo()
        o.update(self.recursiveDecode(v))
        return o

    def shapeInfoDecode(self, v):
        o = ShapeInfo()
        o.update(self.recursiveDecode(v))
        return o

    def shaderInfoDecode(self, v):
        o = ShaderInfo()
        o.update(self.recursiveDecode(v))
        return o

rawDescription: Overriding nested JSON encoding of inherited default supported objects like dict, list


rawDescription: how to retrieve field value (values are itself string)in given line using regular expression in python

description: Retrieve field value (values are itself string)in given line using regular expression in python


code:
tree.add_node(1, label=2)
tree.add_node(2, label=3)
tree.add_node(3, label=1)
tree.add_node(4, label=7)
tree.add_node(5, label=3)
tree.add_node(6, label=9)
tree.add_node(7, label=2)

rawDescription: How to create duplicate nodes in PyGraphviz?

description: Create duplicate nodes in PyGraphviz


code:
class CommentForm(Form):
    language = SelectField(u'What You Want', choices=CAN_BE_FILLED_LATER_ON)
    code     = TextAreaField()

rawDescription: Flask WTF-forms adding select and textarea


rawDescription: Python, yaml nested objects

description: Python, yaml nested objects


code:
from django.forms.models import modelformset_factory
from my_project.my_app.models import Beverage, Inventory

def update_inventory(request, location_id):

    InventoryFormSet = modelformset_factory(Beverage, form=InventoryForm)
    qs = Beverage.objects.filter(location=location_id)
    formset = InventoryFormSet(queryset=qs)
    if request.method == 'POST':
        formset = InventoryFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                beverage = form.save(commit=False)
                units_reported = form.cleaned_data['units_reported']
                Inventory(beverage=beverage, units_reported=units_reported).save()
    ...

rawDescription: Django: creating dynamic forms

description: Django: creating dynamic forms


code: most_related_tags[9] = (str(i['tag']), str(ij['tag']), correlation)

rawDescription: Store ten most related items in structured array Python


code:
#!usr/bin/env python

import wx
import threading
import Queue
import random
import time

TextEventType = wx.NewEventType()
EVT_THREAD_TEXT_EVENT = wx.PyEventBinder(TextEventType, 1)

global_queue = Queue.Queue()

def threadStart(numthrds, queue, window):
    for i in range(numthrds):
        i = TextThread(queue, window)

class TextThread(threading.Thread):
    def __init__(self, queue, output_window):
        threading.Thread.__init__(self)
        self.inqueue = queue
        self.output_window = output_window
        self.start()

    def run(self):
        word = self.inqueue.get()
        self.setName(word.upper())
        wait = random.randrange(1, 10)
        time.sleep(wait)
        msg = 'Thread: ' + self.getName() + '--wait= ' + str(wait) + ' ' + word
        evt = NewTextEvent(TextEventType, -1)
        evt.setText(msg)
        wx.PostEvent(self.output_window, evt) #post EVT_THREAD_TEXT_EVENT
        #self.inqueue.task_done() #may not need this if non-blocking

class NewTextEvent(wx.PyCommandEvent):
    def __init__(self, evtType, id):
        wx.PyCommandEvent.__init__(self, evtType, id)

        self.msg = ''

    def setText(self, text):
        self.msg = text

    def getText(self):
        return self.msg

class TextFrame(wx.Frame):
    def __init__(self, parent, id, *args, **kwargs):
        wx.Frame.__init__(self, parent, id, *args, **kwargs)
        self.queue = Queue.Queue()
        framesizer = wx.BoxSizer(wx.VERTICAL)
        self.panel = ThreadPanel(self, wx.ID_ANY)
        framesizer.Add(self.panel, 0, wx.EXPAND)
        self.SetSizerAndFit(framesizer)

        self.Bind(EVT_THREAD_TEXT_EVENT, self.OnThreadText)

    def OnThreadText(self, evt):
        msg = evt.getText()
        self.panel.out_tc.AppendText(msg + '\n')

class ThreadPanel(wx.Panel):
    def __init__(self, parent, id, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        vsizer = wx.BoxSizer(wx.VERTICAL)
        self.wordtc = wx.TextCtrl(self, id=wx.ID_ANY, value='', size=(350, -1))
        self.inst_text = wx.StaticText(self, wx.ID_ANY,
            label='Enter a list of space-separated words')
        self.out_tc = wx.TextCtrl(self, id=wx.ID_ANY, size=(350, 300),
            value='', style=wx.TE_MULTILINE)
        self.start_button = wx.Button(self, wx.ID_ANY, label='Start Threads')

        vsizer.Add(self.inst_text, 0, wx.ALIGN_LEFT)
        vsizer.Add(self.wordtc, 0, wx.EXPAND)
        vsizer.Add(self.start_button)
        vsizer.Add((100,100))
        vsizer.Add(self.out_tc, 0, wx.EXPAND)
        self.SetSizer(vsizer)
        self.Bind(wx.EVT_BUTTON, self.OnStartButton, self.start_button)

    def OnStartButton(self, evt):
        self.out_tc.Clear()
        text = self.wordtc.GetValue()
        self.wordtc.Clear()
        if not text.count(','):
            text = text.split(' ')
        num_thrds = len(text)
        for word in text:
            word = word.strip()
            self.GetParent().queue.put(word)
        threadStart(num_thrds, self.GetParent().queue, self.GetParent())

if __name__ == "__main__":
    app = wx.App()
    frame = TextFrame(None, wx.ID_ANY, 'Thread test')
    frame.Show()
    app.MainLoop()

rawDescription: Updating the wx.gauge without while-loop


rawDescription: How to match a date pattern in strings

description: Match a date pattern in strings


code:
df = DataFrame(np.random.randn(12,1),index=pd.MultiIndex.from_product([list(range(3)),list(range(4))],names=['foo','bar']))
df.reset_index()
x = df.reset_index()
df2 = x.set_index(['foo','bar']).sortlevel()
df2

rawDescription: Select rows from a list of tuples in pandas


code:
def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

rawDescription: Function to return the stripped whitespace of a string


code:
with open("info.txt") as inf:
    data = []
    for line in inf:
        line = line.split()
        if len(line)==4:
            data.append(line)

data.sort(key=lambda s:(s[2],s[1]))

rawDescription: Python Sorting a text file by fields

description: Python Sorting a text file by fields


code:
if all(x % element for element in lst):
    ...

rawDescription: Removing Redundancies/Condensing Code

description: Removing Redundancies/Condensing Code


code:
from scipy.stats import norm
import matplotlib.pyplot as plt

cdf = discrete_cdf(your_data)
xvalues = range(0, max(your_data))
yvalues = [cdf(point) for point in xvalues]
plt.plot(xvalues, yvalues)

rawDescription: Python: How to plot a cdf function given an array of numbers


code: results.sort(key=lambda b: (b.item_publication_year, b.item_publication_month))

rawDescription: Sorting the catalog results by multiple fields


code:
class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def __call__(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1

yourfunc = Foo()

rawDescription: Static variable in python?

description: Static variable in python


code:
import matplotlib.pyplot as plt

y = range(20)
x1 = range(20)
x2 = range(0, 200, 10)

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(y, x1, align='center', color='gray')
axes[1].barh(y, x2, align='center', color='gray')
axes[0].invert_xaxis()
plt.show()

rawDescription: Using Python libraries to plot two horizontal bar charts sharing same y axis


code:
from twisted.protocols.policies import LimitConnectionsByPeer
...
factory = ConsoleSMTPFactory()
wrapper = LimitConnectionsByPeer(DenyFactory(ConsoleSMTPFactory(...)))
reactor.listenTCP(465, wrapper)

rawDescription: Logging SMTP connections with Twisted

description: Logging SMTP connections with Twisted


code:
import base64
jinja2_environment.filters['b64encode'] = base64.b64encode

rawDescription: Jinja2: Converting hex to Base64

description: Jinja2: Converting hex to Base64


rawDescription: Python program to create sphere coordinates not working


code:
from pylab import *

# define some grids
xgrid = arange(20, 31)
ygrid = arange(10, 16)

xscan = []
yscan = []

for i, yi in enumerate(ygrid):
    xscan.append(xgrid[::(-1)**i]) # reverse when i is odd
    yscan.append(ones_like(xgrid) * yi)

# squeeze lists together to vectors
xscan = concatenate(xscan)
yscan = concatenate(yscan)

# quick plot
plot(xscan, yscan, '.-')
axis([19, 31, 9, 16])
show()

rawDescription: Raster scan pattern python

description: Raster scan pattern python


rawDescription: Fill in missing values with nearest neighbour in Python numpy masked arrays?


code:
import pygame, sys, time, os, copy
from pygame.locals import *

def ret_bitmap(fname):
    return pygame.image.load('C:/Python32/PygameImages/' + rstill.bmp)

class character():
    def __init__(self, x=0, y=0, direction='up'):

        self.rstill = [ret_bitmap('rstill.bmp')]
        self.lstill = [ret_bitmap('lstill.bmp')]
        self.bstill = [ret_bitmap('bstill.bmp')]
        self.fstill = [ret_bitmap('fstill.bmp')]

        self.lwalk = [ret_bitmap('lwalk1.bmp'), ret_bitmap('lwalk2.bmp')]
        self.rwalk = [ret_bitmap('rwalk1.bmp'), ret_bitmap('rwalk2.bmp')]
        self.fwalk = [ret_bitmap('fwalk1.bmp'), ret_bitmap('fwalk2.bmp')]
        self.bwalk = [ret_bitmap('bwalk1.bmp'), ret_bitmap('bwalk2.bmp')]

        self.direction = direction
        self.animation_frame = 0
        self.x, self.y = x, y

        ## == Load the first frame to show the user
        ##  Note: We don't load the image, we load the list.
        if self.direction == 'up':
            self.sprite = self.fwalk
        elif self.direction == 'down':
            self.sprite = self.bwalk
        elif self.direction == 'left':
            self.sprite = self.lwalk
        else:
            self.sprite = self.rwalk

    def move(self, direction):
        self.direction = direction

        if direction == 'left':
            self.x -= 1
            self.sprite = self.lwalk
        elif direction == 'right':
            self.x += 1
            self.sprite = self.rwalk
        elif direction == 'up':
            self.y += 1
            self.sprite = self.fwalk
        else: # Down
            self.y -= 1
            self.sprite = self.bwalk

    def update(self, direction):
        if clock.tick() > 9:
            self.animation_frame += 1

            if self.animation_frame > len(self.sprite):
                self.animation_frame = 0

    def get_image(self):
        return self.sprite[self.animation_frame]

pygame.init()
screen = pygame.display.set_mode((492,360))
clock = pygame.time.Clock()

Character = character(x=240, y=300, direction='down')
background = ret_bitmap('forest.png')

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

    if event.type == KEYDOWN:
        if (event.key == K_LEFT):
            Character.move('left')

        elif (event.key == K_RIGHT):
            Character.move('right')

        elif (event.key == K_UP):
            Character.move('up')

        elif (event.key == K_DOWN):
            Character.move('down')

    Character.update() # Just updates the animation frame, if the time is right

    screen.blit(background, (0,0))
    screen.blit(Character.get_image(), (Character.x, Character.y))

    pygame.display.update()

rawDescription: I can't get my class to work in pygame

description: I can't get my class to work in pygame


code:
import mock
import unittest

from lib.event import Event
from example import Monolith

class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        # Setup
        m = Monolith()

        # Exercise
        m.foo('raw_event')

        # Verify
        event_mocked.assert_called_with('metadata_example', 'action_example')

rawDescription: Python unit test mock, get mocked function's input arguments


rawDescription: How can I get a full list of class members without instantiating a class?

description: Get a full list of class members without instantiating a class


code:
def __init__(self,new):
    if type(new) is BSTNode:
        self._data = new.data
        self._left = new.left
        self._right = new.right
    else:
        self._data = new
        self._left = None
        self._right = None

rawDescription: Confusion with recursion and property setters in Python


rawDescription: Function awfully slow

description: Function awfully slow


code:
import __future__
__future__.print_function
__future__.print_function.optional
__future__.print_function.mandatory
__future__.print_function.compiler_flag

rawDescription: Getting parameter names for __future__ functions in python


code:
#if need column LongTime
DF_Qmin = DF_Qmin.reset_index()

print (DF_Qmin.groupby(DF_Qmin.LongTime.dt.date).last())

rawDescription: Last 10 minutes per day

description: Last 10 minutes per day


code:
class SplitableList(list):
    def split(self,sep): return separate(self,sep)

a = SplitableList([1,3,4,6,8,5,3,4,5,8,4,3])
b = a.split([3,4]) # returns desired result

rawDescription: Python use split with arrays

description: Python use split with arrays


code:
list_1 = ["a1", "a2", "a3"]
list_2 = ["b1", "b2", "b3"]
from itertools import product, starmap
list(starmap(lambda x, y: x + " " + y, product(list_1, list_2)))

rawDescription: Problems computing the score of a pairwise list in an iterative way?


code:
directions = {"UP":partial(move, op_func=operator.add, z="x"),
              "DOWN":partial(move, op_func=operator.sub, z="x"),
              "RIGHT":partial(move, op_func=operator.add, z="y"),
              "LEFT":partial(move, op_func=operator.sub, z="y")}

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


code:
import sys, io
sys.version
io.open is open

rawDescription: How do I find out if one Python function is an alias for another one?

description: Find out if one Python function is an alias for another one


code:
from wand.image import Image

class MyStatisticsImage(Image):
    def my_statistics(self):
        """Calculate & return tuple of stddev, mean, max, & min."""
        s = library.MagickGetImageChannelStatistics(self.wand)
        # See enum ChannelType in magick-type.h
        CompositeChannels = 0x002F
        return (s[CompositeChannels].standard_deviation,
                s[CompositeChannels].mean,
                s[CompositeChannels].maxima,
                s[CompositeChannels].minima)

rawDescription: Python-wand: How can I read image properties/statistics


code: {'month_average': 40}

rawDescription: Django/python date aggregation by month and quarter


code:
output = []
for line in input:
    values = line.strip().split('=', 1)[1]
    data = values.split(',')
    output.append(dict(name=data[0], addr=data[1], phone=data[2]))

rawDescription: How do I convert strings separated by comma into dictionary in python?

description: Convert strings separated by comma into dictionary in python


code:
class Program(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id="org.example.Foo",
                                 flags=Gio.ApplicationFlags.FLAGS_NONE)

prg = Program()
sys.exit(prg.run(sys.argv));

rawDescription: Python GTK3 inheritance

description: Python GTK3 inheritance


code:
@register.filter(is_safe=True)
@stringfilter
def lowerfirst_if_starts_with_v(value):
    """Lowercase the first character of the value."""
    return value and value[0] =='v' and value[0].lower() + value[1:]

rawDescription: Django always capitalizes a model's verbose name in admin index page


rawDescription: Python 3.2.1: Can't Index Shape, Need to Access a Particular Rectangle Later


code:
roll_n_dices = lambda n: random.getrandbits(n)
r = roll_n_dices(4)
binstr = bin(r)[2:].zfill(4)
sorted_binstr = "1"*binstr.count("1") + "0"*binstr.count("0")
hex_value = hex(int(sorted_binstr, 2))

rawDescription: begginer Python -Trouble with concatenating an array of 4 binary ints

description: Begginer Python -Trouble with concatenating an array of 4 binary ints


code:
import itertools

data=[]
with open('data.txt','r') as f:
    for key,group in itertools.groupby(f,lambda line: line.startswith('#meta')):
        if key:
            meta=next(group).strip()
        else:
            lines=''.join(group).strip()
            data.append((meta,lines))
print(data)

rawDescription: How to read a file with variable multi-row data in Python

description: Read a file with variable multi-row data in Python


code:
my_table_no_headers = zip(*my_table_no_headers)
first_trip_id= my_table_no_headers[trip_id][0]
all_trip_ids= my_table_no_headers[trip_id] #note this is not a copy!

rawDescription: How can I store a 2D array in python, like table in MySQL?

description: Store a 2D array in python, like table in MySQL


code:
import string
message = 'mw'
key = 'f'
enc_table = string.maketrans(
    string.ascii_lowercase,
    ''.join(shift(c, key) for c in string.ascii_lowercase)
)
message.translate(enc_table) # -> 'rb'

rawDescription: How to make shift('w','f') return 'b'?

description: Make shift('w','f') return 'b'


code: df2 = df2.ffill().bfill(0)

rawDescription: restrict filling in missing data for panda to a single index on multi-indexed DataFrame

description: Restrict filling in missing data for panda to a single index on multi-indexed DataFrame


code:
url = 'https://secure.ssa.gov/apps10/reference.nsf/instructiontypecode!openview&restricttocategory=POMT'
response = urllib.urlopen(url)
content = response.readlines()  # get response as list of lines
import difflib
d = difflib.Differ()

diffed = d.compare(content, content)
print('\n'.join(diffed))

rawDescription: Comparing HTML with difflib

description: Comparing HTML with difflib


code:
def unique_func(sentence, number):
    sentence = sentence.translate(None, punctuation).lower()
    return len([w for w in set(sentence.split()) if len(w) >= number])

rawDescription: Counting unique words of a minimum length in a string


code:
for root, dirs, files in os.walk('mydir'):
  for filename in files:
    z.write(os.path.join(root, filename))

rawDescription: How to add the contents of a directory to a zip file?

description: Add the contents of a directory to a zip file


rawDescription: Numpy extract arbitrary subarray along one axis


code:
if test in ['a', 'b', 'c', 'd']: #list slower than tuple -- ('a', 'b', 'c', 'd')
   do_something()

rawDescription: Is it possible to check if a value is equal to another in python quickly when referring it to a list?


code:
from bs4 import BeautifulSoup
page = """useless
          some text
          useless"""
soup = BeautifulSoup(page)
soup.find_all(lambda e: e.name == 'span' and e.attrs.get('id') == '')
soup.select('span[id=""]')

rawDescription: Get content of tags with empty id in BeautifulSoup


rawDescription: How to find the most recent row for each item in a Django managed database?

description: Find the most recent row for each item in a Django managed database


rawDescription: Regular expression in python to capture first operator


rawDescription: Elasticsearch : es.index() changes the Mapping when message is pushed


code:
with open('path/to/input') as infile:
  words = []
  for line in infile:
    words.append(line.strip()[::-1])

with open('path/to/output', 'w') as outfile:
  for word in words[::-1]:
    outfile.write(word)
    outfile.write('\n')

rawDescription: Is it possible to reverse the order of items in a list without using the built-in .reverse() function?


code:
import atexit

csvfile = None
def generateCSVfile(fileName,fileDescription,fileLocation,md5Hash):
    global csvfile
    if csvfile is None:
        # Lazily open file on first call
        csvfile = open('deploymentTemplate.csv', 'w')
        atexit.atexit(csvfile.close)  # Close cleanly on program exit

    try:
        csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL, newline='')
        # do whatever writing you need to csvwriter
    finally:
        csvfile.flush()  # Match behavior of repeated with/open, force predictable flush

rawDescription: open a CSV file once and write several lines to it from a loop python

description: Open a CSV file once and write several lines to it from a loop python


code:
d = {}
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    next(reader)
    for name, val in reader:
        d.setdefault(name, 0)
        d[name] += float(val.lstrip("-"))

rawDescription: CSV in hashtable then calculate sum

description: CSV in hashtable then calculate sum


rawDescription: Path not found when executing my python script from my cmd prompt


code:
if __name__ == '__main__':
    import time
    print('Type Ctrl+C to exit')
    try:
        while True:
            info = wait_for_print_job_info(timeout=0.25)
            if not info:
                continue
            for nd in info:
                job_id, key, value = nd
                if key == 'job_status':
                    status_string = job_status_string(value)
                    value = '%#010x (%s)' % (value, status_string)
                print('[%08x] %s: %s' % (job_id, key, value))
                time.sleep(.05)
            print('')
            time.sleep(.05)
    except KeyboardInterrupt:
        pass

rawDescription: How to catch printer event in python

description: Catch printer event in python


code:
import subprocess
import unittest

class BashTestCase(unittest.TestCase):
    def test_complete(self):
        completion_file="asdf-completion"
        partial_word="f"
        cmd=["asdf", "other", "arguments", partial_word]
        cmdline = ' '.join(cmd)

        out = subprocess.Popen(['bash', '-i', '-c',
            r'source {compfile}; COMP_LINE="{cmdline}" COMP_WORDS=({cmdline}) COMP_CWORD={cword} COMP_POINT={cmdlen} $(complete -p {cmd} | sed "s/.*-F \\([^ ]*\\) .*/\\1/") && echo ${{COMPREPLY[*]}}'.format(
                compfile=completion_file, cmdline=cmdline, cmdlen=len(cmdline), cmd=cmd[0], cword=cmd.index(partial_word)
                )],
            stdout=subprocess.PIPE)
        stdout, stderr = out.communicate()
        self.assertEqual(stdout, "four five\n")

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

rawDescription: Unit Test for Bash completion script

description: Unit Test for Bash completion script


code:
text = file.read()
updated_text = add_score('UserName', 32, text)

rawDescription: Deleting and inserting a score into a text file form python


code: unidecode(u'影師嗎')

rawDescription: How to make Django slugify work properly with Unicode strings?

description: Make Django slugify work properly with Unicode strings


rawDescription: Computing where the overlap is

description: Computing where the overlap is


code:
import csv

with open('/tmp/so.csv', 'w') as f:
    writer=csv.writer(f)
    writer.writerow(['accessories']+w.keys())
    for item in accessories:
        li=[item]
        for nam in w:
            li.append(w[nam].get(item, 0))
        writer.writerow(li)

rawDescription: Parsing Dictionary Into Spreadsheet in Python


code:
columns = df.columns
for i, bounds in enumerate(zip(upper_bounds, lower_bounds)):
    upper, lower = bounds
    column = columns[i]
    df = df.ix[(df[column] > lower) & (df[column] < upper)]

rawDescription: Apply upper and lower bounds to Pandas Dataframe


code:
if "whatever" in request.POST:
    my_data = request.POST.get("whatever")

rawDescription: AJAX Call to python function not happening from JavaScript function in Django


code: pos_tag([word for word in word_tokenize(sent)])

rawDescription: Confused about priority between stemmer and pos tagger


code:
mylist = [1, 2, 3]
any(x > 4 for x in mylist)
any(x % 2 == 0 for x in mylist)

rawDescription: Branch on boolean statement applied to each element of an iterable


rawDescription: Return minimum X (that can contain Y items) for arbitrary number of items


code: data = [map(convert, entry) for entry in data]

rawDescription: Change only one element in list to float or other transformation


code:
def per_section(iterable):
    row = []
    for line in iterable:
        if line.startswith('-'):
            if row:
                yield row
            row = line[1:].split() + ['']
        else:
            row[-1] += line.strip()
    if row:
        yield row

rawDescription: creating list from separated lines

description: Creating list from separated lines


code:
n = 3
it = iter(my_list)
rn = map(str, range(1, n+1))
for sli in zip(it, it, it):
    print(" ".join(["{}: {}".format(a,b) for a,b in zip(rn, sli)]))

rawDescription: How to retrieve groups of n items in list

description: Retrieve groups of n items in list


rawDescription: Modify values in a nested dictionary based on their keys


code:
import datetime

year_dropdown = []
for y in range(2011, (datetime.datetime.now().year + 5)):
    year_dropdown.append((y, y))

rawDescription: Creating year dropdown in Django template


code: imshow(array, interpolation="nearest")

rawDescription: Prevent anti-aliasing for imshow in matplotlib


code: [row['value'] for row in table.where('key == search_key')]

rawDescription: How should python dictionaries be stored in pytables?


code:
for x in range(width):
    for y in range(height):
        px = pixels[x][y]
        if px[0] == 255 and px[1] == 255 and px[2] == 255:
            for i,j in targets(x,y):
                newpixels[i][j] = replacementColor

rawDescription: PIL Best Way To Replace Color?

description: PIL Best Way To Replace Color


code:
callable(f.module)
callable(f.function)

rawDescription: Multiple dot syntax in python and matplotlib


code:
dictionary = {
  'key1': {'a': 1, 'b': 2, 'c': 10},
  'key2': {'d': 1, 'e': 1, 'c': 11},
  'key3': {'d': 2, 'b': 1, 'g': 12}}
list1 = ('a', 'b', 'c')
for value in list1:
     print(value, max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf'))))

rawDescription: Find Maximum Value in Nested Dictionary and return Key


code:
class YourRequestHandler(BlobstoreUploadHandler, RequestHandler):
    pass

rawDescription: GAE: how can I combine a BlobstoreUploadHandler and a RequestHandler in 1 webpage


code:
P2 = alt(Kx, Ky, u, v, pk)
P1 = orig(Kx, Ky, u, v, pk)
np.allclose(P1, P2)

rawDescription: Numpy multiplication of vectors of different size avoiding for loops


code:
directory_path = os.path.dirname(os.path.abspath(__file__))
print(directory_path)

rawDescription: Editing Paths in Python

description: Editing Paths in Python


code:
def export_f1(modeladmin, request, queryset):
    for obj in queryset.iterator():
         pass

rawDescription: django queryset iterator not returning records in action

description: Django queryset iterator not returning records in action


code:
class ChocolateCake(object):
    pass

rawDescription: Using Python's isinstance

description: Using Python's isinstance


code:
...
import re
my_regex = r"(?mis){0}".format(re.escape(last_name))
...

rawDescription: how to find a particular string in an element of array in python

description: Find a particular string in an element of array in python


code:
AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
found_sand = random.choice(AllSands)
AllSands.remove(found_sand)

rawDescription: Take a string out of a tuple - python

description: Take a string out of a tuple - python


rawDescription: Python array manipulation

description: Python array manipulation


code:
"""Register tkinter classes with threadbox for immediate usage.

This module clones several classes from the tkinter library for use with
threads. Instances from these new classes should run on whatever thread
the root was created on. Child classes inherit the parent's safety."""

__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '4 June 2012'
__version__ = 1, 0, 0

################################################################################

import time
import tkinter.filedialog
import tkinter.font
import tkinter.messagebox
import tkinter.scrolledtext
import tkinter.ttk
import threadbox

################################################################################

tkinter.NoDefaultRoot()

@threadbox.MetaBox.thread
def mainloop(self):
    "Creates a synthetic main loop so that threads can still run."
    while True:
        try:
            self.update()
        except tkinter.TclError:
            break
        else:
            time.sleep(tkinter._tkinter.getbusywaitinterval() / 1000)

threadbox.MetaBox.clone(tkinter.Misc, {'mainloop': mainloop})

################################################################################

OldButton = threadbox.MetaBox.clone(tkinter.Button)
Canvas = threadbox.MetaBox.clone(tkinter.Canvas)
OldFrame = threadbox.MetaBox.clone(tkinter.Frame)
Menu = threadbox.MetaBox.clone(tkinter.Menu)
PhotoImage = threadbox.MetaBox.clone(tkinter.PhotoImage)
Spinbox = threadbox.MetaBox.clone(tkinter.Spinbox)
StringVar = threadbox.MetaBox.clone(tkinter.StringVar)
Text = threadbox.MetaBox.clone(tkinter.Text)
Tk = threadbox.MetaBox.clone(tkinter.Tk)
Toplevel = threadbox.MetaBox.clone(tkinter.Toplevel)

################################################################################

Button = threadbox.MetaBox.clone(tkinter.ttk.Button)
Checkbutton = threadbox.MetaBox.clone(tkinter.ttk.Checkbutton)
Entry = threadbox.MetaBox.clone(tkinter.ttk.Entry)
Frame = threadbox.MetaBox.clone(tkinter.ttk.Frame)
Label = threadbox.MetaBox.clone(tkinter.ttk.Label)
Labelframe = threadbox.MetaBox.clone(tkinter.ttk.Labelframe)
Progressbar = threadbox.MetaBox.clone(tkinter.ttk.Progressbar)
Radiobutton = threadbox.MetaBox.clone(tkinter.ttk.Radiobutton)
Scale = threadbox.MetaBox.clone(tkinter.ttk.Scale)
Scrollbar = threadbox.MetaBox.clone(tkinter.ttk.Scrollbar)
Sizegrip = threadbox.MetaBox.clone(tkinter.ttk.Sizegrip)
Treeview = threadbox.MetaBox.clone(tkinter.ttk.Treeview)

################################################################################

Directory = threadbox.MetaBox.clone(tkinter.filedialog.Directory)
Font = threadbox.MetaBox.clone(tkinter.font.Font)
Message = threadbox.MetaBox.clone(tkinter.messagebox.Message)
ScrolledText = threadbox.MetaBox.clone(tkinter.scrolledtext.ScrolledText)

rawDescription: Send/sync variable/text over LAN in Python 3


code:
_client = None

def get_client():
    global _client
    if _client is None:
        _client = MyXmpp()
    return _client

@celery.task
def send_jabber(message):
    get_client().send_admin_xmpp(message)

rawDescription: celery task and xmpp

description: Celery task and xmpp


code:
string = """Hello this is JURASSIC WORLD shut up Ok
[REVIEW] The movie BATMAN is awesome lol"""
re.findall(r'\b(?<!\[)[A-Z ]{2,}(?!\])\b', string)

rawDescription: Regex uppercase words with condition

description: Regex uppercase words with condition


code:
# Display Menu Bar
root.config(menu = menu_Bar)

rawDescription: Python quit unexpectedly

description: Python quit unexpectedly


code:
import xml.etree.ElementTree as ET

tree = ET.parse('data')
for node in tree.getiterator():
    if int(node.attrib.get('age', 0)) > 21:
        node.attrib['alcohol'] = 'yes'
root = tree.getroot()
ET.register_namespace("", "XYZ")
print(ET.tostring(root))

rawDescription: updating XML attribute value in python

description: Updating XML attribute value in python


code: self.dbobject = getattr(ret,'all')()

rawDescription: Python, Django, how to use getattr (or other method) to call object that has multiple attributes?


code:
from datetime import timedelta
def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}'.format(hours, minutes)

custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))

rawDescription: Too many decimal places when using timedelta


code:
logger.infoc = lambda msg: logger.info('\033[0;41;97m' + msg + '\033[0m')
logger.infoc('Colored message')

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


code:
d = {k: [] for k in range(10)}
d[3].append(100)
d

rawDescription: Creating a dict of blank lists that are not the same list


code: lambda v: tryconvert(v, 0, int)

rawDescription: Python Try Catch Block inside lambda

description: Python Try Catch Block inside lambda


code:
A = list(range(10))
inds = 3, 6
A[slice(*inds)]

rawDescription: python list / numpy array indexing using tuple unpacking possible?

description: Python list / numpy array indexing using tuple unpacking possible


code:
import random

some_list=["-","-","-","-","-","-","-"]

n=2
for i in range(n):
    some_list[random.randrange(0,len(some_list))]="*"

rawDescription: How to randomly replace a string in a list

description: Randomly replace a string in a list


rawDescription: Regex Group Matching

description: Regex Group Matching


code: file = open("newfile.txt", "r")

rawDescription: web scrape a .txt file using python

description: Web scrape a .txt file using python


code:
def get_context_data(self, **kwargs):
    context = super(SignUpView, self).get_context_data(**kwargs)
    something = something
    context['something'] = something
    return context

rawDescription: Django: How to provide context for a FormView?


code:
class Employees:
  _iter_attr__prio = ["name"]
  def gatherAttrs(self):
    attrs = []
    for key in self._iter_attr__prio + [key for key in self.__dict__ if key not in self._iter_attr__prio]:
        attrs.append('%s = %s' % (key, getattr(self,key)))
    return ', '.join(attrs)

rawDescription: Print out dictionary by (specific) key

description: Print out dictionary by (specific) key


code: new_sample = [x if not x.isdigit() else str((int(x) + 1) % 10) for x in samples]

rawDescription: Python: add 1 to each digit that is an integer


code:
kernel32.OpenProcess(0x1000, 0, 4704)
path = (c_wchar * 260)()
size = c_uint(260)
kernel32.QueryFullProcessImageNameW(304, 0, path, byref(size))
path.value

rawDescription: Find the path of every running process in Python


code:
import Tkinter as tk

def make_bold():
    aText.tag_add("bt", "sel.first", "sel.last")

lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()

aText.tag_config("bt", font=("Georgia", "12", "bold"))

lord.mainloop()

rawDescription: Set to bold the selected text using tags


code:
myList =[1,2,3,4,5,6,7,8,9,10]
for index, value in enumerate(myList, start=1):
    globals()['numb'+str(index)] = value

numb1
numb2
numb3
numb10

rawDescription: Save Numbered Variable

description: Save Numbered Variable


code:
elems = root.findall('.//*') # returns a list
for e in elems:
    print(e.tag)

rawDescription: Python - What does my XML contain?

description: Python - What does my XML contain


code:
import xml.etree.ElementTree as ET
from StringIO import StringIO as sio
raw_text = '<root>can\x92t</root>' # text encoded in cp1252, no XML declaration
t = ET.parse(sio(raw_text))
t = ET.parse(sio('<?xml version="1.0" encoding="UTF-8"?>' + raw_text))
t = ET.parse(sio('<?xml version="1.0" encoding="cp1252"?>' + raw_text))
t.getroot().text
import unicodedata
unicodedata.name(u'\u2019')
fixed_text = raw_text.decode('cp1252').encode('utf8')
t = ET.parse(sio(fixed_text))
t.getroot().text

rawDescription: Alternative XML parser for ElementTree to ease UTF-8 woes?


rawDescription: Creating classes in dictionaries - values being duplicated between classes?


code:
c1 = df.groupby(df['Country'], as_index=True, sort=False, group_keys=True).size()

c2 = c1.set_index(['Country'])

rawDescription: Python Pandas, setting groupby() group labels as index in a new dataframe


code:
from numpy import linspace, meshgrid

def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    xi = linspace(min(x), max(x), resX)
    yi = linspace(min(y), max(y), resY)
    Z = griddata(x, y, z, xi, yi)
    X, Y = meshgrid(xi, yi)
    return X, Y, Z

rawDescription: analogy to scipy.interpolate.griddata?

description: Analogy to scipy.interpolate.griddata


code:
from decimal import Decimal
Decimal(0x9481ef80) / Decimal(2**32) + Decimal(0x4ca1f350)

rawDescription: Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)


code:
def singleton(cls):

    def getinstance():
        if cls not in singleton.instances:
            singleton.instances[cls] = cls()
        return singleton.instances[cls]
    return getinstance

singleton.instances = {}

# Then clear
def tearDown(self):
    singleton.instances = {}

rawDescription: How to delete (tearDown) a singleton instance decorator in Python for unit testing?

description: Delete (tearDown) a singleton instance decorator in Python for unit testing


code:
from itertools import combinations
from numpy import zeros

n = g.vcount()
common_neis = zeros(n, n)
for v in xrange(g.vcount()):
    neis = g.neighbors(v)
    for u, w in combinations(neis, 2):
        # v is a common neighbor of u and w
        common_neis[u, w] += 1
        common_neis[w, u] += 1

rawDescription: Common neighbors and preferential attachment score matrixes using igraph for python


code:
import pandas as pd #import the pandas library
#creating a small dataset for testing
df1 = pd.DataFrame({'PassengerId' :  [1, 2, 3],
        'Name' : ['Abbing, Mr. Anthony', 'Ann, C', 'John, H'],
        'Fare' : [7.25, 71.28, 7.92]})
#extract only the numeric column types
df2 = df1._get_numeric_data()
print(df2)

rawDescription: how to exclude the non numerical integers from a data frame in Python

description: Exclude the non numerical integers from a data frame in Python


code: pylab.plot(temperatures, color='green')

rawDescription: Pylab plot shows no plot points

description: Pylab plot shows no plot points


rawDescription: Python: linking/binding variables together in a dictionary


code:
class Post(models.Model):
    icons = models.ManyToManyField(Icon, through=PostIcon)

rawDescription: Way to allow for duplicate many-to-many entries in Python/Django


rawDescription: Named Entity Recognition (regex for places)


code:
from sys import stdout
from time import sleep

def print_same_line():
    for i in range(10):
        stdout.write("\rCounter: {0}.".format(i))
        sleep(1)
    stdout.write("\n")

print_same_line()

rawDescription: Python - how to get text to appear on same line when iterating?


code:
import numpy as np
from multiprocessing import Pool

def I(v):
    return v

if __name__ == "__main__":  # this boilerplate is required on on Windows
    x = np.random.random(100)
    y = np.random.random(100)

    pool = Pool()
    y[:] = pool.map(I, x)

    print(x == y) # [True, True, True, ...]

rawDescription: Assignment in map method of multiprocessing module (Python)


code:
leftSize = self.left.size() if self.left else 0
rightSize = self.right.size() if self.right else 0
return leftSize + 1 + rightSize

rawDescription: Binary Tree Size function in Python

description: Binary Tree Size function in Python


rawDescription: Array building in Python

description: Array building in Python


code:
class new_string(str):
    def reverse(self):
        blah

s = new_string('hello')
s.reverse()

rawDescription: Python: How to add a custom function to a pre-existing object?


code: wand_instance[x:width, y:height]

rawDescription: Slice image with Wand

description: Slice image with Wand


code:
suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseClass)
unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Run Django unit tests from custom management command


code:
class Blog(models.Model):
    title = models.CharField(max_length=20)
    url = models.URLField()

class Post(models.Model):

    blog = models.ForeignKey(Blog)

rawDescription: How do I have two fields for a choice?

description: Have two fields for a choice


code: li

rawDescription: best way to make nested lists?

description: Make nested lists


code:
for scores in d.itervalues():
    scores.sort(key=lambda x: x[1], reverse=True)

rawDescription: python: sort a nested dictionary

description: Python: sort a nested dictionary


code:
print((df['dates'] != df['orig']).sum())
172

rawDescription: Quickly parse Python datetime in a non-local timezone, adjusting for daylight savings


rawDescription: How to generate a list of palindrome numbers within a given range?

description: Generate a list of palindrome numbers within a given range


code:
from collections import defaultdict

occurrences = defaultdict(int)
# ...
occurrences[tag_name] += 1

rawDescription: Is there a way in beautiful soup to count the number of tags in a html page


rawDescription: delete the first element in subview of a matrix

description: Delete the first element in subview of a matrix


code: execute(foo, roles='web')

rawDescription: How do I decorate Fabric tasks with @roles when my tasks inherit from the Task class?

description: Decorate Fabric tasks with @roles when my tasks inherit from the Task class


code:
set1, set2 = set(list1), set(list2)
[i for i in list1 if i not in set2]
[i for i in list2 if i not in set1]

rawDescription: Missing and Additional values in 2 list

description: Missing and Additional values in 2 list


code:
class C(object):
    # ...
    def __eq__(self, other):
        return self.value == other.value
    def __ne__(self, other):
        return not self == other  # More general than self.value != other.value

C(12) == C(12)  # __eq__() is called
C(12) != C(12)  # __ne__() is called

rawDescription: Python pickle: pickled objects are not equal to source objects


code:
mylist
slashes

rawDescription: How to make a list of Binary numbers a list of Dotted Decimal Numbers?

description: Make a list of Binary numbers a list of Dotted Decimal Numbers


code:
True
True
False
True
True
True
False
True
True
True
False
True
True
False

rawDescription: Validity of a string based on some conditions


code:
class FormatTimeNode(template.Node):
    def __init__(self, date_to_be_formatted, format_string):
        self.date_to_be_formatted = template.Variable(date_to_be_formatted)
        self.format_string = format_string

    def render(self, context):
        try:
            actual_date = self.date_to_be_formatted.resolve(context)
            return actual_date.strftime(self.format_string)
        except template.VariableDoesNotExist:
            return ''

rawDescription: Inheriting context variables inside custom template tags


code: topic_weights = topic_prob_extractor(hdp, 500)

rawDescription: Hierarchical Dirichlet Process Gensim topic number independent of corpus size


code: 0 == False

rawDescription: Python why does int("0") return false

description: Python why does int("0") return false


rawDescription: Python Time Series

description: Python Time Series


code:
np.where(cond) == np.nonzero(cond) # see doc

xs.nonzero() == (xs.row, xs.col) # for coo format
sparse.find(xs) == (row, col, data)

rawDescription: Scipy equivalent of numpy where for sparse matrices


code:
from StringIO import StringIO
from tokenize import generate_tokens as gt
from pprint import pprint as pp
code = 'x=""""""'
codeio = StringIO(code)
tokens = list(gt(codeio.readline))
pp(tokens)

rawDescription: python, x = """"""; lexed as triple quotes or 3 pairs of quotes

description: Python, x = """"""; lexed as triple quotes or 3 pairs of quotes


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

import shutil
import os

# from this answer: http://stackoverflow.com/q/1033424/3889452
def remove(value):
    deletechars = '®'
    for c in deletechars:
        value = value.replace(c,'')
    return value

for root, folders, files in os.walk(r'C:\Users\myname\da\data\originals\Word_4_0'):
    for f in files:
        rename = remove(f)
        shutil.move(os.path.join(root,f),os.path.join(root,rename))
    for folder in folders:
        rename = remove(folder)
        shutil.move(os.path.join(root,folder),os.path.join(root,rename))

rawDescription: Registered Trademark: Why does strip remove ® but replace can't find it? How do I remove symbols from folder and file names?


code: df = pd.read_csv('matrix.txt',sep=',', header = None, skiprows=1000, chunksize=1000)

rawDescription: pandas read csv file line by line

description: Pandas read csv file line by line


code:
class Parent:

    PATH_PROPERTIES = 'parent'

    def __init__(self, path):
        self.props = { self.PATH_PROPERTIES: path }

    @property
    def path(self):
        return self.props[self.PATH_PROPERTIES]

class Child(Parent):

    PATH_PROPERTIES = 'child'

c = Child('path')
print(c.path)

rawDescription: Python class inheritance: dynamic attribute creation


code:
def process_catalogue(p_text):
    speakers = make_catalogue(c_text)
    s_speakers = sum_words_per_paragraph_items(speakers)
    t_speakers = total_word_count(s_speakers)

rawDescription: Python: How to sum up the word count for each person in a dialogue?


code:
a = np.array([True, True, True, False, False])
b = np.array([1,2,3,4,5])
b[a]

rawDescription: Numpy selecting specific column index per row by using a list of indexes


rawDescription: Nearest neighbor 1 dimensional data with a specified range


code:
window_length = 30 # number of point for the window
variance = np.array([np.var(Y[i-window_length / 2.: i+window_length/2.]) for i in range(200)])

rawDescription: Filter an array based on density

description: Filter an array based on density


code:
result = None
with open("filename", 'r') as fh:
    result = map(json.loads, fh)

rawDescription: python: convert list of strings of json type to list of dictionaries

description: Python: convert list of strings of json type to list of dictionaries


code:
def formulate(name, **data):
   def __init__(self):                 # 1
       for key, val in data.items():
           setattr(self, key, val)     # 2
   struct = type(name, (), {'__slots__': tuple(data.keys()), '__init__': __init__})
   return struct

Bar = formulate('Bar', **dict(a=1, b=2))  # 3
bar = Bar()                               # 4
print('__dict__' in dir(bar))
# False
print('__slots__' in dir(bar))
# True
print(bar.__slots__)
# ['a', 'b']
print(bar.a)
# 1

rawDescription: Formulating a dynamic class in Python

description: Formulating a dynamic class in Python


code:
b_set = set(b)
next(element for element in a if element in b_set)

rawDescription: Finding if any element in a list is in another list and return the first element found


code:
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
c=pdc.Constants()
p=pdt.Calendar(c)
p.parse('Today 3:20 PM')
p.parse('Yesterday 11:06 AM')

rawDescription: What's the best way to make a time from "Today" or "Yesterday" and a time in Python?


code: list(map(lambda x:'.'.join(x[0][:4])+"/"+str(x[1])+" "+x[0][4], list(zip([[str(int(i, 2)) for i in  item.split()] for item in mylist], slashes))))

rawDescription: How to make a list of Binary numbers a list of Dotted Decimal Numbers?


code:
from django.conf.urls import url
from .views import CityDetailView

urlpatterns = [
    url(r'^(?P<state>\w+)/(?P<city>\w+)/$', CityDetailView.as_view()),
]

rawDescription: Clean, name-based urls with class-based views


code:
for inst_A in listA: # this creates a new name called inst_A which points
                     # to a value in listA
    for inst_B in listB:
        if inst_A.id == inst_B.id:
            # this assignment changes the inst_A name to now point to inst_B
            inst_A = inst_B

    # At the bottom of the loop, inst_A is recycled, so the value it was
    # assigned to (inst_B) is forgotten

rawDescription: Python: Updating Class Instances in one List-Variable based on same Class Instances from Another List-Variable


code:
table = list()
for t in temperatures:
     row = list()
     row.append(t)
     for v in windspeeds:
          row.append(windspeed(t, v))
     table.append(row)

print (4*" "+" ".join("%3d" % _ for _ in windspeeds))
print("\n".join(" ".join("%3d" % col for col in row) for row in table))

rawDescription: Was asked to make a simple Windchill index table


code:
import matplotlib as mpl
mpl.rcParams['font.size'] = 9.0

rawDescription: How to set the labels size on a pie chart in python

description: Set the labels size on a pie chart in python


code:
from string import Template
t = Template("This is an $example with $vars")
t.substitute({ 'example': "example", 'vars': "variables"})

rawDescription: Python multiline string - $ for variables


code:
from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast

macros = Macros()

@macros.decorator
@macros.block
@macros.expr
def fpipe(tree, **kw):

    @Walker
    def pipe_search(tree, stop, **kw):
        """Search code for bitwise or operators and transform `a | b` to `b(a)`."""
        if isinstance(tree, BinOp) and isinstance(tree.op, BitOr):
            operand = tree.left
            function = tree.right
            newtree = q[ast[function](ast[operand])]
            return newtree

    return pipe_search.recurse(tree)

rawDescription: functional pipes in python like %>% from dplyr

description: Functional pipes in python like %>% from dplyr


code:
# search for parts you need in column 3
for subitem in re.findall("(.*?) \((.*?)\)", item[2]):
    temp_split = [subitem[0]]
    temp_split.extend(subitem[1].split("/"))

rawDescription: python split list column into multiple columns in original list

description: Python split list column into multiple columns in original list


code:
import time
import sys

def type(str):
    for letter in str:
        print(letter, end='')
        sys.stdout.flush()
        time.sleep(0.02)
    print("\n")

type("This sentence is typed.")

rawDescription: Python: Printing letters one by one in Command Prompt


code:
client = ctypes.cdll.LoadLibrary(os.path.join(myDir, 'rpmclient.dll'))
client.printer_setup.argtypes = [ctypes.c_void_p,
                                 ctypes.c_wchar_p,
                                 ctypes.c_char_p,
                                 ctypes.c_int32,
                                 ctypes.POINTER(ctypes.c_wchar_p),
                                 ctypes.POINTER(ctypes.c_char_p)]

client.printer_setup.restype = ctypes.c_int32
client.CleanupA.argtypes = [ctypes.c_char_p]
client.CleanupA.restype = ctypes.c_int32
client.CleanupW.argtypes = [ctypes.c_wchar_p]
client.CleanupW.restype = ctypes.c_int32

p_in = ctypes.c_wchar_p(self.itemMap['device'].GetValue())
p_out = ctypes.c_wchar_p()

d_in = ctypes.c_char_p(getattr(self, 'devmode', ''))
d_out = ctypes.c_char_p()

res = client.printer_setup(self.GetHandle(),
                           p_in,
                           d_in,
                           False,
                           p_out,
                           d_out)

if res == 0:
  return

if res > 1:
  # Error display code here.

  return

self.devmode = d_out.value

rawDescription: Saving / Restoring Printer DevModes - wxPython / win32print


code:
import itertools

def numeric_prefix(s):
    n = ''.join(itertools.takewhile(lambda c: c.isdigit(), s))
    return int(n) if n else 0

rawDescription: removing non-numeric characters from a string

description: Removing non-numeric characters from a string


code: iiii

rawDescription: Deleting consonants from a string in Python


code:
class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

rawDescription: How to define two fields "unique" as couple

description: Define two fields "unique" as couple


code: [list(set(a)-set(b)) for a, b in zip(list1, list2)]

rawDescription: Python: more readable list comprehension


code:
CDRS = Table('CDRS', metadata, autoload=True)
i = CDRS.insert()

rawDescription: How to implement session.add on this code:

description: Implement session.add on this code:


code:
def dates(data, dates1):
    lines = data.split("\n")
    r = re.compile("\d+/\d+/\d+")
    dict_days = Counter(dt for line in lines
                        for dt in r.findall(line) if dt in dates1)
    return dict_days.most_common(5)

rawDescription: Performance - searching a string in a text file - Python


code: l.sort(key=lambda a: a['time'], reverse=True)

rawDescription: How to sort this list in Python?

description: Sort this list in Python


code: d_all = np.sqrt(np.einsum('ijk->ij',(origs[:,None,:] - dests)**2))

rawDescription: einsum and distance calculations

description: Einsum and distance calculations


code:
import django.dispatch
m2m_post_save = django.dispatch.Signal(providing_args=["instance"])

rawDescription: Django multiple many to many and post_save processing


code:
g = df4.groupby('name', as_index=False)
g.sum()

rawDescription: Pandas Dataframe - Count values based on index position


code:
from nltk.corpus import brown
brown_tagged_sents = brown.tagged_sents()
len(brown_tagged_sents)
brown_tagged_sents[0]
total_len = len(brown_tagged_sents)
train_len = int(90 * total_len/100)
train_set = brown_tagged_sents[:train_len]
train_brown_tagged_words = cfd(chain(*train_set))
train_brown_tagged_words['asbestos']

rawDescription: Create Dictionary from Penn Treebank Corpus sample from NLTK?


code: df['id'] = df['y'].map(func)

rawDescription: pandas: apply a function to each unique element in a dataframe column and merge back the output

description: Pandas: apply a function to each unique element in a dataframe column and merge back the output


code:
def createFormClass(validate):
    class MyClass(object):
        if validate:
            def clean_email(self):
                pass

    return MyClass

MyClassValidated = createFormClass(True)
MyClassNotValidated = createFormClass(False)

rawDescription: Form class __init__ not working

description: Form class __init__ not working


code: stats = df.describe()

rawDescription: Getting Data of a boxplot - Pandas

description: Getting Data of a boxplot - Pandas


code:
from pydub import AudioSegment
from pydub.silence import split_on_silence

sound = AudioSegment.from_mp3("my_file.mp3")
chunks = split_on_silence(sound,
    # must be silent for at least half a second
    min_silence_len=500,

    # consider it silent if quieter than -16 dBFS
    silence_thresh=-16
)

rawDescription: Using pyDub to chop up a long audio file


code:
na = a.shape[0]
nb = b.shape[0]
accum = np.ones((na,nb),dtype=bool)
for i in range(a.shape[1]):
    accum &=  np.abs((a[:,i] - b[:,i].ravel())) < tol[i]
x1,x2 = np.nonzero(accum)

rawDescription: Finding intersection of two matrices in Python within a tolerance?


code:
import timeit
timeit.timeit("deque([x + 'abc' for x in ['x', 'y', 'z']], maxlen=0)",
              'from collections import deque')
timeit.timeit("deque(map(lambda x: x + 'abc', ['x', 'y', 'z']), maxlen=0)",
              'from collections import deque')

rawDescription: Python 2 vs 3: Replace list comprehensions with map()?


code: tree.xpath("//*[%s]" % query)

rawDescription: How to find element on the page by keywords in list using Selenium?

description: Find element on the page by keywords in list using Selenium


code:
import struct, array
foo = b"\x00\xff"
list(bytearray(foo))
struct.unpack('{}B'.format(len(foo)), foo)
array.array('B', foo)

rawDescription: Python 2 and 3 compatible method to convert bytes to integer


code:
c = Client()
c.some.method(x=1, y=2)

rawDescription: Overriding __getattr__ to support dynamic nested attributes


code:
import re
p = re.compile(r'([a-z]) ([(a-z])')
test_str = "abc def (ghi) OR jkl"
subst = r"\1 AND \2"
result = re.sub(p, subst, test_str)
print(result) # => abc AND def AND (ghi) OR jkl

rawDescription: Python re.sub query parsing

description: Python re.sub query parsing


code:
for file in files:
    fname = os.path.join(dir, file)
    inFile = codecs.open(fname, "r", "utf-8")
    outFile = codecs.open(fname + ".new", "w", "utf-8")
    for line in inFile:
        newline = do_replacements_on(line)
        outFile.write(newline)
    inFile.close()
    outFile.close()
    os.rename(fname + ".new", fname)

rawDescription: Optimizing find and replace over large files in Python


rawDescription: Different callback when widget changed by user/programatically


code:
[build_ext]
#define=
#include_dirs=/usr/local/include
#library_dirs=/usr/local/lib
libraries=sqlite3
define=SQLITE_OMIT_LOAD_EXTENSION

rawDescription: Python: The pysqlite library does not support C extension loading