code:
import numpy as np
...
def on_message(client, userdata, msg): # msg.payload is incoming data
    img = base64.b64decode(msg.payload);
    npimg = np.fromstring(img, dtype=np.uint8);
    source = cv2.imdecode(npimg, 1)

rawDescription: From JPG to b64encode to cv2.imread()

description: From JPG to b64encode to cv2.imread()


code: [[int(y) for y in x] for x in values]

rawDescription: Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?


rawDescription: How should I show results of BeautifulSoup parsing in Django?


code:
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
result = urllib.request.urlopen(request)
resulttext = result.read()

rawDescription: How to use urllib in python 3?

description: Use urllib in python 3


code:
from itertools import dropwhile
import operator

l = list(dropwhile(operator.not_, l))

rawDescription: Delete 0s that occur only at the beginning of a list


rawDescription: Merge lists of different size with order


rawDescription: Smallest ASCII Value in a List

description: Smallest ASCII Value in a List


code:
import email.header as eh

unicode_data= u''.join(
    str_data.decode(codec or 'ascii')
    for str_data, codec
    in eh.decode_header('=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='))
# unicode_data now is u'Πεζοπορία στον Κιθαιρώνα'

rawDescription: Python encoding ISO to UTF8

description: Python encoding ISO to UTF8


code: df2[['m','d']].apply(lambda x: (abs(df1.m - x.m) < df1.d +x.d).any(), axis=1)

rawDescription: Determine if one range is within another


code: 'SELECT *  FROM mytable mytable where time between' +UNIQUE_DATES[i] +'and'+ UNIQUE_DATES[j]   ;

rawDescription: Memory efficient way of fetching postgresql uniqueue dates?


code: listC = [value if index not in listB else 0 for index, value in enumerate(listA)]

rawDescription: Update list elements based on a second list as index


rawDescription: Fill zero values of 1d numpy array with last non-zero values


code:
objOut.obj = [1, 2, 3]
objOut.obj.append(0.25)
objOut.obj.extend([4, 5, 6])

rawDescription: Modify a member variable outside the class object and have changes in the class object


code:
import os, os.path

for root, _, files in os.walk(dirtocheck):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.getsize(fullpath) < 200 * 1024:
            os.remove(fullpath)

rawDescription: Python script to loop through all files in directory, delete any that are less than 200 kB in size


code:
import random
s = random.randint(0, 2**10000 - 1)

rawDescription: Generating a 10000 bit random sequence

description: Generating a 10000 bit random sequence


code:
int(not 0)
int(not 1)
not 0 == 1
not 1 == 0

rawDescription: python how to "negate" value : if true return false, if false return true

description: Python how to "negate" value : if true return false, if false return true


code: np.random.randint(1, 10, (2,5))

rawDescription: generating random values based on condition in structured array python

description: Generating random values based on condition in structured array python


code:
class FileUpload(models.Model):
    docFile = models.FileField(upload_to=path_file())

rawDescription: Delete a media file after each succesive upload in Django


code:
from datetime import datetime
import pytz
import calendar
calendar.timegm(pytz.timezone('America/Los_Angeles').localize(datetime.strptime('2012-11-20 00:00:00', '%Y-%m-%d %H:%M:%S')).utctimetuple())

rawDescription: How to convert datetime in Pacific timezone to UTC timestamp?

description: Convert datetime in Pacific timezone to UTC timestamp


code:
import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

rawDescription: How to make an unaware datetime timezone aware in python

description: Make an unaware datetime timezone aware in python


code:
class Product(models.Model):
    name = models.CharField(max_length=20)
    stock = models.IntegerField()
    price = models.FloatField()

class Desktop(Product):
    memory_size = models.CharField(max_length=20)
    storage_size = models.CharField(max_length=20)
class Monitor(Product):
    resolution = models.CharField(max_length=20)
    screen_size = models.CharField(max_length=20)

rawDescription: Django: Model with varying fields (Entity-Attribute-Value model)


code: re.findall(".+resume.*\.pdf", j, re.I)

rawDescription: Finding and moving PDF and DOC files to different directories using python


rawDescription: SVD - Matrix transformation Python

description: SVD - Matrix transformation Python


code:
def make_combinations(drivers, vehicles):
    return [
        Combination(driver, vehicle)
        for driver in drivers
        for vehicle in vehicles]

rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


rawDescription: Efficient storage of large string column in pandas dataframe


code:
repr(cols)
x.replace("u", "")

rawDescription: pandas column names to list

description: Pandas column names to list


code:
import copy
a = copy.deepcopy(b)
c = hybrid_array(a,args)

rawDescription: apply two functions to the two halves of a numpy array

description: Apply two functions to the two halves of a numpy array


rawDescription: Numpy: efficient way to generate combinations from given ranges


code: plt.scatter(x.index, x.values)

rawDescription: Python sort_values plot is inverted

description: Python sort_values plot is inverted


code:
from spyne.util.wsgi_wrapper import WsgiMounter

app1 = Application([SomeService], tns=namespace1,
    in_protocol=Soap11(), out_protocol=Soap11())
app2 = Application([SomeOtherService], tns=namespace2,
    in_protocol=Soap11(), out_protocol=Soap11())
wsgi_mounter = WsgiMounter({
    'app1': app1,
    'app2': app2,
})

rawDescription: Multiple namespaces in spyne SOAP web service


code:
all_matches = p1.finditer(your_string)
matches = [match.group() for match in all_matches if match.group() not in ('=', '=>')]

rawDescription: python regexp matching one or more characters in a group, except for particular alternatives

description: Python regexp matching one or more characters in a group, except for particular alternatives


code:
import requests

data = requests.get('http://vimeo.com/api/v2/video/31161781.json').json()

rawDescription: How to retrieve and display a Vimeo video's JSON data in python 3.x?

description: Retrieve and display a Vimeo video's JSON data in python 3.x


code: pred.apply(lambda row: row.loc[useProb.loc[row.name]], axis=1)

rawDescription: Create a Series from a Pandas DataFrame by choosing an element from different columns on each row


code:
from datetime import datetime
a = datetime(2014,11,10)  # works just the same, but you can also
b = datetime(2014,12,24)  # add hours/minutes/seconds etc.
b-a
(b-a).days

rawDescription: Python Calculation

description: Python Calculation


code:
import random

with open("file.txt") as x:
    words = x.read().splitlines()

def c_grid(l):
    grid = [listofwords[i:i + 5] for i in range(0, len(listofwords), 5)]
    for l in grid:
        print("".join("{:10}".format(i) for i in l))

listofwords = []
for i in range(25):
    myLen = len(words)
    res = random.choice(range(myLen))
    listofwords.append(words.pop(res))

print(listofwords)
c_grid(listofwords)

rawDescription: Python - Using Random with No Repeated Words and Selecting a Spare Word from a List


code:
class Person(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

rawDescription: In Django how can I search for related models based on the order they were added to a ManyToMany Field?


code:
def runs_of_ones_list(bits):
  return [sum(g) for b, g in itertools.groupby(bits) if b]

rawDescription: find length of sequences of identical values in a numpy array

description: Find length of sequences of identical values in a numpy array


code:
name_story = {
    'name': dict['data']['name'],
    'story': dict['data']['story'] + dict['data']['story2'],
}

rawDescription: Layer between data extraction and storage


rawDescription: Possible to modify every first tuple element in a list of tuples?


code:
import struct

binary_value = struct.pack('!2IH50s', seqno, ip, port, usrname)

rawDescription: How to Pack Different Types of Data Together into Binary Data with Python


code:
def approx_binomial(n, p, size=None):
    gaussian = np.random.normal(n*p, n*p*(1-p), size=size)
    # Add the continuity correction to sample at the midpoint of each integral bin.
    gaussian += 0.5
    if size is not None:
        binomial = gaussian.astype(np.int64)
    else:
        # scalar
        binomial = int(gaussian)
    return binomial

rawDescription: Alternative to numpy.random.binomial that allows 64 bits or more?


code:
(r'profile/$', login_required(profile,'student')),
(r'editprofile/$', login_required(editprofile,'student')),

rawDescription: Django - view, url weirdness

description: Django - view, url weirdness


code:
class SimpleTest(TestCase):
   fixtures = ['test_data.json']

rawDescription: Overwrite auto_now for unittest

description: Overwrite auto_now for unittest


code:
tablero_data1 = [(((1,), (3,), (1,)), ((3,), (1,), (1,))), [[0, 0, 0], [0, 0, 0],[0, 0, 0]]]
tablero_data2 = [(((1, 2), (1,), (1, 1)), ((1, 2), (1,), (1, 5))), [[0, 1, 0], [0, 0, 2], [0, 0, 0]]]

def print_board(board_data:"[border,inside]"):
    """border = (rows,columns)
       inside = [ [int] ]
       columns = ( espesication, )
       rows = ( espesication, )
       espesication = (int,)"""
    (rows,columns),inside = board_data
    board_size = len(columns)
    nivel_columns = max(map(len,columns))
    nivel_rows = max(map(len,rows))
    rows    = tuple(map(lambda x: x+(" ",)*nivel_rows,rows))
    inside  = list(map(lambda f:f[:board_size],inside))
    columns = tuple(map(lambda esp:tuple(reversed(esp)),columns))
    for i in reversed( range(nivel_columns) ):#print columns info
        for esp in columns:
            if len(esp)>i:
                print("  %d  "%esp[i],end="")
            else:
                print( "     ",end="")
        print()
    for j,fila in enumerate(inside):#print rows
        print("".join(map(lambda i: "[ %s ]"%cell_text(i),fila)) +" "+ " ".join(map(str,rows[j][:nivel_rows]))+"|" )

print_board(tablero_data1)
print()
print_board(tablero_data2)

rawDescription: Python 3 Picross Board Print

description: Python 3 Picross Board Print


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

rawDescription: Running syncdb in django after converting to ConfigParser


code:
class Foo:
    abc = classmethod(A.abc)

    @classmethod
    def abcd(cls, fn=A.abc):
        pass

rawDescription: How to surely refer to global objects in a class during definition?

description: Surely refer to global objects in a class during definition


code:
def FetchOneAssoc(cursor) :
    data = cursor.fetchone()
    if data == None :
        return None
    desc = cursor.description

    dict = {}

    for (name, value) in zip(desc, data) :
        dict[name[0]] = value

    return dict

rawDescription: Pulling entry from MySQLdb in Python

description: Pulling entry from MySQLdb in Python


code: new_list = [[0 if sublist[0] is 'A' else 1, sublist[1], -1 if sublist[0] is 'A' else 1.2*sublist[1]] for sublist in plot]

rawDescription: Edit and append items to nested list - Python 2.7


rawDescription: getting values from a numpy array between two points

description: Getting values from a numpy array between two points


code:
import os

need_newline = False
try:
    with open('sample_FACTS_bronto_import_add.csv', 'rb') as f:
        f.seek(0, 2)
        if f.tell() > 0:
            f.seek(-1, 1)
            need_newline = f.read(1) != b'\n'
except IOError:
    pass

with open('Franchise_Name_Scrub_List.csv', 'rb') as f1, \
     open('sample_FACTS_bronto_import_add.csv', 'ab') as f2:
    if need_newline:
        f2.write(os.linesep.encode())
    f2.writelines(f1)

rawDescription: Writing csv in python

description: Writing csv in python


code:
A = zeros(N)
for k in range(N):
    def callback(x):
        return k*x

    A[k] = integrate(callback, a, b)

rawDescription: Python changing function definition in loop?


code:
def anagram_match(w):
    w = list('w')
    w.sort()
    return w == ARG

rawDescription: Find out the words from a python list which contains permutation of another word


rawDescription: match element of a list based on another list in python where elements of one list is the substring of elements of another list

description: Match element of a list based on another list in python where elements of one list is the substring of elements of another list


code:
print(arr[0] in G)
# True

rawDescription: Dictionary not recognizing floating point keys


code: print (mydate.strftime('%Y-%m-%d'))

rawDescription: datetime objects format

description: Datetime objects format


code:
url = "https://release.domain.com/release_cr_new.plreleaseid=26851&v=2&m=a&dump_csv=1"
headers = {
  "Accept-Encoding" : "gzip,deflate,sdch",
  "Accept-Language" : "en-US,en;q=0.8",
  "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36",
  "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Referer" : "https://release.domain.com/release_cr_new.html?releaseid=26851&v=2&m=a",
  "Cookie" : "releasegroup=Development; XR77=3q3pzeMQc1gf-jDlpNtkgr4WvZYqxVZSYzeQHfGAwMTAeZQ6D3g2e6w; __utma=147924903.423899313.1373397746.1378841205.1380290587.15; __utmc=147924903; __utmz=147924903.1380290587.15.14.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); pubcookie_s_release.domain.com=Hm17WT1VJbPpBLOQ+NhtyBbZlfO9qntsoGP0P8BEVeh4d0ay+THE3EkNLc6PV5rJ40Ui7uj/+c6f2tzZYWOJ/j+dyoP5l+J//rL875K9ERxio1FZeiUVRQgeabetZ+V1AWlrkjURmAw2SU1hEz/f2pCt0sHe06C14vWA95PFu1Smp6viWOL8QnaPHFWhGU3uQQH5Wxex0CziHbrYXHuKwnxwWejvVtTM8e8aIHkM2WuB3IIDhGMVtd0r292owvcv6Rvcl7tYSoQaQYfSpPZreXo4tNO9gh9ZIGqao8LaCfG5Fw8+Ow5wQKf2ryVuPc8Ah4MTIzC1UeZxBtxSTyZk5E1in7LCV9E+d/5G84U+ECcdn166gJg1iMG68II81YJO9fYs91gGtA5iUa6h3RpFo+ysBkqbHjCpetOUxfHh47sdr4nUoIWEb0LfKVTYfvmW6BNGx4m90PqE8aQlknv7zxqAQrujqe7h5zSpmaD5UjrfRwp7lYD+6e88vgQzLgWlcAA=; _session_id=eb0095f849a509c3cf65b43680b3002a; default_column_2=bugid%2Cloginname%2Ccomponent%2Cversionvalue%2Cbugdate%2Cshortdescription%2Cpriority%2Cstatus%2Cqacontact%2Csqa_status%2Cis_dep"
}

response = requests.get(url, headers=headers)

rawDescription: How to download a file (perl cgi backend) using python requests

description: Download a file (perl cgi backend) using python requests


code: one/two

rawDescription: What's the best way to retrieve the module path from the project in python?


code:
mapping = np.where(people['b'] > people['a'], 'Group1', 'Group2')
mapping
people.groupby(mapping).sum()

rawDescription: Groupby with User Defined Functions Pandas


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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.random((8, 10)), extent=(2, 6, -1, 1), interpolation='nearest', aspect='auto')

rawDescription: Aligning two combined plots - Matplotlib


rawDescription: How can I merge one dataframe into another, inserting rows that do not exist?

description: Merge one dataframe into another, inserting rows that do not exist


code:
def loads(str):
    file = StringIO(str)
    return Unpickler(file).load()

rawDescription: How to control what gets imported when you unpickle python object?

description: Control what gets imported when you unpickle python object


code:
cn = MySQLdb.connect('server', 'user', 'password', 'database')
c = cn.cursor()
unit_ids = ('0A1', '0A2', '0A3', '0A4')
c.execute("select count(*) from foo where id in %s", (unit_ids,))
c._last_executed

rawDescription: How can I prevent extra quotations being inserted into MySQLdb statement from Python?

description: Prevent extra quotations being inserted into MySQLdb statement from Python


code:
myObject = bge.logic.getCurrentController().owner

myObject['myproperty_named_has_run_before'] = True

rawDescription: How to permanently change a variable in a Python game loop

description: Permanently change a variable in a Python game loop


code: load_more = driver.find_element_by_link_text("LOAD MORE")

rawDescription: Selenium can't seem to find and click a button on website? - Python


code: threading.Timer(10, aFunc).start()

rawDescription: Python and multiprocessing... how to call a function in the main process?


rawDescription: Nested List and count()

description: Nested List and count()


code:
numpy.array([1, 2, 3, 4]).dtype
numpy.array([1, 2, 3.0, 4]).dtype
numpy.issubdtype(numpy.array([1, 2, 3, 4]).dtype, numpy.integer)
numpy.issubdtype(numpy.array([1, 2, 3.0, 4]).dtype, numpy.integer)

rawDescription: How to type check each element of 1 dimensional ndarray

description: Type check each element of 1 dimensional ndarray


code: doc = {'field1': docsite, 'field2': docsite.copy()}

rawDescription: Python Dictionary in Dictionary

description: Python Dictionary in Dictionary


code: [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0]

rawDescription: Is this list comprehension pythonic enough?


code:
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

rawDescription: Replace console output in python

description: Replace console output in python


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

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

x = np.array([10000, 1000, 100, 10, 1, 5, 50, 500, 5000, 50000])
y = np.array([-10000, -1000, -100, -10, -1, 5, 50, 500, 5000, 50000])

ax.plot(x,abs(y),'+-b',label='all data')
ax.plot(abs(x[y<= 0]),abs(y[y<= 0]),'o',markerfacecolor='none',
                                        markeredgecolor='r',
                                        label='we are negative')

ax.set_xscale('log')
ax.set_yscale('log')

ax.legend(loc=0)

plt.show()

rawDescription: Connect different data series with the same line


code:
def find_terms(words, max_words_per_term):

    # If there are no words, you've reached the end. Stop.
    if len(words) == 0:
        return []

    # What's the max term length you could generate from the remaining
    # words? It's the lesser of max_words_per_term and how many words
    # you have left.
    max_term_len = min(len(words), max_words_per_term)

    # Find all the terms that start with the first word.
    initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]

    # Here's the recursion. Find all of the terms in the list
    # of all but the first word.
    other_terms = find_terms(words[1:], max_words_per_term)

    # Now put the two lists of terms together to get the answer.
    return initial_terms + other_terms

rawDescription: How do I generate multi-word terms recursively?

description: Generate multi-word terms recursively


code:
import matplotlib.pyplot as plt

x, y = [0, 10, 20], [10, 0, 0]
fig, ax = plt.subplots()
ax.plot(x, y, 'ko')

# Pad by 5% of the data range before autoscaling:
ax.margins(0.05)

plt.show()

rawDescription: Markers hidden by axis

description: Markers hidden by axis


code: data = [[int(n) for n in line.split()] for line in ins]

rawDescription: Python read file into 2d list

description: Python read file into 2d list


rawDescription: Applying function to every other column in pandas dataframe


code:
import ruamel.yaml

file_name = 'input.yml'
from ruamel.yaml.util import load_yaml_guess_indent

config, ind, bsi = load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

ruamel.yaml.round_trip_dump(config, open('output.yml', 'w'),
                            indent=ind, block_seq_indent=bsi)

rawDescription: How to update yaml file using python

description: Update yaml file using python


code:
o5 = O5()
o5.method
o5.method()
o5.__dict__["var"]
o5.magic

rawDescription: Confused with getattribute and setattribute in python


code:
p = nx.shortest_path(gr,source=2, target=0)
# [2, 1, 0]

rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code:
with open('tilemap.txt') as input:
    tilemap = [list(line.strip()) for line in input]

rawDescription: Import text from a txt file as a list within a list, and manipulate that data with column / row coordinates


rawDescription: Error in the results of a list comprehension


code:
def peek(iterable):
    peek = iterable.next()
    return peek, itertools.chain([peek], iterable)

rawDescription: How do I check the content of iterable object?

description: Check the content of iterable object


code:
from itertools import chain, product
from pprint import pprint
pprint([tuple(chain.from_iterable(i)) for i in product(l2, [l1[0]], l3)])

rawDescription: How to append elements from 2 short lists into another big list of tuples?

description: Append elements from 2 short lists into another big list of tuples


code: firefox = webdriver.Firefox()

rawDescription: Using selenium at hosted app?

description: Using selenium at hosted app


code:
import urllib
url = u'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'
urllib.unquote(url)

rawDescription: How to decode url to path in python, django

description: Decode url to path in python, django


code:
import psutil

pythons_psutil = []
for p in psutil.process_iter():
    try:
        if p.name() == 'python.exe':
            pythons_psutil.append(p)
    except psutil.Error:
        pass

rawDescription: How to detect if a process is running using Python on Win and MAC

description: Detect if a process is running using Python on Win and MAC


code:
d = { 'foo' : very_long_value }

urlpatterns = patterns('',
    url('^aaaa/$', 'aaa', d),
    url('^bbbb/$', 'bbb', d),
    url('^cccc/$', 'ccc', d),
)

rawDescription: Django optional url parameter for each url() in a pattern()


rawDescription: url_for for class-based views in Flask-Admin

description: Url_for for class-based views in Flask-Admin


code:
from subprocess import Popen, PIPE, STDOUT

cmd = 'bash -i -c "alias"'
event = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
output = event.communicate()[0]
print(output)

rawDescription: How to show user aliases in python

description: Show user aliases in python


code:
from pprint import pprint as pp

matrix(None, 2,3)

matrix(None, 4,3)

x = matrix(None, 3,5,2)
pp(x)
x[1][3][0] = "test"
pp(x)

rawDescription: More elegant way to initialize list of duplicated items in Python


code:
from tkinter import *
from random import *

root= Tk()
col=10
row=10
num=[[randint(0,9) for i in range(col)] for j in range(row)]

labels = []
for k in range(row):
    theLabel= Label(root,text=' '.join(str(e) for e in num[k]))
    theLabel.pack()
    labels.append(theLabel)

def ch():
    for label in labels:
        row = [randint(0,9) for i in range(col)]
        label.config(text = ' '.join(str(e) for e in row))

root.after(5000,ch)
root.mainloop()

rawDescription: How to refresh the window with Tkinter

description: Refresh the window with Tkinter


code:
from zope.configuration import xmlconfig
from calc import eval

xmlconfig.file('configure.zcml')

assert eval('2 + 2') == 4

rawDescription: How to make zope load my ZCML?

description: Make zope load my ZCML


code:
class ball(self, size, color, name):
  self.size = size
  self.color = color
  self.name = name

rawDescription: python getting a specific attribute from a list of objects

description: Python getting a specific attribute from a list of objects


code:
def unmask(num, width, offset):
     return (num & (2**width - 1) << offset) >> offset

rawDescription: Converting binary timestamp to string

description: Converting binary timestamp to string


code: m = zeros(8)

rawDescription: How to auto-generate and assign variables corresponding to elements in a matrix?

description: Auto-generate and assign variables corresponding to elements in a matrix


code: cpy = get(x, 1, 2).copy()

rawDescription: Copy a single axis of a numpy array by index


code:
def listFunc(lst):
    if len(lst) == 0: return ''
    if len(lst) == 1: return lst[0]
    return ", and ".join([", ".join(lst[:-1]), lst[-1]])

rawDescription: Is there a better way to accomplish this python excercise? (Beginner)


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

numdata = 100
t = np.linspace(0, 100, numdata)
y = 1/t**(1/2.0)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.xaxis.set_ticks_position('top')
ax.yaxis.grid(linestyle = '-', color = 'gray')
ax.invert_yaxis()
ax.plot(t, y, 'g-', linewidth = 1.5)

plt.show()

rawDescription: How to plot with x-axis at the top of the figure?

description: Plot with x-axis at the top of the figure


rawDescription: Subset Sum with Backtracking on Python

description: Subset Sum with Backtracking on Python


code:
def gen_replace_value_with_definition(key_to_find, definition):
    for key in current_dict.keys():
        if key == key_to_find:
            current_dict[key] = definition
            yield True
    yield False

found = False
while not found:
    found = next(gen_replace_value_with_definition('corse', 'Definition of "corse" via generator'))

print(current_dict)

rawDescription: Python dictionary replace values

description: Python dictionary replace values


code: comptest('')

rawDescription: Python - Compress Ascii String

description: Python - Compress Ascii String


code:
df1 = DataFrame([[1,'one'],[2,'two'],[3,'three'],[4,'four'],[5,'five']], columns=['number', 'name'])
df2 = DataFrame([['a','one'],['b','too'],['c','three'],['d','fours'],['e','five']], columns=['letter', 'name'])

df2['name'] = df2['name'].apply(lambda x: difflib.get_close_matches(x, df1['name'])[0])
df1.merge(df2)

rawDescription: is it possible to do fuzzy match merge with python pandas?

description: Is it possible to do fuzzy match merge with python pandas


code:
idx = permutations + 3*np.arange(N)[:,None]
bb = aa.reshape(2,-1)[:,idx].reshape(2,N,3)

rawDescription: Select values from a set of arrays according to an array of permutations


rawDescription: Python nested for loop to split a file into lines then each line into variables


code:
#Setting linspace and making the fit, make sure to make you data numpy arrays
x_new = np.linspace(ms[0], ms[-1], dtype=float)
m = np.array(ms, dtype=float)
deg = np.array(degrees, dtype=float)
guess = np.array( [100, 500, -30, 350, -0.1, 0.0051, 1, -0.01, -0.01, -0.01], dtype=float)
p , e = optimize.curve_fit(piecewise_linear, m, deg)
#Plotting data and fit
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x_new, piecewise_linear(x_new, *p), '-', df)
ax.set_ylim([0, 450])
ax.set_xlim([0, 800])

rawDescription: Plotting a piece-wise fit to non-linear data


code:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

rawDescription: Can two distributions deliver the same package?


code:
import time

def localTzname():
    offsetHour = time.timezone / 3600
    return 'Etc/GMT%+d' % offsetHour

rawDescription: How to get system timezone setting and pass it to pytz.timezone?

description: Get system timezone setting and pass it to pytz.timezone


code:
blog = Blog(name='This is a blog post', tagline='python django')
blog.save(using='sqlite')

rawDescription: How to use other than default database

description: Use other than default database


code:
from functools import partial, update_wrapper

def annotate_from(f):
    return partial(update_wrapper,
                   wrapped=f,
                   assigned=('__annotations__',),
                   updated=())

rawDescription: How to type annotate overrided methods in a subclass?

description: Type annotate overrided methods in a subclass


rawDescription: Alternative of showbits() in Python to show 16 bit binary representation


code:
def qwer(num):
    return dict([(str(i), i) for i in range(num+1)])

rawDescription: What is the name of this dictionary?

description: What is the name of this dictionary


rawDescription: Drawing from certain probabilities in Gaussian Normal Multivariate Distribution in numpy


rawDescription: Open new prompts to run binaries in python


code:
import numpy as np
import pandas as pd

def mpmt(amt, i, nper):
    """
    Calculate the monthly payments on a loan/mortgage
    """
    i = i/12  # convert to monthly interest
    i1 = i + 1  # used multiple times in formula below
    return amt*i1**nper*i/(i1**nper-1)

def ipmt(amt, i, per, nper):
    """
    Calculate interest paid in a specific period, per, of a loan/mortgage
    """
    i = i/12  # convert to monthly interest
    i1 = i + 1  # used multiple times in formula below
    return (amt*i*(i1**(nper+1)-i1**per))/(i1*(i1**nper-1))

def amorttable(amt, i, nper):
    """
    Create an amortization table for a loan/mortgage
    """
    monthlypmt = mpmt(amt, i, nper)

    # the following calculations are vectorized
    df = pd.DataFrame({'month':np.arange(1, nper+1)})
    df['intpaid'] = ipmt(amt, i, df['month'], nper)
    df['prinpaid'] = monthlypmt - df['intpaid']
    df['balance'] = amt
    df['balance'] -= np.cumsum(df['prinpaid'])
    return df

print(amorttable(7692, .18, 12).round(2))

rawDescription: Using Excel like solver in Python or SQL


code: list(depthGenerator(PLACES, 1))

rawDescription: Python: Get items at depth? (set library?)


rawDescription: How do I generate a TimedeltaIndex from a column of timestamps where the each TimeDelta is generated with reference to the previous timestamp

description: Generate a TimedeltaIndex from a column of timestamps where the each TimeDelta is generated with reference to the previous timestamp


code:
def bisect_any_to_iter(pred, it):
    it = iter(it)
    head = []
    for i in it:
        if pred(i):
            head.append(i)
        else:
            tail = itertools.chain([i], it)
            break
    return iter(head), tail

a, b = bisect_iter_to_iter(str.isalpha, iter(l))
list(a)
list(b)

rawDescription: how to split a list in two at the point where predicate is first False

description: Split a list in two at the point where predicate is first False


code:
some_variable = convert("filename.pdf")
print(some_variable)
#do something with your variable

rawDescription: I want to extract text from a PDF to a .text file using PDFminer. I have found the code but I have no idea how to use it


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

dataX = np.array([1,2,3,4,5,6,7,8,9,10])
dataY = np.array([1193,1225,1125,1644,1255,13676,2007,2008,12359,1210])

ax = plt.subplot(111)
def on_click(event):
    if event.dblclick:
       ax.plot((event.xdata, event.xdata), (mean-standardDeviation, mean+standardDeviation), 'r-')
       plt.show()

def _yes(event):
    print("yolo")

mean = np.mean(dataY)
standardDeviation = np.std(dataY)

ax.plot(dataX, dataY, linewidth=0.5)
plt.connect('button_press_event', on_click)

axcut = plt.axes([0.9, 0.0, 0.1, 0.075])
bcut = Button(axcut, 'YES', color='red', hovercolor='green')
bcut.on_clicked(_yes)

plt.show()

rawDescription: Matplotlib Python: How to add panel button


code:
for article in bibliography:
    for key in article:
        ...

rawDescription: A more "pythonic" approach to "check for None and deal with it"


code: mynamedtuple = MyNamedTuple(firstvalue, secondvalue)

rawDescription: When and why should I use a namedtuple instead of a dictionary?


code:
for i, data in df.iterrows():
    holding_status = (df.loc[:(i-1), 'entry'] - df.loc[:(i-1), 'filtered_exit']).sum()
    if data.exit == 0 or i == 0:
        df.loc[i, 'filtered_exit'] = 0
    elif data.exit == 1:
        if holding_status == 0:
            df.loc[i, 'filtered_exit'] = 0
        elif holding_status == 1:
            df.loc[i, 'filtered_exit'] = 1

rawDescription: Using Pandas DataFrame to Generate Trading Signals


code:
from skimage import io
io.use_plugin('freeimage')
data = io.imread('/tmp/data.tif')

rawDescription: Should I bother for array type in Python?


code: pd.rolling_mean(df.T, 3)

rawDescription: Mean in group of columns

description: Mean in group of columns


code:
from string import uppercase as up
import itertools

def to_base(q, alphabet):
    if q < 0: raise ValueError( "must supply a positive integer" )
    l = len(alphabet)
    converted = []
    while q != 0:
        q, r = divmod(q, l)
        converted.insert(0, alphabet[r])
    return "".join(converted) or alphabet[0]

class TimestampUniqifier( object ):
    def __init__(self):
        self.last = ''
        self.counter = itertools.count()
    def __call__( self, str ):
        if str == self.last:
            suf = self.counter.next()
            return str + to_base( suf, up )
        else:
            self.last = str
            self.counter = itertools.count()
            return str

timestamp_uniqify = TimestampUniqifier()

rawDescription: How would you translate this from Perl to Python?


code:
Range('C3').value = list(zip([sum(x) for x in zip(Range('A3:A9').value,
                              Range('B3:B9').value)]))

rawDescription: Xlwings - adding columns

description: Xlwings - adding columns


code:
def pcm(clustering):
    n = clustering.size
    data = np.ones((n,), dtype=bool)
    indptr = np.arange(n+1)
    return csr_matrix((data, clustering, indptr))

rawDescription: Speeding up summing certain columns in a matrix


code:
keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
    result.append(attributes[key])

rawDescription: Building a list of dictionary values, sorted by key


code: temp_score += len(dic[j][2] & dic[k][2])

rawDescription: How to reduce the number of for-loops for shortening running time in Python programming?

description: Reduce the number of for-loops for shortening running time in Python programming


code:
import functools

def gen2func(generator):

    gen = []

    @functools.wraps(generator)
    def wrapper(*args, **kwargs):
        if not gen:
            gen.append(generator(*args, **kwargs))
        return next(gen[0])

    return wrapper

rawDescription: Function which computes once, caches the result, and returns from cache infinitely (Python)


code:
with open('myfile.txt', 'r') as f:
    text = f.read()

rawDescription: String from input is limited?

description: String from input is limited


code:
import pymel.core as pm
import pymel.core.uitypes as pmui

modelPanelList = []
modelEditorList = pm.lsUI(editors=True)
for myModelPanel in modelEditorList:
    if myModelPanel.find('modelPanel') != -1:
        modelPanelList.append(myModelPanel)

for modelPanel in modelPanelList:
    pmui.ModelEditor(modelPanel).setRendererName("ogsRenderer")

rawDescription: How to query current viewport renderer in maya

description: Query current viewport renderer in maya


rawDescription: Reshaping an dynamic array of numbers to a fixed size


code:
from collections import Counter

counts = Counter(row[0] for row in block)
block = [row for row in block if counts[row[0]] == 1]

rawDescription: Delete same rows from list of lists in python


code:
def test():
    for i in xrange(11):
         v = 'strain' + '%d' % i
         globals()[v] = []

test()
strain5

rawDescription: How can I use the command vars()[x] into a function?

description: Use the command vars()[x] into a function


code:
class Super:
   @classmethod
   def do_something(cls):
     print('Super doing something')

class Child(Super):
    def __init__(self):
        self.do_something = lambda: print('Child Doing Something')

rawDescription: python overriding a classmethod with an instance method

description: Python overriding a classmethod with an instance method


code:
import random

class Fight:
        def __init__ (self): self.scores = [0, 0]
        def heScores (self): self.scores [1] += 1
        def youScore (self): self.scores [0] += 1

        @property
        def best (self): return max (self.scores)

        @property
        def winner (self): return 'You win.' if self.scores [0] > self.scores [1] else 'He wins.'

fight = Fight ()
print ('Fight begins.')
question, answer = 'left', 'right'
while fight.best != 2:
    if random.randint (0, 1): question, answer = answer, question
    if answer in input ('He throws a {} hook, which way will you dodge? '.format (question) ):
        print ('Nice job, you knocked him out.')
        fight.youScore ()
    else:
        print ('Oh no, he knocked you out.')
        fight.heScores ()
print (fight.winner)

rawDescription: Using a class to keep score in python

description: Using a class to keep score in python


code: cmp_func = CMPFUNC(py_cmp_func)

rawDescription: How to create a CFuncType in Python

description: Create a CFuncType in Python


rawDescription: Using the if "x" in function to do a calculator but total isn't being produced


rawDescription: A list as a key for a dictionary

description: A list as a key for a dictionary


rawDescription: parsing a line into a dictionary through a list comprehension

description: Parsing a line into a dictionary through a list comprehension


code:
g
g = g.reset_index()
g

rawDescription: How to move pandas data from index to column after multiple groupby

description: Move pandas data from index to column after multiple groupby


code:
result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))

rawDescription: Getting all combinations of key/value pairs in Python dict


code:
import copy
board[1] = copy.copy(deck1)
board[1] = copy.deepcopy(deck1)

rawDescription: The Python assignment operator, function definitions, and variable definitions


code:
from eve import Eve
from eve.auth import BasicAuth

import bcrypt

class BCryptAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):
        # use Eve's own db driver; no additional connections/resources are used
        accounts = app.data.driver.db["accounts"]
        account = accounts.find_one({"username": username})
        return account and \
            bcrypt.hashpw(password.encode('utf-8'), account['salt'].encode('utf-8')) == account['password']

def create_user(documents):
    for document in documents:
        document['salt'] = bcrypt.gensalt().encode('utf-8')
        password = document['password'].encode('utf-8')
        document['password'] = bcrypt.hashpw(password, document['salt'])

app = Eve(auth=BCryptAuth)
app.on_insert_accounts += create_user

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

rawDescription: In Eve, how can you store the user's password securely?


code:
class MyRadioButton(QPushButton):
    checkSignal = QtCore.Signal(str)

    def __init__(self, value=None, label=None):
        QPushButton.__init__(self)
        self.__value = value
        self.__checked = False
        self.setCheckable(True)  # This will 'hold' the button once clicked
        self.clicked.connect(self.toggleCheck)  # Signal emitted on click

    def toggleCheck(self):
        if self.__checked == False:
                self.__checked = True
                self.checkSignal.emit(self.__value)
        else:
                self.__checked = False

rawDescription: Custom signal not working in PySide

description: Custom signal not working in PySide


code: C = B.subgraph(filter(lambda x:x[1]>10, B.degree(data['domain']).items()))

rawDescription: Python how to choose what to print in a networkX graph


code:
df
df.dtypes

rawDescription: match the dataframe with the list of columns names

description: Match the dataframe with the list of columns names


code:
import pypyodbc
connStr = """
DSN=myDb_SQLEXPRESS;
"""
cnxn = pypyodbc.connect(connStr)
crsr = cnxn.cursor()
sql = """
BULK INSERT myDb.dbo.SpikeData123
FROM 'C:\\__tmp\\biTest.txt' WITH (
    FIELDTERMINATOR='\\t',
    ROWTERMINATOR='\\n'
    );
"""
crsr.execute(sql)
cnxn.commit()
crsr.close()
cnxn.close()

rawDescription: How to Speed up with Bulk Insert to MS Server from Python with Pyodbc from CSV


rawDescription: Merge DataFrames in Pandas using the mean


rawDescription: On what CPU cores are my Python processes running?


code:
def reopen_binary(fobj):
    mode = fobj.mode
    if 'b' not in mode:
        mode += 'b'
    return open(fobj.name, mode)  # encoding and newline options don't apply

rawDescription: Re-open a file in binary mode with Python


code: pd.to_datetime(pd.Series(s) + '_2015', format='%b_%d_%Y')

rawDescription: Convert list to datetime in pandas

description: Convert list to datetime in pandas


code:
hands = [draw(5) for _ in xrange(1000)]
four_of_a_kinds = [hand for hand in hands if is_four_of_a_kind(hand)]
four_of_a_kinds_count = len(four_of_a_kinds)

rawDescription: Test 5-card hand for four of a kind

description: Test 5-card hand for four of a kind


rawDescription: How can I cluster a list of a list of tuple (tag, probability)? - python

description: Cluster a list of a list of tuple (tag, probability)? - python


code:
def chooseColor(self):
    color = askColor()
    self.b["bg"] = color # or however you change a color in python/tkinter

rawDescription: Python Tk - Dynamically change button, defined in function, on click


code:
g = df.groupby('id_customer')
g.head(2)

rawDescription: Pandas, create columns after groupby

description: Pandas, create columns after groupby


code:
from lxml import etree as ET
data = """

a

b

c

d

"""
tree = ET.fromstring(data)
value = "c"
int(tree.xpath("count(//ol/li[. = '%s']/preceding-sibling::li)" % value))

rawDescription: Find the number(position) of a node in list


code:
@my_dec
def my_view(request):
    return HttpResponse(...)

rawDescription: how to get the url of the view calling the decorator in the decorator?

description: Get the url of the view calling the decorator in the decorator


code:
import dis
def sum1():
    s = 0
    for i in range(1000000):
        s += i
    return s

dis.dis(sum1)

rawDescription: Python built-in sum function vs. for loop performance


code: ['blah', 'tete', 'head']

rawDescription: How to remove an array containing certain strings from another array in Python

description: Remove an array containing certain strings from another array in Python


code:
string = "BCVDBCVCBCBD"
i = 2
[x + y for x, y in zip(string, string[i:])]

rawDescription: Grouping in a list with sequence re-read


code:
name_filter = ['Brand','Color']

print(df[df.name.isin(name_filter)].pivot(index='ID', columns='name', values='Value'))

rawDescription: How to conditionally transpose in pandas (similar to SQL case when withn group by)

description: Conditionally transpose in pandas (similar to SQL case when withn group by)


rawDescription: Python & Pandas: series to timedelta

description: Python & Pandas: series to timedelta


rawDescription: Replace all non-alphanumeric characters in a string


code:
trial_seq = [0]*36
indices = range(36)
random.shuffle(indices)
for i in range(36):
    trial_seq[indices[i]] = i % 4;

rawDescription: Generating random numbers in range until a max for that number has been met in python


code: getAdditionalGooglePages = beautifulSoupObj.find_all('a', id="fl")

rawDescription: BeautifulSoup Django Parse for Links

description: BeautifulSoup Django Parse for Links


code: [a for a in re.split(r'([A-Z][a-z]*\d*)', txt) if a]

rawDescription: Splitting a string by capital letters

description: Splitting a string by capital letters


code:
from twisted.internet import reactor
reactor.stop()

rawDescription: How to stop a TimerService from within the LoopingCall

description: Stop a TimerService from within the LoopingCall


rawDescription: Storing values from loop in a list or tuple in Python


rawDescription: Python re.findall with * and **

description: Python re.findall with * and **


rawDescription: Replacing end numbers in a string python


code:
for loc in true_locs:
    if loc > last_true_loc + N:
        last_true_loc = loc
    else:
        input[loc] = False

rawDescription: Filling next N rows in pandas with False when True found


code:
from IPython.display import display,HTML,clear_output
HTML('<b>Hello world</b>')

rawDescription: Is it possible to dynamically update a cell using HTML for ipython Notebook


rawDescription: How to convert pandas single column data frame to series or numpy vector

description: Convert pandas single column data frame to series or numpy vector


code:
with open('/root/Dec/dec_no_quotes.csv', 'rb') as fin, \
    open('/root/Dec/dec_pipe.txt', 'wb') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout, delimiter='|')
    writer.writerows(reader)

rawDescription: python program gets KILLED with no errors during csv phare

description: Python program gets KILLED with no errors during csv phare


code:
stress_dict = {}

with open('stress.txt', 'r') as f:
    for line in f:
        word_stress = line.strip().split(',')
        word = word_stress[0].strip().lower()
        stress = word_stress[1].strip()
        stress_dict[word] = stress

rawDescription: Check for iambic pentameter?

description: Check for iambic pentameter


code:
n=4
[b[i:i+n] for i in range(len(b)-n+1)]

rawDescription: Quick implementation of character n-grams using python


code:
import HTMLParser
h= HTMLParser.HTMLParser()
h.unescape('alpha < β')

rawDescription: How can I change '>' to '>' and '>' to '>'?

description: Change '>' to '>' and '>' to '>'


rawDescription: How to discard part of function output in python?

description: Discard part of function output in python


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

x = np.exp2(np.arange(10))

plt.semilogy(x)
plt.yticks(x, x)

# Turn y-axis minor ticks off
plt.gca().yaxis.set_minor_locator(mpl.ticker.NullLocator())

plt.show()

rawDescription: PyLab: Plotting axes to log scale, but labelling specific points on the axes


code:
from collections import OrderedDict
od = OrderedDict(enumerate("abcdefg"))
od

rawDescription: How do you get the first 3 elements in Python OrderedDict?

description: Get the first 3 elements in Python OrderedDict


rawDescription: Changing the value of a variable stored in a dictionary


rawDescription: Converting binary to float

description: Converting binary to float


code:
def setup(self):
    self.value = "good"
    self.value2 = "day"
    self.value3 = "sir"

myclass = type("TestSample", (Sample,), dict(__init__=setup))

rawDescription: Python27: Subclassing a class by using type


rawDescription: Is there an efficient way of passing arguments?


code:
from sqlalchemy import create_engine, Column, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class User(Base):
    __tablename__ = "user"
    id = Column(types.Integer, primary_key=True)
    name = Column(types.String(255))
    email = Column(types.String(255), unique=True)
    login = Column(types.String(255), unique=True)

# do not create any table
#engine = create_engine('sqlite:///:memory:', echo=True)
#session = scoped_session(sessionmaker(bind=engine))
#Base.metadata.create_all(engine)

# check if column is (any) a primary_key or has unique constraint
# Note1: You can use User.__table__.c too, it is a alias to columns
# Note2: If you don't want to use __table__, you could use the reflection API like:
#        >>> from sqlalchemy.inspection import inspect
#        >>> columns = inspect(User).columns
result = dict([(c.name, any([c.primary_key, c.unique])) for c in User.__table__.columns])

print(result)

rawDescription: SQLAlchemy Determine If Unique Constraint Exists


code:
def add_sidebar_stuff(request):
    model_urls =  MajorSiteInfoData.objects.only('location')

    return {
        'link_urls': model_urls,
    }

rawDescription: django - How to create an object to be used in many views (for a dynamic menu)

description: Django - How to create an object to be used in many views (for a dynamic menu)


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

z = np.arange(40).reshape(4, 10)
x = np.linspace(1900, 2000, 10)
y = np.linspace(20, 50, 4)

fig, ax = plt.subplots()
ax.pcolormesh(x, y, z, cmap='gist_earth')
plt.show()

rawDescription: Adding a constant to the x axis

description: Adding a constant to the x axis


code:
if "a" <= surname[0].lower() <= "l":
    surname1.append(surname)
if "m" <= surname[0].lower() <= "z":
    surname2.append(surname)

rawDescription: How to i make it so surnames that start with A-L are written to a different file

description: I make it so surnames that start with A-L are written to a different file


code:
first = [0,1,2,3,4,5]
second = [4,5,6,7,9]
sorted(set(first + second))

rawDescription: Create a list of integer elements from list of objects


code:
import yaml
f = open('tree.yaml')
# use safe_load instead load
dataMap = yaml.safe_load(f)
f.close()

rawDescription: YAML parsing and Python?

description: YAML parsing and Python


rawDescription: Python: unpack format characters

description: Python: unpack format characters


rawDescription: Python: '{:,}'.format() why is this working?


rawDescription: Pandas: how to match multiple pattern (OR) with np.where


code:
'hel'  'lo'
'cat'        'egory'
'ab''cd'

rawDescription: Why is the following string literal allowed?


code:
class EventForm(forms.ModelForm):
    class Meta:
        fields = ('title', 'description', 'location')

class EventTimeForm(forms.ModelForm):
    class Meta:
        fields = ('start_time',)

rawDescription: Multiple models in one form

description: Multiple models in one form


code:
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
# retrieve network resource ...
QtGui.QApplication.restoreOverrideCursor()

rawDescription: Make a progress bar for an ongoing request in Python


code:
try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext
import numpy as np

ext_modules = [Extension("my_code_cython",["my_code_cython.pyx"]),
               Extension("another_code_cython",["another_code_cython.pyx"])]

setup(
    name= 'Generic model class',
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include()],
    ext_modules = ext_modules)

rawDescription: Python: How to create a .pyd file?

description: Python: How to create a .pyd file


code:
"""
    test logging configuration
"""
import logging

from mod import log
log.setup_logging()

logger = logging.getLogger(__name__)

logger.debug('debug msg')
logger.info('info msg')
logger.warning('warning msg')
logger.error('error msg')
logger.exception('exception msg')

rawDescription: No handler found for library with logging configured


rawDescription: Pandas saving and reading DataFrame to json


code:
import logging
from flask import Flask
from werkzeug.serving import WSGIRequestHandler, _log

app = Flask(__name__)

@app.route('/hello')
def hello():
    return '
Hello, World.
'

class MyRequestHandler(WSGIRequestHandler):
    # Just like WSGIRequestHandler, but without "- -"
    def log(self, type, message, *args):
        _log(type, '%s [%s] %s\n' % (self.address_string(),
                                         self.log_date_time_string(),
                                         message % args))

    # Just like WSGIRequestHandler, but without "code"
    def log_request(self, code='-', size='-'):
        self.log('info', '"%s" %s', self.requestline, size)

if __name__=="__main__":
    logging.basicConfig(filename='werkzeug.log', level=logging.INFO)
    logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)
    app.run(debug=True, request_handler=MyRequestHandler)

rawDescription: How to remove the "- -" from flask's logging?

description: Remove the "- -" from flask's logging


code:
class Watcher(type):
    def __init__(cls, name, bases, clsdict):
        if len(cls.mro()) > 2:
            print("was subclassed by " + name)
        super(Watcher, cls).__init__(name, bases, clsdict)

class SuperClass:
    __metaclass__ = Watcher

print("foo")

class SubClass0(SuperClass):
  pass

print("bar")

class SubClass1(SuperClass):
  print("test")

rawDescription: Python: Run code when a class is subclassed


code:
list(random_powerset(range(3)))
list(random_powerset(range(3)))
list(random_powerset(range(3)))
list(random_powerset(range(3)))
list(random_powerset(range(3)))
list(random_powerset(range(3)))

rawDescription: Randomize chain from itertools

description: Randomize chain from itertools


code:
dftest
dftest

rawDescription: Python: In a dataframe, create a new column with a string sliced from a column with the value of another column


code:
host = property(**host())
name = host

rawDescription: Can I make a property refernence to different getter in python

description: Make a property refernence to different getter in python


code: df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()

rawDescription: Summing across rows of Pandas Dataframe

description: Summing across rows of Pandas Dataframe


rawDescription: Python eig for generalized eigenvalue does not return correct eigenvectors


rawDescription: How to find elements that are common to all lists in a nested list?

description: Find elements that are common to all lists in a nested list


rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


rawDescription: Django: How to return all models associated with a ForeignKey including all attributes of those models?


code:
subset = {}
for percent in np.arange(10, 100, 10):
    np.random.shuffle(train_set) # shuffle in-place
    subset[percent] = train_set[:len(train_set)*percent*0.01].copy() # selection of training data

rawDescription: Pythonic strategy to overwrite global variables in a for loop


code:
def newtons_method(x_init, fn, max_iter=100):
    """
    returns: approx. val of root of the function passed in, fn;
    pass in: x_init, initial value for the root;
    max_iter, total iteration count not exceeded;
    fn, a function of the form:
    def f(x): return x**3 - 2*x
    """
    x = x_init
    eps = .0001
    # set initial value different from x_init so at lesat 1 loop
    x_old = x + 10 * eps
    step = .1
    c = 0
    # (x - x_old) is convergence criterion
    while (abs(x - x_old) > eps) and (c < max_iter):
        c += 1
        fval = fn(x)
        dfdx = (fn(x + step)) - fn(x) / step
        x_old = x
        x = x_old - fval / dfdx
    return x, c

rawDescription: How can I check to see the number of iterations Newton's method takes to run?

description: Check to see the number of iterations Newton's method takes to run


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


rawDescription: How to count the number of times a certain pattern in a sublist occurs within a list and then append that count to the sublist?

description: Count the number of times a certain pattern in a sublist occurs within a list and then append that count to the sublist


code:
Author.objects.get(
    **{field.name: getattr(author1, field.name)
       for field in author1._meta.get_fields(include_parents=False)}
)

rawDescription: Django Query from given object instance

description: Django Query from given object instance


code:
def dsquared_line_points(P1, P2, points):
    '''
    Calculate only squared distance, only needed for comparison
    http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
    '''
    xdiff = P2[0] - P1[0]
    ydiff = P2[1] - P1[1]
    nom  = (
        ydiff*points[:,0] - \
        xdiff*points[:,1] + \
        P2[0]*P1[1] - \
        P2[1]*P1[0]
    )**2
    denom = ydiff**2 + xdiff**2
    return np.divide(nom, denom)

def rdp_numpy(M, epsilon = 0):

    # initiate mask array
    # same amount of points
    mask = np.empty(M.shape[0], dtype = bool)

    # Assume all points are valid and falsify those which are found
    mask.fill(True)

    # The stack to select start and end index
    stack = [(0 , M.shape[0]-1)]

    while (len(stack) > 0):
        # Pop the last item
        (start, end) = stack.pop()

        # nothing to calculate if no points in between
        if end - start <= 1:
            continue

        # Calculate distance to points
        P1 = M[start]
        P2 = M[end]
        points = M[start + 1:end]
        dsq = dsquared_line_points(P1, P2, points)

        mask_eps = dsq > epsilon**2

        if mask_eps.any():
            # max point outside eps
            # Include index that was sliced out
            # Also include the start index to get absolute index
            # And not relative
            mid = np.argmax(dsq) + 1 + start
            stack.append((start, mid))
            stack.append((mid, end))

        else:
            # Points in between are redundant
            mask[start + 1:end] = False

    return mask

rawDescription: Modify the Ramer–Douglas–Peucker (RDP) algorithm in numpy to return a mask instead of the values


code:
bye
hello

rawDescription: Method Overriding?

description: Method Overriding


code:
d = {}
for l in lst:
    _id = l['prod_id']
    if _id in d:
        d[_id]['quantity'] += l['quantity']
    else:
        d[_id] = l

rawDescription: How to add two items in list of dictionaries

description: Add two items in list of dictionaries


rawDescription: pyqt4 drag and drop files in Qlistview

description: Pyqt4 drag and drop files in Qlistview


rawDescription: Localise float notation

description: Localise float notation


code:
regex0 = re.compile('''
    @               # at sign
    (?:             # start non-capturing group
        \w+             # non-whitespace, one or more
        \b              # a boundary character (i.e. no more \w)
        |               # OR
        (               # capturing group
            \(              # left paren
            [^@(),]+        # not an @(),
            (?:                 # another non-caputing group
                , *             # a comma, then some spaces
                [^@(),]+        # not @(),
            )*              # some quantity of this non-capturing group
            \)              # a right paren
        )               # end of non-capuring group
    )           # end of non-capturing group
    ''', re.VERBOSE)

# and this puts them into the attributes list.
groupedAttributes = re.findall(regex0, query)
for item in groupedAttributes:
    attributes.extend(item.strip("(").strip(")").split(", "))

rawDescription: Regex for finding valid sphinx fields

description: Regex for finding valid sphinx fields


rawDescription: How to decrease running time of this particular solution?

description: Decrease running time of this particular solution


rawDescription: Math operations from string

description: Math operations from string


code: display.blit(masked, (0, 0))

rawDescription: Pygame - is there any way to only blit or update in a mask


code:
from __future__ import print_function

def dump_instruction_opcodes(start, end):
    opcodes = list()
    for ea in xrange(start, end):
        opcodes.append(idaapi.idaapi.get_original_byte(ea))

    return opcodes

def main():
    # get cursor position
    screen_ea = ScreenEA()

    func = idaapi.get_func(screen_ea)
    if not func:
        print("No function at address {:#x}".format(screen_ea))
        return
    elif not func.does_return:
        print("Function doesn't have an exit point...")
        return
    func_start = func.startEA
    func_end = func.endEA
    func_name = GetFunctionName(func_start)

    print("Function '{}' starts at {:#x} and ends at {:#x}".format(func_name, func_start, func_end))

    # traverse code or data in function boundaries
    for head in Heads(func_start, func_end):
        # we just want code, not data
        if isCode(GetFlags(head)):
            next_head = NextHead(head, func_end)
            #if last instruction, set end to func_end
            if next_head == BADADDR:
                next_head = func_end
            #print("Current inst: {:#x}, next inst: {:#x}".format(head, next_head))
            opcodes = dump_instruction_opcodes(head, next_head)
            printable_opcodes = ["{:02x}".format(op) for op in opcodes]
            print("Current inst: {:#x} [{}]".format(head, ' '.join(printable_opcodes)))

    print("[*] Done!")

if __name__ == "__main__":
    main()

rawDescription: [IDA Pro][python Script] :: How to Export binary pattern of an address up to it is end?


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
plt.show()

rawDescription: Interactive figure with OO Matplotlib

description: Interactive figure with OO Matplotlib


code:
class IDFactory(object):
  def __init__(self):
    self._by_id = {}

  def register(self, cls):
    self._by_id[cls.ID] = cls
    return cls

  def register_as(self, name):
    def wrapper(cls):
      self._by_id[name] = cls
      return cls
    return wrapper

  # ...

@factory.register_as("A")  # doesn't require ID anymore
@factory.register          # can still use ID, even mix and match
@factory.register_as("B")  # imagine we got rid of B,
class A(object):           #  and A fulfills that roll now
  ID = "A"

rawDescription: How to get a reference to the current class from class body?

description: Get a reference to the current class from class body


code:
c.execute('SELECT 1 FROM sqlite_master WHERE tbl_name="foo" AND sql LIKE "%AUTOINCREMENT%"')
c.fetchone()

rawDescription: How to programmatically determine whether a column is set to AUTOINCREMENT in SQLite?

description: Programmatically determine whether a column is set to AUTOINCREMENT in SQLite


code:
#!/usr/bin/env python
from datetime import datetime, timedelta

# utc = 1980-01-06UTC + (gps - (leap_count(2014) - leap_count(1980)))
utc = datetime(1980, 1, 6) + timedelta(seconds=1092121243.0 - (35 - 19))
print(utc)

rawDescription: How to get current date and time from GPS unsegment time in python

description: Get current date and time from GPS unsegment time in python


code:
g.apply(lambda x: x['date'].iloc[-1] - x['date'].iloc[0])
g.apply(lambda x: x['date'].max() - x['date'].min())

rawDescription: Calculating date_range over GroupBy object in pandas


code:
cuda_env = Environment(...) # default, without the offending flags
std_env = cuda_env.Clone()  # create a copy
std_env.Append(CPPFLAGS=['-std=c++0x'])

rawDescription: Strange behaviour appending/removing from array with SCons


code: start()

rawDescription: Function Is Not Running

description: Function Is Not Running


code:
def addFive(number):
    return number + 5

rawDescription: Python number averages using lists and keys


rawDescription: Numpy - slicing 2d row or column vector from array


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

#-- Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)

#-- Extract the line...
# Make a line with "num" points...
x0, y0 = 5, 4.5 # These are in _pixel_ coordinates!!
x1, y1 = 60, 75
length = int(np.hypot(x1-x0, y1-y0))
x, y = np.linspace(x0, x1, length), np.linspace(y0, y1, length)

# Extract the values along the line
zi = z[x.astype(np.int), y.astype(np.int)]

#-- Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].imshow(z)
axes[0].plot([x0, x1], [y0, y1], 'ro-')
axes[0].axis('image')

axes[1].plot(zi)

plt.show()

rawDescription: How to extract an arbitrary line of values from a numpy array?

description: Extract an arbitrary line of values from a numpy array


code:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet

rang = sheet.Range("A1","A3")
names = rang.Value
nameLst = [name[0] for name in names]

for rowI in range(1,3):
    cellNames = sheet.Cells(rowI,2).Value
    cellNamesLst = [cellName.strip() for cellName in cellNames.split(",")]
    matchLst = [matchName for matchName in cellNamesLst if matchName in nameLst]
    allMatches = ", ".join(matchLst)
    sheet.Cells(rowI,3).Value = allMatches

rawDescription: In excel with python, how do you find words, from an entire column, in a cell containing multiple words?


code:
class A(object):
    _var = 5

    @property
    def var(self):
        return self.__class__._var

    @var.setter
    def var(self, value):
        self.__class__._var = value

rawDescription: How to use a variable within a class that will be independent of any objects created in python?

description: Use a variable within a class that will be independent of any objects created in python


code:
# write.py
__all__ = ['AppendStr'] # put all functions in except the ones others shall not see
# so id you do from write import * nothing else will be imported but what is __all__

rawDescription: Is this a thread-safe module, and actually how do you write one?


code:
class Test:

  @property
  def dynamic_value(self):
    return 'dynamic'

rawDescription: Assigning class variable dynamic value from inside a classs


code:
import admin
if not admin.isUserAdmin():
        admin.runAsAdmin()

rawDescription: How to run python script with elevated privilege on windows

description: Run python script with elevated privilege on windows


code:
def split(input_date):
    try:
        my_date = date(*map(int, input_date.split('-')))
    except ValueError:
        my_date = None

timeit.timeit('f("2014-07-08")', 'from __main__ import split as f')

rawDescription: Speeding up datetime.strptime

description: Speeding up datetime.strptime


code: np.transpose(b, (0, 2, 1))[msk]

rawDescription: Reshaping/extending numpy mask

description: Reshaping/extending numpy mask


code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder

kv_string = '''
<MyWidget>:
    canvas:
        Color:
            rgb: 0.1, 0.6, 0.3
        Ellipse:
            size: self.size
            pos: self.pos
        Clear
        Color:
            rgb: 0.6, 0.2, 0.1
        Ellipse:
            size: self.size
            pos: self.center
'''

Builder.load_string(kv_string)

class MyWidget(Widget):
    pass

class TestApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    TestApp().run()

rawDescription: Clean canvas in kivy language

description: Clean canvas in kivy language


code: ['this','is','a','single argument']

rawDescription: Python -- how to read and change specific fields from file? (specifically, numbers)


code:
def uniq(fn):
    uniq_elems = set()
    def handler(*args, **kwargs):
        uniq_elems.update(fn(*args, **kwargs))
        return uniq_elems
    return handler
@uniq
def finding(q):
    return (item for item in sentences
            if item.lower().find(q.lower()) != -1)

rawDescription: Remove strings containing words from list, without duplicate strings


code:
# Subset of matplotlib rcParams that should be different for the inline backend.
# c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'}

rawDescription: How to set the matplotlib figure default size in ipython notebook?

description: Set the matplotlib figure default size in ipython notebook


code: gloss = L2[1].strip()

rawDescription: removing mysterious line break python

description: Removing mysterious line break python


rawDescription: Parsing web page in python using Beautiful Soup


code: [[i[0],k1,v1] for i in d for k1,v1 in i[1].items()]

rawDescription: Iterating through multiple values in a dictionary?


code: np.meshgrid(*[A, B, C])

rawDescription: Generation of multidimensional Grid in Python


code:
import gevent
from gevent.queue import Queue, Empty

messagesOut = Queue()
def clientWorker(address):
    client = zerorpc.Client()
    if (None != client):
        client.connect(address)
        while True:
            try:
                messages = messagesOut.get()
                client.passMessages(messages) # a method on the Node.js-side ZeroRPC server
            except: # Empty could be thrown here if you're interested
                pass
            finally:
                gevent.sleep(0)

rawDescription: Bidirectional ZeroRPC in Python client invoke causes AssertionError


code: line(49, "of beer on the wall")

rawDescription: How to reverse an int in python?

description: Reverse an int in python


code:
from urlparse import urlparse, parse_qs
for pageno in xrange(1, int(parse_qs(urlparse(url).query)['page'][0]) + 1):
    pass # do something useful here like building a url string with pageno

rawDescription: Python Web Scraping - Navigating to Next_Page link and obtaining data


rawDescription: pandas retrieve the frequency of a time series

description: Pandas retrieve the frequency of a time series


code: best = max(graphs, key=lambda g: rank(graph, g)) # select best graph by ranking it against original

rawDescription: lookahead algorithm in Python

description: Lookahead algorithm in Python


code:
class Person(models.Model):
    name = models.CharField(max_length=40)
    birthday = models.DateTimeField() # their next birthday

rawDescription: Queryset of people with a birthday in the next X days


rawDescription: Python: Very slow execution loops

description: Python: Very slow execution loops


code:
import re

input = ['MAPLEWOOD AVE', 'LYNNDALE ', 'SUGAR DR']
ref = ['LYNNDALE (?:RD)?', 'HOMAN (?:AVE)?', 'MAPLEWOOD (?:AVE)?', 'LYNNDALE (?:LN)?']
output = dict([ (i, [ r for r in ref if re.match(r, i) ]) for i in input ])

rawDescription: Match two Python lists with regular expressions, and create dictionary output


code:
import pprint
A = [['point'], ['point', 'floating']]
B = [['floating', 'undefined', 'point'], ['point']]
C = []

for a in A:
    for b in B:
        if a==b:
            C.append([a,b])
        elif all (len(x)>=2 for x in [a,b]) and not set(a).isdisjoint(b):
            C.append([a,b])

pprint.pprint(C)

rawDescription: Mapping two list of lists based on its items into list pairs in Python


rawDescription: Storing a large dictionary with non-unique key-value pairs


code:
def nonMaximalSupress2(image,NHoodSize):
    #
    dX, dY = NHoodSize
    M, N = image.shape
    for x in range(0,M-dX+1):
        for y in range(0,N-dY+1):
            window = image[x:x+dX, y:y+dY]
            if np.sum(window)==0:
                localMax=0
            else:
                localMax = np.amax(window)
            maxCoord = np.argmax(window)
            # zero all but the localMax in the window
            window[:] = 0
            window.flat[maxCoord] = localMax
    return image

rawDescription: Non local maxima suppression in python

description: Non local maxima suppression in python


code:
...

class DeckCreateForm(forms.ModelForm):
    ...
    def __init__(self, post_data, files_data):
        self.csv_file = files_data.get('csv_file', None)
        return super(DeckCreateForm, self).__init__(post_data, files_data)

    def save(self, *args, **kwargs):
        deck = super(DeckCreateForm, self).save(*args, **kwargs)
        self.handle_csv_file(self.csv_file, deck)
        return deck

    def handle_csv_file(f, deck):
        ...
        for chunk in f.chunks():
            ...
        ...

rawDescription: How to access the Django forms.FileField file (*not models.FileField*)?

description: Access the Django forms.FileField file (*not models.FileField*)


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import unittest, time, re

desired_cap = []
desired_cap.append({'browser': 'Chrome', 'browser_version': '33.0', 'os': 'OS X', 'os_version': 'Mavericks', 'resolution': '1600x1200'})
desired_cap.append({'browser': 'Firefox', 'browser_version': '27.0', 'os': 'OS X', 'os_version': 'Mavericks', 'resolution': '1600x1200'})

class RegWD(unittest.TestCase):
    def setUp(self):
        for driver_instance in desired_cap:
            driver_instance['browserstack.debug'] = True
            self.driver = webdriver.Remote(
            command_executor='http://browserstackstuff.com',
            desired_capabilities=driver_instance)
            self.base_url = "http://blahtestsite.com/"

rawDescription: How to run one python webdriver test in multiple browsers

description: Run one python webdriver test in multiple browsers


code: func(1, 2, 3)   # raises TypeError

rawDescription: Dynamically define functions with varying signature


code:
True + 0
True + False

rawDescription: What do the binary operators mean when applied to logicals?


rawDescription: python, regular expressions, named groups and "logical or" operator

description: Python, regular expressions, named groups and "logical or" operator


code:
import pkg_resources

data = pkg_resources.resource_string('conf', 'constants.cfg')

rawDescription: Python : How to access file from different directory


code:
from pymongo.son_manipulator import SONManipulator

class Transform(SONManipulator):
  def transform_incoming(self, son, collection):
    for (key, value) in son.items():
      if isinstance(value, Custom):
        son[key] = encode_custom(value)
      elif isinstance(value, dict): # Make sure we recurse into sub-docs
        son[key] = self.transform_incoming(value, collection)
    return son
  def transform_outgoing(self, son, collection):
    for (key, value) in son.items():
      if isinstance(value, dict):
        if "_type" in value and value["_type"] == "custom":
          son[key] = decode_custom(value)
        else: # Again, make sure to recurse into sub-docs
          son[key] = self.transform_outgoing(value, collection)
    return son

rawDescription: Encoding custom python objects as BSON with pymongo


code:
import urllib
from lxml import html
from urlparse  import urljoin
def main():
    url = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_IEC_14496-26_2010_Bitstreams/DVD1/mpeg4audio-conformance/compressedMp4/"

    page = html.fromstring(urllib.urlopen(url).read())

    for link in page.xpath("//a/@href"):
        runme("wget " + urljoin("http://standards.iso.org/", link))

rawDescription: python download all files in a web page

description: Python download all files in a web page


code:
import ast
source = '2 + 2'
node = ast.parse(source, mode='eval')
ast.dump(node)

rawDescription: How to compile text as a function using AST?

description: Compile text as a function using AST


rawDescription: Can I run multiple Ipython qt console in the same time?

description: Run multiple Ipython qt console in the same time


code: answer = [x for x, y in zip(list1, list2) if x == y]

rawDescription: Count occurrences of number in two lists and return one list


code: indexes= df3.index.values

rawDescription: delete a part of pd.DataFrame with Python

description: Delete a part of pd.DataFrame with Python


code:
import inspect
def func (k = lambda x: x ** 2):
    if not callable(k) or len(inspect.getargspec(k).args) != 1:
        raise TypeError('k must take exactly one argument.')
    # Do whatever you want

rawDescription: Python specify lambda arguments as a function argument


code: stra = ' '.join(s.rstrip(',') for s in lista)

rawDescription: Python 2 string operation on a list

description: Python 2 string operation on a list


rawDescription: Permute a list using Python

description: Permute a list using Python


code:
import os

wallet = 'test.txt'
filepath = r'C:\\'

def search():
    for root,dirs,files in os.walk(filepath):
        if wallet in files:
            return os.path.join(root, wallet)
        else:
            return 'Nope.. not here'
print(search())

rawDescription: Using os.walk to get my file path in Python


code:
import numpy as np

def ss1(A):
    return np.add(A[:,:-1,:],A[:,1:,:])

def ss2(A,output):
    return np.add(A[:,:-1,:],A[:,1:,:],output)

rawDescription: Optimize NumPy sum of matrices iterated through every element


code:
a = { 'fruits': 'apple' 'grape', 'vegetables': 'carrot'}
b = { 'fruits': 'banana'}
a.viewitems() - b.viewitems()  # python3.x -- Just use `items` :)
b['vegetables'] = 'carrot'  # add the correct vegetable to `b` and try again.
a.viewitems() - b.viewitems()

rawDescription: Comparing two dictionaries and printing key value pair in python


code:
myRenderView.ViewSize = [984, 962]
SaveScreenshot('image.png', magnification=1, quality=100, view=myRenderView)

rawDescription: In Python script for Paraview, can I specify the resolution when I do a SaveScreenshot()?


code: values1 = filter(lambda x: len(x) > 1, values)

rawDescription: Selecting specific lists in a file

description: Selecting specific lists in a file


code:
from itertools import izip_longest

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

for a, b, c in grouper(3, seq):
    pass

rawDescription: Split list in tuples of three

description: Split list in tuples of three


rawDescription: Lagrange interpolation in Python: as a result matematical formula


rawDescription: How to use a list of strings [which may contain any character] as keys?

description: Use a list of strings [which may contain any character] as keys


code:
view_maker = lambda name: (lambda: name)

for name in ('/hi', '/bye'):
    endpoint = name.replace("/", "")
    app.add_url_rule(name, view_func=view_maker(name), endpoint=endpoint)

rawDescription: flask -- how to get around limitation that app.route / app.add_view_rule doesn't work with closures?

description: Flask -- how to get around limitation that app.route / app.add_view_rule doesn't work with closures


code:
c = copy.deepcopy(a)
a, c
a[1].append(5)
a, c

rawDescription: Understanding dict.copy() - shallow or deep?


code:
drange = [i for i in xrange(j) for k in range(2)]
drange

rawDescription: How can I repeat elements in place in an array in Python?

description: Repeat elements in place in an array in Python


code: mag = np.sqrt(vgrad[0]**2 + vgrad[1]**2)

rawDescription: Generating gradient map of 2D array

description: Generating gradient map of 2D array


rawDescription: Parsing html for specific script type

description: Parsing html for specific script type


rawDescription: Removing custom widget from QVBoxLayout

description: Removing custom widget from QVBoxLayout


code:
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import RANSACRegressor

# data: 1000 obs, 100 of them are outliers
# =====================================================
np.random.seed(0)
a = np.random.randn(1000)
b = np.random.randn(1000)
d = 2 * a - b + np.random.randn(1000)
# the last 100 are outliers
d[-100:] = d[-100:] + 10 * np.abs(np.random.randn(100))

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].scatter(a, d, c='g')
axes[0].set_xlabel('a')
axes[0].set_ylabel('d')
axes[1].scatter(b, d, c='g')
axes[1].set_xlabel('b')

rawDescription: Identifying chunks of outliers from a 1D and 2D data in Python


code:
# This one returns a scene based on its name or key in the scenes array
def next_scene(self, scene_name):
    return Map.scenes.get(scene_name)

# And this one  returns the opening scene which is set when you create the map.
def opening_scene(self):
    return self.next_scene(self.start_scene)

rawDescription: Learn Python the Hard Way Exercise 43

description: Learn Python the Hard Way Exercise 43


code: '#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])

rawDescription: How to print string in this way

description: Print string in this way


code:
curOuter = db.cursor()
rows=[]
for row in curOuter.execute('SELECT * FROM myConnections'):
    id  = row[0]
    scList = retrieve_shared_connections(id)
    for sc in scList:

        rows.append((id,sc))
curOuter.executemany('''INSERT INTO sharedConnections(IdConnectedToMe, IdShared) VALUES (?,?)''', rows)
db.commit()

rawDescription: Using multiple cursors in a nested loop in sqlite3 from python-2.7


code:
tmp = min(y,z)
z=max(y,z)
y=tmp

rawDescription: Number sort using Min, Max and Variables


code:
if __name__ == '__main__':
    import doctest
    import the_current_module
    doctest.testmod(the_current_module)

rawDescription: Running doctests through iPython and pseudo-consoles


code: df = tm.makeTimeDataFrame(nper=1000)

rawDescription: What does the .N mean in this block of Python code?


code:
def get_values(keys=None):
    if keys is None:
        keys = []
    rv = {}
    for key in keys:
        # Keep in mind, this is a reference to
        # an object in my_dict, not a copy. Also,
        # you may want to handle keys not found in my_dict:
        # ignore them, or set rv[key] to None?
        rv[key] = my_dict[key]
    return rv

d1 = get_all_values()   # Empty dict
d2 = get_all_values([])  # Explicitly empty dict
d3 = get_all_values(["foo", "bar"])  # (Sub)set of values
d4 = get_all_values(my_dict) # A copy of my_dict

rawDescription: Unique constant reference

description: Unique constant reference


rawDescription: Python and numpy - removing rows from a corresponding matrix


code:
if liquid in test_tube:
    test_tube[liquid] += milliliters
else:
    test_tube[liquid] = milliliters

rawDescription: memorize a value of a dictionary

description: Memorize a value of a dictionary


code:
from nltk.tag import pos_tag
sent = "dog is barking at tree"
[i for i in pos_tag(sent.split()) if i[1] == "NN"]

rawDescription: How to get all the meanings of a word using python NLTK?

description: Get all the meanings of a word using python NLTK


code:
binascii.hexlify(struct.pack('>i', 123))
binascii.hexlify(struct.pack('<i', 123))

rawDescription: Hexlify an integer in Python

description: Hexlify an integer in Python


code:
class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        exclude = ('user',)

rawDescription: Passing instance/default value to a ModelFormSet for the empty forms to use, in a view


code:
def intcaststr(bitlist):
    return int("".join(str(i) for i in bitlist), 2)

def intcastlookup(bitlist):
    return int(''.join('01'[i] for i in bitlist), 2)

def shifting(bitlist):
    out = 0
    for bit in bitlist:
        out = (out << 1) | bit
    return out

timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcaststr as convert', number=100000)
timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcastlookup as convert', number=100000)
timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import shifting as convert', number=100000)

rawDescription: Bits list to integer in Python

description: Bits list to integer in Python


code: y = x.reshape(x.shape[0]/2, 2, x.shape[1], 2)

rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


code: graph = nx.Graph(edges)  # Well that was easy

rawDescription: How to find the shortest dependency path between two words in Python?

description: Find the shortest dependency path between two words in Python


code:
import json
import os

def append_record(record):
    with open('my_file', 'a') as f:
        json.dump(record, f)
        f.write(os.linesep)

# demonstrate a program writing multiple records
for i in range(10):
    my_dict = {'number':i}
    append_record(my_dict)

rawDescription: Append list of Python dictionaries to a file without loading it


rawDescription: Numpy - Dot Product of a Vector of Matrices with a Vector of Scalars


rawDescription: Using Float questions

description: Using Float questions


code:
newx = np.linspace(minX, maxX, 1000)
newy = np.interp(newx, x, y)

rawDescription: Downsampling non-uniform 1D signals

description: Downsampling non-uniform 1D signals


rawDescription: Retrieving a ForeignKey attribute based on the URL of the website?


rawDescription: Replacing html script element sources with regular expression in Python


code:
class Media:
    js = ('path/to/action_buttons.js', )

rawDescription: Django admin, display actions as buttons


rawDescription: python Pandas calling a complex function in groupby.agg

description: Python Pandas calling a complex function in groupby.agg


code:
from collections import Iterable, Iterator
isinstance([], Iterable)
isinstance([], Iterator)
isinstance(iter([]), Iterator)

rawDescription: What is a better pythonic version of this conditional deleting?


code:
from collections import defaultdict

def iter_file(filename):
    with open(filename) as inp:
        for line in inp:
            line = line.split(' ')
            yield line[:-1] + line[-1].split('\t')

def do_correction(n4, n5):
    n4_dict = defaultdict(list)
    for words_n4 in n4:
        n4[words_n4[2], words_n4[3]].append(words_n4)

    for words_n5 in n5:
        words_n4 = next(
            (words_n4 for words_n4 in n4_dict[words_n5[1], words_n5[2]]
                if (words_n4[0]+words_n4[1] == words_n5[0] and
                words_n4[4] >= words_n5[3])),
            None)
        if words_n4:
            yield words_n4[:-1] + words_n5[3:]
        else:
            words_n4 = next(
                (words_n4 for words_n4 in n4_dict[words_n5[2], words_n5[3]]
                    if (words_n4[0] in words_n5[0] and
                    words_n4[1] == words_n5[1] and
                    words_n4[4] >= words_n5[4])),
                None)
            if words_n4:
                idx = words_n5[0].find(words_n4[0])
                yield [words_n5[:idx], words_n5[idx:]], words_n5[1:]
            else: # not found
                yield ['none'] + words_n5

with open('corrected', 'w') as output:
    for words in do_correction(iter_file('N4'), iter_file('N5')):
        output.write('%s\t%s' %(' '.join(words[:-1]), words[-1]))

rawDescription: Faster way to search strings in big file with python


code:
options = ["one","two","three"]
...
self.menuVar = tk.StringVar(master)
self.optionMenu = tk.OptionMenu(master, self.menuVar, *options)
...
self.menuVar.set(options[0])

rawDescription: Set Python OptionMenu by index

description: Set Python OptionMenu by index


code: arithOperand <<= Optional('-') + (powerExpr | real | identifier | groupedArithExpr)

rawDescription: Parser failing - pyparsing

description: Parser failing - pyparsing


rawDescription: Python Selenium : Xpath element not found


code: screen = CreateDC("DISPLAY", NULL, NULL, NULL);

rawDescription: Python PIL library-- Is there a way to select which screen ImageGrab.grab() grabs in a multi-monitor setup?


rawDescription: Python list comprehension to map from flat list to mimic a nested structure


code:
import Constants

const=Constants.const
print(const.y)
# 10
print(const.x)
# 10

rawDescription: python binding of variable to particular expression

description: Python binding of variable to particular expression


rawDescription: connecting to server and sending data to it in python

description: Connecting to server and sending data to it in python


code: dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

rawDescription: best way to extract subset of key-value pairs from python dictionary object

description: Extract subset of key-value pairs from python dictionary object


code:
form.fields['new_name'] = form.fields['answer']
del form.fields['answer']

rawDescription: Set custom 'name' attribute for RadioSelect in Django


code:
def haraprasadj(fhandle, identifiers):
    data = [line.strip().split('\t')[1:] for line in fhandle.readlines()]
    fhandle.close()
    result = np.array(filter(lambda x:x[1] in identifiers, data))
    time =result[:,0]
    ids = result[:,1]
    value = result[:,2]
    res = {}
    for i in identifiers:
        msk = np.where(ids==i, True, False)
        res[i] = np.array(zip(time[msk], value[msk]), dtype=[('time','datetime64[us]'), ('value','f8')])
    return res

rawDescription: quick parsing of csv-like file

description: Quick parsing of csv-like file


code:
from bottle import request, route

@route("/posthere", method="POST")
def postResource():
    #do code
    myDict = request.json['myDict']
    return {"result": "something"}

rawDescription: Is it possible to post an object from jquery to bottle.py?


code:
import ast
for line in f.readlines():
    temp_list = ast.literal_eval(line.split('/t')[1])
    # do something

rawDescription: converting part of a text file to list

description: Converting part of a text file to list


code:
def dictsetter(item, name):
     def f(value):
         item[name] = value
     return f

mypath = dictsetter(test["a"]["b"], "c")

mypath(2)

rawDescription: Storing dictionary path in Python

description: Storing dictionary path in Python


code: qsort(arr, left, newPivotIndex)

rawDescription: QuickSort in Python - program hangs for larger input sizes?


rawDescription: Python taking paired string and integer input


code: df = df[df.Country_FAO.isin(top10)]

rawDescription: Subsetting stacked pandas dataframe

description: Subsetting stacked pandas dataframe


code: non_zero_values = array1[non_zero_mask]

rawDescription: Replacing entries of an array with those of different array


code:
response = urllib2.urlopen(request)

data = response.read()

rawDescription: python: download file and send it to online storage in realtime

description: Python: download file and send it to online storage in realtime


code:
def pca(X, nb_components=0):
    [n,d] = X.shape
    if (nb_components <= 0) or (nb_components>6):
        nb_components = n

    MU = X.mean(axis=0)
    for i in range(n):
        X[i,:] -= MU

    S = (np.dot(X, X.T) / float(n))

    eigenvalues, eigenvectors = np.linalg.eigh(S)

    s = np.where(eigenvalues < 0)
    eigenvalues[s] = eigenvalues[s] * -1.0
    eigenvectors[:,s] = eigenvectors[:,s] * -1.0

    indexes = np.argsort(eigenvalues)[::-1]
    eigenvalues = eigenvalues[indexes]
    eigenvectors = eigenvectors[:,indexes][:,0:nb_components]

    eigenvectors = np.dot(X.T, eigenvectors)

    for i in range(nb_components):
        eigenvectors[:,i] = normalize_vector(eigenvectors[:,i])

    return (eigenvalues, eigenvectors, MU)

rawDescription: Principal Component Analysis in Python: Analytical Mistake


code:
import cStringIO

tempimg = cStringIO.StringIO(imgstr.decode('base64'))

im = Image.open(tempimg)

rawDescription: Load an html5 canvas into a PIL Image with Django


code:
dirList = [name for name in sorted(os.listdir(path))
           if re.search(r'\.mp3', name)]

rawDescription: Why are these strings escaping from my regular expression in python?


code:
import os

def get_paths(s, sep=os.sep):
    return [x for x in s.split() if len(x.split(sep)) > 1]

rawDescription: Extract path like strings from string

description: Extract path like strings from string


rawDescription: Dealing with multiple python versions when python files have to use #!/bin/env python


code:
#execute this after the "hook up each entry to its children" section.
#remove "children" from leaf nodes.
for entry in entries.itervalues():
    if not entry["children"]:
        del entry["children"]

rawDescription: Convert a flat tab-delimited file into Json nested structure


code:
from random import random as r

numlin=50

matt = []
for j in xrange(numlin):
    matt.append([r()*20, r()*10,r()*20,r()*10])

rawDescription: Plot points with different colors in a matplotlib animation


code:
animals = ["ant", "antelope", "zebra", "anteater", "cod", "cat"]

animals.sort(key=lambda name: (name[0], -len(name), name))

print(animals)

rawDescription: Custom sort in Python 3

description: Custom sort in Python 3


code:
def update(all_marks, stud_num, mark, column):
    for i in range(len(all_marks)):
        if stud_num in all_marks[i]:
            all_marks[i][column] = mark
    return all_marks

rawDescription: Replacing values in csv by using python

description: Replacing values in csv by using python


code: pd.set_printoptions(max_colwidth, 1000)

rawDescription: How to remove ellipsis from a row in a Python Pandas series or data frame?

description: Remove ellipsis from a row in a Python Pandas series or data frame


code:
codes = {'CAD': 'Dolar Canadiense',
         'GBP': 'Libra Esterlina',
         'MXN': 'Peso Mexicano',
         'CHF': 'Franco Suiso',
         'EUR': 'Euro',
         'DKK': 'Corona Danesa',
         'SEK': 'Corona Sueka',
         'JPY': 'Yen Japones',
         'CUP': 'Peso Cubano',
         'PAB': 'Balboa Panama',
         'AUD': 'Dolar Australiano',
         'USD': 'Dolar Estadounidense',
         'NOK': 'Corona Noruega'
         }

rawDescription: how to return choices value in mongoengine stringfield

description: Return choices value in mongoengine stringfield


code:
print = logging.info
logging.basicConfig(level=logging.WARNING if QUIET else logging.INFO,
                    format="%(message)s")

rawDescription: What's an easy way to implement a --quiet option in a python script


code: opt2_2 = {key:(opt1[key], opt2[key]) for key in opt1.keys()}

rawDescription: Can I have 3 elements in a dictionary

description: Have 3 elements in a dictionary


code:
import yaml

a = ['item 1','item 2','item 3','item 4']
yaml.dump(a, explicit_start=True, default_flow_style=False)

rawDescription: How do I convert a python list to simple YAML?

description: Convert a python list to simple YAML


code:
with open("example.txt","r") as first, open("output.txt","r") as second:
    result = [word
              for line1, line2 in zip(first, second)
              for combo in zip(line1.split(), line2.split())
              for word in combo]

rawDescription: How to approach for a list comprehension solution?

description: Approach for a list comprehension solution


code: mydict = dict((key, "It's an elephant") for key in mydict)

rawDescription: How do I assign the same value for each key?

description: Assign the same value for each key


code:
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.tag(name='captureas')
def do_captureas(parser, token):
    try:
        tag_name, args = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError("'captureas' node requires a variable name.")
    nodelist = parser.parse(('endcaptureas',))
    parser.delete_first_token()
    return CaptureasNode(nodelist, args)

class CaptureasNode(template.Node):
    def __init__(self, nodelist, varname):
        self.nodelist = nodelist
        self.varname = varname

    def render(self, context):
        output = self.nodelist.render(context)
        context[self.varname] = output
        return ''

@register.filter(name='join_my_tags')
@stringfilter
def join_my_tags(text):
    return text.replace(' ][ ', '')

rawDescription: Postprocess django template nodes to combine tags before rendering


code: reduce(lambda x, y: pd.merge(x, y, left_index=True, right_index=True), list_of_dfs)

rawDescription: Inner Join list of DataFrames on Row Values


code:
from PyQt5 import QtGui, QtWidgets
app = QtWidgets.QApplication([''])
icon = QtGui.QIcon.fromTheme('edit-copy')
icon.themeName()
icon.availableSizes()
QtGui.QIcon.hasThemeIcon('icon_that_does_definitely_not_exist')

rawDescription: PyQt5 QIcon.hasThemeIcon(...) always true


code:
my_color = random.choice(colors)
color(my_color)
color_times[my_color] += 1 # you have to initialize color_times before the loop

rawDescription: Counting red lines from lines of random colors


code: subprocess.call(["sh", "-c", "perl myCode.pl >results.txt"])

rawDescription: Run Perl code (with output to file) from Python


code: output = [{'x': l[i], 'y': l[i+1]} for i in range(0, len(l), 2)]

rawDescription: List of dictionaries from pairs in list

description: List of dictionaries from pairs in list


rawDescription: Django: Counting objects based on filter value that changes?


code:
class NoLoggingWSGIRequestHandler(WSGIRequestHandler):

    def log_message(self, format, *args):
        pass

rawDescription: Control wsgiref simple_server log

description: Control wsgiref simple_server log


rawDescription: Python Pandas is it possible to find the max value in a generated series without having to store the series into memory?


code:
def setView(self, view):
    self._view = view

rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


rawDescription: Match open and close brackets in garbled string


code:
pattern.match("foo /bar/ baz").group(1)
pattern.match("foo /bar\/bam/ baz").group(1)
pattern.match("foo /bar/bam/ baz").group(1)
pattern.match("foo\/oof /bar\/bam/ baz").group(1)

rawDescription: Regular expression: Match string between two slashes if the string itself contains escaped slashes


rawDescription: How to get a classifier's confidence score for a prediction in sklearn?

description: Get a classifier's confidence score for a prediction in sklearn


code:
import string
x=raw_input()
not_found=set(string.ascii_lowercase) - set("".join(x.split()))
print (list(not_found))

rawDescription: Print letters not in string

description: Print letters not in string


code:
def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

rawDescription: Arrays to Matrix numpy

description: Arrays to Matrix numpy


code:
import itertools
s = 'kfc'
d = {'k':'1', 'c':'3'}

rawDescription: Get ALL results of a word mapping with a dictionary


code:
class Login(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ...

class WelcomePage(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ...

rawDescription: Python Tkinter GUI Frame: How to call a class method from inside a function of another class?


code: "Foreground: #ffffff Background: #000000"

rawDescription: How to get a value for "foreground" in tkinter/ttk python?

description: Get a value for "foreground" in tkinter/ttk python


code:
try:
  yield 42
finally:
  do_something()

rawDescription: Workaround for python 2.4's yield not allowed in try block with finally clause