code:
from cv2 import matchTemplate as cv2m

def search_sequence_cv2(arr,seq):
    """ Find sequence in an array using cv2.
    """

    # Run a template match with input sequence as the template across
    # the entire length of input array and get scores.
    S = cv2m(arr.astype('uint8'),seq.astype('uint8'),cv2.TM_SQDIFF)

    # Now, with floating point array cases, the matching scores might not be
    # exactly zeros, but would be very small numbers as compared to others.
    # So, for that use a very small to be used to threshold the scorees
    # against and decide for matches.
    thresh = 1e-5 # Would depend on elements in seq. So, be careful setting this.

    # Find the matching indices
    idx = np.where(S.ravel() < thresh)[0]

    # Get the range of those indices as final output
    if len(idx)>0:
        return np.unique((idx[:,None] + np.arange(seq.size)).ravel())
    else:
        return []         # No match found

rawDescription: Searching a sequence in a NumPy array

description: Searching a sequence in a NumPy array


code:
import numpy as np

a = np.loadtxt("test.txt")

np.savetxt("odd.txt", a[a%2==1])
np.savetxt("even.txt", a[a%2==0])

rawDescription: Separate odd and even numbers into different output files


rawDescription: Pandas: add dataframes to dataframe - match on index and column value


code:
class ServerThread(threading.Thread):
    def __init__(self):
         threading.Thread.__init__(self)
         self.localServer = SimpleThreadedXMLRPCServer(("localhost",10007))
         self.localServer.register_function(getTextA) #just return a string

    def run(self):
         self.localServer.serve_forever()

rawDescription: Python Multithreading XMLRPC server (?)

description: Python Multithreading XMLRPC server (?)


code:
import unum.units
safe_dict = dict((x,y) for x,y in unum.units.__dict__.items() if '__' not in x)
safe_dict['__builtins__'] = None

def convert(s):
    if '__' in s:
       raise ValueError("Won't do this with underscores...it's unsafe")
    return eval(s,safe_dict)

rawDescription: Casting string to 'unit' object in Python


code:
pre_count = Article.objects.count()

# Your Logic

post_count = Article.objects.count()

self.assertEqual(post_count-pre_count, 1)

rawDescription: Python / Django - is there an assertion similar to Rails' assert_difference?


code:
fd = open("/tmp/out", "r")
...
fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
flag = fcntl.fcntl(fd, fcntl.F_GETFD)

rawDescription: python Non-block read file

description: Python Non-block read file


rawDescription: Plot a (polar) color wheel based on a colormap using Python/Matplotlib


code:
class Post(db.Document):
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
    title = db.StringField(max_length=255, required=True)
    slug = db.StringField(max_length=255, required=True)
    body = db.StringField(required=True)
    meta = {'collection': 'customcollection'}

rawDescription: How to retrieve records in a different collection using python's mongoengine?

description: Retrieve records in a different collection using python's mongoengine


code: new_img = nifti.NiftiImage(result)

rawDescription: Iterating through a multidimensional array


code:
def not_double_cap_word(word):
    cap_count = sum(ch.isupper() for ch in word)
    return cap_count < 2

rawDescription: python filter rewrite filter

description: Python filter rewrite filter


code: list(merge(xrange(1, 9), 'abc', 3))   # note that this works for any iterable!

rawDescription: Merge 2 lists at every x position

description: Merge 2 lists at every x position


rawDescription: Numpy random choice multiple loops

description: Numpy random choice multiple loops


code:
#encoding:utf-8
from random import *

class randomStringGenerator:
    def __init__(self):
        self.aList = []
        self.again = True
        self._prepare()

    def _prepare(self):
        allowed = input("What are the characters that you will allow?\n"
                        "Please press the chracters you want and leave a space between each character\n, then enter to submit\n"
                        "e.g. 'a' 'b' 'c'\n")
        aList = allowed.split(" ")
        minimum = input("What is the minimum number of characters in the string that you want? \n")
        maximum = input("What is the maximum number of characters in the string that you want? \n")
        self.aList = aList
        self.minimum = int(minimum)
        self.maximum = int(maximum)

    def generateRandNum(self, mini, maxi):
        x = randint(mini,maxi)
        return x

    def generateRandString(self):
        ans = u""
        strSize = self.generateRandNum(self.minimum, self.maximum)
        pos = 0
        while(pos < strSize):
            size = len(self.aList)
            idx = self.generateRandNum(0, size - 1)
            char = self.aList[idx]
            ans = ans + char
            pos += 1
            ans.encode('utf-8')
        return ans

    def getAgain(self):
        return self.again

    def replay(self):
        x = input("Would you like to generate another string using the same settings? y/n \n")
        if(x == "y"):
            return self.generateRandString()
        else:
            y = input("Would you like to generate another string using different settings? y/n \n")
            if(y == "y"):
                self._prepare()
                return self.generateRandString()
            else:
                self.again = False
                return ""

if __name__ == "__main__":
    s = randomStringGenerator()
    print (s.generateRandString())
    while(s.getAgain()):
        print (s.replay())

rawDescription: Encoding accented/dotted characters in python?


code:
[ins.to_bytes() for ins in dis.get_instructions(code)]
b''.join([ins.to_bytes() for ins in dis.get_instructions(code)]) == code.co_code

rawDescription: Strange behaviour when creating a function directly from CodeType and FunctionType in python


code:
j, = np.nonzero(np.in1d(b, x))
j
b[j]

rawDescription: Find indices of mutually exclusive elements between two arrays in python


code:
def add_student(self, key, value):
    self.student[key] = value

rawDescription: assigning objects to another object python

description: Assigning objects to another object python


rawDescription: how to retrieve value from text file using python?

description: Retrieve value from text file using python


code:
df['species'] = np.random.choice(2,150)
sns.pairplot(df, hue="species", size=2.5)

rawDescription: How to load data from np matrix to seaborn?

description: Load data from np matrix to seaborn


code: np.fft.fft(Msig.T, axis=0)

rawDescription: FFT in Matlab and numpy / scipy give different results


code:
obj = [[] for i in range(20)]
obj

rawDescription: Python : creating multiple lists

description: Python : creating multiple lists


code:
max(max(l_one), max(l_two))
min(min(l_one), min(l_two))

rawDescription: Python find min & max of two lists

description: Python find min & max of two lists


code:
from nltk.stem import PorterStemmer
porter = PorterStemmer()
word = "analysis"
word
porter.stem(word)
from __future__ import print_function, unicode_literals
word
word2 = "analysis"
word2

rawDescription: Why did PortStemmer in NLTK converts my "string" into u"string"


code:
class OwnerChange(forms.ModelForm):
    required_css_class = 'required'

    ## Update the queryset to order by username
    owner = forms.ModelChoiceField(queryset=User.objects.order_by('username'))

    class Meta:
        model = Cluster
        fields = ['owner']

rawDescription: Unable to sort a user ForeignKey in Django


code:
class UdevWrapper:
    def udevadm_trigger(self):
        call(['/sbin/udevadm', 'trigger', '--action=change'])

rawDescription: Unit test python udev interaction

description: Unit test python udev interaction


code: T = [[{"first":None,"second":None}]*4 for x in range(4)]

rawDescription: How to create a matrix with values as dictionaries in python

description: Create a matrix with values as dictionaries in python


code:
import sched, time, datetime

def print_time():
    print("The time is now: {}".format(datetime.datetime.now()))

# Run 10 seconds from now
when = time.time() + 10

# Create the scheduler
s = sched.scheduler(time.time)
s.enterabs(when, 1, print_time)

# Run the scheduler
print_time()
print("Executing s.run()")
s.run()
print("s.run() exited")

rawDescription: Is there any Python module available which can alarm after certain time


rawDescription: Elements of the original list changes when a deep copy of changes


code:
seen = set()
for n in packagelist:
    if n[0] not in seen:
        print (n[0])
        seen.add(n[0])

rawDescription: Removing duplicate from tuple in list

description: Removing duplicate from tuple in list


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(18,9))
map = Basemap(projection='cyl', lat_0 = 57, lon_0 = -135, resolution = 'c', area_thresh = 0.1, llcrnrlon=0.0, llcrnrlat=-60.0, urcrnrlon=360.0, urcrnrlat=60.0)
map.drawcoastlines()
map.drawcountries()
map.drawparallels(np.arange(-90,90,15.0),labels=[1,1,0,1])
map.drawmeridians(np.arange(-180,180,15),labels=[1,1,0,1])
map.drawmapboundary()

IR = np.random.rand(3298, 9896)

map.imshow(IR)

rawDescription: overplot array on a world map in python

description: Overplot array on a world map in python


rawDescription: Numpy, Reading from File with no delimiter but fixed pattern


code:
user = request.user
logs = user.logs

rawDescription: Perform a SQL JOIN on Django models that are not related?


rawDescription: How to select two elements from list and do math on them in Python?

description: Select two elements from list and do math on them in Python


code:
re.split(
    r"""\s*   # Match (but don't capture) optional whitespace characters
    (         # Capture...
     [^\w\s]+ # one or more non-whitespace, non-alphanumeric characters
    )         # End of capturing group
    \s*       # Match (but don't capture) optional whitespace characters""",
    'number1 * number2', flags=re.VERBOSE)

rawDescription: How do I split without removing delimeter, if it's whitespace

description: Split without removing delimeter, if it's whitespace


code:
def combinations_with_replacement(iterable, r, startWord=None):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    if startWord is None:
        indices = [0] * r
    else:
        assert len(startWord) == r
        indices = [pool.index(l) for l in startWord]
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

rawDescription: Python bruteforce combinations given a starting string


code: AUGGAGAGAGAAAAUUUGGGGGGGAAAAAAUAA

rawDescription: Extract a part of a string in python

description: Extract a part of a string in python


code: new_value = value[0].strip('"')  # for double quoted strings

rawDescription: Adding string values (varchars) to MySQL table without quotation marks with Django/Python


code:
import urlparse
import requests

parsed_url = urlparse.urlsplit('http://example.com/render/')
params = {'start': '0', 'count': '1', 'currency': '20', 'country': 'CDN'}

def get_listing_info(host):
    url = urlparse.urlunsplit(parsed_url[:1] + (host,) + parsed_url[2:])
    r = requests.get(url, headers={'Host': parsed_url.netloc}, params=params)
    return r.json().get('listinginfo')

rawDescription: python- How to properly send http GET requests to different Host-IPs but same host

description: Python- How to properly send http GET requests to different Host-IPs but same host


code:
for i in range(len(table)):
    for j in range(len(table[i])):
       ...

rawDescription: Copying a list in python

description: Copying a list in python


code:
import libxml2

txt = '\n<Data>\n  <R><F>Key</F><F>Val</F><F>Flag</F></R>\n  <R><F>01</F><F>AAA</F><F>Y</F></R>\n  <R><F>02</F><F>BBB</F><F>N</F></R>\n</Data>\n'

rows = []
for elem in libxml2.parseDoc(txt):
    if elem.name == 'R':
        curRow = []
        rows.append(curRow)
    elif elem.name == 'F':
        curRow.append(elem.get_content())

rawDescription: regex to parse tables wrapped into xml

description: Regex to parse tables wrapped into xml


code: numbers = []

rawDescription: How do I prevent Python's append method replacing existing values?

description: Prevent Python's append method replacing existing values


code:
class my_account_invoice_line(osv.osv):
    _inherit = "account.invoice.line"

    def _default_analytics_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        custom_id = context.get('custom_field_id', False)
        if custom_id:
            # ...your code to do something with custom_id goes here...
            return True # or whatever suits your needs to be used as default
        return False

    _defaults = {
        'analytics_id': _default_analytics_id,
        }

my_account_invoice_line()

rawDescription: Access invoice header data (invoice_id) from invoice line tree


code:
class MyThirdDict(dict):
    my_method = my_func

rawDescription: building a class from functions in python

description: Building a class from functions in python


code:
for loc in (self.room, self.floor, self.building):
    if loc is not None:
        location.append(loc)
        break

rawDescription: Python: a better way to write a if-then block with join?


code:
from numpy.fft import fft, ifft

def periodic_corr(x, y):
    """Periodic correlation, implemented using the FFT.

    x and y must be real sequences with the same length.
    """
    return ifft(fft(x) * fft(y).conj()).real

rawDescription: circular cross correlation python

description: Circular cross correlation python


code:
l_in = [T(id=1, children=[]), T(id=2, children=[]), [T(id=3, children=[]),
        T(id=4, children=[]), [T(id=5, children=[])]]]
l_expected = [T(id=1, children=[]),
              T(id=2, children=[T(id=3, children=[]),
                                T(id=4, children=[T(id=5, children=[])])])]
l_ouput = magic(l_in)
repr(l_output) == repr(l_expected)

rawDescription: Nesting lists in python

description: Nesting lists in python


code:
def my_cycle(seq):
    while seq:
        for element in seq:
            yield element

cycled_list = my_cycle(L)
for x in range(10):
    print(next(cycled_list))

rawDescription: Cycle Through List Items

description: Cycle Through List Items


rawDescription: The number of intersections between columns


rawDescription: PyQt - How to connect multiple signals to the same widget


code:
def logout(request, *args, **kwargs):
    do_something()
    from django.contrib.auth.views import logout as authlogout
    return authlogout(request, *args, **kwargs)

rawDescription: Hacking Django Admin, hooks for login/logout


rawDescription: How to efficiently remove non-ASCII characters and numbers, but keep accented ASCII characters

description: Efficiently remove non-ASCII characters and numbers, but keep accented ASCII characters


code: x & y

rawDescription: What is the correct way to AND in python?


code:
posts = Post.objects.all()
sortedposts = {}
for p in posts:
    sortedposts.setdefault(p.pub_date.year, {})\
               .setdefault(p.pub_date.strftime('%b'), [])\
               .append(p)

rawDescription: Django: drop-down list

description: Django: drop-down list


rawDescription: Preventing nested list output from a for-loop / list comprehension when appending new values to an Array


rawDescription: How can I tell MATLAB that the data I am importing is a series of vectors, not just a series of letters?

description: Tell MATLAB that the data I am importing is a series of vectors, not just a series of letters


code: a.replace("xxxxxx", "foo")

rawDescription: string replace in Python

description: String replace in Python


code:
import numpy as np
a = np.ones((2, 3))
b = np.delete(a, 2, axis=1)

rawDescription: Numpy's delete not working

description: Numpy's delete not working


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    'django.core.context_processors.request'  # This one in particular
)

rawDescription: Django multi tenancy

description: Django multi tenancy


code:
final_df = pd.pivot_table(
    df,
    index='user_id',
    columns='type_id',
    values='avg',
    agg_func=np.average
)

rawDescription: How to transfer SQL Group by results to a Pandas dataframe

description: Transfer SQL Group by results to a Pandas dataframe


code:
# prepare the array that will hold the 'result set':
AB = NP.column_stack((A, NP.zeros((A.shape[0], B.shape[1]-1))))

def join(A, B) :
    '''
    returns None, side effect is population of 'results set' NumPy array, 'AB';
    pass in A, B, two NumPy 2D arrays, representing the two SQL Tables to join
    '''
    k, v = B[:,0], B[:,1:]
    dx = dict(zip(k, v))
    for i in range(A.shape[0]) :
        AB[i:,-2:] = dx[A[i,0]]

rawDescription: Moving large SQL query to NumPy

description: Moving large SQL query to NumPy


code:
from functools import partial

def pr(text):
  print(text)

def frun(func):
  func()

frun(partial(pr, *pr_args))

rawDescription: send arguments for function arguments in python

description: Send arguments for function arguments in python


code:
import numpy as np
np.random.seed(5)
a = np.random.random([3,3]) > 0.5
b = np.random.random([3,3]) > 0.5

rawDescription: Matrix multiplication in numpy

description: Matrix multiplication in numpy


code: dictAB = dict((k, [dictA[k], dictB[k]]) for k in set(dictA) & set(dictB))

rawDescription: Refactoring with python dictionary comprehension


code:
if c=='images':
            ftp=FTP('127.0.0.1',userid,passwd)
            if not 'images' in ftp.nlst():
                ftp.mkd('images')
            ftp.cwd('images')

elif c=='documents':
            ftp=FTP('127.0.0.1',userid,passwd)
            if not 'documents' in ftp.nlst():
                ftp.mkd('documents')
            ftp.cwd('documents')

elif c=='audios':
            ftp=FTP('127.0.0.1',userid,passwd)
            if not 'audios' in ftp.nlst():
                ftp.mkd('audios')
            ftp.cwd('audios')

elif c=='videos':
           ftp=FTP('127.0.0.1',userid,passwd)
           if not 'videos' in ftp.nlst():
            ftp.mkd('videos')
           ftp.cwd('videos')
else:
            ftp=FTP('127.0.0.1',userid,passwd)
            if not 'others' in ftp.nlst():
                ftp.mkd('others')
            ftp.cwd('others')
files=ftp.nlst()

rawDescription: Show files uploaded of a particular format on ftp server using python


rawDescription: append match to new list and delete match from original list

description: Append match to new list and delete match from original list


code:
def sum(n, m):
    ...

rawDescription: if Python doesn't support method overloading, then why does this method overload work while this other does not?

description: If Python doesn't support method overloading, then why does this method overload work while this other does not


code: base.paste(image, box, image)

rawDescription: Opening PNG with PIL/Pillow

description: Opening PNG with PIL/Pillow


rawDescription: Python: How to execute external program with parameters from another file?


code:
x = 0
while x < y: x +=1

rawDescription: Python single line while loop

description: Python single line while loop


code:
I,J = where(a>0)   # a is 2d
a[I,J]
a[(I,J)]

rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


code:
dat_dict = {}

for ct in country:
    b = pd.read_excel(str(ct + ".xls"), parse_dates = True, format = '%dd%.mm.%YYYY', index_col = [0], skiprows=1,)

    #I am not sure what b is but if you can store it as a pd.Series in the data_dict
    #instead of pd.Dataframe then you won't need b.iloc[:,0] later on.

    b = pd.DataFrame(b[ str("Ann.PD-" + rec) ] )
    #b.columns = [ct]
    dat_dict[ct] = b.iloc[:,0]

rawDescription: How to keep dates as index and inner join keys in multiple excel files

description: Keep dates as index and inner join keys in multiple excel files


code:
example = {}
example[1] = "whatever"
example[99] = "whatever"
example[-12] = "something else"
example['cow'] = 'pie'
#delete
example.pop(99)

rawDescription: python insert into list at constant x position

description: Python insert into list at constant x position


code:
import virtkey

v = virtkey.virtkey()
v.press_keycode(66)
v.release_keycode(66)  # first release doesn't release it
v.release_keycode(66)

rawDescription: Anybody know how to toggle caps lock on/off in Python?


code:
item_count_vector = [
    [d['CNT'] for d in grp]
    for key, grp in itertools.groupby(cursor.fetchall(), key=lambda row: row['ID'])
]

...

rawDescription: From MySQL table to Python list

description: From MySQL table to Python list


code:
x_data = int(x.get())
y_data = int(y.get())
z_data = int(z.get())

rawDescription: How do I store a value entered on a Tk entry widget in a variable

description: Store a value entered on a Tk entry widget in a variable


code:
from PIL import Image
import numpy as np

data = np.random.randint(0,2**16-1,(1000,1000))
im = Image.fromarray(data)
im.save('test.tif')

im2 = Image.open('test.tif')
data2 = np.array(im2.getdata()).reshape(im2.size[::-1])

rawDescription: numpy.array of an "I;16" Image file

description: Numpy.array of an "I;16" Image file


rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


code:
class Default(dict):
    def __init__(self, default, *args, **kwargs):
        self.default = default
        dict.__init__(self, *args, **kwargs)
    def __missing__(self, key):
        return self.default

rawDescription: Python String template dict KeyError, how set detault value


code:
if optDate:
    now = datetime.datetime.strptime(optDate, '%Y%m%d%H%M%S').replace(tzinfo=pytz.utc)
else:
    now = datetime.datetime.now(pytz.utc)

rawDescription: test time-based scripts

description: Test time-based scripts


code:
...
self.parentvariable1 = 2
def parentfunction1(self):
    ...

rawDescription: How could I make a good application architecture in Python with PyQt?


code: column_elms = [E("table-column",{"column-width":"41mm"}) for _ in xrange(COLUMNS)]

rawDescription: Why are my Python arguments not unpacking?


rawDescription: Getting information about the user from Facebook using django_facebook


code: s.sort(key = operator.itemgetter(1, 2))

rawDescription: Sort a list by multiple attributes?

description: Sort a list by multiple attributes


code: sentence = 'Hi, %s! Your new contact email %s has been confirmed' % ('KemyLand', address)

rawDescription: How to account for string formatting in Python variable assignment?

description: Account for string formatting in Python variable assignment


rawDescription: How can I quickly compare a list and a set?

description: Quickly compare a list and a set


code: d = dict([(y,x) for x,y in enumerate(t)])

rawDescription: pythonic way to associate list elements with their indices

description: Pythonic way to associate list elements with their indices


code:
def hello_user(self):
    return self.get_name

rawDescription: LPTHW ex. 45, how to return functions from a class in another module?


code:
def addingcustomer(file_name,new_name):
    f=open(file_name,"r+")
    for line in f:
        if new_name in line:
            f.close()
            return False
    # the name didn't exist
    f.write(new_name)
    f.write("\n")
    f.close()
    return True

rawDescription: How do i make a while loop so it reads through every single line in .txt file before it decide what to?

description: Make a while loop so it reads through every single line in .txt file before it decide what to


rawDescription: Python: How to distinguish between inherited methods


code:
import cProfile
import pstats

cProfile.run('partition(70)', 'partition.test')
p = pstats.Stats('partition.test')
p.sort_stats('name')
p.print_stats()

rawDescription: Optimizing a Partition Function

description: Optimizing a Partition Function


code:
a = [(1, 2, 3)]
b = []
b = a[:]
b is a
b[0] is a[0] # Initially the objects are the same
b[0] += (4,) # Now a new object is created and overwrites b[0]
b[0] is a[0]
b[0]
a[0]

rawDescription: applying a function on an object in python

description: Applying a function on an object in python


code: max(hand, key=lambda c: rank_cards.index(c[0]))

rawDescription: Getting highest value card in list

description: Getting highest value card in list


code:
C = np.random.rand(20,1600,500)
d = np.random.randint(0, 20, size=900)
e = np.random.randint(1600, size=900)
f = np.random.randint(400, size=900)
b = np.random.randint(100, size=50)
g = np.random.rand(50)

rawDescription: Speed up for loop with numpy

description: Speed up for loop with numpy


code:
from collections import Counter

counter = None
for line in f.readlines():
    line = line.strip("\n")
    if line.startswith(">"):
        if counter is not None:
            print(counter)
        print(line)
        counter = Counter()
    elif line.startswith("A") or line.startswith("T") or line.startswith("C") or line.startswith("G"):
        seq = line
        y = 0
        for y in range(2, len(seq), 3):
            x = seq[y]
            counter[x] += 1
print(counter)

rawDescription: Reading ATCG DNA sequences, and calculates the numbers of ATCG in third place


code:
import asyncio
from websockets import connect

class EchoWebsocket:
    async def __aenter__(self):
        self._conn = connect("wss://echo.websocket.org")
        self.websocket = await self._conn.__aenter__()
        return self

    async def __aexit__(self, *args, **kwargs):
        await self._conn.__aexit__(*args, **kwargs)

    async def send(self, message):
        await self.websocket.send(message)

    async def receive(self):
        return await self.websocket.recv()

async def main():
    async with EchoWebsocket() as echo:
        await echo.send("Hello!")
        print(await echo.receive())  # "Hello!"

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: How can I implement asyncio websockets in a class?

description: Implement asyncio websockets in a class


rawDescription: Sort a text file by multiple columns

description: Sort a text file by multiple columns


code:
import pandas as pd
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]}
a = pd.DataFrame(oldcols)

newf = a.pivot(index='col1', columns='col2')
print(newf)

rawDescription: Change column values to column headers in pandas


code:
class Car:

    def take_to_repair_shop(self):
        pass

    def drive_to_the_beach(self):
        pass

    repair = take_to_repair_shop # <---
    beach = drive_to_the_beach   # <---

rawDescription: What is the best way to alias method names in python?


code: print(re.sub(r'(\d+)', r'\n\1', input))

rawDescription: How to split string before number

description: Split string before number


code:
from natsort import natsorted, ns
x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
natsorted(x, key=lambda y: y.lower())
natsorted(x, alg=ns.IGNORECASE)  # or alg=ns.IC

rawDescription: Does Python have a built in function for string natural sort?


code:
class Status(models.Model):
    code = models.IntegerField()
    text = models.CharField(maxlength=255)

    @classmethod
    def successful(cls):
        return cls.objects.get(code=0)

    @classmethod
    def failed(cls):
        return cls.objects.get(code=1)

rawDescription: Django model class methods for predefined values


rawDescription: Convert string to packed data in Python

description: Convert string to packed data in Python


code:
import os
from scipy.misc import imread
import numpy as np

imagePath = 'c:/your jpgs/'
savepath = imagePath

#save as text no decompressing
for filename in os.listdir(imagePath):
    if filename!='.DS_Store' and filename[-3:]=='jpg':
        with open(filename,'rb') as fin:
            b = fin.read()
            fin.close()
        out = ','.join(b)+'\n'
        with open(savepath+'trainMatrix1.txt','a') as fut:
            fut.write(out)
            fut.close()

rawDescription: convert JPG to txt causes change in file size in python

description: Convert JPG to txt causes change in file size in python


code:
class Object(object):
    __metaclass__ = Singleton
    def __init__(self, arg=None):
        print("creating instance with arg:", arg)

rawDescription: Passing arguments to singletons in python


rawDescription: python search through text files composed of lines

description: Python search through text files composed of lines


rawDescription: How to get indices of non-diagonal elements of a numpy array?

description: Get indices of non-diagonal elements of a numpy array


code:
from forbiddenfruit import curse
from numpy import ndarray
from numpy.linalg import inv
curse(ndarray,'H',property(fget=lambda A: A.conj().T))
curse(ndarray,'I',property(fget=lambda A: inv(A)))

rawDescription: Conjugate transpose operator ".H" in numpy


code:
import os
os.system('arp -a > ipaddresses.tmp')
f = open('ipaddresses.tmp', 'r')

rawDescription: Python check for online ip addresses

description: Python check for online ip addresses


code:
df.start_sec[i] = df.start_sec[i] * scale
df.end_sec[i] = df.end_sec[i] * scale

rawDescription: Updating values in a DataFrame

description: Updating values in a DataFrame


code:
def max_execs(n=5):
    def decorator(fn):
        fn.max = n
        fn.called = 0
        def wrapped(*args, **kwargs):
            fn.called += 1
            if fn.called <= fn.max:
                return fn(*args, **kwargs)
            else:
                # Replace with your own exception, or something
                # else that you want to happen when the limit
                # is reached
                raise RuntimeError("max executions exceeded")
        return wrapped
    return decorator

rawDescription: How are these type of python decorators written?


code:
_, breaks=np.histogram(df.MAT,bins=5)
ax=df.boxplot(column='N0_YLDF',by='Class')
ax.xaxis.set_ticklabels(['%s'%val for i, val in enumerate(breaks) if i in df.Class])

rawDescription: Boxplot stratified by column in python pandas


code:
import csv
from itertools import groupby
from operator import itemgetter

cn = 10001
with open("test.txt") as f, open("out.txt", "w") as tmp:
    r, wr = csv.reader(f, delimiter="|"), csv.writer(tmp, delimiter="|")
    head, d = next(r), {}
    wr.writerow(["ID"] + head)
    for k, v in groupby(r, key=itemgetter(4)):
        wr.writerows([cn]+sub for sub in v)
        cn += 1

rawDescription: Match attributes against one another Python


code:
rcParams['figure.figsize'] = 16, 12
df_analyze.hist()
plt.savefig('hist.png')

rawDescription: Setting python pandas histogram size

description: Setting python pandas histogram size


code:
_,id = np.unique(anArray,return_inverse=True)
out = (id.max() - id + 1).reshape(anArray.shape)

rawDescription: Numpy Array Rank All Elements

description: Numpy Array Rank All Elements


rawDescription: Best way to isolate one coefficient of a multivariate polynomial in sympy

description: Isolate one coefficient of a multivariate polynomial in sympy


code:
from Tkinter import *
import tkFont
import Image #This is the PIL Image library

rawDescription: Resizing pictures in PIL in Tkinter

description: Resizing pictures in PIL in Tkinter


rawDescription: Get Attribute type of a model in Django

description: Get Attribute type of a model in Django


rawDescription: Filter a pandas dataframe using values from a dict


code:
...
hm = plt.contourf(x, levels = levels, cmap = "rainbow", vmax = 0.3 * levels[-1] + 0.7 * levels[-2])
...

rawDescription: Nonlinear Colormap/Heatmap

description: Nonlinear Colormap/Heatmap


code:
class Sub(AbstractClass):
   '''Subtype template implements AbstractClass base type and adds
      its own 'foo' attribute. Note (though poor style, that __slots__
      and __dict__ style attributes may be mixed.'''

   def __init__(self):
       '''Subtype initializer. Sets 'foo' attribute. '''
       self.foo = "bar"

rawDescription: python: abstract base class' __init__(): initializion or validation?

description: Python: abstract base class' __init__(): initializion or validation


rawDescription: what is the delimiter in my text

description: What is the delimiter in my text


code:
sql = '''
UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
%s
END
WHERE NAME IN (%s)
''' % (conditions_string, where_string)

rawDescription: Python - Generate a multiple row update query


rawDescription: xpath not contains A and B

description: Xpath not contains A and B


code: playerletter = input("What letter would you like to be? X or O? \n").upper

rawDescription: Variable won't be assigned to input in Python


rawDescription: Python JSON serialize a Decimal object

description: Python JSON serialize a Decimal object


rawDescription: How to compute an expensive high precision sum in python?

description: Compute an expensive high precision sum in python


code: global picked1, picked2, picked3, picked4, picked5, picked6

rawDescription: How can I show a variable on command that is updating constantly?

description: Show a variable on command that is updating constantly


code: syslog.openlog('Blah', 0, getattr(syslog, facility))

rawDescription: AttributeError: 'module' object has no attribute 'something'


rawDescription: I need to add all my output numbers from my loop?


code:
app = webapp2.WSGIApplication([
    webapp2.Route(r'/oauth/callback', handler='oauth.CallbackHandler', name='callback-uri-name'),
])

rawDescription: GAE: python code to check if i'm on dev_appserver or deployed to appspot


code:
import PythonMagick

sample = PythonMagick.Image('sample.jpg')
watermark = PythonMagick.Image('watermark.jpg')

sample.composite(watermark, 50, 50,
                 PythonMagick.CompositeOperator.AtopCompositeOp)

sample.write('output.jpg')

rawDescription: Drawing text in PythonMagick?

description: Drawing text in PythonMagick


code:
Header1,Header2,Header3
A,1,10
B,2,20
C,3,30

rawDescription: How to create dict using csv file with first row as keys

description: Create dict using csv file with first row as keys


code:
WIDTH = 60
HEIGHT = 20
cells = [[EMPTY]*WIDTH for y in xrange(HEIGHT)]

rawDescription: printing out dictionnaires

description: Printing out dictionnaires


code:
from mako.template import Template
Template('${"%20s%10s" % ("string 1", "string 2")}').render()

rawDescription: Formatting with mako

description: Formatting with mako


code:
a = A.make(1)
b = A.make(a)

rawDescription: Python assignment to self in constructor does not make object the same


code:
import numpy as np
ar = np.frombuffer(surface.get_data(), dtype=np.int32)
bitmask = (ar.reshape(WIDTH, HEIGHT) != 0)

rawDescription: getting the bitmask of a text string in python

description: Getting the bitmask of a text string in python


code:
from pylab import plot, title, xlabel, ylabel, savefig, legend, array

values = [(3, 4, 5), (7, 8, 9), (2, 3, 4)]
days = array([24, 25, 26])

for temp in zip(*values):
    plot(days, array(temp))
title('Temperature at december')
xlabel('Days of december')
ylabel('Temperature')
legend(['min', 'avg', 'max'], loc='lower center')
savefig("temperature_at_christmas.pdf")

rawDescription: How do I plot a list of tuples with matplotlib?

description: Plot a list of tuples with matplotlib


code: S=[np.split(z,2,0) for y in np.split(X,2,2) for z in np.split(y,2,1)]

rawDescription: split ndarray into chunks - whilst maintaining order

description: Split ndarray into chunks - whilst maintaining order


code: df -= df.median(axis=0)

rawDescription: Deducting the median from each column

description: Deducting the median from each column


code:
test = {'a': 1, 'b': 2 , 'c': 3 , 'd': 4}

user_input = raw_input("Type 'abcd':")

number = int("".join(str(test[character]) for character in user_input))

rawDescription: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

description: Make a 'while' loop print the results of the loop's conditional into a single line(concatenated)


code: print('\t'.join(map(repr, x)))

rawDescription: How do I join integers, Decimal() and datetime.datetime() in a list?

description: Join integers, Decimal() and datetime.datetime() in a list


rawDescription: Use between_time() on MultiIndex?

description: Use between_time() on MultiIndex


code:
from functools import reduce

dfs = [df1, df2, df3, df3, df5]

def my_merge(df1, df2):
    res = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
    cols = sorted(res.columns)
    pairs = []
    for col1, col2 in zip(cols[:-1], cols[1:]):
        if col1.endswith('_x') and col2.endswith('_y'):
            pairs.append((col1, col2))
    for col1, col2 in pairs:
        res[col1[:-2]] = res[col1].combine_first(res[col2])
        res = res.drop([col1, col2], axis=1)
    return res

print(reduce(my_merge, dfs))

rawDescription: pandas: merge several dataframes

description: Pandas: merge several dataframes


rawDescription: Obtain one number from numpy subarrays given its peer


code:
s
s.strip('{}')
s.strip('{}').split(',')
list(map(lambda x:x.split('#'), s.strip('{}').split(',')))

rawDescription: Parsing a string containing # as separator


code: dir(obj)

rawDescription: looping over all member variables of a class in python

description: Looping over all member variables of a class in python


rawDescription: Numpy array.resize() - zeros 'first'

description: Numpy array.resize() - zeros 'first'


rawDescription: How to rearrange table in pandas in a format suitable for analysis in R?

description: Rearrange table in pandas in a format suitable for analysis in R


code:
from collections import defaultdict

def split_series(points, interval):
    offset = points[0][0]
    maxval = (points[-1][0] - offset) // interval
    vals = defaultdict(list)
    for key, value in points:
        vals[(key - offset) // interval].append(value)
    return [vals[i] for i in xrange(maxval + 1)]

rawDescription: Grouping data points into series

description: Grouping data points into series


code:
# self.FW.En is an entry widget.
self.FW.En.bind('<KeyRelease>', self.find)

rawDescription: Variable updating one step behind in list searcher in Tkinter


rawDescription: Passing variables onto a MongoDB Query

description: Passing variables onto a MongoDB Query


code:
import csv

with open('aggregated.csv', 'w') as out_file:
  writer = csv.writer(out_file)
  for key, value in sorted(totals.items()):
    row = list(key) + [value]
    writer.writerow(row)

rawDescription: How to aggregate column values from a CSV file in Python

description: Aggregate column values from a CSV file in Python


code:
import timeit
setup = "from __main__ import convert_to_celsius, convert_to_celsius_lambda, convert_to_celsius_lambda_once"
timeit.timeit("convert_to_celsius(100, 'kelvin')", setup=setup)
timeit.timeit("convert_to_celsius_lambda(100, 'kelvin')", setup=setup)

rawDescription: Recommended usage of Python dictionary, functions as values


code:
#! python3
strings = [
    "Germany  ; Federal Republic of Germany\tRépublique fédérale d'Allemagne\n",
    "English  ; English language\tanglais\n",
    "February\tfévrier\n",
]

import re

for s in strings:
    m = re.match(r"^(\S+)(?:  ; [^\t]+)?\t([^\n]+)\n", s)
    print((m.group(1), m.group(2)))

rawDescription: Regular expression for advanced string

description: Regular expression for advanced string


code:
def get_colour(self):
    return self.colour

rawDescription: Difference between @classmethod and a method in python


code:
def unpack_nfirst(seq, nfirst):
  it = iter(seq)
  for x in xrange(nfirst):
    yield next(it, None)
  yield tuple(it)
first, rest = unpack_nfirst(seq, 1)

rawDescription: How to unpack tuple of length n to m<n variables

description: Unpack tuple of length n to m<n variables


code:
import os,string
path = '.'
path = os.path.normpath(path)
res = []
for root,dirs,files in os.walk(path, topdown=True):
    depth = root[len(path) + len(os.path.sep):].count(os.path.sep)
    if depth == 2:
        # We're currently two directories in, so all subdirs have depth 3
        res += [os.path.join(root, d) for d in dirs]
        dirs[:] = [] # Don't recurse any deeper
print(res)

rawDescription: List directories with a specified depth in Python


code:
a = True
b = 1 if a else 2
b

rawDescription: Python scoping and if-then statements

description: Python scoping and if-then statements


code:
import pandas as pd

df_pivot = df.pivot(index='tenor', columns='date', values='value')

DayCounts = {"D":1, "M":365.0/12, "Y":365}
index = sorted(df_pivot.index, key=lambda v:int(v[:-1])*DayCounts[v[-1]])

df_pivot.reindex(index)

rawDescription: Pivot data and maintain original sort order


code:
from collections import defaultdict

def create_myDict(mylists):
    myDict = defaultdict(list)
    for sublist in mylists:
        for i in range(len(sublist)):
            myDict[sublist[i]].append(i)
    return myDict

rawDescription: Create dictionary from multiple lists

description: Create dictionary from multiple lists


rawDescription: How to write to database all cache in Odoo environment?

description: Write to database all cache in Odoo environment


code:
import csv

with open('Stockinventory.txt', 'r', newline='') as f:
    items = list(csv.reader(f, skipinitialspace=True))

rawDescription: Rewriting array to text file, need to put each part on new line


code: x_y = zip(xy, xy[1:])

rawDescription: convert a list of x and y coordinates into multistring

description: Convert a list of x and y coordinates into multistring


code:
if __name__ == "__main__":
    fileName = "SomeSiteValidURLs.csv"
    FILE_LINES = 10,000,000
    NUM_WORKERS = cpu_count() * 2
    chunksize = FILE_LINES // NUM_WORKERS * 4  # Try to get a good chunksize. You're probably going to have to tweak this, though. Try smaller and lower values and see how performance changes.
    pool = Pool(NUM_WORKERS)

    with open(FileName, "rb") as f:
        result_iter = pool.imap(crawlToCSV, f)
    with open("Output.csv", "ab") as f:
        writeFile = csv.writer(f)
        for result in result_iter:  # lazily iterate over results.
            writeFile.writerow(result)

rawDescription: Multithreading in Python/BeautifulSoup scraping doesn't speed up at all


code:
def sasquatchicorn(name):
    return property(lambda self: getattr(self, name) + ' sasquatch',
                    lambda self, val: setattr(self, name, val + ' unicorns'))

class Foo(object):
    bar = sasquatchicorn('_bar')
    baz = sasquatchicorn('_baz')

rawDescription: Python: Generic getters and setters

description: Python: Generic getters and setters


code:
def residuals(p, x, y):
    return func(p, x)-y

rawDescription: SciPy LeastSq Dfun Usage

description: SciPy LeastSq Dfun Usage


code:
gene1, gene2 = [], []
for line in file:
    if matches_gene1(line):
        gene1.append(parse_gene1(line))
    elif matches_gene2(line):
        gene2.append(parse_gene2(line))
    elif matches_gene0(line):
        gene0 = parse_gene0(line)
        do_stuff_with(gene0, gene1, gene2)
        gene1, gene2 = [], []

rawDescription: how to keep data from lines in file until condition met later in file python

description: Keep data from lines in file until condition met later in file python


code: data_original = np.dot(data_reduced, pca.components_) + pca.mean_

rawDescription: PCA inverse transform manually

description: PCA inverse transform manually


rawDescription: Discontiguous array slices in Python

description: Discontiguous array slices in Python


code:
dummies['val'] = df.val
dummies

rawDescription: Pandas / Numpy: How to Turn Column Data Into Sparse Matrix


code:
import pytz
calcutta = pytz.timezone('Asia/Calcutta')
utc = pytz.utc
current_time = calcutta.localize(DT.datetime.utcnow())
print(current_time)
# 2013-05-12 18:33:19.368705+05:30
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368705+00:00

rawDescription: Get new datetime object according to timezone difference


code:
import sys.path
sys.path.append('.')

rawDescription: How do I resolve sys.path differences in Python and IronPython

description: Resolve sys.path differences in Python and IronPython


rawDescription: convert character to unicode

description: Convert character to unicode


code:
import datetime

from yourapp.models import Event

def upcoming_events(request):
    now = datetime.date.today()
    return {'approaching': Event.objects.exclude(event_date__lt=now)[:5]}

rawDescription: Showing a list of objects alongside a Django DetailView


code:
import numpy as np
from collections import Counter

def increment_counts_in_matrix_from_chain(markov_chain, transition_counts_matrix):
    for i in xrange(1, len(markov_chain)):
        old_state = markov_chain[i - 1]
        new_state = markov_chain[i]
        transition_counts_matrix[old_state, new_state] += 1

def using_counter(chain, counts_matrix):
    counts = Counter(zip(chain[:-1], chain[1:]))
    from_, to = zip(*counts.keys())
    counts_matrix[from_, to] = counts.values()

def using_bincount(chain, counts_matrix):
    flat_coords = np.ravel_multi_index((chain[:-1], chain[1:]), counts_matrix.shape)
    counts_matrix.flat = np.bincount(flat_coords, minlength=counts_matrix.size)

def using_bincount_reshape(chain, counts_matrix):
    flat_coords = np.ravel_multi_index((chain[:-1], chain[1:]), counts_matrix.shape)
    return np.bincount(flat_coords, minlength=counts_matrix.size).reshape(counts_matrix.shape)

rawDescription: How can I speed up transition matrix creation in Numpy?

description: Speed up transition matrix creation in Numpy


code: LOGIN_URL = reverse_lazy('login')

rawDescription: Django - use reverse url mapping in settings


code: df = df.sort_values(by='day')

rawDescription: How to plot values for multiple factors from one column across several dates in pandas + matplotlib?

description: Plot values for multiple factors from one column across several dates in pandas + matplotlib


code: [i for i in range(len(letterlist)) if letterlist[i-1:i+2] == ["C","A","C"]]

rawDescription: how to find a pattern of string elements in a list?

description: Find a pattern of string elements in a list


code:
from django.core.cache import cache

def my_mongo_view(request):
    ret = cache.get('home-rendered')
    if ret is None:
        ret = render_to_response('home.html', ...)
        cache.set('home-rendered', ret)
    return ret

rawDescription: Is possible to save render_to_response template from django to server?


code:
from Queue import Queue
import subprocess
import logging
main_queque = Queue()

def worker():
    global main_roles_queque
    while True:
        try:
            cmd = main_queque.get()
            #do_work(item)
            #time.sleep(5)
            handler = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            stdout, stderr = handler.communicate()
            logging.critical("[queue_worker]: stdout:%s, stderr:%s, cmd:%s" %(stdout, stderr, cmd))
            main_queque.task_done()
        except Exception as error:
            logging.critical("[queue_worker:error] %s" %(error))

rawDescription: How to store response when http client closed a connection?

description: Store response when http client closed a connection


code:
urlpatterns = patterns('',
    # ...
    url(r'^call/ajax/$', 'myapp.views.home_ajax', name='home-ajax'),
)

rawDescription: JSON from JS to View in django

description: JSON from JS to View in django


code:
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

rawDescription: How to import a module given the full path?

description: Import a module given the full path


code:
for key, group in groupby(data, group_key):
    group = list(group)
    if any(item[Col["STATUS"]] == "R" for item in group):
        for item in group:
           item[Col["STATUS"]] = "R"

rawDescription: Changing elements within a groupby

description: Changing elements within a groupby


code:
def BudgetJson(request):
    from django.http import JsonResponse
    out_list = []
    resultset = models.Expense.objects.filter(category_id=1)
    for model in resultset:
        temp_dict = {'expense_period': model.expensePeriod, 'expense_name':model.expenseName, 'expense_amount':model.expenseAmount }
        out_list.append(temp_dict)
    data = {'data' : out_list }
    return HttpResponse(json.dumps(data), content_type='application/json')

rawDescription: Looping through a nested JSON object in datatables


code:
for f in br.forms():
    print(f._pairs())

response = br.open("http://www.w3schools.com/html/html_forms.asp")
for f in br.forms():
    print(f)
    print(f._pairs())

rawDescription: Getting the key and value of br.forms() in Mechanize


rawDescription: Python - Plotting a raster image/contour plot with XY and Z points


code:
#Plot first element with labels
plt.plot(Xu.ravel()[0],Yu.ravel()[0], 'g>',label='u')
plt.plot(Xv.ravel()[0],Yv.ravel()[0],'r^',label='v')
plt.plot(Xc.ravel()[0],Yc.ravel()[0],'kx',label='p')

#plot remaining without Legend
plt.plot(Xu.ravel()[1:],Yu.ravel()[1:], 'g>',legend=False)
plt.plot(Xv.ravel()[1:],Yv.ravel()[1:],'r^',legend=False)
plt.plot(Xc.ravel()[1:],Yc.ravel()[1:],'kx',legend=False)

rawDescription: plt.save saves a different image

description: Plt.save saves a different image


code:
@hybrid_property
def radius(self):
    return abs(self.length) / 2

@radius.expression
def radius(cls):
    return fn.ABS(cls.length) / 2

rawDescription: Defining virtual fields in peewee

description: Defining virtual fields in peewee


rawDescription: python find and match exact string

description: Python find and match exact string


rawDescription: Read txt file for specific fields and store them in a numpy array


code:
from distutils.version import StrictVersion
versions = ["1.7.0", "1.7.0b0", "1.11.0"]
sorted(versions, key=StrictVersion)

rawDescription: Sort Versions in Python

description: Sort Versions in Python


code:
with unpatch('foo.narf', self.test_foo):
    foo.narf()

rawDescription: Python: calling stop on mock patch class decorator


code:
from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

rawDescription: How to do parallel programming in Python

description: Do parallel programming in Python


code:
def comparison(x):
    return len(x), x

rawDescription: Comparing string in python

description: Comparing string in python


code:
new_im = Image.new("RGBA", new_size) # makes the black image
# Note the "A" --------^

rawDescription: Python: Combining images using paste with overlapping pixels and areas with alpha channel=0


code: saw2 = np.tile(x,4)

rawDescription: How to rewrite the code which appends to lists with numpy arrays

description: Rewrite the code which appends to lists with numpy arrays


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

def generate_data():
    a = np.arange(25).reshape(5, 5)
    b = 10 * np.random.rand(5, 5)
    return a - b

def update(data):
    mat.set_data(data)
    return mat

def data_gen():
    while True:
        yield generate_data()

fig, ax = plt.subplots()
mat = ax.matshow(generate_data())
plt.colorbar(mat)
ani = animation.FuncAnimation(fig, update, data_gen, interval=500,
                              save_count=50)
plt.show()

rawDescription: Animate quadratic grid changes (matshow)


rawDescription: Django database query: How to filter objects by date range?


code:
#!/usr/bin/python3

from numpy import arange

import matplotlib
from matplotlib import pyplot as plt
custom_preamble = {
    "text.usetex": True,
    "text.latex.preamble": [
        r"\usepackage{amsmath}", # for the array macros
        ],
    }
matplotlib.rcParams.update(custom_preamble)

x = arange(5)
y = arange(5)

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

l1, = ax.plot(x, y)
l2, = ax.plot(x * 2, y)
l3, = ax.plot(x * 3, y)

leg = ax.legend(
    [l1, l2, l3],
    ["", "", ""],
    bbox_to_anchor = (0.98, 0.25),
    handletextpad = 4,  # space between lines and text -- used here as a placeholder
    labelspacing = 0.1, # space between lines in a legend
    )
leg.set_zorder(1)

ax.text(0.955, 0.21,

    r"\begin{array}{rcl}"
    r"     \varepsilon_i & < & -\xi"
    r"\\ |\varepsilon_i| & < & \xi"
    r"\\   \varepsilon_i & > & \xi"
    r"\end{array}",

    transform = ax.transAxes,
    horizontalalignment = 'right',
    verticalalignment = 'top',
    zorder = 5,
        )

fig.savefig("mwe.png")

rawDescription: Align legend rows in matplotlib

description: Align legend rows in matplotlib


code:
s="bla bla bla \uf604 bla bla bla"
print(s)
s="bla bla bla \uf604 bla bla bla"
s.replace('\uf604','X')

rawDescription: Replacing a unicode character in a string in Python 3


code:
from functools import partial, partialmethod

class partialmethod_with_descriptorargs(partialmethod):
    def __get__(self, obj, cls):
        get = getattr(self.func, "__get__", None)
        result = None
        if get is not None:
            new_func = get(obj, cls)
            if new_func is not self.func:
                args = [a.__get__(obj, cls) if hasattr(a, '__get__') else a
                        for a in self.args]
                kw = {k: v.__get__(obj, cls) if hasattr(v, '__get__') else v
                      for k, v in self.keywords.items()}
                result = partial(new_func, *args, **kw)
                try:
                    result.__self__ = new_func.__self__
                except AttributeError:
                    pass
        if result is None:
            # If the underlying descriptor didn't do anything, treat this
            # like an instance method
            result = self._make_unbound_method().__get__(obj, cls)
        return result

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
from operator import mul
base = [2, 3, 5]
powers = [1, 0, 0]
l = [n**p for n, p in zip(base, powers) if p != 0]
reduce(mul, l, 1)

rawDescription: Python: optimizing the product of a chain of factor-to-the-nth if n is not zero


code: root.bind('<Return>', go)

rawDescription: Stepping through function with button instead of input()


rawDescription: Expanding NumPy array over extra dimension


code: list(map(lst.__getitem__, starmap(slice, combinations(range(len(lst)+1), 2))))

rawDescription: python connected combinations of list items

description: Python connected combinations of list items


code:
import unidecode
somestring = u"äüÊÂ"
unidecode.unidecode(somestring)

rawDescription: Possible to do a string replace with a dictionary?


code: times

rawDescription: How to find times when a variable is below a certain value in pandas

description: Find times when a variable is below a certain value in pandas


code:
class Foo:
    a = None
    @property
    def a(self):
        '''
        >>> 1 == 1
        False
        '''
        pass
    @a.setter
    def a(self, v):
        pass

Foo.a
Foo.a.__doc__

rawDescription: python-2.7: doctests ignored in setter method of a class

description: Python-2.7: doctests ignored in setter method of a class


code:
html = '''

Simple example

This is a simple example of html page

 '''

soup = BeautifulSoup(html)

''.join(taggify(soup))
Out[34]: '

'

rawDescription: Get a structure of HTML code

description: Get a structure of HTML code


code:
def __init__(self,numin,xes,vees,masses):
    self.stars = []
    self.numstars = numin
    for n in range(numin):
        self.stars.append(Star(xes[n],vees[n],masses[n]))

rawDescription: python over-writing my list elements

description: Python over-writing my list elements


code: figure(figsize=(11.69,8.27)) # for landscape

rawDescription: Python: A4 size for a plot

description: Python: A4 size for a plot


rawDescription: regex/beautifulsoup how to extract the all values of column from html table?

description: Regex/beautifulsoup how to extract the all values of column from html table


rawDescription: Generalizing matrix transpose in numpy

description: Generalizing matrix transpose in numpy


code:
def get_value(mydict, keys):
    if not keys:
        return mydict
    key = keys[0]
    try:
        newdict = mydict[key]
    except (TypeError, KeyError):
        return 0
    return get_value(newdict, keys[1:])

rawDescription: Reaching into a nested dictionary several levels deep (that might not exist)


code:
inputlist = ['foo: a message', 'bar: d message', 'bar: b message', 'foo: c message']
sorted(inputlist, key=lambda s: s[5:])

rawDescription: Sort from a certain position in a String


rawDescription: Location of stored offline data for cartopy


rawDescription: How do I flattern a pySpark dataframe by one array column?

description: Flattern a pySpark dataframe by one array column


code:
odd, even = [], []
for value in multiples:
    if value % 2 == 0:
        even.append(value)
    else:
        odd.append(value)

rawDescription: Count even and odd numbers and the totals (python)


rawDescription: create a dictionary for a certain range in Python

description: Create a dictionary for a certain range in Python


code:
def pivotarraywithallitems(df):
    users,i= np.unique(df['user'],return_inverse=True)
    item,j= np.unique(df['item'],return_inverse=True)
    miss= (~in1d(arange(1,6),item)).cumsum()
    j+=miss[j]
    a=zeros((len(users),len(item)+miss[-1]),float)*NaN
    a[i,j]=df['rating']
    return a

rawDescription: How to aggregate the values of a DataFrame (and output a numpy array quickly)?

description: Aggregate the values of a DataFrame (and output a numpy array quickly)


code: sorted(keys, key=lambda k: int(k) if k.isdigit() else float('-inf'))

rawDescription: Python3: sorting a list of dictionary keys


code:
def find_index2(arr, x):
    return np.where((arr == x).all(axis=1))[0]

rawDescription: Fast way to find index of array in array of arrays


code: item = SetProperties(Item01Object)

rawDescription: Python: Copy properties with it's functions (fget, fset, fdel) from one class to another


rawDescription: Django help - how to get data from foreign keys


code:
def describe(obj):
    for key in dir(obj):
        try:
            val = getattr(obj, key)
        except AttributeError:
            continue
        if callable(val):
            help(val)
        else:
            print('{k} => {v!r}'.format(k=key, v=val))
        print('-' * 80)
describe(a)

rawDescription: get QuadMesh object from Axes (or Figure)

description: Get QuadMesh object from Axes (or Figure)


rawDescription: Breaking a list in to parts by subject

description: Breaking a list in to parts by subject


code:
Url_3
Url_4

rawDescription: Printing contents in particular section of configuration file in Python


code:
df = pandas.DataFrame(
    [(1, 2), (1, 3), (1, 4), (2, 1),(2,2,)], columns=['col1', 'col2'])
df = Container(df)
df['col1'][3] = 0
print(df)
#    col1  col2
# 0     1     2
# 1     1     3
# 2     1     4
# 3     2     1
# 4     2     2
gp = df.groupby('col1').aggregate(np.count_nonzero)
print(gp)
#       col2
# col1
# 1        3
# 2        2
print(type(gp))
# <class '__main__.Container'>

print(type(gp[gp.col2 > 2]))
# <class '__main__.Container'>

tf = gp[gp.col2 > 2].reset_index()
print(type(tf))
# <class '__main__.Container'>

result = df[df.col1 == tf.col1]
print(type(result))
# <class '__main__.Container'>

rawDescription: How to redirect all methods of a contained class in Python?

description: Redirect all methods of a contained class in Python


code: [[j.strip() for j in i]  for i in lst]

rawDescription: How to remove all \n's and make it as csv file of 5 columns?

description: Remove all \n's and make it as csv file of 5 columns


code:
# Here we decided to use spearman correlation
correlation_matrix = timeSeries.T.corr(method='spearman')

# Do the clustering
Z = hac.linkage(correlation_matrix, 'single')

# Plot dendogram
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('sample index')
plt.ylabel('distance')
hac.dendrogram(
    Z,
    leaf_rotation=90.,  # rotates the x axis labels
    leaf_font_size=8.,  # font size for the x axis labels
)
plt.show()

rawDescription: Hierarchical clustering of time series in Python scipy/numpy/pandas?


code:
# thanks to jdi for the help in the for-loop
if form.is_valid():
        # A for loop is used here, because my database contains 5 images and 5              thumbnails
        image_list = ['image_%d' % i for i in xrange(1,6)]
        for image_name in image_list:
            form_image = form.cleaned_data[image_name]
            try:
                details = Model.objects.get(pk=pk)
                if getattr(details, image_name, None) != form_image:
                    getattr(details, image_name, None).delete(save=False)
            except Model.DoesNotExist:
                pass

rawDescription: Imagekit - cache image not deleted after deleting original


code:
import argparse
from ast import literal_eval

class Package():
    def __init__(self, id, value, tag):
        if (value <= 0):
            raise ValueError("Amount must be greater than 0")
        self.id = id
        self.value = value
        self.tag = tag

def packages(s):
    try:
        data = literal_eval(s)
    except:  # TODO: avoid bare except and handle more specific errors
        raise argparse.ArgumentTypeError("Invalid 'packages' format.")

    return [Package(*item) for item in data]

parser = argparse.ArgumentParser()
parser.add_argument('--packages', dest="packages", type=packages, nargs=1)
args = parser.parse_args()
print(args.packages)

rawDescription: Use argparse to parse a list of objects

description: Use argparse to parse a list of objects


code: # pylint: disable=C0103

rawDescription: How do I tell PyLint "it's a variable, not a constant" to stop message C0103?

description: Tell PyLint "it's a variable, not a constant" to stop message C0103


code:
import urlparse
url = 'http://example.com/wps/portal/lYuxDoIwGAYf6f9aqKSjMNQ/?PartNo=74743&IntNumberOf=&is='
split_url = urlparse.urlsplit(url)
split_url.path

rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
import numpy as np
def image_entropy(img):
    w,h = img.size
    a = np.array(img.convert('RGB')).reshape((w*h,3))
    h,e = np.histogramdd(a, bins=(16,)*3, range=((0,256),)*3)
    prob = h/np.sum(h) # normalize
    prob = prob[prob>0] # remove zeros
    return -np.sum(prob*np.log2(prob))

rawDescription: How to detect motion between two PIL images? (wxPython webcam integration example included)

description: Detect motion between two PIL images? (wxPython webcam integration example included)


code:
excludehosts = restAPI.objects.values_list('rest_host', flat=True)
missinghosts = soapAPI.objects.exclude(soap_host__in=excludehosts)

rawDescription: Compare two alike fields from two separate models


code:
#!/usr/bin/python

from BeautifulSoup import BeautifulSoup
import feedparser

feedurl = feedparser.parse('http://dustinheroin.chompblog.com/index.php?cat=22&feed=rss2')
statusupdate = feedurl.entries[0].content

soup = BeautifulSoup(statusupdate[0]['value'])
print(soup.find("img")["src"])

rawDescription: RSS/Python - Parsing Single Image URL

description: RSS/Python - Parsing Single Image URL


code:
df1 = df1.join(df2['eins'])
mask = (df1['zick']>= 2) & (df1['zick'] < 4)
df1.loc[~mask, 'eins'] = np.nan
df1

rawDescription: Conditional join Pandas.Dataframe

description: Conditional join Pandas.Dataframe


rawDescription: Trouble making a table with HTML.py in python


code: print(cur.fetchall()) # Fetch all rows

rawDescription: Python (pymysql) Select...Where query returning boolean, not desired value


code: pprint.pprint(sorted(mylist, key=lambda d: (month_to_index[d['month'][:3]], d['month'][-4:])))

rawDescription: list of dictionary Sorting in python

description: List of dictionary Sorting in python


code: "these,should,be,separated,by,commas"

rawDescription: Combining objects in a list. Python

description: Combining objects in a list. Python


code:
import cairo
import rsvg
import gtk

class Viewer(object):
    def __init__(self):
        self.string = """<svg width="800" height="600"></svg>"""
        self.svg = rsvg.Handle(data=self.string)
        self.win = gtk.Window()
        self.da = gtk.DrawingArea()
        self.win.add(self.da)
        self.da.set_size_request(800, 600)
        self.da.connect("expose-event", self._expose_cairo)
        self.win.connect("destroy", self._destroy)
        self.win.show_all()
        self.win.present()

    def _expose_cairo(self, win, event):
        self.svg = rsvg.Handle(data=self.string)
        cr = self.da.window.cairo_create()
        self.svg.render_cairo(cr)

    def _destroy(self, widget, data=None):
        gtk.main_quit()

    def renderSVG(self, text):
        x, y, w, h = self.win.allocation
        self.da.window.invalidate_rect((0,0,w,h), False)
        self.string = text

rawDescription: How to use python to generate a magazine cover?

description: Use python to generate a magazine cover


code:
import requests, json
api_root = 'http://localhost:5555/api'
task_api = '{}/task'.format(api_root)
args = {'args': [1, 2]}
url = '{}/async-apply/my_app.add'.format(task_api)
print(url)
resp = requests.post(url, data=json.dumps(args))
reply = resp.json()
reply

rawDescription: Celery - Activate a task via command line or HTTP requests


code:
def start_process(queue):
  while True:
    try:
        m = queue.get()
        if m == 'exit':
            print ('cleaning up worker...')
            # add here your cleaning up code
            break
        else:
            print (m)
    except KeyboardInterrupt:
        print ('ignore CTRL-C from worker')
  print('goodbye cruel world')

if __name__ == '__main__':
  queue = Queue()

  process = Process(target=start_process, args=(queue,))
  process.start()

  queue.put(12)
  print ('sending exit')
  queue.put('exit')
  process.join()

rawDescription: Python 3 control multiprocessing

description: Python 3 control multiprocessing


code:
fred
wilma

rawDescription: appending a single string to each element of a list in python

description: Appending a single string to each element of a list in python


code:
DIR = 'C:/Data/'

def fn_CorpusFromDIR(xDIR):
    ''' functions to create corpus from a Directories
    Input: Directory
    Output: A dictionary with
             Names of files ['ColNames']
             the text in corpus ['docs']'''
    import os
    Res = dict(docs = [open(os.path.join(xDIR,f)).read() for f in os.listdir(xDIR)],
               ColNames = map(lambda x: 'P_' + x[0:6], os.listdir(xDIR)))
    return Res

rawDescription: efficient Term Document Matrix with NLTK

description: Efficient Term Document Matrix with NLTK


code: config = selective_merge(config, user_config)

rawDescription: Python/JSON: Merge default and user configuration


rawDescription: I have need the N minimum (index) values in a numpy array


code:
class AdvisorForm( forms.ModelForm ):
  class Meta:
    model=Advisor

  def __init__( self, *args, **kwargs ):
    super( AdvisorForm, self ).__init__( *args, **kwargs )
    self.fields[ 'name' ].widget.attrs[ 'placeholder' ]="Enter name"

rawDescription: using modelformset_factory and placeholder

description: Using modelformset_factory and placeholder


code: np.dot(M, M.T)

rawDescription: Transforming a mapping matrix

description: Transforming a mapping matrix


code:
connSqlServer = pyodbc.connect(driver='{SQL Server Native Client 10.0}',
                               server='192.106.0.102,1443',
                               database='master',
                               uid='sql2008',pwd='password123')

rawDescription: python pyodbc : how to connect to a specific instance

description: Python pyodbc : how to connect to a specific instance


rawDescription: Break bytes object into n equally sized blocks based on index


code:
# -*- coding: utf-8 -*-

import csv

with open('a.csv', 'r') as file_a:
    with open('b.csv', 'r') as file_b:
        with open('c.csv', 'w') as file_c:
            reader_a = csv.reader(file_a, delimiter=',')
            reader_b = csv.reader(file_b, delimiter=',')
            writer_c = csv.writer(file_c)

            for cols_a in reader_a:
                cols_b = reader_b.next()
                writer_c.writerow(cols_a + cols_b)

rawDescription: How to merge .csv files to do a matrix

description: Merge .csv files to do a matrix


code:
vals = np.linspace(0,1,3)
nplots = len(vals)
fig, axs = plt.subplots(nrows=nplots, ncols=1, sharex=True)
for i, alpha in enumerate(vals):
    axs[i].plot(np.linspace(0,1,100), alpha * np.linspace(0,1,100)**2)
plt.show()

rawDescription: How to share x axes into a loop?

description: Share x axes into a loop


rawDescription: Numpy Slicing slow?

description: Numpy Slicing slow


code:
# Usually the same behavior:
result = [[1, 2, 3], [4, 5, 6]]
map(None, *result)
zip(*result)
# But if result has only one iterable in it:
result = [[1, 2, 3]]
map(None, *result)
zip(*result)

rawDescription: How do I convert apply(map, args) to map(function, iterable) in this case?

description: Convert apply(map, args) to map(function, iterable) in this case


rawDescription: django haystack module search with whoosh

description: Django haystack module search with whoosh


code: [''.join(p) for p in itertools.chain(len2, len3, len4, len5, len6)]

rawDescription: How to iterate through alpha and numeric numbers

description: Iterate through alpha and numeric numbers


code:
setup(
    name='foobar',
    version='1.0.0',
    # other attributes
)

rawDescription: What is the correct way to share package version with setup.py and the package?


code:
import itertools

def grouper(n, iterable, fillvalue=None):
  "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  args = [iter(iterable)] * n
  return itertools.izip_longest(fillvalue=fillvalue, *args)

rawDescription: Python : Get many list from a list

description: Python : Get many list from a list


code:
def STDIN_BASEADDRESS():
    return 0x40600000
def STDOUT_BASEADDRESS():
    return 0x40600000

# ****************************************************************

# Definitions for driver UARTLITE
def XPAR_XUARTLITE_NUM_INSTANCES():
    return 1

rawDescription: converting include file in C to python

description: Converting include file in C to python


code:
unique_ids = df.groupby('id', as_index=False).first()
unique_ids['geometry'] = GeoSeries([Point(x, y) for x, y in zip(unique_ids['lon'], unique_ids['lat'])])

rawDescription: Pandas and GeoPandas indexing and slicing


rawDescription: Why does setattr work differently for attributes and methods?


code:
lot = [ ('a','b'),('c','d') ]
result = []
for a_tuple in lot:
    for item in a_tuple:
            result.append(item)
result

rawDescription: List comprehension interpretation order while turning list of tuples into a list


code:
url("^%s(?P<category>.*)%s$" % _slashes,
    "mezzanine.blog.views.blog_post_list",
    name="blog_post_list_category")

rawDescription: Customizing Mezzanine

description: Customizing Mezzanine


code:
with open('myfile') as fd:
  len = fd.readline()
  metadata_json = fd.read(int(len))
  metadata = json.loads(metadata)
  data = fd.read()

rawDescription: optimal method to parse a json object in a datafile

description: Optimal method to parse a json object in a datafile


code:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '/media/'  # Added this

rawDescription: Using django ImageField with Tastypie

description: Using django ImageField with Tastypie


rawDescription: How to replace r'\xb0' with r'\260'

description: Replace r'\xb0' with r'\260'


code:
import functools

def sensitive_variables(*variables):
 """
 Indicates which variables used in the decorated function are sensitive, so
 that those variables can later be treated in a special way, for example
 by hiding them when logging unhandled exceptions.

 Two forms are accepted:

* with specified variable names:

    @sensitive_variables('user', 'password', 'credit_card')
    def my_function(user):
        password = user.pass_word
        credit_card = user.credit_card_number
        ...

* without any specified variable names, in which case it is assumed that
  all variables are considered sensitive:

    @sensitive_variables()
    def my_function()
        ...
"""
 def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if variables:
            wrapper.sensitive_variables = variables
        else:
            wrapper.sensitive_variables = '__ALL__'
        return func(*args, **kwargs)
    return wrapper
 return decorator

rawDescription: Django 1.3 Error report remove sensitive information


code:
sql = """
    SET TEXTSIZE 2147483647;
    SELECT  Req.ID,
            ShReq.Summary AS [Short Name],
            ShReq.ALM_SharedText AS [Text],
            Req.ContainedBy,
            Req.DocumentID
    FROM    CurMKS..ALM_Requirement Req
            JOIN CurMKS..ALM_SharedRequirement ShReq ON Req.[References] = ShReq.ID
    WHERE DocumentID = 111111;
      """

rawDescription: Python with MS SQL - truncated output

description: Python with MS SQL - truncated output


code:
def find_cube_root(n):
    lo = 0
    hi = n
    while lo < hi:
        mid = (lo+hi)//2
        if mid**3 < n:
            lo = mid+1
        else:
            hi = mid
    return lo

def is_perfect_cube(n):
    return find_cube_root(n)**3 == n

rawDescription: Is cube root integer?

description: Is cube root integer


code:
class AuthHandler(webapp.RequestHandler):
  def get(self):
    user_id = self.request.get("user_id")
    # send a message indicating the user received the email and
    # verified to our client page. You may want to send other data.
    channel.send_message(user_id, "authorized")
    # probably want to show a nice "you've been authorized" page or something

rawDescription: How can I send data to Chrome extension?

description: Send data to Chrome extension


code:
from flask import Flask
from urllib import quote_plus

app = Flask('my_app')
app.jinja_env.filters['quote_plus'] = lambda u: urllib.quote_plus(u)

rawDescription: quote_plus urlencode filter in jinja

description: Quote_plus urlencode filter in jinja


code:
word = "first portion|middle|,end"
word.split('|')

rawDescription: Python - Having a sub for loop with the same variable


rawDescription: loop trough a python list of tuples and change a value

description: Loop trough a python list of tuples and change a value


code:
import ttk
from Tkinter import *
from another_script import run_script

def process():
    run_script()

root = Tk()
root.title("Test Script")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

ttk.Button(mainframe, text="Process", command=process).grid(column=0, row=0)

root.mainloop()

rawDescription: Where does my workbook popup?

description: Where does my workbook popup


rawDescription: recursively implementing 'minimum number of coins' in python

description: Recursively implementing 'minimum number of coins' in python


code:
class Derived(Base):
    def __init__(self, *args, **kwargs):
        self.decorator = whatever
        super(Derived, self).__init__(*args, **kwargs)

rawDescription: What's the cleanest way to add a decorator from a derived class to its base class?


code:
img = plt.contourf(np.random.random((20,20)))
print(img.cmap.name)

rawDescription: What was the default color palette for images in seaborn version 0.2?


code:
formone = render.formone('')
formtwo = render.formtwo('')

rawDescription: Templates in web.py

description: Templates in web.py


code:
data_file = open("myfile.txt")
data = data_file.read()
data_file.close()

rawDescription: How to print results from text file to window using Python

description: Print results from text file to window using Python


rawDescription: Opening file from python

description: Opening file from python


code:
import operator
percentOfPathElement = [diff / pathLength for diff in map(operator.sub, elementList[1:], elementList)]

rawDescription: Iterate through list and going back one item


code: user_sets = (set_1, set_2, set_3, set_4)

rawDescription: Finding the intersection between sets and awarding points


rawDescription: filling last known data with pandas

description: Filling last known data with pandas


rawDescription: Adding DataFrame groups as data columns

description: Adding DataFrame groups as data columns


code:
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
vals = np.reshape(A, (9))
pts = np.array([[i,j] for i in [0.0, 0.5, 1.0] for j in [0.0, 0.5, 1.0]] )
grid_x, grid_y = np.mgrid[0:1:7j, 0:1:5j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')

rawDescription: python - Extend 2-d array and interpolate the missing values

description: Python - Extend 2-d array and interpolate the missing values


rawDescription: Adding Colorbar legend to Basemap plot containing multiple shapefiles


rawDescription: Flask multiple URL handlers process URLs partially


code:
import re

re_search = '(?P<pre>[^ ])llo(?P<post>[^ ])'
re_replace = '\g<pre>ll\g<post>'

print(re.sub(re_search, re_replace, 'hello world'))
print(re.sub(re_search, re_replace, 'helloworld'))

rawDescription: replacing unigrams and n-grams in python without changing words

description: Replacing unigrams and n-grams in python without changing words


code:
from cStringIO import StringIO
s = StringIO()
s.write('foo')
s.getvalue()
s.truncate(0)
s.seek(0)
s.getvalue()
s.write('bar')
s.getvalue()

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


rawDescription: It is possible to round up integers using format?


code:
deltaY = P2_y - P1_y
deltaX = P2_x - P1_x

rawDescription: How to calculate the angle between a line and the horizontal axis?

description: Calculate the angle between a line and the horizontal axis


code: erlangList <<= Suppress('[') + delimitedList( Group(erlangDict|erlangList) ) + Suppress(']')

rawDescription: pyparsing: grammar for list of Dictionaries (erlang)

description: Pyparsing: grammar for list of Dictionaries (erlang)


code:
import io
txt = "foo\nbar\nbaz"
stream = io.StringIO(txt)
stream.read(5)

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


rawDescription: python pygame input controls

description: Python pygame input controls


rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


rawDescription: How to make django test framework read from live database?

description: Make django test framework read from live database


code:
from weakref import WeakSet

class foo:
    _instances = WeakSet()

    def __init__(self, value):
        self.value = value
        foo._instances.add(self)

    def getvalues(self):
        return sum(instance.value for instance in foo._instances)

rawDescription: Python: reference to other instances of class objects


code: print('Test: ', credentials[test_name] == test_code)

rawDescription: Searching and sorting in text files

description: Searching and sorting in text files


rawDescription: Alternative to using 'in' with numpy.where()


code:
with MyFile('test.log', 'w') as mylog:
    mylog.write('...')

rawDescription: Write a file to disk only when first content is written into it


code:
def initialize():
    print('initialize')
def do_the_thing(args):
    print('doing things',args)
def function(args):
    _function(args)
def firsttime(args):
    global _function
    initialize()
    do_the_thing(args)
    _function=do_the_thing
_function=firsttime

rawDescription: Changing a function implementation in Python


code:
with open("NegativeHotspot.txt") as f:
    reader = csv.DictReader(f, delimiter="\t")

rawDescription: Matching elements in a file to a nested dictionary python


code:
def parse(tokens):
    """parse: tokens_iter or generator -> Node
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes,
    that represent the expression."""

    next_tok = next(tokens)

    if next_tok.isdigit():
        return ('literal', next_tok)

    elif next_tok == "+":
        return ('add', parse( tokens ), parse( tokens )) # first argument is the node.left, second is the node.right
    elif next_tok == "-":
        return ('sub', parse( tokens ), parse( tokens ))
    elif next_tok == "*":
        return ('mul', parse( tokens ), parse( tokens ))
    elif next_tok == "//":
        return ('div', parse( tokens ), parse( tokens ))

    else:
        return ('variable', next_tok )

# And, example:
print(parse(iter(['-', '//', 'y', '2', 'x'])))

rawDescription: Python Simple Parse Tree Interpreter

description: Python Simple Parse Tree Interpreter


code:
from collections import Counter
l = [{'name': 'john', 'amount': 50}, {'name': 'al', 'amount': 20}, {'name': 'john', 'amount': 80}]
summed = Counter()
for d in l:
    summed[d['name']] += d['amount']

summed
[{'name': name, 'amount': amount} for name, amount in summed.most_common()]

rawDescription: How to combine values in python list of dictionaries

description: Combine values in python list of dictionaries


code:
from code import InteractiveInterpreter

code1 = """
def foo():
    print notDefined

foo()
"""

code2 = """
def baz(spam):
    print spam

baz('eggs')
"""

interpreter = InteractiveInterpreter()
interpreter.runcode(code1)
interpreter.runcode(code2)

rawDescription: Python compiler connected to a button

description: Python compiler connected to a button


code:
# drewk's answer, optimized by using from_iterable instead of *
def double_chain(s):
    return ''.join(chain.from_iterable(zip(s, s)))

# Ashwini Chaudhary's answer
def double_mult(s):
    return ''.join([x*2 for x in s])

# Jon Clements' answer, but optimized to take the re.compile and *2 out of the loop.
r = re.compile('(.)')
def double_re(s):
    return r.sub(r'\1\1', s)

rawDescription: Double every letter in string

description: Double every letter in string


code:
import numpy as np

gen = np.random.RandomState(0)

n_total = 1000
n_train = 800

train_idx = gen.choice(n_total, size=n_train)
test_idx = np.setdiff1d(np.arange(n_total), train_idx)

rawDescription: Cross-validation: finding row indices for a test set that aren't part of a training set


code:
def _get_employee_count(cls):
    return cls.employeeCount
get_employee_count = classmethod(_get_employee_count)

rawDescription: Class methods/instance methods in Python


rawDescription: Parsing csv file and writing rows to file according to relative size


code:
primes = [2] # we're going to start with 2 directly
count = 1    # and we have already one; `2`
x = 2
while count < 1000:
    x += 1
    isPrime = True          # assume it’s a prime
    for p in primes:        # check for every prime
        if x % p == 0:      # if it’s a divisor of the number
            isPrime = False # then x is definitely not a prime
            break           # so we can stop this loop directly

    if isPrime:             # if it’s still a prime after looping
        primes.append(x)    # then it’s a prime too, so store it
        count += 1          # and don’t forget to increase the count

rawDescription: Trouble finding the 1000th prime using python


code:
ITEM_TYPE_MAP = {
    "foo": TextForm,
    "bar": SomeOtherForm,
}

rawDescription: How to instatiate a Django Form dynamically by string?

description: Instatiate a Django Form dynamically by string


code:
def f1(f):
    def f3():
        def f4(*args):
            return f3()(*args)
        return f(f4)

    return f3()

rawDescription: Decoding a Cryptic Python statement

description: Decoding a Cryptic Python statement


code: reduce(addfoo, foos, defaultdict(set))

rawDescription: using map or similar to update a dictionary when not using a class

description: Using map or similar to update a dictionary when not using a class


code: list_bar = [ foo() for _ in xrange(1000000) ]

rawDescription: Python list of Objects taking up too much memory


code:
import pandas
import sys
df = pandas.DataFrame({'a':(1,2,3,4), 'b':(5,6,7,8)})

def bar(row, k):
    axis_i = sys._getframe(2).f_locals['i']
    # data frame the function is applied to
    dataf = sys._getframe(2).f_locals['self']
    axis = sys._getframe(2).f_locals['axis']
    # number of elements along the chosen axis
    n = dataf.shape[(1,0)[axis]]
    if axis_i == 0 or axis_i == (n-1):
        res = 0
    else:
        res = dataf['a'][axis_i - k] + dataf['b'][axis_i + k]
    return res

rawDescription: Apply function over relative rows in Pandas


code:
deck = Deck()
hand = deck.deal(3)
print(" - ".join(map(str, hand)))
if min(hand[0], hand[1]) < hand[2] < max(hand[0], hand[1]):
    print("Winner!")
else:
    print("Loser.")

rawDescription: Python Simple Card Game to Learn Classes


code:
@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
    jsdata = request.form['javascript_data']
    return jsdata

rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


code: [items[k:k+m] for k in range(0,len(items),m)]

rawDescription: Creating new lists with a consistent range of indexes from another list


code:
import re
mystring = re.sub(r"^\W+", "", mystring)

rawDescription: How to remove special characters from the beginning of a string in Python

description: Remove special characters from the beginning of a string in Python


code:
# Get random source from G.node
source = random.choice(G.node)

min_tree = nx.bfs_tree(G, source)
# Accessible nodes are any node in this list, except I need to remove source.

all_accessible = min_tree.node.keys()
all_accessible.remove(source)
target = random.choice(all_accessible.node.keys())

random_path = nx.shortest_path(G, source, target)

rawDescription: More efficient way of running a random traversal of a directed graph with Networkx


code:
A
strel = ndimage.generate_binary_structure(2, 1)
out

rawDescription: Replace values in an 2d array according to neighboring values


code:
from mpl_toolkits.basemap import Basemap

def drawmlat(self, arg1, arg2, kw=something):
    pass

Basemap.drawmlat = drawmlat

rawDescription: How do I add a method to a class from a third-party Python module without editing the original module

description: Add a method to a class from a third-party Python module without editing the original module


code:
records.keys
arr.keys

rawDescription: Store different datatypes in one NumPy array?


code:
from itertools import groupby
from operator import itemgetter

cursor.execute('''select eventid, timestamp, value from table
                  where type="VALUE" order by eventid''')
result = [tuple(chain.from_iterable(r[1:] for r in rows))
          for eventid, rows in groupby(cursor, itemgetter(0))]

rawDescription: Converting database query results from strings to tuples efficiently


code:
from datetime import date

def next_pi_date():
    today = date.today()
    pi_date = date(today.year, 3, 14)
    if pi_date < today:
        pi_date = pi_date.replace(year=pi_date.year + 1)
    return pi_date

rawDescription: Dates ( pi-Day )

description: Dates ( pi-Day )


code:
index = pd.DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'])
df1 = pd.DataFrame({'S':[True,False,False]}, index=index)
df2 = pd.DataFrame({'P':['','On','On']}, index=index)
df3 = pd.DataFrame({'C':['On','On','On']}, index=index)

rawDescription: After Pandas Dataframe pd.concat I get NaNs


rawDescription: Using django exclude filter problem with empty m2m field


rawDescription: slicing tuples backwards - how to handle getting the first element?

description: Slicing tuples backwards - how to handle getting the first element


code:
from collections import OrderedDict
from pymongo import MongoClient
import bson

client = MongoClient()
sample_db = client['sample']
test_col = sample_db['test']

test_col.drop()

data = OrderedDict([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
test_col.insert(data)
print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))

test_col.drop()

data = bson.son.SON([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
test_col.insert(data)
print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))

rawDescription: How to get ordered dictionaries in pymongo?

description: Get ordered dictionaries in pymongo


rawDescription: How to convert a string to a float in python?

description: Convert a string to a float in python


code:
to_morse = {v: k for k, v in morse.items()}

def can_morse(msg):
    return all(ch in to_morse for ch in msg.upper())

msg = "Hello  World"
if can_morse(msg):
    print(" ".join([to_morse[ch] for ch in msg.upper()]))

rawDescription: If String ONLY contains "-" or "."

description: If String ONLY contains "-" or "."


code: valno = self.free_values_start_number + 0

rawDescription: Search range of int values using djapian


code:
import tkinter as ttk

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

def on_variable_change(a,b,c): # `trace` send 3 argument to `on_variable_change`

    #print(a, b, c)

    selected = step_type.get()

    if selected == "Kill":
        goal_label['text'] = "Required Kills"
    elif selected == "Explore":
       goal_label['text'] = "Location ID"
    elif selected == "Conversation":
       goal_label['text'] = "NPC ID"

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

mainframe = ttk.Tk()

# Step Type

step_type = ttk.StringVar() # there is the rule: variable name lowercase with _

ttk.Label(mainframe, text="Step Type").grid(column=1, row=16)

ttk.Radiobutton(mainframe, text="Kill", value="Kill", variable=step_type).grid(column=2, row=16, sticky='E')
ttk.Radiobutton(mainframe, text="Explore", value="Explore", variable=step_type).grid(column=3, row=16, sticky='E')
ttk.Radiobutton(mainframe, text="Conversation", value="Conversation", variable=step_type).grid(column=4, row=16, sticky='E')

step_type.set("Kill")
# use `trace` after `set` because `on_variable_change` use `goal_label` which is not created yet.
step_type.trace("w", on_variable_change)

# Step Goal

step_goal = ttk.StringVar()
goal_label = ttk.Label(mainframe, text="Required Kills")
goal_label.grid(column=1, row=17)
goal_entry = ttk.Entry(mainframe, width=20, textvariable=step_goal)
goal_entry.grid(column=2, row=17, sticky='E')

# --- star the engine ---

mainframe.mainloop()

rawDescription: Check OptionMenu selection and update GUI


code:
def uuid2slug(uuidstring):
    return uuid.UUID(uuidstring).bytes.encode('base64').rstrip('=\n').replace('/', '_')

def slug2uuid(slug):
    return str(uuid.UUID(bytes=(slug + '==').replace('_', '/').decode('base64')))

rawDescription: Convert UUID 32-character hex string into a "YouTube-style" short id and back


code:
import urllib.request
from bs4 import BeautifulSoup
page = 'http://bandcamp_website.com/'
html = urllib.request.urlopen(page).read()
soup = BeautifulSoup(html, 'html.parser')
files = []
for n in soup.find_all('audio'):
    files.append(n.get('src'))
for file in files:
    urllib.request.urlretrieve(file, filename='C:/directories/your_filename')

rawDescription: How to download audio from bandcamp in Python

description: Download audio from bandcamp in Python


code:
parser=argparse.ArgumentParser()
parser.add_argument('--dates', nargs=2, metavar=('START DATE','END_DATE'),
                   help='start date and end date in YYYY-MM-DD')
print(parser.format_help())

rawDescription: Python Optional Argument Pair

description: Python Optional Argument Pair


code:
import sys
from PyQt4 import QtGui, QtCore
from time import strftime

class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.Time)
        self.timer.start(1000)
        self.lcd = QtGui.QLCDNumber(self)
        self.lcd.display(strftime("%S"))
        self.setCentralWidget(self.lcd)
        self.setGeometry(300,300,250,100)

    def Time(self):
        if int(strftime("%S")) % 10 == 0:
            self.timer.setInterval(5000)
        else:
            self.timer.setInterval(1000)
        self.lcd.display(strftime("%S"))

def main():
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: Update QWidget every minutes

description: Update QWidget every minutes


code:
foods = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices', 'I_want_ten_lemon_cookies', 'I_want_four_lemon_juices']

orange=[]
lemon=[]

for food in foods:
    if 'orange' in food.split('_'):
        orange.append(food)
    elif 'lemon' in food.split('_'):
        lemon.append(food)

rawDescription: How to separate a single list into multiple list in python

description: Separate a single list into multiple list in python


code:
[sum(x*y for x, y in zip(list1_choices, list2))
 for list1_choices in itertools.product(list1, repeat=len(list2))]

rawDescription: mulitply list elements in python

description: Mulitply list elements in python


code:
idx = df.sum(axis=1).order(ascending=False).head(3).index
df.ix[idx]

rawDescription: Getting top 3 rows that have biggest sum of columns in `pandas.DataFrame`?


rawDescription: Converting minutes to HH:MM format in Python


code:
def is_consecutive(datelist):
    for idx, my_date in enumerate(datelist[:-1]):
        month_diff = datelist[idx + 1].month - my_date.month
        year_diff = datelist[idx + 1].year - my_date.year
        if ((month_diff == 1 and year_diff == 0) or
            (month_diff == -11 and year_diff == 1)):
            continue
        else:
            return False
    return True

rawDescription: Determine consecutive dates

description: Determine consecutive dates


code:
async def some_func():  # async is used instead of a coroutine decorator
    # Assume SomeObj implements __anext__, __aiter__, __aenter__, and __aexit__
    s = SomeObj()
    async for item in s:  # You can suspend while iterating over s using __anext__
       print(item)

    async with SomeObj() as s: # You can suspend on enter and exit of this context manager using __aenter__ and __aexit__
        await s.some_method() # await is used instead of yield from

rawDescription: Python coroutines on builtin functions

description: Python coroutines on builtin functions


code:
import ast
a = "('TO', 'RP', 'TO')"
b = ast.literal_eval(a)
b
b[0]

rawDescription: using python extract string from a list of string

description: Using python extract string from a list of string


rawDescription: Find indices of large array if it contains values in smaller array


code: [('john', 'john'), ('is', 'john'), ('sleeping', 'john')]

rawDescription: Concatenating items from two lists to form n-grams using python


code: df.apply(standardize, axis=1).mean(1)

rawDescription: python pandas .map double variable lambda

description: Python pandas .map double variable lambda


rawDescription: How to slice middle element from list

description: Slice middle element from list


rawDescription: python pandas: apply a function with arguments to a series

description: Python pandas: apply a function with arguments to a series


code:
class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

fruits = dict(zip(['apple', 'banana'], [Fruit('apple', 'red'), Fruit('banana', 'yellow')]))

print("An apple is %s" % fruits['apple'].color)

rawDescription: Accessing list of Python objects by object attribute


code:
w = 5    # half-size of the window around i, j
p = np.nditer(plan[i-w:i+w, j-w:j+w], flags=...)

rawDescription: Numpy array comparison using nditer

description: Numpy array comparison using nditer


code: str.format(*args, **kwargs)

rawDescription: insert variable values into a string in python

description: Insert variable values into a string in python


code:
def drawTree(self, tree, f):
    id = 0
    nodes = [(None, self)]  # queue with nodes to process

    while nodes:
        parent, node = nodes.pop(0)
        tree.add_node(id, label=node.data, color='goldenrod2', style='filled')

        if parent is not None:
            weight = 1
            if tree.get_node(parent).attr['label'] == str(node.data):
                # same value, increase weight of edge to straighten it.
                weight = 10
            tree.add_edge(parent, id, color='sienna', style='filled', weight=weight)

        if node.left is not None:
            nodes.append((id, node.left))
        else:
            none_id = '{}_left_none'.format(id)
            tree.add_node(none_id, label='', color='goldenrod1', shape='box', style='filled')
            tree.add_edge(id, none_id, color='sienna', style='filled')

        if node.right is not None:
            nodes.append((id, node.right))
        else:
            none_id = '{}_right_none'.format(id)
            tree.add_node(none_id, label='', color='goldenrod1', shape='box', style='filled')
            tree.add_edge(id, none_id, color='sienna', style='filled')

        id += 1

    tree.write(f)
    img = pgv.AGraph(f)
    img.layout(prog='dot')
    img.draw(f.split('.')[0] + '.png')
    img.close()

rawDescription: How to create duplicate nodes in PyGraphviz?

description: Create duplicate nodes in PyGraphviz


code:
import operator

unique_preserve_order(yourlist, key=operator.itemgetter(1))

rawDescription: delete duplicates from list of tuples

description: Delete duplicates from list of tuples


code:
import importlib

i = importlib.import_module("matplotlib.text")

rawDescription: import module from string variable

description: Import module from string variable


rawDescription: Getting matrix from data using pandas or python


rawDescription: Pandas Convert Mixed Types to String

description: Pandas Convert Mixed Types to String