code:
try:
    from tkinter import *
except ImportError:
    from Tkinter import *

text = Text()
text.pack()
text.insert(END, '1st\n2nd\n3rd')
# text.tag_add("here", "2.0", "3.0") # <----------------------
text.tag_add("here", "2.0", "2.0+1lines") # <----------------------
text.tag_config("here", background="yellow", foreground="blue")
mainloop()

rawDescription: Tkinter fill whole line with background colour


code:
from django.core.cache import cache
cache._cache.flush_all()

rawDescription: In Django, how to clear all the memcached keys and values?


rawDescription: remove certain pattern in string in python

description: Remove certain pattern in string in python


code:
lines = order['OrderLines']['OrderLine']
lines = [lines] if not isinstance(lines, list) else lines

for line in lines:
    ...

rawDescription: How do I use a for loop when reading from a dictionary that might contain a list of dicts, but might not?

description: Use a for loop when reading from a dictionary that might contain a list of dicts, but might not


code:
from datetime import *
d1 = datetime.strptime('05/01/2012', "%d/%m/%Y").date()
d2 = datetime.strptime('06/01/2012', "%d/%m/%Y").date()
delta = d2 - d1
print(delta.days)

rawDescription: How do I obtain the delta between two dates?

description: Obtain the delta between two dates


code:
def main():
    global REDIS_QUEUE
    REDIS_QUEUE = redis.StrictRedis(host=SERVER_IP, port=6379, db=0)
    # whatever else

rawDescription: Initializing global object in Python

description: Initializing global object in Python


code:
def ask_number(low, high):
    while True:
        try:
            number = int(raw_input("Enter a number within the range: "))
        except ValueError:
            continue
        if low <= number <= high:
            return number

rawDescription: Python while loop/range

description: Python while loop/range


code:
import sys
from time import sleep

for i in range(3):
    sys.stdout.write('.')
    sys.stdout.flush()
    sleep(1)

print('Welcome!')

rawDescription: Why is my python output delayed to the end of the program?


rawDescription: Setting markers in plot according to values in list


rawDescription: How to slice a list into sublists that exist within a new list

description: Slice a list into sublists that exist within a new list


rawDescription: Numpy stick arrays horizontally

description: Numpy stick arrays horizontally


code:
while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
        y = int(input("y = "))
    except ValueError:
        print("Please enter a number") # don't break here, let loop repeat
    else:
        break # only break when there is no error

rawDescription: Stuck on an error in Python 3 (exceptions, loop)


code:
from ipaddress import ip_network, IPv6Network
L = [ip_network(x) for x in ['ff00::/8', 'fd00::/8', '172.16.0.0/12', '10.0.0.0/8']]
L.sort(key=lambda x: (isinstance(x, IPv6Network), x))
L

rawDescription: Sorting a list of IPv4Network and IPv6Network objects


code:
import argparse
import ast

parser = argparse.ArgumentParser() #allow the creation of known arguments ...

namespace,unparsed = parser.parse_known_args()

def parse_arg(arg):
    k,v = arg.split('=',1)
    try:
        v = ast.literal_eval(v) #evaluate the string as if it was a python literal
    except ValueError:          #if we fail, then we keep it as a string
        pass

    return k.lstrip('-'),v

d = dict(parse_arg(arg) for arg in unparsed)
print(d)

rawDescription: Command line arguments as variable definition in Python


code:
newentry = model(chunk)
session.merge(newentry)

rawDescription: Select list of Primary Key objects in SQLAlchemy


code:
import os
from django.contrib.staticfiles.management.commands.runserver import Command as RunserverCommand
class Command(RunserverCommand):
    def run(self, *args, **options):
        if os.environ.get('RUN_MAIN') != 'true':
            self.stdout.write('About to start running on ' + self.addr)
        super(Command, self).run(*args, **options)

rawDescription: Why is run called twice in the Django dev server?


code:
from datetime import datetime

sorted(response,
       key=lambda k: datetime.strptime(k['createDate'], '%Y-%m-%d %I:%M:%S %p'),
       reverse=False)

rawDescription: Python: Sort datetime in str format with lambda


code:
import random

def countSixes(start):
    newNum = random.randrange(0,10)
    if newNum == 6:
        return start + 1
    else:
        return start

if __name__ == '__main__':
    import multiprocessing
    pool = multiprocessing.Pool(1) #use one core for now

    start = 0
    async_results = [pool.apply_async(countSixes, (start,)) for i in range(1000)]

    print(sum(r.get() for r in async_results))

rawDescription: Python Multiprocessing - Just not getting it


code:
import ctypes
ctypes.windll.kernel32.SetConsoleTitleA("My New Title")

rawDescription: Set Windows command-line terminal title in Python


code:
import numpy as np
from collada import *

mesh = Collada()
axis = asset.UP_AXIS.Z_UP
mesh.assetInfo.upaxis = axis

image = material.CImage("material_0_1_0-image", "DSC_5195.jpg")
surface = material.Surface("material_0_1_0-image-surface", image)
sampler2d = material.Sampler2D("material_0_1_0-image-sampler", surface)
map1 = material.Map(sampler2d, "UVSET0")

image2 = material.CImage("material_0_1_1-image", "Untitled.png")
surface2 = material.Surface("material_0_1_1-image-surface", image2)
sampler2d_2 = material.Sampler2D("material_0_1_1-image-sampler", surface2)
map2 = material.Map(sampler2d_2, "UVSET0")

effect1 = material.Effect("material_0_0-effect", [], "lambert", emission=(0.0, 0.0, 0.0, 1),\
                     ambient=(0.0, 0.0, 0.0, 1), diffuse=(0.890196, 0.882353, 0.870588, 1),\
                     transparent=(1, 1, 1, 1), transparency=1.0, double_sided=True)
effect2 = material.Effect("material_0_1_0-effect", [surface, sampler2d], "lambert", emission=(0.0, 0.0, 0.0, 1),\
                     ambient=(0.0, 0.0, 0.0, 1),  diffuse=map1, transparent=map1, transparency=0.0, double_sided=True)

effect3 = material.Effect("material_0_1_1-effect", [surface2, sampler2d_2], "lambert", emission=(0.0, 0.0, 0.0, 1),\
                     ambient=(0.0, 0.0, 0.0, 1),  diffuse=map2, transparent=map2, transparency=0.0, double_sided=True)

mat1 = material.Material("material_0_0ID", "material_0_0", effect1)
mat2 = material.Material("material_0_1_0ID", "material_0_1_0", effect2)
mat3 = material.Material("material_0_1_1ID", "material_0_1_1", effect3)

mesh.effects.append(effect1)
mesh.effects.append(effect2)
mesh.effects.append(effect3)

mesh.materials.append(mat1)
mesh.materials.append(mat2)
mesh.materials.append(mat3)

mesh.images.append(image)
mesh.images.append(image2)

#red x-axis
#green z-axis
#blue y-axis

h = 7.0
b = 7.0
w = 10.0

m1position = [0, 0, 0, 0, b, 0, w, b, 0, w, 0, 0, 0, 0, h, 0, b, h, w, b, h, w, 0, h]
m1normal = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1]
m1uv = [1, 1, 0, 0, 1, 0, 0, 1]

m1position_src = source.FloatSource("mesh1-geometry-position", np.array(m1position), ('X', 'Y', 'Z'))
m1normal_src = source.FloatSource("mesh1-geometry-normal", np.array(m1normal), ('X', 'Y', 'Z'))
m1uv_src = source.FloatSource("mesh1-geometry-uv", np.array(m1uv), ('S', 'T'))

geom = geometry.Geometry(mesh, "mesh1-geometry", "mesh1-geometry", [m1position_src, m1normal_src, m1uv_src])
geom1 = geometry.Geometry(mesh,"mesh1-geometry1","mesh1-geometry1",[m1position_src, m1normal_src, m1uv_src])
geom2 = geometry.Geometry(mesh,"mesh1-geometry2","mesh1-geometry2",[m1position_src,m1normal_src, m1uv_src])

input_list = source.InputList()
input_list.addInput(0, 'VERTEX', "#mesh1-geometry-position")

input_list1 = source.InputList()
input_list1.addInput(0, 'VERTEX', "#mesh1-geometry-position")
input_list1.addInput(1, 'TEXCOORD', "#mesh1-geometry-uv", set="0")

input_list2 = source.InputList()
input_list2.addInput(0, 'VERTEX', "#mesh1-geometry-position")
input_list2.addInput(1, 'TEXCOORD', "#mesh1-geometry-uv", set="0")

indices1 = np.array([0, 1, 2, 2, 3, 0, 0, 1, 5, 5, 0, 4, 7, 2, 6, 2, 7, 3, 4, 3, 7, 3, 4, 0])
indices2 = np.array([2, 1, 1, 2, 5, 0, 5, 0, 6, 3, 2, 1])
indices3 = np.array([6,1,5,2,4,0,4,0,7,3,6,1])

triset1 = geom.createTriangleSet(indices1, input_list, "material_0_0")
triset2 = geom1.createTriangleSet(indices2, input_list1, "material_0_1_0")
triset3 = geom2.createTriangleSet(indices3, input_list2, "material_0_1_1")

geom.primitives.append(triset1)
geom1.primitives.append(triset2)
geom2.primitives.append(triset3)

mesh.geometries.append(geom)
mesh.geometries.append(geom1)
mesh.geometries.append(geom2)

matnode1 = scene.MaterialNode("material_0_0", mat1, inputs=[])
matnode2 = scene.MaterialNode("material_0_1_0", mat2, inputs=[])
matnode3 = scene.MaterialNode("material_0_1_1", mat3, inputs=[])

geomnode = scene.GeometryNode(geom, [matnode1])
geomnode1 = scene.GeometryNode(geom1, [matnode2])
geomnode2 = scene.GeometryNode(geom2, [matnode3])

node = scene.Node("Model", children=[geomnode, geomnode1, geomnode2])
myscene = scene.Scene("SketchUpScene", [node])
mesh.scenes.append(myscene)
mesh.scene = myscene

mesh.write("untitled.dae")

rawDescription: Texturing on 3d Blocks using pycollada

description: Texturing on 3d Blocks using pycollada


code:
import unicodedata
unicodedata.name(chr(128132))
unicodedata.name(chr(128133))
unicodedata.name(chr(128139))

rawDescription: Getting the names of unicode pictograms

description: Getting the names of unicode pictograms


code:
justtime = "14:10"
links = Driver.find_elements_by_xpath("//div[contains(.,'%s')]" % justtime)

rawDescription: Should be Simple XPATH?

description: Should be Simple XPATH


code:
def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()

    path = self.path[1:]
    components = string.split(path, '/')

    node = parse_node(content, components)

    self.wfile.write(json.dumps(node))

    return

def parse_node(node, components):
    # For a valid node and component list:
    if node and len(components) and components[0] != "favicon.ico":
        # Dicts will return parse_node of the top-level node component found,
        # reducing the component list by 1
        if type(node) == dict:
            return parse_node(node.get(components[0], None), components[1:])

        elif type(node) == list:
            # A list with an "all" argument will return a full list of sub-nodes matching the rest of the URL criteria
            if components[0] == "all":
                return [parse_node(n, components[1:]) for n in node]
            # A normal list node request will work as it did previously
            else:
                return parse_node(node[int(components[0])], components[1:])
    else:
        return node

    # Handle bad URL
    return None

rawDescription: How do I get all of one key from a list of dicts in Python?

description: Get all of one key from a list of dicts in Python


code:
obj = ctypes.py_object(buf)
address = ctypes.c_void_p()
length = ctypes.c_ssize_t()
ctypes.pythonapi.PyObject_AsReadBuffer(obj, ctypes.byref(address), ctypes.byref(length))
int_pointer = address.value

rawDescription: Get address of read-only mmap object

description: Get address of read-only mmap object


rawDescription: Matplotlib: Remove scientific notation in subplot


code: another_func.__doc__ = "My documentation"

rawDescription: How should I comment partial Python functions?


rawDescription: Python ETREE parsing of a windows XML output


code:
class MyHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self._pcb = tornado.ioloop.PeriodicCallback(self._cb, 1000)
        self._pcb.start()

    def _cb(self):
        self.write('Kapooya, Kapooya!')
        self.flush()

    def on_connection_close(self):
        self._pcb.stop()

rawDescription: How to return some variable once in few seconds to client?

description: Return some variable once in few seconds to client


code:
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name=modname,
                     sources=[pyxfilename],
                     extra_compile_args=['-O3', '-march=native'])

rawDescription: How can I set Cython compiler flags when using pyximport?

description: Set Cython compiler flags when using pyximport


code:
var1 = 2
var2 = 5
print("INFORMATION",
      "------------",
      "Variable1: {}".format(var1),
      "Variable2: {}".format(var2), sep='\n')

rawDescription: Print multiple lines with variables in a single print() statement in Python


code:
from youtube_dl import YoutubeDL # $ pip install youtube-dl
url = 'https://www.youtube.com/watch?v=pvAsqPbz9Ro'
ydl = YoutubeDL()
r = ydl.extract_info(url, download=False)
r['url']

rawDescription: Wrting python script that uses youtube-dl to extract just only the download link?


code: resultFile = open("c:\\temp\\output4.csv", 'ab')

rawDescription: Append rows to csv file

description: Append rows to csv file


code:
LinkFormset = forms.modelformset_factory(Link)
class LinkSectionForm(forms.ModelForm):
    def __init__(self, **kwargs):
        super(LinkSectionForm, self).__init__(**kwargs)
        self.link_formset = LinkFormset(instance=self.instance,
                                        data=self.data or None,
                                        prefix=self.prefix)

    def is_valid(self):
        return (super(LinkSectionForm, self).is_valid() and
                    self.link_formset.is_valid())

    def save(self, commit=True):
        # Supporting commit=False is another can of worms.  No use dealing
        # it before it's needed. (YAGNI)
        assert commit == True
        res = super(LinkSectionForm, self).save(commit=commit)
        self.link_formset.save()
        return res

rawDescription: Django admin - inline inlines (or, three model editing at once)


code:
import re
re.sub( ' *- *', '', txt )

rawDescription: How to join correctly join words that trails or heads of dashes? - python

description: Join correctly join words that trails or heads of dashes? - python


code:
for string in list :
    if not string.endswith('\n'):
         string += '\n'

rawDescription: Why isn't the string value updated?

description: Why isn't the string value updated


code:
class Node(object):

  __slots__ = 'data', 'left', 'right'

  def __init__(self, data=None, left=None, right=None):
    self.data  = data
    self.left  = left
    self.right = right

rawDescription: Data structures with Python

description: Data structures with Python


code:
weights_1_array = ...  # ndarray of weights for layer 1
biases_1_array = ...  # ndarray of biases for layer 1

conv_kernel_1 = tf.nn.conv2d(input, weights_1_array, [1, 4, 4, 1], padding='SAME')
bias_layer_1 = tf.nn.bias_add(conv_kernel_1, biases_1_array)

rawDescription: Set weight and bias tensors of tensorflow conv2d operation


code:
# somewhere in a views.py

def shutdown(request):
    import os
    os.kill(os.getpid(), 9)

rawDescription: Halting Django's dev server via page request?


code:
import glob  # Import any python module
moduleType = type(glob)

onTheFly = moduleType("OnTheFly", "Docstring for this module")

rawDescription: Does Python import instantiate a mystery class?


code:
for i, (name, age, city) in enumerate(stooges, start=1):
    print("Stooge {}: {} {} {}".format(i, name, age, city))

rawDescription: How to merge two for loops

description: Merge two for loops


rawDescription: Regex How to match Empty

description: Regex How to match Empty


code:
import collections

result = collections.defaultdict(list)

for d in dictionaries:
    for k, v in d.items():
        result[k].append(v)

rawDescription: How do I convert a list of dictionaries to a dictionary of lists in Python?

description: Convert a list of dictionaries to a dictionary of lists in Python


code:
def iter_values(it):
    if hasattr(it, 'itervalues'):
        return it.itervalues()
    return iter(x)

rawDescription: Generic iterator over the values (instead of over the keys) of any iterable


code:
from numba.compiler import compile_isolated

# second argument specifies the argument types to the sum function
cfunc = compile_isolated(sum, (types.int64, types.int64))

# get llvm IR as string
llvm_code_str = str(cfunc.llvm_module)

rawDescription: Retrieve generated LLVM from Numba

description: Retrieve generated LLVM from Numba


code:
#-*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
def callback():
    execfile("script.py")
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()

rawDescription: how to link a button to another .py file in python2.7

description: Link a button to another .py file in python2.7


code:
wDebug.move(0,0)
wDebug.deleteln()
wDebug.addstr(4, 0, msg)
wDebug.refresh()

rawDescription: Python Curses IRC/IM style updates

description: Python Curses IRC/IM style updates


code:
class ExpenditureForm(forms.ModelForm):

   exp_date = forms.DateField(widget=AdminDateWidget(attrs={'class':'nameOfYourClass'}))

rawDescription: How to set class to columns in django model formsets

description: Set class to columns in django model formsets


code:
import copy
resultsvalidation = copy.deepcopy(resultsvalidationparam)

rawDescription: Python keeps overwriting argument, even when copied in or outside of function


code:
def main():
    infile=open("putNamesHere.txt","r")
    outfile=open("getFromHere.txt","w")
    for line in infile:
        line=line.upper()
        mystring=('*'+line.rstrip()+'*\n')
        outfile.write(mystring)

rawDescription: Python text file lines keep formatting

description: Python text file lines keep formatting


code:
csv_r = csv_reader(w)
csv_w = csv.writer(w)

rawDescription: Python CSV read row by row and insert new data


code:
size_to_read = 999999
with open(file_name, "r") as f:
  read_part = f.read(size_to_read)
  if(not len(read_part) == size_to_read):
    eol_reached_unexpectedly()

rawDescription: A size of a data that actually was read

description: A size of a data that actually was read


code:
import matplotlib.pyplot as plt
import matplotlib
import random
import scipy.stats as ss

pop = range(100)
x = random.sample(pop, 10)
y = random.sample(pop, 10)
PC = ss.pearsonr(x, y)
plt.scatter(x,y,color="#3F5D7D")
blank = matplotlib.patches.Rectangle((0,0), 0, 0, fill=False, edgecolor='none', visible=False)
plt.legend([blank], ['PK:  %.3f'%(PC[0])], prop={'size':12},bbox_to_anchor=(1.1, 1.1))
plt.show()

rawDescription: Python Plot, delete just the Label from the Legend


rawDescription: Pandas dataframe slice indexing by index criterias


code:
#!/usr/bin/env python
import SimpleHTTPServer

class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_my_headers()

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")

if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)

rawDescription: Can I set a header with python's SimpleHTTPServer?

description: Set a header with python's SimpleHTTPServer


code:
def WarmWelcome(*data_sets):
    def _decorator(func):
        def _func():
            for ds in data_sets:
                func(*ds)
        return _func
    return _decorator

@WarmWelcome(
    ("abc", ),
    ("xyz", ),
    ("def", ),
)
def hello(name):
    return "hello " +name

rawDescription: Using Decorator for Data Driven Tests

description: Using Decorator for Data Driven Tests


code: newtup = [tup for tup in oldtup if tup[0] in listToSearchTuple]

rawDescription: search tuple with a list and return new tuple with only elements of the list

description: Search tuple with a list and return new tuple with only elements of the list


rawDescription: Color handling in Python

description: Color handling in Python


code:
import math
epsilon = 1e-6
m = grb.Model()
# .....
if m.SolCount > 0:
    solution = {v.varName: v.X for v in m.getVars() if math.abs(v.X) > epsilon}

rawDescription: Get best-known feasible answer after time limit


code:
def fcopy(file1, file2):
    os.chdir('C:/Users/Noah/Documents/myPython')
    open_file_1 = open(file1, 'r')
    open_file_2 = open(file2, 'w')
    for line in open_file_1:
        open_file_2.write(line)
    open_file_1.close()
    open_file_2.close()
    open_file_2 = open(file2, 'r')
    for line in open_file_2:
        print(line)
    open_file_2.close()

rawDescription: Python File I/O: Implementing a function that copy's the content of one text file to an empty text file


code:
from itertools import groupby

groups, temp = [], []
# Group items based on the actual values
for key, grp in groupby(pairs):
    grp = list(grp)
    # If it is a group of zeros and the size is >= 4
    if key == 0 and len(grp) >= 4:
        # Add the accumulated groups to the result
        groups.append(temp)
        # Make the accumulator free
        temp = []
    else:
        # If it is a group of non-zeros or zeros of size < 4,
        # extend the accumulated group
        temp.extend(grp)

if temp:
    groups.append(temp)

print(groups)
# [[1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 0, 3, 3, 3, 3], [4, 4, 4, 4]]

rawDescription: Merging and removing elements from list in a loop


code:
import urllib2
import time
import threading
from multiprocessing import Process, Queue

ACTION_ENTER = 7
ACTION_BACKSPACE = 110

event = threading.Event()

def do_request(url, q):
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    data = response.read()
    response.close()
    q.put(data)

def allchannels_timer(self):
   for i in range(1):
        time.sleep(0.3)
        self.getControl(4202).setLabel("0%")
        #DOWNLOAD THE XML SOURCE HERE
        url = ADDON.getSetting('allchannel.url')
        q = Queue()
        p = Process(target=do_request, args=(url, q))
        p.start()
        while p.is_alive():
            if event.is_set():
                p.terminate()
                return
            time.sleep(.3)
        # Make sure you don't read from the queue after calling terminate()
        data = q.get()

if action == ACTION_BACKSPACE:
     if img1_yellow == False:
       self.getControl(4202).setLabel("")
       event.set()
       self.thread.join()

if action == ACTION_ENTER:
     if img1_yellow == True:
         event.clear()
         self.thread = threading.Thread(target=self.allchannels_timer)
         self.thread.setDaemon(True)
         self.thread.start()

rawDescription: Cannot close thread in xbmc:

description: Cannot close thread in xbmc:


code:
import pycurl
c1 = pycurl.Curl()
c1.setopt(pycurl.URL, 'http://www.google.com')
c1.setopt(pycurl.PROXY, 'localhost')
c1.setopt(pycurl.PROXYPORT, 8080)
c1.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)

c2 = pycurl.Curl()
c2.setopt(pycurl.URL, 'http://www.yahoo.com')
c2.setopt(pycurl.PROXY, 'localhost')
c2.setopt(pycurl.PROXYPORT, 8081)
c2.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)

c1.perform()
c2.perform()

rawDescription: Using urllib2 with SOCKS proxy

description: Using urllib2 with SOCKS proxy


code:
client = riak.RiakClient(port=10018)
bucket = client.bucket('somebucket')
key = bucket.get('somekey')
old_meta = key.get_metadata()
old_meta['usermeta'] = {'new_key': 'new_value'}
key.set_metadata(old_meta).store()

rawDescription: Riak set timeout for individual keys

description: Riak set timeout for individual keys


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

# Parameters.
input_filename = "JPCLN001.IMG"
shape = (2048, 2048) # matrix size
dtype = np.dtype('>u2') # big-endian unsigned integer (16bit)
output_filename = "JPCLN001.PNG"

# Reading.
fid = open(input_filename, 'rb')
data = np.fromfile(fid, dtype)
image = data.reshape(shape)

# Display.
plt.imshow(image, cmap = "gray")
plt.savefig(output_filename)
plt.show()

rawDescription: Read .img medical image without header in python


code:
...
for i in disc_ex:
    new_disc = i.replace(findall('<(.*)>',i),'')
    disc.extend([re.sub(r'<(.*)/>','',new_disc)])

rawDescription: Python regex to find and regex to remove from list


code:
from datetime import date,timedelta

myday = mifirstday+timedelta(weeks=1)
myday = mifirstday+timedelta(days=4)

rawDescription: User input number of days and generate the start date and end date using python


code:
def foo(bar_q):
    while True:
        data = get_some_data()
        # copy or deepcopy if foo will be updating data instead of fetching new
        bar_q.put(copy.copy(data))
        time.sleep(120)

def bar(bar_q):
    # wait for the first data
    data = bar_q.get()
    bar_q.task_done()
    while True:
        process_some_data(data)
        try:
            # get new data if available
            data = bar_q.get_nowait()
            bar_q.task_done()
        except Queue.Empty:
            pass

rawDescription: Multithreading Python: Thread Communication


code:
import argparse

class VAction(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print 'values: {v!r}'.format(v=values)
        if values==None:
            values='1'
        try:
            values=int(values)
        except ValueError:
            values=values.count('v')+1
        setattr(args, self.dest, values)

parser=argparse.ArgumentParser()
parser.add_argument('-v', nargs='?', action=VAction, dest='verbose')
args=parser.parse_args(['-v'])
print(args)
# Namespace(verbose=1)

args=parser.parse_args(['-v -v'])
print(args)
# Namespace(verbose=2)

args=parser.parse_args(['-v -v -v'])
print(args)
# Namespace(verbose=3)

args=parser.parse_args(['-vv'])
print(args)
# Namespace(verbose=2)

args=parser.parse_args(['-vvv'])
print(args)
# Namespace(verbose=3)

args=parser.parse_args(['-v 2'])
print(args)
# Namespace(verbose=2)

rawDescription: Verbose level with argparse and multiple -v options


code:
import tornado.queues
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop

NUM_WORKERS = 10
QUEUE_SIZE = 100
q = tornado.queues.Queue(QUEUE_SIZE)
AsyncHTTPClient.configure(None, max_clients=NUM_WORKERS)
http_client = AsyncHTTPClient()

@gen.coroutine
def worker():
    while True:
        url = yield q.get()
        try:
            response = yield http_client.fetch(url)
            print('got response from', url)
        except Exception:
            print('failed to fetch', url)
        finally:
            q.task_done()

@gen.coroutine
def main():
    for i in range(NUM_WORKERS):
        IOLoop.current().spawn_callback(worker)
    with open("urls.txt") as f:
        for line in f:
            url = line.strip()
            # When the queue fills up, stop here to wait instead
            # of reading more from the file.
            yield q.put(url)
    yield q.join()

if __name__ == '__main__':
    IOLoop.current().run_sync(main)

rawDescription: tornado: AsyncHttpClient.fetch from an iterator?

description: Tornado: AsyncHttpClient.fetch from an iterator


code:
def all_passing(nums, grade = 70):
    new = []
    for l in nums:
        boo = True
        for x in l:
            if x <= grade:
                boo = False
        new.append(boo)
    return new

rawDescription: Sorting through list of lists?

description: Sorting through list of lists


code:
def text_compare(text1, text2, isjunk=None):
    return difflib.SequenceMatcher(isjunk, text1, text2).ratio()

rawDescription: Text difference algorithm

description: Text difference algorithm


code:
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
s = df.xs(3)
s.name = 10
df.append(s)

rawDescription: Pandas: Appending a row to a dataframe and specify its index label


code:
#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
     browser.get(url)
     button = browser.find_element_by_name('button')
     button.click()
     # wait for the page to load
     WebDriverWait(browser, timeout=10).until(
         lambda x: x.find_element_by_id('someId_that_must_be_on_new_page'))
     # store it to string variable
     page_source = browser.page_source
print(page_source)

rawDescription: Get page generated with Javascript in Python


code:
#!/usr/bin/env python
#vim: encoding=utf-8

import time
import unittest
from threading import Thread

from celery import Celery, states
from celery.bin.celeryd import WorkerCommand

class CELERY_CONFIG(object):
    BROKER_URL = "memory://"
    CELERY_CACHE_BACKEND = "memory"
    CELERY_RESULT_BACKEND = "cache"
    CELERYD_POOL = "solo"

class CeleryTestCase(unittest.TestCase):
    def test_inprocess(self):
        app = Celery(__name__)
        app.config_from_object(CELERY_CONFIG)

        @app.task
        def dumpy_task(dct):
            return 321

        worker = WorkerCommand(app)
        #worker.execute_from_commandline(["-P solo"])
        t = Thread(target=worker.execute_from_commandline, args=(["-c 1"],))
        t.daemon = True
        t.start()
        ar = dumpy_task.apply_async(({"a": 123},))
        while ar.status != states.SUCCESS:
            time.sleep(.01)
        self.assertEqual(states.SUCCESS, ar.status)
        self.assertEqual(ar.result, 321)
        t.join(0)

rawDescription: Python Celery could start with a threading inprocess ?


code:
class MyClass:
  """Some neat description

  :undocumented: x
  """

  def _y(self): pass
  def x(self): pass
  def z(self): pass

rawDescription: epydoc hide some class functions?

description: Epydoc hide some class functions


code: struct.unpack('>f', '>s\xb6F')[0]

rawDescription: How to decode / encode decimal values in python?

description: Decode / encode decimal values in python


code:
df['ix'] = df.groupby('person')['success'].apply(
    lambda x: pd.Series(0).append(x.cumsum().head(-1))
).tolist()

df['wait'] = df.groupby(['person','ix']).apply(lambda x: pd.Series(range(len(x)))).tolist()

#In [97]: df
#Out[97]:
#  person  success  wait  ix
#0    bob        0     0   0
#1    bob        1     1   0
#2    bob        0     0   1
#3    bob        0     1   1
#4    bob        1     2   1
#5    bob        0     0   2
#6   mary        1     0   0
#7   mary        0     0   1
#8   mary        0     1   1
#9   mary        0     2   1

rawDescription: Pandas DataFrame - Count rows between values efficiently


rawDescription: list.__str__ reversed

description: List.__str__ reversed


code:
d={"A":{"B":{"C":"FOO"}}}
[(k1,k2,k3,v3) for k1,v1 in  d.items() for k2,v2 in v.items() for k3,v3 in v1.items()]

rawDescription: Functional solution for looping through nested dictionaries


code: ax.set_yticklabels([u'é', u'ã', u'â'])

rawDescription: Accented characters in Matplotlib

description: Accented characters in Matplotlib


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri

X = np.load('./mydatars.npy')
# My data points are strictly positive. This doesn't work if I don't center about the origin.
X -= X.mean(axis=0)

rad = np.linalg.norm(X, axis=1)
zen = np.arccos(X[:,-1] / rad)
azi = np.arctan2(X[:,1], X[:,0])

tris = mtri.Triangulation(zen, azi)

fig = plt.figure()
ax  = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(X[:,0], X[:,1], X[:,2], triangles=tris.triangles, cmap=plt.cm.bone)
plt.show()

rawDescription: Delaunay Triangulation of points from 2D surface in 3D with python?


code:
from google.appengine.api import users
from google.appengine.ext import ndb  # Note, I'm using ndb rather than db

class Name(ndb.Model):
    username = ndb.StringProperty()

class MainHandler(BaseHandler):
    def get(self):
        self.render('input.html')
    def post(self):
        user = users.get_current_user()
        username = self.request.get('username')
        a = Name(id=user.id(), username=username)
        a.put()

        self.redirect('/welcome')

class WelcomeHandler(BaseHandler):
    def get(self):
        user = users.get_current_user()
        key = ndb.key(user.id())
        name_entity = key.get()
        self.render('welcome.html', username=name_entity.username)

rawDescription: Python | Appengine: What is the bug in my code that is preventing me from getting output as "Welcome, (username of the person)"?


code:
import dis
foo = lambda :[]
bar = lambda :list()
dis.dis(foo)
dis.dis(bar)

rawDescription: Why are list(), dict(), and tuple() slower than [], {}, and ()?


code:
payload = json.dumps({"host": "tst123:3306"})
headers = {'content-type': 'application/json'}
r = requests.put(url, data=payload, headers=headers)

rawDescription: Unwanted string formatting

description: Unwanted string formatting


code:
import tkFont
small_font = tkFont.Font(size=5) # Specify font size, and use default style for other parameters

self.lb = Listbox(f,selectmode=MULTIPLE, bd=1, height=10, font=small_font)

rawDescription: TKinter ListBox item height

description: TKinter ListBox item height


code:
import numpy as np
df.B[(df.B < 10) | (df.B > 70)] = np.nan
df.C[df.C != 200] = np.nan

rawDescription: Pandas selection keeping the same shape as original DataFrame


code:
# Python 3.
return any("\u0590" <= c <= "\u05EA" for c in s)
# Python 2.
return any(u"\u0590" <= c <= u"\u05EA" for c in s)

rawDescription: The right way to check of a string has hebrew chars


code:
def remove_missing_rows(app_list):
    print("########### Missing row removal ###########")
    filterfunc = lambda row: not all([row[1], row[4], row[5]])
    missing_rows = set(filter(filterfunc, app_list))

    print("Number of missing entries: " + str(len(missing_rows)))  # 967 with current method

    # Remove the missing_rows from the original data
    # note: should be a lot faster with a set
    app_list = [row for row in app_list if row not in missing_rows]
    return app_list

rawDescription: Iterate through a for loop using multiple cores in Python


code:
pnl = pd.Panel(np.random.randn(33, 55, 77))  # mental: (first@33, second@77, third@55)
pnl.shape
pnl[0].shape  # mental: pnl[first=0]
pnl[0][0].shape  # mental: pnl[first=0][second=0]
pnl.shape
pnl.ix[:, 0, 0].shape  # mental: pnl.ix[:, third=0, second=0]
pnl.ix[0, :, 0].shape  # mental: pnl.ix[first=0, :, second=0]
pnl.ix[0, 0, :].shape  # mental: pnl.ix[first=0, third=0, :]
pnl.ix[:, :, 0].shape  # mental: pnl.ix[:, :, second=0]
pnl.ix[:, 0, :].shape  # mental: pnl.ix[:, third=0, :]
pnl.ix[0, :, :].shape  # mental: pnl.ix[first=0, :, :]

rawDescription: Why does Pandas Panel have messed up axes order?


code: item != 'None'

rawDescription: Python Test for Full List

description: Python Test for Full List


code: sorted(your_list, key=lambda x: (your_dict[x]['downloads'], your_dict[x]['date']))

rawDescription: Sort nested dictionary by value, and remainder by another value, in Python


code:
def smart_truncate(content, length=100, suffix='...'):
    if len(content) <= length:
        return content
    else:
        return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix

rawDescription: Truncate a string without ending in the middle of a word


code:
class TestMock(unittest.TestCase):

    original = MyObject

    def setUp(self):
        global MyObject
        MyObject = MockMyObject

    def tearDown(self):
        global MyObject
        MyObject = TestMock.original

    def testFunction(self):
        MyObject().do_mocked_function()

rawDescription: Reloading the current module when unittesting


code:
from multiprocessing import Pool
# Use the following if you prefer to use threads over processes.
# from multiprocessing.pool import ThreadPool as Pool

urls = ['https://someurl', 'https://someurl', ...]

def download_json(url):
    req2 = urllib2.Request(url)
    req2.add_header('cookie', cookie)
    response = urllib2.urlopen(req2)
    data = response.read()
    return json.loads(data)

pool = Pool()
vals = pool.map(download_json, urls)

rawDescription: Replacement for urllib2

description: Replacement for urllib2


code:
#!/usr/bin/env python

import os
from win32com.client import Dispatch

fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()

cwd = os.getcwd()

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()

os.chdir(cwd)

fh = open('foo.txt', 'a')
fh.write('world')
fh.close()

rawDescription: MS Outlook CDO/MAPI Blocking Python File Output?


rawDescription: Is there a list of default template variables in django?


code:
# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 1000, 800
screen=pygame.display.set_mode((width, height))

# 3 - Load images
background = pygame.image.load("start.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(background, (0,0))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                background = pygame.image.load("stage2.png")
        # check if the event is the X button
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit()
            exit(0)

rawDescription: How do I make it so it goes to a new scene on keypress? (Pygame)

description: Make it so it goes to a new scene on keypress? (Pygame)


code:
def brute_force_clean_nans(x, y):
    x_clean, y_clean = [], []
    cnt = 0
    for _x, _y in zip(x, y):
        if np.isnan(_y):
            cnt += 1
            if cnt == 5:
                 # on the 5th nan, put it in the list to break line
                 x_clean.append(_x)
                 y_clean.append(_y)
            continue
        cnt = 0
        x_clean.append(_x)
        y_clean.append(_y)
    return x_clean, y_clean

rawDescription: Join NaN values in matplotlib

description: Join NaN values in matplotlib


rawDescription: Is There a Way to Return a String Concatenation in Python?


code:
for evoNode in node.getElementsByTagName('evolution'):
  evoName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
  evoId      = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
  evoLevel   = getText(evoNode.getElementsByTagName("level")[0].childNodes)
  evoCost      = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes)

  temporaryEvo = Evolutions(evoName, evoId, evoLevel, evoCost)
  evolutionList.append(temporaryEvo)

  # Or you can go with the 1 liner
  evolutionList.append(Evolutions(evoName, evoId, evoLevel, evoCost))

rawDescription: Python classes from a for loop

description: Python classes from a for loop


code:
from matplotlib.pyplot import figure, show
from scipy.stats import gaussian_kde
from numpy.random import normal
from numpy import arange

def violin_plot(ax, data, pos, bp=False):
    '''
    create violin plots on an axis
    '''
    dist = max(pos)-min(pos)
    w = min(0.15*max(dist,1.0),0.5)
    for d,p in zip(data,pos):
        k = gaussian_kde(d) #calculates the kernel density
        m = k.dataset.min() #lower bound of violin
        M = k.dataset.max() #upper bound of violin
        x = arange(m,M,(M-m)/100.) # support for violin
        v = k.evaluate(x) #violin profile (density curve)
        v = v/v.max()*w #scaling the violin to the available space
        ax.fill_betweenx(x,p,v+p,facecolor='y',alpha=0.3)
        ax.fill_betweenx(x,p,-v+p,facecolor='y',alpha=0.3)
    if bp:
        ax.boxplot(data,notch=1,positions=pos,vert=1)

if __name__=="__main__":
    pos = range(5)
    data = [normal(size=100) for i in pos]
    fig=figure()
    ax = fig.add_subplot(111)
    violin_plot(ax,data,pos,bp=1)

    data_x = [0, 1, 2, 2, 3, 4]
    data_y = [1.5, 1., 0.7, 2.5, 1, 1.5]
    ax.plot(data_x, data_y, 'or')
    fig.savefig("violins.gif")

rawDescription: Plotting single points on a graph

description: Plotting single points on a graph


rawDescription: For tuple in list, if 3rd element of tuple is in dicionary, replace the element with the value


rawDescription: How to find the real user home directory using python?

description: Find the real user home directory using python


code:
import os

# ./foo -> ./bar
filepath = "./foo"

if (os.path.realpath(filepath) != filepath):
    targetpath = os.path.realpath(filepath)

os.remove(filepath)
if (targetpath):
     os.remove(targetpath)

rawDescription: How to delete the symlink along with the source directory

description: Delete the symlink along with the source directory


code:
s = input("My input ") # for 2.x it will be raw_input
s = int(s) if len(s) <= 3 else int(s[0:3])

rawDescription: How to make an input be only numbers and not allow a more than a certain amount of characters?

description: Make an input be only numbers and not allow a more than a certain amount of characters


code:
if n > 0:
    return srs_print(S, n-1, rules)
else:
    return S

rawDescription: Why won't my Python function be recursive/call itself?


code:
from Crypto.Cipher import AES
import binascii
key = binascii.unhexlify('1F61ECB5ED5D6BAF8D7A7068B28DCC8E')
IV = 16 * '\x00'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode, IV=IV)
text = binascii.unhexlify('020ABC00ABCDEFf8d500000123456789')
ciphertext = encryptor.encrypt(text)
print(binascii.hexlify(ciphertext))

rawDescription: AES 128 in Python

description: AES 128 in Python


code:
df = pd.DataFrame([[np.nan, 2, 5], [2, 5, np.nan], [2, 5, np.nan]])
df # example frame
df[df.notnull()] = 1
df

rawDescription: Pandas opposite of fillna(0)

description: Pandas opposite of fillna(0)


code:
cmd = ['tool', '--server=commander.company.com', 'runProcedure', 'Android_Main',
   '--procedureName', 'priority_kw', '--actualParameter',
   'changes=' + var, 'gerrit_server=review-android.company.com']

rawDescription: how to set var including quotes in a command variable

description: Set var including quotes in a command variable


code:
l = [i.split(": ") for i in open("def.txt")] #read and parse the input
l #here is what we got
with open("out.txt", "w") as f: #open the out file
   f.write("<tbl>\n")
   for k, v in l: #iterate and write
        f.write("
{}	{}
\n".format(k, v))
   f.write("</tbl>\n")

rawDescription: parse variables file in Python

description: Parse variables file in Python


code:
bytearray.__base__
bytes.__base__

rawDescription: Superclass of bytes and bytearray?

description: Superclass of bytes and bytearray


code:
odd=[]
even=[]
[even.append(i) if i%2==0 else odd.append(i) for i in xrange(1,21)]

rawDescription: How can I add the values of If and Else in two different lists, using list comprehension?

description: Add the values of If and Else in two different lists, using list comprehension


code:
q = db.query('select * from fruits')
q.getresult()

rawDescription: how to itirate over Postgresql rows in python script?

description: Itirate over Postgresql rows in python script


code:
from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget):
    def __init__(self):
        super().__init__()

        layout = QtGui.QVBoxLayout()
        self.setLayout(layout)

        lblhm = QtGui.QLabel("Hauptmessung", self)
        layout.addWidget(lblhm)

        self.__hm_b = self.__add_button("Messung öffnen", layout)
        self.__hm_config_b = self.__add_button("Configruation öffnen", layout)

        lblzm = QtGui.QLabel("Zusatzmessung", self)
        layout.addWidget(lblzm)

        self.__zm_b = self.__add_button("Messung öffnen", layout)
        self.__zm_config_b = self.__add_button("Configuration öffnen", layout)

    def button_pressed(self):
        print('Button pressed')

    def __add_button(self, text: str, layout: QtGui.QLayout):
        btn = QtGui.QPushButton(text, self)
        layout.addWidget(btn)
        btn.clicked.connect(self.button_pressed)
        return btn

if __name__== '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    wnd = MyWindow()
    wnd.show()
    sys.exit(app.exec_())

rawDescription: How to react to a button click in pyqt5

description: React to a button click in pyqt5


code:
from PySide import QtGui, QtCore
import pylab as plt
import numpy as np

N_SAMPLES = 1e6

def test_plot():
    time = np.arange(N_SAMPLES)*1e-3
    sample = np.random.randn(N_SAMPLES)
    plt.plot(time, sample, label="Gaussian noise")
    plt.legend(fancybox=True)
    plt.title("Use the slider to scroll and the spin-box to set the width")
    q = ScrollingToolQT(plt.gcf())
    return q   # WARNING: it's important to return this object otherwise
               # python will delete the reference and the GUI will not respond!

class ScrollingToolQT(object):
    def __init__(self, fig):
        # Setup data range variables for scrolling
        self.fig = fig
        self.xmin, self.xmax = fig.axes[0].get_xlim()
        self.step = 1 # axis units

        self.scale = 1e3 # conversion betweeen scrolling units and axis units

        # Retrive the QMainWindow used by current figure and add a toolbar
        # to host the new widgets
        QMainWin = fig.canvas.parent()
        toolbar = QtGui.QToolBar(QMainWin)
        QMainWin.addToolBar(QtCore.Qt.BottomToolBarArea, toolbar)

        # Create the slider and spinbox for x-axis scrolling in toolbar
        self.set_slider(toolbar)
        self.set_spinbox(toolbar)

        # Set the initial xlimits coherently with values in slider and spinbox
        self.set_xlim = self.fig.axes[0].set_xlim
        self.draw_idle = self.fig.canvas.draw_idle
        self.ax = self.fig.axes[0]
        self.set_xlim(0, self.step)
        self.fig.canvas.draw()

    def set_slider(self, parent):
        # Slider only support integer ranges so use ms as base unit
        smin, smax = self.xmin*self.scale, self.xmax*self.scale

        self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, parent=parent)
        self.slider.setTickPosition(QtGui.QSlider.TicksAbove)
        self.slider.setTickInterval((smax-smin)/10.)
        self.slider.setMinimum(smin)
        self.slider.setMaximum(smax-self.step*self.scale)
        self.slider.setSingleStep(self.step*self.scale/5.)
        self.slider.setPageStep(self.step*self.scale)
        self.slider.setValue(0)  # set the initial position
        self.slider.valueChanged.connect(self.xpos_changed)
        parent.addWidget(self.slider)

    def set_spinbox(self, parent):
        self.spinb = QtGui.QDoubleSpinBox(parent=parent)
        self.spinb.setDecimals(3)
        self.spinb.setRange(0.001, 3600.)
        self.spinb.setSuffix(" s")
        self.spinb.setValue(self.step)   # set the initial width
        self.spinb.valueChanged.connect(self.xwidth_changed)
        parent.addWidget(self.spinb)

    def xpos_changed(self, pos):
        #pprint("Position (in scroll units) %f\n" %pos)
        #        self.pos = pos/self.scale
        pos /= self.scale
        self.set_xlim(pos, pos + self.step)
        self.draw_idle()

    def xwidth_changed(self, xwidth):
        #pprint("Width (axis units) %f\n" % step)
        if xwidth <= 0: return
        self.step = xwidth
        self.slider.setSingleStep(self.step*self.scale/5.)
        self.slider.setPageStep(self.step*self.scale)
        old_xlim = self.ax.get_xlim()
        self.xpos_changed(old_xlim[0] * self.scale)
#        self.set_xlim(self.pos,self.pos+self.step)
 #       self.fig.canvas.draw()

if __name__ == "__main__":
    q = test_plot()
    plt.show()

rawDescription: Python/Matplotlib/Pyside Fast Timetrace scrolling


code:
def run_progress_bar(finished_event):
    chars = itertools.cycle(r'-\|/')
    while not finished_event.is_set():
        sys.stdout.write('\rWorking ' + next(chars))
        sys.stdout.flush()
        finished_event.wait(0.2)

# somewhere else...
finished_event = threading.Event()
progress_bar_thread = threading.Thread(target=run_progress_bar, args=(finished_event,))
progress_bar_thread.start()
# do stuff
finished_event.set()
progress_bar_thread.join()

rawDescription: Python: Run a progess bar and work simultaneously?


code: from .SomeClass import SomeClass

rawDescription: Make a package work as just one import

description: Make a package work as just one import


rawDescription: Getting indices of a specific value in numpy array


code:
import Tkinter, os

class SimpleApp():
    def __init__(self,parent):
        self.parent = parent
        self.parent.geometry('500x300+200+50')
        self.parent.title('Main Window')
        self.home_dir=os.getcwd()

        ## pass same Tkinter instance to the class
        SetHomeDir(parent=self.parent, home=self.home_dir)

class SetHomeDir():
    def __init__(self,parent, home):
        self.parent = parent
        self.top=Tkinter.Toplevel(self.parent)
        self.top.geometry('500x100+200+500')
        self.top.title('Set Home Directory')

        #Input Box
        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self.top, textvariable=self.entryVariable)
        self.entryVariable.set(home)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.focus_set()

        self.top.grid_columnconfigure(0,weight=1)
        self.top.resizable(True,False)

if __name__ == "__main__":
    root=Tkinter.Tk()
    app = SimpleApp(root)
    root.mainloop()

rawDescription: Unable to to show value in Entry widget in Tkinter GUI


code:
from mayavi import mlab
import numpy as np

s=64
x,y,z = np.ogrid[0:s,0:s,0:s/2]

data = np.sqrt((x-s/2)**2 + (y-s/2)**2 + (2*z-s/2)**2)

grid = mlab.pipeline.scalar_field(data)
grid.spacing = [1.0, 1.0, 2.0]

contours = mlab.pipeline.contour_surface(grid,
                         contours=[5,15,25], transparent=True)
mlab.show()

rawDescription: How to display a volume with non-cubic voxels correctly in mayavi

description: Display a volume with non-cubic voxels correctly in mayavi


code:
import json
from odftoarray import ODSReader  # renamed the file to odftoarray.py

r = ODSReader("your_file.ods")
arrays = r.getSheet("your_data_sheet_name")
json.dumps(arrays)

rawDescription: ODS file to JSON

description: ODS file to JSON


code:
sentence = "Hi my name is Bob"
words = sentence.split()
average = sum(len(word) for word in words)/len(words)
average

rawDescription: Python: How can I calculate the average word length in a sentence using the .split command?


code:
from sys import maxint
type(-maxint)
type(-maxint-1)
type(-maxint-2)

rawDescription: most negative value for python

description: Most negative value for python


code:
for line in lst:
    ...
    d = collections.Counter(nline)
    m = d.most_common(1)
    print( "None" if m is None else m[0] )

rawDescription: Speed up the code

description: Speed up the code


code:
def save(self, *args, **kwargs):
    if self.published and self.pub_date is None:
        self.pub_date = timezone.now()
    elif not self.published and self.pub_date is not None:
        self.pub_date = None
    super(Model, self).save(*args, **kwargs)

rawDescription: django - update date automatically after a value change

description: Django - update date automatically after a value change


rawDescription: How to check for a string format in python?

description: Check for a string format in python


code:
import os
system_name = os.popen('/bin/hostname')

if system_name.read().rstrip() == 'localhost.localdom':
    logging.info('Please correct host name for proxies, it is showing localhost')
    sys.exit()

rawDescription: unable to get os.getenv('HOSTNAME') work during the startup

description: Unable to get os.getenv('HOSTNAME') work during the startup


code:
def __iter__(self):
    node = self.head
    while node is not None:
        yield node
        node = node.next

rawDescription: How can I make MyList iterable?

description: Make MyList iterable


code:
# -*- coding: utf-8 -*-
import sys
from time import time, sleep
from PyQt4.QtGui import QApplication, QSplashScreen, QPixmap

from gui.gui import MainWindow

def main():
    app = QApplication(sys.argv)
    start = time()
    splash = QSplashScreen(QPixmap("aquaticon/images/splash_screen.jpg"))
    splash.show()
    while time() - start < 1:
        sleep(0.001)
        app.processEvents()
    win = MainWindow()
    splash.finish(win)
    win.show()
    app.exec_()

if __name__ == "__main__":
    main()

rawDescription: Why QSplashscreen does not always work?

description: Why QSplashscreen does not always work


code:
"""
Show how to modify the coordinate formatter to report the image "z"
value of the nearest pixel given x and y
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

X = 10*np.random.rand(5,3)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(X, cmap=cm.jet, interpolation='nearest')

numrows, numcols = X.shape
def format_coord(x, y):
    col = int(x+0.5)
    row = int(y+0.5)
    if col>=0 and col<numcols and row>=0 and row<numrows:
        z = X[row,col]
        return 'x=%1.4f, y=%1.4f, z=%1.4f'%(x, y, z)
    else:
        return 'x=%1.4f, y=%1.4f'%(x, y)

ax.format_coord = format_coord
plt.show()

rawDescription: Can python make a tile plot?

description: Can python make a tile plot


code:
numbers = np.arange(100,dtype=int)
longs = 1 << np.arange(100).astype(object)

rawDescription: Left shift inconsistancy

description: Left shift inconsistancy


code:
import functools

labels[i].mousePressEvent = functools.partial(self.print_some, source_object=labels[i])

def print_some(self, event, source_object=None):
    print("Clicked, from", source_object)

rawDescription: Getting Information Which QLabel Clicked in PyQT


code:
import re
{k : re.sub('wrong', 'right', v) for k,v in mydict.items()}

rawDescription: Python: parsing a value(string) in a dictionary and replace it


code: some_value = getattr(MyModel.objects.filter(...).first(), 'some_value', None)

rawDescription: get attribute from object if object exists

description: Get attribute from object if object exists


code:
s = "My page with..."
s += "More data"
for y in x:
    s += "And this!"
return s

rawDescription: Dynamic printing in web.py

description: Dynamic printing in web.py


code:
ind = ~(isnan(x1)|isnan(x2));
x1 = x1(ind);
x2 = x2(ind);

rawDescription: Can someone teach me how to show that these two time series correlate?


code:
def bar():
  """My function.

  That does foo.
  """
  pass

bar.__doc__

def bar():
  "My function.\n"
  "\n"
  "That does foo.\n"
  pass

bar.__doc__

rawDescription: Can a docstring consist of multiple string literals?


code:
class reify(object):
    """ Use as a class method decorator.  It operates almost exactly like the
    Python ``@property`` decorator, but it puts the result of the method it
    decorates into the instance dict after the first call, effectively
    replacing the function it decorates with an instance variable.  It is, in
    Python parlance, a non-data descriptor.  An example:

    .. code-block:: python

       class Foo(object):
           @reify
           def jammy(self):
               print('jammy called')
               return 1

    And usage of Foo:

    >>> f = Foo()
    >>> v = f.jammy
    'jammy called'
    >>> print(v)
    1
    >>> f.jammy
    1
    >>> # jammy func not called the second time; it replaced itself with 1
    """
    def __init__(self, wrapped):
        self.wrapped = wrapped
        try:
            self.__doc__ = wrapped.__doc__
        except: # pragma: no cover
            pass

    def __get__(self, inst, objtype=None):
        if inst is None:
            return self
        val = self.wrapped(inst)
        setattr(inst, self.wrapped.__name__, val)
        return val

rawDescription: Python caching in objects

description: Python caching in objects


code:
for i in range(1, 4):
    type_dict['type_%d' % i] = myTree.cssselect('element_type_%d' % i)

rawDescription: More pythonic way to pick multiple element types from tagged data


code:
def getData(ts):
    dataID2 = data[ts.name]
    i = np.searchsorted(dataID2.values, ts.values, side='left')
    return dataID2.index[i]

dataFrame['ID2'] = dataFrame.groupby('ID1')['RAND'].transform(getData)

rawDescription: Optimizing Python code - overhead due to pandas.core.series.Series.__getitem__


code:
def read_directory():
    matches =[]
    directory = '/home/akallararajappan/www.mangalam.com/agriculture'
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.html'):
                matches.append(os.path.join(root, file))
    return matches

rawDescription: List all HTML files in a directory python code not working


rawDescription: Accessing a matrix element by matrix[(a, b), c] instead of matrix[a, b, c]


code: db.execute("SELECT count(*) from table where field = %s", [val])

rawDescription: Python Dynamic Query on Strings

description: Python Dynamic Query on Strings


code:
import shlex
argument_string = "-a arga -b \"argument b\" arg1 arg2"
l = shlex.split(argument_string)
l

rawDescription: Python Optparse from Argument String

description: Python Optparse from Argument String


rawDescription: Help with a regular expression - Python

description: Help with a regular expression - Python


code:
from Tkinter import *
from tkFileDialog import askopenfilename

def openfile():
    filename = askopenfilename(parent=root)
    f = open(filename)
    x = f.read()
    text.insert(INSERT,(x,))

root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

text = Text(root)
text.pack()

root.config(menu=menubar)
root.mainloop()

rawDescription: Using a variable from a function outside the function


rawDescription: xml.dom.minidom count how many tags of a specific type exist

description: Xml.dom.minidom count how many tags of a specific type exist


code:
myList = ['02', '03', '04', '05', '06', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive']
removedList = [x for x in myList if x!='Inactive'] # original list unchanged
# or
removedList = filter(lambda x: x!='Inactive', myList) #leaves original list intact

rawDescription: Why does remove() not remove the value specified?


code:
from sqlalchemy import inspect

u = User(name='Alice')
inspection = inspect(u)
inspection.pending  # False

db.session.add(u)
inspection.pending # True

db.session.commit()
inspection.pending # False

rawDescription: Flask sqlalchemy check whether object in db.session and ready for commit


code:
import zmq
import zmq.ssh
context = zmq.Context()
socket = context.socket(zmq.REQ)
zmq.ssh.tunnel_connection(socket, "tcp://locahost:5555", "myuser@remote-server-ip")
socket.send(b"Hello")
reply = socket.recv()

rawDescription: Remote tcp connection in python with zeromq


code:
from __future__ import print_function
map(print, [1, 2, 3])
# 1
# 2
# 3

rawDescription: Use print inside lambda

description: Use print inside lambda


code:
from PyQt4 import QtGui
import sys
class MultiButton(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self._b1 = QtGui.QPushButton("B1")
        self._b2 = QtGui.QPushButton("B2")
        self._arrangeWidgets()
        self.setStyleSheet("background-color: rgb(0, 0, 0);\n"+\
                           "color: rgb(255, 255, 255);\n"+\
                           "border:1px solid #7F462C ;\n")
        self._moveStart = False
        self._startX = 0
        self._startY = 0

    def _arrangeWidgets(self):
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._b1)
        #horizontal spacing remains constant now
        layout.addSpacing(90)
        layout.addWidget(self._b2)
        self.setLayout(layout)

    def mousePressEvent(self,event):
        self._moveStart = True
        self._startX = event.pos().x() - self.pos().x()
        self._startY = event.pos().y() - self.pos().y()
        return QtGui.QWidget.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        if self._moveStart:
            self.setGeometry(event.pos().x() - self._startX,event.pos().y() - self._startY,self.width(),self.height())
            self._moveStart = False
            self._startX = 0
            self._startY = 0

        return QtGui.QWidget.mouseReleaseEvent(self, event)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    wd = QtGui.QMainWindow()
    wd.resize(500,500)
    mb = MultiButton()
    mb.setFixedSize(200,50)
    wd.setCentralWidget(mb)
    wd.show()
    sys.exit(app.exec_())

rawDescription: Have 2 pyqt buttons move synchronized when mouse moves


code:
badInput = True
while badInput:
    filesize = input("Podaj rozmiar pliku i jednostke (np. \"100 mb\", \"130 gb\", \"84 kb\"): ")
    if filesize[-3:] ==  ' mb' or filesize[-3:] == ' kb' or filesize[-3:] == ' gb':
        badInput = False
        print("true")
    else:
        print("Podaj jeszcze raz rozmiar pliku w formacie [liczba format] np. 12 kb")

rawDescription: Python - getting back to the line with input


code:
new_list = []
for element in list:
   name = re.findall('my name is (.*?) and i\'m', element, re.DOTALL)[0]
   age = re.findall('and i\'m (.*?) years old', element, re.DOTALL)[0]
   new_list.append([name, age])

rawDescription: Python - Create list with multiple sub-lists


code:
def extract_channel_views(joined_dataset):
    channel_views = joined_dataset[1]
    channel = channel_views[0]
    views = channel_views[1]
    return (channel,views)

rawDescription: Apache Spark - How to split a joined dataset


code:
entryid = 1

try:
    match = next(s for s in inputlist if s['id'] == entryid)
except StopIteration:
    match = None  # not found

rawDescription: Finding an element in list

description: Finding an element in list


code:
# Import
import Tkinter
import ttk

# Class
class App:

    # Init
    def __init__(self):
        self.options = ["All", "Odd", "Even"] # Combobox elements
        self.values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Treeview elements

        self.last_filter_mode = "" # Combobox change detector

        self.create()

    # Build GUI
    def create(self):
        self.root = Tkinter.Tk() # Can be substituted for Toplevel
        self.root.title("Filtered Listbox")

        self.frame = Tkinter.Frame(self.root)
        # I like to use pack because I like the aesthetic feel
        # pady is 5 so that the widgets in the frame are spaced evenly
        self.frame.pack(fill="both", padx=10, pady=5)

        self.filter_mode = Tkinter.StringVar(); # Combobox StringVar
        # Set it to the initial value of combobox
        # Also consider using self.options[0] for uniformity
        self.filter_mode.set("All")

        self.combobox = ttk.Combobox(
            self.frame, textvariable=self.filter_mode, state="readonly",
            values=self.options)
        self.combobox.pack(fill="x", pady=5)

        # So that the scroll bar can be packed nicely
        self.treeview_frame = Tkinter.Frame(self.frame)
        self.treeview_frame.pack(fill="x", pady=5)

        column_headings = ["A", "B", "C"] # These are just examples
        self.treeview = ttk.Treeview(
            self.treeview_frame, columns=column_headings, show="headings")
        self.treeview.pack(fill="y", side="left")

        self.treeview_scroll = ttk.Scrollbar(
            self.treeview_frame, orient="vertical", command=self.treeview.yview)
        self.treeview_scroll.pack(fill="y", side="right")
        self.treeview.config(yscrollcommand=self.treeview_scroll.set)

    # Recursize update function called with root.after
    def update(self):
        filter_mode = self.filter_mode.get()

        # Check for change in the filter_mode
        if filter_mode != self.last_filter_mode:

            items = self.treeview.get_children()
            for item in items:
                self.treeview.delete(item) # Clear the treeview

            # Combobox options
            if filter_mode == "All":
                for element in self.values:
                    self.treeview.insert("", "end", values=(element))

            if filter_mode == "Odd":
                for element in filter(
                    lambda x: True if x % 2 != 0 else False, self.values):
                    self.treeview.insert("", "end", values=(element))

            if filter_mode == "Even":
                for element in filter(
                lambda x: True if x % 2 == 0 else False, self.values):
                    self.treeview.insert("", "end", values=(element))

            self.last_filter_mode = filter_mode # Update current filter mode

        self.root.after(100, self.update) # Call this function again

    def main(self):
        self.update() # Start the recursive update function
        self.root.mainloop() # Start the app

a = App()
a.main()

rawDescription: Listbox filtering using a combo box

description: Listbox filtering using a combo box


code:
#!/usr/bin/env python3

from lxml import etree

lines = None
with open('ex.xml') as f:
    lines = f.read()

doc = etree.fromstring(lines)
elem = doc.xpath("//name[text()='John Smith']")

for e in elem:
    parent = e.getparent()
    print(parent.tag)

rawDescription: Use python to determine what element(s) a value is in


code:
from collections import defaultdict

l=lambda:defaultdict(l)
table=l()

table[0][1][2][3][4][5]=6

rawDescription: multi-level defaultdict with variable depth in python

description: Multi-level defaultdict with variable depth in python


code:
from matplotlib.mlab import PCA
data = array(randint(10,size=(10,3)))
results = PCA(data)

rawDescription: Principal Component Analysis (PCA) in Python


code:
def love6(a,b):
    return a==6 or b==6 or a+b==6 or abs(a-b)==6

rawDescription: "if else" in python

description: "if else" in python


code:
while True:
    if TRACK_IS_PLAYING:
        for i in range(0,8):
            MIDI_OUT.send_message(clock)

        time.sleep(interval)

rawDescription: 2 endless looping threads in Python

description: 2 endless looping threads in Python


code:
import re
who, what = re.match(r'(.*) likes (.*)', 'tim likes kung pao').groups()
who
what

rawDescription: Python inverse template, get vars from a string


code: [url for url in urlstring.split(',') if 2 <= len(url.split('.')[-2]) <= 4]

rawDescription: splitting a string->list to be checked

description: Splitting a string->list to be checked


code:
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        your_input_string += event.unicode

rawDescription: I'm trying to use pygame and need and interface


code:
import win32api

HUMAN_KEYPRESS_TIME = 0.3

def press_key(vk_code):
    state = int(win32api.GetKeyState(vk_code))
    if state == -127 or state == -128:
        return 1
    else:
        return 0

keyDown = False
if __name__ == "__main__":
    firstPress = True
    while True:
        p_key = 80
        if press_key(p_key):
            if firstPress:
                firstPress = False
                print("P key was pressed.")
        else:
            firstPress = True

rawDescription: How do I "execute" only one key press inside a while loop? (PyWin32)


code: value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

rawDescription: How to get the difference between two dictionaries in Python?

description: Get the difference between two dictionaries in Python


code:
with open("danish.train", 'r') as f:
    train_lines = f.readlines()

for file_number in range(1, 12):
    with open("danish.test.part-%02d" % file_number, 'r') as f:
        test_lines = set(f)
    with open("danish.train.part-%02d" % file_number, 'w') as g:
        g.writelines(line for line in train_lines if line not in test_lines)

rawDescription: File output based on the contents of another file


code:
def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)

a
rreplace(a, 'word', 'xxx', a.count('word') - 1)

rawDescription: How to replace all occurences except the first one?

description: Replace all occurences except the first one


code: re.findall(r"([a-fA-F\d]{32})", data)

rawDescription: Python regex for MD5 hash

description: Python regex for MD5 hash


code:
handles = self.driver.window_handles
self.driver.switch_to_window(handles[-1])

rawDescription: ChromeDriver/Selenium take a black screenshot when in a separate tab


code:
import re
seq = 'ACCGCTACGATCGATCGAAAAAAAAAAAAAAAAAACGATCGAC'
[(m.group(), m.start())
    for m in re.finditer(r'([ACGT])\1{9,}', seq)
        if len(m.group()) >= 10]

rawDescription: Python, find the length of the (n)n string by regex


code:
idx = pd.date_range("2013-01-01", periods=1000)
val = np.random.rand(1000)
s = pd.Series(val, idx)

g = s.groupby([s.index.year, s.index.month]).mean()

ax = g.plot()
ax.set_xticks(range(len(g)));
ax.set_xticklabels(["%s-%02d" % item for item in g.index.tolist()], rotation=90);

rawDescription: How to plot a pandas multiindex dataFrame with all xticks

description: Plot a pandas multiindex dataFrame with all xticks


code:
df
df
df

rawDescription: How to append a 1 to the end of each single digit element within an array, list, or dataframe in Python Pandas?

description: Append a 1 to the end of each single digit element within an array, list, or dataframe in Python Pandas


code: target.write("%s\n" % infile)

rawDescription: How to make user inputted data automatically appear on a new line?

description: Make user inputted data automatically appear on a new line


code:
question = "Is this a question?"

# Render the text:
font = pygame.font.SysFont("Arial", 20)
text_surface = font.render(question, true, (0,0,0))

# Blit the text to the screen
text_rect = text_surface.get_rect()
text_rect.center = (100,100)
screen.blit(text_surface, text_rect.topleft)

rawDescription: Mixing Graphics and Text into one window


code: x_a = x + i*y

rawDescription: Is there a major difference between the two scipy Hilbert transforms?


code: df_new.apply(lambda r: pd.Series(function_taking_row(r), index=colnames), axis=1)

rawDescription: Applying a python function that returns a list and writing to columns of dataframe


code:
for x in result:
    row = { d[0].lower(): col for (d, col) in zip(cursor.description, x) }
    name = row['name']
    age = row['age']

rawDescription: Python processing sql records

description: Python processing sql records


rawDescription: Postgres ILIKE Query with Flask/SQLAlchemy


code:
from scipy import stats
import numpy as np

dataset = np.array([[1.5,3.3,2.6,5.8],[1.5,3.2,5.6,1.8],[2.5,3.1,3.6,5.2]])
stats.mstats.zscore(dataset)

rawDescription: Can't use scipy stats function on nested list


code:
sorted(yourArray, key=lambda x: x[3])
#sort yourArray by the 4th value in every list

rawDescription: How do I sort records which are like `a | b | c | 8` and `n | 8 | p | 4` in Python?

description: Sort records which are like `a | b | c | 8` and `n | 8 | p | 4` in Python


code:
def followers(request, username):

    followers  = Followers.objects.filter(username=username)
    userdetail  = AuthUser.objects.filter(username=username)

    template = 'profil/em-profile-follower.html'
    context = RequestContext(request,{'followers': followers, 'userinfo': userdetail})
    return direct_to_template(template,context)

rawDescription: Django child-parent template relation

description: Django child-parent template relation


code:
from collections import defaultdict

def clean_line(line):
    name, _, value = line.partition(':')
    return name.strip(), value.strip()

def process_file(dic_, file, key):
    for line in file:
        name, value = clean_line(line)
        dic_[name][key] = value

def f_phone_addr(phonefile, addrfile):

    out = defaultdict(dict)
    with open(phonefile) as pf, open(addrfile) as af:
        process_file(out, pf, 'phone')
        process_file(out, af, 'address')
    return out

rawDescription: Combine two txt files into one dictionary with corrections


rawDescription: How to merge and sum duplicates in python?

description: Merge and sum duplicates in python


code:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'name': 'clitool',
    'author': 'aa',
    'author_email': 'ww',
    'version': '1.0-rc',
    'install_requires': ['nose'],
    'packages': [],
    'entry_points' : {
        'console_scripts': ['clitool=clitool.cli:main'],
    }
}

setup(**config)

rawDescription: How to install Python script on Windows?

description: Install Python script on Windows


code:
weights = [layers[j].weights for j in range(self.n_layers)]
losses = [tf.nn.l2_loss(w) for w in weights]
total_loss = tf.add_n(losses)

rawDescription: sum over a list of tensors in tensorflow

description: Sum over a list of tensors in tensorflow


code:
from myapp.models import Traffic, Email

class DashboardView(TemplateView):

    template_name = "dashboard/pages/dashboard.html"

    def get_context_data(self, **kwargs):
        context = super(DashboardView, self).get_context_data(**kwargs)
        context['email_list'] = Email.objects.all()
        context['traffic_list'] = Traffic.objects.all()
        return context

rawDescription: Creating Django Query Sets to Access Entire Database


code:
import hashlib
if self.hash_type in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']:
     func = getattr(hashlib, self.hash_type)

rawDescription: How can I replace `eval` in my function?

description: Replace `eval` in my function


code:
#!/usr/bin/env python
import subprocess
import xlwt
process=subprocess.Popen('Test_Project.exe',stdout=subprocess.PIPE)
out,err = process.communicate()
wb=xlwt.Workbook()
sheet=wb.add_sheet('python')
row = 0
for line in out.split('\n'):
    for i,wrd in enumerate(line.split()):
        sheet.write(row,i,wrd)
    row=row+1
wb.save('stdoutput.xls')

rawDescription: Writing console output(space seperated text) to seperate columns of excel sheet using Python


code:
import numpy as NP
A = NP.random.randint(0, 10, 100)

bins = NP.array([0., 20., 40., 60., 80., 100.])

# d is an index array holding the bin id for each point in A
d = NP.digitize(A, bins)

rawDescription: How to get data in a histogram bin

description: Get data in a histogram bin


code:
import wx
import numpy as np
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.figure import Figure
from matplotlib.widgets import Cursor
from matplotlib.backends.backend_wxagg import \
   FigureCanvasWxAgg as FigCanvas, \
   NavigationToolbar2WxAgg as NavigationToolbar

class wxPlotting(wx.Frame):
   title = 'Test'
   def __init__(self):
      wx.Frame.__init__(self, None, -1, self.title)
      self.time = np.arange(10000)
      self.data = np.random.random(10000)
      self.sb = self.CreateStatusBar()
      self.create_main_panel()
      self.axes.plot(self.time, self.data)
      self.background = self.canvas.copy_from_bbox(self.fig.bbox)
      self.canvas.draw()

   def create_main_panel(self):
      self.panel = wx.Panel(self)
      self.fig = Figure((5.0, 4.0), dpi=100)
      self.canvas = FigCanvas(self.panel, -1, self.fig)
      self.axes = self.fig.add_subplot(111)
      self.text = self.axes.text(0., 1.005, '', transform = self.axes.transAxes, animated=True)
      self.cursor = Cursor(self.axes, useblit=True, color='red')
      self.canvas.mpl_connect('motion_notify_event', self.cbUpdateCursor)
      self.vbox = wx.BoxSizer(wx.VERTICAL)
      self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.panel.SetSizer(self.vbox)
      self.vbox.Fit(self)

   def cbUpdateCursor(self, event):
      if event.inaxes:
         text = 'x = %5.4f, y = %5.4f' % (event.xdata, event.ydata)
         self.sb.SetStatusText(text)

         self.canvas.restore_region(self.background)
         self.text.set_text(text)
         self.axes.draw_artist(self.text)
         self.canvas.blit(self.text.get_window_extent())

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

rawDescription: Python/Matplotlib - Quickly Updating Text on Axes


code:
cmds.window(windowID, title='Towers Of Hanoi', sizeable=False, resizeToFitChildren=True)
cmds.columnLayout(columnAttach=('both', 5), columnWidth=200)

cmds.text(label='Num. of Disks:')

diskNumUIField = cmds.intScrollBar(min=2, max=12, value=2, step=1, largeStep=2)

cmds.rowLayout(numberOfColumns=2, columnWidth2=(90, 80))

cmds.button(label='Place Disks', width=75, command=blablabla)
cmds.button(label='Clear All', width=75, command=blablabla)

cmds.setParent('..')

cmds.rowLayout(numberOfColumns=2, columnWidth2=(90, 80))

cmds.button(label='Solve it!', width=75, command=blablabla)
cmds.button(label='Exit', width=75, command=blablabla)
cmds.showWindow()

rawDescription: Maya scripting: Issue when creating user interfaces (rows and columns)


code:
class SSHProtocol(recvline.HistoricRecvLine):
    [...]
    def characterReceived(self, ch, moreCharactersComing):
        self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
        self.lineBufferIndex += 1

        #if not self.password_input:
        #    self.terminal.write(ch)

rawDescription: Twisted Conch MockSSH: implement 'stty -echo'


code:
root = Root()
RootApp = cherrypy.Application(root)
Domain2App = cherrypy.Application(root)
SecureApp = cherrypy.Application(Secure())

vhost = cherrypy._cpwsgi.VirtualHost(RootApp,
    domains={'www.domain2.example': Domain2App,
             'www.domain2.example:443': SecureApp,
             })

cherrypy.tree.graft(vhost)

rawDescription: How to get CherryPy to listen only on a specific host

description: Get CherryPy to listen only on a specific host


code:
for i in list:
    try:
        myVal.append(float(i))
    except:
        pass

rawDescription: Skipping over array elements of certain types


code:
a = {'q':1, 'w':2, 'e':3}
target = 'q'

for k,v in a.items():
    if k == target:
        print(v)

rawDescription: dictionaries - check if value has key

description: Dictionaries - check if value has key


rawDescription: How to get the index of a maximum element in a numpy array along one axis

description: Get the index of a maximum element in a numpy array along one axis


code:
import pytz
from datetime import datetime
now = datetime.utcnow().replace(tzinfo = pytz.utc)

rawDescription: Python - simplest and most coherent way to get timezone-aware current time in UTC?


code:
def rakhi():
    entry1.configure(state="normal")
    entry2.configure(state="normal")

rawDescription: how to enable a entry by clicking a button in Tkinter?

description: Enable a entry by clicking a button in Tkinter


code: from ..helper import a

rawDescription: How to use the Python package inside a project

description: Use the Python package inside a project


code:
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()

rawDescription: in Python scipting, how do I capture output from subprocess.call to a file

description: In Python scipting, how do I capture output from subprocess.call to a file


code:
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import mlpy.wavelet as wave

# Make some random data with peaks and noise
############################################################
def gen_data():
    def make_peaks(x):
        bkg_peaks = np.array(np.zeros(len(x)))
        desired_peaks = np.array(np.zeros(len(x)))
        # Make peaks which contain the data desired
        # (Mid range/frequency peaks)
        for i in range(0,10):
            center = x[-1] * np.random.random() - x[0]
            amp = 100 * np.random.random() + 10
            width = 10 * np.random.random() + 5
            desired_peaks += amp * np.e**(-(x-center)**2/(2*width**2))
        # Also make background peaks (not desired)
        for i in range(0,3):
            center = x[-1] * np.random.random() - x[0]
            amp = 80 * np.random.random() + 10
            width = 100 * np.random.random() + 100
            bkg_peaks += amp * np.e**(-(x-center)**2/(2*width**2))
        return bkg_peaks, desired_peaks

    # make x axis
    x = np.array(range(0, 1000))
    bkg_peaks, desired_peaks = make_peaks(x)
    avg_noise_level = 30
    std_dev_noise = 10
    size = len(x)
    scattering_noise_amp = 100
    scat_center = 100
    scat_width = 15
    scat_std_dev_noise = 100
    y_scattering_noise = np.random.normal(scattering_noise_amp, scat_std_dev_noise, size) * np.e**(-(x-scat_center)**2/(2*scat_width**2))
    y_noise = np.random.normal(avg_noise_level, std_dev_noise, size) + y_scattering_noise
    y = bkg_peaks + desired_peaks + y_noise
    xy = np.array( zip(x,y), dtype=[('x',float), ('y',float)])
    return xy
# Random data Generated
#############################################################

xy = gen_data()

# Make 2**n amount of data
new_y, bool_y = wave.pad(xy['y'])
orig_mask = np.where(bool_y==True)

# wavelet transform parameters
levels = 8
wf = 'h'
k = 2

# Remove Noise first
# Wave transform
wt = wave.uwt(new_y, wf, k, levels)
# Matrix of the difference between each wavelet level and the original data
diff_array = np.array([(wave.iuwt(wt[i:i+1], wf, k)-new_y) for i in range(len(wt))])
# Index of the level which is most similar to original data (to obtain smoothed data)
indx = np.argmin(np.sum(diff_array**2, axis=1))
# Use the wavelet levels around this region
noise_wt = wt[indx:indx+1]
# smoothed data in 2^n length
new_y = wave.iuwt(noise_wt, wf, k)

# Background Removal
error = 10000
errdiff = 100
i = -1
iter_y_dict = {0:np.copy(new_y)}
bkg_approx_dict = {0:np.array([])}
while abs(errdiff)>=1*10**-24:
    i += 1
    # Wave transform
    wt = wave.uwt(iter_y_dict[i], wf, k, levels)

    # Assume last slice is lowest frequency (background approximation)
    bkg_wt = wt[-3:-1]
    bkg_approx_dict[i] = wave.iuwt(bkg_wt, wf, k)

    # Get the error
    errdiff = error - sum(iter_y_dict[i] - bkg_approx_dict[i])**2
    error = sum(iter_y_dict[i] - bkg_approx_dict[i])**2

    # Make every peak higher than bkg_wt
    diff = (new_y - bkg_approx_dict[i])
    peak_idxs_to_remove = np.where(diff>0.)[0]
    iter_y_dict[i+1] = np.copy(new_y)
    iter_y_dict[i+1][peak_idxs_to_remove] = np.copy(bkg_approx_dict[i])[peak_idxs_to_remove]

# new data without noise and background
new_y = new_y[orig_mask]
bkg_approx = bkg_approx_dict[len(bkg_approx_dict.keys())-1][orig_mask]
new_data = diff[orig_mask]

##############################################################
# plot the data and results
fig = plt.figure()

ax_raw_data = fig.add_subplot(121)
ax_WT = fig.add_subplot(122)

ax_raw_data.plot(xy['x'], xy['y'], 'g')
for bkg in bkg_approx_dict.values():
    ax_raw_data.plot(xy['x'], bkg[orig_mask], 'k')

ax_WT.plot(xy['x'], new_data, 'y')

fig.tight_layout()
plt.show()

rawDescription: Inverse Wavelet Transform [/xpost signalprocessing]


code:
import ctypes

...

frame.f_locals.update({
    'a': 'newvalue',
    'b': other_local_value,
})
ctypes.pythonapi.PyFrame_LocalsToFast(
    ctypes.py_object(frame), ctypes.c_int(0))

rawDescription: Modify *existing* variable in `locals()` or `frame.f_locals`


code:
from bs4 import BeautifulSoup
import requests

url = 'https://twitter.com/search?q=%23bangkokbombing%20since%3A2015-08-10%20until%3A2015-09-30&src=typd&lang=en'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
r = requests.get(url, headers=headers)
data = r.text
soup = BeautifulSoup(data, "lxml")
all_likes = soup.find_all('span', class_='ProfileTweet-actionCountForPresentation')
print(all_likes)

rawDescription: Using Python to Scrape Nested Divs and Spans in Twitter?


code:
def sum_of_powers(base_list, expo_list):

        end = []
        sum = 0 #added sum
        j = 0
        i = 0
        k = 0 #added for loop in getting sum

        while j < len(expo_list):
            sum = 0 #re-initialize value to 0 for the next loop
            i = 0 #re-initialize value to 0 for the next loop
            k = 0 #re-initialize value to 0 for the next loop
            sub_accum = []

            while i < len(base_list):
                sub_accum.append(base_list[i]**expo_list[j])
                i += 1

            while k < len(sub_accum): #loop though temporary list to add its values
                sum = sum + sub_accum[k]
                k += 1

            end.append(sum) #end should be at level of 1st layer when all have been calculated and should only insert the sum of 'sub_accum'

            j += 1

        return end

rawDescription: Using nested while loops to create a sum or powers list, python


code:
import re
e = r'(\d+,?)+'
re.findall(e, 'Array(0, 0, 0, 7)')

rawDescription: How do I write a RE to match part of string

description: Write a RE to match part of string


code:
if request.COOKIES['language'] == 'EN':
    return """<b>%s</b>""" % "Home"

rawDescription: JavaScript cookie value can't be retrieved in Django


code:
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    #'django.middleware.locale.LocaleMiddleware',
    'localeurl.middleware.LocaleURLMiddleware',
    'multilingual.middleware.DefaultLanguageMiddleware',
    'multilingual.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.middleware.common.CommonMiddleware',
)

rawDescription: Using multilingual and localeurl in django


code:
import json
with open('file.txt', 'r') as f:
    data = json.loads(f.read())
for line in data:
    with open(line['Name'] + '.txt', 'w') as f:
        f.write(json.dumps(line))

rawDescription: split txt file to multiple files named according to their contents in Python

description: Split txt file to multiple files named according to their contents in Python


code:
import csv
from stocks.models import Stocks
fields = ["Ticker", "Name", "Exchange"]
for row in csv.reader(open('NASDAQ.csv', 'rU'), dialect='excel'):
    row_dict = dict(zip(fields, row))
    indusCode = urllib2.urlopen("http://finance.yahoo.com/q/in?s=" + row_dict['Ticker']).read()
    industry = indusCode.split('<b>Industry: ')[1].split('</b>')[0]
    industry = industry.replace("&", "&")
    row_dict['Industry'] = industry
    Stocks.objects.create(**row_dict)

rawDescription: Django: Auto Populate CharField using Urllib2


code:
for t in w:
    l.append(t.replace(".",""))

rawDescription: Different outputs in removing characters from a list - Python


code:
import re
s = '  hello world!   '
match = re.search(r"^\s*(\S.*?)\s*$", s)
match.group(1), match.start(1), match.end(1)

rawDescription: Stripping a string and getting start index and end index


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

def compute_cluster(c):
    """each cluster can be computed independently"""
    ... # compute a cluster here

if __name__=="__main__":
   pool = Pool(10) # run 10 task at most in parallel
   pool.map(compute_cluster, range(10))

rawDescription: parallel excution and file writing on python

description: Parallel excution and file writing on python


code:
with open("/etc/passwd") as f:
    lines = f.readlines()

group_dict = {}
for line in lines:
    split_line = line.split(":")
    user = split_line[0]
    gid = split_line[3]
    # If the group id is not in the dict then put it in there with a list of users
    # that are under that group
    if gid not in group_dict:
        group_dict[gid] = [user]
    # If the group id does exist then add the new user to the list of users in
    # the group
    else:
        group_dict[gid].append(user)

# Iterate over the groups and users we found. Keys (group) will be the first item in the tuple,
# and the list of users will be the second item. Print out the group and users as we go
for group, users in group_dict.iteritems():
    print("Group {}, users: {}".format(group, ",".join(users)))

rawDescription: Sorting content of the file in Python

description: Sorting content of the file in Python


rawDescription: matplotlib Legend sign and text are not aligned

description: Matplotlib Legend sign and text are not aligned


code:
latest_phone_numbers = Person.objects.raw('''
SELECT p1.id, p1.name, p1.phone, p1.created
FROM person_person p1, (
    SELECT name, MAX(created) AS max_created
    FROM person_person
    GROUP BY name
) AS p2
WHERE p1.name = p2.name AND p1.created = p2.max_created
''')

rawDescription: Filtering Django Query by the Record with the Maximum Column Value


code:
x
0.5 * (numpy.sign(x) + 1)

rawDescription: Does a heaviside step function exist?

description: Does a heaviside step function exist


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

class ECC(object):
    """
    class to implement elliptic curve and find P+Q=R on the plot
    """

    def __init__(self,a,b,px,qx,qy):
        """
        initialize input variables
        """
        self.a = a
        self.b = b
        self.pxlam = px
        self.qxlam = qx
        self.invertQy = qy
        self.fig = plt.figure(1)
        self.ax = SubplotZero(self.fig, 111)

    def drawAxis(self):
        """
        draw main x,y axis
        """
        #fig = plt.figure(1)
        #ax = SubplotZero(fig, 111)
        self.fig.add_subplot(self.ax)
        for direction in ["xzero", "yzero"]:
            self.ax.axis[direction].set_axisline_style("->")
            self.ax.axis[direction].set_visible(True)

    def ecclambda(self,xl,a,b):
        """
        returns points elliptic curve for P and Q
        y**2 = x**3 + a*x + b
        """
        return sqrt(xl**3 + a*xl + b)

    def elliptic_curve(self,x,y):
        """
        takes in x,y as set of points, returns the elliptic curve
        y**2 = x**3 + a*x + b
        """
        return pow(y, 2) - pow(x, 3) - x * self.a - self.b

    def onclick(self, event):
        x = event.xdata
        if event.button == 1:
            self.pxlam = x
        if event.button == 3:
            self.qxlam = x

        self.update()

    def update(self):
        pylam = self.ecclambda(self.pxlam,self.a,self.b)  # calculate P from pxlam
        qylam = self.ecclambda(self.qxlam,self.a,self.b)  # calculate Q from qxlam
        self.p.set_data([self.pxlam], [pylam])
        self.q.set_data([self.qxlam], [qylam])
        self.pt.set_x(self.pxlam-0.25)
        self.pt.set_y(pylam+0.5)
        self.qt.set_x(self.qxlam-0.25)
        self.qt.set_y(qylam+0.5)
        plt.gcf().canvas.draw()

    def plotGraph(self):
        """
        main plotting of elliptic curve and points/line for P+Q=R
        P+Q=R --->>>  -R is plotted (xr,yr), R is plotted (xr, -yr)
        conditional with invertQy allows inversion of Q across x-axis; set option in main()
        """
        self.drawAxis()
        y, x = np.ogrid[-10:10:100j, -10:10:100j]  # range grid  [from : to : how_many_points]
        xlist = x.ravel(); ylist = y.ravel()
        plt.contour(xlist, ylist, self.elliptic_curve(x,y), [0])
        pylam = self.ecclambda(self.pxlam,self.a,self.b)  # calculate P from pxlam
        qylam = self.ecclambda(self.qxlam,self.a,self.b)  # calculate Q from qxlam
        if self.invertQy == 1:  qylam = -qylam # optional, inverts qy to negative on the plot
        plt.plot([self.pxlam,self.qxlam], [pylam,qylam], color = "c", linewidth=1)
        self.p = plt.plot([self.pxlam], [pylam], "mo")[0]
        self.q = plt.plot([self.qxlam], [qylam], "mo")[0]
        self.pt = plt.text(self.pxlam-0.25,pylam+0.5, '$P$')
        self.qt = plt.text(self.qxlam-0.25,self.qxlam+0.5, '$Q$')
        s = (pylam - qylam)/(self.pxlam - self.qxlam)  # calculate s slope
        xr = s**2 - self.pxlam - self.qxlam  # x-value of R
        yr = pylam + s*(xr - self.pxlam)  # y-value of -R; -y is R (inverted across x-axis)
        plt.plot([xr],[yr],"mo")
        plt.plot([xr],[-yr],"co")
        plt.plot([self.qxlam,xr], [qylam,yr], color = "c", linewidth=1)
        plt.plot([xr,xr], [yr,-yr], "x--")
        plt.text(xr+0.25,yr, '$-R$'); plt.text(xr+0.25,-yr, '$R$')
        plt.text(-9,6,' P: (%s ,%s) \n Q: (%s ,%s) \n R: (%s ,%s) \n a: %s \n b: %s '
                %(self.pxlam,pylam,self.qxlam,qylam,xr,-yr,self.a,self.b),
                fontsize=10, color = 'blue',bbox=dict(facecolor='tan', alpha=0.5))
        plt.title(r"Elliptic Curve Implementation $y^{2} = x^{3} + a*x + b$", fontsize = 16, color = 'b')
        self.fig.canvas.mpl_connect('button_press_event', self.onclick)
        #[xi,yi] = plt.ginput(0)
        ##print "ginput ",xi,yi
        plt.grid(True)
        plt.show()

def main():

    a = -2; b = 1; px = -1.55; qx = -0.1
    invertQy = 0 # set to 1 if q should be inverted to negative along its y axis
    ec = ECC(a,b,px,qx,invertQy)
    ec.plotGraph()

if __name__ == '__main__':
    main()

rawDescription: Python -- Matplotlib user input from mouse for plotting


code:
import re
import urllib3
from bs4 import BeautifulSoup

jpg_regex = re.compile('\.jpg$')
site_regex = re.compile('website\.com\/wallpaper\/')

pool = urllib3.PoolManager()
request = pool.request('GET', 'http://your_website.com/')
soup = BeautifulSoup(request)

jpg_list = list(soup.find_all(name='a', attrs={'href':jpg_regex}))
site_list = list(soup.find_all(name='a', attrs={'href':site_regex}))

result_list = map(lambda a: a.get('href'), jpg_list and site_list)

rawDescription: Searching Large String for file path. Return filepath + filename


code:
from multiprocessing import Pool

def main():
    po = Pool()
    for file in glob.glob('*.csv'):
        filepath = os.path.join(DATA_DIR, file)
        po.apply_async(mine_page, (filepath,), callback=save_data)
    po.close()
    po.join()
    file_ptr.close()

def mine_page(filepath):
    #do whatever it is that you want to do in a separate process.
    return data

def save_data(data):
    #data is a object. Store it in a file, mysql or...
    return

rawDescription: python -> multiprocessing module

description: Python -> multiprocessing module


code: all(predicate(x) for x in string)

rawDescription: True for all characters of a string

description: True for all characters of a string


code:
class Address(ndb.Model):
  type = ndb.StringProperty() # E.g., 'home', 'work'
  street = ndb.StringProperty()
  city = ndb.StringProperty()

class Contact(ndb.Model):
  name = ndb.StringProperty()
  addresses = ndb.StructuredProperty(Address, repeated=True)

guido = Contact(name='Guido',
                addresses=[Address(type='home',
                                   city='Amsterdam'),
                           Address(type='work',
                                   street='Spear St',
                                   city='SF')])

guido.put()

rawDescription: App Engine: Structured Property vs Reference Property for one-to-many relationship


code:
class LaterPagesTable(Table):
    def __init__(self, data, laterColWidths=None, laterStyle=None, **kwargs):
        Table.__init__(self, data, **kwargs)

        self._later_column_widths = laterColWidths
        self._later_style = laterStyle

    def split(self, availWidth, availHeight):
        self._calc(availWidth, availHeight)
        if self.splitByRow:
            if not rl_config.allowTableBoundsErrors and self._width>availWidth: return []
            tables = self._splitRows(availHeight)

            if len(tables):
                self.onLaterPages(tables[1])
            return tables
        else:
            raise NotImplementedError

    def onLaterPages(self, T):
        if self._later_column_widths:
            T._argW = self._later_column_widths

        if self._later_style:
            T.setStyle(self._later_style)

rawDescription: Reportlab Table split

description: Reportlab Table split


code:
auth1 = tweepy.auth.OAuthHandler('CONSUMER KEY','CONSUMER SECRET')
auth1.set_access_token('ACCESS TOKEN','ACCESS TOKEN SECRET')
api = tweepy.API(auth1)

class StreamListener(tweepy.StreamListener):
    def __init__(self, f):
        super(StreamListener, self).__init__()
        self._f = f
    def on_status(self, status):
        printf(status)
        self._f.write(status.text)

with open('twitterMessages.txt', 'w') as outf:
    l = StreamListener(outf)
    streamer = tweepy.Stream(auth=auth1, listener=l, timeout=3000000000 )
    setTerms = ['lol', 'Lol', 'LOL']
    streamer.filter(None,setTerms)

rawDescription: Adding class variables to defined class

description: Adding class variables to defined class


code:
variables = [a, b, c, d, e]
if len(set(variables)) == len(variables):
    print("All variables are different")

rawDescription: Python test if all N variables are different


rawDescription: Django lxml parsing issue with value

description: Django lxml parsing issue with value


code:
#Adapted from https://djangosnippets.org/snippets/2619/

@register.tag(name='counter')
def do_counter(parser, token):
    """
    Counter tag. Can be used to output and increment a counter.

    Usage:
    - {% counter %} to output and post-increment the counter variable
    - {% counter reset %} to reset the counter variable to 1
    - {% counter last %} to access the last counter variable without incrementing

    """
    try:
        tag_name, request = token.contents.split(None, 1)
    except ValueError:
        request = None

    if request == 'reset':
        reset = True
        last = False
    elif request == 'last':
        last = True
        reset = False
    else:
        reset = False
        last = False

    return CounterNode(reset, last)

class CounterNode(template.Node):
    def __init__(self, reset, last):
        self.reset = reset
        self.last= last

    def render(self, context):
        # When initializing or resetting, set counter variable in render_context to 1.
        if self.reset or ('counter' not in context.render_context):
            context.render_context['counter'] = 1

        # When resetting, we don't want to return anything
        if self.reset:
            return ''
        # When ask for last, return previous count
        if self.last:
            return context.render_context['counter']-1

        counter = context.render_context['counter']

        # Increment counter
        context.render_context['counter'] += 1

        # Return counter number
        return counter

rawDescription: Why counter tag is not working as expected in django?


code:
from itertools import izip_longest
[list(x) for x in itertools.izip_longest([1,2,3],[4,5,6,7],['a','b'])]

rawDescription: arbitrary sequences in "zipped" sequences (mapped sequences actually)

description: Arbitrary sequences in "zipped" sequences (mapped sequences actually)


code: {z: {y: {x: [] for x in data_types} for y in t} for z in experiments}

rawDescription: python how to create dictionaries in dictionaries from lists

description: Python how to create dictionaries in dictionaries from lists