code:
from multiprocessing import Lock, Manager, Process
from multiprocessing.managers import BaseManager

class Container(object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return "C" + str(self.value)
    def multiply(self, factor):  # added method
        self.value *= factor

def process(inputs, start, end):
    for i in range(start, end):
        inputs.apply(i, 'multiply', (10,))

class ListProxy(object):
    def __init__(self):
        self.nl = []
    def append(self, x):
        self.nl.append(x)
    def __getitem__(self, key):
        return self.nl[key]
    def __iter__(self):
        return iter(self.nl)
    def apply(self, i, method, args, **kwargs):
        getattr(self.nl[i], method)(*args, **kwargs)

class ListManager(BaseManager):
    pass

ListManager.register('ListProxy', ListProxy,
                     exposed=['append', '__getitem__', '__iter__', 'apply'])

def main():
    manager = ListManager()
    manager.start()
    output = manager.ListProxy()

    for v in range(10):
        output.append(Container(v))
    print([str(v) for v in output])

    t1 = Process(target=process, args=(output, 0, 5))
    t2 = Process(target=process, args=(output, 5, 10))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    print([str(v) for v in output])

if __name__ == '__main__':
    main()

rawDescription: Shared-memory complex writable data structures


code:
list_of_lists=[]
category=0
list_of_lists.append([])

f = open(file_name,'r')

for line in f.readlines():
    item = line.strip('\n') # no white spaces in the list
    if len(item) > 0:
         #add to current category
         list_of_lists[category].append(item)
    else:
         #add new category
         list_of_lists.append([])
         category = category + 1
f.close()

rawDescription: ordered list of lists

description: Ordered list of lists


code:
from bson.json_util import dumps

dumps(results)

rawDescription: Return Pymongo result in Python Bottle

description: Return Pymongo result in Python Bottle


code:
cursor.execute("""INSERT into main_app_financialstatements
  (statement_id, provider_id, url, date)
VALUES (%s, (SELECT id FROM main_app_provider WHERE provider=%s), %s, %s)""",
  (statement_id, provider, url, date))

rawDescription: Compound SQL INSERT statement

description: Compound SQL INSERT statement


code:
z
for i in z.itertext():
  print(i)

rawDescription: How do I access text between tags with xml.etree.ElementTree

description: Access text between tags with xml.etree.ElementTree


code:
parser = argparse.ArgumentParser('Cool', add_help=False)
parser.add_argument('-h', '--hi', action='store_true', dest='hi')

rawDescription: Overriding default argparse -h behaviour


code:
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_const', const=True, default=False)
parser.add_argument('-b', action='store_const', const=True, default=False)
args = parser.parse_args()

rawDescription: Python argparse allow combined flags

description: Python argparse allow combined flags


rawDescription: Printing values in row order from dictionary/ list


code:
class userInfo(models.Model):
  #model fields

  def __unicode__(self):
    return self.auth.username

rawDescription: django - inlineformset_factory with more than one ForeignKey

description: Django - inlineformset_factory with more than one ForeignKey


code: phases = ( phases + np.pi) % (2 * np.pi ) - np.pi

rawDescription: Opposite of numpy.unwrap

description: Opposite of numpy.unwrap


code: index = [index for index,line in enumerate(all_lines) if "Gold.Protein.RotatedAtoms"  in line]

rawDescription: finding a value by looping, multiple files python

description: Finding a value by looping, multiple files python


rawDescription: string manipulation: partly convert to lowercase

description: String manipulation: partly convert to lowercase


code:
from django.shortcuts import render

def search(request):

    template_name = 'search.html'

    query = request.GET.get('q', '')
    if query:
        # query example
        results = MyEntity.objects.filter(name__icontains=query).distinct()
    else:
        results = []
    return render(
        request, template_name, {'results': results})

rawDescription: How to write a django view to search in database?

description: Write a django view to search in database


code:
class Language(forms.Form):
    language = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={'onchange':'ajaxfunction()'}))

rawDescription: Call ajax on dropdown button

description: Call ajax on dropdown button


code:
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Select qSQL with id=4.
cursor.execute("SELECT qSQL FROM TBLTEST WHERE id = 4")

# Fetch a single row using fetchone() method.
results = cursor.fetchone()

qSQL = results[0]

cursor.execute(qSQL)

# Fetch all the rows in a list of lists.
qSQLresults = cursor.fetchall()
for row in qSQLresults:
    id = row[0]
    city = row[1]

    #SQL query to INSERT a record into the table FACTRESTTBL.
    cursor.execute('''INSERT into FACTRESTTBL (id, city)
                  values (%s, %s)''',
                  (id, city))

    # Commit your changes in the database
    db.commit()

# disconnect from server
db.close()

rawDescription: Insert data into MySQL table from Python script


code:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    def save_related(self, request, form, formsets, change):
        if not form.cleaned_data['type']:
            type, created = Type.objects.get_or_create(name="Teacher")
            form.cleaned_data['type'] = [type]
        form.save_m2m()
        for formset in formsets:
             self.save_formset(request, form, formset, change=change)

rawDescription: django many to many save admin

description: Django many to many save admin


code:
timer = QTimer()
connect(timer, SIGNAL(timeout()), this, SLOT(update()))
timer.start(1000)

rawDescription: PyQt4 Drawing and sleep

description: PyQt4 Drawing and sleep


code: sched.add_job(job_function, trigger='interval', hours=2, end_date='2016-10-10 09:30')

rawDescription: Writing a Python script that runs everyday till a specified date


code:
from jsonschema import validate

schema = {
    "type" : "object",
    "properties" : {
        "userId": {"type" : "number"},
        "appUserId": {"type" : "number"},
    },
    "oneOf": [
        {
             "type": "object",
             "required": ["userId"],
        },
        {
             "type": "object",
             "required": ["appUserId"],
        }
    ],
}

validate({'userId': 1}, schema) # Ok
validate({'appUserId': 1}, schema) # Ok
validate({'userId': 1, 'appUserId': 1}, schema) # ValidationError

rawDescription: JSON Schema: Validate that exactly one property is present


code:
from TwitterAPI import TwitterAPI

TWEET_TEXT = 'some tweet text'
IMAGE_PATH = './some_image.png'

api = TwitterAPI(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN_KEY,ACCESS_TOKEN_SECRET)

# STEP 1 - upload image
file = open(IMAGE_PATH, 'rb')
data = file.read()
r = api.request('media/upload', None, {'media': data})
print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE')

# STEP 2 - post tweet with a reference to uploaded image
if r.status_code == 200:
    media_id = r.json()['media_id']
    r = api.request('statuses/update', {'status':TWEET_TEXT, 'media_ids':media_id})
    print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')

rawDescription: Add multiple images to a tweet with python and twitterApi?


code: return ':'.join(x.encode('hex') for x in fvalue)

rawDescription: Displaying scapy StreamSocket data

description: Displaying scapy StreamSocket data


code:
rows = [[1,2,3,4],[3,5,88,9],[4,55,-6,0],[0,34,22,1222]]
t1 = [(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))]
print(t1)

# Easy loop
t2 = []
for i in range(len(rows[0])):
    innerElements = []
    for row in rows:
        innerElements.append(row[i])
    newTuple = ( min(innerElements),max(innerElements) )
    t2.append(newTuple)

print(t2)

rawDescription: Equivalent for loop expression for complex list comprehension


code: filtered_array = numpy.array(filter(lambda row: 12<row[0]<16, array))

rawDescription: Numpy: get only the array rows that have a value in an interval


code: shutdown = 'shutdown /r /t {0} /c "{1}"'.format(d,m)

rawDescription: Interactive Shutdown program displays help page?


code:
def main():
    subprocess.call("cls", shell=True)
    ipList,hostList,manfList,masterList,temp = [],[],[],[],[]
    ipList,hostList,manfList, = getIPs(),getHosts(),getManfs()
    entries = len(hostList)
    i = 0
    for i in xrange(i, entries):
        temp = [hostList[i], manfList[i], ipList[i]]
        masterList.append(temp)
    with open("output.csv", "wb") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(masterList)

rawDescription: Python list write to CSV without the square brackets


rawDescription: How to create a filename with a trailing period in Windows?

description: Create a filename with a trailing period in Windows


code:
import pygame
from pygame.locals import QUIT, KEYDOWN, K_ESCAPE, K_SPACE, SRCALPHA

class Game(object):
    def __init__(self):
        pygame.init()
        self.width, self.height = 800, 800
        pygame.display.set_caption("Surfarray test")
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.background = pygame.Surface((self.width, self.height))
        self.background.fill((255, 255, 255))
        self.background.convert()
        self.bar = pygame.Surface((200, 100))
        self.bar.fill((255, 0, 0))
        self.bar.convert()

        self.sprite = pygame.sprite.GroupSingle()
        self.sprite.add(CustomSprite(pygame.Rect(5, 5, 100, 100)))

    def input(self):
        for event in pygame.event.get():

            if event.type == QUIT:
                return False

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return False
                if event.key == K_SPACE:
                    # make bar transparent by pressing the space bar
                    self.sprite.update()

    def main(self):
        while True:
            if self.input() is False:
                return False
            self.draw()

    def draw(self):
        self.screen.blit(self.background, (0, 0))
        self.screen.blit(self.bar, (5, 5))
        self.sprite.draw(self.screen)
        pygame.display.update()

class CustomSprite(pygame.sprite.Sprite):
    def __init__(self, rect):
        pygame.sprite.Sprite.__init__(self)
        self.rect = rect
        # SRCALPHA flag makes the pixel format include per-pixel alpha data
        self.image = pygame.Surface((rect.width, rect.height), SRCALPHA)
        self.image.convert_alpha()
        self.image.fill((126, 126, 126))

    # magic happens here
    def update(self):
        pxa = pygame.surfarray.pixels_alpha(self.image)
        pxa[:] = 100  # make all pixels transparent

if __name__ == "__main__":
    game = Game()
    game.main()

rawDescription: Why is Surface.unlock failing to unlock the surface for blitting?


code:
a = np.random.rand(100)*400 - 200
b = np.random.rand(100)*16 + 4
a[:10] = -200
b[:10] = 4

f, ax = plt.subplots(3)

ax[0].hexbin(a, b, gridsize=20, extent=[-200,200,4,20], cmap=plt.cm.binary)

H, xedges, yedges = np.histogram2d(a, b, bins=20, range=[[-200,200],[4,20]])
ax[1].imshow(H.T, interpolation='nearest', cmap=plt.cm.binary, aspect='auto',
                extent=[xedges[0],xedges[-1],yedges[0],yedges[-1]], origin='lower')

# simplest and most reliable:
ax[2].hist2d(a, b, bins=20, range=[[-200,200],[4,20]], cmap=plt.cm.binary)

rawDescription: Different behaviour of hexbin and histogram2d


code:
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

rawDescription: How to run a Tcl Script in a folder in Python?

description: Run a Tcl Script in a folder in Python


code:
dirs = os.listdir(path)
dirs = [i.split('-', 2)[1] for i in dirs]
print(dirs)

rawDescription: Split strings in list

description: Split strings in list


rawDescription: Iterate over numpy array to fill a python list


code: np.vstack((one, two, three))

rawDescription: Python Numpy add 3 arrays in one array

description: Python Numpy add 3 arrays in one array


code:
import random

class Critter(object):
    """A virtual pet"""

    def __init__(self, name, hunger=None, boredom=None):
        self.name = name
        self.hunger = hunger if hunger is not None else random.randrange(0, 21)
        self.boredom = boredom if boredom is not None else random.randrange(0, 21)

    def __str__(self):
        rep = "\nCritter object\n"
        rep += "Name: " + str(self.name) + ", Hunger: " + str(self.hunger) + ", Boredom: " + str(self.boredom)
        return rep

rawDescription: How do i create an object with random value of attributes through for loops in python?

description: Create an object with random value of attributes through for loops in python


code:
likes = json.loads(likes_data)
comments = json.loads(comments_data)
data = {'likes': likes['data'], 'comments': comments['data']}
self.response.out.write(json.dumps(data))

rawDescription: Python - Combining two json objects

description: Python - Combining two json objects


code:
from collections import defaultdict

def pretty_print_lst(lst):
    if not lst:
        return ""
    elif len(lst) == 1:
        return lst[0]
    elif len(lst) == 2:
        # Join together two letters using " and " as the join.
        return " and ".join(lst)
    else:
        # Use a "list slice" to join all in the list but the last item,
        # using ", " as the join, then append " and " and append the
        # last item.  Last item is indexed with -1, which always works no
        # matter how many or few items are in the list.
        return ", ".join(lst[:-1]) + " and " + lst[-1]

def print_rec(seq):
    # group according to counts
    d = defaultdict(list)
    for row in seq:
        n, letter = row  # get count and letter from the row
        d[n] += letter  # append letter to that count list

    # get a list of (key, value) pairs
    # so the list entries are: (count, list_of_letters)
    results = list(d.items())
    results.sort()
    if len(results) == 1 and results[0][0] == 0:
        # if all 4 letters have a count of 0,
        print("No data")
    else:
        for count, lst in results:
            s = pretty_print_lst(lst)
            print(s)

lst = [ (8, 'a'), (8, 'b'), (2, 'c'), (8, 'd')]
print_rec(lst)

rawDescription: How to group, sort, count records and output results

description: Group, sort, count records and output results


code:
import Tkinter as tk
master = tk.Tk()
variable = tk.StringVar(master)
options = {"one": 1, "two": 2}
tk.OptionMenu(master, variable, *options.keys()).pack()
...
wanted = options[variable.get()]

rawDescription: Tkinter OptionMenu DisplayOptions and Assignment Values


code:
from collections import defaultdict

# Read in file line-by-line for the first time
# Build up dictionary of txt1 to set of txt2 s
txt1totxt2 = defaultdict(set)
f=open('file.txt','r')
for line in f:
    lst = line.split()
    txt1=lst[0]
    txt2=lst[1]
    txt1totxt2[txt1].add(txt2);

# The dictionary tells us whether the second text
# is unique or not. If it's unique the set has
# just one element; otherwise the set has > 1 elts.
# Read in file for second time, sending each line
# to the appropriate output file
f.seek(0)
oh1=open('result1.txt','w')
oh2=open('result2.txt','w')

for line in f:
    lst = line.split()
    txt1=lst[0]
    if len(txt1totxt2[txt1]) == 1:
        oh1.write(line)
    else:
        oh2.write(line)

rawDescription: Find and print same elements in a loop

description: Find and print same elements in a loop


code:
import numpy as np
a = np.array([[[1, 2, 3]]])
a
a*3

rawDescription: matrix multiplication with a constant

description: Matrix multiplication with a constant


code:
if choice_id == "1":
    stocks = Get_Quote(symbol)
elif choice_id == "2":
    stocks = Get_percent_change(symbol)

rawDescription: Why can't I change the value of variable after applying if-else condition?


code:
from pympler.asizeof import asizeof
obj = [1, 2, (3, 4), 'text']
asizeof(obj)

rawDescription: Deep version of sys.getsizeof

description: Deep version of sys.getsizeof


code: print( chr( ord(ch)+key ), end=' ')

rawDescription: Creating a Caeser program: Converting ASCII to characters


code:
def get_difference(file_1, file_2):
    data_1 = set(open(file_1, encoding='utf-8').read().splitlines())
    data_2 = set(open(file_2, encoding='utf-8').read().splitlines())
    return data_1 - data_2

rawDescription: Pandas to compare the column (A) with other column (B) and return the unique values which is present in Column (A)


code:
"""S.O. 12766628

Usage:
    script.py voucher add <code> <credits> [<points>]
    script.py voucher del <code>
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='S.O. 12766628')
    print(arguments)

rawDescription: How do I make an argument optional if a condition is met?

description: Make an argument optional if a condition is met


code:
def is_anonymous(self):
    return self.id == 0

rawDescription: Create a new object using an existing id


code:
import functools

def decorator(f):
    @functools.wraps(f)
    def _decorator():
        f()
    return _decorator

@decorator
def foo():
    pass

rawDescription: See decorated Django view names in NewRelic


code:
import locale
locale.setlocale(locale.LC_NUMERIC, "")
def format_num(num):
    """Format a number according to given places.
    Adds commas, etc. Will truncate floats into ints!"""

    try:
        inum = int(num)
        return locale.format("%.*f", (0, inum), True)

    except (ValueError, TypeError):
        return str(num)

def get_max_width(table, index):
    """Get the maximum width of the given column index"""
    return max([len(format_num(row[index])) for row in table])

def pprint_table(out, table):
    """Prints out a table of data, padded for alignment
    @param out: Output stream (file-like object)
    @param table: The table to print. A list of lists.
    Each row must have the same number of columns. """
    col_paddings = []

    for i in range(len(table[0])):
        col_paddings.append(get_max_width(table, i))

    for row in table:
        # left col
        print >> out, row[0].ljust(col_paddings[0] + 1),
        # rest of the cols
        for i in range(1, len(row)):
            col = format_num(row[i]).rjust(col_paddings[i] + 2)
            print >> out, col,
        print >> out

table = [["", "taste", "land speed", "life"],
    ["spam", 300101, 4, 1003],
    ["eggs", 105, 13, 42],
    ["lumberjacks", 13, 105, 10]]

import sys
out = sys.stdout
pprint_table(out, table)

rawDescription: Print out table in a format specified by user in Python?


code:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Pick a directory')
for filename in os.listdir(dirname):
    temp = cv2.imread(filename,-1)

rawDescription: Python GUI: How to browse a directory and read ALL files in it?


code:
import urllib

response = urllib.urlopen('http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true').read()

print(response)

rawDescription: What python libraries can tell me approximate location and time zone given an IP address?


rawDescription: Having an issue changing index from integer to date in pandas


code:
import pandas as pd
Sr1 = pd.Series([1,2,3,4], index = ['A', 'B', 'C', 'D'])
Sr2 = pd.Series([5,6], index = ['A', 'C'])
Sr1+Sr2
Sr1.add(Sr2, fill_value=0)

rawDescription: Adding pandas Series with different indices without getting NaNs


code:
response = c.remoteAdministrationCall(
    loginId='admin@yellowfin.com.au',
    password='test',
    function='LOGINUSER',
    orgId=1,
    person={'userId': 'myuser@user.com', 'password': 'reset123'}
)

rawDescription: PySimpleSoap and wsdl

description: PySimpleSoap and wsdl


code: whos

rawDescription: Equivalent of "whos" command in Python Numpy


code:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of white color in HSV
    # change it according to your need !
    lower_white = np.array([0,0,0], dtype=np.uint8)
    upper_white = np.array([0,0,255], dtype=np.uint8)

    # Threshold the HSV image to get only white colors
    mask = cv2.inRange(hsv, lower_white, upper_white)
    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

rawDescription: Tracking white color using python opencv


code:
from datetime import datetime, timedelta
one_week_ago = datetime.today() - timedelta(days=7)
jobs = Job.objects.filter(report_by_date__gte=one_week_ago)

rawDescription: Django Queryset: filter by weeks

description: Django Queryset: filter by weeks


rawDescription: Tests not being convered by 2to3 in setup.py?


code:
import collections as c
a1 = ['a' , 'b','c']
q1 = c.deque(maxlen=3)
q1.append('a')
q1.append('d')
q1.append('c')
counter = sum(1 if a == q else 0 for (a, q) in zip(a1, q1))
# or, they're basically equivalent
counter = sum(1 for (a, q) in zip(a1, q1) if a == q)

rawDescription: Comparing elements of deque and list

description: Comparing elements of deque and list


code:
''' Returns frequency of function words '''
def get_func_word_freq(words,funct_words):
    fdist = nltk.FreqDist([funct_word for funct_word in funct_words if funct_word in words])
    funct_freq = {}
    for key,value in fdist.iteritems():
        funct_freq[key] = value
    return funct_freq

''' Read LIWC 2007 English dictionary and extract function words '''
def load_liwc_funct():
    funct_words = set()
    data_file = open(liwc_dict_file, 'rb')
    lines = data_file.readlines()
    for line in lines:
        row = line.rstrip().split("\t")
        if '1' in row:
            if row[0][-1:] == '*' :
                funct_words.add(row[0][:-1])
            else :
                funct_words.add(row[0])
    return list(funct_words)

rawDescription: Calculate frequency of function words

description: Calculate frequency of function words


code:
player = my_lib.PlayerCharacter()
assert player.position == (0, 0)  # or whatever assert syntax `pymock` uses
press_key('k')
assert player.position == (0, 1)

rawDescription: How do I test whether a module is imported in Python for Test-Driven Development of a game?

description: Test whether a module is imported in Python for Test-Driven Development of a game


rawDescription: Passing parameters to shell input from python


code: local("php root/protected/yiic.php migrate --interactive=0")

rawDescription: Fabric Remote Execution requiring a user response from a prompt?


code:
from dateutil.parser import parse as dateparser
dateparser("Wed Mar 13 10:10 EDT 2013").strftime("%Y-%m-%d %H:%M")

rawDescription: How to convert a date format like 'Wed Mar 13 10:10 EDT 2013' to "2013-03-13 10:10" in robot frame work or python

description: Convert a date format like 'Wed Mar 13 10:10 EDT 2013' to "2013-03-13 10:10" in robot frame work or python


code: s = copy.deepcopy(self.lst)

rawDescription: assignment overriden to keep changing original instance variable in Python class

description: Assignment overriden to keep changing original instance variable in Python class


code:
#!/usr/bin/env python
import fileinput

freq = {}
max_freq = 0

for line in fileinput.input():
    length = len(line)
    freq[length] = freq.get(length, 0) + 1
    if freq[length] > max_freq:
        max_freq = freq[length]

for i in range(max_freq, -1, -1):
    for length in sorted(freq.keys()):
        if freq[length] >= i:
            print('#', end='')
        else:
            print(' ', end='')
    print('')

rawDescription: Vertical Histogram in Python

description: Vertical Histogram in Python


rawDescription: calculating sum totals in groupings pandas dataframe

description: Calculating sum totals in groupings pandas dataframe


code:
orig = [start]
for x in diff:
    orig.append(orig[-1] + x)

rawDescription: Efficient way to use python's lambda, map


rawDescription: python string as hex terminated with null

description: Python string as hex terminated with null


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

nplots = 3
xmin = 0
xmax = 30
subrange = float(xmax-xmin)/float(nplots)

ax = plt.subplot(111)
plt.setp(ax, 'frame_on', False)
ax.set_ylim([0, 5])
ax.set_xlim([xmin, xmax])
ax.set_xticks([])
ax.set_yticks([])
ax.grid('off')

xranges = [(2,8), (5,10), (3,15)]

for j in xrange(nplots):
    x = np.arange(*xranges[j])
    y = np.sin(x)*np.sin(x)

    new_x = (x-x[0])*subrange/float(x[-1]-x[0])+j*subrange ## remapping the x-range

    ax.plot(new_x,y)

plt.show()

rawDescription: make subplots have the same x range

description: Make subplots have the same x range


code:
import sys
import time
import atexit
from guppy import hpy

_last_log_time = time.time()
_logfile = open('logfile.txt', 'w')

def heapy_profile(frame, event, arg):
    currtime = time.time()
    if currtime - _last_log_time < 1:
        return
    _last_log_time = currtime
    code = frame.f_code
    filename = code.co_filename
    lineno = code.co_firstlineno
    idset = hpy().heap()
    logfile.write('%s %s:%s\n%s\n\n' % (currtime, filename, lineno, idset))
    logfile.flush()

atexit.register(_logfile.close)
sys.settrace(heapy_profile)

rawDescription: Python line-by-line memory profiler?

description: Python line-by-line memory profiler


code:
s = 'abcdefgh12345678abcdefgh'
import re

a, b, c = re.findall("\w{8}", s)
print(a, b, c)

a, b, c = (s[i:i + 8] for i in range(0, len(s), 8))
print(a, b, c)

rawDescription: how to split a string in groups of multiple variables

description: Split a string in groups of multiple variables


code:
import requests
from bs4 import BeautifulSoup
import csv

def grab_listings():
    for i in range(0, 5):
        url = "http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/{}/"

        r = requests.get(url.format(i + 1))
        soup = BeautifulSoup(r.text, 'html.parser')
        l_area = soup.find("div", {"class": "wlt_search_results"})

        for elem in l_area.findAll("a", {"class": "frame"}):
            yield elem["href"]

l = grab_listings()

with open("gyms.csv", "w") as file:
    writer = csv.writer(file)
    for row in l:
        writer.writerow(row)

rawDescription: Python - Why is this data being written to file incorrectly?


code:
import re
pattern = "[^_]_[^_]|[^_]"
re.findall(pattern, "SAB_bARGS_D", re.IGNORECASE)

rawDescription: Dividing a string into list according to the format given


code:
with open('file') as f:
    for line in f:
        pos = f.find('Total IPC')
        if pos >= 0:
            line[pos : pos + as_many_chars_you_need]

rawDescription: How to extract a specific value from 1000 shell script files?

description: Extract a specific value from 1000 shell script files


code:
class Person(object):
    def __init__(self):
        self.first_name = 'Will'
        self.second_name = 'Awesome'

my_guy = Person()
my_guy.gender = "Male"
print(my_guy.gender)

rawDescription: Is this possible to dynamically to generate an attribute in a python object?


code:
b = bytes('a', 'ascii')
b
b[0]

rawDescription: How to convert Python ASCII value to it's hexidecimal value (in bytes)

description: Convert Python ASCII value to it's hexidecimal value (in bytes)


code:
import cairo
import numpy
import sys

def convert_to_grayscale(img_in):
    """Convert an image to grayscale.

    Arguments:
        img_in: (cairo.ImageSurface) input image.

    Return:
        (cairo.ImageSurface) image in grayscale, in ARGB32 mode.

    Timing:
        ~100ms to convert an image of 800x800

    Examples:
        # returns a B&W image
        >>> convert_to_grayscale(cairo.ImageSurface.create_from_png('test.png'))
    """
    a = numpy.frombuffer(img_in.get_data(), numpy.uint8)
    w, h = img_in.get_width(), img_in.get_height()
    a.shape = (h, h, 4)

    assert sys.byteorder == 'little', (
        'The luminosity vector needs to be switched if we\'re in a big endian architecture. '
        'The alpha channel will be at position 0 instead of 3.')
    alpha = a[:, :, 3]
    alpha.shape = (w, h, 1)

    luminosity_float = numpy.sum(a * numpy.array([.114, .587, .299, 0]), axis=2)
    luminosity_int = numpy.array(luminosity_float, dtype=numpy.uint8)
    luminosity_int.shape = (w, h, 1)
    grayscale_gbra = numpy.concatenate((luminosity_int, luminosity_int, luminosity_int, alpha),
                                       axis=2)
    stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, w)
    assert stride == 4 * w, 'We need to modify the numpy code if the stride is different'
    img_out = cairo.ImageSurface.create_for_data(grayscale_gbra, cairo.FORMAT_ARGB32, w, h, stride)

    return img_out

rawDescription: How to convert an image to grayscale with Cairo

description: Convert an image to grayscale with Cairo


code:
from random import randint
import time

def loop():
    return randint(100,200)

def save_lst(lst):
    with open("mon_fich", "w") as f:
        f.write(", ".join(lst))

lst = list()
while True:
        lst.append(str(loop()))
        if len(lst)>=100:
            save_lst(lst)
            lst = list()
        time.sleep(0.001)

rawDescription: Python : Printing While Loop data set to a file


code:
monthly.index.to_series().head()
monthly.index.to_series().apply(lambda x: x.strftime("%Y-%m")).head()

rawDescription: Pandas - Create column from DateTimeIndex


code: (r'^/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'})

rawDescription: Separate Admin/User authentication system in Django


rawDescription: Flatten DataFrame with multi-index columns


code:
import ctypes
ctypes.cdll.msvcrt._write(1, 0, 0)

rawDescription: Write 0 characters to a file descriptor

description: Write 0 characters to a file descriptor


code:
def cp_files_tmp(src, dest):
    src_files = os.listdir(src)
    for file_name in src_files:
        full_file_name = os.path.join(src, file_name)
        full_destination=os.path.join(dest,file_name)
        if (os.path.isfile(full_file_name)):
            while os.path.exists(full_destination):
                full_destination += ".duplicate"
            shutil.copy(full_file_name, full_destination)

dest = 'C:/temp/'
src_A= 'C:/sil/in/'
src_B= 'C:/olw/in/'

cp_files_tmp(src_A, dest) # cp files
cp_files_tmp(src_B, dest) # cp files

rawDescription: copy (duplicate) files in python

description: Copy (duplicate) files in python


code:
img = wx.Image(filepath, wx.BITMAP_TYPE_ANY)
bmp = wx.BitmapFromImage(img)
b = wx.BitmapButton(self, -1, bmp, (20, 20),
                   (bmp.GetWidth()+10, bmp.GetHeight()+10))

rawDescription: Create a load of button images from .jpg files


code:
def move(self, x, y):
    self.shipRect.center[0] += x
    self.shipRect.center[1] += y

rawDescription: How to Move a Sprite in Pygame

description: Move a Sprite in Pygame


code:
from skimage import io
from skimage import color
from skimage import filter
import matplotlib.pyplot as plt

image = color.rgb2gray(io.imread('4g1te.png'))
denoised = filter.denoise_tv_bregman(image, 1)
edges = filter.canny(denoised, 1, 0.01, 0.1)

fig, axes = plt.subplots(ncols=2)
axes[0].imshow(denoised)
axes[1].imshow(edges)
for ax in axes:
    ax.set_axis_off()
plt.show()

rawDescription: Long Boundary Detection in a Noisy Image


code: p = re.compile("^[-\w]+$", re.DEBUG)

rawDescription: Python: How does regex re.compile(r'^[-\w]+$') search? Or, how does regex work in this context?


code:
import sys
def print_there(x, y, text):
     sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
     sys.stdout.flush()

rawDescription: Is it possible to print a string at a certain screen position inside IDLE?


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

N = 50
M = 5 # Number of bins

x = np.random.rand(N)
y = np.random.rand(N)
a2 = 400*np.random.rand(N)

# Create the DataFrame from your randomised data and bin it using groupby.
df = pd.DataFrame(data=dict(x=x, y=y, a2=a2))
bins = np.linspace(df.a2.min(), df.a2.max(), M)
grouped = df.groupby(np.digitize(df.a2, bins))

# Create some sizes and some labels.
sizes = [50*(i+1.) for i in range(M)]
labels = ['Tiny', 'Small', 'Medium', 'Large', 'Huge']

for i, (name, group) in enumerate(grouped):
    plt.scatter(group.x, group.y, s=sizes[i], alpha=0.5, label=labels[i])

plt.legend()
plt.show()

rawDescription: creating a matplotlib scatter legend size related

description: Creating a matplotlib scatter legend size related


code:
from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()

rawDescription: Python, HTTPS GET with basic authentication


code: ab = zip((['keyword'] * len(kws)), kws)

rawDescription: How to dict(zip) for every item on list?

description: Dict(zip) for every item on list


code:
import sys

def is_float(n):
    state = 0
    src = ""
    ch = n
    if state == 0:
        if ch.isdigit():
            src += ch
            state = 1
            ...

data = open("file.data", 'r').read()
for n in data: # characters
    sys.stdout.write("%12.8e\n" % is_float(n))

rawDescription: How to read in one character at a time from a file in python?

description: Read in one character at a time from a file in python


code:
httpd = simple_server.WSGIServer(
    ('localhost', 8000),
    simple_server.WSGIRequestHandler,
)

def app(environ, start_response):
    # environ['REMOTE_ADDR'] is what you're looking for!
    pass

httpd.set_app(app)

rawDescription: PyAMF: How do you get the client's ip address?


code:
from tkinter import *

questions =["What is the name of the Simpsons' next door neighbour?","What is the name of the    school bus driver?",
        "Who runs the Kwik-e-mart?","What does Bart do at the end of the opening credits?"]

answers = [ "Ned Flanders","Otto","Apu","Write On The Blackboard"]

#removed globals from here
score = 0
i = 0

def submit():
    '''runs the submit button'''
    global i
    global score

    if answer.get().lower()==answers[i].lower():
        score+=1

    i+=1 #first increment, then show the question since you already show it at startup

    try:  #since you get the IndexError on this line, I used on here
        question.config(text=questions[i])
    except IndexError:
        print ("something")

    scoretxt.config(text = "Your score is: {}".format(str(score)))
    answer.delete(0,END)

window = Tk()
window.title("Simpsons Quiz")
window.wm_iconbitmap("homer.ico")
window.configure(background ="#ffd600")

banner = PhotoImage(file ="the-simpsons-banner.gif")
Label(window,image = banner).grid(row = 0,columnspan = 6)
Label(window,text = "Question : ",bg ="#ffd600",justify=LEFT).grid(row = 1,column = 0)
Label(window,text = "Type answer here: ",bg = "#ffd600",justify=LEFT).grid(row = 3, column = 0)
scoreLabel =Label(window,bg = "#ffd600")
scoretxt = Label(window,text ="Your score is: ?",bg = "#ffd600")
scoreLabel.grid(row=5,column = 2)
scoretxt.grid(row = 6,column = 2)
question=Label(window,bg = "white",text= questions[0],justify=LEFT)
question.grid(row =1,column=1)
answer = Entry(window,bg ="white",width = 30)
answer.grid(row = 3,column=1)

# make a submit button

Button(window,text= "Submit",bg = "white",command = submit).grid(row = 3,column = 2)

mainloop()

rawDescription: Python 3 and Tkinter- how to control a quiz loop


code:
def foo(self, request, method='post', page=None, **options):
    #do something
    self.another_foo(**options)

rawDescription: how to send extra arguments to another function

description: Send extra arguments to another function


code:
users = tweepy.api.lookup_users(screen_names=['twitter', 'cleg'])
for user in users:
    print(user)

rawDescription: How to find what serial number a user has in Twitter

description: Find what serial number a user has in Twitter


code:
def GetByName(self):
    lname = self.txtlname.GetValue() or None
    fname = self.txtfname.GetValue() or None
    result = self.emplu.GetEmpID(lname, fname)

rawDescription: How can I improve this code for checking if text fields are empty in WxPython?

description: Improve this code for checking if text fields are empty in WxPython


code:
mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]
d = {}

for key, value in mytup:
    if d.get(key) < value:  # d.get(key) returns None if the key doesn't exist
        d[key] = value      # None < float('-inf'), so it'll work

result = d.items()

rawDescription: Find those tuples in which the second element is maximum among all values with same first element


code:
def caught_speeding(speed, is_birthday):
    adjustment = 5 if is_birthday else 0
    if speed <= 60 + adjustment:
        return 0
    elif speed <= 80 + adjustment:
        return 1
    else:
        return 2

rawDescription: Is it efficient to perform individual, nested if statements?


code:
from ctypes import *

class Varnam(Structure):
    __fields__ = [("scheme_file",c_char_p),
                  ("suggestions_file",c_char_p),
                  ("internal",c_void_p)]

varnam_ptr = POINTER(Varnam)

libvarnam = cdll.LoadLibrary("libvarnam.so") # on Linux
# libvarnam = cdll.libvarnam                 # on Windows

varnam_init = libvarnam.varnam_init
varnam_init.argtypes = [c_char_p, POINTER(varnam_ptr), POINTER(c_char_p)]

def my_varnam_init(scheme_file):
     handle = varnam_ptr()
     msg = c_char_p()
     r = varnam_init(scheme_file. handle.byref(), msg.byref())
     if r != 0:
          raise Exception(msg)
     return handle

rawDescription: Passing structure with pointers to other structures in ctypes


code:
from django.core.files import File

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'r'))
p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
name = str(uuid1()) + os.path.splitext(f.name)[1]
p.image.save(name, f)
p.save()

rawDescription: "Upload" a file from django shell

description: "Upload" a file from django shell


rawDescription: Python-Disabling Action

description: Python-Disabling Action


code:
import numpy_indexed as npi
npi.unique(np.sort(A, axis=1))

rawDescription: Numpy or python filter data set for reciprocal relationships


code:
import lxml.etree as ET

dom = ET.parse(xml_filename)
xslt = ET.parse(xsl_filename)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

rawDescription: How to transform an XML file using XSLT in Python?

description: Transform an XML file using XSLT in Python


code:
def restart_helper(self):
    # kill the process if open
    try:
        self.subp.kill()
    except OSError:
        # can't kill a dead proc
        pass

    self.start_helper()
    # the wait comes after you opened the process
    # if you want to know how the process ended you can add
    # > if self.subp.wait() != 0:
    # usually a process that exits with 0 had no errors
    self.subp.wait()

rawDescription: How to clean up after subprocess.Popen?

description: Clean up after subprocess.Popen


code:
import matplotlib.patches

# get the axes (note that you should actually capture this when creating the subplot)
ax = plt.gca()

# iterate through the children of ax
for art in ax.get_children():
    # we are only interested in FancyArrowPatches
    if not isinstance(art, matplotlib.patches.FancyArrowPatch):
        continue
    # remove the edge, fill with black
    art.set_edgecolor([0, 0, 0, 0])
    art.set_facecolor([0, 0, 0, 1])
    # make it bigger
    art.set_mutation_scale(30)
    # move the arrow head to the front
    art.set_zorder(10)

rawDescription: Change FaceColor and EdgeColor of Matplotlib Streamplot Arrows


code:
g = u""
s = s.decode('UTF-8')

rawDescription: Hebrew unicode in Python

description: Hebrew unicode in Python


code:
class GroupSerializer(serializers.ModelSerializer):

    user_count = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ('id', 'name','user_count')

    def get_user_count(self, obj):
        return obj.user_set.count()

rawDescription: Add a count field to a django rest framework serializer


code:
# map and filter
map(lambda x:x+1, filter(lambda x:x%3, range(10)))
# same as LC
[x+1 for x in range(10) if x%3]

rawDescription: Google python style guide

description: Google python style guide


code:
for row in sam:
    c[row[2]] += 1

rawDescription: Count occurrence of string with spaces using Counter


code:
f = open('cartas.txt', 'r')
g = open('copiar.txt', 'r+')

for line in f:
    line = line.replace('s', 'ch')
    g.write(line)

f.close()
g.close()

rawDescription: Replacing words in a file

description: Replacing words in a file


code:
import pprint
import re

urls = ['http://www.example.com/user/1234',
        'http://www.youtube.com/user/126',
        'http://www.youtube.com/user/125',
        'http://www.forum.com/useryoutube/12']

pattern = re.compile('//www\.(\w+)\.')

keys = ['forum', 'youtube']
results = dict()

for u in urls:
    ms = pattern.search(u)
    key = ms.group(1)
    if key in keys:
        results.setdefault(key, []).append(u)

pprint.pprint(results)

rawDescription: Organizing Results in Python

description: Organizing Results in Python


code:
class Person(Entity):
    def __init__(self, state, name, age, gender):
        self.gender = gender
        super(Person, self).__init__(state, name, age)

rawDescription: Python Class Inheritance: How to initialize a subclass with values not in the parent class


code:
combos = [str(i) + str(n) for i in x for n in y] # or `i`+`n`, () for a generator
combinations = dict((i+1,c) for i,c in enumerate(combos))
# Only in Python 2.6 and newer:
combinations = dict(enumerate(combos, 1))
# Only in Python 2.7 and newer:
combinations = {i+1:c for i,c in enumerate(combos)}

rawDescription: Creating dict from all possible combinations of 2 separate lists


code:
lookup = {v:i for i, v in enumerate(arr2)}
[lookup[v] for v in arr1]

rawDescription: indices of NumPy arrays intersection

description: Indices of NumPy arrays intersection


code:
class YourModel(ndb.Model):
  some_datetime = ndb.DateTimeProperty()
  some_date = ndb.ComputedProperty(lambda self: self.some_datetime.date)

rawDescription: How to compare a python date against a DateTimeProperty in an NDB query

description: Compare a python date against a DateTimeProperty in an NDB query


code:
import dateutil.parser as p

(p.parse("02:20:03")+datetime.timedelta(minutes=2)).time()

rawDescription: Add a minute to a string

description: Add a minute to a string


code:
def fib():
    a,b=0,1
    while True:
        yield a
        a,b=b,a+b

next(fib())
next(fib())
gen = fib()
next(gen)
next(gen)

rawDescription: Python generator initialize- 2 ways ,different outputs


code:
# assuming which duplicate is removed doesn't matter...
for row in MyModel.objects.all():
    if MyModel.objects.filter(photo_id=row.photo_id).count() > 1:
        row.delete()

rawDescription: Delete Duplicate Rows in Django DB

description: Delete Duplicate Rows in Django DB


code:
pairs = [('abc', 'xyz'), ('123', '987'), ('abc', '987')]

pairLambs = []

for p in pairs:
    pairLambs.append(lambda p=p: print(p))

pairLambs[0]()
pairLambs[1]()
pairLambs[2]()

rawDescription: Python lambda as constant functor

description: Python lambda as constant functor


code:
from logging.handlers import TimedRotatingFileHandler

class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
    def __init__(self, logfile, when, interval):
        super(MyTimedRotatingFileHandler, self).__init__(logfile, when, interval)
        self._header = ""
        self._log = None

    def doRollover(self):
        super(MyTimedRotatingFileHandler, self).doRollover()
        if self._log is not None and self._header != "":
            self._log.info(self._header)

        def setHeader(self, header):
            self._header = header

        def configureHeaderWriter(self, header, log):
            self._header = header
            self._log = log

# create time-rotating log handler
logHandler = MyTimedRotatingFileHandler(logfile, when='midnight')
form = '%(asctime)s %(name)s %(levelname)s: %(message)s'
logFormatter = logging.Formatter(form)
logHandler.setFormatter(logFormatter)

# create logger
log = logging.getLogger('MyLogger')
logHandler.configureHeaderWriter('test-header', log)
log.addHandler(logHandler)
log.setLevel(logging.INFO)

rawDescription: Write a header at every logfile that is created with a time-rotating logger


code:
all_my_lists = {} #USE A DICT!!!
all_my_list[listx[2]] = listx  #listx[2] gives the 3rd value in listx

rawDescription: Python, rename a list with one of its values


code:
from multiprocessing import Process, Queue
import time
import random
from __future__ import print_function

def f(param, queue):
    #do the minimization and add result to queue
    #res = minimize(param)
    #queue.put(res)

    #to make this a working example I'll just sleep a
    #a random amount of time
    sleep_amount = random.randint(1, 10)
    time.sleep(sleep_amount)
    res = param*sleep_amount
    queue.put(res)

q = Queue()
p = Process(target=f, args=(2.2, q))
max_time = 3
t0 = time.time()

p.start()
while time.time() - t0 < max_time:
    p.join(timeout=1)
    if not p.is_alive():
        break

if p.is_alive():
    #process didn't finish in time so we terminate it
    p.terminate()
    result = None
else:
    result = q.get()
print(result)

rawDescription: Stop Scipy minimize after set time

description: Stop Scipy minimize after set time


code:
from django.db.models import Count

#group by portfolios count
User.objects.annotate(portfolios=Count('portfolio')).order_by('portfolios')
#group by projects count
User.objects.annotate(projects=Count('portfolio__project')).order_by('projects')

rawDescription: How to sort in a django queries?

description: Sort in a django queries


code:
addresses = 'friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>'
email.utils.getaddresses([addresses])

rawDescription: Method for parsing text Cc field of email header?


code:
ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

rawDescription: How to merge multiple dicts with same key?

description: Merge multiple dicts with same key


code:
import threading,time
def play1():
    while time.time() <= start_time:
        pass
    threading.Thread(target=listen_to_audio).start()
def play2():
    while time.time() <= start_time:
        pass
    threading.Thread(target=play_audio).start()
start_time=time.time()+20
threading.Thread(target=play1).start()
threading.Thread(target=play2).start()

rawDescription: Starting two methods at the same time in Python


code:
class A(type):
    def _repr_pretty_(cls, p, cycle):
        p.text(repr(self))

    def __repr__(cls):
        return 'This Information'

class B:   #or for Py3K: class B(metaclass=A):
    __metaclass__ = A

rawDescription: IPython representation of classes

description: IPython representation of classes


code: var = self.__helper(record)

rawDescription: passing self as an argument in a helper method

description: Passing self as an argument in a helper method


rawDescription: Faster way to transform group with mean value in Pandas


code: sum(x["status"]=="connecting" for x in self.servers.values())

rawDescription: How to compact this for?

description: Compact this for


code:
gc.DEBUG_STATS
gc.DEBUG_COLLECTABLE
gc.DEBUG_UNCOLLECTABLE
gc.DEBUG_INSTANCES
gc.DEBUG_OBJECTS
gc.DEBUG_SAVEALL
gc.DEBUG_LEAK

rawDescription: Python: logging the garbage collector

description: Python: logging the garbage collector


code:
from subprocess import Popen, PIPE
p = Popen(['omxplayer', filePath], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.write(' ') # sends a space to the running process
p.stdin.flush() # if the above isn't enough, try adding a flush

rawDescription: Python interact with running process

description: Python interact with running process


rawDescription: Getting all href from a code

description: Getting all href from a code


code: AllItems = [QComboBoxName.itemText(i) for i in range(QComboBoxName.count())]

rawDescription: Getting all items of QComboBox - PyQt4 (Python)


code:
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    "django.core.context_processors.request",
)

rawDescription: python-social-auth with django /?next= variable

description: Python-social-auth with django /?next= variable


code:
import Tkinter as tk

root = tk.Tk()
tk.Label(root, text="this is the root window").pack()
root.geometry("200x200")
for i in range(4):
    window = tk.Toplevel()
    window.geometry("200x200")

    tk.Label(window, text="this is window %s" % i).pack()

root.mainloop()

rawDescription: How to open multiple windows in Tkinter

description: Open multiple windows in Tkinter


rawDescription: Random syntax error in python?

description: Random syntax error in python


code:
final_grid = np.empty((nrows,ncols))
for ii in xrange(len(data)):
    final_grid[row[ii,:],col[ii,:]] = data[ii]

rawDescription: Avoid for-loops in assignment of data values


code:
def dijkstra(self, graph, start, end):
        D = {} # Final distances dict
        P = {} # Predecessor dict

        for node in graph.keys():
            D[node] = -1 # Vertices are unreachable
            P[node] = ""
        D[start] = 0 # The start vertex needs no move
        unseen_nodes = graph.keys() # All nodes are unseen

        while len(unseen_nodes) > 0:
            shortest = None
            node = ''
            for temp_node in unseen_nodes:
                if shortest == None:
                    shortest = D[temp_node]
                    node = temp_node
                elif (D[temp_node] < shortest):
                    shortest = D[temp_node]
                    node = temp_node
            unseen_nodes.remove(node)
            for child_node, child_value in graph[node].items():
                if D[child_node] < D[node] + child_value['weight']:  # I changed the code here
                    D[child_node] = D[node] + child_value['weight']   # I changed the code here
                    P[child_node] = node
        path = []
        node = end
        while not (node == start):
            if path.count(node) == 0:
                path.insert(0, node) # Insert the predecessor of the current node
                node = P[node] # The current node becomes its predecessor
            else:
                break
        path.insert(0, start) # Finally, insert the start vertex
        return path

rawDescription: Will my dicts of dicts work for this Dijkstra's algorithm?


code:
import mymodule

while mymodule.go():
    reload(mymodule)

rawDescription: Python object persistence over re-execs

description: Python object persistence over re-execs


rawDescription: Convert relative URL to fully qualified URL using Python


code:
class MyView(ListAPIView):
    http_method_names = ['get', 'post']
    # ...

rawDescription: Restrict a Django REST framework generic view to a set of HTTP methods


code:
def make_fruit(name, kwargs):
    def my_init(self):
        Fruit.__init__(self, **kwargs)
    return type(name, (Fruit,), {'__init__': my_init})

Apple = make_fruit('Apple', apple)

rawDescription: Python: Programatically create subclasses based on __init__ values


code:
from M2Crypto import SSL
SSL.Connection.clientPostConnectionCheck = None

rawDescription: What to put for a commonName when making an OpenSSL key?


code:
def stripName(name):
    return name[0].strip()

rawDescription: python startswith method

description: Python startswith method


code: os.system("konsole --workdir " + os.getcwd() + "&")

rawDescription: python 2.7. How to open an independent terminal inheriting globals and current folder

description: Python 2.7. How to open an independent terminal inheriting globals and current folder


rawDescription: getting only values fullfilling condition in a numpy array

description: Getting only values fullfilling condition in a numpy array


code:
validCombo = sorted(validCombo, key=lambda elem: elem[numDays][1], reverse = True)
validCombo = sorted(validCombo, key=lambda elem: elem[numDays][0])

rawDescription: Sorting a list of list of tuples

description: Sorting a list of list of tuples


code:
second = re.search(r'(.(?!son))+', str_to_search)
#output: 'ababa'

rawDescription: Python regular expression issue

description: Python regular expression issue


rawDescription: Is it possible to delete/remove a wx.aui.AuiManager pane?


code:
from random import randint

class Dice(object):
    def __init__(self):
        self.dice = []

    def roll(self,how_many):
        for i in range(how_many):
            self.dice.append(randint(1,6))

hand = Dice()
hand.roll(5)
print(hand.dice)

rawDescription: How to do this first step in my programming project in python 2.7

description: Do this first step in my programming project in python 2.7


code:
from itertools import islice

with open('A.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=';')
     for row in islice(reader,5000,6000):
           response = urllib2.urlopen(row[12])

rawDescription: How to read only a specific range of lines out of a csv file with python?

description: Read only a specific range of lines out of a csv file with python


code:
def dynamic_attrs(cls):
    for v, k in getattr(cls, '_pairs', []):
        setattr(cls, k, v)
    # you also optionally delete the _pairs attr here using del cls._pairs
    return cls

@dynamic_attrs
class TestObject(object):
    """reflects constants in _test_object"""
    _pairs = (
        ( 1       , 'A' ),
        ( 2       , 'B' ),
        ( 4       , 'C' ),
        ( 8       , 'D' ),
    )

rawDescription: programattically define attributes on class definition

description: Programattically define attributes on class definition


rawDescription: Python String unwanted overwrite

description: Python String unwanted overwrite


rawDescription: Saving Output as List

description: Saving Output as List


code:
import numpy as np
import matplotlib.pyplot as plt
AD = 0.2
D = 0.4
delta = 8

def Parabolic(x, delta, D, AD):
    rtn_arr = np.zeros(len(x))
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    lgc_arr = tempx<tempD
    x_cut = x[lgc_arr]
    x0_cut = x0[lgc_arr]
    rtn_arr[lgc_arr] = ((2**delta)/(D-AD)**delta)*(D/2 - (x_cut-x0_cut))**delta
    return rtn_arr

figure = plt.figure(figsize=(10,8), dpi=72)
xmin = -1.0
xmax = 1.0
X = np.linspace(xmin,xmax,1000)
plt.plot(X, Parabolic(X, delta=8, D=0.4, AD=0.2))

rawDescription: Conditional Plotting with Numpy and Pyplot


code:
views.py
class NextSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__gt=date.today()).order_by("start_date")[0]
        except IndexError:
            raise Exception("No Next Subscription Found")

class CurrentSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__lt=date.today()).order_by("-start_date")[0]
        except IndexError:
            raise Exception("No Current Subscription Found")

rawDescription: Django using timedelta to filter results in template


code:
def addLayers(self):
    """ Adds Checkboxes inside the listview dynamically based on the number of layers loaded in QGIS. """

    canvas = qgis.utils.iface.mapCanvas()
    allLayers = canvas.layers()
    if canvas.layerCount > 0:
        model = QStandardItemModel()
        for i in allLayers:
            item = QStandardItem('%s' % i.name())
            item.setCheckable(True)
            model.appendRow(item)

        self.dlg.DatacheckerlistView1.setModel(model)
        self.dlg.DatacheckerlistView1.show()

rawDescription: Creating check boxes dynamically inside the listview based on the layers loaded in QGIS


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

import glob
import h5py
#Define the xy size of the mapped array
xsize=3
ysize=3

lengthh5=9
readlist=[]
for i in range (0,lengthh5):
    npraw=np.random.rand(200,50,50)
    readlist.append (npraw)

''' Slider visualization'''
from matplotlib.widgets import Slider
fig=plt.figure()
ls = []
for k in range (0,lengthh5):
    ax=fig.add_subplot(xsize,ysize,k)
    frame = 10
    l = ax.imshow(readlist[k][frame,:,:])
    ls.append(l)
    plt.axis('off')
    sframe = Slider(fig.add_subplot(50,1,50), 'Frame', 0, len(readlist[0])-1, valinit=0)

def update(val):
    frame = np.around(sframe.val)
    for k, l in enumerate(ls):
        l.set_data(readlist[k][frame,:,:])

sframe.on_changed(update)

plt.show()

rawDescription: Python Using pyplot slider with subplots


rawDescription: Making a call to a thread object's method from the context of the thread


code:
def deduplicate(infile, outfile):
    seen = set()
    #final = []
    with open(outfile, "a") as out, open(infile) as in_:
        for line in in_:
            check = tuple(line.split(",")[:2])
            if check not in seen:
                #final.append(line.strip())
                out.write(line) # why 'strip' the '\n' then 'write' a new one?
                seen.add(check)
    #return "\n".join(final)

rawDescription: python script for removing duplicates taking 24 hrs+ to loop through 10^7 records

description: Python script for removing duplicates taking 24 hrs+ to loop through 10^7 records


code: pd.DataFrame({k: df.vec.isin(v) for k, v in comps.iteritems()})

rawDescription: The python version of R's %in% function

description: The python version of R's %in% function


code:
from dateutil.parser import parse
d = parse('2009/05/13 19:19:30 -0400')
d

rawDescription: How to parse dates with -0400 timezone string in python?

description: Parse dates with -0400 timezone string in python


code:
import argparse
parser = argparse.ArgumentParser(description='your description')
parser.add_argument('-entry', dest="entry")
args = parser.parse_args()
print (args.entry)

rawDescription: python: call a function with parameter from input

description: Python: call a function with parameter from input


rawDescription: Python: How do I remove the formatting when joining items from a list into a string?


code:
#!/usr/bin/env python3
import sys
import cgi
tmp = cgi.FieldStorage()
dat = tmp['upload_file']
import mimetypes
gtype,encoding = mimetypes.guess_type(dat.filename)

sys.stdout.buffer.write (b'Content-type:' + gtype.encode('ascii') + b'\r\n\r\n')
sys.stdout.buffer.write (dat.file.read())

rawDescription: Getting back bytes object instead of uploaded file


code:
iris.groupby("Name").PetalWidth.plot(kind='kde', ax=axs[1])
iris.groupby("Name").PetalWidth.hist(alpha=0.4, ax=axs[0])

rawDescription: Plotting histograms against classes in pandas / matplotlib


rawDescription: Python "extend" for a dictionary

description: Python "extend" for a dictionary


rawDescription: Ceil and floor equivalent in Python 3 without Math module?


code:
with patch.dict('mymodule.mydict', {'newkey': 'newvalue'}):
    assert mymodule.mydict == {'newkey': 'newvalue'}

rawDescription: mock dictionary at module level

description: Mock dictionary at module level


code:
import csv

def write_dicts(dicts, keys, filename):

   with open(filename, 'w') as csvfile:
       writer = csv.DictWriter(csvfile, keys, extrasaction='ignore')
       for d in dicts:
           writer.writerow(d)

rawDescription: Python Dynamic Execution

description: Python Dynamic Execution


code:
def find_nearest(arr,value):
    newList = arr - value
    sort = np.sum(np.power(newList, 2), axis=1)
    return newList[sort.argmin()]

rawDescription: Sorting a 2D numpy array on to the proximity of each element to a certain point


code:
a=[1,3,5,10,13]
sub_list_start = 1
sub_list_end = 3
a[sub_list_start : sub_list_end+1] = [9,7]
a

rawDescription: Replacing a sublist with another sublist in python


code:
with open('file.jpg', 'wb') as handle:
    handle.write(data_string)

rawDescription: Convert and save string to binary file in Python


code:
def has_duplicate_words(filename):
    with open(filename, 'r') as f:
        words = set()
        for line in f.readlines():
            lineWords = line.split()
            for word in lineWords:
                if word in words:
                    return True

                words.add(word)
    return False

rawDescription: How do I write a function that returns true if there are duplicate words in a file

description: Write a function that returns true if there are duplicate words in a file


code:
#**************************************************************************#
# Set up a graph. A click creates a blue box. More blue boxes can be made
# by choosing "Make a new box" from right/click menu.
#**************************************************************************#

import wx
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *

#**************************************************************************#
class MainCanvas(wx.Frame):
    """ Class to set up graph """
    def __init__(self):
        wx.Frame.__init__(self,None,-1, 'Make Blue Boxes',size=(550,350))
        self.Bind(wx.EVT_CLOSE, self.deleteAll)

    #**********************************************************************#
    def deleteAll(self,event):
        sys.exit()

    #**********************************************************************#
    def setupGraph(self):
        """ Set up window and graph """
        self.definePlot()
        self.canvas = FigCanv(self, -1, self.figure)
        self.setSizer()

    #**********************************************************************#
    def definePlot(self):
        """ Define attributes of graph """
        self.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

    #**********************************************************************#
    def setSizer(self):
        """ Set the size of the graph """
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

#**************************************************************************#
class BlueBox(MainCanvas):
    """ Class to set up BlueBox """
    def __init__(self):
        MainCanvas.__init__(self)

    #**********************************************************************#
    def setupBlueBox(self):
        """ Blue box set up """
        self.blueBox = patches.Rectangle((0, 0), 0.05, 0.05,
                fc = "Blue", visible = False, zorder = 3)
        # Set zorder so new boxes are in front of old
        if len(self.listDT)>1:
            oldz = self.listDT[len(self.listDT)-2].blueBox.get_zorder() + 3
            self.listDT[len(self.listDT)-1].blueBox.set_zorder(oldz)

        self.axes.add_patch(self.blueBox)

    #**********************************************************************#
    def onPick(self, event):
        """ Behavior when graph is clicked """
        # Refresh BlueBox position and coordinate text
        self.refreshBlueBox(event)
        # Set the current BlueBox visible
        self.listDT[len(self.listDT)-1].setVisible()

    #**********************************************************************#
    def refreshBlueBox(self, event):
        """ Blue box refresh    """
        # Center the BlueBox (Point Box) over the mouse click location
        self.blueBox.set_x(event.xdata - .5 * self.blueBox.get_width())
        self.blueBox.set_y(event.ydata - .5 * self.blueBox.get_height())

    #**********************************************************************#
    def setVisible(self):
        """ Make BlueBox visible and refresh canvas """
        self.blueBox.set_visible(True)
        self.figure.canvas.draw()

    #**********************************************************************#
    def setGraphAttributes(self, axes, figure, listDT):
        """ Tell each BlueBox about the graph attributes it needs """
        self.axes = axes
        self.figure = figure
        self.listDT = listDT

#**************************************************************************#
class MyPopupMenu(BlueBox):
    """ Class to handle right clicks """
    def __init__(self):
        BlueBox.__init__(self)

    #**********************************************************************#
    def setup(self):
        """ Set up graph and BlueBox """
        self.setupGraph()
        # Bind right clicks to open the popup menu
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,
                self.createPopupMenu)

        # Create lists for BlueBoxs and binding IDs
        self.listDT = []
        self.listBID = []

        self.popupCreateNew = wx.NewId()
        self.menu = wx.Menu()
        self.cn = self.menu.Append(self.popupCreateNew,
                "Make a new box")
        self.Bind(wx.EVT_MENU, self.createNew, self.cn)

        # Make the first BlueBox
        self.newBox()

    #**********************************************************************#
    def createPopupMenu(self, event):
        """ Create all parts of the right-click popup menu """
        self.PopupMenu(self.menu)

    #**********************************************************************#
    def newBox(self):
        """ Make a new BlueBox """
        self.listDT.append(BlueBox())
        self.listDT[len(self.listDT)-1].setGraphAttributes(self.axes,
                self.figure, self.listDT)
        self.listDT[len(self.listDT)-1].setupBlueBox()
        self.listBID.append(self.figure.canvas.mpl_connect('button_press_event',
                self.listDT[len(self.listDT)-1].onPick))

    #**********************************************************************#
    def createNew(self, event):
        """ Create a new BlueBox """
        event.Skip()
        self.newBox()
        if len(self.listBID) > 1:
            self.figure.canvas.mpl_disconnect(self.listBID[len(self.listBID)-2])

#**************************************************************************#
class app(wx.App):
    """ Create and show all """
    def OnInit(self):
        self.mpm = MyPopupMenu()
        self.mpm.setup()
        self.frame = self.mpm.Show()
        return True

#**************************************************************************#
# Run the program
#**************************************************************************#
app = app(0)
app.MainLoop()

rawDescription: Window close does not close program, even with a function calling sys.exit() bound to the window's close_event. What might cause this?


rawDescription: Can python's slice notation be used outside of brackets?


code:
sentence = "Hello world. How are you? Hello"
counts = collections.Counter(sentence.split()) # note that this still counts punctuation. Thus, "Hello," and "Hello" are two different words

rawDescription: Word frequency counter for locally stored website


code:
while True:
    if self.h <= 1:
        incr = 1
    elif self.h >= 359:
        incr = -1
    self.h += incr
    ...
    ...

rawDescription: Is there a more efficient algorithm for this process?


rawDescription: wxPython statusbar

description: WxPython statusbar


code:
from operator import itemgetter
import bisect

data = ((0, 16777215, 'ZZ'), (1000013824, 1000079359, 'CN'), (1000079360, 1000210431, 'JP'), (1000210432, 1000341503, 'JP'), (1000341504, 1000603647, 'IN'))
sorted_data = sorted(data, key=itemgetter(0))
lower_bounds = [lower for lower,_,_ in data]

def lookup_ip(ip):
    index = bisect.bisect(lower_bounds, ip) - 1
    if index < 0:
        return None
    _, upper, country = sorted_data[index]
    return country if ip <= upper else None

print(lookup_ip(-1))          # => None
print(lookup_ip(999))         # => 'ZZ'
print(lookup_ip(16777216))    # => None
print(lookup_ip(1000013824))  # => 'CN'
print(lookup_ip(1000400000))  # => 'IN'

rawDescription: What's a faster way to look up a value in a list of tuples?


code:
from itertools import izip_longest
[x+y   for x,y in izip_longest(list1,list2, fillvalue = ['',''])]

rawDescription: Combine two 2D Lists of unequal length to create one new list


code:
import zlib

compressedString = zlib.compress(originalString, 9)  # Compress at level 9

decompressedString = zlib.decompress(compressedString)

rawDescription: How to compress a string in Python to store it in Redis?

description: Compress a string in Python to store it in Redis


rawDescription: Get global variables from file as dict?

description: Get global variables from file as dict


code:
from collections import defaultdict
dic = defaultdict(int)
for a, b in start:
    dic[a] += b
list(dic.items())

rawDescription: How to add tuples y values if x values are the same?

description: Add tuples y values if x values are the same


code:
class InboundMailHandler(InboundMailHandler):
    def post(self):
        msg = email.message_from_string(self.request.body)
        if msg:
            charset = 'utf-8'
            from_realname, from_emailaddr = email.utils.parseaddr(msg['from'])
            to_realname, to_emailaddr = email.utils.parseaddr(msg['to'])
            # parse e-mail body, look for text/plain part only
            body = ''
            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() and part.get_content_type()=='text/plain': # ignore text/html
                        charset = part.get_content_charset()
                        body = part.get_payload(decode=True).decode(part.get_content_charset())
            else:
                body = msg.get_payload(decode=True)
                body = body.decode('utf-8')
            subject, encoding = email.header.decode_header(msg['subject'])[0]
            if encoding != None:
                subject = subject.decode(encoding)
            else:
                subject = subject.decode('utf-8')

rawDescription: How to parse inbound GAE email manually?

description: Parse inbound GAE email manually


code:
def getCars(self):
    if "cars" in self:
        return self["cars"]
    elif "car" in self:
        return [self["car"]]  # build a list for the single car!
    else:
        return []  # return an empty list if neither key exists

rawDescription: Inconsistent Return Type

description: Inconsistent Return Type


code:
from datetime import datetime
date1 = datetime.strptime(date1, "%d/%m/%Y")
date2 = datetime.strptime(date2, "%d/%m/%Y")
date3 = datetime.strptime(date3, "%d/%m/%Y")
date4 = datetime.strptime(date4, "%d/%m/%Y")
datelist = [date1, date2, date3]
for j in datelist:
     if j <= date4:
          print(j.strftime('%d/%m/%Y'))

rawDescription: greater than 'date' python 3

description: Greater than 'date' python 3


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(0.2, 0.7, 'No mathtex')
ax.text(0.2, 0.5, 'This superscript $is^{in}$ italics')
ax.text(0.2, 0.3, 'While this $\mathregular{is^{really}}$ the same font')
plt.show()

rawDescription: Is there a way to do subscripts/superscripts in Matplotlib without TeX?


code:
def smallest_contiguous(s, N):
    lst = list(s)
    lst.sort()
    Nm = N-1
    for i in xrange(len(lst) - Nm):
        if lst[i] + Nm == lst[i + Nm]:
            return range(lst[i], lst[i]+N)
    return []

rawDescription: Finding smallest contiguous integers in a Python set


code:
s = pd.Series(['a', 'b,c', np.nan, 'd,e,f'])
s.str.split(',')

rawDescription: TypeError with Python UDF returned inexplicably


code:
import plotly.plotly as py
from plotly import tools
from plotly.graph_objs import Bar, Data, Figure, Layout, Marker, Scatter

x_0 = [1, 2, 4, 6, 7, 7]
x_1 = [10, 10, 10, 10, 10, 10]
y_0 = [2, 3, 4, 2, 3, 3]

trace1 = Bar(
    x=x_0,
    marker=Marker(color='#001f3f'),
    orientation='h',
)

trace2 = Bar(
    x=x_1,
    marker=Marker(color='#0074D9'),
    orientation='h',
)

trace3 = Scatter(y=y_0)

fig = tools.make_subplots(1, 2)
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)
fig.append_trace(trace3, 1, 2)
fig['layout'].update(barmode='stack')

py.iplot(fig, filename='oecd-networth-saving-bar-line')

rawDescription: How to a stacked bar chart with line chart using Plotly?

description: A stacked bar chart with line chart using Plotly


code:
my_re = re.compile("stuff=\s+(\S+)\s+(\S+)")
line = "stuff= foo bar"
matches = my_re.search(line)
if matches:
  print(matches.groups())

rawDescription: Python Regex Table Creator from file

description: Python Regex Table Creator from file


code:
import sys
oldsysstdout = sys.stdout
class flushfile():
    def __init__(self, f):
        self.f = f
    def __getattr__(self,name):
        return object.__getattribute__(self.f, name)
    def write(self, x):
        self.f.write(x)
        self.f.flush()
    def flush(self):
        self.f.flush()
sys.stdout = flushfile(sys.stdout)

rawDescription: Make ipython notebook print in real time


code:
class Source:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Dest:
    def __init__(self, a):
        self.a = a

    @classmethod
    def from_source(cls, src):
        return Dest(src.x + src.y)

s = Source(5, 3)
d = Dest.from_source(s)
assert d.a == 8

rawDescription: How to name method used by __init__ to determine value of new object?

description: Name method used by __init__ to determine value of new object


rawDescription: can python's list method `index()` find a list element in a list

description: Can python's list method `index()` find a list element in a list


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock

Builder.load_string("""
<MyWidget>:
    canvas:
        Color:
            rgb: 0.5, 0.8, 1
        Rectangle:
            size: self.size
            pos: self.pos
    TextInput
        size_hint: 0.5, 0.5
        pos_hint: { 'center_x' : 0.5, 'center_y' : 0.5 }
        background_normal: 'white.png'
        background_active: 'white.png'
""")

class MyWidget(FloatLayout):
    pass

class ClientApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    ClientApp().run()

rawDescription: Remove kivy text input boarders

description: Remove kivy text input boarders


code:
exec("x=42")
print(x)

rawDescription: What does "dynamic creation of variables" mean?


code:
def whatever(input):
    """
    >>> whatever(0)
    '0'
    >>> whatever(1)
    '10'
    >>> whatever(2)
    '1110'
    >>> whatever(3)
    '3110'
    >>> whatever(4)
    '132110'
    >>> whatever(5)
    '1113122110'
    """
    def looksay(input, result):
        if not input:
            return result
        else:
            left, right = input[0], input[1:]
            if not result:
                result = '1' + left
            else:
                left_result, count, right_result = result[:-2], int(result[-2]), result[-1]
                if left == right_result:
                    result = left_result + str(count + 1) + right_result
                else:
                    result = result + '1' + left
            return looksay(right, result)
    def helper(number, result):
        if number == 0:
            return result
        else:
            return helper(number - 1, looksay(result, ''))
    return helper(input, '0')

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: reading a string of numbers as words then printing each word as a number

description: Reading a string of numbers as words then printing each word as a number


rawDescription: How to create Jinja2 custom filters with django_jinja app?

description: Create Jinja2 custom filters with django_jinja app


code:
try:
  myDict["myKey"]["nestedDictKey2"] = anotherValue
except KeyError:
  myDict["myKey"] = {"nestedDictKey2": anotherValue}

rawDescription: Updating nested dictionaries when data has existing key


code:
import boto.ec2

conn = boto.ec2.connect_to_region('us-west-2')
conn.copy_snapshot(source_region='us-east-1', source_snap_id='snap-12345678',
                   description='My new copy')

rawDescription: boto - copy snapshot to another region

description: Boto - copy snapshot to another region


code:
import re
p = re.compile(r'[b-df-hj-np-tv-z][aeiou](?=[b-df-hj-np-tv-z])')
#                                        ^^^                 ^
test_str = "lolololol"
print(p.findall(test_str))
print(len(p.findall(test_str)))

rawDescription: Re-evaluate a Character in Python Regex

description: Re-evaluate a Character in Python Regex


code:
from threading import Thread
import curses
import time

#global variables
line_thread_1 = 0
line_thread_2 = 0
end_1 = False
end_2 = False

def thread1():
    global line_thread_1
    global end_1
    for i in xrange(10):
        time.sleep(0.5)
        line_thread_1 += 1
    end_1 = True

def thread2():
    global line_thread_2
    global end_2
    for i in xrange(10):
        time.sleep(0.25)
        line_thread_2 += 1
    end_1 = True

thread1 = Thread(target=thread1)
thread2 = Thread(target=thread2)
thread1.start()
thread2.start()

stdscr = curses.initscr()
while not (end_1 or end_2):
    stdscr.erase()
    stdscr.addstr('>>> Thread 1: ' + str(line_thread_1) + ' of 10\n')
    stdscr.addstr('>>> Thread 2: ' + str(line_thread_2) + ' of 10\n')
    stdscr.refresh()
    time.sleep(1)
curses.endwin()

rawDescription: Python: Print to separate bash line for every thread, in a multithread application


code:
elem.tag
elem.get('number')
elem.text

rawDescription: LXML itertree parsing tag information

description: LXML itertree parsing tag information


code: sorted(st, key=lambda x: (x[1]*-1,x[0]))

rawDescription: How to sort in python based on two parameters but with different orders

description: Sort in python based on two parameters but with different orders


code:
from flask import Flask, url_for, render_template, redirect
from flask import request # <-- add this

# ... snip setup code ...

# We need to specify the methods that we accept
@app.route("/test-post", methods=["GET","POST"])
def test_post():
    # method tells us if the user submitted the form
    if request.method == "POST":
        name = request.form.name
        email = request.form.email
    return render_template("form_page.html", name=name, email=email)

rawDescription: Flask, html and javascript desktop app

description: Flask, html and javascript desktop app


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

import sys
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base

from PyQt4 import QtCore, QtGui, uic

# My base structure

base = declarative_base()

class User(base):
    __tablename__ = "users"
    id_ = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)

    name = sqlalchemy.Column(sqlalchemy.String(20))

    def __repr__(self):
        return "<User(id='%s', name='%s')>" % (self.id_, self.name)

# Creating my base and my session
engine = sqlalchemy.create_engine("sqlite:///my_db.db", echo='debug')
base.metadata.create_all(engine)

DBsession = sqlalchemy.orm.sessionmaker(bind=engine)
session = DBsession()

# My model, i just want to show data
class UserListModel(QtCore.QAbstractListModel):

    def __init__(self, session, parent = None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self.session = session
        self.refresh()

    def refresh(self):
        self.users = self.session.query(User).all()

    def rowCount(self, parent):
        return len(self.users)

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            value = self.users[index.row()]
            return "%s : %s" % (value.id_, value.name)

def add_user(session, tmp_name):
    session.add(User(name=tmp_name))
    session.commit()

# Populating my db
if not session.query(User).count():
    session.add(User(name="edouard"))
    session.add(User(name="jean"))
    session.add(User(name="albert"))
    session.commit()

# Creating my app
app = QtGui.QApplication(sys.argv)
mywindow = QtGui.QWidget()

# Combobox and his model
combobox = QtGui.QComboBox(mywindow)
combobox.setModel(UserListModel(session))

mywindow.show()
sys.exit(app.exec_())

rawDescription: PyQt application with sqlalchemy database


code:
import random
sum(random.random()*50 + 80 for _ in range(1000))

rawDescription: summation of 1000 different random numbers between 80-130?

description: Summation of 1000 different random numbers between 80-130


code:
import time
import random

def doTimeConsumingStep(N):
    """
    This represents the computational part of your simulation.

    For the sake of illustration, I've set it up so that it takes a random
    amount of time which is occasionally longer than the interval you want.
    """
    r = random.random()
    computationTime = N * (r + 0.2)
    print("...computing for %f seconds..."%(computationTime,))
    time.sleep(computationTime)

def timerTest(N=1):
    repsCompleted = 0
    beginningOfTime = time.clock()

    start = time.clock()
    goAgainAt = start + N
    while 1:
        print("Loop #%d at time %f"%(repsCompleted, time.clock() - beginningOfTime))
        repsCompleted += 1
        doTimeConsumingStep(N)
        #If we missed our interval, iterate immediately and increment the target time
        if time.clock() > goAgainAt:
            print("Oops, missed an iteration")
            goAgainAt += N
            continue
        #Otherwise, wait for next interval
        timeToSleep = goAgainAt - time.clock()
        goAgainAt += N
        time.sleep(timeToSleep)

if __name__ == "__main__":
    timerTest()

rawDescription: Control the speed of a loop

description: Control the speed of a loop


code:
def _accumulate_stress(betweenness,S,P,sigma,s):
    delta = dict.fromkeys(S,0)
    while S:
        w = S.pop()
        for v in P[w]:
            delta[v] += (1.0+delta[w])
        if w != s:
            betweenness[w] += sigma[w]*delta[w]
    return betweenness

rawDescription: Faster way to calculate the number of shortest paths a vertex belongs to using Networkx


code:
from django.views.generic import ListView

class NewsView(ListView):
    paginate_by = 3
    template_name = 'blog-right-sidebar.html',
    context_object_name = 'news'
    queryset = News.objects.filter(is_active=True).order_by('-timestamp')

    def get_context_data(self, **kwargs):
        # Here you can add any additional context items.
        context = super(NewsView, self).get_context_data(**kwargs)
        context['var'] = 'value'
        return context

rawDescription: global name 'object_list' is not defined on django 1.6

description: Global name 'object_list' is not defined on django 1.6


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

fig = plt.figure()

ax = plt.subplot(1,1,1)

N = 10
M = 10

plt.xlim(0,N+M)
plt.ylim(0,N+M)

x = np.arange(N+M)
y = np.arange(N+M)

bars = [b for b in plt.bar(x[:N],y[:N],1)]

def init():
    return bars

# animation function.  This is called sequentially
def animate(i):
    if i<M:
        bars.append(plt.bar(x[N+i],y[N+i],1)[0])
    return bars

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames = 10, interval=200, blit=True)
plt.show()

rawDescription: Add new bins at each iteration of a an animation in matplotlib


code:
def all_same_sign(ints):
    return all(x < 0 for x in ints) or all(x > 0 for x in ints)

rawDescription: Feedback on implementation of function which compares integer signs in Python


code: users = [User(user, password) for user, password in zip(usernameList, passwordList)]

rawDescription: Joining two lists that correspond to each other to create a list of class objects


rawDescription: Python, code a number with exponential decimal notation


code:
Person = type('Person', (models.Model,), {
    'first_name': models.CharField(max_length=255),
    'last_name': models.CharField(max_length=255),
})

rawDescription: Runtime model generation using django

description: Runtime model generation using django


rawDescription: Get every nth item in list inside of another list


code:
class MyTCPHandler(SocketServer.BaseRequestHandler):
      def handle(self):
            self.DriveSend = self.request.recv(1024).strip()
            self.SteeringSend = self.request.recv(1024).strip()
            MotorControl(self)
            return (self.DriveSend,self.SteeringSend)

def MotorControl(motor_var):
      print(motor_var.DriveSend)
      print(motor_var.SteeringSend)
      print('test')

rawDescription: activating a Function from another function in a different class

description: Activating a Function from another function in a different class


code:
from jinja2 import Template

my_template = Template("""

{% for url in urls %}
{{ url }}
{% endfor %}

""")

urls = ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"]
rendered_html = my_template.render(urls=urls)

rawDescription: HTML Generator, Gallery Generator or Templating?


code:
with self.canvas:
    Scale(6)
    self.pixelart = Rectangle(texture=texture, pos=(0, 0), size=(64, 64))

rawDescription: What is the most efficient way to create a pixelated game with Kivy?


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# And this code will not give you any problems

s1 = 'É, Á, Ö, Ü. Ó,'
logging.info (s1)
s2 = s1 + ':' + s1
logging.info ("%s,%s", s1, s2)

rawDescription: Python unicode string operation in App Engine failing


code:
def new_obj(self):
    return self.__class__()

rawDescription: How to create object of derived class inside base class in Python?

description: Create object of derived class inside base class in Python


rawDescription: Send a packet of data literally via UDP in Python


code: read_files = filter(lambda f : f != 'result.txt', glob.glob('*.txt'))

rawDescription: Not opening a specific text file in Python


code:
def alpha_word():
    word = list(input('Enter a word: '))
    return word == sorted(word)

rawDescription: Return Boolean depending on whether or not string is in alphabetical order


code:
from django.db.models.signals import post_save
from somewhere_in_my_app import my_post_save_handler

post_save.disconnect(my_post_save_handler)
instance.save()
post_save.connect(my_post_save_handler)

rawDescription: Django - how do I _not_ dispatch a signal?


code:
class Foo(object):
    def __init__(self):
        pass
    def __eq__(self, other):
        return isinstance(other, Foo)

rawDescription: Check if an object is in a shelve

description: Check if an object is in a shelve


code:
np.savetxt('output.txt', a.reshape(a.shape[0]*a.shape[1]*a.shape[2]),
            delimiter=' ', newline='\n')

rawDescription: Printing a multi-dimension array to text file in pythonic way


code:
def sqrs(seq):
    indices = [(x % 3, x / 3) for x in range(0, 9)]  # Set up a list of coordinates
    boxes = [[seq[x*3+xx][y*3+yy] for xx, yy in indices] for x, y in indices]  # Use the list of coordinates both to reference the boxes and to reference the cells within the box, to reorganize the list.
    return boxes

rawDescription: Extracting Boxes from Sudoku Solution as List of Lists


code:
from numpy import *

# Your original list of numpy arrays ...
b = [array([5, 7]), array([5, 5])]
# ... can be converted to list of lists
c = [list(x) for x in b]

rawDescription: How to convert array inside list into list item using Python?

description: Convert array inside list into list item using Python


code:
import sys
class MyClass: pass

L1 = []
L2 = []
L1.append(MyClass())
sys.getrefcount(L1[0])
L2.append(L1[0])
sys.getrefcount(L1[0])
del L1[0]
sys.getrefcount(L2[0])

rawDescription: Tracking references to object instances

description: Tracking references to object instances


code:
class Intermediate(B):
    def process(self):
        for item in self.items:
            try:
                self.process_item(item)
            except ItemError as err:
                handle_error(err)

class D(C, Intermediate):
    pass

rawDescription: Override method on parent class

description: Override method on parent class


code:
import os
def return_file(name):
    filepath = os.path.join('/path/to/your/cgi-bin', name)
    if os.path.isfile(filepath):
        return open(filepath, 'b').read()

rawDescription: How to download a file located in web server CGI-bin folder?

description: Download a file located in web server CGI-bin folder


code:
interval = 1000 # 1 second
def update():
    log = d.getLastLog()
    if (log[0] != prev[0]):
        logField.config(state=NORMAL)
        logField.insert('1.0',str(log)+'.\n')
        logField.config(state=DISABLED)
        prev = log
    root.after(interval, update)
root.after(interval, update)

rawDescription: retrieve from database dynamically to tkinter gui

description: Retrieve from database dynamically to tkinter gui


code:
a
b
a==b
np.all(a==b,axis=1)
np.where(np.all(a==b,axis=1))

rawDescription: Numpy Array Get row index searching by a row


code:
listA = [ [1,20], [3,19], [37,11], [21,17] ]
listB = [ [1,20], [21,17] ]
setA = frozenset([frozenset(element) for element in listA])
setB = frozenset([frozenset(element) for element in listB])
setA
setB
setB <= setA

rawDescription: list is a subset of another list

description: List is a subset of another list


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('chart_point.xlsx')

worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})

data = [
    [1, 2, 3, 4, 5],
    [2, 4, 6, 8, 10],
    [3, 6, 9, 12, 15],

]

# Write the data for the chart.
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])

# Add a chart series with markers but turn some off.
chart.add_series({
    'categories': '=Sheet1!$A$1:$A$5',
    'values': '=Sheet1!$B$1:$B$5',
    'marker': {'type': 'automatic'},
    'points': [
            {'fill': {'none': True}, 'line': {'none': True}},
            {'fill': {'none': True}, 'line': {'none': True}},
            {'fill': {'none': True}, 'line': {'none': True}},
            {'fill': {'none': True}, 'line': {'none': True}},
    ],
})

# Add a second chart series.
chart.add_series({
    'categories': '=Sheet1!$A$1:$A$5',
    'values': '=Sheet1!$C$1:$C$5',
    'marker': {'type': 'automatic'},
    'points': [
            {'fill': {'none': True}, 'line': {'none': True}},
            {},
            {'fill': {'none': True}, 'line': {'none': True}},
            {'fill': {'none': True}, 'line': {'none': True}},
            {'fill': {'none': True}, 'line': {'none': True}},
    ],
})

worksheet.insert_chart('E9', chart)

workbook.close()

rawDescription: create point in graph using xslwriter

description: Create point in graph using xslwriter


code:
while True:
    question=input("do you like maths?")
    while True:
        re_do=input("Would you like to check anything else?")
        if re_do.lower=="no":
            quit()
        elif re_do.lower=="yes":
            break
        elif re_do.lower() !="no" and re_do.lower() !="yes":
            print("Yes or No answer only: ")
            continue

rawDescription: set a variable to only accept certain strings on python and break while loops using if/else

description: Set a variable to only accept certain strings on python and break while loops using if/else


code:
def elimina_client(self):
    with open("clienti.txt","r") as f:
        lines=f.readlines()

    with open("clienti.txt","w") as f:
        [f.write(line) for line in lines if line.strip() ]

rawDescription: How to eliminate blank lines from a file

description: Eliminate blank lines from a file


code:
if any(s in shp_name for s in ("Forwarder", "T_", "Grad")):
    ...

rawDescription: Using "if not" with multiple string arguments Python


code:
class Singleton(object):

    __instance = None

    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            cls.__instance.name = "The one"
        return cls.__instance

rawDescription: Python singleton / object instantiation

description: Python singleton / object instantiation


code:
def __lt__(self, other):
    return self.age < other.age

rawDescription: How do I make a heap queue of objects in python?

description: Make a heap queue of objects in python


code:
_tmp = b.pages
_tmp()

rawDescription: Python property callable

description: Python property callable


code:
query_arg = ['bad_threshold__lte', 'bad_threshold__lte', 'okay_threshold_3__lte', 'tasty_threshold__lte', 'delicious_threshold__lte']

Q(**{query_arg[int(threshold) - 1]: user.profile.taste_tolerance})

rawDescription: Django/Python DRY: how to avoid repeat code when working with Q objects and model attributes


code:
parser = argparse.ArgumentParser()
parser.add_argument('--abc', nargs='?', default="default")
parser.parse_args()
parser.parse_args(['--abc'])
parser.parse_args(['--abc', 'value'])

rawDescription: ArgumentParser: Optional argument with optional value


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

np.random.seed(42)
N = 1000
A1 = np.random.multivariate_normal(mean=[1,-4], cov=[[2,-1],[-1,2]],size = N)
A2 = np.random.multivariate_normal(mean=[1,-3], cov=[[1,1.5],[1.5,3]],size= N)

fig, ax = plt.subplots()
ax.scatter(A1[:,0], A1[:,1], color="blue", alpha=0.2)
ax.scatter(A2[:,0], A2[:,1], color="red", alpha=0.2)

rawDescription: Different color for each set in scatter plot on matplotlib


rawDescription: meaning of "." after first element in numpy array

description: Meaning of "." after first element in numpy array


code:
while sub_process.poll() is None:
    output_line = sub_process.stdout.readline()

rawDescription: Async read console output with python while process is running


code:
incorrect = 0
max_tries = 3
choices = ['red', 'green', 'yellow']

while incorrect < max_tries:
    user_input = raw_input()
    if user_input not in choices:
        incorrect += 1
    else:
        rest_of_the_code(user_input)
        incorrect = 0

if incorrect == max_tries:
    sys.exit(1)

rawDescription: Is there a way to stop a program after x amount of tries?


code:
from math import log

...

level = int(log(x, 2))
level = min(level, 10) # as suggested by Morb
print(level)

rawDescription: Simplifying this Python code for RPG levels


code:
from math import sqrt

def get_ordered_list(points, x, y):
   points.sort(key = lambda p: sqrt((p.x - x)**2 + (p.y - y)**2))
   return points

rawDescription: How to order a list of points by distance to a given point?

description: Order a list of points by distance to a given point


rawDescription: Using einsum without explicit replication


code: df.groupby('A').agg([np.mean, lambda x: np.std(x, ddof=0)])

rawDescription: Python Pandas: Passing Multiple Functions to agg() with Arguments