code:
...

wm = pyinotify.WatchManager()
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler, timeout=10)
wm.add_watch(PATH, pyinotify.IN_MODIFY, rec=True)

while True:
    # Do something unrelated to pyinotify
    time.sleep(5)

    notifier.process_events()
    #loop in case more events appear while we are processing
    while notifier.check_events():
        notifier.read_events()
        notifier.process_events()

rawDescription: Read new line with pynotify

description: Read new line with pynotify


code:
df = rdd.toDF(sampleRatio=0.2)
# or...
df = sqlContext.createDataFrame(rdd, samplingRatio=0.2)

rawDescription: saving a list of rows to a Hive table in pyspark

description: Saving a list of rows to a Hive table in pyspark


rawDescription: Python Find all letter chars in string and surround with text


code:
import numpy as np
a = np.arange(24).reshape((4,6))
a
a.reshape((2,a.shape[0]//2,3,-1)).mean(axis=3).mean(1)

rawDescription: resize with averaging or rebin a numpy 2d array

description: Resize with averaging or rebin a numpy 2d array


code:
@coroutine
def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
    future = futures.Future(loop=loop)
    h = future._loop.call_later(delay, future.set_result, result)
    try:
        return (yield from future)
    finally:
        h.cancel()

rawDescription: Python asyncio: return vs set_result

description: Python asyncio: return vs set_result


code:
import ghdiff
diff_as_html = ghdiff.diff(md1,md2)

rawDescription: How to compare two models to be rendered with Markdown using Django?

description: Compare two models to be rendered with Markdown using Django


code:
import os
print(os.__dict__)
os.__dict__[new_set_name] = set()
setattr(os, new_set_name, set())

rawDescription: How to access the string stored in the variable? (Python)

description: Access the string stored in the variable? (Python)


code:
root = Node(tag=ex[0])
from_list(ex[1:], root=root)

rawDescription: defining multi branching nested tree in python recursively

description: Defining multi branching nested tree in python recursively


code:
import os
from flask.ext import assets
from app import app

env = assets.Environment(app)

# Tell flask-assets where to look for our coffeescript and sass files.
env.load_path = [
    os.path.join(os.path.dirname(__file__), 'js'),
    os.path.join(os.path.dirname(__file__), 'styles'),
]

coffee = assets.Bundle('**/*.coffee', filters='coffeescript', output="app.js")
env.register('coffee', coffee)

rawDescription: Using Flask-Assets with Flask-Mako

description: Using Flask-Assets with Flask-Mako


code: a = ['cat', 'dog', 'mouse'];

rawDescription: Finding and substituting a list of words in a file using regex in Python


code:
length_freq = collections.Counter(lengths)
((best_length, _),) = length_freq.most_common(1)

rawDescription: Total number of similar items which meet uniqueness criteria


code: True

rawDescription: Numpy: outer product of n vectors

description: Numpy: outer product of n vectors


code:
with open("match.txt", "w") as f:
    for sub, cont in od.items():
        f.write(sub)
        f.writelines(cont)

rawDescription: I want to list up string in python followed example


rawDescription: How to create an 'contact book' in python using dictionaries?

description: Create an 'contact book' in python using dictionaries


rawDescription: How to override default help message on python function

description: Override default help message on python function


code:
class AbstractHTTPHandler(BaseHandler):
    # ...
    def do_open(self, http_class, req):
        # ...
        h = http_class(host, timeout=req.timeout) # will parse host:port

rawDescription: Python CURL speficied ip address

description: Python CURL speficied ip address


code: result = to_sparse_pivot(df, 'id', 'item', 'count')

rawDescription: How to create dummy variable and then aggregate using scikit-learn?

description: Create dummy variable and then aggregate using scikit-learn


code:
pad = 100
og = np.pad(og, pad, mode='constant')
new_ker = np.zeros_like(og)
new_ker[:nx//2,:nx//2] = ker[:nx//2,:nx//2]
new_ker[:nx//2,-nx//2:] = ker[:nx//2,-nx//2:]
new_ker[-nx//2:,:nx//2] = ker[-nx//2:,:nx//2]
new_ker[-nx//2:,-nx//2:] = ker[-nx//2:,-nx//2:]
ker = new_ker

# doesn't change
v1 = np.fft.fft2(ker)
v2 = np.fft.fft2(og)
v0 = np.fft.ifft2(v1*v2)

# unpadding the result
v0 = v0[pad:-pad,pad:-pad]

rawDescription: Python 2D convolution without forcing periodic boundaries


code:
soft = os.environ['SERVER_SOFTWARE']
ver = soft[soft.find('/')+1:]  # Either '1.8.8' or '2.0' depending on version.

rawDescription: How to programatically get the SDK version in Google Appengine (Python)?

description: Programatically get the SDK version in Google Appengine (Python)


code:
from __future__ import division
import Tkinter as tk

def joules(wavelength, freq_out, energy_out):
    freq = 299792458 / wavelength
    energy = 6.62606957e-34 * freq

    freq_out.set("Frequency: %g" % freq)
    energy_out.set("Energy: %g" % energy)

def main():
    mainwin = tk.Tk()
    mainwin.title("Wave1")

    wavelength = tk.IntVar()
    tk.Entry(mainwin, textvariable=wavelength).pack()

    freq = tk.StringVar()
    tk.Label(mainwin, textvariable=freq).pack()

    energy = tk.StringVar()
    tk.Label(mainwin, textvariable=energy).pack()

    button = tk.Button(mainwin, text="Joules", command=lambda:
                joules(wavelength.get(), freq, energy)).pack()

    mainwin.mainloop()

if __name__ == "__main__":
    main()

rawDescription: Fetching a number from an Entry widget and running it through a function called by a button in Python 2 Tk


code:
def int2dot( intip ):
    return '.'.join([ str( (intip>>x*8) & 0xFF ) for x in [3,2,1,0]])
def dot2int( dotip ):
    return reduce( lambda r,x: int(x)+(r<<8), dotip.split('.'), 0 )

def merge_ip_list(ip_list):
    if not ip_list:
        return []
    orig = map(dot2int,ip_list)
    orig.sort()
    start = orig[0]
    prev = start-1
    res = []
    for x in orig:
        if x != prev+1:
            res.append((int2dot(start),int2dot(prev)))
            start = x
        prev = x
    res.append((int2dot(start),int2dot(prev)))
    return res

rawDescription: Python - convert list of IP addresses to a list of address ranges


rawDescription: Python word game. Last letter of first word == first letter of second word. Find longest possible sequence of words


code:
class PythonObjectEncoder(json.JSONEncoder):
    def default(self, obj):
        return {'_python_object': pickle.dumps(obj).decode('latin1')}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(dct['_python_object'].encode('latin1'))
    return dct

data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'},
        Decimal('3.14')]
j = json.dumps(data, cls=PythonObjectEncoder, indent=4)
data2 = json.loads(j, object_hook=as_python_object)
assert data == data2  # both should be same

rawDescription: Making object JSON serializable with regular encoder


code:
#!/usr/bin/env python2.7

import csv

with open('xyz.csv', 'wb') as outfile:
      w = csv.writer(outfile)
      w.writerow(['stringa','multiline\015string',])

rawDescription: Mulitple Lines in a single Excel cell

description: Mulitple Lines in a single Excel cell


code:
projects = ProjectComment.select_related('user', 'user__profile').exclude(user__isnull=True).all()

for project in projects:
    users = [user for user in project.user.all()]

rawDescription: Using Django ORM to get a related model in a method


code:
import subprocess
output = subprocess.check_output(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'])

rawDescription: How to store the result of an executed shell command in a variable in python?

description: Store the result of an executed shell command in a variable in python


code:
@db.collation()
def collate_case_insensitive(s1, s2):
    return cmp(s1.lower(), s2.lower())

rawDescription: Case insensitive sort with peewee

description: Case insensitive sort with peewee


code:
es_logger = logging.getLogger('elasticsearch')
es_logger.propagate = False
es_logger.setLevel(logging.INFO)
es_logger_handler=logging.handlers.RotatingFileHandler('top-camps-base.log',
                                                      maxBytes=0.5*10**9,
                                                      backupCount=3)
es_logger.addHandler(es_logger_handler)

es_tracer = logging.getLogger('elasticsearch.trace')
es_tracer.propagate = False
es_tracer.setLevel(logging.DEBUG)
es_tracer_handler=logging.handlers.RotatingFileHandler('top-camps-full.log',
                                                   maxBytes=0.5*10**9,
                                                   backupCount=3)
es_tracer.addHandler(es_tracer_handler)

logger = logging.getLogger('mainLog')
logger.propagate = False
logger.setLevel(logging.DEBUG)
# create file handler
fileHandler = logging.handlers.RotatingFileHandler('top-camps.log',
                                               maxBytes=10**6,
                                               backupCount=3)
fileHandler.setLevel(logging.INFO)
# create console handler
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
consoleHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(consoleHandler)
logger.addHandler(fileHandler)

rawDescription: Logging using elasticsearch-py

description: Logging using elasticsearch-py


code:
people = range(10)
[p for i, p in enumerate(people, 1) if i % 3]

rawDescription: Controlling the flow of for loop in python


rawDescription: two question about python regular expressions

description: Two question about python regular expressions


code: self.dna_sequence = self.entry_1.get()

rawDescription: Can't find the AT content in percentage (tkinter, classes)


code:
import BeautifulSoup
html = "

"
soup = BeautifulSoup.BeautifulSoup(html)

rawDescription: How to get a nested element in beautiful soup

description: Get a nested element in beautiful soup


code:
import weakref

class CallListDescriptor(object):
    def __init__(self):
        self._class_level_values = weakref.WeakKeyDictionary()

    def __get__(self, instance, type):
        if instance is None:
            # class-level access
            try:
                return self._class_level_values[type]
            except KeyError:
                default = CallList()
                self._class_level_values[type] = default
                return default
        # instance-level access
        return instance._call_lists.setdefault(self, CallList())

class State(object):
    def __init__(self):
        # for the instance-level values
        self._call_lists = {}

    on_enter = CallListDescriptor()

rawDescription: Class variables and inheritance in Python


code:
#!/usr/bin/env python3

import re

routes = []
with open('routes.php', 'r') as f:
    current_comment = ''
    in_comment = False
    for line in f:
        line = line.lstrip()
        if line.startswith('/**'):
            in_comment = True

        if in_comment:
            current_comment += line

        if line.startswith('*/'):
            in_comment = False

        if line.startswith('Route::'):
            matches = re.search(r"Route::([A-Z]+)\('(.*)', '(.*)'\);", line)
            groups = matches.groups()
            routes.append({
                'comment': current_comment,
                'method': groups[0],
                'path': groups[1],
                'handler': groups[2],
            });
            current_comment = '' # reset the comment

print(routes)

rawDescription: Python 3 read file by part

description: Python 3 read file by part


code:
import requests
import getpass

from requests.auth import HTTPBasicAuth

username = raw_input('Username: ')
password = getpass.getpass('Password: ')

res = requests.post(
    'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken',
    auth=HTTPBasicAuth(username, password),  # basic authentication
    params={  # url parameters
        'grant_type': 'password',
        'username': 'email@address.com',
        'password': 'SomePassword'
    })

rawDescription: Using Python to test HTTP APIs

description: Using Python to test HTTP APIs


code: l = [f for f in os.listdir() if re.search(re1, f)]

rawDescription: select files from path

description: Select files from path


rawDescription: python gather together ascii and utf-8 stuff

description: Python gather together ascii and utf-8 stuff


code:
import datetime
'wordcount-' + datetime.datetime.now().strftime("%m%d%Y-%H") + '.txt'

rawDescription: Read files based on dates in their names in Python


code:
for row in reader:
    print(row)

rawDescription: Python script reading from a csv file

description: Python script reading from a csv file


rawDescription: Error while getting a file path using a dialog in PyQt


code: included = hg[hg["not inc"] == False]

rawDescription: Pandas days between in a single column

description: Pandas days between in a single column


code:
def decrypt_val(cipher_text):
    dec_secret = AES.new(MASTER_KEY[:32])
    raw_decrypted = dec_secret.decrypt(base64.b64decode(cipher_text))
    clear_val = raw_decrypted.rstrip("\0")
    return clear_val

rawDescription: Basic encrypt() and decrypt() function

description: Basic encrypt() and decrypt() function


code:
Entry.objects.filter(Q(start__range=(appointment.start, appointment.end)) |
    Q(end__range=(appointment.start, appointment.end)))

rawDescription: Django complex queries

description: Django complex queries


code:
# views.py
from django.db import connections
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from .models import Play

def graph(request):
    return render(request, 'graph/graph.html')

def play_count_by_month(request):
    data = Play.objects.all() \
        .extra(select={'month': connections[Play.objects.db].ops.date_trunc_sql('month', 'date')}) \
        .values('month') \
        .annotate(count_items=Count('id'))
    return JsonResponse(list(data), safe=False)

rawDescription: Passing data from Django to D3

description: Passing data from Django to D3


code:
class ProtectedAttribute(object):
    """Basic descriptor functionality for a protected attribute.

    Args:
      name (str): The name of the attribute to back the descriptor
        (usually the name the descriptor is assigned to with a single
        additional leading underscore).

    """

    def __init__(self, name, **kwargs):
        self.name = name

    def __get__(self, obj, typ):
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        setattr(obj, self.name, value)

    def __delete__(self, obj):
        delattr(obj, self.name)

rawDescription: Writing a function to define class properties


code:
@classmethod
@synchronized(lock)
def foo(cls):
    pass

rawDescription: Decorate a function after it is defined?

description: Decorate a function after it is defined


code:
from sympy.mpmath import odefun
from matplotlib import pyplot as plt
f = odefun(lambda x, y: x / (x**2 + y**2)**1.5, 0, 1)
X = range(1000)
listx = [f(x) for x in X]
plt.plot(X, listx)
plt.show()

rawDescription: Speed issues, python not responding: Solving ODEs


code:
from itertools import product

# pair info for each image with info of every image from another dictionary
for (fn1, d1), (fn2,d2) in product(dict1.iteritems(), dict2.iteritems()):
    for property_, list_value in d1.iteritems():
        compute_cosine_similarity(list_value, d2[property_])

rawDescription: Python: Iterate over two dictionaries that has lists as its values


rawDescription: Getting list of tags from Python minidom XML


code:
params = {'xt': 'urn:btih:%s' % b32hash,
          'dn': metadata['info']['name'],
          'tr': metadata['announce'],
          'xl': metadata['info']['length']}
import urllib
paramstr = urllib.urlencode(params)
magneturi = 'magnet:?%s' % paramstr
magneturi

rawDescription: Given a .torrent file how do I generate a magnet link in python?


code:
import csv
import calendar
from collections import defaultdict

months = [calendar.month_name[i] for i in range(0, 13)]
totals = defaultdict(int)

with open("data.csv", "r") as inf, open("data-out.csv", "w") as ouf:
    reader = csv.DictReader(inf)
    writer = csv.DictWriter(ouf, ['Name'] + months[5:9])
    writer.writeheader()
    for row in reader:
        m1 = months[int(row['Date1'].split('/')[0])]
        p2 = int(row['Price2'])
        totals[m1] += p2

        m2 = months[int(row['Date2'].split('/')[0])]
        p1 = int(row['Price1'])
        totals[m2] += p1

        writer.writerow({'Name': row['Name'], m1: p2, m2: p1})

    totals['Name'] = 'Total'
    writer.writerow(totals)

rawDescription: writing csv output python

description: Writing csv output python


rawDescription: Numpy built in elementwise append

description: Numpy built in elementwise append


code: any(v in X for v in (a, b, c))

rawDescription: python membership testing order by rarity

description: Python membership testing order by rarity


code:
import collections, json
data = json.loads(response_string, object_pairs_hook=collections.OrderedDict)

rawDescription: Converting to json re-orders objects in python


code: get_value(driver, "Issuer")

rawDescription: Selenium: Find adjacent elements

description: Selenium: Find adjacent elements


code:
import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def read(logfile):
    with open(logfile) as f:
        data = []
        while True:
            line = f.readline()
            time.sleep(0.1)
            if line:
                data.append(float(line.split(',')[1][:-2]))
                yield data

def animate(values):
    line, = plt.plot(values, color='blue')
    return line,

fig = plt.figure(figsize = (5,5))

ani = FuncAnimation(fig, animate, frames=read('log.txt'), interval=10)
plt.show()

rawDescription: How to chart live updates to logfile using matplotlib?

description: Chart live updates to logfile using matplotlib


code:
data.merge(df.reset_index(),
           how='left',
           on=['Date', 'Store'])

rawDescription: Speeding up past-60-day mean in pandas

description: Speeding up past-60-day mean in pandas


code:
class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm
    a = forms.CharField(max_length=20)
    #All my attributes here

rawDescription: Can I have a Django form without Model

description: Have a Django form without Model


code:
@app.route('/search/<location>')
def search(location=None):
    location = location or request.args.get('location')
    # perform search

rawDescription: url structure and form posts with Flask

description: Url structure and form posts with Flask


code:
def add (obj):
    session, engine = loadSession()
    session.add(obj)
    commit_and_close(session, engine)

rawDescription: Create set of Python functions

description: Create set of Python functions


code:
import numpy as np
X = [5, 7, 9, 5]
Y = [2, 0, 4, 1]
Z = [7, 2, 4, 6]
A = np.array([Y, Z, [1] * len(X)]).transpose()
a, b, mean = np.linalg.lstsq(A, X)[0]
print(a, b, mean)

rawDescription: Loops to minimize function of arrays in python


rawDescription: Keep other columns when using min() with groupby


rawDescription: I want to append the whole list to each other


code:
import struct
def unpack_with_final_asciiz(fmt, dat):
    """
    Unpack binary data, handling a null-terminated string at the end
    (and only at the end) automatically.

    The first argument, fmt, is a struct.unpack() format string with the
    following modfications:
    If fmt's last character is 'z', the returned string will drop the NUL.
    If it is 's' with no length, the string including NUL will be returned.
    If it is 's' with a length, behavior is identical to normal unpack().
    """
    # Just pass on if no special behavior is required
    if fmt[-1] not in ('z', 's') or (fmt[-1] == 's' and fmt[-2].isdigit()):
        return struct.unpack(fmt, dat)

    # Use format string to get size of contained string and rest of record
    non_str_len = struct.calcsize(fmt[:-1])
    str_len = len(dat) - non_str_len

    # Set up new format string
    # If passed 'z', treat terminating NUL as a "pad byte"
    if fmt[-1] == 'z':
        str_fmt = "{0}sx".format(str_len - 1)
    else:
        str_fmt = "{0}s".format(str_len)
    new_fmt = fmt[:-1] + str_fmt

    return struct.unpack(new_fmt, dat)

rawDescription: Unpacking a struct ending with an ASCIIZ string


code:
myclass.a = 3
x.a
y.a
del x.a
x.a

rawDescription: How to change all objects of a class at once?

description: Change all objects of a class at once


code:
tweet_phrases = "I love iphone . I am so in love with iphone . iphone is great . samsung is great . iphone sucks. I really really love iphone cases. samsung can never beat iphone . samsung is better than apple"
from nltk.collocations import *
import nltk

rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
d = {}
str(d or '')

rawDescription: Convert empty dictionary to empty string


rawDescription: Plotting Weekly Tick Data From A Year Time Series


code:
['+foo = bar', '+foofoo = barbar', '+foofoofoo = barbarbar']
['+spam = eggs', '+spamspam = eggseggs']

rawDescription: Split list based on first character - Python


rawDescription: Find last match with python regular expression


code:
df2 = DataFrame(df.values[:,[2,0,1]],columns=list('ABC'))
df2

rawDescription: change Pandas dataframe column order in place

description: Change Pandas dataframe column order in place


code:
with open("in.csv") as f:
    r = csv.reader(f)
    od = OrderedDict()
    for row in r:
        key, *rest = row
        od.setdefault(key, []).append(rest)

import csv
from collections import OrderedDict
from itertools import groupby
from operator import itemgetter

with open('in.csv') as f:
    r = csv.reader(f)
    od = OrderedDict()
    for k, v in groupby(r, key=itemgetter(0)):
        od[k] = [sub for _, *sub in v]
print(od)

rawDescription: Converting CSV data to list in dictionary


rawDescription: Get only those elements of array that match all elements of test array?


code: option.get('value', 'There is no value!')

rawDescription: Get value attribute for each tag found using Tag.find_all()


code: ['That was a very loud beep.\n\n ', "I don't even know\n if this is working. ", 'Mark?\n\n ', 'Mark are you there?\n\n\n']

rawDescription: Preserve empty lines with NLTK's Punkt Tokenizer


code:
def to_lower(mod_func):
  def deco(func):
    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
      return func(*map(mod_func, args), {(k, mod_func(v)) for (k,v) in kwargs})
    return _wrapper
  return deco

rawDescription: Is there a way to transform a function to accept a callable that is evaluated just before the function?


code:
def is_prime_mers(step, result = None, modulo = None):
    if result is None:
        result = 4                    # Default value
    if modulo is None:
        modulo = cunt_mersenne(step)  # Default value

rawDescription: Initialize parameter in recursive function in Python


code:
@contextlib.contextmanager
def logname(name):
    old_name = context.name
    if old_name is None:
        context.name = name
    else:
        context.name = "%s.%s" % (old_name, name)

    try:
        yield
    finally:
        context.name = old_name

def as_logname(name):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            with logname(name):
                return f(*args, **kwargs)
        return wrapper
    return decorator

rawDescription: How can you make logging module functions use a different logger?

description: Make logging module functions use a different logger


code:
s.hist()
savefig('path/to/figure.pdf')  # saves the current figure

rawDescription: save a pandas.Series histogram plot to file

description: Save a pandas.Series histogram plot to file


title: w

title: x

title: y

title: z

title: a

title: b

title: c

title: d

rawDescription: Python tree structure dictonary creation issue


rawDescription: How can I return the shortest word within the longest line?

description: Return the shortest word within the longest line


code:
'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n'
'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape')

rawDescription: python compare "\n" escape chars with "\\n"

description: Python compare "\n" escape chars with "\\n"


code:
d = {}
for i in a:
        dest = '/home/zurelsoft/my_files'
        fullname = os.path.join(dest, i) #Get the file_full_size to calculate size
        st = int(os.path.getsize(fullname))
        d[i] = size(st)

rawDescription: How to add all the elements inside loop in Python?

description: Add all the elements inside loop in Python


code:
from functools import reduce, partial
from itertools import groupby

pdf = reduce(
    partial(pd.merge, left_index=True, right_index=True, how='outer'),
    (pd.concat(list(g))
     for cols, g in groupby(sorted(df.values(),
                                   key=lambda df_: tuple(df_.columns)),
                            lambda df_: tuple(df_.columns)))
)

rawDescription: Merge many sub-dataframes in a big dataframe in a loop in python pandas


rawDescription: Reducing an axis with numpy

description: Reducing an axis with numpy


code:
# coding=utf-8
## \authors Cezary K. Wagner

from threading import Lock

__indent = 0
__patched = False

def logImports():
  global __patched
  if __patched == True:
    return

  import time
  import logging
#  import inspect
  import __builtin__

  original__import__ = __builtin__.__import__

  def patched__import__(name, *args):
    global __indent
    lock = Lock()
    lock.acquire()
    spaces = ' ' * (__indent * 2)
#    callerFrame = inspect.currentframe().f_back
#    moduleName = callerFrame.f_globals['__name__']
#    lineNumber = callerFrame.f_lineno
#    logging.debug('%simport start %s %s:%s.' % (spaces, name, moduleName, lineNumber))
    __indent += 1
    start = time.clock()
    try:
      module = original__import__(name, *args)
      delta = time.clock() - start
    # import could fail
    finally:
      lock.release
      __indent -= 1
    if delta >= 1.0:
      logging.debug('%simport end %s in %ss' % (spaces, name, delta))
    return module

  __builtin__.__import__ = patched__import__
  __patched = True

rawDescription: How to measure Python import loading times/latencies in AppEngine

description: Measure Python import loading times/latencies in AppEngine


code:
try:
    with transaction.atomic():
        var = request.session['var']
except KeyError:
    var = False

rawDescription: Django check session without creating it in datebase


code:
input_f = input("Enter the file name to read from: ")
output_f = input("Enter the file name to write to... ")

fw = open(output_f, "w")

with open(input_f) as fo:
    for w in fo:
        for c in w:
            if c.isalpha():
                fw.write(c.lower())
            if c.isspace():
                fw.write('\n')

fo.close()
fw.close()

rawDescription: Writing only lower case letters to file in Python


code:
for k, v in na.items():
    la.setdefault(k, []).extend(v)

rawDescription: Is there a python builtin for merging dicts where I can pass the function to run when there's key conflicts?


code:
class Foo:
    @classmethod
    def bar(cls): pass
    @staticmethod
    def baz(): pass

Foo.__dict__['bar'].__get__(Foo(), Foo)
Foo.__dict__['baz'].__get__(Foo(), Foo)
Foo().bar
Foo().baz

rawDescription: Python method accessor creates new objects on each access?


code:
from django.views.generic.create_update import get_model_and_form_class
def form_user_default(request):
    if request.method == 'GET':
        model, custom_form = get_model_and_form_class(Post,None)
        custom_form.author = request.user
        return {'form':custom_form}
    else: return {}

rawDescription: Setting object owner with generic create_object view in django


rawDescription: retrieve the standard deviation of the y-intercept

description: Retrieve the standard deviation of the y-intercept


code: thenewdict = cPickle.loads(thestring)

rawDescription: How do I store a dict/list in a database?

description: Store a dict/list in a database


code:
import pylab as plt

x=[12, 13, 14, 15, 16]
y=[14, 15, 16, 17, 18]

xticks=[12,13,14,15,16]

fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y,'o-')

ax.set_xticks(xticks)
ax.set_xticklabels(xticks[:-1]+[""])
plt.show()

rawDescription: How to make the last mark invisible in a matplotlib axes subplot?

description: Make the last mark invisible in a matplotlib axes subplot


code:
def layout_corr(str):
    ms = layout_re.search(str)
    if ms:
       return ms.group()
    else:
       p = re.compile(r'((?:\w+\s+){1,2})layout')
       ms = re.findall(p,str)
       return ms

rawDescription: Check regex result in a list ,if-else python


code:
jeff = Student()
jeff.name = "Jeff"
jeff.homework = [85, 92, 61, 78]
jeff.hw_average()  # 79

rawDescription: Using Loops to Simplify Python Dictonaries


code:
def forest_map(self):
    valid_map = lambda x: 20 <= int(x) <= 100
    valid_obstacle = lambda x: any( x == y for y in ('Y', 'N', 'y', 'n') )

    # the choice function will guarantee its safe to use int on the result
    self.map_x = int(self.choice("Map Width", valid_map))
    self.map_y = int(self.choice("Map Length", valid_map))
    self.obstacles = self.choice("Obstacles (Y/N)", valid_obstacle)

def choice(self, message, validate):
    """
    Prompt a user for input and validate the input

    Args:
        message (str): Message to display at prompt
        validate (callable): callable of one parameter to validate input
    Returns:
        str: A valid user input
    """
    is_valid = False
    while not is_valid:
        # prompt for input
        value = raw_input(message)

        # validate input with our validation function
        # if validate(value) returns True, it ends the loop
        try:
            is_valid = validate(value)

        # maybe the validation function throws an exception
        # its best to catch the specific error class, but I'll use Exception for simplicity
        except Exception:
            is_valid = False
    return True

rawDescription: Python input validation -- int between 20 and 100, no letters


code:
from itertools import takewhile
with open("myFile.txt") as f:
        array = []
        for line in f:
            if line.startswith('start flag'):
                data = takewhile(lambda x: not x.startswith("stop flag"),f)
                # use data and repeat

rawDescription: Read multiple block of file between start and stop flags


code:
while True:
    if threading.activeCount() < thread_limit:
        Thread1().start()
# I will never run because I want to wait until while True has finished to run!
t = threading.Timer(1.0, justAClass().do_soemthing())
t.start()

rawDescription: Python running two threads simultaneously


code:
from flask_login import login_required, current_user
@app.route("/user_needed")
@login_required
def some_function():
    print(current_user)

rawDescription: Passing POST call values using url_for in Flask


rawDescription: How do python classes work?

description: How do python classes work


rawDescription: Django, Python X value in List of Dicts/Queryset


code:
import subprocess

command1 = subprocess.Popen(['command1', 'args1', 'arg2'])
command2 = subprocess.Popen(['command2', 'args1', 'arg2'])

rawDescription: python execute shell command and continue without waiting and check if running before executing

description: Python execute shell command and continue without waiting and check if running before executing


code:
x=[0, 1, 1, 0]
y=[0, 0, 1, 1]
z=[0, 1, 2, 3]
tridat=[[0,3,2],[0,2,1]] # 2 triangles in counterclockwise order

triang=tri.Triangulation(x,y,tridat) #this has changed
refiner=tri.UniformTriRefiner(triang)
interp=tri.LinearTriInterpolator(triang,z) #linear interpolator
new,new_z=refiner.refine_field(z,interp,subdiv=6) #refined mesh

fig = plt.figure()
plt.tripcolor(new.x,new.y,new_z,cmap=cm.jet)

rawDescription: MATLABs fill in PyPlot

description: MATLABs fill in PyPlot


code:
def move():
    global x_vel
    global y_vel
    global direction
    if direction is not None:
        canvas1.move(rect, x_vel,y_vel)
    window.after(33,move)  # Indetation.

rawDescription: How can I get my animation loop working?

description: Get my animation loop working


code:
a=np.arange(12).reshape(3,4)
[np.dot(a[i],a[i]) for i in range(3)]
np.einsum('ij,ij->i',a,a)

rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


code:
for i in range(0, img_layers):
  img.seek(i)
  a = numpy.array(img.getdata(), dtype=dtype) # Majority of time in this call
  a.resize(sx, sy, channels)
  z = i % sz
  frame = i // sz
  dset[frame, z, ...] = a

rawDescription: How do I fill an n-dimensional array in HDF5 from a 1D source?

description: Fill an n-dimensional array in HDF5 from a 1D source


code: [(exponent, sum(value for _, value in values)) for exponent, values in groupby(sorted(l, key=itemgetter(0)), key=itemgetter(0))]

rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


code: df = df[rows_to_keep]

rawDescription: How can I delete a row in a Pandas dataframe if the entire row is null?

description: Delete a row in a Pandas dataframe if the entire row is null


code:
name.index(',')
name[:28] # string up to index 28
name[30:] # string starting at index 30 (we have to consider the space too)
index = name.index(',')
name[index + 2:] + ', ' + name[:index]

rawDescription: Swapping first and last name positions

description: Swapping first and last name positions


code:
import cities_light

from django.db import models

from cities_light.settings import ICountry
from cities_light.receivers import connect_default_signals
from cities_light.abstract_models import (AbstractCountry, AbstractRegion,
    AbstractCity)

class Country(AbstractCountry):
    capital = models.CharField(max_length=50)
connect_default_signals(Country)

class Region(AbstractRegion):
    pass
connect_default_signals(Region)

class City(AbstractCity):
    pass
connect_default_signals(City)

def process_country_import(sender, instance, items, **kwargs):
    instance.capital = items[ICountry.capital]

cities_light.signals.country_items_post_import.connect(process_country_import)

rawDescription: How to add capital to django-cities-light country model?

description: Add capital to django-cities-light country model


rawDescription: How to create a keyframe with Python API for 3D Studio Max

description: Create a keyframe with Python API for 3D Studio Max


code:
l = LinkedList([1, 2, 3, 3, 3, 4, 5])
for value in l:
    print(value)

rawDescription: Single Linked List search in Python

description: Single Linked List search in Python


rawDescription: Django count matches query with contains


code:
def _get_total_quantity(self, cr, uid, ids, field, args, context = None):
    res = {}
    for po in self.browse(cr, uid, ids, context = context):
        res[po.id] = sum([x.quantity for x in po.order_line])

    return res

rawDescription: Row counter Openerp - Item Custom Module


code:
not_a_tuple = (0)
type(not_a_tuple)
t = 0,
type(t)

rawDescription: Using manager to modify variables between multiprocess processes


rawDescription: How to chosse AWS profile using Boto3 to connect to CloudFront

description: Chosse AWS profile using Boto3 to connect to CloudFront


code:
for ele in a_lst[:]:
    if  any(d['Name'] == ele['Name'] for d in b_lst):
        a_lst.remove(ele)

rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


code: all(e['type'] == L[0]['type'] for e in L)

rawDescription: Pythonic way of comparing multiple elements in a list of dictionaries


code: df.groupby({x: x // 100 for x in range(len(df))})

rawDescription: Pandas: Grouping DataFrame by hundreds

description: Pandas: Grouping DataFrame by hundreds


code: areas_pos = abs(z[:-1] + z[1:]) * 0.5 * dx # signs of both z are same

rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code: data.loc[0] = data.loc[1]

rawDescription: How to assign one row of a hierarchically indexed Pandas DataFrame to another row?

description: Assign one row of a hierarchically indexed Pandas DataFrame to another row


code:
template = {'thing1': '', 'thing2': '', 'thing3': ''}
apile = template.copy()
apile['thing1'] = 1
apile
template

rawDescription: How to create copies of a python object that are not linked to original object?

description: Create copies of a python object that are not linked to original object


code:
df = pd.read_csv('foo.csv')
res = df.Value - df.Value.shift()
res

rawDescription: pandas groupby on a values based on n-1 index record

description: Pandas groupby on a values based on n-1 index record


code:
import sys
from noise import snoise2
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')
result = Image.new('L', img.size)
width, height = img.size

factor = 15
res = result.load()
im = img.load()
for x in xrange(width):
    for y in xrange(height):
        n1 = snoise2(x, y)
        n2 = snoise2(y, x)
        pt = [int(round(x + n1 * factor)), int(round(y + n2 * factor))]
        pt[0] = min(max(0, pt[0]), width - 1)
        pt[1] = min(max(0, pt[1]), height - 1)
        res[x, y] = im[tuple(pt)]
result.save(sys.argv[2])

rawDescription: How do you use Python's Noise 1.1.1 for Coordinates?

description: Use Python's Noise 1.1.1 for Coordinates


code:
original_dict = {
    'name': "Rahul",
    'userTimestamp': 1,
    'user': {'id': '20',
             'links': {'self': [{'href': 'https://john.com'}]},
             'mail': 'john@john.com',
             'message': 'Hello world',
             'name': 'john'}
}

def get_dict_with_relevant_fields(orig_dict, interesting_fields):
    new_dict = {}
    for key, value in orig_dict.iteritems():
        if key in interesting_fields:
            new_dict[key] = value
        elif isinstance(value, dict):
            new_dict.update(get_dict_with_relevant_fields(value, interesting_fields))

    return new_dict

rawDescription: Best way to obtain information from a dict

description: Obtain information from a dict


code:
for attr in ['__a', '__b', '__c']:
    if hasattr(self, attr):
        var = getattr(self, attr)
        # Do something
    else:
        pass # or do something else

rawDescription: Set up a Python list from possibly non-existing variables


code:
import re
from os import fsync

def updating(filename,dico):

    RE = '(('+'|'.join(dico.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)'
    pat = re.compile(RE)

    def jojo(mat,dic = dico ):
        return dic[mat.group(2)].join(mat.group(1,3))

    with open(filename,'rb') as f:
        content = f.read()

    with open(filename,'wb') as f:
        f.write(pat.sub(jojo,content))

#-----------------------------------------------------------

vars = ['ENABLEPRINTER','PRINTERLIST','PRNT1.PORT']
new_values = ['y','PRNT3','8310']
what_to_change = dict(zip(vars,new_values))

updating('configfile_1.txt',what_to_change)

rawDescription: Edit configuration file through python

description: Edit configuration file through python


code:
def changelist_view(self, request, extra_context=None):
    ...
    ChangeList = self.get_changelist(request)

    cl = ChangeList(request, self.model, list_display,
        list_display_links, list_filter, self.date_hierarchy,
        search_fields, list_select_related, self.list_per_page,
            self.list_max_show_all, self.list_editable, self)

    # Actions with no confirmation
    if (actions and request.method == 'POST' and
            'index' in request.POST and '_save' not in request.POST):
        if selected:
            response = self.response_action(request, queryset=cl.get_queryset(request))
    ...

rawDescription: How to get filtered queryset in django admin?

description: Get filtered queryset in django admin


code:
with open('testFile.txt') as fin:
    data = [line.split() for line in fin]

rawDescription: Read file into dictionary and manipulate data


code:
weights = [(1,2), (2,0), (3, 1)]
numNonZero = (k for k, w in weights if w > 0)
next(numNonZero)
next(numNonZero)
next(numNonZero)
next(numNonZero, -1)

rawDescription: Python equivalent of Scala's lazy val

description: Python equivalent of Scala's lazy val


code: any(map(operator.gt, a,b))

rawDescription: Playing with the Python zip function

description: Playing with the Python zip function


code:
plt.imshow(data, cmap='jet', interpolation='none')
plt.savefig('image.png')

rawDescription: Black and white colorbar

description: Black and white colorbar


rawDescription: Find substrings in string using python

description: Find substrings in string using python


code:
a = A()
list_of_c = a.c_set.all()

rawDescription: Django get base model from parent model

description: Django get base model from parent model


code:
import os
appdata_dir_name = os.getenv("APPDATA")

rawDescription: How do you find the root directory so that a path works across multiple computers?

description: Find the root directory so that a path works across multiple computers


rawDescription: Calculating the Fisher criterion in Python


rawDescription: Correct Syntax for clearing SettingWithCopyWarning in Pandas


code:
from xml.dom.minidom import DOMImplementation

imp = DOMImplementation()
doctype = imp.createDocumentType(
    qualifiedName='foo',
    publicId='',
    systemId='http://www.path.to.my.dtd.com/my.dtd',
)
doc = imp.createDocument(None, 'foo', doctype)
doc.toxml()

rawDescription: Set a DTD using minidom in python

description: Set a DTD using minidom in python


code:
@lru_cache(maxsize=32)
class C(object):
    def __init__(self, num):
        self.num = num

rawDescription: Unique representations of Python objects


code: proc.terminate() # terminate the process.

rawDescription: Stop a command line command in script

description: Stop a command line command in script


code:
def format_row(row):
    return '|' + '|'.join('{0:^3s}'.format(x) for x in row) + '|'

def format_board(board):
    # for a single list with 9 elements uncomment the following line:
    # return '\n\n'.join(format_row(row) for row in zip(*[iter(board)]*3))
    # for a 3x3 list:
    return '\n\n'.join(format_row(row) for row in board)

rawDescription: How to print a board in python?

description: Print a board in python


rawDescription: Index multiple, non-adjacent ranges in numpy


code:
from datetime import datetime
datetime.now()

rawDescription: How do I get the atomic clock time in python?

description: Get the atomic clock time in python


code:
with open("1.txt", "r") as crs:
    k, v = zip(*(line.split() for line in crs))

rawDescription: reading a datafile to array/list

description: Reading a datafile to array/list


code:
mocked_client = mock_client({})
my_code(mocked_client)
self.assertEqual(
    mocked_client.append_dictionary.call_args_list,
    [
        mock.call("key", "value"),
    ]
)

rawDescription: Passing arguments to mock method

description: Passing arguments to mock method


code:
for path,value in traverse(doc):
    print("{} = {}".format(path,value))

rawDescription: Python: Loop through all nested key-value pairs created by xmltodict


code:
def callback(self, event):
    mybutton = event.widget
    text_at_row_col = mybutton["text"]

rawDescription: finding widgets on a grid (tkinter module)

description: Finding widgets on a grid (tkinter module)


code:
id_ = 'test'
pw = '12345'
depart = 'none'
class_ = 'GM'
name = 'name'
birthday = 'None'
grade = 3
subgrade = 2

sql = 'exec [my_database].[dbo].[my_table](?, ?, ?, ?, ?, ?, ?, ?)'
values = (id_, pw, depart, class_, name, birthday, grade, subgrade)

cursor.execute(sql, (values))

rawDescription: Using stored procedures[python + ms sql]


code:
[item for item in iterable if condition]
{key:val for key, val in iterable if condition}
{item for item in iterable if condition}

rawDescription: What's the pythonic idiom for making a simple list out of a list of instances?


code:
res.index = res.index.droplevel(1)
res

rawDescription: Merge multiple dataframes with non-unique indices


code:
a = 0
b = 1     # this is the first fibonacci number

# First iteration of for loop
c = a + b # c is now 1, the second fibonacci number
a = b     # a is now 1
b = c     # b is now 1

# Second iteration
c = a + b # c is now 2, the third fibonacci number
a = b     # a is now 1
b = c     # b is now 2

# Third iteration
c = a + b # c is now 3, the fourth fibonacci number
a = b     # a is now 2
b = c     # b is now 3

# Fourth iteration
c = a + b # c is now 5, the fifth fibonacci number
a = b     # a is now 3
b = c     # b is now 5

# Remaining 98 iteration omitted

rawDescription: Advice with python program's for loops in order to calculate 103 Fibonacci element


code:
while thread.is_alive():
    thread.join(.1)

rawDescription: Catch Keyboard Interrupt in program that is waiting on an Event


code:
#! /usr/bin/python3
from sys import exit

class Location:
    def __init__ (self, welcome, menu, choices):
        self.welcome = welcome
        self.choices = choices
        self.menu = menu

    def enter (self, *args):
        if not self.choices:
            print (args [0] )
            exit (0)
        print ('\n\n{}\n{}'.format ('*' * 20, self.welcome) )
        while True:
            print ()
            print (self.menu)
            print ('\n'.join ('{}: {}'.format (index + 1, text) for index, text in enumerate (choice [0] for choice in self.choices) ) )
            try:
                choice = int (input () )
                return self.choices [choice - 1] [1:]
            except: pass

class World:
    locations = {
        'Beginning': Location ('As you take way on to your adventure... You meet this strange man.\nHe tells you that he can not be trusted.\nHe tells you that the door on the right is going to be good. He also tells you that the left door will lead you to good as well. But you cannot trust him...', 'Which door do you pick?', [ ('Left', 'GoodDoor', [] ), ('Right', 'BadDoor', [] ) ] ),
        'GoodDoor': Location ('You seem to have chosen a door that has three distinct routes. You still do not know whether or not your choice of doors were correct... You hesitate to choose which route you take but you have to choose...', 'Which route do you choose?', [ ('Route 1', 'Finish', ['You are in heaven!'] ), ('Route 2', 'Desert', [] ), ('Route 3', 'Finish', ['You trip and die.'] ) ] ),
        'BadDoor': Location ('You enter this door and you see two routes, which one do you choose?', 'You choose from the left route or the right route.', [ ('Left', 'GoodDoor', [] ), ('Right', 'Finish', ['You ended in hell.'] ) ] ),
        'Finish': Location ('', '', [] ),
        'Desert': Location ('You walk into a desert and it\'s unbearably hot... You have two options... You stay here and hope that somebody will save you, or you keep walking... Which one do you choose?', 'Do you choose to stay or move?', [ ('Stay', 'Finish', ['You die of thirst'] ), ('Move', 'GoodDoor', [] ) ] )
        }

    @classmethod
    def enter (bananaphone):
        room = World.locations ['Beginning']
        params = []
        while True:
            room, params = room.enter (*params)
            room = World.locations [room]

World.enter ()

rawDescription: The CLI seems to ignore my function and go to another! (Python)


code: display(data)

rawDescription: Python tab creation

description: Python tab creation


code:
from itertools import izip
edges, weights = izip(*dict_edges.iteritems())
g = Graph(edges, edge_attrs={"weight": weights})

rawDescription: How to add edges in an igraph object from a dictionary

description: Add edges in an igraph object from a dictionary


code: combined = set(listA) & set(listB)

rawDescription: How to intersect two horizontal lists using python?

description: Intersect two horizontal lists using python


rawDescription: Pandas data types change when iterating over the major axis


code:
for i, key in enumerate(dic):
    do_some_stuff()
    if i > 10:
        break

rawDescription: python loop to run only once for temporary testing

description: Python loop to run only once for temporary testing


code:
from itertools import groupby
from operator import attrgetter
{k:list(v) for k, v in groupby(reports, attrgetter('status'))}

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
r='ABCD'
list(r)

rawDescription: Splitting a string into a list

description: Splitting a string into a list


code:
self.rangeselect.on_trait_change(self.on_selection_changed, "selection")

def on_selection_changed(self, selection):
    if selection != None:
        self.rangeXMin, self.rangeXMax = selection

rawDescription: Chaco: Get Index and Value out of a chaco plot


code:
import functools
from types import FunctionType

def wrap_functions(module_dict):
    for k, f in module_dict.items():
        if not isinstance(f, FunctionType):
            continue
        def get_wrapper(f):
            def wrapper(*func_args, **func_kwargs):
                print(f(*func_args, **func_kwargs))
            return functools.wraps(f)(wrapper)
        module_dict[k] = get_wrapper(f)

rawDescription: Python introspection

description: Python introspection


code: y = ["{0:0>2}".format(v) for v in x]

rawDescription: Python - list transformation

description: Python - list transformation


code: max(dictionary, key=dictionary.get)

rawDescription: Get most frequent item in python dictionary given frequencies


code:
import numpy as np
groupMatrix = np.array([
    [1, 1, 0, 0],
    [1, 0, 0, 0],
    [0, 0, 0, 2],
    [3, 3, 0, 2]
])
np.nonzero(groupMatrix)
zip(np.nonzero(groupMatrix))

rawDescription: how can I get the position of the nonzero values in a numpy array?

description: Get the position of the nonzero values in a numpy array


code:
def make_elem_class(name):
    """Dynamically creates the class with a type() call."""

    def init(self, content=None, **kwargs):
        super(elemcls, self).__init__(tag=name, content=content, **kwargs)

    elemcls = type(name, (elem,), {"__init__" : init})
    return elemcls

rawDescription: Mix type(), and custom __init__() using super().__init__()


rawDescription: Optimal way to replace characters in large string with Python?


code:
for proc_name, ms in itertools.groupby(measurements, lambda m: m.processor.name):
    set_up_some_stuff(proc_name)
    for meas in ms:
        process(meas)

rawDescription: SQLAlchemy: Iterate over each subset of a query result set partitioned by ordering parameters


code:
import os

width = os.get_terminal_size().columns
print("hello world".center(width))

rawDescription: Is it possible to align a print statement to the center in Python?


code:
class MyModel(db.Model):
  @classmethod
  def kind(cls):
    return 'prefix_%s' % super(MyModel, cls).kind()

rawDescription: Set a kind name independently of the model name (App Engine datastore)


code: pd.expanding_apply(series, lambda x: x.argmax())

rawDescription: pandas series cumulative argmax

description: Pandas series cumulative argmax


rawDescription: Delete elements at different indices in a text file


code: zip(*sorted(zip(*a), key=lambda column: column[0]))

rawDescription: How can I sort a 2D list?

description: Sort a 2D list


code:
data = json.loads(json_string)
limited = {str(k): data[str(k)] for k in range(1, 11)}

rawDescription: Load part of a json in python

description: Load part of a json in python


code:
fileName = "test.txt"
read_file = open(fileName, "r")
with read_file as open_file:
    data = open_file.read().rstrip()
    keyword = "ape"
    data = ' '.join(["\n"*(word == keyword) + word for word in data.split()]).strip()
#   data = data.replace(keyword, "\n"+keyword).strip()
    print(data)

rawDescription: How to end for loop in Python?

description: End for loop in Python


code:
stringExample = ["a", "\n", "b", "\n", "G"]
x = ''.join(stringExample)
y = x.replace("\n", "")
print(y)
# abG

rawDescription: How can i make sure \n does not register? when it is in a string

description: Make sure \n does not register? when it is in a string


code: list1 = []

rawDescription: List Title Depends on Variable in Python


rawDescription: How to find the following desired probability using computational method (e.g. using Python)?

description: Find the following desired probability using computational method (e.g. using Python)


code:
import re
string1 = "498results should get"
int(re.search(r'\d+', string1).group())

rawDescription: How to get integer values from a string in Python?

description: Get integer values from a string in Python


code:
for i in range(number_of_observations):
    hour_sums[hour[i]] = hour_sums[hour[i]] + rentals[i]

rawDescription: Is there a way to use bincount with a clause in python?


code:
import numpy as np
from scipy.linalg import qr

def solve_minnonzero(A, b):
    x1, res, rnk, s = np.linalg.lstsq(A, b)
    if rnk == A.shape[1]:
        return x1   # nothing more to do if A is full-rank
    Q, R, P = qr(A.T, mode='full', pivoting=True)
    Z = Q[:, rnk:].conj()
    C = np.linalg.solve(Z[rnk:], -x1[rnk:])
    return x1 + Z.dot(C)

rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
import ctypes

libc = ctypes.CDLL(None)
syscall = libc.syscall

rawDescription: Make syscall in Python

description: Make syscall in Python


code:
with open(file_name) as fid:
    lines = fid.readlines()
for line in lines[:-n_skip]:
    do_something_with(line)

rawDescription: Simple Way of NOT reading last N lines of a file in Python


code:
import subprocess
subprocess.call("shell commands go in here")

rawDescription: Python-how to send commands to existing shell?


code: [{'name': 'a name', 'titles': ['baz', 'foo', 'bar']}]

rawDescription: List/Dict Data Manipulation - Delete Duplicates


code:
number = 32424234

import struct
result = struct.pack("I", number)

rawDescription: How do I convert 32b (four characters) from an int value to an ASCII string in python

description: Convert 32b (four characters) from an int value to an ASCII string in python


code:
for line in open('myfile','r'):
    do_something(line)

rawDescription: Check that matrix keys are in running order - python


code:
simple_list = range(100)

def f(l):
    it = iter(l)
    i =  next(it)
    for ele in it:
        if abs(ele - i) >= 5:
            yield i
            i = ele
    yield i

simple_list[:] = f(simple_list)
print(simple_list)
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

rawDescription: Remove items from a list in Python based on previous items in the same list


code: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)

rawDescription: Python Pandas: Convert Rows as Column headers


code: fig.savefig(fname, dpi=400)

rawDescription: Python matplotlib image + points plot

description: Python matplotlib image + points plot


code:
user = User.get_or_insert(my_facebook_id)

thing = Thing()
thing.put()

user.things.append(thing.key())
user.put()

rawDescription: Minimize subqueries with IN queries on AppEngine (python)


code:
d = decimal.Decimal("100.000")
d
d.normalize()

rawDescription: How can I "trim" significant figures of a Decimal in Python to only those that are non-zero?


code:
r"""
TEST topic_message STRINGS:
ok:  'This topic is A-ok.     This topic is     A-ok.'
bad: 'This topic is <not>-ok. This topic is {not}-ok.'

MEASURED PYTHON STATEMENTS:
Method 1: 're1.search(topic_message)'
Method 2: 're2.match(topic_message)'
Method 3: 'set(invalid_chars).intersection(topic_message)'
"""

rawDescription: Efficient way to search for invalid characters in python


code:
for i in range(len(c)):
    c_2=np.power(c,2)
    c2.append(c_2)

rawDescription: take different powers of a vector and save in txtfile

description: Take different powers of a vector and save in txtfile


code:
# file messages.py
messages = dict(
    struct1=[
        dict(field="name", type="string", ignore=False),
        dict(field="id", type="int", enums={0: "val1", 1: "val2"}),
        ],
    struct2=[
        dict(field="object", type="struct1"),
        ]
    )

rawDescription: Parsing a datafile in python (2.5.2)

description: Parsing a datafile in python (2.5.2)


rawDescription: Import Matlab Workspace variables into Spyder (Python)


code:
b = ['Hello', ',', 'who', 'are', 'you', '?']
list(join_punctuation(b))
' '.join(join_punctuation(b))

rawDescription: Join split words and punctuation with punctuation in the right place


code: sum( [SimpleLoc1, SimpleLoc2, SimpleLoc3], start=ComplexLoc() )

rawDescription: Avoiding Python sum default start arg behavior


code: {{ form.field_name.field.foo }}

rawDescription: Attaching additional information to form fields


code:
@mock.patch('mem.network_call')
def test_search(mock_network_call):
    mock_network_call.return_value = 2
    assert mem.NetworkEngine().search(1) == 2

rawDescription: How can memoized functions be tested?

description: How can memoized functions be tested


code:
with open("propertyOutput.csv", "wb") as fp:
    writer = csv.DictWriter(fp, header)
    for row in table:
        if not stringNeed.isdigit():
            rows['zip'] = "not number"
        # even more stuff to check and edit here
        # write the edited row
        writer.writerow(row)

rawDescription: how to write back to open csv file in python

description: Write back to open csv file in python


code:
def changescase(uc):
    return uc != uc.lower() or uc != uc.upper()

rawDescription: Unicode case conversion

description: Unicode case conversion


code:
def search(df, df_condition):
    return [(x, df.columns[y]) for x,y in np.argwhere(df_condition(df))]

rawDescription: Python pandas: Getting the locations of a value in dataframe


code:
def __init__(self, iterable):
    self.__iter__ = iterable.__iter__

rawDescription: python make class iterable by returning embedded iterable

description: Python make class iterable by returning embedded iterable


code: f['Adj Close'].corr()

rawDescription: how to pick out individual columns of numerical values from Datareader pandas?

description: Pick out individual columns of numerical values from Datareader pandas


code:
if ID in line:
    linea_buscada = linea

rawDescription: Error on variable after assignment?

description: Error on variable after assignment


code: df[df>=3].apply(lambda x: x.first_valid_index(), axis=1)

rawDescription: Pandas Series with column names for each value above a minimum


code:
from difflib import Differ
s1 = ["one",  "three", "twoo"]
s2 = ["one",  "tow", "tree"]
result = Differ().compare(s1, s2)
result
for x in result:
    pass

list(result)

rawDescription: Result of Differ.compare() vanishes after using once


code:
def is_happy(items):
   return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items)

rawDescription: Is it possible to nest the all function?

description: Is it possible to nest the all function


code: Event.objects.filter(day = 'Friday')

rawDescription: How to call database records and the data that also goes with it

description: Call database records and the data that also goes with it


code:
s = "the quick brown fox jumps over the lazy dog"
def capitalize_long(match, length):
    word = match.group(0)
    return word.capitalize() if len(word) > length else word

r = re.compile('\w+')
r.sub(partial(capitalize_long, length=3), s)

rawDescription: Python lambda with regex

description: Python lambda with regex


code:
for sprite in group:
    if isinstance(sprite, your_class):
        sprite.kill()

rawDescription: Pygame delete all objects in class

description: Pygame delete all objects in class


code:
with open('test.html', 'w') as f:
    f.write(template.render(res=res))

rawDescription: How to display the result with temple jinjia2 or others?

description: Display the result with temple jinjia2 or others


code:
def unicode_notation(c):
    x = ord(c)
    if 32 <= x < 128:
        return c
    if x < 256:
        return '\\x{:02x}'.format(x)
    if x < 0x10000:
        return '\\u{:04x}'.format(x)
    return '\\U{:08x}'.format(x)

new = ''.join(unicode_notation(c) for c in u)

rawDescription: Python: Replace character by its Unicode-representation


code:
class mg:
    bar = 5

def foo():
    mg.bar = 10

rawDescription: python: can i import the module namespace within the module itself?

description: Python: can i import the module namespace within the module itself


code:
file = ["It's us or them.\n",
'"Ah, yes--a simple matter."\n',
'Could you hold that for me?\n',
'Holmes was accessible upon the side of flattery, and also, to do him justice, upon the side of kindliness.\n',
'Trust your instincts.\n']
list(word_search("us", file))
list(word_search("you", file))

rawDescription: wrong output in search file for word code

description: Wrong output in search file for word code


code:
import numpy as np
TOL = 1.0e-3
a = np.random.random((10,10))
i = np.argsort(a.flat)
d = np.diff(a.flat[i])
result = a.flat[i[d>TOL]]

rawDescription: Find unique elements of floating point array in numpy (with comparison using a delta value)


code: number.startswith(('1', '0'))

rawDescription: And and Or confusion

description: And and Or confusion


code:
import matplotlib.pyplot as plt

def my_plot(location_dataset, min_temperature, max_temperature):
    condition = (location_dataset['temperature'] > min_temperature) & (dataset['temperature'] <= max_temperature)
    subset = location_dataset[condition] # subset the data based on the temperature range

    x = subset['precipitation'] # takes the precipitation column only
    # N.B. referenca taken to fig
    fig = plt.figure(figsize=(8, 6))
    plt.plot(x)
    plt.show()

    return fig

rawDescription: save a plot resulting from a function matplotlib python

description: Save a plot resulting from a function matplotlib python


code:
sage: version()
'Sage Version 6.3, Release Date: 2014-08-10'

rawDescription: How Accelerate factor function from SAGE


rawDescription: Pandas: df.refill, adding two columns of different shape


rawDescription: Python: delete the words between two delimeters


code:
import gobject
gobject.timeout_add(milliseconds, callback)

rawDescription: Periodically call a function in pygtk's main loop


code:
import xml.etree.ElementTree as ET
root = ET.fromstring(xml)
[item.find('description').text for item in root.iter('item')
 if'KEYWORD' in item.find('title').text]
# => [' description text of interest "1"', ' description text of interest "k" ']

rawDescription: parsing xml with python, selecting a tag using a sibling tag as selector

description: Parsing xml with python, selecting a tag using a sibling tag as selector


code: pd.read_csv(..., header=None)

rawDescription: Python Pandas does not read the first row of csv file


code: e_value  = float(linearr[6])

rawDescription: e value script program

description: E value script program


code:
from urllib import urlretrieve
import urlparse
from bs4 import BeautifulSoup
import urllib2

url = "http://en.wikipedia.org/wiki/Main_Page"
soup = BeautifulSoup(urllib2.urlopen(url))
for img in soup.select('a.image > img'):
    img_url = urlparse.urljoin(url, img['src'])
    file_name = img['src'].split('/')[-1]
    urlretrieve(img_url, file_name)

rawDescription: Fetching Image from URL using BeautifulSoup


code:
import collections

def nesteddict():
    return collections.defaultdict(nesteddict)

nd = nesteddict()
for a, b, c in rows:
    nd[a][b] = c

rawDescription: Populating nested dictionary from database query


code:
import matplotlib.pyplot as plt
from itertools import islice, chain

def chunks(n, iterable):
    it = iter(iterable)
    while True:
       chunk = tuple(islice(it, n))
       if not chunk:
           return
       yield chunk

with PdfPages('foo.pdf') as pdf:
    for chunk in chunks(4, df2):
        fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 4))
        axes = chain.from_iterable(axes)  # flatten 2d list of axes

        for (key, group), ax in zip(chunk, axes):
            group.plot(ax=ax)

        pdf.savefig(fig)

rawDescription: Plot and save multiple figures of group by function as pdf


code:
dp_set = set(dp)
[x for x in rt if x not in dp_set]
[3]

rawDescription: Most pythonic means to find out if an element from one list is not a member of another list


code:
from django.db.models import Q

def month_in(months, field='date'):
    q = Q()
    for m in months:
       q |= Q(**{field + '__month': m})
    return q

Sample.objects.filter(month_in([2, 7, 9, 12]), date__year=2013)

rawDescription: Get records for multiple months in django query


code: re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', some_string)

rawDescription: python: replacing exact with minus sign

description: Python: replacing exact with minus sign


code:
file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)
diff_text = p2.communicate()[0]

rawDescription: Redirect command to input of another in Python


code:
class Bunch:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

...
def method1(self):
    return Bunch(name="method1",
                 list=[1, 2, 3])

rawDescription: Python, best way to return/handle complex data from a method


code:
tuple_ = (a,b,c)
"\n".join( str(foo(i)) for i in tuple_ )

rawDescription: Tuple to string with a function to each element


code:
def getconfig( x, prompt ):
  try:
    theconf= config[x]
  except Exception:
    config[x] = raw_input( prompt )
    theconf= config[x]
  return theconf

rawDescription: (Python) Shelve + try: how to search for a key and set it if it doesn't exists without repeating code?


code: ABC = [ list(chain.from_iterable(z)) for z in product(*SETS) ]

rawDescription: Python: Concatenate list of lists in the algebraic way


code:
import numpy as np

data = np.random.randint(0, 10, size=(100000, 2))

rawDescription: Fastest way to calculate the centroid of a set of coordinate tuples in python without numpy


code:
import concurrent.futures

data = [
    {(1, 2, 3), (2, 3, 4), (3, 4, 5), ...},
    {(12, 13, 14), (15, 16, 17), ...},
    ...
]

def jaccard(A, B):
    return len(A & B) / len(A | B)

with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(jaccard, *sets): sets
               for sets in combinations(data, 2)}

    for future in concurrent.futures.as_completed(futures):
        jaccard_index = future.result()
        print(jaccard_index) # write output to a file or database here

rawDescription: hashing large sequences of numbers, creating sets of hashes, storing, and comparing similarity of sets using python

description: Hashing large sequences of numbers, creating sets of hashes, storing, and comparing similarity of sets using python


rawDescription: Pythonic way to insert every 2 elements in a string


code:
sections=config_instance.sections()
ids=[config_instance.get(sec,'id') for sec in sections]

rawDescription: config parser python

description: Config parser python


code: [[sum(t*k for t,k in zip(i,j)) for j in m2] for i in m1]

rawDescription: Python: How do I multiply and sum elements across two lists (without using a library)?


code:
#func as defined above

x=2 ; y=3
x,y = func(x,y) #this unpacks the tuple (202,303) into two values and x and y
print(x,y) #prints 202 303

rawDescription: How to change the scope of a variable in a function? Python

description: Change the scope of a variable in a function? Python


code:
df1['date'] = pd.DatetimeIndex (df1.creationdate).date
df2['date'] = pd.DatetimeIndex (df2.date).date
df=df1.merge(df2, on='date', how='inner')
df

rawDescription: Loop through rows in pandas dataframe

description: Loop through rows in pandas dataframe


code: items.sort(key=lambda x: sum(x[1]))

rawDescription: How does a Python custom comparator work?


rawDescription: Why is this python regular expression matching only one character, instead of the desired words?


code:
[random.choice('abcde') for _ in range(3)]
[random.choice('abcde') for _ in range(3)]
[random.choice('abcde') for _ in range(3)]

rawDescription: Random string generation with upper case letters and digits in Python


code:
def with_slashes_cpu_usage_str(cpu_percentage):
    hashes_str = '#' * int(round(cpu_percentage / 10))
    slash_str  = '/' * (cpu_percentage % 10 >= 5)
    return 'CPU:[{hash}{slash}]'.format(hash=hashes_str, slash=slash_str)

rawDescription: Python: Add character to string an amount of times depending on an int


code: return min(l, key=int)

rawDescription: Python - Sorting List of Ints User Input


rawDescription: Compare german umlaut in Python

description: Compare german umlaut in Python


code:
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy.sql import join, select
from sqlalchemy import *
# engine = create_engine("postgresql://<username>:@localhost/<DBname>")
engine = create_engine("sqlite:///:memory:")
engine.execute(r"""
    CREATE TABLE userprofile (
        id integer primary key,
        fieldid integer,
        keep integer,
        discard integer
    )
""")
engine.execute(r"""
    CREATE TABLE profilefield (
        id integer primary key,
        fieldid integer,
        keep integer,
        discard integer
    )
""")
metadata = MetaData(engine)
Session = sessionmaker(engine)
profiles = Table('userprofile',metadata,autoload=True)
profilefields = Table('profilefield',metadata,autoload=True)
engine.execute(profiles.insert({'fieldid': 1, 'keep': 2, 'discard': 3}))
engine.execute(profilefields.insert({'fieldid': 1, 'keep': 2, 'discard': 3}))
class DBObj(object):
     def __repr__(self):
        return "DBobj" + str(self.__dict__)

j = join(profiles,
         profilefields,
         profiles.c.fieldid==profilefields.c.fieldid)

rawDescription: SQLAlchemy - Mapping subset of columns from inner join of autoloaded tables


code: CAM = cv.CaptureFromCAM(0)

rawDescription: Use cv.CaptureFromCAM in Django

description: Use cv.CaptureFromCAM in Django


code:
#!/usr/bin/python3
# Python 3

rawDescription: Specifying a script is Python 2 or 3 which version of Python a program is written for


code:
import numpy as np
np.array([[1, 2], [3, 4]])

rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


code: result = ' '.join(words[i] for i in sorted(allindx))

rawDescription: Python: finding the two words following a key word


code:
for link in soup.select('a[href^="/players"]'):
    print(link["href"])

rawDescription: Using `find_all()` to get all tags of a subset of that same tag


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


rawDescription: Best way to put functions python

description: Put functions python


rawDescription: Split numpy array at multiple values?

description: Split numpy array at multiple values


rawDescription: Using scrapy, how to make xpath more selective?


code:
from urlparse import urlparse
o = urlparse('http://url.something.com/bla.html?querystring=stuff')

url_without_query_string = o.scheme + "://" + o.netloc + o.path

rawDescription: How do I remove a query from a url?

description: Remove a query from a url


code:
class SaleList(ListView):
    template_name = 'sale_list.html'
    model = Sale
    context_object = 'sale_list'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(SaleList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context

rawDescription: Count objects with ListView

description: Count objects with ListView


code: word_list = [punctuation.sub("", word) for word in word_list]

rawDescription: Removing punctuation/numbers from text problem


rawDescription: Convert a Date in String Format to a datetime.date


code:
data = json.dumps({'type':'state', 'statstype':'1','area':'CA'})

ajax = requests.post("http://droughtmonitor.unl.edu/Ajax.aspx/ReturnTabularDM",
                  data=data,
                  headers=headers)
from pprint import pprint as pp

pp(ajax.json())

rawDescription: Get all td content inside tbody of tr in python using lxml


code:
def isOdd(num):
    if type(num) not in [int, long]:
        return False
    if str(num)[-1] in "13579":
        return True
    return False

rawDescription: How would I check if a number is odd in python without using modulo or a library?


code: result = requests.post(api, auth=auth)

rawDescription: Facing issue while POST when it has no payload (python code)


code:
points, values = zip(*d.items())

points = numpy.array(points)
values = numpy.array(values)

reds   = values[:, 0]
greens = values[:, 1]
blues  = values[:, 2]

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
import numpy as np

keys = ['key1', 'key2', 'key3']

values = np.matrix([
    [1.1, 1.2, 1.3, 1.4],
    [2.1, 2.2, 2.3, 2.4],
    [3.1, 3.2, 3.3, 3.4]
])

weights = np.matrix([[10., 20., 30., 40.]]).transpose()

res = (values * weights).transpose().tolist()[0]

items = zip(res, keys)
items.sort(reverse=True)

rawDescription: Fastest way to rank items with multiple values and weightings


code: parent_pks = recent.values_list('parent', flat=True).distinct()

rawDescription: Django unique filtering

description: Django unique filtering


rawDescription: Initializing numpy masked array from Python int list with None values


code:
from __future__ import print_function
import random
import timeit
from itertools import chain
import numpy as np

def unique_concatenate(x):
    return np.unique(np.concatenate(x))

def short_set_union_rest(x):
    # This assumes x[0] is the shortest list in x
    return list(set(x[0]).union(*x[1:]))

def long_set_union_rest(x):
    # This assumes x[-1] is the longest list in x
    return list(set(x[-1]).union(*x[1:]))

def empty_set_union(x):
    return list(set().union(*x))

def set_chain(x):
    return list(set(chain(*x)))

big_range = list(range(10**7))
small_range = list(range(10**5))
many_uniques = [[random.choice(big_range) for i in range(j)]
                for j in range(10, 10000, 10)]
many_duplicates = [[random.choice(small_range) for i in range(j)]
              for j in range(10, 10000, 10)]
many_small_lists = [[random.choice(big_range) for i in range(10)]
                    for j in range(10, 10000, 10)]
few_large_lists = [[random.choice(big_range) for i in range(1000)]
                    for j in range(10, 100, 10)]

if __name__=='__main__':
    for x, n in [('many_uniques', 1), ('many_duplicates', 4),
                 ('many_small_lists', 800), ('few_large_lists', 800)]:
        timing = dict()
        for func in [
                'unique_concatenate', 'short_set_union_rest', 'long_set_union_rest',
                'empty_set_union', 'set_chain']:
            timing[func, x] = timeit.timeit(
                '{}({})'.format(func, x), number=n,
                setup='from __main__ import {}, {}'.format(func, x))
        print('{:20} | {:20} | {}'.format('func', 'x', 'time'))
        for key, t in sorted(timing.items(), key=lambda item: item[1]):
            func, x = key
            print('{:20} | {:20} | {:.3f}'.format(func, x, t))
        print(end='\n')

rawDescription: Fastest way to get union of lists - Python


code:
class AddressableHardware(object):
    """
    Base class for addressable hardware components.

    Attributes:
    base_address -- the base address of the device.
    """

    def __init__(self, base_address):
        self.base_address = base_address

class MyHardware(AddressableHardware):
    """
    An example hardware device.
    """

    reg1 = RegisterDescriptor(2, 4)
    reg2 = RegisterDescriptor(6, 1)

    def __init__(self, base_address):
        AddressableHardware.__init__(self, base_address)

mh = MyHardware(0x2E)
print(mh.reg1)
mh.reg2 = b'\x00'

rawDescription: Python - hardware handling, how to efficiently implement hardware registers as a property in an object


code:
square_list = []
[square_list.append(i**2) for i in range(1,6)]

rawDescription: what do the brackets mean around this python line?

description: What do the brackets mean around this python line


code:
import re

string = "He is 100, I am 18.5 and we are 0.67. Maybe we should 100, 200, and 200b 200, 67.88"

s = re.findall(r"[-+]?\d*\.\d+|\d+", string)

print(s)

rawDescription: How to extract only numbers from input file. Numbers can be float/int

description: Extract only numbers from input file. Numbers can be float/int


code:
def foo_generator():
    i,r = foo()
    while i != 0:
      yield i,r
      i,r = foo()

myList = list(foo_generator())

rawDescription: Python List Comprehension. Generating a List by repeatedly calling a function till it returns a predefined value


code:
Usage
d = MultiKeyMultiValNonDeterministicDict()

d["red","blue","green"] = {
    # {rule_set} : {result: probability}
    frozenset(["red", "green"]): {"ballon": 0.8},
    frozenset(["blue"]): {"toy": 0.15},
    frozenset([]): {"car": 0.05}
}

rawDescription: Multikey Multivalue Non Deterministic python dictionary


rawDescription: Time Ticks: 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001


rawDescription: Checking QValidator's state

description: Checking QValidator's state


code:
l = [random.randint(0, 10) for i in range(300)]
plot(l)
plt.xlim(xmin=5)       # I set to start at 5. No label is draw
plt.xticks(arange(5, 301, 50))  # this makes the first xtick at left to be 5

rawDescription: How can I force pyplot to show axis limits

description: Force pyplot to show axis limits


code:
result = df.groupby(['JOB', 'NAME', 'MONTH', 'YEAR']).sum().reset_index(['MONTH'])

#                   MONTH  DAYS  SALARY
# JOB    NAME YEAR
# Employ Mary 2014      1    15     200
#             2014      2     5     190
#             2013     12     5      23
# Worker Bob  2014      1    21     210
#             2014      2     8      80
#             2013     12     3      17

rawDescription: Pandas multiple index with multiple aggregate functions


code:
folder = 1
run_folder = os.path.join(currentwd, 'Folder_{:03d}'.format(folder))

rawDescription: os.path.join producing an extra forward slash

description: Os.path.join producing an extra forward slash


code:
if request.GET.get('type', None) == 'json' and not request.user.is_authenticated():
    #check cache
    cached_page = cache.get(request.get_full_path())
    if cached_page:
        return HttpResponse(json.dumps(cached_page), content_type="application/json")

rawDescription: Django cache 2 different versions of a url (JSON & HTML)


code: dict(tuple(string.split(': ')) for string in fileobject.readlines())

rawDescription: Convert string from external file to Python dictionary


code:
from itertools import combinations
from math import factorial as fac  # extra

z = "asdfghjk"
n = len(z)  # extra
for i in range(1, 9):
    print("{} of {}, {} combinations".
          format(i, n, fac(n) // (fac(i)*fac(n-i))))  # extra
    for combo in combinations(z, i):
        print(''.join(combo), end = ', ')
    print('\n')  # extra

rawDescription: how to iterate a 8 letters, and i want them to iterate in length and content? Python

description: Iterate a 8 letters, and i want them to iterate in length and content? Python


code:
import re

tu = ('This is my first regex python example '
      'yahooa yahoouuee bbbiirdd',

      'bbbiirdd',

      'fookirooksooktook',

      'crrsciencezxxxxxscienceokjjsciencq')

reg   = re.compile(r'([bcdfghj-np-tv-z])(\1?)')
dereg = re.compile('science([^aeiou])|([^aeiou])ook')

def Frepl(ma):
    g1,g2 = ma.groups()
    if g2:  return 'science' + g2
    else:   return g1 + 'ook'

def Fderepl(ma):
    g = ma.group(2)
    if g:  return g
    else:  return 2*ma.group(1)

for strt in tu:
    resu =   reg.sub(Frepl  , strt)
    bakk = dereg.sub(Fderepl, resu)
    print ('----------------------------------\n'
           'strt = %s\n'    'resu == %s\n'
           'bakk == %s\n'   'bakk == start : %s'
           % (strt, resu, bakk, bakk==strt))

rawDescription: How do I reverse regex substitution?

description: Reverse regex substitution


rawDescription: How to delete elements of a circular list until there is only one element left using python?

description: Delete elements of a circular list until there is only one element left using python


code:
while self.running:
    product = produced() ### I/O operations
    queue.put(product)
for x in range(number_of_consumers):
    queue.put(None)  # Termination code

rawDescription: How to terminate Producer-Consumer threads from main thread in Python?

description: Terminate Producer-Consumer threads from main thread in Python


code:
import cv2
import cv2.cv as cv
import numpy as np
import math
# Load Image
img = cv2.imread('circles1.png',0)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

# Specify different radii
radii = np.arange(0,310,10)

# For each pair of radii...
for idx in range(len(radii)-1):
    # Get the minimum and maximum radius
    # Note you need to add 1 to each minimum
    # as the maximum of the previous pair covers this new minimum
    minRadius = radii[idx]+1
    maxRadius = radii[idx+1]

    # Hough Transform - Change here
    circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,5,
                               param1=25,param2=75,minRadius=minRadius,maxRadius=maxRadius)

    # Skip if no circles are detected - Change here
    if circles is None:
        continue

    circles = np.uint16(np.around(circles))

    # Go over circles, eliminating the ones that are not cocentric enough
    height, width = img.shape
    center = (width/2,height/2)
    for i in circles[0,:]:
        # draw the outer circle
        if math.sqrt((center[0]-i[0])**2 + (center[1]-i[1])**2) < 15:
            cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),1)
            # draw the center of the circle
            cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)

cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Circular Hough Transform misses circles

description: Circular Hough Transform misses circles


code:
with open('myconfig.yaml', 'r') as cfile:
   config = yaml.load(cfile)

rawDescription: Userfriendly way of handling config files in python?


code:
user = auth.authenticate(auth_link=link)
if user:
  auth.login(request, user)

rawDescription: Self Authenticating Links in Django

description: Self Authenticating Links in Django


code:
rect = self.hAA.create_rectangle(...)
...
self.hAA.itemconfig(rect, ...)

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


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

# border.py

import wx

class Example(wx.Frame):

    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title,
            size=(260, 180))

        self.InitUI()
        self.Centre()
        self.Show()

    def InitUI(self):

        panel = wx.Panel(self)

        panel.SetBackgroundColour('#4f5049')
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        midPan = wx.Panel(panel)
        midPan.SetBackgroundColour('#ededed')
        dummy = wx.StaticText(panel, wx.ID_ANY, "")
        midPan2 = wx.Panel(panel)
        midPan2.SetBackgroundColour('#1f1f1f')

        hbox.Add(midPan, -1, wx.LEFT|wx.TOP, border=10 )
        hbox.Add(dummy,-1, wx.LEFT,border=20)
        hbox.Add(midPan2, -1, wx.RIGHT, border=10)
        vbox.Add(hbox)
        panel.SetSizer(vbox)

if __name__ == '__main__':

    app = wx.App()
    Example(None, title='Border')
    app.MainLoop()

rawDescription: How to have border of different sizes in wxwidgets?

description: Have border of different sizes in wxwidgets


rawDescription: Python seek on remote file using HTTP

description: Python seek on remote file using HTTP


code:
                           # You've got a str "s".
s = s.decode('latin-1')    # (or what the encoding might be …)
                           # Now "s" is a unicode object.
s = s.encode('utf-8')      # Encode as UTF-8 string.
                           # Now "s" is a str again.
s = urllib2.quote(s)       # URL encode.
                           # Now "s" is encoded the way you need it.

rawDescription: Python encode url with special characters


rawDescription: Converting dataframe to numpy array causes all numbers to be printed in scientific notation


code:
import networkx as nx

def binary_tree_layout(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5,
                  pos = None, parent = None):
    '''If there is a cycle that is reachable from root, then this will see infinite recursion.
       G: the graph
       root: the root node of current branch
       width: horizontal space allocated for this branch - avoids overlap with other branches
       vert_gap: gap between levels of hierarchy
       vert_loc: vertical location of root
       xcenter: horizontal location of root
       pos: a dict saying where all nodes go if they have been assigned
       parent: parent of this branch.
       each node has an attribute "left: or "right"'''
    if pos == None:
        pos = {root:(xcenter,vert_loc)}
    else:
        pos[root] = (xcenter, vert_loc)
    neighbors = G.neighbors(root)
    if parent != None:
        neighbors.remove(parent)
    if len(neighbors)!=0:
        dx = width/2.
        leftx = xcenter - dx/2
        rightx = xcenter + dx/2
        for neighbor in neighbors:
            if G.node[neighbor]['child_status'] == 'left':
                pos = binary_tree_layout(G,neighbor, width = dx, vert_gap = vert_gap,
                                    vert_loc = vert_loc-vert_gap, xcenter=leftx, pos=pos,
                    parent = root)
            elif G.node[neighbor]['child_status'] == 'right':
                pos = binary_tree_layout(G,neighbor, width = dx, vert_gap = vert_gap,
                                    vert_loc = vert_loc-vert_gap, xcenter=rightx, pos=pos,
                    parent = root)
    return pos

rawDescription: preserving the left and right child while printing python graphs using networkx

description: Preserving the left and right child while printing python graphs using networkx


code:
class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True :
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(2,y,anchor="nw", text=linenum)
            i = self.textwidget.index("%s+1line" % i)

rawDescription: Tkinter adding line number to text widget


code:
for f_a in glob.glob(file_directory + "*_data_a.dat"):
    process_file(f_a, 'a')
    for f_b in glob.glob(file_directory + f_a[:-11] + "_data_b.dat"):
        # we only ever expect to find one item to loop over here though
        process_file(f_b, 'b')

rawDescription: Using glob twice in a Python script

description: Using glob twice in a Python script


code: t = (Vf-Vi)/a

rawDescription: Solving a physics equation in Python

description: Solving a physics equation in Python


code: two_word_sets = ["mike dc", "car dc", "george dc", "jerry dc"]

rawDescription: Python - print tab delimited two-word set


code:
import requests
import urllib

session = requests.Session()

file={'file':(open('practice.txt','r').read())}

url = 'http://www.camp.bicnirrh.res.in/featcalc/tt1.php'

payload = {
  'length'   :'length',     #Length
  'netcharge':'netcharge',  #Net Charge
  'aliphatic':'aliphatic',  #Aliphatic Index
  'gravy'    :'gravy'       #Hydrophobicity
  }

raw = urllib.urlencode(payload)

response = session.post(url, files=file, data=payload)

print(response.text)

rawDescription: Using request.post to post multipart form data via python not working


rawDescription: Is there a Python equivalent to the mahalanobis() function in R? If not, how can I implement it?


code:
p = subprocess.Popen('/usr/bin/wc -l A-Z*/A-Z*.F*', shell=True,
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
(output, _) = p.communicate(input='')

rawDescription: Correct incantation of subprocess with shell=True to get output and not hang


code:
def OnPageNavigation(self, evt):
    ...
    uri = evt.GetURL() # you may need to deal with unicode here

    if "PROXY/HOVER_EVENT_START/" in uri:
        # Simple way to get the link
        link = uri.split("PROXY/HOVER_EVENT_START/")[1]
        ...
        # Run your mouseover code
        ...
        evt.Veto()
        return
    elif "PROXY/HOVER_EVENT_END/" in uri:
        ...
        # Run your mouseout code
        ...
        evt.Veto()
        return
    ...

rawDescription: Detect link mouseover events in wxPython's html2-webview


code:
from flask import url_for

if form.validate_on_submit():
    meal = form.meal.data
    return redirect(url_for('tip_calculator', meal=meal))

rawDescription: How do I make this function redirect to a given html page?

description: Make this function redirect to a given html page


code:
from urllib.request import urlopen
print(urlopen('http://bit.ly/1cPIdPg').geturl())

rawDescription: Using python to expand a bit.ly link

description: Using python to expand a bit.ly link


code: print ("The area is", area)

rawDescription: How to write a program in python 3.3.4 that works out the area of a rectangle?

description: Write a program in python 3.3.4 that works out the area of a rectangle


code:
N = len(B)
result = np.full(len(C), np.nan)
result[:N] = np.where(np.in1d(C[:N], A), B, np.nan)

rawDescription: Get Value From a NumPy Array

description: Get Value From a NumPy Array


code: title = re.findall('(?s)<title>(.*?)</title>', content)

rawDescription: Having issues with re.findall

description: Having issues with re.findall


code: a = (i for i in range(1e12))

rawDescription: Python: itertools.product consuming too much resources


code:
bear = wn.synsets('bear', pos='n')[0]
bear.definition()
black_bear = wn.synsets('black_bear', pos='n')[0]
black_bear.definition()
hypobear = set([i for i in bear.closure(lambda s:s.hyponyms())])
hyperblackbear = set([i for i in black_bear.closure(lambda s:s.hypernyms())])
black_bear in hypobear
animal = wn.synsets('animal')[0]
animal.definition()
hypoanimal = set([i for i in animal.closure(lambda s:s.hyponyms())])
black_bear in hypoanimal
bear in hypoanimal

rawDescription: How to determine multiword A is a B in wordnet?

description: Determine multiword A is a B in wordnet


code:
[]
['trxns.xml', 'foobar.xml']
['foobar.xml', 'trxns.xml']

rawDescription: Problem with shelve module?

description: Problem with shelve module


code:
l=['a', 'b', 'c']
''.join(l)
'-'.join(l)
' - spam ham and eggs - '.join(l)

rawDescription: Concatenate elements of a list

description: Concatenate elements of a list


code:
import re

def mycmp(version1, version2):
    def normalize(v):
        return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")]
    return cmp(normalize(version1), normalize(version2))

rawDescription: Version number comparison

description: Version number comparison


code:
def locatexml(pattern,exfiles=None):
    for path, dirs, files in os.walk(settings.MEDIA_ROOT):
        for filename in fnmatch.filter(files, pattern):
            if filename not in exfiles:
                yield os.path.join(path, filename)

rawDescription: Exclude python list containing filenames in os.walk


rawDescription: PIL and Bitmap from WinAPI

description: PIL and Bitmap from WinAPI


code:
index_first = bisect.bisect_left(preprocessed_events, (start_date,))
index_last = bisect.bisect_right(preprocessed_events, (end_date,))

rawDescription: Structure to store and retrieve date information between two specific dates


rawDescription: Get a complicated if-statement to work with an array? Python


code:
number = [53, 64, 68, 71, 77, 82, 85]
col_one = list(itertools.combinations(number, 4))
col_two = [[n for n in number if n not in c1_list] for c1_list in col_one]

rawDescription: Randomizing an array into two arrays

description: Randomizing an array into two arrays


code:
a_list = ['a', 'b', 'c', 'd']
iter_list = iter(a_list)

for val in iter_list:
   print(val) # do_stuff(val)
   if val == 'b':
       break

print('taking a break')
# do_stuff()

for val in iter_list:
    print(val) #continue_doing_stuff(val)

rawDescription: Is there a way to remember the position in a python iterator?


code: root.bind("1", some_function)

rawDescription: Python Keystroke / Mouseclick Refference, codes list?


code: [x+y for x in '12345' for y in 'abc']

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
def ifnull(var, val):
  if var is None:
    return val
  return var

foo = ifnull(foo, 42)

rawDescription: Python equivalent for MySQL's IFNULL

description: Python equivalent for MySQL's IFNULL


code:
sort_idx = np.argsort(Z1[:, 0])
sorted_insert = np.searchsorted(Z1[:, 0], Z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)

rawDescription: Matching elements in numpy array

description: Matching elements in numpy array


code:
# This is so called association table, which links two tables in many-to-many
# relationship.  In this case it links same table's ('users') different rows.
user_contacts = Table(
    'user_contacts', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('contact_id', Integer, ForeignKey('users.id'), primary_key=True),
)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    contacts = relationship(
        'User',
        secondary=user_contacts,
        primaryjoin=id==user_contacts.c.user_id,
        secondaryjoin=id==user_contacts.c.contact_id
    )

rawDescription: Trouble mapping multiple foreign keys to parent table


code: df.merge(mdf, on='id', how='left')

rawDescription: Python Pandas isin return index

description: Python Pandas isin return index


code:
first = set(open('firstFile').readlines())
second = set(open('secondFile').readlines())

diff = second - first

rawDescription: Python diff and get the new part

description: Python diff and get the new part


rawDescription: how to group a text file by first 3 characters of lines?

description: Group a text file by first 3 characters of lines


code: a.a = a.a

rawDescription: Why set a bound method to python object create a circular reference?


rawDescription: Special case when finding min key for dictionary in Python


code:
a =  [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]
from collections import OrderedDict
list(OrderedDict.fromkeys(y for x in a for y in x))

rawDescription: How to create a list only with a unique element using this list?

description: Create a list only with a unique element using this list


rawDescription: can I save models in this way in Django ?

description: Save models in this way in Django


rawDescription: get all decimal places after division

description: Get all decimal places after division


code:
from collections import defaultdict

out = defaultdict(dict)
for name, phonenumber in phone.iteritems():
    out[name]['phone'] = phonenumber
for name, address in addr.iteritems():
    out[name]['address'] = address

rawDescription: Merge two dictionaries while sharing the keys


rawDescription: How can I convert a bytestring array in a hex string in Python 3.4?

description: Convert a bytestring array in a hex string in Python 3.4


code:
def callproc(self, procname, args=()):
    from types import UnicodeType
    db = self._get_db()
    charset = db.character_set_name()
    for index, arg in enumerate(args):
        q = "SET @_%s_%d=%s" % (procname, index,
                                     db.literal(arg))
        if isinstance(q, unicode):
            q = q.encode(charset)
        self._query(q)
        self.nextset()

    q = "CALL %s(%s)" % (procname,
                         ','.join(['@_%s_%d' % (procname, i)
                                   for i in range(len(args))]))
    if type(q) is UnicodeType:
        q = q.encode(charset)
    self._query(q)
    self._executed = q
    if not self._defer_warnings: self._warning_check()
    return args

rawDescription: Using variables in Stored procedures with Python and MySQL


code:
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

rawDescription: Python socket works as a telnet connection and requires double read


code:
def do_really_complicated_thing(info):
    # lots of complicated steps
    return really_complicated_data

rawDescription: Python Flask - Processing input obtained from front-end in the back-end


code: scipy.optimize.fmin(lambda r: -f(r), 10)

rawDescription: maximum of a function on a specified domain in iPython

description: Maximum of a function on a specified domain in iPython


code: '''He yelled "Whatever's the matter?"'''

rawDescription: Does Python have an equivalent of Perl's qq?


code:
for i in range(10):
    button = tk.Button(...)
    button.configure(command=lambda b=button: move(b))

rawDescription: How to get the variable name of a button I have just clicked, tkinter

description: Get the variable name of a button I have just clicked, tkinter