code:
from itertools import groupby

new_list = [sublist + [sum(1 for _ in g)] for sublist, g in groupby(list_1)]
# -> [['a', 'b', 1], ['a', 'c', 3], ['b', 'e', 1], ['d', 'q', 2]]

rawDescription: Counting and appending sublist elements in python


code:
randlist = [randon.random() for i in range(n)]
total = sum(randlist)
randlist = [i/total for i in randlist]

rawDescription: Generate a list of fixed value for sum of entries


code:
with open(filename, 'w') as fh:
 indent(tree.getroot())
 tree.write(fh, encoding="ISO-8859-1")

rawDescription: PY 2.7 XML pretty writing to a file option?


code:
with open(dest, "a") as file:
    for tweet in iterator_that_returns_tweets:
        file.write(json.dumps(tweet) + "\n")

rawDescription: memory management: open vs string-building

description: Memory management: open vs string-building


code:
binned = np.full((bin_idx[-1]+1, np.max(col_idx)+1), np.nan)
binned[bin_idx, col_idx] = x

rawDescription: Numpy index a 1D array to 2D

description: Numpy index a 1D array to 2D


code:
pattern = r'^1?$|^(11+?)\1+$'
re.match(pattern, '1'*10)    #matches
re.match(pattern, '1'*11)    #doesn't match

rawDescription: Is_prime function via regex in python (from perl)


code:
import pika

# Step #3
def on_open(connection):

    connection.channel(on_channel_open)

# Step #4
def on_channel_open(channel):

    channel.basic_publish('test_exchange',
                            'test_routing_key',
                            'message body value',
                            pika.BasicProperties(content_type='text/plain',
                                                 delivery_mode=1))

    connection.close()

# Step #1: Connect to RabbitMQ
parameters = pika.URLParameters('amqp://guest:guest@localhost:5672/%2F')

connection = pika.SelectConnection(parameters=parameters,
                                   on_open_callback=on_open)

try:

    # Step #2 - Block on the IOLoop
    connection.ioloop.start()

# Catch a Keyboard Interrupt to make sure that the connection is closed cleanly
except KeyboardInterrupt:

    # Gracefully close the connection
    connection.close()

    # Start the IOLoop again so Pika can communicate, it will stop on its own when the connection is closed
    connection.ioloop.start()

rawDescription: Can we speed up publishing messages via RabbitMQ


code:
def parse(self, response):
    hxs = Selector(response)
    pin_links = hxs.xpath("//div[@class='pinHolder']/a/@href").extract()
    repin_counts = hxs.xpath("//em[@class='socialMetaCount repinCountSmall']/text()").extract()
    like_counts = hxs.xpath("//em[@class='socialMetaCount likeCountSmall']/text()").extract()
    board_names = hxs.xpath("//div[@class='creditTitle']/text()").extract()

    items = []
    for pin_link, repin_count, like_count, board_name in zip(pin_links, repin_counts, like_counts, board_names):
        item = PinterestItem()
        item["pin_link"] = pin_link.strip()
        item["repin_count"] = repin_count.strip()
        item["like_count"] = like_count.strip()
        item["board_name"] = board_name.strip()
        items.append(item)
    return items

rawDescription: Only getting one line of output with scrapy to json file


code:
for _ in range(10):
    print('Hello')

rawDescription: Disregarding python variables

description: Disregarding python variables


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

rawDescription: Django's Double Underscore

description: Django's Double Underscore


code: list(itertools.permutations([1+2j, 1-2j, 2+j, 2-j]))

rawDescription: Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)


rawDescription: How do I restart the IDLE Python Shell in Linux?

description: Restart the IDLE Python Shell in Linux


rawDescription: Genetic Algorithm roulette selection - returning 2 parent chromosomes


code:
string = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY POTATO'
words = string.split()
unique_words = []

#Remove the duplicates while preserving order
for word in words:
    if word not in unique_words:
        unique_words.append(word)

#Generate the indexes for the words
indexes = [unique_words.index(word)+1 for word in words]
print(indexes)
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5, 10]

rawDescription: Why does my code print off 18 instead of 10, and could you provide any solutions?


code: df = df.reset_index(drop=True)

rawDescription: How to delete or drop the column labelled "index" from a dataframe when using to_csv() to save as csv

description: Delete or drop the column labelled "index" from a dataframe when using to_csv() to save as csv


code:
vehicles = {'ford', 'honda', 'toyota', 'steve_urkel_car'} #etc
df[df.isin(vehicles).sum(1) >= 2]

rawDescription: Pandas: Select rows where a number of strings appear more than once


code:
import multiprocessing
import execution
import datetime

#assume we have a function:
#exection.run_main_with_args(filename,name,today_str,dbfolder)

today = datetime.datetime.today()
def my_execute(filename):
    if '.htm' in filename:
       name = filename.strip('.htm')
       dbfolder = "C:/newscript/db/" + name
       os.makedirs(dbfolder)
       execution.run_main_with_args(filename,name,str(today),dbfolder)

p = multiprocessing.Pool()
p.map(my_execute,list_of_files_to_process)

rawDescription: running script multiple times simultaniously in python 2.7

description: Running script multiple times simultaniously in python 2.7


code:
d = {'key1': 'string1', 'key2': 15, 'key3': ['item1', 'item2', 'item3', 'item4']}
parameters = [(k, v1) for k, v in d.iteritems() for v1 in (v if isinstance(v, list) else [v])]
parameters

rawDescription: How do I concisely convert a python dictionary to a list of tuples, given a dictionary in which the values may be different types?

description: Concisely convert a python dictionary to a list of tuples, given a dictionary in which the values may be different types


code:
# settings.py
AUTHENTICATION_BACKENDS=(
    'myapp.backends.LegacyBackend',
    'django.contrib.auth.backends.ModelBackend',
)

# myapp.backends
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.utils.encoding import force_bytes
import hashlib

class LegacyBackend(ModelBackend):

    # We only need to override the authenticate method
    def authenticate(self, username=None, password=None, **kwargs):
        # most of this is copied directly from ModelBackend's authenticate method
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)

            # This is the normal route that hands off to the password hasher pipeline
            # but we will sidestep it entirely and verify the password here
            #
            # if user.check_password(password):
            #    return user

            pwhash = hashlib.md5(force_bytes(password)).hexdigest()
            hash = hashlib.md5(force_bytes(pwhash+"salt"+username)).hexdigest()
            if hash == user.password:
                # update the user's password if you want, so you can phase out this backend
                user.set_password(password)
                user.save(update_fields=["password"])
                return user

        except UserModel.DoesNotExist:
            UserModel().set_password(password)

rawDescription: Django password hasher with username in hash


code:
import urllib, urllib2, cookielib
url='http://localhost:8080/rest/auth/latest/session'
post={"username" : "admin", "password" : "hunter2"}
post_data=urllib.urlencode(post)
cookie = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
opener.open(url,post_data)
cookie.save('cookie_filename', True)

rawDescription: How do you POST and receive a cookie in Python?

description: POST and receive a cookie in Python


code: return pd.Series({"x": valuex, "y": valuey, "z": valuez})

rawDescription: Run a function on every row of a pandas dataframe with dictionary return


code:
table = {}
with open('File2.txt') as f_in:          # Generates the dictionary
    for line in f_in:
        line = line.strip()
        table[line.split('\t')[0]] = line.split('\t')[1]

with open('File1.txt') as f_1, open('File3.txt', 'w') as f_2:   # Matches against the dictionary
    for line in f_1:
        key = line.strip()
        if key in table:
            f_2.write('%s\t%s\n'%(key,table[key]))
        else:
            f_2.write("%s\t'not found'\n"%key)

rawDescription: PYTHON dictionary and look up table

description: PYTHON dictionary and look up table


code:
from PyQt4 import QtGui, QtCore

class messageBox(QtGui.QWidget):
    def __init__(self, text):
        super(messageBox, self).__init__()
        self.message = text
        self.initUI()

    def initUI(self):
        self.resize(250, 100)
        self.move(300, 300)
        self.label = QtGui.QLabel(self)
        self.label.setText(self.message)

class MainWidget(QtGui.QWidget):
    def __init__(self, text):
        super(MainWidget, self).__init__()
        button = QtGui.QPushButton('Push')
        button.pressed.connect(self.on_button_pressed)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(button)
        self.setLayout(layout)

    def on_button_pressed(self):
        self.box = messageBox('foo')
        self.box.show()

app = QtGui.QApplication([])
mw = MainWidget('test')
mw.show()
app.exec_()

rawDescription: Widget opens for a second then automatically closes?


code:
import os
from http.server import SimpleHTTPRequestHandler, HTTPServer

os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27')
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
httpd.serve_forever()

rawDescription: Simple http server in Python 3.5.1 Shell


code:
from abaqus import *
from abaqusConstants import *

s1 = mdb.models['Model-1'].ConstrainedSketch(name='__profile__',sheetSize=200.0)
g, v, d, c = s1.geometry, s1.vertices, s1.dimensions, s1.constraints
s1.Line(point1=(-21.25, 22.5), point2=(-33.75, -20.0))
s1.Line(point1=(-33.75, -20.0), point2=(-3.75, -32.5))
s1.Line(point1=(-3.75, -32.5), point2=(40.0, -25.0))
s1.Line(point1=(40.0, -25.0), point2=(25.0, 25.0))
s1.Line(point1=(25.0, 25.0), point2=(-21.25, 22.5))

#this creates the actual part - which is a planar surface that exists in 3D space
p = mdb.models['Model-1'].Part(name='Part-2', dimensionality=THREE_D,type=DEFORMABLE_BODY)

p = mdb.models['Model-1'].parts['Part-2']

p.BaseShell(sketch=s1)
del mdb.models['Model-1'].sketches['__profile__']

#the following finds and creates a "surface" on the part.
f = p.faces
face=f.findAt(coordinates=(0.0,0.0,0.0))
face_ind=face.index
side1Faces=f[face_ind:face_ind+1]

p.Surface(side1Faces=side1Faces, name='Surf-1')

rawDescription: Creating a surface with a sketch using Abaqus Python


code:
from django.contrib.auth.models import User
u = User.objects.all()[0]
u._meta.fields[1].__class__.__name__
u._meta.fields[1].name
u._meta.fields[1].max_length
u._meta.fields[1].blank

rawDescription: How to get properties of a model attribute?

description: Get properties of a model attribute


code: hats(c = 'something')

rawDescription: Optional Default Values

description: Optional Default Values


code:
def OSinfo(runthis):
    osstdout = subprocess.Popen(runthis, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)

    theInfo = osstdout.communicate()[0].strip()

    return (theInfo, osstout.returncode)

rawDescription: Python check exit status of a shell command


code:
import time
nonce = "some string"
while True:
  latest_nonce = client.block_latest()['nonce']
  if latest_nonce != nonce:
     nonce = latest_nonce
  time.sleep(2)

rawDescription: Saving a string in python associated with an API


code:
def paste(sources, dest, delimiter=' '):
    fsrc = [open(fname, 'r') for fname in sources]
    fdest = open(dest, 'w')
    for t in zip(*fsrc):
        outline = delimiter.join([line.strip() for line in t]) + '\n'
        fdest.write(outline)
    for f in fsrc:
        f.close()
    fdest.close()

paste(('file1', 'file2', 'file3'), 'final_file')

rawDescription: write text file from text files python

description: Write text file from text files python


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

x = np.random.randn(10000)

fig = plt.figure()
ax = fig.add_subplot(111)

# 100 is the number of bins
n = ax.hist(x, 100, facecolor='green', alpha=0.75)

# n[0] is the array of bin heights,
# n[1] is the array of bin edges
xmin = min(n[1]) * 1.1
xmax = max(n[1]) * 1.1
ymax = max(n[0]) * 1.1

ax.set_xlim(xmin, xmax)
ax.set_ylim(0, ymax)
ax.grid(True)

plt.show()

rawDescription: Turn Weighted Numbers into Multiple Histograms


code:
import re
day_re = re.compile(r'((?:Mon|Tues|Wednes|Thurs|Fri|Sat|Sun)day \d{2}/\d{2}/\d{4}) (.*)')
shift_re = re.compile(r'([A-Z]{5,} [^A-Z]*(?:[A-Z]{1,4}[^A-Z]+)*)')

def appointments(lines):
    """
    Given iterator `lines` containing one or more appointments per day,
    generate individual appointments.
    """
    for line in lines:
        day, remainder = day_re.match(line).groups()
        shifts = shift_re.findall(remainder)
        if shifts:
            for shift in shifts:
                yield '{} {}'.format(day, shift.strip())
        else:
            yield '{} {}'.format(day, remainder.strip())

rawDescription: Split one line to multiple lines based on pattern


code:
#Create a function to split the values
def splitter(ratio):
    try: #Try to split the values
        return ratio.split(" : ")[0], ratio.split(" : ")[1]
    except AttributeError: #return None for NaN's
        return None, None
#apply the function to the column
df.loc[:, 'MaleNumerator'], df.loc[:, 'FemaleDenominator'] = zip(*df.male_female_Ratio.apply(splitter))

rawDescription: How to deal with the values "ratio" when analysing data without using Series in Pandas

description: Deal with the values "ratio" when analysing data without using Series in Pandas


code:
from string import punctuation
word = "-scary!"
word.strip(punctuation)

rawDescription: Is this a correct/efficient way to trim punctuation in python?


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

a = add          # bind
b = a(34, 1)     # call

rawDescription: Blocks of code in python

description: Blocks of code in python


code:
root = Tk()

def move_window(event):
    root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))

root.overrideredirect(True) # turns off title bar, geometry
root.geometry('400x100+200+200') # set new geometry

# make a frame for the title bar
title_bar = Frame(root, bg='white', relief='raised', bd=2)

# put a close button on the title bar
close_button = Button(title_bar, text='X', command=root.destroy)

# a canvas for the main area of the window
window = Canvas(root, bg='black')

# pack the widgets
title_bar.pack(expand=1, fill=X)
close_button.pack(side=RIGHT)
window.pack(expand=1, fill=BOTH)

# bind title bar motion to the move window function
title_bar.bind('<B1-Motion>', move_window)

root.mainloop()

rawDescription: Can I change the title bar in Tkinter?

description: Change the title bar in Tkinter


code: sorted(TheGame.turn, key=lambda user: user.distance_to_goal(TheGame.hole.goal_position))

rawDescription: Sorting a list using calculation from class definition


code:
def do_whois(data):
    if data: return Popen(['whois', str(data)], stdout=PIPE,stderr=STDOUT).communicate()[0]
    return 'No entries'

def check_whois(data):
    if 'No entries' in data or 'Not found' in data:return False
    test = re.search("country.+([A-Z].)",whois_result)
    return test.group(1)

def find_whois(domain, ip):
    return check_whois(do_whois(domain)) or check_whois(do_whois(ip))

rawDescription: Simple beginner stuff, multiple conditional test


code:
def get_object(self, queryset=None):
    """
    Returns the object the view is displaying.
    By default this requires `self.queryset` and a `pk` or `slug` argument
    in the URLconf, but subclasses can override this to return any object.
    """
    # Use a custom queryset if provided; this is required for subclasses
    # like DateDetailView
    if queryset is None:
        queryset = self.get_queryset()
    # Next, try looking up by primary key.
    pk = self.kwargs.get(self.pk_url_kwarg)
    slug = self.kwargs.get(self.slug_url_kwarg)
    if pk is not None:
        queryset = queryset.filter(pk=pk)

    # Next, try looking up by slug.
    if slug is not None and (pk is None or self.query_pk_and_slug):
        slug_field = self.get_slug_field()
        queryset = queryset.filter(**{slug_field: slug})
    # If none of those are defined, it's an error.
    if pk is None and slug is None:
        raise AttributeError("Generic detail view %s must be called with "
                         "either an object pk or a slug."
                         % self.__class__.__name__)
    try:
        # Get the single item from the filtered queryset
        obj = queryset.get()
    except queryset.model.DoesNotExist:
        raise Http404(_("No %(verbose_name)s found matching the query") %
                  {'verbose_name': queryset.model._meta.verbose_name})

    return obj

rawDescription: How does Django know what 'pk' to use in urls.py?


code: res = [word for word in simpleTokenize(string) if word not in stopwords]

rawDescription: What's the most efficient way to filter values out of a list based on the values in another list


rawDescription: Selecting html element tag(?) name selenium python


code:
import Tkinter as tk

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

        self.menubar = tk.Menu()
        self.test1Menu = tk.Menu()
        self.test2Menu = tk.Menu()
        self.menubar.add_cascade(label="Test1", menu=self.test1Menu)
        self.menubar.add_cascade(label="Test2", menu=self.test2Menu)

        self.test1Menu.add_command(label="Enable Test2", command=self.enable_menu)
        self.test1Menu.add_command(label="Disable Test2", command=self.disable_menu)
        self.test2Menu.add_command(label="One")
        self.test2Menu.add_command(label="Two")
        self.test2Menu.add_command(label="Three")
        self.test2Menu.add_separator()
        self.test2Menu.add_command(label="Four")
        self.test2Menu.add_command(label="Five")

        root.configure(menu=self.menubar)

    def enable_menu(self):
        self.menubar.entryconfig("Test2", state="normal")

    def disable_menu(self):
        self.menubar.entryconfig("Test2", state="disabled")

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

rawDescription: tkinter enable/disable menu

description: Tkinter enable/disable menu


code:
int(''.join(str(el)
            for el in [Digits1, Digits2, Digits3, Digits4, Digits5, Digits6, Digits7]))

rawDescription: How to combine different integers to one

description: Combine different integers to one


rawDescription: Regex in python not matching what grep does


code:
with open('originalfile.csv','r') as f:
  with open('newfile.csv','w') as new_file:
    for row in f:
      if not is_junk(row):
        new_file.write(row)

def is_junk(row):
  return not row.strip() or ( not ( ("Retail" in row ) or is_float(row.split()[-1]) ) )

def is_float(str):
  try:
    float(str)
    return True
  except ValueError:
    return False

rawDescription: Python - CSV to extract data from text file into a CSV file


code:
with open('output.json', 'r') as f:
    timestamps = json.load(f)
for i in timestamps:
    starttime = int(datetime.datetime.fromtimestamp(i["start_time"]).strftime('%S'))
    endtime = int(datetime.datetime.fromtimestamp(i["end_time"]).strftime('%S'))
    clip = video.subclip(starttime, endtime)
    clips_array.append(clip)
final_clip = concatenate_videoclips(clips_array)
final_clip.write_videofile("Out_File.mp4")

rawDescription: Creating multiple subclips from a video with unixtime from a json?


code:
import os
import urllib
import webapp2

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class MainHandler(webapp2.RequestHandler):
  def get(self):
    upload_url = blobstore.create_upload_url('/upload')
    self.response.out.write('')
    self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
    self.response.out.write("""Upload File: <input type="file" name="file">
 <input type="submit"
        name="submit" value="Submit"> </form>""")

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
    blob_info = upload_files[0]
    self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/upload', UploadHandler),
                               ('/serve/([^/]+)?', ServeHandler)],
                              debug=True)

rawDescription: AJAX Based Dynamic Image Serving - Google App Engine Python 2.7


code:
item['title'] = sel.xpath('text()').extract()[0]
item['link'] = sel.xpath('@href').extract()[0]

rawDescription: How can I strip a string with different ends in Python for scrapy bot?

description: Strip a string with different ends in Python for scrapy bot


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import dates
import datetime

plt.close('all')

#---- generate some data ----

t = [datetime.datetime(2015, 1, 1, 0) +
     datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
x = np.random.rand(len(t))

#---- create figure and axe ----

fig = plt.figure()

ax = fig.add_axes([0.1, 0.2, 0.85, 0.75])

#---- format xaxis ----

# position of the labels
xtk_loc = [datetime.datetime(2015, 1, 1, 0) +
           datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
ax.set_xticks(xtk_loc)
ax.tick_params(axis='both', direction='out', top='off', right='off')

# format of the labels
hfmt = dates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate(rotation=90, ha='center')

#---- set axes labels ----

ax.set_ylabel('Number of tasks', labelpad=10, fontsize=14)
ax.set_xlabel('Time', labelpad=20, fontsize=14)

#---- plot data ----

ax.plot(t, x, color="#004c99", label="Number of Tasks")
ax.fill_between(t, x, 0, facecolor='#00a1e4', alpha=0.5, lw=0.5)

#---- set axis limits ----

timemin = datetime.datetime(2015, 1, 1, 0)
timemax = datetime.datetime(2015, 1, 1, 12)

ax.axis(xmin=timemin, xmax=timemax)

plt.show()

rawDescription: Good date format on x-axis matplotlib

description: Good date format on x-axis matplotlib


code:
pussaIndex = 0
for cat in cats:
    if cat.getcatNum() % 2 == 0:
        # add the next four elements from `listPussa`
        for i in range(4):
            cat.addPussa(listPussa[pussaIndex])
            pussaIndex += 1

rawDescription: Classes and methods, with lists in Python


code:
form.populate_obj(user)
user.put()

rawDescription: Populate an App Engine NDB entity with data from WTForms


code:
from wsgiref import simple_server
from pyamf.remoting.gateway.wsgi import WSGIGateway

## amf services ##################################################

def echo(data):
    return data

def reverse(data):
    return data[::-1]

def rot13(data):
    return data.encode('rot13')

services = {
    'myservice.echo': echo,
    'myservice.reverse': reverse,
    'myservice.rot13': rot13,
}

## server ########################################################

def main():
    app = WSGIGateway(services)

    simple_server.make_server('localhost', 8080, app).serve_forever()

if __name__ == '__main__':
    main()

rawDescription: How does AMF communication work?

description: How does AMF communication work


code:
all_data = " ".join([line for line in file]).split("ID")
return [", ".join([item.split(" ")[::2] for item in all_data])]

rawDescription: parsing repeated lines of string based on initial characters

description: Parsing repeated lines of string based on initial characters


code:
import csv
from .models import MyModel

... # get the data out of the csv file using the python csv library

for data in csvdata:
   MyModel.objects.get_or_create(data[0])

rawDescription: Django - Where to put CSV reading code

description: Django - Where to put CSV reading code


code:
import hashlib
with open('really-large-file', 'rb') as f:
    f.seek(- 4096 * 1024, 2)
    print (hashlib.md5(f.read()).hexdigest())

rawDescription: In python, create md5 hash from the last 4KB of a file


code:
# store the cumsum, since it's used multiple times
cum_a = a.cumsum(axis=0)

# find the indices as before
indices = np.argmax(abs(cum_a), axis=0)

# construct the indices for the second and third dimensions
y, z = np.indices(indices.shape)

# get the values with np indexing
max_mag_signed = cum_a[indices, y, z]

rawDescription: Numpy signed maximum magnitude of cumsum along an axis


code:
class SpriteDict(object):
    def __init__(self, name):
        self.spriteSize = (35, 35)
        # change this old line:
        #self.spritesheet = loadImage("patchconsprites.png", (0,120,136,0))[0]
        # to this:
        self.spritesheet = pygame.image.load("./images/patchconsprites.png")
        self.sprites = []
        start = charCoords[name]
        char = list(start)
        image = pygame.Surface((35,35))
        for y in range(5):
            char[0] = start[0]
            for x in range(9):
                rect = (char[0], char[1], char[0]+self.spriteSize[0], char[1]+self.spriteSize[1])
                image.blit(self.spritesheet, (0,0), rect)
                # and put the transparency code here:
                image = image.convert()
                colorkey = image.get_at((0,0))
                image.set_colorkey(colorkey, RLEACCEL)
                # end new code
                self.sprites.append(image)
                char[0] += self.spriteSize[0]+2
            char[1] += self.spriteSize[1]+2

rawDescription: When blitting a sprite with colorkey transparency in Pygame, the areas that should be transparent are black


code:
import os
open(os.path.join(os.path.dirname(__file__), 'Directory', 'input.txt'))

rawDescription: How to get text file from a relative path?

description: Get text file from a relative path


code:
import random
[random.uniform(0, 7) for i in range(4)]

rawDescription: Simple Python Random Module

description: Simple Python Random Module


rawDescription: Is it possible for BeautifulSoup to work in a case-insensitive manner?


code:
class X(object):
    @classmethod
    def foo(cls, fun):
        def wrapper(self, *args, **kwargs):
            self.write(*args, **kwargs)
            return fun(self, *args, **kwargs)
        return wrapper

    def write(self, *args, **kwargs):
        print(args, kwargs)

class Y(X):
    @X.foo
    def bar(self, x):
        print("x:", x)

Y().bar(3)
# prints:
#   (3,) {}
#   x: 3

rawDescription: Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes


code:
a_set = set(['A', 'BF', 'B', 'BA', 'ABF', 'AF', 'F', 'BFA', 'AFB', 'BAF', 'FA', 'FB', 'AB', 'FAB', 'FBA'])
min_len = min( len(x) for x in a_set  )
[ x for x in a_set if len(x) == min_len ]

rawDescription: retrieve all the smallest strings from a set in python

description: Retrieve all the smallest strings from a set in python


code:
from os import environ
environ['CFLAGS'] = '-I/path/to/my/custom/lib'
environ['LDFLAGS'] = '-Lpath/to/my/custom/lib -lcustomlib'
import pyximport
pyximport.install()

rawDescription: Python: pyximporting a pyx that depends on a native library


code:
def check_word_type(self, filename):
    words = ['noun','verb','vrb','adj','adv'] #I am not sure if adj and adv are variables
    for i in words:
        if i in filename:
            self.word_type = str(i) #just make sure its string
        else:
            self.word_type = ''
    return self.word_type

rawDescription: Check if the filename contains a string Python


code:
from sqlalchemy.sql import select, func
...
Column('version', Integer, default=select([func.max(1,
    func.max(version_table.c.old_versions))]))

rawDescription: Setting a default value in sqlalchemy

description: Setting a default value in sqlalchemy


code:
size = 'GG|0,WQ|3,EW|8,RE|23'
elements = size.split(',')
a = [dict([x.split('|')]) for x in elements]

rawDescription: Can this code be rewritten to be more pythonic?


code:
@app.route('/hello', defautls={'name': 'world'}, methods=['POST'])
@app.route('/hello/<name>', methods=['POST'])
def hello(name):
    print(name)  # will be 'world' when going to bare /foo
    data = request.get_json()
    k = data.get('k', 20)
    return jsonify(k=k, status='ok')

requests.post('http://localhost/hello', json={'k': 2})

rawDescription: Posting JSON to Flask view using Requests returns 404


code:
import re
m = re.compile('^[abilrstu]+$')
m.match('australia') is not None
m.match('dummy') is not None
m.match('australian') is not None

rawDescription: Python code that will find words made out of specific letters. Any subset of the letters could be used


code:
import signal

# Intercept ctrl-c, ctrl-\ and ctrl-z
def signal_handler(signal, frame):
    pass
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGTSTP, signal_handler)

rawDescription: Why does pressing Ctrl-backslash result in core dump?


code:
import djng

def index(request):
    return djng.Response('Hello, world')

if __name__ == '__main__':
    djng.serve(index, '0.0.0.0', 8888)

rawDescription: How do I write a single-file Django application?

description: Write a single-file Django application


code:
from collections import namedtuple
Point = namedtuple("Point", "x y")
p1 = Point(x=11, y=22)

rawDescription: What is the Python counterpart to an Ada record / C++ struct type?


code:
client.update_port('1fe691a6-f3a0-4586-b126-9fabb11e962a',
                   {'port':
                     {'binding:vif_type': 'avp'}})

rawDescription: Openstack Neutron: How to update port vif-model using update_port() api


code:
new_audio_data = modified_array_of_samples.tostring()
new_audio_segment = original_audio_segment._spawn(data=new_audio_data)

rawDescription: Converting samples from .get_array_of_samples() back to an AudioSegment


code:
from operator import itemgetter
from string import ascii_uppercase

data = [19, 14, 36]

labelled = zip(data, ascii_uppercase) # [(19, 'A'), (14, 'B'), (36, 'C')]

sorted_data = sorted(labelled,
                     key=itemgetter(0)) # [(14, 'B'), (19, 'A'), (36, 'C')]

labels = [pair[1] for pair in sorted_data] # ['B', 'A', 'C']

rawDescription: assign names to elements of unknown size list in python

description: Assign names to elements of unknown size list in python


code:
for i in range(X):
    gobject.idle_add(workerFunction)

rawDescription: How to implement a Mutex in Python when using Gtk with PyGTK

description: Implement a Mutex in Python when using Gtk with PyGTK


code: counter = len(f.readlines())

rawDescription: How do i print/return the number of lines in a file

description: Print/return the number of lines in a file


code:
list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
sum(x.count('foobar') for x in list)

rawDescription: python .count for multidimensional arrays (list of lists)

description: Python .count for multidimensional arrays (list of lists)


code:
from sys import stdout
from logging import StreamHandler, getLogger
from twisted.python.log import startLogging, logfile
observer = startLogging(stdout, setStdout=False)
getLogger().addHandler(StreamHandler(stream=logfile))
getLogger().log(100, "Hello")

rawDescription: logging to file with twistd and python logging

description: Logging to file with twistd and python logging


code:
import a
class A: # replacement A
    ...

a.A = A

rawDescription: Python 2.7 override the entire class definition in a different module


code:
a=(("a",2),("b",2),("a",1))
from operator import itemgetter
sorted(a, key=itemgetter(1, 0))

rawDescription: how to sort tuple in python?

description: Sort tuple in python


code:
button_tnt = Button(fenster,
                    text="TNT Serie HD",
                    command= lambda: startstream('http://dreambox:8001/1:0:19:7B:B:85:C00000:0:0:0:'))

rawDescription: Python - subprocess error

description: Python - subprocess error


rawDescription: NLTK stem words produces odd results

description: NLTK stem words produces odd results


code:
for i in range(5):
    command_string = "Thread-" + "%d" % i
    thread = Thread(i, command_string)
    thread.start()

rawDescription: c style thread creation in python

description: C style thread creation in python


code:
# input('Press <Enter> to end the program')  # (X)
window.mainloop()  # OR mainloop()

rawDescription: Tkinter window closes automatically after Python program has run in PyCharm


code:
template = '(case when %s is not null then 1 else 0 end)'
query = '(%s) > 2' % reduce(lambda a, b: '%s + %s' % (a, b),
                            [template % f for f in db.mytable])
rows = db(query).select(db.mytable.ALL)

rawDescription: Sql more than 2 is note null

description: Sql more than 2 is note null


code:
import collections, operator, functools
def func(lst, request_keys, op=operator.add):
    matching_dicts = collections.defaultdict(list)
    for d in lst:
        key = tuple(sorted(((k, d[k]) for k in d if k not in request_keys)))
        matching_dicts[key].append(d)

    for group in matching_dicts.values():
        merged = dict(group[0])
        merged.update({key: functools.reduce(op, (g[key] for g in group))
                       for key in request_keys})
        yield merged

rawDescription: Pythonic way of finding duplicate maps in a list while ignoring certain keys, and combining the duplicate maps to make a new list


code:
from Tkinter import *

def main():
    window = Tk()
    window.title("TexComp")
    window.geometry("500x500")
    window.resizable(height=FALSE,width=FALSE)

    windowBackground = '#E3DCA8'

    window.configure(bg=windowBackground)

    instruction = Label(text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.", bg=windowBackground)
    instruction.place(x=115, y=10)

    text1 = Text(width=25)
    text1.pack(side=LEFT)
    text2 = Text(width=25)
    text2.pack(side=RIGHT)

    scroll1y=Scrollbar(window, command=text1.yview)
    scroll1y.pack(side=LEFT, fill=Y, pady=65)
    scroll2y=Scrollbar(window, command=text2.yview)
    scroll2y.pack(side=RIGHT, fill=Y, pady=65)

    mainloop()

if __name__ == '__main__':
    main()

rawDescription: NoneType object has no attribute yview

description: NoneType object has no attribute yview


code:
# get data from old image (as you already did)
data = list(oldimg.getdata())

# create empty new image of appropriate format
newimg = Image.new(format, size)  # e.g. ('RGB', (640, 480))

# insert saved data into the image
newimg.putdata(data)

rawDescription: How to build an image object in PIL/Python

description: Build an image object in PIL/Python


code:
# Good uses.
p = re.compile(r"(?:[^\\])\\g<(\w+)>")

for m in p.finditer(r"</\g\<at__tribut1>\\g<notattribut>>"):
    print(m.group(1))

# Bad uses.
p = re.compile(r"(?:[^\\])\\g(?!<\w+>)")

if p.search(r"</\g\<at__tribut1>\\g<notattribut>>"):
    print("Wrong use !")

rawDescription: Regex pattern for illegal regex groups `\g<...>`


code:
mystring = input("Enter the sentence you wish to be an acronym: ")

mystring_length = len(mystring)

print(mystring[0] ,end="")

for i in range (1,mystring_length):
    if mystring[i].isupper():
        print(". " ,end="")
        print(mystring[i],end="")

rawDescription: How do I stop the dot from printing after the last letter?

description: Stop the dot from printing after the last letter


code: test_set_final = [[r, c[-1]] for [r], c in zip (test_set_final, test_set)]

rawDescription: Python "data naming"

description: Python "data naming"


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

def highResPoints(x,y,factor=10):
    '''
    Take points listed in two vectors and return them at a higher
    resultion. Create at least factor*len(x) new points that include the
    original points and those spaced in between.

    Returns new x and y arrays as a tuple (x,y).
    '''

    # r is the distance spanned between pairs of points
    r = [0]
    for i in range(1,len(x)):
        dx = x[i]-x[i-1]
        dy = y[i]-y[i-1]
        r.append(np.sqrt(dx*dx+dy*dy))
    r = np.array(r)

    # rtot is a cumulative sum of r, it's used to save time
    rtot = []
    for i in range(len(r)):
        rtot.append(r[0:i].sum())
    rtot.append(r.sum())

    dr = rtot[-1]/(NPOINTS*RESFACT-1)
    xmod=[x[0]]
    ymod=[y[0]]
    rPos = 0 # current point on walk along data
    rcount = 1
    while rPos < r.sum():
        x1,x2 = x[rcount-1],x[rcount]
        y1,y2 = y[rcount-1],y[rcount]
        dpos = rPos-rtot[rcount]
        theta = np.arctan2((x2-x1),(y2-y1))
        rx = np.sin(theta)*dpos+x1
        ry = np.cos(theta)*dpos+y1
        xmod.append(rx)
        ymod.append(ry)
        rPos+=dr
        while rPos > rtot[rcount+1]:
            rPos = rtot[rcount+1]
            rcount+=1
            if rcount>rtot[-1]:
                break

    return xmod,ymod

#CONSTANTS
NPOINTS = 10
COLOR='blue'
RESFACT=10
MAP='winter' # choose carefully, or color transitions will not appear smoooth

# create random data
np.random.seed(101)
x = np.random.rand(NPOINTS)
y = np.random.rand(NPOINTS)

fig = plt.figure()
ax1 = fig.add_subplot(221) # regular resolution color map
ax2 = fig.add_subplot(222) # regular resolution alpha
ax3 = fig.add_subplot(223) # high resolution color map
ax4 = fig.add_subplot(224) # high resolution alpha

# Choose a color map, loop through the colors, and assign them to the color
# cycle. You need NPOINTS-1 colors, because you'll plot that many lines
# between pairs. In other words, your line is not cyclic, so there's
# no line from end to beginning
cm = plt.get_cmap(MAP)
ax1.set_color_cycle([cm(1.*i/(NPOINTS-1)) for i in range(NPOINTS-1)])
for i in range(NPOINTS-1):
    ax1.plot(x[i:i+2],y[i:i+2])

ax1.text(.05,1.05,'Reg. Res - Color Map')
ax1.set_ylim(0,1.2)

# same approach, but fixed color and
# alpha is scale from 0 to 1 in NPOINTS steps
for i in range(NPOINTS-1):
    ax2.plot(x[i:i+2],y[i:i+2],alpha=float(i)/(NPOINTS-1),color=COLOR)

ax2.text(.05,1.05,'Reg. Res - alpha')
ax2.set_ylim(0,1.2)

# get higher resolution data
xHiRes,yHiRes = highResPoints(x,y,RESFACT)
npointsHiRes = len(xHiRes)

cm = plt.get_cmap(MAP)

ax3.set_color_cycle([cm(1.*i/(npointsHiRes-1))
                     for i in range(npointsHiRes-1)])

for i in range(npointsHiRes-1):
    ax3.plot(xHiRes[i:i+2],yHiRes[i:i+2])

ax3.text(.05,1.05,'Hi Res - Color Map')
ax3.set_ylim(0,1.2)

for i in range(npointsHiRes-1):
    ax4.plot(xHiRes[i:i+2],yHiRes[i:i+2],
             alpha=float(i)/(npointsHiRes-1),
             color=COLOR)
ax4.text(.05,1.05,'High Res - alpha')
ax4.set_ylim(0,1.2)

fig.savefig('gradColorLine.png')
plt.show()

rawDescription: How to plot a gradient color line in matplotlib?

description: Plot a gradient color line in matplotlib


rawDescription: Python 3.1.1 string to hex

description: Python 3.1.1 string to hex


rawDescription: Merging two arrays by column

description: Merging two arrays by column


code:
import matplotlib.pyplot as plt
fig, ax_list = plt.subplots(2, 2)
ax_list = ax_list.ravel()
ax_list[0].set_gid('A')
ax_list[1].set_gid('B')
ax_list[2].set_gid('C')

def clicker(event):
    print(event.inaxes.get_gid())

fig.canvas.mpl_connect('button_press_event', clicker)
plt.show()

rawDescription: Determine whether a point lies in a Matplotlib subplot


rawDescription: Find all indices of numpy vector whose value is in a given set


code:
result = [TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level]
result = map(lambda x:x==None and 'Null' or str(x), result)
ME.csvoutput.write(",".join(result)+'\n')

rawDescription: replace None with Null, in place

description: Replace None with Null, in place


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

my_map = Basemap(projection='poly', lat_0=0, lon_0=-160,
    resolution = 'h', area_thresh = 0.1,
    llcrnrlon=140, llcrnrlat=-60,
    urcrnrlon=-100, urcrnrlat=60)

plt.figure(figsize=(16,12))

my_map.drawcoastlines()
my_map.drawcountries()
my_map.fillcontinents(color='coral', lake_color='aqua')
my_map.drawmapboundary(fill_color='aqua')

my_map.drawmeridians(np.arange(0, 360, 20))
my_map.drawparallels(np.arange(-90, 90, 10))

plt.show()

rawDescription: Matplotlib Mollweide/Hammer projection: region of interest only


code:
import os, sys
from tkinter import Tk, filedialog
from tkinter.messagebox import showinfo

class Dialog:

    def __init__(self, path):
        self.path = path
        self.dst_path = ''
        self.root = root = Tk()

        root.iconify()
        root.after_idle(self.askdirectory)
        root.mainloop()

    def askdirectory(self):
        self.dst_path = filedialog.askdirectory(initialdir=self.path)
        showinfo('Selected Path', self.dst_path)
        self.root.destroy()

if __name__ == '__main__':
    if len(sys.argv) > 1:
        path = sys.argv[1]
        if os.path.isfile(path):
            path = os.path.dirname(path)

        dialog = Dialog(path)

        #if dialog.dst_path: do_something(dialog.dst_path)

rawDescription: Use selected explorer file or folder path as a variable in a python script for a contextual menu


code:
import string

class X(object):
  def __getattr__(self, name):
    if name in string.lowercase and len(name) == 1:
      def call_into_module(arg):
        return module.do(arg, name)
      return call_into_module

    return super(X, self).__getattr__(name)

rawDescription: How to dynamically clone class methods but be able to tell them apart in Python

description: Dynamically clone class methods but be able to tell them apart in Python


code:
def plotElapsedDis(axis, jvm1, jvm2, ylabel, title, name):
    import matplotlib.pyplot as plt
    import numpy as np
    #fig, ax = plt.subplots(111)
    fig = plt.figure()
    ax = fig.add_subplot(111)
        ## the data
    N = len(jvm1)
    #menMeans = [18, 35, 30, 35, 27]
        #womenMeans = [25, 32, 34, 20, 25]
    ind = np.arange(N)+1
    width = 0.25                      # the width of the bars

    # add "hatch"
    rects1 = ax.bar(ind-width, jvm1, width, color='white', edgecolor='black', hatch="*")

    rects2 = ax.bar(ind, jvm2, width, color='white', edgecolor='black', hatch='//')

    ax.set_ylabel(ylabel)
    ax.set_title(title)
    plt.xticks(ind , axis, rotation=90)
    ax.legend( (rects1[0], rects2[0]), ('Originl', 'Optimal') )
    fig.tight_layout() # make sure it fits
    plt.show()

plotElapsedDis(keys, y_jvm1, y_jvm2, 'seconds', 'CPU Elapsed', '../tmp/cpu_elapsed.jpg')

rawDescription: Pretty plot bar chart in python with matplotlib


code:
from subprocess import check_output

out = check_output(["openssl", "rsautl", "-encrypt", "-inkey", "key"])

rawDescription: Call a shell command in python

description: Call a shell command in python


code:
import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
WINDOWIDTH = 600
height = 600
screen = pygame.display.set_mode((WINDOWIDTH, height), 0, 32)
pygame.display.set_caption('Noitceted Nosilloc')

# set up direction variables
DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9

MOVESPEED = 10

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)

# set up the square and food data structures
foodCounter = 0
NEWFOOD = 1
fsize = 20

class MyRect(object):
    def __init__(self, x, y, l, vx, vy, color=(0, 0, 0)):
        self.rect = pygame.Rect(x, y, l, l)
        self.vx = vx
        self.vy = vy
        self.color = color

    def move(self):
        self.rect.x += self.vx
        self.rect.y += self.vy

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)

class Square(MyRect):
    def __init__(self, x, y, l, vx, vy, color=(0, 0, 0)):
        super().__init__(x, y, l, vx, vy, color=color)
        self.iw = 0
        self.ih = 0

    def registerIncrease(self, iw, ih):
        self.iw += iw
        self.ih += ih

        if self.iw > 1:
            self.rect.w += 1
            self.iw -= 1

        if self.ih > 1:
            self.rect.h += 1
            self.ih -= 1

    def update(self, screen, foods):
        # move the square data structure
        self.move()

        # check if the square has move out of the window
        if self.rect.top < 0 or self.rect.bottom > height:
            self.vy *= -1
            self.rect.top = max(self.rect.top, 0)
            self.rect.bottom = min(self.rect.bottom, height)
        if self.rect.left < 0 or self.rect.right > WINDOWIDTH:
            self.vx *= -1
            self.rect.left = max(self.rect.left, 0)
            self.rect.right = min(self.rect.right, WINDOWIDTH)

        # draw the square onto the surface
        self.draw(screen)

        # check if the square has intersected with any food squares.
        for food in foods:
            if self.rect.colliderect(food.rect):
                food.setVel(self)
                self.registerIncrease(0.1, 0.1)

class Food(MyRect):
    def setVel(self, square):
        self.vx = square.vx
        self.vy = square.vy

    def update(self, screen, foods):
        if self.vx != 0 or self.vy != 0:
            # move the square data structure
            self.move()

            # check if the square has move out of the window
            if self.rect.bottom < 0 or self.rect.top > height or self.rect.right < 0 or self.rect.left > WINDOWIDTH:
                foods.remove(self)

        # draw the square onto the surface
        self.draw(screen)

square = Square(300, 100, 25, -MOVESPEED, MOVESPEED, color=WHITE)

foods = []
for i in range(20):
    foods.append(Food(random.randint(0, WINDOWIDTH - fsize), random.randint(0, height - fsize), fsize, 0, 0, color=GREEN))

# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(Food(random.randint(0, WINDOWIDTH - fsize), random.randint(0, height - fsize), fsize, 0, 0, color=GREEN))

    # draw the black background onto the surface
    screen.fill(BLACK)

    square.update(screen, foods)

    # draw the food
    for food in foods:
        food.update(screen, foods)

    # draw the window onto the screen
    pygame.display.update()
    mainClock.tick(80)

rawDescription: Pygame: One square making other squares bounce


rawDescription: How can i reverse the output in my binary adder?

description: Reverse the output in my binary adder


code:
#models.py
class ProfileStatus(models.Model):
    status = models.CharField(max_length=32)

class Profile(models.Model):
    name = models.CharField(max_length=32)
    status = models.ForeignKey(ProfileStatus)

#forms.py
class ProfileForm(forms.Form):
    name = forms.CharField(max_length=32)
    status = forms.ModelChoiceField(queryset=ProfileStatus.objects.all())

rawDescription: how to combine tables?

description: Combine tables


code:
from tkinter import *
import tkinter.messagebox
import os, time

root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')

label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)

entry1 = Entry(root)
entry1.place(x = 180, y = 140)

def remove():
    #To fix extension bug
    et = entry1.get()
    if '.txt' not in et:
        et += '.txt'

    print(os.listdir())
    print(et)
    if et in os.listdir():
        print("os.remove(",et,")")
        tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
    else:
        tkinter.messagebox.showerror('Error!', 'File not found!')

button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)

root.mainloop()

rawDescription: Removing text files in Python tkinter

description: Removing text files in Python tkinter


code:
data = [
    {'value': u'sasi', 'set': u'ITEM1'},
    {'value': u'babu', 'set': u'ITEM1'},
    {'value': u'unni', 'set': u'ITEM2'},
    {'value': u'x', 'set': u'ITEM3'},
    {'value': u'y', 'set': u'ITEM3'},
    {'value': u'z', 'set': u'ITEM3'},
]

data = sorted(data, key=lambda d: d['set'])
import itertools
{key: list(d['value'] for d in grp)
 for key, grp in itertools.groupby(data, key=lambda d: d['set'])}

rawDescription: Create key, value pairs based on the querydata


code: names_list = [obj.name() for obj in obj_list]

rawDescription: convert a list containing objects, to a list containing a specific function or properties of those objects

description: Convert a list containing objects, to a list containing a specific function or properties of those objects


code: python:[row, metric('ga:totalEvents', {'ga:dimension1': row})]

rawDescription: collective.googleanalytics report with filter containing tag

description: Collective.googleanalytics report with filter containing tag


code:
m_cluster = wx.MenuItem(menu, -1, "&Cluster\tAlt-C", "Cluster Options.")
m_cluster.SetTextColour(colour)
menu.AppendItem(m_cluster)

rawDescription: Can one set the text colour for a wxMenuItem in Python?


code:
from datetime import datetime

d1 = datetime.strptime(date1, "%m-%d-%y")
d2 = datetime.strptime(date2, "%m-%d-%y")

assert d1 > d2

rawDescription: Python check earlier of two string dates


code: dict(zip(List1, List2))

rawDescription: Combining two lists in python2.7.2 as index and value


code:
release_type = "NIGHTLY"
Popen(['testrunner.bat',
       '-s"CCT000 - Deploy Software Release"',
       '-R"TestSuite Report"',
       '-E"Default environment"',
       '-Ppath.packages.sq=Y:' + release_type,
       'C:CIHEDeploymentCI-XXX-DeploySwRelease'])

rawDescription: Using Popen in Python to execute bat script with variable


code:
import os;
...
cur_cron = os.popen('crontab -l > current_crontab.txt');
cur_cron.read();
cur_cron.close();
fopen_cron = file('current_crontab.txt', 'a');
fopen_cron.write("\n### Comment here if you like");
fopen_cron.write("\n* * * * * Put your command here");
fopen_cron.close();

rawDescription: Python: How to handle 'crontab' command?

description: Python: How to handle 'crontab' command


code:
cols = mytable.get_property('n-columns')
rows = mytable.get_property('n-rows')

rawDescription: Getting size of Gtk.Table in python

description: Getting size of Gtk.Table in python


code:
import zlib

with open("MyImage.jpg", "rb") as in_file:
    compressed = zlib.compress(in_file.read(), 9)

with open("MyCompressedFile", "wb") as out_file:
    out_file.write(compressed)

rawDescription: Compress Images in Python (No Archive)

description: Compress Images in Python (No Archive)


code: conn.Win32_Process.Create(CommandLine='cmd.exe /c mkdir temp')

rawDescription: Execute system commands using wmi python on remote computer


code:
def create_empty_csvs(*stringcsv_names):
    for i in stringcsv_names:
        with open(i + '.csv', 'w') as f:
            pass

rawDescription: Python/CSV - Method to create a CSV file with argument as file name


code:
a = [1,0,0,0,0,1,0,0,0,1] # initial array
b = { index : value for index, value in enumerate(a) if value != 0 }

rawDescription: python interpolation with undesired zeros

description: Python interpolation with undesired zeros


code:
import requests
url = 'http://www.yelp.com/user_details_reviews_self?userid=0S6EI51ej5J7dgYz3-O0lA'
html = requests.get(url).text
import re
rating_pattern = re.compile(r'\d.\d star rating">')
for rating in re.findall(rating_pattern, html):
    print(rating)

rawDescription: How to extract reviewer's ratings from Yelp.

description: Extract reviewer's ratings from Yelp.


code:
class Sum_DB(db.Model):
    name_of_profile = db.StringProperty(required = True)
    float_value= db.FloatProperty()

class MainHandler(webapp2.RequestHandler):
  def get(self, *args, **kwargs):
    r = Sum_DB(name_of_profile='test1', float_value=float(1.2359))
    s = Sum_DB(name_of_profile='test2', float_value=float(2.2355))
    t = Sum_DB(name_of_profile='test3', float_value=float(4.2185))

    r.put()
    s.put()
    t.put()

    # Using the Query class
    query = Sum_DB.all()

    # You can now iterate over that 'query', with each element
    # representing an entity from your datastore. Each entity
    # will have the properties you defined in Sum_DB, so you
    # can access them by name.
    sum_me_up = sum(result.float_value for result in query)

    # Or using GQL - the concept/result is the same
    query2 = db.GqlQuery('SELECT * from Sum_DB')
    sum_me_up2 = sum(result.float_value for result in query2)

    self.response.out.write('Query: {0} | GQL: {1}'.format(sum_me_up,
                                                           sum_me_up2))

app = webapp2.WSGIApplication([
                   ('/', MainHandler),
                   ],
                   debug=True)

rawDescription: Summing all float entities within a Database on App Engine


code:
from multiprocessing import Process, Queue
import zmq
import time

class TestClass(Process):
    def __init__(self, queue):
        super(TestClass, self).__init__()
        self.queue = queue

    def run(self):
        # Setting up connections
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.SUB)
        self.socket.connect("tcp://192.168.0.6:8577")
        self.socket.setsockopt(zmq.SUBSCRIBE, b'')

        while True:
            msg = self.socket.recv()
            self.queue.put(msg)

if __name__ == "__main__":
    queue = Queue()
    c = TestClass(queue)
    c.start()  # Don't use run()
    # Do something else

rawDescription: Different behavior in run and start in Python multiprocessing


code:
def getKey(item):
    return (item['Frequency'], item['Letter'])

rawDescription: Sorting a list based on the 2nd key

description: Sorting a list based on the 2nd key


code:
import re
s = "badges: @badges=;color=;display-name=;emotes=;message-id=34;thread-id=5575526_123681740;turbo=0;user-id=5575526;user-type= :teonnyn!teonnyn@teonnyn.tmi.twitch.tv WHISPER blastweb :Hello Bot"
re.findall(r'user-type=\s+:(\w+)!.*:([\S\s]+)', s)

rawDescription: In Python, how can I filter just the user and message in Twitch API's WHISPER command using regex?


code:
scene = bpy.context.scene
queue = scene.sequence_editor.sequences

queue[0].blend_alpha = 0.0
queue[0].keyframe_insert('blend_alpha', frame=1)

queue[0].blend_alpha = 1.0
queue[0].keyframe_insert('blend_alpha', frame=10)

rawDescription: Scripting the Keyframe Inserts for Opacity and Volume


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

z = -np.linspace(9,15,100)
x = np.linspace(-26,26,1000)

x,z = np.meshgrid(x,z)

Z = -np.exp(-0.05*z) +4*(z+10)**2
X = x**2

plt.contour(x,z,(X+Z),[0])
plt.xlim([-1.5,1.5])
plt.ylim([-11.5,-8.5])

rawDescription: How to plot an ellipse by its equation on Python?

description: Plot an ellipse by its equation on Python


code:
res = struct.pack("=B",i) ## uint8_t
res = struct.pack("=b",i) ## int8_t

res = struct.pack("=H",i) ## uint16_t
res = struct.pack("=h",i) ## int16_t

res = struct.pack("=I",i) ## uint32_t
res = struct.pack("=i",i) ## int32_t

res = struct.pack("=Q",i) ## uint64_t
res = struct.pack("=q",i) ## int64_t

res = struct.pack("=f",i) ## float
res = struct.pack("=d",i) ## double

rawDescription: conversion of unicode string in python

description: Conversion of unicode string in python


code:
def getcol(cols, index, default=None):
    try:
        return cols[index].findAll(text=True)[0]
    except IndexError:
        return default

rawDescription: Trouble with for loop with BeautifulSoup


code:
import unittest
from unittest.mock import *
from pd import get_link, ReportNotReadyException

import retry
orig_retry_internal = retry.api.__retry_internal
def _force_retry_params(new_tries=-1, new_delay=0, new_max_delay=None, new_backoff=1, new_jitter=0):
    def my_retry_internals(f, exceptions, tries, delay, max_delay, backoff, jitter, logger):
        # call original __retry_internal by new parameters
        return orig_retry_internal(f, exceptions, tries=new_tries, delay=new_delay, max_delay=new_max_delay,
                                   backoff=new_backoff, jitter=new_jitter, logger=logger)
    return my_retry_internals

class MyTestCase(unittest.TestCase):
    @patch("retry.api.__retry_internal", side_effect=_force_retry_params(new_tries=1))
    def test_something(self, m_retry):
        self.assertRaises(ReportNotReadyException, get_link, None)

rawDescription: how to mock function call used by imported pypi library in python

description: Mock function call used by imported pypi library in python


code:
with open('Test.csv', 'wb') as f:
    w = csv.writer(f)
    for row in zip(a, b, c):
        w.writerow(row)

rawDescription: Python adding integer lists as columns to CSV


rawDescription: multi chart in python

description: Multi chart in python


code:
from django.views.generic import View

class LoginView(View):
    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)

                return HttpResponseRedirect('/form')
            else:
                return HttpResponse("Inactive user.")
        else:
            return HttpResponseRedirect(settings.LOGIN_URL)

        return render(request, "index.html")

class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect(settings.LOGIN_URL)

rawDescription: Creating login and logout class based views in Django 1.8


code:
from sqlalchemy.orm import validates

class Item(db.Model):
    # I need to ensure the code column converts values to uppercase automatically
    code = db.Column(db.String(30), primary_key=True)
    name = db.Column(db.String(250), nullable=False)

    @validates('code', 'name')
    def convert_upper(self, key, value):
        return value.upper()

rawDescription: Best way to force values to uppercase in sqlalchemy field

description: Force values to uppercase in sqlalchemy field


rawDescription: obtain multi-dimensional list manipulating the original list in python

description: Obtain multi-dimensional list manipulating the original list in python


code:
x,y,z = indx.shape
a,b,_ = np.ogrid[:x,:y,:z]
raster[a,b,indx]

rawDescription: Indexing Multi-dimensional arrays

description: Indexing Multi-dimensional arrays


code: total = sum(len(item) for item in mydict.itervalues())

rawDescription: Counting dictionary- list items python

description: Counting dictionary- list items python


code:
secure_filename("My cool movie.mov")
secure_filename("../../../etc/passwd")
secure_filename(u'i contain cool \xfcml\xe4uts.txt')

rawDescription: Determine if a path is legal

description: Determine if a path is legal


code:
from nltk.tokenize import PunktSentenceTokenizer
from bs4 import BeautifulSoup

html_doc = '''<title>abcd</title>

i want to take everything in an HTML document and capitalize the sentences (within paragraph tags).
the input file has everything in all caps.

my attempt has two flaws - first, it removes the paragraph tags, themselves, and second, it simply lower-cases everything in the match groups.
 i don't quite know how capitalize() works, but I assumed that it would leave the first letter of sentences... capitalized.

there may be a much easier way to do this than regex, too. Here's what I have:

'''

soup = BeautifulSoup(html_doc, 'html.parser')

for paragraph in soup.find_all('p'):
    text = paragraph.get_text()
    sent_tokenizer = PunktSentenceTokenizer(text)
    sents = [x.capitalize() for x in sent_tokenizer.tokenize(text)]
    paragraph.string = "\n".join(sents)

print(soup)

rawDescription: Regex to capitalize paragraphs in HTML python


code:
import re

def tokenise(txt):
    # Expand "'ve"
    txt = re.sub(r"(?i)(\w)'ve\b", r'\1 have', txt)
    # Separate punctuation from words
    txt = re.sub(r'\b', ' ', txt)
    # Remove isolated, single-character punctuation,
    # and articles (a, an, the)
    txt = re.sub(r'(^|\s)([.;:]|[Aa]n|a|[Tt]he)($|\s)', r'\1\3', txt)
    # Split into non-empty strings
    return filter(bool, re.split(r'\s+', txt))

# Example use
txt = "I've got an A mark!!! Such a relief... I should've partied more."
words = tokenise(txt)
print (','.join(words))

rawDescription: How to keep repetative punctuation while parsing python string?

description: Keep repetative punctuation while parsing python string


code:
import tkinter as tk
from tkinter import ttk, messagebox

def reset_choice():
    button_run.configure(state=tk.DISABLED)
    button_a.configure(state=tk.NORMAL)
    button_b.configure(state=tk.NORMAL)
    button_c.configure(state=tk.NORMAL)

def reset_sim():
    global choice
    global switch
    reset_choice()
    choice.set('')
    switch = False

def run_sim():
    global choice
    global switch
    if messagebox.askyesno('Are you sure?', 'You chose {}, do you want to switch?'.format(choice.get())):
        reset_choice()
        switch = True
    else:
        print('You chose door {}'.format(choice.get()))
        if switch:
            print('You switched choice before running')
        print('Running sim...')
        reset_sim()

def select_door():
    button_run.configure(state=tk.NORMAL)
    button_a.configure(state=tk.DISABLED)
    button_b.configure(state=tk.DISABLED)
    button_c.configure(state=tk.DISABLED)

root = tk.Tk()
frame = ttk.Frame(root)
frame.grid(column=0, row=0)

choice = tk.StringVar()
switch = False

button_a = ttk.Radiobutton(frame, text="A", variable=choice, value="A", command=select_door)
button_b = ttk.Radiobutton(frame, text="B", variable=choice, value="B", command=select_door)
button_c = ttk.Radiobutton(frame, text="C", variable=choice, value="C", command=select_door)

button_run = ttk.Button(frame, text="Run", command=run_sim, state=tk.DISABLED)

button_a.grid(column=0, row=0)
button_b.grid(column=1, row=0)
button_c.grid(column=2, row=0)
button_run.grid(column=1, row=1)

root.mainloop()

rawDescription: Tkinter Buttons: How make sure certain buttons have been pressed before running the main part of your script


code:
data = {}
# Parse file
data['id'] = id_value;
data['date'] = date_value;
# ... and so on

rawDescription: Python - splitting up many small txt files into a data structure to feed into mysql


code:
def my_reverser(x):
  try:
    x_ = x[::-1]
  except TypeError:
    return x
  else:
    return x if len(x) == 1 else tuple(my_reverser(e) for e in x_)

rawDescription: Reversing a nested tuple in python using the function reversed


code:
import numpy as np
import pylab as p

data=np.array(np.random.rand(1000))
y,binEdges=np.histogram(data,bins=100)
bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
p.plot(bincenters,y,'-')
p.show()

rawDescription: Plot line graph from histogram data in matplotlib


code:
#: A list of file identifiers for all the fileids used by this
#: corpus reader.
_FILES = ('cntlist.rev', 'lexnames', 'index.sense',
          'index.adj', 'index.adv', 'index.noun', 'index.verb',
          'data.adj', 'data.adv', 'data.noun', 'data.verb',
          'adj.exc', 'adv.exc', 'noun.exc', 'verb.exc', )

def __init__(self, root):
    """
    Construct a new wordnet corpus reader, with the given root
    directory.
    """
    super(WordNetCorpusReader, self).__init__(root, self._FILES,
                                              encoding=self._ENCODING)

rawDescription: I have a database and API for hindi wordnet. I want to access this wordnet from NLTK python. Is there any way to add our own wordnet into NLTK?


code:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

pp = PdfPages('multipage.pdf')

fig=plt.figure()
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212)

pp.savefig(fig)

fig2=plt.figure()
ax1=fig2.add_subplot(311)
ax2=fig2.add_subplot(312)
ax3=fig2.add_subplot(313)

pp.savefig(fig2)

pp.close()

rawDescription: Multiple subplots in one pdf page figure with matplotlib


code:
import numpy as np
import pylab as plt

target = 250
beta = 1.0/target

Y = np.random.exponential(beta, 5000)
plt.hist(Y, normed=True, bins=200,lw=0,alpha=.8)
plt.plot([0,max(Y)],[target,target],'r--')
plt.ylim(0,target*1.1)
plt.show()

rawDescription: Manipulating the numpy.random.exponential distribution in Python


code:
import tkinter as tk

units = {'feet': (.3048, 'meters'), 'meters': (3.2808399, 'feet')}
def convert():
    orig = unit.get()
    mult, to = units[orig]
    output.set(str(mult * float(entry.get())) + ' ' + to)

root = tk.Tk()
output = tk.StringVar()
entry = tk.Entry(root)
unit = tk.Spinbox(root, values=tuple(units), width=10, wrap=True)
go = tk.Button(root, text='Convert', command=convert)
display = tk.Label(root, textvariable=output)
entry.grid(row=0, column=0)
unit.grid(row=0, column=1)
go.grid(row=0, column=2)
display.grid(row=1, column=0)
root.mainloop()

rawDescription: linking a command to a spinbox in Tkinter

description: Linking a command to a spinbox in Tkinter


code:
import mongoengine
from bson import ObjectId

class DuckTypedQuerySet(list):

    def __init__(self, data, document):
        if not hasattr(data, '__iter__') or isinstance(data, mongoengine.Document):
            raise TypeError("DuckTypedQuerySet requires iterable data")

        super(DuckTypedQuerySet, self).__init__(data)

        self._document = document

    @property
    def objects(self):
        return self

    def _query_match(self, instance, **kwargs):
        is_match = True

        for key, value in kwargs.items():
            attribute = getattr(instance, key, None)

            if isinstance(attribute, ObjectId) and not isinstance(value, ObjectId):
                attribute = str(attribute)

            if not attribute == value:
                is_match = False
                break

        return is_match

    def filter(self, **kwargs):
        data = filter(lambda instance: self._query_match(instance, **kwargs), self)

        return self.__class__(data, self._document)

    def get(self, **kwargs):
        results = self.filter(**kwargs)

        if len(results) > 1:
            raise self._document.MultipleObjectsReturned("{0} items returned, instead of 1".format(len(results)))

        if len(results) < 1:
            raise self._document.DoesNotExist("{0} matching query does not exist.".format(str(self._document)))

        return results[0]

    def first(self):
        return next(iter(self), None)

    def all(self):
        return self

    def count(self):
        return len(self)

def cache_user_articles(user_id):
    key = "articles_{0}".format(user_id)

    articles = cache.get(key)

    if articles is None:
        articles = DuckTypedQuerySet(list(Article.objects.filter(user_id = user_id)), document = Article)
        cache.set(key, articles)

    return articles

rawDescription: Convert list into queryset

description: Convert list into queryset


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

x, y = np.genfromtxt('data', unpack=True, skip_header=1)
# find lots of points on the piecewise linear curve defined by x and y
M = 1000
t = np.linspace(0, len(x), M)
x = np.interp(t, np.arange(len(x)), x)
y = np.interp(t, np.arange(len(y)), y)
tol = 1.5
i, idx = 0, [0]
while i < len(x):
    total_dist = 0
    for j in range(i+1, len(x)):
        total_dist += math.sqrt((x[j]-x[j-1])**2 + (y[j]-y[j-1])**2)
        if total_dist > tol:
            idx.append(j)
            break
    i = j+1

xn = x[idx]
yn = y[idx]
fig, ax = plt.subplots()
ax.plot(x, y, '-')
ax.scatter(xn, yn, s=50)
ax.set_aspect('equal')
plt.show()

rawDescription: How to generate equispaced interpolating values

description: Generate equispaced interpolating values


code: num = int(raw_input('Give me a number: '))

rawDescription: Compare list element to input numbers in python


code:
import numpy as np
dt = np.dtype([('a', np.int64, 1), ('b', np.float64, 1)])
a = np.array([1,2,3,4], dtype=np.int64)
b = np.array([1.,2.,3.,4.], dtype=np.float64)
ab = np.array(zip(a,b), dtype=dt)
ab[:]['a']
ab[:]['b']

rawDescription: Combining two 1D arrays of different data types into 1 2D array in PYTHON


code:
#Create the T letter - Draw T
vita = turtle.Turtle()
vita.up() #add this
vita.goto(100,0)
vita.down() #add this
vita.shape("turtle")
vita.color("blue")
vita.forward(5)
vita.forward(100)
vita.back(50)
vita.right(90)
vita.forward(100)

rawDescription: Python turtle, delete line

description: Python turtle, delete line


rawDescription: Python Regex - Escaping

description: Python Regex - Escaping


code:
import optparse
parser = optparse.OptionParser()
(options, args) = parser.parse_args()
type(options)
help(optparse.Values)

rawDescription: What kind of object does parser.parse_args()[0] return?


code:
from java.sql import DriverManager

def show_db_info(db_url, usr, passwd, schema_name=None):
    db = DriverManager.getConnection(db_url, usr, passwd)
    dbmi = db.getMetaData()
    ...

rawDescription: How to utilize the java compiled libraries in python?

description: Utilize the java compiled libraries in python


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('myurl')

link = driver.find_element_by_link_text('search')
link.click()

rawDescription: How should I use this onclick(javascript) in Python


code:
import random
score = 0
ops = ['+','-','*']

for i in range(10):
    num1 = random.randint(1,9)
    num2 = random.randint(1,9)
    operation = random.choice(ops)
    print(num1)
    print(operation)
    print(num2)
    user = int(input(""))
    if operation == "+":
        answer = num1 + num2
    elif operation == "-":
        answer = num1 - num2
    elif operation == "*":
        answer = num1 * num2

    if user == answer:
        print("correct")
        score = score + 1
    else:
        print("Incorrect")
    print (score)

rawDescription: How would I loop a randomly generated arithmetic 10 times over? this is my code so far


code:
from PySide import QtGui, QtCore, QtSvg

class TestTreeItem(QtGui.QTreeWidgetItem):
    def __init__(self, parent, value, status):
        super(TestTreeItem, self).__init__(parent)

        # Column 0
        self.setText(value)

        # Column 1
        # Using Qt Resources. All of the maps are to svg files.
        status_map = {0: ":/images/good",
        1: ":/images/warning",
        2: ":/images/error"}

        svg_renderer = QtSvg.QSvgRenderer(status_map[status])
        image = QtGui.QImage(64, 64, QtGui.QImage.Format_ARGB32)
        # Set the ARGB to 0 to prevent rendering artifacts
        image.fill(0x00000000)
        svg_renderer.render(QtGui.QPainter(image))
        pixmap = QtGui.QPixmap.fromImage(image)
        icon = QtGui.QIcon(pixmap)
        self.setIcon(1, icon)

        self.setSizeHint(1, QtCore.QSize(64, 64))

rawDescription: PySide: How to set an SVG icon in QTreeWidget's item and change the size of the icon?


code:
from dateutil import relativedelta as rdelta
from datetime import date
d1 = date(2001,5,1)
d2 = date(2012,1,1)
rd = rdelta.relativedelta(d2,d1)
"{0.years} years and {0.months} months".format(rd)

rawDescription: calculate the difference between two datetime.date() dates in years and months

description: Calculate the difference between two datetime.date() dates in years and months


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

pi = np.pi
sqrt = np.sqrt
exp = np.exp

def make_node_image(measured_value, std_dev, coverage="0.96",imageID=1):

    DPI = 100
    TODPI=1
    MINSIZE = 50 # in DPI
    MAXSIZE = 400 # in DPI
    MAXAMPLITUDE = .005

    # make radius,std_dev  values in grid units
    mean_circle_radius = int(sqrt(measured_value/pi)/TODPI)
    image_circle_radius = int(sqrt((measured_value + 2*std_dev)/pi)/TODPI)
    if image_circle_radius < MINSIZE:
        raise Exception("image_circle_radius too small!")
    if image_circle_radius > MAXSIZE:
        raise Exception("image_circle_radius too large!")

    grid_std_dev = std_dev/TODPI

    gradient_amplitude = 1/(std_dev*sqrt(2*pi))/MAXAMPLITUDE
    gradient_fade = np.zeros([2*image_circle_radius,
                              2*image_circle_radius])
    for ix in range(2*image_circle_radius):
        for iy in range(2*image_circle_radius):
            r = sqrt((ix-image_circle_radius)**2
                     +(iy-image_circle_radius)**2)
            gradient_fade[ix,iy] = exp(
                -(r-mean_circle_radius)**2
                 /(2*grid_std_dev**2))

    image_gradient = gradient_amplitude*gradient_fade

    fig = plt.figure(figsize=(2*image_circle_radius/DPI,
                              2*image_circle_radius/DPI),dpi=DPI)

    ax = fig.add_axes([0,0,1,1],frameon=True, xticks=[], yticks=[])

    #***generate_image_from_gradient***
    im = ax.imshow(image_gradient,vmin=0,vmax=1)

    patch = patches.Circle((image_circle_radius,image_circle_radius),
                           radius=image_circle_radius,fc='white')

    #***scale_and_clip_image_to_image_circle_radius***
    im.set_clip_path(patch)

    name = 'circImage%d.png'%imageID
    fig.savefig(name)

    return name

make_node_image(90000*pi,100)

rawDescription: Is there a simple way to generate bitmaps with a gradient using Python?


code:
from PySide import QtGui, QtCore

class AltTabPressEater(QtCore.QObject):
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and (event.key() == 16777217 or event.key() == 16777218):
            return True # eat alt+tab or alt+shift+tab key
        else:
            # standard event processing
            return QtCore.QObject.eventFilter(self, obj, event)

app = QtGui.QApplication([])

tabs = QtGui.QTabWidget()
filter = AltTabPressEater()
tabs.installEventFilter(filter)
push_button1 = QtGui.QPushButton("QPushButton 1")
push_button2 = QtGui.QPushButton("QPushButton 2")

tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()

vBoxlayout = QtGui.QVBoxLayout()
vBoxlayout.addWidget(push_button1)
vBoxlayout.addWidget(push_button2)
tabs.resize(250, 150)
tabs.move(300, 300)
tab3.setLayout(vBoxlayout)

tabs.addTab(tab1, "Tab 1")
tabs.addTab(tab2, "Tab 2")
tabs.addTab(tab3, "Tab 3")

tabs.show()

app.exec_()

rawDescription: Prevent tab cycling with Ctrl+Tab by default with QTabWidget


code:
from scipy.interpolate import UnivariateSpline
old_indices = np.arange(0,len(a))
new_length = 11
new_indices = np.linspace(0,len(a)-1,new_length)
spl = UnivariateSpline(old_indices,a,k=3,s=0)
new_array = spl(new_indices)

rawDescription: numpy interpolation to increase a vector size

description: Numpy interpolation to increase a vector size


code:
# untested, all bugs are free  ;)
n = input('write for nummbers ')
n = int(n) # you need n as a number
i=0
while n != 6174:
    i += 1     #"i" show how many times iteration happened.
    large = "".join(sorted(str(n), reverse=True))
    little = "".join(sorted(str(n),))
    n = int(large) - int(little)
print(n, i)

rawDescription: while-loop to number 6174

description: While-loop to number 6174


code:
class Foo(Base):
    __tablename__ = "foo"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}

    ...

    column = db.Column(db.String(500))

rawDescription: Database agnostic way to say I want a column to be UTF-8 in SqlAlchemy?


code:
np_array = np.zeros(length)
_l = min(length, len(list_like))
np_array[:l] = list_like[:l]

rawDescription: Creating fixed length numpy array from variable length lists


code:
for infile in glob.glob( os.path.join(path, '*.png')):
    viewer = subprocess.Popen(['some_viewer', infile])
    viewer.terminate()
    viewer.kill()  # make sure the viewer is gone; not needed on Windows

rawDescription: How can I close an image shown to the user with the Python Imaging Library?

description: Close an image shown to the user with the Python Imaging Library


code:
"What is your name?".replace("?","") #this is the most clear
#or
filter(lambda x:x!= "?","What is your name?")
#or
"".join(x for x in "What is your name?" if x != "?")
#or
"What is your name?".translate(None,"?") #this is my favorite

rawDescription: Removing Question marks from string

description: Removing Question marks from string


code:
x = 10
lst = [] #Note: do not use list as a variable name, it shadows the built-in
while x != 0:
    lst.append(raw_input('Enter a word: '))
    x-=1

rawDescription: Until statement/loop python?

description: Until statement/loop python


rawDescription: numpy._r with a list

description: Numpy._r with a list


code:
contigDict = {}
for line in open('contigsFile.txt'):
    contigId, isoform, length = line.split()
    if contigId in contigDict:
        curr_Isoform, curr_length = contigDict[contigId]
        if int(curr_length) < int(length):
            contigDict[contigId] = (isoform, length)
    else:
        contigDict[contigId] = (isoform, length)

rawDescription: keep longest isoforms - multiple keys in dictionary with python

description: Keep longest isoforms - multiple keys in dictionary with python


code:
String.objects.filter( language = 'english',
                       string__original_string__isnull = True )

rawDescription: Django query - Retrieve objects that don't have other object pointing to them


code:
import scrapy
from selenium import webdriver

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['ebay.com']
    start_urls = ['http://www.ebay.com/sch/i.html?_odkw=books&_osacat=0&_trksid=p2045573.m570.l1313.TR0.TRC0.Xpython&_nkw=python&_sacat=0&_from=R40']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

                # get the data and write it to scrapy items
            except:
                break

        self.driver.close()

rawDescription: selenium with scrapy for dynamic page

description: Selenium with scrapy for dynamic page


code:
define("logging", default="info",
       help=("Set the Python log level. If 'none', tornado won't touch the "
             "logging configuration."),
       metavar="debug|info|warning|error|none")

rawDescription: How to log from handlers in tornado in console?

description: Log from handlers in tornado in console


code:
from collections import Counter
computers = ['computer17', 'computer6', 'comps', 'computer17']
Counter(computers)

rawDescription: Count the occurrences of the elements in list


code:
with open('AvailableTickets.txt', 'r') as fin:
    tickets_raw = fin.read()
    tickets_list = tickets_raw.split(', ')
    with open('TestTickets.txt', 'a') as f:
        if len(tickets_list) < 10:
            f.write(tickets_raw)
        else:
            f.write(', '.join(tickets_list[-10:]))

rawDescription: Python - Appending new floats and deleting old floats in a text file


code:
allKeys = [uinput.KEY_LEFTSHIFT, uinput.KEY_LEFTCTRL, uinput.KEY_SPACE, uinput.KEY_U,
          uinput.KEY_A, uinput.KEY_B, uinput.KEY_C, uinput.KEY_D,
          uinput.KEY_E, uinput.KEY_F, uinput.KEY_0, uinput.KEY_1,
          uinput.KEY_2, uinput.KEY_3, uinput.KEY_4, uinput.KEY_5,
          uinput.KEY_6, uinput.KEY_7, uinput.KEY_8, uinput.KEY_9]

device = uinput.Device(allKeys)

sleepInterval = 0.003

def printChar(charCode):
  time.sleep(sleepInterval)
  device.emit(uinput.KEY_LEFTSHIFT, 1);
  device.emit(uinput.KEY_LEFTCTRL, 1);
  device.emit_click(uinput.KEY_U);
  device.emit(uinput.KEY_LEFTSHIFT, 0);
  device.emit(uinput.KEY_LEFTCTRL, 0);
  time.sleep(sleepInterval)

  for symbol in charCode:
    device.emit_click(uinput._chars_to_events(symbol)[0]);
    time.sleep(sleepInterval)

  device.emit_click(uinput.KEY_SPACE);
  time.sleep(sleepInterval)

charString = "string that will be typed"
for char in charString:
  printChar('{:04x}'.format(ord(char)))

rawDescription: Paste a string into selected text field in Gnome using Python


code:
from operator import itemgetter

def load_dataset(fp, columns, types=None, delimiter=' ', skip_header=True):
    get_columns = itemgetter(*columns)
    if skip_header:
        next(fp)
    dataset = []
    for line in fp:
        parts = line.split(delimiter)
        columns = get_columns(parts)
        if types is not None:
            columns = [convertor(col) for convertor, col in zip(types, columns)]
        dataset.append(columns)
    return dataset

rawDescription: import text file to process specific columns

description: Import text file to process specific columns


code:
def content_file_name(instance, filename):
    name, ext = os.path.splitext(filename)
    ext = ext.lstrip(".")                          # Remove leading dot
    if ext in ("jpg", "jpeg", "png"):
        subdir = "phots"
    elif ext in ("txt", "asc"):
        subdir = "text"
    else:
        subdir = extension
    upload_dir = os.path.join('uploads', 'resource', subdir)
    return os.path.join(upload_dir, filename)

rawDescription: python separate file by extension and save into folder accordingly

description: Python separate file by extension and save into folder accordingly


code:
import struct
struct.pack('>H', 0xbba1)
hex(struct.unpack('>H', '\xbb\xa1')[0])

rawDescription: Python 2: Why is this bytestring order switched in struct.pack() and struct.unpack() methods?


code:
kernelSize = 3
kernelOffset = int(kernelSize / 2) # Assumes only odd-sized kernels
for x in xrange(len(A1)):
    for y in xrange(len(A1[0])):
        total = 0
        for kx in xrange(kernelSize):
            for ky in xrange(kernelSize):
                offsetX = -kernelOffset + kx # Should give something in the range [-1, 1]
                offsetY = -kernelOffset + ky
                currentX = x + offsetX
                currentY = y + offsetY
                if currentX < 0 or currentX >= len(A1) or currentY < 0 or currentY >= len(A1[0]): # do nothing if "out of bounds"
                    continue
                total += A1[currentX][currentY] * A2[kx][ky]
        A3[x][y] = total

rawDescription: Python: Directional Navigation in 2d Array


code:
import random

def compareInput(n):
                if n == randomNumber: #Compares guess and the random number
                        print("YAY!! you won the number was: " + n)
                        return True
                        #(something) Loop should stop here.
                else:
                        print("Wrong guess")
                        return False

print("Guess the number") #Prints guess number duh!
randomNumber = str(random.randint(1,20)) #Generates a number between 1 and 20 and converts it to string
while True: #Input loop
        guess = str(input()) #Takes input and converts it to string
        if len(guess) > 0 and guess.isdigit() : #input must be a number and at lest 1 digit
                if compareInput(guess): #Call compareInput function
                        break # We got the right guess!
        else:
                print("Wrong input")

rawDescription: Stop a loop inside function in Python 3

description: Stop a loop inside function in Python 3


code:
sel = selenium('localhost', 4444, browser, my_url)
html = sel.get_eval("this.browserbot.getCurrentWindow().document.getElementById('1').innerHTML")

rawDescription: How to get the html source of a specific element with selenium?

description: Get the html source of a specific element with selenium


rawDescription: Extract identical slices/indexed elements from all sublists


code:
import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        # define a command to be called by the validation code.  %P
        # represents the value of the entry widget if the edit is
        # allowed. We want that passed in to our validation comman so
        # we can validate it. For more information see
        # http://tcl.tk/man/tcl8.5/TkCmd/entry.htm#M7
        vcmd = (self.register(self._validate), '%P')
        e = tk.Entry(self, validate="key", validatecommand=vcmd)
        e.pack()

    def _validate(self, P):
        # accept the empty string, "." or "-." (to make it possible to
        # enter something like "-.1"), or any string that can be
        # converted to a floating point number.
        try:
            if P in (".", "-", "-.", ""):
                return True
            n = float(P)
            return True
        except:
            self.bell()
            return False

app=SampleApp()
app.mainloop()

rawDescription: Making Entry widget "disabled" like in windows calc


code:
imin = df.groupby("Symbol")["x"].transform("idxmin")
df["yminx"] = df.loc[imin, "y"].values
df

rawDescription: selecting a column value based on a different column value after applying Groupby

description: Selecting a column value based on a different column value after applying Groupby


code:
def clean(self, data, initial=None):
    try:
        if data.size > somesize:
            raise ValidationError('File is too big')

        (junk, ext) = os.path.splitext(data.name)
        if not ext in ('.jpg', '.gif', '.png'):
            raise ValidationError('Invalid file type')

    except AttributeError:
        raise ValidationError(self.error_messages['invalid'])

    return FileField.clean(self, data, initial)

rawDescription: Extending a form field to add new validations


code:
@property
def paths(self):
    if sys.version_info >= (2, 6, 0):
        return watchdog.utils.bricks.OrderedSet()
    return set()

rawDescription: Python watchdog: what is the 'empty' directory snapshot?


code:
import time
CLOCKS_PER_SEC = 1.0
seconds = time.clock() / CLOCKS_PER_SEC

rawDescription: cvUpdateMotionHistory in Python/OpenCV

description: CvUpdateMotionHistory in Python/OpenCV


code:
import sys
import csv

data=[]
f=open("stockcontrol.csv")
reader=csv.DictReader(f,fieldnames=['code','level','target','distancefromtarget'])
for line in reader:
  if int(line['level']) <= 5:
    line['level']= line['target']
    line['distancefromtarget']= 0
  data.append("%s,%s,%s,%s"%(line['code'],line['level'],line['target'],line['distancefromtarget']))
f.close()

f=open("stockcontrol.csv","w")
f.write("\n".join(data))
f.close()

rawDescription: String Replace for Multiple Lines In A CSV


code:
from quantities import units

unit_symbols = [u.symbol for _, u in units.__dict__.items()
    if isinstance(u, type(units.deg))]

rawDescription: Need a list of all units available in quantities python package


code:
files = {
    'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'),
    'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'),
}
response = requests.post(url, files=files)

rawDescription: Content-Type in for individual files in python requests


code:
x_new = numpy.array(x)
y_new = numpy.array(y)

x_new = numpy.roll(x_new, len(x_new)/2)
y_new = numpy.roll(y_new, len(y_new)/2)

rawDescription: python diagram: change x axis inside out

description: Python diagram: change x axis inside out


code:
input = ['item01', 'item02', 'item03']
output = [{"title":x} for x in input]

rawDescription: Convert flat list to associative list or dictionary


code: return self._api

rawDescription: Python - passing object references?

description: Python - passing object references


code:
width = max(i.get_rect().width for i in images)
height = sum(i.get_rect().height for i in images)

out = py.Surface((width, height), flags=py.SRCALPHA)

pos = 0
for i in images:
    r = out.blit(i, (0, pos))
    pos += i.get_rect().height

rawDescription: Images not blitting

description: Images not blitting


code:
from pylab import *

t = linspace(0.0, pi, 100)
x = cos(t)
y = sin(t)
figure(0)
subplot(111, autoscale_on=False, xlim=(-1.2, 1.2), ylim=(-.2, 1.2))

point,  = plot([x[0]], [y[0]], marker='o', mfc='r', ms=3)

for j in arange(len(t)):
    # reset x/y-data of point
    point.set_data(x[:j], y[:j])
    plt.pause(0.05)
    plt.draw() # redraw current figure

rawDescription: Matplotlib interactive environment does not work


code:
header = ""
with open(path_to_copy_from, 'rb') as f:
    for i in range(4):
        byte = f.read(1)
        header += hex(ord(byte))[2:] + " "

rawDescription: python copy file based on header

description: Python copy file based on header


code:
s = 'some string'
dir(s)

rawDescription: AttributeError: 'str' object has no attribute 'toLowerCase'


code: line = line.split(':', 1)

rawDescription: Python File Parser

description: Python File Parser


code:
from multiprocessing import Pool
pool = Pool(processes=6) # run no more than 6 at a time
pool.map(run_assignments_parallel, project_list) # pass full list (12 items)

rawDescription: Python Multiprocessing Worker/Queue

description: Python Multiprocessing Worker/Queue


rawDescription: Restart the loop if file doesn't exist

description: Restart the loop if file doesn't exist


code:
f=open('my-file.txt','rU')
raw=f.read()
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)

rawDescription: How do I create my own NLTK text from a text file?

description: Create my own NLTK text from a text file


code:
def OnSearch(self, event=None):

    value = self.filter.GetValue()
    if not value:
        self.RecreateTree()
        return

    wx.BeginBusyCursor()

    for category, items in _treeList:
        self.searchItems[category] = []
        for childItem in items:
            if SearchDemo(childItem, value):
                self.searchItems[category].append(childItem)

    wx.EndBusyCursor()
    self.RecreateTree()

rawDescription: wxPython - dynamially update a listctrl depending on input into a textctrl

description: WxPython - dynamially update a listctrl depending on input into a textctrl


code:
# Example: loops monitoring events forever.
#
import pyinotify

# Instanciate a new WatchManager (will be used to store watches).
wm = pyinotify.WatchManager()
# Associate this WatchManager with a Notifier (will be used to report and
# process events).
notifier = pyinotify.Notifier(wm)
# Add a new watch on /tmp for ALL_EVENTS.
wm.add_watch('/tmp', pyinotify.ALL_EVENTS)
# Loop forever and handle events.
notifier.loop()

rawDescription: pyinotify: Handling IN_MODIFY triggers

description: Pyinotify: Handling IN_MODIFY triggers


code:
import urllib2
bio_page = urllib.urlopen(bio_url).read()

rawDescription: A simple spider question

description: A simple spider question


code: sorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower()))

rawDescription: In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?


code: del myList[beginIndex:endIndex+1]

rawDescription: removing elements incrementally from a list

description: Removing elements incrementally from a list


code: [j*2+1 if i==0 else j*2 for i, j in enumerate(old_list)]

rawDescription: Python list comprehension for if-else statements


code:
from docker import Client
cli = Client(base_url='tcp://172.16.3.87:2375', version='1.22')
container_id = cli.create_container(
  'busybox',
  'ls',
  name='test',
  ports=[1111],
  host_config=cli.create_host_config(port_bindings={ 1111:8000 }, publish_all_ports=True)
)

response = cli.start(container=container_id.get('Id'))
print(container_id)
print(response)

rawDescription: Port binding with a container in docker-py doesn't work


code:
del request.vars.file
redirect(URL('form2', vars=request.vars))

rawDescription: Web2py - preventing uploaded file content from appearing in URL when using redirect() with request.vars


code:
desired_lines = [1, 5, 38, 200]

for n, line in enumerate(or_profile_file):
    if (n+1) in desired_lines:
        new_profile_file.write(line)

rawDescription: Python copying certain lines from one file to another


code: plt.fill_betweenx(X, Y, 35) #or max(X) or whatever cut-off you may want.

rawDescription: matplotlib fill between discrete points

description: Matplotlib fill between discrete points


code:
# this allows for integers to be divided by integers and give a float result
# program is runnable in both python 2 and 3
from __future__ import division
from sys import exit
weight = 97
items = [[17, 19], [22, 19], [65, 64], [21, 19], [27, 26], [19, 21], [58, 61],
[43, 46], [1, 3], [44, 42], [22, 22], [52, 53], [10, 8], [37, 35], [60, 62],
[42, 39], [36, 36], [62, 60], [50, 47], [62, 62], [47, 48], [15, 16], [12, 12],
[6, 5], [30, 27], [52, 49], [30, 32], [3, 4], [21, 18], [58, 58], [43, 42],
[50, 50], [41, 41], [60, 60], [55, 58], [64, 63], [32, 33], [11, 12], [11, 13],
[46, 44], [22, 21], [20, 19], [47, 45], [24, 24], [35, 32], [28, 31], [14, 15],
[35, 37], [9, 10], [23, 22], [45, 46], [34, 32], [34, 37], [37, 39], [42, 41],
[59, 57], [24, 22], [15, 13], [33, 34], [3, 3], [55, 55]]

# this is about half of the problem: we must sort the items by the priority
# which which we want them.  this would be their happiness to weight ratio
sorted_items = sorted(items, key=lambda item: item[1] / item[0], reverse=True)

happiness = int()
for item1 in range(len(sorted_items) - 2):
    for item3 in range(item1 + 2, len(sorted_items)):
        for item2 in range(item1 + 1, item3):
            # try to use as much weight as possible, we don't want
            # our bag to go underfilled with 3 efficient but light items
            if (sorted_items[item1][0] +
                sorted_items[item2][0] +
                sorted_items[item3][0] <= weight):
                # we haven't gone over weight! possible solution found!
                happiness = max(sorted_items[item1][1] +
                                sorted_items[item2][1] +
                                sorted_items[item3][1], happiness)

print(happiness)

rawDescription: Python:Find array sum

description: Python:Find array sum


code:
with concurrent.futures.ProcessPoolExecutor() as e:
    @functools.lru_cache
    def work(*args, **kwargs):
        return e.submit(slow_work, *args, **kwargs)

rawDescription: How to share a cache?

description: Share a cache


code: ax.scatter(x, y, z, c=values, alpha=0.3, edgecolors='none',vmin=2100,vmax=2600)

rawDescription: How to make colorbar display set limits with 3D data

description: Make colorbar display set limits with 3D data


rawDescription: Sum of all counts in a collections.Counter


code:
from collections import Counter
from operator import attrgetter
Counter(map(attrgetter("class"),points))

rawDescription: Python list comprehension for dictionaries an example


code:
import numpy as np

a = 2; b = 3; c = 4; d = 5
n = np.array([a,b,c])
x1 = np.array([0,0,d/c])
x2 = np.array([0,d/b,0])

def is_equal(n,m):
    return n-m < 1e-10

def is_on_the_plane(v):
    return is_equal(v[0]*a + v[1]*b + v[2]*c, d)

assert is_on_the_plane(x1)
assert is_on_the_plane(x2)

# Get the normal basis
b1 = x2 - x1
b2 = np.cross(n, b1)

c1 = x1 + b1 + b2
c2 = x1 + b1 - b2
c3 = x1 - b1 + b2
c4 = x1 - b1 - b2

assert is_on_the_plane(c1)
assert is_on_the_plane(c2)
assert is_on_the_plane(c3)
assert is_on_the_plane(c4)

assert is_equal(np.dot(c1-c3, c1-x2), 0)
assert is_equal(np.dot(c2-c1, c2-c4), 0)
# etc. :

#   c3        c1
#
#        x1
#
#   c4        c2

rawDescription: how to generate rectangle from a plane equation ax+by+cz=d?

description: Generate rectangle from a plane equation ax+by+cz=d


code:
t = u/1.0 + min(c, EPS)
x -= t  # same as x = x - t

rawDescription: equals sign after a decrement operator in C++ code

description: Equals sign after a decrement operator in C++ code


code:
soup = BeautifulSoup("This is my text")
span = soup.find('span')
str(span) # Outputs 'This is my text'

rawDescription: How to get HTML representation of a child element in BeautifulSoup?

description: Get HTML representation of a child element in BeautifulSoup


code:
from multiprocessing import Pool

with Pool() as p:
    all_codes = p.map(my_function, files)
return {f:code for code, f in zip(all_codes, files)}

rawDescription: Dirty parallelisation of Python program

description: Dirty parallelisation of Python program


code:
import numpy as np
axis = 0
index = list(np.ix_(*[np.arange(i) for i in z2.shape]))
index[axis] = z2.argsort(axis)
z2[index]

# Or if you only need the 3d case you can use np.ogrid.

axis = 0
index = np.ogrid[:z2.shape[0], :z2.shape[1], :z2.shape[2]]
index[axis] = z2.argsort(axis)
z2[index]

rawDescription: numpy: applying argsort to an array

description: Numpy: applying argsort to an array


code:
import networkx as nx
G = nx.DiGraph()
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('C', 'D')
G.add_edge('C', 'A')
nx.simple_cycles(G)

rawDescription: How can I find circular relations in a graph with Python and Networkx?

description: Find circular relations in a graph with Python and Networkx


code:
import numpy as np

as1 = np.argsort(a1[:,-1])
orig_order = np.argsort(as1)
as2 = np.argsort(a2[:,-1])

ans = np.hstack((a1[as1][:,:-1], a2[as2]))[orig_order]

rawDescription: ordering and concatinating two arrays based on one column elements

description: Ordering and concatinating two arrays based on one column elements


code:
# ... import your Models
from django.core.serializers import serialize

qs1 = Model1.objects.filter(...)
qs2 = Model2.objects.filter(...)
...

fixture = serialize('json', list(qs1) + list(qs2) + list(...))
with open('fixture.json', 'w') as f:
    f.write(fixture)

rawDescription: Saving django test database in a fixture?


code: [string[start:start+4] for start in xrange(0, len(string), 4)]

rawDescription: Split string into a list, with items of equal length


code:
from datetime import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler

def tick():
    print('Tick! The time is: %s' % datetime.now())

if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_executor('processpool')
    scheduler.add_job(tick, 'interval', seconds=3)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

try:
    scheduler.start()
except (KeyboardInterrupt, SystemExit):
    pass

rawDescription: Schedule daily task in a Python app

description: Schedule daily task in a Python app