code:
for line in log1:
    test = line[4].split('-')[1] # changes test-#### to ####
    if test in tests:
        tests[test].update({
            'thread': line[1],
            'run':    line[3],
            'url':    line[6],
            'times':  ', '.join(tests[test]['times'])
        })

rawDescription: Parse data from 2 log files in Python

description: Parse data from 2 log files in Python


code:
import numpy as np
a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array([-1,-2,-3,-4,-5,1,2,-3,-4])

x = np.linspace(a.min(), a.max(), 1000)
y = np.interp(x, a, b)

m = y <= 0
plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'b-', lw=2)
m = y > 0
plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'r--', lw=2)

rawDescription: How to plot with different linestyles in pylab

description: Plot with different linestyles in pylab


rawDescription: Creating a file to lookup paths and file names?


code:
import email.message
import imaplib
import random
import time
import xoauth

MY_EMAIL = 'youremail@gmail.com'
MY_TOKEN = '<token>'
MY_SECRET = '<secret>'

# construct the oauth access token
nonce = str(random.randrange(2**64 - 1))
timestamp = str(int(time.time()))
consumer = xoauth.OAuthEntity('anonymous', 'anonymous')
access = xoauth.OAuthEntity(MY_TOKEN, MY_SECRET)
token = xoauth.GenerateXOauthString(
    consumer, access, MY_EMAIL, 'imap', MY_EMAIL, nonce, timestamp)

# connect to gmail's imap service.
imap = imaplib.IMAP4_SSL('imap.googlemail.com')
imap.debug = 4
imap.authenticate('XOAUTH', lambda x: token)

# create the message
msg = email.message.Message()
msg['Subject'] = 'subject of the message'
msg['From'] = MY_EMAIL
msg['To'] = MY_EMAIL
msg.set_payload('Body of the message')

# append the message to the drafts folder
now = imaplib.Time2Internaldate(time.time())
imap.append('[Gmail]/Drafts', '', now, str(msg))

imap.logout()

rawDescription: Programatically Save Draft in Gmail drafts folder


code:
import func1, func2
operation_dispatcher = {
    "func1": getattr(func1, "func1"),
    "func2": getattr(func2, "func2"),
}

def something_calling_funcs(func_name, param):
    """Calls func_name with param"""
    func_to_call = operation_dispatcher.get(func_name, None)
    if func_to_call:
        func_to_call(param)

rawDescription: Call a user defined function given its name as a string input to another function Python 2.7


rawDescription: processing a set of unique tuples

description: Processing a set of unique tuples


code:
(line for f in (itertools.chain(f, (f for f in (f,) if f.close() and False))
                for f in (open("filename") for _ in itertools.repeat(())))
 for line in f)

rawDescription: Re-reading file when cycling over a file object in Python


code:
getter = itemgetter('apple', 'grape')
apple, grape = getter(foodColors())
apple2, grape2 = getter(foodColors())

rawDescription: Assign values in returned dictionary to unique variables


code:
output = {k1: {k2: (d1.get(k1, {}).get(k2), d2.get(k1, {}).get(k2))
          for k2 in set(list(d1.get(k1, {}).keys()) + list(d2.get(k1, {}).keys()))}
          for k1 in set(list(d1.keys()) + list(d2.keys()))}

rawDescription: merge to dictionaries preserving different values

description: Merge to dictionaries preserving different values


code:
response = some_calculation(result)
return jsonify(response)

rawDescription: Trouble with Flask Requests - returns GET before any actions


code:
from django.utils import simplejson as json

def index(request):
   fields    = MyModel._meta.fields
   data      = json.loads(serializers.serialize("json", MyModel.objects.all()))

   def parse_data(data):

        result = []

        # flatten the dictionary
        def flatten_dict(d):
            """
            Because the only nested dict here is the fields, let's just
            remove the 'fields' suffix so that the fields can be loaded in
            template by name
            """
            def items():
                for key, value in d.items():
                    if isinstance(value, dict):
                        for subkey, subvalue in flatten_dict(value).items():
                            yield subkey, subvalue
                    else:
                        yield key, value

            return dict(items())

        for d in data:
            # change the 'pk' key name into its actual name in the database
            d[Employee._meta.pk.name] = d.pop('pk')
            # append the flattend dict of each object's field-value to the result
            result.append(flatten_dict(d))

        return result

   context_instance = RequestContext(request, {
       'data'      : parse_data(data),
       'fields'    : fields,
   })
   return TemplateResponse(request, 'index.html', context_instance)

rawDescription: Display table of objects django

description: Display table of objects django


code:
from ghost import Ghost
from bs4 import BeautifulSoup
ghost = Ghost()
ghost.open('http://localhost:8000')

soup = BeautifulSoup(ghost.content)
soup.find_all('a')

rawDescription: Making AJAX calls with Python

description: Making AJAX calls with Python


rawDescription: Highlighting a clicked line in an unfocused Tkinter text widget


rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


rawDescription: How to bind a constant parameter in Python?

description: Bind a constant parameter in Python


code:
a = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
b = [1, 4]
b_set = set(b)
[elem for elem in a if elem in b_set]

rawDescription: A subset of a list with elements available in another list


code:
r = Revision(name = self.name,
             content = self.content,
             created = self.created,
             modified = self.modified,
             user = self.user)
r.put()

rawDescription: Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code


code: temp = z[:]

rawDescription: How can I assign by value in python

description: Assign by value in python


code:
import psutil

print(psutil.pids()) # Print all pids

rawDescription: Checking if program is running

description: Checking if program is running


rawDescription: Python root logger messages not being logged via handler configured with fileConfig


rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
result = L[0]
for num in L[1:]:
    result -= num

rawDescription: How to subtract from a user-inputed list

description: Subtract from a user-inputed list


code:
class StreamHandler(Handler):
    def __init__(self, stream=None):
        Handler.__init__(self)
        if stream is None:
            stream = sys.stderr
        self.stream = stream

rawDescription: Python StringIO is not correctly capturing data from stderr


code:
import collections
short_data = collections.defaultdict(collections.Counter)
for key, value in data.items():
    short_key = (key[0], key[1], key[3])
    short_data[short_key] += collections.Counter(dict(data[key]))

rawDescription: Python Dictionary Trouble: Grouping by elements in tuple key


code:
from subprocess import check_output,CalledProcessError
def apt_cache(*args):
    try:
        return check_output(args)
    except CalledProcessError as e:
        return e.output

print(apt_cache("apt-cache","showpkg ","python"))

rawDescription: How to lookup debian package info with Python

description: Lookup debian package info with Python


code:
from scrapy import signals
from scrapy.exceptions import DropItem

class DuplicatesPipeline(object):
    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.ids_seen.add(item['id'])
            return item

rawDescription: Writing to multiple files with Scrapy

description: Writing to multiple files with Scrapy


code:
from django.http import HttpResponse
from django.views.generic import View

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('This is GET request')

    def post(self, request, *args, **kwargs):
        return HttpResponse('This is POST request')

rawDescription: Django GET and POST handling methods

description: Django GET and POST handling methods


rawDescription: How can I get the set difference of two Sparse Matrices?

description: Get the set difference of two Sparse Matrices


code:
driver = webdriver.Chrome()
driver = webdriver.Firefox()
driver = webdriver.Ie()

rawDescription: Python webdriver from Selenium

description: Python webdriver from Selenium


code: return query

rawDescription: GAE Datastore ndb models accessed in 5 different ways


rawDescription: Numpy genfromtxt issue with datetime with multiple columns


code:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

rawDescription: Python Script execute commands in Terminal


code: data

rawDescription: Python List splitting, sorting by date, then joining


code:
df.index.min()
df.index.max()

rawDescription: How to access first and last timestamp in dataframe

description: Access first and last timestamp in dataframe


rawDescription: Printing until a specific character position in python


code:
sentence = "the foo and the bar is foo bar"
words = sentence.split()

def get_distance(w1, w2):
     if w1 in words and w2 in words:
          return abs(words.index(w2) - words.index(w1))

rawDescription: Determining proximity between 2 words in a sentence in Python


code:
def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
bools = list(map(lst,isNum))
deleted = 0
for idx, val in enumerate(bools):
    if val:
            continue
    else:
            del lst[idx-deleted]
            deleted = deleted + 1

rawDescription: How to remove strings that contain letters from a list?

description: Remove strings that contain letters from a list


code:
def diff_func(df):
    return df.diff()

rawDescription: calculate diff() in python on subsets of data within a dataframe

description: Calculate diff() in python on subsets of data within a dataframe


rawDescription: How to use Pandas to create Dictionary from column entries in DataFrame or np.array

description: Use Pandas to create Dictionary from column entries in DataFrame or np.array


code:
print(*[''.join(t) for t in reorder_product('ABCD', 'xy')])
# Output:
#     Ax Bx Cx Dx Ay By Cy Dy

rawDescription: How to sort itertools.product in Python?

description: Sort itertools.product in Python


code:
if a_tuple:
    pass

rawDescription: "Non-equal" or "greater than" is quicker?


code:
def sumNCubes(n):
    return sum(i**3 for i in range(1,n+1))

rawDescription: How to add the sum of cubes using a function in python?

description: Add the sum of cubes using a function in python


code:
l = range(10)
l
import numpy
a = numpy.array(l)
a

rawDescription: gotchas where Numpy differs from straight python?

description: Gotchas where Numpy differs from straight python


code:
def __init__(self,spam,eggs,swallow,coconut):
    self.spam = spam
    self.eggs = eggs
    self.swallow = swallow
    self.coconut = coconut

rawDescription: Initializing object variables - a Java approach, a Python approach?


code:
d = [[1, 1], [0, 0]]
from itertools import permutations, chain
from pprint import pprint
pprint(sorted([i[:2], i[2:]] for i in set(permutations(chain.from_iterable(d)))))

rawDescription: Generate all unique permutations of 2d array


code:
# call the method in the main thread
spinner = self.workerFuncSpinner(
    taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i)

# create a thread that will call whatever `self.workerFuncSpinner` returned,
# with no arguments
t = threading.Thread(target=spinner)

# run whatever workerFuncSpinner returned in background thread
t.start()

rawDescription: Python threading issue: threads blocking each other


code: unique_vals = df1[~df1.Star_ID.isin(df2.Star_ID)].append(df2[~df2.Star_ID.isin(df1.Star_ID)], ignore_index=True)

rawDescription: Selecting Unique Rows between Two DataFrames in Pandas


rawDescription: make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy

description: Make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy


code: np.choose([1,2], x)

rawDescription: How to get values from a 2-d Array with indices

description: Get values from a 2-d Array with indices


code: classes = {'situation': Situation}

rawDescription: python create object from string

description: Python create object from string


rawDescription: Convert a 2d matrix to a 3d one hot matrix numpy


code: pars, pcov = opt.curve_fit(function, x1, y1, p0=[0.1, -10, 0.1])

rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code:
class Test(object):
    def __init__(self, a, b, c):
        self.a, self.b, self.c = a, b, c

    def __repr__(self):
        return 'Test(%s, %s, %s)' % (self.a, self.b, self.c)

    def multiply_attr(self, attrname, scale):
        attr = getattr(self, attrname)
        attr *= scale
        setattr(self, attrname, attr)

t = Test(1, 2, 3)
print(t)

t.multiply_attr('a', 5)
t.multiply_attr('b', 10)
t.multiply_attr('c', 20)
print(t)

rawDescription: Python: No pass by reference.. how to do it then?


rawDescription: pandas dataframe view vs copy, how do I tell?

description: Pandas dataframe view vs copy, how do I tell


code:
import json

data = json.loads(inputstring)
# process the same way as above.

rawDescription: How to remove commas, brackets in python using regular expression?

description: Remove commas, brackets in python using regular expression


code: d = {e['name']: e['value'] for e in items}

rawDescription: Get Value of a key from List of dictionary


code:
title_flag = 0

with open('some_file', 'r') as afile:
    for line in afile:
        thetitle, mustbreak = body(line)
        if thetitle is not Note: title = thetitle
        if mustbreak: break

rawDescription: Is it possible to repeat an iteration of a loop?


code:
from balut.lib.forms.validators import is_unique

class RedirectMixin(object):
    name = db.StringField(max_length=1000, required=True, help_text="Used internally")
    matching_type = db.IntField(
        help_text='`Equals` has higher priority. With concurrent `Start with` rules, longest `Url_from` wins',
        required=True, choices=MATCHING_TYPES)
    add_unmatched_ending = db.BooleanField(
        help_text='Example: Starts with /a/ redirect to /b/. This will make /a/c/ redirect to /b/c/',
        default=False)
    url_from = db.StringField(max_length=1000, required=True, unique_with='matching_type',
                              help_text='Case insensitive')
    url_to = db.StringField(max_length=1000, required=True)
    form_args = dict(url_from={'validators': [is_unique(with_='matching_type', message=None)]})

rawDescription: Flask Admin validate unique_with errors

description: Flask Admin validate unique_with errors


code:
twitter_api.statuses.user_timeline()
# ^- this converts to "api.twitter.com/1/statuses/user_timeline.json"

twitter_api.statuses.user_timeline(user_id="a")
# ^- this converts to "api.twitter.com/1/statuses/user_timeline.json?user_id=a"

twitter_api.statuses.user_timeline(foo)
# ^- this breaks - "foo" is not a key/value pair, and cannot be sent

rawDescription: Get user id from user name for twitter using python


code:
while True:
    s1 = input("Please enter the amount of sides on the dice: ")
    s2 = input("Please enter the number of times you want to repeat: ")
    try:
        sides = int(s1)
        times = int(s2)
        break
    except ValueError:
        pass

rawDescription: How to repeat in python

description: Repeat in python


code: import a_ridiculously_long_module_name as short_name

rawDescription: Can you define aliases for imported modules in Python?

description: Define aliases for imported modules in Python


code:
df = df.reset_index()
df.head()

rawDescription: Where did my dimensions go when I did a groupby in pandas?


rawDescription: Removing Trailing Zeros in Python

description: Removing Trailing Zeros in Python


code:
from nltk import FreqDist
fd = FreqDist(list('aaabbbbbcccccdddddddd'))
last_two = FreqDist(dict(fd.most_common()[-2:]))
last_two.plot()
last_three = FreqDist(dict(fd.most_common()[-3:]))
last_three.plot()

rawDescription: plot the 50 least frequent words with nltk

description: Plot the 50 least frequent words with nltk


code:
l = [("A","field1"),("A","field1"),("B","field1")]

from collections import Counter

print([k+(v,) for k,v in Counter(l).items()])

rawDescription: Grouping tuples using libraries in Python


code:
def gibsSample(pB,pC,pA_B,pD_BC,pE_D,pF_C,label_A,label_B,label_C,label_D,label_E,label_F,T):
    #initial state
    sample=('A=F','B=n','C=F','D=h','E=F','F=F')
    sampleState=[]
    for i in range(T):
        #draw sample A from p(A | B,C,D,E,F)
        sample_A=sampleA(sample,pA_B)

        #draw sample B from p(B | A,C,D,E,F)
        sample_B=sampleB(sample,pB,pA_B,pD_BC)

        #draw sample C from p(C | A,B,D,E,F)
        sample_C=sampleC(sample,pC,pD_BC,pF_C)

        #draw sample D from p(D | A,B,C,E,F)
        sample_D=sampleD(sample,pD_BC,pE_D)

        #draw sample E from p(E | A,B,C,D,F)
        sample_E=sampleE(sample,pE_D)

        #draw sample F from p(F | A,B,C,D,E)
        sample_F=sampleF(sample,pF_C)

        t = (sample_A, sample_B, sample_C, sample_D, sample_E, sample_F)
        sampleState.append(t)
    return sampleState

rawDescription: How to understand the variable scope in python?

description: Understand the variable scope in python


code:
data = []
for tag in tds:
    mfr = tag.find("span")
    if mfr:
        data.append(mfr.text.split(":")[-1].strip())

rawDescription: Exporting Beautiful Soup table scrape results to CSV


rawDescription: Matching parts of two csv files to return certain elements


code: result = [user for user in Users.select() if user.name not in a_list_of_names]

rawDescription: Delete an element from peewee Query select


code:
import fnmatch
import re

s = '/path/eggs/foo/bar'
pattern = "eggs/*"

re.search(fnmatch.translate(pattern), s)
# <_sre.SRE_Match object at 0x10049e988>

rawDescription: .gitignore style fnmatch()

description: .gitignore style fnmatch()


code:
from stat import S_IWUSR # Need to add this import to the ones above

os.chmod(filename, S_IWUSR|S_IREAD) # This makes the file read/write for the owner

rawDescription: Change file to read-only mode in Python

description: Change file to read-only mode in Python


rawDescription: Distribution plot of an array

description: Distribution plot of an array


code:
data_points, num_spikes = 1000000, 10000

data = np.random.rand(data_points)
spiketimes = np.random.randint(data_points, size=(num_spikes))

rawDescription: Most efficient way to extract parts of one array based on another


code: df.groupby('s_id', as_index = False).apply(c_id_overlap)

rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
class WeightedArc(Arc):
    def __new__(cls, arc, weight):
        self = tuple.__new__(cls, arc)
        self.weight = weight
        return self

rawDescription: How do I create a tuple with an attribute using Python?

description: Create a tuple with an attribute using Python


code:
def detect_language_v2(chunks, api_key):
    """
    chunks: either string or sequence of strings

    Return list of corresponding language codes
    """
    if isinstance(chunks, basestring):
        chunks = [chunks]

    url = 'https://www.googleapis.com/language/translate/v2/detect'

    data = urllib.urlencode(dict(
        q=[t.encode('utf-8') if isinstance(t, unicode) else t
           for t in chunks],
        key=api_key), doseq=True)

    # the request length MUST be < 5000
    if len(data) > 5000:
        raise ValueError("request is too long, see "
            "http://code.google.com/apis/language/translate/terms.html")

    #NOTE: use POST to allow more than 2K characters
    request = urllib2.Request(url, data,
        headers={'X-HTTP-Method-Override': 'GET'})
    d = json.load(urllib2.urlopen(request))

    return [sorted(L, key=itemgetter('confidence'))[-1]['language']
            for L in d['data']['detections']]

rawDescription: Python - can I detect unicode string language code?


code:
from django.db.models import When, Case, F, IntegerField

Product.objects.annotate(
     sales_price=Case(
         When(discount__isnull=True, then=F('price')),
         When(discount__isnull=False, then=(F('price') - (F('discount') * F('price')) / 100)),
         output_field=IntegerField(),
     )
)

rawDescription: How to make a conditional query in Django

description: Make a conditional query in Django


code:
if evaluateBet(userInput) == True:
    points = ( points + (wager * 2) )
    wager = 0

rawDescription: How do I make a score counter for my game in python?

description: Make a score counter for my game in python


rawDescription: Copy 2D array to a 3D one - Python / NumPy


code: ('hijacked!', 'y')

rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


rawDescription: Wrestling with Python MySQLdb timedelta

description: Wrestling with Python MySQLdb timedelta


code:
new_things = {}
for thing in things:
    thing_id = thing['id']
    try:
        old_thing = new_things[thing_id]
    except KeyError:
        new_things[thing_id] = thing
    else:
        old_thing['ua'].extend(thing['ua'])
new_things = new_things.values()

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

train_data1 = ["football is the sport", "gravity is the movie", "education is important"]
vectorizer = TfidfVectorizer(stop_words='english')

print("Applying first train data")
X_train = vectorizer.fit_transform(train_data1)
print(vectorizer.get_feature_names())

print("\n\nApplying second train data")
train_data2 = ["cricket", "Transformers is a film", "AIMS is a college"]
X_train = vectorizer.transform(train_data2)
print(vectorizer.get_feature_names())

print("\n\nApplying fit transform onto second train data")
X_train = vectorizer.fit_transform(train_data1 + train_data2)
print(vectorizer.get_feature_names())

rawDescription: Updating the feature names into scikit TFIdfVectorizer


rawDescription: column matrix representation in python

description: Column matrix representation in python


code:
import json

with open('prueba.json', 'r') as f:
    config = json.loads(f.read())

with open('prueba.json', 'w') as f:
    # Here I update window settings as an example
    config['window']['innerHeight'] = 1440
    config['window']['innerWidth'] = 900
    f.write(json.dumps(config))

rawDescription: make a custom json sort order in python

description: Make a custom json sort order in python


code:
class Config(Borg):

    def __init__(self, config_file):
        super(Config, self).__init__()
        # load and parse file, saving settings to `self`

rawDescription: Borg Design Pattern

description: Borg Design Pattern


code:
import matplotlib.pyplot as plt

v= range(25)#f.variables['store_Bio'][0,0:24,0]

plt.plot(v, linestyle='-',linewidth=5.0, c='c')

plt.xticks(range(25),[str(i) for i in range(25)])
plt.yticks(range(0,180,10),[str(i) for i in range(0,180,10)])

plt.xlabel('Hour')
plt.ylabel('Average Biogenic Emissions')
plt.title ('Daily average Biogenic Emissions March 2013')
plt.ylim(0, 180)
plt.xlim(0,23)

plt.show()

rawDescription: can't change matplotlib.pyplot tick marks

description: Can't change matplotlib.pyplot tick marks


code: subprocess.Popen(['bash', '-c', '. foo.sh; go'])

rawDescription: Can a python script execute a function inside a bash script?


code:
r = requests.Session()

# GET request
gr = r.get("http://www.feline.dk")
bsObj = BeautifulSoup(gr.text,"html.parser")
auth_string = bsObj.find("input", {"name": "__RequestVerificationToken"})['value']

# POST request
search_request = "Geography.Geography=Hou&Geography.GeographyLong=Hou%2C+Danmark+(Ferieomr%C3%A5de)&Geography.Id=847fcbc5-0795-4396-9318-01e638f3b0f6&Geography.SuggestionId=&Period.Arrival=&Period.Duration=7&Period.ArrivalCorrection=False&Price.MinPrice=&Price.MaxPrice=&Price.MinDiscountPercentage=&Accommodation.MinPersonNumber=&Accommodation.MinBedrooms=&Accommodation.NumberOfPets=&Accommodation.MaxDistanceWater=&Accommodation.MaxDistanceShopping=&Facilities.SwimmingPool=false&Facilities.Whirlpool=false&Facilities.Sauna=false&Facilities.InternetAccess=false&Facilities.SatelliteCableTV=false&Facilities.FireplaceStove=false&Facilities.Dishwasher=false&Facilities.WashingMachine=false&Facilities.TumblerDryer=false"

gr = r.post(
    url = 'http://www.feline.dk/search/',
    data = search_request,
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
)

print(gr.url)

rawDescription: Using python to scrape ASP.NET site with id in url


code:
import vendor
my_obj = vendor.mymodule.mysubmodule.any_class.AnyClass()

from vendor import mymodule
my_obj = mymodule.mysubmodule.any_class.AnyClass()

...

from vendor.mymodule.mysubmodule import any_class
my_obj = any_class.AnyClass()

rawDescription: How to structure python application

description: Structure python application


rawDescription: Python (to C#) Method Conversion

description: Python (to C#) Method Conversion


rawDescription: Extract indices of a 2D binary array

description: Extract indices of a 2D binary array


code:
class A(object): ...
class B(A): ...

def setUp(self):
    with patch('A', new_callable=Mock) as MockObject:
        self.b = B()
        self.b.__class__.__bases__ = (MockOjbect,)

rawDescription: unittesting: patching an objects __base__

description: Unittesting: patching an objects __base__


code:
def overlap(coors1, coors2, tolerance ):

    # Perform elementwise absolute subtractions between input arrays
    sub_abs_vals = np.abs(coors1[None,:,:] - coors2[:,None,:])

    # Check for ANY equality along 0-th axis & ALL equality along 2-nd axis.
    # Return the corresponding row from first input array.
    return coors1[np.all(np.any(sub_abs_vals<=tolerance,axis=0),axis=1)]

rawDescription: How to find the tolerable overlap between 2 arrays of x,y coordinates in python (numpy)

description: Find the tolerable overlap between 2 arrays of x,y coordinates in python (numpy)


code:
from tornado.options import define,options
define("mysql_host", default="127.0.0.1:3306", help="database host")
define("mysql_database", default="forum", help="database name")
define("mysql_user", default="root", help="database user")
define("mysql_password", default="111111", help="database password")

db = tornado.database.Connection(
    host=options.mysql_host, database=options.mysql_database,
    user=options.mysql_user, password=options.mysql_password)

rawDescription: How do I access my database level functions inside other classes/files in Tornado?

description: Access my database level functions inside other classes/files in Tornado


rawDescription: Correct way of getting time delta value from config file


code:
import time

class ExpiringDict(dict):
    def __init__(self, expiry_secs, *args, **kwargs):
        self.expire = time.time() + expiry_secs
        self.expiry_secs = expiry_secs

        super(ExpiringDict, self).__init__(*args, **kwargs)

    def _reset_expire(self):
        self.expire = time.time() + self.expiry_secs

    def _check_expire(self):
        if time.time() > self.expire:
            self.clear()

    def __setitem__(self, key, value):
        self._reset_expire()
        return super(ExpiringDict, self).__setitem__(key, value)

    def update(self, *args, **kwargs):
        self._reset_expire()
        return super(ExpiringDict, self).update(*args, **kwargs)

    def __getitem__(self, *args, **kwargs):
        self._check_expire()
        return super(ExpiringDict, self).__getitem__(*args, **kwargs)

    def __getattribute__(self, name):
        attr = super(ExpiringDict, self).__getattribute__(name)
        if name not in {"_check_expire", "expire", "clear"}:
            self._check_expire()
        return attr

rawDescription: What method is used when accessing a dict as a whole?


code: node = start_node(Alist)

rawDescription: python passing variables between functions

description: Python passing variables between functions


rawDescription: ipython notebook R cell magic as a python function

description: Ipython notebook R cell magic as a python function


code:
key = cell[0].strip().strip('"').strip("'")
value = cell[1].strip().strip('"').strip("'")
if key in rowData:
    rowData[key] = rowData[key] + ":" + value
else:
    rowData[key] = value

rawDescription: Parsing a semi colon delimited file in python to create a CSV


rawDescription: searching & comparing valuse in csv files with python

description: Searching & comparing valuse in csv files with python


code: [['500xxxxxxxxxxxxxxxx', 'Sample Case 1', 'Sample Account 1', None]]

rawDescription: Nested OrderedDict to nested list with varying levels of nesting


code:
def funcprint(*args):
    for f in args:
        with open(f, 'r') as inp:
            ...

funcprint("C:/file1.txt", "C:/file2.txt")

rawDescription: Python: unknown # of files as function arg


code:
if brush2.get_rect().collidepoint(pygame.mouse.get_pos()):
    screen.blit(brush2, (x -23.5,y-23.5))
    pygame.display.update()

rawDescription: paint application - python

description: Paint application - python


code:
from sympy import latex
tl = map(lambda tc: '$'+latex(tc)+'$',t)
df = DataFrame(tl, index=['Situation 1', 'Situation 2'], columns=['Answer'])
df

rawDescription: How to Render Math Table Properly in IPython Notebook


code:
def subpeptides(peptide):
    l = len(peptide)
    looped = peptide + peptide
    for start in range(0, l):
        for length in range(1, l):
            print(looped[start:start+length])

rawDescription: How to generate subpeptides (special combinations) from a string representing a cyclic peptide?

description: Generate subpeptides (special combinations) from a string representing a cyclic peptide


code:
a, b, c = BitVecs('a b c', 32)
solve(a == b + c, c == b + 5)

rawDescription: Z3: can Z3 tells me if arithmetic operations return concrete value?


code:
if db_field.name == "company":
    kwargs['queryset'] = request.user.company_set.all()

rawDescription: django admin - populate field with callable

description: Django admin - populate field with callable


code:
d = {'AA': [('No Av', 'Ave', 3.35, 'Max', 0.9, 'Min', -6.8),
            ('analist disp:', -5.0), u' AA: Jan 11, 2016\t\t\t']}

def flat(xs):
    for x in xs:
        if isinstance(x, (list, tuple)):
            for y in flat(x):
                yield y
        else:
            yield x

# If there's only one item in the dictionary
next([key] + list(flat(value)) for key, value in d.items())
# => ['AA', 'No Av', 'Ave', 3.35, 'Max', 0.9, 'Min', -6.8, 'analist disp:',
#     -5.0, u' AA: Jan 11, 2016\t\t\t']

rawDescription: How to flatten a "complex" dictionary into a list

description: Flatten a "complex" dictionary into a list


rawDescription: Pandas Dataframes- Adding Fields Based on Column Titles


code:
sp_info = soup.select('.left-room-info')[i].text.strip().split('\r')
if len(sp_info) > 1:
    sp_info = [ info.strip() for info in sp_info ]

rawDescription: Python - Crawl Multiple Classes within a Page Using BeautifulSoup


code:
def category(vals):
    return 1 if all(vals) else 2 if any(vals) else 0

rawDescription: Efficient way of counting True and False


code:
from collections import defaultdict

data = defaultdict(list)

data[2].append(3)
data[5].append(42)

rawDescription: Building a list inside a list in python

description: Building a list inside a list in python


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

# mock-up of data being used
x = 6
y = 7
table = np.zeros((x, y))

# plotting
fig = plt.figure(1)
plt.title('Example Plot')

plt.gca().xaxis.grid(True, color='darkgrey', linestyle='-')
plt.gca().yaxis.grid(True, color='darkgrey', linestyle='-')
plt.show()

rawDescription: python matplotlib gridspec, unwanted arbitrary axis labels

description: Python matplotlib gridspec, unwanted arbitrary axis labels


rawDescription: Python sharing data across all modules in django app


rawDescription: python: make the elements of a list within a certain range

description: Python: make the elements of a list within a certain range


code:
from fabric.api import *
from fabric.contrib import project

env.roledefs['static'] = ['user@123.123.123.132',]

# Where the static files get collected locally. Your STATIC_ROOT setting.
env.local_static_root = '/tmp/static'

# Where the static files should go remotely
env.remote_static_root = '/home/static-files'

@roles('static')
def deploy_static():
    local('./manage.py collectstatic')
    project.rsync_project(
        remote_dir = env.remote_static_root,
        local_dir = env.local_static_root,
        delete = True
    )

rawDescription: How to deploy static files to a separated machine

description: Deploy static files to a separated machine


code:
theta = np.linspace(0,2*pi, 360)   # 360 equally spaced values between 0 and 2*pi
r = (a*(1-e**2))/(1+e*cos(theta))

rawDescription: Plotting elliptical orbits

description: Plotting elliptical orbits


code:
repr({u'IP': u'aaa'})
json.dumps({u'IP': u'aaa'})

rawDescription: How do I to translate this json format into correct format that can be used pandas read_json()

description: To translate this json format into correct format that can be used pandas read_json()


code:
pyplot.axis([xmin, xmax, ymin, ymax])
pyplot.gca().set_aspect('equal', adjustable='box')

rawDescription: Define the limits of my axes, but with an equal scale in both directions with matplotlib


code: new_labels[labels == labels[i, j]] = new_label_value

rawDescription: Set superpixel color

description: Set superpixel color


code:
cursor.execute(query)
numrows = int(cursor.rowcount)
for x in range(0,numrows):
    row = cursor.fetchone()

rawDescription: offset/limit programmatically with python mysqldb

description: Offset/limit programmatically with python mysqldb


code:
getattr(obj, method_name)()
operator.methodcaller(method_name)(obj)  # needs import operator
eval("obj." + method_name + "()")

rawDescription: Choosing which instance method to use

description: Choosing which instance method to use


code:
class Foo(object):
    def __init__(self, name):
        self.name = name

    def __rmul__(self, x):
        return Foo(str(x) + self.name)

    def __add__(self, x):
        return Foo(str(self.name) + ' + ' + str(x.name))

    def __str__(self):
        return self.name

rawDescription: Any way to have undeclared variables for algebraic expressions?


code:
def levelVarsGetter(l):
    return {'URLRegEx': baseDict['L%dRegex' % l],
            'titleRegEx': baseDict['L%dTitleRegex' % l],
            'buildPortion': baseDict['L%dbuildPortion' % l],
            'levelParser': 'level_%d' % l}

rawDescription: Making a dynamic variable set

description: Making a dynamic variable set


code:
if __name__ == '__main__':
    save_out = sys.stdout  # save the original stdout so you can put it back later
    out_file = open(r'C:\Temp\out.txt', 'w')
    sys.stdout = out_file

    save_err = sys.stderr
    err_file = open(r'C:\Temp\err.txt', 'w')
    sys.stderr = err_file

    main()  #call your main function

    sys.stdout = save_out  # set stdout back to it's original object
    sys.stderr = save_err

    out_file.close()
    err_file.close()

rawDescription: How do you make Python wait so that you can read the output?

description: Make Python wait so that you can read the output


rawDescription: A python non finished function

description: A python non finished function


rawDescription: Is it possible to obtain the path of the script using argparse?


code:
def fruitfilter(fruits):
    sortedfruits = sorted(fruits, key=(itemgetter(0), -itemgetter(2)))
    for fruit, group in groupby(sortedfruits, key=itemgetter(0)):
        yield next(group)

fruits = list(fruitfilter(fruits))

rawDescription: Python Filter List Items Relative to Each Other


code:
CELERY_ROUTES = {
    'mypackage.myclass.runworker'      : {'queue':'myqueue'},
}

rawDescription: Interoperating with Django/Celery From Java


code:
MyList = ['a', 'b', 'c', 'd', 'e']
all(letter in MyList for letter in 'bad')
all(letter in MyList for letter in 'test')

rawDescription: convert list to string?

description: Convert list to string


code:
my_var = (somethinglikethis
          .where(we=do_things)
          .where(we=domore)
          .where(we=everdomore))

rawDescription: Correct Style for Python Line breaks

description: Correct Style for Python Line breaks


code:
import unittest

class Test(unittest.TestCase):
    @params_from_file('file.txt')  # {"name":"url_1", "url":"http://check.com", "expected": "23"}
    def test_url(self, name, url, expected):
        self.assertEqual(name, 'url_1')
        self.assertEqual(url, 'http://check.com')
        self.assertEqual(expected, '23')
        # print(name, url, expected)

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

rawDescription: How to dynamically create parameterized test from the file (json or yaml) in python

description: Dynamically create parameterized test from the file (json or yaml) in python


code:
s1 = 'provider:sipoutilp1.ym.ms'
s2 = 'provider:sipoutqtm.ym.ms'
RE_PROVIDER = re.compile(r'(?P<provider>(?<=sipout)(ilp|qtm))')
RE_PROVIDER.search(s1).groupdict()
RE_PROVIDER.search(s2).groupdict()

rawDescription: How to print substring using RegEx in Python?

description: Print substring using RegEx in Python


code:
from collections import defaultdict
dd = defaultdict(list)
for el in a:
    dd[el[0]].append(el[-1])

# defaultdict(<type 'list'>, {100: [0, 3, 1], 101: [2, 5, 2], 102: [1, 2, 0], 103: [0, 4, 2]})

rawDescription: Using the last element from each list in Python


rawDescription: What's the best style, class method or global function?


code:
max(ld, key=lambda d: d['size'])
max(enumerate(ld), key=lambda item: item[1]['size'])

rawDescription: Python list of dicts, get max value index


code: ' '.join([str(x) for x in np.hstack((a.T.real, a.T.imag)).flat])

rawDescription: Pythonic way to print a multidimensional complex numpy array to a string


code:
import random
list=["A","B","C"]
listitem = random.randint(0,len(list))
list[listitem]
listitem = random.randint(0,len(list))
list[listitem]

rawDescription: How to print a random value name from a list?(python)

description: Print a random value name from a list?(python)


code: find.Replacement.Font.Color = 255       # wdColorRed

rawDescription: How can I open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python?

description: Open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python


code:
for field in form:
    # these are available to you:
    field.name
    field.description
    field.label.text
    field.data

rawDescription: Iterating over submitted form fields in Flask?


code:
def newlist():
    with open('words.txt') as fin:
        return set(''.join(sorted(word.strip())) for word in fin)

newlist()

rawDescription: Think Python Ch12 Ex 4: Code seems correct but hangs when compiled


code:
from django import forms

class ContactForm1(forms.Form):
    subject = forms.CharField(max_length=100)
    sender = forms.EmailField()

class ContactForm2(forms.Form):
    message = forms.CharField(widget=forms.Textarea)

rawDescription: can you use Form Wizard for Model Forms in django?

description: Use Form Wizard for Model Forms in django


code:
remaining = locallist[:]
pick = 'Ann-Marie, the butcher (1)'
remaining.remove('Ann-Marie, the butcher (1)')
print(remaining)

pick = 1
remaining.pop(1)
print(remaining )

['Bella, the flourist (2)', 'Caitlyn, the painter(3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
['Bella, the flourist (2)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']

rawDescription: Removing a item from a list and updating it python


rawDescription: PEP 3130: Difference between switch case and if statement code blocks


code:
attributes = ['translateX', 'translateY', 'translateZ',
              'rotateX', 'rotateY', 'rotateZ']
for a in attributes:
    getattr(object, a).set(1.5)

rawDescription: Set attribute without string concatination


code: new_dict = {key: list(values) for key, values in new_dict.items()}

rawDescription: Get a string list from a word

description: Get a string list from a word


code:
@app.route('post/<variable>', methods=['GET'])
def daily_post(variable):
    #do your code here
    return render_template("template.html",para1=meter1, para2=meter2)

rawDescription: How to generate dynamic urls in flask?

description: Generate dynamic urls in flask


code:
from collections import defaultdict

earnings = defaultdict(float)  # float has a default value of 0.

rawDescription: Most concise way to define multiple variables


code:
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required

@login_required
def file(request, filename):
    file = get_object_or_404(File, user=request.user, filename=filename)
    return HttpResponse(open(file.filename, 'rb').read())

rawDescription: View function is not being called in Django


code: nsolve(C_b - 10.4866, C0, 1) # for numerical solution

rawDescription: Sympy library solve to an unknown variable


rawDescription: Interleaving two numpy index arrays, one item from each array


code:
def minus_score(line):
    return -int(line.split()[0])

rawDescription: Write to file python - Linebreak issue (\n)


code:
import numpy as np

x = np.random.randn(20, 3)
x_new = x[np.sum(x, axis=1) > .5]

rawDescription: Filter rows of a numpy array?

description: Filter rows of a numpy array


code: List1 = [s for s in List1 if not s.isdigit()]

rawDescription: Hi I was wondering if there was a data type in Python that only allows letters to be inputed and not numbers


code:
import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))
plt.setp(axes.flat, xlabel='X-label', ylabel='Y-label')

pad = 5 # in points

for ax, col in zip(axes[0], cols):
    ax.annotate(col, xy=(0.5, 1), xytext=(0, pad),
                xycoords='axes fraction', textcoords='offset points',
                size='large', ha='center', va='baseline')

for ax, row in zip(axes[:,0], rows):
    ax.annotate(col, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
                xycoords=ax.yaxis.label, textcoords='offset points',
                size='large', ha='right', va='center')

fig.tight_layout()
# tight_layout doesn't take these labels into account. We'll need
# to make some room. These numbers are are manually tweaked.
# You could automatically calculate them, but it's a pain.
fig.subplots_adjust(left=0.15, top=0.95)

plt.show()

rawDescription: Row and column headers in matplotlib's subplots


code: import re

rawDescription: Read a CSV file and put double quotes around data items


code: {{ my_dict|my_filter|safe }}

rawDescription: Create a table, line-by-line of a dictionary using json.dump or pprint in django template [python]


code:
pivoted = pivoted.reset_index()
pivoted

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


code:
def do_stuff(li, s_val, s_key):
    key = li[0]
    for x in li[1:]:
        if x in s_val:
            yield key,x
        elif x in s_key:
            key = x

rawDescription: How do you merge two lists into a list of sublists where each sublist is paired based on the sequence of the items in the list?

description: Merge two lists into a list of sublists where each sublist is paired based on the sequence of the items in the list


code:
def sd(st):
    return sum(int(d) for d in st)

number = input('Give me a number: ')

trial = number
while True:
    n = abs(sd(trial[::2]) - sd(trial[1::2]))
    if n < 11: break
    trial = str(n)

if n > 0:
    ...
else:
    ...

rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
def vote_op(angle, belong, THRES_THETA, lines_lengths_vstacked, max_line_length):
    intermediate = (0.3 * (1-(angle[belong]/THRES_THETA)) + 0.7 * (lines_lengths_vstacked[belong]/max_line_length))
    b_ind = np.hstack([0, np.cumsum(np.sum(belong, axis=1))])
    votes = np.add.reduceat(intermediate, b_ind[:-1])
    return votes

rawDescription: numpy 2d boolean array indexing with reduce along one axis

description: Numpy 2d boolean array indexing with reduce along one axis


code:
class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
    def commit(self):
        pass

jason = User('jason', 'jason@email.com')
jack = User('jack', 'jack@yahoo.com')

rawDescription: Clear all class variables between instances


code:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector

class MySpider(scrapy.Spider):

    symbols = ["SCMP"]
    name =  "yahoo"
    allowed_domains = ["yahoo.com"]

    def stock_list(symbols):
        start_urls = []
        for symb in symbols:
            start_urls.append("http://finance.yahoo.com/q/is?s={}&annual".format(symb))
        return start_urls
    start_urls = stock_list(symbols)

    def parse(self, response):
        revenue = Selector(response=response).xpath('//td[@align="right"]').extract()
        print(revenue)

rawDescription: Python: Scrapy start_urls list able to handle .format()?


code:
def solve(d, *keys):
    indexes = [i for i, x in enumerate(zip(*(d[k] for k in keys)))
                                                                if len(set(x)) != 1]
    return {k:[v[x] for x in indexes] for k, v in d.items()}

rawDescription: Removing each element at the value in each key


code:
from osgeo import gdalnumeric

image_array = gdalnumeric.LoadFile(raster)

rawDescription: Read ERDAS Imagine Images into Individual Variables as Matrices


code: int(s.encode('hex'), 16)

rawDescription: How to convert a string to its Base-10 representation?

description: Convert a string to its Base-10 representation


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

allLists = [a, b, c]

allSets = list(map(set, allLists))
allTokens = set.union(*allSets)
sortedTokens = sorted(allTokens)

rawDescription: Compare N lists and insert/append blank entries where discrepancies exist


code: isinstance(o, (str, unicode))

rawDescription: What's the canonical way to check for type in python?


rawDescription: Efficient way to multiply/add/devide each element of a list with each element of another list in Python


code:
df['closest'] = idx.index.map(lambda x: df.ix[x][idx.ix[x]])
df

rawDescription: indexing a pandas DataFrame

description: Indexing a pandas DataFrame


code: find("string", source1, source2)

rawDescription: Python: "Multiple" multiple arguments in function


code:
from collections import defaultdict
new_d = defaultdict(tuple)
for k,v in d.items():
    new_d[v] += (k,)

new_d

rawDescription: Fliping dictionary key value Python

description: Fliping dictionary key value Python


code:
def remLines(infilepath, outfilepath, delim, above, below):
    infile = open(infilepath)
    outfile = open(outfilepath, 'w')
    buff = []
    line = infile.readline()
    while line:
        if line.strip() == delim:
             buff = []
             for _ in range(below): # need to error check here, if you're not certain that your input file is correctly formatted
                 infile.readline()
        else:
            if len(buff) == above:
                outfile.write(buff[0])
                buff = buff[1:]
            buff.append(line)
        line = infile.readline()
    outfile.write(''.join(buff))

if __name__ == "__main__":
    remLines('path/to/input', 'path/to/output', "Position fix ind: 0", 6,3)

rawDescription: Remove amount of lines above and below a line containing a string


rawDescription: How to reduce a collection of ranges to a minimal set of ranges

description: Reduce a collection of ranges to a minimal set of ranges


code:
@patch("Parent.Imported")  # <---
def test_init_002(self, mock_parent_init):
    a = Derived("I am Derived")
    mock_parent_init.assert_called_with("I am Derived")
    self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

rawDescription: Mock parent class __init__ method

description: Mock parent class __init__ method


code:
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.cnbc.com/id/101790001?__source=yahoo%7Cfinance%7Cheadline%7Cheadline%7Cstory&par=yahoo&doc=101790001%7CThink%20college%20is%20expensiv#")
soup = BeautifulSoup(r.content)
text =[''.join(s.findAll(text=True)) for s in soup.findAll("div", {"class":"group"})]
print (text)
['\n  Congratulations, graduates, on your diploma. Now what about that $29,000 student loan debt? \n  More than 70 percent of graduates will carry student debt into the real world, according to the Institute for College Access and Success. And the average debt is just shy of $30,000.  \n  But the news will get worse next week when interest rates on student loans are set to rise again.   \n  Though federal student loan rates are fixed for the life of the loan, these rates reset for new borrowers every July 1, thanks to legislation that ties the rates to the performance of the financial markets.  \n  The interest rate on federal Stafford loans will go from its current fixed rate of just under 4 percent to 4.66 percent for loans that are distributed between July 1 and June 30, 2015.  \n Read MoreStudent loan problem an easy fix: Sen. Warren \n  For graduate students, the rate on Stafford loans will rise from just over 5 percent  to 6.21 percent.  \n  Direct PLUS Loans for graduates and parents are still the most expensive, with rates rising to 7.21 percent.\n', '\n  The increase in monthly federal student loan payments can add up quickly, but shouldn\'t be too burdensome for most students. For every $10,000 in loans, new borrowers will pay about $4 more a month based on a 10-year repayment period.   \n Read MoreWhy millennial women don\'t save for retirement \n  Still, experts warn that this is only just the beginning.  \n  "Federal student loan rates will continue to increase in the next few years and will likely hit the maximum rate caps which are as high as 10.5 percent for some loans," said Mark Kantrowitz, senior vice president and publisher of Edvisors.com.  \n  For sophomore student Samantha Cook, the decision to go to George Washington University was a big one financially. She says she had doubts about it.  \n  "My parents wanted to assure me that no matter what I picked, we\'d find a way to make it work," Cook said. Like most families, Cook and her parents are making it work by combining their household savings, scholarships and grants—and student loans.    \n Read MoreCramer: Offset high cost of higher education \n  Despite rising tuition and borrowing costs, the Cook family decided against Samantha transferring to an in-state university.  \n  Despite the debt load she is taking on, she said, "the value of a GW degree for me at least would be more valuable when looking for jobs later on." \n —By CNBC\'s Sharon Epperson \n']

rawDescription: Cleaning text string after getting body text using Beautifulsoup


code:
tree.rooted = True
Phylo.draw(tree, branch_labels=lambda c: c.branch_length)

rawDescription: Create a Dendogram from Genome

description: Create a Dendogram from Genome


code:
['Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here',
 'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here',
 'Layer:outline\nLine 1 text goes here\nLine 2 text goes here']

rawDescription: How can I split this string in Python?

description: Split this string in Python


code:
maxvi = np.argsort(a,axis=1)
ii = np.argsort(maxvi[:,-1])

pcolor(a[ii,:])

rawDescription: plotting a 2D matrix in python, code and most useful visualization

description: Plotting a 2D matrix in python, code and most useful visualization


code: import json

rawDescription: passing unicode strings from django to javascript

description: Passing unicode strings from django to javascript


code:
class SingletonA:
    _instance = None
    def __init__(self):

        # some state
        print("Creating dummy state in SingletonA")

    def _init(self):

        # some state
        print("Creating state in SingletonA")
        self.X = 1.
        self.Y = 2.
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(SingletonA, cls).__new__(
                cls, *args, **kwargs)
            cls._instance._init()
        return cls._instance

rawDescription: singleton design pattern in Python with state

description: Singleton design pattern in Python with state


rawDescription: Calculating the gap between pairs of twin primes in python


code:
@method_decorator
def view_method(request, param, more_param):
    new_content = request.new_content

rawDescription: What information do Python/Django decorators have access to?


rawDescription: Python: How to remove quotes around numbers from string


code: pd.concat([df1, df2], axis=1, keys=['precedingWord', 'comp'])

rawDescription: Turn dataframe into frequency list with two column variables in Python


code:
def three_diag_mat(m,h):
    # Initialize output array
    out = np.zeros((m,3+m-2))

    # Setup the triplets in each row as [1,-2,1]
    out[:,:3] = 1
    out[:,1] = -2

    # Reset the ending "1" of the second last row as zero.
    out[m-2,2] = 0

    # Slice upto m**2 elements in a flattened version.
    # Then, scale down the sliced output by h**2 for the final output.
    return (out.ravel()[:m**2].reshape(m,m))/(h**2)

rawDescription: Numerical Differenciation as Matrix-Vector Product


code:
import subprocess
import os

path_to_pdf = os.path.abspath('C:\test_file.pdf')
# I am testing this on my Windows Install machine
path_to_acrobat = os.path.abspath('C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe')

# this will open your document on page 12
process = subprocess.Popen([path_to_acrobat, '/A', 'page=12', path_to_pdf], shell=False, stdout=subprocess.PIPE)
process.wait()

rawDescription: Python - open pdf file to specific page/section


code:
obj= eval(myString)
obj['session_key']

rawDescription: which is the best way to get the value of 'session_key','uid','expires'

description: Which is the best way to get the value of 'session_key','uid','expires'


code:
from time import sleep

def main():
    timeout_after_four_seconds = timeout(4)
    # create copies of a function that have a timeout
    a = timeout_after_four_seconds(do_something)
    b = timeout_after_four_seconds(do_something)
    c = timeout_after_four_seconds(do_something)
    # execute the functions in separate processes
    a('Hello', 1)
    b('World', 5)
    c('Jacob', 3)
    # poll the functions to find out what they returned
    results = [a, b, c]
    polling = set(results)
    while polling:
        for process, name in zip(results, 'abc'):
            if process in polling:
                ready = process.ready
                if ready is True:       # if the function returned
                    print(name, 'returned', process.value)
                    polling.remove(process)
                elif ready is None:     # if the function took too long
                    print(name, 'reached timeout')
                    polling.remove(process)
                else:                   # if the function is running
                    assert ready is False, 'ready must be True, False, or None'
        sleep(0.1)
    print('Done.')

def do_something(data, work):
    sleep(work)
    print(data)
    return work

if __name__ == '__main__':
    main()

rawDescription: Start python Process with output and timeout


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

description: Compile text as a function using AST


code:
s = '[DataMember(Name = "version", EmitDefaultValue = false, Order = 5)]'

print(s.split("Name =")[1].split(",")[0].strip()[1:-1])
version

rawDescription: How to split string into dictionary and return a specific dictionary value?

description: Split string into dictionary and return a specific dictionary value


code: struct.unpack("Q", struct.pack("d", python_double) )[0]

rawDescription: Float to Real48

description: Float to Real48


code: L = [x + [0] for x in L]

rawDescription: How can I add an additional row and column to an array?

description: Add an additional row and column to an array


code:
lines = list(chain.from_iterable(open(f, 'rU') for f in glob('./files/*.??')))
lines.sort()

with open('listTogether.txt', 'w') as out:
    out.writelines(lines)

rawDescription: Merge all .txt files into one text file and alphabetise that text file


code: "file1.txt" "file2.txt"

rawDescription: Pycharm and sys.argv arguments

description: Pycharm and sys.argv arguments


code:
libc_name = ctypes.util.find_library("c")
libc = ctypes.CDLL(libc_name)

libc.memcmp.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t)

len(a) == len(b) and libc.memcmp(a, b, len(a)) == 0

rawDescription: compare ctypes arrays without additional memory

description: Compare ctypes arrays without additional memory


code: data = np.arange(6*3).reshape(6,3); data

rawDescription: Python matplotlib animation randomly jumping to initial position


code:
#!/usr/local/bin/python3.3

from itertools import chain
from random import randint

def leaf(t):
    return isinstance(t, str)

def random(n):
    def extend(t):
        if leaf(t):
            return (t+'l', t+'r')
        else:
            l, r = t
            if randint(0, 1): return (l, extend(r))
            else: return (extend(l), r)
    t = ''
    for _ in range(n-1): t = extend(t)
    return t

def format(t):
    def pad(prefix, spaces, previous):
        return prefix + (' ' * spaces) + previous
    def merge(l, r):
        l_above, l_below, l_lines = l
        r_above, r_below, r_lines = r
        gap = r_below + l_above
        gap_above = l_above
        gap_below = gap - gap_above
        def lines():
            for (i, line) in enumerate(chain(r_lines, l_lines)):
                if i < r_above:
                    yield ' ' + line
                elif i - r_above < gap_above:
                    dash = '_' if i - r_above == gap_above - 1 else ' '
                    if i < r_above + r_below:
                        yield pad(dash + '/', 2 * (i - r_above), line)
                    else:
                        yield pad(dash + '/', 2 * gap_below - 1, line)
                elif i - r_above - gap_above < gap_below:
                    if i < r_above + r_below:
                        yield pad(' \\', 2 * gap_above - 1, line)
                    else:
                        spaces = 2 * (r_above + gap_above + gap_below - i - 1)
                        yield pad(' \\', spaces, line)
                else:
                    yield ' ' + line
        return (r_above + gap_above, gap_below + l_below, lines())
    def descend(left, t):
        if leaf(t):
            if left:
                return (1, 0, [t])
            else:
                return (0, 1, [t])
        else:
            l, r = t
            return merge(descend(True, l), descend(False, r))
    def flatten(t):
        above, below, lines = t
        for (i, line) in enumerate(lines):
            if i < above: yield (' ' * (above - i - 1)) + line
            else: yield (' ' * (i - above)) + line
    return '\n'.join(flatten(descend(True, t)))

if __name__ == '__main__':
    for n in range(1,20,3):
        tree = random(n)
        print(format(tree))

rawDescription: print a binary tree on its side

description: Print a binary tree on its side


code:
@a.setter
def a(self, value):
    print ("called a setter")
    self.a = value

rawDescription: infinite recursion in python3.3 setter

description: Infinite recursion in python3.3 setter


code:
{
    'address': {
        'city': 'Toronto',
        'street': 'Baddessa'
    },
    'name': 'Shalom'
}

rawDescription: Store path to dictionary value for setting value


code:
reg_t = np.arange(0, 99)
reg_lon = f_lon(reg_t)
reg_lat = f_lat(reg_t)

rawDescription: Resample time-series of position evenly in time


code:
from collections import OrderedDict
...
testValues = OrderedDict(zip(testValues, testValues)) # from your example

rawDescription: Sorting the values within a dropdown widget in ipython notebook


code:
class Test(object):
    pass

@classmethod
def classfunc(cls, attr):
    print(cls, attr)

Test.cf = classfunc

rawDescription: How to add classmethod to a python class?

description: Add classmethod to a python class


code: integers = [2] + [n for n in range(3, limit+1) if n % 2]

rawDescription: Python code structure & convention - Creating a elements for a list with a loop


code:
n = 10
x = np.random.random(n)
y = np.random.random(n)
np.polyfit(x, y, 1)[0]
(n*(x*y).sum() - x.sum()*y.sum()) / (n*(x*x).sum() - x.sum()*x.sum())

rawDescription: Fully vectorise numpy polyfit

description: Fully vectorise numpy polyfit


code:
from scipy.interpolate import interp1d
from scipy import arange, array, exp

def extrap1d(interpolator):
    xs = interpolator.x
    ys = interpolator.y

    def pointwise(x):
        if x < xs[0]:
            return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
        elif x > xs[-1]:
            return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
        else:
            return interpolator(x)

    def ufunclike(xs):
        return array(map(pointwise, array(xs)))

    return ufunclike

rawDescription: How to make scipy.interpolate give an extrapolated result beyond the input range?

description: Make scipy.interpolate give an extrapolated result beyond the input range


code:
from itertools import starmap
starmap(f, d.iteritems())

rawDescription: Functional conversion from dictionary to list


code:
# this returns the columns as a list
columns = df.columns.tolist()
# removes the last column, the newest one you added
tofirst_column = columns.pop(-1)
# just move it to the start
new_columns = [tofirst_column] + columns

# then you can the rest
df2 = df[new_columns]

rawDescription: Python: Printing dataframe to csv

description: Python: Printing dataframe to csv


code:
a = ["pera", "uva", "maca", "saladamista"]
b = a[:]
b.reverse()

rawDescription: assign the result of an list operation to var

description: Assign the result of an list operation to var


code:
for thing in list_of_stuff:
    x = __import__('inner-script')
    x.className(thing, counter)

rawDescription: Run python from python without Popen or os.system


code: data_tupled_list = [(a,b+c) for a,b,c in zip(*data_list)]

rawDescription: How to concatenate two items from different lists using python?

description: Concatenate two items from different lists using python


rawDescription: Using prepared data for Sci-kit classification


rawDescription: Sampling a datetime from lines for days and columns for hours


code: result_np = np.frombuffer(result, dtypye=ctypes.c_uint16)

rawDescription: How to use Python and OpenCV with multiprocessing?

description: Use Python and OpenCV with multiprocessing


code:
from itertools import product

def all_versions_of_word(word, alt_chars, skip_orig=True):
    chars = [ch + alt_chars.get(ch, "") for ch in word]
    combos = product(*chars)
    if skip_orig and word: next(combos)  # drop the first item
    return ("".join(c) for c in combos)

def transform_passwords(passwords, alt_chars={"a":"@", "s":"$"}):
    for word in passwords:
        yield from all_versions_of_word(word, alt_chars)

rawDescription: Append to Python list all possible transformations for each list item


code:
m,n,r = a.shape
offset = n*r*np.arange(m)[:,None] + r*np.arange(n)
np.put(a,indices + offset,-1)

rawDescription: Index multiple dimensions of a multi-dimensional array with another - NumPy/ Python


code:
class AddressSegment(AutoEnum):
    misc = "not currently tracked"
    ordinal = "N S E W NE NW SE SW"
    secondary = "apt bldg floor etc"
    street = "st ave blvd etc"

rawDescription: How do I put docstrings on Enums?

description: Put docstrings on Enums


code: sorted(myList, key=val_dict.get)

rawDescription: Sort Python list by dict key,value

description: Sort Python list by dict key,value


rawDescription: creating elevation/height field gdal numpy python

description: Creating elevation/height field gdal numpy python


code:
def map2(f, seq):
    it = imap(f, seq)
    try:
        len(seq)
    except:
        return it
    else:
        return type(seq)(it)

rawDescription: `map`-like function preserving sequence-type


code:
import re

pattern = re.compile(r'''(?<![^\t\n])\W*b(["'])(.*?)\1\W*?(?![^\t\n])''')
with open('outfile', 'w') as outfile:
    for line in open('infile'):
        outfile.write(pattern.sub(r'\2', line))

rawDescription: Regex + Python to remove specific trailing and ending characters from value in tab delimited file


rawDescription: How to directly set RGB/RGBA colors in mayavi

description: Directly set RGB/RGBA colors in mayavi


code: d.groupby('Name').Name.apply(lambda n: n + np.concatenate(([''], (np.arange(len(n))+1).astype(str)[1:])))

rawDescription: How to modify duplicated rows in Python pandas

description: Modify duplicated rows in Python pandas


rawDescription: How to apply numpy.linalg.norm to each row of a matrix?

description: Apply numpy.linalg.norm to each row of a matrix


rawDescription: How does pandas calculate skew

description: How does pandas calculate skew


code:
ListA = ['stop', 'kill']
ListB = ['stoppable', 'killable', 'stopkill']
sum(a.lower() in b.lower() for a in ListA for b in ListB)
len(set(b for a in ListA for b in ListB if a.lower() in b.lower()))

rawDescription: Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring


code:
index_map = {v: i for i, v in enumerate(a_list)}
sorted(a.items(), key=lambda pair: index_map[pair[0]])

rawDescription: How to sort a dictionary based on a list in python

description: Sort a dictionary based on a list in python


code:
ent1but = Tkinter.Button(window, text="Show ent1", command=getent1)
ent1but.pack()

rawDescription: How to save entry field values to disk in Tkinter?

description: Save entry field values to disk in Tkinter


code:
df = pd.DataFrame(np.random.random((4,4)), columns=["a", "ab", "aba", "b"])
both_sides(df, "a")
pd.DataFrame.both_sides = both_sides
df.both_sides("a")

rawDescription: Convert a user function to be a dataframe method (or equivalent)


code:
from lxml import etree
root = etree.Element('пример')
print(etree.tostring(root))
print(etree.tounicode(root))

rawDescription: What is right way to use cyrillic in python lxml library


code:
teams = {}
teams_and_scores = zip(List_team,List_score) #this will pair each team with their score

for team, score in teams_and_scores:
    if team in teams:
        teams[team] += score #add score if team is already in dictionary
    else:
        teams[team] = score #add team to dictionary with their score

rawDescription: Sum values from a list, selected by another list


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

naive = datetime(2015, 2, 1)
pacific = pytz.timezone('America/Los_Angeles')
aware = pacific.localize(naive, is_dst=None)

print(is_summer_time(aware))

rawDescription: How to determine if a timezone specific date in the past is daylight saving or not in python?

description: Determine if a timezone specific date in the past is daylight saving or not in python


code:
import struct
seqno = 42
ip = 0xc6fcce10
port = 80
usrname = 'Martijn Pieters'
struct.pack('!2IH50s', seqno, ip, port, usrname)

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


code:
import matplotlib.pyplot as plt

plt.ylabel("Determinant Squared")
plt.xlabel("Iterations")
plt.plot(losses)

rawDescription: matrix determinant differentiation in tensorflow

description: Matrix determinant differentiation in tensorflow


code:
sample = '''\

    SOME_TEXT

'''
soup = BeautifulSoup(sample, 'html.parser')
soup.div
soup = BeautifulSoup(sample, 'lxml')
soup.div
soup = BeautifulSoup(sample, 'html.parser')
soup.div

rawDescription: How to extract an element's content in HTML?

description: Extract an element's content in HTML


rawDescription: Why does numpy indexing work differently in higher dimensions?


code:
class _Tile(object):
    def __init__(self, x, y):
        """A naive implementation of Tile that doesn't care
        what its side length is and doesn't have any properties
        to hide its attributes"""
        self.x = x
        self.y = y
    @classmethod
    def tiles_to_pixels(cls, tile):
        return cls(tile._x * tile.side_length, tile._y * tile.side_length)
    @classmethod
    def tiles_to_tiles(cls, tile):
        return cls(tile._x, tile._y)

class Tile(object):
    def __init__(self, x, y, side_length):
        """A tile object in a map"""
        self._x = x # x-coord in tiles
        self._y = y # y-coord in tiles
        self.side_length = side_length # pixels per tile
    @property
    def in_pixels(self):
        """self.in_pixels returns an object whose .x and .y
        correspond to the x and y position IN PIXELS of the
        top-left corner of the tile."""
        _tile = _Tile.tiles_to_pixels(self)
        return _tile
    @property
    def in_tiles(self):
        """self.in_tiles returns an object whose .x and .y
        correspond to the x and y position IN TILES of the
        top-left corner of the tile."""
        _tile = _Tile.tiles_to_tiles(self)
        return _tile
    def change_side_length(self, new_length):
        """Use to change the side length. This can break
        your whole map since it's naive, so be careful."""
        self.side_length = new_length

my_tile = Tile(0,0,32) # 32 pixel tile starting at (0,0)
my_tile.x # NameError, since it's called my_tile._x
my_tile.in_tiles.x # 0
my_tile.in_pixels.y # 0
other_tile = Tile(4,7,32) # 32 pixel tile starting at (4,7)
other_tile.y # NameError, see above
other_tile.in_tiles.y # 7
other_tile.in_pixels.x # 128

rawDescription: Property set correctly inside an object but not accessible outside


code:
image = gkt.Image()
image.set_from_pixbuf(pixbuf)

rawDescription: Scale an image in GTK

description: Scale an image in GTK


code: print (" ".join(random.choice(thesaurus[x]) if x in thesaurus else x for x in part2))

rawDescription: Print one word from a list within a dictionary (python)


rawDescription: Transpose and copy column data to each row


code: isinstance(a, type_to_test_for)

rawDescription: How to get Qt widget type

description: Get Qt widget type


code:
import pydoc
pydoc

rawDescription: Displaying python documentation of all methods and attributes with a certain word in a module


rawDescription: Numba : cell vars are not supported

description: Numba : cell vars are not supported


code:
import argparse
import textwrap as _textwrap

class LineWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)

parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=LineWrapRawTextHelpFormatter)
parser.add_argument('--foo', type=int, default=42, help="FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an u")
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help="BAR! FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry.")
parser.print_help()

rawDescription: Python argparse.RawTextHelpFormatter with line wrap


code:
def format_duration(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

duration = 170
format_duration(duration)
duration += 10
format_duration(duration)

rawDescription: Minutes and seconds as a variable in Python


code:
x = [['aaa', 'bb','ccc'], ['ophkn','h','aa']]
j = 1
max(len(i[j]) for i in x)

rawDescription: Python max length of j-th item across sublists of a list


code: max(p.attrOne for p in self.allPartners)

rawDescription: Get the object with the max attribute's value in a list of objects


code:
Swahili
English
Russian

rawDescription: Python: Extracting specific data with html parser


code:
# Import tornado libraries
import tornado.ioloop
import tornado.web
# Import URL mappings
from url import application
# Import zeroMQ libraries
from zmq.eventloop import ioloop
# Import zeroMQ.py functions
from zeroMQ import startListenToMessageQueue
# Import zeroMQ settings
import zeroMQ_settings
# Import our executor
import executors
# Import our db_settings
import db_settings

# main.py is the main access point of the tornado app, to run the application, just run "python main.py"

# What this will do is listen to port 8888, and then we can access the app using
# http://localhost:8888 on any browser, or using python requests library
if __name__ == "__main__":
    # Install PyZMQ's IOLoop
    ioloop.install()

    # Set the application to listen to port 8888
    application.listen(8888)

    # Get the current IOLoop
    currentIOLoop = tornado.ioloop.IOLoop.current()

    # Execute ZeroMQ Subscriber for our topics
    executors.executor.submit(startListenToMessageQueue(zeroMQ_settings.server_subscriber_ports,
                                                        zeroMQ_settings.server_subscriber_IP,
                                                        zeroMQ_settings.server_subscribe_list))

    # Test if the connection to our database is successful before we start the IOLoop
    db_settings.testForDatabase(db_settings.database)

    # Start the IOLoop
    currentIOLoop.start()

rawDescription: Python Tornado - How to create background process?


code:
from itertools import combinations

def partial_duplicate_destroyer(mydict, tolerance):
    #Modifies in-place. Returns only as a convenience. Copy if you don't want this behaviour.
    for key1, key2 in combinations(mydict, 2):
       if key1 in mydict and key2 - tolerance < key1 < key2 + tolerance:
         del mydict[key1]
    return mydict

rawDescription: Compare a dict to itself and remove similar keys efficiently


code:
shapes = {shape.__name__.lower(): shape
          for shape in Shape.__subclasses__()}

def MagicShape(kind, color, size):
    try:
        return shapes[kind](color, size)
    except KeyError:
        raise ValueError(kind)

rawDescription: Can a class in python behave like a specified class based on a passed parameter?


code:
longItem = ["..."] #your item
longItemStr = "".join(longItem).replace('\n ', '\n') # make a string out of list
shortl = longItemStr.partition('\n') # define the phrase length
longItemStr = longItemStr[:len(shortl[0])] # cut other copies
print(longItemStr)

rawDescription: removing duplicates in python and selenium

description: Removing duplicates in python and selenium


code:
def del_A(name):
    print('An A deleted:' + name)

class A(object):
    def __init__(self, name, finalizers):
        print('A created')
        self.name = name
        finalizers.append(weakref.ref(self, lambda wr, n = self.name: del_A(n)))

class B(object):
    def __init__(self):
        print('B created')

def do_work(finalizers):
    a = A('a1', finalizers)
    b = B()
    a.other = b
    b.other = a

if __name__ == '__main__':
    finalizers = []
    do_work(finalizers)

rawDescription: Weak reference callback is not called because of circular references


code:
process = subprocess.call([
    "perl", "-i", "-pe",
    r"s/(?<=password=)\w+/\1mynewordtesting/", var])

rawDescription: Perl Regex issue via Python Script

description: Perl Regex issue via Python Script


code:
class Process:
    def __init__(self, command, loop=None):

        self.loop = loop or asyncio.get_event_loop()

        self.created = False
        self.killed = asyncio.Future()

        self.proc = self.loop.subprocess_exec(
            lambda: WorkerInteraction(self),  # see upstream repo
            *command)

        self.transport = None
        self.protocol = None

    async def create(self):
        self.transport, self.protocol = await self.proc

    def communicate(self, timeout):
        if self.killed.done():
            raise Exception("process was already killed "
                            "and no output is waiting")

        return ProcessIterator(self, self.loop, timeout)

class ProcessIterator:
    """
    Asynchronous iterator for the process output.
    Use like `async for (fd, data) in ProcessIterator(...):`
    """

    def __init__(self, process, loop, run_timeout):
        self.process = process
        self.loop = loop
        self.run_timeout = run_timeout

        self.overall_timer = None

        if self.run_timeout < INF:
            # set the global timer
            self.overall_timer = self.loop.call_later(
                self.run_timeout,
                functools.partial(self.timeout, was_global=True))

    def timeout(self):
        if not self.process.killed.done():
            self.process.killed.set_exception(ProcTimeoutError(
                self.process.args,
                self.run_timeout,
            ))

    async def __aiter__(self):
        return self

    async def __anext__(self):
        # either the process exits,
        # there's an exception (process killed, timeout, ...)
        # or the queue gives us the next data item.
        # wait for the first of those events.
        done, pending = await asyncio.wait(
            [self.process.protocol.queue.get(), self.process.killed],
            return_when=asyncio.FIRST_COMPLETED)

        # at least one of them is done now:
        for future in done:
            # if something failed, cancel the pending futures
            # and raise the exception
            # this happens e.g. for a timeout.
            if future.exception():
                for future_pending in pending:
                    future_pending.cancel()

                # kill the process before throwing the error!
                await self.process.pwn()
                raise future.exception()

            # fetch output from the process
            entry = future.result()

            # it can be stopiteration to indicate the last data chunk
            # as the process exited on its own.
            if entry == StopIteration:
                if not self.process.killed.done():
                    self.process.killed.set_result(entry)

                    # raise the stop iteration
                    await self.stop_iter(enough=False)

            return entry

        raise Exception("internal fail: no future was done!")

    async def stop_iter(self):
        # stop the timer
        if self.overall_timer:
            self.overall_timer.cancel()

        retcode = self.process.returncode()

        raise StopAsyncIteration()

rawDescription: Cancel asynchronous iterator by timeout

description: Cancel asynchronous iterator by timeout


code:
import numpy as np
from scipy.spatial.distance import cdist
x = np.random.rand(10, 2)
t = np.random.rand(8, 2)
cdist(x, t, 'sqeuclidean')

rawDescription: Optimisation of a simple vector operation (python)


code:
t = Text()
t.config(wrap=WORD)

rawDescription: Python 3 Tkinter: How to word-wrap text in Tkinter Text


code:
import os
import sys
from distutils.errors import DistutilsPlatformError

PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)

def get_python_version():
    """Return a string containing the major and minor Python version,
    leaving off the patchlevel.  Sample return values could be '1.5'
    or '2.2'.
    """
    return sys.version[:3]

def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
    """Return the directory containing the Python library (standard or
    site additions).

    If 'plat_specific' is true, return the directory containing
    platform-specific modules, i.e. any module from a non-pure-Python
    module distribution; otherwise, return the platform-shared library
    directory.  If 'standard_lib' is true, return the directory
    containing standard Python library modules; otherwise, return the
    directory for site-specific modules.

    If 'prefix' is supplied, use it instead of sys.prefix or
    sys.exec_prefix -- i.e., ignore 'plat_specific'.
    """
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    if os.name == "posix":
        libpython = os.path.join(prefix,
                                 "lib", "python" + get_python_version())
        if standard_lib:
            return libpython
        else:
            return os.path.join(libpython, "site-packages")

    elif os.name == "nt":
        if standard_lib:
            return os.path.join(prefix, "Lib")
        else:
            if get_python_version() < "2.2":
                return prefix
            else:
                return os.path.join(prefix, "Lib", "site-packages")

    elif os.name == "os2":
        if standard_lib:
            return os.path.join(prefix, "Lib")
        else:
            return os.path.join(prefix, "Lib", "site-packages")

    else:
        raise DistutilsPlatformError(
            "I don't know where Python installs its library "
            "on platform '%s'" % os.name)

rawDescription: A way to get the path to the user installed packages on Linux and OS X operating systems? (Usable for Python versions between 2.5 - 2.7)


code:
import cv2
from numpy import array
img = cv2.imread('flower.jpg')
img2 = array( 200  * (img[:,:,2] > img[:,:, 1]), dtype='uint8')

rawDescription: How to find the shape of an object in an image using python

description: Find the shape of an object in an image using python


rawDescription: Matplotlib polar bar-plot legend

description: Matplotlib polar bar-plot legend


code: full_tensor = np.array(reduce(operator.add, master_dict.values()))

rawDescription: Numpy normalization code is strangely slow


rawDescription: Format an array as string in Python

description: Format an array as string in Python


code:
class WeeklyInfo(db.Model):
   user = db.UserProperty()
   date = db.DateProperty(auto_now=False, auto_now_add=False)
   confirm = db.BooleanProperty()

class Demo(db.Model):
  someData = db.StringProperty()
  weekly = db.ReferenceProperty(WeeklyInfo)

rawDescription: How to create a new property in google app engine

description: Create a new property in google app engine


code: sorted(csv1) == sorted(csv2)

rawDescription: Python comparing two CSV files when order of rows doesn't matter


rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


rawDescription: Pass keyword argument to another function where the keyword has a default value


code:
for x in iterate(func, d + f.name):
    yield x

rawDescription: Python: lazy iterating through directory-like structure


code:
points = list(readfile(pathname))
max_x = max(x for x, y in points)
max_y = max(y for x, y in points)

rawDescription: Extracting minimum and maximum x-values Python


code:
import csv
from collections import OrderedDict

d = OrderedDict() # keep the order

with open('in.csv', 'r') as f1, open("output.csv", "w") as out:
    r = csv.reader(f1,delimiter=",")
    header = next(r) # store header
    writer = csv.writer(out,delimiter=",")
    for row in r:
        price = float(row[2])
        # first check price will be less than than inf so we will add the key/value
        if d.get(row[2], float("inf")) > price:
            d[row[0]] = row
    writer.writerow(header) # write header
    for tup in d.values(): # write updated items
        writer.writerow(tup)

rawDescription: Keep duplicated item with lowest price in csv file


code: df = pd.DataFrame(np.random.random((1000, 100)))

rawDescription: Most Pythonic Way to Create Many New Columns in Pandas


code: (not (letter.lower() in word) or not(letter.lower() in guessed_letters)) and letter != ' '

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code:
[(self.margin+self.g_width)*self.column+self.margin,\
                        (self.margin+self.g_height)*self.row+self.margin, \
                            self.g_width,self.g_height]

rawDescription: Can grid arrays be translate to (x,y) coordinates in Pygame?


code:
def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    if row == -1:
        result = True
    else:
        result = False
        num = 0
        while num < 9 and not result:
            num += 1
            if self.isValid(grid, row, col, num):
                grid[row][col] = num

                if self.solve_grid(grid, row, col):
                    result=True
                else:
                    grid[row][col] = 0

    return result

rawDescription: splitting multiple return statements into different functions

description: Splitting multiple return statements into different functions


code:
from xml.dom.minidom import Text, Element

t = Text()
e = Element('p')

t.data = '<bar><a/><baz spam="eggs"> & blabla &entity;</>'
e.appendChild(t)

rawDescription: Python: Escaping strings for use in XML

description: Python: Escaping strings for use in XML


code: ALL = object()

rawDescription: Unique constant reference

description: Unique constant reference


code:
re.findall (r'(?<=moving towards )[^-.]*', string)
['a particular point']

rawDescription: Regex to match a particular word followed by another, along with a boundary identifier


code:
import re

def parse_slash_date(value):
    m = re.match(r'^(?P<day>[0-9]{1,2})/(?P<month>[0-9]{1,2})/(?P<year>[0-9]{4})$', value)
    if m:
        return '%s-%s-%s' % (
            m.group('year'), m.group('month'), m.group('day'))

rawDescription: Django Model DateField to_python

description: Django Model DateField to_python


code:
r = {}
for key, value in d.items():
    for element in value:
        r[element] = key

l = [r.get(i) for i in xrange(1, max(r) + 1)]

rawDescription: How to convert dictionary of indices to list of keys?

description: Convert dictionary of indices to list of keys


code:
import bpy
import os
for ob in bpy.context.scene.objects:
    print("object name:  ", ob.data.name)

rawDescription: Blender - Open and parse a .blend file from python script


code:
import numpy # Assuming you have numpy available

class Houses(object):
    def __init__(self, dimension_x=None, dimension_y=None):
        self.dimension_x = dimension_x
        self.dimension_y = dimension_y
    def GetDimensions(self):
        return (self.dimension_x,self.dimension_y)

class HouseManager(object):
    def __init__(self):
        self.house_list = []
    def PushNewHouse(self,dim_x,dim_y):
        self.house_list.append(House(dim_x,dim_y))
    def CompareDimensions(self):
        dims = [list(instance.GetDimensions()) for instance in self.house_list]
        dims = numpy.array(dims)
        # .... futher processing on matrix

rawDescription: Interaction of objects in object-oriented programming


code:
def swap_permute(vals):
    if len(vals) < 2:
        return [vals[:]]

    r1 = swap_permute(vals[1:])
    s1 = [vals[:1] + x for x in r1]

    r2 = swap_permute(vals[2:])
    s2 = [vals[1::-1] + x for x in r2]

    return s1 + s2

rawDescription: python combinators list with constraints without itertools

description: Python combinators list with constraints without itertools


code:
answer = 0    # or a reasonable number

if c == 1:
    answer = 90
# ...

rawDescription: Can you define a variable inside an if statement?

description: Define a variable inside an if statement


rawDescription: How to make this kind of equality array fast (in numpy)?

description: Make this kind of equality array fast (in numpy)


code:
import StringIO
s = StringIO.StringIO()
s.write('hello')
s.readlines()
s.seek(0)
s.readlines()

rawDescription: File downloaded always blank in Python, Django


code:
self.enemy.score  += int(self.player.side == side)
self.player.score += int(self.player.side != side)

rawDescription: What are some interesting alternatives to line-by-line if/else statements?


rawDescription: How to create an index on a ndarray using pandas

description: Create an index on a ndarray using pandas


code:
for i in range(len(a)):
    csv_writer.writerow('{}, {}, {}, {}'
        .format(a[i], b[i], c[i], d[i]))

rawDescription: How to make a CSV file from a number of lists?

description: Make a CSV file from a number of lists


code:
def get_bad_apple_time():
    # create a bad apple every 5 to 15 seconds
    # assuming your FPS is 60
    return random.randrange(5, 16) * 60

#  all bad apple coordinates go here
bad_apples = []

# timeout until the next bad apple shows up
next_bad_apple = get_bad_apple_time()

rawDescription: PyGame wormy - threads with bad apples

description: PyGame wormy - threads with bad apples


code: game(greedy, zoomin, board)

rawDescription: Python 3 Passing a Function into Another Function


code: x

rawDescription: Relocate zeros to the end of the last dimension in multidimensional numpy array


code:
if user.is_active:
    login(request, user)
    state = "You're successfully logged in!"
    return render_to_response('ucproject/portal/index.html',
           {'state':state, 'username':username}, context_instance=RequestContext(request))

rawDescription: Django HttpResponseRedirect vs render_to_response - how to get a login form to behave the way I need it to


code: testMethod = getattr(self, methodName)

rawDescription: Python unittest, how to display TestCase's methods' docstring in report?


code:
for filename in all_files:
    for data in read_objects(filename):
        if 'text' and 'coordinates' in data:
            f.writerow([data['id'], data['geo']['coordinates']])

rawDescription: Adding brackets and commas to multiple JSON objects


code:
import sys

def calculate_line_endings(filename):
    cr = lf = crlf = lfcr = 0
    for line in open(filename, "rb"):
        if line.endswith('\r\n'):
            crlf += 1
        elif line.endswith('\n\r'):
            lfcr += 1
        elif line.endswith('\r'):
            cr += 1
        elif line.endswith('\n'):
            lf += 1

    print('crlf: %s' % crlf)
    print('lfcr: %s' % lfcr)
    print('cr: %s' % cr)
    print('lf: %s' % lf)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        sys.exit('usage: %s <filename>' % sys.argv[0])
    else:
        calculate_line_endings(sys.argv[1])

rawDescription: Get newline stats for a text file in Python


code:
with open('titles_file.txt') as f:
    titlelist = f.readlines()

rawDescription: Giving different titles to plots in for-loop


code:
def func(df):
    idx = df.reset_index()['DeliveryCount'].idxmax()
    return df['DeliveryNb'].iloc[idx]

rawDescription: Python pandas idxmax for multiple indexes in a dataframe


code: reader = csv.reader(f1 if coding else itertools.chain([line], f1))

rawDescription: Neat way to check first line of a file before reading CSV


rawDescription: List in a list recognition in python

description: List in a list recognition in python


code:
re.findall(
    r'[^\w\s]+|\s+(?!(?:month|year|day|hour|minute|second))\w*\s*|\s+|\w+',
    text
)

rawDescription: parsing dates and times

description: Parsing dates and times


rawDescription: python regex help: match all text between '"icon":"' AND '.png",'

description: Python regex help: match all text between '"icon":"' AND '.png",'


rawDescription: How to concatenate double curly brackets with variables in javascript

description: Concatenate double curly brackets with variables in javascript


code: DateR = date.compile()

rawDescription: Composable Regexp in Python

description: Composable Regexp in Python


code: my_grid = [my_input[i:i+4] for i in range(0,len(my_input),4)]

rawDescription: Appending a list to make a 4x4 matrix cipher


code:
def pip_install():
    with cd(env.path):
        with prefix('source venv/bin/activate'):
            run('pip install -r requirements.txt')

rawDescription: How to export virtualenv?

description: Export virtualenv


code:
tom_index = next(index for (index, d) in enumerate(lst) if d["name"] == "Tom")
# 1

rawDescription: Find the index of a dict within a list, by matching the dict's value


code:
def float_eq(a, b):
    return abs(a - b) < 0.01

A = FuzzyDict(float_eq=float_eq)
B = FuzzyDict(float_eq=float_eq)
A['a'] = 2.345
A['b'] = 'a string'
B['a'] = 2.345
B['b'] = 'a string'
B['a'] = 2.3445
A == B
B['a'] = 234.55
A == B
B['a'] = 2.345
B['b'] = 'a strin'
A == B

rawDescription: Comparing Python dicts with floating point values included


code:
x = A()
y = A()
x.foo['bar'] = "baz"

rawDescription: Python - inbound outbound argument

description: Python - inbound outbound argument


code:
Event.objects.filter(articles__publishDate__gt=dateStart)\
             .filter(articles__publishDate__lt=dateEnd)\
             .annotate(count=Count('articles')).order_by('-count')

Person.objects.filter(articles__publishDate__gt=dateStart)\
              .filter(articles__publishDate__lt=dateEnd)\
              .annotate(count=Count('articles')).order_by('-count')

rawDescription: How to make a filtering annotation with ManyToMany relation in Django?

description: Make a filtering annotation with ManyToMany relation in Django


code:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent, bg="blue")
        self.parent = parent

        button = tk.Button(parent, text="a button")
        button.pack()

root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

rawDescription: Creating Frames in tkinter

description: Creating Frames in tkinter


code:
from xlsxwriter.utility import xl_rowcol_to_cell

cell = xl_rowcol_to_cell(1, 2)  # C2

rawDescription: Python xlsxwriter: Adjust excel reference cells in loop when creating formula


code:
def orig_efreqs(m):

    col_total = m.sum(axis=0)
    row_total = m.sum(axis=1)
    n = int(col_total.sum(axis=1))

    A = sparse.coo_matrix(m)
    for i,j in zip(A.row,A.col):
        m[i,j]= col_total.item(j)*row_total.item(i)/n

    return m

rawDescription: Faster way to build a matrix of expected frequencies from a sparse matrix of counts


code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

Builder.load_string("""
<MyWidget>:
    cols: app.tiles
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
    Label:
        text: "test"
""")

class MyWidget(GridLayout):
    pass

class MyApp(App):
    tiles = 5
    def build(self):
        return MyWidget()

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

rawDescription: How to access a global var in Kivy file?

description: Access a global var in Kivy file


code:
from graphics import *

def main_function():
    win = GraphWin ("Example" , 1000,1000)
    win.setBackground("green")
    circle_params = [(50, 50, 20, "blue"),
                   (50 ,100, 20, "blue"),
                   (50,100, 20, "green"),
                   (300,50, 20, "green"),
                   (350,50, 20, "green"),
                   (400,50, 20, "green"),
                   (450,50, 20, "green"),
                   ]
    helper_function(win, circle_params)

def helper_function(win, circle_params):
    for param in circle_params:
        a = Circle(Point(param[0], param[1]), param[2]).setFill(param[3]).draw(win)

rawDescription: creating multiple objects graphics

description: Creating multiple objects graphics


code:
import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(file)

rawDescription: Find all files in directory with extension .txt in Python


code: [x for x in lst if all(re.search(s, x) for s in strings_to_match)]

rawDescription: Find sublist of strings that match a regex that requires ordered inclusion from another list


code:
import io
from IPython.nbformat import current

def convert(py_file, ipynb_file):
    with io.open(py_file, 'r', encoding='utf-8') as f:
        notebook = current.reads(f.read(), format='py')
    with io.open(ipynb_file, 'w', encoding='utf-8') as f:
        current.write(notebook, f, format='ipynb')

convert('test.py', 'test.ipynb')

rawDescription: Is there a IPython notebook api?

description: Is there a IPython notebook api


code: manual

rawDescription: running web2py scheduler in production

description: Running web2py scheduler in production


code:
file = __builtin__.open(filename, mode, buffering)
if encoding is None:
     return file

rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


code: a = np.fromiter(Data, dtype=np.float, count=DataLength.value) # copy

rawDescription: How to convert pointer to c array to python array

description: Convert pointer to c array to python array


code: max(None, arg1, arg2, arg3)

rawDescription: Python inspect module: keyword only args