code:
import glob
import os

path = 'C:/Users/me/Desktop/'  # give the path where all the folders are located
list_of_folders = ['test1', 'test2']  # give the program a list with all the folders you need
names = {}  # initialize a dict

for each_folder in list_of_folders:  # go through each file from a folder
    full_path = os.path.join(path, each_folder)  # join the path
    os.chdir(full_path)  # change directory to the desired path

    for each_file in glob.glob('*.cpp'):  # self-explanatory
        with open(each_file) as f:  # opens a file - no need to close it
            names[each_file] = sum(1 for line in f if line.strip())

    print(names)

rawDescription: Going through all folders in Python

description: Going through all folders in Python


code:
map(tuple, map(lambda row:
    [float(row[0]), int(row[1]), parse(row[2])], res))

rawDescription: what is this saying in python

description: What is this saying in python


rawDescription: Python: Export a matrix in csv

description: Python: Export a matrix in csv


rawDescription: How to access this dictionary of dictionaries with a numbered index in Python?

description: Access this dictionary of dictionaries with a numbered index in Python


rawDescription: Get coordinates from a wikipedia page

description: Get coordinates from a wikipedia page


code:
@app.route('/getNoteText',methods=['GET','POST'])
def GetNoteText():
    if request.method == 'POST':
        file = request.files['pic']
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        processImage(filename)
    else:
        return "Y U NO USE POST?"

rawDescription: Uploading image from Android to Python server


code:
def asterix_triangle(i, t=0):
    if i == 0:
        return 0
    else:
        print(' ' * ( i + 1 ) + '*' * ( t * 2 + 1 ))
        return asterix_triangle( i - 1, t + 1 )

asterix_triangle(5)

rawDescription: Asterisk triangle in python

description: Asterisk triangle in python


code:
# Get combinations using itertools.product
combs = np.array(list(product(range(N), repeat=4)))

# Perform L2 norm and elementwise exponential calculations to get final o/p
out = np.exp(-np.sqrt((combs**2).sum(1))**2).reshape(N,N,N,N)

rawDescription: Defining an ndarray in python via a formula


rawDescription: dictionary-based keyword categorization

description: Dictionary-based keyword categorization


rawDescription: How to distinguish left click , right click mouse clicks in pygame?

description: Distinguish left click , right click mouse clicks in pygame


code:
ws = websocket.WebSocketApp("ws://localhost:9999/track",
                                on_open    = on_open,
                                on_message = on_message,
                                on_error   = on_error,
                                on_close   = on_close,
                                header     = {'head1:value1','head2:value2'}
                                )

rawDescription: How to add more headers in websocket python client

description: Add more headers in websocket python client


code:
def __hash__(self):
    return (self.name, self.ID, self.age).__hash__()

rawDescription: Creating unique list of objects from multiple lists


code:
df_cross = pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])
df_cross.columns = ["{0}_{1}".format(l1, l2) for l1, l2 in df_cross.columns]
df_cross

rawDescription: R dcast equivalent in python pandas

description: R dcast equivalent in python pandas


code:
def myFunction2(data, *args, **kwargs):
    if 'key' not in kwargs:
        kwargs['key'] = lambda x: x # identity map (pass without a key)
    return tuple( f(data, key=kwargs['key']) for f in args )

rawDescription: Refactor a couple of functions into one by accepting sets and returning sets


code: out = "".join(c for c in asking if c not in ('!','.',':'))

rawDescription: How to remove all the punctuation in a string? (Python)

description: Remove all the punctuation in a string? (Python)


rawDescription: Pythonic iteration over multiple lists in parallel


code:
def swap(s, i, j):
    lst = list(s);
    lst[i], lst[j] = lst[j], lst[i]
    return ''.join(lst)

rawDescription: Swap characters in string

description: Swap characters in string


code:
from inspect import signature
signature(foo)

rawDescription: Retrieve the names of (and default values of) the arguments accepted by a specified function


code:
Decimal(0.1)
Decimal(0.2)
Decimal(0.3)
Decimal(0.4)
Decimal(0.5)

rawDescription: How to plus one at the tail to a float number in Python?

description: Plus one at the tail to a float number in Python


code:
df1
df2

rawDescription: pandas dataframe join with where restriction

description: Pandas dataframe join with where restriction


code:
def contain(word, letters):
    return not set(letters).isdisjoint(set(word))

rawDescription: Is there a better algorithm for exercise 9.3 in 《Think Python: How to Think Like a Computer Scientist》


code:
from PyKDE4.kdeui import *
icon = KIcon("*The Icon Name*")

rawDescription: System theme icons and PyQt4

description: System theme icons and PyQt4


code:
branch="xyz"
version="12.2"

print ('My Job Name', {'BRANCH_NAME': '{0}'.format(branch) , 'VERSION': '{0}'.format(version) })
# ('My Job Name', {'BRANCH_NAME': 'xyz', 'VERSION': '12.2'})

rawDescription: Python string formatting displays issue

description: Python string formatting displays issue


code:
config_dict = {sect: dict(parser.items(sect)) for sect in parser.sections()} # ozgur's one-liner
del config_dict['root']

rawDescription: using ConfigParser and dictionary in Python

description: Using ConfigParser and dictionary in Python


code:
content = content.replace('Hi', 'hi')
content = content.replace('HELLO', 'hello')

rawDescription: replace certain strings in a file

description: Replace certain strings in a file


code: frequentItems.sort(key = mis.get)

rawDescription: Sort List of string based on value in Dict


code:
pvt = np.vstack([nodes, positions, velocities, times])
pvt = np.ascontiguousarray(pvt.transpose().astype(int))

timer = time()
xjus.addPvtFrame(pvt)
print("Add PVT time to C code: %fs" % (time() - timer))

rawDescription: Improve speed of passing data from Python to C(++) via ctypes


code:
def task(data):
    analyze(data)

rdata = ipp.Reference('data')
ar = view.apply(task, rdata)
result = ar.get()

rawDescription: Sharing queues with ipyparallel cluster

description: Sharing queues with ipyparallel cluster


code:
{
'331418': {'genus': 'Dracunculus', 'specie': 'insignis'},
'331419': {'genus': 'Bejaria', 'specie': 'sprucei'},
'331420': {'genus': 'Paecilomyces', 'specie': 'sp. JCM 12545'},
'331416': {'genus': 'Macromedaeus', 'specie': 'distinguendus'},
'331417': {'genus': 'Physalopteroidea'}
}

rawDescription: Making a dictionary from multiple items in lists


code: print("\n".join(["{}, {} {}OK".format(i, j, "" if i == j else "N") for i, j in izip_longest(a, b, fillvalue="null")]))

rawDescription: Python - diff-like order comparision of 2 lists with unequal sizes,


code:
import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
rows = []
cols = []
vals = []
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int)
            if r > 0:
                index[r] += 1
                rows.append(r-1)
                cols.append(index[r]-1)
                vals.append(i+(j-1)*dy)

outshape = max(rows)+1, max(cols)+1  # now you know the size
output = np.zeros(outshape, np.int)
output[rows, cols] = vals

rawDescription: Python numpy indexing does not work

description: Python numpy indexing does not work


rawDescription: list.__delslice__ python 3

description: List.__delslice__ python 3


code:
# Pass None to use full subset.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args or None).send(item[0])

# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

rawDescription: Whats the pythonic way to handle empty *args when creating a set?


rawDescription: Ignore time offsets in Pandas Dataframe

description: Ignore time offsets in Pandas Dataframe


code:
import sys
import os

fpath = sys.argv[-1]

print(os.path.isabs(fpath))
print(fpath)

rawDescription: Getting file path from command line arguments in python


code:
# import itertools
# l= [list(g) for k,g in itertools.groupby(df.D,lambda x:x in [0]) ]

rawDescription: Python Pandas count interval of occurrence


code: out = [reduce(lambda a, b: a * b, i) for i in zip(x1, x2, x3)]

rawDescription: Reduce list based on index

description: Reduce list based on index


code:
print("Highest scores in descending order:")
for name, scores in highest_scores:
    print_func(name, max(scores))
print("")

print("Highest average scores in descending order:")
for name, scores in highest_averages:
    print_func(name, sum(scores)/float(len(scores)))
print("")

print("Alphabetical order:")
for name, scores in alphabetical_names:
    print_func(name, scores)

rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
class Player(object):
    ...
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)
        # indicates that we are standing on the ground
        # and thus are "allowed" to jump
        self.on_ground = True
        self.xvel = 0
        self.yvel = 0
        self.jump_speed = 10
        self.move_speed = 8

rawDescription: Add collision detection to a plattformer in pygame


rawDescription: Pandas: Creating Column From Previous TimeSeries Value


code:
names = [population[random.randint(0, len(population)-1)] for x in range(5)]
names

rawDescription: randomly choose from list using random.randint in python

description: Randomly choose from list using random.randint in python


code:
dict2 = OrderedDict (sorted(occupants_map.items() ) )

list = dict2.values()
print(list)

rawDescription: Python - I need a collection with negative indices


rawDescription: Get mean value of certain part of array

description: Get mean value of certain part of array


code:
import dis

from_import_src = """
from subprocess import call
foo = call
"""

plain_import_src = """
import subprocess
foo = subprocess.call
"""

from_bytecode = compile(from_import_src, "from_import", "exec")
plain_bytecode = compile(plain_import_src, "plain_import", "exec")

print("from ... import ...")
dis.dis(from_bytecode)

print("\nimport ...")
dis.dis(plain_bytecode)

rawDescription: import module or any component in python

description: Import module or any component in python


code:
class Animal(models.Model):
    name = models.CharField(max_length=30)
    _downcast = None
    # to store the subclass instance, so that
    # subsequent calls don't hit the database

    def speak(self):
        return "I am an animal"

    def downcast(self):
        if self._downcast is None:
            if hasattr(self, 'cat'):
                self._downcast = self.cat
            elif hasattr(self, 'dog'):
                self._downcast = self.dog

        return self._downcast

class Cat(Animal):
    def speak(self):
        """ OVERRIDE """
        return "MEAOO"

class Dog(Animal):
    def speak(self):
        """ OVERRIDE """
        return "WOOOOF"

rawDescription: Access child methods in Python Django

description: Access child methods in Python Django


code: a[:, None] - b

rawDescription: How to efficiently apply an operator to the cartesian product of two arrays?

description: Efficiently apply an operator to the cartesian product of two arrays


code:
class Category(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateField()
    status = models.BooleanField()

rawDescription: Django access m2m model value in template


code:
def magic(s):
    if '/' in s:
        return datetime(s)
    elif '.' in s:
        return float(s)
    else:
        return int(s)

rawDescription: Reading CSV files in numpy where delimiter is ","


code:
import binascii
def to_byte_escapes(b):
   return ''.join('\\x' + binascii.hexlify(byte) for byte in b)

rawDescription: open bin file and convert ascii to hex

description: Open bin file and convert ascii to hex


code:
dict_List = [(x, FID_GC_dict[x]) for x in FID_GC_dict.keys()]

dict_List = [(k,v) for k,v in FID_GC_dict.iteritems()]

rawDescription: Sorting a nesting list by the first item -- itemgetter not doing the trick


code:
@login_required
def index():
    return render_template('index.html',
                            title='test home title')

rawDescription: I need help following along this decorator. And confirmation if I'm correct


code:
def servos(**kwargs):
    for k, v in kwargs.iteritems():
        kwargs[k] = servo.Servo(*v)
    return kwargs

rawDescription: Preferred way to format a dictionary being passed to a function?


rawDescription: Perfect numbers in python

description: Perfect numbers in python


code:
n = 0xdeadbeef
x = format(n, 'x')
s = re.sub('(..)', r'\\x\1', x)
# or s = ''.join(r'\x{}{}'.format(*b) for b in pairwise(x))
# or s = ''.join(r'\x' + x[i:i+2] for i in range(0, len(x), 2))

rawDescription: Pythonic way to convert an integer into a hex-escaped string


code: strLst = 'I am student'.split()

rawDescription: How to alphabetize a column?

description: Alphabetize a column


code:
from multiprocessing import Process, Manager

def f(L):
    row = L[0] # take the 1st row
    row.append(10) # change it
    L[0] = row #NOTE: important: copy the row back (otherwise parent
               #process won't see the changes)

if __name__ == '__main__':
    manager = Manager()

    lst = manager.list()
    lst.append([1])
    lst.append([2, 3])
    print(lst) # before: [[1], [2, 3]]

    p = Process(target=f, args=(lst,))
    p.start()
    p.join()

    print(lst) # after: [[1, 10], [2, 3]]

rawDescription: Can I create a shared multiarray or lists of lists object in python for multiprocessing?

description: Create a shared multiarray or lists of lists object in python for multiprocessing


code:
t_pos = numpy.copy(posVec)
t_dir = numpy.copy(dirVec)

rawDescription: Numpy array values changed without being aksed?


code:
import re

name='Courtney'

with open("old_text.txt") as f:
   txt = f.read()
   new_txt=re.sub(r'(\b{}\b.*?)(\s*\{}\b\s*)'.format(name,name),'\1',txt,re.S)

rawDescription: Deleting every second occurence of a word in a txt file (Python)


code:
searchfor = ['og', 'at']
s[s.str.contains('|'.join(searchfor))]

rawDescription: pandas test if str contains one of a list

description: Pandas test if str contains one of a list


rawDescription: How do I copy the formatting of a number to another number?

description: Copy the formatting of a number to another number


code:
def parse_file(file):
    id = ''
    gene = ''

    for line in file:
        if line.startswith('>'):
            if gene:
                yield id, gene

            id = line[1:]
            gene = ''
        else:
            gene += line.strip()
    else:
        yield id, gene # Final gene

rawDescription: Rewind File Pointer to Previous Line Python File IO


code: {{ content|safe }}

rawDescription: How to modify certain part of Django content by adding <span>, while keeping the original format of paragraph text?

description: Modify certain part of Django content by adding <span>, while keeping the original format of paragraph text


rawDescription: Application Layout with Groups of single items in Python


code:
def isOverflow(num, width=32):
    if num > 0:
        if num >> width-1:
            return True
    elif num < 0:
        if abs(num) > (1 << width - 1):
            return True
    return False

rawDescription: Detect int32 overflow using 0xFFFFFFFF masking in Python?


code:
import requests
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=3)
b = requests.adapters.HTTPAdapter(max_retries=3)
s.mount('http://', a)
s.mount('https://', b)
s.get(url)

rawDescription: Cleanly setting max_retries on Python requests get or post method


code: b''.join(chr(x) for x in xors)

rawDescription: How to xor in python using hex

description: Xor in python using hex


code: coffeeA_df.apply(lambda row: users_df[(users_df['Epoch'] - row['Epoch'] / 1000).abs() < timeWindow].iloc[0], axis=1)

rawDescription: In Pandas, how to find occurrence of one value from one dataframe in another dataframe?


code:
product_values = []
for value in product_value:
    value = value.strip() # get rid of any excess whitespace
    value = float(value) # ProductValue appears to be a float of some sort
    product_values.append(value) # store the value

rawDescription: How do I Extract a Javascript Value using Regular Expressions?


code:
@asyncio.coroutine
def do_connect():
    global tcp_server  # Make sure we use the global tcp_server
    while True:
        try:
            tcp_server = yield from loop.create_connection(TcpClient,
                                                           'localhost', 8000)
        except OSError:
            print("Server not up retrying in 5 seconds...")
            yield from asyncio.sleep(5)
        else:
            break

rawDescription: How to reconnect a socket on asyncio?

description: Reconnect a socket on asyncio


rawDescription: How to autodoc a function inside a method in Sphinx

description: Autodoc a function inside a method in Sphinx


code:
import rpy2.robjects as robjects
robjects.r['load'](".RData")

rawDescription: Loading .RData files into Python

description: Loading .RData files into Python


rawDescription: How do I get a whole number as a result for a cube root?

description: Get a whole number as a result for a cube root


rawDescription: subprocess.Popen in different console

description: Subprocess.Popen in different console


code:
#Creating a player object
player = Player(0,0,playerimage)

#When you want to draw the player object use its draw() method
player.draw()

#Same for moving the player object
#I have included an event loop to show an example
#I used the arrow keys in this case
speedx = 0
speedy = 0

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            speedy = -5
            speedx = 0
        elif event.key == pygame.K_DOWN:
            speedy = 5
            speedx = 0
        elif event.key == pygame.K_RIGHT:
            speedy = 0
            speedx = 5
        elif event.key == pygame.K_LEFT:
            speedy = 0
            speedx = -5
    elif event.type == pygame.KEYUP:
        speedx = 0
        speedy = 0

#Now after you event loop in your object updates section do...
player.move(speedx,speedy)
#And be sure to redraw your player
player.draw()

#The same idea goes for other objects such as obstacles or even scrolling backgrounds

rawDescription: Using classes in Pygame

description: Using classes in Pygame


code:
# Assuming df is the input DataFrame
mask = pd.Series(True, index=df.index)
if condition_id:
    mask &= df['condition_id'] == condition_id
if subject_id:
    mask &= ...

rawDescription: Filter Pandas DataFrame depending on whether the filter value is specified


code:
arr>15
arr[arr>15]

rawDescription: Python 2D NumPy array comprehension

description: Python 2D NumPy array comprehension


rawDescription: Formatting an unordered string in python


code: np.full((12), [' '],dtype=str)

rawDescription: creating a numpy array filled with a character

description: Creating a numpy array filled with a character


code:
maxsort = counts.argsort()[::-1]
(unique[maxsort],counts[maxsort])

rawDescription: how to find most frequent string element in numpy ndarray?

description: Find most frequent string element in numpy ndarray


rawDescription: Compare Sequences Python

description: Compare Sequences Python


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: result = np.split(extracted, indices[1:-1])

rawDescription: Multiple lists of indices for one array in numpy


code:
class MyForm(forms.ModelForm):
    model = MyModel
    exclude = ['field']

rawDescription: Model field blank=false doesn't work when field is readonly in admin.py


code:
app = QtGui.QApplication(sys.argv)

widget = QtGui.QLabel()
widget.setGeometry(50,200,500,500)
renderer =  QtSvg.QSvgRenderer('Zeichen_123.svg')
widget.resize(renderer.defaultSize())
painter = QtGui.QPainter(widget)
painter.restore()
renderer.render(painter)
widget.show()

sys.exit(app.exec_())

rawDescription: Simple way to display SVG image in a PyQt window


code:
unique = set([ 'one', 'two', 'two'])
len(unique) # is 2

rawDescription: Counting the number of unique words in a list


rawDescription: Invert position of sublists

description: Invert position of sublists


code:
prev_occurrence = None
for occurrence in sorted( occurrence for seq_patt in SequencePattern.seq_patterns for occurrence in seq_patt.occurrences ):
    if prev_occurrence and ( occurrence[ 0 ] == prev_occurrence[ 0 ] ) and ( occurrence[ 1 ] - prev_occurrence[ 1 ] == 1 ):
        print( '# prev_occurrence %s occurrence: %s' % ( prev_occurrence, occurrence, ))
    prev_occurrence = occurrence

rawDescription: How to perform this sort operation in python

description: Perform this sort operation in python


rawDescription: Variable number of arguments and recursion in Python


code:
import pandas as pd
import csv

test = pd.read_csv("output/Emails.csv", quoting=csv.QUOTE_NONE, error_bad_lines=False)

print (test.shape)
#(381422, 22)

rawDescription: Not reading all rows while importing csv into pandas dataframe


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

def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
        return None

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

def near(a, b, rtol=1e-5, atol=1e-8):
    return abs(a - b) < (atol + rtol * abs(b))
def crosses(line1, line2):
    """
    Return True if line segment line1 intersects line segment line2 and
    line1 and line2 are not parallel.
    """
    (x1,y1), (x2,y2) = line1
    (u1,v1), (u2,v2) = line2
    (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
    e, f = u1-x1, v1-y1
    denom = float(a*d - b*c)
    if near(denom, 0):
        # parallel
        return False
    else:
        t = (e*d - b*f)/denom
        s = (a*f - e*c)/denom
        # When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the
        # line segments
        return 0<=t<=1 and 0<=s<=1

for Fs in np.linspace(70e3,200e3,4):
    Vo_sweep = np.linspace(0,1,1000)
    delta_I = [i*Fs*np.log((i+1.1)/10) for i in range(len(Vo_sweep))] #[I_max(Vo) for Vo in Vo_sweep]
    plt.plot(Vo_sweep,delta_I)

plt.vlines(0.71,min(delta_I),max(delta_I))

for Fs in np.linspace(70e3,200e3,4):
    x = np.linspace(0,1,1000)
    y = [i*Fs*np.log((i+1.1)/10) for i in range(len(Vo_sweep))]
    for i in range(1,len(delta_I)):
        p1 = np.array([x[i-1],y[i-1]],dtype='float')
        p2 = np.array([x[i],y[i]],dtype='float')
        k1 = np.array([0.71,min(delta_I)],dtype='float')
        k2 = np.array([0.71,max(delta_I)],dtype='float')
        if crosses((p2,p1),(k1,k2)):
            seg = line_intersection((p2,p1),(k1,k2))
            plt.scatter(seg[0],seg[1],c='red',s=90)
            print(seg)

plt.ylim(min(delta_I),max(delta_I))
plt.xlim(0,1)

plt.show()

rawDescription: Show interception values, matplotlib

description: Show interception values, matplotlib


code:
x = [('a', 'c', 'e'), ('k', 'n')]
y = [('e', 'd', 'w'), ('c', 'a', 'e'), ('n', 'k')]
set_x = set(frozenset(a) for a in x)
set_y = [frozenset(a) for a in y]
[y_element in set_x for y_element in set_y]

rawDescription: Looking for an elegant way of finding the intersection between two lists of words' tuples in different orders


code:
def convertMac(octet):
    mac = [binascii.b2a_hex(x) for x in list(octet)]
    return ":".join(mac)

rawDescription: How to convert from hex-encoded string to a "human readable" string?

description: Convert from hex-encoded string to a "human readable" string


code:
class AjaxApp(Flask or Blueprint):

    def ajax_route(self, rule, **options):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                if request.method == 'POST':
                    return f(*args, **kwargs)
                return render_template("masterPage.html")

            endpoint = options.pop('endpoint', None)
            methods = options.pop('methods', ['GET', 'POST'])
            self.add_url_rule(rule, endpoint, wrapper, methods=methods, **options)
            return wrapper
        return decorator

rawDescription: How to redirect from a CatchAll method without being re-catched in Python/Flask

description: Redirect from a CatchAll method without being re-catched in Python/Flask


code:
import pandas as pd
writer = pd.ExcelWriter('path\\to\\output\\file.xls')

i = 1
for csvfile in glob.glob(os.path.abspath('D:\csvjoin\*.csv')):
    df = pd.read_csv(csvfile)
    df.to_excel(writer, 'sheet%s' % i)
    i += 1

writer.save()

rawDescription: joining two .xls file into a single .xls file with 2 sheets

description: Joining two .xls file into a single .xls file with 2 sheets


code:
class MyTestCase(BaseTestCase):
    @classmethod
    def setUpClass(cls):
        # Call SetUpClass from parent (BaseTestCase)
        super(MyTestCase, cls).setUpClass()
        # Do more stuff...

rawDescription: When running a method from a Python superclass, how can I know the name of the child class that invoked it?


code:
uniq=set()
for i in l: # O(n), n=|l|
    if not (i in uniq or tuple([i[1], i[0], i[2]]) in uniq): # O(1)-Hashtable
            uniq.add(i)

list(uniq)

rawDescription: filter out "reversed" duplicated tuples from a list in Python

description: Filter out "reversed" duplicated tuples from a list in Python


code:
while True:
    name = input("What is your name? ")
    if name.isalpha():
        break
    else:
        print("Make sure to enter your actual name.")
        continue

rawDescription: How would I disallow numbers as input?

description: How would I disallow numbers as input


code:
SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'import.path.to.email_check',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details'
)

rawDescription: Filtering or restricting Google-Oauth2 login to a set of users in Django using Python Social Auth


code: exec(c, {"public": public, "secret":lambda: print("Haha! Doppelganger.")})

rawDescription: Creating a simple scripting language in Python


code: burp = Card('SPADES')

rawDescription: How to get a retrieve a string from a tuple directly?

description: Get a retrieve a string from a tuple directly


code:
def crawl_recursive(self, response):
    if response.meta["present_depth"] > response.meta["depth_limit"]:
        #too deep!
        return []

rawDescription: How to set different depth limits for different websites when crawling in python scrapy?

description: Set different depth limits for different websites when crawling in python scrapy


code:
class MyDict(dict):
    def my_method(self, a_tuple):
        return my_func(self, a_tuple)

rawDescription: building a class from functions in python

description: Building a class from functions in python


code:
a_dict = AliasDefaultDict(dict)
a_dict['food', 'canned_food']['spam'] = 'delicious'
a_dict['food']
a_dict['canned_food']
a_dict

rawDescription: 2d dictionary with many keys that will return the same value


code:
g = df.groupby(["unique_id", "period_id"], as_index=False)
g.transform("max")
df.update(g.transform("max"))
g.nth(0)

rawDescription: Pandas - remove duplicate rows except the one with highest value from another column


code:
mm = m[:, np.newaxis]
mm.dot(C)
(mm.T).dot(C)
C.dot(mm)

rawDescription: What is the difference between using matrix multiplication with np.matrix arrays, and dot()/tensor() with np.arrays?


code:
class Player():
    def __init__(self):
        print("here")

rawDescription: In python, how do I call a class multiple times and have randint be random?


code:
from PyQt4 import QtGui

if __name__ == '__main__':
    app = QtGui.QApplication([])
    label = QtGui.QLabel()
    icon =  app.style().standardIcon(QtGui.QStyle.SP_MessageBoxWarning)
    label.setPixmap(icon.pixmap(32))
    label.show()
    app.exec_()

rawDescription: How do I add StandardPixmap to a layout?

description: Add StandardPixmap to a layout


code: rdf.unstack(['First', 'Third']).reorder_levels(['First', 'Second', 'Third'], axis=1).sortlevel(0, axis=1)

rawDescription: Add a column with a groupby on a hierarchical dataframe


code: df1 = df.filter(regex='cm')

rawDescription: How to process column names and create new columns

description: Process column names and create new columns


code:
import simplejson
simplejson.dumps({'foo': 'bar'})
simplejson.loads(_)

rawDescription: How do I serialize a Python dictionary into a string, and then back to a dictionary?

description: Serialize a Python dictionary into a string, and then back to a dictionary


rawDescription: python create list from text file

description: Python create list from text file


code: dict1.update((k, dict2[k]) for k in dict1.viewkeys() & dict2.viewkeys())

rawDescription: Update dict without adding new keys?

description: Update dict without adding new keys


code:
from collections import defaultdict

grid = ['094G.016', '094G.019', '194P.005', '194P.015', '093T.021', '093T.102', '094G.032']
d = defaultdict(list)

for item in grid:
    k,v = item.split('.')
    d[k].append(v)

result = ['%s.%s' % (k, '/'.join(v)) for k, v in d.items()]

rawDescription: Python: How to evaluate a part of each item in a list, and append matching results?


code:
aList = ['a','b','c']
for i,x in enumerate(aList):
    print(i,x)

rawDescription: JSON, lists and recursion in python

description: JSON, lists and recursion in python


code:
import itertools

class PhoneWords(object):
    letters = {
        2: 'abc',
        3: 'def',
        4: 'ghi',
        5: 'jkl',
        6: 'mno',
        7: 'pqrs',
        8: 'tuv',
        9: 'wxyz'
    }

    def __init__(self, num_string):
        self.num = [int(i) for i in num_string]                 # => [3, 4]
        self.chars = [PhoneWords.letters[i] for i in self.num]  # -> ['def', 'ghi']

    def __iter__(self):
        return (''.join(letters) for letters in itertools.product(*self.chars))

rawDescription: custom permutation python?

description: Custom permutation python


code:
def using_apply(df):
    grouped = df.groupby(pd.TimeGrouper('1H'))
    result = grouped.apply(foo).unstack(-1)
    result = result.sortlevel(axis=1)
    return result[['radiation', 'tamb', 'new_column']]

def foo(grp):
    radiation = grp['radiation'].sum()
    tamb = grp['tamb'].mean()
    cnt = grp['tamb'].count()
    return pd.Series([radiation, tamb, cnt], index=['radiation', 'tamb', 'new_column'])

rawDescription: insert new non-existing column in how= of resample

description: Insert new non-existing column in how= of resample


code:
out = StringIO()
fmt = lambda x: '{0:.2f}'.format(x) if pd.notnull(x) else 'Ted'
df.to_html(out,float_format=fmt)
out.getvalue()

rawDescription: pandas to_html no value representation

description: Pandas to_html no value representation


code: cpyright = ''.join(["My Super App ", unichr(169), " 2012"])

rawDescription: Copyright symbol for a Pyramid app

description: Copyright symbol for a Pyramid app


code:
nameList = ["grade 1", "grade 2222222222", "grade 3"]
gradeList = ["1/1", "2/2", "100000/100000"]

fmt = '{:<8}{:<20}{}'

print(fmt.format('', 'Assignment', 'Grade'))
for i, (name, grade) in enumerate(zip(nameList, gradeList)):
    print(fmt.format(i, name, grade))

rawDescription: Printing 2 evenly populated lists side by side evenly


code: data = np.zeros(250,dtype='float32, (250000,2)float32')

rawDescription: Making my NumPy array shared across processes


code:
from functools import reduce

def calc_diff(state, val):
    max=state[-1]['max']
    diff=max-val
    if (diff<0): max=val
    state.append({'max': max, 'diff': diff})
    return state

in_list=[1,2,1,2,3,1]

states=reduce(calc_diff, in_list, [{'max': 0}])[1:]

result=list(map(lambda s: [0, s[0]], filter(lambda s: s[1]['diff']>0.1, enumerate(states))))

rawDescription: filtering array with conditional control variables in python to create numpy matrix

description: Filtering array with conditional control variables in python to create numpy matrix


code:
a = [6]
b = [6,7,8]
c = [item for item in b if item in a]
c

rawDescription: Compare unequal lists

description: Compare unequal lists


code:
def count(n):
    occurrences = 0
    for i in range(n, 0, -1):  # i -> n, n-1, n-2, ... 3, 2, 1
        occurrences += i//2    # add whole number of 2's in this value of i
    return occurrences

print(count(10))  # 25
print(count(9))   # 20

rawDescription: Python -- divisibility and count

description: Python -- divisibility and count


code:
import re

def change_string(string, replacement):
    def repl(match):
        o, c = match.group('open'), match.group('close')
        if o + c in ('..', "''", '()'):
            return '{}{}{}'.format(o, replacement, c)
        return match.group(0)
    return re.sub(r"(?P<open>['.(]).*?(?P<close>['.)])", repl, string)

rawDescription: Replace generic string with something else in python


rawDescription: Python: Read hex from file into list?

description: Python: Read hex from file into list


code:
try:
  a = x
except NameError:
  a = y

rawDescription: What is the most Pythonic way to provide a fall-back value in an assignment?


code:
from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
     'This is the first document.',
     'This is the second second document.',
     'And the third one.',
     'Is this the first document?'
     ]

X = TfidfVectorizer(preprocessor=preProcess)
X.fit(corpus)
X.get_feature_names()

rawDescription: How can I pass a preprocessor to TfidfVectorizer? - sklearn - python

description: Pass a preprocessor to TfidfVectorizer? - sklearn - python


code:
section_a_cost = 0
section_b_cost = 0
section_c_cost = 0

rawDescription: How do I repeat this and save the result for each section?

description: Repeat this and save the result for each section


code:
issuer
website

rawDescription: Key to Value to Key in Python Dictionary


code:
# -*- mode: python -*-

block_cipher = None

a = Analysis(['HelloWidget.py'],
             pathex=['C:\\Users\\spearsc\\Documents\\python_projects\\HelloWorldGui'],
             binaries=None,
             datas=[('.\mainwindow.ui', '.')],
             hiddenimports=['PySide.QtXml'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='HelloWidget',
          debug=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='HelloWidget')

rawDescription: PyInstaller error with PySide

description: PyInstaller error with PySide


code:
ar = a.reshape(a.shape[0],-1)
a[sortidx][np.append(True,(np.diff(ar[sortidx],axis=0)!=0).any(1))]
dims = np.append(1,(ar[:,:-1].max(0)+1).cumprod())
a[np.unique(ar.dot(dims),return_index=True)[1]]

rawDescription: Finding duplicate matrices in Python?

description: Finding duplicate matrices in Python


rawDescription: Terminate a sockert.recv in a thread in Python


code:
def whois(k,  i):
    k = k[i]
    who = check_output(['whois',  k], universal_newlines=True)
    print(who)
    return  dict(map(str.strip,ele.split(":",1)) for ele in re.findall('\w+:\s+.*', who))
d = whois([1,1,1,1, "216.58.208.228"],4)

print(d["NetHandle"])
from pprint import pprint as pp
pp(d)

rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


rawDescription: Converting html source content into readable format with Python 2.x


code:
x = [1, 2, 3]
[x[a:b + 1] for a in range(len(x)) for b in range(a, len(x))]

rawDescription: How to create subsequences for sequence e.g. [1,2,3] not including non-adjacent subsequences (e.g. [1,3]) in Python

description: Create subsequences for sequence e.g. [1,2,3] not including non-adjacent subsequences (e.g. [1,3]) in Python


rawDescription: Iterating through a Pandas Dataframe

description: Iterating through a Pandas Dataframe


code:
import collections
def top5_words(text):
    counts = collections.Counter(text.split())
    return [elem for elem, _ in counts.most_common(5)]
top5_words("""As the title says, I need to write a code that returns a list of 5 words (from an input string) that have the highest frequency. This is what I have so far""")

rawDescription: Python - Return top 5 words with highest frequency


code:
string = "a descriptor dps foo 23 bar fd quux"
patterns = ["dps", "23", "fd"]
reduce(lambda s, pat: s.split(pat, 1)[0], patterns, string)
reduce(lambda s, pat: s.split(pat, 1)[0], patterns, "uiopuiopuiopuipouiop")

rawDescription: Slice a string after a certain phrase?

description: Slice a string after a certain phrase


code:
from flask import abort, request

@app.before_request
def limit_remote_addr():
    if request.remote_addr != '10.20.30.40':
        abort(403)  # Forbidden

rawDescription: How to limit Flask dev server to only one visiting ip address

description: Limit Flask dev server to only one visiting ip address


rawDescription: Not Getting proper links from google search results using mechanize and Beautifulsoup


code:
corrections = Series(correct_spellings, index=incorrect_spellings)
new_data_corrected = new_data.replace(corrections)

rawDescription: Spelling Correction in a Dataframe Object , Python


rawDescription: python regex inserting a space between punctuation and letters

description: Python regex inserting a space between punctuation and letters


code:
from collections import Counter
Counter("aab")
Counter("abb")
Counter("aab") == Counter("abb")
Counter("aab") == Counter("aba")

rawDescription: Why does this Python Dict code work?

description: Why does this Python Dict code work


code:
from itertools import dropwhile

for files in filepath:
    with open(files, 'r') as f:
        dropped = dropwhile(lambda _line: "Abstract" not in _line, f)
        next(dropped,"")
        for line in dropped:
                print(line)

rawDescription: How to only read lines in a text file after a certain string using python?

description: Only read lines in a text file after a certain string using python


code:
now = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
results = MyTable.objects.filter(datetime_field__gte=now)

rawDescription: Add custom SQL into WHERE clause in Django, without using .raw()


code:
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
    # Running on production App Engine, so use a Google Cloud SQL database.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '/cloudsql/project-id:instance-name',
            'NAME': 'database-name',
            'USER': 'root',
        }
    }
elif os.getenv('SETTINGS_MODE') == 'prod':
    # Running in development, but want to access the Google Cloud SQL instance in production.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'INSTANCE': 'cloud-sql-instance-ip-address',
            'NAME': 'database-name',
            'USER': 'root',
            'PASSWORD': 'password',
        }
    }
else:
    # Running in development, so use a local MySQL database.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'database-name',
            'USER': 'username',
            'PASSWORD': 'password',
        }
    }

rawDescription: How to run Django management commands against Google Cloud SQL

description: Run Django management commands against Google Cloud SQL


code:
import asyncio
import requests

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = yield from future1
    response2 = yield from future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

rawDescription: How could I use requests in asyncio?

description: How could I use requests in asyncio


rawDescription: Make use of binary operation sign in a variable


code:
y = ["a", "b", "c", "l"]
s = ["banana split", "lumberjack"]
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

rawDescription: For loop with If not working as expected


code:
class Transactionlog(Base):
    ...
    @classmethod
    def copy(cls, t):
        t_new = cls()
        t_new.tlog_newData = t.tlog_newData
        ...

rawDescription: Re-using a sqlalchemy ORM object to insert multiple records


code:
def lookup(x):
    return something

data = lookup(request)
open(output, 'w').write(data)

rawDescription: Looking up content and exporting results


rawDescription: override y axis tick labels without affecting the graph shape in pyplot

description: Override y axis tick labels without affecting the graph shape in pyplot


code:
to_remove = set()
for f1 in lst:
    if f1 in to_remove:
        continue
    for f2 in lst:
        if f2 in to_remove:
            continue
        if f1 != f2 and f1.intersect(f2):
            if f1.score >= f2.score:
                to_remove.add(f2)
            else:
                to_remove.add(f1)
lst = [x for x in lst if x not in to_remove]

rawDescription: Python 2.7 delete items form list while looping


rawDescription: parse and rearrange hostnames

description: Parse and rearrange hostnames


code:
values = B[range(B.shape[0]), C]
values

rawDescription: Efficent insertion of not aligned elements in a numpy array


code:
class MyContainer:
   pass

a = MyContainer()
a.x = Foo()
a.y = Foo()

a.x.DoFoo()

rawDescription: Object trees in Python

description: Object trees in Python


code: [ (m, d[m]) for m in maxima ]

rawDescription: Find sequence in two Numpy arrays

description: Find sequence in two Numpy arrays


code:
Food
Person
Food
Vehicle
Food

rawDescription: Python - reading complex lines of text into dictionary


rawDescription: How do I compose a frequency list from unique arrays of different length in numpy

description: Compose a frequency list from unique arrays of different length in numpy


rawDescription: Converting an open curve to a list of ordered pixels: a Python test code with numpy


code:
Cap_Austria = EntryTemplate(root, 'default text')
Cap_Austria.pack(side = RIGHT)

City = Cap_Austria.get()

rawDescription: How can I use the get() function to turn the answer in the entry() box into a string

description: Use the get() function to turn the answer in the entry() box into a string


code:
import numpy as np
Y = np.sum((X - X[:,None,:])**2,2)

rawDescription: Can I do (x_i-x_j)^T(x_i-x_j) for x_i, x_j are rows in a X matrix with numpy native function instead of loop

description: Do (x_i-x_j)^T(x_i-x_j) for x_i, x_j are rows in a X matrix with numpy native function instead of loop


code:
sentence = 'The quick brown fox jumps over the lazy dog'
sum(1 for word in sentence.split() if len(word) >= 4)
sum(len(word) >= 4 for word in sentence.split())

rawDescription: Count each list element with min 4 chars


rawDescription: AJAX jQuery on click dynamically created only works first time


code:
from nose_parameterized import parameterized

class TestSequence(unittest.TestCase):
    @parameterized.expand([
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    ])
    def test_sequence(self, name, a, b):
        self.assertEqual(a,b)

rawDescription: How to generate dynamic (parametrized) unit tests in python?

description: Generate dynamic (parametrized) unit tests in python


code: Peers.select().where((Peers.user == 'foo') & (Peers.deleted >> None))

rawDescription: Peewee syntax for selecting on null field


code: ids = df.groupby(['FName', 'LName']).id.apply(lambda x: list(x)[-1])

rawDescription: matching between two columns and taking value from another in pandas

description: Matching between two columns and taking value from another in pandas


code:
class Rifle(object):
    def __init__(self, player):
        self.ammo = 10
        self.player = player
        self.player.check()

rawDescription: Why cant I access a property of an instance from another class?


code:
npzfile = numpy.load('file.npz')
npzfile
npzfile['a']
npzfile['b']
npzfile['c']

rawDescription: How to save big (not huge) dictonaries in Python?

description: Save big (not huge) dictonaries in Python


code:
from time import sleep
def fade(color, direction, step, delay=0):
    ...
    for i in range(100, 0, step):
        ...
        sleep(delay)
    return fade(color, direction, step, delay=delay)

rawDescription: LED fade in python - implementing multithreading


code:
@user_passes_test(lambda u: u.groups.filter(name='company').exists())
def company_view(request):
    ...

rawDescription: How to add a Group to every Instance of a Model

description: Add a Group to every Instance of a Model


code:
def distant_pairs(n):
    for d in range(n, 0, -1):
        for i in range(n-d):
            yield (i, i+d)

rawDescription: Fastest way to get pairs from a list ordered by their distance in the list


code:
import datetime
import csv

WEEK = datetime.timedelta(weeks=1)
DAY = datetime.timedelta(days=1)
MONTH = datetime.timedelta(days=30)

# read the entire file to memory in a dict keyed by date
data = {}
with open('file.csv') as csvfile:
    for row in csv.DictReader(csvfile):
        data[datetime.datetime.strptime(row['date'], '%d/%m/%y').date()] = row

rawDescription: Python question relating to dated values in a csv file


code: print([v for k,v in myclass.__dict__.items() if not k.startswith("__")])

rawDescription: Python 2.7: How to get the list of static variables in a class?


code:
bool(re.match('he', 'Hello', re.I))
bool(re.match('el', 'Hello', re.I))

rawDescription: Case-insensitive string startswith in Python


code: from itertools import groupby

rawDescription: De-duplicating list of tuples, prefering certain ones


rawDescription: Python: How to find properties of items in a series


code:
# Import request if you haven't.
from flask import request

@app.route('/new_upload', methods=['GET', 'POST'])
@login_required
def upload_file():

    if request.method == 'POST':
        # This will be executed on POST request.
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash("File uploaded: Thanks!", "success")
            return redirect(url_for('upload_file'))

    # This will be executed on GET request.
    return render_template('upload.html')

rawDescription: Bad Request(400) when upload file, Flask


code:
def get_names(input_dictionary):
    list_of_keys = []
    for item in input_dictionary.iteritems():
        list_of_keys.append(item[0])
    return list_of_keys

rawDescription: Get a list of a dictionary's key names

description: Get a list of a dictionary's key names


code:
def dictionary(words):
    result = {}
    for word in words:
        word = word.strip()
        result[word] = 'yupp!'
    return result

with open('words.txt') as fin:
    result = dictionary(fin)
    print('the' in result)

rawDescription: pulling a dictionary out of the function that created it (python)

description: Pulling a dictionary out of the function that created it (python)


code:
scores = [...]
roundedScores = [int(score) for score in scores]

rawDescription: How to change variables fed into a for loop in list form

description: Change variables fed into a for loop in list form


code:
from django.db.models.signals import post_save

# Your models ...

def increase_nation_counter(instance, created, **kwargs):
    if created: # Just increase counter if it's a new Entry
        instance.nation.counter += 1
        instance.nation.save()

post_save.connect(increase_nation_counter, sender=Entry)

rawDescription: How to keep track of how many foreign keys are connected to an object?

description: Keep track of how many foreign keys are connected to an object


code:
from tkinter import *

def Dialog1Display():
    Dialog1 = Toplevel()
    Dialog1.geometry("100x100")

def Dialog2Display():
    Dialog2 = Toplevel()
    Dialog2.geometry("1000x1000")

master=Tk()

Button1 = Button(master, text="Small", command=Dialog1Display)
Button2 = Button(master, text="Big", command=Dialog2Display)

Button1.pack()
Button2.pack()
master.mainloop()

rawDescription: Can I adjust the size of message box created by tkMessagebox?

description: Adjust the size of message box created by tkMessagebox


code:
from sqlalchemy import func
object.data = func.compress(mydata)
session.add(object)
session.commit()

rawDescription: mysql Compress() with sqlalchemy

description: Mysql Compress() with sqlalchemy


code:
def abDucks (a,b):
    while (a - b >= 1):
        print(a, "Little Ducks swimming in the sea")
        print("And if ",b," Little Ducks should accidentally drown")
        print("There'll be ", (a-b), "Little Ducks swimming in the sea\n")
        a -= b
    else:
        print(a, "Little Ducks swimming in the sea")
        print("And if ",b," Little Ducks should accidentally drown")
        print("There'll be no Little Ducks swimming in the sea\n")

rawDescription: Need help on Python Decrementing

description: Need help on Python Decrementing


code:
import re
re.findall('(?:"[^"]*"|.)+', text)

rawDescription: parsing a string in python: how to split newlines while ignoring newline inside quotes

description: Parsing a string in python: how to split newlines while ignoring newline inside quotes


code: patt = r'({0},? )+{1} {0}'.format(noun_patt, conj_patt)

rawDescription: Find Pattern in Textfile From Several Elements In Several Lists?


rawDescription: Passing unique dictionary addresses to class instances


code:
freqs = np.linspace(49, 51, 1000)
pows = np.array([goertzel(x, ff, sfreq) for ff in freqs])

fig, ax = plt.subplots(1, 1)
ax.plot(freqs, pows, label='DFT coefficients')
ax.set_xlabel('Frequency (Hz)')
ax.legend(loc=1)

rawDescription: Efficiently compute 50Hz content of signal


code:
startstring = 'ACCGXXCXXGTTACTGGGCXTTGT'
array = startstring.split('X')

rawDescription: DNA sequencing using python

description: DNA sequencing using python


code:
approx1 = approxAnswer.next()
approx2 = approxAnswer.next()

rawDescription: fixed point iteration algorithm

description: Fixed point iteration algorithm


rawDescription: Nested dictionaries in classes

description: Nested dictionaries in classes


code: graph.es["weight"] = range(g.ecount())

rawDescription: igraph: how to use add_edges when there are attributes?

description: Igraph: how to use add_edges when there are attributes


rawDescription: iterating over a list by a certain number

description: Iterating over a list by a certain number


code:
from urlparse import urlparse, parse_qs
qs = urlparse("http://example.com/hello?q=1&b=1").query
parse_qs(qs)

rawDescription: Calling cgi.FieldStorage for an arbitrary url


code:
class O(object):
    c = str.capitalize
    r = str.replace
    s = str.strip

def process_line(line, *ops):
    i = iter(ops)
    while True:
        try:
            op = i.next()
            args = i.next()
        except StopIteration:
            break
        line = op(line, *args)
    return line

rawDescription: Defining dynamic functions to a string

description: Defining dynamic functions to a string


code: [classes][students][grades]

rawDescription: Dot notation string manipulation

description: Dot notation string manipulation


code:
import dill as pickle
pickled = pickle.dumps(session)
restored = pickle.loads(pickled)

rawDescription: Store python requests session in persistent storage


code:
dictionary = {}
for i in a:
        for j in a:
            c = set(a[i]).intersection(set(a[j]))
            if len(c) == 1:
                d = set(a[i]).difference(c)
                c = list(c)[0]
                value = list(d)[0]
                if c in dictionary and value not in dictionary[c]:
                    dictionary[c].append(value)
                elif c not in dictionary:
                    dictionary.setdefault(c, [])
                    dictionary[c].append(value)

            else: pass

rawDescription: How do I extract part of a tuple that's duplicate as key to a dictionary, and have the second part of the tuple as value?

description: Extract part of a tuple that's duplicate as key to a dictionary, and have the second part of the tuple as value


code:
def func(*args):
    mylist=[]
    z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
    for x,y in z.items():
        for t in args:
            if t in y:
                mylist.append(x)
    return mylist
print (func(1,"CI"))

rawDescription: Iterating over dict values

description: Iterating over dict values


code:
a = np.random.randint(-5,1, [5,6]);
b = np.all(a < 0, axis=0)
b
deleted_indices = np.where(b == False)
deleted_indices
c = a[:,b]
c

rawDescription: Python row index of deleted row

description: Python row index of deleted row


code:
filedata = ""

for key in d1 :
    if key in d2 :
        filedata += "%s, %s, %s, %s\n" % (d1[key][0], d1[key][1], d2[key][2], d2[key][3])

file3 = open('output.txt', 'w')
file3.write(filedata)
file3.close()

rawDescription: Merge two files with some data manipulation Python


code:
ids = set(str(result[5]) for result in text_results)
ids.update(str(result[4]) for result in doc_results)

rawDescription: Create a set from items in two lists

description: Create a set from items in two lists


code: plot(sig)

rawDescription: rectangular pulse train in python

description: Rectangular pulse train in python


rawDescription: Find the k smallest values of a numpy array


code:
import time
from subprocess import call

for color in('a', 'e', 'c'): #cycles through different colours
    call('cls', shell=True) #clears the screen
    call('color ' + color, shell=True)
    print('The quick brown fox jumps over the lazy dog.')
    time.sleep(1)

input("\nPress enter to exit. ")

rawDescription: Change shell print color in python 3.3.2


code:
app.config['SQLALCHEMY_ECHO'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

rawDescription: Creating flask form with selects from more than one table


code: yield from submodel_generator(newpat, current+1, maxn)

rawDescription: Python: how to make a recursive generator function


code:
cell[0][0]
cell[0, 0]
type(cell)

rawDescription: How do I use mlabwrap to call a matlab function with cell arguments from python?

description: Use mlabwrap to call a matlab function with cell arguments from python


code:
def fill_range(initial_range, fill_vallue):
    smallest = initial_range[0]
    biggest = initial_range[-1]
    items = set(initial_range)
    for i in range(smallest, biggest+1):  # use xrange on python2.x
        if i in items:
            yield i
        else:
            yield fill_value

rawDescription: Insert value in Incremental List not working


code:
def __getattr__(self, attr):
    if attr == "foo":
        #function "foo" returns an integer
        return foo()
    ...

rawDescription: doc for __getattr__ defined attributes

description: Doc for __getattr__ defined attributes


code:
class Tree(object):
    ...
    def in_order(self):
        if self.left is not None:
            for node in self.left.in_order():
                yield node
        yield self  #  <-- yielding the node itself
        if self.right is not None:
            for node in self.right.in_order():
                yield node

rawDescription: Python in order traversal to a flat list


rawDescription: keep only lowest value per row in a Python Pandas dataset

description: Keep only lowest value per row in a Python Pandas dataset


code:
def isiterable(x):
  try: iter(x)
  except TypeError: return False
  else: return True

rawDescription: How can I check if an object is an iterator in Python?

description: Check if an object is an iterator in Python


code:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
    #...
    url(r'^article/(\d+)/$', 'news.views.article', name='article_by_id'),
    #...
)

rawDescription: Django dynamic links

description: Django dynamic links


code:
import  pandas as pd

df = pd.read_csv("in.csv",skiprows=3,header=None)
print(df)

rawDescription: Python convert comma separated list to pandas dataframe


code:
[(u'Arts & Entertainment',
  [u'Celebrities & Entertainment News',
   (u'Comics & Animation',
    [u'Anime & Manga', u'Cartoons', u'Comics'])])]

rawDescription: How to turn a Html nested list into a Python's one

description: Turn a Html nested list into a Python's one


code:
import json

from myspecialpackage import json

rawDescription: Module and package with same name

description: Module and package with same name


code:
class User(ModelBase):
    name = None
    hats = []

rawDescription: Issue with multiple records of the same subdocument returned for MongoDb and Python


code: (meanx, meany, cenx, ceny) = np.floor([meanx, meany, cenx, ceny]).astype(np.int32)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
def findLine(prog, target):
   for l in range(0, len(prog)):  #range doesn't include last element.
      progX = prog[l].split()
      #you probably only want to check the first element in progX
      #since that's the one with the label
      if progX[0] == target:
          return l  #This is the one we want, return the index

      #Your code for comparison
      #for i in range(0, len(progX)):
      #   if progX[i] == target:
      #      a = progX[i]

rawDescription: Python 3 - Finding which index of a list contains a particular string as a substring


code:
class form(forms.Form):
    file = forms.FileField(required=False)

rawDescription: How to make FileField in django optional?

description: Make FileField in django optional


code:
import yagmail
import whois
w = whois.whois('google.com')

yag = yagmail.SMTP('yourusername@gmail.com', 'yourpasswrd')
yag.send(contents = str(w))

rawDescription: Storing return data of print Whois in Python


code:
from threading import Thread
my_list = ['http://stackoverflow.com/', 'http://google.com']
threads = list()
for x in my_list:
    t = Thread(target=process_x, args=(x,))
    t.start()

rawDescription: MultiThreading with a python loop

description: MultiThreading with a python loop


code:
proc = subprocess.Popen(
    cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, _ = proc.communicate()

rawDescription: Are pipes in each process independent?

description: Are pipes in each process independent


code:
instance_method = f.method
instance_method.__func__ is Foo.method
instance_method.__self__ is f

rawDescription: Different way to create an instance method object in Python


code:
a1 = Asset(Name=u'Asset 1')
a2 = Asset(Name=u'Asset 2')
a3 = Asset(Name=u'Asset 3')

a1.Assets=[a1,a2,a3]

rawDescription: How to create an Elixir class that has a ManyToMany relationship with itself

description: Create an Elixir class that has a ManyToMany relationship with itself


code: time_at_start_of_today_utc = time_at_start_of_today_local - time.timezone

rawDescription: get unix time from yesterday 0000 hrs to today 0000 hours using python

description: Get unix time from yesterday 0000 hrs to today 0000 hours using python


code:
pairs = {'{': '}', '[': ']', '(': ')'}

def parse_groups(string):
    stack = []
    last = 0
    for i, c in enumerate(string):
        if c in pairs:
            # push onto the stack when we find an opener
            if not stack and last < i:
                # yield anything *not* grouped
                yield string[last:i]
            stack.append((c, i))
        elif c in pairs:
            if stack and pairs[stack[-1][0]] == c:
                # Found a closing bracket, pop the stack
                start = stack.pop()[1]
                if not stack:
                    # Group fully closed, yield
                    yield string[start:i + 1]
                    last = i + 1
            else:
                raise ValueError('Missing opening parethesis')

    if stack:
        raise ValueError('Missing closing parethesis')

    if last < len(string):
        # yield the tail
        yield string[last:]

rawDescription: Is there a simple string parser for Python?


code:
import multiprocessing as mp

class Consumer(mp.Process):
    def __init__(self, task_queue, result_queue, lock, lst):
            mp.Process.__init__(self)
            self.task_queue = task_queue
            self.result_queue = result_queue
            self.lock = lock
            self.lst = lst

    def run(self):
            proc_name = self.name
            while True:
                next_task = self.task_queue.get()
                if next_task is None:
                    self.task_queue.task_done()
                    break
                answer = next_task(lock = self.lock, lst = self.lst)
                self.task_queue.task_done()
                self.result_queue.put(answer)
            return

class Task(object):
    def __init__(self, i):
        self.i = i

    def __call__(self, lock, lst):
        with lock:
            lst[self.i] = "test {}".format(self.i)
            print([lst[i] for i in range(3)])

if __name__ == '__main__':
   tasks = mp.JoinableQueue()
   results = mp.Queue()
   manager = mp.Manager()
   lst = manager.list(['']*3)

   lock = mp.Lock()
   num_consumers = mp.cpu_count() * 2
   consumers = [Consumer(tasks, results, lock, lst) for i in xrange(num_consumers)]

   for w in consumers:
      w.start()

   for i in xrange(3):
      tasks.put(Task(i))

   for i in xrange(num_consumers):
      tasks.put(None)

   tasks.join()

rawDescription: Python : multiprocessing and Array of c_char_p


code:
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:    # wasn't an int
            pass

sides = get_int("Please enter the amount of sides on the dice: ")
times = get_int("Please enter the number of times you want to repeat: ")

rawDescription: How to repeat in python

description: Repeat in python


rawDescription: Sorted data while plotting heatmap

description: Sorted data while plotting heatmap


code: data

rawDescription: Is there better way to merge dictionaries contained in two lists in Python?


code:
if logger:
    logger.debug("abc")

rawDescription: Implementing an optional logger in code

description: Implementing an optional logger in code


code: df2 = df.set_index('City')

rawDescription: Create series from one row of dataframe

description: Create series from one row of dataframe


code:
ncores = 8
init = sc.parallelize(xrange(10000), ncores * 2).cache()

rawDescription: Spark iteration time increasing exponentially when using join


code:
dfs = {}
for f in filelist:
    ...
    df = pd.read_csv(f)  # this returns a DataFrame
    for x in sum_list:
        ...
        dfs[sdo] = df[df.summary_level == x]  # again, this return a DataFrame

rawDescription: Calling Pandas Data Frames Created with globals() Inside For Loop


rawDescription: Pandas: get index of removed row

description: Pandas: get index of removed row


code:
class SimpleTable(tables.Table):
    amend = TemplateColumn('<input type="checkbox" value="{{ record.pk }}" />', verbose_name="Amend")

rawDescription: django-tables2 checkbox column name

description: Django-tables2 checkbox column name


rawDescription: column max with list of matrices

description: Column max with list of matrices


code:
conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO urbandictionary (SEARCH_WORD, SEARCH_STRING) \
      VALUES (?,?)", [search, q2])
conn.commit()
conn.close()

rawDescription: how save output from python to database?

description: How save output from python to database


code: self.kicks = [QtGui.QCheckBox(self) for _ in xrange(16)]

rawDescription: Qt - Create Widget dynamically

description: Qt - Create Widget dynamically


code: itertools.islice(lst, 0, None, 2)

rawDescription: Python: How to transform a 'flat' sequence into a sequence of tuples?


rawDescription: python argparse with time format

description: Python argparse with time format


code:
class LazyProperty(property):
    def __init__(self, *args, **kwargs):
        # Let property set everything up
        super(LazyProperty, self).__init__(*args, **kwargs)
        # We need a name to save the cached result. If the property is called
        # "test" save the result as "_test".
        self._key = '_{0}'.format(self.fget.__name__)

    def __get__(self, obj, owner=None):
        # Called on the class not the instance
        if obj is None:
            return self

        # Value is already fetched so just return the stored value
        elif self._key in obj.__dict__:
            return obj.__dict__[self._key]

        # Value is not fetched, so fetch, save and return it
        else:
            val = self.fget(obj)
            obj.__dict__[self._key] = val
            return val

rawDescription: Declaring class attributes in __init__ vs with @property


code: lis = dr.find_elements_by_css_selector("#profileInfo2  li")

rawDescription: Getting empty list while parsing

description: Getting empty list while parsing


code:
def foobar(d):
    temp = d.copy()
    # your logic goes here
    return temp

rawDescription: How do I modify a dict locally as to not effect the global variable in python

description: Modify a dict locally as to not effect the global variable in python


rawDescription: Read CSV with two different delimiters

description: Read CSV with two different delimiters


code:
user_addresses = [{"name": "First Address"},
                  {"name": "Second Address"}]
form = AddressesForm(addresses=user_addresses)
return render_template("edit.html", form=form)

rawDescription: Add input fields dynamically with wtforms


code: [[int(y) for y in x.split()] for x in lis]

rawDescription: How can I split this list of strings to list of lists of ints?

description: Split this list of strings to list of lists of ints


code: l_two = list(set(l_one))

rawDescription: How to reduce lines with list comprehensions in Python?

description: Reduce lines with list comprehensions in Python


code:
self.files = {}

for file in files:
    lexer = guess_lexer__for_filename(file, None)
    self.files.setdefault(type(lexer), []).append(file)

rawDescription: Is it reasonable to use type(a) as a dictionary key?


code: db.col.find({"$or": conditions})

rawDescription: Dynamically build query with regex in PyMongo


rawDescription: How do I fit a quadratic surface to some points in Python?

description: Fit a quadratic surface to some points in Python


code:
G.add_edge(1, 2, key='xyz', weight=7)
G.edges(data=True)

rawDescription: Changing edge attributes in networkx multigraph


code:
app = Flask(__name__)
app.url_map.converters['int_list'] = IntListConverter

rawDescription: Capture a list of integers with a Flask route


code: c = xy - ln(x)

rawDescription: Sage plot slope field and differential equation


code:
mask = data.copy()
grp = ((mask.notnull() != mask.shift().notnull()).cumsum())
grp['ones'] = 1
for i in list('abcdefgh'):
    mask[i] = (grp.groupby(i)['ones'].transform('count') < 5) | data[i].notnull()

rawDescription: Interpolate (or extrapolate) only small gaps in pandas dataframe


code:
import csv
with open('test.csv') as f:
    fieldnames = ('variable', 'name', 'date', 'location', 'youtube')
    r = csv.DictReader(f, fieldnames)
    next(f, None) # skip header
    rows = []
    for row in r:
        if row['variable'] == 'e1':
            row['name'] = 'My birthday'
        if row['variable'] == 'e2':
            row['location'] = 'India'
        rows.append(row)
    w = csv.DictWriter(a_file, fieldnames)
    w.writerows(rows)

rawDescription: Replacing variable with values from a CSV-file in python


code:
def extend_dict(extend_me, extend_by):
    if isinstance(extend_by, dict):
        for k, v in extend_by.iteritems():
            if k in extend_me:
                extend_dict(extend_me.get(k), v)
            else:
                extend_me[k] = v
    else:
        extend_me += extend_by

extend_dict(file1, file2)

rawDescription: python merge complex YAML

description: Python merge complex YAML


code:
text1
text2

rawDescription: Python: Regular expression to extract text between any two tags in a html


code:
u = np.zeros(10)
u
u[0] = 1
u[1] = 10
u[-1] = 9 #last element
u[-2] = np.pi #second last element
u
u.shape
u[9] #calling
y = np.zeros((4,2))
y
y[1] = 10 #this will assign all the second row to be 10
y
y[0,1] = 9 #now this is 2D assignment, we use 2 indices!
y[3] = np.pi #all 4th row, similar to y[3,:], ':' means all
y[2,1] #3rd row, 2nd column
y[2,1] = 7

y

rawDescription: vectorized assignment statement for selected elements of 2d array in numpy

description: Vectorized assignment statement for selected elements of 2d array in numpy


code:
import pycurl
from io import BytesIO

buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://stackoverflow.com/')
c.setopt(c.WRITEDATA, buffer)
c.perform()
body = buffer.getvalue()

print('TOTAL_TIME: %f' % c.getinfo(c.TOTAL_TIME))
print('CONNECT_TIME: %f' % c.getinfo(c.CONNECT_TIME))
print('PRETRANSFER_TIME: %f' % c.getinfo(c.PRETRANSFER_TIME))
print('STARTTRANSFER_TIME: %f' % c.getinfo(c.STARTTRANSFER_TIME))

c.close()

rawDescription: Getting DNS resolution time and response time with Python


code:
v_in = Infix(np.vectorize(lambda x,y: contains(y, x), excluded={1,}))
# even easier: v_in = Infix(np.in1d)

rawDescription: Numpy search for elements of an array in a subset


code: triangle[row][i] = max([elem + next[n] for n in neigh(i,len(next))])

rawDescription: Finding the Maximum Route in a given input


code: res = [ [ next(iter(set(r) & set(c))) for c in cols ] for r in rows ]

rawDescription: How to cross 2 two-dimensional arrays in python?

description: Cross 2 two-dimensional arrays in python


code: DATABASE.sort(key=lambda x: len(x['SPECIAL_KEY']), reverse=True)

rawDescription: Python3: Make itemgetter sort by string length


code:
self.capture = Capture()
self.start_button = QtGui.QPushButton('Start',self)
self.start_button.clicked.connect(self.capture.startCapture)

self.end_button = QtGui.QPushButton('End',self)
self.end_button.clicked.connect(self.capture.endCapture)

self.quit_button = QtGui.QPushButton('Quit',self)
self.quit_button.clicked.connect(self.capture.quitCapture)

rawDescription: OpenCV Video Capture with PyQt4

description: OpenCV Video Capture with PyQt4


code:
s = '''
      My Class: TEST DATA

      Test Section:

      MY SECTION

      MY SECTION 2

    	'''
import re
re.findall('(?<=Test)(.*?)(?=	)', s)  # without flags
re.findall('(?<=Test)(.*?)(?=	)', s, flags=re.S)
re.findall('(?s)(?<=Test)(.*?)(?=	)', s)

rawDescription: RegEx Get string between two strings that has line breaks


rawDescription: Split string multiple times in Python

description: Split string multiple times in Python


code:
import os
cwd = os.getcwd()
files = os.listdir(cwd)
files
files_fsys = os.listdir(files[1])
files_fsys = os.listdir(files[0])
files_fsys

rawDescription: Python: Directory searching

description: Python: Directory searching


rawDescription: Converting integers to bytes

description: Converting integers to bytes


rawDescription: Python cross matching

description: Python cross matching


code:
class TagListView(ListView):

    template_name = "tag_post_list.html"

    def get_queryset(self):
        slug = self.kwargs['slug']
        try:
            tag = Tag.objects.get(slug=slug)
            return tag.post_set.all()
        except Tag.DoesNotExist:
            return Post.objects.none()

rawDescription: Using get_queryset() method in ListView, Django 1.9


code:
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np

def my_formatter(x, pos):
    """Format 1 as 1, 0 as 0, and all values whose absolute values is between
    0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
    formatted as -.4)."""
    val_str = '{:g}'.format(x)
    if np.abs(x) > 0 and np.abs(x) < 1:
        return val_str.replace("0", "", 1)
    else:
        return val_str

# Generate some data.
np.random.seed(1) # So you can reproduce these results.
vals = np.random.rand((1000))

# Set up the formatter.
major_formatter = FuncFormatter(my_formatter)

plt.hist(vals, bins=100)
ax = plt.subplot(111)
ax.xaxis.set_major_formatter(major_formatter)
plt.show()

rawDescription: removing leading 0 from matplotlib tick label formatting

description: Removing leading 0 from matplotlib tick label formatting


code: np.cumsum(x, axis=1)

rawDescription: numpy ndarrays: row-wise and column-wise operations

description: Numpy ndarrays: row-wise and column-wise operations


code:
def formattime(time):
    # format to workweeks, workdays, hours and minutes
    # a workweek is 5 days, a workday is 8 hours
    hours, minutes = divmod(time, 60)
    days, hours = divmod(hours, 8)  # work days
    weeks, days = divmod(days, 5)   # work weeks
    components = [str(v) + l for l, v in zip('wdhm', (weeks, days, hours, minutes)) if v]
    return ''.join(components) or '0m'

rawDescription: Format duration in minutes as weeks, days, hours, minutes


code:
file = open("file.txt", "w")

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)

rawDescription: Python how to keep writing to a file without erasing what's already there


rawDescription: specifying "skip NA" when calculating mean of the column in a data frame created by Pandas

description: Specifying "skip NA" when calculating mean of the column in a data frame created by Pandas


rawDescription: Taking a string of numbers and inserting + and - operators


rawDescription: Unable to upgrade YouTube session token without logging into Google Accounts user API


code:
cursor.execute(
    '''INSERT INTO main_territory (code, name) VALUES (%(code)s, %(name)s)''',
    {'code': item[0], 'name': item[1]})

rawDescription: String formatting on SQL insert using dict


rawDescription: Clicking Specific button with Selenium

description: Clicking Specific button with Selenium


code: print (" ".join([function(word) for word in split]))

rawDescription: Python: for loop - print on the same line


code:
#main.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import worker # This is to import worker.py
class menubar(object):
    def __init__(self):
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        self.cc.cast = None
        self.systray = True
        self.stopped = False

        self.obj = worker.Worker()  # The worker is started with no parent!
        self.thread = QThread()  # We initialise the Qthread class with no parent!
        self.obj.intReady.connect(self.onIntReady) # We receive the signal that the list is ready
        self.obj.moveToThread(self.thread) # Moving the object to the thread
        self.obj.finished.connect(self.thread.quit) # When the method is finished we receive the signal that it is finished
        self.thread.started.connect(self.obj._search_cast_) # We need to connect the above with the desired method inside the work.py

        self.app = QtWidgets.QApplication(sys.argv)

        def search_menu(self):
            self.SearchAction = self.menu.addAction("Search")
            self.SearchAction.triggered.connect(self.search_cast)

        def onIntReady(self, availablecc):     # This method receives the list from the worker
            print ('availablecc', availablecc)  # This is for debugging reasons to verify that I receive the list with the correct content
            self.availablecc = availablecc

        def search_cast(self):   #This method starts the thread when  self.SearchAction is triggered
            args.select_cc = True
            self.thread.start()

rawDescription: PyQt5 QObject: Cannot create children for a parent that is in a different thread


code:
len(quotes)
len(symbols)
symbols

rawDescription: structure of python numpy arrays

description: Structure of python numpy arrays


rawDescription: Adding data to related table with SQLAlchemy


code:
import pandas as pd

df.join(df.column3.apply(pd.Series)).drop('column3', 1).set_index([u'column1', u'column2']).stack().reset_index().drop('level_2', 1).rename(columns={0:'column3'})

rawDescription: Flattening an array in pandas

description: Flattening an array in pandas


code:
i, time, temp, hum, light_lv, light_v = np.loadtxt(
    'DHT11.csv', delimiter = ',', skiprows = 1,
    usecols = (0,2,3,4,5,6), unpack = 1)

time = [DT.datetime.fromtimestamp(t/1000) for t in time]
light_lv = 1.0/light_lv*1000

rawDescription: Python Use data/time as x-axis?

description: Python Use data/time as x-axis


code:
import lxml.html as lh
content='''\

    1.
    A domesticated carnivorous mammal
    (Canis familiaris)
    related to the foxes and wolves and raised in a wide variety of breeds.

'''
doc=lh.fromstring(content)
for div in doc.cssselect('div.ds-list'):
    print(div.text_content())

rawDescription: lxml cssselect Parsing

description: Lxml cssselect Parsing


code:
top_padding = 5
top = ttk.Button(frame, text="Top")
top.grid(row=0, column=1, sticky=tk.N, pady=(top_padding, 0))

left_padding = 5
left = ttk.Button(frame, text="Left")
left.grid(row=1, column=0, sticky=tk.W, padx=(left_padding, 0))

right_padding = 5
right = ttk.Button(frame, text="Right")
right.grid(row=1, column=2, sticky=tk.E, padx=(0, right_padding))

bottom_padding = 5
bottom = ttk.Button(frame, text="Bottom")
bottom.grid(row=2, column=1, sticky=tk.S, pady=(0, bottom_padding))

root.mainloop()

rawDescription: Tkinter button distance from window edges


code:
def count_zeros_and_lines(fname):
    try:
        with open(fname) as f:
            zeros = total = 0
            for line in f:
                if line.strip() == '0':
                    zeros += 1
                total += 1
            return zeros, total
    except IOError:
        # not a file we can read
        return None

rawDescription: Search within a file in python

description: Search within a file in python


rawDescription: Combining 2-d arrays to form a 3-d array


code:
filtered_sets = (model
    .freqItemsets()
    .filter(lambda x: x.items[0] != 'A_String_0')
    .collect())

rawDescription: Python 2.7 : delete item from list by value


rawDescription: Weird behavior specifying date limits with pandas


code: sum(1 for i in x if i)

rawDescription: Python Multidimensional Arrays - most efficient way to count number of non-zero entries


code:
import random
fruits = ["mango", "pomelo", "guava", "grapefruit", "watermelon"]
DoDict = {'do1': random.choice}

rawDescription: How can I insert a random element into a dictionary and have it randomised whenever I call it?

description: Insert a random element into a dictionary and have it randomised whenever I call it


code:
strings = 'a b c d e f g'
mylist = strings.split()
pairs = []

count = 0
for x in mylist:
    if count == len(mylist) - 1:
        break
    pairs += [mylist[count]+mylist[count+1]]
    count += 1

print(' '.join(pairs)) # ab bc cd de ef fg

rawDescription: Python: Easier way to change/edit items in a list?


code: df.apply(lambda x:x/sum(x), axis = 1) #with your original dataFrame

rawDescription: Can a pandas series be a column rather than a row?


code: result = '***' in x or (not  '**' in x and '*' in x)

rawDescription: In python, test for 1 or 3 consecutive instances of a string, but not 2 (without regex)


code:
from operator import *

str_ops = {'<':lt,'>':gt,'==':eq} # etc
op = str_ops.get(my_operator) #where my_operator was previously your 'operator'
assert op is not None #or raise your own exception
if op(a,b):
    c+=5

rawDescription: Using a string as an operator?

description: Using a string as an operator


code:
open_info = ['Cube 1, 9:30am to 10:00am, Thursday, March 3, 2016', 'Cube 2, 5:00pm to 5:30pm, Thursday, March 3, 2016']

answer = [[int(s.split(':',1)[0][-2:]), int(s.split(':')[1][:2]),
           s.split(':')[1][2:4]] for s in open_info]
print(answer)

rawDescription: Condensing Multiple List Comprehensions

description: Condensing Multiple List Comprehensions


code:
from __future__ import print_function    #for python2 compatibility.

from math import sqrt
from decimal import Decimal, getcontext

getcontext().prec = 102

total = 0
for a in range(100):
    if not sqrt(a) % 1 == 0:
        ans = str(Decimal(a).sqrt()).replace('.', '')[:100]
        digits = map(int, ans)
        print(a, sum(digits), "--------", sep='\n')

        total += sum(digits)
print(total)

rawDescription: Correctly compute square root digital expansions


rawDescription: Celey + Python ignores update_state calls


code:
iter_str = iter(list_str)
front, back = list(itertools.takewhile(lambda i: i != "Bad", iter_str)), list(iter_str)
front
back

rawDescription: Python - Looping through a list of strings to form new strings


rawDescription: How to test for closeness in angular quantities

description: Test for closeness in angular quantities


code:
choiceBox = wx.Choice(choices=aList, id = wx.ID_ANY, parent=self, pos=wx.Point(0, 289),
                                      size=wx.Size(190, 21), style=0)

rawDescription: Fastest way to populate wx.Choice?

description: Fastest way to populate wx.Choice


code:
#valid, "normal" way
a = random_int()
b = a

#the same, shorthand
b = a = random_int()

rawDescription: Multiple assignment from a function

description: Multiple assignment from a function


code:
from django.db.models.signals import post_save
from django.contrib.auth import User
from myUserProfileApp import UserProfile

def make_user_profile(sender, **kwargs):
    if 'created' not in kwargs or not kwargs['created']:
        return

    # Assumes that the `ForeignKey(User)` field in "UserProfile" is named "user".
    profile = UserProfile(user=kwargs["instance"])
    # Set anything else you need to in the profile, then...
    profile.save()

post_save.connect(make_user_profile, sender=User, weak=False)

rawDescription: Django - how to write users and profiles handling in best way?


rawDescription: What is the pythonic way to implement a parse tree for custom format?


code:
class UserProfile(UserenaBaseProfile):

        user = models.OneToOneField(User, unique=True)
        city = models.CharField(max_length=32, blank=True, null=True)

rawDescription: Extending Django User model with django-allauth


code: { v : v**2 for v in l }

rawDescription: Is there a more pythonic way to build this dictionary?


code:
def segment(value,numsplits):
    return ["{}-{}".format(value*i//numsplits, 1 + value//numsplits*i + value//numsplits) for i in range(numsplits)]

rawDescription: splitting a list dynamically with range and value to split

description: Splitting a list dynamically with range and value to split


code: ['phabaa', 'phabea', 'phabia', 'phaboa', 'phabua', 'phabya', 'phabrca', 'phebaa', 'phebea', 'phebia', 'pheboa', 'phebua', 'phebya', 'phebrca', 'phibaa', 'phibea', 'phibia', 'phiboa', 'phibua', 'phibya', 'phibrca', 'phobaa', 'phobea', 'phobia', 'phoboa', 'phobua', 'phobya', 'phobrca', 'phubaa', 'phubea', 'phubia', 'phuboa', 'phubua', 'phubya', 'phubrca', 'phybaa', 'phybea', 'phybia', 'phyboa', 'phybua', 'phybya', 'phybrca', 'phrcbaa', 'phrcbea', 'phrcbia', 'phrcboa', 'phrcbua', 'phrcbya', 'phrcbrca', 'sdabaa', 'sdabea', 'sdabia', 'sdaboa', 'sdabua', 'sdabya', 'sdabrca', 'sdebaa', 'sdebea', 'sdebia', 'sdeboa', 'sdebua', 'sdebya', 'sdebrca', 'sdibaa', 'sdibea', 'sdibia', 'sdiboa', 'sdibua', 'sdibya', 'sdibrca', 'sdobaa', 'sdobea', 'sdobia', 'sdoboa', 'sdobua', 'sdobya', 'sdobrca', 'sdubaa', 'sdubea', 'sdubia', 'sduboa', 'sdubua', 'sdubya', 'sdubrca', 'sdybaa', 'sdybea', 'sdybia', 'sdyboa', 'sdybua', 'sdybya', 'sdybrca', 'sdrcbaa', 'sdrcbea', 'sdrcbia', 'sdrcboa', 'sdrcbua', 'sdrcbya', 'sdrcbrca', 'nnabaa', 'nnabea', 'nnabia', 'nnaboa', 'nnabua', 'nnabya', 'nnabrca', 'nnebaa', 'nnebea', 'nnebia', 'nneboa', 'nnebua', 'nnebya', 'nnebrca', 'nnibaa', 'nnibea', 'nnibia', 'nniboa', 'nnibua', 'nnibya', 'nnibrca', 'nnobaa', 'nnobea', 'nnobia', 'nnoboa', 'nnobua', 'nnobya', 'nnobrca', 'nnubaa', 'nnubea', 'nnubia', 'nnuboa', 'nnubua', 'nnubya', 'nnubrca', 'nnybaa', 'nnybea', 'nnybia', 'nnyboa', 'nnybua', 'nnybya', 'nnybrca', 'nnrcbaa', 'nnrcbea', 'nnrcbia', 'nnrcboa', 'nnrcbua', 'nnrcbya', 'nnrcbrca', 'mmabaa', 'mmabea', 'mmabia', 'mmaboa', 'mmabua', 'mmabya', 'mmabrca', 'mmebaa', 'mmebea', 'mmebia', 'mmeboa', 'mmebua', 'mmebya', 'mmebrca', 'mmibaa', 'mmibea', 'mmibia', 'mmiboa', 'mmibua', 'mmibya', 'mmibrca', 'mmobaa', 'mmobea', 'mmobia', 'mmoboa', 'mmobua', 'mmobya', 'mmobrca', 'mmubaa', 'mmubea', 'mmubia', 'mmuboa', 'mmubua', 'mmubya', 'mmubrca', 'mmybaa', 'mmybea', 'mmybia', 'mmyboa', 'mmybua', 'mmybya', 'mmybrca', 'mmrcbaa', 'mmrcbea', 'mmrcbia', 'mmrcboa', 'mmrcbua', 'mmrcbya', 'mmrcbrca', 'ghabaa', 'ghabea', 'ghabia', 'ghaboa', 'ghabua', 'ghabya', 'ghabrca', 'ghebaa', 'ghebea', 'ghebia', 'gheboa', 'ghebua', 'ghebya', 'ghebrca', 'ghibaa', 'ghibea', 'ghibia', 'ghiboa', 'ghibua', 'ghibya', 'ghibrca', 'ghobaa', 'ghobea', 'ghobia', 'ghoboa', 'ghobua', 'ghobya', 'ghobrca', 'ghubaa', 'ghubea', 'ghubia', 'ghuboa', 'ghubua', 'ghubya', 'ghubrca', 'ghybaa', 'ghybea', 'ghybia', 'ghyboa', 'ghybua', 'ghybya', 'ghybrca', 'ghrcbaa', 'ghrcbea', 'ghrcbia', 'ghrcboa', 'ghrcbua', 'ghrcbya', 'ghrcbrca']

rawDescription: Python script to generate words from letters and two letter combination


code:
total = 0.0
for i in range(scoresno):
    total += input("Enter exam score: ")

average = total/scoresno

rawDescription: Sum all range variables in Python?

description: Sum all range variables in Python


code: newdf = df.withColumn('total', sum(df[col] for col in df.columns))

rawDescription: Add column sum as new column in PySpark dataframe


code:
DATABASES = {
  'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'projectdb',
      'USER': 'root',
      'PASSWORD': 'root',
      'HOST': '/Applications/MAMP/tmp/mysql/mysql.sock',
      'PORT': '8888',
  }
}

rawDescription: Set up a Django Project with Mamp?

description: Set up a Django Project with Mamp


code:
schema = {
    'things': {
        'type': 'dict',
        'valueschema': {
             'type': 'dict',
             'schema':{
                 'foo': {'type': 'string'},
                 'bar': {'type': 'string'}
             }
         }
     }
}

rawDescription: In Cerberus can you use 'valueschema' with a type of 'dict'?


code: A

rawDescription: how to set on zero 3d numpy array?

description: Set on zero 3d numpy array


code: entry.tag_add('sel', '1.0', 'end-1c')

rawDescription: In tkinter 8.5, how do I highlight (select) text in Text widget with a button click?


code:
if allfeatures.dtype.name == 'uint8':
    header.append(0)
else:
    allfeatures = allfeatures.astype('<f4', copy=False)
    header.append(5)

header = numpy.array(header, dtype='<i4')

rawDescription: Safest way to save binary file with numpy to be read


code: ['i am writing to stdin']

rawDescription: writing to stdin from java to python

description: Writing to stdin from java to python


code:
empList = []
empName = input("Please enter employee name. (Last name, First name):\n")
nameSplit = tuple(empName.split(","))
empList += nameSplit

rawDescription: Input into tuple that goes into list

description: Input into tuple that goes into list


code:
def someFunction(x):
  return (x)

for x in range(0, len(R)):
  R[x] = someFunction(R[x])

rawDescription: How to find the index of an array within an array

description: Find the index of an array within an array


code:
class Constant:  # use Constant(object) if in Python 2
    def __init__(self, value):
        self.value = value
    def __get__(self, *args):
        return self.value
    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.value)

rawDescription: Is it possible to define a class constant inside an Enum?


code:
def filepath(filename, foldername=None, envar='MYAPPDIR'):
  default = os.path.join(os.environ.get("XDG_CONFIG_HOME", "~/.config"), "myFolder")
  dirpath = os.path.expanduser(os.environ.get(envar, default))
  if foldername:
    dirpath = os.path.join(dirpath, foldername)

  try:
    os.makedirs(dirpath)
  except OSError as e:
    if e.errno != errno.EEXIST:
      raise
  return os.path.join(dirpath, filename)

rawDescription: Python Creating Unwanted Folder in Directory


code:
a = [u'username', u'first name', u'last name']
b = [[u'user1', u'Jack', u'Dawson'], [u'user2', u'Roger', u'Federer']]
import json
print(json.dumps([dict(zip(a, row)) for row in b], indent=1))

rawDescription: Creating json from lists using zip

description: Creating json from lists using zip


code:
import matplotlib.pyplot as plt

def myfun(args):
    data, ax = args
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
map(myfun, para)
plt.show()

rawDescription: Is it possible to plot within user-defined function with python and matplotlib?


code:
def matching_values_by_keys(d, key1, key2):
    # figure out which elements of each list to keep
    keep_indices = set()
    for index,value in enumerate(d[key1]):
        if value == d[key2][index]:
            keep_indices.add(index)

    # now go through each dictionary entry and keep the wanted elements
    new_d = {}
    for key,lst in d.items():
        new_lst = []
        for index,value in enumerate(lst):
            if index in keep_indices:
                new_lst.append(value)
        new_d[key] = new_lst

    return new_d

rawDescription: Comparing elements in the value at two keys


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

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

rawDescription: Scatter plot and Color mapping in Python


code: Range: bytes=StartPos-StopPos

rawDescription: How to resume file download in Python?

description: Resume file download in Python


rawDescription: Python Creating a nested list with random module


code:
import numpy as np
import pylab as pl

longs = (np.random.rand(60, 1) + np.linspace(-np.pi, np.pi, 80000)).reshape(-1)
lats = np.sin(longs) + np.random.rand(len(longs)) * 0.1

bad_index = (longs>0) & (longs<1)
bad_longs = longs[bad_index]
bad_lats = lats[bad_index]

ranges = [[np.min(lats), np.max(lats)], [np.min(longs), np.max(longs)]]
h, lat_range, long_range = np.histogram2d(lats, longs, bins=(300,300), range=ranges)
bad_h, lat_range2, long_range2 = np.histogram2d(bad_lats, bad_longs, bins=(300,300), range=ranges)

y, x = np.where(h)
count = h[y, x]
pl.scatter(long_range[x], lat_range[y], s=count/20, c=count, linewidths=0, cmap="Blues")

count = bad_h[y, x]
pl.scatter(long_range2[x], lat_range2[y], s=count/20, c=count, linewidths=0, cmap="Reds")

pl.show()

rawDescription: 3g coverage map - visualise lat, long, ping data


code:
import re
p = re.compile(r'([A-Za-z]+?)(?:Suff)?\b')
test_str = "textSuff more words tSuff"
print(re.findall(p, test_str))

rawDescription: Ignore optional suffix without preceding delimiter


code:
import email.utils as eutils
import time
import datetime

ntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')
print(ntuple)
# (2010, 8, 16, 24, 0, 0, 0, 1, -1)
timestamp=time.mktime(ntuple)
print(timestamp)
# 1282017600.0
date=datetime.datetime.fromtimestamp(timestamp)
print(date)
# 2010-08-17 00:00:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Tue, 17 Aug 2010 00:00:00

rawDescription: How can I convert the time in a datetime string from 24:00 to 00:00 in Python?

description: Convert the time in a datetime string from 24:00 to 00:00 in Python


code:
from subprocess import *
Popen("cmd /k dir")

rawDescription: how to open a cmd shell in windows and issue commands to that shell using python

description: Open a cmd shell in windows and issue commands to that shell using python


code:
def update(self, pos):
    if pos != 0:
        self.speed -= 1
        self.x += pos
        # no more self.speed checks
        if self.index < self.max_index:
            self.index += 1
        else:
            self.index = 0
        self.img = self.images[self.index]
    # change True to False if needed, or change the operator.
    if pos < 0:
        self.img = pygame.transform.flip(self.img,True,False)
    screen.blit(self.img,(self.x,self.y))

rawDescription: How to flip an img in Pygame, having trouble in my code?

description: Flip an img in Pygame, having trouble in my code


code:
import numpy as np
import pandas as pd

df1 = pd.DataFrame({'A': [1, 2, 3, 2, 5, 2, 5, 3, 2, 0, 5, 1],
                    'B': [2, 4, 5, 6, 6, 1, 2, 3, 2, 4, 4, 1]},
                   index=pd.date_range('2011-1-2', '2011-01-03 20:00', freq='240T'))

df2 = pd.DataFrame({'N': 1}, index=pd.date_range('2011-1-2', '2011-01-03'))

def next_n_asof(x, t, n):
    i = np.argmax(df1.index > t)
    return x[i:i + n]

print(pd.concat(next_n_asof(df1.A, t, 4)
               for t in df2.index))

def func(df, index, length):
    start = df.index.get_indexer_for(index)
    mask = np.zeros(len(df), dtype='bool')
    for i in range(length):
        mask[start+i] = True
    return df.loc[mask]

index = df2.index + pd.DateOffset(hour=4)
print(func(df1['A'], index, length=4))

rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


code: someList.extend(['extra', 'list', 'elements'] for _ in range(someNumber))

rawDescription: Pythonic way to add several identical values to a list


code:
import numpy as np
import os

def iter_arrays(fname, array_ndim=2, dim_dtype=np.int, array_dtype=np.double):

    with open(fname, 'rb') as f:
        fsize = os.fstat(f.fileno()).st_size

        # while we haven't yet reached the end of the file...
        while f.tell() < fsize:

            # get the dimensions for this array
            dims = np.fromfile(f, dim_dtype, array_ndim)

            # get the array contents
            yield np.fromfile(f, array_dtype, np.prod(dims)).reshape(dims)

rawDescription: How can I read successive arrays from a binary file using `np.fromfile`?

description: Read successive arrays from a binary file using `np.fromfile`


code:
from scipy.io import savemat
from scipy import sparse
M = sparse.csr_matrix(np.arange(12).reshape(3,4))
savemat('temp', {'M':M})
x=loadmat('temp.mat')
x
x['M'].A

rawDescription: importing a python sparse matrix into MATLAB

description: Importing a python sparse matrix into MATLAB


code:
def bisection(a, b, TOL):
    c = (a + b) / 2.0
    while (b - a) / 2.0 > TOL:
        if f(c) == 0:
            return c
        elif f(a) * f(c) < 0:
            b = c
        else:
            a = c
        c = (a + b) / 2.0
        print ("Current value of c is {}".format(c))
    return c

rawDescription: My bisection code in python doesnt return the root


rawDescription: Python: Unpack individual strings from tuple using Unpacking asterisk argument


rawDescription: String Replacement Combinations

description: String Replacement Combinations


rawDescription: Scipy.misc.imread flatten argument -- converting to grey scale


code:
df = pd.DataFrame({'iso': ['4He', '16O', '197Au']})
result = df['iso'].str.split('(\d+)([A-z]+)', expand=True)
result = result.loc[:,[1,2]]
result.rename(columns={1:'x', 2:'y'}, inplace=True)
print(result)

rawDescription: split string into number and text with pandas

description: Split string into number and text with pandas


code:
from itertools import izip_longest

def find_prefixes(strings):
    zipped = izip_longest(*strings, fillvalue='')
    for index, letters in enumerate(zipped):
        if index == 0:
            prefixes = letters  # assumes there will always be a prefix
        else:
            poss_prefixes = [prefix + letters[i] for i, prefix in enumerate(prefixes)]
            prefixes = [prefix if poss_prefixes.count(prefix) == letters.count(prefix)  # changed > 1 to == letters.count(prefix)
                        else prefixes[i] for i, prefix in enumerate(poss_prefixes)]
    return set(prefixes)

rawDescription: Left factoring using Python

description: Left factoring using Python


code:
#!/usr/bin/env python3
import mmap
import string

uppercase = string.ascii_uppercase.encode()
ncolumn = 3 # select 4th column
with open('file', 'r+b') as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_WRITE) as mm:
    while True:
        mm.readline()   # ignore every other line
        pos = mm.tell() # remember current position
        if not mm.readline(): # EOF
            break
        if mm[pos + ncolumn] in uppercase:
            mm[pos + ncolumn] |= 0b0100000 # lowercase

rawDescription: Python - How can I change bytes in a file


code: dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)

rawDescription: Python - Combine two dictionaries, concatenate string values?


rawDescription: python regex: how to split string into distinct groups based on alphabets, digits and punctuation

description: Python regex: how to split string into distinct groups based on alphabets, digits and punctuation


rawDescription: Transform the relationship data with weight into a Matrix in python


code: df

rawDescription: Pandas: Impute NaN's

description: Pandas: Impute NaN's