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

fig = plt.figure()

ax = plt.axes(xlim=(0, 2), ylim=(0, 100))

N = 4
lines = [plt.plot([], [])[0] for _ in range(N)]

def init():
    for line in lines:
        line.set_data([], [])
    return lines

def animate(i):
    for j,line in enumerate(lines):
        line.set_data([0, 2], [10 * j,i])
    return lines

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()

rawDescription: Defining multiple plots to be animated with a for loop in matplotlib


code:
current_enemy = random.choice(enemy)
encounter(current_enemy)
# ...
if choice=="Attack":
  print(name,choice,"s",current_enemy,".","You deal",dmg,"damage","to it.")
# etc...

rawDescription: Using previous random string in python

description: Using previous random string in python


code:
from poster.encode import MultipartParam

iter_encode = MultipartParam.iter_encode.im_func  # function object
iter_encode.func_defaults = (8192,)  # set new defaults, a 1-element tuple

rawDescription: Python poster buffer size

description: Python poster buffer size


code:
access = set(['John', 'Jane', 'Jack', 'Janice'])

if (user_input in access):
    print ('Allow in!')
else:
    print ('Deny!')

rawDescription: Looking for elements in a set

description: Looking for elements in a set


code:
tree = your_qtreewidget  # replace every 'tree' with your QTreeWidget
strings = list_of_strings
l = []  # list of QTreeWidgetItem to add
for i in strings:
    l.append(QTreeWidgetItem(i))  # create QTreeWidgetItem's and append them
tree.addTopLevelItems(l)  # add everything to the tree

rawDescription: Adding a row to QTreeWidget

description: Adding a row to QTreeWidget


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

data = {}
data['dataset1'] = {}
data['dataset2'] = {}
data['dataset3'] = {}

n = 500
for k,v in data.iteritems():
    upper = random.randint(0, 1000)
    v['A'] = np.random.uniform(0, upper, size=n)
    v['B'] = np.random.uniform(0, upper, size=n)
    v['C'] = np.random.uniform(0, upper, size=n)

fig, axes = plt.subplots(ncols=3, sharey=True)
fig.subplots_adjust(wspace=0)

for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
    ax.boxplot([data[name][item] for item in ['A', 'B', 'C']])
    ax.set(xticklabels=['A', 'B', 'C'], xlabel=name)
    ax.margins(0.05) # Optional

plt.show()

rawDescription: how to make a grouped boxplot graph in matplotlib

description: Make a grouped boxplot graph in matplotlib


code:
def read_file():
    jd_records = []
    file_name = "test.csv"
    with open(file=file_name, mode='rt') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)
        incsv = csv.reader(inf, delimiter=",")

        if has_header:
            next(incsv)

        for row in incsv:
            jd_records.append(row)
            line_num += 1
            if not line_num % 10000:
                yield jd_records
                del jd_records[:]

        if jd_records:
            yield jd_records

rawDescription: how to yield 10000 lines of a file in python?

description: Yield 10000 lines of a file in python


code:
search = [u'']
bool(search)

rawDescription: Django query parameters not returning None


code:
for sublist in A:
    for index, value in enumerate(sublist[1]):
        if value == '-':
            sublist[1][index] = B[index]

rawDescription: Conditionally replacing items with two lists


code:
def count(element,seq):
    """Counts how often an element occurs
    ...in a sequence"""
    count = 0
    for i in seq:
        if  element == i:
            count += 1
    return count

rawDescription: Alternative to list.count( ) in python

description: Alternative to list.count( ) in python


code:
from blessings import Terminal # $ pip install blessings

t = Terminal()
with t.location(0, t.height - 1):
    print('This is at the bottom.')

rawDescription: Print over last line in terminal

description: Print over last line in terminal


code:
import java.util.ArrayList as ArrayList
import java.lang.String as String
...
javaList = ArrayList()
for subList in [ ["a","b"] , ["c","d"] , ["e","f"] ]:
    javaSubList = ArrayList()
    for s in subList:
        javaSubList.add(String(s))
    javaList.add(javaSubList)
return javaList

rawDescription: Returning python list to Java

description: Returning python list to Java


code:
import requests
cookies = {'birthtime': '568022401'}
r = requests.get('http://store.steampowered.com/', cookies=cookies)

rawDescription: Python Beautiful Soup - Getting past Steam's age check


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

ims = []
fig = plt.figure("Animation")
ax = fig.add_subplot(111)

for imgNum in range(10):
    img = np.random.rand(10,10) #random image for an example

    frame =  ax.imshow(img)
    t = ax.annotate(imgNum,(1,1)) # add text

    ims.append([frame,t]) # add both the image and the text to the list of artists

anim = animation.ArtistAnimation(fig, ims, interval=350, blit=True, repeat_delay=350)

plt.show()

rawDescription: Add text to image animated with matplotlib ArtistAnimation


rawDescription: how to post a new comment through a method in django?

description: Post a new comment through a method in django


code:
from msvcrt import getch

chars = {b'f': 'ph'}  # You could easily extend this dictionary.

while True:
    z = getch()
    if z in chars:
        print(chars[z])

rawDescription: Python: get key event and output something else


code:
import multiprocessing
import subprocess

def process_pdf(path):
    subprocess.call(['jruby', 'C:\\jruby-1.7.4\\bin\\tabula', path, ...])

pool = multiprocessing.Pool(3)      # 3 processes
results = []
for path in search_for_files():
    results.append(pool.apply_async(process_pdf, [path]))
for result in results:
    result.wait()

rawDescription: Throttling Popen() calls

description: Throttling Popen() calls


code:
allLines = r.readlines()
bestOf = re.split(' ', allLines)
f = open("output.txt", 'w')
for line in allLines[2:]:
    z = re.split(' ', line)
    if z[0] == bestOf[0] and z[1] == bestOf[1]:
        # match, compare values
        if z[7] > bestOf[7]:
            bestOf = z
    else:
        # no match, next set
        f.write(bestOf)
        bestOf = z

rawDescription: compare lines within a single file using python

description: Compare lines within a single file using python


code:
from pyramid.view import notfound_view_config

@notfound_view_config(request_method='GET')
def notfound_get(request):
    return Response('Not Found during GET, dude', status='404 Not Found')

@notfound_view_config(request_method='POST')
def notfound_post(request):
    return Response('Not Found during POST, dude', status='404 Not Found')

@notfound_view_config(context='.your_package.api_class')
def notfound_post(request):
    """matches only when traversal returns an object of API class"""
    return Response('Not Found during POST request on API endpoint, dude', status='404 Not Found')

rawDescription: Url-Specific 404 Not Found With Traversal Routing


code:
from ftplib import FTP
ftp = FTP('ftp.debian.org')     # connect to host, default port
ftp.login()                     # user anonymous, passwd anonymous@
ftp.cwd('debian')               # change into "debian" directory
ftp.retrlines('LIST')           # list directory contents
ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()

rawDescription: How to download files automatically from ftp supported website using Python?

description: Download files automatically from ftp supported website using Python


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

N = 500
data1 = np.random.randn(N)
data2 = np.random.randn(N)
colors = np.linspace(0,1,N)

plt.scatter(data1, data2, c=colors, cmap=cm.Blues)

plt.colorbar()

plt.show()

rawDescription: Pyplot colormap line by line

description: Pyplot colormap line by line


code:
axes.set_autoscale_on(True)
axes.autoscale_view(True,True,True)
axes.set_ylim(0, 11) # 11 -> max(yvalues) + 1

rawDescription: Autoscale with margin in matplotlib

description: Autoscale with margin in matplotlib


code:
with open('myfile.chn', 'rb') as f:
   i = 0
   for x in f:
      i += 1
      print(x)
print('reached the EOF')

rawDescription: EOF in a binary file using python

description: EOF in a binary file using python


code: sorted_urls = sorted(all_urls, key=lambda x: ('season-' in x, 'en' not in x))

rawDescription: Complex sort using lambda

description: Complex sort using lambda


code: chunk_size = int(line.strip().split(';')[0], 16)

rawDescription: How to read size of chunks in Transfer-encoding: chunks?

description: Read size of chunks in Transfer-encoding: chunks


code:
# Create a lookup structure for words
word_dictionary = dict((entry[0], entry) for entry in tuples)

findings = []
word_re = re.compile(r'\b\S+\b') # only need to create the regexp once
for sentence in data:
    for word in word_re.findall(sentence): # Check every word in the sentence
        if word in word_dictionary: # A match was found
            entry = word_dictionary[word]
            findings.append([sentence, word, entry[1], entry[2]])

rawDescription: Optimize a find and match code in Python


code:
from pprint import pprint

# pos is (row, column), not (x, y)
class Node:
    def __init__(self, val, pos):
        self.val = val
        # Position info is stored here and ALSO as index in graph -
        # this is a form of data duplication, which is evil!
        self.pos = pos
        self.visited = False
    def __repr__(self):
        # nice repr for pprint
        return repr(self.pos)

# You had mistake here, "arena" instead of "graph"
# Before posting questions on stackoverflow, make sure your examples
# at least produce some incorrect result, not just crash.
# Don't make people fix syntax errors for you!
def bfs(graph, start):
    fringe = [[start]]
    # Special case: start == goal
    if start.val == 'g':
        return [start]
    start.visited = True
    # Calculate width and height dynamically. We assume that "graph" is dense.
    width = len(graph[0])
    height = len(graph)
    # List of possible moves: up, down, left, right.
    # You can even add chess horse move here!
    moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while fringe:
        # Print fringe at each step
        pprint(fringe)
        print('')
        # Get first path from fringe and extend it by possible moves.
        path = fringe.pop(0)
        node = path[-1]
        pos = node.pos
        # Using moves list (without all those if's with +1, -1 etc.) has huge benefit:
        # moving logic is not duplicated. It will save you from many silly errors.
        # The example of such silly error in your code:
        # graph[pos[0-1]][pos[1]].visited = True
        #           ^^^
        # Also, having one piece of code instead of four copypasted pieces
        # will make algorithm much easier to change (e.g. if you want to move diagonally).
        for move in moves:
            # Check out of bounds. Note that it's the ONLY place where we check it. Simple and reliable!
            if not (0 <= pos[0] + move[0] < height and 0 <= pos[1] + move[1] < width):
                continue
            neighbor = graph[pos[0] + move[0]][pos[1] + move[1]]
            if neighbor.val == 'g':
                return path + [neighbor]
            elif neighbor.val == 'o' and not neighbor.visited:
                # In your original code there was a line:
                # if neighbor is not neighbor.visited:
                # which was completely wrong. Read about "is" operator.
                neighbor.visited = True
                fringe.append(path + [neighbor])  # creates copy of list
    raise Exception('Path not found!')

if __name__ == '__main__':
    # Graph in convenient form: 0 is empty, 1 is wall, 2 is goal.
    # Note that you can have multiple goals.
    graph = [
        [0, 1, 0, 1],
        [0, 0, 0, 0],
        [0, 1, 0, 1],
        [0, 0, 2, 1]
    ]
    # Transform int matrix to Node matrix.
    TRANSLATE = {0: 'o', 1: 'x', 2: 'g'}
    graph = [[Node(TRANSLATE[x], (i, j)) for j, x in enumerate(row)] for i, row in enumerate(graph)]
    # Find path
    try:
        path = bfs(graph, graph[0][0])
        print("Path found: {!r}".format(path))
    except Exception as ex:
        # Learn to use exceptions. In your original code, "no path" situation
        # is not handled at all!
        print(ex)

rawDescription: Breadth first search in python stuck in infinite loop


code: elements = ['%{0}%'.format(element) for element in elements]

rawDescription: Perform a string operation for every element in a Python list


code:
s
s[np.arange(len(s)),s[:,-1]] = 1
s

rawDescription: Replacing value in a numpy array using as an index another value from the same array


code:
n=2
v = [x[i+n]-x[i] for i in range(len(x)-n)]

rawDescription: taking difference of array with specific spacing in numpy

description: Taking difference of array with specific spacing in numpy


code:
s = 'ab, c d'
cmpfn = lambda x: -len(x)
sorted([''.join(y for y in x if y.isalnum()) for x in s.split()], key=cmpfn)[0]

rawDescription: filter string in comprehension list with nested loops

description: Filter string in comprehension list with nested loops


code:
class RaceTelemetryData(models.Model):
  user = models.ForeignKey(..., index_db=True)
  race = models.ForeignKey(YourRaceModel, index_db=True)
  time = models.IntegerField()
  gas = models.IntegerField()
  speed = models.SmallIntegerField()
  # and so on...

rawDescription: Django database planning - time series data


code: Force = [(function(x)-0.5)/slope for x in Power]

rawDescription: Equating a list to the function of another list


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('output.xlsx')
worksheet = workbook.add_worksheet()

format = workbook.add_format()
format.set_border(style=1)

worksheet.write('A1', "Hello, world!", format=format)

workbook.close()

rawDescription: Xlsxwriter can't set border width

description: Xlsxwriter can't set border width


code:
class MyClass():
    ...
    @staticmethod
    def unpickle():
        with file('test_file', 'rb') as f:
            return pickle.load(f)

data = MyClass.unpickle()

rawDescription: Save to file and load an instance of a python class with its attributes


code:
def check(given):
   hash = {}
   for li in given:
      for val in li:
         if val in hash:
            return False
         hash[val] = 1
   return True

rawDescription: list checking in python

description: List checking in python


code:
import csv
from collections import namedtuple

fh = csv.reader(open(you_file, "rU"), delimiter=',', dialect=csv.excel_tab)
headers = fh.next()
Row = namedtuple('Row', headers)
OCRs = [Row._make(i)._asdict() for i in fh]
db.engine.execute(OpenChromatinRegion.__table__.insert(), OCRs)

# plus your loop for multiple files and exception handling of course =)

rawDescription: Python: CSV to list of dictionaries to DB rows?


rawDescription: Reformatting Pandas dataframe?

description: Reformatting Pandas dataframe


rawDescription: Get name of primary field of Django model


code:
x = 2
d1 = {
    "number": 3,
    "foo": "bar",
    "color": "blue" if x == 1 else "red" if x == 2 else "purple"
}
# or:
x = 3
d2 = dict(
    number=3,
    foo="bar",
    color="blue" if x == 1 else "red" if x == 2 else "purple"
)
print(d1["color"]) # => red
print(d2["color"]) # => purple

rawDescription: Create key/value pair in Python using an if conditional


code: d = Image.objects.filter(**{'image__endswith': "jpg"})

rawDescription: How do I use a string as a keyword argument?

description: Use a string as a keyword argument


code:
import bisect
lst = [207, 357, 470, 497, 537]
bisect.bisect_left(lst, 0)
bisect.bisect_left(lst, 360)

rawDescription: Given boundaries, find interval

description: Given boundaries, find interval


code:
from django.core.urlresolvers import reverse
from django.http import Http404

class RestrictStaffToAdminMiddleware(object):
    """
    A middleware that restricts staff members access to administration panels.
    """
    def process_request(self, request):
        if request.path.startswith(reverse('admin:index')):
            if request.user.is_authenticated():
                if not request.user.is_staff:
                    raise Http404
            else:
                raise Http404

rawDescription: How do I restrict access to admin pages in Django?

description: Restrict access to admin pages in Django


code:
def prepare():
    temp = "%04XT2000A" % 76
    send(temp)

def send(tx_string):
    checksum = 0x02
    serial.write(checksum)

    # hint: int conversion will not work since tx_string is a
    # string representation of a hex value, add conversion code for this
    while(tx_string):
        serial.write(int(tx_string[0]))
        checksum = checksum ** int(tx_string[0])
        tx_string = tx_string[1:]

    serial.write(0x03)
    checksum = checksum ** 0x03
    serial.write(checksum)

rawDescription: Translate C++ code that uses char type to Python


code: list2 = list(set(list2) - set(list1))

rawDescription: What is wrong with this python list removal loop?


code:
from urllib2 import Request, urlopen
from pyPdf import PdfFileWriter, PdfFileReader
from StringIO import StringIO

url = "http://www.silicontao.com/ProgrammingGuide/other/beejnet.pdf"
writer = PdfFileWriter()

remoteFile = urlopen(Request(url)).read()
memoryFile = StringIO(remoteFile)
pdfFile = PdfFileReader(memoryFile)

for pageNum in xrange(pdfFile.getNumPages()):
        currentPage = pdfFile.getPage(pageNum)
        #currentPage.mergePage(watermark.getPage(0))
        writer.addPage(currentPage)

outputStream = open("output.pdf","wb")
writer.write(outputStream)
outputStream.close()

rawDescription: Opening pdf urls with pyPdf

description: Opening pdf urls with pyPdf


code:
bar(xs, ys, width=1, align='center', color='brown')
plot(xs, ys, color='purple', lw=2, marker='s')

rawDescription: plotting histogram as line graph in matplot using x and y values in python

description: Plotting histogram as line graph in matplot using x and y values in python


rawDescription: I have a very big list of dictionaries and I want to sum the insides


code:
class Post:
    body = ">>> print('Hello world')"

    @property
    def html_body(self):
        # 1. Locate all ... blocks
        # 2. Convert the text in them to proper HTML
        ...
        return processed_body

    # which should return
    # ">>> print('Hello world')"

rawDescription: Re-enable autoescape after it has been disabled in Jinja2


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.transforms as transforms

# set up fig and axis
fig = plt.figure()
currentAxis = plt.gca()

# set translation
dx, dy = 5/72., -5/72.
offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
shadow_transform = currentAxis.transData + offset

# plot patch shadow
rect = patches.Rectangle((0.2, 0.420), 0.65, 0.730, transform=shadow_transform,
                         edgecolor = None, facecolor = "black", zorder = 3)
currentAxis.add_patch(rect)

# plot patch
rect = patches.Rectangle((0.2, 0.420), 0.65, 0.730, edgecolor = None,
                         facecolor = "white", zorder = 3)
currentAxis.add_patch(rect)

rawDescription: Draw a rectangle with a shadow on a plot


code:
s = '12345679010111213'
list(s)
' '.join(list(s))
' '.join(s) # works since str is also an iterable

rawDescription: Python splitting list by whitespace

description: Python splitting list by whitespace


code:
import random

die1 = random.randint(1,10)
die2 = random.randint(1,10)

if die1 > die2:
    die1, die2 = die2, die1

print('Die 1:',die1,'Die 2:',die2)

if die1 == die2:
    print('Even-steven!')
else:
    print("Not the same, let's play!")

    die3 = random.randint(1,10)
    print('Die 3:',die3)

    if die3 > die1 and die3 < die2 or die3 < die1 and die3 > die2:
        print ('You win!')
    elif die3 == die1 or die3 == die2:
        print ('You hit the post - You lose double your bet!')
    else:
        print('Sorry - You lose!')

print('Thanks for playing!')

rawDescription: Python Game of inbetween - can't get if-elif to work


code:
import moduleX
dir(moduleX)
help(moduleX)

rawDescription: List of API commands for Win32api

description: List of API commands for Win32api


code:
for row in r:
    summary = dict(zip(columns, row))
    results.append(summary)

rawDescription: Sqlite query to python dictionary

description: Sqlite query to python dictionary


code:
fig, (axis1,axis2) = plt.subplots(2,1,sharex=True,figsize=(15,8))

ax1 =   data['corr_bund_ust'].plot(ax=axis1 ,title='bund_ust')
ax1.set_xticklabels(data.index.strftime('%Y.%m.%d'), rotation=90)

ax2 =   data['corr_ust_ktb'].plot(ax=axis2,title='ust_ktb')
ax2.set_xticklabels(data.index.strftime('%Y.%m.%d'), rotation=90)

rawDescription: How can to combine two graphs

description: How can to combine two graphs


code:
from threading import Thread

class myThread(Thread):

    args = None

    def __init__(self, group=None, target=None, args=(), name=None, kwargs = None, daemon = None):
        self.args = args
        super(RaThread, self).__init__(group=group, target=target, args=args, name=name, kwargs=kwargs, daemon=daemon)

rawDescription: Get Arguments of Thread Variable

description: Get Arguments of Thread Variable


code:
import wave
import codecs
import struct

#opening files
input_file = wave.open(r"sample.wav", 'rb')
output_file = wave.open(r"sample_out.wav", 'wb')

#Get input file parameters and set them to the output file after modifing the channel number.
in_params = list(input_file.getparams())

out_params = in_params[:]
out_params[0] = 1
output_file.setparams(out_params)

nchannels, sampwidth, framerate, nframes, comptype, compname = in_params
format = '<{}h'.format(nchannels)

#reading frames from first file and storing in the second file
for index in range(nframes):
    frame = input_file.readframes(1)
    data = struct.unpack(format, frame)
    value = data[0]     # first (left) channel only
    value = (value * 2) // 3    # apply a simple function to each value
    output_file.writeframes(struct.pack('<h', value))

#closing files
input_file.close()
output_file.close()

rawDescription: WAV file modifier using Python

description: WAV file modifier using Python


code:
def main():
    name = "firstname lastname"

    for i in range(len(name)):
        print(name[i:] + name[:i])
main()

rawDescription: Python - Cycing through a string

description: Python - Cycing through a string


code:
alltext = myfile.read()
tokenized_sentences = nltk.word_tokenize(alltext)

rawDescription: issue recognizing NEs with StanfordNER in python NLTK

description: Issue recognizing NEs with StanfordNER in python NLTK


code:
coast = Reader("ne_50m_coastline")     # defined in shapefile.py

plt.figure()

for shape in coast.shapes()[:20]:   # first 20 shapes out of 1428 total

    x, y = zip(*shape.points)

    plt.plot(x, y)

plt.xlim(110, 180)
plt.ylim(-40, 20)

plt.savefig("Australia Australia Australia Australia we love ya' Amen")
# https://www.youtube.com/watch?v=_f_p0CgPeyA&feature=youtu.be&t=121

plt.show()

rawDescription: Access coastal outlines (e.g. from Basemap, or somewhere else) without installing Basemap


code:
try:
  new_list1.append(float(item))
except (ValueError, TypeError):
  pass

rawDescription: What to code to delete any item in a list that can not be converted into a float?


code: s.resample("M", how="count")

rawDescription: how to aggregate by month of datetime in pandas frame?

description: Aggregate by month of datetime in pandas frame


code:
PROJECT_NAME      = "Python"
OUTPUT_DIRECTORY  = pyexample
GENERATE_LATEX    = NO
GENERATE_MAN      = NO
GENERATE_RTF      = NO
OPTIMIZE_OUTPUT_JAVA = YES
INPUT             = pyexample.py
QUIET             = YES
JAVADOC_AUTOBRIEF = YES
SEARCHENGINE      = NO

rawDescription: Documenting Python packages with doxygen


code:
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

rawDescription: Python mapper for adjacent pairs

description: Python mapper for adjacent pairs


code:
class SoftballRoster(object):

    def __init__(self, first_name, last_name, team, position):

        self._first_name = first_name
        self._last_name = last_name
        self._team = team
        self._position = position

    def first_name(self):
        return self._first_name.capitalize()
    first_name = property(first_name)

    def last_name(self):
        return self._last_name.capitalize()
    last_name = property(last_name)

    # another option is to use the decorator syntax:

    @property
    def team(self):
        return self._team

    @property
    def last_name(self):
        return self._position

rawDescription: Python properties...is it possibe?

description: Python properties...is it possibe


code:
def get_cpu_type():
    from win32com.client import GetObject
    root_winmgmts = GetObject("winmgmts:root\cimv2")
    cpus = root_winmgmts.ExecQuery("Select * from Win32_Processor")
    return cpus[0].Name

rawDescription: How to get the processor name in Python?

description: Get the processor name in Python


code:
for filename in glob.iglob(pattern):
    with open(filename, 'r+a') as fd:
        for num_lines, line in enumerate(fd): pass
        # num_lines is now one *less* that the actual line count.
        fd.write('\n' * max(0, 144 - num_lines))

rawDescription: Adding an x number of new lines to the end of a file Python


code:
from numpy import linspace, meshgrid
import numpy as np
from pprint import pprint
from scipy.interpolate import griddata

def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    grid_x, grid_y = np.mgrid[min(x): max(x):1j * resX, min(y): max(y):1j * resY]
    Z = griddata(np.array(zip(x, y)), np.array(z), (grid_x, grid_y), method='nearest')
    return grid_x, grid_y, Z

x =[0,1.0,2.0]
y = [0.0,10.0,20.0]
z = [0.0, 20.0, 50.0]

X,Y,Z =  grid(x,y,z)

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot_surface(X,Y,Z)
plt.show()

rawDescription: Python convert large data arrays to grid for matplotlib


code: sheet["A1"].alignment.vertical = "top"

rawDescription: How can I align text in a cell to the top with openpyxl?

description: Align text in a cell to the top with openpyxl


code:
import re
re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')
re.findall('[A-Z][^A-Z]*', 'ABC')

rawDescription: Python: Split a string at uppercase letters


code:
found=False
if year < 1993:   # If less than 93, then month doesn't matter
    found = True
elif (year == 1993) and (month <= 4):   # If 1993, check month
    found = True

if found:
    print("You are old enough to drink in Washington")
else:
    print("You aren't 21 yet")

rawDescription: How to output a string statement using an if statement in python

description: Output a string statement using an if statement in python


code:
src = open('source').read()
if src not in open('dest').read():
    with open('dest', 'a') as dst:
        dst.write(src)

rawDescription: Conditionally append file contents

description: Conditionally append file contents


code:
it = iter(list1)
from itertools import repeat
chunked_lists =  zip(it,it,it,repeat("data"))
[(1, 2, 3, 'data'), (4, 5, 6, 'data'), (7, 8, 9, 'data'), (10, 11, 12, 'data')]

rawDescription: Adding and creating chunks of a list in python


code:
people = (('fred','sam','jane','betty'), (1,2,3,4))
p_dict = dict(zip(*people))

rawDescription: operator.setitem problem in python 3

description: Operator.setitem problem in python 3


code:
import socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

rawDescription: Inter-process communication between Python and Scala programs


code: [index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]

rawDescription: Can I use a List Comprehension to get Line Indexes from a file?

description: Use a List Comprehension to get Line Indexes from a file


code:
try:
    return self._text
except AttributeError:
    self._text = None
return self._text

rawDescription: using python properties inside __init__?

description: Using python properties inside __init__


code:
import clr
clr.AddReference('IronPython')
clr.AddReference('System')
clr.AddReference('mscorlib')
clr.AddReference('Microsoft.Scripting')
clr.AddReference('MyStandardLib')
#Now you can reference things like 'import lxml as L .....

from IronPython.Hosting import Python
from Microsoft.Scripting import SourceCodeKind

spath = "C:/fred.py"  # Path to script

engine = Python.CreateEngine()
#Now add your assemblies (like the standard library) to the engine
for assembly in clr.References:
    runtime.LoadAssembly(assembly)

source = engine.CreateScriptSourceFromFile(spath, SourceCodeKind.Statements)
mod = engine.CreateScope()
runtime = engine.Runtime

source.Execute(mod)

rawDescription: py2exe gtk execute scripts from directory

description: Py2exe gtk execute scripts from directory


code:
from scipy.sparse import coo_matrix
import scipy
nrows = 100000
ncols = 100000
row = scipy.array([1,3,5,7,9])
col = scipy.array([2,4,6,8,10])
values = scipy.ones(col.size)
m = coo_matrix((values, (row,col)), shape=(nrows, ncols), dtype=float)

rawDescription: Calculate Similarity of Sparse Matrix

description: Calculate Similarity of Sparse Matrix


code: [[] for _ in range(4)]          # use xrange in python-2.x

rawDescription: Creating a list of lists with consecutive numbers


code:
key = OpenKey(HKEY_CURRENT_USER, 'Network', 0, KEY_ALL_ACCESS) # Open the root Network key.
ndrives = QueryInfoKey(key)[0] # Get the number of subkeys inside.
for i in range(ndrives): # For each subkey index...
    drive = EnumKey(key, i) # Get the subkey name.
    t = OpenKey(HKEY_CURRENR_USER, 'Network\\' + drive, 0, KEY_ALL_ACCESS) # Open the drive key.
    # Do stuff with t.

rawDescription: Python WinReg Path Wildcard

description: Python WinReg Path Wildcard


code: spritecollideany(sprite, group, collided = None)

rawDescription: Is it posible to test collision detection between one object and sprites group?


code:
import uno
from com.sun.star.beans import PropertyValue
from com.sun.star.util import SortField

def create_sort_field(column, sort_ascending):
    oSortField = SortField()
    oSortField.Field = column
    oSortField.SortAscending = sort_ascending
    return oSortField

def sort_cols():
    oSheet = XSCRIPTCONTEXT.getDocument().getSheets().getByIndex(0)
    oCellRange = oSheet.getCellRangeByName("B1:M30")
    oSortFields = (
        create_sort_field(11, False),  # column M
        create_sort_field(0, True),)   # column B
    oSortDesc = [PropertyValue()]
    oSortDesc[0].Name = "SortFields"
    oSortDesc[0].Value = uno.Any(
        '[]com.sun.star.util.SortField', oSortFields)
    oCellRange.sort(oSortDesc)

# Functions that can be called from Tools -> Macros -> Run Macro.
g_exportedScripts = sort_cols,

rawDescription: Converting a Libre/Star/Openoffice Basic macro to python - issue with object types


code:
strong = li.find_all("strong")
if strong:
    yield strong

rawDescription: Is there a pretty way to yield if in Python 3.3?


code:
from xml.etree import ElementTree
import os

def edit_xml_file(data):
    e = ElementTree.fromstring(data)

    for file_element in e.findall('file'):

        analyse_element = file_element.find('analyse')

        in_context_exact_element = analyse_element.find('inContextExact')
        in_context_exact_words = int(in_context_exact_element.get('words'))
        in_context_exact_element.set('words', '0')

        cross_file_repeated_element = analyse_element.find('crossFileRepeated')
        cross_file_repeated_words = int(cross_file_repeated_element.get('words'))
        cross_file_repeated_element.set('words', '0')

        total_element = analyse_element.find('total')
        total_element.set('words', str(in_context_exact_words + cross_file_repeated_words))

    xmlstr = ElementTree.tostring(e)
    return xmlstr

def main():

    source_directory = 'xmlfiles'

    for filename in os.listdir(source_directory):

        if not filename.endswith('.xml'):
            continue

        xml_file_path = os.path.join(source_directory, filename)
        with open(xml_file_path, 'r+b') as f:
            data = f.read()
            fixed_data = edit_xml_file(data)
            f.seek(0)
            f.write(fixed_data)
            f.truncate()

if __name__ == '__main__':
    main()

rawDescription: how to edit XML files in batch / python

description: Edit XML files in batch / python


code:
df = pd.DataFrame([[1, 2, "A"], [1, 4, "A"], [5, 6, "B"]])
df
df.pivot_table(index=0, values=1, columns=2)  # default aggfunc is 'mean'
df.pivot_table(index=0, values=1, columns=2, aggfunc='first')

rawDescription: Python Take first observation per group Using pandas.pivot_table


code:
df = pd.DataFrame(np.random.randn(5,5))
df[df < 0.1] = np.nan
df
movers = ~np.isnan(df.values)
df.values[movers] = np.random.permutation(df.values[movers])
df

rawDescription: Permute Matrix while keeping some items in place


code:
"My name is {0}.".format("Austin")
"I am {} years old and make ${:.2f} per hour.".format(50, 50.29999) # positional arguments
myDict = { "language" : "English", "major" : "Computer Networking" }
"I speak {language} and have a degree in {major}.".format(**myDict)
myList = [2, "German Sheppard", "Lucy", "Ethel" ]
"I own {} {}s named '{}' and '{}'.".format(*myList)

rawDescription: Python % operator vs concatenation

description: Python % operator vs concatenation


code:
import threading

def is_it_done():
    # get some dummy predictable results
    if not hasattr(is_it_done, 'results'):
        is_it_done.results = iter([False] * 3)
    return next(is_it_done.results, True)

def job_watch():
    is_done = False

    def d():
        is_done = is_it_done()
        print('is_done: {}'.format(is_done))
        timer = threading.Timer(3, d).start()

    d()

job_watch()

rawDescription: Python polling MSSQL at set interval

description: Python polling MSSQL at set interval


code:
import  csv
with open(file1) as f1,open(file2) as f2:
    rd1, rd2 = csv.reader(f1) ,list(csv.reader(f2))
    for row1 in rd1:
        for row2 in rd2:
            if row1[0] == row2[0] and row1[1] == row2[1]:
                print('There is a match', row1[0], row1[1])

rawDescription: Not Iterating through all lines from a csv file python3


code:
try:
    import xlrd
    import mmap

    def XLSDictReader(f, sheet_index=0):
        data    = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
        book    = xlrd.open_workbook(file_contents=data)
        sheet   = book.sheet_by_index(sheet_index)

        def item(i, j):
            return (sheet.cell_value(0,j), sheet.cell_value(i,j))

        return ( dict(item(i,j) for j in range(sheet.ncols)) \
                     for i in range(1, sheet.nrows) )

except ImportError:
    XLSDictReader = None

rawDescription: DictReader for Excel-Files

description: DictReader for Excel-Files


rawDescription: Get last item from a list as integer/float


code:
@app.route('/page/<page_id>')
def page(page_id):
    pageid = page_id
    # You might want to return some sort of response...

rawDescription: python flask how to get route id from url

description: Python flask how to get route id from url


code:
import numpy as np

N = 100
m = np.zeros((N, N))
# initial point to start random fill
i, j = np.random.randint(0, N, 2)
# mark as filled
m[i, j] = 1

active = [(i, j)] # add initial to active cells to expand from

while active:
    c = np.random.randint(0, len(active)) # choose random cell
    i, j = active[c] # get coordinates

    # get all neighbors
    neighbors = set([(min(N-1, max(0, x)), min(N-1, max(0, y))) for x in range(i-1, i+2) for y in range(j-1, j+2)])
    neighbors = [n for n in neighbors if m[n] == 0] # get all unmarked neighbors

    if neighbors:
        # choose random neighbor and mark it
        random_neighbor = neighbors[np.random.randint(0, len(neighbors))]
        m[random_neighbor] = 1

        if len(neighbors) <= 1: # if there are no more unmarked neighbors left
            del active[c] # remove from active list

        active.append(random_neighbor) # add marked neighbor to active list
    else:
        del active[c]

rawDescription: How to enumerate the cells of a Matrix using random flood filling?

description: Enumerate the cells of a Matrix using random flood filling


code:
class MyHandler(tornado.web.RequestHandler):
    def render(self, *args, **kwargs):
        kwargs['my_context_variable'] = 'context'
        return super(MyHandler, self).render(*args, **kwargs)

rawDescription: context_processor for tornado framework

description: Context_processor for tornado framework


code:
btn = wx.Button(self, wx.ID_ANY, 'Start', size=(25,-1))
btn.SetMinSize(wx.Size(25,25))

self.Layout()

rawDescription: Resizing wxPython Widgets

description: Resizing wxPython Widgets


code: defaultdict(lambda : defaultdict(int))

rawDescription: Python: defaultdict of defaultdict?

description: Python: defaultdict of defaultdict


code:
import shutil
import os
loc = "testfolder"
path = os.getcwd() + '/' +  loc + "/"
dirs = os.listdir( path )
for file in dirs:
   name =  file
   shutil.make_archive(name, 'zip', path)

rawDescription: Zip all subdirectories using python

description: Zip all subdirectories using python


code:
while True:
    data=the_socket.recv(8192)
    if len(data) == 0: break
    ...

rawDescription: Python client disconnect if server closes connection


code:
x = a
y = b
foo(x, y)

rawDescription: Ensure Memory Location of Variable hasn't Changed


code:
@app.route('/questions/<int:id>')
@app.route('/questions/<int:id>/<slug>')
def question(id, slug=None):
    ...

rawDescription: Can I add optional URL description after final slash using Flask with a variable in the URL?

description: Add optional URL description after final slash using Flask with a variable in the URL


code:
import a

if __name__ == "__main__":
  a.A(listOfInputTuplesForB)

rawDescription: Where should the " if __name__ = '__main__' " idiom be placed when using the Python multiprocessing module?


code:
import numpy as np
import random
e1=np.random.random((15,)).reshape(-1,1)
e2=e1+0.05*np.random.standard_normal(15).reshape(-1,1)
e1[random.sample(range(e1.shape[0]), 5),:] = np.nan
e2[random.sample(range(e2.shape[0]), 5),:] = np.nan
np.concatenate((e1,e2),axis=1)

rawDescription: Python data missing at random in two different arrays. Looking to combine these to make a single array


code:
import wx

def run(nb):
    for i in range(1, 5, 1):
        adp(nb, i)

def adp(nb, p):
    newpage = Page(nb)
    newpage.SetBackgroundColour(wx.GREEN)
    wx.StaticText(newpage, -1, "PAGE "+str(p), style=wx.ALIGN_CENTRE)
    wx.CallAfter(nb.AddPage, newpage, "Page "+str(p))

class Page(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        wx.StaticText(self, -1, "This is a Page object", (20,20))

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Notebook Test")
        p = wx.Panel(self)
        self.nb = wx.Notebook(p)
        self.page1 = Page(self.nb)

        sizer = wx.BoxSizer()
        sizer.Add(self.nb, 1, wx.EXPAND)
        p.SetSizer(sizer)

if __name__ == "__main__":
    app = wx.App()
    mf = MainFrame()
    mf.Show()
    mf.nb.AddPage(mf.page1, "Testseite 1")
    run(mf.nb)
    app.MainLoop()

rawDescription: New wxNotebook-Pages stay empty in wxPython


code:
import Tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.op = tk.StringVar(self)
        self.op.set("enable")
        self.om = tk.OptionMenu(self, self.op, "enable","disable", command=self.OnOption)
        self.entry = tk.Entry(self, width=30)
        self.om.pack()
        self.entry.pack()

    def OnOption(self, event):
        state = "normal" if self.op.get() == "enable" else "disabled"
        self.entry.configure(state=state)

app=App()
app.mainloop()

rawDescription: disable/enable a widget using combobox?

description: Disable/enable a widget using combobox


code: exec('a=4; b=2.5; c=a*b; print c')

rawDescription: Parsing user input as python code in self-designed GUI


code:
import time
import curses

stdscr = curses.initscr()

n = 0
b = 0
for _ in range(0, 5):
    i = 1
    for _ in range(0, 123):
        stdscr.addstr(b, 0, "Current: %d" % i)
        i = i + 1
        n = n + 1
        time.sleep(0.01)
        stdscr.addstr(b+1, 0, "Total: %d" % n)
        stdscr.refresh()
    b = b + 1

rawDescription: Python - How to display two counters in for loops


code:
import sys
from PyQt4 import QtGui,QtCore

class gui(QtGui.QMainWindow):
    def __init__(self):
        super(gui, self).__init__()
        self.initUI()

    def dataReady(self):
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(str(self.process.readAll()))
        self.output.ensureCursorVisible()

    def callProgram(self):
        # run the process
        # `start` takes the exec and a list of arguments
        self.process.start('ping',['127.0.0.1'])

    def initUI(self):
        # Layout are better for placing widgets
        layout = QtGui.QHBoxLayout()
        self.runButton = QtGui.QPushButton('Run')
        self.runButton.clicked.connect(self.callProgram)

        self.output = QtGui.QTextEdit()

        layout.addWidget(self.output)
        layout.addWidget(self.runButton)

        centralWidget = QtGui.QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

        # QProcess object for external app
        self.process = QtCore.QProcess(self)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyRead.connect(self.dataReady)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda: self.runButton.setEnabled(False))
        self.process.finished.connect(lambda: self.runButton.setEnabled(True))

#Function Main Start
def main():
    app = QtGui.QApplication(sys.argv)
    ui=gui()
    ui.show()
    sys.exit(app.exec_())
#Function Main END

if __name__ == '__main__':
    main()

rawDescription: RealTime output from a subprogram to stdout of a pyQT Widget


rawDescription: How to know when you are in a symbolic link

description: Know when you are in a symbolic link


code:
import wx
from wx.lib import analogclock as ac

class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,'AnalogClock',size=(600,400))

        menubar=wx.MenuBar()
        first=wx.Menu()
        item=first.Append(wx.NewId(), "Change background colour","background colour" )
        menubar.Append(first, "FILE")
        self.SetMenuBar(menubar)

        self.status=self.CreateStatusBar()

        self.clock = ac.AnalogClockWindow(self)
        self.clock.SetTickSizes(h=20, m=7)
        self.clock.SetTickStyles(ac.TICKS_DECIMAL)
        self.clock.SetHandColours('black')
        self.clock.SetTickColours('black')

        self.colorList = ['black','blue','yellow','red']

        self.Bind(wx.EVT_MENU, self.onClick,item)

    def onClick(self,event):
        count = wx.SingleChoiceDialog(None, "Which colour u want??", "Title", self.colorList)
        if count.ShowModal() == wx.ID_OK:
            custom = count.GetStringSelection()

            self.clock.SetBackgroundColour(custom) #change the colour of background

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1)
        frame.Show(True)
        frame.Centre()
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: how to change the colour of the clock directly from the menubar?

description: Change the colour of the clock directly from the menubar


code:
def do_prefix(name, prefix):
    if prefix:
        return "%s.%s" % (prefix, name)
    return name

def get_fields_flat(model):
    return [name for name in iter_fields(model)]

def iter_fields(model, prefix=None):
    fields = model._meta.fields
    for field in fields:
        name = do_prefix(field.attname, prefix)
        yield  name
        if field.rel:
            rel = field.rel.to
            for f in iter_fields(rel, name):
                yield f

rawDescription: Django: Get model fields recursively (ForeignKeys and it's fields) as strings into a 1 level list


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

rawDescription: How to kill a while loop with a keystroke?

description: Kill a while loop with a keystroke


code:
for line in f.readlines():
    mnemonic_line.append(line[0:3])
    mnemonic_line.append(line[5:8])
    mnemonics.append(mnemonic_line)
    mnemonic_line = []

rawDescription: python readlines() creating a new list each time

description: Python readlines() creating a new list each time


code:
width = int(input("Please enter a width: "))

i = 0
while i < width*2:
    if i < width:
        print("-" * i+ " *" * (width-i) + "-" * i)
    else:
        print("-" * ((2*width-i) -1) + " *" * (i - width + 1) + "-" *     ((2*width-i) -1))
    i += 1

rawDescription: Python Loop Reverse Diamond

description: Python Loop Reverse Diamond


code:
myfile = open('/home/graham/Desktop/Experiment/listcsv.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows([path] for path in list_of_paths)

rawDescription: How to I generate a CSV file from a python list with each list item in a seperate row


code:
import bokeh
import bokeh.plotting as bplot

bplot.reset_output()
bplot.output_notebook()
bplot.figure(x_range=[0,1],
             y_range=[0,1])
bplot.rect([0.5], [0.5], [0.2], [0.2])
bplot.show()

rawDescription: Bokeh plots won't draw rectangle glyphs

description: Bokeh plots won't draw rectangle glyphs


code:
class Image(db.Model):

    reference = db.ReferenceProperty(Article,
            collection_name='matched_images', verbose_name='Title')
    primary_image = blobstore.BlobReferenceProperty()

rawDescription: store the BlobKey in the model

description: Store the BlobKey in the model


code:
for x in range(1,20):
   f = open("test"+str(x), 'w')
   f.write(str(x) + "\n" + str(20-x))
   f.close()

rawDescription: Python creating a file and adding numbers


code:
import csv
with open('datafile.txt', 'rb') as f:
    for row in csv.reader(f, delimiter='|'):
        ...

rawDescription: Python: Parse Text file with '|' to MySql table


code:
env.roledefs = {
    'first_half': ['host1', 'host2'],
    'second_half': ['host3', 'host4'],
}

def deploy_server():
    ...
    # deploy one host from current role here

def deploy():
    # first role:
    env.roles = ['first_half']
    execute('deploy_server')
    test()  # here test deployed servers
    # second role:
    env.roles = ['second_half']
    execute('deploy_server')

rawDescription: Deploying to multiple EC2 servers with Fabric


code:
MAGIC = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'  # Fix key for handshake on server side
class WebSocketsHandler(socketserver.StreamRequestHandler):
   def handshake(self):
      data = self.request.recv(1024).strip()
      hsKey = hsUpgrade = b''
      for header in data.split(b'\r\n'):
         if header.startswith(b'Sec-WebSocket-Key'): hsKey = header.split(b':')[1].strip()
         if header.startswith(b'Upgrade'): hsUpgrade = header.split(b':')[1].strip()
      if hsUpgrade != b"websocket": return
      digest = b64encode(bytes.fromhex(sha1(hsKey + MAGIC).hexdigest())).decode('utf-8')
      response = ('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n'
            'Connection: Upgrade\r\nSec-WebSocket-Accept: {}\r\n\r\n'.format(digest))
      print('Handshaking...{}'.format(digest))
      self.handshake_done = self.request.send(response.encode('utf8'))

rawDescription: Python Server Websocket Handshake Response


code:
import json
from collections import OrderedDict

def list_to_csv(listdat):
    csv = ""
    for val in listdat:
        csv = csv+","+str(val)
    return csv[1:]

lines = []
csvfile = "csvfile.csv"
outcsvfile = "outcsvfile.csv"
jsonfile = "jsonfile.json"

with open(csvfile, encoding='UTF-8') as a_file:
        for line in a_file:
            lines.append(line.strip())

columns = lines[0].split(",")
data = lines[1:]

whole_data = []
for row in data:
    fields = row.split(",")
    i = 0
    rowData = OrderedDict()
    for column in columns:
        rowData[columns[i]] = fields[i]
        i += 1
    whole_data.append(rowData)

with open(jsonfile) as json_file:
    jsondata = json.load(json_file)

keys = list(jsondata.keys())

for key in keys:
    value = jsondata[key]
    for each_row in whole_data:
        each_row[key] = value

with open(outcsvfile, mode='w', encoding='UTF-8') as b_file:
    b_file.write(list_to_csv(columns)+'\n')
    for row_data in whole_data:
        row_list = []
        for ecolumn in columns:
            row_list.append(row_data.get(ecolumn))
        b_file.write(list_to_csv(row_list)+'\n')

rawDescription: Edit CSV file in python which reads values from another json file in python


code:
import numpy as np
import matplotlib.pylab as pl

id        = np.array([1,1,1,2,2,2,2,3,3,5,6,7])
timestamp = np.array([1,2,3,1,2,3,4,1,2,2,3,4])
score     = np.array([100,115,120,12,20,15,30,14,100,20,20,100])

pl.figure()
for i in np.unique(id):     # Loop over all the unique id's
    pw = np.where(id == i)  # which elements belong to this id
    pl.plot(timestamp[pw], score[pw], '-x', label=str(i))
pl.legend(frameon=False, loc='best')

rawDescription: python plot multiple line time serie

description: Python plot multiple line time serie


code: modTime = max([os.path.getmtime(os.path.join(dir, p)) for p in os.listdir(dir)])

rawDescription: Folder modification time including the files inside it?


code:
import os
import sys
import importlib
import inspect
import logging

def load_module(module_path, filename):
    """ returns the module if filename is a module else None """
    if filename.endswith('.py'):
        module = filename[:-3]
    elif os.path.exists(os.path.join(module_path, filename, '__init__.py')):
        module = filename
    else:
        return None
    try:
        return importlib.import_module(module)
    except:
        logging.exception('Loading %s failed.' % module)
        return None

class PluginManager(object):
    def __init__(self):
        self.modules = {}
        self.classes = {}

    def add_path(self, module_path):
        sys.path.append(module_path)
        for filename in os.listdir(module_path):
            module = load_module(module_path, filename)
            if module:
                self.modules[module.__name__] = module
                self._extract_classes(module)
        sys.path.remove(module_path)

    def _extract_classes(self, module):
        for name in dir(module):
            obj = getattr(module, name)
            if inspect.isclass(obj):
                if hasattr(obj, '_VERSION'):
                    version = getattr(obj, '_VERSION')
                    logging.info("Found %s.%s %s" % (module.__name__, name, version))
                    self.classes[name] = obj

logging.getLogger().level = logging.INFO
plugins = PluginManager()
plugins.add_path('/home/test/multitool')

rawDescription: How to load all modules in directory and get class from module

description: Load all modules in directory and get class from module


rawDescription: How to find a custom tag within another tag using Selenium

description: Find a custom tag within another tag using Selenium


code:
fig =plt.figure(figsize=(10,8))
ax = plt.subplot()
xi,yi = np.linspace(195.2260,391.2260,50), np.linspace(4108.9341,4304.9341,50)
## the image
img=mpimg.imread('4d4178c16eb7aaf6.png')

ax.imshow(img,
        extent=[min(xi), max(xi), min(yi), max(yi)])
## the rest

height = np.array(list(csv.reader(open("terr_grd.csv","tr"),delimiter=','))).astype('float')

terrf = ax.contourf(xi, yi, height,15, cmap=plt.cm.Blues,alpha=0.5)
terr = ax.contour(xi, yi, height, 15,
            colors='k',alpha=0.5)
ax.clabel(terr, fontsize=9, inline=1)

fig.savefig("theplot.png")

plt.show()

rawDescription: Plotting terrain as background using matplotlib


code:
class foo(object):
    def __init__(self, bar, baz):
        self.baz = baz
    def __call__(self,waldo):
        return self.baz * waldo

rawDescription: Python serialize lexical closures?

description: Python serialize lexical closures


code:
seen = set()
item_list = [seen.add(item) or item for item in item_list if item not in seen]

rawDescription: Best way to eliminate duplicates in a list, but keep previous relative order

description: Eliminate duplicates in a list, but keep previous relative order


code:
import itertools
from collections import defaultdict

a1 = {u'SFP_1': [u'cat', u'3'], u'SFP_0': [u'cat', u'5', u'bat', u'1']}

b1 = itertools.chain.from_iterable(a1.itervalues())
c1 = defaultdict(int)
for animal, count in itertools.izip(*[iter(b1)] * 2):
    c1[animal] += int(count)
# c1 => defaultdict(<type 'int'>, {u'bat': 1, u'cat': 8})

c1 = {animal: str(count) for animal, count in c1.iteritems()}
# c1 => {u'bat': '1', u'cat': '8'}

rawDescription: Convert list into dictionary in python

description: Convert list into dictionary in python


code:
with open("myserver.pem", "w") as w:
    w.write("""\
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAnTsiYssvsuM1DRjyhqD8+ZB8ESqUFHgzeBYONp3yqjK8ICw/LRrxjXGXidAW
aPBXfktv3zN/kFsLMEFJKrJs/TLCfXG1CwFHMZzJRLM4aE6E0j6j+KF96cY5rfAo82rvP5kQdTIm
-----END RSA PRIVATE KEY-----
""")

rawDescription: creating a new text file using heredoc

description: Creating a new text file using heredoc


code:
from java import io

def saveObject(x, fname="object.bin"):
    outs = io.ObjectOutputStream(io.FileOutputStream(fname))
    outs.writeObject(x)
    outs.close()

def loadObject(fname="object.bin"):
    ins = io.ObjectInputStream(io.FileInputStream(fname))
    x=ins.readObject()
    ins.close()
    return x

rawDescription: How to save a Java object in Jython/Python

description: Save a Java object in Jython/Python


code:
#this is what you start with
words = [ ('word1', 'file1', 5),
    ('word1', 'file2', 3),
    ('word2', 'file1', 2),
    ('word2', 'file3', 5) ]

#grouped by words
simple = {}
for word, f, count in words:
    try: simple [word] [f] = count
    except: simple [word] = {f: count}

print (simple)

#find files which contain both w1 and w2
def findTwoWords (data, w1, w2):
    files1 = set (data [w1].keys () )
    files2 = set (data [w2].keys () )
    return files1 & files2

print ('"word1" and "word2" appear together in {}'.format (findTwoWords (simple, 'word1', 'word2') ) )

rawDescription: How to merge and search duplicate values?

description: Merge and search duplicate values


code: _cell.number_format = '#,##0.00€'

rawDescription: Set openpyxl cell format to currency

description: Set openpyxl cell format to currency


code: [x for x in dict1.keys() if x not in dict2.keys()]

rawDescription: Concise way to find "key" difference between 2 dictionaries?


code:
class BaseProxy(object):
     # ...
     def _incref(self):
         # ...
         util.debug('INCREF %r', self._token.id)
     # ...
     def _after_fork(self):
         # ...
         self._incref()
         # ...

rawDescription: Starting multiple multiprocessing Managers becomes extremely slow


code:
tuples = (('a',), ('b',))
tuple(tup + (1,) for tup in tuples)

rawDescription: Updating a tuple of tuples

description: Updating a tuple of tuples


code: [ someDict[k] for k in someList ]

rawDescription: Using a list objects to look up items in a dictionary in Python


code:
df1 = df1.drop_duplicates()

df1 = df1.set_index('Display Name')
df2 = df2.set_index('Display Name')

df2_c = df2.copy()

df2.update(df1)
df1.update(df2_c)

del df2_c

rawDescription: Pandas: Update Multiple Dataframe Columns Using Duplicate Rows From Another Dataframe


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

fig,ax = plt.subplots(1)

x=y=np.arange(11)

ax.plot(x,y,'go-')

def vspandash(thisax,xmark,xwidth=0.6,ndash=10,colour1='r',colour2='m'):

    interval = 1./ndash
    hxwidth = xwidth/2.

    for j in np.arange(0,1,interval*2):
        thisax.axvspan(
                xmin=xmark-hxwidth,xmax=xmark+hxwidth,
                ymin=j,ymax=j+interval,
                facecolor=colour1,alpha=0.25,edgecolor='None'
                )
        thisax.axvspan(
                xmin=xmark-hxwidth,xmax=xmark+hxwidth,
                ymin=j+interval,ymax=j+interval*2.,
                facecolor=colour2,alpha=0.25,edgecolor='None'
                )

# Lets explore the different options
vspandash(ax,2)                           # Default width, number of dashes, and colours
vspandash(ax,4,ndash=20)                  # Increase number of dashes
vspandash(ax,6,xwidth=0.3)                # Change width of shaded region
vspandash(ax,8,colour1='b',colour2='g')   # Change colours of dashes

plt.show()

rawDescription: Pyplot axvspan: Multiple colors in one span (vertically)


code:
number=0
missword="ghost"
while number<3:
    guess = input("What is the missing word? ")
    if guess!="ghost": # Assuming you actually want this to be missword?
        print("Try again")
        number += 1 # Changed to a unary operator, slightly faster.
    elif guess==missword:
        print("Game Over")
        break
    else:
        print("Game over")
        # Is this ever useful?

rawDescription: Conditional Count Loop Python

description: Conditional Count Loop Python


code:
import yourscript # is in yourscript.py

yourclass = yourscript.Yourclass()
yourclass.run()

rawDescription: How to start a Python script from Django website?

description: Start a Python script from Django website


code:
cards = list(range(52)) # your actual cards
random.shuffle(cards)
hand = [cards.pop() for _ in range(5)] # pop first 5 card from shuffled deck
hand

rawDescription: Appending list items to another list randomly


code:
def anno_example(sigma, mu):
    Sample = np.random.normal(mu, sigma, 10000)

    figHS = plt.figure(figsize=(9,6))
    axHS = figHS.add_subplot(1, 1, 1)
    n, histbins, patches = axHS.hist(Sample,100, histtype='step', normed=1)

    axHS.plot(histbins, plt.mlab.normpdf(histbins, mu, sigma))

    axHS.annotate("$\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%i$"%
                  (Sample.mean(), Sample.std(), len(Sample)),
                  xytext=(0.8, 0.85), bbox=dict(boxstyle="sawtooth", fc="w"),
                  xy=(0.8, 0.85), xycoords=axHS.transAxes)
    axHS.annotate(" $\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%s$"%(mu,sigma,"--"),
                  xytext=(0.6, 0.85), bbox=dict(boxstyle="round", fc="w"),
                  xy=(0.6, 0.85), xycoords=axHS.transAxes)

anno_example(0.12, 0.5)
anno_example(0.1,  0.3)
anno_example(0.05, 0.2)

rawDescription: PYTHON: Annotate boxes disapear dependant on range


code:
import httplib2
client = httplib2.Http(ca_certs='ca.crt')
client.add_certificate(key='client_private_key.pem', cert='cert_client.pem', domain='')
headers, resp = client.request(query)

rawDescription: How to create a dual-authentication HTTPS client in Python without (L)GPL libs?

description: Create a dual-authentication HTTPS client in Python without (L)GPL libs


code:
from os import system

cls = lambda: system('cls')

rawDescription: How can I make python import a module as soon as it is Invoked in terminal?

description: Make python import a module as soon as it is Invoked in terminal


code: f.write('some text\n')

rawDescription: How do you write to a new line when writing to a file in Python?

description: Write to a new line when writing to a file in Python


code:
import random

def make_number():
  val = random.random()
  if val < 0.1: #10%
    return 10000
  elif val < 0.3: # 20%
    return 1000
  elif val < 0.6: # 30%
    return 100
  else: # 40%
    return 10

values = [make_number() for i in range(10)]
print (values)

rawDescription: Random amount calculator

description: Random amount calculator


code: conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)

rawDescription: 'None' is Unicode and not NoneType in python sqlite3


code: dot_product = sum(dict_1[key]*dict_2.get(key, 0) for key in dict_1)

rawDescription: Dot product with dictionaries

description: Dot product with dictionaries


code:
import icu # pip install PyICU
sorted(['a','b','c','ä'])
collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))
sorted(['a','b','c','ä'], key=collator.getSortKey)

rawDescription: How do I sort unicode strings alphabetically in Python?

description: Sort unicode strings alphabetically in Python


rawDescription: Accessing positions in lists

description: Accessing positions in lists


rawDescription: wxPython: Execute an event function automatically at program startup

description: WxPython: Execute an event function automatically at program startup


code:
isinstance("foo", basestring)
isinstance(["foo"], basestring)
isinstance(u"foo", basestring)

rawDescription: How to tell if something can be split python

description: Tell if something can be split python


code:
from unittest import defaultTestLoader
nose.run(suite=defaultTestLoader.loadTestsFromTestCase(TALogout_Test))

rawDescription: Test case running twice not once

description: Test case running twice not once


rawDescription: SqlAlchemy Select Relation Type

description: SqlAlchemy Select Relation Type


code:
string         = doubleString / singleString
doubleString   = ~'"([^"]|(\"))*"'
singleString   = ~"'([^']|(\'))*'"

rawDescription: Escaped Strings in Parsing Expression Grammars


code:
from kivy.core.window import Window
with self.canvas:
    self.translate = Translate(Window.width / 2, Window.height / 2.)

rawDescription: Scale python kivy line

description: Scale python kivy line


code:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(args = "demo.exe", stdout=subprocess.PIPE, startupinfo=startupinfo)

rawDescription: Killing the background window when running a .exe from a Python program


code:
class Profile(UpdateView):
    ...
    def get_queryset(self):
        queryset = super(Profile, self).get_queryset()
        if not self.request.user.is_authenticated():
            return queryset.none()
        else:
            return queryset.filter(pk=self.request.user.pk)

rawDescription: How do I stop anyone being able to update anybody's details?

description: Stop anyone being able to update anybody's details


rawDescription: Plot each number array element as a horizontal line


code:
import os

target_dir = "/Users/usename/dirctectory/"

for path, dirs, files in os.walk(target_dir):
    for i in range(len(files)):
        filename, ext = os.path.splitext(files[i])
        newname_pre = 'newname_pre'
        new_file = newname_pre + str(i) + ext

        old_filepath = os.path.join(path, files[i]) # here was the problem
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

rawDescription: rename filenames with index

description: Rename filenames with index


code:
rng = pd.period_range('2013-10-01',periods=24, freq='H').to_timestamp()
df.resample('1H', how=lambda x: len(x)).reindex(index=rng,fill_value=0)

rawDescription: Pandas resample with all day range

description: Pandas resample with all day range


code:
print(' <select name="user">')
os.chdir("D:/users")
for files in os.listdir("."):
    if files.endswith(".txt"):
        print('<option value="D:/users/'+files+'">'+files.replace('.txt','')+'</option>')

print('</select> ')

rawDescription: To make a dynamic dropdown with list of files in a directory using python-cgi


code:
class LogOutput(models.Model):
    raw = models.TextField()

    class Meta:
        abstract = True

class DataFileLogOutput(LogOutput):
    pass

class SuiteFileLogOutput(LogOutput):
    pass

class DataFile(models.Model):
    name = models.CharField()#etc.
    logoutput = models.OneToOneField(DataFileLogOutput)

class Suite(models.Model):
    # Many Suites will have the same datafile:
    datafile = models.ForeignKey(DataFile)

    # Each Suite has a unique LogOutput different from the DataFile's
    # and as with the DataFile, that LogOutput will have just one Suite
    logoutput = models.OneToOneField(SuiteLogOutput)

rawDescription: Use OneToOneField inlined in Django Admin


code: t = Table(name, meta, autoload=True)#, autoload_with=engine)

rawDescription: How to get SqlAlchemy Table to read "implicit" schema

description: Get SqlAlchemy Table to read "implicit" schema


code:
total_task_list = SortedDict( sorted( task_list.items() ) )
# And then:
total_task_list.insert(0, 'Overdue Tasks', [overdue_actions, 0])

rawDescription: Add dictionary to sortedDict

description: Add dictionary to sortedDict


code:
import datetime as dt
hours = [(i, dt.time(i).strftime('%I %p')) for i in range(24)]

rawDescription: Clean way of creating list of hours

description: Clean way of creating list of hours


code:
from PIL import Image
im= Image.open('Tulips.jpg')

out=im.convert("RGB", (
    0.412453, 0.357580, 0.180423, 0,
    0.212671, 0.715160, 0.072169, 0,
    0.019334, 0.119193, 0.950227, 0 ))
out.save("Image2.jpg")

out2=im.convert("RGB", (
    0.9756324, 0.154789, 0.180423, 0,
    0.212671, 0.715160, 0.254783, 0,
    0.123456, 0.119193, 0.950227, 0 ))
out2.save("Image3.jpg")

out3= im.convert("1")
out3.save("Image4.jpg")

out4=im.convert("RGB", (
    0.986542, 0.154789, 0.756231, 0,
    0.212671, 0.715160, 0.254783, 0,
    0.123456, 0.119193, 0.112348, 0 ))
out4.save("Image5.jpg")

out5=Image.blend(im, out4, 0.5)
out5.save("Image6.jpg")

listofimages=['Tulips.jpg', 'Image2.jpg', 'Image3.jpg', 'Image4.jpg', 'Image5.jpg', 'Image6.jpg']

def create_collage(width, height, listofimages):
    cols = 3
    rows = 2
    thumbnail_width = width//cols
    thumbnail_height = height//rows
    size = thumbnail_width, thumbnail_height
    new_im = Image.new('RGB', (width, height))
    ims = []
    for p in listofimages:
        im = Image.open(p)
        im.thumbnail(size)
        ims.append(im)
    i = 0
    x = 0
    y = 0
    for col in range(cols):
        for row in range(rows):
            print(i, x, y)
            new_im.paste(ims[i], (x, y))
            i += 1
            y += thumbnail_height
        x += thumbnail_width
        y = 0

    new_im.save("Collage.jpg")

create_collage(450, 300, listofimages)

rawDescription: Making a collage in PIL

description: Making a collage in PIL


code:
content = """SS Derek_Jeter Yankees
P Johan_Santana Mets
C Ivan_Rodriguez Tigers"""

lines = content.split("\n")

players = []
for x in lines:
  pos, name, team = x.split(' ')
  players.append( Player(name, pos, team) )

# players is a list of the Player objects

rawDescription: Use a word in a string to create an object in Python


code:
from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt

fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(nrows=2, ncols=3)
# add plot code here
ax1.xaxis.set_major_locator(MaxNLocator(nbins=9))
ax1.yaxis.set_major_locator(MaxNLocator(nbins=7))
#repeat for other axes

rawDescription: Number of bins in matplotlib axes (number of majorticks)


code:
order = df.columns
return df.resample('W-Fri', how=ohlc_dict)[order]

rawDescription: Why does Pandas DataFrame Resample change column Order


code:
def merge_lists(list1, list2):
    sortedList = []
    pointer1 = 0
    pointer2 = 0

    while pointer1 < len(list1) and pointer2 < len(list2):
        if list1[pointer1] < list2[pointer2]:
            sortedList.append(list1[pointer1])
            pointer1 += 1
        elif list1[pointer1] > list2[pointer2]:
            sortedList.append(list2[pointer2])
            pointer2 += 1
        else:
            sortedList.append(list1[pointer1])
            pointer1 += 1

    while pointer1 < len(list1):
        sortedList.append(list1[pointer1])
        pointer1 += 1

    while pointer2 < len(list2):
        sortedList.append(list2[pointer2])
        pointer2 += 1

    return sortedList

rawDescription: How to create a sorted list given two already sorted lists ( cannot modify either given lists )

description: Create a sorted list given two already sorted lists ( cannot modify either given lists )


code:
schema = {
  # Simple default
  'title': {
    'type': 'string',
    'default': 'M.'
  },
  # Default in a dict
  'others': {
    'type': 'dict',
    'schema': {
      'code': {
        'type': 'integer',
        'default': 100
      }
    }
  },
  # Default in a list of dicts
  'mylist': {
    'type': 'list',
    'schema': {
      'type': 'dict',
      'schema': {
        'name': {'type': 'string'},
        'customer': {
          'type': 'boolean',
          'default': False
        }
      }
    }
  }
}

rawDescription: How can I set default values in Eve?

description: Set default values in Eve


code:
import bpy
import mathutils

mesh_obj = bpy.context.active_object

minz = 999999.0

for vertex in mesh_obj.data.vertices:
    # object vertices are in object space, translate to world space
    v_world = mesh_obj.matrix_world * mathutils.Vector((vertex.co[0],vertex.co[1],vertex.co[2]))

    if v_world[2] < minz:
        minz = v_world[2]

mesh_obj.location.z = mesh_obj.location.z - minz

rawDescription: Blender - Move mesh so that smallest Z point is on the Z = 0 plane


code:
for comment in comments_generator(client, VIDEO_ID):
        author_name = comment.author[0].name.text
        text = comment.content.text

        post_date = comment.published.text
        last_update_date = comment.update.text

        print("{}(date:{}): {}".format(author_name, post_date, text))

rawDescription: Retrieving timestamp of YouTube comments


code:
html = 'plan_49913.doc
 Document superseded by:  January 2012	'
bs = BeautifulSoup(html)
texts = [ node.next for node in bs.findAll('td') if node.next.endswith('.doc') ]
texts

rawDescription: Beautiful Soup - Grabbing the string after the first specified tag


code:
AOI = []
for t in Town:
    for r in Range:
        for s in Section:
            AOI.append(t + r + s)

rawDescription: Trying to combine (concatenate) elements from 3 lists into one, new list


code:
for val in data:
    if val is not None and (val.end() - val.start()) == 11:
        result.append(val.groupdict())

rawDescription: Additional length check to given RegEx

description: Additional length check to given RegEx


code:
r3 = requests.get('https://api.website.com', params=myhheadersaders2)
struct = r3.json()  # this is the data from the API

car_data = struct.get('List')
fieldnames=car_data[0].keys()

# now you are simply overwriting it with some sample data,
# ignoring whatever is returned from the API
# struct = {'TotalCount': 1, ...}]}

# this is the same as car_data = struct.get('List')
# car_info = struct.get('List')

with open('car_info.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(car_data)

rawDescription: Processing data from API to CSV

description: Processing data from API to CSV


code:
import numpy as N
import matplotlib as M
import matplotlib.pyplot as PLT

# Set up a simple function to plot
x,y = N.meshgrid(range(10),range(10))
values = N.exp(x*y/10. - 1)

levels = N.logspace(-1, 4, 10)
log_norm = M.colors.LogNorm()
# Currently not used - linear scaling
linear_norm = M.colors.Normalize()
# Plot the function using the indices as the x and y axes
PLT.contourf(values, norm=log_norm, levels=levels)
PLT.colorbar(format='%.2f')
PLT.show()

rawDescription: Colorbar does not show values when using LogNorm()


rawDescription: Most efficient way to get the integer index of a key in pandas


code:
from sqlalchemy.sql import between
import datetime
# [all other relevant imports]

td = datetime.timedelta(seconds=2)
t1_entry = session.query(table_1).filter(table_1.name == 'the_name').first()
if t1_entry is not None:
 tmin = t1_entry.date - td
 tmax = t1_entry.date + td
 t2_entry = session.query(table_2).filter(between(table_2.date, tmin, tmax)).first()
 return (t1_entry, t2_entry)
return None

rawDescription: Filter objects within two seconds of one another using SQLAlchemy


code: line[8] = line[8].replace(letter, "")

rawDescription: how do replace all occurrences of certain characters?

description: How do replace all occurrences of certain characters


code:
def get_male_owners(self):
    return [res for res in self.results if res.owner.sex.male]

def get_cards_5_to_10(self):
    return [res for res in self.results if res.car and self.is_5_to_10(res.car)]

def is_5_to_10(self, car):
    return 5 <= car.age <= 10

rawDescription: What's the most Pythonic way to refactor this list building code?


code:
def main():
    # Asks which command you want to run.
    word = input("Which command? ").strip().lower()

    # Runs the command/s.

    if word == "info":
        print("Info command.")

    elif word == "replace":
        print("Replace command.")

    elif word == "ping":
        print("Ping command")

    elif word == "quit":
        return False

    else:
        print("Command not found")
    return True

while main():
    pass

rawDescription: IDLE - Python: Go back to a certain line, how can I do this?


code:
from django.forms.models import model_to_dict, fields_for_model

class UserDetailsForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        _fields = ('first_name', 'last_name', 'email',)
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        super(UserDetailsForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserDetails
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserDetailsForm, self).save(*args,**kwargs)
        return profile

rawDescription: Creating one Django Form to save two models


code:
from matplotlib import pyplot as plt

fig, ax = plt.subplots(1, 1)

ax.hold(True)

patches = ax.bar([1],[1], lw = 20., facecolor = 'w', edgecolor= 'red')
ax.plot([0,2],[0,0], 'k')
ax.plot([0,2],[1,1], 'k')

ax.set_xlim(0.8,2)
ax.set_ylim(-0.2,1.2)

# get the patch object representing the bar
bar = patches[0]

# set the clipping path of the bar patch to be the same as its path. this trims
# off the parts of the bar edge that fall outside of its outer bounding
# rectangle
bar.set_clip_path(bar.get_path(), bar.get_transform())

rawDescription: Matplotlib: How to increase linewidth of bar without changing its size?


code:
from collections import deque

def breadth(self):
    string = ""
    q = deque([self.root])
    while q:
        node = q.popleft()
        string += str(node.data)
        if node.left:
            q.append(node.left)
        if node.right:
            q.append(node.left)
    return string

rawDescription: breadth first search traversal in python

description: Breadth first search traversal in python


code:
rR = "3,28,2"
rR = re.split(r"[\W]+", rR)
map(int, xrange(*map(int, rR)))

rawDescription: Generationg a list from user-input dynamically


code:
from django.db.models import Q

user = request.user
conditions = Q(creator=user) | Q(friend=user)
relevant_friends_list = FriendShip.objects.filter(conditions)

rawDescription: Django How would I filter Friend objects elegantly by name when using the built in User model?


code: newpoints = numpy.array([x.split(',') for x in points], dtype=numpy.float)

rawDescription: split array rows into columns from commas

description: Split array rows into columns from commas


code:
from copy import deepcopy
totalstats = deepcopy(mystats)

rawDescription: Way to save a dictionary as a separate reference in python


code:
nth_byte = 5
with open('old_file_path', 'r') as old_buffer, open('new_file_path', 'w') as new_buffer:
    # copy until nth byte
    new_buffer.write(old_buffer.read(nth_byte))
    # insert new content
    new_buffer.write('this')
    # copy the rest of the file
    new_buffer.write(old_buffer.read())

rawDescription: Append to a file after nth byte in python


code: uploaded_image = im.upload_image(url=URL_OF_IMAGE, title="Uploaded with PyImgur")

rawDescription: Uploading image using pyimgur to imgur, using images link


code:
import os
import cv2

mypath = os.path.join('c:\\', 'asdf', 'jkl')

images = list()
for item in os.listdir(mypath):
    if '.jpg' in item:  # this could be more correctly done with os.path.splitext
        image = cv2.imread(os.path.join(mypath, item))
        if image is not None:
            images.append(image)

rawDescription: Python 2.7 opening multiple files from non-default directory (for opencv)


rawDescription: Decimal zero padding

description: Decimal zero padding


code:
import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)

rawDescription: Python - is there a way to store an operation(+ - * /) in a list or as a variable?


code:
aggr = lambda df: df.apply(tuple)
df.groupby(pd.Grouper(freq='30S', level=0)).aggregate(aggr)

rawDescription: Panda group dataframes into user specified time period


code:
from fabric.api import env, run, sudo, cd
from datetime import datetime

def proxy():
    env.user = "root"
    env.hosts = ['proxy']
    env.key_filename = "/home/root/monitorserver.pem"
    with cd('/home/root/'):
        createfile()
        run("fab production")

def production():
    """Defines production environment ."""
    env.is_debuggable = False
    env.user = "root"
    env.hosts = ['appserver']
    env.key_filename = "/home/root/appserver.pem"
    createfile()

def createfile():
    """Start Excecute test commands"""
    sudo("touch /tmp/test_%s" % datetime.now().strftime('%H:%M:%S'))

rawDescription: Fabric deploying application to a proxyed server


code:
import csv
from cStringIO import StringIO
first=StringIO('hi, welcome')
second=StringIO("'hi,hi',hi")
third=StringIO("'hi, hello,yes','hello, yes','eat,hello'")
fourth=StringIO("'hiello, 332',9")
rfirst=csv.reader(first,quotechar="'")
rfirst.next()
rsecond=csv.reader(second,quotechar="'")
rsecond.next()
rthird=csv.reader(third,quotechar="'")
rthird.next()
rfourth=csv.reader(fourth,quotechar="'")
rfourth.next()
second=StringIO('"hi,hi",hi') # This will be more straightforward to interpret.
r=csv.reader(second)
r.next()
third=StringIO('"hi, hello,yes","hello, yes","eat,hello"')
r=csv.reader(third)
r.next()

rawDescription: Splitting by "," in python

description: Splitting by "," in python


code:
from Tkinter import *
root = Tk()

def callback(var):
    print ("%d" %var)

menubar = Menu(root)

# create a pulldown menu, and add it to the menu bar
filemenu = Menu(menubar, tearoff=0)
filemenu.add("command", label="Open", command=lambda: callback(1))
filemenu.add("command", label="Save", command=lambda: callback(2))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

# create more pulldown menus
editmenu = Menu(menubar, tearoff=0)
editmenu.add("command", label="Cut", command=lambda: callback(3))
editmenu.add("command", label="Copy", command=lambda: callback(4))
editmenu.add("command", label="Paste", command=lambda: callback(5))
menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add("command", label="About", command=lambda: callback(6))
menubar.add_cascade(label="Help", menu=helpmenu)

# display the menu
root.config(menu=menubar)

root.mainloop()

rawDescription: Getting the value of selected item in optionMenu Tkinter


code:
patches, texts = ax.pie(fracs, labels=labels, colors = colors,
                        startangle=10, labeldistance=0.8)
for t in texts:
    t.set_horizontalalignment('center')

plt.show()

rawDescription: Matplotlib Pie Chart Labels Alignment

description: Matplotlib Pie Chart Labels Alignment


code:
import your_module

method_names = ['function1', 'function2']

for name in method_names:
  func = gettattr(your_module, name)
  # invoke now
  func() # Pass in your arguments if needed.

rawDescription: Turning a list of strings into function calls


rawDescription: How to speed up python networking?

description: Speed up python networking


code:
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor

def cpu_bound_operation(x):
    time.sleep(x) # This is some operation that is CPU-bound

@asyncio.coroutine
def main():
    # Run cpu_bound_operation in the ProcessPoolExecutor
    # This will make your coroutine block, but won't block
    # the event loop; other coroutines can run in meantime.
    yield from loop.run_in_executor(p, cpu_bound_operation, 5)

loop = asyncio.get_event_loop()
p = ProcessPoolExecutor(2) # Create a ProcessPool with 2 processes
loop.run_until_complete(main())

rawDescription: How to combine python asyncio with threads?

description: Combine python asyncio with threads


code:
from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing
from wand.compat import nested

with nested(Image(width=100, height=100, background=Color("transparent")),
            Image(width=100, height=100, background=Color("transparent"))) as (text,
                                                                               shadow):
    with Drawing() as ctx:
        ctx.stroke_color = Color("black")
        ctx.fill_color = Color("white")
        ctx.font_size = 48
        ctx.text(text.width/2, text.height/2, 'A')
        ctx(text)
    with Drawing() as ctx:
        ctx.fill_color = Color("navy")
        ctx.font_size = 48
        ctx.text(text.width/2, text.height/2, 'A')
        ctx(shadow)
    shadow.gaussian_blur(80, 3)
    shadow.composite(text, -3, -3)
    shadow.trim()
    shadow.save(filename='shadow_a.png')

rawDescription: Shaped shadows with wand

description: Shaped shadows with wand


code:
translator = { 'BINARY'         : 'RAW',\
           'BFILE'          : 'BFILE',\
           'BLOB'           : 'BLOB',\
           'CLOB'           : 'CLOB',\
           'CURSOR'         : 'CURSOR',\
           'DATETIME'       : 'DATE',\
           'FIXED_CHAR'     : 'CHAR',\
           'FIXED_UNICODE'  : 'NCHAR',\
           'INTERVAL'       : 'INTERVAL',\
           'LONG_STRING'    : 'LONG',\
           'LONG_UNICODE'   : 'LONG ',\
           'NCLOB'          : 'NCLOB',\
           'NUMBER'         : "NUMBER",\
           'OBJECT'         : 'OBJECT',\
           'ROWID'          : 'ROWID',\
           'STRING'         : 'VARCHAR2',\
           'TIMESTAMP'      : 'TIMESTAMP',\
           'UNICODE'        : "NVARCHAR2" }

str_coltype     # example:  "<type 'cx_Oracle.NUMBER'>"
cx_coltp = re.findall("\.([^\.]+)'>$", str_coltype)[0]
ora_coltp = translator[ cx_coltp ]

rawDescription: How to make DDL from cursor.description or a select-statement

description: Make DDL from cursor.description or a select-statement


rawDescription: How to split strings by only the first special character that's within the string?

description: Split strings by only the first special character that's within the string


code:
# X - some data in 2dimensional np.array

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

# here "model" is your model's prediction (classification) function
Z = model(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=pl.cm.Paired)
plt.axis('off')

# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)

rawDescription: plot decision boundary matplotlib

description: Plot decision boundary matplotlib


rawDescription: How to create a class property with a metaclass that only overrides when the class itself doesn't have it defined?

description: Create a class property with a metaclass that only overrides when the class itself doesn't have it defined


code:
import os
import multiprocessing

NUMBER_OF_SESSIONS = 10

def worker():
    while True:
        os.system("dir")

if __name__ == '__main__':
    jobs = []
    for i in range( NUMBER_OF_SESSIONS ):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

rawDescription: How to open multiple cmd sessions through a python script?

description: Open multiple cmd sessions through a python script


code:
def filter_list(li, word):
    return sorted((elem for elem in li if word.lower() in elem.lower()), key=len)

rawDescription: Filter a list and order items by relevance


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig = plt.figure()
ax = fig.add_subplot(111)
bar_0_10 = ax.bar(np.arange(0,10), np.arange(1,11), color="k")
bar_10_100 = ax.bar(np.arange(0,10), np.arange(30,40), bottom=np.arange(1,11), color="g")
# create blank rectangle
extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
ax.legend([extra, bar_0_10, bar_10_100], ("My explanatory text", "0-10", "10-100"))
plt.show()

rawDescription: Is it possible to add a string as a legend item in matplotlib


code:
from heapq import merge
merge(*iterables)

rawDescription: How can I izip in python with sorted output?

description: Izip in python with sorted output


code:
def isCellNeighbor(c1, c2):
   if abs(c1.x - c2.x) == 1: return True
   if abs(c1.y - c2.y) == 1: return True
   return False

rawDescription: DFS Graph Generation in Python

description: DFS Graph Generation in Python


code:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Z = np.random.random(size=(7,7))
x = 10.0 ** np.arange(-2, 5)
y = 10.0 ** np.arange(-4, 3)
ax.set_yscale('log')
ax.set_xscale('log')
ax.pcolor(x, y, Z)

rawDescription: Log x-scale in imshow :: matplotlib

description: Log x-scale in imshow :: matplotlib


code:
import moviepy.editor as mp
clip = mp.VideoFileClip("movie.mp4")
clip_resized = clip.resize(height=360) # make the height 360px
clip_resized.write_videofile("movie_resized.mp4")

rawDescription: How To Resize a Video Clip Python

description: How To Resize a Video Clip Python


code:
import subprocess
subprocess.call(['gksudo','python that_file.py'])

rawDescription: How to gain root privileges in python via a graphical sudo?

description: Gain root privileges in python via a graphical sudo


code:
for c in itertools.combinations(stuff, 7):
    print(c)

rawDescription: Is there a effective way to get only K combinations of a list?


code:
from tkinter import *
import random

def callback():
    nameList = userInput.get().split()
    name = random.choice(nameList)
    Label(root, text=name).pack()

root = Tk()

userInput = StringVar()

ent = Entry(root, textvariable=userInput)
ent.pack()
btn = Button(root, text="Go", command=callback)
btn.pack()

root.mainloop()

rawDescription: Python & tkinter: input names and then select one at random


code:
return render_to_response('MeetingHub/addmeeting.html',
    {'meetingform': meetingform, 'message':message,
    'meeting': meeting, 'participants': participants,
    #... and anything else that might be helpful to show on the page
    },
    context_instance=RequestContext(request))

rawDescription: returning a list of objects with HttpResponseRedirect

description: Returning a list of objects with HttpResponseRedirect


code:
import os
import shutil as sh
from collections import defaultdict

DESKTOP = '/home/mac/Desktop'

#This dictionary will contain: <extension>: <list_of_files> mappings
register = defaultdict(list)

#Populate the register
for dir_, dirs, fnames in os.walk('/home/mac/Desktop'):
    for fname in fnames:
        register[fname.rsplit('.', 1)[1]].append(os.path.join(dir_, fname))

#Iterate over the register, creating the directory and moving the files
#with that extension in it.
for dirname, files in register.iteritems():
    dirname = os.path.join(DESKTOP, dirname)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    for file_ in files:
        sh.move(file_, dirname)

rawDescription: Find files with extension in directory and subdirectories?


code:
import json
data = json.loads(...)

rawDescription: Where to start with parsing JSON?

description: Where to start with parsing JSON


code:
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
)

STATIC_URL = '/static/'

rawDescription: how to share a folder in django development server depyloment

description: Share a folder in django development server depyloment


rawDescription: How to convert BeautifulSoup.ResultSet to string

description: Convert BeautifulSoup.ResultSet to string


code:
import numpy as np
mychar = 'd'
np.array(list(np.binary_repr(ord(mychar), width=4))).astype('bool')

rawDescription: python: convert ascii character to boolean array

description: Python: convert ascii character to boolean array


code:
import numpy as np

import traits.api as traits
import traitsui.api as ui
import chaco.api as chaco
from enable.api import ComponentEditor

class PlotController(ui.Controller):
    view = ui.View(ui.Item('plot', editor=ComponentEditor(), show_label=False),
                   height=300, width=300, resizable=True)

    def object_close_signal_changed(self, info):
        info.ui.dispose()

class BasicPlot(traits.HasTraits):
    close_signal = traits.Event()
    plot = traits.Instance(chaco.Plot)

class LinePlot(BasicPlot):

    def __init__(self, plotdata):
        self.plot = chaco.Plot(plotdata)
        self.plot.plot(('x', 'y'))

class BarPlot(BasicPlot):

    def __init__(self, plotdata):
        self.plot = chaco.Plot(plotdata)
        self.plot.candle_plot(('x', 'ymin', 'ymax'))

available_plot_types = dict(line=LinePlot, bar=BarPlot)

class PlotSelector(traits.HasTraits):

    plot_type = traits.Enum(['line', 'bar'])
    traits_view = ui.View('plot_type', style='custom')

    def __init__(self, x, y):
        ymin = y - 1
        ymax = y + 1
        self.plotdata = chaco.ArrayPlotData(x=x, y=y, ymin=ymin, ymax=ymax)
        self.figure = None

    def _plot_type_changed(self):
        plot_class = available_plot_types[self.plot_type]
        if self.figure is not None:
            self.figure.close_signal = True
        self.figure = plot_class(self.plotdata)
        controller = PlotController(model=self.figure)
        controller.edit_traits()

N = 20
x = np.arange(N)
y = x + np.random.normal(size=N)
plot_selector = PlotSelector(x, y)
plot_selector.configure_traits()

rawDescription: Dynamically create plots in Chaco

description: Dynamically create plots in Chaco


code:
import xlrd
import xlwt
import xlutils
from xlutils.copy import copy

r_book = xlrd.open_workbook(fname)
w_book = xlutils.copy.copy(r_book)
r_sheet = r_book.sheets()[0] # Taking the first sheet
w_sheet = w_book.get_sheet(0)

x_y_value = r_sheet.cell(X, Y).value
w_sheet.write(A, B, x_y_value)
w_book.save(fname)

rawDescription: Copying value of cell (X,Y) to cell (A,B) in same sheet of an Excel file using Python


code:
minstat = {}
for month in stat2011:
    minstat[month] = min(stat2011[month], stat2012[month], stat2013[month])

rawDescription: Finding MIN & MAX values across 3 different dictionaries


code:
by_first = df.groupby('first_bp_intron')
df['phi5'] = by_first['unique_junction_reads'].transform(lambda x: x/x.sum())
by_last = df.groupby('last_bp_intron')
df['phi3'] = by_last['unique_junction_reads'].transform(lambda x: x/x.sum())
df

rawDescription: pandas groupby add column from apply operation

description: Pandas groupby add column from apply operation


rawDescription: How do I convert a list of ascii values to a string in python?

description: Convert a list of ascii values to a string in python


code:
from decimal import Decimal
x = Decimal('0.0000000001')
y = Decimal('-0.00000000001')

rawDescription: Hold large number in Python Variable

description: Hold large number in Python Variable


code:
with open("tile.txt", "a+") as f:
    for line in code.splitlines():
        f.write(line + '\n') # Add new line at the end of each line
        print("    "+line)

rawDescription: Write to a file python

description: Write to a file python


code:
sorted(known, key=known.get, reverse=True)
''.join(sorted(known, key=known.get, reverse=True))

rawDescription: Map two dictionaries by the highest values


code:
parser = etree.XMLParser(remove_blank_text=True) # lxml.etree only!
root = etree.XML("<root>  <a/>   <b>  </b>     </root>", parser)
etree.tostring(root)

rawDescription: Stripping spaces between XML nodes with Python


code:
import cv2
import numpy as np

def main():
    lower_pink = np.array([160, 50, 50])
    upper_pink = np.array([180, 255, 255])
    threshold = 100  # TODO Adapt to your needs.
    cap = cv2.VideoCapture(0)

    while True:
        _, frame = cap.read()
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv, lower_pink, upper_pink)
        masked = cv2.bitwise_and(frame, frame, mask=mask)
        cv2.imshow('frame', frame)
        cv2.imshow('mask', mask)
        cv2.imshow('masked', masked)
        # if cv2.countNonZero(mask) > threshold:
        #     print('FOUND')
        #     break
        print(cv2.countNonZero(mask))
        #
        # Wait for escape key.
        #
        if cv2.waitKey(500) == 27:
            break

    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

rawDescription: Stop the webcam after it detects a specific color


code:
ax = fig.add_subplot(111)

ax.plot(x1, np.zeros(x1.shape), 'b+', ms=20)  # rug plot
x_eval = np.linspace(-10, 10, num=200)
ax.plot(x_eval, kde1(x_eval), 'k-', label="Scott's Rule")
ax.plot(x_eval, kde1(x_eval), 'r-', label="Silverman's Rule")

rawDescription: how to make rug plot in matplotlib

description: Make rug plot in matplotlib


code: data_all = (data - np.min(data, axis=0))/(np.max(data, axis=0) - np.min(data, axis=0))

rawDescription: Less code lines for scaling and stacking columns in numpy


code: os.environ['PATH'] = '/home/foo/bar/bin:' + os.environ['PATH']

rawDescription: Python ENV file overwritten by PHP ENV

description: Python ENV file overwritten by PHP ENV


rawDescription: Define string between comma x and comma y the split all bytes using a comma


code: print('.', end='', flush=True)

rawDescription: Print on the same line, step after step

description: Print on the same line, step after step


code:
from bs4 import BeautifulSoup

html = """

                500k
                £4.71
                £23.53

"""
soup = BeautifulSoup(html)
for item in soup.find_all('tr', {'data-price': True}):
    print(item['data-price'])

# 4.7056

rawDescription: Website Scraper

description: Website Scraper


rawDescription: Sum identical elements of an array based on their indicies


code:
import threading
import time

class Typewriter(threading.Thread):
    def __init__(self, your_string):
        threading.Thread.__init__(self)
        self.my_string = your_string

    def run(self):
        for char in my_string:
            libtcod.console_print(0,3,3,char)
            time.sleep(50)

# make it type!
typer = Typewriter(your_string)
typer.start()
# wait for it to finish if you want to
typer.join()

rawDescription: async wait / non blocking wait in python

description: Async wait / non blocking wait in python


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

from gi.repository import Gtk

PEOPLE =    [
            "Frank",
            "Martha",
            "Jim Bob",
            "Francis"
            ]

class TreeCombo(object):
    def __init__(self):
        self.win = Gtk.Window(title="Combo with liststore")
        self.win.connect('delete-event', Gtk.main_quit)

        self.store = Gtk.ListStore(str)
        for person in PEOPLE:
            self.store.append([person])

        # self.combo = Gtk.ComboBox.new_with_model(self.store)
        self.combo = Gtk.ComboBox()

        self.tree = Gtk.TreeView(self.store)
        self.selector = self.tree.get_selection()
        self.selector.set_mode(Gtk.SelectionMode.MULTIPLE)

        self.combo_cell_text = Gtk.CellRendererText()

        self.column_text = Gtk.TreeViewColumn("Text", self.combo_cell_text, text=0)

        self.tree.append_column(self.column_text)

        self.combo.add(self.tree)

        self.win.add(self.combo)

        self.win.show_all()

def main():
    prog = TreeCombo()
    Gtk.main()

if __name__ == "__main__":
    main()

rawDescription: How to choose multiple items in a GTK combobox in python

description: Choose multiple items in a GTK combobox in python


code:
from jsonschema import Draft3Validator
my_schema = json.loads(my_text_file) #or however else you end up with a dict of the schema
Draft3Validator.check_schema(schema)

rawDescription: How do I validate a JSON Schema schema, in Python?

description: Validate a JSON Schema schema, in Python


rawDescription: Spacing/empty border for wxWidgets

description: Spacing/empty border for wxWidgets


code:
ax = plt.gca()
ax.grid(True)
ax.plot(millionspins, millions, marker='+', color='b')

rawDescription: Axis plotting in python - matplotlib

description: Axis plotting in python - matplotlib


code:
def onecmd(self, line):
  if not line:
    return self.emptyline()
  if cmd is None:
    return self.default(line)
  self.lastcmd = line
  if cmd == '':
    return self.default(line)
  else:
    # iterate over all submodules that have been added including ourselves
    # self.submodules would just be a list or set of all submodules as mentioned above
    func = None
    for submod in self.submodules:
      # just return the first match we find
      if hasattr(submod, 'do_%s' % cmd):
        func = getattr(submod, 'do_%s' % cmd)
        break # instead of breaking, you could also add up all the modules that have
              # this method, and tell the user to be more specific
    if func is not None:
      return func(arg)
    else:
      return self.default(line)

rawDescription: How to structure a python cmd application which has separate command modules

description: Structure a python cmd application which has separate command modules


code: rhs = sol.rhs

rawDescription: Sympy right hand side of inequality

description: Sympy right hand side of inequality