code:
returnedOrders = (session
                  .query(ORDER)
                  .join(RESTAURANT, and_(ORDER.RESTAURANTSID==RESTAURANT.RESTAURANTSID))
                  .filter(ORDER.RESTAURANTSID==restaurantID)
                  .order_by(*sortOrders(sort_method))  # expand tuples
                  .all()
                  )

def sortOrders(sort_method):
    if sort_method == 'date':
        return (ORDER.ORDERSDATE,)  # @new: return tuple
    elif sort_method == '-date':
        return (ORDER.ORDERSDATE.desc(),)  # @new: return tuple
    elif sort_method == 'restaurant,cost':
        return (
            RESTAURANT.RESTAURANTSNAME,
            ORDER.ORDERSCOST,
        )
    elif sort_method == 'restaurant,-cost':
        return (
            RESTAURANT.RESTAURANTSNAME,
            ORDER.ORDERSCOST.desc(),
        )
    else:
        assert False, "Unexpected sort method {}".format(sort_method)

rawDescription: Syntax to sort more than one column in SQLAlchemy


code:
import numpy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
         [(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
         [(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
         [(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]

# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]

z = np.array([0.1, 9.4, 3.8, 2.0])

fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)

# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()

plt.show()

rawDescription: Set line colors according to colormap

description: Set line colors according to colormap


code: d = getPage(url, method='POST', postdata="hello, world, or whatever.")

rawDescription: Python - Twisted : POST in a form

description: Python - Twisted : POST in a form


code:
import numpy as np
arr1 = np.array((1, 2, 3))
arr2 = np.array((4, 5, 6))
arr1 - arr2
(arr1 - arr2) ** 2
np.sum((arr1 - arr2) ** 2)

rawDescription: Python: fast residuals computing

description: Python: fast residuals computing


code:
import itertools
l = [[1], [2], [3, 4]]
list(itertools.product(*l))

rawDescription: Enumerating all possibilites for a nondeterministic list


code:
import itertools

def PHRED_get():
    temp_scores = []
    all_scores = []
    fastq_location
    print("Building PHRED score bins...")
    for seq_record in itertools.islice(SeqIO.parse(fastq_location, "fastq"), 100):
        temp_scores = seq_record.letter_annotations
        temp_scores = temp_scores['phred_quality']
        all_scores.append(temp_scores)
    all_scores = list(itertools.chain(*all_scores))
    score_bin_maker(all_scores)

rawDescription: Biopython -- reading a fixed number of seq_records at a time


code:
try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

rawDescription: graceful interrupt of while loop in ipython notebook

description: Graceful interrupt of while loop in ipython notebook


code:
def prime(num):
    """True if num is prime, false otherwise"""
    check = True
    #if num in copy:
    #    copy.remove(num)
    for x in range(2,x-1):
        if num % x == 0:
            check = False
            break
    return check

rawDescription: How to write more Pythonic Code

description: Write more Pythonic Code


code:
class Profile(models.Model):
    age = models.IntegerField()

rawDescription: django-registration additional field in signup form

description: Django-registration additional field in signup form


rawDescription: How do I modify this REGEX to pick up all dates in the test string

description: Modify this REGEX to pick up all dates in the test string


code:
class SomeClass(object):

  def __init__(self, value):
    self.value = value

  def __str__(self):
    return '<SomeClass %s>' % self.value

rawDescription: How to set string render method for a class in Python

description: Set string render method for a class in Python


code:
year_list = range(2000,2014)
filenames = ["calendar_{0}.txt".format(year) for year in year_list]
filenames

rawDescription: How to create a list with a range of years?

description: Create a list with a range of years


code:
import Tkinter as tk
import random

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

        self.canvas = tk.Canvas(self, width=500, height=500, background="black")
        self.canvas.pack(fill="both", expand=True)

        self.particles = []
        for i in range(1000):
            x = random.randint(1, 499)
            y = random.randint(1, 499)
            particle = self.canvas.create_oval(x,y,x+4,y+4,
                                               outline="white", fill="white")
            self.particles.append(particle)

        self.animate()

    def animate(self):
        for i, particle in enumerate(self.particles):
            deltay = (2,4,8)[i%3]
            deltax = random.randint(-2,2)
            self.canvas.move(particle, deltax, deltay)

        self.after(30, self.animate)

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

rawDescription: Gui for Particlefilter with Python

description: Gui for Particlefilter with Python


code:
import string
import random

def randompassword():
  chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + '!@#$%^&*(|`~[];;<>,.)'
  size = random.randint(8, 12)
  return ''.join(random.choice(chars) for x in range(size))

rawDescription: Python v3 ( Random password generator )

description: Python v3 ( Random password generator )


code:
def update_UserProfile_views(request):
    try:
        current_user = request.user
        user = UserProfile.objects.get(user_name=current_user)
    except Exception:
        return render(request, 'base.html', {})
    else:
        if request.method == "POST":
            form = ProfileForm(request.POST,instance=user)
            if form.is_valid():
                profile = form.save(commit=False)
                profile.save()
        else:
            form = ProfileForm()
        return render(request, 'base.html', {'form': form})

rawDescription: How can I update the details of current user using forms and views

description: Update the details of current user using forms and views


code:
from Tkinter import *

# creates window
window = Tk()
size = window.winfo_screenheight()
window.title("This is a window")

# set up geometry using string formatting operator %
window.geometry("%dx%d+%d+%d" % (1000, 1000, 10, 10))
window.update()

# creates canvas
canvas = Canvas(window, bg='green')

# pack is a layout manager
canvas.pack(fill=BOTH, expand=1)
canvas.update()
canvas.create_rectangle(0, 1000, 1000, 0, fill="orange", width=10, outline="white", tag="border")

def shooting():
    global loaded_gun

    c = canvas.coords("player")
    canvas.create_line(c[0],c[1] + 20,c[2],c[3],width=5,fill="yellow",tag="shot")
    loaded_gun = 0

    move_shot("shot")

def move_shot(name):
    global loaded_gun

    canvas.move(name,0,-10)
    canvas.update()

    if loaded_gun == 0:
        shot = canvas.coords(name) # furas

        for x in enemies: # furas

            en = canvas.coords(x) # furas

            if en[0] <= shot[0] <= en[0] + 70: # furas
                if shot[1] <= en[1] + 70: # furas
                    #print(canvas.coords(enemies[x]))
                    canvas.delete(x) # furas
                    #print(canvas.coords(name))
                    enemies.remove(x) # furas
                    canvas.delete(name)
                    loaded_gun = 1
                    break

        if shot[1] < 0: # furas
            canvas.delete(name) # furas
            loaded_gun = 1 # furas

    if loaded_gun == 0: # furas
        window.after(50, move_shot, "shot")

def on_key_press(event):
    global canvas,loaded_gun

    c = canvas.coords("player")

    if event.keysym == 'Left' and c[0] > 0:
        canvas.move("player", -20,0)
    elif event.keysym == 'Right' and c[2] < 1000:
        canvas.move("player", 20, 0)
    elif event.keysym == 'space':
        if loaded_gun == 1:
            shooting()
    elif event.keysym == 'Shift_L':
        loaded_gun = 1
        canvas.delete("shot")

def draw_enemy():
    global enemies

    c = [100,100,170,170]
    inc = 100

    enemies = []

    for x in range(8):
        for y in range(4):
            enemy = canvas.create_rectangle(c[0] + inc * x, c[1] + inc * y,c[2] + inc * x,c[3] + inc * y,fill="red",tag="enemy")
            enemies.append(enemy)

def move_enemy():
    canvas.move("enemy", 0, 20)
    window.after(1000, move_enemy) # furas

#----------------------------------------------------------------------

canvas.create_line(500, 950,500,1000, width=15, fill="red",tag="player")

loaded_gun = 1

draw_enemy()

window.bind_all('<Key>', on_key_press) # furas

move_shot("shot") # furas
move_enemy() # furas

window.mainloop()

rawDescription: Python...Tkinter collisions

description: Python...Tkinter collisions


code:
df['avg(A)|B'] = df.groupby('B')['A'].transform('mean')
df

rawDescription: Add mean of column A for each value of column B


code: " ".join("ab" + "d"*i + "c" for i in range(1, 5))

rawDescription: Can sed write few outputs for the same input?


code:
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns

df = sns.load_dataset("tips")

grid = sns.FacetGrid(df, col="day")
bp = grid.map(sns.barplot,"time",'total_bill','sex')

grid.axes[0][0].legend()

bp.set_titles("{col_name}")
bp.set_ylabels("Time (s)")
bp.set_xlabels("Number")
sns.plt.show()

rawDescription: How to put the legend on first subplot of seaborn.FacetGrid?

description: Put the legend on first subplot of seaborn.FacetGrid


code:
img2 = img.copy()     # Copy the image.
img2[img2 < 128] = 0   # Set all values less than 128 to 0 (black).
img2[img2 >= 128] = 255   # Set all values equal or greater than 128 to 255 (white).
lbl, n = label(img2)

rawDescription: How to label different objects in a non solid black background?

description: Label different objects in a non solid black background


code:
s='auszuschließen…'
s
print(s)
b=s.encode('ascii','xmlcharrefreplace')
b
print(b)
b.decode()
print(b.decode())

rawDescription: Printing escaped Unicode in Python

description: Printing escaped Unicode in Python


code:
# find all blobs and label them
n, labels, stats, _ = cv2.connectedComponentsWithStats(mat)

rawDescription: How to count white pixels in every blob in opencv?

description: Count white pixels in every blob in opencv


code:
import itertools
d = dict(itertools.chain({k:30 for k in [...]}.items(),
                         {k:31 for k in [...]}.items()))

rawDescription: Calling Methods on Python's Dictionary Literals


rawDescription: How to ensure Blob metadata is kept when copying blob in Python App Engine

description: Ensure Blob metadata is kept when copying blob in Python App Engine


code:
HOSTS = ['backup-ros', 'backupa-files', 'print-server1','print-server2']
backups = [x for x in HOSTS if x.startswith('backup-')]
backups

rawDescription: match a substing in a list of substrings

description: Match a substing in a list of substrings


rawDescription: Python conversion from c_double to float


code:
import fileinput

deleted = 0
for line in fileinput.input(inplace=True):
    stripped = line.rstrip()
    deleted += len(line) - len(stripped) + 1  # don't count the newline
    print(stripped)

print("Whitespace deleted: {}".format(deleted))

rawDescription: I'm making a python script that strips whitespace off of the end of lines, but it is only working on the first line


code:
from xml.etree import ElementTree as ET
xx = ET.parse('file.xml')
authorName = xx.findall('.//AuthorName')
for name in authorName:
    nameStr = ' '.join([child.text for child in name])
    print(nameStr)

rawDescription: Python: Append two XML tags

description: Python: Append two XML tags


code:
if key in myDict and innerkey in myDict[key]:
      myDict[key][innerKey] += 1
elif key in myDict:
      myDict[key][innerKey] = 0

rawDescription: Python increment value for dictionary within a dictionary


code:
instruction(priority=priority_value, action=action_value,
            data=data_value, condition=condition_value)

rawDescription: How to handle missing args in python __init__?

description: Handle missing args in python __init__


code:
from SimpleCV import *
from imagegtk import DisplayImage

im = Image("Lenna")
image = im.toRGB.getBitmap()

d = DisplayImage(title="iamgegtk")

label = gtk.Label("Lenna")
d.box.pack_start(label,False,False,0)

but1 = gtk.Button("Quit")
but1.connect("clicked",d.leave_app)
d.box.pack_end(but1,False,False,2)

d.show(image)

rawDescription: How to extend SimpleCV with GUI

description: Extend SimpleCV with GUI


code:
import random

inplay = 0
x = ""
def in_play():
    global inplay, guessesTaken
    guessesTaken = 0
    if inplay == True:
        play()
    else:
        inplay = True
        play()

def play():
    global guessesTaken
    while inplay == True:
        print('Hello! What is your name?')
        myName = input()

    number = random.randint(1, 20)
    print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

    while guessesTaken < 5:
        print('Take a guess.')
        guess = input()
        guess = int(guess)
        guessesTaken = guessesTaken + 1

        if guess < number:
            print('Your guess is too low.')

        elif guess > number:
            print('Your guess is too high.')

        elif guess == number:
            break

    if guess == number:
        guessesTaken = str(guessesTaken)
        print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
        in_play()

    elif guess != number:
        number = str(number)
        print('Nope. The number I was thinking of was ' + number)
        in_play()

in_play()

rawDescription: How do you restart a python guess a number game?

description: Restart a python guess a number game


code:
def insert_line_para_nums(infile, outfile):
    f = open(infile, 'r')
    out = open(outfile, 'w')
    linecount = 0
    paragraphcount = 0
    empty = True
    for i in f:
        if '\n' in i:
            linecount += 1
            if len(i) < 2:
                empty = True
            elif len(i) > 2 and empty is True:
                paragraphcount = paragraphcount + 1
                empty = False
            if empty is True:
                paragraphnumber = 0
            else:
                paragraphnumber = paragraphcount
        out.write('%-4d %4d %s' % (paragraphnumber, linecount, i))
    f.close()
    out.close()

rawDescription: Python Count paragraph

description: Python Count paragraph


code:
import types
def instance_has_method(instance, name):
    try:
        attr = getattr(instance, name)
        return isinstance(attr, types.FunctionType)
    except AttributeError:
        return False

rawDescription: Seeking a different way in using Reflection or Introspection in Python


code:
import struct

struct.unpack('Q', data)

rawDescription: How to convert on python side this eight bytes to number ( unsigned long)?

description: Convert on python side this eight bytes to number ( unsigned long)


code:
import pandas as pd

data = pd.DataFrame({'SessionId': [1, 1, 2, 3, 3, 3, 3],
                     'Query': ['a', 'b', 'a', 'b', 'b', 'c', 'a']})

pd.crosstab(data.SessionId, data.Query).plot.barh(stacked=True)

rawDescription: Pandas stacked bar chart

description: Pandas stacked bar chart


code:
def split_on_crosses(infile, chunk_size):
    head_num = 1  # counter for chunks
    head_file = open('1-head.txt', 'w')  # outport to first head file
    tails = []  # outports to tail files
    with open(infile,'r') as inport:  #open raw data
        for i, line in enumerate(inport, start=1):
            head_file.write(line)
            for t in tails:  # write to all tail files
                t.write(line)
            if i % chunk_size == 0:  # boundary of chunk is reached
                tails.append(open('%s-tail.txt' % head_num, 'w'))  # add one tail file
                head_num += 1
                head_file = open('%s-head.txt' % head_num, 'w')  # switch to next head file

split_on_crosses('infile.txt', 10)

rawDescription: how to get certain line from file using python

description: Get certain line from file using python


code:
def test_that_all_inputs_have_name_attr( self ):
    response = home_page( HttpRequest() )
    from xml.dom.minidom import parseString
    page_as_doc = parseString( response.content )
    inputs = page_as_doc.getElementsByTagName( 'input' )
    for input_el in inputs:
        attr_map = input_el.attributes
        fail_msg = ''
        for i in range( attr_map.length ):
            attr = attr_map.item( i )
            fail_msg += "\nname '%s' value '%s'" % ( attr.name, attr.value )
        if not fail_msg:
            fail_msg = "none!"
        self.assertTrue( input_el.hasAttribute( "name" ), "\nINPUT attributes: %s" % fail_msg )

rawDescription: Django get a DOM object from an HttpResponse


code:
class MyBall:
    @property
    def rect(self):
        return pygame.Rect(round(self.x), round(self.y), *self.size)

    def __init__(self, startingLoc, size, *args, **kwargs):
        self.x = float(startingLoc[0])
        self.y = float(startingLoc[1])
        self.size = size  # Size does not need to be floats, but can be.
          # ...

rawDescription: How do I deal with pixels in pygame?

description: Deal with pixels in pygame


code:
event = Event.objects.get(id=1)
tickets = event.ticket_set.all()

rawDescription: Accessing other models through foreign keys in Django and Python


code:
for seqs in projSeqs:
    seqFileDir = os.path.join(projStorage, seqs)
    seqFileTemplate = os.path.join(seqFileDir, '%s_stringHere.File' % seqs)
    shutil.copyfile(projTemplate, seqFileTemplate)
    shutil.copystat(projTemplate, seqFileTemplate)

rawDescription: Copy template file to multiple directories, query template files for rename based on directory


code:
import sys, time

buf_size = 1024
for counter in xrange(buf_size):
    sys.stdout.write('a')
time.sleep(3)

rawDescription: How can I flush the linux stdio-redirect-buffer of an already running python program?

description: Flush the linux stdio-redirect-buffer of an already running python program


code:
class x(object):
  def __getitem__(self, x): return x

x()[2, 3:6, 4]

rawDescription: Ugly Code: Amusing comment?

description: Ugly Code: Amusing comment


code: NewInput.extend([name, Numid])

rawDescription: Append the value of several variables into a list at the same time


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

# Specify data / labels
y = [3198293, 189910]
xlabels = ['transactional','promotional']
bar_width = 0.90

x = np.arange(len(y))

fig, ax = plt.subplots()
ax.bar(x, y, width=bar_width)
ax.set_xticks(x + (bar_width/2.0))
ax.set_xticklabels(xlabels)
plt.show()

rawDescription: how to draw a simple bar chart with labels in python using matplotlib in python?

description: Draw a simple bar chart with labels in python using matplotlib in python


code:
import urllib
from io import StringIO

class CachedRequest(object):
    def __init__(self, url):
        self._request = urllib.urlopen(url)
        self._content = None

    def __getattr__(self, attr):
        # if attr is not defined in CachedRequest, then get it from
        # the request object.
        return getattr(self._request, attr)

    def read(self):
        if self._content is None:
            content = self._request.read()
            self._content = StringIO()
            self._content.write(content)
            self._content.seek(0)
            return content
        else:
            return self._content.read()

    def seek(self, i):
        self._content.seek(i)

rawDescription: urllib.request: any way to read from it without modifying the request object?

description: Urllib.request: any way to read from it without modifying the request object


code:
import string
# make a sequence of stuff to pickle
stuff = string.ascii_letters
# iterate over the sequence, pickling one object at a time
import pickle
with open('foo.pkl', 'wb') as f:
    for thing in stuff:
        pickle.dump(thing, f)

things = []
f = open('foo.pkl', 'rb')
# load the first two objects
things.append(pickle.load(f))
things.append(pickle.load(f))
# get the remaining pickled items
while True:
    try:
        things.append(pickle.load(f))
    except EOFError:
        break

stuff
things
f.close()

rawDescription: Loading an unknown amount of pickled objects in python


code:
my_dict = {"Polic":("a","c","e"), "Batman":("b","d")}

with open("my/File.txt", "w", encoding='utf-8') as file:
    for k,v in my_dict.items():
        file.write('"{}","{}"\n'.format(k, '","'.join(v)))

rawDescription: Save unbalanced dictionary in txt file

description: Save unbalanced dictionary in txt file


code:
class IconModel(QSqlTableModel):
    def data(self, index, role=Qt.DisplayRole):
        if index.column() == FILENAME_COLUMN_INDEX:
             if role == Qt.DecorationRole:
                  filename = super(IconModel, self).data(index, Qt.DisplayRole)
                  return icon_for_filename(filename)
             elif role == Qt.DisplayRole:
                  return ''
        # Other columns/roles:
        return super(IconModel, self).data(index, role)

rawDescription: How to use a QStyledItemDelegate to render QIcons for a column?

description: Use a QStyledItemDelegate to render QIcons for a column


code:
import re

def explode(s):
    pattern = r'(\w[\w\d_]*)\((.*)\)$'
    match = re.match(pattern, s)
    if match:
        return list(match.groups())
    else:
        return []

rawDescription: Python: splitting a function and arguments


code:
def maxSubArray(seq):
    all_sum = cur_sum = 0
    all_beg = cur_beg = 0
    all_end = 0
    for cur_end, x in enumerate(seq, 1):
        if cur_sum + x > 0:
            cur_sum += x
            if all_sum < cur_sum:
                all_sum = cur_sum
                all_beg, all_end = cur_beg, cur_end
        else:
            cur_sum = 0
            cur_beg = cur_end
    return all_sum, all_beg, all_end

rawDescription: Issue getting the beginning of a max subarray


code:
draw = ImageDraw.Draw(resultImage)
draw.rectangle([0,0,width,height], fill=desiredPixel)

rawDescription: how to change all pixels in a given rectangle

description: Change all pixels in a given rectangle


code:
import numpy as np
W = np.maximum( A, A.transpose() )

rawDescription: Making a numpy ndarray matrix symmetric

description: Making a numpy ndarray matrix symmetric


code:
def diff(v):
    result = []
    for i in range(1, len(v)):
        result.append(v[i] - v[i-1])
    return result

def ismonotone(v, tol=0):
    b = 0
    dv = diff(v)
    if min(dv) >= -tol:
        b = b | 1
    if max(dv) <= tol:
        b = b | 2
    return b

rawDescription: converting matlab code to python code

description: Converting matlab code to python code


code:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling import models

# Create a model
x = np.arange(101) - 50       # x-axis
g1 = models.Gaussian1D(amplitude=2, mean=0, stddev=4)
g2 = models.Gaussian1D(amplitude=3, mean=0, stddev=3)
array1 = g1(x)
array2 = 1 - g2(x)

from scipy.ndimage import convolve1d

conv_array2 = convolve1d(array1, array2)
conv_array2 /= conv_array2.max()

# One can also use numpy convolve here
conv_array = np.convolve(array1, array2, mode='same') # Red curve
conv_array /= max(conv_array) # Normalization

plt.plot(x, array1)
plt.plot(x, array2)
plt.plot(x, conv_array) # Is centered on 0
plt.plot(x, conv_array2) # Is centered on 0
plt.show()

rawDescription: Convolution of symmetric arrays with NumPy: why is the result shifted?


code:
# tested on 1.2.3
form = VoteForm(initial={})
form.fields['field_name'].widget = forms.HiddenInput() # make sure you call widget()

form.as_p() # shows new widget

rawDescription: Python / Django - Edit Model Forms After Creation


code:
temp_dict = {
    'a': OrderedDict([
        ('aardvark', (6,True)),
        ('apple', (3,True)),
    ]),
    'b':OrderedDict([
        ('banana', (2,False)),
        ('bobble', (8,True)),
    ]),
}

rawDescription: Using an OrderedDict within a dictionary declaration


code:
expr = " and ".join(k + "=='" + v + "'" for (k,v) in kwargs.items())
readJson = readJson.query(expr)

rawDescription: Query data using pandas with kwargs

description: Query data using pandas with kwargs


code:
with open("/path/to/storage/file", "w") as f:
    for row in cursor:
        f.write(row['your_field'])

rawDescription: Writing huge Mongo result set to disk w/ Python in a resource friendly way


code:
connStr = (
    r"Driver={Microsoft Access Driver (*.mdb)};"
    r"Dbq=C:\whatever\mydatabase.mdb;"
    r"SystemDB=C:\whatever\mydatabase.mdw;"
    r"UID=yourUserName;"
    r"PWD=yourPassword;"
    )

rawDescription: Using Python to manipulate an Access database protected with UserName and Password


code:
#!/usr/bin/env python2
import fnmatch
import itertools
import os

ignore_dir = lambda d: d in ('.git', '.svn', '.hg')
src_dir = '/Volumes/Mac OS Drive/Data/input/' # source directory
dst_dir = '/path/to/destination/'        # destination directory
for root, dirs, files in os.walk(src_dir):
    for input_file in fnmatch.filter(files, "*.input"): # for each input file
        output_file = os.path.splitext(input_file)[0] + '.output'
        output_dir = os.path.join(dst_dir, root[len(src_dir):])
        if not os.path.isdir(output_dir):
            os.makedirs(output_dir) # create destination directories
        analyze(os.path.join(root, input_file), # perform analysis
                os.path.join(output_dir, output_file))

    # don't visit ignored subtrees
    dirs[:] = itertools.ifilterfalse(ignore_dir, dirs)

rawDescription: Recreate input folder tree for output of some analyses


code:
import bitstring
stream=bitstring.BitStream()
stream.append("int:32=4")
stream.append("int:16=10")
stream.append("int:8=24")
stream
stream.bytes

rawDescription: Python byte buffer object?

description: Python byte buffer object


code:
import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame()

df['x'] = random.sample(range(1, 100), 25)
df['y'] = random.sample(range(1, 100), 25)

L = []
for i in range(25):
    L.append('longlonglabel' + str(i))

df.index = L
cg = sns.clustermap(df)

# Iterate over the labels
for text in cg.ax_heatmap.get_yticklabels():
    text.set_rotation('horizontal')

plt.show()

rawDescription: Clustering a pandas dataframe with seaborn - overlapping labels


code:
import requests
files = {'file': open('happy.txt', 'rb')}
url = "http://tempsend.com/send"
r = requests.post(url, data={'expire':'2678400'}, files=files)
r.url

rawDescription: How to add form-data variables to a post request using python requests module?

description: Add form-data variables to a post request using python requests module


code:
def load_extension(self, module_str):
        """Load an IPython extension by its module name.
        Returns the string "already loaded" if the extension is already loaded,
        "no load function" if the module doesn't have a load_ipython_extension
        function, or None if it succeeded.
        """
        if module_str in self.loaded:
            return "already loaded"

        from IPython.utils.syspathcontext import prepended_to_syspath

        with self.shell.builtin_trap:
            if module_str not in sys.modules:
                with prepended_to_syspath(self.ipython_extension_dir):
                    __import__(module_str)
            mod = sys.modules[module_str]
            if self._call_load_ipython_extension(mod):
                self.loaded.add(module_str)
            else:
                return "no load function"

rawDescription: How %load_ext work in ipython

description: How %load_ext work in ipython


code: "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s." % {'name': "Mike", 'nickname': "Goose"}

rawDescription: Passing a dictionary into a string in python


code:
import random
print('\n'.join("%s is %s"%(i_got_this_from_stackoverflow, "odd" if i_got_this_from_stackoverflow%2 else "even")for i_got_this_from_stackoverflow in random.sample(list(range(int(input("Please enter the lower bound of the numbers: ")), int(input("Please enter the upper bound of the numbers: ")))), 20)))

rawDescription: Generate 20 random integers and indicate whether each number is odd or even


code: sorted(data, key = lambda item : float(item["AveragePoints"]), reverse = True)

rawDescription: Python sorted method treats two digit string as three digit string


code:
import PyQt4.QtGui as gui

app = gui.QApplication([])

w = gui.QWidget()

gl = gui.QGridLayout(w)

lab = gui.QLabel(text='Nom')
gl.addWidget(lab,0,0)

le = gui.QLineEdit(text='BarsCond')
gl.addWidget(le,0,1)

##########################

hl = gui.QHBoxLayout()
label_1 = gui.QLabel(text='Offset')
OffsetCond = gui.QLineEdit(text='-1')
hl.addWidget(label_1)
hl.addWidget(OffsetCond)

gl.addLayout(hl,0,2)

############################

pb1 = gui.QPushButton(text='BarsC')
gl.addWidget(pb1,1,0)

cb = gui.QComboBox()
gl.addWidget(cb,1,1)

pb2 = gui.QPushButton(text='NBars')
gl.addWidget(pb2,1,2)

w.show()
app.exec_()

rawDescription: PyQt4: nesting two elements into one cell


code:
import json

call_record = {} # To create an empty dictionary
call_record["source1"] = {} # To append an empty dictionary to the key "source1"
call_record["source1"]["destination11"] = [] # An empty array as value for "destination11"
call_record["source1"]["destination11"].append("datetime1", "datetime2") # To append element datetime1 and datetime2 to destination11 array
call_record_json = json.dumps(call_record, ensure_ascii=False)

rawDescription: Adding keys with empty values and then adding values in a nested format in python


code:
from tkinter import *
from functools import partial

class omniAnaliz(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.text_vars=[]  ## text widget id's
        self.screen()

    def screen(self):
        ctr=0
        for txt in ['1D D6 F8 F0 C3 08 04 00 62 63 64 65 66 67 68 69',
                '30 F0 F8 D6 1D 64 64 01 00 71 1D 9F 00 1D 9F 00',
                'a, b, c, 1, 2, 4']:
            t = Text(self, height=1, width=50)
            t.pack(side="bottom")
            t.insert(END, txt)
            t.configure(state="disabled")
            t.bind("<Button-3>", partial(self.hex2dec, ctr))
            ## first ID is item[0], 2nd text widget is item[1], etc.
            self.text_vars.append(t)
            ctr += 1

        self.label_text=StringVar()
        self.label_text.set("Nothing yet")
        self.l1 = Label(self, textvariable=self.label_text)
        self.l1.pack(side='top')

    def hex2dec(self, widget_num, event):
        this_text_widget=self.text_vars[widget_num]
        self.label_text.set(this_text_widget.get(SEL_FIRST, SEL_LAST))

root = Tk()
omniAnaliz(root).pack()
root.mainloop()

rawDescription: How to get selected text in multiple text widget in python?

description: Get selected text in multiple text widget in python


code:
def get_free_device_name(instance):
    all_device_names = ["/dev/xvd%s" % (x) for x in ascii_lowercase]
    device_list = instance.block_device_mappings
    used_device_names = set()
    for device in device_list:
        used_device_names.add([device['DeviceName']])
    return list(set(all_device_names) - used_device_names).pop()

rawDescription: boto3 show next available device name on instance

description: Boto3 show next available device name on instance


code:
import random

while True:
    right = 0
    wrong = 0

    for i in range(10):

            x = random.randint (2,29)
            y = random.randint (3,29)
            z = (x*y)
            qq = input("What's " + str(x) + " times " + str(y) + "? ")

            if   str(z) == str(qq):
                 right = right +1
                 print ("Correct!\n")

            else:
                wrong = wrong + 1
                print ("Wrong the correct answer is ",str(z),"\n")

    print ("You got", right, "out of 10 questions")

    if right==10:
            print ("Well Done! Perfect score!")

    elif right>=5:
            print ("Well done! try getting perfect score next time")

    else:
            print ("Noob")
    #################################################
    restart = "y"
    yess = input ("Would you like to try again? y/n?")
    if restart != yess:
        break;

rawDescription: python while loop, im stuck help! :C

description: Python while loop, im stuck help! :C


rawDescription: stacking unequal matrices in python

description: Stacking unequal matrices in python


code:
class PlaylistViewSet(viewsets.ModelViewSet):
    serializer_class = PlaylistSerializer
    lookup_field = 'id'

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)

rawDescription: Django Rest Framework setting default PrimaryKeyRelated field value?


code:
import cgi
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
f = form['file'].file
# You can use `f` as a file object: f.read(...)

rawDescription: Handle file from WSGI request

description: Handle file from WSGI request


code:
import re
string = 'ltrim(rtrim(to_char(base_field_name, format))) renamed_field_name'
rx = re.compile('^(.*?\()*(.+?)(,.*?)*(,|\).*?)*$')
rx.search(string).group(2)
rx.search('base_field_name').group(2)

rawDescription: recursive nested expression in Python

description: Recursive nested expression in Python


code:
for i in range(len(data)):
  if i >= 2148 and i <= 3505:
    if data[i][0] == 146: # assuming each data element is a 3 element tuple
     data[i][0] += 1

rawDescription: How to only select and edit set ranges of values

description: Only select and edit set ranges of values


rawDescription: How do I check HTTP headers of an incoming request to Google Appengine in Python?

description: Check HTTP headers of an incoming request to Google Appengine in Python


rawDescription: Isolate the first number after a letter with regular expressions


rawDescription: Python: multiplication override

description: Python: multiplication override


code:
def init_db(filename=':memory:'):

    db = sqlite3.connect(filename)
    db.execute("CREATE TABLE Alerts (SID INT, Signature TEXT)")
    return db

db = init_db()

someFunction() # Function generates a nested list i.e. ALL
db.executemany("INSERT INTO Alerts (SID, Signature) VALUES (?,?)", (ALL))

c = db.cursor()
c.execute('SELECT SID, count(*) as CountOf from Alerts group by SID')
result=c.fetchall()

rawDescription: sqllite3 not grouping by count

description: Sqllite3 not grouping by count


code:
def ReadAndMerge():
    library1filename = input("Enter 1st filename to read and merge:")
    with open(library1filename, 'r') as library1:
        library1contents = library1.read()

    library2filename = input("Enter 2nd filename to read and merge:")
    with open(library2, 'r') as library2:
        library2contents = namelibrary2.read()

    print(library1contents)
    print(library2contents)

    combined_contents = library1contents + library2contents  # concatenate text

    print(combined_contents)

    combined_filename = "combined.txt"    # ask user for name here?
    with open(combined_filename, "w") as combined_file:
        combined_file.write(combined_contents)

rawDescription: libraries or database concatenation

description: Libraries or database concatenation


code:
my_row = data_column.query.filter_by(dc_name=myNewName).first()

# delete the row from db session if it exists
if my_row is not None:
    db.session.delete(my_row)
    db.session.commit()

rawDescription: sqlalchemy in flask: how to " delete .. where ... "?

description: Sqlalchemy in flask: how to " delete .. where ... "


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2)

for i in range(4):
    inner = gridspec.GridSpecFromSubplotSpec(2, 1,
                    subplot_spec=outer[i], wspace=0.1, hspace=0.1)

    for j in range(2):
        ax = plt.Subplot(fig, inner[j])
        t = ax.text(0.5,0.5, 'outer=%d, inner=%d' % (i,j))
        t.set_ha('center')
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)

fig.show()

rawDescription: Matplotlib - adding subplots to a subplot?


code: shell.SendKeys(u"When Unicode characters are pasted here, harmony shall hopefully ensue".encode("utf-16le"), 0)

rawDescription: Unicode SendKeys Alternative (Any programming language)


code:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
s.setblocking(False)
local_ip_address = s.getsockname()[0]
print(local_ip_address)  # prints 10.0.2.40

rawDescription: Find my server ip address with Twisted

description: Find my server ip address with Twisted


code:
def DriverSpeed (): # No parameters here...
    DriverSpeed = int(input("Enter Driver Speed: "))
    return DriverSpeed

def OverOrUnderSpeedLimit (number):
    UnderSpeedLimet = False
    if DriverSpeed(number) < int(50) ==0: # you gave it a parameter here...
        OverSpeedLimet = True
    return SpeedLimet

rawDescription: PYTHON: TypeError: DriverSpeed() takes 0 positional arguments but 1 was given


rawDescription: Python turtle get tkinter root

description: Python turtle get tkinter root


code:
class EducationalClass(models.Model):
    students = models.ManyToManyField(User)

rawDescription: Django: Store List of Users in model?

description: Django: Store List of Users in model


code:
def bubble_sort_2nd_value(tuples_list):

    NEWLIST = []
    itemMoved=0
    for i in tuples_list:
        NEWLIST.append(i)
    for i in range(len(NEWLIST)):
         for j in range(i+1, len(NEWLIST)):
             if(NEWLIST[j][1]<NEWLIST[i][1]):
                 itemMoved=1
                 NEWLIST[j],NEWLIST[i] = NEWLIST[i],NEWLIST[j]

    if(itemMoved==0): print("None")
    else: print(NEWLIST)

tuples_list = [("h1",1),("h2",2),("h3", 3), ("hi" , 4)]

bubble_sort_2nd_value(tuples_list)

rawDescription: python3.3 bubble sort: returning None if list already sorted

description: Python3.3 bubble sort: returning None if list already sorted


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

driver = webdriver.Chrome(executable_path=r"C:\Users\xx\xx\xx\xx\xx\xx\chromedriver.exe")
driver.get("http://wogcc.state.wy.us/urecordsMenu.cfm?Skip=%27Y%27&oops=ID14447")
assert "Download Menu" in driver.title
form = driver.find_element_by_xpath("/html/body/table[2]/tbody/tr[7]/td/form/table[1]/tbody/tr[3]/td[2]/select/option[37]")
submit = driver.find_element_by_xpath("/html/body/table[2]/tbody/tr[7]/td/form/table[1]/tbody/tr[3]/td[1]/font/img")

ActionChains(driver).move_to_element(form).click(form).perform()
ActionChains(driver).move_to_element(submit).click(submit).perform()

rawDescription: Retrieve a zip file from a website in an automated script


code:
import Tkinter as tk

class PasswordTest(object):
    ''' Password Entry Demo '''
    def __init__(self):
        root = tk.Tk()
        root.title("Password Entry Demo")

        self.entry = e = tk.Entry(root)
        e.pack()
        e.bind("<Key>", self.entry_cb)

        b = tk.Button(root, text="show", command=self.button_cb)
        b.pack()

        root.mainloop()

    def entry_cb(self, event):
        #print(`event.char`, event.keycode, event.keysym )
        self.entry.config(show='')
        #Hide text after 1000 milliseconds
        self.entry.after(1000, lambda: self.entry.config(show='*'))

    def button_cb(self):
        print('Contents:', repr(self.entry.get()))

PasswordTest()

rawDescription: Python's tkinter smart entry password

description: Python's tkinter smart entry password


code:
class MyHandler(CGIHTTPServer.CGIHTTPRequestHandler):

    # Disable logging DNS lookups
    def address_string(self):
        return str(self.client_address[0])

handler = MyHandler

rawDescription: How to disable reverse dns lookup in python webserver?

description: Disable reverse dns lookup in python webserver


rawDescription: Is it possible to name the x and y axes in a matplotlib hexbin diagram?


code:
class Foo:
     x = 42

f = Foo()
g = Foo()

g.x = 99

print(f.x, g.x)

rawDescription: In python if a instance data attribute has the same name as the class data attribute, then can we access both for such an object


code:
app = Tk()
f = Frame(app,bg="yellow",width=50,height=50)
f.grid(row=0,column=0,sticky="NW")
f.grid_propagate(0)
f.update()
l = Label(f,text="123",bg="yellow")
l.place(x=25, y=25, anchor="center")
app.mainloop()

rawDescription: Tkinter: Center label in frame of fixed size?


code:
import re
import string

''.join(map(lambda x: string.lowercase[len(x) - 1], re.findall(r'\s+', 'hello all  the   world')))
# 'abc'

rawDescription: number of space between each word

description: Number of space between each word


code:
from bokeh.plotting import figure, HBox, output_file, show, VBox, ColumnDataSource
from bokeh.models import Range1d, HoverTool
from collections import OrderedDict
import random

xscale = zip(levelsdf2[('series1', 'Start')], levelsdf2[('series1', 'Stop')])
xscale2 = zip(levelsdf2[('series2', 'Start')], levelsdf2[('series2', 'Stop')])
yscale2 = zip([9.2 for x in range(len(levelsdf2[(name, 'Start')]))],[9.2 for x in range(len(levelsdf2[(name, 'Start')]))])

TOOLS="pan,wheel_zoom,box_zoom,reset,hover"
output_file("linesandquads.html")
hover_tips = levelsdf2.index.values
colors = ["#%06x" % random.randint(0,0xFFFFFF) for c in range(len(xscale))]
proc1 = 'Log'
proc2 = 'MazF2h'
expression1 = levelsdf2[(proc1, 'Level')]
expression2 = levelsdf2[(proc2, 'Level')]
source = ColumnDataSource(
    data=dict(
        start=[min(xscale[x]) for x in range(len(xscale))],
        stop=[max(xscale[x]) for x in range(len(xscale))],
        start2=[min(xscale2[x]) for x in range(len(xscale2))],
        stop2=[max(xscale2[x]) for x in range(len(xscale2))],
        gene=hover_tips,
        colors=colors,
        expression1=expression1,
        expression2=expression2,

    )
)

p1 = figure(plot_width=900, plot_height=500,y_range=[8,10.5],tools=TOOLS)
p1.quad(left="start", right="stop", top=[9.211 for x in range(len(xscale))],
        bottom = [9.209 for x in range(len(xscale))], source=source, color="colors")

p1.multi_line(xscale2,yscale2, source=source, color="colors", line_width=20)

hover = p1.select(dict(type=HoverTool))

hover.tooltips = OrderedDict([
    (proc1+" (start,stop, expression)", "(@start| @stop| @expression1)"),

    ("Gene","@gene"),
])

show(p1)

rawDescription: Bokeh hovertool in multiple_line plot

description: Bokeh hovertool in multiple_line plot


code:
def drop_alpha(s):
    return ''.join(itertools.compress(
            s, itertools.cycle([True, True, True, False])))
drop_alpha('12345678')

rawDescription: Quickly take every n values from string python


code:
model = sm.tsa.ARMA(y, (2, 2))
results = model.fit()
results.predict()

rawDescription: python statsmodels: "params" parameter for predict function of arima models

description: Python statsmodels: "params" parameter for predict function of arima models


code:
args = argp.parse_args()
args.o = open(args.o,'w')

rawDescription: When using argparse, should validation and initialization happen in custom types or actions?


code:
lines = data.replace('*', ',').splitlines()
''.join(line for line in lines if line and not line.startswith('>')).rstrip(',')

rawDescription: convertion of format in python

description: Convertion of format in python


code:
import numpy as np
A = np.ndarray(shape=(2,2), dtype=float, order='F')
B = np.ndarray(shape=(2,2), dtype=float, order='F')
C = np.ndarray(shape=(2,2), dtype=float, order='F')
D = np.ndarray(shape=(2,2), dtype=float, order='F')

T = np.array([[A,B],[C,D]])

rawDescription: Matrix of array creation in numpy

description: Matrix of array creation in numpy


code:
# Increase a picture given an offset, a color and the anciant
# content must be centered or not.
# Offsets must be positive.
def increaseAndCopy(pic, offsetX, offsetY, bg_color=black, center=True):

  # Offsets must be positive
  if (offsetX < 0.0) or (offsetY < 0.0):
    printNow("Error: Offsets must be positive !")
    return None

  new_w = pic.getWidth() + int(2*offsetX)
  new_h = pic.getHeight() + int(2*offsetY)

  startX = 0
  startY = 0
  if (center) and (offsetX > 1.0):
    startX = int(offsetX)
  if (center) and (offsetY > 1.0):
    startY = int(offsetY)

  new_pic = makeEmptyPicture(new_w, new_h)
  # Fill with background color
  setAllPixelsToAColor(new_pic, bg_color)

  # Process copy
  for x in xrange(pic.getWidth()):
    for y in xrange(pic.getHeight()):
      px = getPixel(pic, x, y)
      new_px = getPixel(new_pic, x + startX, y + startY)
      setColor(new_px, getColor(px))

  return new_pic

file = pickAFile()
picture = makePicture(file)

# Pass an offset of 0.5 to increase by 1 pixel
#new_picture = increaseAndCopy(picture, 0.5, 0, blue)
new_picture = increaseAndCopy(picture, 10, 20, gray, True)

if (new_picture):
  writePictureTo(new_picture, "/home/biggerPic.png")
  show(new_picture)

rawDescription: Increasing image width by one pixel

description: Increasing image width by one pixel


code:
mongo_keys = ["location.coords", "name"]
for k in mongo_keys:
    do_something(mongo_result[k])

rawDescription: Pymongo auto sort the input dictionary

description: Pymongo auto sort the input dictionary


code:
location_list = Locations.objects\
                 .filter(organisation=organisation_id)\
                 .order_by('country_of_location')
output = '<br />'.join([str(loc.organisation)+' from '+str(loc.organisation.country_of_origin) for loc in location_list])

rawDescription: Djangonic way to get second order DB-info in Django?


code:
from collections import namedtuple, Counter
# You can probably think of a better name than this
datum = namedtuple('datum', 'Posit R B G')
Counter(tuple(datum(**d) for d in a) for a in data).most_common()
# You might actually want to make the conversion permanent;
# the data is possibly easier to work with that way given the
# fixed key structure, and it should save memory too

rawDescription: Counting most common list in list of (list of dictionaries)


code:
text = "seeking help on possible homework task"
raw_words = text.split(" ")

positive_words = ['seeking','help']
negative_words = ['homework']

positive_score = len([word for word in raw_words if word in positive_words])
negative_score = len([word for word in raw_words if word in negative_words])

total_score = positive_score - negative_score

rawDescription: Classification based on List of Words Python


code:
# in urls.py
url(r'^custom-reset/$', 'myapp.views.custom_password_reset', name='custom_password_reset'),

# in views.py
from django.contrib.auth.views import password_reset
def custom_password_reset(request, *args, **kwargs):
    # Do your custom processing of the args and kwargs
    return password_reset(request, *args, **kwargs)

rawDescription: Can we pass and over ride the values of django built_in method paremeters?


code:
with open(filename) as f:
   lines=f.readlines()

d=dict()
for line in lines:
  line=line.strip()
  if line:
     (k,v)=line.split(":", 1)
     d[k]=v

print("%s: %s" % (d['Package'], d['Version']))

rawDescription: Is there a way to concatenate separated string values in a .txt file using Python?


code:
class PrevNextMixin(object):
    def get_prev_next(self):
        objects = list(self.__class__.objects.all())

rawDescription: Django getting objects from a mixin

description: Django getting objects from a mixin


code:
query = r.table('yelp_user').filter({"name":"Arthur"})
for row in query.run(connection):
    print(row)

rawDescription: Printing the response of a RethinkDB query in a reasonable way


code:
import numpy as np
import numpy.ma as ma

randomArray = np.random.random_integers(0, 10, (5, 5, 5))
maskingValues = [1, 2, 5]
maskedRandomArray = ma.MaskedArray(randomArray, np.in1d(randomArray, maskingValues))

rawDescription: Mask 3D numpy array where array is equal to a list of values


code:
class BaseModel:
    created_at = ndb.DateTimeProperty(auto_now_add=True)
    modified_at = ndb.DateTimeProperty(auto_now=True)

class User(BaseModel, EndpointsModel):
    username = ndb.StringProperty(required=True)

rawDescription: Subclass properties don't appear when extending EndpointsModel


code:
from scipy.stats import genextreme
shape = -0.5
loc = 0.0
scale = 2.5
x = np.linspace(scale/shape, 20, 200)
y = genextreme.cdf(x, shape, loc, scale)
import matplotlib.pyplot as plt
plt.plot(x, y, label="GEV CDF")
plt.legend(loc='best')

rawDescription: Plot Cumulative Distribution Function from shape, scale, and location parameters


code:
class ObjectiveDetails(models.Model, FillableModelWithLanguageVersion):
    user = models.ForeignKey(User)
    language_version = models.ForeignKey('LanguageVersion')
    field = models.TextField(null=False, blank=False, max_length=5000)
    objective_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False)
    objective_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False)

    class Meta:
        ordering = ['language_version', 'id']

class LanguageVersion(models.Model):
    """Language version selection for a user"""
    user = models.ForeignKey(User)
    language_code = models.CharField(max_length=32)
    language_code_disabled = models.BooleanField(default=False)
    language_version_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False)
    language_version_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False)  # the date the language version is updated when the user changes their subscription type.

    class Meta:
        ordering = ['language_code']

rawDescription: django models.py ordering using foreign field

description: Django models.py ordering using foreign field


code:
def main():
    while True:
        try:
            (f, r) = function_one()
            (x, z) = function_two(f, r)
            function_three(x, z)
        except WhateverErrors:
            break

rawDescription: How do I loop a sequence of functions in Python?

description: Loop a sequence of functions in Python


code:
bin_addr = results.reply_tree.reply[n]['answer']['rdata']['ipv4_address']
string_addr = '.'.join(map(str, map(ord, bin_addr)))

rawDescription: how do you make an IPv4 address printable with the getdnsapi python API?

description: Make an IPv4 address printable with the getdnsapi python API


code:
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self.archorlist = []

    def handle_starttag(self, tag, attrs):
        if tag == 'a' and 'href' in attrs:
            self.anchorlist.append(attrs['href'])

rawDescription: confused with HTMLParser attribute

description: Confused with HTMLParser attribute


code:
re.findall("_\\w+_", 'sdsd _sdsd_ sdsd sdsd _sssssssss_')
re.findall("_\\w+_", '')

rawDescription: Regex search return result or empty

description: Regex search return result or empty


code:
import jellyfish
jellyfish.levenshtein_distance('jellyfish', 'smellyfish')

rawDescription: String similarity in Python

description: String similarity in Python


code:
def getLoc(ar):
    cursor = conn.execute("SELECT location.name FROM area,location WHERE area.name = ?", (ar,))

rawDescription: Can not get my parameter to work inside SELECT WHERE clause in python


code:
"""
Before this code, there goes soup xml document generation. Except part, I mentioned in topic, we just create empty options tags in document, thus, creating almost done document.
Right after that, with this little script, we will use basic python provided element tree methods.
"""

import xml.etree.ElementTree as ET

ET_tree = ET.parse("exported_file.xml")
# Here we import exactly the same file, we opened with soup. Exporting can be done in different file, if you wish.
ET_root = ET_tree.getroot()

for position, opt in enumerate(item.find('options')):
# Position is pretty important, as this will remove 'counter' thing in for loop, I was using in code in first example. Position will be used for getting out exact items from array, which works like template for our option tag names.
    opt.set('name', str(array[position]))
    opt.text = 'text'
# Same way, with position, we can get data from relevant array, provided, that they are inherited or connected in same way.

tree = ET.ElementTree(ET_root).write('exported_file.xml',encoding="UTF-8",xml_declaration=True)
# This part was something, I researched before quite lot. This code will help save xml document with utf-8 encoding, which is very important.

rawDescription: Chosing next relative in Python BeautifulSoup with automation


code:
import logging

sqla_logger = logging.getLogger('sqlalchemy')
sqla_logger.propagate = False
sqla_logger.addHandler(logging.FileHandler('/path/to/sqla.log'))

rawDescription: How to suppress sqlalchemy.engine.base.Engine logging to stdout?

description: Suppress sqlalchemy.engine.base.Engine logging to stdout


code:
import os
from shutil import copy2

SOURCE = "c:\\source\\"

DEST = "c:\\dest\\"

# Iterate recursively through all files and folders under the source directory
for path, dirs, files in os.walk(SOURCE):
    # For each directory iterate over the files
    for f in files:
        # Grab the first letter of the filename
        starting_letter = f[0].upper()
        # Construct the full path of the current source file
        source_path = os.path.join(path, f)
        # Construct the destination path using the first letter of the
        # filename as the folder
        dest_path = os.path.join(DEST, starting_letter)
        # Create the destination folder if it doesn't exist
        if not os.path.isdir(dest_path):
            os.makedirs(dest_path)
        # Copy the file to the destination path + starting_letter
        copy2(source_path, dest_path)

rawDescription: Moving files by starting letter in powershell, python or other scripting language running windows


code: dataset = Dataset(title="Sheet name")

rawDescription: How do I add sheet name for each datasheet in an XLS file generated from "tablib"?

description: Add sheet name for each datasheet in an XLS file generated from "tablib"


code:
if r == (self.endpoint[0]*2) and c == (self.endpoint[1]*2):
    return True
if self.reverselist[r][c] != ' ':
    return False

# mark the current attempt as on the route
self.setStar(r,c)

# don't need to setStar or setExplan anywhere while
# trying moves - the recursive functions will do that
if self.solver(r-1,c):
    return True
if self.solver(r,c+1):
    return True
if self.solver(r,c-1):
    return True
if self.solver(r+1,c):
    return True

# if we reach here then there is no solution found from
# the current r, c so mark it as ! for backtracking
self.setExplan(r,c)

return False

rawDescription: Python Maze Recursion

description: Python Maze Recursion


code:
from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.ticker import MultipleLocator, FuncFormatter
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

for dir in ax.axis:
    ax.axis[dir].set_visible(dir.endswith("zero"))

ax.set_xlim(-.35,.4)
ax.set_ylim(-.25,.45)
ax.set_aspect('equal')

tick_format = lambda x, i: '' if x == 0.0 else '%.1f' % x
for a in [ax.xaxis, ax.yaxis]:
    a.set_minor_locator(MultipleLocator(0.02))
    a.set_major_formatter(FuncFormatter(tick_format))

theta = np.arange(2*np.pi/3,6*np.pi,0.01)
r = 1 / theta

ax.plot(r*np.cos(theta), r*np.sin(theta), lw=2)

plt.show()
raw_input()

rawDescription: polar plot in python

description: Polar plot in python


rawDescription: Convert nested dictionary into dataframe


code:
def nop(x):
    return x

rawDescription: Using lambdas in a function within a function


code:
from Tkinter import *
import Forecast

class Frames(object):

    def __init__(self):
        pass

    def main_frame(self, root):
        root.title('WeatherMe')
        root.geometry('300x100')

        self.query = StringVar()

        Label(root, text='Enter a city below').pack()

        Entry(root, textvariable=self.query).pack()

        Button(root, text="Submit", command=self.result_frame).pack()

    def result_frame(self):
        result = Toplevel()
        result.title('City')
        result.geometry('1600x150')

        print(self.query.get()) #This would print the StringVar's value , use this in whatever way you want.

        forecast = Forecast.GetWeather('City Here').fetch_weather()

        Label(result, text='1-3 DAY: \n' + forecast[0]).pack()
        Label(result, text='4-7 DAY: \n' + forecast[1]).pack()
        Label(result, text='8-10 DAY: \n' + forecast[2]).pack()

        Button(result, text="OK", command=result.destroy).pack()

root = Tk()
app = Frames()
app.main_frame(root)
root.mainloop()

rawDescription: Passing variables between two windows Tkinter


code:
timeit.timeit("sum([1 for i in permutations([1, 2, 3, 4, 5])])", setup="from itertools import permutations", number=1000)
timeit.timeit("sum([1 for i in perms([1, 2, 3, 4, 5])])", setup="from test import perms", number=1000)

rawDescription: Fastest permutations implementation in Python


code: return self.decode('ASCII')

rawDescription: How to correctly inherit from str?

description: Correctly inherit from str


rawDescription: Deleting rows in numpy array between boundaries


code:
numToBaseB(1024,2)
numToBaseB(4,2)

rawDescription: str() not returning string in my function

description: Str() not returning string in my function


code:
import socks
import socket

# Can be socks4/5
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4,'127.0.0.1', 9050)
socket.socket = socks.socksocket

# Magic!
def getaddrinfo(*args):
    return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo

import urllib

rawDescription: DNS over proxy?

description: DNS over proxy


code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *

app = QApplication(sys.argv)

# Create a stack with 2 webviews
stack = QStackedWidget()
mapper = QSignalMapper(stack)
mapper.mapped[int].connect(stack.setCurrentIndex)
for i in range(2):
    web = QWebView(stack)
    stack.addWidget(web)
    # When a webview finishes loading, switch to it
    web.loadFinished[bool].connect(mapper.map)
    mapper.setMapping(web, i)

# load the page in the non visible webview
stack.widget(1).load(QUrl("http://myapp.example.com"))
stack.show()

sys.exit(app.exec_())

rawDescription: How to double buffering a WebKit page using QWebView and PySide?

description: Double buffering a WebKit page using QWebView and PySide


code:
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Main(QWidget):

    def __init__(self):
        super(Main, self).__init__()
        self.setupUI()

    def setupUI(self):
        self.label = QLabel('0')

        okBtn = QPushButton('Start Foo')
        okBtn.clicked.connect(self.startFoo)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.label)
        mainLayout.addWidget(okBtn)
        self.setLayout(mainLayout)

        self.setWindowTitle('Main')

    def startFoo(self):
        foo = Foo()
        foo.exec_()
        self.label.setText(str(foo.edit.text()))

class Foo(QDialog):

    def __init__(self):
        super(Foo, self).__init__()
        self.setupUI()
        self.var = 0

    def setupUI(self):

        # QLineEdit
        self.edit = QLineEdit()

        # QPushButton
        okBtn = QPushButton('OK')
        okBtn.clicked.connect(self.setVar)

        # main layout
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.edit)
        mainLayout.addWidget(okBtn)
        self.setLayout(mainLayout)

        self.setWindowTitle('Foo')

    def setVar(self):
        self.var = self.edit.text()
        self.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Main()
    ex.show()
    app.exec_()

rawDescription: Suspend the current function until the dialog is closed


code:
precompiled = []
for phrase in phrases:
    b1, b2 = str(phrase).strip().split(" ")
    precompiled.append(b1+"_"+b2, re.compile(r"%s\ *\t*\n*%s"%(b1,b2), re.IGNORECASE))

for (input, output) in ...:
    with open(output,"w") as o:
        with open(input) as i:
            data = i.read()
            for (pattern, regex) in precompiled:
                data = regex.sub(pattern, data)
            o.write(data)

rawDescription: Python: Faster regex replace

description: Python: Faster regex replace


code:
try:
    input = raw_input
except NameError:
    pass

rawDescription: Backwards-compatible input calls in Python


code:
#!/usr/bin/python2.5
from email.utils import parsedate
import mailbox

def extract_date(email):
    date = email.get('Date')
    return parsedate(date)

the_mailbox = mailbox.mbox('/path/to/mbox')
sorted_mails = sorted(the_mailbox, key=extract_date)
the_mailbox.update(enumerate(sorted_mails))
the_mailbox.flush()

rawDescription: How can I reorder an mbox file chronologically?

description: Reorder an mbox file chronologically


code:
import lxml.html

a = "AAA: BBB

Text: WahtIwant
"
root = lxml.html.fromstring(a)
[x.tail for x in root.xpath('//font[@size="2"]/parent::b')]

rawDescription: grabbing value from html by xpath in python

description: Grabbing value from html by xpath in python


rawDescription: Using pop for removing element from 2D array


code:
from collections import defaultdict

d = defaultdict(set)

with open('somefile.txt') as thefile:
   for line in the_file:
      if line.strip():
          value, key = line.split('|')
          d[key].add(value)

for k,v in d.iteritems():  # use d.items() in Python3
    print('{} - {}'.format(k, len(v)))

rawDescription: Count unique values per unique keys in python dictionary


rawDescription: Python, sort a list by another list

description: Python, sort a list by another list


code:
self.UsrName = QLineEdit("username")
self.UsrName.mousePressEvent = lambda event: self.UsrName.clear()

rawDescription: How can i create my own SIGNAL and channel it to a SLOT?

description: Create my own SIGNAL and channel it to a SLOT


code:
def remRow(self, row):
    self.gridlayout.removeWidget(self.entries[row])
    self.entries[row].deleteLater()
    del self.entries[row]

rawDescription: Is there any way to remove a QWidget in a QGridLayout?


code:
import os
resourcesdir = os.path.join(os.path.dirname(__file__), 'Resources')

rawDescription: Applescript - pygame, application bundle


code:
import os
import zipfile

dir = "C:/Test/002"

# get list of all subdirectories in the directory
subdirs = [subdir for subdir in os.listdir(dir) if os.path.isdir(os.path.join(dir, subdir))]

# create a zip archive for each subdirectory
for subdir in subdirs:
    zf_name = "C:/" + subdir + ".zip"
    zf = zipfile.ZipFile(zf_name, mode='w')
    for dirpath,dirs,files in os.walk(os.path.join(dir, subdir)):
        for f in files:
            fn = os.path.join(dirpath, f)
            zf.write(fn)

rawDescription: Create individual archives from individual folders with Zipfile


code:
import numpy as np
from scipy.spatial.distance import pdist, squareform

#create n x d matrix (n=observations, d=dimensions)
A = np.array([[1,9,2,4], [1,2,3,1]]).T

# explicitly calculate the whole n x n distance matrix
dist_mat = squareform(pdist(A, metric="euclidean"))

# mask the diagonal
np.fill_diagonal(dist_mat, np.nan)

# and calculate the minimum of each row (or column)
np.nanmin(dist_mat, axis=1)

rawDescription: array of minimum euclidian distances between all points in array

description: Array of minimum euclidian distances between all points in array


code:
import lxml.etree as ET

fin = '''\
<root>
  <e>
    <head>
       <id>3</id>
       <word>abandon</word>
    </head>
    <body>
       <head>
          <word>accept</word>
       </head>
    </body>
  </e>
</root>'''

root = ET.fromstring(fin)
word = root.xpath('.//word[not(ancestor::body)]')
print(ET.tostring(word[0]))
# <word>abandon</word>

rawDescription: (xpath in python) I'd like to select a node which doesn't have "body" as its ancestor


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.http import Request
from scrapy.selector import *

from scrapy.item import Item, Field

class CraiglistSampleItem(Item):
    title = Field()
    link = Field()
    description = Field()

class MySpider(CrawlSpider):
    name = "craigs"
    allowed_domains = ["craigslist.org"]
    start_urls = ["http://minneapolis.craigslist.org/moa/"]

    rules = (Rule(SgmlLinkExtractor(allow=("index\d00\.html", ), restrict_xpaths=('//p[@class="nextpage"]',))
        , callback="parse_items", follow=True),
    )

    def parse_items(self, response):
        hxs = HtmlXPathSelector(response)

        titles = hxs.select("//span[@class='pl']")
        for title in titles:
            item = CraiglistSampleItem()
            item["title"] = title.select("a/text()").extract()[0]
            item["link"] = title.select("a/@href").extract()[0]

            url = "http://minneapolis.craigslist.org%s" % item["link"]
            yield Request(url=url, meta={'item': item}, callback=self.parse_item_page)

    def parse_item_page(self, response):
        hxs = HtmlXPathSelector(response)

        item = response.meta['item']
        item['description'] = hxs.select('//section[@id="postingbody"]/text()').extract()
        return item

rawDescription: Scrapy Recursive download of Content

description: Scrapy Recursive download of Content


rawDescription: Merge specific column into dataframe

description: Merge specific column into dataframe


code:
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
bucket_location = bucket.get_location()
if bucket_location:
    conn = boto.s3.connect_to_region(bucket_location)
    bucket = conn.get_bucket(bucket_name)

rawDescription: Boto get s3 bucket location

description: Boto get s3 bucket location


code:
def every_second():
    global currency, cps, root
    currency.set(currency.get() + cps.get())
    root.after(1000, every_second)

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

rawDescription: Update a variable every second in Python?


rawDescription: A condition in an array, Python

description: A condition in an array, Python


code:
import sys, glob, win32api, os

pdfLoc = sys.argv[1]
try:
    copies = int(sys.argv[2])
except:
    copies = 1

for pdfname in glob.glob(os.path.join(pdfLoc, "*.pdf")):
    fullpath = os.path.join(pdfLoc, pdfname)
    for copy in range(copies):
        win32api.ShellExecute(0, "print", pdfname, None, ".", 0)

rawDescription: Using a Loop to print copies, Python

description: Using a Loop to print copies, Python


code:
handlers = self.log.handlers[:]
for handler in handlers:
    handler.close()
    self.log.removeHandler(handler)

rawDescription: python does not release filehandles to logfile

description: Python does not release filehandles to logfile


code:
left,right = a.split('=', 1)
answer = left.split('::')[1:] + [right]

rawDescription: Matching two almost similar string (python)


code:
# Multi-for generator expression allows us to create a flat iterable of words
all_words = (word for bigram in _bigrams for word in bigram.split())

def no_runs_of_words(words):
    """Takes an iterable of words and returns one with any runs condensed."""
    prev_word = None
    for word in words:
        if word != prev_word:
            yield word
        prev_word = word

final_string = ' '.join(no_runs_of_words(all_words))

rawDescription: Merging or reversing n-grams to a single string


code:
import random

bitstring = "100111001101010101010101"
print("old genome :  " + bitstring)
newGenome="".join(["10"[int(bit)] if random.random() < 0.05 else bit for bit in bitstring])
print("new genome :  " + newGenome)

rawDescription: Unable to mutate an iterated string

description: Unable to mutate an iterated string


code:
from timecode import Timecode

tc1 = Timecode('29.97', '00:04:22:04')
tc2 = Timecode('30', frames=tc1.frames)

rawDescription: Converting timecodes

description: Converting timecodes


code:
for t in list_of_tuples:
    t[1].sort()

rawDescription: Format a nested list in place

description: Format a nested list in place


code:
a = "this is the right string"
b = "this is right the string"

sum([1 for i,v in zip(a.split(), b.split()) if i == v])

rawDescription: Python - Most efficient way to compare # of words sequenced in "right" order across two strings/lists


code:
if os.path.isdir(path):
    path = os.path.join(path, "")

rawDescription: can os.path.join (or other python method) append a '/' automatically for the case of the directory?

description: Can os.path.join (or other python method) append a '/' automatically for the case of the directory


code:
# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QLabel

class ChildDlg(QDialog):
   def closeEvent(self, event):
      print("X is clicked")

class mainClass(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        openDlgBtn = QPushButton("openDlg", self)
        openDlgBtn.clicked.connect(self.openChildDialog)
        openDlgBtn.move(50, 50)

        self.setGeometry(100, 100, 200, 200)
        self.show()

    def openChildDialog(self):
        childDlg = ChildDlg(self)
        childDlgLabel = QLabel("Child dialog", childDlg)

        childDlg.resize(100, 100)
        childDlg.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mc = mainClass()
    sys.exit(app.exec_())

rawDescription: How to detect dialog's close event?

description: Detect dialog's close event


code:
a  = etree.Element("a")
b  = etree.SubElement(a, "b")
c  = etree.SubElement(a, "c")
d1 = etree.SubElement(c, "d")
d2 = etree.SubElement(c, "d")
tree = etree.ElementTree(c)
print(tree.getpath(d2))
tree.xpath(tree.getpath(d2)) == [d2]

rawDescription: Getting the Path of an XML Node in Python


rawDescription: Pandas compare two dataframes and remove what matches in one column


code:
def writeScore(name, score):

    name = str(name)
    score = str(score)

    if name in b:
        index = b.index(name)
        f.seek(0,0)
        with open('oldscores.txt', 'a') as f2:
            f2.write(a[index])
        if index == (len(b)-1):
            newscore = a[index].rstrip("\n").split(" ")
            newscore[3] = score
            a[index] = " ".join(newscore)
        else:
            newscore = a[index].rstrip("\n").split(" ")
            newscore[3] = score + "\n"
            a[index] = " ".join(newscore)
        for i in a:
            f.write(i)
    else:
        f.write("\nname: {} score: {}".format(name, score))

with open('scores.txt', 'r+') as f:
    a = f.readlines()
    b = [i.split(" ")[1] for i in a]
    writeScore(PLAYERNAME,SCORE) # Enter the name of the player and the score in here.

rawDescription: Find name in file and then replace their score in python


code:
class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

rawDescription: Creating an Instance of a Class with a variable in Python


code:
def foo(bar, spam=[]):
    spam.append(bar)
    print(spam)

foo
foo('Monty')
foo('Python')
foo.func_defaults
del foo
foo

rawDescription: Lifetime of default function arguments in python


code:
class ReloadableItemLoader(ItemLoader):
    def __init__(self, *args, **kwargs):
        super(ReloadableItemLoader, self).__init__(*args, **kwargs)

        for key, value in self.item.iteritems():
            self._add_value(key, value)

rawDescription: scrapy Itemloader: how to load with Item()/dict

description: Scrapy Itemloader: how to load with Item()/dict


code:
class ScoredList():
    def __init__(self, dct=None):
        self.dct = dct if dct is not None else {}

rawDescription: Python default / optional Variables

description: Python default / optional Variables


code:
for i in range(sheet.nrows):
     row = sheet.row_values(i)
     for j in range(len(row)):
          if row[j] == search_value:
                return i,j
return None

rawDescription: python xlrd string match

description: Python xlrd string match


code:
import sys

val = 0
for looper in range(1, 10):
    val += 1
    sys.stdout.write("\r%d" % (val))
    sys.stdout.flush()
    time.sleep(1) # sleep added so that you can see the effect

rawDescription: How to replace text on python shell

description: Replace text on python shell


code:
class Deck:
    def __init__(self, cards):
        self.cards = cards
l0 = [1, 2, 3]
d1 = Deck(l0)
d2 = Deck(l0)
d1.cards
d2.cards
d1.cards.append(4)
d2.cards

rawDescription: strange object instance behaviour in unittest

description: Strange object instance behaviour in unittest


code:
class A (object):
  def __init__(self):
    pass

class B (A):
  def __init__(self):
    super(B, self).__init__()

class C (B):
  def __init__(self):
    super(C, self).__init__()

rawDescription: Why python super does not accept only instance?


code:
data = [{'category': 'nestedloops', 'title': 'Number Puzzle I', 'url': 'number-puzzle-i.html', 'n': '087', 'points': '60', 'key': 'numberpuzzles1'}, {'category': 'nestedloops', 'title': 'Getting Individual Digits', 'url': 'getting-individual-digits.html', 'n': '088', 'points': '80', 'key': 'gettingindividualdigits'}]
ordering = {'key': 0, 'url': 1, 'title': 2, 'category': 3,
            'flags': 4, 'points': 5, 'n': 6}
outlist = []
for d in data:
    outlist.append([])
    for k in sorted(d.keys(), key=lambda k: ordering[k]):
        outlist[-1].append(json.dumps({k: d[k]}))

for i, l in enumerate(outlist):
    outlist[i] = "{" + ",".join((s[1:-1] for s in outlist[i])) + "}"

s = "[" + ",".join(outlist) + "]"

rawDescription: custom JSON sort_keys order in Python

description: Custom JSON sort_keys order in Python


code:
def delPage(self, pageTitle):
    for index in range(self.dataNoteBook.GetPageCount()):
        if self.dataNoteBook.GetPageText(index) == pageTitle:
            self.dataNoteBook.DeletePage(index)
            self.dataNoteBook.SendSizeEvent()
            break

rawDescription: How to delete a notebook page?

description: Delete a notebook page


rawDescription: How to change cursor shape of QPlainTextEdit (Pyqt, PySide)

description: Change cursor shape of QPlainTextEdit (Pyqt, PySide)


code:
# TODO Use name and key that works for you.
my_processes['de_DE@euro'] = Popen(args1, stdout=PIPE, stderr=PIPE, env={'LANG':'de_DE@euro','TZ':'Europe/Berlin'})

rawDescription: possible to generate a dynamic variable?

description: Possible to generate a dynamic variable


code:
q1 = pyes.TermQuery("title", "rainbow")
q2 = pyes.TermQuery("artist", "kermit")
query = BooleanQuery(must=[q1, q2])
search = pyes.Search(query)
results = conn.search(search, index_name, doc_type)

rawDescription: How to use TermQuery to do an AND query across multiple terms?

description: Use TermQuery to do an AND query across multiple terms


rawDescription: Python filter tuples with different sizes


code:
matrix1 = [[1+x+y*rowCount for x in range(rowCount)] for y in range(columnCount)]
matrix1

rawDescription: python oneline to create matrix of given order

description: Python oneline to create matrix of given order


code:
import pandas as pd
import numpy as np
from lmfit import Model

df = pd.DataFrame({
  'A'      : pd.Series([1, 1, 1, 2, 2, 2, 2]),
  'B'      : pd.Series([5, 4, 6, 6, 5, 6, 5]),
  'target' : pd.Series([87.79, 40.89, 215.30, 238.65, 111.15, 238.65, 111.15])
})

def fun(A, B, p1 = 1, p2 = 1):
  return p1 * np.exp(A) + p2 * np.exp(B)

model = Model(fun, independent_vars=['A', 'B'])
fit = model.fit(df['target'], A = df['A'], B = df['B'])

rawDescription: Using multiple independent variables in Python lmfit


code:
B = A[:]  #makes a copy of only the first level of the mutable
B = copy(A)  #same as above, returns a 'shallow copy' of A
B = deepcopy(A)  #copies every element in the mutable, on every level

rawDescription: unexpected behaviour with variables definition in python

description: Unexpected behaviour with variables definition in python


code:
db.define_table(
    'stock_data',
    Field('company_id', db.company),
    Field('years_id', db.years),
    Field('equity', 'integer'),
    format = '%(equity)s %(years_id)s -> %(company_id)s')

matching_company_id = db.stock_data.company_id == request.vars.company_id
unique_company_year = IS_NOT_IN_DB(db(matching_company_id), 'stock_data.years_id')
db.stock_data.years_id.requires = IS_IN_DB(db, 'years.id', db.years._format,
                                           _and=unique_company_year)

rawDescription: How do I "link" a web2py database?

description: "link" a web2py database


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

plt.figure(figsize=(10,5))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

#make some sample data
x = np.linspace(-5,5,200)
X,Y = np.meshgrid(x,x)
Z = 100*np.cos(np.sqrt(x**2 + Y**2))**2 + 50

np.random.seed(1)
for i in range(0,11):
    #Add some hot pixels
    Z[np.random.randint(low=0,high=199),np.random.randint(low=0,high=199)]= np.random.randint(low=200,high=255)
    #and dead pixels
    Z[np.random.randint(low=0,high=199),np.random.randint(low=0,high=199)]= np.random.randint(low=0,high=10)

#And some hot pixels in the corners and edges
Z[0,0]   =255
Z[-1,-1] =255
Z[-1,0]  =255
Z[0,-1]  =255
Z[0,100] =255
Z[-1,100]=255
Z[100,0] =255
Z[100,-1]=255

#Then plot it
ax1.set_title('Raw data with hot pixels')
ax1.imshow(Z,interpolation='nearest',origin='lower')

def find_outlier_pixels(data,tolerance=3,worry_about_edges=True):
    #This function finds the hot or dead pixels in a 2D dataset.
    #tolerance is the number of standard deviations used to cutoff the hot pixels
    #If you want to ignore the edges and greatly speed up the code, then set
    #worry_about_edges to False.
    #
    #The function returns a list of hot pixels and also an image with with hot pixels removed

    from scipy.ndimage import median_filter
    blurred = median_filter(Z, size=2)
    difference = data - blurred
    threshold = 10*np.std(difference)

    #find the hot pixels, but ignore the edges
    hot_pixels = np.nonzero((np.abs(difference[1:-1,1:-1])>threshold) )
    hot_pixels = np.array(hot_pixels) + 1 #because we ignored the first row and first column

    fixed_image = np.copy(data) #This is the image with the hot pixels removed
    for y,x in zip(hot_pixels[0],hot_pixels[1]):
        fixed_image[y,x]=blurred[y,x]

    if worry_about_edges == True:
        height,width = np.shape(data)

        ###Now get the pixels on the edges (but not the corners)###

        #left and right sides
        for index in range(1,height-1):
            #left side:
            med  = np.median(data[index-1:index+2,0:2])
            diff = np.abs(data[index,0] - med)
            if diff>threshold:
                hot_pixels = np.hstack(( hot_pixels, [[index],[0]]  ))
                fixed_image[index,0] = med

            #right side:
            med  = np.median(data[index-1:index+2,-2:])
            diff = np.abs(data[index,-1] - med)
            if diff>threshold:
                hot_pixels = np.hstack(( hot_pixels, [[index],[width-1]]  ))
                fixed_image[index,-1] = med

        #Then the top and bottom
        for index in range(1,width-1):
            #bottom:
            med  = np.median(data[0:2,index-1:index+2])
            diff = np.abs(data[0,index] - med)
            if diff>threshold:
                hot_pixels = np.hstack(( hot_pixels, [[0],[index]]  ))
                fixed_image[0,index] = med

            #top:
            med  = np.median(data[-2:,index-1:index+2])
            diff = np.abs(data[-1,index] - med)
            if diff>threshold:
                hot_pixels = np.hstack(( hot_pixels, [[height-1],[index]]  ))
                fixed_image[-1,index] = med

        ###Then the corners###

        #bottom left
        med  = np.median(data[0:2,0:2])
        diff = np.abs(data[0,0] - med)
        if diff>threshold:
            hot_pixels = np.hstack(( hot_pixels, [[0],[0]]  ))
            fixed_image[0,0] = med

        #bottom right
        med  = np.median(data[0:2,-2:])
        diff = np.abs(data[0,-1] - med)
        if diff>threshold:
            hot_pixels = np.hstack(( hot_pixels, [[0],[width-1]]  ))
            fixed_image[0,-1] = med

        #top left
        med  = np.median(data[-2:,0:2])
        diff = np.abs(data[-1,0] - med)
        if diff>threshold:
            hot_pixels = np.hstack(( hot_pixels, [[height-1],[0]]  ))
            fixed_image[-1,0] = med

        #top right
        med  = np.median(data[-2:,-2:])
        diff = np.abs(data[-1,-1] - med)
        if diff>threshold:
            hot_pixels = np.hstack(( hot_pixels, [[height-1],[width-1]]  ))
            fixed_image[-1,-1] = med

    return hot_pixels,fixed_image

hot_pixels,fixed_image = find_outlier_pixels(Z)

for y,x in zip(hot_pixels[0],hot_pixels[1]):
    ax1.plot(x,y,'ro',mfc='none',mec='r',ms=10)

ax1.set_xlim(0,200)
ax1.set_ylim(0,200)

ax2.set_title('Image with hot pixels removed')
ax2.imshow(fixed_image,interpolation='nearest',origin='lower',clim=(0,255))

plt.show()

rawDescription: Automatically remove hot/dead pixels from an image in python


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

# something random to plot
data = (np.random.random(10000)*10)**3

# log-scaled bins
bins = np.logspace(0, 3, 50)
widths = (bins[1:] - bins[:-1])

# Calculate histogram
hist = np.histogram(data, bins=bins)
# normalize by bin width
hist_norm = hist[0]/widths

# plot it!
plt.bar(bins[:-1], hist_norm, widths)
plt.xscale('log')
plt.yscale('log')

rawDescription: Scaled logarithmic binning in python

description: Scaled logarithmic binning in python


code:
df
df
df.a = df.a.astype('category')
df.dtypes

rawDescription: create categorical variables by condition in python with pandas or statsmodels

description: Create categorical variables by condition in python with pandas or statsmodels


code:
import xml.etree.ElementTree as ET

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

xml = '''<vehicleTravelTimeMeasurements>
        <vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
            <start link="1" pos="3.864983"/>
            <end link="3" pos="23.275375"/>
        </vehicleTravelTimeMeasurement>
        <vehicleTravelTimeMeasurement name="" no="3">
            <start link="1" pos="3.864983"/>
            <end link="2" pos="13.275375"/>
        </vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>'''

root = ET.fromstring(xml)
new = ET.Element("vehicleTravelTimeMeasurement", name = "kkk", no = "4")
newsub1 = ET.SubElement(new, "start", link = "1", pos="3.88888")
newsub2 = ET.SubElement(new, "end",link = "3", pos = "3.88888")
root.insert(2, new)
indent(root)
with open('test.xml', 'w') as f:
    f.write(ET.tostring(root))

rawDescription: add element in a existing xml file python

description: Add element in a existing xml file python


code: itertools.combinations(list, r)

rawDescription: Python: create a polynomial of degree n

description: Python: create a polynomial of degree n


code:
my_keys = ["Hello", "World"]
my_values1 = ["Why", "that"]

my_dict1 = dict(zip(my_keys, my_values1))

my_dict2 = dict.fromkeys(my_dict1.keys())

rawDescription: Make unlimited versions of a dict, same keys, different values


code:
pipelines = []

match = {
    'discussion_id': {
        '$in': discussion_ids
    }
}

if start and end:
    match['created_at'] = {
        '$gte': start,
        '$lt': end
    }

pipelines.append({ '$match': match })

if order:
    pipelines.append({ '$sort': { 'created_at': order } })

pipelines.append({ '$project': { 'poster_id': '$poster_id' } })
pipelines.append({ '$group': { '_id': '$poster_id', 'post_id': { '$first': '$_id' } } })

if skip:
    pipelines.append({ '$skip': skip })

if limit:
    pipelines.append({ '$limit': limit })

results = self.db.posts.aggregate(pipelines)

rawDescription: Distinct sorting and grouping with MongoDB aggregation framework


code:
import numpy as np
arr1 = np.arange(5).reshape(5, 1)
arr2 = np.arange(5, 10).reshape(1, 5)
arr1
arr2
arr1.reshape(arr2.shape)
arr2.reshape(arr1.shape)

rawDescription: Change the shape of an array using another array


code:
from pylab import plot, show, savefig, xlim, figure, \
                hold, ylim, legend, boxplot, setp, axes

# function for setting the colors of the box plots pairs
def setBoxColors(bp):
    setp(bp['boxes'][0], color='blue')
    setp(bp['caps'][0], color='blue')
    setp(bp['caps'][1], color='blue')
    setp(bp['whiskers'][0], color='blue')
    setp(bp['whiskers'][1], color='blue')
    setp(bp['fliers'][0], color='blue')
    setp(bp['fliers'][1], color='blue')
    setp(bp['medians'][0], color='blue')

    setp(bp['boxes'][1], color='red')
    setp(bp['caps'][2], color='red')
    setp(bp['caps'][3], color='red')
    setp(bp['whiskers'][2], color='red')
    setp(bp['whiskers'][3], color='red')
    setp(bp['fliers'][2], color='red')
    setp(bp['fliers'][3], color='red')
    setp(bp['medians'][1], color='red')

# Some fake data to plot
A= [[1, 2, 5,],  [7, 2]]
B = [[5, 7, 2, 2, 5], [7, 2, 5]]
C = [[3,2,5,7], [6, 7, 3]]

fig = figure()
ax = axes()
hold(True)

# first boxplot pair
bp = boxplot(A, positions = [1, 2], widths = 0.6)
setBoxColors(bp)

# second boxplot pair
bp = boxplot(B, positions = [4, 5], widths = 0.6)
setBoxColors(bp)

# thrid boxplot pair
bp = boxplot(C, positions = [7, 8], widths = 0.6)
setBoxColors(bp)

# set axes limits and labels
xlim(0,9)
ylim(0,9)
ax.set_xticklabels(['A', 'B', 'C'])
ax.set_xticks([1.5, 4.5, 7.5])

# draw temporary red and blue lines and use them to create a legend
hB, = plot([1,1],'b-')
hR, = plot([1,1],'r-')
legend((hB, hR),('Apples', 'Oranges'))
hB.set_visible(False)
hR.set_visible(False)

savefig('boxcompare.png')
show()

rawDescription: matplotlib: Group boxplots

description: Matplotlib: Group boxplots


code:
import transaction

def redirect_to_trial(trans, obj=None, parent=None):
    if obj.id not in parent:
        request = getattr(obj, 'REQUEST', None)
        if request:
            trial_url = obj.__parent__.__parent__.absolute_url()
            request.response.redirect(trial_url)

@grok.subscribe(ISite, IObjectRemovedEvent)
def on_site_delete(obj, event):
    kwargs = dict(
        obj = obj,
        parent = event.oldParent,
    )
    transaction.get().addAfterCommitHook(redirect_to_trial, kws=kwargs)

rawDescription: Plone: reacting to object removal

description: Plone: reacting to object removal


code:
def fizzbuzz(n):
    result = []
    for x in range(1, n+1):
        if x % 3 == 0 and x % 5 == 0:
            result.append("fizz buzz")
        elif x % 3 == 0:
            result.append('fizz')
        elif x % 5 == 0:
            result.append('buzz')
        else:
            result.append(str(x))
    return result

def main():
    print(', '.join(fizzbuzz(20)))

main()

rawDescription: Trying to turn fizzbuzz into a function in python 3


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

def rand_data():
    return np.random.uniform(low=10., high=20., size=(5000,))

# Generate data.
x1 = rand_data()

# Define histogram params.
binwidth = 0.25
x_min, x_max = x1.min(), x1.max()
bin_n = np.arange(int(x_min), int(x_max + binwidth), binwidth)

# Obtain histogram.
hist1, edges1 = np.histogram(x1, bins=bin_n)
# Normalization parameter.
param = 5.

# Create arrays adding elements so plt.bar will plot the first and last
# vertical bars.
x2 = np.concatenate((np.array([0.]), edges1))
y2 = np.concatenate((np.array([0.]), (hist1 / param), np.array([0.])))

# Plot histogram normalized by the parameter defined above.
plt.xlim(min(edges1) - (min(edges1) / 10.), max(edges1) + (min(edges1) / 10.))
plt.bar(x2, y2, width=binwidth, color='none', edgecolor='b')
plt.step(x2, y2, where='post', color='r', ls='--')

plt.show()

rawDescription: Plot histogram normalized by fixed parameter


code:
from itertools import islice
for x in islice(L, 1, None): # start=1, stop=None
    print(x)

rawDescription: Create an iterator from a certain point

description: Create an iterator from a certain point


code:
import datetime

class DailyPost(ndb.Model):
  user = ndb.KeyProperty(kind=User)
  content = ndb.StringProperty()
  #created = ndb.DateTimeProperty(auto_now_add=True)

class GetOrCreateHandler(webapp2.RequestHandler):
  def get(self):
    user = self.session.get_user() # user from session (pseudo code)
    _id = '%s.%s' % (user.id, datetime.date.today().strftime('%s'))
    DailyPost.get_or_insert(_id, user=user, content='bla')
    self.response.write(post.content)

rawDescription: how to limit number of entity. google app engine

description: Limit number of entity. google app engine


code:
@property
def attr(self):
    return self._attr

@property.setter
def attr(self, value):
    self._attr = value

# legacy access to the attr property
def GetAttr(self):
   warnings.warn("deprecated", DeprecationWarning)
   return self.attr

def SetAttr(self, value):
   warnings.warn("deprecated", DeprecationWarning)
   self.attr = value

rawDescription: Is is possible to determine if a method was called via a property in Python3?


code:
with open('input', 'rb') as f:
    data = f.read()
data = list(data)
data = [byte + 1 for byte in data]
data = bytes(data)
# If this is all you're going to do, you could just do this:
# data = bytes((byte + 1) % 256 for byte in data)
with open('output', 'wb') as f:
    f.write(data)

rawDescription: How to Write List if Hex Values to a File Python


code:
df["D"] = pd.rolling_mean(df["C"], window=3, center=True, min_periods=2)
df

rawDescription: Pandas moving window over rows

description: Pandas moving window over rows


code:
type_buy_order_list = []
for order in volume_buy_order_list:
    if order[3] == "limit":
        type_buy_order_list.append(order)
    if order[3] == "liquid":
        type_buy_order_list.append(order)
    if order[3] == "conditional":
        type_buy_order_list.append(order)

rawDescription: Django: Sort object by string attribute non-alphabetically


code:
dataset = dict()
# first, if we use `with` then file will be closed automatically
with open('text1.txt', 'r') as f:
    # when we want to just iterate over file lines, we can omit `readlines` and use this simple syntax
    for line in f:
        # strip() is important, because each line we read ends with '\n' character - and we want to strip it off.
        # partition() returns tuple of left-part, separator and right-part,
        # but we don't need that separator value so we assign it to a dummy variable.
        # rpartition() is better choice if name may contain ':' character in it.
        name, _, value = line.strip().rpartition(':')
        if name not in dataset:  # newly encountered name?
            # here we create a new `list` holding our value
            dataset[name] = [value]
        else:
            # append the value to existing list
            dataset[name].append(value)

# now print out resulting data
for name, values in dataset.items():
    print(':'.join([name] + values))

rawDescription: Python - Read from text file and amalgamate information


code:
class App(object):
    def __init__(self, args):
        ...
        self.args = self._parse_arguments(args)
        ...

    def _parse_arguments(args):
        parser = argparse.ArgumentParser()
        ...
        result = parser.parse_args(args)
        return result

rawDescription: where to position argparse in code

description: Where to position argparse in code


code:
options = [
    {'vehicle': 'Car', 'destination': 'Ghana', 'coeff': 0.3},
    {'vehicle': 'Van', 'destination': 'Nigeria', 'coeff': 0.2},
    {'vehicle': 'Truck', 'destination': 'Togo', 'coeff': 0.33},
    {'vehicle': 'Van', 'destination': 'Kenya', 'coeff': 0.17},
    {'vehicle': 'Truck', 'destination': 'Somalia', 'coeff': 0.31},
]
while True:
    print("Vehicle Shipping Rates to Africa")
    for i, opt in enumerate(options):
        print("%i. %s to %s" % (i+1, opt['vehicle'], opt['destination']))
    option = options[int(raw_input("Enter the choice:"))]
    value = float(raw_input("Enter the car price:"))
    cost = value / option['coeff']
    print("It would cost $%s to ship a %s that cost $%s to %s." % (cost, option['vehicle'], value, option['destination']))
    print("Vehicle price you entered: %s" % value)
    print("Shipping cost: %s" % cost)
    again = raw_input("Would you like to choose another selection, Y=Yes or N=No.")
    if again.lower() == 'n':
        break
print("Thank you our application.")

rawDescription: Converting Pseudo Code To Python

description: Converting Pseudo Code To Python


code:
import os
import numpy as np

result = None
for root, dirs, files in os.walk('.', topdown = True):
    for filename in files:
        with open(os.path.join(root, filename), 'r') as f:
            data = np.genfromtxt(f, unpack=True, names=True, dtype=None)
        if result is None:
            result = data
        else:
            result = np.vstack((result, data))

print(result[:10]) # print first 10 lines
np.save('/tmp/outfile.npy', result)

rawDescription: How can i combine several database files with numpy?

description: Combine several database files with numpy


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

mean = [10,12,16,22,25]
variance = [3,6,8,10,12]

x = np.linspace(0,40,1000)

for i in range(4):
    sigma = np.sqrt(variance[i])
    y = mlab.normpdf(x,mean[i],sigma)
    plt.plot(x,y, label=r'$v_{}$'.format(i+1))

plt.xlabel("X")
plt.ylabel("P(X)")
plt.axvline(x=15, ymin=0, ymax=1,ls='--',c='black')

plt.legend()
plt.show()

rawDescription: Writing variables as subscripts in math mode


code: pygame.transform.scale(screenPrescaled, (1920, 1080), window)

rawDescription: Pygame (Python) Scale Transform Slow

description: Pygame (Python) Scale Transform Slow


code:
truncate_date = connection.ops.date_trunc_sql('day','timestamp')
qs = qs.extra({'date':truncate_date})
return qs.values('date').annotate(Sum('amount')).order_by('date')

rawDescription: Django - get distinct dates from timestamp


code:
from lxml import etree

xml_input = 'Input.xml'
xml_output = 'Output.xml'

with open(xml_input) as xml:
   root = etree.XML(xml.read())

#create dictionary where key is an ID and value is a list of nodes with the ID
node_dict = {}
for node in root.xpath('//*[@ID]'):
   try:
      node_dict[node.get('ID')].append(node)
   except KeyError:
      node_dict[node.get('ID')] = [node]

for key, nodes in node_dict.iteritems():
   #find all nodes with childs
   nodes_with_childs = [node for node in nodes if len(node.xpath('./*')) > 0]

   #leave only first node with childs, remove other nodes
   if len(nodes_with_childs) > 0:
      for node in set(nodes) - set([nodes_with_childs[0]]):
         node.getparent().remove(node)
   else:
      #leave only first node, remove other nodes
      for node in nodes[1:]:
         node.getparent().remove(node)

with open(xml_output, 'w') as xml:
   xml.write(etree.tostring(root, xml_declaration=True))

rawDescription: Remove Duplicate entries from XML files, based on the condition.


code:
# ...
infile.close()

channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal'}
re_dis = re.compile(r'displacement\s[-+]?[0-9]*\.?[0-9]+')

for material, values in materials.items():
    lx.eval('select.item {Matr: %s} set textureLayer' % material)
    uvmap = materials[material]['uvmap']
    for v in values:
        m = re_dis.match(v)
        if m or v in channels.keys():
            lx.eval('shader.create constant')
            lx.eval('item.setType imageMap textureLayer')
            imagepath = materials[material][v]
            imagename = os.path.splitext(os.path.basename(imagepath))[0]
            lx.eval('clip.addStill {%s}' % imagepath)
            lx.eval('texture.setIMap {%s}' % imagename)
            if m:
                # we can't auto map to the channels dict
                lx.eval('shader.setEffect %s' % 'displace')
            else:
                lx.eval('shader.setEffect %s' % channels[v])

rawDescription: Match specific string + any float number in python


code:
while True:
    s = input('Enter something : ')
    if s == 'quit':  # Do this check first
        break
    elif len(s) > 3:  # Then see if the input is too long
        print('too big')
        continue
    print('something')

rawDescription: Python - what to do when you can't use the break statement?


code:
import requests

headers = {'content-type': 'text/xml; charset=utf-8'}
response = requests.post(url, data="<data>the data is here</data>", headers=headers)
fd = open("filename.xml", "w")
fd.write(response.text)
fd.close()

rawDescription: Python equivalent of curl for posting data from file


code:
def deafultHighlight(self, argument):
    self.content = self.text.get("1.0", tk.END)
    self.lines = self.content.split("\n")

    if (self.previousContent != self.content):
        self.text.mark_set("range_start", self.row + ".0")
        data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

        for token, content in lex(data, PythonLexer()):
            self.text.mark_set("range_end", "range_start + %dc" % len(content))
            self.text.tag_add(str(token), "range_start", "range_end")
            self.text.mark_set("range_start", "range_end")

    self.previousContent = self.text.get("1.0", tk.END)

rawDescription: Improve Pygments Syntax Highlighting Speed for Tkinter Text


code:
generator = email.generator.Generator(out_file)
generator.flatten(msg)

rawDescription: Save an email.Message object into a file


code:
def take(dictionary, key):
    return {key: dictionary[key]}

R = take(D, k)

rawDescription: "Slice" out one element from a python dictionary


rawDescription: wxPython on Mac OS X: creating a wx.Frame without stealing focus

description: WxPython on Mac OS X: creating a wx.Frame without stealing focus