code:
class BlogArticleSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.HyperlinkedRelatedField(view_name='user-detail', format='json')

    class Meta:
        model = BlogArticle
        fields = ('title', 'blog_content', 'author')

rawDescription: django rest framework: hypelinking referenced entitites

description: Django rest framework: hypelinking referenced entitites


rawDescription: Help with Python/Qt4 and QTableWidget column click


code:
from django.http import HttpResponse
from models import UPAdministrative

def upadministrative_geometry_json(request, upadmin_id):
    up_admin = UPAdministrative.objects.get(pk=upadmin_id)
    geojson = up_admin.ls.geojson
    return HttpResponse(geojson, mimetype='application/json')

rawDescription: How to send json from django view and receive it on HTML

description: Send json from django view and receive it on HTML


code:
from django.conf import settings

...

class Pages(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL) # or models.OneToOneField(...)

rawDescription: Django custom user how to now link it FK


code:
def grouper_nofill(n, iterable):
    '''list(grouper_nofill(3, 'ABCDEFG')) --> [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
    '''
    it=iter(iterable)
    def take():
        while 1: yield list(itertools.islice(it,n))
    return iter(take().next,[])

chunksize=256
async_results=[]
for finput in grouper_nofill(chunksize,itertools.izip(matrices, inds)):
    async_results.extend(pool.map_async(myfunc, finput).get())
async_results=np.array(async_results)

rawDescription: Combining itertools and multiprocessing?

description: Combining itertools and multiprocessing


rawDescription: Security of a Caesar cipher cascade

description: Security of a Caesar cipher cascade


code:
class MyModelAdmin(ModelAdmin):
    def delete_view(self, request, object_id, extra_context=None):
        # if request.POST is set, the user already confirmed deletion
        if not request.POST:
            perform_my_action()
        super(MyModelAdmin, self).delete_view(request, object_id, extra_context)

rawDescription: Is it possible to override the method used to call Django's admin delete confirmation page?


code:
from itertools import combinations
def sub_s(st,word):
   all_s = (x for x in st if x in word)
   return len([x for x in (combinations(all_s, len(word))) if "".join(x) == word] )

rawDescription: Find all occurrences of a divided substring in a string


code:
import time
url = 'http://example.com/index'
'%s?_=%d' % (url, time.time() * 1000)

rawDescription: Extra ?= and numbers in GET request header when called through AJAX


code:
tree_top = os.path.abspath(
    os.path.expanduser(
        os.path.expandvars(
            sys.argv[1]
        )
    )
)

rawDescription: How should I shorten this line of Python code?


code: a[np.arange(a.shape[0]), amin_index]

rawDescription: Apply numpy index to matrix

description: Apply numpy index to matrix


code:
import numpy as np
test = np.array([[1,2,3]])
test
print(test)
test.shape
type(test)

rawDescription: how to generate this type of data?

description: Generate this type of data


code:
firsts = [i for i, v in enumerate(log_files) if '_0001' in v]
list_of_lists = [log_files[i:j] for i, j in zip(firsts, firsts[1:] + [None])]

rawDescription: Change list into list of lists based on location of subset


code:
from tkinter import *
from random import randint

class FlipBell(object):
    """
    GUI to simulate cointoss.
    """
    def __init__(self, wdw, dimension, delay):
        """
        Determines the layout of the GUI.
        wdw : top level widget, the main window,
        dimension : determines the size of the canvas,
        increment : step size for a billiard move,
        delay : time between updates of canvas.
        """
        wdw.title('Coin flips and Bell Curve')
        self.cnv = Canvas(wdw, width=dimension,
                          height=dimension, bg='white')
        self.cnv.grid()

        self.ct_instances=[]
        self.colors=["blue", "red", "yellow", "gray", "green"]
        self.delay=delay
        self.offset=0
        self.create_next()

    def create_next(self):
        """ create one ball for each color in self.colors
            and call each existing ball's flip function to
            move it a random amount
        """
        x=5
        y=5
        incr=10*self.offset
        CT=CoinToss(self.cnv, x+incr, y+incr, self.colors[self.offset])
        ##save each CoinToss (ball) instance in a list
        self.ct_instances.append(CT)
        self.offset += 1

        ## call flip (move ball) for each instance
        for instance in self.ct_instances:
            instance.flip()

        if self.offset < len(self.colors):
            self.cnv.after(self.delay, self.create_next)

class CoinToss:
    def __init__(self, canvas, start_x, start_y, color):
        self.cnv=canvas
        self.cointoss(start_x, start_y, color)

    def cointoss(self, start_x, start_y, color):
        self.this_ball=self.cnv.create_oval(start_x-5, start_y-5, start_x+5, start_y+5,
                       outline='black', fill=color, tag="dot")

    def flip(self):
        """ move the ball created for this class instance by a random amount
        """
        rand_value = randint(10, 50)
        self.cnv.move(self.this_ball, rand_value, rand_value)

if __name__ == "__main__":
    top = Tk()
    dimension = 400 # dimension of canvas
    delay = 500     # how much sleep before update --> 1/2 second
    num_flips = 3
    FP=FlipBell(top, dimension, delay)
    top.mainloop()

rawDescription: Update multiple oval coordinates on canvas in python using tkinter


code:
import pandas as pd
t = pd.Series([1,2,3,4,5])
t
t.shift(1)
t-t.shift(1)

rawDescription: Lagging and differencing variables

description: Lagging and differencing variables


rawDescription: django filter : can filter with tuple?

description: Django filter : can filter with tuple


code:
@login_manager.user_loader
def load_user(id):
    return "get the user properly and create the usermixin object"

rawDescription: flask-login session gets destroyed on every apache restart

description: Flask-login session gets destroyed on every apache restart


code:
import collections

# Use 'rb' to open files

infn1 = '/home/lucas/Doutorado/Projeto Eduardo/Exoma Neandertal/Listas_eduardo/Phase1_missing.vcf'
infn2 = '/home/lucas/Doutorado/Projeto Eduardo/Exoma Neandertal/Listas_eduardo/Neandertais.vcf'
outfn = '/home/lucas/Doutorado/Projeto Eduardo/Exoma Neandertal/Listas_eduardo/Neandertais_and_YRI.vcf'

def readfile(fname):
    '''
    Read in a file and return a dictionary of lines, keyed by the item in the second column
    '''
    results = collections.defaultdict(list)
    # Read in binary mode -- it's quicker
    with open(fname, 'rb') as f:
        for line in f:
            parts = line.split("\t")
            if not parts:
                continue
            gene = parts[2]
            results[gene].append(line)
    return results

dict1 = readfile(infn1)
dict2 = readfile(infn2)

with open(outfn, 'wb') as outf:
    # Find keys that appear in both files
    for key in set(dict1) & set(dict2):
        # For these keys, print all the matching
        # lines in the first file
        for line in dict1[key]:
            print(line.rstrip())
            outf.write(line)

rawDescription: How compare files quicker in python?

description: How compare files quicker in python


code:
from itertools import chain
[(k1[0], k1[1], k2) for k1, k2 in zip(chain.from_iterable(dge), nde)]

rawDescription: Building tuples from nested lists

description: Building tuples from nested lists


code: xmpp.send_presence(to_jid, status="My app's status")

rawDescription: XMPP bot status message on GAE

description: XMPP bot status message on GAE


code:
# The 2D array I'm trying to add to the STACK
STAR = [[1, 1, 1, 1, 1],\
        [1, 1, 2, 1, 1],\
        [1, 2, 3, 2, 1],\
        [1, 1, 2, 1, 1],\
        [1, 1, 1, 1, 1,]]
STAR = np.asarray(STAR)

# Initialize STACK to be an empty array the same size as STAR
STACK = np.zeros(STAR.shape, np.float_)

# A function that appends STAR to STACK
def add_Star(star):
    out = np.dstack((STACK,star))

    return out

# Call the function
STACK = add_Star(STAR)

rawDescription: Storing 2D array inside a larger 3D array


code:
p = subprocess.Popen(args = "myprog.exe" + " " +
                     str(input1) + " " +
                     str(input2) + " " +
                     str(input3) + " " +
                     " ".join(strpoints), stdout = subprocess.PIPE)

rawDescription: send an arbitrary number of inputs from python to a .exe

description: Send an arbitrary number of inputs from python to a .exe


code:
import string
import random
random.choice(string.ascii_letters + string.digits)

rawDescription: How can I select random characters in a pythonic way?

description: Select random characters in a pythonic way


code: [s for s in re.split(r'[ ,;]', '"Jan","Feb";"Mar" "Apr", "May";') if s]

rawDescription: How to split a string in python based on any combination of semicolon, whitespace and comma?

description: Split a string in python based on any combination of semicolon, whitespace and comma


code:
result = []
dec = int(input("Please enter number to convert to decimal: "))
while dec>0:
    quoteint = dec/2
    rem = dec%2
    result.append(rem)
    dec = int(dec/2)
result = result[::-1]
print(' '.join(str(r) for r in result))

rawDescription: How to reverse generated integer order in python

description: Reverse generated integer order in python


code: new_module = __import__(modulename)

rawDescription: importing a module when the module name is in a variable

description: Importing a module when the module name is in a variable


rawDescription: How to convert a column with multiple values into binary variables in Pandas

description: Convert a column with multiple values into binary variables in Pandas


code:
import matplotlib.pyplot as plt
plt.plot(range(5), range(5), 'ro', markersize=20, clip_on=False, zorder=100)
plt.show()

rawDescription: How do I let my matplotlib plot go beyond the axes?

description: Let my matplotlib plot go beyond the axes


code:
d
realData = d[d.Borough != "Unspecified"]
realData = pandas.Series(data=realData.Borough.values, index=realData.City)
d['Borough'] = d.City.map(realData)
d

rawDescription: Conditionally replacing values based on values in another column


code:
from cffi import FFI
ffi = FFI()
ffi.cdef("""

typedef struct PROPVARIANT {
    unsigned short    vt;
    unsigned short    wReserved1;
    unsigned short    wReserved2;
    unsigned short    wReserved3;
    union {
        int          intVal;
        wchar_t*      bstrVal;
        /* shortened for clarity */
    };
} PROPVARIANT;

typedef unsigned long long HRESULT;
typedef uint32_t PROPID;

HRESULT GetNumberOfFormats(uint32_t * numFormats);
HRESULT GetHandlerProperty2(uint32_t index, PROPID propID, PROPVARIANT * value);

void * malloc(size_t);
void memset(void*, int, int);
void free(void*);
""")

S_OK = 0x00000000  # Operation successful
VT_BSTR = 8
kExtension = 2

dll7z = ffi.dlopen('7z.dll')
C = ffi.dlopen(None)

num_formats = ffi.new('uint32_t*')
assert dll7z.GetNumberOfFormats(num_formats) == S_OK
print(num_formats[0])

tmp_pvar = ffi.cast("PROPVARIANT*", C.malloc(ffi.sizeof('PROPVARIANT')))
C.memset(tmp_pvar, 0, ffi.sizeof('PROPVARIANT'))

for i in range(num_formats[0]):
    assert dll7z.GetHandlerProperty2(i, kExtension, tmp_pvar) == S_OK
    assert tmp_pvar != ffi.NULL
    assert tmp_pvar[0].vt == VT_BSTR

    print(ffi.string(tmp_pvar[0].bstrVal))

C.free(tmp_pvar)

rawDescription: Python CFFI + 7z.dll (COM) == access violations (sometimes)


code:
from random import randint
user1 = {
    "name":input("Enter your name"),
    "board":[]
}
user2 = {
    "name":input("Enter your name"),
    "board":[]
}
users = [user1, user2]    # Actually this is not used anymore

def set_board(user):
    for x in range(5):
        user["board"].append(x)

def print_board(user):
    print(' '.join(str(user["board"])))

print("Let's start")
set_board(user1)
set_board(user2)
print_board(user1)
print_board(user2)

rawDescription: python list not getting appended

description: Python list not getting appended


code:
keys = [MyModel.ref.get_value_for_datastore(x) for x in referers]
referees = db.get(keys)

rawDescription: appengine: cached reference property?

description: Appengine: cached reference property


code:
import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

rawDescription: How to use youtube-dl from a python program

description: Use youtube-dl from a python program


code:
def grid_string_maker(word_block, x, y): # creates string from grid
    pos_word_vert = word_block[0][x] + word_block[1][x] + word_block[2][x]
    pos_word_hor = word_block[y][0] + word_block[y][1] + word_block[y][2]
    return (pos_word_vert, pos_word_hor)

def find_word(word_block, x, y, validate_words):
    pos_word_vert, pos_word_hor = grid_string_maker(word_block, x, y)
    if pos_word_vert == validate_words: #Checks if the string vertically from up to down matches
        return True
    else: #If top to bottom doesnt match, it reverses
        rev_pos_word_vert = pos_word_vert[::-1]
        if rev_pos_word_vert == validate_words: #Checks if the reversed bottom to top matches
            return True
    if pos_word_hor == validate_words: #Checks if the string vertically from up to down matches
        return True
    else: #If top to bottom doesnt match, it reverses
        rev_pos_word_hor = pos_word_hor[::-1]
        if rev_pos_word_hor == validate_words: #Checks if the reversed bottom to top matches
            return True
    return False

validate_words = "THE"

rawDescription: Python Returns None instead of True/False


code:
rows = [('a','x1',1),('a','x2',5),('b','x1',1)]
result = dict()
for key1, key2, value in rows:
  result.setdefault(key1, {}).update({key2: value})

rawDescription: Python list of tuples to nested dict

description: Python list of tuples to nested dict


code:
import requests, json

data =  {
   "query": {
    "range" : {
      "created_at" : {
        "gte": "now-2h",
        "lte": "now"
      }
    }
  }
}

url = "http://localhost/_search?pretty"

response = requests.post(url, data = json.dumps(data))

rawDescription: Python : curl command option with `-d` to python


rawDescription: Unexpected result using .ix indexing with list vs range


code:
from elasticsearch_dsl.query import MultiMatch

q = request.GET.get('q', None)
query = MultiMatch(query=q, fields=['title', 'body'], fuzziness='AUTO')
s = Search(using=elastic_client, index='post').query(query)
response = s.execute()

rawDescription: Python elasticsearch dsl search multi fields and order result


code:
class NonASCIIJSONEncoder(json.JSONEncoder):
    def __init__(self, **kwargs):
        kwargs['ensure_ascii'] = False
        super(NonASCIIJSONEncoder, self).__init__(**kwargs)

rawDescription: Flask JSONEncoder set ensure_ascii to False


code: sorted(map(lambda x: sorted(x[:2]) + [x[2]], li))

rawDescription: Multi-item sort based with two different list items and reorder/reshuffle?


code:
class MyApp(wx.App):
    def OnInit(self):
        # Set application name before anything else
        self.SetAppName("My App Name")
        mainframe = MyMainFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(mainframe)
        mainframe.Show()
        return 1

if __name__ == '__main__':
    myapp = MyApp()
    myapp.MainLoop()

rawDescription: Mac OS Quit Application menu label same as python script name


code:
# Using Generator Expression with `Counter` to speed it up a little bit
from collections import Counter
count = Counter(item for e in c for item in e.split())

# Get most frequently used words
words = {item for item, cnt in count.most_common(6)}

# filter the `words` in `c` and reconstruct the sentences in `c`
[" ".join([item for item in e.split() if item not in words]) for e in c]

rawDescription: Remove strings from elements of a list - Python


code:
character = [image, stats[:], team_color]
character[1][1] -= 1

print( character, stats )
(['image_name', [1, 1, 3], 'red'], [1, 2, 3])

rawDescription: Variable Assignment Error

description: Variable Assignment Error


code:
tags = ["school", "hollywood"]
r.db("test").table("posts").filter(
  lambda post: post["tags"].contains(lambda tag:
    r.expr(tags).contains(tag)
  )
).run(conn)

rawDescription: Multiple filter using lambda in python on rethinkdb?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.nxutils import points_inside_poly
from itertools import product, compress

pv = [(1,1),(5,1),(5,9),(3,2),(1,1)]

x, y = np.meshgrid(np.arange(10),np.arange(10))
x, y = x.flatten(), y.flatten()

xy = np.vstack((x,y)).T

grid = points_inside_poly(xy,pv)

xv, yv = zip(*pv)
xp, yp = zip(*compress(xy,grid))

plt.plot(xp,yp,'o',color='red',label='points')
plt.plot(xv,yv,'o',color='blue',label='vertices')
plt.xlim((0,10))
plt.ylim((0,10))
plt.legend()
plt.show()

rawDescription: I have a set of points along the oval. How do I create a filled binary mask


code:
"""Easy generation of new events classes and binder objects"""

__author__ = "Miki Tebeka <miki.tebeka@gmail.com>"

import wx

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

def NewEvent():
    """Generate new (Event, Binder) tuple
        e.g. MooEvent, EVT_MOO = NewEvent()
    """
    evttype = wx.NewEventType()

    class _Event(wx.PyEvent):
        def __init__(self, **kw):
            wx.PyEvent.__init__(self)
            self.SetEventType(evttype)
            self.__dict__.update(kw)

    return _Event, wx.PyEventBinder(evttype)

def NewCommandEvent():
    """Generate new (CmdEvent, Binder) tuple
        e.g. MooCmdEvent, EVT_MOO = NewCommandEvent()
    """
    evttype = wx.NewEventType()

    class _Event(wx.PyCommandEvent):
        def __init__(self, id, **kw):
            wx.PyCommandEvent.__init__(self, evttype, id)
            self.__dict__.update(kw)

    return _Event, wx.PyEventBinder(evttype, 1)

rawDescription: What is the difference between wx.lib.newevent.NewEvent() and wx.NewEventType()?


code:
from openpyxl.workbook import Workbook
from openpyxl.cell import get_column_letter, Cell, column_index_from_string, coordinate_from_string

wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.worksheets[0]
ws.title = "range names"

# inserting sample data
for col_idx in xrange(1, 10):
    col = get_column_letter(col_idx)
    for row in xrange(1, 10):
        ws.cell('%s%s' % (col, row)).value = '%s%s' % (col, row)

# inserting column between 4 and 5
column_index = 5
new_cells = {}
ws.column_dimensions = {}
for coordinate, cell in ws._cells.iteritems():
    column_letter, row = coordinate_from_string(coordinate)
    column = column_index_from_string(column_letter)

    # shifting columns
    if column >= column_index:
        column += 1

    column_letter = get_column_letter(column)
    coordinate = '%s%s' % (column_letter, row)

    # it's important to create new Cell object
    new_cells[coordinate] = Cell(ws, column_letter, row, cell.value)

ws._cells = new_cells
wb.save(filename=dest_filename)

rawDescription: Insert column using openpyxl

description: Insert column using openpyxl


code:
# Define the required groups
req = set(['AF','PLAT','ROOT'])
# Group and filter results
f = df.groupby('A').filter(lambda g:req.issubset(set(g.B)))

#   A     B       C
#2  2    AF  0.0021
#3  2  PLAT  0.0011
#4  2  ROOT  0.0008

rawDescription: Finding grouped items with a full set of attributes in Pandas


rawDescription: How to use a Sqlalchemy Model out of a session context?

description: Use a Sqlalchemy Model out of a session context


code:
import struct
import socket
import time
import threading
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser  # ver. < 3.0

class machineClass():
    def __init__(self):
        self.read_config() # gets IP's and Ports for machine and relay socket and stores them in self.machineIP, self.machinePort, self.relayIP and self.relayPort
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.machineIP, self.machinePort))

        self.stopRelayEvent = threading.Event()
        self.relayStoppedEvent = threading.Event()

        relaySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        relaySocket.bind((self.relayIP,self.relayPort))

        relayThread = threading.Thread(target=self.relay, args=(relaySocket,self.s,self.stopRelayEvent,self.relayStoppedEvent))

        relayThread.start()

        print(" Machine [connected]")

    def relay(self,relaySocket,machineSocket,stopRelayEvent,relayStoppedEvent):
        while 1:
            if not relayStoppedEvent.isSet():
                relayStoppedEvent.set()
            relaySocket.listen(1) # waits for connection from software **B**, in loop because **B** reconnects every now and then. While waiting, connection is not blocked for **C** because relayStoppedEvent is set.
            relayCon, relayAddr = relaySocket.accept()
            relayStoppedEvent.clear()
            print('Connected with Software **B** on ' + relayAddr[0] + ':' + str(relayAddr[1]))

            while 1:
                if not stopRelayEvent.isSet():
                    if relayStoppedEvent.isSet():
                        relayStoppedEvent.clear()
                    data = relayCon.recv(84)
                    if len(data) == 0:
                        break # in case connection is lost, break loop and go back to waiting for new connection.
                    machineSocket.send(data)
                    relayCon.send(machineSocket.recv(84))
                else:
                    relayStoppedEvent.set()
                    data = relayCon.recv(84)

    def sendDataToMachine(self,data): # Function for **C** to send data to machine **B**
        self.stopRelayEvent.set()
        self.relayStoppedEvent.wait()
        self.s.send(data)
        time.sleep(.1)
        return_data = self.s.recv(84)
        self.stopRelayEvent.clear()
        return return_data

rawDescription: Relay between two sockets, interrupt to plug in own commands


code:
import json
from pprint import pprint

json_data=open('/tmp/AutoScale.json')
data = json.load(json_data)

for i in range(len(data["AutoScalingGroups"])):
    pprint(data["AutoScalingGroups"][i]["LaunchConfigurationName"])
    json_data_2=open('/tmp/launchConfig.json')
    data_2 = json.load(json_data_2)
    pprint(data_2["LaunchConfigurations"][i]["LaunchConfigurationName"])
    json_data_2.close()      # closed second file
json_data.close()          # closed first file

rawDescription: Using Python to read multiple JSON files


code:
#!/usr/bin/env python
from multiprocessing import Pool

def work_on(args):
    """Process a single file."""
    i, filename = args
    print("working on %s" % (filename,))
    return i

def files():
    """Generate input filenames to work on."""
    #NOTE: you could read the file list from a file, get it using glob.glob, etc
    yield "inputfile1"
    yield "inputfile2"

def process_files(pool, filenames):
    """Process filenames using pool of processes.

    Wait for results.
    """
    for result in pool.imap_unordered(work_on, enumerate(filenames)):
        #NOTE: in general the files won't be processed in the original order
        print(result)

def main():
   p = Pool()

   # to do "successive" multiprocessing
   for filenames in [files(), ['other', 'bunch', 'of', 'files']]:
       process_files(p, filenames)

if __name__=="__main__":
   main()

rawDescription: Successive multiprocessing

description: Successive multiprocessing


code:
from PyQt4 import QtGui
import sys

class MyApp(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # Cannot resize or maximize
        self.setFixedSize(1045, 770)
        widget = QtGui.QWidget(self)
        self.setCentralWidget(widget)
        # Add button test
        self.dateLabel = QtGui.QLabel("Test")
        self.pushButton = QtGui.QPushButton('Test button')

        grid = QtGui.QGridLayout()
        grid.addWidget(self.dateLabel, 0, 0)
        grid.addWidget(self.pushButton, 0, 1)
        widget.setLayout(grid)

        self.pushButton.clicked.connect(self.closeEvent)

    def closeEvent(self, event):
        QtGui.QApplication.quit()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

rawDescription: Access QT Designer Objects Programmatically


code:
def require_uid(fn):
    def check_uid(**kwargs):
        cookie_uid = request.get_cookie('cookieName', secret='cookieSignature')

        if cookie_uid:
            # do stuff with a user object
            return fn(**kwargs)
        else:
            redirect("/loginagain")

    return check_uid

@route('/userstuff', method='GET')
@require_uid
@view('app')
def app_userstuff():
    # doing things is what i like to do
    return dict(foo="bar")

rawDescription: Check authentification for each request in Bottle


code:
str_obj = pickle.dumps([1,2,3])
str_obj

rawDescription: Python: Emailing a pickled object without intermediate file


code:
from datetime import datetime
timestamp = datetime.utcnow()
end_of_day = datetime(year=timestamp.year, month=timestamp.month, day=timestamp.day, hour=23, minute=59, second=59)
end_of_day

rawDescription: How to save memcache value till quota is replenished?

description: Save memcache value till quota is replenished


code:
r = urllib2.urlopen(url)
CHUNK_SIZE = 1 << 20
with open('compressed_file.tar.gz', 'wb') as f:
    # line belows downloads all file at once to memory, and dumps it to file afterwards
    # f.write(r.read())
    # below is preferable lazy solution - download and write data in chunks
    while True:
        chunk = r.read(CHUNK_SIZE)
        if not chunk:
            break
        f.write(chunk)

rawDescription: Download a file in python with urllib2 instead of urllib


code:
def multiply(x, y):
    product = 0
    for i in xrange(x):
        product = add(product, y)
    return product

rawDescription: Understanding what is API wrapper around existing library


code:
use_pgdb = 0
try:
    import pgdb
    use_pgdb = 1
except:
    try:
        import psycopg2
    except:
        raise exceptions.ImportError('No PostgreSQL library, install psycopg2 or PyGres!')
if use_pgdb:
    _CONN = pgdb.connect(connect_string)
else:
    _CONN = psycopg2.connect(dsn)

rawDescription: New project Python 3x PostgreSQL 9x and pg8000 1x DBAPI?


code:
import csv

NUMCOLS = 13

with open('train.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    # initialize totals
    Icount = 0
    Hcount = 0
    H_col_totals = [0.0 for _ in range(NUMCOLS)]  # init to floating pt value for Py 2
    I_col_totals = [0.0 for _ in range(NUMCOLS)]  # init to floating pt value for Py 2
    # read and process file
    for row in reader:
        if row:  # non-blank line?
            # update running total for each column
            row = list(map(int, row))
            for col in range(NUMCOLS):
                if row[col] > 0:
                    Icount += 1
                    I_col_totals[col] += row[col]
                else:
                    Hcount += 1
                    H_col_totals[col] += row[col]

# compute average of data in each column
if Hcount < 1:  # avoid dividing by zero
    HPavgs = [0.0 for _ in range(NUMCOLS)]
else:
    HPavgs = [H_col_totals[col]/Hcount for col in range(NUMCOLS)]

if Icount < 1:  # avoid dividing by zero
    IPavgs = [0.0 for _ in range(NUMCOLS)]
else:
    IPavgs = [I_col_totals[col]/Icount for col in range(NUMCOLS)]

print("Total number of healthy patients: {}".format(Hcount))
print("Total number of ill patients: {}".format(Icount))
print("Averages of healthy patients: " +
      ", ".join(format(HPavgs[col], ".2f") for col in range(NUMCOLS)))
print("Averages of ill patients: " +
      ", ".join(format(IPavgs[col], ".2f") for col in range(NUMCOLS)))

rawDescription: How to get averages per column not row from a CSV file?

description: Get averages per column not row from a CSV file


code:
def print_latency(f):
    def wrapped(*args, **kwargs):
        try:
            start = time.time()
            r = f(*args, **kwargs)
        finally:
            print >>sys.stderr, 'Latency (%s): %.3fs' % (f.__name__, time.time() - start)
        return r
    wrapped.__name__ = f.__name__
    return wrapped

@print_latency
def my_view(request):
    ...

rawDescription: need help with intermediate/advanced caching in django, with memcached and friends

description: Need help with intermediate/advanced caching in django, with memcached and friends


code:
from Tkinter import *

class MyApp:
    def __init__(self, parent):

        #------ constants for controlling layout of buttons ------
        button_width = 15
        button_padx = "2m"
        button_pady = "1m"
        buttons_frame_padx =  "3m"
        buttons_frame_pady =  "0m"
        buttons_frame_ipadx = "3m"
        buttons_frame_ipady = "0m"
        # -------------- end button constants ----------------

        # First declare ORIGINAL Window area
        self.myParent = parent
        self.myParent.geometry("640x400")

        # Layer ONE
        ### Our First layer/frame is called frameLayerOne
        self.frameLayerOne = Frame(parent, bg="green")
        self.frameLayerOne.pack(expand=YES, fill=BOTH)

        ### We will stack vertically inside frameLayerOne.
        ### Inside frameLayerOne, we will create
        ### a menu_frame, then a sub frame into which we will
        ### put an output_frame and an input_frame.

        # Layer TWO
        # MENU FRAME - Layer Two
        self.menu_frame = Frame(self.frameLayerOne, borderwidth=5,  relief=RIDGE, bg="cyan")
        self.menu_frame.pack(side=TOP, expand=NO,  padx=0, pady=0, ipadx=0, ipady=0, fill=X)

        MessageMenuFrame="Menu frame.\n"
        # Label(self.menu_frame, text=MessageMenuFrame, justify=LEFT).pack(side=TOP, anchor=W)

        # buttons frame
        self.buttons_frame = Frame(self.menu_frame) # , bg="red"
        self.buttons_frame.pack(side=TOP,
            ipadx=buttons_frame_ipadx,
            ipady=buttons_frame_ipady,
            padx=buttons_frame_padx,
            pady=buttons_frame_pady,)

        # now we add the buttons to the buttons_frame
        self.button1 = Button(self.buttons_frame, command=self.button1Click)
        self.button1.configure(text="CONNECT", background= "green")
        self.button1.focus_force()
        self.button1.configure(width=button_width,
            padx=button_padx,
            pady=button_pady)

        self.button1.pack(side=LEFT)
        # T3 - bound to regular button1Click
        self.button1.bind("<Return>", self.button1Click)

        self.button2 = Button(self.buttons_frame, command=self.button2Click)
        self.button2.configure(text="QUIT", background="red")
        self.button2.configure(width=button_width,
            padx=button_padx,
            pady=button_pady)

        self.button2.pack(side=RIGHT)
        # T3 - bound to regular button2Click
        self.button2.bind("<Return>", self.button2Click)

        # SUB FRAME - Layer Two
        self.sub_frame = Frame(self.frameLayerOne) # , bg="red"
        self.sub_frame.pack(side=BOTTOM, expand=YES,  padx=0, pady=0, ipadx=0, ipady=0, fill=BOTH)

        # Layer THREE
        # INPUT FRAME - Layer Three
        self.input_frame = Frame(self.sub_frame, borderwidth=5,  relief=RIDGE, bg="black")
        self.input_frame.pack(side=BOTTOM, expand=NO,  padx=0, pady=0, ipadx=0, ipady=0, fill=X)

        # Text widget for user input to send to server
        self.InputText = Text(self.input_frame, height=4, bg="black", fg="green")
        self.InputText.pack()
        self.InputText.insert(END, "User input here")

        self.InputText.bind('<Return>', self.return_key)

        # OUTPUT FRAME - Layer Three
        self.output_frame = Frame(self.sub_frame, borderwidth=5,  relief=RIDGE, bg="blue")
        self.output_frame.pack(side=BOTTOM, expand=YES,  padx=0, pady=0, ipadx=5, ipady=25, fill=BOTH)

        # Text widget for output from code and server
        self.OutputText = Text(self.output_frame, bg="black", fg="green")
        self.OutputText.pack()
        self.OutputText.insert(END, "server and code output here")

    def return_key(self, event):
        text = "you pressed Return"
        self.InputText.insert(END, text)

    def button1Click(self, event=None): # T3 - give it a default event of None
        if self.button1["background"] == "green":
            self.button1["background"] = "yellow"
        else:
            self.button1["background"] = "green"
        self.button1.focus_set() # T3 - set focus to this button so Return works

    def button2Click(self, event=None): # T3 - give it a default event of None
        self.myParent.destroy()

root = Tk()
myapp = MyApp(root)
root.mainloop()

rawDescription: Python TKinter binding to enter key

description: Python TKinter binding to enter key


rawDescription: Assign glob.iglob() results to a list

description: Assign glob.iglob() results to a list


code:
self.label.set_use_markup(True)
t = time.strftime('%m/%d/%Y-%H%M%S')
self.label.set_markup('The time: ' + t)

rawDescription: Changing font in Window created in python code


code:
M = N.repeat(N.arange(1,11), 5).reshape(10,-1)
M
for i in range(5):
   N.random.shuffle(M[:,i])
M

rawDescription: filling in numpy array

description: Filling in numpy array


code:
contours = cv.FindContours(imgg,storage,cv.CV_RETR_TREE,cv.CV_CHAIN_APPROX_SIMPLE,(0,0))
colours = [ (0,255,0,0),   # green
            (255,0,0,0),   # blue
            (255,255,0,0), # cyan
            (0,255,255,0), # yellow
            (255,0,255,0), # magenta
            (0,0,255,0)]   # red
i=0
while contours:
    cv.DrawContours(img, contours, colours[i], colours[i], 0, thickness=-1)
    i = (i+1) % len(colours)
    contours = contours.h_next() # go to next contour
cv.ShowImage('img',img)
cv.WaitKey(0)

rawDescription: What does result of 'list(contour)' denote?


code:
for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                down_pressed = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                down_pressed = False

if down_pressed:
  print("Down is pressed")

rawDescription: Pygame key pressed down

description: Pygame key pressed down


code:
import time, sys

for i in range(15):
    sys.stdout.write("   ")
    x = i % 4
    sys.stdout.write('\r' + "." * x )
    time.sleep(0.5)
    sys.stdout.flush()

rawDescription: Wait animation "..." to appear over and over


code:
from string import maketrans

def encrypt(s, scheme):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    translation = maketrans(alphabet, scheme)
    return s.translate(translation)

rawDescription: Substitution Encryption (ProblemSetQuestion) in Python


code:
import unittest
from mock import *
from datetime import datetime, timedelta
import time

mock_time = Mock()
mock_time.return_value = time.mktime(datetime(2011, 6, 21).timetuple())

class TestCrawlerChecksDates(unittest.TestCase):
    @patch('time.time', mock_time)
    def test_mock_datetime_now(self):
        self.assertEqual(datetime(2011, 6, 21), datetime.now())

rawDescription: Is it possible and safe to replace functions as time() or sleep() for testing purposes?


code: href="{% url foo %}?bar=1"

rawDescription: how to modify the reverse url for GET?

description: Modify the reverse url for GET


code:
from heapq import nsmallest
in_list = [1, 2, 3, 4, 5, 6]
nsmallest(3, in_list)

rawDescription: How do I return a list of the 3 lowest values in another list

description: Return a list of the 3 lowest values in another list


code:
instance = test_class()
answer = instance.GetType().GetProperty("Amount").PropertyType

rawDescription: Ironpython get type of property of dot net class


rawDescription: variable doesn't reset in while loop with function

description: Variable doesn't reset in while loop with function


code:
from Tkinter import *
from tkFileDialog import *

root = Tk()
root.withdraw() # hide root

path = askdirectory()
root.mainloop()

rawDescription: Calling tkFileDialog without opening a parent window


code:
class Fantasy():
    def womble(self):
        print('I am a womble!')
    def dragon(self):
        """ Make the Dragon roar! """
        print('I am a dragon...ROAR!')
help(Fantasy)

rawDescription: Updating Python Script with Updated Method?


code: results = [obj.callable() for _, obj in obj_list]

rawDescription: For loop, iterate and call

description: For loop, iterate and call


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

def _blit_draw(self, artists, bg_cache):
    # Handles blitted drawing, which renders only the artists given instead
    # of the entire figure.
    updated_ax = []
    for a in artists:
        # If we haven't cached the background for this axes object, do
        # so now. This might not always be reliable, but it's an attempt
        # to automate the process.
        if a.axes not in bg_cache:
            # bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.bbox)
            # change here
            bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.figure.bbox)
        a.axes.draw_artist(a)
        updated_ax.append(a.axes)

    # After rendering all the needed artists, blit each axes individually.
    for ax in set(updated_ax):
        # and here
        # ax.figure.canvas.blit(ax.bbox)
        ax.figure.canvas.blit(ax.figure.bbox)

# MONKEY PATCH!!
matplotlib.animation.Animation._blit_draw = _blit_draw

vls = np.linspace(0,2*2*np.pi,100)

fig=plt.figure()
img, = plt.plot(np.sin(vls))
ax = plt.axes()
ax.set_xlim([0,2*2*np.pi])
#ttl = ax.set_title('',animated=True)
ttl = ax.text(.5, 1.05, '', transform = ax.transAxes, va='center')

def init():
    ttl.set_text('')
    img.set_data([0],[0])
    return img, ttl

def func(n):
    ttl.set_text(str(n))
    img.set_data(vls,np.sin(vls+.02*n*2*np.pi))
    return img, ttl

ani = animation.FuncAnimation(fig,func,init_func=init,frames=50,interval=30,blit=True)

plt.show()

rawDescription: Animated title in matplotlib

description: Animated title in matplotlib


code:
import ast

d = ast.literal_eval("{'code1':1,'code2':1}")

rawDescription: Convert unicode string dictionary into dictionary in python


code: area = int(size_result.split('.')[0])

rawDescription: using python to remove extra characters from strings and remove two decimal places to make it an integer

description: Using python to remove extra characters from strings and remove two decimal places to make it an integer


code:
class DictScreen(Screen):
   category_selected = ObjectProperty(None)

   def on_category_selected(self, instance, value):
      category_selected = value
      self.clear_widgets()
      self.add_widget(Button(text=category_selected.name))

rawDescription: Init screen in kv on button release using ScreenManager


code:
import pandas as pd
import numpy as np

values = pd.Series([-1, -2.4, 5, 6, 7, -4, -8, 0])
sign_str = "--+++--0"

sign_map = {
    "+" : 1,
    "0" : 0,
    "-" : -1
}

expected_signs = list(map(sign_map.get, sign_str))
observed_signs = np.sign(values)
np.all(expected_signs == observed_signs)

rawDescription: How to check if the signs of a Series conform to a given string of signs?

description: Check if the signs of a Series conform to a given string of signs


rawDescription: Python: Divide each row of a DataFrame by another DataFrame vector


rawDescription: create lists of unique names in a for -loop in python

description: Create lists of unique names in a for -loop in python


code:
class AForm(ModelForm):
    a_field = Field(required=False,
                    widget=forms.HiddenInput)
    class Meta:
        model = AModel

    def clean_a_field(self):
        return 10

rawDescription: Django - Assign default value to field in ModelForm


code:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from scrapy.spider import Spider
from scrapy.selector import HtmlXPathSelector
from scrapy import log
from scrapy.selector import Selector

class jobSpider(Spider):
    name='jobSpider'
    wd = webdriver.Chrome()
    wd.get("https://www.leforem.be/particuliers/offres-emploi-recherche-par-criteres.html?exParfullText=&exPar_search_=true&exParGeographyEdi=true")
    wd.switch_to_frame("cible")

    def parse(self, response):
        log.start()

        wait = WebDriverWait(wd, 10).until(
        (EC.visibility_of_element_located((By.ID, 'blocResultat'))))
        print(wd.page_source)

        stuff=Selector(text=wd.page_source).xpath('//a[contains(@onclick,"win=window.o    pen(\'JobOffs")]').extract()
        print(stuff)

rawDescription: Scrapy not entering parse method

description: Scrapy not entering parse method


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

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

        self.label = QLabel("Try Ctrl+O", self)
        self.shortcut = QShortcut(QKeySequence("Ctrl+O"), self)
        self.shortcut.activated.connect(self.on_open)

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

        self.setLayout(self.layout)
        self.resize(150, 100)
        self.show()

    @pyqtSlot()
    def on_open(self):
        print("Opening!")

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

rawDescription: PyQt5: Keyboard shortcuts w/ QAction

description: PyQt5: Keyboard shortcuts w/ QAction


code:
class Profile(models.Model):
    accounts = models.ManyToManyField('project.Account',
                                      through='project.ProfileAccount')

    def get_accounts(self):
        return self.accounts.order_by('link_to_profile')

class Account(models.Model):
    name = models.CharField(max_length=32)

class ProfileAccount(models.Model):
    profile = models.ForeignKey('project.Profile')
    account = models.ForeignKey('project.Account', related_name='link_to_profile')
    number = models.PositiveIntegerField()

    class Meta:
        ordering = ('number',)

rawDescription: Django ManyToManyField ordering using through?


code:
class A(object):
   def __str__(self):
       return "I'm friendly!"
   def __repr__(self):
       return "If different, I'm generally more verbose!"
a = A()
print(a)
a

rawDescription: What built-in function is called when entering object in interactive Python shell?


code:
table_query = neo4j.CypherQuery(db, "merge (x: Table{name: 'table_param'}) return x")
results = table_query.execute()

for r in results:
    # get the node you return in your query
    my_node = r[0]
    # get the properties of your node
    props = my_node.get_properties()

rawDescription: CypherResults py2neo get node object

description: CypherResults py2neo get node object


code:
class Form(wx.Dialog):
 def __init__(self):
  wx.Dialog.__init__(MAIN_WINDOW, -1, "Dialog")
  self.Bind(wx.EVT_CLOSE, self.onClose)
  ...
 def onClose(self, evt):
  self.Destroy()

rawDescription: wxPython App - Ensure All Dialogs are Destroyed

description: WxPython App - Ensure All Dialogs are Destroyed


code:
import commands
from easygui import *

output = commands.getstatusoutput("command")
msgbox(msg=output[1])

rawDescription: python with flashdrives and linux commands

description: Python with flashdrives and linux commands


code: bound_handler = handler.__get__(self, MyWidget)

rawDescription: Python: Bind an Unbound Method?

description: Python: Bind an Unbound Method


code:
class FileBrowser(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setGeometry(0, 0, 920, 780)
        self.initClasses()
        # changes
        layout = QVBoxLayout(self) # create layout out
        layout.addWidget(self.groupBox1) # add widget
        layout.addWidget(self.labelGroup1_ShotInfo) # add widget
        # set my layout to make sure contents are correctly rendered
        self.setLayout(layout)

    def initClasses(self):
        # GroupBox
        self.groupBox1 = GroupBox(self, QRect(20, 10, 191, 131),  'Shot Info')

        # Label
        self.labelGroup1_ShotInfo = Label(self, QRect(10, 26, 52, 15),  'Film')

rawDescription: Pyqt GroupBox parenting

description: Pyqt GroupBox parenting


code:
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('url here')

driver.find_element_by_class_name('download-data-link1').click()

rawDescription: downloading a file from a webpage using python script without url , calling onClick function

description: Downloading a file from a webpage using python script without url , calling onClick function


code: dict = { "a1" : True } # True is occuped

rawDescription: Repeat random placing of ships in battleship, depending on restrictions


code:
from numpy import prod
from itertools import combinations
lst = [2,3,5,7]
[prod(x) for i in range(2, len(lst)+1) for x in combinations(lst, i)]

rawDescription: Compute all products for all numbers in a python list


code:
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
    for k,v in c.iteritems():
        c3.setdefault(k, []).append(v)

rawDescription: Combining the values in two dictionaries into a list


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
i = 2 # do it 2 times
while i > 0:
    driver = webdriver.Firefox()
    driver.get("http://www.jonessoda.com/contests/back2school")

    def find_by_xpath(locator):
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, locator))
        )

        return element

    class FormPage(object):
        def fill_form(self, data):
            find_by_xpath('//input[@name = "fname"]').send_keys(data['fname'])
            find_by_xpath('//input[@name = "lname"]').send_keys(data['lname'])
            find_by_xpath('//input[@name = "email"]').send_keys(data['email'])
            find_by_xpath('//select[@name = "birthday_month"]').send_keys(data['month'])
            find_by_xpath('//select[@name = "birthday_day"]').send_keys(data['day'])
            find_by_xpath('//select[@name = "birthday_year"]').send_keys(data['year'])

            return self # makes it so you can call .submit() after calling this function

        def submit(self):
            find_by_xpath('//input[@value = "Submit"]').click()

    data = {
        'fname': 'Sheep',
        'lname': 'Test',
        'email': 'jess@sheeptest.com',
        'month': 'October',
        'day': '29',
        'year': '1920'
    }

    FormPage().fill_form(data).submit()
    driver.quit() # closes the webbrowser
    i = i - 1

rawDescription: Filling Out Web Form Data Using Built-In Python Modules


code:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero

def schechter_fit(x, alpha=2):
    y = pow(x,alpha)*numpy.exp(-x)-10
    return y

schechter_range = numpy.linspace(10, 12, 10000)

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

ax.plot(schechter_range, schechter_fit(schechter_range), 'k')

rawDescription: Exponential function: what have I done wrong?


code:
for instance in SESSION.query(SampleClass).filter(SampleClass.id == 2):
  for colname in instance.__table__.columns.keys():
    setattr(instance, colname, 'text_to_insert')

rawDescription: How can I reference a column without entering the column name?

description: Reference a column without entering the column name


code:
class ExamCreateForm(forms.ModelForm):
    class Meta:
        model = Exam
        fields = '__all__'

    def __init__(self, cc, *args, **kwargs):
        super(ExamCreateForm, self).__init__(*args, **kwargs)
        if cc:
            del self.fields['section']

rawDescription: Excluding django form fields when condition met


rawDescription: Convert simple function to arrange list into a one liner?


code:
import time

# ....

def get_timestamp():
    # Make the timestamp whatever you want...
    return time.strftime("%Y%m%d-%H%M%S")

# ....

face_present = []
ts_start = None
ts_prev = None

# ....

while (cap.isOpened()):
    ret, frame = cap.read()
    ts = get_timestamp()

    # ....

    if len(faces) > 0: # Some faces detected
        if ts_start is None: # This is the start of current sequence
            ts_start = ts
    elif (ts_start is not None) and (ts_prev is not None):
        # First frame without face following a sequence with face...
        face_present.append((ts_start, ts_prev))
        ts_start = None

    ts_prev = ts

rawDescription: OpenCV face presence/absence periods of time


code:
__all__ = (
    ####### Class Objects

    #CoGetClassObject - Normal, not wrapped
    'CoDllGetClassObject', #Get ClassObject from a DLL file

    ####### ClassFactory::CreateInstance Wrappers

    'CoCreateInstanceFromFactory', #Create an object via IClassFactory::CreateInstance
    'CoCreateInstanceFromFactoryLicenced', #Create a licenced object via IClassFactory2::CreateInstanceLic

    ###### Util

    'CoReleaseObject', #Calls Release() on a COM object

    ###### Main Utility Methods

    #'CoCreateInstance', #Not wrapped, normal call
    'CoCreateInstanceLicenced', #CoCreateInstance, but with a licence key

    ###### Hacky DLL methods for reg-free COM without Activation Contexts, manifests, etc
    'CoCreateInstanceFromDll', #Given a dll, a clsid, and an iid, create an object
    'CoCreateInstanceFromDllLicenced', #Given a dll, a clsid, an iid, and a license key, create an object
)

IID_IClassFactory2 = "{B196B28F-BAB4-101A-B69C-00AA00341D07}"

from uuid import UUID
from ctypes import OleDLL, WinDLL, c_ulong, byref, WINFUNCTYPE, POINTER, c_char_p, c_void_p
from ctypes.wintypes import HRESULT
import pythoncom
import win32com.client

import logging
log = logging.getLogger(__name__)

def _raw_guid(guid):
    """Given a string GUID, or a pythoncom IID, return the GUID laid out in memory suitable for passing to ctypes"""
    return UUID(str(guid)).bytes_le

proto_icf2_base = WINFUNCTYPE(HRESULT,
    c_ulong,
    c_ulong,
    c_char_p,
    c_ulong,
    POINTER(c_ulong),
)
IClassFactory2__CreateInstanceLic = proto_icf2_base(7, 'CreateInstanceLic', (
    (1, 'pUnkOuter'),
    (1 | 4, 'pUnkReserved'),
    (1, 'riid'),
    (1, 'bstrKey'),
    (2, 'ppvObj'),
    ), _raw_guid(IID_IClassFactory2))

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

def _pc_wrap(iptr, resultCLSID=None):
    #return win32com.client.__WrapDispatch(iptr)
    log.debug("_pc_wrap: %s, %s"%(iptr, resultCLSID))
    disp = win32com.client.Dispatch(iptr, resultCLSID=resultCLSID)
    log.debug("_pc_wrap: %s (%s)", disp.__class__.__name__, disp)
    return disp

def CoCreateInstanceFromFactory(factory_ptr, iid_interface=pythoncom.IID_IDispatch, pUnkOuter=None):
    """Given a factory_ptr whose interface is IClassFactory, create the instance of clsid_class with the specified interface"""
    ClassFactory = pythoncom.ObjectFromAddress(factory_ptr.value, pythoncom.IID_IClassFactory)
    i = ClassFactory.CreateInstance(pUnkOuter, iid_interface)
    return i

def CoCreateInstanceFromFactoryLicenced(factory_ptr, key, iid_interface=pythoncom.IID_IDispatch, pUnkOuter=None):
    """Given a factory_ptr whose interface is IClassFactory2, create the instance of clsid_class with the specified interface"""
    requested_iid = _raw_guid(iid_interface)

    ole_aut = WinDLL("OleAut32.dll")
    key_bstr = ole_aut.SysAllocString(unicode(key))
    try:
        obj = IClassFactory2__CreateInstanceLic(factory_ptr, pUnkOuter or 0, c_char_p(requested_iid), key_bstr)
        disp_obj = pythoncom.ObjectFromAddress(obj, iid_interface)
        return disp_obj
    finally:
        if key_bstr:
            ole_aut.SysFreeString(key_bstr)

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

def CoReleaseObject(obj_ptr):
    """Calls Release() on a COM object. obj_ptr should be a c_void_p"""
    if not obj_ptr:
        return
    IUnknown__Release = WINFUNCTYPE(HRESULT)(2, 'Release', (), pythoncom.IID_IUnknown)
    IUnknown__Release(obj_ptr)

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

def CoCreateInstanceLicenced(clsid_class, key, pythoncom_iid_interface=pythoncom.IID_IDispatch, dwClsContext=pythoncom.CLSCTX_SERVER, pythoncom_wrapdisp=True, wrapas=None):
    """Uses IClassFactory2::CreateInstanceLic to create a COM object given a licence key."""
    IID_IClassFactory2 = "{B196B28F-BAB4-101A-B69C-00AA00341D07}"
    ole = OleDLL("Ole32.dll")
    clsid_class_raw = _raw_guid(clsid_class)
    iclassfactory2 = _raw_guid(IID_IClassFactory2)
    com_classfactory = c_void_p(0)

    ole.CoGetClassObject(clsid_class_raw, dwClsContext, None, iclassfactory2, byref(com_classfactory))
    try:
        iptr = CoCreateInstanceFromFactoryLicenced(
                factory_ptr = com_classfactory,
                key=key,
                iid_interface=pythoncom_iid_interface,
                pUnkOuter=None,
        )
        if pythoncom_wrapdisp:
            return _pc_wrap(iptr, resultCLSID=wrapas or clsid_class)
        return iptr
    finally:
        if com_classfactory:
            CoReleaseObject(com_classfactory)

#-----------------------------------------------------------
#DLLs

def CoDllGetClassObject(dll_filename, clsid_class, iid_factory=pythoncom.IID_IClassFactory):
    """Given a DLL filename and a desired class, return the factory for that class (as a c_void_p)"""
    dll = OleDLL(dll_filename)
    clsid_class = _raw_guid(clsid_class)
    iclassfactory = _raw_guid(iid_factory)
    com_classfactory = c_void_p(0)
    dll.DllGetClassObject(clsid_class, iclassfactory, byref(com_classfactory))
    return com_classfactory

def CoCreateInstanceFromDll(dll, clsid_class, iid_interface=pythoncom.IID_IDispatch, pythoncom_wrapdisp=True, wrapas=None):
    iclassfactory_ptr = CoDllGetClassObject(dll, clsid_class)
    try:
        iptr = CoCreateInstanceFromFactory(iclassfactory_ptr, iid_interface)
        if pythoncom_wrapdisp:
            return _pc_wrap(iptr, resultCLSID=wrapas or clsid_class)
        return iptr
    finally:
        CoReleaseObject(iclassfactory_ptr)

def CoCreateInstanceFromDllLicenced(dll, clsid_class, key, iid_interface=pythoncom.IID_IDispatch, pythoncom_wrapdisp=True, wrapas=None):
    iclassfactory2_ptr = CoDllGetClassObject(dll, clsid_class, iid_factory=IID_IClassFactory2)
    try:
        iptr = CoCreateInstanceFromFactoryLicenced(iclassfactory2_ptr, key, iid_interface)
        if pythoncom_wrapdisp:
            return _pc_wrap(iptr, resultCLSID=wrapas or clsid_class)
        return iptr
    finally:
        CoReleaseObject(iclassfactory2_ptr)

rawDescription: Accessing unregistered COM objects from python via a registered TLB


code:
from os import path
from glob import glob
EXTENSIONS = ['*.pdf', '*.eml', '*.doc']
DOC_PATH = '/PATH/TO/YOUR/FILES'

files = []
for ext in EXTENSIONS:
    files.extend(glob(path.join(DOC_PATH, ext)))

# files will now contain all files in DOCPATH with EXTENSIONS

rawDescription: How to upload arbitrary number of files with different file types

description: Upload arbitrary number of files with different file types


code:
def userchoicevalidator():
    x = input("Please Enter Your Choice: ")
    while x not in list('123'):
        x = input("Please Enter Your Choice: ")

rawDescription: how to make sure user inputs a given set of numbers in python

description: Make sure user inputs a given set of numbers in python


code:
import subprocess
subprocess.call("service postgresql start ; wait ; service metasploit start ; wait ; armitagedate", shell=True)

rawDescription: Python OS command

description: Python OS command


rawDescription: Python check for blank CSV value not working


code:
def get_function(f_name):
    """Return function from library..."""
    lib = f_name.rsplit('.', 1)[0]
    modl = __import__(lib)
    comps = f_name.split('.')[1:]
    for comp in comps:
        modl = getattr(modl,comp)
    return modl

rawDescription: Python2 reflection: Strange behavior of __import__()


code:
import subprocess
subprocess.call(['fab', '-f', 'fabfile.py', '-u ec2-user', '-i', 'id_rsa', '-H', bakery_internalip, 'deploy'])

rawDescription: How to call my fabfile within my Python script

description: Call my fabfile within my Python script


code:
class TestClass(ParentClass):
    def __init__(self):
        ParentClass.map_event_to_callback(ParentClass.event, lambda text: print("hello"))

rawDescription: Is it un-pythonic to define a function inside of a class method?


code:
import time
max_radius = 20

i0 = time.time()
class DiscTemplate:
    def __init__(self, max_r):
        self.memos = []
        for k_r in range(1, max_r + 1):
            k_r_sq = k_r ** 2
            self.memos.append([])
            for x in range(-max_r, max_r + 1):
                x_sq = x ** 2
                for y in range(-max_r, max_r + 1):
                    y_sq = y ** 2
                    if x_sq + y_sq <= k_r_sq:
                        self.memos[k_r - 1].append((x,y))

        self.max_r = max_r

    def get_disc(self, r):
        return self.memos[r - 1]
test = DiscTemplate(20)
i1 = time.time()

print("time to make class:", i1 - i0)

t0 = time.time()
disc = test.get_disc(2)
t1 = time.time()

print("time to produce disc:", t1 - t0)
print("Disc coordinates: \n", disc)

rawDescription: Python to Draw a Filled "Circle" on a Grid


code:
from PIL import Image                                  # .INIT
im = Image.open( "ColorLookUpTABLE___TEST_CHART.png" ) # .GET 258,200 [px]
imB = im.resize( ( 516, 400 ) )                        # .SET 516,400 [px] a double
imB                                                    # .CHK instance
imB.show()                                             # .GUI shown

rawDescription: Not possible to resize images to bigger sizes with Pillow?


code:
quoted_string = '"this is a quote"'
quoted_string
import ast
unquoted_string = ast.literal_eval(quoted_string)
unquoted_string

rawDescription: ConfigParser.get returning a string need to convert it to section


code:
K = 5
fitness_landscape = np.random.uniform (0, 1, size = (N,) + (2,) * K)
fitness_landscape.shape

rawDescription: How to make random N-dimensions by using Numpy?

description: Make random N-dimensions by using Numpy


code:
for let in llistL:
    if let == letter:
        print("Found it!")
        break
else:
    print("nope could'nt find it")

rawDescription: What happens when loop gets to the end?

description: What happens when loop gets to the end


code:
RedirectView(
    url=reverse_lazy('admin:login'),
    query_string=True,
    # You might want to set permanent=False,
    # as it defaults to True for Django < 1.9
    permanent=False,
)

rawDescription: Django: admin login with parameter

description: Django: admin login with parameter


code:
'''
Created on Apr 29, 2016

@author: billal begueradj
'''
from tkinter import *

class Application(Frame):

   def __init__(self,  master):
       super(Application,self).__init__(master)
       self.grid()
       self.create_widgets()

   def create_widgets(self):
       self.be=Button(self,text="start", command = self.enable_widgets)
       self.be.grid(row=1,column=1,sticky="s")

       self.columnconfigure(0, pad=3)
       self.columnconfigure(1, pad=3)
       self.columnconfigure(2, pad=3)
       self.columnconfigure(3, pad=3)

       self.rowconfigure(0, pad=5)
       self.rowconfigure(1, pad=5)
       self.f3=Frame(self)
       self.f3.grid(row=2,column=1)
       fuel = Button(self.f3, text="Button",width=19)
       fuel.grid(row=1, column=0)
       Temp = Button(self.f3, text="Button",width=19)
       Temp.grid(row=1, column=1)
       Th = Button(self.f3,text="Button",width=19)
       Th.grid(row=1, column=2)
       Eo = Button(self.f3, text="Button",width=19)
       Eo.grid(row=1, column=3)

       Bh = Button(self.f3, text="Button",width=19)
       Bh.grid(row=2, column=0)
       Abs = Button(self.f3, text="Button",width=19)
       Abs.grid(row=2, column=1)
       sp = Button(self.f3, text="Button",width=19)
       sp.grid(row=2, column=2)
       fo = Button(self.f3, text="Button",width=19)
       fo.grid(row=2, column=3)
       for child in self.f3.winfo_children():
           child.configure(state = 'disable')

   def enable_widgets(self):
       '''Enable the child widgets'''
       for child in self.f3.winfo_children():
           child.configure(state = 'normal')

root= Tk()
app=Application(root)
app.mainloop()

rawDescription: How to make state of window idle until button is pressed in python tkinter?

description: Make state of window idle until button is pressed in python tkinter


code:
import tkinter as tk
from tkinter import ttk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.tree = ttk.Treeview()
        self.tree.pack()
        for i in range(10):
            self.tree.insert("", "end", text="Item %s" % i)
        self.tree.bind("<Double-1>", self.OnDoubleClick)
        self.root.mainloop()

    def OnDoubleClick(self, event):
        item = self.tree.selection()[0]
        print("you clicked on", self.tree.item(item,"text"))

if __name__ == "__main__":
    app = App()

rawDescription: Command for clicking on the items of a Tkinter Treeview widget?


code:
def flatten_dict(in_dict):
    in_dict_keys = in_dict.keys()
    in_dict_values = in_dict.values()
    in_dict_values_list = []
    for value1 in in_dict_values:
        for value2 in value1:
            in_dict_values_list.append(value2)
    flattenned_dict = in_dict.copy()

    "create new dict with 'substtitutions'"
    for key in in_dict_keys:
        for i, value in enumerate(in_dict[key]):
            if value in in_dict_keys:
                flattenned_dict[key][i] = {value:in_dict[value]}
    "clean up new dict"
    for value in in_dict_values_list:
        if value in flattenned_dict:
            del flattenned_dict[value]

    return flattenned_dict

if __name__ == "__main__":
    input1 = {'1': ['2', '3', '4'],'2': ['5', '6', '7'],'3': ['8', '9', '10'],}
    input2 = {'1': ['2', '3', '4'],'2': ['5', '6', '7'],'3': ['8', '9', '10'],'7': ['11', '12']}
    flattenned_dict = flatten_dict(input2)
    print(flattenned_dict)

rawDescription: Flattening a dictionary representing a graph into a dictionary of lists


code:
import multiprocessing

# Maximum number of cpus to use at a time
max_threads = multiprocessing.cpu_count() - 1

pool = multiprocessing.Pool(max_threads)
list_files = pool.map(func,list_of_csvs)
pool.close()
pool.join()

rawDescription: Parallel processing a large number of tasks


code:
import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#CSV to JSON Conversion
csvfile = open('C://test//final-current.csv', 'r')
reader = csv.DictReader( csvfile )
mongo_client=MongoClient()
db=mongo_client.october_mug_talk
db.segment.drop()
header= [ "S No", "Instrument Name", "Buy Price", "Buy Quantity", "Sell Price", "Sell Quantity", "Last Traded Price", "Total Traded Quantity", "Average Traded Price", "Open Price", "High Price", "Low Price", "Close Price", "V" ,"Time"]

for each in reader:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)

rawDescription: how to push a csv data to mongodb using python

description: Push a csv data to mongodb using python


rawDescription: Python convert unicode minus sign to float


code:
def save(self, *args, **kwargs):
    serializer = ChatMessageSerializer(self)
    message_endpoint = ''.join(self.firebase_key)
    client.patch(message_endpoint, serializer.data)

rawDescription: Let Django model save() to firebase but not to database


rawDescription: Python - Multi-Dimensional Arrays

description: Python - Multi-Dimensional Arrays


rawDescription: opening a parent folder and highlighting particular child in default file browser using python

description: Opening a parent folder and highlighting particular child in default file browser using python


code:
from reportlab.pdfgen import canvas

c = canvas.Canvas("hello.pdf")
c.setTitle("hello stackoverflow")
c.drawString(100, 750, "Welcome to Reportlab!")
c.save()

rawDescription: Provide tab title with reportlab generated pdf


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

# Author: João S. O. Bueno
# Copyright (c) 2009 - Fundação CPqD
# License: LGPL V3.0

from types import ModuleType, FunctionType, ClassType
import sys

def find_dependent_modules():
    """gets a one level inversed module dependence tree"""
    tree = {}
    for module in sys.modules.values():
        if module is None:
            continue
        tree[module] = set()
        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            if isinstance(attr, ModuleType):
                tree[module].add(attr)
            elif type(attr) in (FunctionType, ClassType):
                tree[module].add(attr.__module__)
    return tree

def get_reversed_first_level_tree(tree):
    """Creates a one level deep straight dependence tree"""
    new_tree = {}
    for module, dependencies in tree.items():
        for dep_module in dependencies:
            if dep_module is module:
                continue
            if not dep_module in new_tree:
                new_tree[dep_module] = set([module])
            else:
                new_tree[dep_module].add(module)
    return new_tree

def find_dependants_recurse(key, rev_tree, previous=None):
    """Given a one-level dependance tree dictionary,
       recursively builds a non-repeating list of all dependant
       modules
    """
    if previous is None:
        previous = set()
    if not key in rev_tree:
        return []
    this_level_dependants = set(rev_tree[key])
    next_level_dependants = set()
    for dependant in this_level_dependants:
        if dependant in previous:
            continue
        tmp_previous = previous.copy()
        tmp_previous.add(dependant)
        next_level_dependants.update(
             find_dependants_recurse(dependant, rev_tree,
                                     previous=tmp_previous,
                                    ))
    # ensures reloading order on the final list
    # by postponing the reload of modules in this level
    # that also appear later on the tree
    dependants = (list(this_level_dependants.difference(
                        next_level_dependants)) +
                  list(next_level_dependants))
    return dependants

def get_reversed_tree():
    """
        Yields a dictionary mapping all loaded modules to
        lists of the tree of modules that depend on it, in an order
        that can be used fore reloading
    """
    tree = find_dependent_modules()
    rev_tree = get_reversed_first_level_tree(tree)
    compl_tree = {}
    for module, dependant_modules in rev_tree.items():
        compl_tree[module] = find_dependants_recurse(module, rev_tree)
    return compl_tree

def reload_dependences(module):
    """
        reloads given module and all modules that
        depend on it, directly and otherwise.
    """
    tree = get_reversed_tree()
    reload(module)
    for dependant in tree[module]:
        reload(dependant)

rawDescription: how to find list of modules which depend upon a specific module in python

description: Find list of modules which depend upon a specific module in python


code:
from functools import wraps
def make_logg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        logg = open("server_log_404.txt", 'a')
        logg.write("\r\n\r\n========================\n")
        logg.write("%s\n" % datetime.datetime.today().ctime())
        logg.write("%s\n" % request.url )
        logg.write("%s" % request.headers)
        logg.write("%s\n" % str(request.form))
        logg.write("%s\n" % str(request.args))
        logg.close()
        return f(*args, **kwargs)
    return wrapper

rawDescription: python flask normal function to decoration

description: Python flask normal function to decoration


code:
import re
test = 'Something Else ( neW ) other and another (nEw ) with (nEw ) '
re.sub(r'\(\s*[nN][eE][wW]\s*\)','',test)

rawDescription: How to use re.findall or re.search to get the matches not found

description: Use re.findall or re.search to get the matches not found


code: regex(str, 'a?b?c?d?. . . ')

rawDescription: Regex to match any string that keeps the order in a sequence even if it's not complete


rawDescription: Round down to 5 factor value in float value


code:
# Imports
import numpy as np
from numpy.random import random

# Original calculation for testing purposes
def ftrue(A, X):
  ""
  K = np.zeros((len(X), len(X)))
  KA_true = np.zeros((len(X), len(X)))

  for i, Xi in enumerate(X):
    for j, Xj in enumerate(X):
      dij = Xi - Xj
      K += np.outer(dij, dij)
      KA_true += A[i, j] * np.outer(dij, dij)
  return ftrue

# Better: No Python loops. But, makes a large temporary array.
def fbetter(A, X):
  ""
  c = X[:, None, :] - X[None, :, :]
  b = A[:, :, None] * c           # ! BAD ! temporary array size N**3
  KA_better = np.tensordot(b, c, axes = [(0,1),(0,1)])
  return KA_better

# Best way: No Python for loops. No large temporary arrays
def fbest(A, X):
  ""
  KA_best = np.tensordot(A.sum(1)[:,None] * X, X, axes=[(0,), (0,)])
  KA_best += np.tensordot(A.sum(0)[:,None] * X, X, axes=[(0,), (0,)])
  KA_best -= np.tensordot(np.dot(A, X), X, axes=[(0,), (0,)])
  KA_best -= np.tensordot(X, np.dot(A, X), axes=[(0,), (0,)])
  return KA_best

# Test script
if __name__ == "__main__":

  # Parameters for the computation
  N = 250
  X = random((N, N))
  A = random((N, N))

  # Print the error
  KA_better = fbetter(A, X)
  KA_best = fbest(A, X)

  # Test against true if array size isn't too big
  if N<100:
    KA_true = ftrue(A, X)
    err = abs(KA_better - KA_true).mean()
    msg = "Mean absolute difference (better): {}."
    print(msg.format(err))

  # Test best against better
  err = abs(KA_best - KA_better).mean()
  msg = "Mean absolute difference (best): {}."
  print(msg.format(err))

rawDescription: Fast weighted scatter matrix calculation


code:
def save(self, *args, **kwargs):
    if self.park.featureteimage_set.exclude(pk=self.pk).count() >= 3:
        raise ValidationError('too much featuretes')
    super(FeatureteImage, self).save(*args, **kwargs)

rawDescription: Django - Limiting the amount of objects created to 3 and being able to update them.


code:
from __future__ import division  #You don't need this in Python3
import curses
from math import *

screen = curses.initscr()
curses.noecho()
curses.cbreak()
curses.start_color()
screen.keypad( 1 )
curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_CYAN)
highlightText = curses.color_pair( 1 )
normalText = curses.A_NORMAL
screen.border( 0 )
curses.curs_set( 0 )
max_row = 10 #max number of rows
box = curses.newwin( max_row + 2, 64, 1, 1 )
box.box()

strings = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m", "n" ] #list of strings
row_num = len( strings )

pages = int( ceil( row_num / max_row ) )
position = 1
page = 1
for i in range( 1, max_row + 1 ):
    if row_num == 0:
        box.addstr( 1, 1, "There aren't strings", highlightText )
    else:
        if (i == position):
            box.addstr( i, 2, str( i ) + " - " + strings[ i - 1 ], highlightText )
        else:
            box.addstr( i, 2, str( i ) + " - " + strings[ i - 1 ], normalText )
        if i == row_num:
            break

screen.refresh()
box.refresh()

x = screen.getch()
while x != 27:
    if x == curses.KEY_DOWN:
        if page == 1:
            if position < i:
                position = position + 1
            else:
                if pages > 1:
                    page = page + 1
                    position = 1 + ( max_row * ( page - 1 ) )
        elif page == pages:
            if position < row_num:
                position = position + 1
        else:
            if position < max_row + ( max_row * ( page - 1 ) ):
                position = position + 1
            else:
                page = page + 1
                position = 1 + ( max_row * ( page - 1 ) )
    if x == curses.KEY_UP:
        if page == 1:
            if position > 1:
                position = position - 1
        else:
            if position > ( 1 + ( max_row * ( page - 1 ) ) ):
                position = position - 1
            else:
                page = page - 1
                position = max_row + ( max_row * ( page - 1 ) )
    if x == curses.KEY_LEFT:
        if page > 1:
            page = page - 1
            position = 1 + ( max_row * ( page - 1 ) )

    if x == curses.KEY_RIGHT:
        if page < pages:
            page = page + 1
            position = ( 1 + ( max_row * ( page - 1 ) ) )
    if x == ord( "\n" ) and row_num != 0:
        screen.erase()
        screen.border( 0 )
        screen.addstr( 14, 3, "YOU HAVE PRESSED '" + strings[ position - 1 ] + "' ON POSITION " + str( position ) )

    box.erase()
    screen.border( 0 )
    box.border( 0 )

    for i in range( 1 + ( max_row * ( page - 1 ) ), max_row + 1 + ( max_row * ( page - 1 ) ) ):
        if row_num == 0:
            box.addstr( 1, 1, "There aren't strings",  highlightText )
        else:
            if ( i + ( max_row * ( page - 1 ) ) == position + ( max_row * ( page - 1 ) ) ):
                box.addstr( i - ( max_row * ( page - 1 ) ), 2, str( i ) + " - " + strings[ i - 1 ], highlightText )
            else:
                box.addstr( i - ( max_row * ( page - 1 ) ), 2, str( i ) + " - " + strings[ i - 1 ], normalText )
            if i == row_num:
                break

    screen.refresh()
    box.refresh()
    x = screen.getch()

curses.endwin()
exit()

rawDescription: How to make a scrolling menu in python-curses

description: Make a scrolling menu in python-curses


code:
from lxml import html
raw = '''

2/6 (ABL TTTTTSSSSSS
11)v 11/4

2/6 (ABL TTTTTSSSSSS
11)v1 11/4

'''

root = html.fromstring(raw)
result = [''.join(txt for txt in td.xpath("a/following-sibling::text()")).strip() \
            for td in root.xpath("//td")]

result

rawDescription: XPATH (again) optional tag element extract single string


code:
import sys
def str_to_obj(astr):
    '''
    str_to_obj('scipy.stats.stats') returns the associated module
    str_to_obj('scipy.stats.stats.chisquare') returns the associated function
    '''
    # print('processing %s'%astr)
    try:
        return globals()[astr]
    except KeyError:
        try:
            __import__(astr)
            mod=sys.modules[astr]
            return mod
        except ImportError:
            module,_,basename=astr.rpartition('.')
            if module:
                mod=str_to_obj(module)
                return getattr(mod,basename)
            else:
                raise

rawDescription: Pythonic way to get `package.module.Class`


code:
import itertools as it

newdic = {}
for v, grp in it.groupby(sorted((v, k) for k, v in dic.items)):
  newdic[min(k for _, k in grp)] = v

rawDescription: python dict remove duplicate values by key's value?

description: Python dict remove duplicate values by key's value


code:
choice = ""
while choice.lower() not in ("e", "elect", "c", "create"):
    choice = input("Would you like to elect a speed setting for the vectors,, create your own? (Type 'E' for elect, 'C' for create) ")

rawDescription: Why is my while loop not terminating?

description: Why is my while loop not terminating


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

theta = np.arange(0, 2, 1./180)*np.pi
r = abs(4*np.sin(2*theta))
r2 = 2 + 0*theta
r3 = np.minimum(r, r2)
plt.polar(theta, r, lw=3)
plt.polar(theta, r2, lw=3)
plt.fill_between(theta, 0, r3, alpha=0.2)
plt.show()

rawDescription: Fill Between Two Polar Curves with matplotlib fill_between


code:
learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
    learning_rate=learning_rate).minimize(mse)

sess = tf.Session()

# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})

rawDescription: How to set adaptive learning rate for GradientDescentOptimizer?

description: Set adaptive learning rate for GradientDescentOptimizer


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('someURL')
el = driver.find_element_by_id("someid")
webdriver.ActionChains(driver).move_to_element(el).click(el).perform()

rawDescription: Unable to perform click action in selenium python


code:
class CourseField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
         # return the field you want to display, which is Course
         return obj.Course

class EducationalRequirementForm(forms.ModelForm):
    Course = CourseField(queryset=Courses_list.objects.all())

rawDescription: Django: Getting foreign key value to show in forms


rawDescription: Cut and resubmit url in python

description: Cut and resubmit url in python


code:
try:
    input_list = list(input_val)
except TypeError:
    input_list = list((input_val,))

rawDescription: Passing a non-iterable to list.extend ()


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

pygame.init()
screen=pygame.display.set_mode((640,480))
clock=pygame.time.Clock()

px=35
py=35
prect=pygame.Rect(px-10,py-10,20,20)

class Enemy(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.rad=random.randint(5,10)
        self.rect=pygame.Rect(0,0,0,0)
        self.x_dir = random.choice(('left','right'))
        self.y_dir = random.choice(('up','down'))
    def move(self, mode='chase'):
        if mode=='chase':
            if self.x>px:
                self.x-=1
            elif self.x<px:
                self.x+=1
            if self.y<py:
                self.y+=1
            elif self.y>py:
                self.y-=1
        else: # roam around
            # Move for x direction
            if self.x_dir == 'left':
                if self.x > 1:
                    self.x -= 1
                else:
                    self.x_dir = 'right'
                    self.x += 1
            else:
                if self.x < px - 1:
                    self.x += 1
                else:
                    self.x_dir = 'left'
                    self.x -= 1
            # Now move for y direction
            if self.y_dir == 'up':
                if self.y > 1:
                    self.y -= 1
                else:
                    self.y_dir = 'down'
                    self.y += 1
            else:
                if self.y < py - 1:
                    self.y += 1
                else:
                    self.y_dir = 'up'
                    self.y -= 1

enemies=[Enemy(50,60),Enemy(200,100), Enemy(200,400), Enemy(200,200), Enemy(200,400), Enemy(200,200)]
roam = {} # Dict to track relative roam/chase
roam_count = {} # Dict to track time for which roaming
max_roam = {}
max_chasing = len(enemies) // 3
cur_chasing = 0
for i, enmy in enumerate(enemies):
    if cur_chasing < max_chasing:
        roam[i] = 'chase'
        cur_chasing += 1
    else:
        roam[i] = 'roam'
    roam_count[i] = 0
    max_roam[i] = random.randint(100, 500)

while True:
    screen.fill((200,230,200))
    key=pygame.key.get_pressed()

    if key[K_UP]:
        py-=2
    if key[K_DOWN]:
        py+=2
    if key[K_RIGHT]:
        px+=2
    if key[K_LEFT]:
        px-=2

    for e in pygame.event.get():
        if e.type==QUIT:
            exit()

    prect=pygame.Rect(px-20,py-20,20,20)

    for e_1, enmy in enumerate(enemies):
        pygame.draw.circle(screen, (255,0,0), (enmy.x-enmy.rad,enmy.y-enmy.rad), enmy.rad, 0)
        moved_once = False
        for e_2, enmy2 in enumerate(enemies):
            if enmy2 is not enmy:
                if enmy.rect.colliderect(enmy2.rect):
                    if roam[e_2] == roam[e_1] == 'roam':
                        if cur_chasing < max_chasing:
                            roam[e_1] = 'chase'
                    elif roam[e_2] == roam[e_1] == 'chase':
                        roam[e_2] = 'roam'
                        cur_chasing -= 1
                    if roam[e_1] == 'roam':
                        roam_count[e_1] += 1
                        enmy.move('roam')
                        if roam_count[e_1] > max_roam[e_1]:
                            roam_count[e_1] = 0
                            if cur_chasing < max_chasing:
                                roam[e_1] = 'chase'
                    else:
                        enmy.move('chase')
                else:
                    if not moved_once:
                        if roam[e_1] == 'roam':
                            roam_count[e_1] += 1
                            enmy.move('roam')
                            if roam_count[e_1] > max_roam[e_1]:
                                roam_count[e_1] = 0
                                if cur_chasing < max_chasing:
                                    roam[e_1] = 'chase'
                        else:
                            enmy.move('chase')
                        moved_once = True

        enmy.rect=pygame.Rect(enmy.x-enmy.rad*2,enmy.y-enmy.rad*2,enmy.rad*2,enmy.rad*2)
        pygame.draw.rect(screen, (0,0,255), enmy.rect, 2)

    pygame.draw.circle(screen, (0,0,255), (px-10,py-10), 10, 0)
    pygame.draw.rect(screen, (255,0,0), prect, 2)
    clock.tick(80)
    pygame.display.flip()

rawDescription: Pygame/Python Test between enemies in a list?


code:
class Foo(FooMessageProtocol):
    def __init__(self, *args, **kwargs):
        self._deferreds = {}
        super(Foo, self).__init__(*args, **kwargs)

    def sendRequest(self, data):
        self.sendMessage(id, data)
        d = self._deferreds[id] = defer.Deferred()
        return d

    def receiveAnswers(self, msg):
        response = parse(msg)
        id = response['id']
        if id in self._deferreds:
            self._deferreds.pop(id).callback(response)

rawDescription: Python Twisted: "wait" for a variable to be filled by another event


code:
el.xpath('//vuln:description',
    namespaces={'vuln': 'http://whitehatsec.com/XML-api-Vuln'})

rawDescription: XPath invalid expression when tag name has curly braces


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        canvas = tk.Canvas(self, width=800, height=500)
        canvas.pack(side="top", fill="both", expand=True)
        for i in range(0, 800, 40):
            i+= 40
            fill = "yellow" if (i / 40) % 2 == 0 else "green"
            canvas.create_rectangle(i, 0, i+20, 500, fill=fill, outline="")
        canvas_id = canvas.create_text(10, 10, anchor="nw")
        canvas.itemconfig(canvas_id, text="this is the text "*300, width=780)
        canvas.itemconfig(canvas_id, font=("courier", 12))
        canvas.insert(canvas_id, 12, "new ")

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

rawDescription: Python GUI toolkits that support text widget transparency or text widget with canvas background?


code:
from rx.executors import ThreadPoolExecutor
from rx.futures import Future

with ThreadPoolExecutor(10) as tp:
    futures = [tp.submit(foo, i) for i in range(10)] # list of futures
    future_all = Future.all(futures) # combines into single future with list of results
    future_all_sum = future_all.map(sum) # maps result list to sum of elements
    print(future_all_sum.result(timeout=10))

rawDescription: I would like to make/have a scala like 'future' async API for python


code:
qs = Department.objects.filter(departmentvolunteer__isnull=True).values_list('name', flat=True)
print(qs.query)

rawDescription: LEFT JOIN Django ORM

description: LEFT JOIN Django ORM


code:
import pickle
#Importing the module

favorite_color = { "Python": "interpreted", "C": "compiled" }
#Initializing a Dictionary (or any Python Object)

pickle.dump( favorite_color, open( "save.p", "wb" ) )
#Saving the Python object in a .p (pickle file)

#Loading the Python object from the Pickle file.
favorite_color = pickle.load( open( "save.p", "rb" ) )

rawDescription: Read python dict from file

description: Read python dict from file


code:
'''
According to the rectangle rule.
'''
import numpy as np
import matplotlib.pylab as pl
from matplotlib.patches import Polygon

# Function definition.
def f(x):
    return x ** 2 + 3

# Integration calculation.
def integration(a, b, n):
    dx = (b - a) / n
    integration = 0
    for i in np.arange(1, n + 1):
        integration += f(a + i * dx)
    integration *= dx
    return integration

# Define integral limits.
a, b = 0, 5

# Define x and y arrays.
x = np.linspace(0, 10, 10000)
y = f(x)

# Plot x and y.
fig, ax = pl.subplots()
pl.plot(x, y, 'b', linewidth = 2)
pl.xlim(xmin = -1, xmax = 11)
pl.ylim(ymin = 0)

# Shade area of the integration beneath the f(x) curve.
ix = np.linspace(a, b, 10000)
iy = f(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor = '0.9', edgecolor = '0.5')
ax.add_patch(poly)

# Print equation text.
pl.text(0.5 * (a + b), 60, r"$\int_{a}^{b}f(x)dx=%.2f$" %integration(a, b, 10000),
horizontalalignment = 'center', fontsize = 20)

# Add x and y axes labels.
pl.figtext(0.9, 0.05, '$x$')
pl.figtext(0.1, 0.9, '$y$')

# Remove right and top plot delimeter lines.
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')

# Add a and b ticks on x axis.
ax.set_xticks((a, b))
ax.set_xticklabels(('$a=%d$' %a, '$b=%d$' %b))
ax.set_yticks([])

# Show the plot.
pl.show()

rawDescription: How to plot the area of given integration?

description: Plot the area of given integration


code: global finish_control

rawDescription: While true loop not ending

description: While true loop not ending


code:
@patch.object(os, 'listdir')
class TestPackage(unittest.TestCase):
    @patch.object(sys, 'exit')
    def test_foo(self, sys_exit, os_listdir):
        os_listdir.return_value = ['file1', 'file2']
        # ... Test logic
        sys_exit.assert_called_with(1)

rawDescription: python - Accessing objects mocked with patch

description: Python - Accessing objects mocked with patch


code:
#As pymunk is python and not C, the constructor to PivotJoint is defined as
def __init__(self, a, b, *args):
    pass

#and the straight conversion from c to python is
pivot1 = PivotJoint(tankControlBody, tankBody, Vec2d.zero(), Vec2d.zero())
# but ofc it works equally well with 0 tuples instead of the zero() methods:
pivot2 = PivotJoint(tankControlBody, tankBody, (0,0), (0,0))

mySpace.add(pivot1, pivot2)

rawDescription: top down friction in pymunk

description: Top down friction in pymunk


rawDescription: how to get user id in flickr from username/useremail using Python?

description: Get user id in flickr from username/useremail using Python


code:
import base64
import socket
import struct

def decode_cookie(cookie):
    """decode a u cookie into an uid

    :param cookie: a cookie value that will be decoded into a uid
    :return: string representing the uid

    This algorithm is for version 2 of http://wiki.nginx.org/HttpUseridModule.

    This nginx module follows the apache mod_uid module algorithm, which is
    documented here: http://www.lexa.ru/programs/mod-uid-eng.html.

    """
    # get the raw binary value
    binary_cookie = base64.b64decode(cookie)

    # unpack into 4 parts, each a network byte orderd 32 bit unsigned int
    unsigned_ints = struct.unpack('!4I', binary_cookie)

    # convert from network (big-endian) to host byte (probably little-endian) order
    host_byte_order_ints = [socket.ntohl(i) for i in unsigned_ints]

    # convert to upper case hex value
    uid = 'u=' + ''.join(['{0:08X}'.format(h) for h in host_byte_order_ints])

    return uid

def encode_uid(uid):
    """encode an uid into a u cookie

    :param uid: an uid that will be encoded into a cookie.
    :return: string representing the u cookie

    The algorithm is for version 2 of http://wiki.nginx.org/HttpUseridModule.

    This nginx module follows the apache mod_uid module algorithm, which is
    documented here: http://www.lexa.ru/programs/mod-uid-eng.html.

    """
    # get the hex value of the uid
    hex_value = uid.split('=')[1]

    # convert 128 bit string into 4 32 bit integers
    host_byte_order_ints = [int(hex_value[i:i+8], 16) for i in range(0, 32, 8)]

    # convert from host byte (probably little-endian) to network byte (big-endian) order
    unsigned_ints = [socket.htonl(i) for i in host_byte_order_ints]

    # convert to raw binary value
    binary_cookie = struct.pack('!4I', *unsigned_ints)

    # get the base64 version of the cookie
    cookie = base64.b64encode(binary_cookie)

    return cookie

rawDescription: Parsing Nginx's http_userid_module cookie in Python


code:
for i, (k,v) in enumerate(container):
    if k == 24:
        container[i] = (k, v+" good")

rawDescription: How to change data in the container while iterating in python

description: Change data in the container while iterating in python


code:
df = pd.DataFrame([[1,2],[3,4]])
row = pd.Series([5,6])
df.append(row, ignore_index=True)

rawDescription: Autoincrementing option for Pandas DataFrame index


code:
#! /usr/bin/env python

import sys
import time
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR

while True:
    p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100)
    if p:
        p.show()
    time.sleep(60) # sleep for one minute

rawDescription: How to make a command repeat itself inside a python script at certain intervals

description: Make a command repeat itself inside a python script at certain intervals


code:
it = iter(dict(...)) # this is the dict(...) from the for statement
first_key = next(it)
results[first_key] = dict(...) # this is the dict(...) from inside the loop

common = set(results[first_key]) # initialize the set with the first item

for key in it:
    results[key] = dict(...) # the inner dict(...) again
    common.intersection_update(result[key])

rawDescription: python intersection initial state standard practice

description: Python intersection initial state standard practice


code:
from itertools import product
[''.join(items) for items in product(array1 + array2, repeat=3)]

rawDescription: Python: Various Lists To Cartesian Product, Variable Length


code:
image_ref = CGWindowListCreateImage(CGRectNull,
                                        kCGWindowListOptionIncludingWindow,
                                        wid,
                                        kCGWindowImageBoundsIgnoreFraming)

pixeldata = CGDataProviderCopyData(CGImageGetDataProvider(image_ref))

height = CGImageGetHeight(image_ref)
width = CGImageGetWidth(image_ref)

image = Image.frombuffer("RGBA", (width, height),
                         pixeldata, "raw", "RGBA", 0, 1)

# Color correction from BGRA to RGBA
b, g, r, a = image.split()
image = Image.merge("RGBA", (r, g, b, a))
np.array(image)
return np.array(image)

rawDescription: Cannot figure out Numpy equivalent for cv.mat.step[0]


code:
from pprint import pprint
pprint(the_list)

rawDescription: How to print a list in Python "nicely"

description: Print a list in Python "nicely"


rawDescription: python time conversion into proper time format

description: Python time conversion into proper time format


code:
lis = [1, 2, 3, 4]
i = 0
while i < len(lis):
    if some_condition:
        print(lis[i])
        i += 1
    elif some_other_condition:
        print(lis[i])
        i -= 1

rawDescription: Rewinding iteration

description: Rewinding iteration


rawDescription: python sockets how to not queue connection requests

description: Python sockets how to not queue connection requests


code:
#! /usr/bin/python3
numbers = []
while True:
    number = int(input('Give me a number: '))
    if number == -99: break
    numbers.append(number)
for number in sorted(numbers, reverse=True):
    print(number)

rawDescription: Python 3 Largest to smallest loop

description: Python 3 Largest to smallest loop


code:
for s in new_list:
   for line in file1:
     try:
       line = line.replace('rabbit', s )
       file2.write(line)
     except:
       continue

rawDescription: search & replace elements of a list into a string iteratively into a new file using python

description: Search & replace elements of a list into a string iteratively into a new file using python


code:
re.search("^(.*)$^.*$", multiline_string, re.M)    # won't match
re.search("^(.*)$\n^.*$", multiline_string, re.M)  # will match

rawDescription: Anchors in Regex

description: Anchors in Regex


code:
from IPython.html.widgets import FloatSlider

# same as before

F1 = FloatSlider(value=5, min=0, max=10)
w=interactive(sigmoid_demo, a=F1, b=7)
display(w)

rawDescription: IPython notebook interactive function: how to save the updated function parameters


code:
def simplify(l):
    i = 0
    while i < len(l):
        s = set(map(abs,l[i]))
        for x in xrange(len(l)):
            if x == i: continue
            if s <= set(map(abs,l[x])):
                l.pop(i)
                i -= 1
                break
        i += 1

rawDescription: Python: a fast way to remove subsets of lists in a list of lists


code:
class OrderItemField(serializers.RelatedField):
    def to_representation(self, value):
        if type(self.root.instance) == list:
            self.root.instance = self.root.instance[0]
        order_item = OrderItem.objects.filter(item=value, order=self.root.instance).first()
        quantity = order_item.quantity
        value = ItemSerializer(value).data
        value['quantity'] = quantity
        return value

class OrderSerializer(serializers.ModelSerializer):
    _current_status = StatusSerializer(required=False, many=False)
    items = OrderItemField(many=True, read_only=True)

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

rawDescription: ManyToMany Through Field Serialization

description: ManyToMany Through Field Serialization


code:
# leave row alone, don't bother deleting columns in it.
new_row = ["a=%s;b=%s;c=%s;d=%s"% (row[12], row[13], row[14])]
# new_row has only one column, with a string constructed of what you need.

writer.writerow(new_row)

rawDescription: How to merge several csv columns into one column using python 2.7?

description: Merge several csv columns into one column using python 2.7


code:
Class._get_collection().aggregate([
    { '$group': {
        '_id': {
            'year': { '$year': '$utc_timestamp' },
            'month': { '$month': '$utc_timestamp' },
            'day': { '$dayOfMonth': '$utc_timestamp' },
        },
        'defects': {
            '$sum': { '$cond': [
                { '$eq': [ '$status', 'defect' ] },
                1,
                0
            ]}
        },
        'totalCount': { '$sum': 1 }
    }},
    { '$project': {
        'defect_rate': {
            '$cond': [
                { '$eq': [ '$defects', 0 ] },
                0,
                { '$divide': [ '$defects', '$totalCount' ] }
            ]
        }
    }}
])

rawDescription: How to run this MongoDB query using MongoEngine

description: Run this MongoDB query using MongoEngine


code:
from multiprocessing import Process
from multiprocessing import Queue

class Sentinel(object): pass

class EchoProcess(Process):

    def __init__(self, iQ):
        Process.__init__(self)
        self.iQ = iQ

    def run(self):
        for istring in iter(iQ.get, Sentinel):
            print(istring)
        print("exited")

if __name__ == "__main__":
    iQ = Queue()
    echoProcess = EchoProcess(iQ)
    echoProcess.start()
    while True:
        istring = raw_input("Enter:")
        if istring == "quit": break
        iQ.put(istring)
    iQ.put(Sentinel)
    echoProcess.join()

rawDescription: Python 2.7: Multiprocessing: How to not block whilst using a queue for communication


code:
p0_1 = [x for x in primary_data if x not in secondary_data]
p1_1 = ' '.join(map(str, p0_1))

rawDescription: Removing dtype from the end of numpy column stack


code:
dir()
dir(__builtins__)

rawDescription: Python - How many Default Modules loaded


code:
class DefaultHelpParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

rawDescription: python argparse: How can I display help automatically on error?

description: Python argparse: How can I display help automatically on error


code:
import threading
import queue

class Worker(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.jobs_queue = queue.Queue()
        self.results_list = list()
    def run(self):
        while True:
            testNumber = self.jobs_queue.get()
            if testNumber == "END":
                return
            # here, do your stuff with 'testNumber'
            # for example, let's multiply it by 2
            answer = testNumber * 2
            # results are appended to a list
            self.results_list.append((self.name,testNumber,answer))
    def calc(self, n):
        self.jobs_queue.put(n)
        if not self.is_alive():
            self.start()
    def get_result(self):
        return self.results_list
    def stop(self):
        # tell the thread to stop,
        # once jobs in queue are done
        self.jobs_queue.put("END")
        self.join()

workers = [Worker('thread 1'), Worker('thread 2'), Worker('thread 3'), Worker('thread 4')]

for n in range(100):
    w = workers[n % 4]
    w.calc(n)

for w in workers:
    w.stop()

for w in workers:
    print(w.get_result())

rawDescription: Python _thread Have each thread process the respective number in a sequence


code:
from collections import defaultdict
d = defaultdict(list)
d['somefile.csv'].extend([3, 4])
print(d)
# defaultdict(<type 'list'>, {'somefile.csv': [3, 4]})
d['somefile.csv']
# [3, 4]

rawDescription: Python: how to assign a dictionary a value which is a list with varying length?