code:
import re

secondbases = []
with open('/example.txt','r') as contents:
    for line in contents:
        splitline = line.split()
        if line[0] == 'C': #If line begins CRISPR, write new info to file and save new CRISP values
            if secondbases != []:
                outputfile = open('/output.txt','a') #With ain't workin for me here, but replace at your own desire
                x = 1
                for base in secondbases:
                    outputfile.write('>CRISPR_' + crispno + '_' + rangestart + '_' + rangeend + '_' +  str(x) + ' ' + base + '\n')
                    x += 1
                outputfile.close()
            secondbases = []
            (crispno,rangestart,rangeend) = (splitline[1],splitline[3],splitline[5])
        elif re.search('[0-9]',line[0]): #If base lines, copy second base string to list
            bases = []
            for a in splitline:
                if re.search('[GTCA]{5,}',a):
                    bases = bases + [a]
            if len(bases) > 1:
                secondbases = secondbases + [bases[1]]
        elif line[len(line)-1] != '\n' and secondbases != []:
            outputfile = open('/output.txt','a')
            x = 1
            for base in secondbases:
                outputfile.write('>CRISPR_' + crispno + '_' + rangestart + '_' + rangeend + '_' +  str(x) + ' ' + base + '\n')
                x += 1
            outputfile.close()

rawDescription: How to select specific information from a file? Python

description: Select specific information from a file? Python


code: c = {k:(c.get(k,0) + c.get(k[::-1],0)) for k in set(map(lambda x: tuple(sorted(x)),c.keys()))}

rawDescription: Accessing the keys of a dict when the keys are tuple and checking the elements of the tuple if they are equal


code:
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt

# Generate some random points for the demo.
np.random.seed(4321)
pts = 0.1 + 0.8*np.random.rand(15, 2)

ch = ConvexHull(pts)

# Get the indices of the hull points.
hull_indices = ch.vertices

# These are the actual points.
hull_pts = pts[hull_indices, :]

plt.plot(pts[:, 0], pts[:, 1], 'ko', markersize=10)
plt.fill(hull_pts[:,0], hull_pts[:,1], fill=False, edgecolor='b')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()

rawDescription: get the index of point which create ConvexHull

description: Get the index of point which create ConvexHull


code:
df = pd.read_csv("bondstack.csv")
df["shift"] = df["open"].shift(-1)
df["b"] = df.apply(lambda row: row["shift"] if row["MA10"] > row["MA100"] else np.nan, axis=1)

rawDescription: Pandas list comprehension in a dataframe


code: timeNow = os.popen('date +\"%s\"').read()

rawDescription: os.system python function in a while loop

description: Os.system python function in a while loop


code: re.sub('(?:Choucroute garnie)*', '#', 'ornithorynque')

rawDescription: Why does re.findall() find more matches than re.sub()?


rawDescription: Django URL Variables - Business Name in URL in stead of ID


code:
from bs4 import BeautifulSoup
data = """

Testing

Test

Test2

Testing2

"""
soup = BeautifulSoup(data)
element = soup.find('h3', text='Test')
element.find_previous_sibling('h4')

rawDescription: Find previous occurrence of an element

description: Find previous occurrence of an element


rawDescription: Set the wrap width for python docs in a terminal


code:
normalized_query = query.replace(' ', '').lower()
return normalized_query

rawDescription: Python: extra assignments in functions

description: Python: extra assignments in functions


code: fname = fname.strip('.csv')   # no semicolons in Python!

rawDescription: python strip function is not giving expected output

description: Python strip function is not giving expected output


rawDescription: Removing a selection from a listbox, as well as remove it from the list that provides it


rawDescription: Iterating over keys and values of a dictionary in mustache / pystache


code:
yourlogger.write("some log test") #this will output BLAH  some log text
yourlogger.write("\n") #this will output BLAH \n

rawDescription: Python 'Logger' class repeats timestamp

description: Python 'Logger' class repeats timestamp


code:
payloadRecon = open('TCPStreamPayload.txt', 'a')
segmentCount = 0
write_original = payloadRecon.write
def write_and_count(self, *args, **kwargs):
    global segmentCount
    segmentCount += 1
    write_original(self, *args, **kwargs)
payloadRecon.write = write_and_count

rawDescription: Python Increasing counter by 1 every time something is written to a file


code:
from collections import deque
import itertools as it

def islice_without_end(it, x):
    d = deque(it.islice(it, x))
    for value in it:
        yield d.popleft()
        d.append(value)

rawDescription: Python modify generator

description: Python modify generator


rawDescription: Python: Update Widgets from outside function using multipocessing Pool


code: True

rawDescription: How to compare two lists in Python efficiently?

description: Compare two lists in Python efficiently


code:
def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

rawDescription: What is the difference between json.dumps and json.load


code:
def find_value(needle, container):
    # Already found the object. Return.
    if isinstance(container, basestring) and needle in container:
        return True

    values = None
    if isinstance(container, dict):
        values = container.values()
    elif hasattr(container, '__iter__'):
        values = container.__iter__()

    if values is None:
        return False

    # Check deeper in the container, if needed.
    for val in values:
        if find_value(needle, val):
            return True

    # No match found.
    return False

rawDescription: search for any string value in an ordered dictionary

description: Search for any string value in an ordered dictionary


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

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], ' o', lw=2)
g = 9.81
h = 2
tc = 200
xs = [1] # the vertical position is fixed on x-axis
ys = [h, h]

# animation function.  This is called sequentially
def animate(y):
    ys[-1] = y
    line.set_data(xs, ys)
    return line,

def get_y():
  for step in range(tc):
    t = step / 100.0
    y = -0.5*g*t**2 + h  # the equation of diver's displacement on y axis
    yield y

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100)

plt.show()

rawDescription: How to plot real-time graph, with both axis dependent on time?

description: Plot real-time graph, with both axis dependent on time


code: n = m[:index] + m[index+1:]

rawDescription: Remove list element without mutation

description: Remove list element without mutation


code:
from nltk.tree import Tree; from nltk.chunk import ne_chunk
[chunk for chunk in ne_chunk(tagged_sent) if isinstance(chunk, Tree)]
[i[0] for i in list(chain(*[chunk.leaves() for chunk in ne_chunk(tagged_sent) if isinstance(chunk, Tree)]))]

rawDescription: Finding Proper Nouns using NLTK WordNet

description: Finding Proper Nouns using NLTK WordNet


code:
import random
from collections import Counter
Counter(int(random.random() < 0.8) for _ in range(1000))

rawDescription: Generate random numbers according to a specific distribution


rawDescription: Get all edges linked to a given node in a networkx graph


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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.random((20, 20)), extent=(0, 10.5, 2, 4.7), aspect=1, interpolation='nearest')

rawDescription: Matplotlib: force aspect ratio in series of plots


code:
for row in zip(a, b, c, d):
    csv_writer.writerow(row)

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

description: Make a CSV file from a number of lists


code: _AppendAction(option_strings=['-l'], dest='l', nargs=None, const=None, default=[1, 2, 3, '4'], type=None, choices=None, help=None, metavar=None)

rawDescription: Please explain reasoning behind code snippet from argparse module


code: return ddda

rawDescription: how do i get this python function to return a value?

description: Get this python function to return a value


code:
q = (session.query(Store)
        .outerjoin(Store.images) # load images
        .options(contains_eager(Store.images)) # tell SA that we hav loaded them so that it will not perform another query
        .filter(Store.is_flagship == True)
    ).all()

rawDescription: KeyedTuple with a list of related data

description: KeyedTuple with a list of related data


code:
class WMGUI(tk.Frame):
    '''
    A GUI for wm
    '''
    def __init__(self, parent=None, *, title='WM'):
        if parent is None:
            parent = tk.Tk()
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.pack() #packs the Frame
        self.initUI(title)

    def initUI(self, title):
        """
        do not call from outside of class
        """
        self.parent.title(title)
        # make game_menu
        game_menu_var = tk.IntVar()
        game_menu_var.set(1)
        self.game_menu = tk.OptionMenu(self, game_menu_var, 1, 2 , 3)
        self.game_menu.pack(side="left")

rawDescription: tkinter Option Menu Is missing

description: Tkinter Option Menu Is missing


code:
def my_function(output=''):  # <-- change 1

    dsides = int(input("how many sides do your dice have?"))
    print("Your dice has " + str(dsides) +" sides")
    dint = int(input("How many dice do you want to roll?"))
    import random
    y = 0
    while y < dint:
        out = random.randint(1, int(dsides))
        output += "{} ".format(out)   # <-- change 2
        # print(str(output))   # <-- change 3
        y=y+1

    while True:
        answer = raw_input('Run again? (y/n): ')
        if answer in ("y", "n"):
            if answer == "y":
                my_function(output)  # <-- recursive call
            else:
                print(output)   # <-- change 4
                print("GoodBye")
                return
        else:
            print ("Invalid input.")
            break

rawDescription: Can't figure out how to make code 'restart'


code:
QtGui.QMessageBox.question(self,
         'Message',
         "Are you sure to quit?",
         QtGui.QMessageBox.Yes,
         QtGui.QMessageBox.No)

rawDescription: JOptionPane equivalent in python?

description: JOptionPane equivalent in python


rawDescription: Removing all duplicates from the list - keeping no instance of a duplicate item


code:
class Foo(object):
    def __init__(self,attr1,attr2):
        self.attr1 = attr1
        self.attr2 = attr2v

rawDescription: Python: Pokemon battle (classes, functions)


code:
a = [2,2,2,1,1,1,1,1,1,1]
from itertools import groupby
["{}*{}".format(k, sum(1 for x in g)) for k, g in groupby(a)]

rawDescription: Are there any smart print methods in Python?


code:
import sys
import os
from subprocess import Popen
from contextlib import contextmanager

@contextmanager
def monitor(stream, callback):
    read, write = os.pipe()
    yield write
    os.close(write)
    with os.fdopen(read) as f:
        for line in f:
            callback(line)
            stream.write(line)

def f(s):
    print("Write")

with monitor(sys.stdout, f) as stream:
    p = Popen(["ls"], stdout=stream)
    p.communicate()

rawDescription: Monitored stream class

description: Monitored stream class


code:
for child in xml_obj.getchildren():
    print(child.attrib)
# {'foo': 'baz'}
# {'foo': 'bar'}

rawDescription: Getting valueless elements in python lxml


code:
template = "http://whatever.org/?title={Title}&note={Note}"
template.format(Title="SampleTitle", Note="SampleNote")

rawDescription: Replacing "tokens" in Python string with alternate values


rawDescription: Python 3: nested dictionary with multiple keys from csv


code:
while True:
    number = input("Enter number: ")
    if not number.isdigit(): # check if a string contains a number with .isdigit()
        print ("Enter only numbers\n")
        continue
    elif len(number) != 10:
        print ("Enter 10 digits\n")
        continue
    else:
        break

rawDescription: Asking for 10-digit numbers

description: Asking for 10-digit numbers


code:
class Foo(object):
    def __init__(self, a=1, b=2):
        inputs = locals()
        del inputs['self'] # remove self variable
        print(inputs)

f = Foo()

rawDescription: Pack function arguments into a dictionary - opposite to **kwargs


code:
class MyTest(object):
  def foo(self, x):
    return self.x * x
  x = 4

f = MyTest()
import dill
with open('test.pkl', 'wb') as s:
  dill.dump(f, s)

rawDescription: Pickle python class instance plus definition


code:
for row in r:
    row.insert(data_1_index, row[data_1_index])
    w.writerow(row)

rawDescription: replacing the first line of a csv file python

description: Replacing the first line of a csv file python


code:
first_level_names = df_unstacked.columns.levels[0]
second_level_names = df_unstacked.columns.levels[1]

rawDescription: Transforming DataFrame (pivot)

description: Transforming DataFrame (pivot)


code: d = make_defaultdict(2, list)

rawDescription: list of tuples to dictionary of dictionaries

description: List of tuples to dictionary of dictionaries


code:
A['nested'] = FuzzyDict(float_eq=float_eq)
A['nested']['a'] = 17.32
B['nested'] = FuzzyDict(float_eq=float_eq)
B['nested']['a'] = 17.321
B['b'] = 'a string'   # changed before
A == B
B['nested']['a'] = 17.34
A == B

rawDescription: Comparing Python dicts with floating point values included


code:
df = DataFrame(dict(date = [Timestamp('20130101'),Timestamp('20130131'),Timestamp('20130331'),Timestamp('20130330')],value=randn(4))).set_index('date')
df
df.index = df.index.to_period('M').to_timestamp('M')
df

rawDescription: pandas: convert datetime to end-of-month

description: Pandas: convert datetime to end-of-month


code: (key for key, val in series.iteritems() for i in range(val))

rawDescription: Pandas: creating dataframe rows from other dataframe information


code:
def test_event(target, value, initiator):
    try:
        return session.query(Word).filter(Word.word == value.word.lower()).one()
    except sqlalchemy.orm.exc.NoResultFound:
        return value

rawDescription: React on UniqueKeyViolation in SQLAlchemy


code:
import inspect
test = getattr(cc, 'func', None)
inspect.ismethod(test)

rawDescription: How to find out whether a function defined for an instance of a class in Python?

description: Find out whether a function defined for an instance of a class in Python


code:
def factorize(n, primes):
    factors = []
    for p in primes:
        if p*p > n: break
        i = 0
        while n % p == 0:
            n //= p
            i+=1
        if i > 0:
            factors.append((p, i));
    if n > 1: factors.append((n, 1))

    return factors

rawDescription: Finding all divisors of a number optimization


rawDescription: Generate a lattice using python

description: Generate a lattice using python


code: sum((Counter(d) for d in test_dict), Counter())

rawDescription: Adding Values that Have the Same Key

description: Adding Values that Have the Same Key


code:
l=logging.getLogger('<distinguishing name>')
#use l's methods

rawDescription: Log messages from two modules to different files and include logging from modules that use other logging facilities


code:
import time

import datetime

rawDescription: Is there a IPython notebook api?

description: Is there a IPython notebook api


rawDescription: python netaddr find closest Ip address match

description: Python netaddr find closest Ip address match


code:
def increment_invoice_number():
    last_invoice = Invoice.objects.all().order_by('id').last()
    if not last_invoice:
         return 'MAG0001'
    invoice_no = last_invoice.invoice_no
    invoice_int = int(invoice_no.split('MAG')[-1])
    new_invoice_int = invoice_int + 1
    new_invoice_no = 'MAG' + str(new_invoice_int)
    return new_invoice_no

rawDescription: Auto increament the invoice number in django backend for new invoice


code:
from bisect import bisect_left

istart = 0
while istart < len(hugelist):
    ifinish = bisect_left(hugelist, (maxx, 0, 0), lo=istart)
    # Now work on the slice hugelist[istart:ifinish].
    # It's possible that istart == ifinish, i.e. that the
    # slice is empty!
    maxx += deltax
    istart = ifinish

rawDescription: python while loop to break up sorted list/array

description: Python while loop to break up sorted list/array


rawDescription: Adding parentheses around a string matched by a regex in Python


rawDescription: How to append to .mat file using scipy.io.savemat?

description: Append to .mat file using scipy.io.savemat


code: topic_links = soup.select('dd a[href*=viewtopic.php]')

rawDescription: BeautifulSoup Grabbing a certain href link and storing it


code: [["First Element of List {0}".format(i)] for i in range(int(input("How Many?")))]

rawDescription: Make a for-loop that makes "n" lists (i.e. 5 lists when n= 5 or 10 lists when n=10)


code: max(arg1, arg2, arg3)

rawDescription: Python inspect module: keyword only args


code:
alist = []
for fname in ('inputFile.csv','lat.csv','lon.csv'):
    with open(fname) as f:
        data = np.fromfile(f,sep=',')
        alist.append( data.ravel() )
a = np.array(alist).T

rawDescription: Translating a gridded csv file with numpy


code:
import csv

XYZ = []
with open("data.csv") as csv_data:
    entries = csv.reader(csv_data, delimiter=",")
    # This can be done with list comprehension, but will be difficult to read
    for entry in entries:
        XYZ.append({
            "name": entry[0],
            "type": entry[1],
            "link": entry[2],
            "level": entry[3]
        })

rawDescription: Implementing array of structures( similar to C) in python by reading data from a file


code: prob = float(prob)

rawDescription: Python: separate results of re.findall

description: Python: separate results of re.findall


code: re.compile(value + '(?!\d)')

rawDescription: Use regular expressions to match any number of characters as long as the first character isn't a digit


code:
your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a

rawDescription: Python Brute Force algorithm

description: Python Brute Force algorithm


code:
out = []
for d, vals in itertools.groupby(sorted(dd, key=func), key=func):
    d['code'] = [val['code'] for val in vals]
    out.append(d)

rawDescription: group dictionary by values in a new nested one

description: Group dictionary by values in a new nested one


rawDescription: Python string FIFO

description: Python string FIFO


rawDescription: Incorrect Output While Comparing Two Lists


rawDescription: How would I scale a 2-dimensional array in python?


code:
class A(QtGui.QWidget):
    def __init__(self):
        super().__init__()

        self.x = 1

        self._initProperties() # Special method for changing values with inheritance
    # end Constructor

    def _initProperties(self):
        """Initialize special inheritance properties."""
        self.setLayout(QtGui.QVBoxLayout())
    # end _initProperties

    def do_something(self):
        return self.x

class B(A):
    # def __init__(self):
    #     super().__init__()
    #
    #     self.y = 2
    # # Because we have _initProperties that will happen at the appropriate time we don't
    # really need __init__. Just use _initProperties.
    # However, I would still use __init__. I just commented it out as an example.

    def _initProperties(self):
        """Initialize special inheritance properties.
        Note: We did not call super, so we are not using the parents _initProperties methods.
              We are overriding the parent method.
        """
        self.y = 2
        self.setLayout(QtGui.QHBoxLayout())
    # end _initProperties

    def do_something(self):
        return super().do_something() + self.y

rawDescription: Sharing code between two almost identical widgets PySide


code:
to_keep = [n for n in outdeg if outdeg[n] != 1]
G.subgraph(to_keep)

rawDescription: How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges?

description: Only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges


code:
from pprint import pprint
date_list = ["1-10-2015","2-10-2015", "3-10-2015"]
cur = collection.aggregate([
    {"$match": {"Booked Date": {"$in": date_list}}},
    {"$project": {
        "Room No": 1,
        "available_date": {
            "$setDifference": [date_list, "$Booked Date"]
        }
    }}
])

rawDescription: Find values from MongDB from an array for only one date


code:
import urllib2
f = urllib2.urlopen('http://www.python.org/')
html = f.read()

rawDescription: Saving information from URL to MySQL database


code:
a
c
a >= c
c <= a

rawDescription: can't compare datetime.datetime to numpy.ndarray

description: Can't compare datetime.datetime to numpy.ndarray


code:
import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]

rawDescription: How can I search sub-folders using glob.glob module in Python?

description: Search sub-folders using glob.glob module in Python


rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


code:
x = 123.0
dist = int(math.log10(abs(x)))

rawDescription: python find first non-zero digit after decimal point

description: Python find first non-zero digit after decimal point


code:
from itertools import imap

with open(filename, 'r') as inputfile:
    key_def_pairs = dict(pairwise(imap(str.rstrip, inputfile)))

rawDescription: Linking two items from two seperate lists together. python


code:
import threading
lock = threading.Lock()
x = 0
def foo():
    global x
    for i in xrange(1000000):
        with lock:
            x += 1
threads = [threading.Thread(target=foo), threading.Thread(target=foo)]
for t in threads:
    t.daemon = True
    t.start()
for t in threads:
    t.join()
print(x)

rawDescription: why using multiple threading to get the sum is correct?

description: Why using multiple threading to get the sum is correct


code:
def split_special(s):
    d = { ':)': '<HAPPY_SMILEY>', ':(': '<SAD_SMILEY>'}
    for smiley, placeholder in d.iteritems():
        s = s.replace(smiley, placeholder)
    s = ''.join(filter(lambda c: c not in '.,!', list(s)))
    for smiley, placeholder in d.iteritems():
        s = s.replace(placeholder, smiley)
    return s.split()

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code:
one = [{k: dic[k] for k in ('restaurant', 'lunch_menu')} for dic in lst]
two = [{k: dic[k] for k in ('restaurant', 'dinner_menu')} for dic in lst]

rawDescription: Creating a copy of a list of dictionaries with a subset of keys


code:
def notebook_install(overwrite=True, user=True):
    import os
    from notebook import install_nbextension
    from notebook.services.config import ConfigManager
    from IPython.display import display, Javascript

    js_path = os.path.join( os.path.dirname(__file__), 'helloworldjs')
    install_nbextension(js_path, overwrite=overwrite,
                        symlink=False, verbose=0, user=user)

rawDescription: Import a iPython Custom Widget Function (File Structure?)


code:
class Person(object):
    def __init__(self):
        self.firstName = None
        self.lastName = None
        self.age = None

rawDescription: Automatically setting getter, setter and deleter in python


rawDescription: Control size of text-only buttons in QToolBar


code:
l
sub

rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


code:
import platform
platform.platform()

rawDescription: What is the most stable and Pythonic cross-platform way to separate a string of path,filename,ext into three separate variables?


code: chars = set(chars)

rawDescription: Why is list element replacement slower than string element replacement in python?


code:
mask
threshold = 3
binary_closing(mask, structure=np.ones(threshold))
numpy_binary_closing(mask,threshold)
mask | binary_closing(mask, structure=np.ones(threshold))
mask| numpy_binary_closing(mask,threshold)

rawDescription: Find consecutive unmasked values

description: Find consecutive unmasked values


code: from scipy.interpolate import interp1d

rawDescription: Interpolating an array within an astropy table column


rawDescription: How to avoid user to click outside popup Dialog window using Qt and Python?

description: Avoid user to click outside popup Dialog window using Qt and Python


code:
from matplotlib.dates   import  DateFormatter,    \
                                AutoDateLocator,   \
                                HourLocator,        \
                                MinuteLocator,       \
                                epoch2num
from matplotlib.ticker  import  ScalarFormatter, FuncFormatter

rawDescription: matplotlib: marker size / color as extra dimension

description: Matplotlib: marker size / color as extra dimension


rawDescription: combining vectors as column matrix in numpy

description: Combining vectors as column matrix in numpy


code:
assert not belongs(setA, set1)
assert not belongs(setA, set2)
assert belongs(setA, set3)
assert belongs(setA, set4)

rawDescription: Pythonic way of writing belongs function in two sets


code:
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'test')
        frame.Show(True)
        server.app = frame
        #Note the server.app

rawDescription: Single Instance Application - Passing commands


rawDescription: Global vs local variable efficiency in multiple function call


rawDescription: Is there a Python module for transparently working with a file-like object as a buffer?


code:
for ss in wn.synsets('small'):
    print(ss)
    for sim in ss.similar_tos():
        print('    {}'.format(sim))

rawDescription: How to get synonyms from nltk WordNet Python

description: Get synonyms from nltk WordNet Python


code:
from itertools import groupby

list1 = [
    'LT50300281984137PAC00_sr_band1.tif',
    'LT50300281984137PAC00_sr_band2.tif',
    'LT50300281984137PAC00_sr_band3.tif',
    'LT50300281994260XXX03_sr_band1.tif',
    'LT50300281994260XXX03_sr_band2.tif',
    'LT50300281994260XXX03_sr_band3.tif'
]

list2 = [
    'LT50300281984137PAC00_mask.tif',
    'LT50300281994260XXX03_mask.tif'
]

def extract_key(s):
    return s[:s.index('_')]

l = sorted(list1 + list2, key=extract_key)
l = [tuple(items) for s, items in groupby(l, key=extract_key)]

rawDescription: Zip Lists together based on many to one relationship


code:
#!/usr/bin/env python3
import math
import struct
import alsaaudio
from itertools import *

def sine_wave(frequency=440.0, framerate=44100, amplitude=0.5):
    """Stolen from here: http://zacharydenton.com/generate-audio-with-python/"""
    period = int(framerate / frequency)
    if amplitude > 1.0: amplitude = 1.0
    if amplitude < 0.0: amplitude = 0.0
    lookup_table = [float(amplitude) * math.sin(2.0*math.pi*float(frequency)*(float(i%period)/float(framerate))) for i in range(period)]
    return (lookup_table[i%period] for i in count(0))

sound_out = alsaaudio.PCM()  # open default sound output
sound_out.setchannels(1)  # use only one channel of audio (aka mono)
sound_out.setrate(44100)  # how many samples per second
sound_out.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)  # sample format

for sample in sine_wave():
    # alsa only eats binnary data
    b = struct.pack("<f", sample)  # convert python float to binary float
    sound_out.write(b)

rawDescription: How to play a sound onto a input stream

description: Play a sound onto a input stream


code:
fig3 = plt.figure()
plt.plot(np.random.randn(10000), 'g-', rasterized=True)

multipage('multipage_w_raster.pdf', [fig2, fig3], dpi=250)

rawDescription: Saving all open matplotlib figures in one file at once


code:
strList = ['blablahihix', 'somethinghihi']
p = re.compile(r'(.+?)\1+')
[set(p.findall(i)) for i in strList]
# from functools import reduce  # In Python 3.x
reduce(lambda a, b: a & b, (set(p.findall(i)) for i in strList))

rawDescription: FInd repeated pattern between strings

description: FInd repeated pattern between strings


code:
line1, line2 = 'first', 'frost'
for k, (x, y) in enumerate(zip(line1, line2)):
    print('Match' if x == y else 'Mismatch', 'on position', k)

rawDescription: Position based matching of 2 strings

description: Position based matching of 2 strings


code:
rval, updates = theano.scan(_step,
                            sequences=[mask, state_below],
                            outputs_info=[tensor.alloc(numpy_floatX(0.),
                                                       n_samples,
                                                       dim_proj),
                                          tensor.alloc(numpy_floatX(0.),
                                                       n_samples,
                                                       dim_proj)],
                            name=_p(prefix, '_layers'),
                            n_steps=nsteps)
return rval[0]

rawDescription: GRU implementation in Theano

description: GRU implementation in Theano


code:
connect(self, hostname, port=22, username=None, password=None,
        pkey=None, key_filename=None, timeout=None, allow_agent=True,
        look_for_keys=True, compress=False)

rawDescription: paramiko ssh.connect - what arguments to send?

description: Paramiko ssh.connect - what arguments to send


code:
from PySide import QtGui

class MyTableWidget(QtGui.QTableWidget):

    def __init__(self):
        super().__init__(None)
        button = QtGui.QPushButton('Click me', self)
        button.clicked.connect(self.buttonClicked)
        self.setCellWidget(2, 1, button)

    def buttonClicked(self):
        button = self.sender()
        print(button.parent() is self)

app = QtGui.QApplication([])
table = MyTableWidget()
table.show()
app.exec_()

rawDescription: How to find out to which QTableWidget a QPushbutton belongs to?

description: Find out to which QTableWidget a QPushbutton belongs to


code:
df = pd.read_csv('foo.csv', sep=',', header=None, parse_dates=[[0, 1]])
df.columns = ['date', 'val']
df.set_index('date', inplace=True)
df

rawDescription: Hourly frequency count with Python

description: Hourly frequency count with Python


rawDescription: Python argparse treat arguments in different ways


code:
def read(ser, queue):
    while True:
         queue.put(ser.readline())
threading.Thread(target=read, args=(ser, queue)).start()

rawDescription: Confusing 'readline' warning in the documentation


rawDescription: DESede in Java and 3des in python

description: DESede in Java and 3des in python


code:
# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
         pathex=['C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting'],
         hiddenimports=[],
         hookspath=None,
         runtime_hooks=None)
for d in a.datas:
    if 'pyconfig' in d[0]:
        a.datas.remove(d)
        break
a.datas += [('Logo.png','C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok     splitting\\Logo.png', 'Data')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='AMOS_Visualizer.exe',
      debug=False,
      strip=None,
      upx=True,
      console=True , icon='C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting\\AMOS.ico')

rawDescription: Pyinstaller --onefile include image in exefile


code:
my_list = ([0, 0, 0],
           [1, 1, 1],
           [3, 3, 3])

threed_array = np.array(my_list, np.float_)
atom_kdtree = KDTree(3)
atom_kdtree.set_coords(threed_array)

# The search is done here. Every point within a radious < 2 from [0, 0, 0].
atom_kdtree.search(threed_array[0], 2.00000000)

# Here we print the points
print(atom_kdtree.get_indices())
print(atom_kdtree.get_radii())

rawDescription: 'search' and all other methods from Biopython.KDTree library gives output as 'None' Although KDTree is created succesfully


code: C = [getattr(obj, 'Bar', None) for obj in (A, B)]

rawDescription: Python: Get attribute from a list of objects of the same type in the most efficient way


code:
import numpy as np

# Generate grids of coordinates from a min, max, and spacing
dx, dy = 0.5, 0.5

# For the larger grid...
Axmin, Axmax = -180, 180
Aymin, Aymax = -90, 90

# For the smaller grid...
Bxmin, Bxmax = -5, 10
Bymin, Bymax = 30, 40

# Generate the indicies on a 2D grid
Ax = np.arange(Axmin, Axmax+dx, dx)
Ay = np.arange(Aymin, Aymax+dy, dy)
Ax, Ay = np.meshgrid(Ax, Ay)

Bx = np.arange(Bxmin, Bxmax+dx, dx)
By = np.arange(Bymin, Bymax+dy, dy)
Bx, By = np.meshgrid(Bx, By)

# Find the corner of where the two grids overlap...
ix, iy = np.argwhere((Ax == Bxmin) & (Ay == Bymin))[0]

# Assert that the coordinates are identical.
assert np.all(Ax[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == Bx)
assert np.all(Ay[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == By)

rawDescription: Where do two 2-D arrays begin to overlap each other?


code: d

rawDescription: Python - Printing words by length

description: Python - Printing words by length


rawDescription: Trivia Game and Choice Function

description: Trivia Game and Choice Function


code:
def combinations(rest, prefix = [], result = []):
    if rest:
        first = rest.pop()
        for item in first:
            prefix.append(item)
            combinations(rest, prefix, result)
            prefix.pop()
        rest.append(first)
    else:
        result.append(list(reversed(prefix)))
    return result

rawDescription: How do I create a recursion of multiple for loops of lists in Python to get combination?

description: Create a recursion of multiple for loops of lists in Python to get combination


code:
import inspect
import functools

def autoargs(*include,**kwargs):
    def _autoargs(func):
        attrs,varargs,varkw,defaults=inspect.getargspec(func)
        def sieve(attr):
            if kwargs and attr in kwargs['exclude']: return False
            if not include or attr in include: return True
            else: return False
        @functools.wraps(func)
        def wrapper(self,*args,**kwargs):
            # handle default values
            for attr,val in zip(reversed(attrs),reversed(defaults)):
                if sieve(attr): setattr(self, attr, val)
            # handle positional arguments
            positional_attrs=attrs[1:]
            for attr,val in zip(positional_attrs,args):
                if sieve(attr): setattr(self, attr, val)
            # handle varargs
            if varargs:
                remaining_args=args[len(positional_attrs):]
                if sieve(varargs): setattr(self, varargs, remaining_args)
            # handle varkw
            if kwargs:
                for attr,val in kwargs.iteritems():
                    if sieve(attr): setattr(self,attr,val)
            return func(self,*args,**kwargs)
        return wrapper
    return _autoargs

rawDescription: Automatically setting class member variables in Python


code:
s = r'\x09'
s.decode('unicode_escape')

rawDescription: How to convert "\x09" back to tab

description: Convert "\x09" back to tab


rawDescription: Problem with exiting a Word doc using Python


rawDescription: How to increment in python-maya?

description: Increment in python-maya


code:
"""
print 'anything with sinple quotes instead of double quotes'
"""

rawDescription: Deactivate code in python without changing indentation or adding comments


rawDescription: How to map word combinations in python

description: Map word combinations in python


code:
def useful_lines(lines, stopterm):
    for line in lines:
        if stopterm in line:
            yield line
            break
        yield line

usefullines = useful_lines(lines, stopterm)
# or...
for line in useful_lines(lines, stopterm):
    # ... do stuff
    pass

rawDescription: Python: item for item until stopterm in item?


rawDescription: Creating a bit mask with BigInts

description: Creating a bit mask with BigInts


code:
def partial_derivative(func, var=0, point=[]):
    args = point[:]
    def wraps(x):
        args[var] = x
        return func(*args)
    return derivative(wraps, point[var], dx = 1e-6)

rawDescription: scipy.misc.derivative for mutiple argument function

description: Scipy.misc.derivative for mutiple argument function


code:
timeit.timeit("{('column_%d' % i): range(i,81, 9) for i in xrange(90)}", number = 100000)
timeit.timeit("index=range(0,81);{('column_%d' % i): index[i:81:9] for i in xrange(90)}", number = 100000)
timeit.timeit("index=range(0,81);{('column_' + str(i)): index[i:81:9] for i in xrange(90)}", number = 100000)

rawDescription: Possible to compress into a dictionary comprehension?


rawDescription: Search and filter pandas dataframe with regular expressions


code:
somedata = {}
somedata['was_false_in_base'] = False

rawDescription: Why do attribute references act like this with Python inheritance?


code:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

rawDescription: Change the key value in python dictionary


code:
seed = raw_input("> ")
goblins_defeated, lucky, princesshelp, end = map(bool, map(int, seed.split()))

rawDescription: Assigning variables from a list, or "how to make an elegant save function"


code:
class A:
    def __init__(self, shape):
        self.shape = shape
        self.matrix = numpy.zeros(shape)

    def __getstate__(self):
        return (self.shape,)

    def __setstate__(self, state):
        self.shape, = state
        self.matrix = numpy.zeros(self.shape)

rawDescription: How to pickle a class instance's variables selectively?

description: Pickle a class instance's variables selectively


code:
def bb(x):
    for n in x:
        if isinstance(n, str):
            print(n)
        elif isinstance(n, tuple):
            count, value = n
            for i in range(count):
                print(value)

rawDescription: I need to print/return multiple elements from tuple in Python


rawDescription: Dividing with big(ish) numbers in C (Get a zero, when I know it isn't zero)


code:
import ast
with open("test.txt") as f:
    user_info = ''
    registros = []
    for line in f:
        if line.startswith('['):
            registros.append(ast.literal_eval(line))
        else:
            user_info += line

rawDescription: How to read just lists in a text file in Python?

description: Read just lists in a text file in Python


code:
TAGS = ((1,'DOG'),(2,'CAT'),(3,'HORSE')) # and so on

class MyThing(models.Model):
   name = models.CharField(max_length=200)
   tag = models.IntegerField(choices=TAGS)

rawDescription: State object in django

description: State object in django


code:
def save_file(df, file_name):
    """
    saves to a csv file in the german excel format, e.g. colon seperated
    :rtype : None
    :param df: the dataframe to be saved
    :param file_name: the filename
    """
    assert isinstance(df, DataFrame)
    df.to_csv(file_name, sep=";")

rawDescription: data editor in Python?

description: Data editor in Python


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(2015)

y = np.random.randint(5, 50, (10,3))
x = np.arange(10)
df = pd.DataFrame(y, index=x)

df = df.divide(df.sum(axis=1), axis=0)
ax = df.plot(kind='area', stacked=True, title='100 % stacked area chart')

ax.set_ylabel('Percent (%)')
ax.margins(0, 0) # Set margins to avoid "whitespace"

plt.show()

rawDescription: 100% area plot of a pandas DataFrame

description: 100% area plot of a pandas DataFrame


code: '\r\n'.join(line for line in a.splitlines() if line)

rawDescription: Python string clean up: How can I remove the excess of newlines of a string in python?


code:
key_names = ["%s_%s" % (friend.facebook_id, page_key) for friend in friends]
markers = db.get(key_names)
# Use get_value_for_datastore to get the entity key without making a trip to the
# datastore
friends_who_bookmarked_keys = [marker.__class__.user.get_value_for_datastore(marker)\
                          for marker in markers]
friends = db.get(friends_who_bookmarked_keys)

rawDescription: List query with, facebook friends in list?


rawDescription: Use ElementTree's findall() to match text of elements


rawDescription: comparing two different lists

description: Comparing two different lists


code: datetime.strptime('2011221', '%Y%W%w')

rawDescription: Get date from ISO week number in Python

description: Get date from ISO week number in Python


code:
def findLetters(wordlist):
    letterList = []
    letters = 'abcdef'
    for word in wordlist:
        if all(letter in letters for letter in word):
            letterList.append(word)
    return letterList

rawDescription: Python text file. Finding strings that contain only characters 'abcdef'


code:
from functools import reduce
print(reduce(lambda a,b: a[b], s.split("."), obj))

rawDescription: Fetching nested value given dot notation


code:
b = spynner.Browser()
b.click("#someAnchorId", wait_load=True)

rawDescription: Use Python Spynner to download a file with a JavaScript doPostBack link


rawDescription: Python: Generating YYMM string between two dates


code: re.match('\\\r', s)

rawDescription: How python and the regex module handle backslashes


code:
import cv2
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('example_gray.jpg',gray)

rawDescription: What's the best way to greyscale in python/django?


code:
data = dict(foo=12, bar=dict(dd=12), ex=dict(a=dict(b=dict(v=12))))
json.loads(re.sub("12", "33", json.dumps(data)))

rawDescription: More pythonic way to change multilevel dictionary values


rawDescription: How does Python take in an expression as a parameter to a function?


code:
from distutils.version import StrictVersion
StrictVersion('00.03') > StrictVersion('00.10')
StrictVersion('00.03') > StrictVersion('00.02')

rawDescription: How to accurately change a parsed version number in string form to numeric?

description: Accurately change a parsed version number in string form to numeric


code:
#! /usr/bin/env python
"""Note: Documentation clearly states, that classes can be pickled,
but only iff they "are defined at the top level of a module"."""
from __future__ import print_function

import pickle

class Person(object):
    """Minimal class to showcase (un)pickle."""
    FULL_NAME_DEFAULT = 'N.N.'

    def __init__(self, full_name=None):
        """Detected initializer (show unpickling behaviour)."""
        if full_name is not None:
            self.full_name = full_name
        else:
            self.full_name = self.FULL_NAME_DEFAULT
        print("Initializer called!")
        self.say_hello()

    def say_hello(self):
        """A method to say a personalized hello."""
        print("Hello! My name is '%s'" % (self.full_name,))

def main():
    """Drive the dumps and loads of Person instances."""
    number_one = Person("Jane Awsome")
    print(number_one)
    print("# Serialize the person number_one ... with default protocol:")
    serialized_person = pickle.dumps(number_one)
    print("# Dump of the data representing the serialized_person:")
    print(serialized_person)
    print("# Now for something completely different ...")
    reborn = pickle.loads(serialized_person)
    print("# Back again a copy of number_one, no __init__ called ;-)")
    reborn.say_hello()

if __name__ == "__main__":
    main()

rawDescription: Python3: How to pickle class objects into text file and read it back?


code:
new_record = {"name": "john smith", "Age": 30, "phone_number": "556"}
filter_predicate = {"phone_number": new_record["phone_number"]}
test = r.table('users').filter(filter_predicate).count().eq(0)
r.branch(test, r.table('users').insert(new_record), None).run()

rawDescription: How do i prevent duplicate records on rethinkdb using python

description: Prevent duplicate records on rethinkdb using python


code:
if __name__=="__main__":
    topfunction()

rawDescription: Python profiling - What are the columns in runsnakerun output?


code:
xs = np.random.random((100,200))
ys = np.random.random((100,200))

f(xs,ys)

rawDescription: Numpy Array index problems

description: Numpy Array index problems


code:
out = np.zeros(A.shape[0], np.bool)     # output is False by default
out[first_idx] = True                   # set first occurrences to True

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


rawDescription: Permutating with repetition and rules between possible values


code: get_mp3_info(groups, pattern, "the Beatles_Abbey_Road-SomeWord-1969")

rawDescription: How to match regex with multiple overlapping patterns?

description: Match regex with multiple overlapping patterns


code:
#! /usr/bin/env python

import os
import random
import pygame
import math
import sys

os.environ["SDL_VIDEO_CENTERED"] = "1"

winw = 600
winh = 600
screen = pygame.display.set_mode((winw, winh))
pygame.display.set_caption(" Charger V1 Lvl1")

clock = pygame.time.Clock()

player1 = pygame.rect.Rect(32, 32, 24, 24)
rect1 = pygame.rect.Rect(550, 550, 16, 16)
rect2 = pygame.rect.Rect(500, 850, 16, 16)

class Player(object):
    def __init__(self):
        self.rect = player1

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_LEFT]:
            self.rect.move_ip(-2, 0)
        if key[pygame.K_RIGHT]:
            self.rect.move_ip(2, 0)
        if key[pygame.K_UP]:
           self.rect.move_ip(0, -2)
        if key[pygame.K_DOWN]:
           self.rect.move_ip(0, 2)

    def collide(self,enemy,enemy_list):
        if self.rect.colliderect(enemy.rect):  # Tests if the player is touching an enemy
            enemy_list.remove(enemy)  # Removes the enemy from the enemy list (Explained lower)

    def draw(self, surface):
        pygame.draw.rect(surface, (0, 0, 128), self.rect)

class Lvl1a(object):
    def __init__(self):
        self.rect = rect1
        self.x = 0
        self.y = 0

    def move(self):
        self.rect.move_ip(0, -1)

    def draw(self, surface):
        pygame.draw.rect(surface, (100, 100, 100), self.rect)

class Lvl1b(object):
    def __init__(self):
        self.rect = rect2
        self.x = 0
        self.y = 0

    def move(self):
        self.rect.move_ip(0, -1)

    def draw(self, surface):
        pygame.draw.rect(surface, (100, 100, 100), self.rect)

pygame.init()

player = Player()
clock = pygame.time.Clock()
lvl1a = Lvl1a()
lvl1b = Lvl1b()
enemies = [lvl1a,lvl1b]  # Create the enemies list

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           break
           running = False

    screen.fill((255, 255, 255))

    for enemy in enemies:  # Runs through the enemy list
        enemy.move()  # Moves the enemy
        player.collide(enemy,enemies)  # Checks if enemy is touching player
        enemy.draw(screen)  # Renders Enemies in the list

    player.draw(screen)
    player.handle_keys()
    pygame.display.update()

    clock.tick(40)

rawDescription: Python Pygame Enemy Collision

description: Python Pygame Enemy Collision


code:
for f in files:
    file = SrcFile(f)
    print(file.name, file.seqlength())

rawDescription: Python3: How to get value from other file with function within class?


code:
gtk-goto-last
gtk-go-back
gtk-go-forward
gtk-apply
gtk-cancel
gtk-close

rawDescription: How do I change the built-in button labels on a gtk.Assistant?

description: Change the built-in button labels on a gtk.Assistant


code:
for rownum in xrange(sh1.nrows):
    wr.writerow(sh1.row_values(rownum))

rawDescription: Python - Using csv and xlrd module to write multi-row excel file to one row csv file


code: pd.concat([dt.apply(ci, axis=1, op=x) for x in [sub, add]], axis=1)

rawDescription: pandas lambda tuple mapping quesion

description: Pandas lambda tuple mapping quesion


code: res

rawDescription: Comparing and Printing values from two dictionaries


code:
g = Graph("/db/productiondata")
g = Graph("/db/testdata")

rawDescription: Can I have a temporary/alternative neo4j graph for testing?

description: Have a temporary/alternative neo4j graph for testing


code:
views.py
from myapp.forms import MenuForm

def menuForm(request):
    if request.method == 'POST': # If the form has been submitted...
        form = MenuForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/success/') # Redirect after POST

    else:
        form = MenuForm() # An unbound form

    return render(request, 'hello.html', {
        'form': form,
    })

rawDescription: newbie Django Choicefield/Charfield display on html page

description: Newbie Django Choicefield/Charfield display on html page


rawDescription: Check a condition in a string with regex


code: x = all(list_of_bools)

rawDescription: Check at once the boolean values from a set of variables


code:
def PolyArea(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

rawDescription: Calculate area of polygon given (x,y) coordinates


code:
def pdf(self,x,*args,**kwds):
    loc,scale=map(kwds.get,['loc','scale'])
    args, loc, scale = self._fix_loc_scale(args, loc, scale)
    x,loc,scale = map(asarray,(x,loc,scale))
    args = tuple(map(asarray,args))
    x = asarray((x-loc)*1.0/scale)
    cond0 = self._argcheck(*args) & (scale > 0)
    cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
    cond = cond0 & cond1
    output = zeros(shape(cond),'d')
    putmask(output,(1-cond0)+np.isnan(x),self.badvalue)
    if any(cond):
        goodargs = argsreduce(cond, *((x,)+args+(scale,)))
        scale, goodargs = goodargs[-1], goodargs[:-1]
        place(output,cond,self._pdf(*goodargs) / scale)
    if output.ndim == 0:
        return output[()]
    return output

rawDescription: How to call numpy/scipy C functions from Cython directly, without Python call overhead?

description: Call numpy/scipy C functions from Cython directly, without Python call overhead


code: response = opener.open(post_url, binary_data)

rawDescription: How to log in to a website with urllib?

description: Log in to a website with urllib


code:
Week = 4

PlanetData = [
    ['Mercury', 69.8, 46.0, planet_time(1.5)],
    ['Venus', 108.9, 107.5, planet_time(-9.0)],
    ['Earth', 152.1, 147.1, planet_time(-1.5)],
    ['Mars', 249.2, 206.7, planet_time(21.0)],
    ["Halley's Comet",5250, 87.7, planet_time(1.54e3)],
]

for Name, Max, Min, Time in PlanetData:
    print("{}, {}".format(Name, Time))

rawDescription: How do I add different amounts to one inputted variable?

description: Add different amounts to one inputted variable


rawDescription: Trying to get all image links of reddit.com using python and re


rawDescription: a way to have django SITEURL constant in settings.py

description: A way to have django SITEURL constant in settings.py


code:
from copy import deepcopy
list2 = deepcopy(list1)

rawDescription: Passed argument/parameter in function is still being changed after removing the reference/alias


code:
def foo(self, b=None):
    return bar(b if b is not None else self.b)

rawDescription: Refactoring "x if x is not None else y" to "x or y"


code: last_idx = bisect_right(sorted_ips, last, first_idx)

rawDescription: How to search a large database of IP addresses in a timely manner?

description: Search a large database of IP addresses in a timely manner


code:
for j,k in enum_upperdiag(mat):
   function(mat[j],mat[k])

rawDescription: NumPy: Iterating over items to right, bottom of given element w/ its index


code: result[key] = df.groupby(['group'])[key].agg(['first', 'last'])

rawDescription: Generate a multi-indexed dataframe from a dictionary with different length of values


code:
import numpy as np
import pandas as pd

def combine64(years, months=1, days=1, weeks=None, hours=None, minutes=None,
              seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
    years = np.asarray(years) - 1970
    months = np.asarray(months) - 1
    days = np.asarray(days) - 1
    types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
             '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
    vals = (years, months, days, weeks, hours, minutes, seconds,
            milliseconds, microseconds, nanoseconds)
    return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
               if v is not None)

dt = pd.Series(['27.02-11.03.2014', '10-11.06.2014'])

df = dt.str.extract(r'(?P<start_day>\d+)(?:\.(?P<start_month>\d+))?-(?P<end_day>\d+)\.(?P<end_month>\d+)\.(?P<year>\d+)')
df = df.astype('float')
df['start_month'] = df['start_month'].fillna(value=df['end_month'])
df['start'] = combine64(df['year'], df['start_month'], df['start_day'])
df['end'] = combine64(df['year'], df['end_month'], df['end_day'])
df = df[['start', 'end']]
print(df)

rawDescription: Human format date range parsing

description: Human format date range parsing


code: b = [e if i != 0 else 5 for i, e in enumerate(a)]

rawDescription: Make a copy of a list and set an element in one line?


code: gb.columns = ['num_ids', 'total_amount', 'max_amount']

rawDescription: Grouped Aggregation on multiple columns in Pandas


code:
#udp broadcast
import socket, time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

while True:
    data = 'test'.encode()
    s.sendto(data, ('255.255.255.255', 1080))
    time.sleep(1)

rawDescription: python socket connecting to different subnet/domain

description: Python socket connecting to different subnet/domain


code: pixarray = (ctypes.c_int * (w_px * h_px))()

rawDescription: efficiently convert string (or tuple) to ctypes array

description: Efficiently convert string (or tuple) to ctypes array


rawDescription: Python regex to print all sentences that contain two identified classes of markup


rawDescription: To get the common letters in two words without repetition


code:
cmap3 = mpl.colors.ListedColormap(sns.husl_palette(256, .33, .85, .6))

plt.figure()
plt.imshow(img, cmap=cmap3)
plt.colorbar()

rawDescription: seaborn husl or hsl color palette is not working: remains default black and white colors

description: Seaborn husl or hsl color palette is not working: remains default black and white colors


code: Model(**kwargs)

rawDescription: Django - create a new instance of a model


code:
from multiprocessing import Process, Queue, JoinableQueue
import types
from time import sleep
import copy_reg

def _pickle_method(method):
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)

copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)

class Worker(Process):
    def __init__(self, cmd_queue, res_queue):
        self.cmd_queue = cmd_queue
        self.res_queue = res_queue
        Process.__init__(self)

    def run(self):
        for f, args, kwargs in iter(self.cmd_queue.get,
                                    (None, (), {})): # None is our sentinel
            self.res_queue.put( f(*args, **kwargs) )
            self.cmd_queue.task_done() # Mark the task as done.
        self.res_queue.put(None) # Send this to indicate no more results are coming
        self.cmd_queue.task_done() # Mark the task as done

class Agent(object):
    def __init__(self):
        self.cmd_queue = JoinableQueue()
        self.res_queue = Queue()
        self.worker = Worker(self.cmd_queue, self.res_queue)
        self.worker.start()

    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['cmd_queue']
        del self_dict['res_queue']
        del self_dict['worker']
        return self_dict

    def __setstate__(self, self_dict):
        self.__dict__ = self_dict

    def produce(self, f, *args, **kwargs):
        self.cmd_queue.put((f, args, kwargs))

    def do_some_work(self):
        self.produce(self.foo, waka='waka')

    def do_some_other_work(self):
        self.produce(self.bar, humana='humana')

    def send_sentinel(self):
        self.produce(None)

    def foo(self, **kwargs):
        sleep(2)
        return('this is a foo')

    def bar(self, **kwargs):
        sleep(4)
        return('this is a bar')

    def get_results(self):  #blocking call
        res = []
        self.cmd_queue.join() # This will block until task_done has been called for every put pushed into the queue.
        for out in iter(self.res_queue.get, None):  # None is our sentinel
            res.append(out)
        return res

#This is the interface I'm looking for.
if __name__=='__main__':
    agents = [Agent() for i in range(50)]
    #this should flow quickly as the calls are added to cmd_queues
    for agent in agents:
        agent.do_some_work()
        agent.do_some_other_work()
        agent.send_sentinel()
    for agent in agents:
        print(agent.get_results())

rawDescription: Python multiprocessing in objects

description: Python multiprocessing in objects


code:
logger = logging.getLogger("Design")
logger.setLevel(logging.DEBUG)
logger.handlers = []

#create a file handler which logs all INFO, DEBUG, ERROR messages

fh = logging.FileHandler('Design.log', mode='w')

fmt = logging.Formatter('[%(levelname)s] %(message)s')

fh.setFormatter(fmt)

#adding the handlers to logger
logger.addHandler(fh)

rawDescription: Logger prints to console even though FileHandler is defined


code:
# create subsets based on criterion
subsets = collections.defaultdict(list)
for item in items:
    subsets[calculate_criteria(item)].append(item)

rawDescription: Elegant optimization in Python

description: Elegant optimization in Python


code:
class CheapClone(object):
    def __init__(self, original):
        self.__dict__ = original.__dict__

rawDescription: SqlAlchemy optimizations for read-only object models


code:
a = ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar']
b = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar']
[idx for idx, values in enumerate(zip(a, b)) if values == ("foo", "bar")]

rawDescription: Subarray from lists of strings

description: Subarray from lists of strings


rawDescription: Check if number is made of both 0 and 1 using regex


code: string = "number is %d" % 1

rawDescription: What is the % operator in python for?

description: What is the % operator in python for


code:
df = pd.DataFrame({'foo':[1,2,3,4]})
df.to_html(classes='mytable')

rawDescription: How to define html id for Pandas Dataframe

description: Define html id for Pandas Dataframe


code: pd.concat( [df1,df2], axis=1)

rawDescription: Conditionally concatenate aggregated columns from different DataFrames into a new DataFrame


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

def fmt(x, y):
    return 'x: {x:0.2f}\ny: {y:0.2f}'.format(x = x, y = y)

class DataCursor(object):
    # http://stackoverflow.com/a/4674445/190597
    """A simple data cursor widget that displays the x,y location of a
    matplotlib artist when it is selected."""
    def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20),
                 formatter = fmt, display_all = False):
        """Create the data cursor and connect it to the relevant figure.
        "artists" is the matplotlib artist or sequence of artists that will be
            selected.
        "tolerance" is the radius (in points) that the mouse click must be
            within to select the artist.
        "offsets" is a tuple of (x,y) offsets in points from the selected
            point to the displayed annotation box
        "formatter" is a callback function which takes 2 numeric arguments and
            returns a string
        "display_all" controls whether more than one annotation box will
            be shown if there are multiple axes.  Only one will be shown
            per-axis, regardless.
        """
        self._points = np.column_stack((x,y))
        self.formatter = formatter
        self.offsets = offsets
        self.display_all = display_all
        if not cbook.iterable(artists):
            artists = [artists]
        self.artists = artists
        self.axes = tuple(set(art.axes for art in self.artists))
        self.figures = tuple(set(ax.figure for ax in self.axes))

        self.annotations = {}
        for ax in self.axes:
            self.annotations[ax] = self.annotate(ax)

        for artist in self.artists:
            artist.set_picker(tolerance)
        for fig in self.figures:
            fig.canvas.mpl_connect('pick_event', self)

    def annotate(self, ax):
        """Draws and hides the annotation box for the given axis "ax"."""
        annotation = ax.annotate(self.formatter, xy = (0, 0), ha = 'right',
                xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
                bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
                arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')
                )
        annotation.set_visible(False)
        return annotation

    def snap(self, x, y):
        """Return the value in self._points closest to (x, y).
        """
        idx = np.nanargmin(((self._points - (x,y))**2).sum(axis = -1))
        return self._points[idx]
    def __call__(self, event):
        """Intended to be called through "mpl_connect"."""
        # Rather than trying to interpolate, just display the clicked coords
        # This will only be called if it's within "tolerance", anyway.
        x, y = event.mouseevent.xdata, event.mouseevent.ydata
        annotation = self.annotations[event.artist.axes]
        if x is not None:
            if not self.display_all:
                # Hide any other annotation boxes...
                for ann in self.annotations.values():
                    ann.set_visible(False)
            # Update the annotation in the current axis..
            x, y = self.snap(x, y)
            annotation.xy = x, y
            annotation.set_text(self.formatter(x, y))
            annotation.set_visible(True)
            event.canvas.draw()

x=[1,2,3,4,5]
y=[6,7,8,9,10]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
scat = ax.scatter(x, y)
DataCursor(scat, x, y)
plt.show()

rawDescription: Get data from plot with matplotlib

description: Get data from plot with matplotlib


code:
import sys
if (sys.version_info.major >= 2 and sys.version_info.minor >= 7):
    import argparse
    # ...
else:
    import optparse

rawDescription: Dynamically choosing Python library based on Python version


code: result = Py_BuildValue("");

rawDescription: How to return a tuple containing a None value from the C API?

description: Return a tuple containing a None value from the C API


code:
# simplified example from the tutorial
import gtk

urls = [
    'http://www.google.com',
    'http://www.google.com/android',
    'http://www.greatstuff.com',
    'http://www.facebook.com',
    ]
liststore = gtk.ListStore(str)
for s in urls:
    liststore.append([s])

completion = gtk.EntryCompletion()
completion.set_model(liststore)
completion.set_text_column(0)

entry = gtk.Entry()
entry.set_completion(completion)

# boilerplate
window = gtk.Window()
window.add(entry)

window.connect('destroy', lambda w: gtk.main_quit())
window.show_all()
gtk.main()

rawDescription: Entry with suggestions

description: Entry with suggestions


code:
import os

my_directory = 'some_directory'
max_files = 20

(_, _, my_files) = os.walk(my_directory).next()

if len([f for f in my_files if f.endswith('.txt')]) > max_files:
    for f in my_files[max_files-1:]:
        os.remove(os.path.join(my_directory, f))

rawDescription: Count how many text files in a directory using python 2.7 and edit them


rawDescription: Dict into Dict Python

description: Dict into Dict Python


code: remainder_list = [v for v in tuple_list if v not in exclude_set]

rawDescription: Why is using a dict so much faster to exclude one list from another?


code:
contents = phonebook_data.read()
if contents == "":       # Can be shortened to `if not contents:`
    print("Your contact book is empty.")

rawDescription: updating tkinter window (Python 3.4)

description: Updating tkinter window (Python 3.4)


code:
[Rectangle(top=2, bottom=3, left=3, right=5),
 Rectangle(top=5, bottom=6, left=3, right=4)]

rawDescription: Detecting rectangles (sub-arrays of same element value) in 2-d list


code: format(num if num >= 0 else (1 << 16) + num, '016b')

rawDescription: two's complement of numbers in python

description: Two's complement of numbers in python


code:
df
df['dt2'] = df['dt'].values.astype('<M8[h]')
df
df.dtypes

rawDescription: Truncate `TimeStamp` column to hour precision in pandas `DataFrame`


code:
def create_OuterClass(dct):
    # print('create_OuterClass: {0}'.format(dct))
    if '__OuterClass__' in dct:
        arg = dct['arg']
        InnerClass_instances = [create_InnerClass(dct2) \
                                for dct2 in dct['InnerClass_instances']]
        return OuterClass(arg, *InnerClass_instances)
    return dct

rawDescription: Python and JSON: using object_hook to do class hinting for multiple different classes


code:
from redis_manager import redis_manager

redis_manager.redis.stuff

rawDescription: How to handle Redis connection across multiple modules?

description: Handle Redis connection across multiple modules


code:
import argparse
import sys
parser=argparse.ArgumentParser()
action1=parser.add_argument('--foo')
action2=parser.add_argument('--bar',
                            help="Only use this if --foo is set")

argv=set(sys.argv)
if (( argv & set(action2.option_strings) ) and
      not ( argv & set(action1.option_strings) )):
                #^ set intersection
     parser.error(' or '.join(action1.option_strings)+
                  ' must be given with '+
                  ' or '.join(action2.option_strings))

rawDescription: python, argparse: enable input parameter when another one has been specified

description: Python, argparse: enable input parameter when another one has been specified


code:
import time

def onceEveryXSeconds(seconds):             # this creates the decorator
    def wrapper(f):                         # decorator for given 'seconds'
        f.last_execution = 0                # memorize last execution time
        def decorated(*args, **kwargs):     # the 'decorated' function
            if f.last_execution < time.time() - seconds:
                f.last_execution = time.time()
                return f(*args, **kwargs)
        return decorated
    return wrapper

rawDescription: Python For Loop List, Function Every 5min


code:
with open("ofile.txt","w") as f:
    for team in d:
        f.write(team)

rawDescription: How do I remove duplicate terms with scores from a text file?

description: Remove duplicate terms with scores from a text file


rawDescription: How can I search a folder which it's name contains specifc character in Python

description: Search a folder which it's name contains specifc character in Python


rawDescription: Link to URL based on form input upon clicking submit


rawDescription: How to pass a lambda expression to a C# constructor from an IronPython script?

description: Pass a lambda expression to a C# constructor from an IronPython script


code:
origin_key = db.Key.from_path('Origin', 123)
wines_query = db.Query(Wine).ancestor(origin_key)

rawDescription: Modeling Hierarchical Data - GAE

description: Modeling Hierarchical Data - GAE


code:
"""
for A in range(1,LargeNumber):
        DoSuff(A)
        DO Mode stuff
        ....
        Done(A)
"""

rawDescription: Deactivate code in python without changing indentation or adding comments


rawDescription: Django Access Primary Model Attribute with select_related


rawDescription: How to extract sublists from a string in Python?

description: Extract sublists from a string in Python


rawDescription: Get the offset for a specific time and timezone in python


code:
def test():
    while True:
        out = get()
        LThumbstickX = out[0]
        LThumbstickY = out[1]
        # and so on

rawDescription: Extract value from a list in another function in Python


code:
def extract_numbers(text):
    return ''.join([x for x in text if x.isdigit()])

rawDescription: How can I separate the numeric parts of filenames using Python?

description: Separate the numeric parts of filenames using Python


rawDescription: Element-wise logical AND on indeterminate number of Pandas Series


code:
from itertools import chain, repeat

def repeated(iterable, n=1):
    items = chain.from_iterable(repeat(item, n) for item in iterable)
    for item in items:
        yield item

    # Or, in Python3.3 you could do:
    yield from items

rawDescription: How to yield element multiple times

description: Yield element multiple times


code:
try:
    with open('test.txt', 'r') as ins: #Opens the file and closes it when Python is done with it
        array = []
        for line in ins:
            array.append(line.rstrip()) # appends each line of the file with trailing white space stripped

        for fahad in array:
            fahad += ".php" # for each item in the list 'array' it concatenates '.php' on to the end. The += operator is the same as fahad = fahad + '.php'
            print(fahad)

except FileNotFoundError: # this is part of a try/except block. If the file isn't found instead of throwing an error this will trigger. Right now nothing happens because of the pass statement but you can change that to print something if you like.
    pass

rawDescription: python read text file to array and edit the array

description: Python read text file to array and edit the array


code:
from collections import defaultdict
from pprint import pprint
import re

filenames = [
    "C7_S6_L001.sorted.bam",
    "C7_S6_L002.sorted.bam",
    "C7_S6_L003.sorted.bam",
    "C7_S6_L004.sorted.bam",

    "CL3_S8_L001.sorted.bam",
    "CL3_S8_L002.sorted.bam",
    "CL3_S8_L003.sorted.bam",
    "CL3_S8_L004.sorted.bam",

    "CL5-B1_S4_L001.sorted.bam",
    "CL5-B1_S4_L002.sorted.bam",
    "CL5-B1_S4_L003.sorted.bam",
    "CL5-B1_S4_L004.sorted.bam"
]

pattern = re.compile(r"([A-Z0-9-_]+)_L\d{3}\.sorted\.bam")
grouped = defaultdict(list)

for filename in filenames:
    match = pattern.search(filename)
    if match:
        key = match.group(1)
        grouped[key].append(filename)

pprint(grouped)

rawDescription: python regex matching file names

description: Python regex matching file names


code:
mydict = {'a': 1, 'b': 2, 'c': 3}

items = mydict.iteritems()
for key,value in items:
    if key == 'b':  # some condition
        try:
            key,value = next(items)
        except StopIteration:
            break
    print(key, value)

rawDescription: incrementing key,value pair inside for loop iterating over dictionary

description: Incrementing key,value pair inside for loop iterating over dictionary


code:
import threading
import sys

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace

rawDescription: How to continuously flash LED (or other while loop) while Python code continues to run

description: Continuously flash LED (or other while loop) while Python code continues to run


code:
with open('dict.obj', 'wb') as fh:
    pickle.dump(obj, fh, pickle.HIGHEST_PROTOCOL)

rawDescription: Python fast dictionary creation with Pickle?


code: os.system("osascript -e 'mount volume \"smb://server/servershare\"'")

rawDescription: Mounting SMB network share on desktop

description: Mounting SMB network share on desktop


code:
print([ getattr(myclass,x) for x in dir(myclass) if not x.startswith("__")])
[20, 30, 40]

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


rawDescription: How to define radius for blur with Python Pillow?

description: Define radius for blur with Python Pillow


code:
class VariableManagerClass:
    def __getattr__(self, attr):
        return AttributeSetter(self, attr)

rawDescription: How to copy all python instances to a new class?

description: Copy all python instances to a new class


code:
bookdict = {
  'Little longer title here': 'Author Name Here',
  'Book Title Here': 'Another Author Name Here',
  'shorter here': 'Diff Name Here'}
bookwidth = max(map(len, bookdict.keys()))
authorwidth = max(map(len, bookdict.values()))

rawDescription: Equally separating words in Python

description: Equally separating words in Python


rawDescription: Finding consecutive segments in a pandas data frame


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

    def __str__(self):
        return str(self._name)

    def __div__(self, other):
        return Div(self, other)

    def __mul__(self, other):
        return Mult(self, other)

    def __add__(self, other):
        return Add(self, other)

    def __sub__(self, other):
        return Sub(self, other)

    def __rdiv__(self, other):
        return Div(other, self)

    def __rmul__(self, other):
        return Mult(other, self)

    def __radd__(self, other):
        return Add(other, self)

    def __rsub__(self, other):
        return Sub(other, self)

class Operation(Symbol):
    def __init__(self, a, b, op):
        self._a = a
        self._b = b
        self._op = op

    def __str__(self):
        return self._op.format(self._a, self._b)

class Add(Operation):
    precedence = 0

    def __init__(self, a, b):
        super(Add, self).__init__(a, b, "{0} + {1}")

class Sub(Operation):
    precedence = 0
    def __init__(self, a, b):
        super(Sub, self).__init__(a, b, "{0} - {1}")

class Mult(Operation):
    precedence = 1
    def __init__(self, a, b):
        if isinstance(a, Operation) and a.precedence < Mult.precedence:
            a_form = "({0})"
        else:
            a_form = "{0}"
        if isinstance(b, Operation) and b.precedence < Mult.precedence:
            b_form = "({1})"
        else:
            b_form = "{1}"
        super(Mult, self).__init__(a, b, a_form + " " + b_form)

class Div(Operation):
    precedence = 1
    def __init__(self, a, b):
        super(Div, self).__init__(a, b, "\\frac{{{0}}}{{{1}}}")

A = Symbol('A')
B = Symbol('B')
C = Symbol('C')
x = Symbol('x')

rawDescription: python math expressions to latex, verbatim (no reordering, factoring, etc.)

description: Python math expressions to latex, verbatim (no reordering, factoring, etc.)


code: "- >/dev/null 2>/dev/null"

rawDescription: convert Ghostscript from os.popen to subsession.popen python

description: Convert Ghostscript from os.popen to subsession.popen python


code:
projects_map = LazyCachedDict('projects_map')
projects_map.get('search term')

rawDescription: Loading dictionary object causing memory spike


code:
for ax, title in zip(g.axes.flat, ['zero', 'one']):
    ax.set_title(title)

rawDescription: Customizing annotation with Seaborn's FacetGrid


code:
Fraction(0.9)
Fraction("0.9")

rawDescription: Python - Parse float string to an integer


code: all(map(lambda x: x.pop(which_column), triangle))

rawDescription: Python - Delete column from a matrix without numPy


code:
class AutoJoiningThread(threading.Thread):
    def run(self):
        threading.Thread.run(self)
        gobject.idle_add(self.join)

rawDescription: In Python, how do I know when a process is finished?


code:
with open (file1, 'r') as f: ids = [line.strip () for line in f]
with open (file2, 'r') as f:
    with open (file3, 'w') as g:
        for line in f:
            if any (line.startswith (id) for id in ids): g.write (line)

rawDescription: If term in file 1 is in line of file 2, write the whole line in file 2 to file 3


rawDescription: Add to the django request.user variable

description: Add to the django request.user variable


code:
class RealisticInfoArray(np.ndarray):
    def __new__(cls, input_array, info=None):
        obj = np.asarray(input_array).view(cls)
        obj.info = info
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'info', None)

    def __reduce__(self):
        # Get the parent's __reduce__ tuple
        pickled_state = super(RealisticInfoArray, self).__reduce__()
        # Create our own tuple to pass to __setstate__
        new_state = pickled_state[2] + (self.info,)
        # Return a tuple that replaces the parent's __setstate__ tuple with our own
        return (pickled_state[0], pickled_state[1], new_state)

    def __setstate__(self, state):
        self.info = state[-1]  # Set the info attribute
        # Call the parent's __setstate__ with the other tuple elements.
        super(RealisticInfoArray, self).__setstate__(state[0:-1])

rawDescription: Preserve custom attributes when pickling subclass of numpy array


code:
import csv

from collections import Counter

with open(r'C:\Report.csv', 'r') as f:
    reader = csv.reader(f)
    severities = Counter(r[3] for r in reader)

rawDescription: Counting occurence of words in CSV column and writing to another CSV?


code:
class DynamicForm(forms.Form):

    options = [
    ('Textbox1', 'Textbox1'),
    ('Textbox2', 'Textbox2'),
    ...
    ]

    dynamic_data = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=options)

    def __init__(self, *args, **kwargs):
        super(DynamicForm, self).__init__(*args, **kwargs)

        for i in range(1,len(self.options)+1):
            self.fields['dd_func_'+str(i)] = forms.ChoiceField(widget=forms.Select, choices= [
                            ('average', 'average'),
                            ('sum', 'sum')], initial='sum', required=False)

    def __getitem__(self, name):
        try:
            field = self.fields[name]
        except KeyError:
            raise KeyError('Key %r not found in Form' % name)
        return forms.forms.BoundField(self, field, name)

rawDescription: Django forms - checkbox group with dropdowns


code:
from Tkinter import *

class Application(Frame):

        def __init__(self, master):
            Frame.__init__(self, master)
            self.grid()
            self.create_widgets()

        def create_widgets(self):
            self.firstname = Entry(self, text="First")
            self.firstname.grid(row= 0, column = 0, columnspan = 2, sticky = W)
            self.firstname.insert(0, "First Name")

            self.lastname = Entry(self)
            self.lastname.grid(row= 1, column = 0, columnspan = 2, sticky = W)
            self.lastname.insert(0, "Last Name")

            self.companyname = Entry(self)
            self.companyname.grid(row= 2, column = 0, columnspan = 2, sticky = W)
            self.companyname.insert(0, "Company Name")

            self.button = Button(self, text="Generate!",
                                 command=self.gen_email)
            self.button.grid()

            #where the generated emails will go
            self.text = Text(self, width = 35, height=5, wrap =WORD)
            self.text.grid(row=4,column=0, columnspan=2, sticky=W)

        def gen_email(self):
            firstname = self.firstname.get()
            lastname =  self.lastname.get()
            companyname =  self.companyname.get()
            self.email_list = []
            self.email_list.append(firstname + "." + lastname + "@" + companyname + ".com")
            self.email_list.append(firstname[0] + lastname + "@" + companyname + ".com")
            self.email_list.append(firstname + lastname[0] + "@" + companyname + ".com")
            self.email_list.append(firstname + "@" + companyname + ".com")
            self.email_list.append(firstname + "_" + lastname +"@" + companyname + ".com")

            self.text.insert(0.0, self.email_list)

root = Tk()
root.title("Email Generator")
root.geometry("400x400")

app = Application(root)
root.mainloop()

rawDescription: Tkinter script: having trouble inserting text


code:
for thing in iterable:
    print(thing)

rawDescription: Python Java forEach equivalent

description: Python Java forEach equivalent


rawDescription: python : How can I replace complex number to -1?

description: Python : How can I replace complex number to -1


rawDescription: Python deep zip

description: Python deep zip


code: columns

rawDescription: Pandas read multiindexed csv with blanks


code:
import random
def test(input_string):
    l = len(input_string)
    if l >= 10:
        return input_string
    input_string += random.choice('abcdefghijklmnopqrstuvwxyz'
                                  'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    return test(input_string)

input_string = ''
input_string = test(input_string)
print(input_string)

rawDescription: recursively concatenate string in python

description: Recursively concatenate string in python


rawDescription: How to iterate over the dictionary keys to calculate cosine similarity using the values?

description: Iterate over the dictionary keys to calculate cosine similarity using the values


code:
i = np.empty(len(a), dtype='i8')
i[a] = np.arange(len(a))
i

rawDescription: Vectorized search of element indeces

description: Vectorized search of element indeces


code: a = [f(x) for x in bar]

rawDescription: How to run an operation on a collection in Python and collect the results?

description: Run an operation on a collection in Python and collect the results


code:
def soupSetup(file_name, encode_type):
    global soup
    soup = BeautifulSoup(open("C:\\Python32\\html\\"+file_name+".html", encoding=encode_type))

rawDescription: Using a script to set variables in IDLE

description: Using a script to set variables in IDLE


code:
nx.draw_networkx(gr)
plt.show()

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

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


code:
A = np.array([1,3,5,-999,3,1,6,8,-999,-999,-999,3,5,7.])
A[A==-999] = np.nan
mask = np.isnan(A)
A[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), A[~mask])

rawDescription: Python: Replacing NaN or MEAN instead of a -999 value in an array


code:
from time import asctime
asctime()

rawDescription: Have python run script at X:00 am

description: Have python run script at X:00 am


code:
x = np.zeros(size)
x[index] = 1.0

rawDescription: Efficient unit basis vector with numpy

description: Efficient unit basis vector with numpy


code:
i, j = np.where(A == 2)
A[i,j]

rawDescription: Index of an element in a numpy array

description: Index of an element in a numpy array


rawDescription: Extract Only Unicode Characters from a String using Regular Expressions


code:
from pylab import *

points = []
points.append((-0.25, -1.0))
points.append((0.7, -0.7))
points.append((1,0))
points.append((0.7,1))
points.append((-0.25,1.2))
points.append((-1,0.5))
points.append((-1,-0.5))
points.append((-0.25, -1.0))

a_line = plot(*zip(*points))[0]
a_line.set_color('g')
a_line.set_marker('o')
a_line.set_markerfacecolor('b')
a_line.set_markersize(30)
axis([-1.5,1.5,-1.5,1.5])

show()

rawDescription: Matplotlib in Python - Drawing shapes and animating them


rawDescription: How do you set the absolute position of figure windows with matplotlib?

description: Set the absolute position of figure windows with matplotlib


rawDescription: Python pandas Filtering out nan from a data selection of a column of strings


code:
def tearDown(self):
    if (not IOLoop.initialized() or
        self.io_loop is not IOLoop.instance()):
        # Try to clean up any file descriptors left open in the ioloop.
        # This avoids leaks, especially when tests are run repeatedly
        # in the same process with autoreload (because curl does not
        # set FD_CLOEXEC on its file descriptors)
        self.io_loop.close(all_fds=True)
    super(AsyncTestCase, self).tearDown()

rawDescription: Getting Bad file descriptor when running Tornado AsyncHTTPTestCase


code:
namespace = {'args': [1,2,3]} # define __name__, __file__ if necessary
execfile('some_script.py', namespace)
result = namespace['result']

rawDescription: Getting return infromation from another python script


rawDescription: Color classification library

description: Color classification library


rawDescription: Get keyboard code of a keypress in Python


rawDescription: How to convert a url string to safe characters with python?

description: Convert a url string to safe characters with python


group: abc

group: xyz

month: JAN FEB FEB MAR DEC

rawDescription: python - create json file from input matrix by grouping rows

description: Python - create json file from input matrix by grouping rows


code: f = lambda x, y: x + y

rawDescription: lambda in python

description: Lambda in python


code:
# Get the first row rgb values
first_row = [rgb_im.getpixel((i,0)) for i in range(rgb_im.size[0])]
# Count how many pixels are black. Note that jpg is not the cleanest of all file formats.
# Hence converting to and from jpg usually comes with some losses, i.e. changes in pixel values.
first_row.count((0,0,0)) # --> 628
len(first_row) #--> 680

rawDescription: How to analyse bitmap image in python, using PIL?

description: Analyse bitmap image in python, using PIL


rawDescription: catalogue a list of dictionaries

description: Catalogue a list of dictionaries


code:
#spell cooldown timer
self.timers['cooldown'] -= 1
if self.timers['cooldown'] < 0:
    self.timers['cooldown'] = 0

rawDescription: Python too slow - Can I rewrite engine in lower level and cp scripts?


code:
import itertools

for i in itertools.count(13):
   print(i)

rawDescription: Easy way to keep counting up infinitely

description: Easy way to keep counting up infinitely


code:
def autocomplete_handler_view(request):
    autocomplete_type = request.matchdict.get('autocomplete', None)
    if autocomplete == 'majorgenre':
        return handle_majorgenre(request.params['term'])

    elif autocomplete == 'programtype':
        return handle_programtype(request.params['term'])

rawDescription: Multiple instances of JQueryUI Autocomplete on same Pyramid page


code:
def convert(list, sep):
    n_str = ''
    for index, I in enumerate(list): #enumerate(list) returns (current position, list[current position]) so if we need to know the current position we use enumerate
        if index != len(list)-1:
            n_str += str(i) + sep #we don't apply the seperator if we're at the end of the list
        else:
            n_str += str(i)
    return n_str

rawDescription: Convert a list into a string and allow for a separator


rawDescription: NumPy Vectorize a function, unknown shape


code:
def handlePreview(self):
    dialog = QtGui.QPrintPreviewDialog()
    dialog.paintRequested.connect(self.handlePaintRequest)
    dialog.exec_()

def handlePaintRequest(self, printer):
    self.view.render(QtGui.QPainter(printer))

rawDescription: Print A Text Through A Printer Using PyQt4


code:
pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

from itertools import zip_longest  # izip_longest for python 2
[tuple(filter(None, col)) for col in zip_longest(pData, rData, sData)]

rawDescription: Python - zip only lists that contain data


code:
from __future__ import print_function
import time
import sys
import platform

if sys.version_info[0]==2:
    range=xrange

times=[]
results=[]
t1=time.time()
t0=t1
tgt=5000000000
bucket=tgt/10
width=len('{:,}  '.format(tgt))
with open('/tmp/disk_test.txt', 'w') as fout:
    for line in range(1,tgt+1):
        fout.write('Line {:{w},}\n'.format(line, w=width))
        if line%bucket==0:
            s='{:15,}   {:10.4f} secs'.format(line, time.time()-t1)
            results.append(s)
            print(s)
            t1=time.time()
    else:
        info=[platform.system(), platform.release(),sys.version, tgt, time.time()-t0]
        s='\n\nDone!\n{} {}\n{} \n\n{:,} lines written in {:10.3f} secs'.format(*info)
        fout.write('{}\n{}'.format(s, '\n'.join(results)))

print(s)

rawDescription: Does size of a file affects the performance of the write in python


code:
if hasattr(self._current_browser(), 'get_screenshot_as_file'):
    self._current_browser().get_screenshot_as_file(path)
else:
    self._current_browser().save_screenshot(path)

rawDescription: Taking a screenshot of a vnc session within a python script


code: d = map(lambda x, y: x + y[1:], a, b)

rawDescription: Append list elements to a list of tuples


code:
x = radius*sin(angle)
y = radius*cos(angle)

rawDescription: Zelle Graphics animation

description: Zelle Graphics animation


code:
from collections import defaultdict

students = defaultdict(dict)
with open(filename, 'r') as f:
    for line in f.readlines():
        elts = line.split()
        student = elts[0]
        movie = elts[1]
        rating = int(elts[2])
        students[student][movie] = rating

rawDescription: Maintaining order in large list of movies/ratings


code:
import pygame,random
pygame.init()
red = (200,0,0)
white = (255,255,255)
black = (0,0,0)
gameDisplay=pygame.display.set_mode((800,600))

FPS=30
clock=pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            quit()
    cur = pygame.mouse.get_pos()
    click=pygame.mouse.get_pressed()
    if click[0] == 1:
        x=random.randint(1,700) #random coords of x
        y=random.randint(50,500) #random coords of y
        wx=random.randint(10,100) #random size of x
        hy=random.randint(60,200) #random size of y
        pygame.draw.rect(gameDisplay,red, (x,y,wx,hy)) #drawing with random variables
        pygame.display.update()

    clock.tick(FPS)

rawDescription: after i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame

description: After i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame


code:
indexes = []
for i in range(len(a)):
   if a[i:i+len(b)] == b:
       indexes.append((i, i+len(b)))

indexes

rawDescription: find indexes of sequence in list in python

description: Find indexes of sequence in list in python


code:
fig, ax = plt.plot()
fig.suptitle('fig title', size = 80)
ax.set_title('my title', size = 10)
ax.set_xlabel('my x label', size = 20)
ax.set_ylabel('my y label', size = 30)
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(40)
for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontsize(50)

rawDescription: how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger

description: Make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger


code:
tree.find('.//dct:title', namespaces=nsmap)
tree.find('.//dct:title', namespaces=nsmap).text

rawDescription: Parsing a specific element from XML using Python/ET


rawDescription: Dictionary With Multiple Values To Nested List


code:
lists = [[1,2,5], [5,6], [2,8,4]]
arr = np.arange(10)*2

extracted = arr[np.concatenate(lists)]

indices = [0] + list(np.cumsum(map(len, lists)))
result = [extracted[indices[i]:indices[i + 1]] for i in range(len(lists))]

rawDescription: Multiple lists of indices for one array in numpy


rawDescription: Complicated referencing with dictionaries, python


rawDescription: Indexing a nested list in python

description: Indexing a nested list in python


code:
tmp = 3.25 * np.nansum(rs) +  .75 * np.nansum(rs * rs)
if not np.isnan(tmp):
  runningSum += tmp

rawDescription: Masked Numpy arrays much slower than normal numpy arrays


rawDescription: Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone


rawDescription: Python: Initialize a datetime object with seconds since epoch


rawDescription: Contour shows dots rather than a curve when retrieving it from the list, but shows the curve otherwise


code:
#######Test data
#file1.txt = this is a test
#file2.txt = this a test
#results#
#is

def translation_comparison():
    with open("file1.txt", 'r') as f1:
        f1 = f1.read().split()
    with open("file2.txt", 'r') as f2:
        f2 = f2.read().split()

    for word in f1:
        if word not in f2:
            print(word)

translation_comparison()

rawDescription: Python Text Document Translation Comparison


code:
import io
import pandas as pd
import numpy as np

text = """key1 col1 col2 val1
1   a     b    0
1   c     d    0
1   e     f    1
1   g     h    0
2   a     b    0
2   c     d    1
2   e     f    0
3   a     b    0
3   c     d    0
3   e     f    0"""

df = pd.read_csv(io.BytesIO(text), delim_whitespace=True)

def sample(df):
    mask = df.val1 == 0
    if np.all(mask):
        return None
    else:
        idx1 = mask.idxmin()
        idx0 = np.random.choice(mask[mask].index)
        return df.loc[[idx0, idx1]]

df.groupby("key1").apply(sample)

rawDescription: Randomly subsampling the rows of a DataFrame in Pandas, with some conditions


rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


rawDescription: How do I create many matrices inside a loop statement with python?

description: Create many matrices inside a loop statement with python


rawDescription: How to convert a Date string to a DateTime object?

description: Convert a Date string to a DateTime object


rawDescription: Finding the index of the second match of a regular expression in python


code: return input.split()

rawDescription: Solving a linear equation in one variable


code: ['size', 'bulk', 'clubs', 'cannibal', 'and', 'fable', 'Pictures', 'pictures', 'stories', 'cabinet', 'size']

rawDescription: Calling NLTK's concordance - how to get text before/after a word that was used?


code:
import os
from os.path import join, getsize

def size_list(mypath):
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                fo.write("\nPath: " +  os.path.join(root, f))
                fo.write("\tSize: " +  str(getsize(os.path.join(root, f))) + " bytes")

size_list("path/to/dir")

rawDescription: Python file path and size

description: Python file path and size


code:
import operator
sorted(lst, key=operator.itemgetter(3),reverse=True)

rawDescription: Sorting by element on data structure in python


code:
def openFileDialog(self):
    import os
    path, _ = QtGui.QFileDialog.getOpenFileName(self, "Open File", os.getcwd())
    self.label.setText(path)
    return path

rawDescription: How to read an attribute in another class?

description: Read an attribute in another class


code:
dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)

rawDescription: Can pandas automatically recognize dates?


code:
import time

def objReach(obj, pos):
    try:
        obj.path = obj.reach(pos, move=False)       # A* (path-finding algorithm)
        obj.last_move = time.time()
        obj.move_after = 1   # move every 1 second.
    except Exception as e:
        sendMsg(str(e))

rawDescription: Continuously capture mouse events with pygame


code: ''.join(filter(is_not_digit, 'h3ll0'))

rawDescription: How to remove numeric character in my input text?

description: Remove numeric character in my input text


code:
def splitList(myList, option):
    if option == 0:
        return [el for el in myList if abs(el) > 5]

rawDescription: Absolute value and adding to a list

description: Absolute value and adding to a list


code: df['Diff'] = df['INVOICED_QUANTITY'].sub(df['QUANTITY_SHIPPED'], fill_value=0)

rawDescription: Find difference between 2 columns with Nulls using pandas


rawDescription: List of tuples deletion

description: List of tuples deletion


code:
function(input1, input2) == newfunction(input1, input2)
#>>> True

rawDescription: Python nested loop comparing two lists and updating a dictionary


code: for k in dict.keys(): ...

rawDescription: Learn Python The Hard Way - Exercise 39

description: Learn Python The Hard Way - Exercise 39


rawDescription: Range with floating point numbers and negative steps


code: PASS="pass"

rawDescription: Running parameterized python script within bash script


code:
def my_function(a,b,c,d,e=True,f="something"): pass

key_maker = make_key_maker(my_function)

key_maker(1,2,3,4)
key_maker(1,2,3,4, e=True)               # same as before
key_maker(1,2,3,4, True)                 # same as before
key_maker(1,2,3,4, True, f="something")  # same as before
key_maker(1,2,3,4, True, "something")    # same as before
key_maker(1,2,3,d=4)                     # same as before
key_maker(1,2,3,d=4, f="something")      # same as before

rawDescription: Identifying equivalent varargs function calls for memoization in Python


code:
import sys
startdata = sys.argv[1]

rawDescription: I want to have raw_input and nohup together in python


code:
from wholeproject.package1 import stuff1
from wholeproject.package2 import moar1

rawDescription: Best way to import database in python project

description: Import database in python project


code: circle.xyz = 100

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


rawDescription: How to expand a list of integer based on a threshold?

description: Expand a list of integer based on a threshold


code:
import os
all_files = (open(f) for f in os.listdir(some_path)) # note () instead of []
for f in all_files:
    pass # do something with the open file here.

rawDescription: Python - Opening successive Files without physically opening every one