code:
from threading import current_thread

class MyThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        self.parent = current_thread()
        Thread.__init__(self, *args, **kwargs)

rawDescription: Python threading - how to get parent ID/name


code:
from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]

rawDescription: Turning a string into a list with specifications


code: [value for key, value in programs.items() if 'new york' in key.lower()]

rawDescription: Find dictionary items whose key matches a substring


code:
import gtk
import urllib2
class Display(object):

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect('destroy', self.destroy)
        self.window.set_border_width(10)

        # a box underneath would be added every time you do
        # vbox.pack_start(new_widget)

        vbox = gtk.VBox()
        self.image = gtk.Image()
        response = urllib2.urlopen('http://1.bp.blogspot.com/-e-rzcjuCpk8/T3H-mSry7PI/AAAAAAAAOrc/Z3XrqSQNrSA/s1600/rubberDuck.jpg').read()

        pbuf = gtk.gdk.PixbufLoader()
        pbuf.write(response)
        pbuf.close()
        self.image.set_from_pixbuf(pbuf.get_pixbuf())

        self.window.add(vbox)
        vbox.pack_start(self.image, False)
        self.entry = gtk.Entry()
        vbox.pack_start(self.entry, False)

        self.image.show()
        self.window.show_all()

    def main(self):
        gtk.main()

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

a=Display()
a.main()

rawDescription: GtkWindow can only contain one widget at a time


rawDescription: How to make loop in python

description: Make loop in python


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=3, sharex=True, sharey=True)
plt.setp(axes.flat, aspect=1.0, adjustable='box-forced')

axes[0].plot(range(50))

plt.show()

rawDescription: new pythonic style for shared axes square subplots in matplotlib?

description: New pythonic style for shared axes square subplots in matplotlib


code:
url = 'http://httpbin.org/post'
files = {'report.xls': open('report.xls', 'rb')}
r = requests.post(url, files=files)

rawDescription: Is there a way to control windows with Python?


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

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pathRoot = QtCore.QDir.rootPath()

        self.model = QtGui.QFileSystemModel(self)
        self.model.setRootPath(self.pathRoot)

        self.indexRoot = self.model.index(self.model.rootPath())

        self.treeView = QtGui.QTreeView(self)
        self.treeView.setModel(self.model)
        self.treeView.setRootIndex(self.indexRoot)
        self.treeView.clicked.connect(self.on_treeView_clicked)

        self.labelFileName = QtGui.QLabel(self)
        self.labelFileName.setText("File Name:")

        self.lineEditFileName = QtGui.QLineEdit(self)

        self.labelFilePath = QtGui.QLabel(self)
        self.labelFilePath.setText("File Path:")

        self.lineEditFilePath = QtGui.QLineEdit(self)

        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.addWidget(self.labelFileName, 0, 0)
        self.gridLayout.addWidget(self.lineEditFileName, 0, 1)
        self.gridLayout.addWidget(self.labelFilePath, 1, 0)
        self.gridLayout.addWidget(self.lineEditFilePath, 1, 1)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addLayout(self.gridLayout)
        self.layout.addWidget(self.treeView)

    @QtCore.pyqtSlot(QtCore.QModelIndex)
    def on_treeView_clicked(self, index):
        indexItem = self.model.index(index.row(), 0, index.parent())

        fileName = self.model.fileName(indexItem)
        filePath = self.model.filePath(indexItem)

        self.lineEditFileName.setText(fileName)
        self.lineEditFilePath.setText(filePath)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(666, 333)
    main.move(app.desktop().screen().rect().center() - main.rect().center())
    main.show()

    sys.exit(app.exec_())

rawDescription: PyQt and QtreeView : How get the path from the selected file


code:
d = {'a':1, 'b':2, 'c':1, 'd':3}
min_val = min(d.values())
{k:v for k,v in d.items() if v > min_val}

rawDescription: Python get remaining runoff voting

description: Python get remaining runoff voting


rawDescription: How to print a value associated with a minimized residual - Python

description: Print a value associated with a minimized residual - Python


code: {key:x[key] for x in categories for key in x}

rawDescription: Could not replace field values in my json object as per the list


code:
import re
re.findall('\d+','gfgfdAAA1234ZZZsddgAAA4567ZZZuijjk')
['1234', '4567']

rawDescription: how to extract a multiple substring from inside a string in Python?

description: Extract a multiple substring from inside a string in Python


code:
#Column 0
booking = LabelFrame(master, text="Booking Information", padx=5, pady=5)
dateFrom = Label(booking, text="Book From:")
days = Label(booking, text="Days:")
dateTo = Label(booking, text="Book To:")
rooms = Label(booking, text="Rooms:")
car = Label(booking, text="Car:")
stayType = Label(booking, text="Stay Type:")
bookStatus = Label(booking, text="Booking Status:")
bHrRule = ttk.Separator(booking, orient=HORIZONTAL)
availableInfo = Label(booking, text="Click Check Availability to show the room types\n available between the selected dates.")
available = Button(booking, text="Check Availability")

#Column 1
dateFromEntry = Entry(booking)
dateFromEntry.insert(END, "DD/MM/YYYY")
daysEntry = Entry(booking)
dateToEntry = Entry(booking)
dateToEntry.insert(END, "DD/MM/YYYY")
roomsEntry = Entry(booking)
carEntry = OptionMenu(booking,carvar, "No", "Yes")
carEntry.config(width=15)
stayType = OptionMenu(booking,typevar, "Self Catering", "All-Inclusive")
stayType.config(width=15)
bookStatus = OptionMenu(booking,statusvar, "placeholder", "same")
bookStatus.config(width=15)

#Column 2
customer = LabelFrame(master, text="Customer fooDetails", padx=5, pady=5)
title = Label(customer, text="Book From:")

booking.grid(padx=(20,10), pady=(20,10), column=0, row=0, columnspan=2)
customer.grid(padx=(0,0), pady=(0,0), column=2, row=0, sticky="N")

# booking
dateFrom.grid(column=0, row=0, padx=blpadx, pady=(5,0),sticky=W)
dateFromEntry.grid(column=1, row=0, padx=bepadx, pady=(5,0))
dateTo.grid(column=0, row=2, padx=blpadx, pady=(5,0), sticky=W)
days.grid(column=0, row=1, padx=blpadx, pady=(5,0), sticky=W)
rooms.grid(column=0, row=3, padx=blpadx, pady=(5,0), sticky=W)
car.grid(column=0, row=4, padx=blpadx, pady=(5,0), sticky=W)
stayType.grid(column=0, row=5, padx=blpadx, pady=(5,0), sticky=W)
bookStatus.grid(column=0, row=6, padx=blpadx, pady=(5,0), sticky=W)
bHrRule.grid(column=0, row=7, columnspan=2, sticky=EW,pady=(15,15))
availableInfo.grid(column=0, row=8, padx=blpadx, pady=(0,10), columnspan=2)
available.grid(column=0, row=9, columnspan=2, pady=(0,15))

daysEntry.grid(column=1, row=1, padx=bepadx, pady=(5,0))
dateToEntry.grid(column=1, row=2, padx=bepadx, pady=(5,0))
roomsEntry.grid(column=1, row=3, padx=bepadx, pady=(5,0))
carEntry.grid(column=1, row=4, padx=bepadx, pady=(5,0))
stayType.grid(column=1, row=5, padx=bepadx, pady=(5,0))
bookStatus.grid(column=1, row=6, padx=bepadx, pady=(5,0))

# customer
title.grid(column=2, row=0, padx=blpadx, pady=(5,0))

rawDescription: Tkinter cannot place Label Frame at the top of a window


code:
def perimeter(side1, side2, side3):
    return float(side1 + side2 + side3)

rawDescription: how to make the result with type "float" in python ?

description: Make the result with type "float" in python


code:
def chkbox_checked(text):
    return lambda : j.append(text)

for i in x:
    c = Checkbutton(root, text=i, command=chkbox_checked(i))
    c.grid(sticky=W)

rawDescription: Python, Tkinter: Get Text from Checkbutton when Checked


code:
np.random.seed(1023)
a = np.random.random((6,5))
thresholds = np.percentile(a, 90, axis=1)
threshold_2d = np.vstack([thresholds]*a.shape[1]).T
a>threshold_2d
a>thresholds[:,np.newaxis]

rawDescription: filter numpy array with row-specific criteria

description: Filter numpy array with row-specific criteria


code:
self.lnchTab.setObjectName("myParentWidget");
self.lnchTab.setStyleSheet('QWidget#myParentWidget { background-color: #1d1d1d ; color: #f8f8f8}')

rawDescription: How to set a style sheet that only affects the parent in PyQT?

description: Set a style sheet that only affects the parent in PyQT


code:
def get_context_data(self, **kwargs):
    context = super(LoginView, self).get_context_data(**kwargs)
    context['next'] = self.request.REQUEST.get('next')
    return context

rawDescription: Redirect to next parameter in Django 1.5


code:
def reST2HTML( str ):
    parts = core.publish_parts(
    source = str,
    writer_name = 'html',
    settings_overrides={'report_level':'quiet'},
    )
    return parts['body_pre_docinfo'] + parts['fragment']

rawDescription: How Do I Suppress or Disable Warnings in reSTructuredText?


code:
punctuation_list = ['?',',','.'] # non exhaustive

for punctuation in punctuation_list:
   fname = fname.replace(punctuation, "")

blacklist = ["the", "to", "are", "and", "for", "this" ]

for word in blacklist:
   fname = fname.replace(" "+word+" ", " ") #replace StopWord preceded by a space and followed by a space with a space

rawDescription: Stop Words from python

description: Stop Words from python


code:
class FSerializer(serializers.Serializer):
    value = serializers.Field(source="f_value")
    metric = serializers.Field(source="f_metric")

class MyModelSerializer(serializers.ModelSerializer):
    somefield = serializers.Field()

    f = FSerializer(source="*")

rawDescription: How can I embed two fields together in serializer

description: Embed two fields together in serializer


code: x = next((v for v in (f(x) for x in a) if v), False)

rawDescription: Shortcut OR-chain applied on list

description: Shortcut OR-chain applied on list


code:
import glob
import csv

with open('somefile.out', 'wb') as out:
    writer = csv.writer(out, delimiter=',')
    for inf in glob.glob(r'E:\EE\EE\TocsData\CSAT\*.csv'):
        with open(inf, 'rb') as csv_input:
            reader = csv.reader(csv_input, delimiter=',', quotechar='|')
            for row in reader:
                writer.write(row)

rawDescription: Python read data from csv and write data to csv


code:
def feetToMeters(feet):
    meters = np.asarray(feet) * 0.3048
    return list(meters) if isinstance(feet, list) else meters

rawDescription: How to properly incorporate duck-typing to return original type?

description: Properly incorporate duck-typing to return original type


code:
print("Registration System")
print("Make sure their is atleast one name in register!")
input("Enter any key to continue ")
set1 = set()
set2 = set()
with open("register.txt", "r") as register:
    registers = [line.rstrip("\n") for line in register]
    for pop in registers:
        print(pop)
        choice = input(
            'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
        if choice == '1':
            set1.add(pop)
        elif choice == '2':
            set2.add(pop)

print(set1)
print(set2)

rawDescription: How do I put a specific user choice into a list from a loop

description: Put a specific user choice into a list from a loop


code:
# serversocket: One server socket listening on some port, has to be non-blocking
# all_sockets : List containing all connected client sockets
while True:
    readset = [serversocket]
    readset += all_sockets

    # Wait for sockets to be ready, with a 0.1 second timeout
    read_ready = select.select(readset, None, None, 0.1)

    # If the listening socket can be read, it means it has a new connection
    if serversocket in read_ready:
        new_connection = serversocket.accept()
        new_connection.setblocking(0);  # Make socket non-blocking
        all_sockets += [new_connection]
        read_ready.remove(serversocket) # To not loop over it below

    for socket in read_ready:
        # Read data from socket
        data = socket.recv(2048)
        for s in all_sockets:
            # Do not send to self
            if s != socket:
                s.send(data)

rawDescription: Passing from one socket to another

description: Passing from one socket to another


code:
image = np.arange(4*4*3).reshape((4, 4, 3))
image
image.flatten()

rawDescription: Convert a color image into single-row numpy array (r1, g1, b1; r2, g2, b2; ...)


code:
import Queue

class GUI:
    # ...

    def tb_click(self):
        self.progress()
        self.prog_bar.start()
        self.queue = Queue.Queue()
        ThreadedTask(self.queue).start()
        self.master.after(100, self.process_queue)

    def process_queue(self):
        try:
            msg = self.queue.get(0)
            # Show result of the task if needed
            self.prog_bar.stop()
        except Queue.Empty:
            self.master.after(100, self.process_queue)

class ThreadedTask(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        time.sleep(5)  # Simulate long running process
        self.queue.put("Task finished")

rawDescription: Tkinter: How to use threads to preventing main event loop from "freezing"


code:
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

driver.get('http://google.com')
element = driver.find_element_by_link_text('About')

ActionChains(driver) \
    .key_down(Keys.CONTROL) \
    .click(element) \
    .key_up(Keys.CONTROL) \
    .perform()

time.sleep(10) # Pause to allow you to inspect the browser.

driver.quit()

rawDescription: Send keys control + click selenium

description: Send keys control + click selenium


code:
#!/usr/bin/python
import gtk

class PyApp(gtk.Window):

    def __init__(self):
        super(PyApp, self).__init__()

        self.set_title("Calculator")
        self.set_size_request(250, 230)
        self.set_position(gtk.WIN_POS_CENTER)

        vbox = gtk.VBox(False, 2)
        table = gtk.Table(5, 4, True)

        table.attach(gtk.Button("Cls"), 0, 1, 0, 1)
        table.attach(gtk.Button("Bck"), 1, 2, 0, 1)
        table.attach(gtk.Label(), 2, 3, 0, 1)
        table.attach(gtk.Button("Close"), 3, 4, 0, 1)

        table.attach(gtk.Button("7"), 0, 1, 1, 2)
        table.attach(gtk.Button("8"), 1, 2, 1, 2)
        table.attach(gtk.Button("9"), 2, 3, 1, 2)
        table.attach(gtk.Button("/"), 3, 4, 1, 2)

        table.attach(gtk.Button("4"), 0, 1, 2, 3)
        table.attach(gtk.Button("5"), 1, 2, 2, 3)
        table.attach(gtk.Button("6"), 2, 3, 2, 3)
        table.attach(gtk.Button("*"), 3, 4, 2, 3)

        table.attach(gtk.Button("1"), 0, 1, 3, 4)
        table.attach(gtk.Button("2"), 1, 2, 3, 4)
        table.attach(gtk.Button("3"), 2, 3, 3, 4)
        table.attach(gtk.Button("-"), 3, 4, 3, 4)

        table.attach(gtk.Button("0"), 0, 1, 4, 5)
        table.attach(gtk.Button("."), 1, 2, 4, 5)
        table.attach(gtk.Button("="), 2, 3, 4, 5)
        table.attach(gtk.Button("+"), 3, 4, 4, 5)

        #vbox.pack_start(gtk.Entry(), False, False, 0)
        vbox.pack_end(table, True, True, 0)

        self.add(vbox)

        self.connect("destroy", gtk.main_quit)
        self.show_all()

PyApp()
gtk.main()

rawDescription: Python - how to make all the buttons aligned per row to look like button wall


code:
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as axes3d

np.random.seed(1)
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
N = 100
X, Y = np.meshgrid(np.arange(N), np.arange(N))
heights = np.sin(2*np.pi*np.sqrt(X**2+Y**2)/N)
ax.plot_surface(X, Y, heights, cmap=plt.get_cmap('jet'))
plt.show()

rawDescription: Draw a terrain with python?

description: Draw a terrain with python


code:
browser = webdriver.Firefox()
browser.set_page_load_timeout(30)

rawDescription: How to set timeout for PhantomJS?

description: Set timeout for PhantomJS


code:
def toUnix(path):
    return path.replace("\\", "/")

rawDescription: os.listdir etc fails on shared windows path (Python 2.5)

description: Os.listdir etc fails on shared windows path (Python 2.5)


code:
import collections
Point = collections.namedtuple('Rectangle', 'x y')
Point(1, 2)

rawDescription: Can the name and the reference of a named tuple be different?


code:
import pickle
import os

high_scores = {}

if os.path.isfile('highscores.pkl'):
    with open("highscores.pkl", "rb") as f:
        high_scores = pickle.load(f)
else:
    high_scores = {"Adam Smith": 65536, "John Doe": 10000}

new_score = (raw_input("Enter your name ").title(), int(raw_input("Enter your score ")))

if new_score[0] in high_scores:
    if new_score[1] > high_scores[new_score[0]]:
        high_scores[new_score[0]] = new_score[1]
else:
    high_scores[new_score[0]] = new_score[1]

with open("highscores.pkl","wb") as out:
    pickle.dump(high_scores, out)

print("-" * 80)
for name, score in high_scores.items():
    print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))

rawDescription: Saving scores with Pickle

description: Saving scores with Pickle


code:
def readline(lines):
    if lines in strings:
        return True
    else:
        return False

with open('output.txt', 'w+') as output_file:
    with open('input.txt', 'r') as input_file:
        for lines in input_file:
            if readline(lines) == True:
                output_file.write('True\n')
                print('true')
            else:
                output_file.write('False\n')
                print('false')

rawDescription: How to read each line in an input text file and determine if each line is true or false?

description: Read each line in an input text file and determine if each line is true or false


code:
from getpass import getpass

name = "user"
say = getpass(prompt="")
print (name, "said:",say)

rawDescription: Python - Clearing the user input?

description: Python - Clearing the user input


code:
import os,sys
import pygame as pg #lazy but responsible (avoid namespace flooding)

class Character:
    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.Surface(self.rect.size).convert()
        self.image.fill((255,0,0))
    def update(self,surface):
        if self.click:
            self.rect.center = pg.mouse.get_pos()
        surface.blit(self.image,self.rect)

def main(Surface,Player):
    game_event_loop(Player)
    Surface.fill(0)
    Player.update(Surface)

def game_event_loop(Player):
    for event in pg.event.get():
        if event.type == pg.MOUSEBUTTONDOWN:
            if Player.rect.collidepoint(event.pos):
                Player.click = True
        elif event.type == pg.MOUSEBUTTONUP:
            Player.click = False
        elif event.type == pg.QUIT:
            pg.quit(); sys.exit()

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pg.init()
    Screen = pg.display.set_mode((1000,600))
    MyClock = pg.time.Clock()
    MyPlayer = Character((0,0,150,150))
    MyPlayer.rect.center = Screen.get_rect().center
    while 1:
        main(Screen,MyPlayer)
        pg.display.update()
        MyClock.tick(60)

rawDescription: How to move image with mouse in pygame?

description: Move image with mouse in pygame


code:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

def peaks(x,y):
    return x * numpy.sin(y)

fig = plt.figure()
ax = fig.gca(projection='3d')
X = Y= numpy.arange(-3, 3, 0.1).tolist()
X, Y = numpy.meshgrid(X, Y)

Z = []
for i in range(len(X)):
    Z.append(peaks(X[i],Y[i]))

ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-8)
cset = ax.contour(X, Y, Z, zdir='x', offset=-8)
cset = ax.contour(X, Y, Z, zdir='y', offset=8)

ax.set_xlabel('X')
ax.set_xlim(-8, 8)
ax.set_ylabel('Y')
ax.set_ylim(-8, 8)
ax.set_zlabel('Z')
ax.set_zlim(-8, 8)

plt.show()

rawDescription: Matplotlib 3D plot - 2D format for input data?


code:
from dateutil import parser

class GermanParserInfo(parser.parserinfo):
    WEEKDAYS = [("Mo.", "Montag"),
                ("Di.", "Dienstag"),
                ("Mi.", "Mittwoch"),
                ("Do.", "Donnerstag"),
                ("Fr.", "Freitag"),
                ("Sa.", "Samstag"),
                ("So.", "Sonntag")]

s = 'Montag, 11. April 2016 19:35:57'
note_date = parser.parse(s, parserinfo=GermanParserInfo())

rawDescription: python - locale in dateutil / parser

description: Python - locale in dateutil / parser


code:
sm = difflib.SequenceMatcher(None, "university", "anniversary")
sm.ratio
sm.ratio()

rawDescription: python appending items in a dictionary with for loop

description: Python appending items in a dictionary with for loop


code:
PASSLIB_CONFIG = """
[passlib]
schemes =
    md5_crypt,
    django_salted_sha1, django_salted_md5,
    django_des_crypt, hex_md5,
    django_disabled

default = md5_crypt

deprecated = django_des_crypt, hex_md5
"""

rawDescription: Are MD5-hashed passwords from PHP's crypt() portable to the Django password field?


code:
import time
time.sleep(2)

rawDescription: Pause before retry connection in Python

description: Pause before retry connection in Python


code:
class A(object):
     pass

class B(A):
     pass

b = B()
c = b.__class__()

rawDescription: Python: Creating a new instance of itself from a base class (possibly via reflection?)


code:
def power(my_list):
    return [ x**3 for x in my_list ]

rawDescription: Raising elements of a list to a power

description: Raising elements of a list to a power


code:
start = 1
lines = ['Step' + str(start) + ':\n']
with open('file.txt','r') as inF:
    prevspace = -1
    for line in inF:
        lspaces = len(line) - len(line.lstrip())
        if lspaces > prevspace and prevspace != -1:
            lines.append('Step' + str(start+1) + ':\n')
            start = start + 1
            lines.append(line)
            prevspace = lspaces
        else:
            lines.append(line)
            prevspace = lspaces
    ifF.close()

with open('newfile.txt','w') as outF:
    for line in lines:
        outF.write(line)
    outF.flush()
    outF.close()

rawDescription: Python - Put new line into file at largest indent


code:
chars = words = lines = 0
with open(file_name, 'r') as in_file:
    for line in in_file:
        lines += 1
        words += len(line.split())
        chars += len(line)

rawDescription: counting characters and lines from a file python 2.7

description: Counting characters and lines from a file python 2.7


rawDescription: Django restapi passing parameter to read()


code:
import pdb
pdb.runcall(foo.bar, x)

rawDescription: Transfer Ipython namespace to ipdb

description: Transfer Ipython namespace to ipdb


rawDescription: Format and print list of tuples as one line


code:
class super(object):
    def __init__(self, klass, obj):
        self.klass = klass
        self.obj = obj
    def __getattr__(self, attrname):
        classes = iter(type(self.obj).__mro__)

        # search the MRO to find self.klass
        for klass in classes:
            if klass is self.klass:
                break

        # start searching for attrname at the next class after self.klass
        for klass in classes:
            if attrname in klass.__dict__:
                attr = klass.__dict__[attrname]
                break
        else:
            raise AttributeError

        # handle methods and other descriptors
        try:
            return attr.__get__(self.obj, type(self.obj))
        except AttributeError:
            return attr

rawDescription: How does Python's super() actually work, in the general case?


code:
import pandas as pd

df = pd.DataFrame([your_dict])
df = df.T
df.hist()

rawDescription: Plotting an histogram from a frequency list in a dictionary in Python


code:
result =  [{'FloatVal':'Floatm','StrVal':'Strm'},{'FloatVal':'Floatnb','StrVal':'Strnb'}]
result.append({'FloatVal':'Floatna','StrVal':'Strna'})
result
result.sort(key=lambda x: x['FloatVal'])
result

rawDescription: Insert dictionary in a list of dictionaries in order


rawDescription: Python get least significant digits from a float (without using string operations)


code:
class C(str):
    def __getattribute__(self, name):
        if name == '__class__':
            return str
        else:
            return super(C, self).__getattribute__(name)

c = C()
c.__class__

rawDescription: When where and how can i change the __class__ attr of an object in Python?


code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2016  Diego Torres Milano
Created on 2016-06-03 by Culebra v11.5.6
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

import unittest

from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase

TAG = 'CULEBRA'

class CulebraTests(CulebraTestCase):

    @classmethod
    def setUpClass(cls):
        cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
        cls.kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
        cls.options = {'start-activity': None, 'concertina': False, 'device-art': None, 'use-jar': False, 'multi-device': False, 'unit-test-class': True, 'save-screenshot': None, 'use-dictionary': False, 'glare': False, 'dictionary-keys-from': 'id', 'scale': 0.5, 'find-views-with-content-description': True, 'window': -1, 'orientation-locked': None, 'save-view-screenshots': None, 'find-views-by-id': True, 'log-actions': False, 'use-regexps': False, 'null-back-end': False, 'auto-regexps': None, 'do-not-verify-screen-dump': True, 'verbose-comments': False, 'gui': True, 'find-views-with-text': True, 'prepend-to-sys-path': False, 'install-apk': None, 'drop-shadow': False, 'output': '/home/diego/tmp/culebra/checbox.py', 'unit-test-method': None, 'interactive': False}
        cls.sleep = 5

    def setUp(self):
        super(CulebraTests, self).setUp()

    def tearDown(self):
        super(CulebraTests, self).tearDown()

    def preconditions(self):
        if not super(CulebraTests, self).preconditions():
            return False
        return True

    def testSomething(self):
        if not self.preconditions():
            self.fail('Preconditions failed')

        _s = CulebraTests.sleep
        _v = CulebraTests.verbose

        self.vc.dump(window=-1)
        checkbox = self.vc.findViewWithTextOrRaise(u'Vibrate')
        self.assertTrue(checkbox.isChecked())

if __name__ == '__main__':
    CulebraTests.main()

rawDescription: How to find out the state of a checkbox using AndroidViewClient

description: Find out the state of a checkbox using AndroidViewClient


code:
import os
random_string = os.urandom(string_length)

rawDescription: Random strings in Python 2.6 (Is this OK?)


code:
import planarity
import networkx as nx
# Example of the complete graph of 5 nodes, K5
G=nx.complete_graph(5)
# K5 is not planar
print(planarity.is_planar(G)) # False
# find forbidden Kuratowski subgraph
K=planarity.kuratowski_subgraph(G)
print(K.edges()) # K5 edges

rawDescription: Python Library for Boyer-Myrvold planarity test or Kuratowski subgraph identification


code:
import re

data = ['1682', 'Scream of Stone (Schrei aus Stein) (1991)', '08-Mar-1996']

def handleYear(matchobj):
    data.insert(2, matchobj.group(1))
    return ''

data[1] = re.sub(r'\s*\((\d+)\)$', handleYear, data[1])

rawDescription: Splitting string at special occurrence of character


code:
def goback(date, days):
    delta = datetime.timedelta( days=days + 2*(days//5) )
    if date.weekday() == 5:
        delta += datetime.timedelta(days=1)
    elif date.weekday() == 6:
        delta += datetime.timedelta(days=2)
    else:
        leftover = date.weekday() - days % 5
        if leftover < 0:
            delta += datetime.timedelta(days=2)
    return date - delta

rawDescription: How to calculate a date back from another date with a given number of work days

description: Calculate a date back from another date with a given number of work days


code:
formatted_text_to_add = 'Sample text'
with open('userfile', 'rb') as filename:
    filetext = filename.read()

newfiletext = formatted_text_to_add + '/n' + filetext
with open('userfile', 'wb') as filename:
    filename.write(newfiletext)

rawDescription: Simple way to add text at the beginning of a script (file) in Python


code:
from gi.repository import Gtk, GObject

class MyClass(object):
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

tree_store = Gtk.ListStore(GObject.TYPE_PYOBJECT)
tree_store.append([MyClass("foo", "bar", 15)])
tree_store.append([MyClass("baz", "qux", 100)])

def make_column(caption, getter):
    rend = Gtk.CellRendererText()
    col = Gtk.TreeViewColumn(caption, rend)
    def _set_cell_text(column, cell, model, it, ignored):
        obj = model.get_value(it, 0)
        cell.set_property('text', getter(obj))
    col.set_cell_data_func(rend, _set_cell_text)
    return col

view = Gtk.TreeView(tree_store)
view.append_column(make_column("First", lambda obj: obj.first))
view.append_column(make_column("Last", lambda obj: obj.last))
view.append_column(make_column("Age", lambda obj: '%d' % obj.age))

w = Gtk.Window()
w.add(view)
w.show_all()
Gtk.main()

rawDescription: GtkTreeView with multiple columns and GtkListStore with single custom type (in Python)


code:
if not isinstance(x, list):
    x = list(x)

rawDescription: Overhead of list() on a list

description: Overhead of list() on a list


code:
if n == 1:
  interval = range(0, 10**n)
else:
  interval = range(10**(n-1), 10**n)

rawDescription: More elegant way to form n-digit range of numbers


code:
import subprocess
subprocess.Popen(["command", "arg1", "arg2"])

rawDescription: Pygtk threading long command line process


code: df = pd.pivot_table(df, rows='WEEK_END_DATE', cols='TITLE_SHORT', values='SALES', aggfunc="sum")

rawDescription: Calculating Covariance in Pandas Time Series


code:
import msvcrt, time
i = 0
while True:
    i = i + 1
    if msvcrt.kbhit():
        if msvcrt.getwche() == '\r':
            break
    time.sleep(0.1)
print(i)

rawDescription: Python - Infinite while loop, break on user input


code:
print("Please enter a number")
number = int(input())

def addTwo(number):
    newNumber = number + 2
    print("Your number plus two is ", str(newNumber))

addTwo(number)

rawDescription: How can I use existing variables and their values as parameters for a function (Python)?

description: Use existing variables and their values as parameters for a function (Python)


code: getattr(getattr(Scripts, gamename), gamename)(version, size, download)

rawDescription: Calling function using string and module name


code:
from django import forms

class ExampleForm(forms.Form):
  name = forms.CharField(label='name', widget=forms.TextInput(attrs={'placeholder': 'Please enter your name'}))

rawDescription: Django: How to get Form field descriptions to show inside the text/entry box and not outside of it? (pic inside)


code:
class Example(Enum):
    this = 1
    that = 2
    dupe = 1
    those = 3

print(len(Example))  # duplicates are not counted
# 3

print(list(Example))
# [<Example.this: 1>, <Example.that: 2>, <Example.those: 3>]

print(Example['this'])
# Example.this

print(Example['dupe'])
# Example.this

print(Example(1))
# Example.this

rawDescription: Is there a dedicated way to get the number of items in a python `Enum`?


code:
cities = [w.split(',')[0] for w in my_list]
term = "de"
results = [city for city in cities if term in city.lower()]

rawDescription: How to find string in item of list python

description: Find string in item of list python


code:
start = 0
end = 300
step = 100
[[1 + x, step + x] for x in range(start, end, step)]

rawDescription: How to create a list of lists in Python

description: Create a list of lists in Python


code:
# Python 3.4
@asyncio.coroutine
def some_coroutine(*some_args, loop=None):
    while True:
        [...]
        result = yield from loop.run_in_executor(
            None,  # Use the default executor
            some_blocking_io_call,
            *some_args)
        [...]

# Python 3.5
async def some_coroutine(*some_args, loop=None):
    while True:
        [...]
        result = await loop.run_in_executor(
            None,  # Use the default executor
            some_blocking_io_call,
            *some_args)
        [...]

loop = asyncio.get_event_loop()
coro = some_coroutine(*some_arguments, loop=loop)
loop.run_until_complete(coro)

rawDescription: python asyncio run_forever or while True

description: Python asyncio run_forever or while True


code:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# an Engine, which the Session will use for connection
# resources
some_engine = create_engine('postgresql://scott:tiger@localhost/')

# create a configured "Session" class
Session = sessionmaker(bind=some_engine)

# create a Session
session = Session()

@celery.task
def mytask(data):
  session.commit(data)

rawDescription: Celery sqlalchemy session

description: Celery sqlalchemy session


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title = title, size=(500, 400))
        self.panel = wx.Panel(self)
        self.label1 = wx.StaticText(self.panel,wx.ID_ANY,"Select the Input File")
        self.fileCtrl = wx.FilePickerCtrl(self.panel, message="Select the input file name")
        self.selectedfile = wx.TextCtrl(self.panel,wx.ID_ANY,"None",size=(490,25))
        self.fileCtrl.Bind(wx.EVT_FILEPICKER_CHANGED, self.Selected)
        row1 = wx.BoxSizer(wx.VERTICAL)
        row1.Add(self.label1,0,wx.TOP | wx.RIGHT,5)
        row1.Add(self.fileCtrl)
        row1.Add(self.selectedfile)
        self.panel.SetSizer(row1)
        self.Show()
    def Selected(self, event):
        self.selectedfile.SetValue(self.fileCtrl.GetPath())
app = wx.App(False)
win = MainWindow(None, "File selector")
app.MainLoop()

rawDescription: Change FilePickerCtrl box width (wxPython)


code:
import logging
from logging.handlers import RotatingFileHandler
import os

def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG):
    logdir = os.path.abspath(logdir)

    if not os.path.exists(logdir):
        os.mkdir(logdir)

    log = logging.getLogger('stumbler')
    log.setLevel(loglevel)

    log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s")

    if txtlog:
        txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5)
        txt_handler.doRollover()
        txt_handler.setFormatter(log_formatter)
        log.addHandler(txt_handler)
        log.info("Logger initialised.")

    if scrnlog:
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(log_formatter)
        log.addHandler(console_handler)

setup_logging('/tmp/logs')
corelog = logging.getLogger('stumbler.core')
corelog.debug("Messages and rainbows...")

rawDescription: Python logging over multiple files

description: Python logging over multiple files


code:
links = self.br.find_elements_by_xpath("//*[@class='image']/a")
if not links:
    links = self.br.find_elements_by_xpath("//*[@class='newPrice']/a")
for products in links:
    self.urls.append(products.get_attribute("href"))

rawDescription: Find elements by XPath with fallback

description: Find elements by XPath with fallback


code: [all_items[1:] for all_items in sorted(x)]

rawDescription: Unpacking "the rest" of the elements in list comprehension - python3to2


code:
x
x.view('<f4').reshape(len(x), -1)

rawDescription: Converting one-dimensional structured array to 2D numpy array


code:
def main():
    wn = turtle.Screen()  # creates a graphics window
    alex = turtle.Turtle()  # create a turtle named alex
    alex.forward(150)  # tell alex to move forward by 150 units
    alex.left(90)  # turn by 90 degrees
    alex.forward(75)  # complete the second side of a rectangle

if __name__ == "__main__":
    main()

rawDescription: Drawing with turtle(python) using PyCharm


code:
def home(request, finhall_id, slug):
    qs = Finhall.objects.all()

    try:
        finhall = qs.get(id=finhall_id, slug=slug)
    except Finhall.DoesNotExist:
        finhall = None

    if finhall:
        similar_finhalls = qs.filter(finhall.state)
    else:
        similar_finhalls = Finhall.objects.none()

    # other stuff

    return render_to_response('home.html', {
        'finhall': finhall,
        'similar_finhalls': similar_finhalls
    },context_instance=RequestContext(request))

rawDescription: Related Objects Not Displaying

description: Related Objects Not Displaying


rawDescription: How to cat string with list objects?

description: Cat string with list objects


rawDescription: In Python 2.4, how can I strip out characters after ';'?


code:
import os, mypackage
template = os.path.join(mypackage.__path__[0], 'templates', 'temp_file')

rawDescription: Python: How to read a (static) file from inside a package?


code: my_handler = TimedRotatingFileHandler(LOG_PATH, when='midnight', backupCount=20)

rawDescription: Rotating logs using RotatingFileHandler by date in Python


code: del arrayName[2]

rawDescription: Remove array item and updating array index


rawDescription: Integer division: is a//b == int(a/b) true for all integers a,b?


code:
times_list=[]
my_variable = 0
while True:
    frame_difference = current_frame - first_frame
    # Case 1:
    if difference_frame == 0 and my_variable == 0:
        continue
    # Case 2:
    if difference_frame != 0 and my_variable == 1:
        continue
    # Case 3:
    if difference_frame != 0 and my_variable == 0:
        my_variable = 1
        # Your comments say this is the only instant you are interested in
        times_list.append(datetime.datetime.now())
    # Case 4:
    if difference_frame == 0 and my_variable == 1:
        my_variable = 0

rawDescription: Pythonic way to record changes inside a while loop


code:
import unittest

from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from sqlalchemy.orm import contains_eager, joinedload
from sqlalchemy.orm import relationship

#Create and engine and get the metadata
Base = declarative_base()
engine = create_engine('mssql://user:pass@Northwind', echo=True)
metadata = MetaData(bind=engine)

#Reflect each database table we need to use, using metadata
class Customer(Base):
    __table__ = Table('Customers', metadata, autoload=True)
    orders = relationship("Order", backref="customer")

class Shipper(Base):
    __table__ = Table('Shippers', metadata, autoload=True)
    orders = relationship("Order", backref="shipper")

class Employee(Base):
    __table__ = Table('Employees', metadata, autoload=True)
#    orders = relationship("Order", backref="employee")
    territories = relationship('Territory', secondary=Table('Employeeterritories', metadata, autoload=True))

class Territory(Base):
    __table__ = Table('Territories', metadata, autoload=True)
    region = relationship('Region', backref='territories')

class Region(Base):
    __table__ = Table('Region', metadata, autoload=True)

class Order(Base):
    __table__ = Table('Orders', metadata, autoload=True)
    products = relationship('Product', secondary=Table('Order Details', metadata, autoload=True))
    employee = relationship('Employee', backref='orders')

class Product(Base):
    __table__ = Table('Products', metadata, autoload=True)
    supplier = relationship('Supplier', backref='products')
    category = relationship('Category', backref='products')

class Supplier(Base):
    __table__ = Table('Suppliers', metadata, autoload=True)

class Category(Base):
    __table__ = Table('Categories', metadata, autoload=True)

class Test(unittest.TestCase):

    def setUp(self):
        #Create a session to use the tables
        self.session = create_session(bind=engine)

    def tearDown(self):
        self.session.close()

    def test_withJoins(self):
        q = self.session.query(Customer)
        q = q.join(Order)
        q = q.join(Shipper)
        q = q.filter(Customer.CustomerID =='ALFKI')
        q = q.filter(Order.OrderID=='10643')
        q = q.filter(Shipper.ShipperID=='1')
        q = q.options(contains_eager(Customer.orders, Order.shipper))
        res = q.all()
        cus = res[0]
        ord = cus.orders[0]
        shi = ord.shipper
        self.assertEqual(shi.Phone, '(503) 555-9831')

rawDescription: How to automatically reflect database to sqlalchemy declarative?

description: Automatically reflect database to sqlalchemy declarative


code:
class MyFormatter(string.Formatter):
    """This is my formatter which is better than the standard one."""
    # customization here ...

MyFormatter().format(format_string, *args, **kwargs)

rawDescription: How can I override the default string formatter in python?

description: Override the default string formatter in python


code:
import ctypes
mv = ctypes.c_int32(1732584193)
mv.value <<= 5
mv
bin(mv.value)

rawDescription: Python left shift (sign issue)

description: Python left shift (sign issue)


code:
v = v.reshape(size, size)
vnew = vnew.reshape(size, size)
unchangeableflag = unchangeableflag.reshape(size, size)
average = v[1:-1, 2:]
average += v[1:-1, :-2]
average += v[2:, 1:-1]
average += v[-2:, 1:-1]
average /= 4.0
vnew[1:-1, 1:-1][unchangeableflag[1:-1, 1:-1] == 0] = average

rawDescription: Speed up a program that calculate the average of the neighbors in a huge array


code: input_widget.bind("<Return>", lambda event: function())

rawDescription: How to get an entry.bind and a button do the same thing?

description: Get an entry.bind and a button do the same thing


code:
import Tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(bg="red", height=100, width=100)
canvas.pack(anchor=tk.NW)

button = tk.Button(text="button")
button.pack(side=tk.RIGHT, anchor=tk.SE)

root.mainloop()

rawDescription: Positionning a canvas and a button in Tkinter


code:
def get_bill_amount():
    while True: # repeat until you hit a break statement or a return
        billAmnt = raw_input('How much is this bill?')
        try:
            amount =  float(billAmnt)
            return amount # exit the loop.
        except ValueError:
            pass
            #Since I've gotten to the end of the while block, start again from the top!

rawDescription: How can I validate user-input in python?

description: Validate user-input in python


code:
import win32gui
GetPixel(GetDC(WindowFromPoint( (XPos,YPos) )), XPos , YPos )

rawDescription: Color picking from given coordinates

description: Color picking from given coordinates


code:
p2 = Popen(command2, stdin=PIPE)
p1 = Popen(command1, stdout=p2.stdin)
p1.wait()
p2.stdin.close()
p2.wait()

rawDescription: Running piped subprocesses gives different result when the launch order changes?


code:
class User(models.Model):
    ...
    pets = models.ManyToManyField(Pet, through='UserPet')

class UserPet(models.Model):
    user = models.ForeignKey(User)
    pet = models.ForeignKey(Pet)
    since = models.DateTimeField(auto_now_add=True)

rawDescription: How to describe this relationship in django's model?

description: Describe this relationship in django's model


code:
for i in range(len(phoneList)):
    if float(lastDue[i]) > 850:
        extra = "**"
    elif float(lastDue[i]) < 850 and int(number[i]) > 350:
        extra = "++"
    else:
        extra = ""
    print("|{}|{}|{}|{}|{}".format(formattedPhoneList[i],namesList[i],number[i], lastDue[i], extra))

rawDescription: Python - printing on the same line after using format string


code:
var1=2
var2=4
var3=float(str(var1)+"."+str(var2))
var3

rawDescription: merge two integer variables in a single float in python

description: Merge two integer variables in a single float in python


code:
class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

j = '{"y": [2, 3, {"a": 55, "b": 66}], "x": 4}'
aa = json.loads(j, object_hook=AttrDict)

rawDescription: using JSON keys as python attributes in nested JSON

description: Using JSON keys as python attributes in nested JSON


code:
d = {}
with open("numbers.txt") as numbers:
    for line in numbers:
        pairs = line.split()
        for i in range(0,len(pairs),2):
           d[pairs[i]] = int(pairs[i+1])
    print(d)

rawDescription: using a dictionary with a file

description: Using a dictionary with a file


code: sources.sort(key=lambda source: source.quality - source.distance, reverse=true)

rawDescription: Weighted Search and Sort Python

description: Weighted Search and Sort Python


code:
import re
bad_words = ['bw1', 'bw2', ... ]

my_expression = '|'.join(re.escape(word) for word in bad_words)
if re.search(my_expression, comment.body):
    do_something()

rawDescription: How to find regexp patterns in a Python list?

description: Find regexp patterns in a Python list


rawDescription: Python idiom for creating a given number of elements in a list


code:
import kate
from kate import documentManager as dm
from PyKDE4.kdecore import KUrl

text = "Lorem ipsum dolor sit amet"

# Open a new empty document
doc = dm.openUrl(KUrl())
# Open an existing file
doc = dm.openUrl(KUrl('/path/to/file.ext'))

# Activate view
kate.application.activeMainWindow().activateView(doc)

# Insert text
pos = kate.activeView().cursorPosition()
doc.insertText(pos, text)

rawDescription: How do I create a new file view in Kate with Python/Pâté?

description: Create a new file view in Kate with Python/Pâté


code:
from Tkinter import *

class App:
    def __init__(self, master):
        self.master = master

        # Gui Creation Block
        master.title("LumenScriptor")
        frame = Frame(master, bd=2, relief=SUNKEN)
        frame.pack()

        self.top = Frame(frame, bg="red", height=150, width=700, relief=SUNKEN, borderwidth=2)
        self.left = Frame(frame, bg="yellow", height=400, width=200, relief=SUNKEN, borderwidth=2)
        self.right = Frame(frame, bg="blue", height=400, width=500, relief=SUNKEN, borderwidth=2)

        self.top.grid(row=0, column=1, columnspan=2)
        self.left.grid(row=1, column=1)
        self.right.grid(row=1, column=2)

        self.top.pack_propagate(0)
        self.left.pack_propagate(0)
        self.right.pack_propagate(0)

        # Sample Label
        self.lbl = Label(frame, text="Log file location")
        self.lbl.grid(row=0, column=0)

        # Sample Label
        self.lbl1 = Label(self.top, text="Top" )
        self.lbl1.pack()

        #Sample Label
        self.lbl2 = Label(self.left, text="Left" )
        self.lbl2.pack()

        # Sample Label
        self.lbl3 = Label(self.right, text="Right" )
        self.lbl3.pack()

# Run the programs
root = Tk()
app = App(root)

root.mainloop()

rawDescription: Why does this simple Python TK Gui progam take 100% CPU


code:
def isPrime(n):
 if n < 2:
  return False
 for i in range(2, n):
  if not n % i:
     return False
 return True

string = input()
primes = []

for i in range(10):
    if isPrime(int(string.replace("_", str(i)))):
        primes.append(i)

for num in primes:
    print(num)

rawDescription: Find prime combinations using Python strings


code:
panel1 = Label(root, border=0, image=p)
panel2 = Label(root, border=0, image=p)

rawDescription: Two Tkinter Images

description: Two Tkinter Images


code:
from tkinter import Tk, Button
root = Tk()
def click():
    print(root.winfo_x(), root.winfo_y())
Button(text="Get position", command=click).grid()
root.mainloop()

rawDescription: Tkinter: How can I determine the position of a Toplevel?


code:
import itertools
lst = [1,1,1]
for xs in itertools.product([1,-1], repeat=len(lst)):
    print([a*b for a,b in zip(lst, xs)])

rawDescription: all possible phase combination

description: All possible phase combination


code:
class Wrapper(object):
    def __init__(self):
        self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]

    def __getattr__(self, n):
        meth = getattr(Wrapped, n)
        def caller():
            results = [meth(w) for w in self.ws]
            sum_ = sum(results,0.0)
            average = sum_/len(self.ws)
            return average
        return caller

rawDescription: python, wrapping class returning the average of the wrapped members

description: Python, wrapping class returning the average of the wrapped members


rawDescription: Numpy - square root of -1 leaves a small real part


code:
from tkinter import *

class Class1(Frame):

    def nv(self,x):
        self.vent = Toplevel(self.master)
        self.app = Class2(self.vent,x)

    def __init__(self,master):
        Frame.__init__(self,master)
        self.master = master
        self.btn = Button(self, text="example", command=lambda: self.nv(1))
        self.btn.pack()
        self.pack()

class Class2(Frame):

    def __init__(self, master, x):
        Frame.__init__(self,master)
        self.master=master
        self.frame=Frame(self.master)
        self.x_text = Label(self, text=str(x))
        self.x_text.pack()
        self.pack()

root = Tk()
marco = Frame(root)
marco.pack()
lf = Class1(marco)
root.mainloop()

rawDescription: Passing class values to another class using Tkinter in Python 3.5


code:
from sqlalchemy.sql.expression import null
db.session.query(models.User.id, null())

rawDescription: adding a null column to s selection in sqlalchemy

description: Adding a null column to s selection in sqlalchemy


code:
s = 'Website is: http://www.somesite.com '
re.findall('Website is:\s+(\S+)', s)

rawDescription: Python Regular Expression for Extrating URL


code:
import sys, os

def find_venv():
  python = sys.executable
  for i in xrange(10):
    if not os.path.islink(python):
      break
    python = os.path.realpath(python)
  return os.path.dirname(os.path.dirname(python))

if not os.environ.has_key("VIRTUAL_ENV"):
  os.environ["VIRTUAL_ENV"] = find_venv()

rawDescription: Mercurial update hook not activating Python virtual environment


code:
PLUGIN_NAME = "Find transliterated tracklisting relationships"
PLUGIN_AUTHOR = "Wieland Hoffmann"
PLUGIN_DESCRIPTION = "I'm too lazy"
PLUGIN_VERSION = "0.1"
PLUGIN_API_VERSIONS = ["1.0"]

from picard.metadata import register_album_metadata_processor
from picard import log

# The relationship type id for transliterations from
# https://musicbrainz.org/relationship/fc399d47-23a7-4c28-bfcf-0607a562b644
TRANS_REL_UUID = "fc399d47-23a7-4c28-bfcf-0607a562b644"

@register_album_metadata_processor
def find_transliteration_relationship(album, metadata, release):
    if "relation_list" in release.children:
        for rel in release.relation_list:
            if rel.relation[0].type_id == TRANS_REL_UUID:
                log.info("Found a transliterated tracklisting relationship")
                for release in rel.relation[0].release:
                    log.info("Its target is https://musicbrainz.org/release/%s",
                             release.id)

rawDescription: How to compare two releases in a MusicBrainz Picard plugin?

description: Compare two releases in a MusicBrainz Picard plugin


code:
for line in shivas_file:
    print('\t'.join(line.split(",")))

rawDescription: How do i print a text file

description: Print a text file


code:
import cv2
import numpy as np

img = cv2.imread('sofsk.png',0)
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)

ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
done = False

while( not done):
    eroded = cv2.erode(img,element)
    temp = cv2.dilate(eroded,element)
    temp = cv2.subtract(img,temp)
    skel = cv2.bitwise_or(skel,temp)
    img = eroded.copy()

    zeros = size - cv2.countNonZero(img)
    if zeros==size:
        done = True

cv2.imshow("skel",skel)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: is there any build-in function can do skeletonization in openCV?

description: Is there any build-in function can do skeletonization in openCV


code:
import random

class ContextFree(object):
  def __init__(self):
    self.rules = {}
    # grab any instancemethod to get an instance of the instancemethod class
    self.instancemethod = type(self.add_rule)
    self.max_depth = 100
    self.depth = 0

  def add_rule(self, func, prob=1):
    rule_name = func.__name__

    if not rule_name in self.rules:
      self.rules[rule_name] = { 'funcs' : [], 'total' : 0 }

    total = self.rules[rule_name]['total']
    self.rules[rule_name]['funcs'].append([range(total,(prob+total)), func])
    self.rules[rule_name]['total'] += prob

    def augmented_func(self, options={}):
      if not self.depth >= self.max_depth:
        self.depth += 1
        pick = self.determine_rule(rule_name)
        print('Generation', self.depth)
        pick(self)

    self.__dict__[rule_name] = self.instancemethod(augmented_func, self)

  def determine_rule(self, rule_name):
    rule = self.rules[rule_name]
    winning_number = random.randrange(0, self.rules[rule_name]['total'])
    for func in rule['funcs']:
      if winning_number in func[0]:
        return func[1]

cf = ContextFree()

def box(self):
  print('Rule for box1')
  self.box()

cf.add_rule(box)

def box(self):
  print('Rule for box2')
  self.box()

cf.add_rule(box)

cf.box()

# Output:
## Generation 1
## Rule for box2
## Generation 2
## Rule for box2
## Generation 3
## Rule for box1
## Generation 4
## Rule for box2
## Generation 5
## Rule for box1
## Generation 6
## Rule for box2
## Generation 7
## Rule for box2
## Generation 8
## Rule for box1
## Generation 9
## Rule for box2
## Generation 10
## Rule for box2
## Generation 11
## Rule for box1
## Generation 12
## Rule for box1
## Generation 13
## Rule for box1
## Generation 14
## Rule for box1
## Generation 15
## Rule for box2
## Generation 16
## Rule for box1
## Generation 17
## Rule for box1
## Generation 18
## Rule for box1
## Generation 19
## Rule for box1
## Generation 20
## Rule for box1
## Generation 21
## Rule for box2
## Generation 22
## Rule for box2
## Generation 23
## Rule for box1
## Generation 24
## Rule for box2
## Generation 25
## Rule for box1
## Generation 26
## Rule for box2
## Generation 27
## Rule for box2
## Generation 28
## Rule for box1
## Generation 29
## Rule for box2
## Generation 30
## Rule for box2
## Generation 31
## Rule for box2
## Generation 32
## Rule for box2
## Generation 33
## Rule for box2
## Generation 34
## Rule for box1
## Generation 35
## Rule for box2
## Generation 36
## Rule for box1
## Generation 37
## Rule for box1
## Generation 38
## Rule for box1
## Generation 39
## Rule for box1
## Generation 40
## Rule for box2
## Generation 41
## Rule for box1
## Generation 42
## Rule for box1
## Generation 43
## Rule for box1
## Generation 44
## Rule for box1
## Generation 45
## Rule for box2
## Generation 46
## Rule for box1
## Generation 47
## Rule for box2
## Generation 48
## Rule for box1
## Generation 49
## Rule for box2
## Generation 50
## Rule for box1
## Generation 51
## Rule for box1
## Generation 52
## Rule for box1
## Generation 53
## Rule for box2
## Generation 54
## Rule for box2
## Generation 55
## Rule for box2
## Generation 56
## Rule for box2
## Generation 57
## Rule for box2
## Generation 58
## Rule for box1
## Generation 59
## Rule for box1
## Generation 60
## Rule for box1
## Generation 61
## Rule for box2
## Generation 62
## Rule for box2
## Generation 63
## Rule for box2
## Generation 64
## Rule for box1
## Generation 65
## Rule for box2
## Generation 66
## Rule for box2
## Generation 67
## Rule for box2
## Generation 68
## Rule for box2
## Generation 69
## Rule for box2
## Generation 70
## Rule for box1
## Generation 71
## Rule for box2
## Generation 72
## Rule for box2
## Generation 73
## Rule for box2
## Generation 74
## Rule for box1
## Generation 75
## Rule for box2
## Generation 76
## Rule for box1
## Generation 77
## Rule for box1
## Generation 78
## Rule for box2
## Generation 79
## Rule for box1
## Generation 80
## Rule for box2
## Generation 81
## Rule for box1
## Generation 82
## Rule for box1
## Generation 83
## Rule for box1
## Generation 84
## Rule for box1
## Generation 85
## Rule for box2
## Generation 86
## Rule for box1
## Generation 87
## Rule for box1
## Generation 88
## Rule for box2
## Generation 89
## Rule for box2
## Generation 90
## Rule for box1
## Generation 91
## Rule for box1
## Generation 92
## Rule for box1
## Generation 93
## Rule for box1
## Generation 94
## Rule for box1
## Generation 95
## Rule for box1
## Generation 96
## Rule for box2
## Generation 97
## Rule for box1
## Generation 98
## Rule for box2
## Generation 99
## Rule for box1
## Generation 100
## Rule for box2

rawDescription: How to express a context free design grammar as an internal DSL in Python?

description: Express a context free design grammar as an internal DSL in Python


code: conditions['tag.slug'] = { '$in': tags }

rawDescription: How to use AND condtion in mongokit when a key has multiple values

description: Use AND condtion in mongokit when a key has multiple values


code: data = np.atleast_1d(data)

rawDescription: numpy genfromtxt collapse recarray when data file has only one row

description: Numpy genfromtxt collapse recarray when data file has only one row


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.scale = tk.Scale(self, orient="horizontal",
                              from_=0, to=600,
                              showvalue=False,
                              command=self._on_scale)
        self.scale_label = tk.Label(self, text="")
        self.scale.pack(side="top", fill="x")
        self.scale_label.pack(side="top")

    def _on_scale(self, value):
        value = int(value)
        minutes = value/60
        seconds = value%60
        self.scale_label.configure(text="%2.2d:%2.2d" % (minutes, seconds))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True);
    root.mainloop()

rawDescription: Dynamically reformat tkinter scale value python 2.7


code:
data = urllib.urlencode([
           ("remote_id[]", 1),
           ("dimension_id[]", 1),
           ("metric[]",metric1),
           ("remote_id[]", 1),
           ("dimension_id[]", 2),
           ("metric[]",metric2)
        ])

rawDescription: POSTing a multidimensional array from Python


rawDescription: django filter with list of values

description: Django filter with list of values


code:
import timeit
import matplotlib.pyplot as plt
import csv

index_element_1=0
index_element_2=2

def create_csv(num_records):
    '''Creates a test CSV'''
    a=open('test.csv','wb')
    a.write("10,20,30,40,50\n"*num_records)
    a.close()

def read_csv(filename):
    '''Returns iterator'''
    cr = csv.reader(open(filename,"rb"))
    return cr

def convert_to_list_method():
    global csv_iterator
    csv_list=list(csv_iterator)
    length_list=len(csv_list)
    x=[None]*length_list
    y=[None]*length_list
    for i in range(0,length_list):
        x[i]=csv_list[index_element_1]
        y[i]=csv_list[index_element_2]
    return [x,y]

def iterate_and_append_method():
    global csv_iterator
    x=[]
    y=[]
    for row in csv_iterator:
        x.append(row[index_element_1])
        y.append(row[index_element_2])
    return [x,y]

CSV_SIZE=range(10000,1010000,10000)
time_convert_to_list=[0]*len(CSV_SIZE)
time_iterate=[0]*len(CSV_SIZE)
count=0

for csv_size in CSV_SIZE:
    create_csv(csv_size)
    global csv_iterator
    csv_iterator=read_csv('test.csv')
    time_convert_to_list[count]=timeit.timeit("convert_to_list_method()", setup="from __main__ import *",number=1)
    csv_iterator=read_csv('test.csv')
    time_iterate[count]=timeit.timeit("iterate_and_append_method()", setup="from __main__ import *",number=1)
    count=count+1

plt.xlabel('CSV Size')
plt.ylabel('Time (s)')
plt.plot(CSV_SIZE,time_convert_to_list,label='Convert to List')
plt.plot(CSV_SIZE,time_iterate,label='Iterate')
plt.legend()
plt.show()

rawDescription: Python performance comparison: Convert an Iterator to List and adding elements by index (after preallocating) vs Append while iterating


code: vowel_indices = [idx for idx, ch in enumerate(your_string) if ch.lower() in 'aeiou']

rawDescription: Attempting to return indices of vowels in a string


code:
class MySpider(CrawlSpider):

    def start_requests(self):
        ...
        yield Request(url1, meta={'category': 'cat1'}, callback=self.parse)
        yield Request(url2, meta={'category': 'cat2'}, callback=self.parse)
        ...

    def parse(self, response):
        category = response.meta['category']
        ...

rawDescription: Python Scrapy: passing properties into parser


code:
from numpy import abs, diag, dot, zeros
from numpy.linalg import lstsq, inv, norm

def irls(A, b, p= 1):
    """Solve least squares problem min ||x||_p s.t. Ax= b."""
    x, p, e= zeros((A.shape[1], 1)), p/ 2.- 1, 1.
    xp= lstsq(A, b)[0]
    for k in xrange(1000):
        if e< 1e-6: break
        Q= dot(diag(1./ (xp** 2+ e)** p), A.T)
        x= dot(dot(Q, inv(dot(A, Q))), b)
        x[abs(x)< 1e-1]= 0
        if norm(x- xp)< 1e-2* e** .5: e*= 1e-1
        xp= x
    return k, x.round()

rawDescription: solve rectangular matrix in python to get solution with arbitrary parameters

description: Solve rectangular matrix in python to get solution with arbitrary parameters


code:
def network_name(instance):
    return '<img src="%s" />' % instance.network.image_url
network_name.allow_tags = True

rawDescription: How to keep Django from escaping HTML in ModelAdmin

description: Keep Django from escaping HTML in ModelAdmin


code:
from subprocess import PIPE,Popen
from shlex import split

p1 = Popen(split("awk /string1\/parameters\/string2 RS=myfile"), stdout=PIPE)
p2 = Popen(["grep", "Value"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
p3 = Popen(split("""sed 's/.*"\(.*\)"[^"]*$/\1/'"""), stdin=p2.stdout, stdout=PIPE)
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.

output = p3.communicate()[0]

rawDescription: python - need help calling awk and sed in python

description: Python - need help calling awk and sed in python


code:
import itertools
import os
import subprocess
import sys
import time

def installing():
    null = open(os.devnull, 'wb')
    p = subprocess.Popen('echo blah && sleep 5', shell=True, stdout=null)
    #p = subprocess.Popen('sudo sh installer.sh', shell=True, stdout=null)
    return p, null

def spin(p_stdout):
    p, stdout = p_stdout
    syms = itertools.cycle(['\\', '|', '/', '-'])
    sys.stdout.write('processing....')
    sys.stdout.flush()
    while p.poll() is None:
        sys.stdout.write('\b'+next(syms))
        sys.stdout.flush()
        time.sleep(0.1)
    p.wait()
    stdout.close()

spin(installing())

rawDescription: Python Do While sh functions

description: Python Do While sh functions


code:
import collections
fruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']
c=collections.Counter(fruit)
print(c.most_common(1))
# [('apple', 4)]

rawDescription: How to get the most represented object from an array

description: Get the most represented object from an array


rawDescription: Get list in nested dictionaries

description: Get list in nested dictionaries


code:
from selenium import webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.implicitly_wait(2)
alert = driver.switch_to_alert()

driver.get("https://calendar page css")

while(True):
   try:
      driver.find_element_by_xpath('//*[@title="Day enabled"]').click()
      driver.refresh()
      alert.accept()
      break
   except Exception as e:
      driver.refresh()
      continue

rawDescription: selenium webdriver refreshing and verify if an attribute change

description: Selenium webdriver refreshing and verify if an attribute change


code:
from collections import defaultdict

# Create zero-filled sim1, sim2, sim3 arrays to avoid append() overhead
len_ = len(db[2]) - 2
for _ in range(3):
    db.append([0] * len_)

# Create dictionary, containing d['word'] = [count, [indexes]]
# Do just one full iteration, and make good use of it by calculating
# sim1 (as 'count') and storing an array of number indexes for each word,
# allowing for a very efficient loop coming up...
d = defaultdict(lambda: [0, []])
for index, word in enumerate(db[2]):
    if index < len_:
        # Accumulate sim1
        d[word][0] += 1
    # Store all db[2] indexes where this word exists
    d[word][1].append(index)

# Now loop only through words which occur more than once (smaller loop)
for word, (count, indexes) in d.iteritems():
    if count > 1:
        # Place the sim1 values into the db[3] array
        for i in indexes:
            if i < len_:
                db[3][i] = count - 1
                # Look for sim2 matches by using index numbers
                next_word = db[2][i+1]
                for next_word_index in d[next_word][1]:
                    if next_word_index - 1 != i and next_word_index - 1 in indexes:
                        # Accumulate sim2 value in db[4]
                        db[4][i] += 1
                        # Look for sim3 matches
                        third_word = db[2][i+2]
                        if third_word == db[2][next_word_index + 1]:
                            # Accumulate sim3 value in db[5]
                            db[5][i] += 1

rawDescription: Find string matches count in list using Python


code:
def build_grocery_list(grocery_file):
    food_list = []
    inner_list = []
    for line in grocery_file:
        if line.strip() == "":
            food_list.append(inner_list)
            inner_list = []
        if line.strip() != "":
            inner_list.append(line.strip())
    if (inner_list):
        food_list.append(inner_list)

    return food_list

rawDescription: Function that creates nested list from text file, python


code:
pattSize = int(input("input pattern size: "))

while pattSize < 3:
    print("warning: pattern size should be at least 3!")
    pattSize = int(input("input pattern size: "))

steps = int(math.ceil(pattSize/2))
steps = list(range(steps))

def pattern(steps):
    for step in steps:
        for i in range(pattSize):
            line = ""
            for j in range(pattSize):
                    if (i == (0 + step) or j == (0 + step) ) and (i > (-1 + step) and j > (-1 + step)) and (i < (pattSize - step) and j < (pattSize - step)):
                        line += "*"
                    elif (i == (pattSize - (1 + step)) or j == (pattSize - (1 +  step)) ) and (i > (-1 + step) and j > (-1 + step)) and (i < (pattSize - step) and j < (pattSize - step)):
                        line += "*"
                    else:
                        line += "."

            print(line)
        time.sleep(0.1)

while True:
    pattern(steps)
    pattern(steps[1:-1][::-1])

rawDescription: How to reverse print a pattern

description: Reverse print a pattern


code:
from BeautifulSoup  import BeautifulSoup
from django import template
from django.template.defaultfilters import stringfilter
import pygments
import pygments.formatters
import pygments.lexers

register = template.Library()
wanted = {'br': '
', 'BR': '
', 'nbsp': ' ', 'NBSP': '&NBSP;', '/>': ''}

def uglyfilter(html):
    content = BeautifulSoup(html)
    for node in content.findAll('span'):
        data = ''.join(node.findAll(text=True))
        if wanted.has_key(data):
            node.replaceWith(wanted.get(data))
    return unicode(content)

@register.filter
@stringfilter
def pygmentized(html):
    soup = BeautifulSoup(html)
    codeblocks = soup.findAll('pre')
    for block in codeblocks:
        if block.has_key('class'):
            try:
                code = ''.join([unicode(item) for item in block.contents])
                lexer = pygments.lexers.get_lexer_by_name(block['class'], stripall=True)
                formatter = pygments.formatters.HtmlFormatter()
                code_hl = pygments.highlight(code, lexer, formatter)
                clean = uglyfilter(code_hl)
                block.contents = [BeautifulSoup(clean)]
                block.name = 'pre'
            except:
                raise
    return unicode(soup)

rawDescription: Filter whitespace and newlines with Pygments


code:
with open('file-one.csv') as f:
    reader = csv.reader(f, delimiter=',')  # adjust accordingly
    file_one = list(reader)
with open('file-two.csv') as f:
    reader = csv.reader(f, delimiter=',')
    file_two = list(reader)

element_to_search = 0  # 0 = first column in the row
line_pairs = zip(file_one, file_two)

with open('file-three.csv','w') as f:
    for line in line_pairs:
        if line[0][element_to_search] == line[1][element_to_search]:
            f.write('{}\n'.format(line[0]))

rawDescription: How do I read in a file, then take each element from this file and search another file to see if it contains the element. Python.

description: Read in a file, then take each element from this file and search another file to see if it contains the element. Python.


code:
window = turtle.Screen()
turtle.right(90)
drawHTree(200,2)

rawDescription: Using recursion to draw patterns in python


code:
class VersionExtension(SessionExtension):
    def before_flush(self, session, flush_context, instances):
        for instance in session.dirty:
            ...
            if hasattr(instance, '_suspend_versioning') and getattr(instance, '_suspend_versioning') is True:
                continue

rawDescription: Selective versioning with SQLAlchemy

description: Selective versioning with SQLAlchemy


code:
import sys
dir_name="/usr/lib/mydir"
sys.path.insert(0,dir_name)

rawDescription: Getting Python to use the ActiveTcl libraries


code:
with open('testfile.txt') as infh:
    fasta = Fasta(infh)
    for dna in fasta:
        print(dna.head)
        print(dna.sequence)

rawDescription: Very basic python object oriented programming: how do I implement a class with functions embedded within it?


code:
DETACHED_PROCESS = 8
subprocess.Popen(executable, creationflags=DETACHED_PROCESS, close_fds=True)

rawDescription: How to start daemon process from python on windows?

description: Start daemon process from python on windows


code:
import subprocess
subprocess.call(["ssh", "myuser@myserver"])

rawDescription: Python ssh - keep connection open after script terminates


code:
def main():
    lines = []
    with open('input.txt') as f:
        lines = f.readlines()

    ins_at = find_occurences_of('mappingSchemeAxis', lines)

    for i in ins_at:
        lines.insert(i,'HELLO WORLD\n')

    with open('input.txt', 'w') as f:
        f.writelines(lines)

def find_occurences_of(needle, haystack):
    ret = []
    for i, line in enumerate(haystack):
        if line.startswith(needle):
            ret.append(i)
    return ret

if __name__ == '__main__':
    main()

rawDescription: Write a line above the current line in a file Python


code:
import requests
r = requests.get('http://goo.gl/NZek5')
r.history
r.history[0].status_code
r.history[0].headers['Location']
r.url
r = requests.get('http://goo.gl/NZek5', allow_redirects=False)
r.status_code
r.url

rawDescription: Http Redirection code 3XX in python requests


code:
class Entity(models.Model):
    ...
    email_addresses = ArrayField(models.EmailField(max_length=200), blank=True)

rawDescription: Django multiple instance/inline field

description: Django multiple instance/inline field


code:
import Image

I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)

img = Image.fromarray(I8)
img.save("file.png")

rawDescription: how to save an array as a grayscale image with matplotlib/numpy?

description: Save an array as a grayscale image with matplotlib/numpy


rawDescription: How to create a user profile when creating a new user

description: Create a user profile when creating a new user


code:
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()

# Updated code below:
filesInRemoteArtifacts = sftp.listdir(path=remoteArtifactPath)
for file in filesInRemoteArtifacts:
    sftp.remove(remoteArtifactPath+file)

# Close to end
sftp.close()
ssh.close()

rawDescription: How to delete all files in directory on remote server in python?

description: Delete all files in directory on remote server in python


code:
import time, threading
from sys import exit
from gi.repository import Gtk, GObject, GLib

def run_core_engine():
    time.sleep(2)
    window.switchToMainFrame()
    time.sleep(2.5)
    GLib.idle_add(window.failDialog, "The window said hello")

class CoreThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        super(CoreThread, self).start()
    def run(self):
        run_core_engine()

class GettingInfoFrame(Gtk.Frame):
    def __init__(self):
        Gtk.Frame.__init__(self)
        self.connect("delete-event", Gtk.main_quit)
        self.set_shadow_type(Gtk.ShadowType.NONE)
        self.set_border_width(45)

        vbox = Gtk.VBox(spacing=10)
        hbox = Gtk.HBox(spacing=10)

        text = Gtk.Label()
        text.set_markup("<b><big>Doing stuff...</big></b>")
        self.spinner = Gtk.Spinner()
        self.spinner.set_size_request(30, 30)
        self.spinner.start()

        hbox.pack_start(text, True, True, 10)
        hbox.pack_start(self.spinner, True, True, 10)
        vbox.pack_start(hbox, True, True, 10)

        self.add(vbox)

class TheMainFrame(Gtk.Frame):
    def __init__(self):
        Gtk.Frame.__init__(self)
        self.set_shadow_type(Gtk.ShadowType.NONE)
        self.set_border_width(150)

        label = Gtk.Label("Hello")
        box = Gtk.VBox()
        box.pack_start(label, True, True, 0)
        self.add(box)

class Window(Gtk.Window):
    def __init__(self):
        ## Setup Main Window
        Gtk.Window.__init__(self, title="Fred the window")
        self.connect("delete-event", Gtk.main_quit)
        self.set_resizable(False)

        self.gettingInfoFrame = GettingInfoFrame()
        self.add(self.gettingInfoFrame)

    def switchToMainFrame(self):
        print("Displaying information in window")
        self.theMainFrame = TheMainFrame()
        self.remove(self.get_child())
        self.add(self.theMainFrame)
        self.show_all()

    def failDialog(self, errorMessage):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
            Gtk.ButtonsType.OK, "INFO:")
        dialog.format_secondary_text(errorMessage)
        dialog.run()

        Gtk.main_quit()

GObject.threads_init()

core_thread = CoreThread()

window = Window()
window.show_all()

Gtk.main()

rawDescription: Gtk MessageDialog causes segfault (PYGObject)


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

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

levels = np.arange(-2.0, 1.601, 0.4)

fig, axes = plt.subplots(1,2, sharey=True)

for ax, zord in zip(axes, [1, -1]):
    ax.contourf(X, Y, Z, levels,
                cmap=cm.get_cmap(cmap, len(levels)-1),
                norm=norm)
    ax.autoscale(False) # To avoid that the scatter changes limits
    ax.scatter(np.random.uniform(-3,3,10),
               np.random.uniform(-2,2,10),
               zorder=zord)
    ax.set_title('Scatter with zorder={0}'.format(zord))

rawDescription: Matplotlib: Scatter Plot to Foreground on top of a Contour Plot


code:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    lower_green = np.array([50, 50, 120])
    upper_green = np.array([70, 255, 255])
    green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image.

    # Threshold the HSV image to get only blue colors
    blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
    mask = blue_mask + green_mask

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

rawDescription: tracking multiple objects by color OpenCV 2.x

description: Tracking multiple objects by color OpenCV 2.x


rawDescription: python: equivalent to Javascript "||" to override non-truthful value

description: Python: equivalent to Javascript "||" to override non-truthful value


code:
my_array = numpy.array([1,2,3,4])

my_array[None, :] # shape 1x4

my_array[:, None] # shape 4x1

rawDescription: Efficient way to add a singleton dimension to a NumPy vector so that slice assignments work


code:
def build_payload(self):
        if isinstance(self.payload, ICMPv6Unknown):
            icmp_type = ord(str(self.payload)[0])
            icmp_class = eval(icmp6typescls[icmp_type])
            if self.payload.haslayer(Raw): #create actual class from the first 2 fields of the ICMPv6Unknown (type and code, ignoring the checksum) and add the other layers if there are any
                self.payload = icmp_class(str(self.payload[0])[0:2]) / self.payload[1:]
        else:
                self.payload = icmp_class(str(self.payload[0])[0:2])
        return super(IPv6 ,self).build_payload()

rawDescription: Making IPv6 update plen field according to ICMPv6 type on Scapy


code:
class MyTestCase(TestCase):
    @mock.patch('app.management.commands.cmd.Command.max_tries', new_callable=mock.PropertyMock)
    def test_update_course_with_exception(self, max_tries_mock):
        max_tries_mock.return_value = 1

rawDescription: Mock Django Commands class variable in UnitTests


code:
if ask('Do you like cheese?'):
    order_cheese() # Some function you've previously defined

rawDescription: True & False in a function def

description: True & False in a function def


code:
import win32com.shell.shell as shell
commands = 'echo hi'
shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c '+commands)

rawDescription: How to run cmd command in Python with admin

description: Run cmd command in Python with admin


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

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)
    ax.imshow(data)

plt.suptitle('Main title')
plt.show()

rawDescription: Pyplot, main title, subplot

description: Pyplot, main title, subplot


code:
s = b"""\
<?xml version="1.0" encoding="utf-8"?>
<users>
    <user id="1">
        <username>xxx</username>
        <password>xxx</password>
        <email>xxx@example.com</email>
        <nickname>xxx</nickname>
        <phone>xxx</phone>
        <status>xxx</status>
    </user>
</users>
"""
t = etree.XML(s)
t.xpath('//username/text()')
t.find('user[@id="1"]/username').text
t.find('user[@id="1"]/password').text

rawDescription: lxml xml parsing users

description: Lxml xml parsing users


rawDescription: How can I remove leading two integers with python script?

description: Remove leading two integers with python script


code:
df=pd.read_table('data.csv', delim_whitespace=True)
df
df.sum()
df[df>0].count()

rawDescription: Pandas column.sum() without having the index values multiply


code:
df
df.ix[:, 2]
df[df.columns[2]]

rawDescription: Selecting pandas column by location

description: Selecting pandas column by location


code:
# Initializing a "guess" variable in global scope is unnecessary, because it's unused.
array = []

# This function doesn't need any arguments, because it handles all logic inside.
def guess_function():
    guess = input("Enter a letter:  ")
    guess = guess.upper()
    while ord(guess) < 64 or ord(guess) > 90:
        print("Invalid input, please try again..")
        guess = input("Enter a letter: ")
        guess = guess.upper()
    return guess

def populate_array(array):
    while len(array) < 26:
        # Call the function and assign to a variable the result.
        guess = guess_function()
        array.append(guess)
        # Because of the while loop, no need to recursively call the self-same function.
        # Instead of printing the array each time, return the array.
        # This way, the calling function can determine how to display the array.
    return array

print(populate_array(array))

rawDescription: Why aren't my input getting appended into the array? (Python)


code:
class priyank_patel:
    def __init__(priyank):
       priyank.bla = 2

rawDescription: What is the "self" in the Python / CherryPy?


code: result = (lambda array: reduce(lambda a,b: some_function(b,array), array))(original_array[:])

rawDescription: How to refer to the whole array within reduce()?

description: Refer to the whole array within reduce()


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

from progress.bar import IncrementalBar
from twisted.internet import defer
from twisted.internet import task
from twisted.internet import utils
from twisted.python import usage

class Options(usage.Options):
    optFlags = [['reactor', 'r', 'Use reactor.run().'],
                ['task', 't', 'Use task.react().'],
                ['cwr', 'w', 'Use callWhenRunning().']]
    optParameters = [['limit', 'l', 255, 'Number of file descriptors to open.'],
                     ['cmd', 'c', 'echo Testing {i}...', 'Command to run.']]

@defer.inlineCallbacks
def main(reactor, opt):
    d = defer.Deferred()
    limit = int(opt['limit'])
    cmd, args = opt['cmd'].split(' ', 1)
    bar = IncrementalBar('Running {cmd}'.format(cmd=opt['cmd']), max=limit)
    for i in range(0, limit):
        try:
            _args = args.format(i=i)
            args = _args
        except KeyError:
            pass
        yield utils.getProcessOutputAndValue('echo', [args])
        bar.next()
    bar.finish()
    defer.returnValue(d.callback(True))

if __name__ == '__main__':
    opt = Options()
    opt.parseOptions()

    if opt['reactor']:
        from twisted.internet import reactor
        task.deferLater(reactor, 0, main, reactor, opt)
        reactor.run()

    elif opt['task']:
        from twisted.internet.task import react
        react(main, [opt])

    elif opt['cwr']:
        from twisted.internet import reactor
        reactor.callWhenRunning(main, reactor, opt)
        reactor.run()

rawDescription: OSError: [Errno 24] Too many open files when using reactor.run() in Twisted


code: from __future__ import unicode_literals

rawDescription: Alternative to u'' for unicode strings

description: Alternative to u'' for unicode strings


rawDescription: Python Logging across multiple classes and files; how to configure so as to be easily disabled?


code:
import os
os.listdir('/foo/bar')[0]

rawDescription: Fast way to read filename from directory?


rawDescription: Splitting semicolon separated string in Python


code:
try:
    import Tkinter
    gui_installed = True
except ImportError:
    gui_installed = False

...

result = somecalc()
if gui_installed:
    display_with_gui(result)
else:
    display_as_text(result)

rawDescription: Change Program Flow based on Available Libraries


rawDescription: Check if HDF5 Store object is empty?

description: Check if HDF5 Store object is empty


code:
import argparse

# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')

# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')

# create the parser for the "b" command
parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices='XYZ', help='baz help')
# print main help
print(parser.format_help())

# retrieve subparsers from parser
subparsers_actions = [
    action for action in parser._actions
    if isinstance(action, argparse._SubParsersAction)]
# there will probably only be one subparser_action,
# but better save than sorry
for subparsers_action in subparsers_actions:
    # get all subparsers and print help
    for choice, subparser in subparsers_action.choices.items():
        print("Subparser '{}'".format(choice))
        print(subparser.format_help())

rawDescription: argparse subparser monolithic help output

description: Argparse subparser monolithic help output


code:
ax = plt.gca()
ax.get_xaxis().get_major_formatter().scaled[365] = '%y'
plt.draw()

rawDescription: How to abbreviate xtick labels years to 2 digits in a matplotlib plot

description: Abbreviate xtick labels years to 2 digits in a matplotlib plot


code:
def save_and_exit():
    save_changed_files()
    sys.exit()

self.createcommand('exit', save_and_exit)

rawDescription: Apple Python launcher is acting on command key bindings


code:
class MyForm(models.ModelForm):
    ...
    def save(self):
        instance = super(MyForm, self).save(commit=False)
        if not self.deposit:
            self.amount = -self.amount
        instance.save()
        return instance

rawDescription: Massage model data before save in Django


code:
FileName = 'Numberdata.dat'
NumberFileHandle = open(FileName, 'r')
newFileString = ""
for Line in NumberFileHandle:
  for char in line: # this will work for any number of lines.
      if char == '4':
        newFileString += "1"
      elif char == '\n':
        newFileString += char
      else:
        newFileString += "9"
NumberFileHandle.close()

NumberFileHandle = open(FileName, 'w')
NumberFileHandle.write(newFileString)
NumberFileHandle.close()

rawDescription: Changing contents of a file - Python

description: Changing contents of a file - Python


code:
from django.conf import settings

setting_name = "LABEL_NAME"
print(getattr(settings, setting_name))

rawDescription: django/python: to access defined constant by equivelent string

description: Django/python: to access defined constant by equivelent string


rawDescription: How to select specific rows and columns in 2d array

description: Select specific rows and columns in 2d array


code:
from scipy import optimize
import numpy as np

x = np.arange(1, 4)
y = x * 3 + 1

f = lambda x, *p: p[0] * x + p[1]
popt, pcov = optimize.curve_fit(f, x, y, [1,-4])
popt
pcov

rawDescription: defining function for scipy.optimize.curve_fit

description: Defining function for scipy.optimize.curve_fit


code:
import dask as dk
import tables
import numpy as np
from time import time

outpath = "/tmp/"
lenx = 300
leny = 100000
fname = "t{0:03d}_{1:03d}.h5".format(int(lenx/100),int(leny/100))

def write_test_file():
    h5file = tables.open_file(outpath+fname,"w")
    pres = np.random.random((lenx,leny))
    atom = tables.Float64Atom()
    filters = tables.Filters(complevel=6, complib='zlib', shuffle=True)
    print("Writing data")
    t01 = time()
    h5file.create_carray(h5file.root,'pressure',atom,(lenx,leny),filters=filters,obj=pres)
    h5file.flush()
    del pres
    t02 = time()
    lines = np.random.random((leny,lenx))
    h5file.create_carray(h5file.root,"lines",atom,(leny,lenx),filters=filters,obj=lines)
    t03 = time()
    print("Data written",t03-t02,t02-t01)
    h5file.close()

def numpy_dot_test():
    print("Open data")
    t1 = time()
    h5open = tables.open_file(outpath+fname,mode="r")
    pressureObject = h5open.get_node("/", "pressure")
    print(pressureObject.shape)
    linesObject=h5open.get_node("/","lines")
    print(linesObject.shape)
    t2 = time()
    ohoo = np.array(linesObject).dot(np.array(pressureObject))
    t3 = time()
    print(ohoo.shape,np.mean(ohoo))
    print("matmul time:",t3-t2,t2-t1)
    h5open.close()

def dask_dot_test():
    import h5py
    import dask.array as da
    h5open2 = h5py.File(outpath+fname)
    t21=time()
    d1=da.from_array(h5open2["/pressure"],chunks=(100,lenx))
    d2=da.from_array(h5open2["/lines"],chunks=(leny,100))
    t22=time()
    print('d1,d2',d1.shape,d2.shape)
    d1.dot(d2).to_hdf5(outpath+'output.h5','testout')
    t23=time()
    print('ohoo',t23-t22,t22-t21)
    h5open2.close()

write_test_file()
    ## numpy_dot_test()
dask_dot_test()

rawDescription: Dot product of hdf5 array

description: Dot product of hdf5 array


code:
def to_representation(self, instance):
    duration = self.fields['duration']
    duration_value = duration.to_representation(
        duration.get_attribute(instance)
    )
    return {
        'name': instance.name,
        'duration of cycle': duration_value
    }

description: Django-rest-framework serializer to_representation


code:
Polls.objects.get(
    Q(question__startswith='Who') | Q(question__startswith='What')
)

rawDescription: Django filtering based on optional parameters


code:
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.copyfile(urllib.urlopen(self.path), self.wfile)

rawDescription: seriously simple python HTTP proxy?

description: Seriously simple python HTTP proxy


code:
print("Content-Type: text/html\n\n")
print("""<html>
 <head></head>
 <body>
 <form name='success' action='nav.py' method='post'>
     <input type='hidden' name='linkB' value='Add Assets' />
 </form>
 <script type='text/javascript'>
     document.success.submit()
 </script>
 </body>""")

rawDescription: Post to another python cgi-script from the current cgi-script


code:
for b in bytearray("message\n","UTF-8"):
    port.write(b)

rawDescription: Pyserial string to byte encoding to write to microcontroller


code:
help(str.istitle)
"Alpha_beta_Gamma".istitle()
"Alpha_Beta_Gamma".istitle()
"Alpha_Beta_GAmma".istitle()

rawDescription: How to check if a character is upper-case in Python?

description: Check if a character is upper-case in Python


code:
from django.contrib.sites.models import RequestSite
site_name = RequestSite(request).domain

rawDescription: Issues with getting multiple site id in django


code:
class Equation_Window(tk.Toplevel):

    def __init__(self):

        tk.Toplevel.__init__(self)

        self.title("Add Equation Set")
        self.resizable(width=False, height=False)

        self.name_entry_var = tk.StringVar()
        self.name_entry = ttk.Entry(self, textvariable=self.name_entry_var, width=30)
        self.name_entry.grid(row=1, columnspan=2, stick="w")

        self.equation_type_var = tk.StringVar()
        self.equation_type = ttk.Combobox(self, textvariable=self.equation_type_var, values=("System", "Exact", "Import Point List..."), state="readonly", width=28)
        self.equation_type.current(0)
        self.equation_type.grid(row=2, columnspan=2, sticky="w")

def add_equation():
    w = Equation_Window()
    w.wait_window()

rawDescription: Tkinter ttk Combobox Default Value

description: Tkinter ttk Combobox Default Value


code:
import os, shutil

#Get the list of all folders present within the particular directory
folder_list = os.walk('.').next()[1]

#Start zipping the folders
for each_folder in folder_list:
    shutil.make_archive(each_folder, 'zip', os.getcwd() + "\\" + each_folder)

rawDescription: How to create zip of a specific folder using shutil

description: Create zip of a specific folder using shutil


code:
hold() # stop the curplot()
# and add the legend just next to the data
x, y = 15.5, 0
for i,area in enumerate(areas):
    rect([x], [y], color=colors[i], width=0.3, height=400)
    text([x], [y], text=area, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle")
    y = y + 100

show()

rawDescription: how to show legend items of patches in bokeh

description: Show legend items of patches in bokeh


code: FirstRowDict[i] = float(tablewidget.item(0, j).text())

rawDescription: Fill a dictionary with all cell values of given row


rawDescription: Trouble vectorizing code

description: Trouble vectorizing code


code:
df = pd.read_csv(StringIO(s), sep='\s+')
df['calendar'] = pd.to_datetime(df['eligyear']*10000 + df['eligmonth']*100 + 1, format='%Y%m%d')
df

rawDescription: Pandas date parser sets day to current when missing


code:
count =10
print('many') if count>=10 else ''

rawDescription: How to check condition and choose return

description: Check condition and choose return


code:
def call_and_type(command, prompt_regex, entry):
    p = pexpect.spawn(command, logfile=sys.stdout, maxread=16384)
    index = p.expect_exact([prompt_regex, pexpect.EOF])
    if index == 0:
        p.setecho(False)
        p.sendline(entry)
        while p.read():
            pass

rawDescription: python pexpect - not taking the expect output

description: Python pexpect - not taking the expect output


code:
# you file containt utf8 chars, you need to specify encoding
# coding=utf-8

import os
import json

# I use a dict structure instead of a list for easier retrieval
# you can easily see if an account exist and get its password
# also global keyword is to avoid, so prefer declaring in the global context instead of pushing to the global context
accounts = {}

# if we have a file, deserialize content
if os.path.exists("/tmp/Accounts.json"):
    try:
        with open("/tmp/Accounts.json") as f:
            accounts = dict(json.loads(f.read()))
    except:
        pass

def createUser():
    # input is equivalent to eval(raw_input(... which is not the goal here
    nUsername = raw_input("Create Username »  ")

    # with a dict, no need to iterate through, simply use `in`
    if nUsername in accounts.keys():
        return createUser()

    nPassword = raw_input("Create Password » ")
    # this is how you assign the new account
    accounts[nUsername] = nPassword
    autoSave()

def autoSave():
    with open("/tmp/Accounts.json", "w") as outfile:
        # we convert here the dict to your list structure
        json.dump(list(accounts.iteritems()), outfile)

def existingUser():
    eUsername = raw_input("Your Username » ")
    ePassword = raw_input("Your Password » ")

    for item in accounts:
        if eUsername in accounts and accounts[eUsername] == ePassword:
            return 'Processing Sucessfully logged into your account!'
        else:
            return "Login failed"

createUser()

rawDescription: Python: Json File Referencing from user Inputs


code:
(lambda x: x).__get__
int.__get__

rawDescription: How does Python know whether a variable in the class is a method or a variable?


code:
@task
def add(x, y):
    return x + y

rawDescription: Python CGI queue

description: Python CGI queue


code:
import moduleX as data

for k, v in data.__dict__.iteritems():
    if isinstance(v, dict) and not k.startswith('_'):
        # do something
        pass

rawDescription: iterate over dictionaries in module

description: Iterate over dictionaries in module


code:
address = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
has_token = False
token = 1
if id == 1:
        has_token = True
        token = random.randrange(1,11,1)
        time.sleep( 5 )
s.bind((address, port))
while token < max_token:
        while not has_token:
                data_token, addr = s.recvfrom(8192)
                if data_token:
                        has_token = True
                        token = int(data_token)
        if (token % 7) != id:
                token = increment_token(token)
                s.sendto(str(token),(next_address,next_port))
                has_token = False
        else:
                token = set_random_token(token)
                s.sendto(str(token),(next_address,next_port))
                has_token = False

rawDescription: Token passing in ring algorithm in python


code: from_bitly = bool(request.GET.get('bitly', False))

rawDescription: Detecting bitly link redirection

description: Detecting bitly link redirection


code:
import http.client
conn = http.client.HTTPSConnection("proxy_domain", 8080)
conn.set_tunnel("www.python.org")
conn.request("HEAD","/index.html")

rawDescription: How to create a HTTP proxy handler with Python 3 HTTP lib

description: Create a HTTP proxy handler with Python 3 HTTP lib


code:
range = [800,1000]

idx_low,idx_high = x.searchsorted(data[:,0], range)

data_within_range = data[idx_low:idx_high,:]

rawDescription: Conditionally extracting elements from a matrix in Python.


code:
from pandas import isnull
frame=frame.applymap(lambda x: {} if isnull(x) else x)
frame

rawDescription: Pandas - replace all NaN values in DataFrame with empty python dict objects


code:
import numpy as np
m = np.triu(np.arange(0, 12, dtype=np.float).reshape(4,3))
m
m[np.tril_indices(m.shape[0], -1)] = np.nan
m

rawDescription: Make a numpy upper triangular matrix padded with Nan instead of zero


code: time_d_float = time_d.total_seconds()

rawDescription: Convert timedelta to floating-point

description: Convert timedelta to floating-point


code:
for idx,x in enumerate(people):
    view.setItem(idx, 0, QtGui.QTableWidgetItem(name[x][:-1][1:]))

rawDescription: python - different variables in same "for" loop?

description: Python - different variables in same "for" loop


code:
def mask(rawBytes):
    data = [ord(i) for i in rawBytes]
    length = len(rawBytes) + 128 if len(rawBytes) + 128 <= 254 else 254
    Bytes = [0x81, length]
    index = 2
    mask = os.urandom(4)
    for i in range(len(mask)):
        Bytes.insert(i + index, mask[i])
    for i in range(len(data)):
        data[i] ^= mask[i % 4]
        Bytes.insert(i + index + 4, data[i])
    return bytes(Bytes)

rawDescription: workaround for python bytes() to handle more than range(0, 256)

description: Workaround for python bytes() to handle more than range(0, 256)