rawDescription: How to display the List diff with out the common lines in python?

description: Display the List diff with out the common lines in python


code:
[row['GRBname'] for row in table.iterrows()
 if args.Scount[0] <= int(row['SCounts']) <= args.Scount[1]]

rawDescription: Issues with using argparse with listcomprehensions


rawDescription: Python - read table with empty fields from file


code:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from reserve.models import UserProfile

class UserProfileInline(admin.TabularInline):
    model = UserProfile

class UserWithProfileAdmin(UserAdmin):
    inlines = [UserProfileInline]

admin.site.unregister(User)
admin.site.register(User, UserWithProfileAdmin)

rawDescription: How can I extend a user profile in django?

description: Extend a user profile in django


code:
df = pd.read_csv('data.csv', index_col='Customer_ID')
df
res = df[list('ABC')].astype(str).sum(1)  # cols = list('ABC')
res

rawDescription: Python - Combining Columns in a CSV file


code: ip_info = [ip.split('/')[0] for ip in ip_info]

rawDescription: Strip Text in all List Items after Character in each list Item Python


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


rawDescription: Unknown response encoding: gathered by urequest.urlopen()


code:
tofilter = ["one.pdf", "two.txt", "three.jpg", "four.png"]
test_strings = ["doc", "pdf", "xls", "jpg"]
filtered = [s for s in tofilter if not any(t in s for t in test_strings)]

rawDescription: Python Logic in searching String

description: Python Logic in searching String


code:
def val():
    if condition:
        return val_if_true
    else:
        return val_if_false

rawDescription: single line if statement - Python

description: Single line if statement - Python


code:
if testmode:
    Popen = DummyPopen
else:
    Popen = subprocess.Popen

rawDescription: extending subprocess.Popen through inheritence

description: Extending subprocess.Popen through inheritence


rawDescription: How to determine the method type of stdlib methods written in C

description: Determine the method type of stdlib methods written in C


code:
class thing:
  def __init__(self, type = ''):
    self.type = type

    self.flight = (self.type in ['bird'])
    self.swim = (self.type in ['fish', 'mammal'])

rawDescription: Assign variables to random elements from list? Python


code: print(" Id State                  Population")

rawDescription: Python3 .format() align usage

description: Python3 .format() align usage


code:
if int(re.search(r'\d+',vsdir).group()) < 2010:
    print("yeh, less tha 2010")
else:
    print("greater than 2010")

rawDescription: convert char to int using regular expression

description: Convert char to int using regular expression


code:
for f in files:
    test = pd.read_csv( f )
    if len( test.columns ) == 4:
        df = df.append( test )

rawDescription: Unit Test with Pandas Dataframe to read *.csv files


code:
df1 = df1.set_index("time")
df2 = df2.set_index("w_time", drop=False)
df1
df2

rawDescription: merging two pandas dataframes on nearest time stamp

description: Merging two pandas dataframes on nearest time stamp


code:
DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/home/JoeButy/mysite/polls/db.sqlite',
    'USER': '',
    'PASSWORD': '',
    'HOST': '',
    'PORT': ''
    }
}

rawDescription: choice_set django tutorial part one

description: Choice_set django tutorial part one


code:
import pprint
pprint.pprint(cases, width=400)

rawDescription: Splitting Lists into even places

description: Splitting Lists into even places


code:
def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

rawDescription: Find a file in python

description: Find a file in python


code:
import module
fname = module.__file__
with open(fname) as fin:
    shebang = next(fin)

rawDescription: Python inspect.getcomments(module) doesn't return the first comment if it's a shebang


code: [float(n.split()[3]) for n in lines if n.startswith("ATOM") and len(n.split())>3]

rawDescription: How to generate an array/list from an output using .split() in Python 2.6

description: Generate an array/list from an output using .split() in Python 2.6


code: os.path.basename('a.b.c').rsplit('.', 1)[0] + ".new"

rawDescription: Python-Which command is better for changing the file extension?


code:
print(astr)
# é
print(combined_astr)
# é

rawDescription: Precompose Unicode Character Sequences in Python


code:
from collections import Counter
c = Counter(y for _, y in item_labels)
item_labels.sort(key=lambda t : c[t[1]])

rawDescription: Python list sort by size of group

description: Python list sort by size of group


code:
import difflib

def possible_countries(c):
    res = difflib.get_close_matches(c, country.keys(), cutoff=0.5)
    return sorted(set(country[r] for r in res))

rawDescription: Compare CSV files and print results using Python


code:
dict1={'a':4,'d':2}
diclist=[{'b':3,'c':3},{'e':1,'f':1}]

for d in diclist:
 for k, v in d.items():
  if k not in dict1 or v < dict1[k]:
   dict1[k] = v

dict1

rawDescription: insert dictionaries to a dictionary in Python

description: Insert dictionaries to a dictionary in Python


code:
dfs = []
for i in range(4):
    dfs.append(...)

rawDescription: How to operate on list of data frame in one instruction

description: Operate on list of data frame in one instruction


rawDescription: Check a phone number with interleaving patterns


code:
EVT_AUINOTEBOOK_PAGE_CLOSE
EVT_AUINOTEBOOK_PAGE_CLOSED
EVT_AUINOTEBOOK_PAGE_CHANGED
EVT_AUINOTEBOOK_PAGE_CHANGING
EVT_AUINOTEBOOK_BUTTON
EVT_AUINOTEBOOK_BEGIN_DRAG
EVT_AUINOTEBOOK_END_DRAG
EVT_AUINOTEBOOK_DRAG_MOTION
EVT_AUINOTEBOOK_ALLOW_DND
EVT_AUINOTEBOOK_DRAG_DONE
EVT_AUINOTEBOOK_BG_DCLICK
EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN
EVT_AUINOTEBOOK_TAB_MIDDLE_UP
EVT_AUINOTEBOOK_TAB_RIGHT_DOWN
EVT_AUINOTEBOOK_TAB_RIGHT_UP

rawDescription: wxpython auinotebook close tab event

description: Wxpython auinotebook close tab event


code: wordsUniqeTags[w] = wordsUniqeTags[w] | set(t)

rawDescription: Is that a tag list or something else?

description: Is that a tag list or something else


code:
from collections import Counter, OrderedDict
from itertools import chain
from csv import writer

check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]

a_list = [('1',), ('2',), ('3',), ('4',)]

with open("out.csv","w") as out:
    wr = writer(out,delimiter=" ")
    cn = OrderedDict(sorted(Counter(a_list).items()))
    wr.writerow(list(chain(*cn)))
    for chk in check_list:
        _cn = Counter(chain(*chk))
        diff = cn.viewkeys() - _cn
        wr.writerow([_cn[k] if k not in diff else 0 for k in cn])

rawDescription: Python 2.7 creating a matrix from lists

description: Python 2.7 creating a matrix from lists


code:
im1 = Image.open('img1.jpg')
im2 = Image.new(im1.mode, im1.size)

rawDescription: Preserving extent from the old image

description: Preserving extent from the old image


rawDescription: How do you set the column width on a QTreeView?

description: Set the column width on a QTreeView


code:
elements=[i[0] for i in a]

avg=sum(elements)/float(len(elements))

rawDescription: Accessing grouped items in arrays

description: Accessing grouped items in arrays


code:
import os, re

ext_list = [".pdf", ".ppt", ".txt"]

def get_filepaths(directory, ext_list):
    folder_paths = []  # List which will store all of the full filepaths.
    job_folders = set([])

    # Walk the tree.

    for dir, subdirs, files in os.walk(directory):
        _, lastlevel = os.path.split(dir)
        if re.search('^[0-9]', lastlevel):
            job_folders.add(lastlevel[:8])

        for item in files:
            root, ext = os.path.splitext(item)
            if ext in ext_list:
                break
        else:
            # Since none of the file extensions matched ext_list, add it to the list of folder_paths
            folder_paths.append(os.path.relpath(dir, directory))

    return folder_paths, job_folders

rawDescription: How to list all directories that do not contain a file type?

description: List all directories that do not contain a file type


code:
from pprint import pprint
dictionary = {'subnet 10.5.5.0 netmask 255.255.255.224': {'option-domain-name': '"internal.example.org"', 'option-domain-name-servers': 'ns1.internal.example.org', 'range': '10.5.5.26 10.5.5.30', 'max-lease-time': '7200', 'default-lease-time': '600', 'option-routers': '10.5.5.1', 'option-broadcast-address': '10.5.5.31'}, 'subnet 10.254.239.32 netmask 255.255.255.224': {'range': 'dynamic-bootp 10.254.239.40 10.254.239.60', 'option-routers': 'rtr-239-32-1.example.org', 'option-broadcast-address': '10.254.239.31'}, 'subnet 10.254.239.0 netmask 255.255.255.224': {'range': '10.254.239.10 10.254.239.20', 'option-routers': 'rtr-239-0-1.example.org, rtr-239-0-2.example.org'}, 'host fantasia': {'hardware': 'ethernet 08:00:07:26:c0:a5', 'fixed-address': 'fantasia.fugue.com'}, 'host passacaglia': {'hardware': 'ethernet 0:0:c0:5d:bd:95', 'server-name': '"toccata.fugue.com"', 'filename': '"vmunix.passacaglia"'}}
for subdict in dictionary.values():
    for key, val in subdict.items():
        if key.startswith('option-'):
            del subdict[key]
            subdict[' '.join(key.split('-', 1))] = val

pprint(dictionary)

rawDescription: Change name of keys in New_dictionary where New_dictionary as value of Main_dictionary


code:
def is_hex(n):
    return n.isdigit() or ("A" <= n.upper() <= "F")

rawDescription: Checking if characters in a file can be integers


code:
import pandas as pd

df_dict = ({'unit' : [1, 1, 1, 2, 2, 2], 'cat' : [1, 2, 3, 1, 2, 4],
           'count' : [8, 3, 2, 2, 8, 7] })
df = pd.DataFrame(df_dict)

df.set_index('unit', inplace = True)

cumsum_count = df.groupby(level=0).apply(lambda x: pd.Series(x['count'].cumsum().values, index=x['cat']))
# unit  cat
# 1     1       8
#       2      11
#       3      13
# 2     1       2
#       2      10
#       4      17
# dtype: int64

cumsum_count = cumsum_count.unstack(level=1).fillna(method='ffill', axis=1)
# cat   1   2   3   4
# unit
# 1     8  11  13  13
# 2     2  10  10  17

totals = df.groupby(level=0)['count'].sum()
# unit
# 1       13
# 2       17
# Name: count, dtype: int64

cumsum_dist = cumsum_count.div(totals, axis=0)
print(cumsum_dist)

rawDescription: Cumulative sum with missing categories in pandas


rawDescription: pandas: function equivalent to SQL's datediff()?

description: Pandas: function equivalent to SQL's datediff()


code: board = [[(0,0)]*lines]*columns

rawDescription: Change values of a list of list (of tuples) in a for statement


code:
from pkg_resources import get_distribution

pkg = get_distribution('package_name')  # also contains a metadata

rawDescription: How to access python package metadata from within the python console?

description: Access python package metadata from within the python console


code:
from cStringIO import StringIO
from sys import stdout

# Save a reference to stdout
STANDARD_OUT = stdout

@app.route("/")
def hello():
    ftp = FTP("someaddress")
    ftp.login()

    # Change stdout to point to a file-like object rather than a terminal
    file_like = StringIO()
    stdout = file_like

    ftp.dir()

    # lines in this case will be a string, not a list
    lines = file_like.getvalue()

    stdout = STANDARD_OUT
    file_like.close()

    return lines

rawDescription: flask+ftplib basic application

description: Flask+ftplib basic application


rawDescription: how find all groups of subsets of set A? Set partitions in Python

description: How find all groups of subsets of set A? Set partitions in Python


code:
from collections import Counter
c = Counter([thing['count'] for thing in things])
c[1]               # Number of elements with count==1
c[2]               # Number of elements with count==2
c.most_common()    # Most common elements
sum(c.values())    # Number of elements
list(c)            # List of unique counts
dict(c)            # Converted to a dict

rawDescription: What is a Pythonic way to count dictionary values in list of dictionaries


code:
_x = x.reshape(-1,3)
_y = np.zeros_like(_x)
for i in xrange(_x.shape[0]):
    _y[i,:] = f(_x[i,:])
y = _y.reshape(x.shape)

rawDescription: Use of numpy.nditer()

description: Use of numpy.nditer()


code:
for line in fh:
    pass
last = line

rawDescription: What is the most efficient way to get first and last line of a text file?


code:
from multiprocessing import Pool,cpu_count

p = Pool(cpu_count()-1)
p.map(download_and_save_the_file,files_to_get)

rawDescription: Threading or Multiprocessing

description: Threading or Multiprocessing


code:
import matplotlib

def setEnv(env):
    matplotlib.use(env)

rawDescription: Conditional import in a module

description: Conditional import in a module


code:
# mkreq.py
from urllib import urlencode
import urllib2
from base64 import b64encode

credentials = {
            'username': 'test@example.com',
            'password': 'password'
}
data = b64encode(urlencode(credentials))
request = urllib2.Request("http://localhost:5000/login")
request.add_data(data)
request.add_header('Content-Type', 'application/gooblygop')
# 'application/x-www-form-urlencoded' seems to be a default Content-Type
login1 = urllib2.urlopen(request).read()
print(login1)
request2 = urllib2.Request("http://localhost:5000/login")
request2.add_data(data)
login2 = urllib2.urlopen(request2).read()
print(login2)

rawDescription: Force Content-Type or expose request.data in Flask for known content-type


code:
from itertools import permutations

permutation_list = set(permutations(x * y))

rawDescription: Python permutations of x unique characters repeated y times each


code: df[3] = df[3].where((pd.notnull(df[3])), None)

rawDescription: Create new row if column value exists

description: Create new row if column value exists


rawDescription: convert a flat list to list of list in python

description: Convert a flat list to list of list in python


code:
class MyPasswordType(String):
    class comparator_factory(String.Comparator):
        def __eq__(self, other):
            return self.operate(operators.eq, hash(other))

rawDescription: SQL Alchemy overriding ==

description: SQL Alchemy overriding ==


code:
def method_of(instance):
    def method_adder(function):
        setattr(instance, function.__name__, function)
        return function
    return method_adder

@method_of(a)
def new_func(arg1, arg2):
    stuff()

rawDescription: Assigning method to object at runtime in Python


code: pixels = [i for row in pixels for i in row]

rawDescription: How can I convert an image's pixel color information into numbers and store it in a CSV?

description: Convert an image's pixel color information into numbers and store it in a CSV


code:
from subprocess import check_output

def merge(inputs, output, grid='2x2'):
    check_output(['pdfjam'] + inputs + ['--nup', grid, '--outfile', output])

merge(['4_P7.pdf', '4_P13.pdf'], 'merged.pdf')

rawDescription: PyPdf Merge error

description: PyPdf Merge error


code:
import itertools as it
res = it.islice(self.results, 1, None)
for number in res:
    # same code you already have goes here
    ...

rawDescription: What's causing the 135k/sec page faults in this python code? (trial-division prime sieve)


rawDescription: Convert python datetime to epoch with strftime


code: s.index[s | s.shift(-1)]

rawDescription: Finding False-True and True-True row indices


code:
d = { "name": "Anne", "address": "4 Elm Street", "dob": datetime.datetime(1977,12,2,1,2,3) }
template('mytemplate.tpl', **d)

rawDescription: Bottle multiple template variables

description: Bottle multiple template variables


rawDescription: How to add two list up in alternate positions? - python

description: Add two list up in alternate positions? - python


code:
from itertools import chain
chain(*[reverselookup[val] for val in found_vals])

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

description: Compare multiple key values from a list of dictionaries


code:
pr = pd.period_range('200001',periods=20,freq='M')
pr
pr.to_timestamp()
pr.to_timestamp(how='e')

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

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


code:
while True:
    sc.addstr(1, 1, time.strftime("%H:%M:%S"))
    sc.refresh()

    key = sc.getch()
    if key == ord('q'):
        break
    elif key < 0:
        time.sleep(1)

rawDescription: Python3 + Curses: How to press "q" for ending program immediately?


code:
from itertools import cycle
from operator import methodcaller

methods = cycle((methodcaller('upper'), methodcaller('lower')))
result = ''.join([next(methods)(c) if c.isalpha() else c for c in sample])

rawDescription: Having trouble with whitespace and strings in a function


code: ['cheesecake', 'bread']

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

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


rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code:
from itertools import chain
q1 = Cat.objects.all() # [<Cat: Daisy [cat]>]

q2 = Dog.objects.all() # [<Dog: Bruno [dog]>]

for each in chain(q1, q2):
    each.make_noise()

# Meow Meow
# Woof Woof

rawDescription: using django, how do i construct a proxy object instance from a superclass object instance?

description: Using django, how do i construct a proxy object instance from a superclass object instance


code: slicer = tuple(slice(i) for i in index)

rawDescription: Getting a slice of a numpy ndarray (for arbitary dimensions)


rawDescription: Python division

description: Python division


code: plt.text(x, y, c.high0 if c.high0 >= 34 else '', fontsize=7, fontweight='bold')

rawDescription: Using plt.text to only plot data that meets a certain criteria


code:
a, b, *c = read_json(request)
c = c[0] if c else 2

rawDescription: Default value in Python unpacking

description: Default value in Python unpacking


code:
message.decode(data)
message.load(data)

rawDescription: Setting custom message properties in Qpid Proton using the Python binding


rawDescription: Does reverse actually reverse a Python iterator?


rawDescription: For loop stacks and external functions without repeating popleft()


code:
from itertools import repeat
for values in stripped_header:
    volume_axis += repeat(int(values), 100)

rawDescription: Python - creating patterned lists

description: Python - creating patterned lists


code:
def upload(request):
    if request.method == 'POST':
        deviceID = measurement.deviceID = str(request.POST['deviceID'])
        return HttpResponse('Success!')
    else:
        return HttpResponse('Invalid Data')

rawDescription: Android app uploading data to a python server via post


code:
common_columns = df1.columns.union(df2.columns)
df1 = df1.reindex(columns=common_columns, fill_value='4WL')
df1
df2 = df2.reindex(columns=common_columns, fill_value='W4L')
pd.concat([df1, df2])

rawDescription: when combining pandas dataframe (concat or append) can I set the default value?

description: When combining pandas dataframe (concat or append) can I set the default value


code: tuple((x,) for x in BaseClass.__subclasses__())

rawDescription: How to retrieve subclasses as tuple of tuple

description: Retrieve subclasses as tuple of tuple


code:
(H.swapaxes(0, 1) / A).swapaxes(0, 1)
H/A[:,None]

rawDescription: Row-wise scaling with Numpy

description: Row-wise scaling with Numpy


code:
from django.conf.urls import include, url
from django.contrib import admin
from testDjango.test import main_view, ajax_view

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^test/', main_view),
    url(r'^test_ajax/', ajax_view)
]

rawDescription: Django - How to use asynchronous task queue with celery and redis


code:
headers = {'Accept-Encoding': 'identity'}
r = requests.get(url, headers=headers)

rawDescription: Get html using Python requests?

description: Get html using Python requests


code: stacked.reset_index().groupby(['split', 'sex', 'group', 'level']).sum().head(4)

rawDescription: Attributes/information contained in DataFrame column names


code: valid = re.fullmatch('[1-5]', UserInput)

rawDescription: Input validation with the `re` library

description: Input validation with the `re` library


code:
df = pd.DataFrame([["(12:25) (No Huddle Shotgun) P.Manning pass short left to W.Welker pushed ob at DEN 34 for 10 yards (C.Graham)."]])
df

rawDescription: Extract a certain part of a string after a key phrase using pandas?


code:
np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)
np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)
np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)

rawDescription: Generating random numbers with weighted probabilities in python


code: datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=pr_time)

rawDescription: PRTime to datetime in Python

description: PRTime to datetime in Python


code: O(nlogn) < O(m*n)

rawDescription: Which is the fastest way to search a value within a set of many "range" objects in Python


rawDescription: Average time for datetime list

description: Average time for datetime list


code:
class Foo(object):
    @many
    @decorators
    @here
    def bar(self):
        pass

rawDescription: Introspection to get decorator names on a method?


code:
import re
re.split("[#$!.\s]+", "The# dog.is.yelling$at!Me to" )

rawDescription: replace special chars to space and create list

description: Replace special chars to space and create list


code: df = pd.read_csv(url, parse_dates=['month'], date_parser=lambda x:pd.to_datetime(x, format='%m/%y'))

rawDescription: PANDAS coarse dates (month/year)

description: PANDAS coarse dates (month/year)


code: fig = plt.figure()

rawDescription: matplotlib PdfPages compounding images

description: Matplotlib PdfPages compounding images


code:
newlen = len(xnew)
chunks = 10
chunklen = newlen/ chunks
ynew = np.empty(newlen, dtype=float)
for i in range(chunks):
    xnew_chunk = xnew[i*chunklen:(i+1)*chunklen]
    query = "{0} <= x & x <= {1}".format(xnew_chunklen.min()*0.9,
                                         xnew_chunklen.max()*1.1)

    with tb.open_file('myfile.h5', 'r') as f:
        data = f.root.mytable.read_where(query)

    f = scipy.interpolate.interp1d(data['x'], data['y'])
    ynew[i*chunklen:(i+1)*chunklen] = f(xnew_chunk)

rawDescription: How to Interpolate Over Data in Pytables Efficiently


code:
class CronForm(forms.Form):
    days = forms.ModelChoiceField(queryset=Books.objects.all().order_by('name'))

rawDescription: django form dropdown list of stored models

description: Django form dropdown list of stored models


code:
def load(name_of_your_saved_file):
    with open(name_of_your_saved_file, 'rb') as inFile:
        newList = cPickle.load(inFile)
    return newList

rawDescription: name 'newList' is not defined

description: Name 'newList' is not defined


code: super(type(b), b).f()

rawDescription: How can I decide to call an overrided method in child class from either parent or child class?

description: Decide to call an overrided method in child class from either parent or child class


code:
#!/usr/bin/env python
import sys
from subprocess import Popen, PIPE
from textwrap import dedent

# generate some output on stdout/stderr
source = Popen([sys.executable, "-c", dedent("""
    from __future__ import print_function
    import sys
    from itertools import cycle
    from string import ascii_lowercase

    for i, c in enumerate(cycle(ascii_lowercase)):
        print(c)
        print(i, file=sys.stderr)
""")], stdout=PIPE, stderr=PIPE)

# convert input to upper case
sink = Popen([sys.executable, "-c", dedent("""
    import sys

    for line in sys.stdin:
        sys.stdout.write(line.upper())
""")], stdin=source.stdout)
source.stdout.close() # allow source to receive SIGPIPE if sink exits

# square input
sink_stderr = Popen([sys.executable, "-c", dedent("""
   import sys

   for line in sys.stdin:
       print(int(line)**2)
""")], stdin=source.stderr)
source.stderr.close() # allow source to receive SIGPIPE if sink_stderr exits

sink.communicate()
sink_stderr.communicate()
source.wait()

rawDescription: "3-way" Python subprocess pipeline: send stdout and stderr to two different processes?


code:
original = b'\xAD\xDE\xDE\xC0'
bytes([c for t in zip(original[1::2], original[::2]) for c in t])

rawDescription: byte reverse AB CD to CD AB with python

description: Byte reverse AB CD to CD AB with python


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim((0, 2100))
ax.bar(0, 2000, width=5)
ax.bar(100, 500, width=5)
ax.bar(40, 1500, width=5)

rawDescription: How to edit x axis with pylab?

description: Edit x axis with pylab


rawDescription: Python cross correlation

description: Python cross correlation


code:
t = Test()
t.__dict__
t.a
t.__dict__
t.a

rawDescription: Python memoising/deferred lookup property decorator


code:
from nltk.corpus import wordnet

def get_wordnet_pos(treebank_tag):

    if treebank_tag.startswith('J'):
        return wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return wordnet.VERB
    elif treebank_tag.startswith('N'):
        return wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return wordnet.ADV
    else:
        return ''

rawDescription: wordnet lemmatization and pos tagging in python

description: Wordnet lemmatization and pos tagging in python


code:
def miner_not_full_action(world, action, ticks):
    # 1. call it via the class. That may or may not work, but you have to provide an action object as the first argument.
    try1 = MinerNotFullAction.miner_to_ore(action, world, ore)
    # 2. call it regularly (as already mentioned), equivalent to 1.
    try2 = action.miner_to_ore(world, ore)

    # If we don't have such an object? Then we create one:
    ac = MinerNotFullAction()
    # and use it to call:
    try3 = ac.miner_to_ore(world, ore)

rawDescription: If a function (that's outside of the class) needs to use a method from a class, how do I call the method?


rawDescription: I have a string that i need to put into an object, but i cant get it to work


code:
import re
repl = re.sub(r'@(\w+)', r'%\1%', strng)

rawDescription: Replace a regex pattern in a string with a replacement string dependant on the match


code:
def line_iterator(file):
    for line in file:
        if not line[0].isdigit() and not line in ["+", "-"]:
            yield line
        else:
            break

with open("./testStage1.txt", 'r') as osrc:
    osrc.seek(291)
    lines = list(line_iterator(osrc))
    #To skip lines from the list containing 'blah'
    lines = [x for x in lines if 'blah' not in line]
    #Do whatever you need with your line list

rawDescription: readline function returning empty string

description: Readline function returning empty string


code: send(IP(), verbose=False)

rawDescription: How can I suppress "Sent $X packet" output in Scapy?

description: Suppress "Sent $X packet" output in Scapy


code: df.to_csv('ouputfile.csv', line_terminator=',', index=False, header=False)

rawDescription: Flattening Table From Excel into Csv with Pandas


code:
lst = a.split()  # automatically cleans up the whitespace for you
print(list(set(lst)))

rawDescription: Inquiry about removing duplicates

description: Inquiry about removing duplicates


code:
from threading import Lock, Thread

x = 0
lock = Lock()

def main():
    global x
    print(x)
    p = Thread(target=change, args=(1,))
    p2 = Thread(target=change, args=(2,))
    p.start()
    p2.start()
    p.join()
    p2.join()

def change(number):
    global x
    with lock:
        x = x + 1
        print('{} - coming from process #{}'.format(x, number))

if __name__ == '__main__':
    main()

rawDescription: Simple Multithreading in Python using Process


code:
with open('random.txt', 'a') as f:
    f.write("\n".join(["FILE{} blabla{}".format(x, x*2) for x in xrange(10)]))

rawDescription: How to create a string with loop in python and save it in file

description: Create a string with loop in python and save it in file


code:
# cElementTree is the faster, C language based big brother of ElementTree
from xml.etree import cElementTree as etree

# Our test XML
xml = '''
<a:p xmlns:a="http://example.com"><a:fld id="{55FBEE69-CA5C-45C8-BA74-481781281731}" type="slidenum">
<a:rPr lang="en-US" sz="1300" i="0"><a:solidFill><a:srgbClr val="000000"/>
</a:solidFill></a:rPr><a:pPr/><a:t>1</a:t></a:fld><a:endParaRPr lang="en-US"
sz="1300" i="0"><a:solidFill><a:srgbClr val="000000"/></a:solidFill>
</a:endParaRPr></a:p>
'''

# Manually specify the namespace. The prefix letter ("a") is arbitrary.
namespaces = {"a":"http://example.com"}

# Parse the XML string
tree = etree.fromstring(xml)

"""
Breaking down the search expression below
  a:fld - Find the fld element prefixed with namespace identifier a:
  [@type='slidenum'] - Match on an attribute type with a value of 'slidenum'
  /a:t - Find the child element t prefixed with namespace identifier a:
"""
slidenums = tree.findall("a:fld[@type='slidenum']/a:t", namespaces)
for slidenum in slidenums:
    print(slidenum.text)

rawDescription: retrieve data from xml tag Python

description: Retrieve data from xml tag Python


code:
from ruamel.yaml import load

def get_longest(d, max_length=0):
    if isinstance(d, dict):
        try:
            l = len(d['subsection'])
            if l > max_length:
                max_length = l
        except:
            pass  # no key "subsection"
        for val in d.values():
            max_length = get_longest(val, max_length)
    elif isinstance(d, list):
        for item in d:
            max_length = get_longest(item, max_length)
    return max_length

data = load(open('input.yml'))

rawDescription: Size of largest sub-dictionary in python


code:
def create_all_applier(method, doc=None):
    def on_all(seq, *args, **kwargs):
        for obj in seq:
            getattr(obj, method)(*args, **kwargs)
    on_all.__doc__ = doc
    return on_all

start_all = create_all_applier('start', "Start all instances")
stop_all = create_all_applier('stop', "Stop all instances")
...

rawDescription: How to call same method for a list of objects?

description: Call same method for a list of objects


rawDescription: Write to list to rows with specific number of columns


code:
class YourClass(models.Model):
    description = models.CharField(max_length=300, unique=True)
    picture = models.ImageField(upload_to='myimages')

rawDescription: Django: does ImageField need a filepath or an actual image object?


code:
import itertools

with open('path/to/file') as infile:
    for line,_stuff in itertools.groupby(infile):
        print(line)

rawDescription: Keep the first line from a block of related lines


rawDescription: Deleting consonants from a string in Python


code:
r"""(?x)   # let's write this complex regex in free-space mode!
\d         # match a digit
$          # at the end of a line
"""

rawDescription: Single, double, or triple double quotes for Python’s raw string notation for regex?


code:
def numbers(num):
    while 1:
        yield from range(num)

rawDescription: How to use For loop to cycle through 1 to 10 again and again until the loop is broken in python

description: Use For loop to cycle through 1 to 10 again and again until the loop is broken in python


code:
def area_of_polygon(vertices):
    pairs = zip(vertices, vertices[1:] + vertices[0:1])
    return sum(x1 * y2 - y1 * x2 for (x1, y1), (x2, y2) in pairs) / 2

rawDescription: Area of a polygon (Recursively using Python)


rawDescription: Unique value in list of lists in Python

description: Unique value in list of lists in Python


code:
data = df.corr()
fig, ax = plt.subplots(1, 1)
m = plot_corr_ellipses(data, ax=ax, cmap='Greens')
cb = fig.colorbar(m)
cb.set_label('Correlation coefficient')
ax.margins(0.1)

rawDescription: How can I plot a correlation matrix as a set of ellipses, similar to the R open-air package?

description: Plot a correlation matrix as a set of ellipses, similar to the R open-air package


code:
all_challenges = session.query(Challenge).all()

for user in some_users:    # however you got these
    for attempt in user.attempts:   # however you got these
        do_something_with(attempt.challenge)  # no SQL will be emitted

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
A    # Modified to show more variety
str2num = (np.fromstring(A, dtype=np.uint8)-48).reshape(-1,4)
str2num
de2bi_convarr = 2**np.arange(3,-1,-1)
de2bi_convarr
out = str2num.dot(de2bi_convarr)
out

rawDescription: fastest way to convert bitstring numpy array to integer base 2

description: Fastest way to convert bitstring numpy array to integer base 2


code:
import networkx as nx
from lxml import html
import matplotlib.pyplot as plt

raw = "...your raw html"

def traverse(parent, graph, labels):
    labels[parent] = parent.tag
    for node in parent.getchildren():
        graph.add_edge(parent, node)
        traverse(node, graph, labels)

G = nx.DiGraph()
labels = {}     # needed to map from node to tag
html_tag = html.document_fromstring(raw)
traverse(html_tag, G, labels)

pos = nx.graphviz_layout(G, prog='dot')

label_props = {'size': 16,
               'color': 'black',
               'weight': 'bold',
               'horizontalalignment': 'center',
               'verticalalignment': 'center',
               'clip_on': True}
bbox_props = {'boxstyle': "round, pad=0.2",
              'fc': "grey",
              'ec': "b",
              'lw': 1.5}

nx.draw_networkx_edges(G, pos, arrows=False)
ax = plt.gca()

for node, label in labels.items():
        x, y = pos[node]
        ax.text(x, y, label,
                bbox=bbox_props,
                **label_props)

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.show()

rawDescription: HTML Parse tree using Python 2.7

description: HTML Parse tree using Python 2.7


code:
class World(object):
    def __init__(self, continents):
        self.continents = continents

class Continent(World):
    def __init__(self, name):
        self.name = '' # name of the continent
    ...

class Country(Continent):
    def __init__(self, name):
        self.name = '' # name of the country
    ...

class City(Country):
    def __init__(self, name):
        self.name = '' # name of the city
    ...

rawDescription: How to created inherited objects using Python?

description: Created inherited objects using Python


code:
def bufcount(filename, linesep=os.linesep, buf_size=2 ** 15):
    lines = 0
    with open(filename, 'rb') as f:
        last = ''
        for buf in iter(f.read, ''):
            lines += buf.count(linesep)
            if last and last + buf[0] == linesep:
                # count line separators straddling a boundary
                lines += 1
            if len(linesep) > 1:
                last = buf[-1]
    return lines

rawDescription: Why Python does not see all the rows in a file?


code:
n = np.array([[None], 0], dtype=object)[:1]
s[pd.isnull(s)] = n

rawDescription: How can I set (dtype=object) numpy array values to Python lists, without numpy interpreting the lists as lists of values?

description: Set (dtype=object) numpy array values to Python lists, without numpy interpreting the lists as lists of values


code:
Button1.grid(row=0,column=0,columnspan=2)
Button2.grid(row=0,column=2)
Button3.grid(row=0,column=4,rowspan=2)
Label1.grid(row=1,column=0)
Label2.grid(row=1,column=1)
Label3.grid(row=1,column=2)

rawDescription: Tkinter / Python grid layout with listboxes


code:
DECIMAL_NUM='123456789'

def main():
    # Get file name from user
    file_name = input("Enter a file name: ")

    # Open the file to read, and get a list of all lines:
    lines = open(file_name, 'r').readlines()

    one = 0
    two = 0
    three = 0
    four = 0
    five = 0
    six = 0
    seven = 0
    eight = 0
    nine = 0

    for line in lines:

        if line.strip(): # Check if line is not empty

            if line[0] == DECIMAL_NUM[0]:
                one += 1
            elif line[0] == DECIMAL_NUM[1]:
                two += 1
            elif line[0] == DECIMAL_NUM[2]:
                three += 1
            elif line[0] == DECIMAL_NUM[3]:
                four += 1
            elif line[0] == DECIMAL_NUM[4]:
                five += 1
            elif line[0] == DECIMAL_NUM[5]:
                six += 1
            elif line[0] == DECIMAL_NUM[6]:
                seven += 1
            elif line[0] == DECIMAL_NUM[7]:
                eight += 1
            elif line[0] == DECIMAL_NUM[8]:
                nine += 1

    print(one)
    print(two)

main()

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

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


code: columns = zip(*rows)

rawDescription: load cvs file in matrix python

description: Load cvs file in matrix python


code:
import cv2
import numpy as np

def find_corners(image):
    im = cv2.Canny(image, 100, 200)

    cnt = cv2.findContours(im,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
    cnt = cv2.approxPolyDP(cnt[0], 5, True)
    return cnt.astype(np.float32)

def main(argv):
    trap = cv2.imread('trap.png', cv2.IMREAD_GRAYSCALE)
    rect = cv2.imread('rect.png', cv2.IMREAD_GRAYSCALE)

    ptsTrap = find_corners(trap)
    ptsRect = find_corners(rect)

    T = cv2.getPerspectiveTransform(ptsTrap, ptsRect)

    warp = cv2.warpPerspective(trap, T, rect.shape[:2])

    cv2.imshow('', warp)
    cv2.imwrite('warp.png', warp)
    cv2.waitKey()
    cv2.destroyAllWindows()

rawDescription: OpenCV Perspective Transform giving unexpected result


code: barplot(y, col="steelblue", border=NA, xlab="Height", ylab="Weight" )

rawDescription: Python's barchart equivalent in R

description: Python's barchart equivalent in R


code:
with open('infile_name','r') as input_file:
    lines = input_file.readlines()
    sorted_lines = sorted(lines, key=lambda s: s.upper())
    output_file = open('outfile_name', 'w')
    output_file.writelines(sorted_lines)

rawDescription: How can I re-arrange orders of lines based on alphabet in Python

description: Re-arrange orders of lines based on alphabet in Python


code:
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
colors = ['#8ffe09','r','#0033ff','#003311','#993333','#21c36f','#c46210','#ed3cca','#ffbf00','g','#000000']
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
s=0
a=1
b=2
for i in range(0, 10):
    s=a+b
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Z axis')
    x = np.random.rand(5, 3)
    y = np.random.rand(5, 3)
    z = np.random.rand(5, 3)
    #ax.cla()
    ax.scatter(x[:, 0], y[:, 1], z[:, 2],color=colors[a-1])
    plt.draw()
    time.sleep(1)   #make changes more apparent/easy to see
    a=a+1
    b=b+2
    if s>10:
         break;

rawDescription: Change color of 3D scatterplot each iteration


code:
import random

f = open('iplist1.txt','w')
for i in range(5000):
    ip = '.'.join([str(random.randint(1,254)) for i in range(4)])
    ip += '/'+str(random.randint(8,24))
    f.write(ip+'\n')
f.close()

f = open('iplist2.txt','w')
for i in range(5000):
    ip = '.'.join([str(random.randint(1,254)) for i in range(4)])
    ip += '/'+str(random.randint(8,24))
    f.write(ip+'\n')
f.close()

rawDescription: Intersections between two lists of thousands of networks


code:
wquery = "UPDATE `cin`.`flags` SET `flag`='%s', `update_time`='%d' WHERE `name`='%s' AND `lockid`='%s'"
cursor.execute(wquery, (pic_bin, update_time, names[index], lockid))

rawDescription: upload web files to mysql in python

description: Upload web files to mysql in python


code:
def dehydrate_country(self, bundle):
    return bundle.obj.country.name

rawDescription: Django-countries and TastyPie: Get country name


code:
board = []
for i in range(3):
    board.append([])
    for j in range(3):
        board[i].append(0)

board

rawDescription: How to initialise a 2D array in Python?

description: Initialise a 2D array in Python


code:
from django.core.management import call_command
call_command('syncdb', interactive=True)
call_command('runserver')

rawDescription: In django, how do I call the subcommand 'syncdb' from the initialization script?


code:
# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Filter by Area.
params.filterByArea = True
params.minArea = 100
params.maxArea =100000

# Don't filter by Circularity
params.filterByCircularity = False

# Don't filter by Convexity
params.filterByConvexity = False

# Don't filter by Inertia
params.filterByInertia = False

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)

# Detect blobs.
keypoints = detector.detect(imthresh)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures
# the size of the circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(imthresh, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

rawDescription: Blob ID tagging for OpenCV python

description: Blob ID tagging for OpenCV python


code:
for line in output.split("\n"):
    if line.startswith('Your MAC address is'):
        addr = line.split()[-1]

rawDescription: How to get last part of line with Python

description: Get last part of line with Python


code: busdict[bus] = [val].append(i)

rawDescription: What is the best way to append lists inside a dict?


rawDescription: Equivelant to rindex for lists in Python


code:
table=soup.find('table', 'bioTableAlt')
for row in table.findAll('tr')[1:]:
    cells = row.findAll('td')
    #retreieve data from cells...

rawDescription: How to fetch some data conditionally with Python and Beautiful Soup

description: Fetch some data conditionally with Python and Beautiful Soup


code:
prev = None
newp = []
length = len(p) - 1
for i in range(length):
  if p[i][0] == p[i+1][0] or p[i][0] == prev:
    newp.append(p[i])
    prev = p[i][0]

if p[length][0] == p[length-1][0]:
  newp.append(p[length])

rawDescription: Comparing and discarding two consecutive elements not complying certain condition in a list using Python


code:
import re
re.sub(r'@\[(.*?)\]', (lambda m: (lambda x: '{1}'.format(x.lower().replace(' ', '-'), x))(m.group(1))), text)

rawDescription: Python / Regular Expression Token conversion with parameter capture


code:
import pandas as pd
import numpy as np
data = pd.DataFrame({"value": np.arange(5)}, index=pd.date_range("2013/02/03", periods=5, freq="3Min"))
data
filler = pd.DataFrame({"value": [100] * 15}, index=pd.date_range("2013/02/03", periods=15, freq="1Min"))
filler
merged = filler.merge(data, how='left', left_index=True, right_index=True)
merged["value"] = np.where(np.isfinite(merged.value_y), merged.value_y, merged.value_x)
merged
merged['2013-02-03 00:01:00':'2013-02-03 00:10:00']

rawDescription: Python pandas, how to truncate DatetimeIndex and fill missing data only in certain interval


code:
import pprint as pp
import requests
pp.pprint(requests.post('https://httpbin.org/post', files={'file': ('filename', fd)}).json())

rawDescription: Replicate Curl command with Python Requests


code:
class ListComponents(generics.ListAPIView):
    serializer_class = MenuItemComponentSerializer

    def get_queryset(self):
        """
        Override .get_queryset() to filter the items returned by the list.
        """
        menuitem = self.kwargs['menuitem']
        return MenuItemComponent.objects.filter(menuItem=menuitem)

rawDescription: How to extend model on serializer level with django-rest-framework

description: Extend model on serializer level with django-rest-framework


code:
from scipy.interpolate import interp1d
f_lon = interp1d(t, lon)
f_lat = interp1d(t, lat)

rawDescription: Resample time-series of position evenly in time


code: ['<Cookie JSESSIONID=BE71BFC3EE6D9799DEBD939A7487BB08 for somewebsite.com>']

rawDescription: Human readable cookie information using cookielib?


code:
if raw_input('Enter a word: ').endswith('s'):
    do_stuff()

rawDescription: Python: Last character of user input

description: Python: Last character of user input


code:
class ImageQuerySet(models.QuerySet):
    def landscapes(self):
        return self.filter(width__gte=models.F('height'))

    def portraits(self):
        return self.filter(width__lte=models.F('height'))

    def small(self):
        return self.filter(width__lte=1200)

    def large(self):
        return self.filter(width__gte=1200)

class ImageManager(models.Manager):
    def get_queryset(self):
        return ImageQuerySet(self.model, using=self._db)

rawDescription: When should I use a custom Manager versus a custom QuerySet in Django?


code:
from datetime import date
d = date(2016, 11, 26)
d.strftime("%Y/%m/%d")
d.strftime("%d-%b-%Y")

rawDescription: Converting dates in Python

description: Converting dates in Python


code:
import re

def matches(s, sub_strings):
    sub_strings = sorted(sub_strings, key=len, reverse=True)
    pattern = '|'.join(re.escape(substr) for substr in sub_strings)
    return re.findall(pattern, s)

rawDescription: find best subset from list of strings to match a given string

description: Find best subset from list of strings to match a given string


code:
import os
whatever = os.fdopen(1, 'w', 0)
os.fstat(1)
del whatever
os.fstat(1)

rawDescription: dup, dup2, tmpfile and stdout in python

description: Dup, dup2, tmpfile and stdout in python


code:
# indices = sum(np.meshgrid(np.arange(length), starts))

indices = np.arange(length) + starts[:, np.newaxis]
# array([[ 0,  1,  2,  3,  4],
#        [10, 11, 12, 13, 14],
#        [21, 22, 23, 24, 25]])
data[indices]

rawDescription: How to efficiently index into a 1D numpy array via slice ranges

description: Efficiently index into a 1D numpy array via slice ranges


code:
leftdata = {'10000': { 'key': '10000', 'fkey':'asdf', 'parent':'10001'},
               '10001': { 'key': '10001', 'fkey':'qwer', 'parent':''},}
rightdata = {'asdf': { 'key': 'asdf', 'fkey':'10000', 'parent':'qwer'},
               'qwer': { 'key': 'qwer', 'fkey':'10001', 'parent':''}}

left = Dataset(leftdata)
right = Dataset(rightdata)
left.set_related_dataset(right)
right.set_related_dataset(left)

rawDescription: Python: I have a dual key list, which is the most effective storage object for retreival


code:
def difft(start,end):
    a,b,c,d = start.hour, start.minute, start.second, start.microsecond
    w,x,y,z = end.hour, end.minute, end.second, end.microsecond
    delt = (w-a)*60 + (x-b) + (y-c)/60. + (z-d)/60000000
    return delt + 1440 if delt<0 else delt

rawDescription: how to substract two datetime.time values in django template,and how to format a duration as hour,minutes

description: Substract two datetime.time values in django template,and how to format a duration as hour,minutes


code: b = copysign(b, a)

rawDescription: Why doesn't Python have a sign function?

description: Why doesn't Python have a sign function


rawDescription: How to reset some function variables in Python in a loop

description: Reset some function variables in Python in a loop


code:
colors=dict((key,[]) for key in keys)
colors

rawDescription: What is the Pythonic way to use (elements of) a list as keys in a dictionary?


code:
from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
            ...
    else:
        # Return an 'invalid login' error message.
        ...

rawDescription: Multiple login fields in django user

description: Multiple login fields in django user


code:
map(min, xyz)
map(max, xyz)

rawDescription: Python 2.7 find min,max on list of lists


code:
import re

lines = [
    'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
    'Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)',
    'msnbot/2.0b (+http://search.msn.com/msnbot.htm)'
]

botname = re.compile('\w+bot/[.\w]+', flags=re.IGNORECASE)
for line in lines:
    matched = botname.search(line)
    if matched:
        print(matched.group())

rawDescription: Extract bot name from user-agent string-Python


rawDescription: Clarification on indexing numpy array in python


code:
from pprint import pprint as pp
pp([y for y in x if y[3] == '2somename'])

rawDescription: Sorting and Grouping Nested Lists in Python


code: ax.plot_surface(x_surf, y_surf, z_surf, cmap=theCM);

rawDescription: matplotlib - 3D plots - combining scatter plot with surface plot

description: Matplotlib - 3D plots - combining scatter plot with surface plot


code:
def adjust_row(row):
    kvp_data = row[3:].valid()
    kvp_data = kvp_data.reshape(kvp_data.size//2, 2)
    kvp = dict(kvp_data)
    return row[:3].append(pd.Series({'kvp': kvp}))

rawDescription: Convert data frame columns to dictionary


code:
def PlayerMove():
    global s1,s2,s3,s4,s5,s6,s7,s8,s9
    move = raw_input('Choose a space 1-9 \n')
    ...

rawDescription: Python Variable

description: Python Variable


code:
def formula(principal,rate,years):
    return principal*pow((1 + rate),years) #return this result

rawDescription: How can I pass multiple values in a function parameter?

description: Pass multiple values in a function parameter


code:
products = sorted(Product.objects.all(),
        key = lambda product : product.lowest_possible_price())

rawDescription: Annotate using an extra field from a ManyToMany model in Django


code:
Store,Region,District,name,location
1234,90,910,MallA,GMT
4567,87,902,MallB,EST
2468,90,811,MallC,PST
1357,87,902,MallD,CST

rawDescription: Convert CSV to well-structured JSON in Python


code:
settings = {}
settings['server'] = '172.16.150.106:1433'
settings['user'] = 'pyadmin'
settings['password'] = 'admin'
settings['db'] = 'SQLSERV_2005'

rawDescription: Python import similar to Django settings file


code:
from dateutil import parser

now = datetime.now().date()
ts = '2015-03-01T17:09:00.000+0000'
ts = parser.parse(ts).date()
print(ts - now).days

rawDescription: Subtracting Dates of Different Formats and converting to Int


code:
df1 = pd.get_dummies(df)
df1.loc[df.v1.isnull(), df1.columns.str.startswith("v1_")] = np.nan
df1

rawDescription: Retaining NaN values after get_dummies in Pandas


code:
def swap(l,n):
    ln = len(l)
    try:
        ind = my_list.index(n)
        l[ind], l[(ind + 1)% ln] = l[(ind + 1) % ln], l[ind]
    except IndexError:
        pass

rawDescription: moving elements in a list of Python

description: Moving elements in a list of Python


code:
for i, item in enumerate(l2):
    item.append(membership[i])

rawDescription: Why does this code change both lists (id is not the same)?


code: max((equation(v), k) for k, v in d.items())[1]

rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


code:
class Run:

    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs

    def execute(self):
        print('Running')
        self.func(*self.args, **self.kwargs)  # call func here

baz = Run(foo, 'bar')  # don't call func here
baz.execute()

rawDescription: Passing function to class in Python

description: Passing function to class in Python


code:
df.drop('catcode',axis = 1, inplace = True)
catcode_fixed.name = 'catcode'
df = df.join(catcode_fixed)

rawDescription: pandas: column formatting issues causing merge problems

description: Pandas: column formatting issues causing merge problems


code:
new_L = []

for e in L:
    new_L.append(e + ' ' * (max_length - len(e)))

rawDescription: I have been trying to write a program python


code:
df = df.set_index('transaction_ts')
df['rolling_count'] = 1
df['rolling_count'] = df.groupby('userID', sort=False)['rolling_count'].transform(lambda x : msum(x,1))

rawDescription: Pandas - Rolling window - uneven interval


code:
func1
func2

rawDescription: Importing Modules from Multiple Parallel Subdirectories (Python)


code:
[
    {
        'name': 'test.sh',
        'childrens': [
            {
                'name': 'api.test.sh',
                'childrens': [
                    {'name': 'blah.api.test.sh', 'childrens': None}
                ]
            }
         ]
    },
    {
        'name': 'test.com',
        'childrens': [
            {'name': 'api.test.com', 'childrens': None}
        ]
    }
]

rawDescription: Sorting and organizing DNS records

description: Sorting and organizing DNS records


code:
for k in xrange(a.shape[0]):
    b = np.linalg.eig(a[k,:,:])

rawDescription: Diagonalisation of an array of 2D arrays


code: [x for i, _ in enumerate(elements) for x in itertools.product(*elements[:i+1])]

rawDescription: How to generate lists from a specification of element combinations

description: Generate lists from a specification of element combinations


rawDescription: Extract tuple from list

description: Extract tuple from list


code: (a == elem).sum(axis=0).argmax()

rawDescription: How to get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python

description: Get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python


code: buflen, buf = win32file.ReadFile(f, 4096, None)

rawDescription: Does Python IO allow opened file to be deleted/renamed on Windows?


code:
def remove_event(dicts, key, id, event_id):
    if key in dicts and id in dicts[key] and "events" in dicts[key][id]:
        dicts[key][id]['events'] = [event for event in dicts[key][id]['events']
                                    if event["eventID"] != event_id]
    else:
        raise ValueError("The actual Events could not be found")

remove_event(data, "Div 4 A Herrar", "1", "3215")

rawDescription: Remove a list item in a nested dictionary


code: df.query("field not in @ban_field")

rawDescription: Remove lines in dataframe using a list in Pandas


code:
last = object()

def function(a, start = 0, end = last):
    if end is last: end = (len(a) - 1)
    return start, end

rawDescription: Using the length of a parameter array as the default value of another parameter of the same function


code:
def gen_X(Y = True, Z = True):
    yield 'a'
    yield 'b'
    yield 'c'
    if Y:
        yield 'd'
    if Z:
        yield 'e'

rawDescription: Conditionals when defining a tuple / list


code: ind_dict = dict((k,i) for i,k in enumerate(NNSRCfile['datetimenew']))

rawDescription: Python: Finding corresponding indices for an intersection of two lists


code:
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text)
    feeds = db.relationship('Feed', secondary=category_feeds,
        backref=db.backref('categories'))

    @property
    def articles(self):
        this_category = Category.query.get(self.id)
        articles = db.session.query(Article).join(Article.feed).filter(Feed.categories.contains(this_category))
        return articles

    def __init__(self, **kwargs):
        for key, value in kwargs.iteritems():
            setattr(self, key, value)

rawDescription: flask-sqlalchemy three way association

description: Flask-sqlalchemy three way association


code:
def get_id(self):
    return self.user
    return self.id

rawDescription: Retrieve data from MongoDB/Flask and display it in an HTML page using Jinja2


code:
def __eq__(self, other):
    return all(
        sorted(v) == sorted(self.__dict__[key])
            if isinstance(v, np.array)
        else self.__dict__[key] == v
        for key, v in other.__dict__.iteritems()
    )

rawDescription: Sort both elements of a tuple, ignoring case, within a list, so that the keys of a dictionary line up correctly


code:
def getAllIndicesRecursively(s, l, agg=[], path=[]):
    for i, v in enumerate(l):
        if isinstance(v, list):
            getAllIndicesRecursively(s, v, agg, path + [ i ] )
        elif v == s: agg += [ path + [ i ] ]
    return agg

rawDescription: How can I find all indices of a value in a multidimensional array?

description: Find all indices of a value in a multidimensional array


code:
TODAY + three_mon_rel + three_mon_rel
TODAY + three_mon_rel + three_mon_rel + three_mon_rel
TODAY + three_mon_rel + three_mon_rel + three_mon_rel + three_mon_rel

rawDescription: How do you add "3 months" to a datetime.date object in python?

description: Add "3 months" to a datetime.date object in python


code:
for key, value in dictionary.iteritems():
    dictionary[key] = tuple(value)

rawDescription: Convert dictionary of lists to dictionary of tuples


rawDescription: Import single csv file with one data field going to separate table


code:
import pickle
import sys
from collections import OrderedDict

numprocs = 10
a = ['a' for i in range(1000000)]
b = [a+[] for i in range(100)]

data1 = [b+[] for i in range(numprocs)]
data2 = [data1+[]] + ['1' for i in range(numprocs-1)]
data3 = [['1'] for i in range(numprocs)]
sizes = OrderedDict()
for idx, data in enumerate((data1, data2, data3)):
    sizes['data{}'.format(idx+1)] = sum(sys.getsizeof(pickle.dumps(d))
                                            for d in data)

for k, v in sizes.items():
    print("{}: {}".format(k, v))

rawDescription: python multiprocessing peculiar memory management

description: Python multiprocessing peculiar memory management


code:
file_bytes = ...   # However you read your input
file_text = file_bytes.decode('UTF-8')
normalized_text = unicodedata.normalize('NFC', file_text)
allowed_categories = set([
    'Ll', 'Lu', 'Lt', 'Lm', 'Lo',  # Letters
    'Nd', 'Nl',                    # Digits
    'Po', 'Ps', 'Pe', 'Pi', 'Pf',  # Punctuation
    'Zs'                           # Breaking spaces
])
filtered_text = ''.join(
    [ch for ch in normalized_text
     if unicodedata.category(ch) in allowed_categories])
filtered_bytes = filtered_text.encode('UTF-8')  # ready to be written to a file

rawDescription: Stripping a unicode text of whatever is not a character


code:
s = "[segment1][segment2][segment2]"
s[1:-1].split('][')

rawDescription: Segment string into array, regex?

description: Segment string into array, regex


code:
a = np.random.random(20)
a
b = np.array((0.3,0.7))
np.sum(a[:,None]<b[None,:], axis=0)
np.sum(a[:,None]<b, axis=0) # b's new axis above is unnecessary...
(a[:,None]<b).sum(axis=0)   # even simpler

rawDescription: Number of elements of array less than each element of cutoff array in python


code:
from random import randrange
diff = len(your_lis) - 10000
for _ in xrange(diff):
    ind = randrange(len(your_lis))
    your_lis.pop(ind)  #a quick timing check suggests that `pop` is faster than `del`

rawDescription: How to delete random items in a list to keep the list in a certain length?

description: Delete random items in a list to keep the list in a certain length


code:
import time
import Queue
import sys
import threading
import subprocess
PIPE = subprocess.PIPE

def read_output(pipe, funcs):
    for line in iter(pipe.readline, ''):
        for func in funcs:
            func(line)
            # time.sleep(1)
    pipe.close()

def write_output(get):
    for line in iter(get, None):
        sys.stdout.write(line)

process = subprocess.Popen(
    ['random_print.py'], stdout=PIPE, stderr=PIPE, close_fds=True, bufsize=1)
q = Queue.Queue()
out, err = [], []
tout = threading.Thread(
    target=read_output, args=(process.stdout, [q.put, out.append]))
terr = threading.Thread(
    target=read_output, args=(process.stderr, [q.put, err.append]))
twrite = threading.Thread(target=write_output, args=(q.get,))
for t in (tout, terr, twrite):
    t.daemon = True
    t.start()
process.wait()
for t in (tout, terr):
    t.join()
q.put(None)
print(out)
print(err)

rawDescription: Subprocess.Popen: cloning stdout and stderr both to terminal and variables


code:
print("Station  | Adjacent | Total")
print("\n".join(["{} | {:>8s} | {}".format(time12h, str(curr-prev), str(curr))
                 for time12h, curr, prev in zip(Train_arrival_time[1:],
                                                time_in_transit,
                                                [ZERO]+time_in_transit)]))

rawDescription: Convert a 12 hour time format to 24 hour time format (keeping record of the day) in python


kind: youtube#video

rawDescription: Python - YouTube API v3 - How to get video ID only?


code:
class MyClass:
    ONE = 1
    TWO = 2

enum_names = {value: name for name, value in vars(MyClass).items() if name.isupper()}
enum_names[1]

rawDescription: Python: Converting value of constant to name of constant


code:
def irr_vec(cfs):
    # Create companion matrix for every row in `cfs`
    M, N = cfs.shape
    A = np.zeros((M, (N-1)**2))
    A[:,N-1::N] = 1
    A = A.reshape((M,N-1,N-1))
    A[:,0,:] = cfs[:,-2::-1] / -cfs[:,-1:]  # slice [-1:] to keep dims

    # Calculate roots; `eigvals` is a gufunc
    res = np.linalg.eigvals(A)

    # Find the solution that makes the most sense...
    mask = (res.imag == 0) & (res.real > 0)
    res = np.ma.array(res.real, mask=~mask, fill_value=np.nan)
    rate = 1.0/res - 1
    idx = np.argmin(np.abs(rate), axis=1)
    irr = rate[np.arange(M), idx].filled()
    return irr

rawDescription: Improve performance of the np.irr function through vectorization


code:
groups = df.groupby('Date')
df =     groups.apply(lambda x: x['v'].reset_index(drop=True))

#line below is equivalent to above but clunkier use if you really want the ValX as columns
#df =     groups.apply(lambda x: pd.Series({"Val{0}".format(1+i):each for i,each in enumerate(x['v'])}))

rawDescription: How do I update dataframe column values with Pandas?

description: Update dataframe column values with Pandas


code:
x.remove_row(0) # Removes the first row
x.remove_row(-1) # Removes the last row

rawDescription: How to index observable coordinates in an astropy Table

description: Index observable coordinates in an astropy Table


code:
...
def get(self, param1, param2):
    ...

rawDescription: Parsing url with webapp2 handler Python GAE


rawDescription: Python Regex Query Syntax

description: Python Regex Query Syntax


code:
myQuery = c.query(wql)
myQuery.Availability

rawDescription: How to access wmi in python?

description: Access wmi in python


code: utext = text.decode('utf-8')

rawDescription: How to understand unicode and utf-8

description: Understand unicode and utf-8


rawDescription: How to retrieve sub documents in a Array from mongoDB using python script

description: Retrieve sub documents in a Array from mongoDB using python script


code: src_path = "/home/data/" + pkg_name + "/file.zip"

rawDescription: Is there any way to access variable like $var (similar to shell scripting) in python?


code:
import os
with open("output.txt","w") as f:
    f.write("\n".join(os.listdir("C:\\")))

rawDescription: How to terminate process in python in certain situation

description: Terminate process in python in certain situation


code:
import logging
import os

class PathTruncatingFormatter(logging.Formatter):
    def format(self, record):
        if isinstance(record.args, dict) and 'pathname' in record.args:
            # truncate the pathname
            filename = os.path.basename(record.args['pathname'])
            if len(filename) > 20:
                filename = '{}~{}'.format(filename[:3], filename[-16:])
            record.args['pathname'] = filename
        return super(PathTruncatingFormatter, self).format(record)

rawDescription: python logging - how do I truncate the pathname to just the last few characters or just the filename?

description: Python logging - how do I truncate the pathname to just the last few characters or just the filename


code:
def example(format_str, year, value):
  format_to_year_to_value_dict = {}

  format_to_year_to_value_dict.setdefault(format_str, {}).setdefault(year, []).append(value)

rawDescription: How to initialize nested dictionaries in Python

description: Initialize nested dictionaries in Python


code: params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))

rawDescription: Python interface to PayPal - urllib.urlencode non-ASCII characters failing


code:
generator = string(data)
data1 = next(generator)
data2 = next(generator)
...

rawDescription: return the element of array java

description: Return the element of array java


code:
def get_clothes():
    for t in allThings:
       if t.garment:
           yield t

def get_hats():
    for t in get_clothes():
        if t.headgear:
            yield t

rawDescription: Optimise filtering lists in Python 2.7

description: Optimise filtering lists in Python 2.7


code:
answer = request.GET['data']
jsonData = json.loads(answer)

for count, question in enumerate(latest_question_list):
    answer = jsonData[str(count + 1)]
    entry = Answer(question=question, answer=answer)
    entry.save()

return HttpResponse("feedback:contactus")

rawDescription: how to get data from json object to a dictionary in python

description: Get data from json object to a dictionary in python


code: largest_key = max(d['a'])

rawDescription: Return the largest value of a given element of tuple keys in a dictionary


code:
import time
t = ValueCache()
while True:
    if t.update(time.time()):
        print("Cache Updated!")

rawDescription: Dectecting a value change in Python loop


rawDescription: Python accessing data in JSON object

description: Python accessing data in JSON object


code:
with open('file1') as fd:
    data1 = dict(line.strip().split()
                 for line in fd if line.strip())

rawDescription: Python to search values in one text file, compare them with values in another text file, then replace values if there is a match


rawDescription: Python : Convert time format to unix_timeformat


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

l = np.array([ (2,2,1), (2,4,0), (2,8,0),
               (4,2,0), (4,4,1), (4,8,0),
               (8,2,0), (8,4,0), (8,8,1) ])

x, xrank = np.unique(l[:,0], return_inverse = True)
y, yrank = np.unique(l[:,1], return_inverse = True)

a = np.zeros((max(xrank)+1, max(yrank)+1))
a[xrank,yrank] = l[:,2]

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

ax.pcolor(x, y, a)
plt.show()

rawDescription: Converting a list of (x,y,z) tuples spaced on a square lattice to an array


code:
def return_equals(*arrays):
    matched = reduce(np.intersect1d, arrays)
    return np.array([np.where(np.in1d(array, matched))[0] for array in arrays])

rawDescription: Most efficient way to implement numpy.in1d for muliple arrays


code:
from itertools import product

my_dict = {'a':[1,2], 'e':[7], 'f':{'x':[{'a':[3,5]}, {'a':[4]}] } }

def process(d):
    to_product = []  # [[('a', 1), ('a', 2)], [('b', 3),], ...]
    for k, v in d.items():
        if isinstance(v, list) and all(isinstance(i, dict) for i in v):
            # specific case, when list of dicts process differently...
            c = product(*list(process(i) for i in v))
            to_product.append([(k, list(l)) for l in c])
        elif isinstance(v, list):
            to_product.append([(k, i) for i in v])
        elif isinstance(v, dict):
            to_product.append([(k, i) for i in process(v)])
        else:
            to_product.append([(k, v)])
    return [dict(l) for l in product(*to_product)]

for i in process(my_dict):
    print(i)

rawDescription: Split python dictionary to result in all combinations of values


code:
df = pd.DataFrame(data)
df.columns = ['Date','Profit']
df['Date'] = pd.to_datetime(df['Date'])
df['weekofyear'] = df['Date'].dt.weekofyear
df.reset_index('Date')
df.sort_index(inplace=True)
df['Weekly_Cum'] = df.groupby('weekofyear').cumsum()

rawDescription: How to do a rolling aggregation of data week wise in python?

description: Do a rolling aggregation of data week wise in python


code: api_sig = api_sig + String.Format("{0:X2}", hashValue(i))

rawDescription: hmacsha1 output hex strings different between vb.net and python

description: Hmacsha1 output hex strings different between vb.net and python


code:
query1 = "(\"SELECT table_schema, table_name, create_time FROM information_schema.tables WHERE table_schema='{$_DVWA['db_database']}' AND table_name='users' LIMIT 1\");"
re.findall(r"='(\{?\$.+?)(?:'(?:\s|;))", query1)
re.findall(r"='(\{?\$.+?)(?:'(?:\s|;))", query)

rawDescription: Regex capturing inserted variables in PHP SQL string statements


code:
from collections import defaultdict
data = defaultdict(list)
for line in file:
    line = line.split('\t')
    data[line[0]].append(line[2])

rawDescription: UPDATE: Calculate vector length according to str value in specific column in Python


code:
fastaDict1 = {'seq1': 'NNNACACGT', 'seq2': 'NNNACACGT'}
fastaDict2 = {'seq1': 'NNNGCACGT'}
for keys in fastaDict1.keys():
    print(keys)
    if keys in fastaDict2:
        for base in range(0, len(fastaDict1[keys])):
            if fastaDict1[keys][base] != 'N' and fastaDict1[keys][base] == fastaDict2[keys][base]:
                print(fastaDict1[keys][base] + '\t' + fastaDict2[keys][base] + '\t' + str(base))
            else:
                print('Bases do not match' + '\t' + str(base))

rawDescription: Multiple conditions to compare values of two dictionaries in python


code:
def circled(x):
    return chr(0x245F+x)    # Python 2: use unichr() instead of chr()

rawDescription: Plot special character as ① in matplotlib


rawDescription: regex: match text between two strings, but farthest right string

description: Regex: match text between two strings, but farthest right string


rawDescription: Is there a way to prevent a python 3 script from being called in python 2?


rawDescription: Count number of rows in a many-to-many relationship (SQLAlchemy)


rawDescription: Python identify file with largest number as part of filename


code:
import logging

logger = logging.getLogger('testlog')
handler = logging.FileHandler('\\path\\to\\testlog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

logger.error("some error occurred")
logger.info('some info msg')
logging.disable(logging.ERROR)
logger.info('another info msg')
logging.disable(logging.NOTSET)
logger.info('last info msg')

rawDescription: How to undo a logging.disable() command in logging module in Python?

description: Undo a logging.disable() command in logging module in Python


rawDescription: Can a tkinter button return a value from an entry on-click?


rawDescription: Python combinations of overlapping pairs on a list


code: data = [p.text_content() for p in tree.xpath('//p')]

rawDescription: HTML parsing with lxml - how to keep empty content in resulting list?


code:
from numpy.polynomial import Polynomial as P
p1 = P([1,1])
p2 = P([1,1,1])
p2(p1)
p1(p2)

rawDescription: evaluating numpy polynomials at other polynomials

description: Evaluating numpy polynomials at other polynomials


code: my_new_list = zip(my_list[0::2], my_list[1::2])

rawDescription: list of ints into a list of tuples python

description: List of ints into a list of tuples python


code: A & B

rawDescription: How to map numpy arrays to one another?

description: Map numpy arrays to one another


code:
from celery import Celery, chain
celery_app = Celery('my_tasks', broker='amqp://', backend='amqp://')

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

@celery_app.task()
def sub(x, y):
    return x - y

c = chain(add.s(3, 4), sub.s(2))

rawDescription: Logging task relationships in Celery

description: Logging task relationships in Celery


code:
import subprocess

subprocess.call(['curl', myLink, '-F', myFile])

rawDescription: Is it possible to make such a request with extra options in Python?


rawDescription: Parsing strings of date ranges in Pandas


code:
class AdminModel(admin.ModelAdmin):
    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

rawDescription: Django: Admin action choices

description: Django: Admin action choices


rawDescription: Django Inheriting from classes

description: Django Inheriting from classes


rawDescription: Best data structure for 3D data?

description: Best data structure for 3D data


code:
import random
from collections import Counter
days_week = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat']
random_list = [random.choice(days_week) for x in range(10)]
random_list
c = Counter(random_list)
c.most_common(1)[0][0]
[c.get(k, 0) for k in days_week]
c.most_common(1)[0][0], [c.get(k, 0) for k in days_week]

rawDescription: Tuple of string and list

description: Tuple of string and list


code:
sub =  response.xpath("//td[@class='dosechart-substance']/a/text()").extract_first()
dose =  response.xpath("//td[@class='dosechart-amount']/text()").extract_first()
form =  response.xpath("//td[@class='dosechart-form']/b/text()").extract_first()
weight =  response.xpath("//td[@class='bodyweight-amount']/text()").extract_first()
sub, dose, form, weight

rawDescription: Scraping data from a table in drug reports with scrapy


code:
def lcs(x, y):
    '''returns the length of longest common subsequence of x and y.
       >>> lcs('abcde','aebd')
       3
    '''
    s_x, s_y = len(x), len(y)
    if s_x>s_y:
        x, y = y, x
        s_x, s_y = s_y, s_x
    y_previous = s_x*[0]
    for y_char in y:
        left_value = 0
        diagonal_value = 0
        n=0
        for x_char in x:
            up_value = y_previous[n]
            if y_char==x_char:
                left_value = diagonal_value+1
            else:
                if left_value<up_value:
                    left_value = up_value
            diagonal_value = up_value
            y_previous[n] = left_value
            n+=1
    return y_previous[-1]

rawDescription: Bound of longest common sub sequence

description: Bound of longest common sub sequence


code: new_val = old_dest * old_source / 256

rawDescription: Pygame and blitting: white on white = gray?


code:
grouped.size()
grouped.size().idxmax()

rawDescription: Pandas group by operations on a data frame


code:
id(df1.index), id(df2.index)
id(df1.index.values), id(df2.index.values)

rawDescription: When I shuffle a copy of a DataFrame, why the original DataFrame is also shuffled?


code:
import unittest
from flask import Flask, redirect, url_for, request
from flask.ext.login import login_required
from flask_login import LoginManager, UserMixin, login_user, current_user

class TestApp(unittest.TestCase):
    def setUp(self):
        app.testing = True

    def tearDown(self):
        app.testing = False

    def test_login(self):
        with app.test_client() as c:
            r = c.post('/login', data={'id': 400617}, follow_redirects=True)
            # current_user is only set in context
            self.assertEqual(current_user.id, 400617)

        # resopnse doesn't depend on context, so can be tested outside block
        self.assertEqual(r.status, '200 OK')
        # any non-anonymous user is authenticated, even if not logged in
        self.assertTrue(User(123).is_authenticated)

app = Flask(__name__)
app.secret_key = 'Stack Overflow'
login = LoginManager(app)
login.login_view = 'login'

class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login.user_loader
def user_loader(id):
    return User(int(id))

@app.route('/')
@login_required
def index():
    return 'index'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User(id=request.form.get('id', type=int))
        login_user(user)
        return redirect(url_for('index'))

    return 'login'

description: Flask-Login is_authenticated inconsistency


code:
class SampleSetFilter(django_filters.FilterSet):
    multi_field_search = MultiFieldFilter(names=["field_foo", "bar", "baz"],lookup_type='in')
    class Meta:
        model = SampleSet
        fields = ('multi_field_srch',)

rawDescription: Search fields in multiple models in Django


rawDescription: Python - removing characters from a list


code: data = np.load(content)

rawDescription: numpy's tostring/fromstring --- what do I need to specify to restore the array

description: Numpy's tostring/fromstring --- what do I need to specify to restore the array


code:
segmentCount = 0
def payload_write(f, *args, **kwargs):
    global segmentCount
    segmentCount += 1
    return f.write(*args, **kwargs)

rawDescription: Python Increasing counter by 1 every time something is written to a file


rawDescription: Extracting username in IRC logs with regex?


code:
a
b
out

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


code:
from IPython.core.magic import  (
    Magics, magics_class, cell_magic, line_magic
)

@magics_class
class StoreSQL(Magics):

    def __init__(self, shell=None,  **kwargs):
        super().__init__(shell=shell, **kwargs)
        self._store = []
        # inject our store in user availlable namespace under __mystore
        # name
        shell.user_ns['__mystore'] = self._store

    @cell_magic
    def sql(self, line, cell):
        """store the cell in the store"""
        self._store.append(cell)

    @line_magic
    def showsql(self, line):
        """show all recorded statements"""
        print(self._store)

    ## use ipython load_ext mechanisme here if distributed
    get_ipython().register_magics(StoreSQL)

rawDescription: Read cell content in an ipython notebook


code:
import operator

for fn in os.listdir(path):

    if fn[0] == '.':
        continue

    try:
        p = os.path.join(path, fn)
    except:
        continue

    s = os.lstat(p)

    if stat.S_ISDIR(s.st_mode):
        l.append((fn, build_tree(p)))
    elif stat.S_ISREG(s.st_mode):
        l.append((fn, s.st_size))

rawDescription: I want to use Python to list a directory, then sort the filenames by size


rawDescription: modifying elements list of tuples python

description: Modifying elements list of tuples python


rawDescription: np.subtract.outer() returning more dimensions than I expect

description: Np.subtract.outer() returning more dimensions than I expect


code:
import glob
images = glob.glob('*.png')

rawDescription: Pre-loading images pygame

description: Pre-loading images pygame


code:
def uprod(*seqs):
    def inner(i):
        if i == n:
            yield tuple(result)
            return
        for elt in sets[i] - seen:
            seen.add(elt)
            result[i] = elt
            for t in inner(i+1):
                yield t
            seen.remove(elt)

    sets = [set(seq) for seq in seqs]
    n = len(sets)
    seen = set()
    result = [None] * n
    for t in inner(0):
        yield t

rawDescription: itertools.product eliminating repeated elements

description: Itertools.product eliminating repeated elements


code:
from unittest.mock import *
m0, m1 = Mock(), Mock()
m = Mock()
m.m0, m.m1 = m0, m1
m0()
m1()
m.mock_calls

rawDescription: Python Unit Testing with two mock objects, how to verify call-order?


code:
import struct
from datetime import date
date(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))

rawDescription: How to unpack binary formatted dates in python?

description: Unpack binary formatted dates in python


code:
import numpy as np
{np.array([1])}

rawDescription: Python set literals didn't work on numpy unique array


rawDescription: Add all elements of an iterable to list

description: Add all elements of an iterable to list


code: '   hello world with 2 spaces and a tab!'.lstrip(' ')

rawDescription: Removing starting spaces in Python?

description: Removing starting spaces in Python


code: 'abcdefabcd'.translate(None, 'acd')

rawDescription: Filtering Characters from a String

description: Filtering Characters from a String


code:
def getLowerTriangularIndices(n):
    return [list(x) for x in np.tril_indices(n)]

rawDescription: fast way to get the indices of a lower triangular matrix as 1 dimensional list in python

description: Fast way to get the indices of a lower triangular matrix as 1 dimensional list in python


code:
my_list = [1, 2, 3, ..., 40]
array = [[my_list[j*5 + i] for i in range(5)] for j in range(8)]

rawDescription: How to store and print a list of numbers in matrix form(python)

description: Store and print a list of numbers in matrix form(python)


rawDescription: Python: Replacing NaN or MEAN instead of a -999 value in an array


code: filter(lambda i: i in ('FR', 'SO'), mylist)

rawDescription: Filtering though a list (Python)

description: Filtering though a list (Python)


code:
## For example, I have 9 daily value during 2013-04-01 to 2014-04-10
start = datetime.datetime.strptime("01-04-2013", "%d-%m-%Y")
end = datetime.datetime.strptime("10-04-2013", "%d-%m-%Y")
date = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

plt.figure(figsize=(12,4))
## y is the data I want to plot
ind = np.arange(len(y))
ax=plt.subplot()
plt.plot(ind,y,lw = 3)
k = []
for i in range(0,len(ind),1):
    k.append(str(date[i])[0:10])

plt.xticks(ind,k,rotation=65)

rawDescription: Python Matplotlib scatter plot adding x-axis labels


code:
import re
p = re.compile(r'(?P<perf_name>\w*)\((?P<perf_params>\w*(?:,\w+)*)\)')
s = "function_1(param_1,param_2,param_3)+function_2(param_4,param_5)*function_3(param_6)+function_4()-function_5(param_7,param_8,param_9,param_10)"
res = [(x.group("perf_name"), x.group("perf_params").split(",")) for x in p.finditer(s)]
print(res)
# => [('function_1', ['param_1', 'param_2', 'param_3']), ('function_2', ['param_4', 'param_5']), ('function_3', ['param_6']), ('function_4', ['']), ('function_5', ['param_7', 'param_8', 'param_9', 'param_10'])]

rawDescription: regex of symbolic expression grouped

description: Regex of symbolic expression grouped


code:
test
test_sorted
out

rawDescription: Fastest way to group by ID for a really big numpy array


code: MultiIndex.from_tuples(sum(couples, []), names=('first', 'second'))

rawDescription: How to create a multiIndex object from series?

description: Create a multiIndex object from series


code:
url(r'^trending/(?P<song_name>.+)-(?P<artist_slug>.+)-(?P<song_id>.+)/$',
                                  songs.trending_song, name='trending_song'),

rawDescription: Incorrect Django URL pattern match for 2 views with the same URL structure?


code:
def make_foo(value):
    result = Foo()
    result.bar = value()
    return result

rawDescription: Add attribute to python class

description: Add attribute to python class


rawDescription: Create a Pandas dataframe with counts of items spanning a date range


code:
import sys
import A
myfuncs=A.f(sys.modules[__name__])

rawDescription: How can A.f defined in module A get list of function defined in B if A.f was called from B


code:
def decode(file):
    while True:
        c = file.read(1)
        if c == "":
            # End of file
            break
        if c != "%":
            # Not an escape sequence
            yield c
            continue
        c = file.read(1)
        if c != "u":
            # One hex-byte
            yield chr(int(c + file.read(1), 16))
            continue
        # Two hex-bytes
        yield chr(int(file.read(2), 16))
        yield chr(int(file.read(2), 16))

rawDescription: Unescape/unquote binary strings in (extended) url encoding in python


code:
def first(xs):
    return xs[0]

def second(xs):
    return xs[1]

rawDescription: How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?

description: Achieve two separate list of lists from a single list of lists of tuple with list comprehension


code:
import cv2
from cv2 import matchTemplate as cv2m

M = cv2m(field_array.astype('uint8'),match_array.astype('uint8'),cv2.TM_SQDIFF)
R,C = np.where(M==0)

rawDescription: How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?

description: Check if one two-dimensional NumPy array contains a specific pattern of values inside it


code:
offset = transforms.ScaledTranslation(0.0, 0.5, fig.dpi_scale_trans)
new_transform = ax.transData + offset
sankey.add(flows=[-0.25, 0.15, 0.1], fc='#37c959', label='two',
           orientations=[-1, -1, -1], prior=0, connect=(0, 0),
           transform = new_transform)

rawDescription: Matplotlib: Is it possible to create an new axis with a given y-offset, without creating subplot?


code: re.sub(findthe, lambda matchObj: replacement.pop(0),sentence)

rawDescription: Replacing each match with a different word


code:
if files:
    elementId = basename(normpath(path)) + "Audio"
    jsonObject.append({
      "elementId" : elementId,
      "params" : {
         "audioPath" : path,
         "sounds" : list(files)
         },
      })

rawDescription: Inserting values into specific locations in a json file with Python


code:
lbl_f = Frame(nb)
Label(lbl_f, text="This label is in a grid").grid(pady=100,sticky='ew')
lbl_f.grid()
lbl_f.rowconfigure('all', weight=1)
lbl_f.columnconfigure('all', weight=1)

rawDescription: expand within notebook does not work as expected

description: Expand within notebook does not work as expected


code:
import sys

etree.ElementTree(parse(sys.stdin)).write(sys.stdout, method='html')

rawDescription: Convert tabbed text to html unordered list?


code:
from collections import OrderedDict

data = """0.0 99.13 0.11
0.5 19.67 0.59
1.0 9.67  0.08
0.5 22.23 1.22""".split('\n')

d = OrderedDict()
for line in data:
    split = line.split(' ', 1)
    d.setdefault(split[0], []).extend(split[1:])

print(d)

rawDescription: Using duplicates to create different text files


code:
Python
import time
import ctypes
start_time = time.time()

x = 0
while x <= 1000000:
    x = x + 1

x = ("--- %s seconds ---" % (time.time() - start_time))
ctypes.windll.user32.MessageBoxA(0, x, "Your title", 1)

rawDescription: Python loop slower than Excel VBA?

description: Python loop slower than Excel VBA


code: test_ctr = test.copy()

rawDescription: Modifying values of small slice of a column


code:
parser = ArgumentParser()
parser.add_argument("function",
                    nargs="?",
                    choices=['function1', 'function2', 'function2'],
                    default='function1',
                    )
args, sub_args = parser.parse_known_args()

if args.function == "function1":
    parser = ArgumentParser()
    parser.add_argument('-a','--a')
    parser.add_argument('-b','--b')
    parser.add_argument('-c','--c')
    args = parser.parse_args(sub_args)
    function1(args.a, args.b, args.c)
elif args.function == "function2":
    ...
elif args.function == "function3":
    ...

rawDescription: Use argparse to call different functions


code: msvcrt.printf(b"%s", string)

rawDescription: Python3k ctypes printf

description: Python3k ctypes printf


code: a = np.array(a)

rawDescription: Initialize empty list with same shape as array


code:
print('\n') # Prints a newline character
print(r'\n') # Escape sequence is not processed
print('\b') # Prints a backspace character
print(r'\b') # Escape sequence is not processed

rawDescription: What does 'r' mean before a Regex pattern?


code:
keys = [key for (key, _) in orig]
weights = [weight for (_, weight) in orig]

rawDescription: Numpy Histogram | Use one dimension to match bin, and another for the actual frequency


code:
import numpy as np
import itertools
import csv

year = np.repeat((1980, 1990 , 2000, 2010), 10)
sex = np.array(['male', 'female']*20)
disease = np.repeat(('d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8'), 5)
draws = np.random.normal(0, 1, size=(sex.shape[0], 1000))

years=np.unique(year)
diseases=np.unique(disease)

draw_sums = dict(((y,d), draws[(year==y)&(disease==d)].sum(axis=0))
                  for y,d in itertools.product(years,diseases))

rawDescription: Summing Arrays by Characteristics in Python


code:
import numpy as np
np.array([[int(i) for i in line.split()] for line in data])
np.array([int(i) for line in data for i in line.split()]).reshape((3, 6))

rawDescription: list comprehension replace for loop in 2D matrix

description: List comprehension replace for loop in 2D matrix


code:
def calc_superfast(L1, L2):
    return np.dot(np.array(L1).sum(0),
                  np.array(L2).sum(0))

rawDescription: efficient algorithm instead of looping

description: Efficient algorithm instead of looping


code: df['ORG1'][mask] = 'A'

rawDescription: Moving row values between columns based on other column values in a Pandas DataFrame


code:
import cgi
import webapp2
import logging
import os, csv
from models import DataStoreModel
import StringIO
from google.appengine.api import app_identity
from mapreduce import base_handler
from mapreduce import mapreduce_pipeline
from mapreduce import operation as op
from mapreduce.input_readers import InputReader

def testmapperFunc(newRequest):
    f = StringIO.StringIO(newRequest)
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        newEntry = DataStoreModel(attr1=row[0], link=row[1])
        yield op.db.Put(newEntry)

class TestGCSReaderPipeline(base_handler.PipelineBase):
    def run(self, filename):
        yield mapreduce_pipeline.MapreducePipeline(
                "test_gcs",
                "testgcs.testmapperFunc",
                "mapreduce.input_readers.FileInputReader",
                mapper_params={
                    "files": [filename],
                    "format": 'lines'
                },
                shards=1)

class tempTestRequestGCSUpload(webapp2.RequestHandler):
    def get(self):
        bucket_name = os.environ.get('BUCKET_NAME',
                                     app_identity.get_default_gcs_bucket_name())

        bucket = '/gs/' + bucket_name
        filename = bucket + '/' + 'tempfile.csv'

        pipeline = TestGCSReaderPipeline(filename)
        pipeline.with_params(target="mapreducetestmodtest")
        pipeline.start()
        self.response.out.write('done')

application = webapp2.WSGIApplication([
    ('/gcsupload', tempTestRequestGCSUpload),
], debug=True)

rawDescription: How to upload data in bulk to the appengine datastore? Older methods do not work

description: Upload data in bulk to the appengine datastore? Older methods do not work


code:
import lxml.html as lh

content='''\

Component
Status
Time / Error

SAVE_DOCUMENT	OK	0.408 s

GET_DOCUMENT	OK	0.361 s

DVK_SEND	OK	0.002 s

DVK_RECEIVE	OK	0.002 s

GET_USER_INFO	OK	0.135 s

NOTIFICATIONS	OK	0.002 s

ERROR_LOG	OK	0.001 s

SUMMARY_STATUS	OK	0.913 s

'''
tree=lh.fromstring(content)
for key, status, t in zip(*[iter(tree.xpath('//td/text()'))]*3):
    print('''{k}_STATUS = "{s}"
{k}_TIME = "{t}"'''.format(k=key,s=status,t=t.rstrip(' s')))

rawDescription: Extract data from HTML table using Python


code: x = df.reset_index(); x[x.RPT_Date.str.endswith("0630")].set_index(['STK_ID', 'RPT_Date'])

rawDescription: How to filter by sub-level index in Pandas

description: Filter by sub-level index in Pandas


code: dh = grouped['VALUE'].aply(lambda s: pd.Series(seriesFeatures(s)))

rawDescription: Splitting a column whose elements are dictionaries into many columns


code: ts[np.concatenate(([True], np.diff(ts.index.year) != 0))] += 1

rawDescription: Pandas Time Series - add a value to the first value in each year


code: user_key = db.Key.from_path('UserInfo', user_id)

rawDescription: ReferenceProperty filter

description: ReferenceProperty filter


code: result = elements[:n] + elements[n+1:]

rawDescription: How to get all the elements in the list without an element at a specific index in python?

description: Get all the elements in the list without an element at a specific index in python


code: uniques = df[['i1','i2']].apply(lambda x:frozenset(x),axis=1)

rawDescription: Hierarchical index multi index containing edge values. Rearrange it?


rawDescription: Find min and max value of any function over an interval


code:
i = raw_input(">>> ")
e = i.lower().split()
af.inp.append(e)

# greeting section
if any(x in e for x in af.x):
    af.greeting()

rawDescription: Error while checking if a string contains an element from a list in Python?


code:
from sympy.physics.vector import ReferenceFrame
from sympy.physics.vector import curl
R = ReferenceFrame('R')

F = R[1]**2 * R[2] * R.x - R[0]*R[1] * R.y + R[2]**2 * R.z

G = curl(F, R)

rawDescription: Calculate curl of a vector field in Python and plot it with matplotlib


code:
counting=0
for comb in combinations(range(1,36), 7):
    if count_consecutive(comb) not in [5, 6, 7]:
        print (comb)
        counting+=1
print (counting)

rawDescription: Count the number of results

description: Count the number of results


code:
with open('file') as f:
    a = f.read().splitlines()

l = [a[i][:i] for i in range(len(a))]
final_list = [''.join(i) for i in zip(*l)][1:]  # since the first element in the list will be empty (`''`), remove it.

print(final_list)

rawDescription: Reading from a file diagonally and having the diagonal characters create a list


code:
import json
datastring = json.dumps(data)
datastring
json.loads(datastring)

rawDescription: How do I store account information in python so that it can be accessed later?

description: Store account information in python so that it can be accessed later


code:
from ctypes import *
# ... Skipped a lot of code which is the same as before...
STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)
windll.Kernel32.GetStdHandle.restype = c_ulong
std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)
textText    = 11
greenText   = 10
defaultText = 15
class PS1(object):
    def __repr__(self):
        # ... Skipping a lot of code which is the same as before ...
        windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, tealText)
        sys.stdout.write(clock)
        windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, greenText)
        sys.stdout.write(" >>> ")
        windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, defaultText)
        return ""

rawDescription: Colored Python Prompt in Windows?

description: Colored Python Prompt in Windows


rawDescription: Detect definition path of a decorated function


code:
start_index = my_list.index(next(e for e in my_list if search_str in e))
end_index = my_list.index(next(e for e in my_list[start_index + 1:] if search_str in e))

rawDescription: Python Array Copying From Word To Word

description: Python Array Copying From Word To Word


code:
import matplotlib.pyplot as plt
import networkx as nx
socialNetworl = nx.Graph()
socialNetworl.add_nodes_from([1,2,3,4,5,6])
socialNetworl.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6)])
nx.draw(socialNetworl, node_size = 800, node_color="cyan", with_labels = True)
plt.show()

rawDescription: I can't see labels in NetworkX diagram

description: I can't see labels in NetworkX diagram


code:
import glob

for fn in glob.glob('*.py'): print(fn)

rawDescription: Finding files in directories in Python

description: Finding files in directories in Python


code:
#execmaker.py would be the name of this file
#stable version
from distutils.core import setup
import py2exe

includes = []
excludes = ['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
            'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
            'Tkconstants', 'Tkinter']
packages = []
dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll',
                'tk84.dll']

setup(
    options = {"py2exe": {"compressed": 2,
                          "optimize": 2,
                          "includes": includes,
                          "excludes": excludes,
                          "packages": packages,
                          "dll_excludes": dll_excludes,
                          "bundle_files": 3,#dont bundle else unstable
                          "dist_dir": "dist",
                          "xref": False,
                          "skip_archive": False,
                          "ascii": False,
                          "custom_boot_script": '',
                         }
              },
    windows=['My_Script.py'] #this is the name of your actual script
)

rawDescription: Compiling a python script I've written as an .exe and .app


code:
if __name__ == '__main__':
    # <-- No need to put things here, unless you want them to run before
    # the app is ran (e.g. you need to initialize something)

    app.run()

rawDescription: Run Python Script into Flask

description: Run Python Script into Flask


rawDescription: Turning a list into a string or a word

description: Turning a list into a string or a word


rawDescription: How can I get absolute difference of two numbers?

description: Get absolute difference of two numbers


code:
def orig_samp(refs, lim=10000):

    # Initialize empty final list.
    b = []

    a1 = np.random.random(10000)

    # Run until the condition is met.
    while (sum(b) < lim):

        # Draw random [0,1) value.
        u = np.random.random()
        # Find closest value in sub-list a[1].
        idx = np.argmin(np.abs(u - a1))
        # Store value located in sub-list a[0].
        b.append(refs[idx])

    return b

rawDescription: Speed up loop to fill an array with closest values from another array


rawDescription: Python, SQLite3: cursor returns duplicates when a commit intervenes


code: vector = np.fromiter((1 for ele in long_list if condition), dtype=int)

rawDescription: better way to vectorize using numpy

description: Better way to vectorize using numpy


code:
def find_position(astring, acharacter):
    positions = []
    for c in range(len(astring)):
        if astring[c] == acharacter:
            positions.append(c)
    return positions

rawDescription: Find a character in multiple places python


code:
columns = ["User Name", "Source", "Staff", "Location", "Attended On", "Used", "Date"]
table = []

for row in table_1.find_all('tr'):
    tds  = row.find_all('td')
    try:
        data = [td.get_text() for td in tds]
        for field,value in zip(columns, data):
            print("{}: {}".format(field, value))
        table.append(data)
    except:
        print("Bad string value")

rawDescription: scraping a table then writing to csv

description: Scraping a table then writing to csv