code: [''.join(item) for item in IT.product('AGT', 'AGT', 'A', 'G', 'G', 'AG', 'G', 'AGT')]

rawDescription: Python Permutations in which each position is limited


rawDescription: Keeping trailing 0 when converting from str to float


code:
def __init__(self, *, ex_args1, ex_args2, **kwargs):
    super.__init__(self, **kwargs) # passes along the unnamed keyword args
    # ...

rawDescription: How to Extend Large Class Methods?

description: Extend Large Class Methods


rawDescription: Why does s[len(s)-1:-1:-1] not work?

description: Why does s[len(s)-1:-1:-1] not work


code:
b = SomeClass(Container(5))
b.attr.data = 10
b.attr.data = 10     # on_change() not called if the value isn't changing
b.attr.data2 = 'foo' # new properties being add result in an on_change() call

rawDescription: Catching changes to a mutable attribute in python


code:
def bubbleSort2(l):
  while not isListSorted(l):
    for i in range(len(l)-1):
      if l[i] > l[i+1]:
        l[i], l[i+1] = l[i+1], l[i]

rawDescription: Bubble Sort following an algorithm

description: Bubble Sort following an algorithm


code:
koef = [logt_a, a_0, T_a*a_0, a_1, T_a*a_1, a_2, T_a*a_2]
M = expand(A)
K = zeros(len(koef), len(koef))
def odvod_mat(par):
    for j in range(len(par)):
        for i in range(len(par)):
            type(par[i])._diff_wrt = True
            P = diff(M, par[i])/2
            B = P.coeff(par[j])
            K[i,j] = B

            #Removal of T_a
            K[i,j] = K[i,j].subs(T_a, 0)
    return K
odvod_mat(koef)

rawDescription: Partial symbolic derivative in Python

description: Partial symbolic derivative in Python


code: zip(data[0], data[1], data[2])

rawDescription: python list manipulation nesting vertically, making it look like a matrix

description: Python list manipulation nesting vertically, making it look like a matrix


code: return MyObj(name=name, obj_one=self.obj_one, obj_two=self.obj_two)

rawDescription: Create object with variable attributes in a cleaner way in python


code:
class Foo(object):
    _number_of_times = 0

    @classmethod
    def yourfunc(cls, x, y):
        for i in range(x):
            for j in range(y):
                cls._number_of_times += 1

rawDescription: Static variable in python?

description: Static variable in python


code: hmac.new(CryptoKey, '^'.join([login, seq, time, amo]), hashlib.md5).hexdigest()

rawDescription: How to set the crypto key for Python's MD5 module?

description: Set the crypto key for Python's MD5 module


code:
class Channel(models.Model):
    name = models.CharField(max_length=200)
    accountid = models.CharField(max_length=34)

    @classmethod
    def get_channel_list(cls, acc):
        return cls.objects.filter(accountid=acc).values_list('name', flat=True)

rawDescription: Django QuerySet with Models

description: Django QuerySet with Models


code:
print("Welcome to Terry Cotta's Tiling Company!")
areaLength = int(input('Input length of area to be tiled in metres: '))

#You could loop until you get correct value

while areaLength <= 0:
    print('Area cannot be lower than 0')
    areaLength = int(input('Input length of area to be tiled in metres: '))
areaWidth = int(input('Input width of area to be tiled: '))

#Same here loop until you get the correct value

while areaWidth <= 0:
    print('Area cannot be lower than 0')
    areaWidth = int(input('Input length of area to be tiled in metres: '))
areaArea = areaLength*areaWidth

tiles = {'ceramic': '3', 'granite': '5', 'marble': '10'}

for x in tiles:
    print(x.title() + " -  Small: $" + str(int(tiles[x])/2) + "  Medium: $" + tiles[x] + "  Large: $" + str(int(tiles[x])*(2)))

tileType = input("What type of tile would you like? Ceramic, granite or marble?: ")
tileType = tileType.lower()

#You had undeclared variable here so changed it

#And I really don't know what you were trying to do here

while tileType != 'yes':
    if tileType not in tiles:
        print('We do not provide that type of tile. Please enter again.')
    tileType = input("What type of tile would you like? Ceramic, granite or marble?: ")
if tileType in tiles:
    tileSize = input('What size tile would you like? Small, medium or large: ')

rawDescription: How to fix the invalid syntax

description: Fix the invalid syntax


code:
for friend in friends:
    newfile.write(friend[u'name'] + "\n")

rawDescription: Filter return results printed in text file python


code:
import numpy as np
def unique(a):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.diff(a, axis=0)
    ui = np.ones(len(a), 'bool')
    ui[1:] = (diff != 0).any(axis=1)
    return a[ui]

rawDescription: Removing duplicate columns and rows from a NumPy  2D array


code:
write_list = ''.join(new_list).split('\n')
output_file = open(filename, 'w')
output_file.writelines(write_list)

rawDescription: Read a text file into python by splitting the file into list items according to a set of characters


code:
class MyListStore(object):
  def __init__(self, title, filter=None):
    self.title = title
    self._model = gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING)
    if filter_func:
      self._model = self.model.filter_new()
      self._model.set_visible_func(filter)

rawDescription: Change C object instance to Python subclass


code:
import os, sys, subprocess, glob

def type_printed(pth, rpm_dirs=False):

    if not os.path.exists(pth):
        print(pth + ' -- does not exist')
        return True
    FNULL = open(os.devnull, 'w')
    if rpm_dirs or not os.path.isdir(pth):
        rc = subprocess.call(['rpm', '-qf', pth], stdout=FNULL, stderr=subprocess.STDOUT)
        if rc == 0:
            print(pth + ' -- IS RPM')
            return True
        print(pth + ' -- NOT an RPM')
        return True
    return False

for pth in sys.path:
    if type_printed(pth):
        continue
    contents = glob.glob(pth + '/*')
    for subpth in contents:
        if type_printed(subpth, rpm_dirs=True):
            continue
        print(subpth + ' -- nothing could be determined for sure')

rawDescription: pip freeze: show only packages installed via pip

description: Pip freeze: show only packages installed via pip


code: cols = [random.choice(seen[firstcol]) for firstcol in seen]

rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


code:
import turtle
turtle.width(5)
yd=xd=-64
turtle.delay(0) # <----
for i in range(2):
    turtle.up()
    turtle.goto(-197.5,yd)
    turtle.down()
    turtle.seth(0)
    turtle.fd(394)
    yd+=128
    turtle.up()
    turtle.goto(xd,197.5)
    turtle.down()
    turtle.seth(270)
    turtle.fd(394)
    xd+=128
turtle.mainloop()

rawDescription: Turtle tracer arguments example trouble

description: Turtle tracer arguments example trouble


code: from flask import current_app

rawDescription: In Flask: How to access app Logger within Blueprint


code:
import numpy as np

l=np.random.rand(3000,30000)
lout1=map(np.unique,l)
#or
lout2=[np.unique(ll) for ll in l]

rawDescription: How to turn Numpy array to set efficiently?

description: Turn Numpy array to set efficiently


rawDescription: Python regex \number adding \0x

description: Python regex \number adding \0x


code: matches = [a for a in (r.match(domain) for r in (first_re, second_re, third_re)) if a]

rawDescription: Is it possible to convert this map/filter code into list comprehension?


code: print("You can get " + str(wrong) + "% back with text corrections")

rawDescription: Invalid syntax with if

description: Invalid syntax with if


code:
df = pd.merge(df1, df2, on='date', sort=False)
df['ids'] = df['ids_x'] + df['ids_y']
df = df.drop(['ids_x','ids_y'],axis=1)

rawDescription: How to merge two list columns when merging DataFrames?

description: Merge two list columns when merging DataFrames


code:
from matplotlib.collections import LineCollection

w = h = 512
lines = np.random.randint(0, 512, size=(10000, 4))
count = acc_lines(lines, w, h)

fig, axes = pl.subplots(1, 2, figsize=(10, 5))
lc = LineCollection(lines.reshape(-1, 2, 2), alpha=0.015, color="black")

axes[0].imshow(count, cmap="gray_r")
axes[1].add_collection(lc)
axes[1].axis((0, w, h, 0))
axes[0].set_aspect("equal")
axes[1].set_aspect("equal")

rawDescription: plotting semitransparent lines / 16bit alpha values

description: Plotting semitransparent lines / 16bit alpha values


code:
for handle in handles:
    printuser(api.GetUser(screen_name=handle))

rawDescription: Twitter User Details and Python

description: Twitter User Details and Python


code:
service_filter = Redirector.service == 122
menu_id_select = session.query(Redirector.menu_id).filter(service_filter)
keyword_select = session.query(Redirector.keyword).filter(service_filter)

rawDescription: Sqlalchemy mass deletion orm creation

description: Sqlalchemy mass deletion orm creation


code:
def next_date(nowfunc=datetime.now):
    now = nowfunc()
    ...

rawDescription: How to test methods that compute relative time in python using unitttest?

description: Test methods that compute relative time in python using unitttest


code:
import os

data = '''
ParentFolder1
    SubFolder1
    Subfolder2
        SubSubFolder1
    SubFolder3
ParentFolder2
    SubFolder1
ParentFolder3
ParentFolder4
    SubFolder1
        SubSubFolder1
            SubSubSubFolder1
        SubSubFolder2
    SubFolder2
ParentFolder5
    SubFolder1
'''[1:]

def show(seq):
    for row in seq:
        print(row)
    print()

def stripcount(s):
    z = s.lstrip(' ')
    count = len(s) - len(z)
    return z, count

joinpath = os.path.join

def make_dir_tree(dir_tree, root=''):
    ''' Create a directory tree in root from dir_tree,
        which is a list of indented directory names.
    '''
    dir_tree = [stripcount(s) for s in dir_tree]
    #show(dir_tree)

    stack = [root]
    depth = -1
    for dname, count in dir_tree:
        if count > depth:
            depth = count
            stack.append(dname)
        elif count < depth:
            depth = count
            stack.pop()
            stack[-1] = dname
        else:
            stack[-1] = dname

        pathname = joinpath(*stack)
        print(pathname)
        os.mkdir(pathname)

dir_tree = data.splitlines()
show(dir_tree)
make_dir_tree(dir_tree, 'testfolder')

rawDescription: Python move "met conditional value" outside of loop


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code:
from IPython.display import display, Math
from sympy import *
x1 = var('x_1')
x2 = var('x_2')
display(Math(latex(x1*x2,mul_symbol='dot')))

rawDescription: Use a symbol for multiplication operator in sympy output in ipython notebook


code:
raw_str = raw_input("Input LineA (x1,y1,x2,y2): ")
# Split the string by commas(this is the separator), raise Exception if we have more or less than 4 values.
tokens = raw_str.split(",")
if len(tokens) != 4:
    raise ValueError("Invalid input.")
# Now we eliminate any SPACEs, TABs, or ; that the user might have input and then convert everything to floats.
var = [item.strip(" \t;") for item in tokens]
lineA = ((float(var[0]), float(var[2])), (float(var[1]), float(var[3])))

rawDescription: input of a tuple on the command line and assigning it to a tuple

description: Input of a tuple on the command line and assigning it to a tuple


code: XLE['time'] = pd.to_datetime(XLE.time)

rawDescription: How to reindex csv data efficiently?

description: Reindex csv data efficiently


code: password = decrypt-password(data)

rawDescription: Use ssh key to encrypt and decrypt a password


rawDescription: How to scrape dynamic content with Selenium?

description: Scrape dynamic content with Selenium


code:
target_projection = ccrs.PlateCarree()
geoms = [target_projection.project_geometry(geom, feature.crs)
         for geom in geoms]

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code: import logging.config

rawDescription: Logger.info never outputs

description: Logger.info never outputs


rawDescription: Numpy from string (Difference of uint8 and uint16) [Combining two uint8 values to one uint16 value]


code:
import wave
import numpy as np

wr = wave.open('input.wav', 'r')
sz = 44100 # Read and process 1 second at a time.
da = np.fromstring(wr.readframes(sz), dtype=np.int16)
wr.close()
left, right = da[0::2], da[1::2]

rawDescription: Read amplitude data from mp3

description: Read amplitude data from mp3


code:
from datetime import datetime

current_date = None
results = []
for line in text:
    line = line.strip()
    if not line:
        continue

    if line.startswith('#'):
        current_date = datetime.strptime(line.strip('# '), '%m/%d/%y').date()
        continue

    entry = {'date': current_date, 'read': False}

    if line.startswith('*') and line.endswith('*'):
        # previously read
        line = line.strip('*')
        entry['read'] = True

    entry['title'] = line
    results.append(entry)

rawDescription: Odd Behaviour of Loop in Python

description: Odd Behaviour of Loop in Python


code:
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
common = cylinder1.common(cylinder2)

rawDescription: Python module for parametric CAD

description: Python module for parametric CAD


code:
oracledata = '2014/10/04'
"//option[contains(@value, '{}')]".format(oracledata)

rawDescription: Finding element by a variable

description: Finding element by a variable


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

a = [1,2,5,6,9,11,15,17,18]

plt.hlines(1,1,20)  # Draw a horizontal line
plt.xlim(0,21)
plt.ylim(0.5,1.5)

y = np.ones(np.shape(a))   # Make all y values the same
plt.plot(a,y,'|',ms = 40)  # Plot a line at each location specified in a
plt.axis('off')
plt.show()

rawDescription: 1D plot matplotlib

description: 1D plot matplotlib


code:
some_list = [[sample(range(1000), 2) for _ in range(100)] for _ in range(100)]
t1_sort.timeit(100)
t1_hash.timeit(1000)

rawDescription: How to Compare Multiple lists of tuples in python?


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


code:
s = """<root>
    <parent>
        <child>foo987654</child>
    </parent>
    <parent>
        <child>bar15245</child>
    </parent>
    <parent>
        <child>baz87742</child>
    </parent>
    <parent>
        <child>foo123456</child>
    </parent>
</root>"""

import xml.etree.ElementTree as ET

root = ET.fromstring(s)
elems = [elem for elem in root.findall('parent') if elem.find('child').text.startswith('foo')]

rawDescription: Find non-root parent node where child contains some text


code: id_list = [j[0] for j in sorted(y, key=lambda e: x.index(e[1].split('/')[-1].split('.')[0]))]

rawDescription: fast ordered sort (and extract from) tuple based on list

description: Fast ordered sort (and extract from) tuple based on list


code:
if len(last5) > 5:
    last5.pop(0)

rawDescription: Generate random numbers without using the last n values in Python


code: ['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']

rawDescription: Regex: How to match sequence of key-value pairs at end of string


code: V_over_WH = V/WH

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code: *[TR(*response) for response in response_results]

rawDescription: Web2Py - using starred expression for rendering HTML table


code:
db.test.update({ "ghi" : "jkl" }, { "ghio" : "jkl" })
db.test.update({ "ghio" : "jkl" }, { "$currentDate" : { "date" : true } })

rawDescription: MongoDb update by replacing the document while using update operation ($currentDate)[pymongo]


code:
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(categorical_features=[2])
race_encoded = enc.fit_transform(racearay)

rawDescription: Using Scikit-Learn's SVR, how do you combine categorical and continuous features in predicting the target?


rawDescription: Python: Iterate over a sub-2d (nested) array to calculate its sum


rawDescription: Using Python Regex to Separate a Coordinate Pair into X and Y Commponents


code: total = sum([val * quant for val, quant in zip(value, quantity)])

rawDescription: Multiply floats from two separate lists in Python


code:
df = pd.DataFrame(data, index=index, columns=columns)
df

rawDescription: Creating an empty Pandas DataFrame, then filling it?


code:
def login(request):
    login_form = LoginForm(request or None)
    if login_form.is_valid():
        login(request, login_form.u) # directly pass the user by accessing from login_form object

    return render(request, 'home.html', {})

rawDescription: Django User Authentication and Login with DRY


code:
d = d.reset_index().drop("freqs", axis=1)
d = d.rename(columns={"levels": "interval", "counts": "numbers"})
d

rawDescription: how to use pandas.cut to group my data?

description: Use pandas.cut to group my data


code:
remotefile = urllib2.urlopen('http://example.com/somefile.zip')
remotefile.info()['Content-Disposition']

rawDescription: How to download a file using python in a 'smarter' way?

description: Download a file using python in a 'smarter' way


code: machine_hand, player_hand, who_won = rps()

rawDescription: Accessing variables outside a function in Python


code:
tv = TreeView(root_options=dict(text='Tree One'), hide_root=True, indent_level=4)
tv.size_hint = 1, None
tv.bind(minimum_height = tv.setter('height'))
populate_tree_view(tv)
root = ScrollView(pos = (0, 0))
root.add_widget(tv)

rawDescription: TreeView in a ScrollView in Kivy - No Scroll


rawDescription: Python multi-dimensional array initialization without a loop


code:
print(lists[0][0])  # 'Item 1'
print(lists[0][1])  # 'Item 3'
print(lists[0][2])  # 'Item 5'
print(lists[1][0])  # 'Item 2'
print(lists[1][1])  # 'Item 4'

rawDescription: Append every other line from a text file? (Python)


rawDescription: How to input a text field which is autopopulating in Python Selenium

description: Input a text field which is autopopulating in Python Selenium


code:
for ser in OpenPorts:
       ser.write('ati')

rawDescription: Is it possible to make multiple instances of serial.Serial() in pyserial?


code:
status = subprocess.run('csvstat --count --c "col1" myfile.csv', output=subprocess.PIPE)
output = status.stdout.decode('ascii')
output = output.split()
result = output[-1]
print(result)

rawDescription: Python subprocess access result in script


code:
combo = QtGui.ComboBox()
model = combo.model()
for row in range(10):
    item = QtGui.QStandardItem(str(index))
    item.setForeground(QtGui.QColor('red'))
    font = item.font()
    font.setPointSize(10)
    item.setFont(font)
    model.addRow(item)

rawDescription: PyQt: How to customize ComboBox Items display


code:
wts = set(WrappedThingy(thingy) for thingy in thingies)
thingies = [wt.thingy for wt in wts]

rawDescription: Custom comparison functions for built-in types in Python


code:
import queue
import threading

# input queue to be processed by many threads
q_in = queue.Queue(maxsize=0)

# output queue to be processed by one thread
q_out = queue.Queue(maxsize=0)

# number of worker threads to complete the processing
num_worker_threads = 10

# process that each worker thread will execute until the Queue is empty
def worker():
    while True:
        # get item from queue, do work on it, let queue know processing is done for one item
        item = q_in.get()
        q_out.put(do_work(item))
        q_in.task_done()

# squares a number and returns the number and its square
def do_work(item):
    return (item,item*item)

# another queued thread we will use to print output
def printer():
    while True:
        # get an item processed by worker threads and print the result. Let queue know item has been processed
        item = q_out.get()
        print("{0[0]} squared is : {0[1]}".format(item) )
        q_out.task_done()

# launch all of our queued processes
def main():
    # Launches a number of worker threads to perform operations using the queue of inputs
    for i in range(num_worker_threads):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()

    # launches a single "printer" thread to output the result (makes things neater)
    t = threading.Thread(target=printer)
    t.daemon = True
    t.start()

    # put items on the input queue (numbers to be squared)
    for item in range(10):
        q_in.put(item)

    # wait for two queues to be emptied (and workers to close)
    q_in.join()       # block until all tasks are done
    q_out.join()

    print( "Processing Complete" )

main()

rawDescription: Learning about Queue module in python (how to run it)


code:
import subprocess
output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)

rawDescription: How to store the result of an executed shell command in a variable in python?

description: Store the result of an executed shell command in a variable in python


code:
p = Process(target=f, args=('bob',))
p.start()
p.join()

rawDescription: Python3 from Thread class to Process

description: Python3 from Thread class to Process


code:
def find_length(num):
    # If number is 0, return the length as 1.
    if num == 0:
        return 1
    length = 0

    # Loop over the number by dividing it by 10
    # and incrementing the length counter.

    while num != 0:
        length += 1
        num /= 10
    return length

def find_inside(num1, num2):
    # Trivial case, when the numbers are same.
    if num1 == num2:
        return (True, 1)

    len_n2 = find_length(num2)
    place = find_length(num1)

    # Iterate over the numbers, extracting the last
    # n digits everytime, where n is length of num2
    # Keep dividing the original number by 10 and
    # decrementing place everytime.

    while num1 != 0:
        if num2 == (num1 % (10 ** len_n2)):
            return (True, place - len_n2 + 1)
        num1 /= 10
        place -= 1
    return (False, -1)

rawDescription: Find a number in a another number

description: Find a number in a another number


code:
class Control(object):
        def __init__(self, word=0):
                self.word = word
        def get_low(self):
                return self.word & 0xFF
        def set_low(self, x):
                self.word &= 0xFF00
                self.word |= x & 0xFF
        def get_high(self):
                return (self.word >> 8) & 0xFF
        def set_high(self, x):
                self.word &= 0x00FF
                self.word |= (x & 0xFF) << 8
        low = property(get_low, set_low)
        high = property(get_high, set_high)

rawDescription: Creating pythonic objects that share memory


code: numlist.extend([str(n) for n in map(float, line.split()) if n > 0])

rawDescription: Taking each item in a list and writing them on a text file


code: sums = tuple(sum(grouped) for grouped in zip(*(method(j) for j in some_list)))

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code:
l = [1,2,3,4,5]
l[::2] = [0, 0, 0] #you can also replace only particular elements using this
l
k = [1,2,3,4,5]
g = ['a','b','c','d']
g[:2] = k[:2] # only replace first 2 elements
g
a = [[1,2,3],[4,5,6],[7,8,9]]
c[:] = a      #creates a shallow copy
a[0].append('foo') #changing a mutable object inside a changes it in c too
a
c

rawDescription: What is the difference between a[:]=b and a=b[:]


rawDescription: Strip URL - Python

description: Strip URL - Python


code:
# This gets around the above limitation
@logged(lambda: "Just for fun", ignored=True)
def some_function(x):
    pass

rawDescription: Python decorator optional argument

description: Python decorator optional argument


code:
for values_tuple in select_distinct(thedicts, ('NAME', 'CLASS')):
    ...

rawDescription: Implementing "select distinct ... from ..." over a list of Python dictionaries


rawDescription: Deleting/Removing the first N or last N from a sprites.Group()


code: np.max(b,axis=1)[...,np.newaxis] == b

rawDescription: Numpy: np.where function given argmax

description: Numpy: np.where function given argmax


code:
from __future__ import print_function
import re

pattern = r'(?P<text>.*?)(?:<(?P<tag>\w+)>(?P<content>.*)</(?P=tag)>|$)'

testcases = [ "Here's some <first>sample stuff</first> in the "
                "<second>middle</second> of some other text.",
              "<first>sample stuff</first> in the "
                "<second>middle</second> of some other text.",
              "Here's some <first>sample stuff</first> in the "
                "<second>middle</second>",
              "<first>sample stuff</first> in the <second>middle</second>",
              "Here's some ",
              "<first>sample stuff</first>",
              "<first></first>",
]

for my_str in testcases:
    print(' my_str: {!r}'.format(my_str))
    # nitty-gritty of conversion from match objects to list
    results = []
    for text, tag, content in re.findall(pattern, my_str):
        if text: results.append(text)
        if tag: results.append((tag, content))
    print('results: {}\n'.format(results))

rawDescription: Finding text in a string that matches a pattern along with the parts of it that don't


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

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

pl.show()

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


code:
def nested_list(depth):
  reduce(lambda l, n: [l], xrange(depth), [])

rawDescription: Python: initialise list of list of list of ... etc


rawDescription: Python Pandas Dataframe - remove data from dataframe if indexed date is older than a certain date


code:
test_mean = np.zeros_like(test)
for i in xrange(test.shape[0]-4):
    test_mean[i] = test[i:i+4].mean(axis=0)

rawDescription: Python - Avarage values of numpy multidimensionnal array every specific time


rawDescription: Finding letters in string, not followed by a number... possibly using RE?


code:
def inclusion(points_a, points_b):
  ch_a = find_convex_hull(points_a)
  return (1.0 * matplotlib.nxutils.points_inside_poly(points_b, ch_a)).mean()

rawDescription: Finding a partial or complete inclusion of a set of points in convex hull of other set of points in 2D in python


code:
@register.tag
def simple_request_aware_tag(parser, token):
    return SimpleRequestAwareNode()

class SimpleRequestAwareNode(template.Node):
    def render(self, context):
        request = template.Variable('request').resolve(context)
        #we want to return the current username for example
        return request.user.get_full_name()

rawDescription: What django resolve_variable do? (template.Variable)


code:
import itertools
splinelist = [(-200, 0, -200), (0, 0, -200), (200, 0, -200), (-200, 0, 0), (0, 0, 0), (200, 0, 0), (-200, 0, 200), (0, 0, 200), (200, 0, 200)]
grouped = itertools.groupby(splinelist, lambda x : x[2])
desiredlist  = [list(group) for key, group in grouped]
print(desiredlist)

rawDescription: Split Vector 3D Array Based on Z Value ~ Python


code: convertedAge = convertedAges[ageOfCat]

rawDescription: Any way I could make this more efficient?


code:
num = 24576
top = num >> 13
top
bin(top)

rawDescription: Trouble with bit manipulation in python

description: Trouble with bit manipulation in python


rawDescription: How can MultipleChoiceField be used with or querys in django?


code:
"""
Usage:
    csv2sql.py [--table <tablename>] <csvfile>

Options:
    --table <tablename>  Name of table in database to import into [default: mytable]

Convert csv file with iperf data into sql script for importing
those data into MySQL database.
"""
from csv import DictReader
from docopt import docopt

if __name__ == "__main__":
    args = docopt(__doc__)
    fname = args["<csvfile>"]
    tablename = args["--table"]
    headers = ["timestamp",
               "server_ip",
               "server_port",
               "client_ip",
               "client_port",
               "tag_id",
               "interval",
               "transferred",
               "bandwidth"
              ]
    sql = """insert into {tablename}
    values ({timestamp},"{server_ip}",{server_port},"{client_ip}",{client_port},{tag_id},"{interval}",{transferred},{bandwidth});"""
    with open(fname) as f:
        reader = DictReader(f, headers, delimiter=",")
        for rec in reader:
            print(sql.format(tablename=tablename, **rec)) # python <= 2.6 will fail here

rawDescription: Export & Map CSV output to MySQL table using Python


code:
def vectorized_form(img):
    R,G,B = [img[:,:,x] for x in range(3)]
    delta15 = np.abs(R.astype(np.int8) - G.astype(np.int8)) > 15  # watch out for np.abs(R-G): because of the UNsigned numbers, they could get clipped!
    more_R_than_B = (R > B)
    is_skin_coloured_during_daytime = ((R > 95) & (G > 40) & (B > 20) &
        (img.ptp(axis=-1) > 15) & delta15 & (R > G) & more_R_than_B)
    is_skin_coloured_under_flashlight = ((R > 220) & (G > 210) & (B > 170) &
        ~delta15 & more_R_than_B & (G > B))
    return np.logical_or(is_skin_coloured_during_daytime, is_skin_coloured_under_flashlight)

rawDescription: Select complex colour range for skin-colour detection in OpenCV with Python


rawDescription: Merge to different dictionaries

description: Merge to different dictionaries


code:
'!!python/tuple [foo, bar, baaz]\n'
('foo', 'bar', 'baaz')

rawDescription: How can I add a python tuple to a YAML file using pyYAML?

description: Add a python tuple to a YAML file using pyYAML


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


rawDescription: relation between two columns Python

description: Relation between two columns Python


rawDescription: Python Check Duplicate in Array

description: Python Check Duplicate in Array


code: {'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}

rawDescription: python tkinter tree get selected item values

description: Python tkinter tree get selected item values


code:
from webhelpers2.html.builder import literal

e1 = literal.escape('& < >')
e1
literal('& < >')

e2 = literal.escape(e1)
e2
Out[5]: literal('& < >')

s = ''.join(e1)
s
Out[7]: '& < >'

rawDescription: Escaping characters in Python, but ignoring already escaped characters


rawDescription: How to stepwise approximate f(x) using Euler's method given f'(x)

description: Stepwise approximate f(x) using Euler's method given f'(x)


code:
my_list = ["hello", "world"]
with open('file.txt', 'w') as f:
    f.write('\n'.join(my_list))  # assuming your list isn't large
    f.write('\n')

rawDescription: how do i find and replace items in a text file in pyscripter?

description: Find and replace items in a text file in pyscripter


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from geraldo import Report, ReportBand, ObjectValue
from geraldo.generators import PDFGenerator

class UnicodeReport(Report):
    title = 'Report'
    additional_fonts = {
        'wqy': '/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc'
    }
    default_style = {'fontName': 'wqy'}

    class band_detail(ReportBand):
        elements = [ObjectValue(attribute_name='name')]

if __name__ == '__main__':
    objects = [{'name': u'한국어/조선말'}, {'name': u'汉语/漢語'}, {'name': u'オナカップ'}]
    rpt = UnicodeReport(queryset=objects)
    rpt.generate_by(PDFGenerator, filename='/tmp/report.pdf')

rawDescription: Unicode characters are boxes in Geraldo/ReportLab generated PDF


code:
#!/usr/bin/env python
import cgi
import fileinput
import os
import shutil
import sys

def textfiles(rootdir, extensions=('.txt',)):
    for dirpath, dirs, files in os.walk(rootdir):
        for f in files:
            if f.lower().endswith(extensions):
               yield os.path.join(dirpath, f)

def htmlfiles(files):
    for f in files:
        root, _ = os.path.splitext(f)
        newf = root + '.html'
        shutil.copy2(f, newf)
        yield newf

for line in fileinput.input(htmlfiles(textfiles(sys.argv[1])), inplace=True):
    if fileinput.isfirstline():
       klass = 'aaa' # start head part
    line = cgi.escape(line.decode('utf-8').strip())
    line = line.encode('ascii', 'xmlcharrefreplace')
    if not line: # empty line
       klass = 'bbb' # start tail part
       print(line)
    else:
       print('
%s
' % (klass, line))

rawDescription: Python multiple regular expression replace


code: concord = text.concordance("cultural", 75, sys.maxint)

rawDescription: Python: how to capture output to a text file? (only 25 of 530 lines captured now)


code:
import tkinter

app = tkinter.Tk()

# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'

# This function will run when pressing the space bar
def on_spacebar_press( event ):
    print( 'Clicked words:', *clicked )

# Button creator function
def create_buttons( words ):
    # Create a button for each word
    for word in words:
        # This function will run when a button is clicked
        def on_button_click(word=word):
            clicked.add( word )
        # Add button
        button = tkinter.Button( app,
                                 text=word,
                                 command=on_button_click )
        # If you have 180 buttons, you should consider using the grid()
        # layout instead of pack() but for simplicity I used this one for demo
        button.pack()

# Binding function tp space bar event
app.bind('<space>', on_spacebar_press)

# This call creates the buttons
create_buttons( words )

# Now we enter to event loop -> the program is running
app.mainloop()

rawDescription: Creating buttons dependent on input, getting user data


code: i = np.argmax(df1.index > t)

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

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


code:
from itertools import tee, izip
it1, it2 = tee(seq)
next(it2)
izip(it1, it2)

rawDescription: Understanding builtin next() function

description: Understanding builtin next() function


rawDescription: How to evaluate two items of the same list and return their sum if equal?

description: Evaluate two items of the same list and return their sum if equal


rawDescription: How to get the length of words in a sentence?

description: Get the length of words in a sentence


rawDescription: l.append[i], object is not subscriptable?

description: L.append[i], object is not subscriptable


code:
hash(a) == hash(b)
a == b
a is b

rawDescription: Three tiers of equality comparison in Python


code:
from mymodule import MyClass
import mock

with mock.patch('mymodule.socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')

rawDescription: mocking a socket connection in Python

description: Mocking a socket connection in Python


code:
from functools import wraps

class Int4(int):
    def __new__(cls, i):
        return super(Int4, cls).__new__(cls, i & 0xf)

def add_special_method(cls, name):
    mname = '__{}__'.format(name)
    @wraps(getattr(cls, mname))
    def convert_to_cls(self, other):
        bound_original = getattr(super(cls, self), mname)
        return type(self)(bound_original(other))
    setattr(cls, mname, convert_to_cls)

for m in ('add', 'sub', 'mul', 'floordiv', 'mod', 'pow',
          'lshift', 'rshift', 'and', 'xor', 'or'):
    add_special_method(Int4, m)
    add_special_method(Int4, 'r' + m)  # reverse operation

rawDescription: How to emulate 4-bit integer in Python 3?

description: Emulate 4-bit integer in Python 3


code: count += name.count(vowels[i])

rawDescription: Counting vowels using nested loop in python


code:
from flask import make_response, redirect, url_for

response = make_response(redirect('/'))

lat = request.form['lat']
lon = request.form['lon']
response.set_cookie('lat', lat)
response.set_cookie('lon', lon)

return response

rawDescription: Heroku Python: What is the proper way to set and get cookies?


code: df.to_csv(f, mode='a', header=False)

rawDescription: pandas DataFrame output end of csv

description: Pandas DataFrame output end of csv


rawDescription: How to call a class's method in python?

description: Call a class's method in python


rawDescription: Pandas series – lowest value in last x rows


code: import foo

rawDescription: Python: what does "import" prefer - modules or packages?


code: func(5, "some", "values", "in", "a", "list")

rawDescription: Passing a list of parameters into a Python function


code:
with open('try.csv', 'w') as f:
    for m in M:
       s = m['student']
       l = m['lecturer']
       Lecturer[l]['limit'] = Lecturer[l]['limit'] - 1
       id = m['projectid']
       p = Project[id]['title']
       c = Project[id]['sourceid']
       r = str(getRank("Single_Projects1copy.csv",s,c))
       print(s+","+l+","+p+","+c+","+r)

       dataPack = (s+","+l+","+p+","+c+","+r)
       pd.DataFrame.from_records([dataPack]).to_csv(f, header=False)

rawDescription: Using Pandas to export multiple rows of data to a csv


rawDescription: Python use array axis to select slice

description: Python use array axis to select slice


code:
star1,star2=None,None

for x in starlist:
    if x.id == starid1:
       star1 = x
       break

for x in starlist:
    if x.id == starid2:
       star2 = x
       break

rawDescription: value assignment in python

description: Value assignment in python


code:
import StringIO
f = StringIO.StringIO()
f.write('asdf')
f.getvalue()

rawDescription: Python, write in memory zip to file

description: Python, write in memory zip to file


rawDescription: importing python logging module settings

description: Importing python logging module settings


rawDescription: Python Lists and Equality

description: Python Lists and Equality


code:
url (
    r'^accounts/register/$',
    RegistrationView.as_view(form_class=extendedRegistrationForm),
)

rawDescription: How to over-ride default registration form in Django-Registration version 1.0?

description: Over-ride default registration form in Django-Registration version 1.0


code:
import numpy as np
np.linspace(0,5,10)

rawDescription: Making a list of evenly spaced numbers in a certain range in python


code:
import settings.default
from settings.local import Config
Config.MYSQL_PORT
Config.MYSQL_URI

rawDescription: How to implement compound configuration variables, or "module level properties?"

description: Implement compound configuration variables, or "module level properties?"


code: poss

rawDescription: Combinations of elements in Dictionary in Python


code: grouped = df.groupby(['Min', 'Se', 'ID'])

rawDescription: pandas or numpy for multi column conditional averaging

description: Pandas or numpy for multi column conditional averaging


code:
import re
re.sub(r'\s+', '-', 'The   Quick  \nBrown\t Fox')

rawDescription: Inserting another character in place of spaces in Python


code:
import unicodedata
def eval_unicode(s):
    #sum all the unicode fractions
    u = sum(unicodedata.numeric(i) for i in s if unicodedata.category(i)=="No")
    #eval the regular digits (with optional dot) as a float, or default to 0
    n = float("".join(i for i in s if i.isdigit() or i==".") or 0)
    return n+u

rawDescription: How do I calculate the numeric value of a string with unicode components in python?

description: Calculate the numeric value of a string with unicode components in python


rawDescription: Matplotlib: Adjust legend location/position


code:
def set_properties(instance, properties):
    for key,val in properties.iteritems():
        setattr(instance, key, val)

rawDescription: more convenient way to assign variables to class object properties

description: More convenient way to assign variables to class object properties


code:
import os
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def dirtree():
    path = os.path.expanduser(u'~')
    return render_template('dirtree.html', tree=make_tree(path))

if __name__=="__main__":
    app.run(host='localhost', port=8888, debug=True)

rawDescription: How to generate an html directory list using Python

description: Generate an html directory list using Python


rawDescription: Pick values only below a certain threshold


code:
from multiprocessing.dummy import Pool as ThreadPool
from scriptB import scriptB_function

args = [1,2,3,4,5,6,7,8]

pool = ThreadPool(4) # 4 threads in pool
result = pool.map(scriptB_function, args)
pool.close()
pool.join()

rawDescription: Limit the number of running instances of a python script


code:
class TestClass(metaclass=saveDirMeta):
    def __init__(self):
        pass # do something

rawDescription: Python get class name

description: Python get class name


code:
class myAudio(object):

    def __init__(self, chunk=1024, fmt=pyaudio.paInt16, channels=1, rate=41000, record_seconds=5):
        self.p = pyaudio.PyAudio()
        self.CHUNK = chunk
        self.FORMAT = fmt
        self.CHANNELS = channels
        self.RATE = rate
        self.RECORD_SECONDS = record_seconds

    def openTheMic(self, **kwargs):
        _chunk          = kwargs.get('chunk',          self.CHUNK)
        _format         = kwargs.get('fmt',            self.FORMAT)
        _channels       = kwargs.get('channels',       self.CHANNELS)
        _rate           = kwargs.get('rate',           self.RATE)
        _record_seconds = kwargs.get('record_seconds', self.RECORD_SECONDS)

        stream = self.p.open(
            format            = _format,
            channels          = _channels,
            rate              = _rate,
            input             = True,
            output            = True,
            frames_per_buffer = _chunk
        )

        print ("***mic is open***")

        for i in range(0, _rate / _chunk * _record_seconds):
             data = stream.read(_chunk)

if __name__ == '__main__':
    mic = myAudio()
    mic.openTheMic(record_seconds = 10)

rawDescription: Way to override a class __init__ in python


rawDescription: Ordering a nested dictionary by the frequency of the nested value


code:
class Translation(ndb.Expando):
  """ parent: original_entity.key
      string_id: language
  """
  pass

rawDescription: What would be the appropiate design for storing content in multiple languages in Google App Engine?


code:
application = QApplication(argv)

locale = QLocale.system().name()
qtTranslator = QTranslator()
if qtTranslator.load("qt_"+locale):
    application.installTranslator(qtTranslator)

main_window = QMainWindow()
main_window.show()

exit(application.exec_())

rawDescription: PyQt: translating standard buttons

description: PyQt: translating standard buttons


code:
stringy = res.decode('utf-8') # or whatever encoding your system uses
print(type(stringy), stringy.splitlines()[0])

rawDescription: subprocess.Popen output: how to overcome the differences with commandline execution

description: Subprocess.Popen output: how to overcome the differences with commandline execution


code:
ma = df.values.argmin(axis=1)[:,None] <= np.arange(df.shape[1])
df.ge(4*df.min(axis=1), axis=0) & ma

rawDescription: identify time point in data frame based on condition per time series

description: Identify time point in data frame based on condition per time series


code:
mylist  = [True , True, False]

[not i for i in mylist]

rawDescription: Flipping the boolean values in a list Python


code:
lfunction = types.FunctionType(marshal.loads(item[1]), globals, closure=UnmarshalClosureValues(item[2]))
gfunctions[item[0]] = lfunction

rawDescription: Can I restore a function whose closure contains cycles in Python?

description: Restore a function whose closure contains cycles in Python


code:
cbVars = {}
for client in dict_list:
    ...
    bizname = client["Business Name"]
    cbVars[bizname] = IntVar()
    cb = Checkbutton(..., onvalue=1, offvalue = 0, variable = cbVars[bizname])
    ...

rawDescription: Checkbox to determine if an action is completed or not


rawDescription: Get list of all paginated URL's from links in txt file in python requests


code:
nrandom = 10
random.sample( colors*(nrandom//len(colors)+1), nrandom )

rawDescription: Returning N random items from smaller original list


code:
from itertools import count, cycle, islice, izip
import lxml.html as lh
import requests

URL_FILE   = "file.txt"
ROW_FORMAT = "{:>5}     {:18} {:>5}     {:18} {:>5}     {}".format
HEADER     = ['Match', 'Up', 'Score', 'Down', 'Score', 'Tournament']

lookfor = {
    'tournament': '//title/text()',
    'round1':     '//div[@data-round]/span/text()',
    'scoreup':    '//div[contains(@class, "top_score")]/text()',
    'scoredown':  '//div[contains(@class, "bottom_score")]/text()'
}

def main():
    with open(URL_FILE) as inf:
        urls = (line.strip() for line in inf)
        for num,url in enumerate(urls, 1):
            # get data
            txt = requests.get(url).text
            tree = lh.fromstring(txt)

            # pull out the bits we want
            scraped = {name:tree.xpath(path) for name,path in lookfor.items()}
            # (and fix the title)
            title = scraped['tournament']
            tournament = title[0].replace('\n', '') if title else ''

            # reslice the data so it lines up
            match_num   = count(1)                               # 1, 2, 3, ...
            up_rounds   = islice(scraped['round1'], 0, None, 2)  # even rounds
            down_rounds = islice(scraped['round1'], 1, None, 2)  # odd rounds
            tournament  = cycle([tournament])      # repeats the name
            # ... and reassemble it
            results = izip(match_num, up_rounds, scraped['scoreup'], down_rounds, scraped['scoredown'], tournament)

            # generate output
            print("\nRound {}:".format(num))

            print(ROW_FORMAT(*HEADER))
            for row in results:
                print(ROW_FORMAT(*row))

if __name__=="__main__":
    main()

rawDescription: Python Requests Scraping

description: Python Requests Scraping


rawDescription: Get Request Headers for Urllib2.Request?

description: Get Request Headers for Urllib2.Request


code:
for reg in RegionIDArray:
    for page in range(1,700,30):
        r = requests.get("https://www.tripadvisor.de/Attractions-c" + str(museumIDArray) +"-g" + str(reg) + "-oa" + str(page) + ".html")
        soup = BeautifulSoup(r.content)

        for item in (a.text for a in soup.select("div.property_title a")):
            if item not in already_printed:
                already_printed.add(item)
                print("POI: " + str(item) + " | " + "Location: " + str(dct[reg]) + " | " + "Art: Museum ")

rawDescription: Crawl Multiple pages from a website (BeautifulSoup,Requests,Python3)


rawDescription: efficiently computing parafac / CP product in numpy

description: Efficiently computing parafac / CP product in numpy


code: map(int, list(str(foo)))

rawDescription: How to convert a number into a linked list of its digits in python

description: Convert a number into a linked list of its digits in python


code: x.merge(y, left_on=['t1'], right_on=['t2'], how='outer')

rawDescription: Interleaving Pandas Dataframes by Timestamp


code: getmax(lst)

rawDescription: Finding how many of a certain character in each element in a list


rawDescription: Plotting surface of implicitly defined volume


code: your_array.reshape(-1, 1)

rawDescription: forcing genfromtxt output to no-vector

description: Forcing genfromtxt output to no-vector


code: letters = (c.lower() for c in text if c.isalpha())

rawDescription: How to impress developers with IronPython/Python

description: Impress developers with IronPython/Python


code:
from smtplib import SMTP_SSL
from email.mime.text import MIMEText

## The SMTP server details

smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"

## The email details

from_address = "address1@domain.com"
to_address = "address2@domain.com"

cc_addresses = ["address3@domain.com", "address4@domain.com"]

msg_subject = "This is the subject of the email"

msg_body = """
This is some text for the email body.
"""

## Now we make the email

msg = MIMEText(msg_body) # Create a Message object with the body text

# Now add the headers
msg['Subject'] = msg_subject
msg['From'] = from_address
msg['To'] = to_address
msg['Cc'] = ', '.join(cc_addresses) # Comma separate multiple addresses

## Now we can connect to the server and send the email

s = SMTP_SSL(smtp_server, smtp_port) # Set up the connection to the SMTP server
try:
    s.set_debuglevel(True) # It's nice to see what's going on

    s.ehlo() # identify ourselves, prompting server for supported features

    # If we can encrypt this session, do it
    if s.has_extn('STARTTLS'):
        s.starttls()
        s.ehlo() # re-identify ourselves over TLS connection

    s.login(smtp_username, smtp_password) # Login

    # Send the email. Note we have to give sendmail() the message as a string
    # rather than a message object, so we need to do msg.as_string()
    s.sendmail(from_address, to_address, msg.as_string())

finally:
    s.quit() # Close the connection

rawDescription: How to send Gmail email with multiple CC:'s

description: Send Gmail email with multiple CC:'s


rawDescription: Regex to match Domain.CCTLD

description: Regex to match Domain.CCTLD


code:
from sympy import *
var('r k I d C t')
eq = Eq(C(t).diff(t), r + k*I + d*C(t))  # note d*C(t) not d*C
ans = dsolve(eq); ans

rawDescription: Differentiation in python using Sympy

description: Differentiation in python using Sympy


code:
def get(d, t, r):
    try:
        return max((x for x in d[t] if x["Rad"] < r), key=lambda x: x["Rad"])["Code"]
    except ValueError:
        return None

rawDescription: How can I lookup based on multiple parameters?

description: Lookup based on multiple parameters


code: django.core.urlresolvers.reverse = ur_reverse_decorator(django.core.urlresolvers.reverse )

rawDescription: Is it possible to redefine reverse in a Django project?


rawDescription: Python Sympy Arbitrary Approximation to Arbitrary Sympy Expression?


code:
for key, val in categories.items() :
    for k, v in items.items() :
        if key == v :
            print(val, k)

rawDescription: How to create a dict from 2 dictionaries in Python?

description: Create a dict from 2 dictionaries in Python


code:
c = [[[1], [2, 3]], [4, 5], [[6, 7, 8], 9]]

def expand(lst):
    try:
        for a in lst:
            for b in expand(a):
                yield b
    except TypeError:
        yield lst

res = list(expand(c))   # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

rawDescription: expanding arbitrary number of sublists within a list

description: Expanding arbitrary number of sublists within a list


code:
from PyQt4 import QtCore, QtGui

class CustomLabel(QtGui.QLabel):

    def __init__(self, line_edit_lst):
        super(CustomLabel, self).__init__("0")
        self.line_edit_lst = line_edit_lst
        for line_edit in self.line_edit_lst:
            line_edit.textChanged.connect(self.update)

    def update(self, ignore):
        total = sum(self.str_to_float(line_edit.text())
                    for line_edit in self.line_edit_lst)
        self.setText(str(total))

    def str_to_float(self, string, default=0):
        try: return float(string)
        except ValueError: return default

class MyDialog(QtGui.QDialog):

    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        hbox = QtGui.QVBoxLayout()
        self.lines = [QtGui.QLineEdit() for _ in range(5)]
        for line in self.lines:
            hbox.addWidget(line)
        self.label = CustomLabel(self.lines)
        hbox.addWidget(self.label)
        self.setLayout(hbox)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MyDialog()
    w.show()
    sys.exit(app.exec_())

rawDescription: Creating a class signal with pyqt4

description: Creating a class signal with pyqt4


code:
mouse_c = pygame.sprite.Sprite()
mouse_c.image = pygame.image.load(milf).convert_alpha()
mouse_c.rect = mouse_c.image.get_rect()
mouse_c.rect.move_ip(10,10)

nPc = pygame.sprite.Sprite()
nPc.image = pygame.image.load(milf).convert_alpha()
nPc.rect = nPc.image.get_rect()
nPc.rect.move_ip(10,10)

rawDescription: converting an image to a rect

description: Converting an image to a rect


code:
x = MyIter('abc')
for item in x:
    print(item, x.tell())

rawDescription: How should I create an iterator that also supports a tell() method?


code: df[masked][['source_ip', 'tids']]

rawDescription: How to split pandas data frame by many criteria

description: Split pandas data frame by many criteria


code: bprive.label.set_text("A new label") # works

rawDescription: Python: Change the label of a matplotlib button on click


code:
s = 'abcd'
s[1:3]      #return sub-string from 1 to 2th index (3 in not inclusive)

rawDescription: Create new list of substrings from list of strings


rawDescription: Override the {...} notation so i get an OrderedDict() instead of a dict()?


code:
ts3 = ts.truncate(before='2011-01-08')
ts3

rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
import my_module
my_module.my_func('a', 'b')

rawDescription: Have command line argument as a default function argument


rawDescription: python how to get string form list value

description: Python how to get string form list value


code:
def cars(self, **kwargs):
    url = "cars"
    for kw in ["model", "color", "miles"]:
        if kwargs.get(kw) is not None:
            url += "/%s=%s" % (kw, kwargs[kw])
    return url

rawDescription: Need to shrink my large if elif statement in python


code:
import time

time.sleep(5)

browser.driver.save_screenshot(str(step+1) + '.png')

rawDescription: saving inline image from splinter

description: Saving inline image from splinter


code:
p = subprocess.Popen(['./arraytest'], shell=False, stdin=subprocess.PIPE)
p.communicate('\0'.join(str(n) for n in HSPACE) + '\0')

rawDescription: How to pass an array from python to shell script and execute it?

description: Pass an array from python to shell script and execute it


code:
# The IMPOSIBLE GAME

import random
import pygame
from pygame.color import Color
from pygame.surface import Surface
from pygame.sprite import Sprite, Group

pygame.init()

# note how pygame defines a lot of colors already for you
colour_list = [Color('Black'), Color('White'), Color('Red'), Color('Blue'), Color('Green')]

# we use a dict to keep a simple 'What Key Moves In Which Direction'-map
keys = {pygame.K_UP:    ( 0, -3),
        pygame.K_DOWN:  ( 0,  3),
        pygame.K_LEFT:  (-3,  0),
        pygame.K_RIGHT: ( 3,  0)}

# using sprites will make your live easy
# e.g. you don't need to handle drawing yourself
class Player(Sprite):
    def __init__(self):
        Sprite.__init__(self)

        # we create a simple rectangular surface
        self.image = Surface((30, 30))
        self.rect = self.image.get_rect()
        self.image.fill(Color('Black'))

        # we set a colorkey so we can create a mask
        # this mask is used for pixel perfect collision
        # which will come in handy not only for circles
        # but if you extend your game to other shape
        self.image.set_colorkey(Color('Purple'))
        self.mask = pygame.mask.from_surface(self.image)
        self.deaths = 0

    def update(self):
        # use a random color from the list
        self.image.fill(random.choice(colour_list))

        # check which keys are pressed
        pressed = pygame.key.get_pressed()
        for key, movement in keys.iteritems():
            if pressed[key]:
                # and move our rect in that direction
                # note how we don't need extra variables
                # the rect is enough
                self.rect.move_ip(movement)

        # we use the clamp_ip function to ensure your rect
        # does not get out of screeen.
        self.rect.clamp_ip(pygame.display.get_surface().get_rect())

        # check if we collide with any object in the objects group
        # we use pygame.sprite.collide_mask to have a pixel perfect
        # collision detection
        # objects is a global variable, which may bother, but we could
        # simply pass it through the update function instead
        if pygame.sprite.spritecollide(self, objects, False, pygame.sprite.collide_mask):
            self.deaths += 1
            self.rect.topleft = (0, 0)

class Circle(Sprite):
    def __init__(self, start_x, speed):
        Sprite.__init__(self)
        # same as the in the Player class
        # we create a simple Surface
        self.image = Surface((30, 30))
        self.rect = self.image.get_rect(x=start_x, y=100)
        self.image.fill(Color('Purple'))
        self.image.set_colorkey(Color('Purple'))
        pygame.draw.ellipse(self.image, Color('Blue'), (0, 0, 30, 30), 0)
        self.mask = pygame.mask.from_surface(self.image)
        self.y_vel = speed

    def update(self):
        # we create a rect which will tell us
        # were we would move
        target = self.rect.move(0, self.y_vel)

        # and if we would go out of screen
        if not pygame.display.get_surface().get_rect().contains(target):
            # we simply change direction
            self.y_vel *= -1

        # then acutally move
        self.rect.move_ip(0, self.y_vel)

screen = pygame.display.set_mode((700, 400))
clock = pygame.time.Clock()
done = False

# When creating the circles, we can specify the start position and speed
objects = Group((Circle(x+100, 5) for x in xrange(0, 500, 100)))

# use a Group to handle updating and drawing
all_group = Group(*objects)
all_group.add(Player())

# your main loop is as easy as this
while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    all_group.update()

    screen.fill(Color('White'))
    all_group.draw(screen)
    pygame.display.flip()

    clock.tick(60)

pygame.quit()

rawDescription: Strange timing issues in PyGame when animating bouncing balls


rawDescription: Timeseries average with python

description: Timeseries average with python


code:
textPad = ScrolledText(self)
textPad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)

rawDescription: Python Tk display and edit a file

description: Python Tk display and edit a file


code:
def proper(func):
    def f(*args, **kwargs):
        s = func(*args, **kwargs)
        return s.difference(args)
    return f

rawDescription: Remove a value from a set with a function decorator


code:
class Spam(object):
    bar = Foo().bar  # *bound* method, taken from an instance of Foo
Spam.bar
Spam().bar
Spam().bar()

rawDescription: Not sure what the Python documentation says about user-defined method objects here


code:
def bugged_recursion(inp_value, list_index=0):
    # i don't get why you compare list_index here
    if list_index == 0:
        # you'll get an IndexError if list_index > len(inp_value)
        if inp_value[list_index] == 'valid':
            status = 'valid inp_value'
        else:
            status = 'invalid inp'
            # there is only one place where you increment list_index
            # i suppose there is something wrong here
            list_index +=1
            # you forgot to return here
            return bugged_recursion(inp_value, list_index=list_index)
    else:
        if inp_value[list_index] == 'valid':
            status = 'index {} is a valid inp_value'.format(list_index)
        else:
            status = 'index is never a valid inp_value'
    return (inp_value,status)

rawDescription: Recursive function that return result from 'if' statement instead of 'else' statement


code:
for b in a:
    for x in b:
        yield x

rawDescription: How to read aloud Python List Comprehensions?

description: Read aloud Python List Comprehensions


code:
fruit = "Orange"
translation[fruit]

rawDescription: Conditional renaming of strings in Python


code:
from operator import add
add(1, 2)
add('a', 'b')

rawDescription: How can I get the addition object for integers?

description: Get the addition object for integers


code:
class Counter(object):
   def __init__(self):
      self.num = 0

   def inc(self):
      self.num += 1

count = Counter()
count.inc()

rawDescription: In Python, what is the difference between an object and a dictionary?


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)

x = np.random.normal(5, 2, 10000)
y = np.random.normal(2, 1, 3000000)

xweights = 100 * np.ones_like(x) / x.size
yweights = 100 * np.ones_like(y) / y.size

fig, ax = plt.subplots()
ax.hist(x, weights=xweights, color='lightblue', alpha=0.5, normed=True)
ax.hist(y, weights=yweights, color='salmon', alpha=0.5, normed=True)

ax.set(title='Histogram Comparison', ylabel='% of Dataset in Bin')
ax.margins(0.05)
ax.set_ylim(bottom=0)
plt.show()

rawDescription: Plot two histograms on the same graph and have their columns sum to 100


code:
def countnonoverlappingrematches(pattern, thestring):
  return re.subn(pattern, '', thestring)[1]

rawDescription: Find out how many times a regex matches in a string in Python


code: [d['key'] for d in l if 'key' in d]

rawDescription: Get a list of values from a list of dictionaries in python


rawDescription: Reformat a column containing dates in Pandas


rawDescription: Python XML Parsing Algorithm Speed

description: Python XML Parsing Algorithm Speed


code:
while True:
   if not GPIO.input(22):
      print("Triggered")
      os.system('omxplayer -o hdmi cow.mp3')
      while not GPIO.input(22):
          time.sleep(.1)
   else:
      print ("Waiting to be triggered again")
      os.system('omxplayer -o hdmi sample.mp3')
      while GPIO.input(22):
          time.sleep(.1)

rawDescription: Pi run command and wait

description: Pi run command and wait


code:
counter = 0
def adder(x, y):
  global counter
  counter += 1
  return x + y

def op(d):
  if d <= 1: return adder
  return lambda x,y:reduce(op(d-1),(x for i in xrange(y)))
op(5)(2,4)
counter
counter = 0
op(3)(4,100)
counter

rawDescription: recursive closures (function generator)

description: Recursive closures (function generator)


rawDescription: Insert 0s into 2d array

description: Insert 0s into 2d array


code:
import re
re.findall(r'[a-zA-Z]+_[a-zA-Z]+_\d+', "music_neu_3, music_pos_76, books_neg_104")

rawDescription: Regular expression with two underlines

description: Regular expression with two underlines


code: hosts = raw_input("enter hosts (separated by a comma):").split(',')

rawDescription: How do you create multiple variables from raw input in python?

description: Create multiple variables from raw input in python


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

nrows, ncols = 3, 3

x = np.linspace(0,10,100)

fig = plt.figure()
for i in range(1,7):
    ax = fig.add_subplot(nrows, ncols, i)
    ax.plot(x, x**i)

plt.show()

rawDescription: loop over 2d subplot as if it's a 1-D

description: Loop over 2d subplot as if it's a 1-D


code:
import string
next(i for i,j in enumerate(g) if j not in string.ascii_letters)

rawDescription: how can i finding the index of non-ASCII character in python string?

description: Finding the index of non-ASCII character in python string


code: continues = input("Write to File? (y = yes):\t").lower()

rawDescription: how to run a continuous loop and add input to text

description: Run a continuous loop and add input to text


rawDescription: np.where() not returning expected indices in numpy python

description: Np.where() not returning expected indices in numpy python


code:
def my_yaml_dump(yaml_obj):
    my_ob = deepcopy(yaml_obj)
    for item in dir(my_ob):
        if item.startswith("_") and not item.startswith("__"):
             del my_ob.__dict__[item]
    return yaml.dump(my_ob)

rawDescription: How can I ignore a member when serializing an object with PyYAML?

description: Ignore a member when serializing an object with PyYAML


code: tmp

rawDescription: Pandas: Change dates in dataframe to same date format


code: subprocess.Popen(["start", "dir"], stdin=subprocess.PIPE, shell=True)

rawDescription: Launch two different scripts in two separate cmd windows using subprocess in python


code:
x,y = (sum(x) for x in zip(*((a*b, a) for _,a,b in d.values())))
x/y   # float(y) in Py2

rawDescription: Using dictionary values to calculate sum of weighted values without explicitly defined weights


code: re.compile("<img src='([^']*)jpg'")

rawDescription: python regular expression could not find all images files

description: Python regular expression could not find all images files


code:
def is_good(d):
    for v in d.values():
        if isinstance(v, list):
            for x in v:
                if isinstance(v, bool):
                    return False
    return True

rawDescription: Python - Enforce non-occurence of bool in list


code:
freq
sorted(['abc','def','ghi'], key=freq.get, reverse=True)

rawDescription: Sort str series by frequency

description: Sort str series by frequency


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

description: Place a table on a plot in Matplotlib


code:
for i in range(0, len(sample), 5):
    chunk = sample[i:i + 4]  # ignore the 5th byte, a space

rawDescription: Split array byte string in Python

description: Split array byte string in Python


code: [max(vals) for _,vals in itertools.groupby(sorted(scores), lambda x:x[0])]

rawDescription: "group by" aggregate functions with dictionary comprehensions


code: ax.contourf(x, y, scalar_field, zdir='y', offset=-y_dim/2-1, cmap=cm.coolwarm)

rawDescription: 3D plot with Matplotlib

description: 3D plot with Matplotlib


code:
queryset = Conversation.objects.filter(Q(user_1=user) | Q(user_2=user)).filter(
                Q(messages__sender=user, messages__archived_by_sender=False) |
                Q(messages__recipient=user, messages__archived_by_recipient=False)).annotate(
                last_activity=Max("messages__created")).order_by("-last_activity")

rawDescription: Django order_by after distinct(). Or distinct?


code:
# Find row and column locations that are non-zero
(rows,cols) = np.nonzero(img)

# Initialize empty list of co-ordinates
skel_coords = []

# For each non-zero pixel...
for (r,c) in zip(rows,cols):

    # Extract an 8-connected neighbourhood
    (col_neigh,row_neigh) = np.meshgrid(np.array([c-1,c,c+1]), np.array([r-1,r,r+1]))

    # Cast to int to index into image
    col_neigh = col_neigh.astype('int')
    row_neigh = row_neigh.astype('int')

    # Convert into a single 1D array and check for non-zero locations
    pix_neighbourhood = img[row_neigh,col_neigh].ravel() != 0

    # If the number of non-zero locations equals 2, add this to
    # our list of co-ordinates
    if np.sum(pix_neighbourhood) == 2:
        skel_coords.append((r,c))

rawDescription: How can I find endpoints of binary skeleton image in OpenCV?

description: Find endpoints of binary skeleton image in OpenCV


code:
manager = Manager()
for i in range(5):
    new_value = manager.Value('i', 0)

rawDescription: Shared variable in python's multiprocessing


code:
from select import select
from subprocess import Popen, PIPE

while True:
    child = Popen('echo hello; echo goodbye>&2', shell=True, stdout=PIPE, stderr=PIPE)
    rfs, _, _ = select([child.stdout, child.stderr], [], [])
    child.wait()
    if len(rfs) > 1:
        print('Data available on both pipes simultaneously! Cannot interleave correctly.')
        break

rawDescription: Python subprocess arbitrarily split output between files


code:
def sbo_extra_dwn(link, name):
    results = []
    sbo_url_dwn = link + name + ".info"
    sbo_url_dwn = sbo_url_dwn.replace("repository", "slackbuilds")

    f = urllib2.urlopen(sbo_url_dwn)
    read_page = f.read()
    for line in read_page.splitlines():
            if line.startswith(' '):
                    line = line[10:-1]
            if line.startswith('http'):
                    results.append(line)
    return results

rawDescription: What is the difference between print and return in a function?


rawDescription: List of edges that don't exist in a networkx graph?


code:
import argparse

class ArgumentParser(argparse.ArgumentParser):
   def __init__(self, *p, **kw):
      super(ArgumentParser, self).__init__(*p, **kw)
      self._reactions = []
   def add_reaction(self, handler):
      self._reactions.append(handler)
   def parse_known_args(self, args=None, namespace=None):
      (args, argv) = super(ArgumentParser, self).parse_known_args(args, namespace)
      for reaction in self._reactions:
         reaction(args)
      return (args, argv)

rawDescription: How to dynamically add options to optparser?

description: Dynamically add options to optparser


code:
from itertools import groupby, chain
from datetime import datetime

rawDescription: python deleting older files that match an unknown pattern (tricky)

description: Python deleting older files that match an unknown pattern (tricky)


code:
string = "big blue chair"
query = "SELECT * FROM albums WHERE title LIKE %s"
values = ["%{}%".format(val) for val in string.split()]
for _ in values[1:]:  # iterate over len(values) - 1
    query += " AND title LIKE %s"
print(query)
print(values)

rawDescription: Safe way to parameterize substring query with AND operator in MySQL + Python


code:
def segment(word):
  def sub(w):
    if len(w) == 0:
      yield []
    for i in xrange(1, min(4, len(w) + 1)):
      for s in sub(w[i:]):
        yield [''.join(w[:i])] + s
  return list(sub(word))

# And if you want a list of strings:
def str_segment(word):
  return [' '.join(w) for w in segment(word)]

rawDescription: Read all possible sequential substrings in Python


code: self._solutions = [[0]*(self.SIZE) for _ in range(self.SIZE)]

rawDescription: Unwanted behavior by Python List of Lists


code:
QRAIN = [ [1000*np.mean(QC[t,z,:,:]) for z in range(279)]
          for t in range(150) ]
QR = np.array(QRAIN)

rawDescription: Separate the first loop append and the second loop append while doing double loop in Python


code:
from pyramid.paster import get_appsettings

settings = get_appsettings('test.ini', name='main')
app = main(settings)

rawDescription: Gettings settings and config from INI file for Pyramid functional testing


code: common_keys = a.keys() & b.keys() & c.keys()

rawDescription: Getting common keys from different dictionaries in python


code: B.index = A.index

rawDescription: Reindexing dataframes and joining columns


rawDescription: matplotlib/python: how to have an area with no values

description: Matplotlib/python: how to have an area with no values


rawDescription: Python: how to map one list and one list of list together


rawDescription: How to create n lists in function of x python

description: Create n lists in function of x python


code:
import __builtin__
__builtin__.any(i % 3 for i in [3, 3, 4, 4, 3])

rawDescription: How to use a built-in function if its name is used by another module?

description: Use a built-in function if its name is used by another module


rawDescription: Desperate parsing HTML with BeautifulSoup in Python


code:
def foo():
    import os
    os.system("rm -rf /")

rawDescription: How can I set the function environment for a Python function?

description: Set the function environment for a Python function


code:
for thing in things:
    other_thing.append(thing)

rawDescription: Matlab - Iterating through an array and appending to a new one


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('F(X, Y)')
plt.show()

rawDescription: Python show a two-dimensional PDF function


rawDescription: Find Arc/Circle equation given three points in space (3D)


code: 'bba' in mylist['b'].values()

rawDescription: Python3 - How can I determine the existence of element values?


code:
# delete_all.py
from django.core.management.base import BaseCommand
from app.models import MyModel

class Command(BaseCommand):
    def handle(self, *args, **options):
        print('Deleting all MyModel records!')
        MyModel.objects.all().delete()
        print('Successfully deleted all MyModel records!')

rawDescription: Django: automatically delete records

description: Django: automatically delete records


rawDescription: How do I turn a dictionary with lists as values into a list of dictionaries with single values?

description: Turn a dictionary with lists as values into a list of dictionaries with single values


code:
import shutil

with open(csvfilename, 'wb') as outf:
    shutil.copyfileobj(response, outf)

rawDescription: JSON query in a post request from Python and save result as csv file


code: desired

rawDescription: python element tree xml parsing

description: Python element tree xml parsing


code:
def find(t, search):
    #
    # Find the *first* dictionary object having
    # the key "search"
    for k in t:
        if k == search:
            return t
        if isinstance(t[k],dict):
            result = find(t[k],search)
            if result:
                return result

    return None

rawDescription: how to traverse this tree?

description: Traverse this tree


rawDescription: matplotlib: how to prevent x-axis labels from overlapping each other

description: Matplotlib: how to prevent x-axis labels from overlapping each other


code: Counter('aabbccaabcaaa')

rawDescription: Dictionary that counts occurrences of its items


code:
def paired(binlist, map={(1, 1): 3, (0, 1): 2, (1, 0): 1, (0, 0): 0}):
    return [map[tuple(binlist[i:i + 2])] for i in range(0, len(binlist), 2)]

rawDescription: Python: calculate value for each pair of values in list


code:
import tkinter as tk
import tkFont

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('T-Pad')

    # Menubar

        menubar = tk.Menu(self)

        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", command=self.close_app)
        menubar.add_cascade(label="File", menu=filemenu)

        formatmenu = tk.Menu(menubar, tearoff=0)
        formatmenu.add_command(label="Font", command=self.show_sizeWin)
        menubar.add_cascade(label="Format", menu=formatmenu)

        self.config(menu=menubar)

    # Bold Button

        boldButton = tk.Button(self, width=12, text='Bold',
                                command=self.make_bold)
        boldButton.pack()

    # Text widget, its font and frame

        self.defaultFont = tkFont.Font(name="defFont")

        textFrame = tk.Frame(self, borderwidth=1, relief="sunken",
                             width=600, height=600)

        textFrame.grid_propagate(False) # ensures a consistent GUI size
        textFrame.pack(side="bottom", fill="both", expand=True)

        self.mText = tk.Text(textFrame, width=48, height=24, wrap='word',
                            font="defFont")
        self.mText.grid(row=0, column=0, sticky="nsew")

    # Scrollbar and config

        tScrollbar = tk.Scrollbar(textFrame, command=self.mText.yview)
        tScrollbar.grid(row=0, column=1, sticky='nsew', pady=1)

        self.mText.config(yscrollcommand=tScrollbar.set)

    # Stretchable

        textFrame.grid_rowconfigure(0, weight=1)
        textFrame.grid_columnconfigure(0, weight=1)

    # Bold Tag

        self.bold_font = tkFont.Font(self.mText, self.mText.cget("font"))
        self.bold_font.configure(weight="bold")
        self.mText.tag_configure("bt", font=self.bold_font)

    # Center main window

        self.update_idletasks()

        xp = (self.winfo_screenwidth() / 2) - (self.winfo_width() / 2) - 8
        yp = (self.winfo_screenheight() / 2) - (self.winfo_height() / 2) - 30
        self.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(), self.winfo_height(),
                                                                                xp, yp))

    # Font Size Window (notice that self.sizeWin is given an alias)

        sizeWin = self.sizeWin = tk.Toplevel(self, bd=4, relief='ridge')

        self.sizeList = tk.Listbox(sizeWin, width=10, height=17, bd=4,
                                font=("Times", "16"), relief='sunken')

        self.sizeList.grid()

        doneButton = tk.Button(sizeWin, text='Done', command=sizeWin.withdraw)
        doneButton.grid()

        for num in range(8,25):
            self.sizeList.insert('end', num)

        sizeWin.withdraw()

        sizeWin.overrideredirect(True) # No outerframe!
        # Below is another way to prevent a TopLevel window from being destroyed.
        # sizeWin.protocol("WM_DELETE_WINDOW", self.callback)

    # Bindings
        # Double click a font size in the Listbox
        self.sizeList.bind("<Double-Button-1>", self.choose_size)
        self.bind_class("Text", "<Control-a>", self.select_all)

##    def callback(self):
##        self.sizeWin.withdraw()

    def select_all(self, event):
        self.mText.tag_add("sel","1.0","end-1c")

    def choose_size(self, event=None):
        size_retrieved = self.sizeList.get('active')
        self.defaultFont.configure(size=size_retrieved)
        self.bold_font.configure(size=size_retrieved)

    def show_sizeWin(self):
        self.sizeWin.deiconify()
        xpos = self.winfo_rootx() - self.sizeWin.winfo_width() - 8
        ypos = self.winfo_rooty()
        self.sizeWin.geometry('{0}x{1}+{2}+{3}'.format(self.sizeWin.winfo_width(),
                                                self.sizeWin.winfo_height(), xpos, ypos))

    def make_bold(self):
        try:
            current_tags = self.mText.tag_names("sel.first")
            if "bt" in current_tags:
                self.mText.tag_remove("bt", "sel.first", "sel.last")
            else:
                self.mText.tag_add("bt", "sel.first", "sel.last")
        except tk.TclError:
            pass

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

rawDescription: Tkinter - RuntimeError: maximum recursion depth exceeded


code:
def HexagonRing(x,y,n,r):
    dc = n*math.sqrt(3) # distance between to neighbouring hexagon centers
    xc,yc = x,y-r*dc # hexagon center of one before first hexagon (=last hexagon)
    dx,dy = -dc*math.sqrt(3)/2,dc/2 # direction vector to next hexagon center
    for i in range(0,6):
        # draw r hexagons in line
        for j in range(0,r):
            xc,yc = xc+dx,yc+dy
            Hexagon(xc,yc,n)
        # rotate direction vector by 60°
        dx,dy = (math.cos(math.pi/3)*dx+math.sin(math.pi/3)*dy,
               -math.sin(math.pi/3)*dx+math.cos(math.pi/3)*dy)

rawDescription: Draw a hexagon tessellation animation in Python


rawDescription: Reg: Error in stretched exponential function fitting


code:
def get_mode():
    while True:
        mode = input('Do you wish to encrypt(e) or decrypt(d) a message: ').lower()
        if mode.lower() in {"e","d"}:
            return mode
        print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def get_message():
    while True:
        message = input('Enter your message: ')
        if all(ch.isalpha() or ch.isspace() for ch in message):
            return message
        print("Invalid input, text must contain alphabetic characters only.")

def get_key():
    return 5

from string import ascii_letters

d = {k: i for i, k in enumerate(ascii_letters)}

enc = ascii_letters

def get_translated_message(mode, message, key):
    if mode == "e":
        return "".join([enc[(d[ch] + key) % 52] if not ch.isspace() else ch for ch in message])
    return "".join([enc[(d[ch] - key) % 52] if not ch.isspace() else ch for ch in message])

rawDescription: Caesar Cipher validation

description: Caesar Cipher validation


code: result = [(key, sum(key in inputDict[nodes] for nodes in digraph)) for key in inputDict]

rawDescription: how to re-write for loop to list comprehension

description: Re-write for loop to list comprehension


rawDescription: Click a checkbox with selenium-webdriver


code:
b=[ HypotheticalBranch(0,0,0),
  HypotheticalBranch(0,1,1),
  HypotheticalBranch(1,2,1),
  HypotheticalBranch(1,3,2),
  HypotheticalBranch(1,4,2) ]

rawDescription: Python Combinatorics, part 2

description: Python Combinatorics, part 2


rawDescription: Optional number of wildcards in URL patterns in Django


code:
def quad(a, b, c):
    return lambda x: a * x**2 + b * x + c

rawDescription: Should I use a class? (Python)

description: Should I use a class? (Python)


code:
with open(file_location, 'rb') as file:
    data = pickle.load(file)
    print(data)

{'tuple': (), 'set': set(), 'int': 0, 'list': [], 'string': ''}

rawDescription: Writing and reading variables in a file in Python


code:
import builtins
print = lambda *args,**kwargs:builtins.print(*args,**kwargs)

rawDescription: Mocking print but allow using it in tests


rawDescription: How to copy unique keys and values from another dictionary in Python

description: Copy unique keys and values from another dictionary in Python


code:
import hashlib
from jinja2.sandbox import SandboxedEnvironment

def md5(s):
    return hashlib.md5(s).hexdigest()

# Sandbox because the source is likely to be untrusted
env = SandboxedEnvironment()

# Parsing any formula, wrapped in {{ ... }}
template = env.from_string('{{md5(salt + md5(password))}}')

# Running it:
hash_ = template.render(md5=md5, salt='3Fd0@5l4x', password='secret')
# hash_ == u'10aaeb818dd269d75bf460469c6b90ab'

rawDescription: Use template to construct md5 hash algorithm


code:
from Tkinter import *
from itertools import cycle
#from tkinter import ttk
def on_button():
    label.set(next(names))

root = Tk()
root.title("Iterator")

mainframe = Frame(root)
mainframe.grid()
names = cycle(["im1.gif","im2.gif","im3.gif"])
label = StringVar()
label.set("Click Next To Cycle Through")
Label(mainframe, textvariable=label).grid(column=2, row=2, sticky=(W, E))
Button(mainframe, text="next", command=on_button).grid(column=3, row=3, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

root.mainloop()

rawDescription: Loop Increment for every click in python/ pyqt


code:
df0 = pd.DataFrame(s0).set_index(s0.groupby(level=0).cumcount(), append=True)
df1 = pd.DataFrame(s1).set_index(s1.groupby(level=0).cumcount(), append=True)
df0

rawDescription: Merge multiple dataframes with non-unique indices


rawDescription: combining values for a large number of overlapping intervals of dictionary keys

description: Combining values for a large number of overlapping intervals of dictionary keys


code: ''.join(string[a:b] for a, b in zip(start_list, end_list))

rawDescription: python concatenate substrings by two lists with given start and end positions

description: Python concatenate substrings by two lists with given start and end positions


code: dict((v,k) for k,v in enumerate(calendar.month_abbr))

rawDescription: month name to month number and vice versa in python

description: Month name to month number and vice versa in python


code: CATEGORIES = ['Arts', 'Business', 'Computers']

rawDescription: Separate output file for every url given in start_urls list of spider in scrapy


code: self.menu.setWindowFlags( QtCore.Qt.CustomizeWindowHint ) # Hide the OS decorations

rawDescription: Python PySide modal Qdialog without OS decoration (title bar, ...)


code:
day_15 = numpy.searchsorted(time, 15)
factory_two[day_15:] = time[:-day_15] * 4

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


rawDescription: How to call a distant shell script from a python file?

description: Call a distant shell script from a python file


code:
def trans_function2(df):
    return df.loc[df['Primary'].argmin()]

df.groupby(level = 0).apply(trans_function2)

rawDescription: pandas groupby - return min() along with time where min() occurs

description: Pandas groupby - return min() along with time where min() occurs


code: [bs,pt,es,sr]

rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code: your_list.sort(key = lambda x : x.anniversary_score)

rawDescription: sorting a list with objects of a class as its items

description: Sorting a list with objects of a class as its items


rawDescription: Using pip within a python script

description: Using pip within a python script


code: table = [[y for x in t for y in x or ['']] for t in transpose(tuples)]

rawDescription: How can I append whole columns to a table (list of lists) in python?

description: Append whole columns to a table (list of lists) in python


code: object_dict = {id(x): x for x in object_list}

rawDescription: reduce python list of objects to dict object.id -> object

description: Reduce python list of objects to dict object.id -> object


code:
def escape_html(s):
  s = s.replace("&", "&")
  s = s.replace(">",">")
  s = s.replace('<','<')
  s = s.replace('"',""")
  return s

rawDescription: Python for loop with a tuple in it

description: Python for loop with a tuple in it


code:
class MyMeta(type):
    def __new__(mcls, name, bases, members):
        cls = type.__new__(mcls, name, bases, members)
        for m in members.values():
            if isinstance(m, SomeAttribute):
                m.bound_cls = cls
        return cls

rawDescription: Best practice way for linking object attributes to class or object


code:
lastset = [...]  # Populate with the output of the last run
thisset = [...]  # The current results

# Remove rows that aren't in the current result set
for row in lastset - thisset:
    deleteentry(row[0])  # Where row[0] is the unique key for the table

# Add rows that weren't in the last result set
for row in thisset - lastset:
    insertentry(row)

rawDescription: Python comparing two massive sets of data in the MOST efficient method possible


code:
import csv
import string
from bs4 import BeautifulSoup
from mechanize import Browser

mech = Browser()
url = "http://www.basketball-reference.com/players/r/rondora01.html"
RR = mech.open(url)

html = RR.read()
soup = BeautifulSoup(html)
table = soup.find(id="per_game")
player_name = soup.select('div#info_box h1')[0].text.strip()

with open('result.csv', 'w') as f:
    writer = csv.writer(f)

    writer.writerow(['Name'] + [item.text for item in table('th')])

    for row in table('tr')[1:]:
        writer.writerow([player_name] + [filter(lambda x: x in string.printable, item.text)
                                         for item in row('td')])

rawDescription: Scaping a table using mechanize & beautiful when some rows contain additional formatting


rawDescription: Reduce a key-value pair into a key-list pair with Apache Spark


code:
import re
re.sub(r'#big([.,\s]|$)', r'#BIG\1', s)

rawDescription: python: Replace/substitute all whole-word match in a string

description: Python: Replace/substitute all whole-word match in a string


code: re.findall('Message: (.+?)$', s, re.M)

rawDescription: How to solve this using regex?

description: Solve this using regex


code:
df2 = df2.fillna(method='ffill')
df2

rawDescription: Detection of concurrent event appearances - pandas and DataFrame, but possibly pure-python related


code: (c_double * 24).from_buffer(arr)[:]

rawDescription: How do I convert a Python list of lists of lists into a C array by using ctypes?

description: Convert a Python list of lists of lists into a C array by using ctypes


rawDescription: Cartesian Product for two dictionaries python


code: a_deck = Deck()

rawDescription: calling one class's method inside another in python

description: Calling one class's method inside another in python


code:
import subprocess
subprocess.call(['python', 'function.py', 'arg1', 'arg2'])

rawDescription: Pass arguments to python functions using subprocess


code:
def new(X):
    CS = np.sum(X, axis=1, keepdims=True)
    D = np.inner(X,X) / np.maximum(CS, CS.T)
    return D

rawDescription: Cython function with variable sized matrix input


rawDescription: base64 encode a JSON for Mixpanel API pixel tracker

description: Base64 encode a JSON for Mixpanel API pixel tracker


code: headers_written = False

rawDescription: Writing headers in CSV file

description: Writing headers in CSV file


code:
def del_for(mylist):
    for i, j in enumerate(reversed(mylist)):
        if j:
            mylist = mylist[:-1*i]
            break

rawDescription: Remove all trailing zeroes in Python list


code:
l2 = object_from_id( id([]) )
l2.append(8)

rawDescription: Is it possible to access an object via memory address?


code: txt = open(filename)

rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code: matches = list(dict_matcher(dict1, dict2 , 2, 6))

rawDescription: Help using *args in tuple matching Python function


code:
result = dict()
with open('users.txt') as f:
    for line in f:
        key = line[:10]
        if key in numbers:
            value = line + f.next()
            result[key] = value

rawDescription: Python merging data in two files

description: Python merging data in two files


code:
class DictToObject:
    def __init__(self, dic):
        for key, value in dic.items():
            setattr(self, key, value)
    def __eq__(self, other):
        return self.id == other.id
    def __hash__(self):
        return hash(self.__dict__.values())
    def __repr__(self):
        return str(self.__dict__.values())

import networkx

s1 = DictToObject({"name":"sarah", "id":"s"})
s2 = DictToObject({"name":"sarah", "id":"s"})

M = networkx.DiGraph()
M.add_edge(s1, s2)

print( M.nodes() )
print( M.edges() )

rawDescription: set custom node equality comparison in networkx

description: Set custom node equality comparison in networkx


code:
import StringIO
dictFile = StringIO.StringIO()
for item in dictionary.iteritems():
    dictFile.write("%s\t%s\n"%item)
cur.copy_from(dictFile, 'myTable')

rawDescription: Copy_from command to copy values of dictionary in a table


code: multiprocessing.Pool(None, initialize, work).map(worker, work)

rawDescription: multiprocess initializer and pickling

description: Multiprocess initializer and pickling


code:
#note that seconds doesn't give you what you want:
(b-a).seconds

rawDescription: How do I check the difference, in seconds, between two dates?

description: Check the difference, in seconds, between two dates


code: _protocol = HTTP11ClientProtocol

rawDescription: Access socket options for twisted.web.client.Agent


code:
def siamese_method(n):

    assert(n % 2 != 0), 'Square side size should be odd!'
    square = [[0 for x in range(n)] for x in range(n)]
    x = 0
    y = int((n + 1) / 2 - 1)
    square[x][y] = 1

    for i in range(2, n * n + 1):
        x_old = x
        y_old = y

        if x == 0:
            x = n - 1
        else:
            x -= 1

        if y == n - 1:
            y = 0
        else:
            y += 1

        while square[x][y] != 0:
            if x == n - 1:
                x = 0
            else:
                x = x_old + 1
            y = y_old

        square[x][y] = i

    for j in square:
        print(j)

siamese_method(3)

rawDescription: Magic Squares - Siamese Method

description: Magic Squares - Siamese Method


code:
def generalize_attr(self, attr, s_value=None):
    # if the attribute exists in a superclass, generalize there,
    # as imposed by invariant (I)
    for clsdef in self.getmro():
        if attr in clsdef.attrs:
            clsdef._generalize_attr(attr, s_value)
            break
    else:
        self._generalize_attr(attr, s_value)

rawDescription: Pythonic ways to use 'else' in a for loop


code:
df.loc[mask,'time'] = df.time[mask].apply(lambda x: x+pd.offsets.Milli(5))
df

rawDescription: Python pandas change duplicate timestamp to unique


code:
def main_hook(self,f):
    while (self.shouldContinue()):
        #do some preparations
        for v in f(self):
            yield v
        #do some tear down

rawDescription: invoking yield for a generator in another function

description: Invoking yield for a generator in another function


rawDescription: Parsing a string for data sets

description: Parsing a string for data sets


code:
import pandas as pd
file1 = pd.read_csv('Data.csv', index_col='ID')
file2 = pd.read_csv('Price.csv', index_col='ID')
pd.concat([file1,file2], axis=1).to_csv('Output.csv')

rawDescription: Adding another column to a CSV file w/ python


code:
import requests

template_url = "http://item-value10.appspot.com/ParseInv"
ids = ["ftpstorage1-730", "ftpstorage2-730", "ftpstorage3-730"]

for id in ids:
    with requests.Session() as session:
        session.get('http://steam.tools/itemvalue/#/' + id)

        storage, app = id.split("-")
        url = template_url.format(storage=storage, app=app)

        response = session.get(url, params={
            "id": storage,
            "app": app
        }, headers={
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
            "Referer": "http://steam.tools/itemvalue/"
        })

        data = response.json()
        total = sum(float(item["price"]) * int(item["count"]) for item in data["items"])
        print(total)

rawDescription: Can't extract a value out of HTML with lxml


code:
t_foo_base
t_foo
t_foo_base
t_foo

rawDescription: Passing a polymorphic object from C++ to a python function


code:
for i, i_list  in [(a, a_list), (b, b_list)]:
    if i == arg:
        if arg not in i_list:
            do_something(arg)
        break
else:
    do_something_else(arg)

rawDescription: Shorten/DRY this python if statement?

description: Shorten/DRY this python if statement


rawDescription: OrderedDict won't sort within a class

description: OrderedDict won't sort within a class


rawDescription: Adding multi-level attributes to nodes using NetworkX


code:
import wx, pyodbc
class MyFrame(wx.Frame):
    def __init__(self, Parent, Title):
        super(MyFrame, self).__init__(None, title=Title, size=(400,400))
        #creating the panel in which all widgets will be stored/created.
        #self.panel1 = wx.Panel(self, pos=(1,1),size=(382,100),style=wx.RAISED_BORDER)
        #now creating the first Label inside the panel

        a = teamData()
        #rows = a.runQueryEmpList("Mama Badi")
        TmLst = a.runQueryTmList()
        abc=[]
        for r in TmLst:
            abc.append(r.Team_Name)

        #static box for the employee details
        self.myvbfrm = wx.StaticBox(self,-1,label="Employee Detail:-",pos=(1,1),size=(380,98))
        #items for the employee details
        LblName = wx.StaticText(self.myvbfrm,-1, 'Team Name:-',(8,20))
        LblName2 = wx.StaticText(self.myvbfrm,-1, 'Employee Name:-',(8,50))
        # employee combobox
        #EmpList = wx.ComboBox(self.myvbfrm,-1,"",(200,50),(100,50))
        EmpList = EmpComboBox(self.myvbfrm,(200,50),(100,50))

        # team combobox
        TeamList = TeamComboBox(self.myvbfrm,(200,20),(100,50), EmpList)
        TeamList.addItem(abc)
        TeamList.Bind(wx.EVT_TEXT, TeamList.addTeamMember)

        #creating the panel in which all widgets will be stored/created.
        self.panel2 = wx.Panel(self, pos=(10,175),size=(365,150),style=wx.RAISED_BORDER)
        #now creating the first Label inside the panel

        myFont = wx.Font(8,wx.DECORATIVE, wx.NORMAL, wx.BOLD,True)
        myLblFont = wx.Font(12,wx.DECORATIVE, wx.NORMAL, wx.BOLD,True)

        #Lbl.SetFont(myFont)
        #Lbl.SetForegroundColour((0,0,0))
        #Lbl.SetBackgroundColour((204,204,204))
        self.SetBackgroundColour((237,237,237))

        LblName.SetFont(myLblFont)
        LblName2.SetFont(myLblFont)

        # now under this __init__ method i will also initiate the method which
        # will create the MenuBar and the Menu Items.
        self.AddMenu()

    # now i will also have to create a method named as AddMenu so that
    # can be run (which will add the Menu Items.
    def AddMenu(self):
        myMenuBar = wx.MenuBar()
        myFileMenu = wx.Menu()
        myEditMenu = wx.Menu()
        exitBtn = myFileMenu.Append(wx.ID_EXIT, 'Exit App')
        editBtn = myEditMenu.Append(wx.ID_MOVE_FRAME, 'Move App')
        myMenuBar.Append(myFileMenu, '&File')
        myMenuBar.Append(myEditMenu, '&Edit')
        self.SetMenuBar(myMenuBar)

        self.Centre()
        self.Show()

class myComboBox(wx.ComboBox):
    def __init__(self, parent, lstposition, lstsize):
        super(myComboBox, self).__init__(parent, -1, value="", pos=lstposition, size=lstsize)

    def addItem(self, Lst=[]):
        self.Lst = Lst
        for el in self.Lst:
            self.Append(el)

    def addTeamMember(self,extra):
        raise NotImplementedError

########################################################################
class EmpComboBox(myComboBox):
    """"""
    pass

########################################################################
class TeamComboBox(myComboBox):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, lstposition, lstsize, empComboBox=None):
        """Constructor"""
        super(myComboBox, self).__init__(parent, -1, value="", pos=lstposition, size=lstsize)
        self.empComboBox = empComboBox

    def addTeamMember(self,extra):
        self.extra = extra
        a = teamData()
        rows = a.runQueryEmpList(self.GetValue())
        for r in rows:
            self.empComboBox.Append(r.Emp_Name)

class myFrm(wx.StaticBox):
    def __init__(self, parent, lblstring, position, BxSize):
        super(myFrm, self).__init__(parent,-1,label=lblstring,pos=position,size=BxSize)

    def borderColor(self):
        self

app = wx.App()
frame = MyFrame(None, 'Clysdale Activity Tracker')
app.MainLoop()

rawDescription: Adding items to wxpython combobox...?

description: Adding items to wxpython combobox...


code:
if sample_instance.indexed and sample_instance.valid: # 'valid' reads better
    protocol = sample_instance.protocol

rawDescription: In Practice, Should all the objects of a class be made to have same number of attributes?


code:
for a in range(11, 20):
    whatever

rawDescription: Is there a greater than but less than function in python?


code:
for doctor in Doctor.objects.all():
   doctor.name = doctor.name[3:]
   doctor.save()

rawDescription: Remove first 3 characters from a field in the database


code:
current = np.copy(thresh_hi)
prev = np.copy(current)
prev[:] = 0
current = cv2.morphologyEx(current, cv2.MORPH_OPEN, kernel5)
iter_num = 0
max_iter = 1000

rawDescription: Image processing issues with blood vessels