code:
#Define your centre node: you need to pull this out of the graph. Call it b.
# The number changes each time: look for a Clade(branch_length=0.03297)
# Its neighbors have branch lengths .00177, .01972, .00774.
b = G.nodes()[112]

# Recursively paint edges below a certain point, ignoring ones we've already seen
def paintedges(graph, startnode, colour):
    for node in graph.neighbors(startnode):
        if node not in alreadyseen: # alreadyseen is in global scope
            graph[startnode][node]["colour"] = colour
            alreadyseen.add(node)
            paintedges(graph, node, colour)

alreadyseen = set([b])
G[b][G.neighbors(b)[0]]["colour"] = "red"
paintedges(G, G.neighbors(b)[0], "red")
G[b][G.neighbors(b)[1]]["colour"] = "blue"
paintedges(G, G.neighbors(b)[1], "blue")
G[b][G.neighbors(b)[2]]["colour"] = "green"
paintedges(G, G.neighbors(b)[2], "green")

# Now make a list of all the colours, in the order networkx keeps the edges
edgecolours = [G[f][t]["colour"] for f,t in G.edges()]
kwargs["edge_color"] = edgecolours

rawDescription: how to get edges from networkx to color differently

description: Get edges from networkx to color differently


code:
def main():
    states_caps = {'Alabama' : 'Montgomery' ,'Alaska': 'Juneau', 'Arizona': 'Pheonix',  'Arkansas':   'Little Rock', 'California': 'Sacramento','Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu'}

    print('Welcome to the Capitals of States quiz!')
    PlayAgain = "Y"
    correct_answer = 0
    incorrect_answer = 0
    states = list(states_caps.keys())
    for state in states:
        print('\nThe state is:', state)
        capital = input('\nWhat is the capital?  ')
        if capital  == states_caps.get(state):
            print('You are correct!!')
            correct_answer +=1
        else:
            print('\nSorry, that is not correct.')
            print('The correct answer is,' , states_caps.get(state))
            incorrect_answer +=1
        PlayAgain = input("\nPlay again? (Y/N) ").upper()
        if PlayAgain == 'N':
            break

    print('\nYou had', correct_answer, 'correct answers and',  incorrect_answer, 'incorrect answers.')

main()

rawDescription: I can't get the final statement to print when entering 'n'


code: df['col2'] = np.where(df['col1']!=0, 'Play', 'NA')

rawDescription: DataFrame column addition

description: DataFrame column addition


code:
old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
new_dict

rawDescription: removing key value pairs by matching values python

description: Removing key value pairs by matching values python


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

iris = np.recfromcsv('iris.csv')
names = set(iris['class'])

x,y = iris['sepal_length'],  iris['sepal_width']

for name in names:
    cond = iris['class'] == name
    plt.plot(x[cond], y[cond], linestyle='none', marker='o', label=name)

plt.legend(numpoints=1)
plt.show()

rawDescription: Pylab: map labels to colors

description: Pylab: map labels to colors


code: list1, list2, list3 = zip(*sorted(zip(list1, list2, list3)))

rawDescription: A more elegant way to sort 3 lists in Python


code:
a = True
b = True
c = False

args = []

if a: args.append('test1')
if b: args.append('test2')
if c: args.append('test3')

test(*args)

rawDescription: How to assemble a list of arguments for a function call

description: Assemble a list of arguments for a function call


code:
import mpylayer
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.container = QtGui.QWidget(self)
        self.container.setStyleSheet('background: black')
        self.button = QtGui.QPushButton('Open', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.container)
        layout.addWidget(self.button)
        self.mplayer = mpylayer.MPlayerControl(
            'mplayer', ['-wid', str(self.container.winId())])

    def handleButton(self):
        path = QtGui.QFileDialog.getOpenFileName()
        if not path.isEmpty():
            self.mplayer.loadfile(unicode(path))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: Howto embed a video via mpylayer into a QWidget frame?


rawDescription: returning a value to a c# program through python script

description: Returning a value to a c# program through python script


rawDescription: How do I read this list and parse it?

description: Read this list and parse it


code:
from skimage.util.shape import view_as_windows
window_shape = (patch_size, patch_size, patch_size)
patch_array = view_as_windows(A, window_shape)

rawDescription: Iterative patch generation for image segmentation - possible to optimise?


rawDescription: Replacing characters in a regex

description: Replacing characters in a regex


code: "(hello) (yes) (yo diddly)"[1:-1].split(") (")

rawDescription: Python split string by start and end characters


code:
from mymodule import MyCLI
from unittest.mock import create_autospec

class TestMyCLI(unittest.TestCase):
    def setUp(self):
        self.mock_stdin = create_autospec(sys.stdin)
        self.mock_stdout = create_autospec(sys.stdout)

    def create(self, server=None):
        return MyCLI(stdin=self.mock_stdin, stdout=self.mock_stdout)

    def _last_write(self, nr=None):
        """:return: last `n` output lines"""
        if nr is None:
            return self.mock_stdout.write.call_args[0][0]
        return "".join(map(lambda c: c[0][0], self.mock_stdout.write.call_args_list[-nr:]))

    def test_active(self):
        """Tesing `active` command"""
        cli = self.create()
        self.assertFalse(cli.onecmd("active"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=False\n", self._last_write())
        self.mock_stdout.reset_mock()
        self.assertFalse(cli.onecmd("active TRue"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=True\n", self._last_write())
        self.assertFalse(cli.onecmd("active 0"))
        self.assertTrue(self.mock_stdout.flush.called)
        self.assertEqual("Autogain active=False\n", self._last_write())

    def test_exit(self):
        """exit command"""
        cli = self.create()
        self.assertTrue(cli.onecmd("exit"))
        self.assertEqual("Goodbay\n", self._last_write())

rawDescription: Create automated tests for interactive shell based on Python's cmd module


code:
import workerpool
import urllib3

URL_LIST = [] # Fill this from somewhere

NUM_SOCKETS = 3
NUM_WORKERS = 5

# We want a few more workers than sockets so that they have extra
# time to parse things and such.

http = urllib3.PoolManager(maxsize=NUM_SOCKETS)
workers = workerpool.WorkerPool(size=NUM_WORKERS)

class MyJob(workerpool.Job):
    def __init__(self, url):
       self.url = url

    def run(self):
        r = http.request('GET', self.url)
        # ... do parsing stuff here

for url in URL_LIST:
    workers.put(MyJob(url))

# Send shutdown jobs to all threads, and wait until all the jobs have been completed
# (If you don't do this, the script might hang due to a rogue undead thread.)
workers.shutdown()
workers.wait()

rawDescription: Urllib2 & BeautifulSoup : Nice couple but too slow - urllib3 & threads?


code:
from collections import Counter

with open("gibrish.txt", 'r') as file:
    chrDict = Counter(f.read())

rawDescription: Dictionary comprehension and checking for keys during creation


code:
common_id = [i for i in a_id if i in b_id]
common_id
common_a_val = [a_val[a_id.index(i)] for i in common_id]
common_a_val
common_b_val = [b_val[b_id.index(i)] for i in common_id]
common_b_val

rawDescription: cross-identification (overlap) of two lists in Python by common identifier

description: Cross-identification (overlap) of two lists in Python by common identifier


code:
positive = filter(lambda v: some_test(v), values)
negative = filter(lambda v: not some_test(v), values)

rawDescription: Is there a filter() opposite builtin?

description: Is there a filter() opposite builtin


code:
s1 = set([1]) # First set
s2 = set([1,2]) # Second set
s1.difference(s2) # Creates a new set with elements in s1 but not in s2
s2.difference(s1)  # Creates a new set with elements in s2 but not in s1
s1.symmetric_difference(s2) # Returns new set with elements in either s1 or s2 but not both
s2.symmetric_difference(s1)

rawDescription: Set weird behavior (python)

description: Set weird behavior (python)


rawDescription: Tuple unpacking in list construction (python3)


code:
import sys
import time
from subprocess import PIPE, Popen
from threading  import Thread

try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.x

ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        timestamp = time.time( )
        queue.put((timestamp, line))
    out.close()

#-- This is how long you're willing to wait before you
#-- consider your Spynner process to be brain-dead.
MAX_WAIT_TIME = 300.0  #-- we'll wait 5 minutes (300 seconds)

#-- Construct a shared queue that will be used to send messages from
#-- the subprocess I/O polling thread to the watchdog (main) thread.
q = Queue()

#-- Spawn your subprocess...
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)

#-- Create a new thread that runs in the same process as the watchdog.
#-- This thread will poll the output of the subprocess and populate the
#-- shared queue.
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

#-- Now, we'll try to read from the shared queue.
try:
    #-- Queries the shared queue for the next item in the queue,
    #-- waiting for up to MAX_WAIT_TIME before failing with an Empty exception.
    timestamp, line = q.get(True, MAX_WAIT_TIME)
except Empty:
    #-- Ok...the queue is empty and it's been MAX_WAIT_TIME since
    #-- We've pulled anything from the queue.
    p.terminate( )  #-- "terminate with extreme prejudice"
else: # got line
    #-- Got a (timestamp, line_of_text) pair, where the timestamp is the
    #-- system time when the I/O polling thread grabbed the line from
    #-- the subprocess pipe.  This timestamp isn't strictly necessary,
    #-- but might come in handy in debugging the brain-dead Spynner process.
    #-- So now...do something with that line of text!
    doSomething(line)

rawDescription: Monitoring for Program Crash

description: Monitoring for Program Crash


code:
tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
l = {}
for t in tuples:
   l[t] = "something"
sorted(l) # equivalent to sorted(l.keys())
sorted(l.items()) # make a list of (key, value) tuples, and sort by key

rawDescription: Populate a list in python

description: Populate a list in python


code:
dialog_instance = MyDialog()
ok_button = wx.FindWindowById(wx.ID_OK, dialog_instance)

rawDescription: How to get the button object created by CreateButtonSizer (or CreateSeparatedButtonSizer) in wxPython

description: Get the button object created by CreateButtonSizer (or CreateSeparatedButtonSizer) in wxPython


rawDescription: Remove decimal places to certain digits without rounding


code:
import sre_compile

def my_compile(p, flags=0):
    ...

sre_compile.compile = my_compile

rawDescription: Override Python Library File to Circumvent Size Limitation


code:
def wave_sort(array, num_peaks=None, start_ascending=True):
    """Sorts the elements of `array` in a sine or cosine manner.

    :param array: The array to be sorted.
    :param num_peaks: The number of (low and high) peaks in the resultant array
    :param start_ascending: If True the result is sin-like, otherwise cos-like.
    """
    if num_peaks is None:
        num_peaks = len(array) // 6
    sorted_ar = sorted(array)
    subarrays = [sorted_ar[i::num_peaks] for i in range(num_peaks)]
    for i, subarray in enumerate(subarrays, start=int(not start_ascending)):
        if i % 2:
            # subarrays are in ascending order already!
            subarray.reverse()
    return sum(subarrays, [])

rawDescription: Sort array of numbers as 'Bell', 'Curve' and 'Wave'


code:
import argparse

parser = argparse.ArgumentParser(description="Manage the cluster")
parser.add_argument("action", choices=["stop", "start"],
                    help="Action to perform")

args = parser.parse_args()
if args.action == "start":
    start_cluster()
if args.action == "stop":
    stop_cluster()

rawDescription: calling functions from command prompt

description: Calling functions from command prompt


code:
from matplotlib import pyplot as plt
import numpy as np
lag_pacf = np.random.randint(-10,10,30)
log_moving_average_difference = [i for i in range(30)]
#plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle  = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()

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

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

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

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

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

plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle  = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')

yys = [0,-1.96/np.sqrt(len(log_moving_average_difference)),1.96/np.sqrt(len(log_moving_average_difference))]
xx, yy = [],[]
xo,yo = [k for k in range(30)],lag_pacf
d = 20
for i in range(1,len(lag_pacf)):
    for k in yys:
        p1 = np.array([xo[i-1],yo[i-1]],dtype='float')
        p2 = np.array([xo[i],yo[i]],dtype='float')
        k1 = np.array([xo[i-1],k],dtype='float')
        k2 = np.array([xo[i],k],dtype='float')
        if crosses((p2,p1),(k1,k2)):
            seg = line_intersection((p2,p1),(k1,k2))
            if seg is not None:
                xx.append(seg[0])
                yy.append(seg[1]-d)
                plt.scatter(seg[0],seg[1],c='red')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()

rawDescription: Python - find where the plot crosses the axhline on python plot


code:
import logging

class MultiFileHandler(logging.FileHandler):

    def __init__(self, filename, mode, encoding=None, delay=0):
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)

    def emit(self, record):
        if self.should_change_file(record):
            self.change_file(record.file_id)
        logging.FileHandler.emit(self, record)

    def should_change_file(self, record):
        if not hasattr(record, 'file_id') or record.file_id == self.baseFilename:
             return False
        return True

    def change_file(self, file_id):
        self.stream.close()

        self.baseFilename = file_id
        self.stream = self._open()

if __name__ == '__main__':

    logger = logging.getLogger('request_logger')
    logger.setLevel(logging.DEBUG)
    handler = MultiFileHandler(filename='out.log', mode='a')
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)

    # Log some messages to the original file
    logger.debug('debug message')
    logger.info('info message')

    # Log some messages to a different file
    logger.debug('debug message',       extra={'file_id':'changed.log'})
    logger.info('info message',         extra={'file_id':'changed.log'})
    logger.warn('warn message',         extra={'file_id':'changed.log'})
    logger.error('error message',       extra={'file_id':'changed.log'})
    logger.critical('critical message', extra={'file_id':'changed.log'})

rawDescription: Is it possible to write many different log files using a single logger?


code:
import time
target_time = time.clock() + 0.025
while time.clock() < target_time:
    pass

rawDescription: Sleep for exact time in python

description: Sleep for exact time in python


code:
import pandas as pd

# get data
from urllib import urlopen
page = urlopen('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data')
df = pd.read_csv(page, header=None, index_col=None)
df.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education-num',
    'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain',
    'capital-loss', 'hours-per-week', 'native-country', 'income']

# put ages in categories and add as columns to DataFrame
age_bins = [0, 25, 45, 65, 150]
age_labels = ["Young", "Middle-aged", "Senior", "Old"]
df['age_cat'] = pd.cut(df['age'], age_bins, labels=age_labels,
    right=True, include_lowest=True)

rawDescription: PYTHON: Appending converted continuous attributes (converted to categorical) to the original dataset using pandas library


code:
from multiprocessing import Process, Queue

def trace_pdf(a,b,c,d):
   x = np.linspace(0,100,a)
   fig2 = plt.figure()
   ax2 = fig2.add_subplot(111)
   ax2.plot(b,c,'b', label='BA',linewidth=3.5)
   ax2.set_title('a pdf like no other')
   fig2.savefig('file.pdf', format='pdf')
   plt.close()

trace_pdf = Process(target=trace_pdf, args=(a,b,c,d))
trace_pdf.start()

rawDescription: automated creation of pdf with Matplotlib blocks the code execution

description: Automated creation of pdf with Matplotlib blocks the code execution


code:
query = """
    SELECT *
    FROM distributor_distributor d
        INNER JOIN user_user_profile up ON up.id = %(user_id)s
        INNER JOIN user_user_distributors_of_user udu ON udu.user_profile_id = %(user_id)s
            AND udu.distributor_id = d.id
    WHERE d.name || d.surname = %(query)s;
"""

dist_list = Distributor.objects.raw(query, {'user_id': request.user.pk, 'query': 'hello world'})

rawDescription: How to use property method as a field in query?

description: Use property method as a field in query


code:
t
[j-i for i, j in zip(t[:-1], t[1:])]  # or use itertools.izip in py2k

rawDescription: Python - Differences between elements of a list


code:
import datetime
def millisecond(dt):
    return dt.microsecond/1000

rawDescription: How can I extend Python's datetime.datetime with my own methods?

description: Extend Python's datetime.datetime with my own methods


code:
import tkinter

# function that is called when you select a certain radio button
def selected():
    print(var.get())

root = tkinter.Tk()

var = tkinter.StringVar() #used to get the 'value' property of a tkinter.Radiobutton

# Note that I added a command to each radio button and a different 'value'
# When you press a radio button, its corresponding 'command' is called.
# In this case, I am linking both radio buttons to the same command: 'selected'

rb1 = tkinter.Radiobutton(text='Radio Button 1', variable=var,
                          value="Radio 1", command=selected)
rb1.pack()
rb2 = tkinter.Radiobutton(text='Radio Button 2', variable=var,
                          value="Radio 2", command=selected)
rb2.pack()

root.mainloop()

rawDescription: Determine which Radiobutton has been selected


code:
for item in tree.iter():
    texts = []
    print(item)
    if item.tag == ROW:
        texts.append('\n')
    elif item.tag == COL:
        texts.append('\t\t')
    elif item.tag == PARA:
        for node in item.iter(TEXT):
            if node.text:
                texts.append(node.text)
    if texts:
        paragraphs.append(''.join(texts))

rawDescription: Python: extract text from docx to txt via parsing word/document.xml


code:
#get the row with maximum number of columns
maxrowlen = 0
maxrowkey = ""
for timesid in d.keys():
    if len(timesid.keys()) > maxrowlen:
         maxrowlen = len(timesid.keys())
         maxrowkey = timesid
maxrowcols = sorted(d[maxrowkey].keys())

# prepare the writing
cell_format = "%10r"    # or whatever suits your data

# create the output string
lines = []
for timesid in d.keys(): # go through all times
    line = ""
    for col in maxrowcols:  # go through the standard columns
         colstr = ""
         if col in d[timesid].keys():   # create an entry for each standard column
             colstr += cell_format % d[timesid][col]  # either from actual data
         else:
             colstr += cell_format % ""                      # or blanks
         line += colstr
    lines.append(line)

text = "\n".join(lines)

rawDescription: need to put a nested Dict into a text file

description: Need to put a nested Dict into a text file


code:
import sys
from PyQt4 import QtGui
import matplotlib
import matplotlib.figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar

class PrettyWidget(QtGui.QWidget):
    def __init__(self):
        super(PrettyWidget, self).__init__()
        self.initUI()

    def initUI(self):

        self.setGeometry(100, 100, 800, 600)
        self.center()
        self.setWindowTitle('S Plot')

        grid = QtGui.QGridLayout()
        self.setLayout(grid)

        btn1 = QtGui.QPushButton('Plot 1 ', self)
        btn1.resize(btn1.sizeHint())
        btn1.clicked.connect(self.plot1)
        grid.addWidget(btn1, 5, 0)

        btn2 = QtGui.QPushButton('Plot 2 ', self)
        btn2.resize(btn2.sizeHint())
        btn2.clicked.connect(self.plot2)
        grid.addWidget(btn2, 5, 1)

        self.figure = matplotlib.figure.Figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        grid.addWidget(self.canvas, 3, 0, 1, 2)
        # grid.addWidget(self.toolbar, ??)

        self.show()

    def plot1(self):
        self.figure.clf()
        ax1 = self.figure.add_subplot(211)
        x1 = [i for i in range(100)]
        y1 = [i**0.5 for i in x1]
        ax1.plot(x1, y1, 'b.-')

        ax2 = self.figure.add_subplot(212)
        x2 = [i for i in range(100)]
        y2 = [i for i in x2]
        ax2.plot(x2, y2, 'b.-')
        self.canvas.draw_idle()

    def plot2(self):
        self.figure.clf()
        ax3 = self.figure.add_subplot(111)
        x = [i for i in range(100)]
        y = [i**0.5 for i in x]
        ax3.plot(x, y, 'r.-')
        ax3.set_title('Square Root Plot')
        self.canvas.draw_idle()

    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

app = QtGui.QApplication(sys.argv)
app.aboutToQuit.connect(app.deleteLater)
GUI = PrettyWidget()
sys.exit(app.exec_())

rawDescription: Embed Matplotlib in PyQt with multiple plot


code:
from itertools import product
abGenerator = product(range(minA, maxA, stepA), range(minB, maxB, stepB))
abArray = (i for i in abGenerator if i[0] < i[1])

rawDescription: What is the best way to obtain every possible combination within multiple ranges in Python?


code:
bank = {
    "88386180860608512" : {      # This is a unique id number
        "balance" : 100,
        "name" : "Aehnon"
    },
    "88469127777243136" : {     # This is a unique id number
        "balance" : 100,
        "name" : "Balanceofevil"
    },
    "89741285950246912" : {     # This is a unique id number
        "balance" : 3310,
        "name" : "Sharky"
    }
}

names = ["Sharky", "Aehnon"]

for v in bank.values():
    if v["name"] in names:
        v['balance'] += 50

print(bank)

rawDescription: Update a value if a seperate key value pair is True


code:
def csv_process(filename, callback, delay=1):
    class waiter:     # wrapper around a file object to wait for new lines on EOF
        def __init__(self, fd, delay=1):
            self.fd = fd
            self.delay = delay
        def __iter__(self):
            return self
        def next(self):  # try to read a line of wait delay seconds
            while True:
                line = fd.readline()
                if line:
                    return line
                time.sleep(self.delay)
        def __next__(self):  # ensure compatibility with Python3.x
            return self.next()
    with open(filename, "rb") as fd:
        rows = csv.reader(waiter(fd, delay), delimiter=',')
        for row in rows:
            callback(row)

rawDescription: Parsing a data feed in python

description: Parsing a data feed in python


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

img = mpimg.imread('stinkbug.png')
circle = plt.Circle((0, 0), radius=100, fc='y')

fig, ax = plt.subplots()
ax.imshow(img)
ax.add_artist(circle)
fig.show()

rawDescription: Is it possible to control matplotlib in predictable way?


code:
def create_user(self, username, email=None, password=None):
    """
    Creates and saves a User with the given username, email and password.
    """
    now = timezone.now()
    if not username:
        raise ValueError('The given username must be set')
    email = UserManager.normalize_email(email)
    user = self.model(username=username, email=email,
                      is_staff=False, is_active=True, is_superuser=False,
                      last_login=now, date_joined=now)

    user.set_password(password)
    user.save(using=self._db)
    return user

rawDescription: Creating django users using two different ways


code:
x = "qwertyui"
chunks, chunk_size = len(x), len(x)/4
[ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]

rawDescription: Split string into strings by length?

description: Split string into strings by length


code:
from selenium import webdriver
driver = webdriver.Firefox()
url = 'urlyouwanttogoto.com'
driver.get(url)
boxesyouwanttocheck = driver.find_elements_by_class_name('whatevertheclassnameis')
for i in boxesyouwanttocheck:
    i.click()

rawDescription: Looking for a Python Web navigation library


code:
# import appropriate module as mod depending on settings, environment
# using importlib.import_module, or __import__

__all__ = []

_instance = mod.WordProc()
for attr in dir(_instance):
    if not attr.startswith('_') and callable(getattr(_instance, attr)):
        locals()[attr] = getattr(_instance, attr)

rawDescription: Python - can a class act like a module?

description: Python - can a class act like a module


code: array ^= 255

rawDescription: Fast value swapping in numpy array

description: Fast value swapping in numpy array


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

theta, r = np.mgrid[0:2*np.pi:20j, 0.2:1:10j]
z = np.random.random(theta.size).reshape(theta.shape)

fig, ax = plt.subplots(ncols=1, subplot_kw=dict(projection='polar'))

ax.pcolormesh(theta, r, z)
ax.set_yticklabels([])
ax.set_ylim([0, 1])

plt.show()

rawDescription: Bulls eye plot of image

description: Bulls eye plot of image


code:
x = np.random.uniform(0,9,size = 10)
y = np.random.uniform(0,9, size = 10)
data = np.c_[x, y]
print(data)

rawDescription: how can I get return the data in nested for python

description: Get return the data in nested for python


code:
if __name__ == "__main__":
    app = wx.App(redirect=False) #or 0
    app.MainLoop()

rawDescription: How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?

description: Disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin


code:
@click.group(help="cmd group")
@click.option('--user', default='*')
@click.pass_context
def main(ctx, user):
    ctx.obj = dict({'user': user})
    pass

@click.command(name='foo')
@click.pass_context
def foo(ctx):
    click.secho(ctx.obj['user'], fg='green')

@click.command(name='bar')
@click.pass_context
def bar(ctx):
    click.secho(ctx.obj['user'], fg='green')

main.add_command(foo)
main.add_command(bar)

rawDescription: How to use same options for cmd in the same group by using python-click

description: Use same options for cmd in the same group by using python-click


rawDescription: Explanation of str.partition() in python


code:
import re

def string_fix(filename, dict):
    filename = filename.replace('.', ' ')
    for key, val in dict.items():
        filename = re.sub(key, val, filename, flags=re.IGNORECASE)
    return filename

dict = {
         r'Legal[\s\-_]?Studies' : 'Legal Studies',
         r'Media[\s\-_]?Studies' : 'Media Studies',
         r'dts' : 'DTS',
         r'hd[\s\-_]?dvd': 'HD DVD',
         r'blu[\s\-_]?ray' : 'Blu-ray',
         r'unix' : 'UNIX',
         r'aac[\s\-_]?2[\.]?0' : 'AAC2.0',
         r'xvid' : 'XviD',
         r'computer[\s\-_]?science' : 'Computer Science'
     }

string_1 = 'legal.studies.131.race.relations.in.the.United.States.'
string_2 = 'mediastudies the triumph of bluray over hddvd'
string_3 = 'computer Science Microsoft vs unix'
string_4 = 'Perception - metamers dts'
string_5 = 'Perception - Cue Integration - flashing dot example aac20 xvid'

print(string_fix(string_1, dict))
print(string_fix(string_2, dict))
print(string_fix(string_3, dict))
print(string_fix(string_4, dict))
print(string_fix(string_5, dict))

rawDescription: bvCase Insensitive Regex Replacement From Dictionary

description: BvCase Insensitive Regex Replacement From Dictionary


code:
import urlparse
parsed = urlparse.urlparse('http://stackoverflow.com/questions/32809595')
parsed.path

rawDescription: Django : extract a path from a full URL

description: Django : extract a path from a full URL


code:
class NoValue:
    pass

if someValue is NoValue:
    doSomething()

rawDescription: How can you define a variable that will never be matched in Python?

description: Define a variable that will never be matched in Python


code:
number2 = random.randint(2,5)
answer4 = random.randint(20//number2, 30//number2)
number1 = number2*answer4

rawDescription: How to divide without remainders on Python

description: Divide without remainders on Python


code:
def get_donors(row):
    d = donors.apply(lambda x: fuzz.ratio(x['name'], row['name']) * 2 if row['Email'] == x['Email'] else 1, axis=1)
    d = d[d >= 75]
    if len(d) == 0:
        v = ['']*3
    else:
        v = donors.ix[d.idxmax(), ['name','Email','Date']].values
    return pd.Series(v, index=['donor name', 'donor email', 'donor date'])

pd.concat((fundraisers, fundraisers.apply(get_donors, axis=1)), axis=1)

rawDescription: Python Pandas fuzzy merge/match with duplicates


rawDescription: How to convert an int to a hex string?

description: Convert an int to a hex string


rawDescription: Error with lxml syntax to parse table elements while validating column contents


code:
numbers = "51-52"
part = [int(x) for x in numbers.split("-")]
print(part)

rawDescription: how to split string and convert to integer

description: Split string and convert to integer


code:
(rng-pd.to_datetime(s.index)).format()
(rng-pd.to_datetime(s.index)).format(formatter=lambda x: x.strftime('%m-%d-%Y'))

rawDescription: Pandas Series: get all dates missing from a datetime slice or range


rawDescription: Setting up Django on an internal server (os.environ() not working as expected?)


code:
class Repo(Base):
    __tablename__ = "repos"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text, unique=True)
    parent_id = db.Column(Integer,db.ForeignKey('repos.id'))
    forks = relationship("Repo",
                backref=backref('parent', remote_side=[id])
            )

rawDescription: One to Many Relationship on same table in SQLAlchemy


code:
# your_app.models
from django.contrib.auth.models import User

class AuthorUser(User):
    class Meta:
        proxy = True

    def __unicode__(self):
        return '%s %s' % (self.first_name, self.last_name)

class YourModel(models.Model):
    author = models.ForeignKey(AuthorUser)

rawDescription: Author foreignkey field automatically chosen in admin space of blog app


rawDescription: Django: How to disable ordering in model


code:
ls = [1,2,3]
ls.insert(0, "new")
ls

rawDescription: Insert at first position of a list in Python


code:
class Point(object):
    # __init__ and __repr__ methods
    # ...
    def disttopoint(self, other):
        # do something using self and other to calculate distance to point
        # result = distance to point
        return result

    def isnear(self, other):
        if (self.disttopoint(other) < epsilon):
            return True
        return False

rawDescription: Class method troubles - Python

description: Class method troubles - Python


code:
# Results container
results = {}

# Collect the data
for item in data:
    # key here is just for later,
    # you could use anything unique to the entry
    # (username for example)
    key = "{0}.{1}".format(item.get('user_name'), item.get('question'))
    if key in results:
        results[key] += item.get('value', 0)
    else:
        results[key] = item.get('value', 0)

# Prints the results as you would like.
for key, count in results.iteritems():
   name, question = key.split('.')
   print [name, question, count]

rawDescription: Python: Best way to keep track of particular values within dictionary


code:
import time, os
os.environ['TZ'] = "Asia/Kolkata"   # timezone you want to display graphs in
time.tzset()

rawDescription: python-rrdtool, how to create graphs in UTC time zone

description: Python-rrdtool, how to create graphs in UTC time zone


code:
prev_content = ""
while True:
  content = ContentFunc()
  if content == prev_content:
      print("Same as last time")
  prev_content = content

rawDescription: How to understand a variable was repeated in python

description: Understand a variable was repeated in python


code:
import argparse

training_pages_list_file = ''
html_page_dir = ''
clf_file_str = ''
user_idf_param = "i_param_used"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Classify some CraigsList Pages')
    parser.add_argument('csv_file', action='store')
    parser.add_argument('file_dir', action='store')
    parser.add_argument('clf_file', action='store')
    parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False)

    args = parser.parse_args((...))

    if args.i_param_used:
        ...

rawDescription: Python argparse boolean issue

description: Python argparse boolean issue


code:
Config = ConfigParser.RawConfigParser()

cfg = open('abcd.txt', 'r')
Config.readfp(cfg)
cfg.close()

cfg = open('abcd.txt', 'w')
Config.remove_option('download', 'repository')
Config.set('download','repository', 'Some URL')
Config.write(cfg)
cfg.close()

rawDescription: Access variables set in setup.cfg

description: Access variables set in setup.cfg


code:
a
np.nonzero(a == a.max())[0]
a[_]

rawDescription: Finding the positions of the max element in a numpy array if there are more than one


code:
data = ['ABC', 'EFG', 'IJK', 'MNO']
zip(*data)

rawDescription: Zip together each element of one list

description: Zip together each element of one list


code:
def textinput(self, title, prompt):
    """Pop up a dialog window for input of a string.

    Arguments: title is the title of the dialog window,
    prompt is a text mostly describing what information to input.

    Return the string input
    If the dialog is canceled, return None.

    Example (for a TurtleScreen instance named screen):
    >>> screen.textinput("NIM", "Name of first player:")

    """
    return simpledialog.askstring(title, prompt)

rawDescription: Python3 turtle how to wait until keypress


code:
def doSomething (x):
    time.sleep(.01)
    for num in range(3):
        print (num, x)

rawDescription: Can't call multiple functions in the same time with multiprocessing


code:
df.gdp = df.gdp.shift(-1)
df
df[:-1]

rawDescription: python: shift column in pandas dataframe up by one

description: Python: shift column in pandas dataframe up by one


code:
import urlparse
url = "http://somesite.com/"
urlparse.urlparse(url).netloc

rawDescription: Python simple regex: get url name without http:// and /


rawDescription: String Manipulation of All Elements of an Array in Python


code:
df["unq"] = df.groupby("Cnt").cumcount() + 1
df

rawDescription: Add column with unique identifiers based on values from other columns in pandas


code:
def list_hook(pairs):
    result = {}
    for name, value in pairs:
        if name == 'id':
            result.setdefault(name, []).append(value)
        else:
            result[name] = value
    return result

data = response.json(object_pairs_hook = list_hook)

for i in range(3):
    print(i, data['apps'][0]['id'][i])

rawDescription: Parsing Python JSON with multiple same strings with different values


code:
def fixup(cls):
    placeholder = '@' + cls.__name__
    for k,v in vars(cls).items():
        if v == placeholder:
            setattr(cls, k, cls)
    return cls

@fixup
class Foo(object):
    bar = '@Foo'

print('Foo.bar: {!r}'.format(Foo.bar))  # -> Foo.bar: <class '__main__.Foo'>

rawDescription: What is the best way to reference class name in class attribute?


code:
# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

rawDescription: Python display text w/ font & color?

description: Python display text w/ font & color


code:
from Tkinter import * # I do not like wild imports, but everyone seems to do it

root = Tk()

scrollbar = Scrollbar(root, orient=VERTICAL) # yes, do this first...
listb = Listbox(root, yscrollcommand=scrollbar.set) # ...because you need it here
scrollbar.config(command=listb.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listb.pack(fill=BOTH, expand=YES) # convince the listbox to resize

item_list = range(400)

for item in item_list:
    listb.insert(item)

exponent = 0
def update_list():
    global exponent
    vw = listb.yview() # Save the current position(percentage) of the top left corner
    for i in item_list:
        listb.delete(i)
        listb.insert(i, i * 10**exponent)
    listb.yview_moveto(vw[0]) # go back to that position
    exponent += 1
    root.after(1000, update_list)

root.after(1000, update_list)
root.mainloop()

rawDescription: Python Tkinter: Update scrolled Listbox - wandering scroll position


code:
import numpy
import pandas as pd
my_array = numpy.array([[1,2],[3,4]])
pd.DataFrame(my_array, columns=list('cd'), index=list('ab'))

rawDescription: Adding names to numpy arrays

description: Adding names to numpy arrays


code:
import re
def is_valid_hostname(hostname):
    if len(hostname) > 255:
        return False
    if hostname[-1] == ".":
        hostname = hostname[:-1] # strip exactly one dot from the right, if present
    allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    return all(allowed.match(x) for x in hostname.split("."))

rawDescription: Validate a hostname string

description: Validate a hostname string


code:
HtmlFile = open(fname, 'r', encoding='utf-8')
source_code = HtmlFile.read()

rawDescription: Reading an HTML File from Folder in Python


code:
from collections import Counter
def is_consistent(spec_a, spec_b):
    c1 = Counter(spec_a)
    c2 = Counter(spec_b)
    result = c1 - c2
    return all(result[key] == 0 for key in c1)

rawDescription: Fast way to check two lists for consistency


code:
for i in xrange(10):
    args = ['python', 'testrun.py', 'HWStatus']
    p = subprocess.Popen(args)
    while p.poll() != 0:
        time.sleep(amount_of_time)

rawDescription: Run a test multiple times from another test


code:
class Button(QPushButton):

    def __init__(self, parent=None):
        super(Button, self).__init__(parent)
        # other initializations...

    def enterEvent(self, QEvent):
        # here the code for mouse hover
        pass

    def leaveEvent(self, QEvent):
        # here the code for mouse leave
        pass

rawDescription: How to Catch Hover and Mouse Leave Signal In PyQt5


code:
class TestWeakMethod(unittest.TestCase):
    def test_call(self):
        class C():
            def c(self,*args,**kwargs):
                return (args,kwargs)
        c=C()
        wc = WeakBoundMethod(c.c)
        self.assertEqual(((1,2,3),{"a":11,"b":"33"}), wc(1,2,3,a=11,b="33"))

    def test_just_bound_method(self):
        c=object()
        self.assertRaises(Exception, WeakBoundMethod, c)
        self.assertRaises(Exception, WeakBoundMethod, object)
        def f():
            pass
        self.assertRaises(Exception, WeakBoundMethod, f)

    def test_is_really_weak(self):
        class C():
            DEAD=False
            def c(self,*args,**kwargs):
                return (args,kwargs)
            def __del__(self):
                C.DEAD = True
        c=C()
        wc = WeakBoundMethod(c.c)
        del c

        self.assertTrue(C.DEAD)
        self.assertRaises(Exception, wc)

rawDescription: How to mock bound method for introspection

description: Mock bound method for introspection


code:
import numpy as np
from matplotlib.backends.backend_agg import RendererAgg
w, h = 256, 256
r = RendererAgg(w, h, 72)
arr = np.frombuffer(r.buffer_rgba(), np.uint8)
arr.shape = r.height, r.width, -1
t = np.linspace(0, 2*np.pi, 100)
x = np.sin(2*t) * w*0.45 + w*0.5
y = np.cos(3*t) * h*0.45 + h*0.5

from matplotlib.lines import Line2D
line = Line2D(x, y, linewidth=5, color=(1.0, 0.0, 0.0), alpha=0.3)
line.draw(r)
pl.imsave("test.png", arr)

rawDescription: efficient calculation of distance to spline curve for all pixels on an image

description: Efficient calculation of distance to spline curve for all pixels on an image


code:
from ast import literal_eval

if line.startswith(self.kind):
    line = line[len(self.kind) + 1:]
    return literal_eval(line)

rawDescription: ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from file


code:
my_list = [ True, False, True ]
all(my_list)
False
any(my_list)
True

rawDescription: How to apply AND to all elements of a list?

description: Apply AND to all elements of a list


code: self.constituents = constituents[:]

rawDescription: Python Classes not acting distinct?

description: Python Classes not acting distinct


code:
null_ptr = POINTER(c_float)()
pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))
null_ptr[0]
null_ptr[5] # etc

rawDescription: Python double pointer

description: Python double pointer


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

t = np.linspace(0, 1, 100)
fig1, axes1 = plt.subplots(3, 3)
fig2, axes2 = plt.subplots(3, 3)

blue, red = "#1E90FF", "#FF6347"
for i in range(3):
    for j in range(3):
        axes1[i, j].plot(t, np.sin((t * np.random.random() * 10)), blue)
        axes2[i, j].plot(t, np.cos((t * np.random.random() * 10)), red)

fig1.tight_layout()
fig2.tight_layout()

rawDescription: Multiple `subplot2grid` in a for loop

description: Multiple `subplot2grid` in a for loop


code:
from collections import defaultdict
myHash = defaultdict(defaultdict) # dictionary
for row in read:
    myHash[row[0]][row[1]] = row[11]

rawDescription: how to parse a file and transfer a set of two pairwise data into a 2D array

description: Parse a file and transfer a set of two pairwise data into a 2D array


code:
import zipfile,os.path
def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        for member in zf.infolist():
            # Path traversal defense copied from
            # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
            words = member.filename.split('/')
            path = dest_dir
            for word in words[:-1]:
                drive, word = os.path.splitdrive(word)
                head, word = os.path.split(word)
                if word in (os.curdir, os.pardir, ''): continue
                path = os.path.join(path, word)
            zf.extract(member, path)

rawDescription: How to unzip file in Python on all OSes?

description: Unzip file in Python on all OSes


code:
keywords=[]
solutions=[]
for i_raw in file:
    i = i_raw.strip() # <-- removes extraneous spaces from start/end of string
    keywords.append((i.split(","))[0])
    solutions.append(((i.split(","))[1]))

rawDescription: Importing strings from a file, into a list, using python


code:
from klepto.archives import *
arch = file_archive('foo.txt')
arch['a'] = 1
arch['b'] = 2
# look at the "in-memory" copy
arch
# look at the "on-disk" copy
arch.archive
# dump from memory to the file
arch.dump()
arch.archive
arch
# delete from the in-memory cache
arch.pop('a')
# delete from the on-disk cache
arch.archive.pop('a')
arch
arch.archive

rawDescription: Python Saving and Editing with Klepto

description: Python Saving and Editing with Klepto


code:
import numpy as np

features = [] # list of lists of the feature vairables.
classes  = [] # list of the target variables
for line in f:
    line = line.strip().split() # will split the line into pieces on any white spaces
    features.append(line[1:-1]) # or whatever indices your features are in
    classes.append(line[-1])    # or whatever index your target variable is in
classes  = np.array(classes)
features = np.array(features,dtype=np.float)

rawDescription: searching k nearest neighbors in numpy

description: Searching k nearest neighbors in numpy


rawDescription: Extra Icon on NavigationToolbar2QTAgg

description: Extra Icon on NavigationToolbar2QTAgg


rawDescription: Can you append a string and a number as a single entry to a list in python?

description: Append a string and a number as a single entry to a list in python


code:
item = defaultvalue
for item in my_iter:
    pass

rawDescription: Cleanest way to get last item from Python iterator


code:
s1 = "/xubuntu/daily/current/lucid-alternate-i386.iso"
s2 = "/xubuntu/daily/current/lucid-alternate-amd64.iso"

pattern = re.compile(r'^.+-(.+)\..+$')

m = pattern.match(s1)
m.group(1)
'i386'

m = pattern.match(s2)
m.group(1)
'amd64'

rawDescription: Python matching some characters into a string


code:
j = df_train.IsAlone.astype(bool) & df_train.Age.isnull()
i = df_train.IsAlone.astype(bool) & ~df_train.Age.isnull()
df_train.loc[j, 'Age'] = df_train.loc[i, 'Age'].mean()

rawDescription: Replacing missing data in pandas.DataFrame not working


code:
import wx
import wx.richtext
import threading
import time

EVT_ID_VALUE = wx.NewId()

class DataEvent(wx.PyEvent):
  def __init__(self, data):
    wx.PyEvent.__init__(self)
    self.SetEventType(EVT_ID_VALUE)
    self.data=data

class Frame3(wx.Frame):
  def __init__(self, parent, title):
    self.counter = 0
    self.worker = None

    wx.Frame.__init__(
      self, name='',
      parent=parent,
      pos=wx.Point(579, 234),
      size=wx.Size(414, 492),
      style=wx.DEFAULT_FRAME_STYLE, title='Frame3'
    )
    self.panel1 = wx.Panel(
      name='panel1',
      parent=self,
      pos=wx.Point(0, 0),
      size=wx.Size(406, 458),
      style=wx.TAB_TRAVERSAL
    )
    self.richTextCtrl1 = wx.richtext.RichTextCtrl(
      parent=self.panel1,
      pos=wx.Point(96, 96),
      size=wx.Size(200, 100),
      style=wx.richtext.RE_MULTILINE,
      value=u''
    )
    self.richTextCtrl1.SetLabel(u'richText')
    self.richTextCtrl1.SetScrollbars(20,20,50,50)
    self.button2 = wx.Button(
      label=u'STOP',
      name='button2',
      parent=self.panel1,
      pos=wx.Point(256, 280),
      size=wx.Size(75, 23),
      style=0
    )
    self.button2.Bind(
      wx.EVT_BUTTON,
      self.OnStop
    )
    self.button1 = wx.Button(
      label=u'START',
      name='button1',
      parent=self.panel1,
      pos=wx.Point(88, 280),
      size=wx.Size(75, 23),
      style=0
    )
    self.button1.Bind(
      wx.EVT_BUTTON,
      self.OnStart
    )
    self.Connect(-1, -1, EVT_ID_VALUE, self.OnValue )

  def OnValue(self, event):
    self.richTextCtrl1.AppendText("%d\n"%event.data)

  def OnStart(self, event):  #START BUTTON
    self.richTextCtrl1.AppendText("START\n")
    if not self.worker:
      self.worker = WorkerThread(self)
      self.worker.start()

  def OnStop(self, event):  #STOP BUTTON
    self.richTextCtrl1.AppendText("STOP\n")
    if self.worker:
      self.worker.stop()

class WorkerThread(threading.Thread):
  def __init__(self, notify_window):
    threading.Thread.__init__(self)
    self.counter = 0
    self._notify_window = notify_window
    self.abort = False

  def run(self):
    while not self.abort:
      self.counter += 1
      wx.PostEvent(self._notify_window, DataEvent(self.counter))
      time.sleep(1)

  def stop(self):
      self.abort = True

if __name__ == '__main__':
    app = wx.App()
    frame = Frame3(None, "My Hello App")
    frame.Show(True)
    app.MainLoop()

rawDescription: How to run code only when i click on a button..python/wxpython/boa constructor

description: Run code only when i click on a button..python/wxpython/boa constructor


code:
class MungedData(object):

    def __init__(self, foo):
        self.datadex = {f:42 for f in foo}

    def myfx(self, x):
        return self.datadex[x] + 1

md = MungedData(somefoo)
print(md.myfx(arg1))
print(md.myfx(arg2))

rawDescription: Pythonic way of generating data outside of a method


code:
items = ['foo','bar','item','item2','item3']
for elm in items:
    setattr(self.ui, elm, False)

rawDescription: Python code refactoring question. Simplification


code:
import sys
sys.path.append("path-here")

rawDescription: How do I set the search path for a Python import?

description: Set the search path for a Python import


code:
while True:
    com = raw_input('Command:').split()
    if len(com) == 0:
        break
    elif com[0] == 'i':
        bike_name =  command[1] + ' ' + command[2]
        return get_product_id(products, bike_name)

rawDescription: Python, continuously prompting for user input


code:
import logging
logger = logging.getLogger(__name__)

def restart_service(node_name):
    print('='*30 + '  Starting to work on ' + node_name + '  ' + '='*30 + '\n')
    logging.info('Connecting to %s in order to restart %s...', node_name, service_name)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    ssh.connect(node_name)
    channel = ssh.get_transport().open_session()
    channel.exec_command(command)
    while True:
        if channel.exit_status_ready():
            break
        rl, wl, xl = select.select([channel], [], [], 0.0)
        if len(rl) > 0:
            # Log output
            logger.info(channel.recv(1024))
    ssh.get_transport().close()
    ssh.close()

rawDescription: Python Paramiko log output of commands to a file


code:
def func(number):
    parser = HTMLParser()
    for x in range(number):
        fromstring(DATA, parser=parser)

rawDescription: Why does multithreading do not speed up parsing HTML with lxml?


code:
import os
def getmount(path):
    path = os.path.realpath(os.path.abspath(path))
    while path != os.path.sep:
        if os.path.ismount(path):
            return path
        path = os.path.abspath(os.path.join(path, os.pardir))
    return path

rawDescription: In Python, how can I get the file system of a given file path


code:
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))

rawDescription: make a global condition break

description: Make a global condition break


code:
lw = self.tabWidget.widget(0) # get the 0th widget
lw.addItem(...)

rawDescription: Pyside getting a widget inside a QtabWidget


rawDescription: How to generate a specific date range in YearMonthDay format?

description: Generate a specific date range in YearMonthDay format


code:
args = {}

args['name__contains'] = cd['name']

if cd['subject'] is not None:
    args['subject'] = cd['subject']
if cd['school'] != '':
    args['school'] = cd['school']
if cd['price']:
    args['price'] = cd['price']

files = File.objects.filter(**args)
return render(request, 'search.html', {'files': files, 'request': request})

rawDescription: how to avoid too many if - else blocks in python

description: Avoid too many if - else blocks in python


code:
@pytest.fixture()
def fixture1():
    return 'fixture1'

@pytest.fixture()
def fixture2(request):
    if 'fixture1' in request._funcargs:
        # fixture1 was requested earlier
        # but most likely you don't need that check because getfuncargvalue always works
        fixture1_instance = request.getfuncargvalue('fixture1')
    return do_stuff(fixture1_instance)

def test_whatever(fixture1, fixture2):
    result = do_some_stuff(fixture1)
    assert result.supermethod(fixture2)

rawDescription: Is it possible to retrieve other requested fixtures from fixture request?


code:
import urllib2
content = urllib2.urlopen(some_url)

rawDescription: Python - How to Send a Command to a Web Server


code:
if __name__ == '__main__':
    "Testing - Accept a single connection"
    class TNS(SocketServer.TCPServer):
        allow_reuse_address = True

    class TNH(TelnetHandler):
        def cmdECHO(self, params):
            """ [<arg> ...]
            Echo parameters
            Echo command line parameters back to user, one per line.
            """
            self.writeline("Parameters:")
            for item in params:
                self.writeline("\t%s" % item)
        def cmdTIME(self, params):
            """
            Print Time
            Added by dilbert
            """
            self.writeline(time.ctime())

    logging.getLogger('').setLevel(logging.DEBUG)

    tns = TNS(("0.0.0.0", 8023), TNH)
    tns.serve_forever()

rawDescription: Creating a CLI shell accessible by telnet using Python


code: select([foo], foo.c.bar.in_([1, 2, 3]))

rawDescription: Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?


rawDescription: matplotlib set own axis values

description: Matplotlib set own axis values


code:
import random
print("Hello and welcome to the AI guessing Game pick a number from 1 to 100 then press H or L to give the clue")
number=input("pick a number from 1 to 100 :")
number=int(number)
tries = 0
computernumber=1

# Bring it outside of your loop.
computernumber=random.randint(1,100)

while computernumber !=(number):
    print (computernumber)
    higherorlower=input("is your number higher or lower use H or L please!")
    if higherorlower == "H":
        computernumber +=1
        tries = int(tries)
        tries +=1
        computernumber=random.randint (computernumber,number)
    else:
            computernumber -=1
            computernumber=random.randint (1,computernumber)
            tries = 0
            tries = int(tries)
            tries +=1

            # Do not use break here
            #break

if computernumber == number:
    if tries == 1 or 0:

        print("Your number was", number,"and it took me",tries,"Try")
    else:
        print("Your number was", number,"and it took me",tries,"Tries")

rawDescription: My While loop isn't working in python

description: My While loop isn't working in python


code:
AJAX_LOOKUP_CHANNELS = {
    'to' : dict(model='auth.User', search_field='username'),
}

rawDescription: Trouble searching User model using django-ajax-selects


code:
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.empty(len(array), int)
ranks[temp] = numpy.arange(len(array))

rawDescription: Rank items in an array using Python/NumPy


code:
self.picname = "some_img.png"
self.picture = pygame.image.load(self.picname)

rawDescription: Pygame image, get the current image file loaded


code:
from PyQt4.QtGui import QTableWidgetItem

class ATableWidgetItem(QTableWidgetItem):

    def __init__(self, id, *args, **kwargs):
        super(ATableWidgetItem, self).__init__(*args, **kwargs)
        self.id = id

a = ATableWidgetItem(0)
b = ATableWidgetItem(0, QTableWidgetItem.UserType)
c = ATableWidgetItem(0, "text", type=QTableWidgetItem.UserType)

class AnotherTableWidgetItem(QTableWidgetItem):

    def __init__(self, id):
        super(AnotherTableWidgetItem, self).__init__()
        self.id = id

d = AnotherTableWidgetItem(0)

class YetAnotherTableWidgetItem(QTableWidgetItem):

    def __init__(self, id, text="", type=QTableWidgetItem.Type):
        super(YetAnotherTableWidgetItem, self).__init__(text, type)
        self.id = id

e = YetAnotherTableWidgetItem(0)
f = YetAnotherTableWidgetItem(0, "Hello")
g = YetAnotherTableWidgetItem(0, "Hello", QTableWidgetItem.UserType)

rawDescription: Init method for subclass of PyQt QTableWidgetItem


code:
import clr
clr.AddReference('MyAssemblyWhichContainsForm.dll')
import MyForm
obj = MyForm("form title")
obj.Show()

rawDescription: Running C# Executable From Iron Python

description: Running C# Executable From Iron Python


code:
if request.POST.get('delete'):
    order_number.delete() # Why was this there? of course, if I have this it will delete till it gets to the next part where it informs the user which order number was deleted!
    request.user.message_set.create(message = "Previous order " + str(order_number.pk) + "  deleted")
    order_number.delete()

rawDescription: Django: String object prints out None

description: Django: String object prints out None


code:
group_df = df.groupby(group_name).agg([np.mean, np.std, np.count_nonzero])
group_df.rename(None, lambda coltuple: '_'.join(coltuple), False, True)

rawDescription: column names on grouped DataFrame output to CSV

description: Column names on grouped DataFrame output to CSV


code:
import pickle
f = open(file_Name,'wb')
pickle.dump(assignment_data, f)
f.close()

rawDescription: Moving data (based on a class) from .py to a dictonary in another .py file


code:
randnum = random.randrange(1, 105) # no list, directly the number.

if randnum < 76:
    return "normal_attack"
elif randnum < 101:
    return "critical_attack"
else:
    return "missed_attack"

rawDescription: Why does my python function not return any of my conditions, other than None?


code:
import datetime

def cal_delta_to(hour, minute):
    now = datetime.datetime.now()
    target = datetime.datetime(*now.timetuple()[0:3], hour=16, minute=30)

    if target < now:  # if the target is before now, add one day
        target += datetime.timedelta(days=1)

    diff = now - target
    return diff.seconds

rawDescription: Seconds left to HH:MM

description: Seconds left to HH:MM


rawDescription: Unpack data read from serial connection

description: Unpack data read from serial connection


code:
for s in stage1_approved_mentor_applications:
   self.assertEqual('stage2.pending', s.status)

rawDescription: Python: Assert that all objects in a list have a specific attribute values


code:
import signal

def in_close(signum = None, frame = None):
    # Here you can attempt to gently exit your application.
    pass

# For some common signals that will close your program.
for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
    signal.signal(sig, in_close)

rawDescription: trigger a function when pc is shutting down - tkinter

description: Trigger a function when pc is shutting down - tkinter


code:
xml = ET.fromstring("<book></book>")
document = ET.parse(tempFile)
childNodeList = document.findall(xpathQuery)
for node in childNodeList:
   xml.append(node)

rawDescription: merging xml files using Element Tree in Python

description: Merging xml files using Element Tree in Python


code:
df_tags = df.apply(lambda x: pd.Series(x['Tags']),axis=1).stack().reset_index(level=1, drop=False)
df_tags.columns = ['Key', 'Value']
df_tags
df.drop('Tags', axis=1).join(df_tags)

rawDescription: Python Pandas, one dict column, create new rows for each key/value pair


code: _console_out = ConsoleHandler()

rawDescription: Pylint - "Using the global statement"

description: Pylint - "Using the global statement"


code:
for i in range(11, 1):
    ws.cell(row=i, column=2).value = i

rawDescription: How to write values of a dict to an empty (new) column in openpyxl?

description: Write values of a dict to an empty (new) column in openpyxl


rawDescription: Pandas index value relating to a threshold exceedance


code:
# ... This stuff is the same...

def _upload_part(argFile, argBucket, verbose, **core_chunk):  # Add verbose argument
    #... Same until you declare the Pool
    pool = Pool(processes=1, initializer=init_log, initargs=(logFile, verbose))  # Add verbose to initargs
   # All the same ...

def init_log(logFile, verbose):
    global logger
    exec_file = os.path.abspath( argv[0] )
    exec_dir = os.path.dirname( exec_file )
    default_logger = dict( pdir=exec_dir, ldir='logs', lname='error.log', level='ERROR',
                           fmt='%(asctime)s %(levelname)s: %(message)s' )

    log_filename = logFile
    level = 'INFO'
    format = '%(asctime)s %(levelname)s: %(message)s'

    default_logger.update( fmt=format, level=level, lname = log_filename )
    if os.path.isabs( log_filename ):
        bdir, log_filename = os.path.split( log_filename )
        default_logger.update(pdir='', ldir = bdir, lname = log_filename )
    logger = _get_logger( **default_logger )

    if verbose:  # Set up StreamHandler here
        try:
            print_handler = logging.StreamHandler(stdout)
            print_handler.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
            print_handler.setFormatter(formatter)
            logger.addHandler(print_handler)
        except (NoOptionError, NoSectionError) as e:
            logger.exception(e)

if __name__ == "__main__":

    freeze_support()

    parser = argparse.ArgumentParser( description="CLI." )
    group = parser.add_mutually_exclusive_group()
    group.add_argument( "-v", "--verbose", action='store_const', const=True, help="Output process messages to stdout \
                        channel")
    args = parser.parse_args()

    logFile = 'mylogfile.txt'
    init_log(logFile)

    bucket_name = 'some-bucket'

    logger.info('Establishing Connection')
    _upload_part('large_testfile.log', bucket_name, args.verbose)  # Pass args.verbose

rawDescription: Python - Using Streamhandler in multiprocessing environment


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

x = np.linspace(0, 6.*np.pi, num=100) #interval (0,6*pi) in 10'000 steps
A = 1.e-4 # Amplitude of sine function
y = A*np.sin(x)

fig, axes = plt.subplots(nrows=2)
for ax, s, title in zip(axes, [2, 0], ['With', 'Without']):
    yinterp = interpolate.UnivariateSpline(x, y, s=s)(x)
    ax.plot(x, yinterp, label='Interpolated')
    ax.plot(x, y, 'bo',label='Original')
    ax.legend()
    ax.set_title(title + ' Smoothing')

plt.show()

rawDescription: Spline representation with scipy.interpolate: Poor interpolation for low-amplitude, rapidly oscillating functions


code:
from decimal import Decimal
obj = Decimal('3.1415926535897932384626433832795028841971')
+obj != obj  # The __pos__ function rounds back to normal precision
obj
+obj

rawDescription: What's the purpose of the + (pos) unary operator in Python?


rawDescription: web2py - test for row with combination of two field values

description: Web2py - test for row with combination of two field values


code:
a = np.random.random((20,3))
b = np.random.random((20,3))
c = np.cross(a,b)
c[0], np.cross(a[0], b[0])
c[1], np.cross(a[1], b[1])
all((c[i] == np.cross(a[i], b[i])).all() for i in range(len(c)))

rawDescription: Python/Numpy - Cross Product of Matching Rows in Two Arrays


code: re.split(r'\s(?=(?:this|into|ones)\b)', "Let's split this string into many small ones")

rawDescription: split python string on multiple string delimiters efficiently

description: Split python string on multiple string delimiters efficiently


code:
names = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']
first_letters = ['A','B','C']
output_names = [name for name in names if (name[0] in first_letters)]
output_names

rawDescription: Get a list of names which start with certain letters


rawDescription: Python MediaWiki table regex (find strings of a particular format, then extract substrings within)


rawDescription: regular expression to get data out of a string

description: Regular expression to get data out of a string


code:
queryCurs.execute("SELECT * FROM PATIENT")
row = 0
while True:
    form = queryCurs.fetchone()
    if form == None:
        break
    for column, item in enumerate(form):
        patientTable.setItem(row, column, QtGui.QTableWidgetItem(str(item)))
    row += 1

rawDescription: How to display in Qtablewidget the data from sqlite.

description: Display in Qtablewidget the data from sqlite.


code:
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.widget = Widget()

    def closeEvent(self, event):
        self.widget.close()

rawDescription: the widget does not close/quit with the main window

description: The widget does not close/quit with the main window


code:
with file("test.xml") as temp:
    temp.write(doc.toprettyxml())
    temp.flush()
    command = ["./cval", "-o", options.output, "-i", str(options.interval), "-s", "%dx%d" %    (options.width, options.height), "-f", str(options.frames), "-x", temp.name]
    subprocess.call(command)

rawDescription: Running subprocess.call to run a Cocoa command-line application


code:
import Tkinter as tk
import time

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):

        # initialize Tkinter
        tk.Tk.__init__(self, *args, **kwargs)

        # hide main window
        self.wm_withdraw()

        # show "please wait..." window
        self.wait = tk.Toplevel(self)
        label = tk.Label(self.wait, text="Please wait...")
        label.pack()

        # schedule the rest of the initialization to happen
        # after the event loop has started
        self.after(100, self.init_phase_2)

    def init_phase_2(self):

        # simulate doing something...
        time.sleep(10)

        # we're done. Close the wait window, show the main window
        self.wait.destroy()
        self.wm_deiconify()

app = SampleApp()
app.mainloop()

rawDescription: Tkinter: one or more mainloops?

description: Tkinter: one or more mainloops


code:
from tkinter import *

class Application(Frame):
    def say_hi(self):
        if self.var.get() or self.var2.get():
            msg = ''
            if self.var.get():
                msg = 'Radio button 1 is checked\n'
            if self.var2.get():
                msg += 'Radio button 2 is checked'

            print(msg) # to sdtout...
            top = Toplevel()
            top.title("Pop-up...")
            msg = Message(top, text=msg)
            msg.pack()
            button = Button(top, text="Close", command=top.destroy)
            button.pack()

    def createWidgets(self):
        self.QUIT = Button(self)
        self.QUIT["text"] = "Close"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit
        self.QUIT.pack({"side": "left"})

        self.var = IntVar()
        self.checkbox = Checkbutton(self)
        self.checkbox["text"] = 'radio1'
        self.checkbox["command"] = self.say_hi
        self.checkbox["variable"] = self.var
        self.checkbox.pack({"side": "left"})

        self.var2 = IntVar()
        self.checkbox2 = Checkbutton(self)
        self.checkbox2["text"] = 'radio2'
        self.checkbox2["command"] = self.say_hi
        self.checkbox2["variable"] = self.var2
        self.checkbox2.pack({"side": "left"})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()

rawDescription: Radio button and messages

description: Radio button and messages


code:
def set_extra_forms(extra_forms, **kwargs):
    EmploymentFormSet = inlineformset_factory(Profile, Employment, form=EmploymentForm, extra=extra_forms)
    return EmploymentFormSet(**kwargs)

rawDescription: Add extra parameter to inlineformset_factory


code:
def foo(**args):
    print(args)
foo(a=1, b=2)

rawDescription: Python arguments as a dictionary

description: Python arguments as a dictionary


code:
import pandas as pd
data_frame = pd.read_table('test_data.txt', sep='\s+', header=None)
data_frame.columns = ['year', 'month', 'day', 'n1', 'n2', 'n3', 'n4', 'type']
data_frame

rawDescription: Python: How do I split a text file and place into VB equivalent of an array?


code:
import xml.etree.ElementTree as ET

class ProgramProperties(object):

    def __init__(self, xmlfile):

        # Parse the XML file
        self.__xmlfile = xmlfile
        self.__xml_tree = ET.parse(xmlfile)
        self.__version_element = self.__xml_tree.getroot().find(".//property[@name='version']")

        # Get an in-memory copy of 'version'
        self.__version = float(self.__version_element.text)

    @property
    def version(self):
        return self.__version

    @version.setter
    def version(self, vers):

        # Avoid unecessary file I/O
        if self.__version != vers:

            # Store in-memory
            self.__version = vers

            # Save the version to the file
            self.__version_element.text = str(vers)
            self.__xml_tree.write(self.__xmlfile)

prog = ProgramProperties('testdata.txt')

# Update the version, which automatically saves it in the setter
prog.version = 3.14

rawDescription: Modify specific XML from python?

description: Modify specific XML from python


code:
import functools
import threading

def run_in_threads(*functions):
    threads = []

    for function in functions:
        thread = threading.Thread(target = function)
        thread.daemon = True
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

def __print_infinite_loop(value, event):
    while not event.is_set():
        print(value)

def __print_my_value_n_times(value, n, event):
    for i in range(n):
        print(value)
    event.set()

if __name__ == "__main__":
    event = threading.Event()
    infinite_loop = functools.partial(__print_infinite_loop, "xyz", event)
    my_values = functools.partial(__print_my_value_n_times, "123", 10, event)
    run_in_threads(infinite_loop, my_values)

rawDescription: How to stop first thread when the second thread is finished in python?

description: Stop first thread when the second thread is finished in python


code:
import re

xml = re.sub(r'.*<root>', '<root>', xml, flags=re.DOTALL)    # Remove leading junk
xml = re.sub(r'\\par[^<]*<', '<', xml)                       # Middle junk
xml = re.sub(r'</root>.*', '</root>', xml, flags=re.DOTALL)  # Trailing junk

rawDescription: Process xml input with python regex

description: Process xml input with python regex


code:
def MyView(request):
   object = MyAuth(request)

   # if it is a redirect then return it.
   if isinstance(object, HttpResponseRedirect):
       return object

   # do stuff with object

   return render('some_template.html')

rawDescription: Django redirect and break current flow

description: Django redirect and break current flow


rawDescription: How to refresh the page in Mechanize?

description: Refresh the page in Mechanize


code:
a = [[0,1,2], [3,4,5], [6,7,8], [9,10,11]]
with multiprocessing.Pool() as pool:
    b = pool.map(reversed, a, chunksize=1)
    c = [list(i) for i in b]

rawDescription: How to efficiently share a common parent atribute class by multiprocessing tasks?

description: Efficiently share a common parent atribute class by multiprocessing tasks


code:
df.groupby(df.date2.dt.year)['fruit']\
    .value_counts()\
    .unstack(1)\
    .plot(kind='bar', stacked=True)

rawDescription: Pandas histogram by dates, and sorted by categories


code:
input = tf.placeholder(tf.float32, [None, 28, 28, 3])
padded_input = tf.pad(input, [[0, 0], [2, 2], [1, 1], [0, 0]], "CONSTANT")

filter = tf.placeholder(tf.float32, [5, 5, 3, 16])
output = tf.nn.conv2d(padded_input, filter, strides=[1, 1, 1, 1], padding="VALID")

rawDescription: Custom padding for convolutions in TensorFlow


rawDescription: Scrapy, detect when new start_url is being


code:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
peak = True
gs1 = GridSpec(1, 2)
for sub in gs1:
  #make axes for two default plots
  ax = plt.subplot(sub)
if peak == True:
  #move default plots to the left
  gs1.update(right = .75)
  #add new plot
  gs2 = GridSpec(1, 1)
  #move plot to the right
  gs2.update(left = .8)
  ax = plt.subplot(gs2[0, 0])
plt.show()

rawDescription: Adding a variable number of sub-plots in a loop. add_subplot


rawDescription: How to check same position in two different lists in python

description: Check same position in two different lists in python


code:
import os
import csv
import sqlite3

def db2csv(file,Table1):
    con = sqlite3.connect("memory.db")
    cur = con.cursor()

    if not os.path.exists(file):
        os.makedirs(file)

    with open(file, 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row in cur.execute('SELECT * FROM Table1 '):
            spamwriter.writerow(row)
    con.commit()

rawDescription: How to transfer data on SQL Table to Excel file in Python?

description: Transfer data on SQL Table to Excel file in Python


code:
while True:
    try:
        os.remove(yourfilename) # try to remove it directly
    except OSError as e:
        if e.errno == errno.ENOENT: # file doesn't exist
            break
        time.sleep(5)
    else:
        break

rawDescription: Check if a file is available (not used by another process) in Python


code:
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication([])
pw = QtGui.QLineEdit()
pw.setEchoMode(QtGui.QLineEdit.Password)
pw.show()
app.exec_()

rawDescription: Password form in PyQt

description: Password form in PyQt


code: [d for d in a if d['name'] == 'pluto']

rawDescription: extract item from list of dictionaries

description: Extract item from list of dictionaries


code:
from pyspark.sql.functions import rand

df = sc.parallelize(range(20)).map(lambda x: (x, )).toDF(["x"])
df.orderBy(rand()).show(3)

## +---+
## |  x|
## +---+
## |  2|
## |  7|
## | 14|
## +---+
## only showing top 3 rows

rawDescription: pyspark: Randomize rows in dataframe

description: Pyspark: Randomize rows in dataframe


code:
from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input1 = PdfFileReader(file("document1.pdf", "rb"))
watermark = PdfFileReader(file("watermark.pdf", "rb"))

page4.mergePage(watermark.getPage(0))

# finally, write "output" to document-output.pdf
outputStream = file("document-output.pdf", "wb")
output.write(outputStream)
outputStream.close()

rawDescription: Place image over PDF

description: Place image over PDF


code:
def left(s, amount):
    return s[:amount]

def right(s, amount):
    return s[-amount:]

def mid(s, offset, amount):
    return s[offset:offset+amount]

rawDescription: Python: Is there an equivalent of mid, right, and left from BASIC?


code:
for num, name in zip(numbers, names):
    print('{0}, {1}'.format(num, name))

rawDescription: Simple way to "mix" respectively two lists in python?


code:
class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

rawDescription: What's the difference between select_related and prefetch_related in Django ORM?


code:
def on_change_interest_fields(self, cr, uid, ids, amountPay, interestType, context):
    interest = amountPay * 0.5
    return {'value': {'interest': interest,},}

rawDescription: Is it possible to calculate the value of a field from another field in the same form in OpenERP?


code:
import networkx as nx
import pygraphviz as pgv # need pygraphviz or pydot for nx.to_agraph()

G = nx.DiGraph()
G.add_edge(1,2,weight=7)
G.add_edge(2,3,weight=8)
G.add_edge(3,4,weight=1)
G.add_edge(4,1,weight=11)
G.add_edge(1,3)
G.add_edge(2,4)

for u,v,d in G.edges(data=True):
    d['label'] = d.get('weight','')

A = nx.to_agraph(G)
A.layout(prog='dot')
A.draw('test.png')

rawDescription: Python, pygraphviz, networkx

description: Python, pygraphviz, networkx


code:
from matplotlib._pylab_helpers import Gcf
from IPython.core.pylabtools import print_figure
from base64 import b64encode

# Plot something
plot([1,2],[3,4])

# Get a handle for the plot that was just generated
fig = Gcf.get_all_fig_managers()[-1].canvas.figure

# Generate a data URL for the image
# Matplotlib's display() would output the plot, so I do this manually.
# There might be a wrapper for this somewhere in IPython, if you're
# unhappy with this line..
image_data = "data:image/png;base64,%s" % b64encode(print_figure(fig)).decode("utf-8")

# Remove the plot from the list of plots for the current cell
Gcf.destroy_fig(fig)

# Now you can use the data URL in your HTML output
HTML("Foo Bar

 Baz" % image_data)

rawDescription: IPython Notebook: How to combine HTML output and matplotlib figures?


code:
s = raw_input()
s
len(s)
s.decode('string_escape')
len(s.decode('string_escape'))

rawDescription: keeping data in a raw mode while passing to re.match

description: Keeping data in a raw mode while passing to re.match


code:
import xml.etree.ElementTree as ET

def sortchildrenby(parent, attr):
    parent[:] = sorted(parent, key=lambda child: child.get(attr))

tree = ET.parse('input.xml')
root = tree.getroot()

sortchildrenby(root, 'NAME')
for child in root:
    sortchildrenby(child, 'NAME')

tree.write('output.xml')

rawDescription: Sorting XML in python etree

description: Sorting XML in python etree


code:
df
df.stack().reset_index()

rawDescription: Transpose csv structure using python pandas


code:
if request.method == 'POST':

    form = DocumentAndPhotoForm(request.POST, request.FILES)
    if form.is_valid():
        if form.cleaned_data.get('document'):

            post1 = Document(user = request.user, document= form1.cleaned_data['document'], title = form1.cleaned_data['title'])
            post1.save()

        if form.cleaned_data.get('img'):
            post2 = Photo(user = request.user, alias = request.user.username, img = form2.cleaned_data['img'], title = "")
            post2.save()

        return HttpResponse(template.Template('''
                <title>Uploaded</title>

Uploaded

                '''
                ).render( template.Context({}))
            )

return render_to_response('upload.html', {'form': form },      context_instance=RequestContext(request))

rawDescription: Django: Uploading photo and word doc on same form not working correctly


code: cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])

rawDescription: Choosing color in matplotlib contour maps


code:
class Foo:
    def __init__(self):
        self.bars = []

    def append_bar(self, *args, **kwargs):
        self.bars.append(Bar(*args, **kwargs))

class Bar:
    def __init__(self, a, b, c, d):
        self.a = a
        self.b = b
        self.c = c
        self.d = d

f=Foo()
f.append_bar(1,2,3,4)

rawDescription: Python - How to use underlying object's constructor as class method?


code:
for key, value in post.iteritems():
    setattr(my_model, key, value)

rawDescription: Copying values from a dictionary into an object in Python


rawDescription: overloading a float to a numpy array

description: Overloading a float to a numpy array


rawDescription: Selenium Python: Download PDF specified by DOM object


rawDescription: How to round a float up on 5

description: Round a float up on 5


code:
row_idx = np.arange(rows)[:, None]
col_idx = np.arange(cols)

binary_img = (row_idx - m * col_idx) > c

rawDescription: Python: Efficient creation of binary image from line


rawDescription: how to compare ndarrays in python

description: Compare ndarrays in python


code:
import gi
gi.require_version('Gtk', '3.0')

from gi.repository import Gtk, Gdk, Vte, GLib

palette_components = [
    (0, 0x0707, 0x3636, 0x4242),    # background
    (0, 0xdcdc, 0x3232, 0x2f2f),
    (0, 0x8585, 0x9999, 0x0000),
    (0, 0xb5b5, 0x8989, 0x0000),
    (0, 0x2626, 0x8b8b, 0xd2d2),
    (0, 0xd3d3, 0x3636, 0x8282),
    (0, 0x2a2a, 0xa1a1, 0x9898),
    (0, 0xeeee, 0xe8e8, 0xd5d5),    # foreground
    (0, 0x0000, 0x2b2b, 0x3636),
    (0, 0xcbcb, 0x4b4b, 0x1616),
    (0, 0x5858, 0x6e6e, 0x7575),
    (0, 0x6565, 0x7b7b, 0x8383),
    (0, 0x8383, 0x9494, 0x9696),
    (0, 0x6c6c, 0x7171, 0xc4c4),
    (0, 0x9393, 0xa1a1, 0xa1a1),
    (0, 0xfdfd, 0xf6f6, 0xe3e3)
    ]

palette = []
for components in palette_components:
    color = Gdk.Color(components[1], components[2], components[3])
    palette.append(color)

def terminal_realize_cb(terminal):
    terminal.set_colors(None, None, palette)

if __name__ == '__main__':
    window = Gtk.Window()
    window.connect('delete-event', Gtk.main_quit)

    terminal = Vte.Terminal()

    # Option 1: connect to the terminal widget's realize event
    # and call it's set_colors() method there
    terminal.connect('realize', terminal_realize_cb)

    terminal.fork_command_full(Vte.PtyFlags.DEFAULT,
                               None,
                               ['/bin/bash'],
                               [],
                               GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                               None,
                               None)

    window.add(terminal)
    window.show_all()

    # Option 2: call the terminal's set_colors() method
    # after the window has been shown (which indirectly
    # realizes the terminal widget)
    #terminal.set_colors(None, None, palette)

    Gtk.main()

rawDescription: Why the method set_color_foreground and its companions set_color_XXX don't work in Vte ( Python - Gtk3)?


code:
data = data.unstack(['observer', 'obstype'])
data.columns = data.columns.droplevel(0)
data

rawDescription: Reshaping data in Pandas (multi index in the columns, maybe in the rows too)


code:
@pm.deterministic
def my_lp_solver(c1=c1):
    c = matrix([float(c1), -5.])
    G = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]])
    h = matrix([3., 3., 0., 0.])
    sol = solvers.lp(c, G, h)
    solution = np.array(sol['x'],dtype=float).flatten()
    return solution

rawDescription: Stochastic Optimization in Python

description: Stochastic Optimization in Python


rawDescription: How do I get the filepath for a class in Python?

description: Get the filepath for a class in Python


rawDescription: django foreign key relation lookup

description: Django foreign key relation lookup


code:
func_dict = {}
func_dict['str1'] = fun1
func_dict['str2'] = fun2
...
def function_lookup(func_string):
    return func_dict.get(func_string)

rawDescription: Better optimization technique using if/else or dictionary


code:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_to_key = {}
    for key, value in sources.items():
        future_to_idday[executor.submit(do_stuff, value)] = key
    for future in concurrent.futures.as_completed(future_to_key):
        key = future_to_key[future]
        result = future.result()
        # process result

rawDescription: Picking up items progressivly as soon as a queue is available


code: os.system('xdg-open "%s"' % foldername)

rawDescription: Standard way to open a folder window in linux?


code:
import operator

def get_column(list_, n):
    return map(operator.itemgetter(n), list_)

rawDescription: Python - column slice of list of list matrix


code:
def setup(self):
    self.proc = subprocess.Popen("test_process")

def cleanup(self):
    self.proc.kill()

rawDescription: Killing a process spawned by another thread


code:
legal = set(['osama','bin','laden'])

def is_legal(seq):
    return all(tok in legal for tok in seq)

rawDescription: Is this boolean test pythonic for limiting a list's members to a set of legal values?


code:
from django.views.generic.edit import FormView
from workshop.models import Workshop, WorkshopAttendee
from workshop.forms import WorkshopAttendeeForm
from django.http import HttpResponseRedirect

class WorkshopAttendeeFormView(FormView):

    def form_valid(self, form):

        self.object = form.save(commit=False)
        self.object.workshop = Workshop.objects.filter(slug=self.kwargs['slug'])[0]
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

rawDescription: Django ModelForms: Seeding a FK related field in the form


code:
from multiprocessing import Process
import time

def child_func():
    time.sleep(1000)

if __name__ == '__main__':
    event = Event()
    child_thread = Process(target=child_func)
    child_thread.start()
    time.sleep(3)
    child_thread.terminate()
    child_thread.join()

rawDescription: Running Python multi-threaded process & interrupt a child thread with a signal


code:
# ... initialize a lookup dictionary
country_to_id_dict = dict((t[1], t[0]) for t in COUNTRIES)

# ... use the dictionary in the query
i = MyModel.objects.filter(country__exact=country_to_id_dict[query])

rawDescription: how can I filter on the second element in a tuple of tuples?

description: Filter on the second element in a tuple of tuples


code:
from osgeo import gdal

def world2Pixel(gt, x, y):
  ulX = gt[0]
  ulY = gt[3]
  xDist = gt[1]
  yDist = gt[5]
  rtnX = gt[2]
  rtnY = gt[4]
  pixel = int((x - ulX) / xDist)
  line = int((ulY - y) / xDist)
  return (pixel, line)

dataset = gdal.Open(filename)
gt = dataset.GetGeoTransform()

pixel, line = world2Pixel(gt, x, y)

band = dataset.GetRasterBand(1)
value = band.ReadAsArray(pixel, line, 1, 1)[0, 0]

rawDescription: Sample raster cell value at coordinates?

description: Sample raster cell value at coordinates


code:
from PySide.QtCore import Signal

class Gui(QWidget):
    def initUI(self):
        ...
        bgThread.dataReceived.connect(lambda data: lbl2.setText(str(data)))

class BackgroundThread(QThread):
    dataReceived = Signal(list)
    ...

    def _summary(self):
        ...
        self.dataReceived.emit(data)

rawDescription: How can I send a list object from a QThread thread to the UI's main thread?

description: Send a list object from a QThread thread to the UI's main thread


code:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()

pupil = [name for name in contents.split('\n') if name]

rawDescription: Saving/Loading lists in Python

description: Saving/Loading lists in Python


code:
from google.appengine.ext import db

xg_on = db.create_transaction_options(xg=True)

def my_txn():
    x = MyModel(a=3)
    x.put()
    y = MyModel(a=7)
    y.put()

db.run_in_transaction_options(xg_on, my_txn)

rawDescription: Cross Group (XG) Transactions and Further Explanation of use


code:
import shlex
import subprocess
from subprocess import STDOUT,PIPE
import os
import socket

class Translator:
    @staticmethod
    def pl_to_en(input_file, output_file):
        # Tokenize
        print("Tokenization started")
        with open("tokenized.txt", "w+") as tokenizer_output:
            with open(input_file) as tokenizer_input:
                cmd = "/home/nlp/opt/moses/scripts/tokenizer/tokenizer.perl -    l pl"
                args = shlex.split(cmd)
                p = subprocess.Popen(args, stdin=tokenizer_input, stdout=tokenizer_output)
                p.wait()
                print("Tokenization finished")

        #Translate
        print("Translation started")
        cmd = "/home/nlp/opt/moses/bin/moses -f /home/nlp/Downloads/TED/tuning/moses.tuned.ini.1 -drop-unknown -input-file tokenized.txt -th 8"
        args = shlex.split(cmd)
        translate_p = subprocess.Popen(args, stdout=subprocess.PIPE)
        translate_p.wait()
        print("Translation finished")
    # Detokenize
        print("Detokenization started")
        with open("detokenized.txt", "w+") as detokenizer_output:
            cmd = "/home/nlp/opt/moses/scripts/tokenizer/detokenizer.perl -l en"
            args = shlex.split(cmd)
            detokenizer_p = subprocess.Popen(args, stdin=translate_p.stdout, stdout=detokenizer_output)
            detokenizer_p.wait()
            print("Detokenization finished")

translator = Translator()
translator.pl_to_en("some_input_file.txt", "some_output_file.txt")

rawDescription: Calling multiple linux processes in Python and collecting output


code:
class MyBooleanProperty(ndb.BooleanProperty):
    def _set_value(self, entity, value):
        if value == '':
            value = None
        ndb.BooleanProperty._set_value(self, entity, value)

rawDescription: Parse value to None in ndb custom property


code:
hex_string = "68656c6c6f"

c_list = []

for c in hex_string.decode("hex"):
    c_list.append(ord(c))

rawDescription: Convert hex-encoded string to decimal array in python


code:
r = [rs[0] for rs in list if rs not in[('g',),('j',)]]
#       ^

rawDescription: how to get only the first element of a touple list into an array

description: Get only the first element of a touple list into an array


code:
import csv

dict1 ={
   "key1": "value1",
   "key2": "value2",
   "key3": "value3"}

dict2 ={
   "key1": "value4",
   "key2": "value5",
   "key3": "value6"}

dict3 ={
   "key1": "value7",
   "key2": "value8",
   "key3": "value9"}

data = [dict1,dict2,dict3]

dict_writer = csv.DictWriter(file('my.csv','wb'),fieldnames=dict1.keys())
dict_writer.writeheader()
dict_writer.writerows(data)

rawDescription: python dicts into CSV

description: Python dicts into CSV


code:
from ctypes import byref, create_unicode_buffer, sizeof, WinDLL
from ctypes.wintypes import DWORD, HMODULE, MAX_PATH

Psapi = WinDLL('Psapi.dll')
Kernel32 = WinDLL('kernel32.dll')

PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010

LIST_MODULES_ALL = 0x03

def EnumProcesses():
    buf_count = 256
    while True:
        buf = (DWORD * buf_count)()
        buf_size = sizeof(buf)
        res_size = DWORD()
        if not Psapi.EnumProcesses(byref(buf), buf_size, byref(res_size)):
            raise OSError('EnumProcesses failed')
        if res_size.value >= buf_size:
            buf_count *= 2
            continue
        count = res_size.value // (buf_size // buf_count)
        return buf[:count]

def EnumProcessModulesEx(hProcess):
    buf_count = 256
    while True:
        buf = (HMODULE * buf_count)()
        buf_size = sizeof(buf)
        needed = DWORD()
        if not Psapi.EnumProcessModulesEx(hProcess, byref(buf), buf_size,
                                          byref(needed), LIST_MODULES_ALL):
            raise OSError('EnumProcessModulesEx failed')
        if buf_size < needed.value:
            buf_count = needed.value // (buf_size // buf_count)
            continue
        count = needed.value // (buf_size // buf_count)
        return map(HMODULE, buf[:count])

def GetModuleFileNameEx(hProcess, hModule):
    buf = create_unicode_buffer(MAX_PATH)
    nSize = DWORD()
    if not Psapi.GetModuleFileNameExW(hProcess, hModule,
                                      byref(buf), byref(nSize)):
        raise OSError('GetModuleFileNameEx failed')
    return buf.value

def get_process_modules(pid):
    hProcess = Kernel32.OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
        False, pid)
    if not hProcess:
        raise OSError('Could not open PID %s' % pid)
    try:
        return [
            GetModuleFileNameEx(hProcess, hModule)
            for hModule in EnumProcessModulesEx(hProcess)]
    finally:
        Kernel32.CloseHandle(hProcess)

for pid in EnumProcesses():
    try:
        dll_list = get_process_modules(pid)
        print('dll_list: ', dll_list)
    except OSError as ose:
        print(str(ose))
    print('-' * 14)

rawDescription: tasklist does not list all Modules in 64-systems

description: Tasklist does not list all Modules in 64-systems


code:
t = threading.Timer(30.0, unban)
t.start() # after 30 seconds, unban will be run

rawDescription: Least painful way to run a Python delay loop


code:
def process_bar(bar):
   return bar + 1

class Foo(object):
    @classmethod
    def from_data(self, datafile, processor=process_bar):
        bar = datafile.read_bar()
        bar = processor(bar)
        return cls(bar)

rawDescription: Python factory method with external function


code:
from functools import wraps

_empty = object()  # sentinel value used to control testing

def dump_ne(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        # remove the expected value from the actual call kwargs
        expected = kwargs.pop('_expected', _empty)

        # call the function with rest of args and kwargs
        result = func(*args, **kwargs)

        # only test when _expected was passed in the kwargs
        # only print when the result didn't equal expected
        if expected is not _empty and expected != result:
            print('FAIL: func={}, args={}, kwargs={}'.format(func.__name__, args, kwargs))

        return result

    return decorated

@dump_ne
def cool(thing):
    return thing.upper()

print(cool('cat'))  # prints 'CAT', test isn't run

for thing in ('cat', 'ice', 'cucumber'):
    print(cool(thing, _expected='CUCUMBER'))
    # dumps info for first 2 calls (cat, ice)

rawDescription: How to pass non-hard-coded parameter to Python decorator?

description: Pass non-hard-coded parameter to Python decorator


code:
import os

nested_list=[
    [u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur'],
    [u'good\tJJ\tgood', u'camera\tNN\tcamera', u'for\tIN\tfor', u'a\tDT\ta', u'good\tJJ\tgood']
]

for i, a_list in enumerate(nested_list):
    #new_dir_path is path to dir you want.
    path = os.path.join(new_dir_path, "list%d.txt" % i) #or "list{}.txt".format(i)
    with open(path, "w") as f:
        for item in a_list:
            f.write(item+"\n") #\n if you want each item on a new line

rawDescription: How to save each element of a list to an independent new file?

description: Save each element of a list to an independent new file


rawDescription: Python regexp. My small program it is impossible to distinguish letters from numbers


code:
fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
[f['name'] for f in fields]

rawDescription: convert list of dicts to list

description: Convert list of dicts to list


code:
# set values in current namespace
for name in vars(messages):
    v = getattr(messages, name)
    globals()[name] = v

rawDescription: How do I do 'from foo import *' using Python's __import__ function

description: Do 'from foo import *' using Python's __import__ function


code:
from google.appengine.api import images

...

@register.simple_tag
def media_file_url(file_obj):
    try:
        return images.get_serving_url(file_obj.file.blobstore_info)
    except:
        return None

rawDescription: get_serving_url in Google App Engine fails in Production Caught InvalidBlobKeyError while rendering

description: Get_serving_url in Google App Engine fails in Production Caught InvalidBlobKeyError while rendering


code:
list_of_dfs = [df1,df2]
reduce(lambda x,y: x.mul(y,fill_value=1), list_of_dfs[1:], list_of_dfs[0])

rawDescription: Python Pandas: How To Set Columns as an Index?


code: from __future__ import division

rawDescription: Lottery probability Python code

description: Lottery probability Python code


code:
from pebble.process import concurrent

TIMEOUT_IN_SECONDS = 5

feed = connect2database()
for data in feed.changes():
    data = process(data)
    concurrent(target=ftpUpload, args=(data, ), timeout=TIMEOUT_IN_SECONDS)

rawDescription: Python Multiprocessing Timeout

description: Python Multiprocessing Timeout


code:
xpos = np.arange(0,4,1)
ypos = np.arange(0,4,1)
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(4*4)
rho = np.random.random((4,4))
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = rho.flatten()
nrm=mpl.colors.Normalize(-1,1)
colors=cm.RdBu(nrm(-dz))
alpha = np.linspace(0.2, 0.95, len(xpos), endpoint=True)
fig = plt.figure()
ax = fig.gca(projection='3d')
for i in range(len(xpos)):
    ax.bar3d(xpos[i],ypos[i],zpos[i], dx[i], dy[i], dz[i], alpha=alpha[i], color=colors[i], linewidth=0)
plt.show()

rawDescription: Matplotlib bar3d variable alpha

description: Matplotlib bar3d variable alpha


code:
class Company(User):
    objects = UserManager()
    class Meta:
        verbose_name = "Company"
        verbose_name_plural = "Companies"

rawDescription: How to change Users name tag in Admin Django

description: Change Users name tag in Admin Django


code:
def _match_region(self, name, position):
    rect = (self.regions["regions"][name]["pos1"], self.regions["regions"][name]["pos2"])
    return all(self.point_inside(rect, position))

if self.last_region and self._match_region(self.last_region, position):
    self.code_to_run_when_match(position)
    return

for name in self.regions["regions"]:
    if self._match_region(name, position):
        self.last_region = name
        self.code_to_run_when_match(position)
        return
return # if code gets here, the points were not inside any of the named regions

rawDescription: Start a dictionary for loop at a specific key value


code:
hour = 1
am_pm = "am"
print('{:02d}:00 {}'.format(hour, am_pm))

rawDescription: How to format number to represent time?

description: Format number to represent time


code:
from logging import getLogger, StreamHandler
from sys import stdout

ALL_LEVELS = 1

log= getLogger("mylogger")
handler= StreamHandler(stdout)
log.addHandler(handler)
log.setLevel(ALL_LEVELS)

log.debug("something")

rawDescription: Getting events of all levels using a non-root logger


code:
filename = 'file'

with open(filename, "rb") as data_file:
    data = data_file.read()
    length = len(data)
    data = int.from_bytes(data, 'big')

data += 1

with open(filename, "wb") as data_file:
    data = data.to_bytes(length, 'big')
    data_file.write(data)

rawDescription: Python - Increment file by 1

description: Python - Increment file by 1