code:
import wx

class PersonalInfoDialog(wx.Dialog):
    def __init__(self, parent):
        super(PersonalInfoDialog, self).__init__(parent)
        self.SetTitle('Personal Info')
        sizer = self.create_controls()
        self.SetSizer(sizer)
    def create_controls(self):
        box = self.create_box()
        buttons = self.create_buttons()
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(box, 1, wx.EXPAND | wx.ALL, 10)
        sizer.Add(buttons, 0, wx.EXPAND | wx.BOTTOM, 10)
        return sizer
    def create_box(self):
        contents = self.create_box_contents()
        box = wx.StaticBox(self, -1, 'Personal Info')
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        sizer.Add(contents, 1, wx.EXPAND | wx.ALL, 10)
        return sizer
    def create_box_contents(self):
        male = wx.CheckBox(self, -1, 'Male')
        married = wx.CheckBox(self, -1, 'Married')
        age = self.create_age()
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(male)
        sizer.AddSpacer(10)
        sizer.Add(married)
        sizer.AddSpacer(10)
        sizer.Add(age)
        return sizer
    def create_age(self):
        age = wx.SpinCtrl(self, -1, '28', min=0, max=100, size=(64, -1))
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        text = wx.StaticText(self, -1, 'Age')
        sizer.Add(text, 0, wx.ALIGN_CENTER_VERTICAL)
        sizer.AddSpacer(10)
        sizer.Add(age)
        return sizer
    def create_buttons(self):
        button = wx.Button(self, wx.ID_OK, 'OK')
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.AddStretchSpacer(1)
        sizer.Add(button)
        sizer.AddStretchSpacer(1)
        return sizer

def main():
    app = wx.App(False)
    dialog = PersonalInfoDialog(None)
    dialog.ShowModal()
    dialog.Destroy()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: Having difficulty understanding wx.Sizers in wxPython


code:
for post in username.newpost_set.all():
    comments = postcomment.objects.filter(commenttag=post).order_by('-postcommentdate')
    # your code here

rawDescription: Django: How to order comments of a post directly under each original post object?


code:
argsortx = np.argsort(x)
x, y, z = x[argsortx], y[argsortx], z[argsortx]

rawDescription: Sort single column numpy arrays using another numpy array in Python


code:
s = ''.join('%s: %s </br>' %
               (a,getattr(user, a)) for a in dir(user) if '__' not in a
           )

rawDescription: What is the right way to add an `if` to a generator expression in Python?


code:
class System(models.Model):
    pass

class Interface(models.Model):
    assigned_to = models.ManyToManyField(to=User)
    system = models.ForeignKey(System)

    @property
    def systems(self):
        Interface.objects.get(system=self.system).interfacedsystem_set.all()

class InterfacedSystem(models.Model):
    interface = models.ForeignKey(Interface)
    system = models.ForeignKey(System)

rawDescription: Django cross table model structure

description: Django cross table model structure


code:
import pandas as pd
# Create a DataFrame example
df = pd.DataFrame(\
    {'Year': [1991 ,2004 ,2001 ,2009 ,1997],\
    'Age': [27 ,25 ,22 ,34 ,31],\
    },\
    index = ['Com_Lag_1' ,'Com_Lag_12' ,'Com_Lag_3' ,'Com_Lag_24' ,'Com_Lag_5'])

# Add of a column containing a numbered version of the index
df['indexNumber'] = [int(i.split('_')[-1]) for i in df.index]
# Perform sort of the rows
df.sort(['indexNumber'], ascending = [True], inplace = True)
# Deletion of the added column
df.drop('indexNumber', 1, inplace = True)

rawDescription: Python: Sort DataFrame index that has a string and number


code:
#!python3

from collections import defaultdict

AB_map = defaultdict(set)
Values = set()

with open('train.tsv') as infile:
    headers = next(infile)
    for line in infile:
        if not line.strip():
            continue
        a,b = map(int, line.split())
        AB_map[a].add(b)
        Values.add(b)

print("# of keys:", len(AB_map.keys()))
print("# of values:", len(Values))

def impact_of_deletion(keylist):
    values_impacted = set([])
    for key in keylist:
        values_impacted.update(AB_map[key])
    return values_impacted

for hyp in ((1,), (1,6)):
    print("Deleting", hyp, "would impact:", len(impact_of_deletion(hyp)))

rawDescription: Building a map for large datasets

description: Building a map for large datasets


code:
class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return 'A({}, {})'.format(self.a, self.b)

    class Empty(object):  # nested class
        def __new__(cls, b):
            return A(0, b)  # ignore cls & return instance of enclosing class

        @staticmethod
        def TypeI(b):
            return A(0, b-1)

        @staticmethod
        def TypeII(b):
            return A(0, b-2)

a = A(1, 1)
print('a: {}'.format(a))      # --> a: A(1, 1)
b = A.Empty(2)
print('b: {}'.format(b))      # --> b: A(0, 2)
bi = A.Empty.TypeI(4)
print('bi: {}'.format(bi))    # --> bi: A(0, 3)
bii = A.Empty.TypeII(6)
print('bii: {}'.format(bii))  # --> bii: A(0, 4)

rawDescription: Using classmethods to implement alternative constructors, how can I add functions to those alternative constructors?


code:
# coding=utf-8
import csv
words = ['يعمل','في','جامعة']
tags = ['verb','prep','noun']
with open('results.csv', 'w', encoding = 'utf-16', newline='') as outfile:
    rowlists = zip(words, tags)
    writer = csv.writer(outfile)
    for row in rowlists:
        writer.writerow(row)

rawDescription: How to save two lists with Unicode strings in csv file in Python?

description: Save two lists with Unicode strings in csv file in Python


code:
battles = soup.find('td', 'td-number-nowidth')
if battles:
   print(battles.get_text())

rawDescription: Python web scraping with regex

description: Python web scraping with regex


rawDescription: How to list all the groups that a user does not belong to in django?

description: List all the groups that a user does not belong to in django


code:
import csv

mylist = [1.11, 2.22, 3.33, 4.44]
with open('myfile.csv', "wb") as f:
    writer = csv.writer(f, delimiter=',')
    for elem in mylist:
        writer.writerow([elem])

rawDescription: Python create excel readable csv from list of float values in single column


code: y = np.cumsum(x)

rawDescription: Running Cumulative sum of 1d NumPy Array


code:
user.aggregate([
   {"$match": {'timeCreated':{ "$gte":date_yesterday, "$lt":date_today } }},
   {'$group':{'_id': "$organization",'count':{"$sum": 1 } }}
])

rawDescription: using $group and $match (with range of date) functions in pymongo query

description: Using $group and $match (with range of date) functions in pymongo query


code:
def access():
    room_code = 12534
    code = int(raw_input('Enter the code: '))
    if code == room_code:
        return 'good'
    return 'death'

rawDescription: Add multiple numbers taken from user input and append it to a list


code: rulesFile = open("example.tsv", "r", encoding="utf-8-sig")

rawDescription: Is there an extra character on the first readline() of a file?


code:
#Create a set of all the records from the first file
lookup = set(open("test01.txt").read().splitlines())
#and then open the second file for reading and a new out file
#for writing
with open("test02.txt") as fin, open("test02.out","w") as fout:
    #iterate through each line in the file
    for line in fin:
        #and split it with the seperator
        line  = map(str.strip, line.split(":"))
        #if the key is in the lookup set
        if line[0] in lookup:
            #replace it with space
            line[0] = " "
        #and then join the line tuple and suffix with newline
        line = ":".join(line) + "\n"
        #finally write the resultant line to the out file
        fout.write(line)

rawDescription: Check words in multi files, if the same then replace by space


code:
jsonDeals = response.json()

deals = []
for deal in jsonDeals['deals']:
    properties = deal['properties']
    if ('dealstage' in properties and
        properties['dealstage']['value'] == 'qualifiedtobuy'):
        deals.append(deal)

if deals:
    print(deals[0]['dealId'])
else:
    print('found no "qualifiedtobuy" deals')

rawDescription: Extracting data from JSON and iterating using python


code:
infoObject = pygame.display.Info()
pygame.display.set_mode((infoObject.current_w, infoObject.current_h))

rawDescription: How to get the resolution of a monitor in Pygame?

description: Get the resolution of a monitor in Pygame


rawDescription: How to convert a script to UTF-8

description: Convert a script to UTF-8


code: users = Table('users', metadata, autoload=True)

rawDescription: Using two databases with Pyramid SqlAlchemy


code:
from code import InteractiveConsole

livePythonInterpreters= {}

class LivePythonCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        ic = InteractiveConsole()
        global livePythonInterpreters
        livePythonInterpreters[self.view.buffer_id()] = ic

class LivePythonListener(sublime_plugin.EventListener):
    def on_modified(self, view):
        ic = livePythonInterpreters[view.buffer_id()]

rawDescription: Sublime Plugin: Share object between TextCommand and EventListener?


code:
class Test:
    a = 1

Test.__dict__

rawDescription: Where are the top-level attributes of a class stored in Python


code:
def __init__(self, user_id=None):
    if user_id is None:
         ...

rawDescription: Create a Python User() class that both creates new users and modifies existing users


code:
import pandas as pd
L = ['a','a','b','b','c','c']
df = pd.DataFrame(L)
df
df = df.drop(3)
df
df.loc[4]
df.loc[5]

rawDescription: python remove element from list without changing index of other elements

description: Python remove element from list without changing index of other elements


code:
class Ten(models.Model):
    nine = models.ForeignKey(Nine)

    @property
    def one(self):
        return self.nine.eight.seven.six.five.four.three.two.one

rawDescription: Best practice for accessing distantly related Django models


code:
s = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
from string import maketrans, ascii_lowercase
T = maketrans(ascii_lowercase, ascii_lowercase[2:] + ascii_lowercase[:2])
s.translate(T)

rawDescription: How to replace strings in a string

description: Replace strings in a string


code:
from SimpleCV import Camera
from SimpleCV import Image

webcam_camera = Camera()
webcam_image = webcam_camera.getImage()
webcam_image.save("frame.jpg")

rawDescription: Capturing frames from macbook isight with PIL


code:
uniq = {d['name']: d.get('age') for d in sorted(l, key=lambda d : d.get('age'))}
uniq
[{'name': k, 'age': v} for k, v in uniq.items()]

rawDescription: How to define "duplicate" when removing duplicate dictionaries in a list?

description: Define "duplicate" when removing duplicate dictionaries in a list


code:
import pysimplesoap
client = pysimplesoap.client.SoapClient(wsdl='http://www.webservicex.net/stockquote.asmx?WSDL')
response = client.GetQuote('GOOG')
client.response
client.response['status']

rawDescription: Get status code for request sent using pysimplesoap


code:
cols = [each for each in df2.columns if each not in ['name','bin']]
df3 = pd.merge(df1, df2, how='left', on=['bin'])
df3[cols] = df3.apply(lambda x:x['score']*x[cols],axis=1)

rawDescription: Pandas dataframe merge and element-wide multiplication


code:
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from random import SystemRandom

# Signing authority (SA) key
priv = RSA.generate(3072)
pub = priv.publickey()

## Protocol: Blind signature ##

# must be guaranteed to be chosen uniformly at random
r = SystemRandom().randrange(pub.n >> 10, pub.n)
msg = "my message" * 50 # large message (larger than the modulus)

# hash message so that messages of arbitrary length can be signed
hash = SHA256.new()
hash.update(msg)
msgDigest = hash.digest()

# user computes
msg_blinded = pub.blind(msgDigest, r)

# SA computes
msg_blinded_signature = priv.sign(msg_blinded, 0)

# user computes
msg_signature = pub.unblind(msg_blinded_signature[0], r)

# Someone verifies
hash = SHA256.new()
hash.update(msg)
msgDigest = hash.digest()
print("Message is authentic: " + str(pub.verify(msgDigest, (msg_signature,))))

rawDescription: Using a blinding factor for RSA in pycrypto


rawDescription: Python 3.4 & Netifaces - Get one specific IPv4 address


code:
class Thing(models.Model):
    id = models.CharField(primary_key=True, max_length=16)
    photo = ImageField('Photo', upload_to=upload_path, null=False, blank=False)
    ...

    def save(self, *args, **kwargs):
        randid = random_id(16)
        while Thing.objects.filter(id=randid).exists():
            logger.error("[Thing] ThingID of %s already exists" % randid)
            randid = random_id(16)
        self.id = randid
        self.photo.name = ".".join([randid, self.photo.name.split(".")[-1]])   # This adds the file extension to the random id generated
        super(Thing,self).save(*args, **kwargs)

rawDescription: Access generated primary key on ImageField upload_to call


rawDescription: str.lstrip() unexpected behaviour

description: Str.lstrip() unexpected behaviour


code:
for row in dictrows:
    out_f.write("%s%s" %(delimiter.join([row[name] for name in fieldnames]),
                lineterminator))

rawDescription: python write to file from a dictionary in batch

description: Python write to file from a dictionary in batch


code:
import itertools
[min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])]

rawDescription: Building a list of months by iterating between two dates in a list (Python)


code:
def checkForKeyPress():

    #if I retrieve at least one quit event since I last checked
    if len(pygame.event.get(QUIT)) > 0:
        #quit the game
        terminate()

    #retrieve all the key release events since we last checked
    keyUpEvents = pygame.event.get(KEYUP)

    #if there are no key release events
    if len(keyUpEvents) == 0:
        #there was no key press, don't return anything
        #and skip the rest of the method
        return None

    #if the user pressed the escape key
    if keyUpEvents[0].key == K_ESCAPE:
        #quit the game
        terminate()

    #if we haven't returned or quit already
    #return the first key released since we last checked
    return keyUpEvents[0].key

rawDescription: What happens in this code?

description: What happens in this code


code:
for circle in circles[:]:
    circle.update()

rawDescription: Python & Pygame: Updating all elements in a list under a loop during iteration


code: df.groupby(df.col1 == df.col2).apply(f)

rawDescription: Is there a way to group by logical comparison of two columns in Pandas?


code:
import itertools
list(itertools.starmap(add, foo))

rawDescription: Unpack nested list for arguments to map()


code:
class MyForm(forms.Form):
    timestamp     = forms.IntegerField(widget=forms.HiddenInput, initial=0)
    #look at the initial = 0

    security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)

    def clean_timestamp(self):
        """Make sure the delay is over (5 seconds)."""
        ts = self.cleaned_data["timestamp"]
        if timestamp != 0 and not time.time() - ts > 5:
            raise forms.ValidationError("Timestamp check failed")
        return ts

    def clean(self):
        cleaned_data = self.cleaned_data
        if len(self._errors) == 0: #it validates
            cleaned_data["timestamp"] = time.time()
        return cleaned_data

rawDescription: How to build a Django form which requires a delay to be re-submitted?

description: Build a Django form which requires a delay to be re-submitted


code:
import webbrowser
url = 'http://www.stackoverflow.com'
url2 = 'http://www.stackexchange.com'

def main():
    webbrowser.open(url2) # To open new window
    print('Opening Stack Exchange website!')
    webbrowser.open_new_tab(url) # To open in new tab
    print('Opening Stack Overflow website in a new tab!')

if __name__ == '__main__':
    main()

rawDescription: Opening tabs using Webbrowser module in Python


code:
class Category(models.Model):
    name = models.CharField(max_length=10)

def cook_category():
    return Category.objects.get(name='cook')

class CookArticle(models.Model):
    #your model
    category = models.ForeignKey(Category, default=cook_category)

rawDescription: Define a django model which use in a foreign key a specific instance of an other model


code: [root for (root, ext) in map(os.path.splitext, os.listdir(path)) if ext == '.py']

rawDescription: python file operation

description: Python file operation


code:
a
a = [[x[0][0]] for x in a]
a

rawDescription: Python: Removing tuples from a list of lists


code:
#!/usr/bin/env python

import bencode
import random
import socket
import sys
import ast
import struct

rand = lambda: ''.join([chr(random.randint(0, 255)) for _ in range(20)])
my_id = rand()

def query(ip, port):
    print("Trying %s:%d" % (ip, port))
    get_peers = {"t":'0f', "y":"q", "q":"get_peers",
        "a": {"id":my_id,
              "info_hash": '\xd9\x9d\x14\x8c\xf7\xb5\xee'
                           '\x84</\x806\xd6d\x13\xb3\xe3\x0f\x1b\xe7'}
    }
    get_peers_bencoded = bencode.bencode(get_peers)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.sendto(get_peers_bencoded, (ip, port))
    s.settimeout(0.5)
    try:
        r = s.recvfrom(1024)
    except socket.timeout:
        return []
    response = bencode.bdecode(r[0])

    if 'values' in response['r']:
        print(response)
        sys.exit()

    ret = []
    for i in range(0, len(response['r']['nodes']), 26):
        s = response['r']['nodes'][i:i+26]
        ip = socket.inet_ntop(socket.AF_INET, s[-6:][:4])
        port = struct.unpack(">H", s[-2:])[0]
        ret += [(ip, port)]
    print("Got %d nodes." % len(ret))
    return ret

if __name__ == '__main__':
    ips = [(socket.gethostbyname('router.bittorrent.com'), 6881)]
    while True:
        node = ips.pop()
        ip, port = node[0], node[1]
        ips += query(ip, port)

rawDescription: How to interpret 'nodes' in a DHT response?

description: Interpret 'nodes' in a DHT response


code: [x[0] for x in sorted(enumerate(a), key=lambda x: x[1])[-5:]]

rawDescription: In Python, how can I get the indices of the 5 greatest values of a list?


code:
import cv2
import numpy as np
rect = [[634, 547],[353, 504],[436, -41],[717,   1]]
poly = np.array([rect], dtype=np.int32)
img = np.zeros((800, 800), np.int8)
cv2.fillPoly(img, poly, 255)
imshow(img, cmap="gray")

rawDescription: Opencv: zero pixels outside of region of interest with rotated rectangle?


code:
name = raw_input ("What's your name?")

if 'Sean' in name:
    name1 = raw_input("Downey or Paul?")
    if 'Downey' in name1:
        print ("Hi Sean Downey")
        x = raw_input("Did you know that the name is irish?")
        if x == 'yea':
            print ('oh cool')
    elif 'Paul' in name1:
        print ("Hi Sean Paul")
    else:
        print ("I don't know that Sean")
else:
    print ('Hi %s') % (name)

rawDescription: Output based on input keywords

description: Output based on input keywords


code:
cmd = ['git', '-C', repo, 'show', r'{0}:{1}'.format(commit, filename)]
p1 = subprocess.Popen(cmd, stdout = subprocess.PIPE)
filter = [ '/bin/cat', '-vet' ]
p2 = subprocess.Popen(filter, stdout = subprocess.PIPE, stdin = p1.stdout)
p2.wait()
stdout = p2.stdout.read()

rawDescription: Python subprocess.Popen to use git pager


code:
@pytest.fixture
def my_object(priority):
    return MyObj(priority)

def test_foo(my_object):
    obj_1 = my_object(1)
    assert something # 1
    obj_2 = my_object(2)
    assert something # 2

rawDescription: initing a pytest fixture with a parameter

description: Initing a pytest fixture with a parameter


code:
class BoringForm(Form):
    until = DateTimeField(
        "Until", format="%Y-%m-%dT%H:%M:%S",
        default=datetime.today, ## Now it will call it everytime.
        validators=[validators.DataRequired()]
    )

rawDescription: wtforms+flask today's date as a default value

description: Wtforms+flask today's date as a default value


code:
jsonp = response.body
j = jsonp[ jsonp.index("(") + 1 : jsonp.rindex(")") ]
json.loads(j)

rawDescription: Scrapy - Error Importing JSON

description: Scrapy - Error Importing JSON


code:
converter= ( (0,) + 255*(255,) ).__getitem__
def black_or_white(img):
    return img.convert('L').point(converter)

rawDescription: Cleaning an image to only black

description: Cleaning an image to only black


code:
def camel_case_split(identifier):
    matches = finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
    return [m.group(0) for m in matches]

rawDescription: How to do CamelCase split in python

description: Do CamelCase split in python


code:
css = '''

QMainWindow
{
background:orange;
}

QLineEdit
{
background:white;
}

QPushButton
{
background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                          stop: 0 #FAFFFA, stop: 0.4 #F5F7F5,
                          stop: 0.5 #F0F2F0, stop: 1.0 #EDEDED);
}
'''

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        Login_Widget = LoginPage(self)
        self.central_widget.addWidget(Login_Widget)
        self.central_widget.setCurrentWidget(Login_Widget)

class LoginPage(QtGui.QWidget):
    def __init__(self, parent=None):
        super(LoginPage, self).__init__(parent)
        self.Username = QtGui.QLineEdit(self)
        self.Password = QtGui.QLineEdit(self)
        self.Password.setEchoMode(QtGui.QLineEdit.Password)
        self.buttonLogin = QtGui.QPushButton('Login', self)
        self.cancelButton = QtGui.QPushButton('Cancel', self)
        loginLayout = QtGui.QFormLayout()
        loginLayout.addRow("Username", self.Username)
        loginLayout.addRow("Password", self.Password)
        horizontallayout = QtGui.QHBoxLayout()
        horizontallayout.addWidget(self.buttonLogin)
        horizontallayout.addWidget(self.cancelButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(loginLayout)
        layout.addLayout(horizontallayout)
        self.setLayout(layout)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setStyleSheet(css)#<------------set your stylesheet
    window = MainWindow()
    window.show()
    app.exec_()

rawDescription: How would I set individual colours for each widget item?


code:
m = re.search('something\s\((.+)\)', input_string)
if m:
    list_of_vars = m.group(1).split()

rawDescription: Trying to create a regexp

description: Trying to create a regexp


rawDescription: How to escape dict from str in python?

description: Escape dict from str in python


code:
import sys, time
from PyQt4 import QtGui, QtCore

class ProgressBar(QtGui.QWidget):
    def __init__(self, parent=None, total=20):
        super(ProgressBar, self).__init__(parent)
        self.progressbar = QtGui.QProgressBar()
        self.progressbar.setMinimum(1)
        self.progressbar.setMaximum(total)
        self.button = QtGui.QPushButton('Start')
        self.button.clicked.connect(self.handleButton)
        main_layout = QtGui.QGridLayout()
        main_layout.addWidget(self.button, 0, 0)
        main_layout.addWidget(self.progressbar, 0, 1)
        self.setLayout(main_layout)
        self.setWindowTitle('Progress')
        self._active = False

    def handleButton(self):
        if not self._active:
            self._active = True
            self.button.setText('Stop')
            if self.progressbar.value() == self.progressbar.maximum():
                self.progressbar.reset()
            QtCore.QTimer.singleShot(0, self.startLoop)
        else:
            self._active = False

    def closeEvent(self, event):
        self._active = False

    def startLoop(self):
        while True:
            time.sleep(0.05)
            value = self.progressbar.value() + 1
            self.progressbar.setValue(value)
            QtGui.qApp.processEvents()
            if (not self._active or
                value >= self.progressbar.maximum()):
                break
        self.button.setText('Start')
        self._active = False

app = QtGui.QApplication(sys.argv)
bar = ProgressBar(total=101)
bar.show()
sys.exit(app.exec_())

rawDescription: Python QT ProgressBar

description: Python QT ProgressBar


code:
def included_numbers(s):
    out = []
    for chunk in s.split():
        if '-' in chunk:
            f, t = chunk.split('-')
            out.extend(range(int(f), int(t)+1))
        else:
            out.append(int(chunk))
    return out

rawDescription: How to convert varying formats of a string into a list of int? (python)

description: Convert varying formats of a string into a list of int? (python)


code:
long_words = ['programming', 'pantaloons']
full_chunk = 'While programming, I prefer to wear my most vividly-hued pantaloons.'
for i, word in enumerate(long_words):
    full_chunk = full_chunk.replace(word, str(i))
full_chunk

rawDescription: Does Python map() allow for indexing?

description: Does Python map() allow for indexing


code:
from operator import itemgetter
import itertools
sorted_zip_list = sorted(zip_list, key=itemgetter(1))
sorted_zip_list
result = []
for _, g in itertools.groupby(sorted_zip_list, itemgetter(1)):
    result.append([e[0] for e in g])
result

rawDescription: Generate sublists of list A by grouping according to list B


code:
oldNewMap = {1: 3, 2: 3, 3: 4, 4: 2, 5: 1, 91: 6}
df['ethnicity'][df.year==year] = df['ethnicity'][df.year==year].map(oldNewMap)

rawDescription: Conditional replacement in pandas

description: Conditional replacement in pandas


code:
from configobj import ConfigObj

sample_config = """
[user01]
name = Sal
# update this value
password = abc123
"""

config = ConfigObj(sample_config.splitlines())
config['user01']['password'] = '123abc'
config.write(sys.stdout)

rawDescription: configparser is dropping comments when writing out

description: Configparser is dropping comments when writing out


code:
from timeit import timeit
list1 = ['a','b','c']
list2 = ['x','y','z']
timeit("list1 == list2", "from __main__ import list1, list2")
str1 = "abc"
str2 = "xyz"
timeit("str1 == str2", "from __main__ import str1, str2")

rawDescription: What's more efficient in python - comparing lists, or strings?


code:
#update list upon drop down
self.cbox = Combobox(self, width = 10, postcommand = self.updtcblist)

def updtcblist(self):
    list = self.getPortLst()
    self.cbox['values'] = list

rawDescription: How to update values to the listbox under Combobox in ttk Python33

description: Update values to the listbox under Combobox in ttk Python33


code:
for index, elem in enumerate(the_list):
    function_call(elem, the_list[:index] + the_list[index + 1:])

rawDescription: Python exclusive loop

description: Python exclusive loop


code:
import os
string = input("Please type the input ")
directory = "c://files//python"
for file in os.listdir(directory):
    if file.endswith(".txt"):
        filecontent = open(file, "r")
        if string in filecontent.read():
            print("The file that matches the input was found at" + file)

rawDescription: how do u make a program that checks many txt files

description: How do u make a program that checks many txt files


rawDescription: PyGObject Gtk.Entry Changing progress bar color


code:
import wx

class Frame(wx.Frame):
  def __init__(self):
    wx.Frame.__init__(self, parent=None)
    panel = Panel(parent=self)
    custom = CustomWidget(parent=panel)
    self.Show()

class Panel(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent=parent)
    self.SetSize(parent.GetClientSize())

class CustomWidget(wx.PyControl):
  def __init__(self, parent):
    wx.PyControl.__init__(self, parent=parent)

    # Create the sizer and make it work for the CustomWidget
    sizer = wx.GridBagSizer()
    self.SetSizer(sizer)

    # Create the CustomWidget's children
    text = wx.TextCtrl(parent=self)
    spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)

    # Add the children to the sizer
    sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
    sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)

    # Set sizer and fit, then layout
    self.SetSizerAndFit(sizer)
    self.Layout()

  # ------------------------------------------------------------
  #  # Make sure that CustomWidget will auto-Layout() upon resize
  #  self.Bind(wx.EVT_SIZE, self.OnSize)
  #  self.Fit()
  #
  #def OnSize(self, event):
  #  self.Layout()
  # ------------------------------------------------------------

app = wx.App(False)
frame = Frame()
app.MainLoop()

rawDescription: wxPython: wx.PyControl layout problem when it is a child of a wx.Panel

description: WxPython: wx.PyControl layout problem when it is a child of a wx.Panel


code: b = [sum(a[current: current+5]) for current in xrange(0, len(a), 5)]

rawDescription: Sum slices of consecutive values in a Python numpy array


code:
cur = conn.cursor('cursor-name') # server side cursor
cur.itersize = 10000 # how much records to buffer on a client
cur.execute("SELECT * FROM mytable;")

rawDescription: Psycopg2 uses up memory on large select query


code:
def receive(self, message):
    plaintext_body = ''
    for plain in message.bodies('text/plain'):
        plaintext_body = plain[1].decode()

    if not plaintext_body and hasattr(message, 'attachments'):
        for attachment in message.attachments:
            if attachment[0].endswith('.txt'):
                plaintext_body = attachment[1].decode()
                if plaintext_body:
                    break

rawDescription: Read .txt file attachment in Google App Engine email


code:
import sys
try:
        import setuptools
except ImportError:
        sys.exit(1)
else:
        sys.exit(0)

rawDescription: How can I tell if Python setuptools is installed?

description: Tell if Python setuptools is installed


code:
from zmq.eventloop import zmqstream, ioloop
import tornado.web
from tornado import websocket

class MyBroadcastWebsocket(websocket.WebSocketHandler):
    clients = set()

    def open(self):
        self.clients.add(self)

    @classmethod
    def broadcast_zmq_message(cls, msg):
        for client in cls.clients:
            client.write_message('Message:' + str(msg)) # Send the message to all connected clients

    def on_close(self):
        self.clients.remove(self)

def run():
    ioloop.install()
    my_stream = zmqstream.ZMQStream(my_zmq_socket) # i.e. a pull socket
    my_stream.on_recv(MyBroadcastWebsocket.broadcast_zmq_message) # call this callback whenever there's a message

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/websocket", MyBroadcastWebsocket),
    ])
    application.listen(8888)
    ioloop.IOLoop.instance()

rawDescription: Python WebSocket server that forwards messages from other server


code:
import sys
z = 5 + 5j
z.imag
z.real
sys.getsizeof(z.imag)
sys.getsizeof(z.real)
sys.getsizeof(z)

rawDescription: What's the relationship between size of integer and complex objects?


code:
set(x['created_by'] for x in dave)
list(set(x['created_by'] for x in dave))

rawDescription: How do I list occurrences of certian values found in a dictionary in a list in python?

description: List occurrences of certian values found in a dictionary in a list in python


code:
import FreeImagePy as FIPY
F = FIPY.Image()
F.new(multiBitmap = "multipage.tiff")
F.appendPage("test1.jpg")
F.appendPage("test2.jpg")
F.deletePage(0)
F.close()

rawDescription: Python library to convert jpgs to multipage tiffs


code:
import win32api
import win32con
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s', filename='watchRegistry.log')
log = logging.getLogger()

hiveToWatch = win32con.HKEY_CURRENT_USER
keyToWatch = 'Software\Microsoft\Calc'

values = {(hiveToWatch, keyToWatch, 'DateTime'): (win32con.REG_DWORD, 1),
          (hiveToWatch, keyToWatch, 'Templates'): (win32con.REG_DWORD, 0),
          (hiveToWatch, keyToWatch, 'UnitConv'): (win32con.REG_DWORD, 0)}

while True:

    for (hive, key, valueName), (valueType, value) in values.iteritems():
        handleWithSetRights = win32api.RegOpenKeyEx(hive, key, 0, win32con.KEY_SET_VALUE)
        log.info(r'Setting %s\%s\%s = %s' % (hive, key, valueName, value))
        win32api.RegSetValueEx(handleWithSetRights, valueName, 0, valueType, value)
        win32api.RegCloseKey(handleWithSetRights)

    # Open and close the handle here as otherwise the set operation above will trigger a further round
    handleToBeWatched = win32api.RegOpenKeyEx(hiveToWatch, keyToWatch, 0, win32con.KEY_NOTIFY)
    win32api.RegNotifyChangeKeyValue(handleToBeWatched, False, win32api.REG_NOTIFY_CHANGE_LAST_SET, None, False)
    win32api.RegCloseKey(handleToBeWatched)

rawDescription: How to watch the Windows registry for changes with Python

description: Watch the Windows registry for changes with Python


code:
import os
# change the directory
os.chdir('c:\dir1\dir2')
# use os to send commands to shell or dos
os.system('python program.py')
# you are done

rawDescription: running a python file thats in a diffrent directory

description: Running a python file thats in a diffrent directory


code:
results_dict = {}
for i in range(5):
    results_dict[i] = []

rawDescription: how to create list with index in name in python

description: Create list with index in name in python


code:
# retrieve file from ftp to memory,
# consider using cStringIO or tempfile modules for your actual usage

from StringIO import StringIO
from django.core.files.base import ContentFile
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.seek(0)
# feed the fetched file to Django image field
new_image.image.save(fname, ContentFile(s.read()))
s.close()

# Or
from django.core.files.base import File
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.size = s.tell()
new_image.image.save(fname, File(s))

rawDescription: How to save to a ImageField from an ftp download in Django

description: Save to a ImageField from an ftp download in Django


code:
class RelatedResource(ModelResource):
    user = fields.ToOneField(UserResource, 'user')

    class Meta:
        queryset = Related.objects.all()
        resource_name = 'related'

class UserResource(ModelResource):
    related = fields.ToOneField(RelatedResource, 'related', full=False) # Default is false

    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'

    def dehydrate(self, bundle):
        show_full = bundle.request.GET.get('full', "false").lower() == "true"
        if show_full:
            old_full = self.related.full
            self.related.full = True
            bundle.data['related'] = self.related.dehydrate(bundle)
            self.related.full = old_full
        return bundle

rawDescription: Toggle fields to be full in the url for tastypie?


code:
cpu_count = multiprocessing.cpu_count()
Pool(processes=cpu_count // 2) # Use only half of the CPUs

rawDescription: PYTHON - why multiprocessing Pool using 100% of CPU?


code:
from urllib.request import urlopen
from bs4 import BeautifulSoup

url ='http://www.websiteaddress.com'
data = urlopen(url)
soup = BeautifulSoup(data, 'html.parser')
result = soup.find('title')
print(result.get_text())

rawDescription: python beautifulsoup get html tag content

description: Python beautifulsoup get html tag content


code:
import crontab
import time

e = crontab.CronTab('*/5 * * * *') # every five minutes
while True:
    delay = e.next()
    time.sleep(delay)
    print("It's time (again)!")

rawDescription: Scheduled background functions for a Python webapp


code:
j,k=input().split(" ")
j=int(j)
k=int(k)

rawDescription: How do I input multiple values from a single line?

description: Input multiple values from a single line


code:
fun_list = []
for i in range(5):
    def fun(e, _ndx=i):
        return e[_ndx]
    fun_list.append(fun)

mylist = range(10)
print([f(mylist) for f in fun_list])

rawDescription: Creating a list of functions in python (python function closure bug?)


code: {{ article.company.all|join:", " }}

rawDescription: Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict?


code:
import pytest

@pytest.fixture(scope="module")
def myFixture1():
    return 5

@pytest.fixture(scope="module")
def myFixture2():
    return 2

@pytest.fixture(scope="module", params=["param1", "param2"])
def myFixture(request):
    if request.param == 'param1':
        return request.getfuncargvalue("myFixture1")
    elif request.param == 'param2':
        return request.getfuncargvalue("myFixture2")

def test_1(myFixture1):
    assert myFixture1 == 5

def test_2(myFixture2):
    assert myFixture2 == 2

def test_all(myFixture):
    assert myFixture in (2,5)

rawDescription: Can params passed to pytest fixture be passed in as a variable?


code:
def some_function(data, format):
    result = []
    for row in data:
        lst = []
        for count, value in enumerate(row):
            if count in format:
                string = format[count].format(value)
                lst.append(string)
            else:
                lst.append(value)
        result.append(lst)
    return result

data = [['foo1', 'bar1'], ['foo2', 'bar2']]
format = {1: '{0} says Hello world'}
print(some_function(data, format))
# prints: [['foo1', 'bar1 says Hello world'], ['foo2', 'bar2 says Hello world']]

rawDescription: storing formatting in a python dictionary

description: Storing formatting in a python dictionary


code:
class PostTable(tables.Table):
    def __init__(self, *args, **kwargs):
        super(PostTable, self).__init__(*args, **kwargs)
        self.current_Time =  datetime.utcnow().replace(tzinfo=utc)

    def render_published(self, value,record):
        tdelta = self.current_Time - record.published

rawDescription: using datetime.utcnow() with DjangoTables2 render_FOO

description: Using datetime.utcnow() with DjangoTables2 render_FOO


code:
d = {'tom':'stats', 'keys':[{'tim': 'doc', 'year': 1999},{'mum':'veg', 'nba':'qweqwe'}] }

def print_all_values(input):
    if isinstance(input, dict):
        for key, value in input.items():
            print_all_values(value)
    elif isinstance(input, list):
        for value in input:
            print_all_values(value)
    else:
        print(input)

print_all_values(d)

rawDescription: Python: print out all values of a complicated data structure (excluding hash keys)


code:
y = svc.decision_function(x)
w_norm = np.linalg.norm(svc.coef_)
dist = y / w_norm

rawDescription: SKLearn: Getting distance of each point from decision boundary?


code:
class Category(models.Model):
    groups = models.ManyToManyField(Group)
    @property
    def title(self):
        return self._title
    def save( self, *args, **kw  ):
        try:
            self._title
        except AttributeError:
            self._title= defaultdict()
        super( Category, self ).save( *args, **kw )

rawDescription: Django model class and custom property

description: Django model class and custom property


code:
table_name = name_a #name of table

# Loop through all columns of dataframe and generate one string per column:
cols_n = df.columns.tolist()
placeholder = ",".join(["%s"]*df.shape[1]) #df.shape[1] gives # of columns
column_names = ",".join(cols_n)
insrt = "INSERT INTO %s " % table_name
for qrt in range(0,df.shape[0]):
   add_SQL_a_1 = insrt + "(" + column_names + ") VALUES (" + placeholder + ")" #part 1/2
   add_SQL_a_2 = add_SQL_a_1 % list_of_tuples[qrt] #part 2/2

rawDescription: Create Python string placeholder (%s) n times


code:
import os
import shutil
import glob

src = 'source_folder'
name = 'D_folder_name'

#In your case this would be something like C:\\A
top = 'root_folder for destination'

for root, dirs, files in os.walk(top):
    if name in dirs:
        for filename in glob.glob(os.path.join(src, '*.*')):
            shutil.copy(filename, os.path.join(root,name))

rawDescription: In Windows command prompt, copy one file (or multiple files) to multiple directories that have a user specified name


code:
with open(fastaname,'r') as fastafile:
    with open(blastfilename,'r') as blastfile:
        for line in blastfile:
            fastaseq = '' # or whatever data type this is
            while True:
                fastaline = fastafile.readline()[:-1]
                if fastaline[0]=='>':
                    break
            fastaseq += fastaline
        somefunction(line,fastaseq)

rawDescription: Processing files line-by-line

description: Processing files line-by-line


code:
s = '\u003cfoo/\u003e'
s.decode( 'unicode-escape' )
s.decode( 'unicode-escape' ).encode( 'ascii' )

rawDescription: How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?

description: Treat an ASCII string as unicode and unescape the escaped characters in it in python


code:
for word in commonWords :
    text = text.replace(' '+word+' ', ' ')

rawDescription: Replacing all occurrences of words from a given set, but only if the word is not contained within another word


code:
from lxml import etree

# derive from 'object' if Python 2.X (it is default in Python 3.X)
class XmlReportGenerator(object):

    def __init__(self):
        # clearer to init instance variables here.
        self.root = etree.Element('results')
        self.doc = etree.ElementTree(self.root)

    def AddMatchRow(self,teamA,teamB, score):
        # Need self.root here
        pageElement = etree.SubElement(self.root,'Flight')
        # Added data elements (or did you want attributes?)
        etree.SubElement(pageElement,'teamA').text = teamA
        etree.SubElement(pageElement,'teamB').text = teamB
        etree.SubElement(pageElement,'score').text = score

    def Save(self,path = None):
        outFile = open('Matches.xml', 'w')
        # Need self.doc here
        self.doc.write(outFile)

# This code will run if the script is executed directly,
# but will be skipped if the script is imported by another script.
if __name__ == '__main__':
    docs = XmlReportGenerator()
    docs.AddMatchRow('FC Barcelona','Madryt','5:0')
    docs.Save()

rawDescription: Problem with defining variables in python


code:
from django.db.models import Q

model = get_object_or_404(MyModel, ~Q(status='deleted'), pk=id)

rawDescription: How to exclude results with get_object_or_404?

description: Exclude results with get_object_or_404


code:
s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu,"

import textwrap
var = textwrap.wrap(s, 100)
for line in var:
    print(len(line))

print(var)

rawDescription: Break a string into chunks, keeping words whole in Python


code:
def parent_post_get_many(result=None, search_params=None, **kw):
   for object in result['objects']:
      for child in object['children']:
         grandchild = Grandchild.query.get(child['grand_child_id'])
         child.update({'grandchild': grandchild})

api.create_api(Parent, postprocessors={'GET_MANY': [parent_post_get_many]})

rawDescription: Flask-SQLAlchemy and Flask-Restless not fetching grandchildren


code:
class RunSelenium(object):

    def printTest(self):
        print('printTest 1!')

    @staticmethod
    def printTest2():
        print('printTest 2!')

def printTest3():
    print('printTest 3!')

# Call a method from an instantiated class
RunSelenium().printTest()

# Call a static method
RunSelenium.printTest2()

# Call a simple function
printTest3()

rawDescription: Trouble accessing another function in the same class (Python)


code:
import plotly.plotly as py
import plotly.tools as tls
from plotly.graph_objs import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates

def line(x, a, b):
    return a * x + b

popt, pcov = curve_fit(line, trend_dates.ravel(), trend_lines.ravel())

fig1 = plt.figure(figsize=(8,6))
plt.plot_date(new_x, trend_lines, 'o', label='Lines')
z = np.polyfit(new_x, trend_lines, 1)
p = np.poly1d(z)
plt.plot(new_x, p(new_x), '-', label='Fit')
plt.title('Lines per day')
fig = tls.mpl_to_plotly(fig1)
fig['layout'].update(showlegend=True)
fig.strip_style()
py.iplot(fig)

rawDescription: Trendline in Plotly Python

description: Trendline in Plotly Python


code:
#trys to create dictionary from african country list
from collections import defaultdict

dic = defaultdict(list)   # automatically creates lists to append to in the dict

for line in sys.stdin:
    mylist = line.split('|')    # call it mylist instead of list
    links = mylist[4].split()
    new = links[0] + ' ' + links[-1]   # can just use -1 to reference last item
    dic[new].append(mylist[4])         # append the item to the list in the dict
                                # automatically creates an empty list if needed

rawDescription: How to append lists in a dictionary in Python?

description: Append lists in a dictionary in Python


code:
class Parent(object):

    @classmethod
    def _match_slug(cls, slug):
        """ Method that checks if we still have a match in the db for current 'slug' """
        return cls.objects.filter(slug=slug).count()

class Child(Parent):
    ...

c = Child()
# Equivalent to Parent._match_slug(c.__class__, x)
c._match_slug(x)

rawDescription: Python Inheritance, Move method to a common class


code:
df['FishersExact'] = df.apply(
    lambda r: scipy.stats.fisher_exact([[r.numerator1, ... ]]),
    axis=1)

rawDescription: Fisher's Exact in scipy as new column using pandas


code:
import random

fortunes = ['fortune1', 'fortune2', 'fortune3']

while True:
    input("Press enter to receive a fortune. ")
    print(random.choice(fortunes))

rawDescription: Random/ Loop challenge

description: Random/ Loop challenge


code:
op.create_foreign_key(
    'fk_location_message_campaign',
    'location_messages', 'campaigns',
    ['campaign_id'], ['id'],
)

rawDescription: How can I add a foreign key constraint on an existing table column via SQLAlchemy?

description: Add a foreign key constraint on an existing table column via SQLAlchemy


code:
sns.factorplot(x='day', y='total_bill', hue='sex', data=tips,
               row='smoker', col='time', kind='violin')

rawDescription: Prevent Overlapping in FacetGrid using col, row, and hue


code: df.loc[:, 'new_col'] = df.A.map(lambda x: x[0])

rawDescription: Accesing every 1st element of Pandas DataFrame column containing lists


code:
import pandas as pd
df['ID'] = pd.read_sql_query('select ifnull(max(id),0)+1 from db_table',cnx).iloc[0,0]+range(len(df))

rawDescription: How to get autoincrement values for a column after uploading a Pandas dataframe to a MySQL database

description: Get autoincrement values for a column after uploading a Pandas dataframe to a MySQL database


code: module = __import__(sys.argv[1])

rawDescription: Python, dynamically invoke script

description: Python, dynamically invoke script


code:
def isGoodFn(f):
    testData = [1,2,3,8,38,73,159]   # random test input
    goodEnough = 0.8 * len(testData)  # need 80% pass rate

    try:
        good = 0
        for i in testData:
            if type(f(i)) is int:
                good += 1
        return good >= goodEnough
    except:
        return False

rawDescription: homogenization the functions can be compiled into a calculate networks?

description: Homogenization the functions can be compiled into a calculate networks


code:
from IPython import embed
embed()

rawDescription: Getting PyScripter Portable to work with IPython


code:
class MainWindow:
    #...
    def edit(self):
        EditWindow()

class EditWindow(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)
        self.add = Button(self, text="ADD", command=self.add)
        self.remove = Button(self, text="REMOVE", command=self.remove)
        self.add.pack()
        self.remove.pack()

rawDescription: Difficulty understand Tkinter mainloop() in python


code:
def generate_randomized_set_valued_hash_function(n, k):
    hashfunc = generate_randomized_hash_function()
    def set_valued_hashfunc(x):
        rng = random.Random(hashfunc(x))
        return set(rng.sample(xrange(n), k))
    return set_valued_hashfunc

rawDescription: Creating random hash function that returns a set


code:
#!/usr/bin/env python2.7
import time, threading

class Ticker(threading.Thread):
  """A very simple thread that merely blocks for :attr:`interval` and sets a
  :class:`threading.Event` when the :attr:`interval` has elapsed. It then waits
  for the caller to unset this event before looping again.

  Example use::

    t = Ticker(1.0) # make a ticker
    t.start() # start the ticker in a new thread
    try:
      while t.evt.wait(): # hang out til the time has elapsed
        t.evt.clear() # tell the ticker to loop again
        print time.time(), "FIRING!"
    except:
      t.stop() # tell the thread to stop
      t.join() # wait til the thread actually dies

  """
  # SIGALRM based timing proved to be unreliable on various python installs,
  # so we use a simple thread that blocks on sleep and sets a threading.Event
  # when the timer expires, it does this forever.
  def __init__(self, interval):
    super(Ticker, self).__init__()
    self.interval = interval
    self.evt = threading.Event()
    self.evt.clear()
    self.should_run = threading.Event()
    self.should_run.set()

  def stop(self):
    """Stop the this thread. You probably want to call :meth:`join` immediately
    afterwards
    """
    self.should_run.clear()

  def consume(self):
    was_set = self.evt.is_set()
    if was_set:
      self.evt.clear()
    return was_set

  def run(self):
    """The internal main method of this thread. Block for :attr:`interval`
    seconds before setting :attr:`Ticker.evt`

    .. warning::
      Do not call this directly!  Instead call :meth:`start`.
    """
    while self.should_run.is_set():
      time.sleep(self.interval)
      self.evt.set()

rawDescription: python: windows equivalent of SIGALRM

description: Python: windows equivalent of SIGALRM


code:
from Tkinter import *
import ttk
from PIL import ImageTk, Image

def showImage():
        lbl1.configure(image=image_tk)
        btn.configure(text = "load image!", command=showImage1)

def showImage1():
        lbl1.configure(image=image_tk1)
        btn.configure(text = "load image!", command=showImage)

root = Tk()
c = ttk.Frame(root, padding=(5, 5, 12, 0))
c.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0,weight=1)

fname = "a.jpg"
image_tk = ImageTk.PhotoImage(Image.open(fname))

fname1 = "b.jpg"
image_tk1 = ImageTk.PhotoImage(Image.open(fname1))  # new image object

btn = ttk.Button(c, text="load image", command=showImage)
lbl1 = ttk.Label(c)
btn.grid(column=0, row=0, sticky=N, pady=5, padx=5)
lbl1.grid(column=1, row=1, sticky=N, pady=5, padx=5)

root.mainloop()

rawDescription: Display new image on Tkinter button command


rawDescription: converting string to int python

description: Converting string to int python


code:
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# generated by wxGlade HG on Tue Oct 04 12:45:03 2011

import wx

# begin wxGlade: extracode
# end wxGlade

class MainGUI(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MainGUI.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.button_3 = wx.Button(self, -1, "Select All")
        self.button_4 = wx.Button(self, -1, "DeselectAll")
        self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        self.button_1 = wx.Button(self, -1, "Refresh")
        self.button_2 = wx.Button(self, -1, "Execute")
        self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MainGUI.__set_properties
        self.SetTitle("frame_1")
        self.SetBackgroundColour(wx.Colour(255, 170, 5))
        self.list_ctrl_1.SetMinSize((200, 264))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MainGUI.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_4.Add(self.button_3, 0, wx.ALL, 5)
        sizer_4.Add(self.button_4, 0, wx.ALL, 5)
        sizer_4.Add((20, 20), 1, wx.EXPAND, 0)
        sizer_1.Add(sizer_4, 0, wx.EXPAND, 0)
        sizer_2.Add(self.list_ctrl_1, 0, wx.ALL|wx.EXPAND, 5)
        sizer_2.Add(self.text_ctrl_1, 0, wx.ALL|wx.EXPAND, 5)
        sizer_3.Add(self.button_1, 0, wx.ALL, 5)
        sizer_3.Add(self.button_2, 0, wx.ALL, 5)
        sizer_2.Add(sizer_3, 0, wx.EXPAND, 0)
        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
        sizer_1.Add(self.text_ctrl_2, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

# end of class MainGUI

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MainGUI(None, -1, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

rawDescription: Panel arrangement in wxpython

description: Panel arrangement in wxpython


rawDescription: How to get queryset as result for join Query using Django ORM?

description: Get queryset as result for join Query using Django ORM


code:
seed = random.randint(0, sys.maxint)
myRand = random.Random(seed)

rawDescription: how to query seed used by random.random()?

description: Query seed used by random.random()


code:
hero = Hero()  # create one Hero instance
hero.view_inventory()  # and make the method calls on this very instance
hero.add_inventory("Key")
hero.view_inventory()

rawDescription: When I run the view_inventory function after appending to the list, the appending item doesn't show


code: max(dateList)

rawDescription: Compare two date strings in python (given in specified format in List)


code:
#example figure1
ax1.plot(range(2),range(2),linewidth=2)
ax1.minorticks_on()
ax1.tick_params('both', length=20, width=2, which='major')
ax1.tick_params('both', length=10, width=1, which='minor')

rawDescription: Make longer subplot tick marks in matplotlib?


code:
def workqueue():
    def wrappedWork(item):
        value = startWork(item)
        if value != "Ok":
            workq.put(item)
    while True:
        item = workq.get()
        gevent.spawn(wrappedWork, item)

rawDescription: Running all Entries from Queue concurrently with gevent.spawn


code:
class RegisterAdmin(admin.ModelAdmin):
    list_display = ['tag', 'active', 'created_at', 'ownership_name']

    def ownership_name(self, obj):
        return obj.person.ownership_name

admin.site.register(Register, RegisterAdmin)

rawDescription: Display fields from multiple models in the standard list admin


code:
def make_proceed(name):
    def proceed(self, *args):
        func = getattr(otherobj, name)
        result = func(*args)
        # result = ... process result  ..
        return result
    return proceed

class dispatch(object):
  def __init__(self, cond=1):
    for index in range(1, cond):
      name = 'step%u' % (index,)
      setattr(self, name, new.instancemethod(make_proceed(name), self, dispatch))

rawDescription: How to dynamically add members to class

description: Dynamically add members to class


code:
from django.db.models import CharField
from django.db.models import  Q

fields = [f for f in table._meta.fields if isinstance(f, CharField)]
queries = [Q(**{f.name: SEARCH_TERM}) for f in fields]

qs = Q()
for query in queries:
    qs = qs | query

table.objects.filter(qs)

rawDescription: searching all fields in a table in django

description: Searching all fields in a table in django


code:
import urllib

def download(url, bytes = 1024):
    """Copy the contents of a file from a given URL
    to a local file.
    """
    webFile = urllib.urlopen(url)
    localFile = open(url.split('/')[-1], 'w')
    localFile.write(webFile.read(bytes))
    webFile.close()
    localFile.close()

rawDescription: What is the best way to open a URL and get up to X bytes in Python?


code:
import csv
import time

HEADER = ['LIGHT', 'VOLTAGE']

# ...

def processing_loop(csvfile):
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(HEADER)

    # ...
    while True:
        light = ReadChannel(light)
        voltage =  ConvertVoltage(light)
        csv_writer.writerow([light, voltage])
        csvfile.flush()
        time.sleep(5)

with open('results.csv', 'w') as csvfile:
    processing_loop(csvfile)

rawDescription: Write to python csv in whileloop

description: Write to python csv in whileloop


code:
xl = Dispatch( "Excel.Application")

xl.Visible = False

xlFile = "C:/tab_colour.xls"

wkb = xl.Workbooks.Open(xlFile)

sheet = xl.Worksheets.Item("SVP INFO")

sheet.Tab.Color = 255

wkb.Save()

wkb.Close()

xl.Quit()

xl = None

rawDescription: How, I can change Excel sheet tab background colour by python


code:
import wx

# Create a .png image with something drawn on a white background
# and put the path to it here.
IMAGE_PATH = 'image.png'

class ShapedFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Shaped Window",
                style = wx.FRAME_SHAPED | wx.SIMPLE_BORDER)
        self.hasShape = False
        self.delta = wx.Point(0,0)

        # Load the image
        image = wx.Image(IMAGE_PATH, wx.BITMAP_TYPE_PNG)
        image.SetMaskColour(255,255,255)
        image.SetMask(True)
        self.bmp = wx.BitmapFromImage(image)

        self.SetClientSize((self.bmp.GetWidth(), self.bmp.GetHeight()))
        dc = wx.ClientDC(self)
        dc.DrawBitmap(self.bmp, 0,0, True)
        self.SetWindowShape()
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_RIGHT_UP, self.OnExit)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
    def OnEraseBackground(self,evt=None):
        pass
    def SetWindowShape(self, evt=None):
        r = wx.RegionFromBitmap(self.bmp)
        self.hasShape = self.SetShape(r)

    def OnDoubleClick(self, evt):
        if self.hasShape:
            self.SetShape(wx.Region())
            self.hasShape = False
        else:
            self.SetWindowShape()

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bmp, 0,0, True)

    def OnExit(self, evt):
        self.Close()

    def OnLeftDown(self, evt):
        self.CaptureMouse()
        pos = self.ClientToScreen(evt.GetPosition())
        origin = self.GetPosition()
        self.delta = wx.Point(pos.x - origin.x, pos.y - origin.y)

    def OnMouseMove(self, evt):
        if evt.Dragging() and evt.LeftIsDown():
            pos = self.ClientToScreen(evt.GetPosition())
            newPos = (pos.x - self.delta.x, pos.y - self.delta.y)
            self.Move(newPos)

    def OnLeftUp(self, evt):
        if self.HasCapture():
            self.ReleaseMouse()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    ShapedFrame().Show()
    app.MainLoop()

rawDescription: How to blit a image directly to the screen without a window?

description: Blit a image directly to the screen without a window


rawDescription: Excluding captured group in re.split

description: Excluding captured group in re.split


code:
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
import serial

app = QtGui.QApplication([])

p = pg.plot()
p.setWindowTitle('live plot from serial')
curve = p.plot()

data = [0]
raw=serial.Serial('COM9', 115200)

def update():
    global curve, data
    line = raw.readline()
    if ("hand" in line):
       line=line.split(":")
       if len(line)==8:
            data.append(float(line[4]))
            xdata = np.array(data, dtype='float64')
            curve.setData(xdata)
            app.processEvents()

timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

rawDescription: Fast plotting data in python

description: Fast plotting data in python


code:
import os,sys,random
import pygame
# NEVER use from ... import *, even if pygame docs tell you to do so.

def disp(phrase, loc, screen, color): # func to display text
    s = font.render(phrase, True, color)
    screen.blit(s, loc)

def draw_star(star): # drawing a star
    # you only need to change a pixel, so use set_at, not draw.line
    screen.set_at((star[0], star[1]), (255, 255, 255))
    star[0] -= 1
    if star[0] < 0:
        star[0] = screen.get_width()
        star[1] = random.randint(0, screen.get_height())

# Divide your code into parts on the basis of what it does like
# initialising pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption('Menu')
font = pygame.font.Font('freesansbold.ttf', 40)
clock = pygame.time.Clock()

# defining the image/marker
image = pygame.Surface((30,50))
image.fill((0,0,0))
pygame.draw.polygon(image,(255,255,255),[(0,0),(0,50),(25,25)],5)

# creating list of stars, used multi-line for loop for readability
stars = []
for i in range(200):
    x = random.randint(0, screen.get_width())
    y = random.randint(0, screen.get_height())
    stars.append([x,y])

pos = 1
while True:
    # events
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif e.type == pygame.KEYDOWN:
            if e.key == pygame.K_DOWN:
                pos += 1
                if pos > 4:
                    pos = 1
            elif e.key == pygame.K_UP:
                pos -= 1
                if pos < 1:
                    pos = 4
            elif e.key == pygame.K_RETURN:
                if pos == 1:
                    import MathsvadersReal
                elif pos == 4:
                    pygame.quit()
                    sys.exit()

    screen.fill((0,0,0))

    # displaying text,image
    disp("Begin"       , (100,100), screen, (255, 255, 255))
    disp("My Profile"  , (100,200), screen, (255, 255, 255))
    disp("Instructions", (100,300), screen, (255, 255, 255))
    disp("Quit"        , (100,400), screen, (255, 255, 255))
    screen.blit(image,(50, (pos * 100)-10 ))

    # drawing stars
    for star in stars:
        draw_star(star)

    pygame.display.flip()
    clock.tick(22)

rawDescription: Can't get my GUI button to run on top of my stars


code:
from matplotlib import pyplot as plt
from matplotlib import rcParams

rcParams['axes.color_cycle'] = ['r','g','k']
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax1 = plt.twinx(ax)

line = []

line.append(ax.plot([1,2,3],[4,5,6])[0])
line.append(ax.plot([1,2,3],[7,6,4])[0])

for advance in range(len(line)):
    ax1._get_lines.color_cycle.next()

ax1.plot([1,2,3],[5,3,1])

rawDescription: matplotlib colororder and twinx

description: Matplotlib colororder and twinx


code:
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
import StringIO
s = StringIO.StringIO()
df.to_csv(s)
s.getvalue()

rawDescription: Convert Pandas dataframe to csv string

description: Convert Pandas dataframe to csv string


code:
# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")

#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is  longer then the result you want to take
#a look at is result 2

result1 = ''
result2 = ''

#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)

#loop through the characters
for i in range(maxlen):
  #use a slice rather than index in case one string longer than other
  letter1=str1[i:i+1]
  letter2=str2[i:i+1]
  #create string with differences
  if letter1 != letter2:
    result1+=letter1
    result2+=letter2

#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)

rawDescription: Comparing two strings and returning the difference. Python 3


code:
class Feed(object):
    def __init__(self, file_name, sep, naming_convention=None):
        self.file_name = file_name
        self.feed_item_naming = naming_convention
        self.sep = sep
        self.feed = self.load_feed()

    def get_head(self, file=None):#lmao...
        '''
            Get the header
            '''

        if not file:
            head = open(self.file_name).readline().split(self.sep)
        else:
            head = file[0].split(self.sep)
        return head

    def __repr__(self):
        return repr(self.feed)

    def load_feed(self):
        '''
            load a feed object
            set the key of each item to the naming convention
            if we have multiple item names we increment the name bill becomes bill_2 and then bill_3 etc...
            '''

        #first we open the file and grab the headers
        file = [x.rstrip() for x in open(self.file_name).readlines()]
        self.header = self.get_head(file)
        if not self.feed_item_naming and self.feed_item_naming not in self.header:
            self.feed_item_naming = self.header[0]
        data = {}
        for line in file[1:]:
            if line != '':
                line = line.split(self.sep)
                pos = line[self.header.index(self.feed_item_naming)]
                while pos in data:
                    try:
                        ending = int(pos[-1])+1
                        pos.replace(pos[-1], ending)
                    except:
                        pos = pos+'_2'
                data[pos] = {}
                for item in self.header:
                    data[pos][item] = line[self.header.index(item)]
        return data

    def unload_feed(self, file_name=None, sep=None):
        '''
            write the modified feed back out to a data file
            '''

        if not file_name:
            file_name = self.file_name
        if not sep:
            sep = self.sep

        with open(file_name, 'wb') as file:
            for i in self.header:
                if i != self.header[-1]:
                    file.write(i+sep)
                else:
                    file.write(i)
            file.write('\n')
            for i in self.feed:
                for x in self.header:
                    if x != self.header[-1]:
                        file.write(str(self.feed[i][x])+sep)
                    else:
                        file.write(str(self.feed[i][x]))
                file.write('\n')

    def add_key(self, key, default_value=None):
        '''
            Add a key to each of the items
            '''
        if key not in self.header:
            for i in self.feed:
                self.feed[i][key]=default_value
            self.header.append(key)

    def get_key_value(self, item, key):
        '''
            get the value for the items key
            '''

        return self.feed[item][key]

    def get_item(self, item):
        '''
            get an individual item
            '''

        return self.feed[item]

    def set_key_value(self, item, key, value):
        '''
            set the value of each items key
            {item:{key:value, key:value}, item...etc}
            '''

        self.feed[item][key] = value

    def set_key_values(self, item, key_value_dict):
        '''
            set multiple key values for an item
            '''

        for k,v in key_value_dict.iteritems():
            self.set_key_value(item, k, v)

    def add_item(self, item):
        '''
            Add a new item
            '''
        while item in self.feed:
            try:
                end = str(int(item[-1])+1)
                item = item.replace(item[-1], end)
            except:
                item = item+'_2'

        self.feed[item] = {}
        self.feed[item][self.feed_item_naming] = item
        for i in self.header:
            if i != self.feed_item_naming:
                self.feed[item][i] = None

f = Feed('file.txt', '_____', 'Name') #initialize a new feed object, make sure that all seperators are the same for each item in your file
f.add_item('Angela') #add a new item
f.set_key_values('Angela', {'Height(m)':5, 'Weight(kg)':123}) #set the new items height and weight
f.add_key('Position')#create a new key for each item
f.unload_feed() #write the feed back to the file
print(f)

rawDescription: How to add a new line in an open txt file in python?

description: Add a new line in an open txt file in python


code:
from myModules.myModule import myClass
# this will cause myModule.py to be evaluated.  only myClass is in scope

from myModules import myModule
# since myModule has already been imported, myModule.py is not evaluated again.
# but now myModule is in scope.

reload(myModule)
# this will cause myModule.py to be evaluated again.

rawDescription: Reload module in python

description: Reload module in python


code:
from tornado.process import Subprocess
from subprocess import PIPE
from tornado import gen

@gen.coroutine
def run_command(command):
    process = Subprocess([command], stdout=PIPE, stderr=PIPE, shell=True)
    yield process.wait_for_exit()  # This waits without blocking the event loop.
    out, err = process.stdout.read(), process.stderr.read()
    # Do whatever you do with out and err

rawDescription: How make an async RequestHandler in tornado python


code:
vs = ['v1', 'v2', 'v3']
df
pd.concat([df.str.count(v) for v in vs], axis=1, keys=vs)

rawDescription: Encoding list variable to flag variable

description: Encoding list variable to flag variable


code:
import timeit

example = 'map(lambda x: x + 1, range(100000)'
t = timeit.Timer(example)
t.timeit()

rawDescription: Test which function is faster

description: Test which function is faster


code:
# -*- coding: utf-8 -*-

import re
match = re.search(u'\\bשלום\\b', u'שלום עולם', re.U)

rawDescription: Using end of word mark with unicode in regular expressions in Python


code: __all__ = ['my_class_name']

rawDescription: Static method vs module function in python


code:
from fractions import Fraction
d = [Fraction(1, 8), Fraction(1, 7), Fraction(1, 6), Fraction(1, 5), Fraction(1, 4),          Fraction(2, 7), Fraction(1, 3), Fraction(3, 8), Fraction(2, 5) , Fraction(3, 7), Fraction(1,   2), Fraction(4, 7), Fraction(3, 5), Fraction(5, 8), Fraction(2, 3), Fraction(5, 7), Fraction(3, 4), Fraction(4, 5), Fraction(5,6), Fraction(6, 7), Fraction(7, 8)]
d.index(Fraction(1,6))

rawDescription: Finding index of list item which is assembled by Fraction class


code:
neis = g.neighbors("a", mode="out")
g.vs[neis]["name"]

rawDescription: IGraph python get neighbour Vetrices from Vertex


code:
deb = '20120601'
fin = '20120831'

start = datetime.datetime.strptime(deb, "%Y%m%d")
end = datetime.datetime.strptime(fin, "%Y%m%d")

dif = int((end-start).total_seconds()/3600) ## time difference in hours

date_list = [(start + datetime.timedelta(hours=x)).strftime("%Y%m%d%H") for x in range(dif+1)]

rawDescription: List of date with hours between two dates


code:
root = Tk()

label1  = Label(root, text="label1")
button1 = Button(root, text="button1")
label2  = Label(root, text="label2")
button2 = Button(root, text="button2")

for c in sorted(root.children):
    root.children[c].pack()

root.mainloop()

rawDescription: Can you pack multiple Tkinter widgets at a time rather than packing them individually?

description: Pack multiple Tkinter widgets at a time rather than packing them individually


code:
L = [1, 2, 3]
def bar():
    return 'shenanigan', [4]

myVar, L[len(L):] = bar()
L

rawDescription: Append part of result into list in python


code:
from collections import Counter

# 1 sheep = 6 rabbits
#
# 1 pig = 2 sheep = 12 rabbits = 1 sheep + 6 rabbits
#
# 1 cow = 3 pig = 6 sheeps = 36 rabbit etc.

TABLE = {
         'rabbit': 1,
         'sheep': 6,
         'pig': 12,
         'cow': 36,
         }

def get_trades(amount, l=()):
    '''
    Recursive function that returns a list of all possible trades as tuples
    '''
    if amount < 0 : return [()] # bad trade (not enough money)
    if amount == 0 : return [l] # bingo!!! we have a full trade possibly.
    possible_trades = []
    animals_sorted = sorted(TABLE, key= lambda key: TABLE[key], reverse=True)
    if l:
        animals_sorted = animals_sorted[animals_sorted.index(l[-1]):] #preventing duplicates - since order doesn't matter
    for something in animals_sorted:
        value = TABLE[something]

        trades = get_trades(amount-value, l + (something,)) #get possible trades for l+something ...
        possible_trades.extend(trades)
    return possible_trades

def get_trades_counters(amount):
    return [Counter(t) for t in get_trades(amount)]

def main():
    print(get_trades_counters(TABLE['pig']))
    print(get_trades_counters(2*TABLE['pig']))
    print(get_trades_counters(2*TABLE['cow']))

if __name__ == '__main__':
    main()

rawDescription: Django text game trade table

description: Django text game trade table


code:
def outer(outer_param):
    # `outer` has no free variables
    outer_var = 2

    def inner(inner_param):
        # `outer_param` and `outer_var` are free variables of `inner`
        inner_var = outer_param + outer_var + inner_param
        return inner_var

rawDescription: free variables in nested function in python

description: Free variables in nested function in python


rawDescription: Plotting a graph with matplotlib where X axis values are not evenly spread


code:
def buildtree(inorder, preorder):
    root_val = preorder[0]
    left_size = inorder.index(root_val) # size of the left subtree

    if left_size > 0:
        left = buildtree(inorder[:left_size], preorder[1:left_size+1])
    else:
        left = None

    if (left_size + 1) < len(inorder):
        right = buildtree(inorder[left_size+1:], preorder[left_size+1:])
    else:
        right = None

    return ListBinaryTree(root_val, left, right)

rawDescription: Reconstructing a binary tree from infix and prefix expressions [python]


code:
from PyQt4 import QtCore,QtGui
import time

class Listener(QtCore.QThread):
    def __init__(self):
        super(Listener,self).__init__()

    def run(self):
        print('listener: started')
        while True:
            time.sleep(2)

    def connect_slots(self, sender):
        self.connect(sender, QtCore.SIGNAL('testsignal'), self.say_hello)

    def say_hello(self):
        print('listener: received signal')

class Sender(QtCore.QThread):
    def __init__(self):
        super(Sender,self).__init__()

    def run(self):
        for i in range(5):
            print('sender: sending signal')
            self.emit(QtCore.SIGNAL('testsignal'))
            time.sleep(2)
        print('sender: finished')

if __name__ == '__main__':
    o_qapplication = QtGui.QApplication([])
    my_listener = Listener()
    my_sender = Sender()
    my_listener.connect_slots(my_sender)
    my_listener.start()
    my_sender.start()
    i_out = o_qapplication.exec_()

rawDescription: Threading and Signals problem in PyQt

description: Threading and Signals problem in PyQt


code:
import datetime

db.test_collection.find({'date': {'$gte': datetime.datetime(2014, 6, 3, 16, 46) }})

rawDescription: mongodb query for date fields

description: Mongodb query for date fields


code: fd = open (data_file, 'w', 100 * size_of_line)

rawDescription: Optimized write to FS in Python

description: Optimized write to FS in Python


code:
args = ['self']
for C in Three.__mro__:
    if '__init__' in C.__dict__:
        args += inspect.getargspec(C).args[1:]

rawDescription: Retrieving arguments from a class with multiple inheritance


code:
def my_pre_post_callback(resource, request):
    allowId = request.args.get('allowId')
    ...

rawDescription: what is the reason that python-eve drops lookup parameters on POST operations?

description: What is the reason that python-eve drops lookup parameters on POST operations


code:
def sub_function():
    nonlocal variable

rawDescription: Python 3 Nested Functions Variable

description: Python 3 Nested Functions Variable


code:
for k, v in my_dict.items():
    my_dict[k] = str(sum(int(c) for c in v))

rawDescription: Changing string dictionary values into integers and adding them up


code: ''.join(c.lower() for c in s if not c.isspace())

rawDescription: Remove whitespace and make all lowercase in a string for python


code:
mybuffer = StringIO.StringIO(open('file.pdf').read())
subprocess.call('pdftk ...', stdin=mybuffer)

rawDescription: Trying to split a large .pdf into multiple files. (python, pdftk)


code:
#!/usr/bin/env python3

import os

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

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="shells")
        self.resize(1000, 1000)

        table = Gtk.Table(2, 2, True)
        self.add(table)

        palette = [Gdk.color_parse('red')] * 16
        terminal1 = Vte.Terminal()
        terminal1.connect('realize', self.on_realize_terminal)
        terminal2 = Vte.Terminal()
        terminal2.connect('realize', self.on_realize_terminal)
        terminal3 = Vte.Terminal()
        terminal3.connect('realize', self.on_realize_terminal)
        terminal4 = Vte.Terminal()
        terminal4.connect('realize', self.on_realize_terminal)

        scrolledwindow1 = Gtk.ScrolledWindow()
        scrolledwindow1.add(terminal1)

        scrolledwindow2 = Gtk.ScrolledWindow()
        scrolledwindow2.add(terminal2)

        scrolledwindow3 = Gtk.ScrolledWindow()
        scrolledwindow3.add(terminal3)

        scrolledwindow4 = Gtk.ScrolledWindow()
        scrolledwindow4.add(terminal4)

        terminal1.fork_command_full(Vte.PtyFlags.DEFAULT, os.environ['HOME'], ["/bin/sh"],
                                   [], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
        terminal2.fork_command_full(Vte.PtyFlags.DEFAULT, os.environ['HOME'], ["/bin/sh"],
                                   [], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
        terminal3.fork_command_full(Vte.PtyFlags.DEFAULT, os.environ['HOME'], ["/bin/sh"],
                                   [], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
        terminal4.fork_command_full(Vte.PtyFlags.DEFAULT, os.environ['HOME'], ["/bin/sh"],
                                   [], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)

        terminal1.set_colors(Gdk.color_parse('red'), Gdk.color_parse('black'), palette)
        terminal2.set_colors(Gdk.color_parse('green'), Gdk.color_parse('black'), palette)
        terminal3.set_colors(Gdk.color_parse('yellow'), Gdk.color_parse('black'), palette)
        terminal4.set_colors(Gdk.color_parse('blue'), Gdk.color_parse('black'), palette)

        table.attach(scrolledwindow1, 0, 1, 0, 1)
        table.attach(scrolledwindow2, 1, 2, 0, 1)
        table.attach(scrolledwindow3, 0, 1, 1, 2)
        table.attach(scrolledwindow4, 1, 2, 1, 2)

    def on_realize_terminal(self, terminal):
        font = terminal.get_font()
        font.set_size(16 * Pango.SCALE)

if __name__ == '__main__':
    win = MainWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()

rawDescription: Using python, GTK+3, Vte libs. How to change the font size of a terminal?


code:
import random

data = {
    'NL': ["Assen", "Almere", "Leeuwarden", "Nijmegen", "Groningen", "Maastricht",
           "Eindhoven", "Amsterdam", "Enschede", "Utrecht", "Middelburg", "Rotterdam"],
    'NO': ["Fredrikstad", "Baerum", "Oslo", "Ringsaker", "Gjovik", "Drammen",
           "Sandefjord", "Skien", "Arendal", "Kristiansand", "Stavanger", "Bergen",
           "Forde", "Alesund", "Trondheim", "Stjordal", "Bodo", "Tromso", "Alta"]
}

random_country = random.choice(list(data.keys()))
random_city = random.choice(data[random_country])

print(random_country, random_city)
# NO Drammen

rawDescription: Choosing a random item from one of two lists, based on a random item from a third


code:
class Calculations(object):
  def __init__(self):
    self.running_total = 0  # or w/ever
  def calculate(self):
    ...

calc = Calculations()

rawDescription: Alternative ways to instantiate a class in Python


code:
from myapp.models import Entry
from django.db.models import Q
Entry.objects.filter(~Q(id = 3))

rawDescription: How do I do a not equal in Django queryset filtering?

description: Do a not equal in Django queryset filtering


code:
import re
filterE = "x.y.prop1====1 and x.y.prop2>=2 and x.y.prop1<3 or x.y.prop4>9"
re.split(r'((?<!=)==(?!=)|<=|>=|!=|<|>)', filterE)

rawDescription: split a string on python math comparators

description: Split a string on python math comparators


code:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageEnhance

width=854
height=480
opacity=0.8
text='copyright'
filename = 'result.png'
black = (0,0,0)
white = (255,255,255)
transparent = (0,0,0,0)

font = ImageFont.truetype('verdana.ttf',15)
wm = Image.new('RGBA',(width,height),transparent)
im = Image.new('RGBA',(width,height),transparent) # Change this line too.

draw = ImageDraw.Draw(wm)
w,h = draw.textsize(text, font)
draw.text(((width-w)/2,(height-h)/2),text,white,font)

en = ImageEnhance.Brightness(wm)
#en.putalpha(mask)
mask = en.enhance(1-opacity)
im.paste(wm,(25,25),mask)

im.save(filename)

rawDescription: Python text with alpha channel background


code:
from operator import itemgetter
from itertools import islice
import  csv

with open("in.txt") as f, open('newindex1.txt','w') as out:
    r = csv.reader(f, delimiter=" ")
    wr = csv.writer(out, delimiter=" ")
    for row in iter(lambda: list(islice(r, 0, 3, 3)), []):
        wr.writerow(map(itemgetter(0, 2), row)[0])

rawDescription: How to extract columnes from Python list?

description: Extract columnes from Python list


code:
class UserProfile(models.Model):
    id = models.BigIntegerField(primary_key = True)
    user = models.OneToOneField(User)
    avatar = models.ImageField(blank=True, upload_to=get_image_path, default='/static/image/avatar/male.png')
    age = models.IntegerField(default=4, validators=[MinValueValidator(3), MaxValueValidator(99)])

rawDescription: Multiple default values specified for column "id" of the table


code:
from subprocess import call

while True:
    try:
        call(["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"], shell=True)
        call(["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"], shell=True)
    except KeyboardInterrupt:
        break  # The answer was in the question!

rawDescription: How to break this loop in Python by detecting key press

description: Break this loop in Python by detecting key press


code:
x = 'asdf foo\nHi\nBar thing'
x.split()

rawDescription: How to split string with 2 arguments?

description: Split string with 2 arguments


code:
import ast
text = '(1,2.556)'
vector = ast.literal_eval(text)
print(vector)

rawDescription: python split a vector format string

description: Python split a vector format string


code:
x = column_width - image_width

sheet.insert_bitmap(filepath_to_bmp, row, col, x)

rawDescription: Python XLWT - Insert Image aligned to top-right corner of cell


code:
df['Monday-Friday'] = df['days'].isin(range(5)).astype(int)
df['Saturday'] = (df['days'] == 5).astype(int)
df['Sunday'] = (df['days'] == 6).astype(int)

rawDescription: How to separate Monday-Friday from Saturday and Sunday Pandas?

description: Separate Monday-Friday from Saturday and Sunday Pandas


code:
Servers=[]

''' Servers Metaclass that handles addition of servers to the list '''
class MetaServer(type):
    def __init__(self, name, bases, attrs):
        self.name = name.capitalize()
        Servers.append(self)
        super(MetaServer, self).__init__(name, bases, attrs)

class ServerBase:
    __metaclass__ = MetaServer
    name='' #name of the specific server class, for each server class

    def __init__(self):
        self.connected = False

rawDescription: Override __import__ in python

description: Override __import__ in python


code:
import maya.cmds as cmds
from functools import partial

def fillTemp(*args):
    theElements = cmds.rowColumnLayout ('listColumn', query=True, childArray=True)
    if theElements > 0:
        for element in theElements:
            cmds.deleteUI (element)
    objectList = cmds.ls(type='nCloth')
    for item in objectList:
        cmds.setParent ('listColumn')
        cmds.text ((item+'labelText'), label=item, align='left',width= 220)
        cmds.button ((item+'_select'), label='Select', width= 50, command=partial(selectNode, item))

def selectNode(node, *args):
    cmds.select(cl=True)
    cmds.select(node)

if (cmds.window('testWin', exists=True)):
    cmds.deleteUI('testWin')

theWindow = cmds.window('testWin', title='Test Window', widthHeight=(270, 390), sizeable=True)
cmds.columnLayout ('mainColumn', adjustableColumn=False)
cmds.button ('FillList', label= "nCloth in Scene", width= 270, command= fillTemp)
cmds.scrollLayout ('nClothScrollList', w=270 , h=150, backgroundColor=(.15,.15,.15) )
cmds.rowColumnLayout ('listColumn', numberOfColumns=2, columnWidth=[(1, 220), (2, 50)])
cmds.setParent('..')
cmds.showWindow (theWindow)

rawDescription: Maya Python: Calling a command on interactively created buttons


rawDescription: Python/scrapy - print objects with long strings


code:
x = 'hello'
y = 'll'
y in x

rawDescription: How do I check if a given Python string is a substring of another one?

description: Check if a given Python string is a substring of another one


code:
groups = {'GroupA': (Threading.Lock(), {}), 'GroupB': (Threading.Lock(), {})}

def request_handler(request):
    # Assuming these come from the user's http post
    user_id = request.userid
    user_group = request.user_group

    glock, group = groups[user_group]
    with glock:
        group[user_id] = group.get(user_id, 0) + 1

rawDescription: How to lock and modify a dictionary safety per unit 'group'

description: Lock and modify a dictionary safety per unit 'group'


code:
import argparse
import collections
parser = argparse.ArgumentParser()
known, unknown_args = parser.parse_known_args()

unknown_options = collections.defaultdict(list)
key = None
for arg in unknown_args:
    if arg.startswith('--'):
        key = arg[2:]
    else:
        unknown_options[key].append(arg)

rawDescription: Parse non-pre-defined argument

description: Parse non-pre-defined argument


code:
def call(*popenargs, **kwargs):
    p = subprocess.Popen(*popenargs, **kwargs)
    return p.wait()

rawDescription: Python subprocess.call and subprocess.Popen giving me different outputs


code:
import matplotlib.pyplot as plt

ys = [x**2 + 3.5 for x in xrange(20)]
xs = range(20)
plt.plot(xs,ys)

a = '2'

plt.text(6, 50,r'$'+a+'x+3.5$')
plt.show()

rawDescription: Use of %s,%f,... when plotting text with matplotlib


code: isinstance(thing, (Iterable, Sequence))

rawDescription: What exactly does "iterable" mean in Python?


code:
s1 = mat[inliers.reshape(-1,1), outliers]
scores = s1.min(axis=0)

rawDescription: Best practice for fancy indexing a numpy array along multiple axes


code:
def read_input(list_of_urls):
    with open(list_of_urls) as f, open('output.txt', 'w+') as f2:
        for line in f:
            n,m = line.split(' ')
            n=int(n)
            m=int(m)
            _,_,thisMaxCycle = max_cycle(n,m)
            f2.write("{0} {1} {2} #{2} being the max cycle for all numbers between {0} and {1}\n".format(n,m,thisMaxCycle))

rawDescription: python 3*n + 1 - calculate longest cycle for a list of numbers

description: Python 3*n + 1 - calculate longest cycle for a list of numbers


code:
class Food(DetailView):
    model = Food
    template_name = 'eat/food.html'
    slug_field = 'name'
    slug_url_kwarg = 'food_url'

    def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.

        By default this requires `self.queryset` and a `pk` or `slug` argument
        in the URLconf, but subclasses can override this to return any object.
        """
        # Use a custom queryset if provided; this is required for subclasses
        # like DateDetailView
        if queryset is None:
            queryset = self.get_queryset()

        # Next, try looking up by primary key.
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        slug = self.kwargs.get(self.slug_url_kwarg, None)
        if pk is not None:
            queryset = queryset.filter(pk=pk)

        # Next, try looking up by slug.
        elif slug is not None:

            ###########
            # Convert the underscores into spaces.
            ###########
            slug = slug.replace('_', ' ')
            ###########

            slug_field = self.get_slug_field()
            queryset = queryset.filter(**{slug_field: slug})

        # If none of those are defined, it's an error.
        else:
            raise AttributeError("Generic detail view %s must be called with "
                                 "either an object pk or a slug."
                                 % self.__class__.__name__)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except queryset.model.DoesNotExist:
            raise Http404(_("No %(verbose_name)s found matching the query") %
                          {'verbose_name': queryset.model._meta.verbose_name})
        return obj

rawDescription: how to run a string method on the slug_field value in a detail view

description: Run a string method on the slug_field value in a detail view


code:
with open('workfile', 'w') as fout:
    fout.write(result)

rawDescription: Writing result to an existing file in python


code:
#!/usr/bin/env python

import wx
from wx import stc
import keyword

class PyDialog(wx.Dialog):
    def __init__(self):
        wx.Dialog.__init__(self, None, -1, 'Python Code')
        sizer = wx.BoxSizer(wx.VERTICAL)

        self.stc = stc.StyledTextCtrl(self, -1)
        self.stc.SetSizeHints(400, 400)
        self.stc.SetLexer(stc.STC_LEX_PYTHON)
        self.stc.SetKeyWords(0, " ".join(keyword.kwlist))
        self.stc.SetMarginType(1, stc.STC_MARGIN_NUMBER)
        # Python styles
        self.stc.StyleSetSpec(wx.stc.STC_P_DEFAULT, 'fore:#000000')
        # Comments
        self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTLINE,  'fore:#008000,back:#F0FFF0')
        self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, 'fore:#008000,back:#F0FFF0')
        # Numbers
        self.stc.StyleSetSpec(wx.stc.STC_P_NUMBER, 'fore:#008080')
        # Strings and characters
        self.stc.StyleSetSpec(wx.stc.STC_P_STRING, 'fore:#800080')
        self.stc.StyleSetSpec(wx.stc.STC_P_CHARACTER, 'fore:#800080')
        # Keywords
        self.stc.StyleSetSpec(wx.stc.STC_P_WORD, 'fore:#000080,bold')
        # Triple quotes
        self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLE, 'fore:#800080,back:#FFFFEA')
        self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, 'fore:#800080,back:#FFFFEA')
        # Class names
        self.stc.StyleSetSpec(wx.stc.STC_P_CLASSNAME, 'fore:#0000FF,bold')
        # Function names
        self.stc.StyleSetSpec(wx.stc.STC_P_DEFNAME, 'fore:#008080,bold')
        # Operators
        self.stc.StyleSetSpec(wx.stc.STC_P_OPERATOR, 'fore:#800000,bold')
        # Identifiers. I leave this as not bold because everything seems
        # to be an identifier if it doesn't match the above criterae
        self.stc.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, 'fore:#000000')

        # Caret color
        self.stc.SetCaretForeground("BLUE")
        # Selection background
        self.stc.SetSelBackground(1, '#66CCFF')

        sizer.Add(self.stc, 0, wx.EXPAND)

        button = wx.Button(self, -1, 'Open...')
        self.Bind(wx.EVT_BUTTON, self.OnOpen, button)
        sizer.Add(button)

        self.SetSizer(sizer)
        sizer.Fit(self)

    def OnOpen(self, evt):
        dlg = wx.FileDialog(
            self,
            message = 'Choose File',
            wildcard = 'Python source (*.py)|*.py',
            style = wx.OPEN)

        if dlg.ShowModal() != wx.ID_OK:
            return

        with open(dlg.GetPath()) as fo:
            self.stc.SetText(fo.read())

        dlg.Destroy()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    dlg = PyDialog()
    with open(__file__) as fo:
        dlg.stc.SetText(fo.read())
    dlg.ShowModal()

rawDescription: Displaying Pretty Python Code in Python (or Other) GUI


code:
import time
driver.find_element_by_css_selector(".MenuIcons.searchButton").click()
time.sleep(1)
driver.find_element_by_partial_link_text("TEXT").click()

rawDescription: Python Selenium: How do I click a link in a drop down menu with css selector?


code:
...
command = 'apt-get upgrade -y'
...

rawDescription: Upgrade linux with a python script

description: Upgrade linux with a python script


code:
import signal
from tornado.ioloop import IOLoop

def on_shutdown():
    print('Shutting down')
    IOLoop.instance().stop()

if __name__ == '__main__':
    ioloop = IOLoop.instance()

    signal.signal(signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(on_shutdown))

    ioloop.start()

rawDescription: pyzmq Tornado ioloop: how to handle KeyboardInterrupt gracefully?

description: Pyzmq Tornado ioloop: how to handle KeyboardInterrupt gracefully


code:
q = """
      INSERT INTO
        tblauto_tagged
        (
           propernoun_SRNO,
           tagger,
           train,
           propernoun,
           propernoun_ID
         ) VALUES (
           %d,
           %s,
           %s,
           %s,
           %s
          )
       """
cursor.execute(q,(j,str(iput),str(corpora),var_string_1,"AUX"))

rawDescription: insert into table MySQL and Python

description: Insert into table MySQL and Python


rawDescription: How to properly use string formatting in Python 2.7?

description: Properly use string formatting in Python 2.7


code:
def isWordGuessed(secretWord, lettersGuessed):
        if secretWord=="" or lettersGuessed==[]:
            return False
        if secretWord[0] not in lettersGuessed:
            return False
        if len(secretWord)==1 and secretWord in lettersGuessed:
            return True
        else:
            return isWordGuessed(secretWord[1:],lettersGuessed)

isWordGuessed('apple', ['a', 'e', 'i', 'k', 'p', 'r', 's'])
isWordGuessed('apple', ['a', 'e', 'i', 'l', 'p', 'r', 's'])

rawDescription: To find secret word from a list?

description: To find secret word from a list


code:
FORMS = [("questions", Questions),
     ("basiccontact", BasicContact),
     ("phonecontact", PhoneContact),]

class ClientFormWizard(SessionWizardView):
    form_list = FORMS
    def done(self, form_list, form_dict, **kwargs):
        # get data from the forms

        form_data = dict()
        for form in form_list:
            form_data.update(form.cleaned_data)

        clientform = ClientForm(form_data)
        new_client = clientform.save()

        # return redirect(...)

rawDescription: Combine data from several forms Django

description: Combine data from several forms Django


code: T_g.append([x for x in rootss(coeff) if np.isreal(x) and x > 0])

rawDescription: Keeping only real positive value from an array


code:
bad_obj_types = ['CAMERA','LAMP','ARMATURE']
for obj in bpy.data.objects:
    if obj.type not in bad_obj_types:
        if len(obj.keys()) > 1:
            # First item is _RNA_UI
            print("Object",obj.name,"custom properties:")
            for K in obj.keys():
                if K not in '_RNA_UI':
                    print( K , "-" , obj[K] )

rawDescription: How do i read out Custom Properties in Blender with Python?

description: Read out Custom Properties in Blender with Python


code:
def myview(request):
    if request.method == 'POST':
        form = JournalForm(request.POST)
    else:
        form = JournalForm(initial={'tank': 123})

    return render_to_response(...)

rawDescription: How do I set default variables for bound forms?

description: Set default variables for bound forms


code:
def namelink(self, name, *dicts):
    """Make a link for an identifier, given name-to-URL mappings."""
    for dict in dicts:
        if name in dict:
            return '%s' % (dict[name], name)

rawDescription: How to make Pydoc document my functions in a specific order?

description: Make Pydoc document my functions in a specific order


code:
[('Option{}'.format(i+1),item) for i,item in enumerate(['A','B','C','D'])]

# EDIT FOR PYTHON 2.5
[('Option%s' % (i+1), item) for i,item in enumerate(['A','B','C','D'])]

rawDescription: Mutating a List in Python

description: Mutating a List in Python


code:
import matplotlib.pyplot as plt

plt.plot(*result.T)

rawDescription: How do I make a numpy array's numbers plot on different axes?

description: Make a numpy array's numbers plot on different axes


code:
count = input("How many numbers do you want to input?")
numbers = [float(num) for num in raw_input("Input numbers, please...").split()]
if count != len(numbers):
  raise SystemExit("You lied to me!")

rawDescription: i want to open n number of integer in one row in Python

description: I want to open n number of integer in one row in Python


code:
class Foo_child(Foo):
    def __init__(self, Foo_instance, c, d):
        super().__init__(c, d)
        self.Foo_instance = Foo_instance

    @property
    def value(self):
        return self.Foo_instance.value

    @value.setter
    def value(self, value):
        self.Foo_instance.value = value

    def method1(self):
        return self.Foo_instance.method1()

rawDescription: Instances of a class and its sub-class sharing state in python


code: driver.find_element(By.XPATH, "//a[contains(text(), 'Sign in')]")

rawDescription: Trouble retrieving this element in selenium