code:
if len(h) < capacity:
    heapq.heappush(h, thing)
else:
    # Equivalent to a push, then a pop, but faster
    spilled_value = heapq.heappushpop(h, thing)
    do_whatever_with(spilled_value)

rawDescription: Maintain a fixed size heap -python

description: Maintain a fixed size heap -python


code: outcome = "".join([your_decoder.decode(x) for x in string.split(" ")])

rawDescription: How do i convert a string of ascii values to there original character/number in python

description: Convert a string of ascii values to there original character/number in python


code:
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'your_host', 'port': 9200}])

q = {"filter":
        {"term":
            {"job desc": "Data Analyst"}
        },
     "_source": {
            "include": ['job place']
        }
    }
# Assume you want "Data Analyst" in the "job desc" field

result = es.search(index='my_index', doc_type='job_list', body=q)

rawDescription: Elastic Search query filtering

description: Elastic Search query filtering


code: { keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] }

rawDescription: Python - can a dict have a value that is a list?


code:
from django.db import models

class MyModel(models.Model):
    date = models.DateField(auto_now_add=True)

rawDescription: Time at which tuple was generated in Django


code:
class Foo(object):
    def __init__(self, max=5, cache=False):
        if cache:
            self.iterable = range(max)
        else:
            self.iterable = iter(xrange(max))

    def __iter__(self):
        return iter(self.iterable)

rawDescription: Define method in init

description: Define method in init


code: db.locations.aggregate([{'$unwind': '$events'}, {'$match': {'events.displayed': True}}])

rawDescription: Optimize double loop//make selection in python or mongodb


code:
import math
dir(math)
help(math.ceil)

rawDescription: In Python how do you put a program inside a program


code:
row = array([0,0,1,2,2,2])
col = array([0,2,2,0,1,2])
data = array([1,2,3,4,5,6])
a = csr_matrix((data, (row, col)), shape=(3,3))
a.A
a.sum(axis=0)  # sum the columns
a.sum(axis=1)  # sum the rows

rawDescription: How to get sum of each row and sum of each column in Scipy sparse matrices (csr_matrix and csc_matrix)?

description: Get sum of each row and sum of each column in Scipy sparse matrices (csr_matrix and csc_matrix)


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

text = '''\
| ID | SourceID | TargetID | Parameter | Values  |
| 1  |    21    |    34    | 23.46513  | 0.12654 |
| 2  |    21    |    34    | 23.46513  | 0.25478 |
| 3  |    21    |    46    | 23.46513  | 0.43564 |
| 4  |    21    |    46    | 23.46513  | 1.02487 |
| 5  |    34    |    21    | 14.56319  | 0.01476 |
| 6  |    34    |    21    | 14.56319  | 0.87265 |
| 7  |    34    |    46    | 14.56319  | 0.46478 |
| 8  |    34    |    46    | 14.56319  | 0.13665 |
| 9  |    46    |    21    | 7.99581   | 0.04189 |
| 10 |    46    |    21    | 7.99581   | 0.91754 |
| 11 |    46    |    34    | 7.99581   | 0.73688 |
| 12 |    46    |    34    | 7.99581   | 0.24299 |'''

def make_table(filename):
    # make sqlite table
    with sqlite3.connect(filename) as con:
        df = pd.read_table(io.BytesIO(text), sep=r'\s*[|]\s*').iloc[:, 1:-1]
        df.to_sql('dataset', con=con, if_exists='replace')

filename = '/tmp/data.sqlite'
make_table(filename)

with sqlite3.connect(filename) as con:
    sql = '''
        SELECT SourceID, TargetID, min(`Values`) as min_value
          FROM dataset
          GROUP BY SourceID, TargetID
    '''
    df = pd.read_sql(sql, con)
    table = df.pivot(index='SourceID', columns='TargetID', values='min_value')

    sql = 'SELECT DISTINCT SourceID FROM dataset ORDER BY Parameter ASC'
    order = pd.read_sql(sql, con)['SourceID']
    table = table.reindex(index=order, columns=order)

    fig, ax = plt.subplots()
    ax.pcolor(table.values, cmap=plt.get_cmap('jet'),
              vmin=df['min_value'].min(), vmax=df['min_value'].max())
    ax.set_xticks(np.arange(table.shape[1] + 1)+0.5, minor=False)
    ax.set_xticklabels(table.columns, minor=False)
    ax.set_yticks(np.arange(table.shape[0] + 1)+0.5, minor=False)
    ax.set_yticklabels(table.index, minor=False)
    ax.set_xlim(0, table.shape[1])
    ax.set_ylim(0, table.shape[0])
    plt.show()

rawDescription: Retrieving and plotting ordered, 2D heatmap data from a SQLite database


code:
ts = np.arange(10)

for i in range(len(ts)-2):
    print(ts[2+i:None if i == 0 else i - 1:-1])

rawDescription: numpy array indexing with negative index

description: Numpy array indexing with negative index


rawDescription: Getting a grid of a matrix via logical indexing in Numpy


code:
import urllib, urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def queXF():
    register_openers()
    url = "http://lilix2/trunk/admin/new.php"
    values = {'form':open('test.pdf'),
          'bandingxml':open('banding.xml'),
          'desc':'description'}
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    request = urllib2.Request(url, data, headers)
    request.unverifiable = True
    response = urllib2.urlopen(request)
    the_page = response.read()

rawDescription: Trying to post multipart form data in python, won't post


rawDescription: Remove widget in gtk.Table?

description: Remove widget in gtk.Table


code:
from tkinter import *
from tkinter.font import Font
import functools
import math
import random
import time

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

class Pong(Canvas):

    DEFAULTS = dict(width=640,
                    height=480,
                    background='black',
                    highlightthickness=0)

    @classmethod
    def main(cls):
        root = Tk()
        root.title('Pong')
        root.resizable(False, False)
        root.bind_all('<Escape>', lambda event: root.destroy())
        game = cls(Font(family='Book Antiqua', size=15, weight='bold'), 5, 100,
                   background='black', width=640, height=480)
        game.grid()
        root.mainloop()

    def __init__(self, font, lives, fps, master=None, cnf={}, **kw):
        for item in self.DEFAULTS.items():
            kw.setdefault(*item)
        super().__init__(master, cnf, **kw)
        self.font = font
        self.p1 = Paddle(lives, 'blue', 10,
                         self.height, 120, 15, 5)
        self.p2 = Paddle(lives, 'blue', self.width - 10,
                         self.height, 120, 15, 5)
        self.wait = 1000 // fps
        self.separator = Box(Point(self.width // 2 - 2, 0),
                             Point(self.width // 2 + 2, self.height))
        self.new_rect(self.separator, 'white')
        self.bind('<p>', self.pause)
        self.p1.bind(self, 'w', 's')
        self.p2.bind(self, 'Up', 'Down')
        self.draw_high = True
        self.after_idle(self.startup)
        self.focus_force()

    def pause(self, event):
        if not self.running_startup:
            self.refresh = self.after_cancel(self.refresh) \
                           if self.refresh else self.after_idle(self.animate)

    def startup(self, countdown=3, target=None):
        if target is None:
            self.running_startup = True
            self.ball = Ball('white', self.width, self.height, 20)
            self.refresh = None
            target = time.clock() + countdown
        for paddle in self.p1, self.p2:
            paddle.center()
        self.draw_all()
        remaining = math.ceil(target - time.clock())
        if remaining:
            self.new_text(Point(self.width >> 1, self.height >> 1),
                          self.random_color(), str(remaining), CENTER)
            self.after(self.wait, self.startup, None, target)
        else:
            self.running_startup = False
            self.after_idle(self.animate)

    @classmethod
    def random_color(cls):
        return '#{:02X}{:02X}{:02X}'.format(*cls.random_bytes(3))

    @staticmethod
    def random_bytes(n):
        return bytes(random.randrange(1 << 8) for _ in range(n))

    def animate(self):
        self.move_all()
        if self.in_bounds():
            self.draw_all()
            self.refresh = self.after(self.wait, self.animate)

    def move_all(self):
        for obj in self.p1, self.p2, self.ball:
            obj.move()
            if obj is not self.ball:
                obj.bounce(self.ball)

    def in_bounds(self):
        if self.boundary.intersects(self.ball.boundary):
            return True
        if (self.p2 if self.ball.position.x > 0 else self.p1).kill():
            self.after_idle(self.startup)
        else:
            self.draw_all()
            self.after(5000, self.quit)
        return False

    def draw_all(self):
        self.delete('actor')
        for obj in self.p1, self.p2, self.ball:
            obj.render(self)
        self.render_status()

    def render_status(self, x_margin=4, y_margin=4):
        self.draw_high = high = (self.ball.position.y > self.height * 0.25) \
                                if self.draw_high else \
                                (self.ball.position.y >= self.height * 0.75)
        if high:
            self.new_text(self.separator.NW + Point(-x_margin, +y_margin),
                          'white', self.p1.status, NE)
            self.new_text(self.separator.NE + Point(+x_margin, +y_margin),
                          'white', self.p2.status, NW)
        else:
            self.new_text(self.separator.SW + Point(-x_margin, -y_margin),
                          'white', self.p1.status, SE)
            self.new_text(self.separator.SE + Point(+x_margin, -y_margin),
                          'white', self.p2.status, SW)

    def new_rect(self, box, color, tag='static'):
        self.create_rectangle(box, fill=color, outline=color, tag=tag)

    def new_oval(self, box, color, tag='static'):
        self.create_oval(box, fill=color, outline=color, tag=tag)

    def new_text(self, point, color, text, anchor, tag='actor'):
        self.create_text(point, fill=color, tag=tag,
                         text=text, anchor=anchor, font=self.font)

    @property
    def width(self):
        return int(self['width'])

    @property
    def height(self):
        return int(self['height'])

    @property
    def boundary(self):
        return Box(Point(0, 0), Point(self.width, self.height))

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

def enum(names):
    return type('enum', (), dict(map(reversed, enumerate(
        names.replace(',', ' ').split())), __slots__=()))()

def copy_sign(x, y):
    return type(x)(math.copysign(x, y))

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

class Paddle:

    PART = enum('null, upper, center, lower')

    def __init__(self, lives, color, alignment, board_height,
                 paddle_height, paddle_width, move_by):
        self.lives = lives
        self.color = color
        self.height = board_height
        self.position = Point(alignment, board_height >> 1)
        self.size = Point(paddle_width >> 1, paddle_height >> 1)
        self.move_by = move_by
        self.score = 0
        self.just_bounced = False

    def kill(self):
        self.lives -= 1
        self.score >>= 1
        return self.lives > 0

    def center(self):
        y, middle = self.position.y, self.height >> 1
        if y < middle:
            self.move(down=True)
        elif y > middle:
            self.move(up=True)

    def move(self, *, up=False, down=False):
        if up or (not down and self.keys.up and
                  self.position.y - self.size.y > 0):
            self.position -= Point(0, self.move_by)
        if down or (not up and self.keys.down and
                    self.position.y + self.size.y < self.height):
            self.position += Point(0, self.move_by)

    def bounce(self, ball):
        minimum = self.size.x + ball.radius
        if self.position.x != ball.position.x and self.overlap(ball, minimum):
            if not self.just_bounced:
                self.just_bounced = True
                self.score += abs(ball.velocity.y)
            sign = +1 if self.position.x < ball.position.x else -1
            if self.collision_area == self.PART.center:
                ball.position.x = self.position.x + minimum * sign
            else:
                ball.position.adjust(self.middle_point, minimum)
            ball.velocity.x = copy_sign(ball.velocity.x, sign)
            ball.change_speed()
        else:
            self.just_bounced = False

    def overlap(self, ball, minimum):
        box = self.boundary
        if box.intersects(ball.boundary):
            self.collision_area = self.PART.center
        elif (self.hi_mid(box) - ball.position).magnitude <= minimum:
            self.collision_area = self.PART.upper
        elif (self.lo_mid(box) - ball.position).magnitude <= minimum:
            self.collision_area = self.PART.lower
        else:
            self.collision_area = self.PART.null
        return self.collision_area

    def render(self, surface):
        box = self.boundary
        surface.new_rect(box, self.color, 'actor')
        surface.new_oval(Box.from_point(self.hi_mid(box), self.size.x),
                         self.color, 'actor')
        surface.new_oval(Box.from_point(self.lo_mid(box), self.size.x),
                         self.color, 'actor')

    def hi_mid(self, boundary):
        self.middle_point = Point(self.position.x, boundary.a.y)
        return self.middle_point

    def lo_mid(self, boundary):
        self.middle_point = Point(self.position.x, boundary.b.y)
        return self.middle_point

    def bind(self, surface, up, down):
        self.keys = KeyListener(surface, up=up, down=down)

    @property
    def boundary(self):
        return Box.from_point(self.position, self.size)

    @property
    def status(self):
        return 'Lives: {}\nScore: {}'.format(self.lives, self.score)

Player = Paddle

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

class KeyListener:

    def __init__(self, widget, **kwargs):
        self.__state = dict.fromkeys(kwargs, False)
        for name, key in kwargs.items():
            widget.bind('<KeyPress-{}>'.format(key), self.__set(name, True))
            widget.bind('<KeyRelease-{}>'.format(key), self.__set(name, False))

    def __set(self, name, value):
        def handler(event):
            self.__state[name] = value
        return handler

    def __getattr__(self, name):
        return self.__state[name]

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

class Ball:

    def __init__(self, color, width, height, size):
        self.color = color
        self.board = Point(width, height)
        self.position = self.board / 2
        self.radius = size >> 1
        self.velocity = Point(1 - 2 * random.randrange(2),
                              1 - 2 * random.randrange(2))
        self.change_speed()

    def change_speed(self, max_x=10, max_y=10):
        speed = self.velocity
        speed.x = copy_sign(random.randint(1, max_x), speed.x)
        speed.y = copy_sign(random.randint(1, max_y), speed.y)

    def move(self):
        self.position += self.velocity
        self.bounce()

    def bounce(self):
        if self.position.y - self.radius < 0:
            self.position.y = self.radius
            self.velocity.y = copy_sign(self.velocity.y, +1)
            self.change_speed()
        elif self.position.y + self.radius > self.board.y:
            self.position.y = self.board.y - self.radius
            self.velocity.y = copy_sign(self.velocity.y, -1)
            self.change_speed()

    def render(self, surface):
        surface.new_oval(self.boundary, self.color, 'actor')

    @property
    def boundary(self):
        return Box.from_point(self.position, self.radius)

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

def autocast(function):
    @functools.wraps(function)
    def cast(self, other):
        if not isinstance(other, self.__class__):
            other = self.__class__(other, other)
        return function(self, other)
    return cast

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

class Point(list):

    def __init__(self, x, y):
        super().__init__((x, y))

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__,
                               ', '.join(map(repr, self)))

    @autocast
    def __add__(self, other):
        return self.__class__(self.x + other.x, self.y + other.y)

    @autocast
    def __sub__(self, other):
        return self.__class__(self.x - other.x, self.y - other.y)

    @autocast
    def __mul__(self, other):
        return self.__class__(self.x * other.x, self.y * other.y)

    @autocast
    def __truediv__(self, other):
        return self.__class__(self.x / other.x, self.y / other.y)

    @autocast
    def __floordiv__(self, other):
        return self.__class__(self.x // other.x, self.y // other.y)

    @autocast
    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self

    @autocast
    def __isub__(self, other):
        self.x -= other.x
        self.y -= other.y
        return self

    def __get_x(self):
        return self[0]

    def __set_x(self, value):
        self[0] = value

    x = property(__get_x, __set_x)

    def __get_y(self):
        return self[1]

    def __set_y(self, value):
        self[1] = value

    y = property(__get_y, __set_y)

    def __get_magnitude(self):
        return math.hypot(self.x, self.y)

    def __set_magnitude(self, value):
        magnitude = self.magnitude
        self.x *= value / magnitude
        self.y *= value / magnitude

    magnitude = property(__get_magnitude, __set_magnitude)

    def adjust(self, projected_from, distance):
        vector = self - projected_from
        vector.magnitude = distance
        self.x = round(projected_from.x + vector.x)
        self.y = round(projected_from.y + vector.y)

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

class Box(list):

    @classmethod
    def from_point(cls, point, extension):
        return cls(point - extension, point + extension)

    def __init__(self, a, b):
        super().__init__((a, b))

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__,
                               ', '.join(map(repr, self)))

    def intersects(self, other):
        return not (self.a.x > other.b.x or other.a.x > self.b.x or
                    self.a.y > other.b.y or other.a.y > self.b.y)

    def __get_a(self):
        return self[0]

    def __set_a(self, value):
        self[0] = value

    a = NW = property(__get_a, __set_a)

    def __get_b(self):
        return self[1]

    def __set_b(self, value):
        self[1] = value

    b = SE = property(__get_b, __set_b)

    @property
    def NE(self):
        return Point(self.b.x, self.a.y)

    @property
    def SW(self):
        return Point(self.a.x, self.b.y)

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

if __name__ == '__main__':
    Pong.main()

rawDescription: How do you control two different objects seperately(two player pong game)?

description: Control two different objects seperately(two player pong game)


code:
def raw_git(function):
    @wraps(function)
    def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
            log_name=None, remove_logs=None):
        try:
            repo = Repo(ABSOLUTE_PATH)
            git = repo.git
        except NoSuchPathError:
            raise Exception("Error in finding local git path!")
        original_function = function(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
                log_name, remove_logs)
        return original_function
    return wrapper

@raw_git
def git_add_log(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
        log_name=None, remove_logs=None):
    log_name = GIT_WORKING_DIR + "/" + log_name
    try:
        git.add(log_filename)
        git.commit(message="Removing oldest logs")
        git.push()
    except GitCommandError:
        raise Exception("There was an error with git command "
                "for removing oldest log(s)")

rawDescription: Python Decorator Object Not Being Available


code:
df = pd.DataFrame(index=['a', 'b'])
df.index.values

rawDescription: Pandas - how to get the data frame index as an array


code:
from scipy.signal import argrelmax
f = xf[scipy.signal.argrelmax(yf[0:N/2])]
Af = np.abs(yf[argrelmax(yf[0:N/2])])

rawDescription: FFT coefficients using python

description: FFT coefficients using python


rawDescription: Numpy: Multiplying a matrix with a 3d tensor -- Suggestion


code:
def expanded(widget, padding=0):
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(widget, 1, wx.EXPAND|wx.ALL, padding)
    return sizer

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text = wx.StaticText(self, label='Panel 1')
        self.SetSizer(expanded(self.text))

rawDescription: Getting a WxPython panel item to expand

description: Getting a WxPython panel item to expand


code: row_id = getattr(row, id_column)

rawDescription: python - string conversion

description: Python - string conversion


code:
def total_len(bst):
    if isinstance(bst, tuple):
        if bst == ():
            return 0
        else:
            return total_len(bst[0]) + total_len(bst[1:])
    else:
        return len(bst)

rawDescription: Python 3.4.3.: sum of all the lengths of strings in binary string tree


code:
def prettify(elem, doctype=None):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    if doctype is not None:
        reparsed.insertBefore(doctype, reparsed.documentElement)
    return reparsed.toprettyxml(indent="  ", encoding = 'utf-8')

doctype = minidom.getDOMImplementation('').createDocumentType(
    'smil', '-//W3C//DTD SMIL 2.0//EN',
    'http://www.w3.org/2001/SMIL20/SMIL20.dtd')

rawDescription: Remove XML Version Tag from ElementTree using Python


code:
import re
to_parse = '@10 points = { ( 2.96296 , 0.822213 ) ( 3.7037 , 0.902167 ) } ; L = { 5.20086 } ; P = { 3.14815 3.51852 } ;'

m_list = re.findall(r'(\w+)\s*=\s*{([^}]*)}', to_parse)
measurements = {}
for k,v in m_list:
    if k == 'points':
        elts = re.findall(r'([0-9.]+)\s*,\s*([0-9.]+)', v)
        measurements[k] = [tuple(map(float, elt)) for elt in elts]
    else:
        measurements[k] = [float(x) for x in v.split()]

print(measurements)

rawDescription: Extracting data from string with specific format using Python


rawDescription: Sort a list efficiently which contains only 0 and 1 without using any builtin python sort function?


code:
self.frame = QtGui.QGroupBox(self)
self.frame.setTitle("Hello World")

rawDescription: PyQt Frame with text

description: PyQt Frame with text


rawDescription: Pythonic Way to Sum List of Lists of Strings


rawDescription: writing a python script that calls different directories

description: Writing a python script that calls different directories


code:
from copy import deepcopy

tmp_colors = deepcopy(colors)

rawDescription: how to copy class object in an array in Python

description: Copy class object in an array in Python


code:
libc = CDLL('libc.so.6') # on Debian/Linux
printf = libc.printf
printf.restype = c_int
printf.argtypes = [POINTER(c_char), c_int]
printf('< %08x >', 1234)

rawDescription: passing python array to c++ function using ctypes

description: Passing python array to c++ function using ctypes


code:
import numpy
a = numpy.arange(10)
# [0 1 2 3 4 5 6 7 8 9]
## Replace a[2:7] with length-2 noise:
insert = -1 * numpy.ones((2))
new = slice(2, 4)
old = slice(2, 7)
#Just to indicate what we'll be replacing:
a[old] = 0
# [0 1 0 0 0 0 0 7 8 9]
a[new] = insert
# [0 1 -1 -1 0 0 0 7 8 9]
#Shift the remaining data over:
a[new.stop:(new.stop - old.stop)] = a[old.stop:]
# [0 1 -1 -1 7 8 9 7 8 9]
#Zero out the dangly bit at the end:
a[(new.stop - old.stop):] = 0
# [0 1 -1 -1 7 8 9 0 0 0]

rawDescription: Replace part of numpy 1D array with shorter array


rawDescription: Tor's stem module (python) loading but not unloading config


code:
while(true):
        i = 0
        while(i < 60):
           try:
               i += 1
               time.sleep(1)
           except KeyboardInterrupt:
                input('Press enter to continue')

rawDescription: How to interrupt a python program?

description: Interrupt a python program


code:
import random

list_of_lists = [
    ['one', 'two', 'three'],
    [1, 2, 3],
    ['foo', 'bar', 'nothing']
]

list_of_iters = [iter(s) for s in list_of_lists]

while list_of_iters:
    key = random.randrange(0, len(list_of_iters))
    random_iter = list_of_iters[key]
    try:
        item = next(random_iter)
    except StopIteration:
        del list_of_iters[key]
        continue
    print(item)

rawDescription: Randomly switch between lists but preserve order of the items


code:
import re
s = """
foo
<?xml-stylesheet type="text/xsl" href="http://www.google.com"?>
bar"""
re.search(r'<\?xml-stylesheet[^>]*?\?>', s)
m = re.search(r'<\?xml-stylesheet[^>]*?\?>', s)
m.group()

rawDescription: What will be regex expression

description: What will be regex expression


code:
dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }
{key: dict(dict1[key], **dict2[key]) for key in dict1}
# ---Or---
{keys: dict(dict1[keys].items() + dict2[keys].items()) for keys in dict1}

rawDescription: Joining values of two dicts by matching key value


code:
#define a key method
        #determine the key using each set of letters, such as the letters of a word in
        #alphabetical order
        #keyof("word") returns "dorw"
        #keyof("dad") returns "add"
        #keyof("add") returns "add"

#ingest the word set method
    #put the word set into a dictionary which maps
    #key->list of up to 10 angrams

#get angrams method
    #accept a word as a parameter
    #convert the word to its key
    #look up the key in the dictionary
    #return the up to 10 angrams

#test case: add "dad" and "add" to the word set.
#    getting angrams for "dad" should return "dad" and "add"
#test case: add "palm" and "lamp" to the word set.
#    getting angrams for "palm" should return "palm" and "lamp"

#consider storing 11 angrams in the list
#a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11.
#Then if a01 is provided, you can return a02-a11, which is 10 angrams

rawDescription: pseudo code in python

description: Pseudo code in python


code:
correct_values = []
for value in p:
    #if eval(d[0], value) and eval(d[1], value):   # basic version
    if all(eval(exp, value) for exp in d):       # ehanced version thanks to @isbadawi
       correct_values.append(value)

rawDescription: Can't process list of dicts against list of strings


code:
from pysnmp.hlapi import *

for errorIndication, errorStatus, \
    errorIndex, varBinds in bulkCmd(
        SnmpEngine(),
        CommunityData('public'),
        UdpTransportTarget(('demo.snmplabs.com', 161)),
        ContextData(),
        0, 50,  # GETBULK specific: request up to 50 OIDs in a single response
        ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.8')),
        lookupMib=False, lexicographicMode=False):

    if errorIndication:
        print(errorIndication)
        break
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex)-1][0] or '?'))
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

rawDescription: pysnmp get subtree and do not resolve oid against mib name

description: Pysnmp get subtree and do not resolve oid against mib name


rawDescription: How can I convert a list of strings into numeric values?

description: Convert a list of strings into numeric values


code:
width, height = im.size
pixels = [pix[i, j] for i in range(width) for j in range(height)]

rawDescription: Import RGB value of each pixel in an image to 1-D array


code:
def __iter__(self):
    attrs = [a for a in dir(self) if not a.startswith("_")]
    for attr_name in attrs:
        attr = getattr(self, attr_name)
        if not hasattr(attr, "__call__"): # or if not callable(attr):
            yield attr_name, attr

rawDescription: Python, Determining between @property and functions


code:
with open('file') as f:
    print(f.read().count(sequence))

rawDescription: Finding number of exact matches of string in file python


code:
import Tkinter as tk
import ttk as ttk
root = tk.Tk()
frame = tk.Frame(root)
frame.grid()
s = ttk.Style()
s.theme_use('clam')
s.configure("red.Horizontal.TProgressbar", foreground='red', background='red')
ttk.Progressbar(frame, style="red.Horizontal.TProgressbar", orient="horizontal", length=600,mode="determinate", maximum=4, value=1).grid(row=1, column=1)
frame.pack()
tk.mainloop()

rawDescription: Change color of progress bar Tkinter

description: Change color of progress bar Tkinter


code:
def amplitude(tree, cur_min=None, cur_max=None):
    if tree is None:
        if cur_min is None:
            return 0
        else:
            return cur_max - cur_min

    if cur_min is None:
        cur_min = cur_max = tree[0]
    else:
        cur_min = min(cur_min, tree[0])
        cur_max = max(cur_max, tree[0])

    return max(amplitude(tree[1], cur_min, cur_max),
               amplitude(tree[2], cur_min, cur_max))

rawDescription: Calculate the max difference between nodes in a binary tree


code:
with open("file.txt") as f:
    for line in f:
        if len(line.split("/")) > 1:
            print(line.split("/")[1])

rawDescription: python split function to read a string between two forward slashes

description: Python split function to read a string between two forward slashes


code:
from math import acos, sqrt
cos_theta=1./sqrt(a*a+b*b+1)
theta=acos(cos_theta)

rawDescription: Orientation of a best fit plane in 3D space


code:
def param_type(**type_spec):
    def deco(f):
        def view(request, **kwargs):
            for k, type_ in type_spec.items():
                kwargs[k] = type_(kwargs[k])
            return f(request, **kwargs)
        return view
    return deco

@param_type(number=int)
def double(request, number=42):
    return HttpResponse(2*number)

rawDescription: What's a good way to handle url parameters types?


code:
class rpartial(partial):
    def __call__(self, *args, **kwargs):
        kw = self.keywords.copy()
        kw.update(kwargs)
        return self.func(*(args + self.args), **kwargs)

rawDescription: implementing functools.partial that prepends additional arguments

description: Implementing functools.partial that prepends additional arguments


code:
class RangeFont(object):

    def __init__(self, range):
        self._range = range

    def __setattr__(self, name, value):
        if name.startswith('_'):
            super(RangeFont, self).__setattr__(name, value)
            return

        for cell in self._range: # assuming a range is iterable
            setattr(cell.font, name, value)

class Range(object):
    @property
    def font(self):
        return RangeFont(self)

rawDescription: Intercepting attributes in python

description: Intercepting attributes in python


code:
import BeautifulSoup

fname = r'c:\mydir\beautifulSoup.html'
soup = BeautifulSoup.BeautifulSoup(open(fname, 'r'))

items = []
last_seen_date = None
for el in soup.findAll('tr'):
    daterow = el.find('td', {'class':'date'})
    if daterow is None:     # not a date - get headline and link
        headline = el.find('td', {'class':'headline'}).text
        link = el.find('a').get('href')
        items.append((last_seen_date, headline, link))
    else:                   # get new date
        last_seen_date = daterow.text

rawDescription: How to loop through a html-table-dataset in Python

description: Loop through a html-table-dataset in Python


code:
import datetime
dt = datetime.datetime(2004, 3, 8)

ax.annotate('A bad day at the office', xy=(dt, 24), xytext=(dt, 25),
            arrowprops=dict(facecolor='black', shrink=0.05),
           )

rawDescription: Annotating a candlestick chart with matplotlib


code: re.sub(r'(Item)', r'- \1', 'A list of things: \nItem1, \nItem2')

rawDescription: Referring to the occurrence in re.sub

description: Referring to the occurrence in re.sub


code:
from ctypes import Structure, windll, c_uint, sizeof, byref

class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]

def get_idle_duration():
    lastInputInfo = LASTINPUTINFO()
    lastInputInfo.cbSize = sizeof(lastInputInfo)
    windll.user32.GetLastInputInfo(byref(lastInputInfo))
    millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
    return millis / 1000.0

rawDescription: wxPython - Trapping Mouse & Keyboard Events without window Focus

description: WxPython - Trapping Mouse & Keyboard Events without window Focus


code:
with env.begin() as txn:
    length = txn.stat()['entries']

rawDescription: How do I count and enumerate the keys in an lmdb with python?

description: Count and enumerate the keys in an lmdb with python


code:
import itertools
x = {"a": 600, "b": 75, "c": 75, "d": 90}
[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]

rawDescription: How many items in a dictionary share the same value in Python


code:
from itertools import izip_longest
lis =  [['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
list(izip_longest(*lis, fillvalue=''))

rawDescription: Python, how to write nested list with unequal lengths to a csv file?


code: df = pd.read_sql(query.statement, query.session.bind)

rawDescription: SQLAlchemy ORM conversion to pandas DataFrame


rawDescription: Python count number of data in array list from response.json


code:
@staticmethod
def expose (widget, event):
    if 'gtk.Layout' in str(type(widget)):
        cr=widget.bin_window.cairo_create()
    else:
        cr = widget.window.cairo_create()
    cr.set_operator(cairo.OPERATOR_CLEAR)
    cr.rectangle(event.area)
    cr.fill()
    cr.set_operator(cairo.OPERATOR_OVER)
    try:
        widget.rgba
    except AttributeError:
        widget.rgba=(0.0,0.0,0.0,0.0)
    cr.set_source_rgba(*widget.rgba)
    cr.rectangle(event.area)
    cr.fill()

rawDescription: how to make gtk.Layout transparent

description: Make gtk.Layout transparent


code:
# Initialize before an event loop:
old_entries = set()

# You need a loop that calls two handlers, each handler returning soon.
# Inside your loop, check for a "new file" event this way:
now_entries = os.listdir(r'\\some directory')
now_entries.symmetric_difference_update(old_entries)
for new_entry in now_entries:
    handle_new_file(new_entry)

rawDescription: Watch a directory in python and parse latest generated text file


code: my_bytes = my_string.encode('utf-8')

rawDescription: How can I do a binary encoding of a string in python?

description: Do a binary encoding of a string in python


code:
# initialisation
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('site one', site_one_page_one_data)
guesser.train('site one', site_one_page_two_data)
# ...etc...
guesser.train('site two', site_two_page_one_data)
guesser.train('site two', site_two_page_two_data)
# ...etc...
guesser.save()

# run time
guesser.load()
results = guesser.guess(page_I_want_to_classify)

rawDescription: How to efficiently determine if webpage comes from a website

description: Efficiently determine if webpage comes from a website


code:
import xml.etree.ElementTree as ET
root = ET.parse(response)

import sys
root.write(sys.stdout)

rawDescription: Experience accessing USGS EST services using python?


rawDescription: Get rid of extra commas from excel file with python


code:
def alive():
    with open("log.txt", "w") as output:
        while True:
            time.sleep(5)
            output.write("X")
            output.flush() # important to ensure that long periods
                       # of 'X' are not kept in buffer and lost on power down.

p = Process(target=f, args=('bob',))
p.start()

time.sleep(40) # simulate real program
p.terminate() # eventually

rawDescription: Append every 5 Seconds

description: Append every 5 Seconds


code: result = commands.getoutput('zcat ' + fullpath + ' |wc -l')

rawDescription: About insert shell commands into python

description: About insert shell commands into python


code:
mail=Mail()
mail.settings.server="smtp.example.com:25" or "gae"
mail.settings.sender="you@example.com"
mail.settings.tls=True or False
mail.settings.login="you:password"

rawDescription: Sending email from an web2py on GAE

description: Sending email from an web2py on GAE


code:
class TestThread_output(Thread):
    def __init__(self,mainForm):
        Thread.__init__(self)
        self.mainForm = mainForm #save reference to the mainFrame GUI
        self.start()    # start the thread
    def run(self):
        for i in range(1000):
            wx.CallAfter(self.mainForm.WriteThis) #since its a diff thread you need callafter(or calllater)
            #I dont think you can do self.mainForm.WriteThis()
            time.sleep(20)

class TMainForm(wx.Frame):
    ...
    def OnAnalyzePress(self,event):
        TestThread0()
        time.sleep(2)
        TestThread1()
        time.sleep(2)
        TestThread2()
        time.sleep(2)
        TestThread_output(self) #<- pass in this as mainFrame argument to thread constructor

rawDescription: Call function in wx.frame from different class in Python


code:
m = df.mean(axis=1)  # calculate once
df = df.loc[:, (m>10) & (m<2)]

rawDescription: Excluding columns from a dataframe based on their mean without using a loop


code:
import matplotlib.pyplot as plt

# On-screen, things will be displayed at 80dpi regardless of what we set here
# This is effectively the dpi for the saved figure. We need to specify it,
# otherwise `savefig` will pick a default dpi based on your local configuration
dpi = 80

im_data = plt.imread('hubble_friday_12102015.jpg')
height, width, nbands = im_data.shape

# What size does the figure need to be in inches to fit the image?
figsize = width / float(dpi), height / float(dpi)

# Create a figure of the right size with one axes that takes up the full figure
fig = plt.figure(figsize=figsize)
ax = fig.add_axes([0, 0, 1, 1])

# Hide spines, ticks, etc.
ax.axis('off')

# Display the image.
ax.imshow(im_data, interpolation='nearest')

# Add something...
ax.annotate('Look at This!', xy=(590, 650), xytext=(500, 500),
            color='cyan', size=24, ha='right',
            arrowprops=dict(arrowstyle='fancy', fc='cyan', ec='none'))

# Ensure we're displaying with square pixels and the right extent.
# This is optional if you haven't called `plot` or anything else that might
# change the limits/aspect.  We don't need this step in this case.
ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)

fig.savefig('test.jpg', dpi=dpi, transparent=True)
plt.show()

rawDescription: Matplotlib - unable to save image in same resolution as original image


rawDescription: Python pop and hex values

description: Python pop and hex values


code: print('The average is: ' + format(average, ',.3f') + '%')

rawDescription: How do I add a % symbol to my Python script

description: Add a % symbol to my Python script


code:
import re

s = 'Hellothegamestarts'
r = ''.join(
    el if idx % 2 == 0 else el[::-1]
    for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr

rawDescription: Converting string using list in python

description: Converting string using list in python


code:
import numpy as np
dt = np.dtype([('name',np.str_,2),('val',np.float_)])
constants = np.array([('pi',3.14),('e',2.72)],dtype=dt)

numbers = constants.view([('constants',dt)])

numbers['constants']

rawDescription: Add hierarchy to numpy structured array

description: Add hierarchy to numpy structured array


code:
p1 = Popen(['./program1'])
p1.wait()
p2 = Popen(['./program2'])
p2.wait()

rawDescription: How to force 2 Python subprocesses to run one after the other

description: Force 2 Python subprocesses to run one after the other


code:
extw=im.getextrema()
grad_b = 10
grad = Image.new('F', (grad_b, im_h))
pix = grad.load()
for i in range(grad.size[0]):    # for every pixel:
    for j in range(grad.size[1]):
        pix[i,j] = (extw[0]-extw[1]/im_h)*j+extw[1]

rawDescription: Generate a gradient from extrema of a float Image


code:
def find_widget(widget, L):
    for i, v in enumerate(L):
      if v[widget] == widget:
          return i

known_widgets= set()
processed_results = []

for x in raw_results:
    widget = x['widget']
    if widget in known_widgets:
        processed_widgets[find_widget(widget, processed_results)]['src'] += '-%s' % x['tag']
        continue
    else:
        processed_results.append(x)
        known_widgets.add(widget)

rawDescription: Need to remove duplicates from a list of dictionaries and alter data for the remaining duplicate (python)


code:
MyList = [('abc', 'def'), ('ghi', 'jkl'), ('mno', 'pqr')]

# Need to iterate over the list elements and pick the targeted tuple elem.
s0 = '\n'.join(item[0] for item in MyList) # 'abc\nghi\nmno'
s1 = '\n'.join(item[1] for item in MyList) # 'def\njkl\npqr'

rawDescription: Joining Elements from a List of Tuples in Python


code:
factors = []

while num % 2 == 0:
  factors.append(2)
  num /= 2

rawDescription: Project Euler #3, infinite loop on factorization


code:
text = "Racławicka Rógé"
text.encode('1252', 'ignore').decode('1252')

rawDescription: Python Polish character encoding issues

description: Python Polish character encoding issues


code: NameValue = unicode(Item.getElementsByTagName("Name")[0].childNodes[0].data.encode("latin-1"), "utf-8")

rawDescription: How to read special characters of a XML file with minidom

description: Read special characters of a XML file with minidom


code: from myapp.myapp_utils import *

rawDescription: Global includes in Django

description: Global includes in Django


code:
import re
data = ['TC', 'CY', 'GS', 'GA', 'CT']
[x for x in data if re.match(r'^[ACGT]+$', x)]

rawDescription: Python-Remove rows based on lack of character


code:
def updateCurrentOccupancy():
    counts_list = countCurrentOccupancy()
    counts_dict = dict(counts_list)

    shelters = session.query(Shelter)
    for shelter in shelters:
        shelter.current_occupancy = counts_dict.get(shelter.id)
        session.add(shelter)

    session.commit()

rawDescription: Pulling a 'counts' list from the first function into the second to update a table


code:
# Read in the file
with open("datafile", 'r') as f:
    data = f.read()

lst = data.split(',')   # Split data on , with str.split
lst[2] = '0'            # Replace the value at index 2 (the third value)
data = ','.join(lst)    # Rebuild the string with str.join

# Write the file out again
with open("datafile", 'w') as f:
     f.write(data)

rawDescription: Replace specific value within file

description: Replace specific value within file


code:
hitApples = pygame.sprite.spritecollide(snake, apple_list, True)
if hitApples:
    callback()

rawDescription: how to invoke another function when sprites collide in pygame

description: Invoke another function when sprites collide in pygame


rawDescription: how to ignore order of values in a tuple with groupby - python

description: Ignore order of values in a tuple with groupby - python


code:
class BookList(wx.ListCtrl):
  def __init__(self, parent, ID=wx.ID_ANY):
    wx.ListCtrl.__init__(self, parent, ID)

    self.InsertColumn(0, 'Title')
    self.InsertColumn(1, 'Author')

    # set column width ...

    self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
    self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)

    # currently selected row
    self.cur = None

  def OnLeftDown(self, event):
    if self.cur != None:
      self.Select( self.cur, 0) # deselect currently selected item

    x,y = event.GetPosition()
    row,flags = self.HitTest( (x,y) )

    self.Select(row)
    self.cur = row

  def OnRightDown(self, event):
    menu = wx.Menu()
    delete = menu.Append(wx.ID_ANY, 'Delete Item')

    self.Bind(wx.EVT_MENU, self.OnDelete, delete)

    # select row
    self.OnLeftDown(event)

    self.PopupMenu(menu, event.GetPosition())

rawDescription: wx.ListCtrl: how can I select a row on EVT_RIGHT_DOWN?

description: Wx.ListCtrl: how can I select a row on EVT_RIGHT_DOWN


code:
def remove(self, member):
    """Remove a file from the archive. Only works if the ZipFile was opened
    with mode 'a'."""

    if "a" not in self.mode:
        raise RuntimeError('remove() requires mode "a"')
    if not self.fp:
        raise RuntimeError(
              "Attempt to modify ZIP archive that was already closed")
    fp = self.fp

    # Make sure we have an info object
    if isinstance(member, ZipInfo):
        # 'member' is already an info object
        zinfo = member
    else:
        # Get info object for member
        zinfo = self.getinfo(member)

    # start at the pos of the first member (smallest offset)
    position = min([info.header_offset for info in self.filelist])  # start at the beginning of first file
    for info in self.filelist:
        fileheader = info.FileHeader()
        # is member after delete one?
        if info.header_offset > zinfo.header_offset and info != zinfo:
            # rewrite FileHeader and copy compressed data
            # Skip the file header:
            fp.seek(info.header_offset)
            fheader = fp.read(sizeFileHeader)
            if fheader[0:4] != stringFileHeader:
                raise BadZipFile("Bad magic number for file header")

            fheader = struct.unpack(structFileHeader, fheader)
            fname = fp.read(fheader[_FH_FILENAME_LENGTH])
            if fheader[_FH_EXTRA_FIELD_LENGTH]:
                fp.read(fheader[_FH_EXTRA_FIELD_LENGTH])

            if zinfo.flag_bits & 0x800:
                # UTF-8 filename
                fname_str = fname.decode("utf-8")
            else:
                fname_str = fname.decode("cp437")

            if fname_str != info.orig_filename:
                if not self._filePassed:
                    fp.close()
                raise BadZipFile(
                      'File name in directory %r and header %r differ.'
                      % (zinfo.orig_filename, fname))

            # read the actual data
            data = fp.read(fheader[_FH_COMPRESSED_SIZE])

            # modify info obj
            info.header_offset = position
            # jump to new position
            fp.seek(info.header_offset, 0)
            # write fileheader and data
            fp.write(fileheader)
            fp.write(data)
            if zinfo.flag_bits & _FHF_HAS_DATA_DESCRIPTOR:
                # Write CRC and file sizes after the file data
                fp.write(struct.pack("<LLL", info.CRC, info.compress_size,
                        info.file_size))
            # update position
            fp.flush()
            position = fp.tell()

        elif info != zinfo:
            # move to next position
            position = position + info.compress_size + len(fileheader) + self._get_data_descriptor_size(info)

    # Fix class members with state
    self.start_dir = position
    self._didModify = True
    self.filelist.remove(zinfo)
    del self.NameToInfo[zinfo.filename]

    # write new central directory (includes truncate)
    fp.seek(position, 0)
    self._write_central_dir()
    fp.seek(self.start_dir, 0)  # jump to the beginning of the central directory, so it gets overridden at close()

rawDescription: Python remove entry from zipfile

description: Python remove entry from zipfile


code:
import csv
import sys

with open('csvTest.txt', 'rb') as file_in:
    with open('test2.csv','wb') as file_out:
        csv_reader = csv.DictReader(file_in, delimiter='\t', quotechar='"')

        fieldnames = ['fName', 'lName', 'addr1', 'city', 'state', 'zip', 'terms',
                      'apptDate', 'product', 'description', 'quantity', 'price',
                      'total', 'taxAmt', 'invoiceNum']

        csv_writer = csv.DictWriter(file_out, delimiter='\t', fieldnames=fieldnames)
        csv_writer.writeheader()

        for row in csv_reader:
            row['description'] = row['description'].replace('/n','').replace(',','')
            print(row)
            csv_writer.writerow(row)

rawDescription: Import TAB delimited csv in python and strip /n and , from description field


code:
if loginForm.is_valid():

    cleaned_info = loginForm.cleaned_data
    c = {}
    uid = ''

    err = ''
    try:
        c = User.objects.raw('SELECT * FROM `user` WHERE BINARY `uname` = %s',
                                        cleaned_info['uname'])
    except User.DoesNotExist:
        err = 'UDNE'

        try:
            uid = c[0].id
        except IndexError:
            err = 'IE'

        if err is '':

            try:
                dbUserDetails = User.objects.get(uname__exact=cleaned_info['uname'],
                                                             id__exact=uid)

                 # Now you know that your username matches with "CASE"

                 # This is kinda dirty solution but will work so
                 # your logic codes will be here for login

            except User.DoesNotExist:
                response_data = {'error': 'true', 'message': 'Wrong username!!!'}

            else:
                response_data = {'error': 'true', 'message': 'Wrong username!!!'}

rawDescription: How to match exact case in database for username in django model?

description: Match exact case in database for username in django model


code:
def pack(self, *args, **kwargs):
    super(CustomFrame, self).pack(*args, **kwargs)
    # Do whatever

rawDescription: Python, Tkinter: How to get a widget to run function on pack?


code:
corpus = np.array(["aaa bbb ccc", "aaa bbb ddd"])
vectorizer = CountVectorizer(decode_error="replace")
vec_train = vectorizer.fit_transform(corpus)
#Save vectorizer.vocabulary_
pickle.dump(vectorizer.vocabulary_,open("feature.pkl","wb"))

#Load it later
transformer = TfidfTransformer()
loaded_vec = CountVectorizer(decode_error="replace",vocabulary=pickle.load(open("feature.pkl", "rb")))
tfidf = transformer.fit_transform(loaded_vec.fit_transform(np.array(["aaa ccc eee"])))

rawDescription: Keep TFIDF result for predicting new content using Scikit for Python


code:
import xml.etree.ElementTree as ET

list_of_files = ["tree1.xml", "tree2.xml", ...]

new_tree = ET.Element("a")
i = 1
for file in list_of_files:
  original_tree = ET.parse(file)
  sub_tree = ET.SubElement(new_tree, str(i))
  i += 1
  sub_tree.append (original_tree)
new_tree.write("merged_tree.xml")

rawDescription: Python ElementTree Copy Node with childs


code:
c.setFont('TestFont')
c.drawString(1,1,'test data here')

rawDescription: Adding a font for use in ReportLab

description: Adding a font for use in ReportLab


code:
from gi.repository import Gtk
combo_box = Gtk.ComboBoxText.new_with_entry()

rawDescription: GTK3 Python type in dropdown box

description: GTK3 Python type in dropdown box


code:
a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]]
set(map(tuple, a))

rawDescription: Python - Fast Way to Remove Duplicates in This List?


code:
to_exclude = ['foo']

from somemodule import *

for name in to_exclude:
    del globals()[name]

rawDescription: import everything from a module except a few methods

description: Import everything from a module except a few methods


rawDescription: Python Class Instance Arithmetic

description: Python Class Instance Arithmetic


code:
import imp
hest  = imp.load_source("Name", Path)

rawDescription: Python compile a script within a GUI

description: Python compile a script within a GUI


code:
f1=open("first.txt","a")
f2=open("second.txt","a")
for line in open("file"):
    s=line.split("=",1)
    f1.write(s[0]+"\n")
    f2.write(s[-1])
f1.close()
f2.close()

rawDescription: Read to right of specific symbol in file from Python


code:
from tkinter import Tk
from win32gui import SetParent, FindWindow, SetWindowPos
import time
import subprocess

def attach_window(window_class, parent, x, y, width, height):
    child = FindWindow(window_class, None)
    SetParent(child, parent)
    SetWindowPos(child, 0, x, y, width, height, 0)

def main():
    root = Tk()

    subprocess.Popen('C:\\Windows\\system32\\notepad.exe')
    subprocess.Popen('C:\\Windows\\system32\\calc.exe')

    # Give child processes enough time to launch
    time.sleep(0.5)

    # Get the HWND of the parent window
    parent = int(root.frame(), 16)

    attach_window('Notepad', parent, 0, 0, 400, 200)
    attach_window('CalcFrame', parent, 0, 205, 420, 320)

    root.geometry('500x500')
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Opening other application in single window using python


rawDescription: Fingerprinting the file type of a string of data in python


code:
re.split('<[^<]*$', '

<div class="_3o-d" id="education')

rawDescription: Python regular expression; match on the last instance


code:
import subprocess

p = subprocess.Popen(["cgps", "-s"], stdout=subprocess.PIPE)

with open("aaa.txt", "w") as f:
    while True:
        line = p.stdout.readline()
        if not line:
            break
        if some_condition(): # <-- check whether you have enough output
            p.terminate()
            break
        f.writeline(line)

p.wait()

rawDescription: Linux, Write output to the file and terminate it using Python


code:
for i, p in zip(list1, list2):
    print(i, p)

rawDescription: Python Increment two strings at the same time


code:
def bin(s):
    return 0 if not s else 2*bin(s[:-1]) + int(s[-1])

convert_2_to_decimal = lambda s: bin(s[1:]) - int(s[0])*2**(len(s)-1)

rawDescription: Writing a function to convert Two's Compliment to Base 10 in Python


code: #!/usr/bin/env python

rawDescription: Creating text files in a python script

description: Creating text files in a python script


code:
from tkinter import *
from tkinter import ttk

buttons = ["Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button"]  # List of contacts

root = Tk()
root.title('MyApp v0.1')
root.geometry('800x600')
#root['bg'] = "white"
root.rowconfigure(0, weight=1)

# Side menu
frame = Frame(root, background = "white")
for i in range(len(buttons)):
    Button(frame, background = "white", text = buttons[i], command = None).grid(row = i, column = 0)
    frame.rowconfigure(i, weight = 1)
frame.grid(row = 0, column = 0, sticky = "nesw")

sep = ttk.Separator(root, orient = "vertical")
sep.rowconfigure(0, weight = 1)
sep.columnconfigure(1, weight = 1)
sep.grid(row = 0, column = 1, padx = 5, sticky = "nesw")

rawDescription: Tkinter grid layout won't expand

description: Tkinter grid layout won't expand


code:
def process_module(self, mod_h, process_func):
    # Pre-processing...
    self._ok = process_func(mod_handle, operation, reg_addr, reg_data, ct.byref(size))
    return operation, reg_addr, reg_data, size.value

def init_module(self, mod_h):
    self.process_module(mod_h, self._init_module)

def config_module(self, mod_h):
    self.process_module(mod_h, self._config_module)

rawDescription: Passing Function names as parameter to define a generic function


code:
from matplotlib.colors import colorConverter
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

# create dummy data
zvals = np.ones((100,100))# np.random.rand(100,100)*10-5
zvals2 = np.random.rand(100,100)*10-5

# generate the colors for your colormap
color1 = colorConverter.to_rgba('white')
color2 = colorConverter.to_rgba('black')

# make the colormaps
cmap1 = mpl.colors.LinearSegmentedColormap.from_list('my_cmap',['green','blue'],256)
cmap2 = mpl.colors.LinearSegmentedColormap.from_list('my_cmap2',[color1,color2],256)

cmap2._init() # create the _lut array, with rgba values

# create your alpha array and fill the colormap with them.
# here it is progressive, but you can create whathever you want
alphas = np.linspace(0, 0.8, cmap2.N+3)
cmap2._lut[:,-1] = alphas

img2 = plt.imshow(zvals, interpolation='nearest', cmap=cmap1, origin='lower')
img3 = plt.imshow(zvals2, interpolation='nearest', cmap=cmap2, origin='lower')

plt.show()

rawDescription: Overlay imshow plots in matplotlib

description: Overlay imshow plots in matplotlib


code: raw_input("Press enter to exit...") # use input() if using Python 3.x

rawDescription: What is the equivalence of cin.ignore() in python?


code:
import numpy as np
import cv2

im = cv2.imread('lines.jpg')
rows,cols = im.shape[:2]
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,125,255,0)
thresh = (255-thresh)
thresh2=thresh.copy()
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

cv2.imshow('image1',im)
cv2.imshow('image3',thresh2)
#cv2.drawContours(im, contours, -1, (0,255,0), 3) #draw all contours
contnumber=4
cv2.drawContours(im, contours, contnumber, (0,255,0), 3) #draw only contour contnumber
cv2.imshow('contours', im)

[vx,vy,x,y] = cv2.fitLine(contours[contnumber], cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
cv2.line(im,(cols-1,righty),(0,lefty),(0,255,255),2)

cv2.imshow('result', im)

cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: How to detect horizontal lines in an image and obtain its y-coordinates using python and opencv?

description: Detect horizontal lines in an image and obtain its y-coordinates using python and opencv


rawDescription: Displaying more than one of an item in pygame


code:
for i in range(0, len(mylogger.handlers)):
    try:
        print(mylogger.handlers[i].baseFilename)
    except AttributeError:
        print('no to file')

rawDescription: Getting filename from Logger object in Python


code:
scriptTags = outputDoc.findAll('script')
for script in scriptTags:
    if script.has_attr('some_attribute'):
        do_something()

rawDescription: Test if an attribute is present in a tag in BeautifulSoup


code:
df1 = df[df1.c==0]
merged = df1.merge(df2, left_on='b', right_on='e')
merge = merged[merged.b != merged.d]

rawDescription: Merge 2 dataframes using <> condition

description: Merge 2 dataframes using <> condition


code:
@patch('cPickle.dump')
@patch('__builtin__.open')
def test_write_out(mock_open, mock_pickle):
    path = '~/collection'
    f = mock_open.return_value
    f.method.return_value = path

    write_out(path, 'data')

    mock_open.assert_called_once_with('~/collection', 'wb')
    mock_pickle.assert_called_once_with('data', f)
    f.close.assert_any_call()

rawDescription: Mocking two functions with patch for a unit test


code:
imei_string = '1234567890123456789'
imei_number = int(imei_string) # 1234567890123456789
imei_bytes = struct.pack('>Q', imei_number) # b'\x11\x22\x10\xf4\x7d\xe9\x81\x15'
buf = b'\xFE\x02' + imei_bytes + seq_bytes

rawDescription: Convert ASCII data to hex/binary/bytes in Python


code: a_list = [e.replace(" ", "-") for e in a_list]

rawDescription: Replace whitespaces with dashes for each item in a list -python


code:
threadpool = gevent.threadpool.ThreadPool()
result = threadpool.spawn(some_non_gevent_friendly_thing_such_as_file_io)

result.get()  # or use ThreadPool.apply/apply_e to get the result value immediately

rawDescription: Can Gevent be used in combination with real threads in CPython?


rawDescription: Generating a identical probability distribution on each run of a test


code:
from numpy.lib.stride_tricks import as_strided
mask = np.random.randint(2, size=(101, 100)).astype(bool)
mask_view  = as_strided(mask, shape=(500,)+mask.shape,
                        strides=(0,)+mask.strides)
mask_view.shape
np.array_equal(mask_view[0], mask_view[499])
np.all(mask_view == 0)
mask[:] = 0
np.all(mask_view == 0)

rawDescription: Slice a broadcast object?

description: Slice a broadcast object


code:
new_env = dict(os.environ)  # Copy current environment
new_env['LANG'] = 'en_US.UTF-8'
p = subprocess.Popen(..., env=new_env)

rawDescription: subprocess.Popen command (antiword) produces different output in shell vs. web application

description: Subprocess.Popen command (antiword) produces different output in shell vs. web application


code:
l = ['1', 'hello',  2, '11', ]
sorted(l, key=lambda x:len(str(x)))

rawDescription: Sort list by length of str(item)

description: Sort list by length of str(item)


rawDescription: Basic Python dictionary question

description: Basic Python dictionary question


code:
for x in get_week_days(2014, 50):
    x_mod = [False for _ in module]
    for y in list:
        if x['date'] == y['day']:
            x_mod[y['module_id']-1] = y
    for my_module in x_mod:
        print(my_module if my_module else 'empty')

rawDescription: multiple loop and printing something else if it dosn't exist

description: Multiple loop and printing something else if it dosn't exist


code: count = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).count()

rawDescription: Django query: Want to count a set in template


code: file.write("My String\n");

rawDescription: writing string to a file on a new line everytime?

description: Writing string to a file on a new line everytime


code:
packfmt = '>issiibBB'
output=struct.unpack(packfmt,response)

rawDescription: Python Parse Minecraft Packet

description: Python Parse Minecraft Packet


code:
import inspect
def callers_module():
   module = inspect.getmodule(inspect.currentframe().f_back)
   return module

rawDescription: Retrieve module object from stack frame

description: Retrieve module object from stack frame


code:
from itty import get, run_itty
import glob, gzip, json, os, functools

def jsonify(origfunc):
    @functools.wraps(origfunc)
    def wrapper(*args, **kwds):
        result = origfunc(*args, **kwds)
        return json.dumps(result, indent=4)
    return wrapper

@get('/logs')
@jsonify
def list_logfiles(request):
    return glob.glob('/var/log/myserver/*.gz')

@get('/logs/(?P<name>\w+)')
def show_logfile(request, name):
    fullname = os.path.join('/var/log/myserver', name)
    with gzip.open(fullname, 'rb') as f:
        return f.read()

run_itty(host='localhost', port=8080)

rawDescription: Python Logging monitor through http server


code:
import os
os.system("adb reboot")

rawDescription: How to write script in python to reboot android tablet multiple times

description: Write script in python to reboot android tablet multiple times


code: enemyList.append(Enemy(randomPosX, randomPosY, enemyType, enemyTypes[enemyType]))

rawDescription: Flyweight pattern - Memory footprint

description: Flyweight pattern - Memory footprint


code: df[['toaddress', 'ccaddress']].applymap(lambda x: str.count(x, '@'))

rawDescription: Python: Count instances of a specific character in all rows within a dataframe column


code:
cons = ({'type': 'ineq', 'fun': lambda w: 0.01 - abs(1 - np.sum(w))},
    {'type': 'ineq', 'fun': lambda w: 1 - abs(np.sum(vMax0(w)))},
    {'type': 'ineq', 'fun': lambda w: 1 - abs(np.sum(vMin0(w)))})

description: Scipy.optimize.minimize ignores constraint


code:
import math

def ci_lower_bound(pos, n, neg=0):

    if n == 0:
        return 0

    # Cannot calculate the square-root of a negative number
    if pos == 0:
        votes, use_neg = neg, True
    else:
        votes, use_neg = pos, False

    # Confidence
    z = 1.96

    phat = 1.0 * votes / n

    # Calculate how confident we are that this is bad or good.
    score = (phat + z*z/(2*n) - z * math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)

    # This relationship is defined above.
    # Multiply by -1 to return a negative confidence.
    if use_neg:
        return -1 * score

    return score

rawDescription: How can I improve this equation so items with more negative votes than positive return a more useful Wilson Score

description: Improve this equation so items with more negative votes than positive return a more useful Wilson Score


code:
import ctypes
from ctypes.util import find_library
libc = ctypes.CDLL(find_library('c'))

userpointer = ctypes.c_void_p()
sizeimage = 320*240*2

if libc.posix_memalign(ctypes.byref(userpointer), libc.getpagesize(),
                       sizeimage) != 0:
    raise Exception('ENOMEM')

rawDescription: posix_memalign within python

description: Posix_memalign within python


code:
# build a dict of column name -> list of column values
stats = {}
with open('stats.txt') as F:
    header = None
    for idx, line in enumerate(F):
        # This is the header
        if idx == 0:
            # save the header for later use
            header = line.split()
            for word in header:
                stats[word] = []
        else:
            # combine the header with the line to get a dict
            line_dict = dict(zip(header, line.split()))
            for key, val in line_dict.iteritems():
                stats[key].append(val)

# remove keys we don't want
stats.pop('%nice')
stats.pop('%steal')

rawDescription: selective items from a list into multiple variables in python

description: Selective items from a list into multiple variables in python


code: ','.join('{}{}'.format(k,v) for k,v in sorted(weights.items()))

rawDescription: Python join with comma is printing only the keys, not keys with values


code:
if set_1 - set_2:
    print("Additional terms")

rawDescription: Determine whether a set contains a value other than that in a different set


code:
collect = shopify.Collect({ 'product_id': product_id, 'collection_id': collection_id })
collect.save()

rawDescription: Shopify Python API: How do I add a product to a collection?


code:
from pyPdf import PdfFileReader
doc = PdfFileReader(file("upload.pdf", "rb"))

rawDescription: Check whether a PDF-File is valid (Python)


code:
import numpy as np
data = np.genfromtxt("G:/mydata.csv", delimiter=',', dtype=object)

rawDescription: How to read tabular data copied from Excel into clipboard using python?

description: Read tabular data copied from Excel into clipboard using python


code:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root, initialdir="/",
                                    title='Please select a directory')

rawDescription: How do I allow a user to select a file?

description: Allow a user to select a file


code:
class MyClass:
    myAttribute = 0

c = MyClass()
c.myAttribute
c.myAttribute = 1
c.myAttribute

rawDescription: Python object attributes - methodology for access


rawDescription: Plot edges of a tree in Python

description: Plot edges of a tree in Python


code:
s = "applebanana"
splits = [(s[:i], s[i:]) for i in range(1,len(s))]
splits
any((eng.check(item[0]) and eng.check(item[1])) for item in splits)

rawDescription: Check if collection of words (pyenchant)


code:
import subprocess

cmd = ['/usr/bin/python', '/path/to/my/second/pythonscript.py']
subprocess.Popen(cmd)

rawDescription: Call a python subprocess as daemon and exit


code:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm

def get_name(request):
   if request.method == 'POST':
      form = NameForm(request.POST)
      if form.is_valid():
          return HttpResponseRedirect('/thanks/')

   else:
      form = NameForm()

   return render(request, 'name.html', {'form': form})

rawDescription: Django form not visible

description: Django form not visible


code:
def func(arg: Param(type = 'int', unit = 'MB')):
   pass

rawDescription: python : is decorators for method arguments possible?

description: Python : is decorators for method arguments possible


rawDescription: Convert a string of numbers into numbers and leaving the date a string in python


code:
import pandas as pd
from StringIO import StringIO
#For Python 3: from io import StringIO

data = \
"""Localization,RNA level,Size
cytoplasm                            ,1 Non-expressed, 7
cytoplasm                            ,2 Very low     ,13
cytoplasm                            ,3 Low          , 8
cytoplasm                            ,4 Medium       , 6
cytoplasm                            ,5 Moderate     , 8
cytoplasm                            ,6 High         , 2
cytoplasm                            ,7 Very high    , 6
cytoplasm & nucleus                  ,1 Non-expressed, 5
cytoplasm & nucleus                  ,2 Very low     , 8
cytoplasm & nucleus                  ,3 Low          , 2
cytoplasm & nucleus                  ,4 Medium       ,10
cytoplasm & nucleus                  ,5 Moderate     ,16
cytoplasm & nucleus                  ,6 High         , 6
cytoplasm & nucleus                  ,7 Very high    , 5
cytoplasm & nucleus & plasma membrane,1 Non-expressed, 6
cytoplasm & nucleus & plasma membrane,2 Very low     , 3
cytoplasm & nucleus & plasma membrane,3 Low          , 3
cytoplasm & nucleus & plasma membrane,4 Medium       , 7
cytoplasm & nucleus & plasma membrane,5 Moderate     , 8
cytoplasm & nucleus & plasma membrane,6 High         , 4
cytoplasm & nucleus & plasma membrane,7 Very high    , 1"""

# Create the dataframe
df = pd.read_csv(StringIO(data))
df['Localization'].str.strip()
df['RNA level'].str.strip()
df['Size'].astype(int)
df['Percent'] = df.groupby('Localization')['Size'].transform(lambda x: x/sum(x))

rawDescription: Pandas: .groupby().size() and percentages


code:
point = Bunch(x=x, y=y, squared=y*y)
point.x

rawDescription: Instance of class `object`

description: Instance of class `object`


code:
import tkinter.ttk
from tkinter.constants import *

class Application(tkinter.ttk.Frame):

    @classmethod
    def main(cls):
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        app = cls(root)
        app.grid(sticky=NSEW)
        root.grid_columnconfigure(0, weight=1)
        root.grid_rowconfigure(0, weight=1)
        root.resizable(True, False)
        root.mainloop()

    def __init__(self, root):
        super().__init__(root)
        self.create_variables()
        self.create_widgets()
        self.grid_widgets()
        self.grid_columnconfigure(0, weight=1)

    def create_variables(self):
        self.player1 = tkinter.StringVar(self, 'Player 1')
        self.player2 = tkinter.StringVar(self, 'Player 2')
        self.timer = tkinter.StringVar(self)
        self.running = tkinter.BooleanVar(self)

    def create_widgets(self):
        self.set_timer = tkinter.ttk.Entry(self, textvariable=self.timer)
        self.start = tkinter.ttk.Button(self, text='Start', command=self.start)
        self.display1 = tkinter.ttk.Label(self, textvariable=self.player1)
        self.display2 = tkinter.ttk.Label(self, textvariable=self.player2)

    def grid_widgets(self):
        options = dict(sticky=NSEW, padx=3, pady=4)
        self.set_timer.grid(column=0, row=0, **options)
        self.start.grid(column=0, row=1, **options)
        self.display1.grid(column=0, row=2, **options)
        self.display2.grid(column=0, row=3, **options)

    def start(self):
        timer = self.timer.get()
        self.player1.set(timer)
        self.player2.set(timer)

if __name__ == '__main__':
    Application.main()

rawDescription: Resizing window doesn't resize contents in tkinter


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

gaussian_numbers = np.random.randn(1000)

# Get histogram
hist, bins = np.histogram(gaussian_numbers, bins=12)

# Threshold frequency
freq = 100

# Zero out low values
hist[np.where(hist <= freq)] = 0

# Plot
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")

rawDescription: Histogram manipulation to remove unwanted data


code:
image = Gtk.Image(stock=Gtk.STOCK_OPEN)
self.browse_button = Gtk.Button(label="Some Label", image=image)

rawDescription: Python - gtk3 add stock icons to Gtk.Buttons


code:
def createListofParts(testbenchParts, testbench, ttype):
    partList = []
    for part in ttype:
        for root, subFolders, files in os.walk(os.path.join(testbenchParts, part)):
            for file in files:
                if file.endswith('.svn-base'):
                    pass
                elif file.endswith('all-wcprops'):
                    pass
                elif file.endswith('entries'):
                    pass
                else:
                    partList.append(os.path.join(root, file))
    return createMatchTuples(partList, testbench) # <- return

rawDescription: Function returning None - from list

description: Function returning None - from list


code:
import pandas as pd

selfjoin = pd.merge(df, df, on = 'Property')
similarity = selfjoin.groupby(('Item_x', 'Item_y'), as_index=False).size()

rawDescription: Pandas : Group by similarities

description: Pandas : Group by similarities


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

def main():
    labels = ['A', 'B', 'C']
    positions = [(2, 5), (1, 1), (4, 8)]
    descriptions = ['Happy Cow', 'Sad Horse', 'Drooling Dog']

    # Plot the data, similar to what you described...
    fig, ax = plt.subplots()
    ax.imshow(np.random.random((10, 10)), interpolation='none')
    for label, xy in zip(labels, positions):
        ax.annotate(label, xy, xytext=(20, 20), size=15,
                    textcoords='offset points',
                    bbox={'facecolor':'white'},
                    arrowprops={'arrowstyle':'->'})

    # Create a legend with only labels
    proxies = [create_proxy(item) for item in labels]
    ax.legend(proxies, descriptions, numpoints=1, markerscale=2)

    plt.show()

def create_proxy(label):
    line = matplotlib.lines.Line2D([0], [0], linestyle='none', mfc='black',
                mec='none', marker=r'$\mathregular{{{}}}$'.format(label))
    return line

main()

rawDescription: Completely custom legend in Matplotlib, Python


code:
import logging
logger = logging.getLogger('django')   # Django's catch-all logger
hdlr = logging.StreamHandler()   # Logs to stderr by default
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)

rawDescription: how do I get django runserver to show me DeprecationWarnings and other useful messages?

description: Get django runserver to show me DeprecationWarnings and other useful messages


code:
del_items = set()
for i in xrange(sizeX):
    if dataX[i] == -999 or dataY[i] == -999:
        del_items.add(i)

rawDescription: Python 2.7: List comprehension with "if-statement" runs very slowly


code:
from moviepy.editor import *

def color_clip(size, duration, fps=25, color=(0,0,0), output='color.mp4'):
    ColorClip(size, color, duration=duration).write_videofile(output, fps=fps)

if __name__ == '__main__':
    size = (200, 100)
    duration = 5
    color_clip(size, duration)

rawDescription: How to make a blank video with Moviepy

description: Make a blank video with Moviepy


code:
pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n', flags=re.DOTALL)
re.findall(pattern,text)

rawDescription: Regex text between two strings

description: Regex text between two strings


code:
import sys
print(sys.byteorder)

rawDescription: How to detect Endianess and Filesystem with Python3

description: Detect Endianess and Filesystem with Python3


code:
mappings = {'D': 1, 'W': 7, 'Y': 365, 'DE': 3650}

def calculate_cigarettes(arg):
    cost = cost_st * how_many * mappings[arg]
    print('It will cost', cost, 'kr total.')

rawDescription: How to avoid a redundant and verbose if-else-structure?

description: Avoid a redundant and verbose if-else-structure


code:
import csv

with open(outfile, "wb") as outf:
    outcsv = csv.writer(outf)
    outcsv.writerow(fieldnames)
    outcsv.writerows(rows)

rawDescription: Python csv: Optimizing header output

description: Python csv: Optimizing header output


code:
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

def plot_ticks(start, stop, tick, n):
    r = np.linspace(0, 1, n+1)
    x = start[0] * (1 - r) + stop[0] * r
    x = np.vstack((x, x + tick[0]))
    y = start[1] * (1 - r) + stop[1] * r
    y = np.vstack((y, y + tick[1]))
    plt.plot(x, y, 'k', lw=1)

n = 10
tick_size = 0.2
margin = 0.05

# define corners of triangle
left = np.r_[0, 0]
right = np.r_[1, 0]
top = np.r_[0.5, 3**0.5 / 2]
triangle = np.c_[left, right, top, left]

# define vectors for ticks
bottom_tick = tick_size * (right - top) / n
right_tick = tick_size * (top - left) / n
left_tick = tick_size * (left - right) / n

plt.plot(triangle[0], triangle[1], 'k', lw=2)
plot_ticks(left, right, bottom_tick, n)
plot_ticks(right, top, right_tick, n)
plot_ticks(left, top, left_tick, n)
plt.axis([left[0]-margin, right[0]+margin, left[1]-margin, top[1]+margin])
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

rawDescription: Python (Matplotlib) - Tick marks on ternary plot


code: ', '.join("aaa, bbb, ccc, dddd, eeee".split(', ')[1:3])

rawDescription: Delete the first word and everything after third comma - Python 2.7


code:
from itertools import permutations

x = 'god'

perms = []

for i in range(1, len(x)+1):
    for c in permutations(x, i):
        perms.append("".join(c))

print(perms)
# ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

rawDescription: Python every possible combination of a string


code:
class Model:
    class Option:
        @property
        def model(self): return Model

rawDescription: Is there a way to access outer class in the nested class in python?


code:
from mpld3 import utils, plugins

class ClickInfo(plugins.PluginBase):
    """Plugin for getting info on click"""

    JAVASCRIPT = """
    mpld3.register_plugin("clickinfo", ClickInfo);
    ClickInfo.prototype = Object.create(mpld3.Plugin.prototype);
    ClickInfo.prototype.constructor = ClickInfo;
    ClickInfo.prototype.requiredProps = ["ids"];
    function ClickInfo(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    ClickInfo.prototype.draw = function(){
        this.props.ids.forEach(function(id, i) {
            var obj = mpld3.get_element(id);
            obj.elements().on("mousedown",
                              function(d){alert("clicked on bar[" + i + "]");});
                              });
    }
    """
    def __init__(self, bars):
        self.dict_ = {"type": "clickinfo",
                      "ids": [utils.get_id(bar) for bar in bars]}
x = range(0,10)
y = np.random.rand(10)

fig, ax = plt.subplots()
bars = ax.bar(x, y)

plugins.connect(fig, ClickInfo(bars))

rawDescription: MPLD3: label information of barplot

description: MPLD3: label information of barplot


code:
import os
fobj = open(os.path.join(os.pardir, "filename"), "w")

rawDescription: How to create a file one directory up?

description: Create a file one directory up


code:
from numpy import random
random.seed(123)

rawDescription: Initialization of the kmeans2 in python

description: Initialization of the kmeans2 in python


code:
from Tkinter import *

root = Tk()
root.title("Help")

scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

help_message = 'This is the help menu. Please scroll through the menu to find the answer to your question'

txt = Text(root, wrap=WORD) # wrap=CHAR, wrap=NONE
txt.pack(expand=1, fill=BOTH)
txt.insert(END, help_message)

txt.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=txt.yview)

mainloop()

rawDescription: How to wrap in Listbox

description: Wrap in Listbox


code: match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )

rawDescription: Get matching elements' values in two arrays


code:
def landed2(input):
    idx = np.floor(input).astype(np.int)
    mask = binary_matrix[idx[:,0], idx[:,1]] == 1
    return input[mask]

res1 = landed(input)
res2 = landed2(input)
np.testing.assert_allclose(res1, res2)

rawDescription: Fast array manipulation based on element inclusion in binary matrix


code:
class CreateVesselForm(forms.ModelForm):

    class Meta:
        model = Vessel
        exclude = ['active']

    # Filtering Choices
    def __init__(self, *args, **kwargs):
        super(CreateVesselForm, self).__init__(*args, **kwargs)
        if kwargs['instance']:
            self.fields['storage'].queryset = kwargs['instance'].storage.all()|Storage.objects.filter(is_free=True)
            self.fields['slot'].queryset = Slot.objects.filter(pk=kwargs['instance'].slot.pk)|Slot.objects.filter(is_free=True)

rawDescription: Django Edit Form Queryset made of Query + Current Selected Option - How to get?


rawDescription: SQLAlchemy: Select count of related many-to-many elements


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

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()

rawDescription: How to update a plot in matplotlib?

description: Update a plot in matplotlib


code:
_strip_non_hex = re.compile(r'^[^:]+:|[^0-9A-Fa-f]')

def _strip(string):
    return re.sub(_strip_non_hex, '', value)

class custom_str(str):
    @classmethod
    def new(cls, value):
        # creates a pure-hexadecimal string
        return custom_str.__new__(cls, _strip(value))

class custom_type(custom_str):
    def __new__(cls, value):
        return super(custom_type, cls).__new__(cls, _strip(value))

    @classmethod
    def new(cls, value):
        return cls('hex:%s' % (binascii.hexlify(value)))

rawDescription: Custom subclassing issue

description: Custom subclassing issue


rawDescription: Adding a section after a symbol to a dictionary in python


code: re.split(r'[\s;]+', text)

rawDescription: Split lines by a character or whitespace python


code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class QDoublePushButton(QPushButton):
    doubleClicked = pyqtSignal()
    clicked = pyqtSignal()

    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.clicked.emit)
        super().clicked.connect(self.checkDoubleClick)

    @pyqtSlot()
    def checkDoubleClick(self):
        if self.timer.isActive():
            self.doubleClicked.emit()
            self.timer.stop()
        else:
            self.timer.start(250)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.button = QDoublePushButton("Test", self)
        self.button.clicked.connect(self.on_click)
        self.button.doubleClicked.connect(self.on_doubleclick)

        self.layout = QHBoxLayout()
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)
        self.resize(120, 50)
        self.show()

    @pyqtSlot()
    def on_click(self):
        print("Click")

    @pyqtSlot()
    def on_doubleclick(self):
        print("Doubleclick")

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

rawDescription: PyQt5: QPushButton double click?

description: PyQt5: QPushButton double click


code:
from collections import defaultdict
d = defaultdict(tuple)
a = [('x', 1), ('x', 2), ('y', 1), ('y', 3), ('y', 4)]
for tup in a:
    d[tup[0]] += (tup[1],)
[tuple(x for y in i for x in y) for i in d.items()]

rawDescription: Python list of tuples merge 2nd element with unique first element


code: dir(object)

rawDescription: What methods does an 'object' has in python?


code:
import datetime
expire_date = datetime.datetime.now()
expire_date = expire_date + datetime.timedelta(days=90)
response.set_cookie(key, guid, expires=expire_date)

rawDescription: python flask not creating cookie when setting expiration

description: Python flask not creating cookie when setting expiration


code:
def vary(target, pattern, subst):
    matches = [m for m in pattern.finditer(target)]
    occurrences = [m.span() for m in matches]
    for path in itertools.product((True, False), repeat=len(occurrences)):
        variant = ''
        anchor = 0
        for match, (start, end), apply_this in zip(matches, occurrences, path):
            if apply_this:
                variant += target[anchor:start] + match.expand(subst)
                anchor = end
        variant += target[anchor:]
        yield variant

rawDescription: Combinatorial product of regex substitutions


code:
from distutils.core import setup
import os
import shutil
import py2exe

data_files = []
setup(
    name='ApplicationName',
    console=['script_file.py'], # 'windows' means it's a GUI, 'console' It's a console program, 'service' a Windows' service, 'com_server' is for a COM server
    # You can add more and py2exe will compile them separately.
    options={ # This is the list of options each module has, for example py2exe, but for example, PyQt or django could also contain specific options
        'py2exe': {
            'packages': [],
            'dist_dir': 'dist', # The output folder
            'compressed': True, # If you want the program to be compressed to be as small as possible
            'includes': ['os', 'logging', 'yaml', 'sqlalchemy', 'pymysql'], # All the modules you need to be included, I added packages such as PySide and psutil but also custom ones like modules and utils inside it because py2exe guesses which modules are being used by the file we want to compile, but not the imports, so if you import something inside main.py which also imports something, it might break.
        }
    },

    data_files=data_files # Finally, pass the

)

rawDescription: Missing modules in py2exe

description: Missing modules in py2exe


code:
#define PY_MAJOR_VERSION    2
#define PY_MINOR_VERSION    5
#define PY_MICRO_VERSION    2

rawDescription: How can I check the version of the python API at compile time?

description: Check the version of the python API at compile time


code:
@method_decorator(login_required(login_url="Accounts:account_login"),
                  name='dispatch')
@method_decorator(user_passes_test(profile_check), name='dispatch')
class AccountSelectView(TemplateView):
    template_name='select_account_type.html'

rawDescription: Django - Correct way to pass arguments to CBV decorators?


code:
def __init__(self):
    for parent_klass in inspect.getmro(self.__class__):
        _d.update(getattr(parent_klass, 'd', {}))
    _d.update(self.d)
    self.d = _d

rawDescription: Dictionary in a child class to update the dictionary with same name defined in parent class instead of over-riding


code: colourMap = ['#72DE18' if i else '#DE1899' for i in colourMap]

rawDescription: Replacing items in a python list based on their current value


code:
#for API1
workers = 4
worker_class = sync
threads = 2

#for API2
workers = 10
worker_class = gevent

rawDescription: Optimal gunicorn-worker configuration (number and class) for Python REST APIs


code:
import os,os.path
curfilePath = os.path.abspath(__file__)
curDir = os.path.abspath(os.path.join(curfilePath,os.pardir)) # this will return current directory in which python file resides.
parentDir = os.path.abspath(os.path.join(curDir,os.pardir)) # this will return parent directory.

rawDescription: How to get the name of parent directory in Python?

description: Get the name of parent directory in Python


code:
words = ['hi', 'Hi']
words = list(map(lambda x: x.lower(), words)) # makes all the words lowercase
words = list(set(words)) # removes all duplicates

rawDescription: How to remove duplicates in a document?

description: Remove duplicates in a document


rawDescription: Click a href button with selenium and python?


code:
dginvdy
factor(dginvdy)

rawDescription: Simplify roots in sympy

description: Simplify roots in sympy


code:
x=[]
for i in xrange(n):
    x.append(i)

rawDescription: How to augment a list in python?

description: Augment a list in python


code:
Person.objects.filter(teacher__isnull=False)
# return Person who has a teacher pointing to it

rawDescription: How to select all objects that are foreign keyed from another model in django?

description: Select all objects that are foreign keyed from another model in django


code:
index = index.order()
index.lexsort_depth

rawDescription: pandas MultiIndex degeneration

description: Pandas MultiIndex degeneration


code:
class Square(Rectangle):

    def __init__(self, x):
        super().__init__(x, x)
        if self.x != self.y:
            raise ValueError("x and y must be equal.")

rawDescription: Arguments and subclassing

description: Arguments and subclassing


code:
from Queue import Empty # <-- only needed to catch Exception
from multiprocessing import Process, Queue, cpu_count

def loadFile(d, i, queue):
    # some other stuff
    queue.put(result)

if name == "main":
    queue = Queue()
    no = cpu_count()
    processes = []

    for i,d in enumerate(sortedDirSet):
        p = Process(target=self.loadFile, args=(d, i, queue))
        p.start()
        processes.append(p)

        if i % no == 0:
            for p in processes:
                p.join()
            processes = []

    for p in processes:
        p.join()

    results = []
    while True:
        try:
            # False means "don't wait when Empty, throw an exception instead"
            data = queue.get(False)
            results.append(data)
        except Empty:
            break

    # You have all the data, do something with it

rawDescription: No increase in speed when multithreading python hdf5 parsing function


rawDescription: handling empty arrays in nested array

description: Handling empty arrays in nested array


code:
def parseSentence(sentence):
    cfrom, cto, incfrom, incto = 0, 0, 0, 0
    place = '' #to keep track of where we are

    for i in range(len(sentence)):
        c = sentence[i]
        if (c == '<'):
            #check for 'cfrom'
            if (sentence[i : i + 4] == '<tag'):
                cfrom = i
                place = 'botag' #begin-open-tag
            #check for 'incfrom'
            elif (sentence[i + 1] == '/' and place == 'intag'):
                incfrom = i
                place = 'bctag' #begin-close-tag
        elif (c == '>'):
            #check for 'cto'
            if (place == 'botag'): #just after '<tag...'
                cto = i
                place = 'intag' #now within the XML tag
            #check for 'incto'
            elif (place == 'bctag'):
                incto = i
                place = ''
                yield (cfrom, cto, incfrom, incto)

rawDescription: How to find the character position of something specified with a <tag>...</>? Python

description: Find the character position of something specified with a <tag>...</>? Python


code:
def shift_list(l, shift, empty=0):
    src_index = max(-shift, 0)
    dst_index = max(shift, 0)
    length = max(len(l) - abs(shift), 0)
    new_l = [empty] * len(l)
    new_l[dst_index:dst_index + length] = l[src_index:src_index + length]
    return new_l

rawDescription: Python: shift elements in a list with constant length


code:
def post(self):
  ...
  # This code is after the code above
  if data.is_valid():
    entity=data.save(commit=False)
    entity.company_lat=lat
    entity.company_lng=lng
    entity.put()

rawDescription: Accessing fields in model in post procedure in Google App Engine


code:
with patch.object(integrations, 'PARTNERS',[partner_type]):
    self._do_stuff()

rawDescription: In python is there a way to patch a list similiar to using patch.dict?


code:
import json
with open('outputfile', 'w') as fout:
    json.dump(your_list_of_dict, fout)

rawDescription: How can I save a list of dictionaries to a file?

description: Save a list of dictionaries to a file


code:
import urllib2
referer = 'link of the page of image'
image   = 'image link '

req = urllib2.Request(image)
req.add_header('Referer', referer)   # here is the trick
response = urllib2.urlopen(req)

output = open('out.jpg','wb')
output.write(response.read())
output.close()

rawDescription: Saving a randomly generated picture using Python mechanize


code:
c = df["column 2"]
c * (c & (c != c.shift())).cumsum()

rawDescription: Add number to column each time a different column has group of True bools


code:
from scipy.signal import butter, lfilter

def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y

if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

rawDescription: How to implement band-pass Butterworth filter with Scipy.signal.butter

description: Implement band-pass Butterworth filter with Scipy.signal.butter


code:
import urllib2
from bs4 import BeautifulSoup

url = 'http://endic.naver.com/search.nhn?isOnlyViewEE=N&query=Rule'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)

playlists = soup.find_all("a", {"playlist": True})
playlists

playlists[0].get("playlist")

rawDescription: Parsing with beautifulsoup and getting an mp3 link


code:
import time, sys

time.sleep(float(sys.argv[1]))

rawDescription: Sleeping in a batch file

description: Sleeping in a batch file


code:
def handler(self, clientsock, addr):
    while 1:
        data = clientsock.recv(BUFF)
        print ('Data : ' + repr(data))
        data = data.decode("UTF-8")
        result = re.match(self.pattern, data)
        if(result):
            self.registerClient(clientsock, data)
        if(data == "Exit"):
            self.exitClient(clientsock)
            break

rawDescription: Threaded python socket server

description: Threaded python socket server


rawDescription: Matlab importdata() function equivalent in Python


code:
import time
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kargs):
        wx.Frame.__init__(self, *args, **kargs)
        self.bt = wx.Button(self)
        self.status = ProgressStatusBar(self)
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.Bind(wx.EVT_BUTTON, self.on_bt, self.bt)

        self.sizer.Add(self.bt, 1, wx.EXPAND)
        self.sizer.Add(self.status, 1, wx.EXPAND)

        self.SetSizer(self.sizer)
        self.Fit()
        self.SetSize((500,200))

    def on_bt(self, evt):
        "press the button and it will start"
        for n in range(100):
            time.sleep(0.1)
            self.status.SetProgress(n)
            self.Update()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MyFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: Progress gauge in status bar, using Cody Precord's ProgressStatusBar


code:
auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions

rawDescription: use django create database scheme or use powerdesigner create database scheme

description: Use django create database scheme or use powerdesigner create database scheme


code:
from scrapy.contrib.linkextractors import LinkExtractor

addition = "?pag_sortorder=0&pag_perPage=999"

LinkExtractor(process_value=lambda x: x + addition)

rawDescription: scrapy append to linkextractor links

description: Scrapy append to linkextractor links


code:
import re

u_id = input("Input User ID: ") #DECLARE u_id : string

rex = re.compile("^[A-Z][a-z]{2}[0-9]{3}$")
if rex.match(u_id):
    print("Correct format")
else:
    print("Incorrect")

rawDescription: String Format Checking in Python

description: String Format Checking in Python


code:
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np

#create image with format (time,x,y)
image = np.random.rand(100,10,10)

#setup figure
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
#set up viewing window (in this case the 25 most recent values)
repeat_length = (np.shape(image)[0]+1)/4
ax2.set_xlim([0,repeat_length])
#ax2.autoscale_view()
ax2.set_ylim([np.amin(image[:,5,5]),np.amax(image[:,5,5])])

#set up list of images for animation

im = ax1.imshow(image[0,:,:])
im2, = ax2.plot([], [], color=(0,0,1))

def func(n):
    im.set_data(image[n,:,:])

    im2.set_xdata(np.arange(n))
    im2.set_ydata(image[0:n, 5, 5])
    if n>repeat_length:
        lim = ax2.set_xlim(n-repeat_length, n)
    else:
        # makes it look ok when the animation loops
        lim = ax2.set_xlim(0, repeat_length)
    return im, im2

ani = animation.FuncAnimation(fig, func, frames=image.shape[0], interval=30, blit=False)

plt.show()

rawDescription: Updating the x-axis values using matplotlib animation


code:
for line in f:
    words = line.split()

rawDescription: problem with f.readline()?

description: Problem with f.readline()


code:
# run excel macro from python
import win32com.client
fn = '//path/filename.xlsm'
xl=win32com.client.Dispatch("Excel.Application")
xl.Application.Visible = True
xl.Workbooks.Open(Filename = fn,ReadOnly = 1)
xl.Application.Run("macroname")
xl=0

rawDescription: Python Modify data of existing .xlsx file


code:
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
req.add_header('Cookie', 'session=value=')
response = urllib2.urlopen(req, data=json.dump(data))

rawDescription: Include session in HTTP POST header

description: Include session in HTTP POST header