code: if myboolean : ...

rawDescription: if True and if False statements

description: If True and if False statements


code:
{'clubName': [u'Manchester City'],
 'matches': [{'date': u'09/09/1911',
              'opponent': u'Liverpool FC',
              'place': u'A',
              'results': u'2:2',
              'round': u'2. Round'},
             {'date': u'16/09/1911',
              'opponent': u'Aston Villa',
              'place': u'H',
              'results': u'2:6',
              'round': u'3. Round'},
             {'date': u'23/09/1911',
              'opponent': u'Newcastle United',
              'place': u'A',
              'results': u'0:1',
              'round': u'4. Round'},
             {'date': u'30/09/1911',
              'opponent': u'Sheffield United',
              'place': u'H',
              'results': u'0:0',
              'round': u'5. Round'},
             {'date': u'07/10/1911',
              'opponent': u'Oldham Athletic',
              'place': u'A',
              'results': u'1:4',
              'round': u'6. Round'},
             {'date': u'14/10/1911',
              'opponent': u'Bolton Wanderers',
              'place': u'H',
              'results': u'3:1',
              'round': u'8. Round'},
             {'date': u'21/10/1911',
              'opponent': u'Bradford City',
              'place': u'A',
              'results': u'1:4',
              'round': u'9. Round'},
             {'date': u'28/10/1911',
              'opponent': u'Woolwich Arsenal',
              'place': u'H',
              'results': u'3:3',
              'round': u'9. Round'},
             {'date': u'04/11/1911',
              'opponent': u'Preston North End',
              'place': u'A',
              'results': u'1:2',
              'round': u'10. Round'},
             {'date': u'11/11/1911',
              'opponent': u'Everton FC',
              'place': u'A',
              'results': u'0:1',
              'round': u'12. Round'},
             {'date': u'18/11/1911',
              'opponent': u'West Bromwich Albion',
              'place': u'H',
              'results': u'0:2',
              'round': u'12. Round'},
             {'date': u'25/11/1911',
              'opponent': u'Sunderland AFC',
              'place': u'A',
              'results': u'1:1',
              'round': u'13. Round'},
             {'date': u'02/12/1911',
              'opponent': u'Blackburn Rovers',
              'place': u'H',
              'results': u'3:0',
              'round': u'15. Round'},
             {'date': u'09/12/1911',
              'opponent': u'Sheffield Wednesday',
              'place': u'A',
              'results': u'0:3',
              'round': u'15. Round'},
             {'date': u'16/12/1911',
              'opponent': u'Bury FC',
              'place': u'H',
              'results': u'2:0',
              'round': u'16. Round'},
             {'date': u'23/12/1911',
              'opponent': u'Middlesbrough FC',
              'place': u'A',
              'results': u'1:3',
              'round': u'17. Round'},
             {'date': u'25/12/1911',
              'opponent': u'Notts County',
              'place': u'A',
              'results': u'1:0',
              'round': u'18. Round'},
             {'date': u'26/12/1911',
              'opponent': u'Notts County',
              'place': u'H',
              'results': u'4:0',
              'round': u'19. Round'},
             {'date': u'30/12/1911',
              'opponent': u'Manchester United',
              'place': u'A',
              'results': u'0:0',
              'round': u'20. Round'},
             {'date': u'06/01/1912',
              'opponent': u'Liverpool FC',
              'place': u'H',
              'results': u'2:3',
              'round': u'21. Round'},
             {'date': u'20/01/1912',
              'opponent': u'Aston Villa',
              'place': u'A',
              'results': u'1:3',
              'round': u'22. Round'},
             {'date': u'27/01/1912',
              'opponent': u'Newcastle United',
              'place': u'H',
              'results': u'1:1',
              'round': u'23. Round'},
             {'date': u'10/02/1912',
              'opponent': u'Oldham Athletic',
              'place': u'H',
              'results': u'1:3',
              'round': u'24. Round'},
             {'date': u'17/02/1912',
              'opponent': u'Bolton Wanderers',
              'place': u'A',
              'results': u'1:2',
              'round': u'27. Round'},
             {'date': u'26/02/1912',
              'opponent': u'Sheffield United',
              'place': u'A',
              'results': u'2:6',
              'round': u'26. Round'},
             {'date': u'02/03/1912',
              'opponent': u'Woolwich Arsenal',
              'place': u'A',
              'results': u'0:2',
              'round': u'28. Round'},
             {'date': u'09/03/1912',
              'opponent': u'Preston North End',
              'place': u'H',
              'results': u'0:0',
              'round': u'28. Round'},
             {'date': u'16/03/1912',
              'opponent': u'Everton FC',
              'place': u'H',
              'results': u'4:0',
              'round': u'29. Round'},
             {'date': u'23/03/1912',
              'opponent': u'West Bromwich Albion',
              'place': u'A',
              'results': u'1:1',
              'round': u'30. Round'},
             {'date': u'28/03/1912',
              'opponent': u'Bradford City',
              'place': u'H',
              'results': u'4:0',
              'round': u'31. Round'},
             {'date': u'30/03/1912',
              'opponent': u'Sunderland AFC',
              'place': u'H',
              'results': u'2:0',
              'round': u'32. Round'},
             {'date': u'05/04/1912',
              'opponent': u'Tottenham Hotspur',
              'place': u'H',
              'results': u'2:1',
              'round': u'33. Round'},
             {'date': u'06/04/1912',
              'opponent': u'Blackburn Rovers',
              'place': u'A',
              'results': u'0:2',
              'round': u'31. Round'},
             {'date': u'08/04/1912',
              'opponent': u'Tottenham Hotspur',
              'place': u'A',
              'results': u'2:0',
              'round': u'35. Round'},
             {'date': u'13/04/1912',
              'opponent': u'Sheffield Wednesday',
              'place': u'H',
              'results': u'4:0',
              'round': u'36. Round'},
             {'date': u'20/04/1912',
              'opponent': u'Bury FC',
              'place': u'A',
              'results': u'2:1',
              'round': u'37. Round'},
             {'date': u'27/04/1912',
              'opponent': u'Middlesbrough FC',
              'place': u'H',
              'results': u'2:0',
              'round': u'38. Round'}]}

rawDescription: My scraper yields too many items instead of merging them all into only a small bunch


code:
# Retrieve the object belonging to the user whose ID is 1.
# Note that you cannot use "user=1", you need to tell Django you
# are querying by id, using "user__id=1" .
obj = MyModel.objects.get(user__id=1)

# Set PK to None so that Django thinks it is not save in the database.
obj.pk = None

# Save to insert it.
obj.save()

rawDescription: Fetch and save a copy of a QuerySet with a new User field in Django


rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code:
result = []
[result.extend(zip(([df.baz[i]])*len(df.foo[i]), df.foo[i])) for i in range(len(df.baz))]
index = [[df.index[i]]*len(df.foo[i]) for i in range(len(df.baz))]
index = [item for sublist in index for item in sublist] # flatten

final = pd.DataFrame(result,index=index, columns = df.columns) # final result

rawDescription: Expand a column holding iterables into rows


code:
import re
from Bio import SeqIO

with open('num.txt') as nums:
    lines = re.findall(r'\w+\.txt\s+\d+', nums.read())

numbers = {}
for line in lines:
    line_split = re.split(r'\.txt\s+', line)
    count = line_split[1]
    numbers[line_split[0]] = int(line_split[1])
data = SeqIO.parse(open('data.txt'), 'fasta')

def new_records():
    for record in data:
        record.seq = record.seq[:numbers.get(record.description.rsplit('|', 1)[-1])]
        yield record

with open('new_data.txt', 'w') as new_data:
    SeqIO.write(new_records(), new_data, 'fasta')

rawDescription: Length cutting through file handling

description: Length cutting through file handling


code:
def log_value(d, key, value):
    log('Updated: {}={}'.format(key, value))

mydict = dict()

rawDescription: why types/class unification majorly in python

description: Why types/class unification majorly in python


code:
#!/usr/bin/env python

from distutils.core import setup, Extension
import numpy.distutils.misc_util

setup(
    ext_modules=[Extension("_add_vectors",
                           ["_add_vectors.c", "add_vectors.c"])],
    include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(),
)

rawDescription: C function called via Python determines wrong array size


code:
[u'The Promise', u'Does It Work?', ... ]
[u'Common Conditions', u'Featured Topics', ... ]

rawDescription: Only print content between tags

description: Only print content between tags


rawDescription: How to pass multiple values for a single URL parameter?

description: Pass multiple values for a single URL parameter


code:
table
table.take(sorter)

rawDescription: Pandas: Sort pivot table

description: Pandas: Sort pivot table


code:
L = ['a', 'b', 'c']
list(L)
list(L)
iter_L = iter(L)  # calls L.__iter__() and returns you a one-shot iterator
list(iter_L)
list(iter_L)

rawDescription: Converting iterator to list changes the iterator


code:
import pandas as pd
df = pd.DataFrame({'a': a, 'b': b})
beta2 = (df.corr() * df['b'].std() * df['a'].std() / df['a'].var()).ix[0, 1]
print(beta2)
# 2.10609347015
assert np.allclose(beta, beta2)

rawDescription: Correlation between columns in DataFrame


rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


code:
{69: {'career': 'manual work', 'category': 'Extremely Low', 'name': 'joe'},
 120: {'career': 'doctor', 'category': 'Superior', 'name': 'james'}}

rawDescription: Using pandas to merge data and output Json


rawDescription: Data from a MATLAB .fig file using Python?


code: cmd = '{0} {1}'.format(LS, FILENAME)

rawDescription: python command substitution for linux commands

description: Python command substitution for linux commands


code:
if hasattr(dummy, 'GetFileSize_cache'):
    if dummy.GetFileSize_cache.has_key(url):
        return dummy.GetFileSize_cache[url]
    else:
        dummy.GetFileSize_cache = {}

rawDescription: Designing a joint function

description: Designing a joint function


rawDescription: Finding all common, non-overlapping substrings


code:
class CameraGroup(pygame.sprite.Group):
    def __init__(self, camera):
        pygame.sprite.Group.__init__(self)
        self.camera = camera

    def draw(self, surface):
        sprites = self.sprites()
        surface_blit = surface.blit
        for spr in sprites:
            self.spritedict[spr] = surface_blit(spr.image, self.camera.apply(spr))
        self.lostsprites = []

rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
class HasPrefix(object):
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value[0:len(other.value)] < other.value

class Prefix(object):
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value < other.value[0:len(self.value)]

class AdaptPrefix(object):
    def __init__(self, seq):
        self.seq = seq
    def __getitem__(self, key):
        return HasPrefix(self.seq[key])
    def __len__(self):
        return len(self.seq)

import bisect
names = ['adam', 'bob', 'bob', 'bob', 'bobby', 'bobert', 'chris']
names.sort()
needle = Prefix('bob')
haystack = AdaptPrefix(names)
leftIndex = bisect.bisect_left(haystack, needle)
rightIndex = bisect.bisect_right(haystack, needle)
print(names[leftIndex:rightIndex])

rawDescription: Perform a binary search for a string prefix in Python


code:
list(split_every(5, range(9)))
list(split_every(3, (x**2 for x in range(20))))
[''.join(s) for s in split_every(6, 'Hello world')]
list(split_every(100, []))

rawDescription: split a generator/iterable every n items in python (splitEvery)

description: Split a generator/iterable every n items in python (splitEvery)


code:
for y in reach(travel_dict, x):
    print("you can go to", y)

rawDescription: Recursive traversal of a dictionary in python (graph traversal)


code:
A
conv_app(A,4)
A = np.append(1,A) # Append 1 and see what happens!
A
conv_app(A,4)

rawDescription: Filtering pandas or numpy arrays for continuous series with minimum window length


code: df[[col for col in df.columns if "Vibration" in col]]

rawDescription: Create a subset of a DataFrame dependant on column name


rawDescription: Python Regex split (A)(B)(C)(D) into new lines


code:
import numpy as np
data = np.random.random(20)
data
import struct
struct.pack('{}d'.format(len(data)), *data)

rawDescription: Making lookup table in python, writing to a binary file that can be read in in a C program


code:
import os,sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

# Google App Engine imports.
from google.appengine.ext.webapp import util

# Force Django to reload its settings.
from django.conf import settings
settings._target = None

import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch

# Log errors.
#import logging
#def log_exception(*args, **kwds):
#    logging.exception('Exception in request:')
#
#django.dispatch.Signal.connect(
#    django.core.signals.got_request_exception, log_exception)

# Unregister the rollback event handler.
django.dispatch.Signal.disconnect(
    django.core.signals.got_request_exception,
    django.db._rollback_on_exception)

def main():
    # Create a Django application for WSGI.
    application = django.core.handlers.wsgi.WSGIHandler()

    # Run the WSGI CGI handler with that application.
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

rawDescription: GAE Configure for Django App

description: GAE Configure for Django App


code:
def gcs(*instances):
    mros = (type(ins).mro() for ins in instances)
    mro = next(mros)
    common = set(mro).intersection(*mros)
    return next((x for x in mro if x in common), None)

rawDescription: Greatest Common Superclass

description: Greatest Common Superclass


code:
ray_arr=np.array((x1,x2))
ray_arr
ray_arr.shape
ray_arr[-1]

rawDescription: Efficient way of appending / extracting list elements


code:
def palm_combinations(points, dist_min=.0, dist_max=.05):
    dists = pdist(points)
    mask = (dists > dist_min) & (dists < dist_max)
    two_good_legs, myinds, triangles = {}, [], []
    s = points.shape[0]
    ind_u1, ind_un = 0, s - 1
    for rowind in xrange(s-1):
        relevant = mask[ind_u1:ind_un]
        ind_u1 = ind_un
        ind_un += s - 1*(rowind+2)
        inds = np.where(relevant)[0] + (rowind+1)
        myinds.append(inds)
        two_good_legs[rowind] = list(itertools.combinations(inds, 2))
    for k,v in two_good_legs.items():
        for tup in v:
            if tup[1] in myinds[tup[0]]:
                triangles.append((k, tup[0], tup[1]))
    return triangles

rawDescription: Speeding up selecting sets of 3 nodes that form triangles with given min and max side length


code:
import lxml.etree as ET

# LOAD XML AND XSL
dom = ET.parse('Input.xml')
xslt = ET.parse('XSLTScript.xsl')

# TRANSFORM XML
transform = ET.XSLT(xslt)
newdom = transform(dom)

# CONVERT TO STRING
tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True)

# OUTPUT TREE TO FILE
xmlfile = open('Output.xml')
xmlfile.write(tree_out)
xmlfile.close()

rawDescription: Find and Replace in Python- based on unknown characters


code:
class EnemiesGroup(object):

    # ... other functions ...

    def clicked(self, event, enemy):
        print('clicked:', enemy),

        # remove oval from canvas
        self.canvas.delete(enemy.oval)

        # remove enemy from list
        self.enemies.remove(enemy)

        # create new enemy after 10s
        root.after(10000, self.add_new_enemy)

    def add_new_enemy(self):

        # can be only 5 enemies
        if len(self.enemies) < 5:
            print('create new enemy')
            e = Enemy(self.canvas)

            # stop new enemy if all enemies are stoped
            e.moving = self.moving

            # bind mouse button to enemy
            self.canvas.tag_bind(e.oval, '<Button-1>', lambda event:self.clicked(event, e))

            self.enemies.append(e)
        else:
            print("You have 5 enemies - I can't add more.")

    # ... other functions ...

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


code:
with open("my.file", "r+") as f:
    [f.readline() for x in range(100)]
    f.truncate()

rawDescription: Python: truncate a file to 100 lines or less


code:
from chocolate import Chocolate
from sweets import Sweet
# ... import everything you want in the tastyfood namespace

rawDescription: Package up Python files

description: Package up Python files


code:
from re import match
def coordinate(coord):
    return bool(match("\s*\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*\)\s*$", coord))

rawDescription: Matching an expression in python regex

description: Matching an expression in python regex


code:
from skimage.transform import ProjectiveTransform
t = ProjectiveTransform()
src = np.asarray(
    [bottom_left, top_left, top_right, bottom_right])
dst = np.asarray([[0, 0], [0, 1], [1, 1], [1, 0]])
if not t.estimate(src, dst): raise Exception("estimate failed")

rawDescription: Transform irregular quadrilateral to rectangle in python matplotlib


code:
def rank_simple(vector):
    return sorted(range(len(vector)), key=vector.__getitem__)

def rankdata(a):
    n = len(a)
    ivec=rank_simple(a)
    svec=[a[rank] for rank in ivec]
    sumranks = 0
    dupcount = 0
    newarray = [0]*n
    for i in xrange(n):
        sumranks += i
        dupcount += 1
        if i==n-1 or svec[i] != svec[i+1]:
            averank = sumranks / float(dupcount) + 1
            for j in xrange(i-dupcount+1,i+1):
                newarray[ivec[j]] = averank
            sumranks = 0
            dupcount = 0
    return newarray

print(rankdata([3, 1, 4, 15, 92]))
# [2.0, 1.0, 3.0, 4.0, 5.0]
print(rankdata([1, 2, 3, 3, 3, 4, 5]))
# [1.0, 2.0, 4.0, 4.0, 4.0, 6.0, 7.0]

rawDescription: Efficient method to calculate the rank vector of a list in Python


rawDescription: how to get a 2d numpy array from a pandas dataframe? - wrong shape

description: Get a 2d numpy array from a pandas dataframe? - wrong shape


code:
import itertools

def enum_iter_slice(collection, slice):
    return enumerate(itertools.islice(collection, slice))

rawDescription: Most Pythonic for / enumerate loop?

description: Most Pythonic for / enumerate loop


rawDescription: Remove everything but the last part of an element


code:
min_obj_set = []
for obj in queryset.order_by('tree_id', '-level'):
    for obj2 in min_obj_set:
        if obj.is_ancestor_of(obj2):
            break
    else:
        min_obj_set.append(obj)

rawDescription: efficient function to retrieve a queryset of ancestors of an mptt queryset

description: Efficient function to retrieve a queryset of ancestors of an mptt queryset


code:
"Exchange Online"
"Office Subscription"
"Identity Service"
"Office 365 Portal"
"Skype for Business"
"SharePoint Online"
"Rights Management Service"
"Yammer Enterprise"
"OneDrive for Business"
"Mobile Device Management"

rawDescription: Querying Office 365 Service Communications API with Python


code:
import collections

def buckets(discrete_set, amin=None, amax=None, bucket_size=None):
    if amin is None: amin=min(discrete_set)
    if amax is None: amax=min(discrete_set)
    if bucket_size is None: bucket_size = (amax-amin)/20
    def to_bucket(sample):
        if not (amin <= sample <= amax): return None  # no bucket fits
        return int((sample - amin) // bucket_size)
    b = collections.Counter(to_bucket(s)
            for s in discrete_set if to_bucket(s) is not None)
    return amin, amax, bucket_size, b

rawDescription: create distribution from a list and generate random numbers which follow that distribution in Python

description: Create distribution from a list and generate random numbers which follow that distribution in Python


code:
if form.process().accepted:
    session.name = form.vars.name
    session.email = form.vars.email
    session.subject = form.vars.subject
    session.message = form.vars.message
    if mail:
        if mail.send(to=['otheremail@yahoo.com'],
            subject='project minerva',
            message= "Hello this is an email send from minerva.com from contact us form.\nName:"+ session.name+" \nEmail : " + session.email +"\nSubject : "+session.subject +"\nMessage : "+session.message+ ".\n "
        ):
            response.flash = 'email sent sucessfully.'
        else:
            response.flash = 'fail to send email sorry!'
    else:
        response.flash = 'Unable to send the email : email parameters not defined'
elif form.errors:
        response.flash='form has errors.'

rawDescription: i am trying send email using web2py with gmail and using smtp setting i have attached all code

description: I am trying send email using web2py with gmail and using smtp setting i have attached all code


code:
import re
sentence_end = re.compile(r'(?<=[.?!])\s+')
sentence_end.split(nX)

rawDescription: How can I do lines of a single string sleep before being printed?

description: Do lines of a single string sleep before being printed


code:
a = np.array([[1,2,3], [4,5,6]])
a
# one way to get Matlab behaivor
(a.T).ravel()

rawDescription: How do you unroll a Numpy array of (mxn) dimentions into a single vector

description: Unroll a Numpy array of (mxn) dimentions into a single vector


code:
with open("/etc/passwd", "rt") as f:
    for line in f:
        if "mail" in line:
            break

rawDescription: How to break from a Python generator with open file handles

description: Break from a Python generator with open file handles


rawDescription: Python generate from list instead of Genfromtext


rawDescription: argparse subcommands with nested namespaces

description: Argparse subcommands with nested namespaces


code:
import asyncio

import websockets

@asyncio.coroutine
def hello():
    connection = yield from websockets.connect('ws://localhost:8000/')
    name = input("What's your name? ")
    yield from connection.send(name)
    print("> {}".format(name))
    for _ in range(3):
        msg = yield from connection.recv()
        print("< {}".format(msg))

    yield from connection.close()

asyncio.get_event_loop().run_until_complete(hello())

rawDescription: Python - how to run multiple coroutines concurrently using asyncio?


rawDescription: List comparison failing

description: List comparison failing


code:
sites = MultiValueField()

def prepare_sites(self, obj):
    return [site.domain for site in obj.sites.all()]

rawDescription: Django Haystack Multisite Indexes

description: Django Haystack Multisite Indexes


code: min(a, key=lambda t:(-t[1],t[0]))

rawDescription: Finding the max in a complex list - Python


code:
from tkinter.ttk import Combobox # python 3 notation
combo = Combobox(root,values=['a','aa','aaaaa','aaaaaaa'],width=3)

rawDescription: In Python Tkinter, how do I set an OptionMenu to a fixed size shorter than the longest item?


rawDescription: How do I get rid of Python Tkinter root window?

description: Get rid of Python Tkinter root window


code:
ints = xrange(33, 127)
key = random.sample(ints, 8)
key
offset = sum(key)
offset
key = ''.join(map(chr, key))
key

rawDescription: How do i take out values from a string? Python

description: Take out values from a string? Python


rawDescription: How to get RMSE from scipy.optimize.leastsq module

description: Get RMSE from scipy.optimize.leastsq module


code:
class Country(object):

    def __init__(self, name, area, population):
        self.name = name
        self.area = area
        self.population = population

rawDescription: reading file into a dictionary

description: Reading file into a dictionary


code:
difference_locations = np.where(df1 != df2)
changed_from = df1.values[difference_locations]
changed_to = df2.values[difference_locations]
pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)

rawDescription: Outputting difference in two pandas dataframes side by side - highlighting the difference


rawDescription: How to change the object that is referenced by a variable?

description: Change the object that is referenced by a variable


code: display = np.empty((cellHeight*nrows, cellWidth*ncols, 3), dtype=np.uint8)

rawDescription: Faster way than concatenate of combining multiple cv2 images (numpy arrays) in python?


code:
# Get size of A
N = A.size

# Perform "(G - A[l])/(G + A[j]))" in a vectorized manner
p1 = (G - A[:,None,None,None])/(G + A[:,None,None])

# Perform "((A[l] - A[j])/(A[l] + A[j]))" in a vectorized manner
p2 = ((A[:,None] - A)/(A[:,None] + A))

# Elementwise multiplications between the previously calculated parts
p3 = p1*p2[...,None,None]

# Set the escaped portion "j != l" output as "G/A[l]"
p3[np.eye(N,dtype=bool)] = G/A[:,None,None]
Fout = p3.prod(1)

# If you need separate arrays just like in the question, split it
Fout_split = np.array_split(Fout,N)

rawDescription: Product of a sequence in NumPy

description: Product of a sequence in NumPy


code: [line.split(':', 1) for line in open('words.txt')]

rawDescription: read text file (colon-separated words) and get a list of tuples

description: Read text file (colon-separated words) and get a list of tuples


code:
class A(object):
    shared_list = []
    def add(self, num):
        self.my_list.append(num)

rawDescription: What is the proper way to share a list between class instances?


code:
static_indices = numpy.ogrid[0:a.shape[0], 0:a.shape[1], 0:a.shape[2]]
a[sort_indices, static_indices[1], static_indices[2]]

rawDescription: Sort a numpy array by another array, along a particular axis


code:
def getdiags(matrix, nr, nc):
    from collections import defaultdict
    d = defaultdict(list)
    for y in range(nr):
        for x in range(nc):
            d[x-y].append(matrix[y][x])
    return d

rawDescription: Diagonal Grid Traverse in Python

description: Diagonal Grid Traverse in Python


code:
from twisted.application.internet import TimerService

def foo():
    from twisted.internet import reactor
    reactor.stop()

from twisted.application.service import Application

application = Application("timer stop")
TimerService(3, foo).setServiceParent(application)

rawDescription: How to stop a TimerService from within the LoopingCall

description: Stop a TimerService from within the LoopingCall


code:
from itertools import izip, islice, tee

def slices(iterable, n):
    return izip(*(islice(it, i, None) for i, it in enumerate(tee(iterable, n))))

rawDescription: Find consecutive combinations

description: Find consecutive combinations


rawDescription: multiple list to tuple

description: Multiple list to tuple


code:
for line in path_output:
    var, equals, rest = line.split(None, 2)
    ...

rawDescription: Using Python2.6 to Parse Bash Output

description: Using Python2.6 to Parse Bash Output


code:
from Tkinter import *
import time

master = Tk()

def my_callback():
    print('Starting my_callback')
    time.sleep(5)
    print('Ending my_callback')

def my_callback2():
    print('Starting my_callback2')
    time.sleep(5)
    print('Ending my_callback2')

b = Button(master, text="OK", command=my_callback)
b.pack()
b = Button(master, text="OK2", command=my_callback2)
b.pack()

mainloop()

rawDescription: Call back in Python

description: Call back in Python


code:
from dis import Bytecode
from inspect import iscode
from itertools import groupby

def _group(i):
    if i.starts_line is not None: _group.starts = i
    return _group.starts

bytecode = Bytecode(func)

for _, iset in groupby(bytecode, _group):
    iset = list(iset)
    try:
        code = next(arg.argval for arg in iset if iscode(arg.argval))
        # Skip <setcomp>, <dictcomp>, <listcomp> or <genexp>
        if code.co_name.startswith('<') and code.co_name != '<lambda>':
            raise TypeError
    except (StopIteration, TypeError):
        continue
    else:
        if any(x.opname == 'LOAD_BUILD_CLASS' for x in iset):
            print(code, 'represents a function {!r}'.format(code.co_name))
        else:
            print(code, 'represents a class {!r}'.format(code.co_name))

rawDescription: Is it possible to access inner functions and classes via code objects?


code: light1ON = GPIO.output(18,HIGH)

rawDescription: Can GPIO.output be assigned to a variable? Raspberry PI


code:
from rest_framework import serializers

class CarSerializer(serializers.ModelSerializer):
    """Serializes car object"""
    class Meta:
        model = Car
        fields = ('id', 'brand',)

class PersonSerializer(serializers.ModelSerializer):
    """Serializes person and car relationship"""
    car = CarSerializer(read_only=True)

    class Meta:
        model = Person
        fields = ('id', 'name', 'car',)

rawDescription: Django Rest Framework approach for JSON API standards


code:
from StringIO import StringIO
import pandas as pd
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

f = StringIO(
"""931,Oxfordshire,9314125,123255,Larkmead School,Abingdon,125,124,20,SUPP,8
931,Oxfordshire,9314126,123256,John Mason School,Abingdon,164,164,25,6,16
931,Oxfordshire,9314127,123257,Fitzharrys School,Abingdon,150,149,9,0,11
931,Oxfordshire,9316076,123298,Our Lady's Abingdon,Abingdon,57,57,SUPP,SUPP,16
""")
df = pd.read_csv(f, names=['A','B','C','D','E','F','G', 'H','I','J', 'K'],
                 header=None)
df.replace('SUPP', 3.0, inplace=True)
df = df.convert_objects(convert_numeric=True)
df['KG'] = df['K']*1.0/df['G']
plt.plot(df['KG'], marker='o')

datacursor(hover=True, point_labels=df['E'])

plt.show()

rawDescription: How to show data labels when you mouse over data

description: Show data labels when you mouse over data


code:
class MyTemplate(string.Template):
    pattern = r'\{(\w+)\}'
a = 'add {new} sentence {with} this word'
t = MyTemplate(a)
t.pattern.findall(t.template)

rawDescription: Python regex to match all words in {}

description: Python regex to match all words in {}


code: res

rawDescription: list comprehension with np.where to compare two arrays and combine them it first entry is equal

description: List comprehension with np.where to compare two arrays and combine them it first entry is equal


code:
cats = db.GqlQuery("SELECT * FROM Cats")
for cat in cats:
    ...

rawDescription: Google Appengine: objects passed to a template changes their addresses in memory


code:
from distutils.core import setup, Extension
setup(name='assembly_include_name', version='1.0', ext_modules=[Extension('assembly_include_name', ['c_assembly_proxy.c'],extra_objects=["assembly_function.o"])])

rawDescription: How to write python extensions in pure asm and would it be efficient?

description: Write python extensions in pure asm and would it be efficient


code:
dictionary = {}
# Insert value1 at index key1
dictionary["key1"] = "value1"

# Overwrite the value at index key1 to value2
dictionary["key1"] = "value2"

print(dictionary["key1"]) # prints value2

rawDescription: Python: defaultdict(dict) how to create nested dictionary?


code: np.minimum(df, np.percentile(df, 90, axis=0))

rawDescription: set value to 99 percentile for each column in a dataframe

description: Set value to 99 percentile for each column in a dataframe


code:
#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz # $ pip install pytz

input_utc_offset = timedelta(hours=-4)
timezone_ids = set()
now = datetime.now(pytz.utc) #XXX: use date that corresponds to input_utc_offset instead!
for tz in map(pytz.timezone, pytz.all_timezones_set):
    dt = now.astimezone(tz)
    tzinfos = getattr(tz, '_tzinfos',
                      [(dt.tzname(), dt.dst(), dt.utcoffset())])
    if any(utc_offset == input_utc_offset for utc_offset, _, _ in tzinfos):
        # match timezones that have/had/will have the same utc offset
        timezone_ids.add(tz.zone)
print(timezone_ids)

rawDescription: pytz: return Olson Timezone name from only a GMT Offset

description: Pytz: return Olson Timezone name from only a GMT Offset


code:
r_init = T.vector()
W = T.matrix()

def step(r):
    r_prime = T.dot(r, W)
    delta = (r_prime - r).norm(1)
    condition = T.lt(delta, N * tol)
    return r_prime, theano.scan_module.until(condition)

outputs, updates = theano.scan(step, outputs_info=[r_init], n_steps=1024)
r_final = outputs[-1]

solve = theano.function(inputs=[r_init, W], outputs=r_final)

rawDescription: Theano: Using theano.scan with theano.scan_module.until


rawDescription: Regular Expression Split on character not in Qualified String (python)


code:
from contextlib import contextmanager

@contextmanager
def thrift_client():
    client, transport = thrift_connect()
    client.functions()
    try:
        yield client
    finally:
        transport.close()

rawDescription: Make an object behave like a module - Python 3


rawDescription: Run code in python script on shutdown signal


code: list_of_querysets = [(qSet1, qSet2, qSet3), (qSet3, qSet2), (qSet1, qSet3)]

rawDescription: Check if queryset already exists

description: Check if queryset already exists


code: table['Purchaser'] = table['Purchaser'].replace(np.nan, 'dummy')

rawDescription: How to use group by and return rows with null values

description: Use group by and return rows with null values


code:
# `jsonp_data` variable contains the body of the response
my_data = loads_jsonp(jsonp_data, "n")

rawDescription: How to write a regular expression to search such string?

description: Write a regular expression to search such string


code:
import functools
import inspect

def verbose(wrapped):
    @functools.wraps(wrapped)  # optional - make wrapper look like wrapped
    def wrapper(*args):
        print('inside wrapper:')
        fsig = inspect.signature(wrapped)
        parameters = ', '.join('{}={}'.format(*pair)
                               for pair in zip(fsig.parameters, args))
        print('  wrapped call to {}({})'.format(wrapped.__name__, parameters))
        for parameter in fsig.parameters.values():
            print("  {} param's annotation: {!r}".format(parameter.name,
                                                         parameter.annotation))
        result = wrapped(*args)
        print('  returning {!r} with annotation: {!r}'.format(result,
                                                         fsig.return_annotation))
        return result
    return wrapper

@verbose
def xXy(x: 'x in X\'s', y: 'y in Y\'s') -> ('x times y','in X and Y units'):
    return x*y

xy = xXy(10, 3)
print('xXy(10, 3) -> {!r}'.format(xy))

rawDescription: Decorator with function annotations

description: Decorator with function annotations


code:
from klepto.keymaps import *

s = stringmap(encoding='hex_codec')
x = [1,2,'3',min]
s(x)
p = picklemap(serializer='dill')
p(x)
sp = s+p
sp(x)

rawDescription: Saving pickle object at each iteration without writing whole object each time


code:
if a[-2] in vowels and a[-1] == 'r':
    a = a[:-2] + 'r'

if len(a) < 6:
    a = 'My{}'.format(a)

rawDescription: How to continue from the 'if' statement to the 'elif' in Python?

description: Continue from the 'if' statement to the 'elif' in Python


code: df.iloc[0:2] = df.iloc[0:2].fillna(method='ffill', axis=1)

rawDescription: Pandas: parse merged header columns from Excel


code:
import epdoc
env.Tool("epydoc")

rawDescription: Run epydoc and/or pylint builders from scons file


rawDescription: Python Programming 3.4.2, Naughts and Crosses. Best way to check how to see if game is won?


rawDescription: Python mac adress matching and processing


code:
from flask import Flask
app = Flask(__name__)
@app.route("/start")
def start():
   return "OK START"
@app.route("/stop")
def stop():
  return "OK STOP!"

if __name__ == "__main__":
   app.run("0.0.0.0",port=8080)

rawDescription: a way to have a Raspberry Pi wait for a command

description: A way to have a Raspberry Pi wait for a command


code: fwd = Widget(...).pack()

rawDescription: Is it possible to run a while loop and check for tkinter input in python 3


code:
def cmod(x, y):
    return abs(x) % abs(y) * (1 if x > 0 else -1)

rawDescription: Changing python math module behaviour for non-positive numbers division


code:
y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))
nbins = y.size
# ...
plt.hist(s, bins=nbins, alpha=0.5)

rawDescription: What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?


code:
import random
x = range(20)
a = []
b = []
for v in x:
    random.choice((a, b)).append(v)

a
b

rawDescription: Random split list, keeping the original order in new lists


code: wilduck_jmitchel3_points = check_match("Wilduck", "jmitchel3")

rawDescription: Basic Match Making for Django and Python


code:
class MD5TransparentFile:
    def __init__(self, source):
        self._sig = hashlib.md5()
        self._source = source

    def read(self, buffer):
        # we ignore the buffer size, just use the `.next()` value in the source iterator
        try:
            line = self._source.next()
            self._sig.update(line)
            return line
        except StopIteration:
            return b''

    def hexdigest(self):
        return self._sig.hexdigest()

rawDescription: python on-the-fly md5 as one reads a stream

description: Python on-the-fly md5 as one reads a stream


rawDescription: Sort a list of sets

description: Sort a list of sets


code: somelist = [random.randint(1, 1000000) for i in xrange(10000)]

rawDescription: Invalid syntax when creating lists

description: Invalid syntax when creating lists


rawDescription: Resize the height of the header in QTableWidget in PyQt


rawDescription: regex returns None on parsing address

description: Regex returns None on parsing address


code: b = a

rawDescription: Python object1 = object2

description: Python object1 = object2


code:
allow_char_set = set(allow_characters)
s = ''.join(c for c in s if c in allow_char_set)

rawDescription: Python Regular Expression Escape or not

description: Python Regular Expression Escape or not


code:
# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {
    "collapse_navigation" : False
}

rawDescription: toctree nested drop down

description: Toctree nested drop down


code:
table = {0x201c: u'"', 0x201d: u'"'}
text.translate(table)

rawDescription: Python: Replacing certain Unicode entities with entities from dictionary


code: [int(binascii.hexlify(x[i:i+3]), 16) for i in range(0, len(x), 3)]

rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


code:
def make_url(genus, species):
    return (
        "http://www.fishbase.ca/summary/{}-{}.html"
        .format(genus.title(), species.lower())
    )

rawDescription: Python Search and Scrape

description: Python Search and Scrape


rawDescription: How to read UTF-8 files with Pandas?

description: Read UTF-8 files with Pandas


code:
def ascending(speed):
    def _ascending(particle):
        particle.y -= speed
    return _ascending

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
producer.running = False
producer.join()
for consumer in consumers:
    consumer.join()

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

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


code:
with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

rawDescription: Reading a file without newlines

description: Reading a file without newlines


rawDescription: Python: Make last item of array become the first


code:
def race_parse(row):
    if row.hispan != 'Not Hispanic':
        return 'Hispanic'
    elif row.race == 'White':
        return 'White'
    elif row.race == 'Black/Negro':
        return 'Black'
    else:
        return 'Other'

df['race4'] = [race_parse(row) for _, row in df.iterrows()]

rawDescription: Pandas function for generating series from dataframe


code: sum((x - 1.0)**2 for x in xlist)

rawDescription: Complex expressions in python reduce

description: Complex expressions in python reduce


rawDescription: Update array values for rows and columns given by a condition


code: count_columns = ['Code', 'Mode', 'Amount', 'From', 'To', 'Weight', 'Cube']

rawDescription: Counting similarities among two pandas dataframes


code:
import tkinter as tk
import os
import json
from tkinter import Toplevel
cert = ""

username = ""
password = ""
base_url = ''
url = ''
splash_page = ''

class BuildApplication(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.lUSER = tk.Label(self, text="Username: ")
        self.lUSER.pack(side="left")
        self.eUSER = tk.Entry(self)
        self.eUSER.pack(side="left")

        self.lPASS = tk.Label(self, text="Password: ")
        self.lPASS.pack(side="left")
        self.ePASS = tk.Entry(self, show="*")
        self.ePASS.pack(side="left")

        #ive tried command= lambda: self.setCredentials(self.eUSER.get(),self.ePASS.get())
        #            command = self.setCredentials(self.eUSER.get(),self.ePASS.get())
        #          But none if it works....
        self.LOGIN = tk.Button(self, text = "Login", fg="green", command=self.setCredentials )
        self.LOGIN.pack(side="left")

        self.QUIT = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy)
        self.QUIT.pack(side="left")

        #self.mainloop()

    def setCredentials(self):
        username = self.eUSER.get()
        password = self.ePASS.get()
        print("username", username)
        print("password", password)
        self.master.destroy()

class SearchApplication(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        print()
        self.some_abel = tk.Label(self, text="create somethng")
        self.some_abel.pack(side="left")
        self.quitb = tk.Button(self, text = "quit", fg="green", command=self.master.destroy )
        self.quitb.pack(side="left")

class MainApplication(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        #Build Data
        self.bBuild = tk.Button(self, text="Build Data", command=self.build)
        self.bBuild.pack(side="top")

        #Search Data
        self.bSearch = tk.Button(self, text="Search",command=self.search)
        self.bSearch["text"] = "Search"
        self.bSearch["command"] = self.search
        self.bSearch.pack(side="top")

        #quit
        self.QUIT = tk.Button(self, text="QUIT", fg="red", command= self.master.destroy)
        self.QUIT.pack(side="bottom")

    def build(self):
        print("Building")
        root2  = tk.Toplevel()
        buildApp = BuildApplication(master=root2)

    def search(self):
        print("Search")
        root3  = tk.Toplevel()
        app2 = SearchApplication(master=root3)

root = tk.Tk()
app = MainApplication(master=root)
app.master.title("fdsafds")

app.mainloop()

rawDescription: Different Windows in TKinter

description: Different Windows in TKinter


code:
foo(args=(), kwargs={})
bar(args=(1,), kwargs={})
baz(args=(), kwargs={'spam': 3})
bork(args=(42,), kwargs={'dent': 17})

foo(args=(), kwargs={})
bar(args=(1,), kwargs={})
baz(args=(), kwargs={'spam': 3})
bork(args=(42,), kwargs={'dent': 17})

rawDescription: Passing (grouped) keyword args to wrapped functions


code: M,N = np.ogrid[:m,:n]

rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
for key, group in itertools.groupby(sorted(List1, key=len), key=len):
    with open('file{}'.format(key), 'w') as f:
        for entry in group:
            f.write(entry)

rawDescription: Extract elements from a list and sorting them by length


code:
def createWordList(line):
    wordList2 =[]
    wordList1 = line.split()
    for word in wordList1:
        cleanWord = ""
        for char in word:
            if char in '!,.?":;0123456789':
                char = ""
            cleanWord += char
        wordList2.append(cleanWord)
    return wordList2

rawDescription: clean line of punctuation and split into words python

description: Clean line of punctuation and split into words python


code:
def remove_word(trie, word):
    current_dict = trie
    for letter in word:
        current_dict = current_dict.get(letter, None)
        if current_dict is None:
            # the trie doesn't contain this word.
            break
    else:
        del current_dict[_end]

rawDescription: How to implement the remove function of a trie in python?

description: Implement the remove function of a trie in python


code:
z=zip(*Files.values())
z
OrderedDict.fromkeys(z)
list(OrderedDict.fromkeys(z))
zip(*OrderedDict.fromkeys(z))

rawDescription: Python remove duplicate values of one key in dict


code:
for x in thousand[400:500]:
    pass

rawDescription: Is there a way to loop through a sub section of a list in Python


code:
@mainBlueprint.before_request
def x(*args, **kwargs):
    if not request.view_args.get('lang'):
        return redirect('/en' + request.full_path)

app.register_blueprint(mainBlueprint, url_defaults={'lang': None})
app.register_blueprint(mainBlueprint, url_defaults='/<lang>')

rawDescription: Flask - how can I always include language code in url


code:
import re

with open("myprogram.py","r",encoding='utf8') as f:
    for x in f.readlines():
        y = x   # Main code x defining as y.
        if re.findall("print",x) == ['print']: # if 'print' is found;
            x = "print(" + x.split("print")[1].strip() + ")" # strip it quotation mark and paranthesis;
            y = y.replace(y,x)  #.. replace y with x.
        with open("different.py","a+") as ff:
            (y.strip()) # attention using \n for every sentence..

rawDescription: Converting scripts to a different version of Python


rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


code:
def divide_numbers(s, n):
    def sub(m):
        return str(float(m.group(1))/n)
    return re.sub('([0-9]+) kg', sub, s)

rawDescription: How to scale all numbers in a string while keeping the format the same in Python?

description: Scale all numbers in a string while keeping the format the same in Python


code:
nested_dict = lambda: collections.defaultdict(nested_dict)

d = nested_dict()
d[1][2][3] = 'Hello, dictionary!'
print(d[1][2][3]) # Prints Hello, dictionary!

rawDescription: How can I get Python to automatically create missing key/value pairs in a dictionary?

description: Get Python to automatically create missing key/value pairs in a dictionary


code: x.reshape(len(x), 1)

rawDescription: Shortest Syntax To Use numpy 1d-array As sklearn X


code:
from random import randrange

def FisherYates(items):
    i = len(items)
    while i > 1:
        i = i - 1
        j = randrange(i+1)  # 0 <= j <= i
        items[j], items[i] = items[i], items[j]
    return

rawDescription: Instead of continue, rerun function

description: Instead of continue, rerun function


code:
vc  = df['Series'].value_counts()
pat = r'|'.join(vc[vc==1].index)          #Regular expression
df  = df[~df['Series'].str.contains(pat)] #Tilde is to negate boolean

rawDescription: Pandas: Delete rows of a DataFrame if total count of a particular column occurs only 1 time


code:
def resize_2d_nonan(array,factor):
    """
    Resize a 2D array by different factor on two axis skipping NaN values.
    If a new pixel contains only NaN, it will be set to NaN

    Parameters
    ----------
    array : 2D np array

    factor : int or tuple. If int x and y factor wil be the same

    Returns
    -------
    array : 2D np array scaled by factor

    Created on Mon Jan 27 15:21:25 2014

    @author: damo_ma
    """
    xsize, ysize = array.shape

    if isinstance(factor,int):
        factor_x = factor
        factor_y = factor
        window_size = factor, factor
    elif isinstance(factor,tuple):
        factor_x , factor_y = factor
        window_size = factor
    else:
        raise NameError('Factor must be a tuple (x,y) or an integer')

    if (xsize % factor_x or ysize % factor_y) :
        raise NameError('Factors must be integer multiple of array shape')

    new_shape = xsize / factor_x, ysize / factor_y

    # non-overlapping windows of the original array
    windows = sliding_window(a, window_size)
    # windowed boolean array for indexing
    notNan = sliding_window(np.logical_not(np.isnan(a)), window_size)

    #list of the means of the windows, disregarding the Nan's
    means = [window[index].mean() for window, index in zip(windows, notNan)]
    # new array
    new_array = np.array(means).reshape(new_shape)

    return new_array

rawDescription: resize a 2D numpy array excluding NaN

description: Resize a 2D numpy array excluding NaN


code:
a.shape
a

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code:
# file args.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--common')
...

rawDescription: What is the scope of python argparse

description: What is the scope of python argparse


code:
abc_categories = map(lambda x: x + '_category', abc_columns)
abc_categories
df[abc_categories] = df[abc_columns].applymap(categories.get)

rawDescription: Efficiently creating additional columns in a pandas DataFrame using .map()


rawDescription: sorting list of lists Python 2.7

description: Sorting list of lists Python 2.7


code:
lst = [3] + list(range(10**4))
seen = set()
any(x in seen or seen.add(x) for x in lst)
seen

rawDescription: How to check for duplicates with less time in a list over 9000 elements by python

description: Check for duplicates with less time in a list over 9000 elements by python


code: df['binned'] = pd.cut(df.val1, bins=bins, labels=labels)

rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


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

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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

ax.yaxis.get_minor_locator().subs([1.5])

# This is the only difference from the last snippet, uses "regular" numbers.
ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

plt.show()

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


code:
import importlib

fileName = ['a','b','c']
for file in fileName:
    module = importlib.import_module(file)
    data.append(module.variableName)

rawDescription: how do I import from a file if I don't know the file name until run time?

description: Import from a file if I don't know the file name until run time


code: np.all(np.diff(xp) > 0)

rawDescription: NumPy: 1D interpolation of a 3D array

description: NumPy: 1D interpolation of a 3D array


code: index = [set.intersection(*[number_locations[num] for num in l]) for l in b]

rawDescription: Find the index of a list which is subset in a list of list


code:
def main():
    config = Configurator()
    config.add_route('user', '/users/{uid}')
    return config.make_wsgi_app()

@view_config(route_name='user', renderer='user_template.mako')
def user_view(request):
    uid = request.matchdict['uid']
    user = find_user(request, uid)
    if user is None:
        raise HTTPNotFound
    return {'user': user}

def find_user(request, uid):
    return request.db.query(User).filter_by(id=uid).first()

rawDescription: How to get an actual Pyramid request when unit testing

description: Get an actual Pyramid request when unit testing


code:
def append_values_inside(key, value):
    temp = []
    for v in value:
        for entry in v:
            temp.append(entry)
    return (key, temp)
for entry in ratings_and_users.map(lambda a: append_values_inside(a[0], a[1])).collect() :
        print(entry)

rawDescription: combining lists inside values in pyspark

description: Combining lists inside values in pyspark


code:
items = [1,2,3,4,5]
inGroup = filter(is_even, items) # list(filter(is_even, items)) in Python 3.x
outGroup = filter(lambda n: not is_even(n), items)
inGroup
outGroup

rawDescription: python equivalent of scala partition

description: Python equivalent of scala partition


code:
import numpy as np

def find_nearest_above(my_array, target):
    diff = my_array - target
    mask = np.ma.less_equal(diff, 0)
    # We need to mask the negative differences and zero
    # since we are looking for values above
    if np.all(mask):
        return None # returns None if target is greater than any value
    masked_diff = np.ma.masked_array(diff, mask)
    return masked_diff.argmin()

rawDescription: How to find nearest value that is greater in numpy array?

description: Find nearest value that is greater in numpy array


code:
from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param1','param2')

    def clean_param1(self):
        data = self.cleaned_data['param1']

        if data == 'spam':
            raise forms.ValidationError("param1 is spam")

        return data

rawDescription: How to control which fields from POST data in ModelForm overwrite fields from instance that is passed in?

description: Control which fields from POST data in ModelForm overwrite fields from instance that is passed in


rawDescription: Scipy's Optimize Curve Fit Limits

description: Scipy's Optimize Curve Fit Limits


code:
import operator
pairs = [(0,1), (5,3)]
xcoords = map(operator.itemgetter(0), pairs)
xcoords

rawDescription: Python function that returns the value at index 0?


code:
class IPv4Pool(models.Model):
    name = models.CharField(max_length=50)

    @property
    def available_ips(self):
        return self.ip_ranges.count()

rawDescription: Field calculated from Foreign Keys, need to save twice?


code:
def session():
    """Returns a :class:`Session` for context-management."""

    return Session()

rawDescription: What's the difference using requests.get and requests_session.get?


code: special_cats = ['cat1','cat2','cat3']

rawDescription: Django url.py Different view functions with the same regex name pattern


code:
scipy.fftpack.fft(np.arange(7))
a = scipy.fftpack.rfft(np.arange(7))
a
a.dtype
a[1:].view(np.complex128)

rawDescription: How should I multiply scipy.fftpack output vectors together?


code:
VAR = value
LONGER = something
VAR1 = value1
# comment
VAR2 = value12
VAR3 = value123
VAR4 = value1234

rawDescription: templated configuration in python or perl?

description: Templated configuration in python or perl


code: num_to_letter = [chr(65 + i) for i in range(4)]

rawDescription: How to do this list/dict comprehension in python

description: Do this list/dict comprehension in python


rawDescription: How to get the optimal optimization variables in Pulp with Python?

description: Get the optimal optimization variables in Pulp with Python


rawDescription: How to query an HDF store using Pandas/Python

description: Query an HDF store using Pandas/Python


code: sum(v1[k] * v2[k] for k in v1)

rawDescription: how can i get the dot product of vectors (list form) in python

description: Get the dot product of vectors (list form) in python


code:
trials = [
    ['dog,cat',(["dog", "cat"], {})],
    ['big fish,cat',(["big fish", "cat"], {})],
    ['"a dog, a cat",a fish',(["a dog, a cat", "a fish"], {})],
    ['key=value',([], {'key':'value'})],
    ['key=the value,x=y',([], {'key':'the value', 'x':'y'})],
    ['dog, big fish, eats="any, but peas", flies = no!',(['dog','big fish'], {'eats':'any, but peas', 'flies':'no!' })],
]
for (x,y) in trials:
    print('%r'%x)
    args = opts(x)
    print(args)
    if args != y:
        print('error, %r'%y)
    print('')

rawDescription: How to parse optional and named arguments into list and dict?

description: Parse optional and named arguments into list and dict


code: np.random.choice(np.arange(5, 9, 0.5), size=3)

rawDescription: How to get 3 float numbers randomly with the step of 0.5 between 5.0 and 9.0 using Numpy?

description: Get 3 float numbers randomly with the step of 0.5 between 5.0 and 9.0 using Numpy


rawDescription: Gradient calculation with python

description: Gradient calculation with python


rawDescription: Python - Function "which" from R in Python


code:
from collections import Counter
from itertools import izip_longest

result = [sum(map(Counter, col), Counter())
    for col in izip_longest(*data.values(), fillvalue={})]

rawDescription: Sum the nested dictionary values in python


code:
class SaveMixin(object):
    def save(self, *args, **kwargs):
        return self, args, kwargs

class Gallery(SaveMixin, object):
    pass

class MyGallery(SaveMixin, object):
    pass

rawDescription: Use a method from other classes w/o inheritance


code:
import subprocess

def method(stream, retries=3):
    while retries > 0:
        line = stream.readline()
        if line:
            yield line
        else:
            retries -= 1

pre_stream = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
stream = subprocess.Popen(cmd, stdin=pre_stream, stdout=subprocess.PIPE).stdout

for parsed in method(stream):
    # do what you want with the parsed data.
    parsed_data.append(parsed)

rawDescription: Parsing the output of a subprocess while executing and clearing the memory (Python 2.7)


rawDescription: Python unique values in a list

description: Python unique values in a list


rawDescription: Difference between union() and union_update() in sets, and others?


rawDescription: Xpath to get prices on amazon

description: Xpath to get prices on amazon


rawDescription: n**n**n heuristics in Python

description: N**n**n heuristics in Python


code: np.max((x + y * cm)[mask])

rawDescription: Is there a better way to rewrite this NumPy Snippet


code:
import cPickle as pickle

data_string = pickle.dumps(data, -1)
#data serialized. -1, which is an optional argument, is there to pick best the pickling protocol
data_loaded = pickle.loads(data) #data loaded.

rawDescription: Sending a Dictionary using Sockets in Python?


code:
def slower():
    result = []
    for elem in some_iterable:
        result.append(elem)
    return result

def faster():
    return [elem for elem in some_iterable]

rawDescription: What is the advantage of a list comprehension over a for loop?


rawDescription: How to make two directory-entries refer always to the same float-value

description: Make two directory-entries refer always to the same float-value


code:
listOfList = [[1,2],[3,4],[5,6]]
map(lambda x: { "OrginalName": x[0], "ExportPath": x[1] }, listOfList )

rawDescription: Insert nested value in mongodb using python


code:
import sqlite3

def max_columns():
    db = sqlite3.connect(':memory:')
    low = 1
    high = 32767  # hard limit <http://www.sqlite.org/limits.html>
    while low < high - 1:
        guess = (low + high) // 2
        try:
            db.execute('CREATE TABLE T%d (%s)' % (
                guess, ','.join('C%d' % i for i in range(guess))
            ))
        except sqlite3.DatabaseError as ex:
            if 'too many columns' in str(ex):
                high = guess
            else:
                raise
        else:
            low = guess
    return low

rawDescription: Determine maximum number of columns from sqlite3


code:
total_active_cells = (cell_counts > 0).sum(0)

print(total_active_cells)
# [0 1 0 2 1 2 2 1 1 2 0 1 0 1 2 0 2 0 1 2 0 1 1]

rawDescription: Row counting with conditional range

description: Row counting with conditional range


code: sorted_lines = sorted(all_lines, key=lambda x: x[0])

rawDescription: Python regex, how to capture multiple rules from 1 string


code:
def upload_to_company(instance, filename):
    if hasattr(instance, 'imgpath'):
        if os.path.exists(instance.imgpath):
            os.remove(instance.imgpath)
    blocks = filename.split('.')
    ext = blocks[-1]
    filename = "%s.%s" % (instance.name, ext)
    instance.title = blocks[0]
    instance.imgpath = os.path.join('media', filename)
    return instance.imgpath

rawDescription: how to change the title of an image upload to a name in a class in django

description: Change the title of an image upload to a name in a class in django


code:
texts = ['apple test', 'test orange fruit']

init = { 'apple': 0, 'orange fruit': 0, 'bunch of bananas': 0 }

def aggregate(agg,x):
  for k in agg:
    if k in x:
      agg[k] += 1
  return agg

counts = reduce(aggregate, texts, init)

rawDescription: Beginner Python query - selecting items in a JSON list


code:
d = {k: v-1 for k,v in d.iteritems()}
d['d']

rawDescription: How to minus one on multiple variable? python

description: Minus one on multiple variable? python


code:
# Assuming you have a large dictionary across a multi-part gzip files.
def files_to_be_analyzed(files):
    lines = ast.literal_eval("".join([gzip.open(file).read() for file in files]))
    date = lines['created_at']
    date_converted = parser.parse(date).strftime('%Y%m%d')
    output_file = gzip.open(date_converted, "a")
    output_file.write(lines + "\n")
    output_file.close()

rawDescription: More Efficient Conversion of Archived Python Dict to JSON


code:
names = ['Anthony','Rudolph', 'Chuck', 'Chuck', 'Chuck', 'Rudolph', 'Bob']

answer = []
name_dict = {}

for name in names:
    if name_dict.get(name):
        name_dict[name] += 1
        answer.append('{}_{}'.format(name, name_dict[name]))
    else:
        name_dict[name] = 1
        answer.append(name)

print(answer)

rawDescription: How to create unique list from list with duplicates

description: Create unique list from list with duplicates


code:
from datetime import datetime
from collections import defaultdict

start = "09/12/2015"
end = "14/12/2015"

start = datetime.strptime(start, "%d/%m/%Y")
end = datetime.strptime(end, "%d/%m/%Y")

d = defaultdict(float)

with open('file') as f:
    l = [i.split('|') for i in f.read().splitlines()]

for key, value in l:
    d[key] += float(value)

l = sorted(((key, value) for (key, value) in d.items()
            if datetime.strptime(key, "%d/%m/%Y") >= start and
            datetime.strptime(key, "%d/%m/%Y") <= end),
           key=lambda x: datetime.strptime(x[0], "%d/%m/%Y"))

for key, value in l:
    print('{} -> {}'.format(key, value))

rawDescription: Compare dates and print sum

description: Compare dates and print sum


code:
padding = 0
a += [padding]*(3-len(a)%3)

rawDescription: python split string every 3rd value but into a nested format

description: Python split string every 3rd value but into a nested format


code:
def binary_search(haystack, needle, lo, hi): # avoid bisect() range limitation
    while lo < hi:
        mid = (lo + hi) // 2
        if haystack[mid] > needle:
            hi = mid
        elif haystack[mid] < needle:
            lo = mid + 1
        else:
            return mid
    return hi

rawDescription: Get the highest possible gmtime for any architecture


code:
def ask_user_name():
    while True:
        username = raw_input("Please give me a username: ")
        if not any(c in username for c in '0123456789'):
            print("Username needs to contain at least one number.")
            continue
        if len(username) >= 8:
            print("Well done")
        elif len(username) <= 1:
            print("More characters please.")
            print("Please try again, input your username again.")
            continue
        break
    return username

print(ask_user_name())

rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


code: df["DATA_MM"] = date

rawDescription: Python PANDAS: New Column, Apply Unique Value To All Rows


code:
from tkinter import *
import random
from PIL import Image, ImageTk

WIDTH, HEIGHT = 150, 150
flags = {
    'England': 'england.gif',
    'Wales': 'wales.gif',
    'Kitty': 'kitty.gif'
}

def batch_resize():

    for k, v in flags.items():
        v = Image.open(v).resize((WIDTH, HEIGHT), Image.ANTIALIAS)
        flags[k] = ImageTk.PhotoImage(v)

def newcountry():

    country = random.choice(list(flags.keys()))
    image = flags[country]
    flagLabel['text'] = country
    flagpicture.config(image=image)

if __name__ == '__main__':

    root = Tk()
    root.configure(bg='black')

    batch_resize()

    flagLabel = Label(root, text="", bg='black', fg='cyan', font=('Helvetica',40))
    flagLabel.pack()

    flagpicture = Label(root)
    flagpicture.pack()

    newflagButton = Button(root, text="Next Country", command=newcountry)
    newflagButton.pack()
    root.mainloop()

rawDescription: how to resize an image to fit the label size? (python)

description: Resize an image to fit the label size? (python)


code:
import mock

attrs_d = {}
def setattrs(name, value):
##    print 'setattrs', name, value
    attrs_d[name] = value
def getattrs(name):
##    print 'getattrs', name
    return attrs_d[name]
mock = mock.MagicMock()
mock.attrs.__setitem__.side_effect = setattrs
mock.attrs.__getitem__.side_effect = getattrs

rawDescription: Test if some field has been initialized in python


code:
with open('filename') as f:
    for chunk in chunk_iterator(f):
        ...

rawDescription: file stream processing in python

description: File stream processing in python


rawDescription: Fetch the details from SOAP xml response


code:
app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        login_user(form.user)
        return redirect(url_for('show_entries'))
    return render_template('login.html', form=form)

rawDescription: Flask view methods and SRP

description: Flask view methods and SRP


code:
event_time = df.index[df.event == "event"]
delta = pd.Timedelta(10, unit="s")

start_idx = df.index.searchsorted(event_time - delta).tolist()
end_idx = df.index.searchsorted(event_time + delta).tolist()

rawDescription: Filtering a panda dataframe based on value and time


code:
a = np.random.random(100)    # an array to draw from
n = 10                       # number of values to draw
i = np.arange(a.size)        # an array of the index value for weighting
w = np.exp(i/10.)            # higher weights for larger index values
w /= w.sum()                 # weight must be normalized

rawDescription: Probabilistic selection from a numpy array


code:
while True:
    do_some_updates(game)
    render_frame(game)

rawDescription: In Python, how do I add 1 every second

description: In Python, how do I add 1 every second


code:
def f(val):
    return [(i, val / i) for i in range(1, int(val**0.5)+1) if val % i == 0]

rawDescription: What is the easiest way to get a list of whole factor pairs of a given integer?


code:
{'www.example.com':
    [
        {'something':
            [
                {'thisthing':
                    [
                        [
                            {'title': 'Detail Page', 'url': 'detail.htm'}
                        ]
                    ]
                },
                [
                    {'title': 'Index Page', 'url': 'index.htm'},
                    {'title': 'Other Page', 'url': 'other.htm'}
                ]
            ],
         'thatthing':
            [
                [
                    {'title': 'About Page', 'url': 'about.htm'}
                ]
            ]
        },
    ]
}

rawDescription: Representing a set of URLs in a list as a tree structure


code:
import Tkinter, win32api, win32con, pywintypes

label = Tkinter.Label(text='Text on the screen', font=('Times New Roman','80'), fg='black', bg='white')
label.master.overrideredirect(True)
label.master.geometry("+250+250")
label.master.lift()
label.master.wm_attributes("-topmost", True)
label.master.wm_attributes("-disabled", True)
label.master.wm_attributes("-transparentcolor", "white")

hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
# http://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx
# The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

label.pack()
label.mainloop()

rawDescription: How to display text on the screen without a window using Python

description: Display text on the screen without a window using Python


code: print("".join([x if i % 3 else x + random_letter for i, x in enumerate(s,1)]))

rawDescription: How to insert number every nth letter in a string in Python?

description: Insert number every nth letter in a string in Python


code:
with open('/home/path/file.csv', 'r+') as csvfile:
    for row in csv.reader(csvfile, delimiter='\t'):
        y = []
        for i in range(0, len(row)):
            x = encrypt(row[i], password)
            y.append(x)
with open('/home/path/file.csv', 'w') as csvfile:
    csvfile.write(''.join(y))

rawDescription: Problems with handling files in Python

description: Problems with handling files in Python


code:
from scrapy.item import Item, Field
from scrapy.contrib.loader.processor import TakeFirst

class MyItemClass(Item):
    url = Field(output_processor=TakeFirst())
    title = Field(output_processor=TakeFirst())
    developer = Field(output_processor=TakeFirst())

rawDescription: scrapy item loader return list not single value

description: Scrapy item loader return list not single value


rawDescription: python argparse extra args

description: Python argparse extra args


code:
import _kurtosis

def kurt4(X, w):
    # add type/size checking if you like
    K = np.zeros(X.shape, np.double)
    scratch = np.zeros(8*(w + 1), np.double)
    _kurtosis.kurt(K, X, scratch, w)
    return K

rawDescription: Implementing a "Kurtosis filter" using scipys generic_filter


code: line = [s.strip() for s in line.split(',')]

rawDescription: Inputting data from file into tuple

description: Inputting data from file into tuple


code: test = sorted(ll1 + ll2)

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
Plotting
# Create the figure and basemap object
fig = plt.figure(figsize=(12, 6))
m = Basemap(projection='robin', lon_0=0, resolution='c')

# Create the projection objects for the convertion
# original (Albers)
inproj = osr.SpatialReference()
inproj.ImportFromWkt(proj)

# Get the target projection from the basemap object
outproj = osr.SpatialReference()
outproj.ImportFromProj4(m.proj4string)

# Convert from source projection to basemap projection
xx, yy = convertXY(xy_source, inproj, outproj)

# plot the data (first layer)
im1 = m.pcolormesh(xx, yy, data[0,:,:].T, cmap=plt.cm.jet)

# annotate
m.drawcountries()
m.drawcoastlines(linewidth=.5)

plt.savefig('world.png',dpi=75)

rawDescription: Plot GDAL raster using matplotlib Basemap


code:
import multiprocessing.managers as m
from multiprocessing.managers import BaseProxy
from multiprocessing import process

def RebuildProxyNoReferent(func, token, serializer, kwds):
    '''
    Function used for unpickling proxy objects.

    If possible the shared object is returned, or otherwise a proxy for it.
    '''
    incref = (
    kwds.pop('incref', True) and
    not getattr(process.current_process(), '_inheriting', False)
    )
    return func(token, serializer, incref=incref, **kwds)

class MyProxy(BaseProxy):
    _exposed_ = ("set_proxy",)
    def set_proxy(self, arg):
        self._callmethod('set_proxy', (arg,))

    def __reduce__(self):
        ret = super(MyProxy, self).__reduce__()
        # RebuildProxy is the first item in the ret tuple.
        # So lets replace it, just for our proxy.
        ret = (RebuildProxyNoReferent,) + ret[1:]
        return ret

class Foo(object):

    def __init__(self):
        self.manager = MyManager()
        self.manager.register('Bar', Bar, MyProxy)
        self.manager.start()
        self.bar = self.manager.Bar()
        print(type(self.bar))
        self.bar.set_proxy(self.bar)

rawDescription: Python: How to pass an Autoproxy object

description: Python: How to pass an Autoproxy object


rawDescription: How to split a Python module into multiple files?

description: Split a Python module into multiple files


rawDescription: NumPy array indexing

description: NumPy array indexing


rawDescription: Pythonic way to modify all items in a list, and save list to .txt file


code:
results = (random.random() for x in xrange(3))
for r in results:
   ...
# results is "used up" now.
# We could have used results_list = list(results) to convert the generator

rawDescription: Populate list or tuple from callable or lambda in python


code:
import json
from collections import MutableMapping

class JSONBackedMapping(MutableMapping):
    def __init__(self, filename, initial=None, **kw):
        self._filename = filename
        try:
            # Try and load the file
            self.load()
        except (ValueError, IOError):
            # failure, fall back to the initial object
            self._data = initial or {}
        self._data.update(**kw)

    def load(self):
        with open(self._filename, 'r') as inf:
            self._data = json.load(inf)

    def save(self):
        with open(self._filename, 'w') as outf:
            json.dump(self._data, outf)

    def __repr__(self):
        return '<{}({!r}, {})>'.format(
            type(self).__name__,
            self._filename, self._data)

    def __len__(self):           return len(self._data)
    def __iter__(self):          return iter(self._data)
    def __getitem__(self, item): return self._data[item]

    def __delitem__(self, item):
        del self._data[item]
        self.save()

    def __setitem__(self, item, value):
        self._data[item] = value
        self.save()

rawDescription: Save a dictionary when it changes

description: Save a dictionary when it changes


code:
meta = sqlalchemy.MetaData(engine, schema='a_schema')
meta.reflect()
pdsql = pd.io.sql.PandasSQLAlchemy(engine, meta=meta)
pdsql.to_sql(df, 'test')

rawDescription: Pandas writing dataframe to other postgresql schema


code:
labels=list('xyzt')
df=pd.DataFrame(a,columns=labels)
df['dist']=abs(df.z-100)
indices=df.groupby(['x','y'])['dist'].apply(argmin)
c=df.ix[indices][labels].reset_index(drop=True)
print(c.head())

rawDescription: Find closest value in array column 4 where array column 1 and 2 match data of another array. Create a new array extracting the results


rawDescription: Syncing code to a label using P4Python

description: Syncing code to a label using P4Python


code:
#using x as a list item
for x in pHand:

    if x[0] == '1' or x[0] == 'J' or x[0] == 'Q' or x[0] == 'K':
        pTotal += 10
    elif x[0] == 'A':
        pTotal += 11
    else:
        pTotal += int(x[0])

rawDescription: Python - For loop isn't kicking in (blackjack game)


rawDescription: selecting numpy array axis by int

description: Selecting numpy array axis by int


code:
df[:2]
df['timestamp'] = pd.to_datetime(df['timestamp'])
df[:2]

rawDescription: Working with dates in pandas

description: Working with dates in pandas


code:
def timeseq(start,stop,interval):
    while start <= stop:
        yield start
        start += interval

rawDescription: Get Intervals Between Two Times

description: Get Intervals Between Two Times


code: assert response.wsgi_request.path == reverse("userhome", kwargs={"pk":user.id})

rawDescription: Redirecting Django built-in login View to a URL taking user's pk as argument


code:
# iterate over points and turn them all red
for point in ax.collections:
    point.set_facecolor("red")

rawDescription: Matplotlib : how to label points individually?


code: name

rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


code:
class AbstractTestClass(metaclass=AbstractTestClassMeta):

    @abstractproperty
    def luminance(self):
        # abstract property
        pass

    @luminance.setter
    @ValidateProperty(Exception, int)
    def luminance(self, value):
        # abstract property validator
        return 0 <= value <= 15

rawDescription: How to provide value validation at abstract class level?

description: Provide value validation at abstract class level


code:
s = df.select_dtypes(include=['int64']) * 2
df[s.columns] = s
df

rawDescription: changing only numerical data in pandas DataFrame

description: Changing only numerical data in pandas DataFrame


code:
import contextlib
import socket
import filegenerator

sock = socket.socket()
with contextlib.closing(sock):
    sock.connect((HOST, 12345))
    for filename in filegenerator.generate():
        with open(filename, 'rb') as f:
            contents = f.read()
            buf = '{0}:{1},{2}:{3},'.format(len(filename), filename,
                                            len(contents), contents)
            sock.sendall(buf)

rawDescription: Python: Upload huge amount of files via FTP


code:
at_words = re.compile(r'(?<=@)\w+')

at_words.findall(inputtext)

rawDescription: extracting multiple instances regex python

description: Extracting multiple instances regex python


code:
items = ((k, k2, v) for k in d for k2, v in d[k].items())
ordered = sorted(items, key=lambda x: x[-1], reverse=True)

rawDescription: Sort a dictionary of dictionaries python


code:
for index, element in zip(range(limit), items):
    ...

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code: res = cache[tuple(x)]

rawDescription: Fastest way to convert a binary list(or array) into an integer in Python


code:
import re
a = 'Builders Club The Ohio State'
re.sub(r'\bThe\b', '', a, flags=re.IGNORECASE)

rawDescription: Python Regex Word Boundaries not working as expected


code:
from heapq import nlargest
ids = nlargest(10, xrange(g.vcount()), key=igraph_eg.__getitem__)
names = g.vs[ids]["name"]

rawDescription: How to get name property out of the result of eigenvalue in igraph?

description: Get name property out of the result of eigenvalue in igraph


code:
octets = '192.168.1.1-255'.split('.')
parsed_ranges = [map(int, octet.split('-')) for octet in octets]

rawDescription: Python - Generate a list of IP addresses from user input


code:
ax.spines['left'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.ylim(ymin=0)
plt.show()

rawDescription: Graph, that crosses y axis

description: Graph, that crosses y axis


rawDescription: Error saving django model with OneToOne field - Column specified twice


code:
from scipy.interpolate import griddata as gd

zi = gd(
    (data[['projected_lon', 'projected_lat']]),
    data.Z.values,
    (xi, yi),
    method='linear')

rawDescription: How can I get my contour plot superimposed on a basemap

description: Get my contour plot superimposed on a basemap


code: from cgi import parse_qs

rawDescription: Regular Expression to extract parts of Twitter query


code:
from google.appengine.ext import ndb
from pprint import pprint as pp

class ndb_Project(ndb.Model):
    name = ndb.StringProperty()
    description = ndb.StringProperty()
    parentProj = ndb.KeyProperty()
    childProj = ndb.KeyProperty(repeated=True)

    def getChildProjects(self):
        a = [ent.getChildProjects() for ent in ndb.get_multi(self.childProj)]
        o = self.to_dict()
        o['urlSafe'] = self.key
        o['childProj'] = a
        return o

p = ndb_Project(name='first', description='first entity')
p.put()

for x in xrange(5):
    tmp = ndb_Project(name=str(x), description='desc %s' % x)
    p.childProj.append(tmp.put())
    for y in xrange(5):
        tmp2 = ndb_Project(name='%s %s' % (x, y), description='desc %s %s' % (x, y))
        tmp.childProj.append(tmp2.put())
    tmp.put()
p.put()

pp(p.getChildProjects())

rawDescription: GAE Recursive Query

description: GAE Recursive Query


rawDescription: python string in-place modification

description: Python string in-place modification


code: model.score(X_train, y_train)

rawDescription: Difference between .score() and .predict in the sklearn library?


code:
  #  'allauth.account.context_processors.account',
  #  'allauth.socialaccount.context_processors.socialaccount',

rawDescription: How to integrate djangobb in an existing project?

description: Integrate djangobb in an existing project


code:
regexes = [re.compile(r'expression 1'), re.compile(r'expression 2'), ...]
for regex in regexes:
  match = regex.search(input_text)
  if match: break

if not match:
  print("We didn't find anything!")

rawDescription: Parsing text with regex in Python: determine match order and mapping value to object type?


rawDescription: Trouble printing text live with Python subprocess.call


code:
from xml.dom.minidom import parse

dom = parse("data.xml")
for node in dom.getElementsByTagName('CallsPerMinute'):
    print(node.firstChild.nodeValue)

rawDescription: How can i get a value in XML file? Python

description: Get a value in XML file? Python


rawDescription: adding columns to dataframe based on values (time stamps)

description: Adding columns to dataframe based on values (time stamps)


rawDescription: Replace a text in a text file in python

description: Replace a text in a text file in python


rawDescription: Ploting solid of revolution in Python 3 (matplotlib maybe)


code:
import matplotlib.pylab as plt

plt.figure()
ax=plt.gca()
y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1]
#plt.plot([10,10,14,14,10],[2,4,4,2,2],'r')
col_labels=['col1','col2','col3']
row_labels=['row1','row2','row3']
table_vals=[[11,12,13],[21,22,23],[31,32,33]]
# the rectangle is where I want to place the table
the_table = plt.table(cellText=table_vals,
                  colWidths = [0.1]*3,
                  rowLabels=row_labels,
                  colLabels=col_labels,
                  loc='center right')
plt.text(12,3.4,'Table Title',size=8)

plt.plot(y)
plt.show()

rawDescription: How can I place a table on a plot in Matplotlib?

description: Place a table on a plot in Matplotlib


code:
idx = df.groupby("primary_key").B.event_data(pd.Series.idxmin)
res2 = df.loc[idx]

rawDescription: Python pandas: retrieve the field associated to the min of another (cross apply equivalent)


code:
import numpy as np
from pprint import pprint

class GlobalArrayHolder(object):
    def __init__(self):
        self.test_array = np.array([1, 2, 3])

arrayholder = GlobalArrayHolder()
pprint(arrayholder.test_array)

rawDescription: Can't append global NumPy array from other module


code:
def _debugFunction(localdict, var_list=''):
    var_list = var_list.split()
    if not var_list:
        var_list = localdict.keys()

rawDescription: Printing 'var' = var

description: Printing 'var' = var


code:
from bs4 import BeautifulSoup

from urllib.request import urlopen

wiki = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

page = urlopen(wiki)

soup = BeautifulSoup(page, 'lxml')

result = soup.find("table", class_="wikitable")

print(result)

rawDescription: Beautiful Soup scrapes only half table

description: Beautiful Soup scrapes only half table


rawDescription: Method that gets called on module deletion in Python


code:
os.chdir('c:\\anotherdir')
fd = open('myfile.txt')

rawDescription: Distinction Between CWD and Import Search Path in Python?


code: df1 = df.sort_values(by = ['ID','DATETIME'])

rawDescription: GroupBy - Datetime diff() combining additional criteria


code:
L = [0,1,1,0]
print("".join(map(str, sorted(L, reverse=True)))) # O(n*log n)

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

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


code:
with mock.patch.object(MyClassUnderTest, "submethod") as submethod_mocked:
    submethod_mocked.return_value = 13
    MyClassUnderTest().main_method()
    submethod_mocked.assert_called_once_with(user_id, 100, self.context,
                                             self.account_type)

rawDescription: Mocking only a single method on an object


code:
for k, v in namcat.items():
    for item in v:
        for key, value in tom.items():
            if value == item:
                running_total += 1

rawDescription: Python Compare Two Key/Value Pairs

description: Python Compare Two Key/Value Pairs


rawDescription: Is there universal if function in numpy?

description: Is there universal if function in numpy


code:
s = 'apple'
zip(s, s[1:])

rawDescription: check 2 consecutive occurrences of the same letter

description: Check 2 consecutive occurrences of the same letter


code:
class NestedDict(dict):
    def __getitem__(self, key):
        if key in self: return self.get(key)
        return self.setdefault(key, NestedDict())
    def __add__(self, other):
        return other
    def __sub__(self, other):
        return other

rawDescription: Nested, infinite dictionary in python

description: Nested, infinite dictionary in python


code:
@jit
def gen_adj(width, height):
    # each pixel has four neighbors, but some of these neighbors are
    # off the grid -- 2*width + 2*height of them to be exact
    n_entries = width*height*4 - 2*width - 2*height
    adj = np.zeros((n_entries, 4), dtype=int)
    gen_adj_loop(width, height, adj)

rawDescription: Optimizing dict of set of tuple of ints with Numba?


rawDescription: Can I make pprint in python3 not split strings, like in python2?

description: Make pprint in python3 not split strings, like in python2


code:
def get_chunks(arr, start, stop):
     rng = stop - start
     rng = rng[rng!=0]      #Need to add this in case of zero sized ranges
     np.cumsum(rng, out=rng)
     inds = np.ones(rng[-1], dtype=np.int)
     inds[rng[:-1]] = start[1:]-stop[:-1]+1
     inds[0] = start[0]
     np.cumsum(inds, out=inds)
     return np.take(arr, inds)

rawDescription: Construct single numpy array from smaller arrays of different sizes


code:
list.sort(cmp = lambda self, other: \
                (self.c, self.a, self.b) < (other.c, other.a, other.b))

rawDescription: In Python how would I compare with multiple values using custom keys?


code:
x=5    # discussed
id(x)  # the 'id' which in cPython is the memory address.
y=x    # now two names, 'x' and 'y' associated with that object
id(y)
z=5    # no guaranteed, likely the same object referred to by 'x' and 'y'
id(z)
del x           # ref count to object '140246146681256' decreased by 1
del y           # same
z
id(z)

rawDescription: Is a variable the name, the value, or the memory location?


code:
x = 3
s = 'hello world'

s[:(len(s) // x) * x]

rawDescription: How to truncate a string's length to the largest multiple of a smaller integer?

description: Truncate a string's length to the largest multiple of a smaller integer


rawDescription: Combine two lists of lists - bitwise

description: Combine two lists of lists - bitwise


code: len(message)

rawDescription: How do you calculate the amount of characters including spaces and numbers in a string

description: Calculate the amount of characters including spaces and numbers in a string


code:
from distutils.core import setup, Extension
import sys

libraries = []

if sys.platform == 'win32':
    libraries.append('ws2_32')

fastbinarymod = Extension('thrift.protocol.fastbinary',
                          sources = ['src/protocol/fastbinary.c'],
                          libraries = libraries,
        )

setup(name = 'Thrift',
      version = '0.1',
      description = 'Thrift Python Libraries',
      author = 'Thrift Developers',
      author_email = 'thrift-dev@incubator.apache.org',
      url = 'http://incubator.apache.org/thrift/',
      license = 'Apache License 2.0',
      packages = [
        'thrift',
        'thrift.protocol',
        'thrift.transport',
        'thrift.server',
      ],
      package_dir = {'thrift' : 'src'},
      ext_modules = [fastbinarymod],
      )

rawDescription: Error setting up thrift modules for python


code: self.lastUpdateTime = int(time.time())

rawDescription: Getting the time remaining before event.wait is done in Python


code: sql = 'INSERT INTO home_title VALUES ({})'.format(', '.join(['%s'] * 57))

rawDescription: Dynamic length of SQL args

description: Dynamic length of SQL args


code:
class GraphGUI():
    ...

    @property
    def myarray(self):
        e_txt = self.textfield.get('1.0', END)
        converted = e_txt.encode('ascii', 'ignore')
        return converted.splitlines()

    def clicked(self):
        print(self.myarray)
        # do whatever else it has to do

rootWin = Tkinter.Tk()
start = Tkinter.Button(rootWin, text="Start!",
                       command=lambda: app.myarray)
...

rawDescription: Python: retrieve objects's value from a class object


code:
import numpy as np
import pandas as pd

def cvscore(fclist):
    sd = np.std(fclist)
    mean = np.mean(fclist)
    cv = sd/mean
    return cv

df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],
                   'CCC' : [100,50,-30,-50]})

df['Score'] = df.iloc[:, 1:].apply(cvscore, axis=1)
print(df)

rawDescription: Apply function row wise on pandas data frame on columns with numerical values


code:
from collections import defaultdict

data = defaultdict(list)

# ... same as before up to your if

if clientkey in data and ref in data[clientkey]:
    print("That invoice already exists")
else:
    data[clientKey].append(ref)

rawDescription: Cannot append string to dictionary key

description: Cannot append string to dictionary key


code:
class OrderTests(TestCase, ShopTest):
    _VIEW = staticmethod(views.order)

    def test_gateway_answer(self):
        url = 'whatever url'
        request = self.request_factory(url, 'GET')
        self._VIEW(request, **{'sku': order.sku})

rawDescription: Call external function without sending 'self' arg


code: fixtureTXT = open("fix.txt", "a")

rawDescription: How to write to a NEW LINE and not always on the same line in a text file after a UNIQUE file.write request?

description: Write to a NEW LINE and not always on the same line in a text file after a UNIQUE file.write request


code:
def _counter(d):
    # how many keys do we have?
    yield len(d)

    # stream the key counts of our children
    for v in d.itervalues():
        if isinstance(v, dict):
            for x in _counter(v):
                yield x

def count_faster(d):
    return sum(_counter(d))

rawDescription: Get the number of all keys in a dictionary of dictionaries in Python


code:
import calendar
nextmonth = calendar.month_name[1:][(calendar.month_name[1:].index(month) + 1) % 12]

rawDescription: Dynamically naming edited csv, to include part of the old csv name


code:
gprmc, hdop, altitude, state, ad, baseid, csq, journey, *_ = information.split('|')
(ptime, gpsindicator, lttd, ns, lgtd,
 ew, speed, course, pdate, dd, *_, checksum) = gprmc.split(',')

rawDescription: list received is bigger than expected

description: List received is bigger than expected


code:
from numpy import matrix
from numpy.linalg import solve

def circfit(xs, ys):
    a = matrix([[x,y,1.] for x,y in zip(xs, ys)])
    b = matrix([[-(x*x + y*y)] for x,y in zip(xs, ys)])
    res = solve(a,b)
    xc = -0.5 * res.item(0)
    yc = -0.5 * res.item(1)
    r = (xc*xc + yc*yc - res.item(2))**0.5
    return xc,yc,r

rawDescription: How do I write this matlab example to python

description: Write this matlab example to python


code: [x for x in first_list if x not in secnd_list] + [x for x in secnd_list if x not in first_list]

rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


rawDescription: Python raw_input a variable name

description: Python raw_input a variable name


code:
for key, values in dico.items():
    for value in values:
        new_dict.setdefault(value, set()).add(key)

rawDescription: Get a string list from a word

description: Get a string list from a word


code: vars()

rawDescription: naming collision in namespaces in modules of python

description: Naming collision in namespaces in modules of python


code:
for row in table:  # iterate over the rows (items of the outer list)

    for column in row:  # iterate over the columns of the current row (items of inner list)

        print("Row:", row_number, "- Column:", column_number)
        print(" --> Item:", table[row_number][column_number])

        # <-- jump back to the column loop head here, if elements remaining

    # <-- jump back to the row loop head here, if elements remaining

rawDescription: why does order of loop nesting matter python?

description: Why does order of loop nesting matter python


code:
def tau(n):
        sqroot,t = int(n**0.5),0
        for factor in range(1,sqroot+1):
                if n % factor == 0:
                        t += 2 # both factor and N/factor
        if sqroot*sqroot == n: t = t - 1 # if sqroot is a factor then we counted it twice, so subtract 1
        return t

rawDescription: How do you implement the divisor function in code?

description: Implement the divisor function in code


code:
target = b*exp(-a*t)
target
target.subs(m)

rawDescription: SymPy: How to get values from expression


code:
pkt_lengths = {
    'CMD': 4,
    'RES': 4,
    'ERR': 6,
    'CMD/RES': 6,
}

get_min_length = pkt_lengths.__getitem__

rawDescription: How to ensure solid contracts without strong typing?

description: Ensure solid contracts without strong typing


rawDescription: Django/python: loop through a dictionary and add an item to it


code:
regex = re.compile(r"{{persondata(.*)}}",re.IGNORECASE|re.MULTILINE|re.UNICODE|re.DOTALL)
regex.search(text).group()

rawDescription: Python Regex not working to extract information from a wiki page


code: user.lower() == "paper"

rawDescription: weird behaviour in python if clause

description: Weird behaviour in python if clause


code: list(enumerate(winners, 1903))

rawDescription: Add a Year to each item in list or Dictionary


code: soup = BeautifulSoup(page, 'xml')

rawDescription: Why Beautiful Soup Ignoring CDATA

description: Why Beautiful Soup Ignoring CDATA


code:
from distutils.core import setup
import py2exe
setup(
 name="mycode",
 windows =['mycode.py'],
 options = {"py2exe": {"packages": ["encodings"]}}
 )

rawDescription: python 3.4 py2exe image.open cannot find the images

description: Python 3.4 py2exe image.open cannot find the images


code:
def start(self, captureNetworkTraffic=False):
    l = [self.browserStartCommand, self.browserURL, self.extensionJs]
    if captureNetworkTraffic:
        l.append("captureNetworkTraffic=true")
    result = self.get_string("getNewBrowserSession", l)

rawDescription: Selenium-rc: How do you use CaptureNetworkTraffic in python


code:
#!/usr/bin/env python
import sys

if sys.version_info[:1] < (3,):
    from pexpect import spawn, EOF # $ pip install pexpect
else:
    from pexpect import spawnu as spawn, EOF # Python 3

child = spawn("./randomNumber") # run command
child.delaybeforesend = 0
child.logfile_read = sys.stdout # print child output to stdout for debugging
child.expect("enter a number: ") # read the first prompt
lo, hi = 0, 100
while lo <= hi:
    mid = (lo + hi) // 2
    child.sendline(str(mid)) # send number
    index = child.expect([": ", EOF]) # read prompt
    if index == 0: # got prompt
        prompt = child.before
        if "too high" in prompt:
            hi = mid - 1 # guess > num
        elif "too low" in prompt:
            lo = mid + 1 # guess < num
    elif index == 1: # EOF
        assert "Congratulations" in child.before
        child.close()
        break
else:
    print('not found')
    child.terminate()
sys.exit(-child.signalstatus if child.signalstatus else child.exitstatus)

rawDescription: subprocess readline hangs waiting for EOF

description: Subprocess readline hangs waiting for EOF


code:
import ImageChops
import math, operator

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add,
        map(lambda h, i: h*(i**2), h, range(256))
    ) / (float(im1.size[0]) * im1.size[1]))

rawDescription: Comparing Image Files

description: Comparing Image Files


code: to_test['Some text']

rawDescription: Python list value setting

description: Python list value setting


code:
import webapp2
class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')

app = webapp2.WSGIApplication([
    ('/', HelloWebapp2),
], debug=True)

def main():
    app.run()

if __name__ == '__main__':
    main()

rawDescription: How can I use webapp2 in Google App Engine using Python 2.5?

description: Use webapp2 in Google App Engine using Python 2.5


code:
reservation = ec2.run_instances( image_id=AMI_ID,
                                 key_name=EC2_KEY_HANDLE,
                                 instance_type=INSTANCE_TYPE,
                                 security_groups = [ SECGROUP_HANDLE, ],
                                 block_device_mappings = [bdm])

rawDescription: How to launch EC2 instance with Boto, specifying size of EBS?

description: Launch EC2 instance with Boto, specifying size of EBS


code:
text = "March 1st 2013 ntp[22485] Time server offset -.0070 sec"
text.rfind('offset')

rawDescription: Extract specific characters from the string