code:
id,key1,key2,key1,key2,key4
1,value1,value2,value3,value4,value5
id,key1,key2
2,value3,value4

rawDescription: Selecting Certain Keys,Values From List of Python Dictionaries to CSV


code:
from multiprocessing import Process
from threading import Lock

x = 0
lock = Lock()

def main():
    global x
    print(x)
    p = Process(target=change, args=(1,))
    p2 = Process(target=change, args=(2,))
    p.start()
    p2.start()
    p.join()
    p2.join()

def change(number):
    global x
    with lock:
        x = x + 1
        print('{} - coming from process #{}'.format(x, number))

if __name__ == '__main__':
    main()

rawDescription: Simple Multithreading in Python using Process


code: from models import *

rawDescription: Django Model With Multiple Classes

description: Django Model With Multiple Classes


code:
# First create a token. We're pretending this user actually exists on your local computer or Active Directory domain.
user = "ltorvalds"
pword = "IAMLINUXMAN"
domain = "." # means current domain
logontype = win32con.LOGON32_LOGON_INTERACTIVE
provider = win32con.LOGON32_PROVIDER_WINNT50
token = win32security.LogonUser(user, domain, pword , logontype, provider)

# Now let's create the STARTUPINFO structure. Read the link above for more info on what these can do.
startup = win32process.STARTUPINFO()

# Finally, create a cmd.exe process using the "ltorvalds" token.
appname = "c:\\windows\\system32\\cmd.exe"
priority = win32con.NORMAL_PRIORITY_CLASS
win32process.CreateProcessAsUser(token, appname, None, None, None, True, priority, None, None, startup)

rawDescription: using WIN32 API CreateProcessAsUser in Python

description: Using WIN32 API CreateProcessAsUser in Python


code:
for i in [["A", 0], ["B", 1], ["C", 2]]:
    tmp = do_stuff(tmp2[i[1]])
    if tmp != None: setattr(inst, i[0], tmp)

rawDescription: Setting properties programmatically

description: Setting properties programmatically


rawDescription: Http POST Accents encoding

description: Http POST Accents encoding


code:
# you are checking values 1-5 and not 1-6!
possibles = list(range(1, 6)) # should be range(7) [exclusive range]

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


rawDescription: Get values from onclick attribute using python bs4


code:
tree = { "a": { "b": 1 }}
transform_node("root", tree)

rawDescription: Arbitrary Dictionary (JSON) to Stricter Tree-like Dictionary (JSON) in Python


code:
from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_passwd_cb(lambda *unused: "yourpassword")
ctx.use_privatekey_file(keyFilename)
ctx.use_certificate_file(certFilename)
someSocket = SSL.Connection(ctx, socket.socket())

rawDescription: Python httplib.HTTPSConnection and password


code:
crypt = f.read()
encrypted_message = []
for letter in crypt:
    encrypted_message.append(monocrypt.get(letter.lower(), letter.lower()) )

rawDescription: How to keep "spaces" although dict contains it?

description: Keep "spaces" although dict contains it


code: df.columns = col_list

rawDescription: python create a data frame with one row by a list

description: Python create a data frame with one row by a list


rawDescription: How to treat a hex as string?

description: Treat a hex as string


rawDescription: Container to Use for Sorting in Python

description: Container to Use for Sorting in Python


code:
from django.db.models import Max
queryset = Priekabos.objects.annotate(max_kada_moketi=Max('grafikas__kada_moketi'))
table = PriekabosTable(queryset)

rawDescription: django-tables2 custom column

description: Django-tables2 custom column


code:
go
click
go
text
[5]

rawDescription: Method chaining with asyncio coroutines

description: Method chaining with asyncio coroutines


code:
import pandas as pd

data = [['a','e'], ['b','f'], ['c','g'], ['d','h'], ['a','i'], ['b','j'],
        ['c','k'], ['d','l']]

df = pd.DataFrame(data, columns=['first', 'second'])
print(df.groupby(['first']).agg(lambda x: x.tolist()))

rawDescription: Data wrangling with python pandas

description: Data wrangling with python pandas


code:
g = df.groupby(['PROT', 'PEP'])
g['SD'].apply(lambda x: np.nan if len(x) < 2 else (x.nlargest(2).sum() / 2))

rawDescription: Filtering, grouping data

description: Filtering, grouping data


code:
def f(x):
    y = 0
    result = []
    for _ in x:
        result.append(y)
        y += np.random.normal(scale=1)
    return np.array(result)

rawDescription: Produce random wavefunction

description: Produce random wavefunction


code:
with open('file.txt', 'r') as f:
    f = f.read().splitlines()
lines = [x for x in f if x and not x.strip().startswith('!')]

rawDescription: How to store each line of a text file into a python list excluding comments

description: Store each line of a text file into a python list excluding comments


code: tst2 = str(tst)

rawDescription: Tuple to string

description: Tuple to string


rawDescription: How to assign "empty" to a list position (python)

description: Assign "empty" to a list position (python)


code:
result = generator_func()
isinstance(result, collections.Sequence)

rawDescription: How can I tell if a structure in Python has order?

description: Tell if a structure in Python has order


code: a_list = [[0] * 10 for _ in range(10)]

rawDescription: Python list confusion

description: Python list confusion


code: destMatches = filter(lambda destEntry:destEntry[0] == sourceMatch, destList)

rawDescription: finding first item in a list whose first item in a tuple is matched

description: Finding first item in a list whose first item in a tuple is matched


code:
def g(x):
    return 3*x*(2-x)

iterate(seed, num, g)
#                  ^

rawDescription: How to pass a function as function parameter in Python

description: Pass a function as function parameter in Python


code:
df.loc[df.index.normalize() == Timestamp('20130102'),'Active'] = True
df

rawDescription: Selecting DataFrame slices by date string


code:
h = HeapQueue([4,3,2,1])
print(h._index_table)
h.heapify()
print(h)
print(h._index_table)
h.push(42)
print(h._index_table)
print(h)

rawDescription: Intercepting heapq

description: Intercepting heapq


code:
dic = {}

dic

rawDescription: Python create Counter object from dictionary, include a sum of values against summarised keys


code:
import os
os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( a, b))

rawDescription: Python: Sound alarm when code finishes

description: Python: Sound alarm when code finishes


rawDescription: One-Many-One Inheritance in Python

description: One-Many-One Inheritance in Python


code:
import io
def savefirst():
    cnv = getscreen().getcanvas()
    global hen
    ps = cnv.postscript(colormode = 'color')
    hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
    im = Image.open(io.BytesIO(ps.encode('utf-8')))
    im.save(hen + '.jpg')

rawDescription: How to convert a Python tkinter canvas postscript file to an image file readable by the PIL?

description: Convert a Python tkinter canvas postscript file to an image file readable by the PIL


code: my_dict = {'cheese': 'cake'}

rawDescription: Python equivalent for HashMap

description: Python equivalent for HashMap


code:
cols = [(k,v) for k,sublist in col_mapping.items()
              for v in sublist]

rawDescription: Grouping Python Panda table with additional heading


code:
class Foo(object):
    def __init__(self, x):
        self.x = x

    @numba.jit
    def dosomething(self, y):
        for i in range(len(self.x)):
            self.x[i] += y[i]

rawDescription: Design heuristics for writing Python classes that interact with `scipy.integrate.odeint`?


code: processed_numbers=[(1 if num<1 else num) for num in map(float,contents.split())]

rawDescription: python: find and replace numbers < 1 in text file

description: Python: find and replace numbers < 1 in text file


code:
import dictionary

dictionary.words[whatever]

rawDescription: Best way to store and use a large text-file in python

description: Store and use a large text-file in python


rawDescription: What is the best way to use the Google API to get just a user's email?


code:
pathPowerBI="C:/Program Files/Microsoft Power BI Desktop/bin"
initialSetup(pathPowerBI)
session = restorePowerPivot("D:/Downloads/PowerPivotTutorialSample.xlsx", "D:/", 60000, pathPowerBI)
df, metadf = runQuery("EVALUATE dbo_DimProduct",60000,1)
endSession(session)

rawDescription: Extracting raw data from a PowerPivot model using Python


code:
import turtle
#import numpy as np
from time import sleep

tlist = list()
colorlist = ["red", "green", "black", "blue", "brown"]
for i in xrange(5):
    tlist.append(turtle.Turtle(shape="turtle"))
    tlist[i].color(colorlist[i])
    tlist[i].speed(1)
screen = turtle.getscreen()
for i in xrange(100):
    screen.tracer(1000)
    for i, t in enumerate(tlist):
        #t.right((np.random.rand(1) - .5) * 180))
        t.right(33 * i)
        #t.forward(int((np.random.rand(1) - .5) * 100))
        t.forward(50 * i)
    sleep(1)
    screen.update()

rawDescription: Running turtles simultaneously with turtle graphics


code:
line = 'Your MAC address is 01:23:45:67:89:ab\n'
line.split()

rawDescription: How to get last part of line with Python

description: Get last part of line with Python


code:
my_ip = '209.85.128.1'
is_in_whitelist = any([my_ip in white_net for white_net in myWhiteList])

rawDescription: How to determine if IP address in whitelist with IPy?

description: Determine if IP address in whitelist with IPy


code: __init__(self, name=None, cnf={}, master=None, **kw)

rawDescription: Tkinter create_image not displaying

description: Tkinter create_image not displaying


code:
class ComponentURLField(serializers.Field):
    def to_native(self, obj):
        """
        Return a URL, given a component instance, 'obj'.
        """

        # Something like this...
        request = self.context['request']
        return reverse('component-detail', kwargs=kwargs, request=request)

rawDescription: How to extend model on serializer level with django-rest-framework

description: Extend model on serializer level with django-rest-framework


code:
from subprocess import communicate
from subprocess import wait

rawDescription: Python subprocess Popen.communicate() equivalent to Popen.stdout.read()?


code:
for index in xrange(len(gList)):   #xrange() or(range() in python 3.x) returns a iterable which contains values from 0 to len(gList)-1
    gList[index].lstrip("0")

rawDescription: How to loop through list evalute first char of each item of list

description: Loop through list evalute first char of each item of list


code: f.blah is f.blah

rawDescription: Python method lookup rules

description: Python method lookup rules


code:
from tkinter import *
from tkinter import ttk

rootwin = Tk()

roomtext = Text(rootwin)
roomtext.grid(column=0, row=0)

def create_scrollbar():
    if roomtext.cget('height') < int(roomtext.index('end-1c').split('.')[0]):
        rtas = ttk.Scrollbar(rootwin, orient = "vertical", command = roomtext.yview)
        rtas.grid(column=1, row=0, sticky=N+S)
        roomtext.config(yscrollcommand = rtas.set)
    else:
        rootwin.after(100, create_scrollbar)

create_scrollbar()
rootwin.mainloop()

rawDescription: Create scrollbar only when text length greater than text area


code:
Name
First
Second
Third
Fourth

rawDescription: Adding a new column on CSV with Python

description: Adding a new column on CSV with Python


code:
d = [dict(zip(keys, l)) for l in t ]
d

rawDescription: Convert list of lists to list of dictionaries


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, high=9, size=(100,2)),
         columns = ['A', 'B'])

threshold = 10 # Anything that occurs less than this will be removed.
value_counts = df.stack().value_counts() # Entire DataFrame
to_remove = value_counts[value_counts <= threshold].index
df.replace(to_remove, np.nan, inplace=True)

rawDescription: Remove low frequency values from pandas.dataframe


code:
import multiprocessing as mp
import copy_reg
import types

def _pickle_method(method):
    # Author: Steven Bethard (author of argparse)
    # http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-
    # instancemethods
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    cls_name = ''
    if func_name.startswith('__') and not func_name.endswith('__'):
        cls_name = cls.__name__.lstrip('_')
    if cls_name:
        func_name = '_' + cls_name + func_name
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    # Author: Steven Bethard
    # http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-
    # instancemethods
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)

# This call to copy_reg.pickle allows you to pass methods as the first arg to
# mp.Pool methods. If you comment out this line, `pool.map(self.foo, ...)` results in
# PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup
# __builtin__.instancemethod failed

copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)

class F(object):
    def f(self, x):
        fq.put('Doing: ' + str(x))
        return x*x

def f_init(q):
    # http://stackoverflow.com/a/3843313/190597 (Olson)
    global fq
    fq = q

def main():
    jobs = range(1,6)
    q = mp.Queue()
    p = mp.Pool(None, f_init, [q])
    f = F()
    results = p.imap(f.f, jobs)
    p.close()

    for r in results:
        print(r, q.get())

if __name__ == '__main__':
    main()

rawDescription: function initialize and object initialization (multiprocessing)

description: Function initialize and object initialization (multiprocessing)


rawDescription: copy numpy array efficiently

description: Copy numpy array efficiently


code:
from itertools import permutations
[i for i in permutations(range(1, 5), 4)]

rawDescription: Go through every possible combination of an array python


code:
relevant_columns = df[df.columns[2:]]
values_as_ints = relevant_columns.convert_objects(convert_numeric=True)
values_valid = values_as_ints.isin((0, 1))
row_valid = values_valid.all(axis=1)
good_rows = df[row_valid]

rawDescription: DataFrame drop rows whose column has certain values


code: lotto = [random.randrange(1, 9) for index in range(7)]

rawDescription: Sequence elements will not modify (Python 3.4)


code: max(a, b, c, key=lambda p: p.distance)

rawDescription: How to choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions?

description: Choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions


code:
soup.select("a[href*=price]")  # href contains 'price'
soup.select("a[href^=price]")  # href starts with 'price'
soup.select("a[href$=price]")  # href ends with 'price'

rawDescription: Navigation with BeautifulSoup

description: Navigation with BeautifulSoup


code:
import sys
a = sys.intern('why do pangolins dream of quiche')
a

rawDescription: What does python sys.intern do, and when should it be used?


rawDescription: Select elements row-wise based on single array


rawDescription: JSON encoding for dict of dicts

description: JSON encoding for dict of dicts


rawDescription: Numpy: efficient array of indices to "bump" array


code:
for xx in range(1,5):
    for yy in range(1,3):
        x0=.25*xx
        y0=.25*yy
        bigR=xx
        littleR=yy
        mpl.rcParams['legend.fontsize'] = 10
        label="parametric curve x0= " + str(x0) + " y0 = " + str(y0) + " R = " + str(bigR) + " r = " + str(littleR)

        fig = plt.figure()
        ax = fig.gca(projection='3d')
        t = np.linspace(-4 * np.pi, 4 * np.pi, 100)
        z = np.linspace(0, 0, 100)
        x = (x0 - (bigR-littleR))*np.cos(((bigR-littleR)*t)/littleR) + y0*np.sin(((bigR-littleR)*t)/littleR) + (bigR-littleR)*np.cos(t)
        y = -(x0 - (bigR-littleR))*np.sin(((bigR-littleR)*t)/littleR) + y0*np.cos(((bigR-littleR)*t)/littleR) + (bigR-littleR)*np.sin(t)

        ax.plot(x, y, z, label=label)
        ax.legend()

        fig.savefig("/tmp/epicycloid{0:d}-{1:d}.png".format(xx,yy))

rawDescription: When saving pylab figure plot, cant change the name from figure_1.png. Also label problems


code:
l = [{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'},
     {'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'},
     {'score': 65, 'credit': 5, 'class': 'B01', 'subject': 'science'},
     {'score': 35, 'credit': 5, 'class': 'C02', 'subject': 'math'}]

l2 = [{'pass_mark': 50, 'subject_all': u'math'},
      {'pass_mark': 70, 'subject_all': u'science'},
      {'pass_mark': 70, 'subject_all': u'music'}]

sub = {dct["subject_all"]: dct["pass_mark"] for dct in l2}

result = [dct for dct in l if dct["score"] >= sub[dct["subject"]]]

print(result)

rawDescription: How to compare with other json objects's value

description: Compare with other json objects's value


code:
r = requests.get ('https://www.dropbox.com/s/7uhheam5lqppzis/singlelineTest.csv?dl=1')
data = str(r.text.encode('utf-8').replace("\xc2\x87", ",")).splitlines()

headers = data.pop(0).split(",")

pidx = headers.index('PlayerID')
partidx = headers.index('Partner')

with open("testData.csv", "wb") as csvfile:
    f = csv.writer(csvfile)
    f.writerow(["PlayerID", "Partner"]) # add headers
    for data in data[1:]:
      words = data.split(',')
      f.writerow([words[pidx], words[partidx]])

rawDescription: Download "csv-like" text data file and convert it to CSV in python


code:
import pandas as pd
import json

def find_element(children_list,name):
    """
    Find element in children list
    if exists or return none
    """
    for i in children_list:
        if i["name"] == name:
            return i
    #If not found return None
    return None

def add_node(path,value,nest):
    """
    The path is a list.  Each element is a name that corresponds
    to a level in the final nested dictionary.
    """

    #Get first name from path
    this_name = path.pop(0)

    #Does the element exist already?
    element = find_element(nest["children"], this_name)

    #If the element exists, we can use it, otherwise we need to create a new one
    if element:

        if len(path)>0:
            add_node(path,value, element)

    #Else it does not exist so create it and return its children
    else:

        if len(path) == 0:
            nest["children"].append({"name": this_name, "value": value})
        else:
            #Add new element
            nest["children"].append({"name": this_name, "children":[]})

            #Get added element
            element = nest["children"][-1]

            #Still elements of path left so recurse
            add_node(path,value, element)

rawDescription: Creating D3 nested JSON Data with Python


code:
mapping2 = mapping.set_index(['from_symbol', 'end_date']).sort_index()
mapping2
df['mapping'] = df.apply(lambda x: mapping2.loc[x['symbol']][x['date']:].values[0][0], axis=1)
df

rawDescription: Join two pandas dataframes with only end dates


code:
count = np.bincount(B.ravel())
tally = np.bincount(B.ravel(), weights=A.ravel())
freq = tally / count

rawDescription: Plotting Histogram using data from 2 numpy matrices


code: 'Normalized Distance in Chamber ($\\frac{x}{L}$)'

rawDescription: \frac{}{} won't work for me w/ pylab

description: \frac{}{} won't work for me w/ pylab


code:
import numbers, operator
def average( what ):
    if not isinstance( what, list ):
        return what
    if not all( isinstance(item, numbers.Number) for item in what ):
        return what
    if len(what) == 0:
        return None
    else:
        return operator.truediv( sum( what ), len( what ) )

rawDescription: Correcting the code in python

description: Correcting the code in python


code:
def sign_up_account_admin(request):
    """
    """
    user = None
    user, msg = save_form_data(request)
    req_dict = {"msg": msg}
    if user:
        ret = redirect('homepage') #-- This works pretty fine
    else:
        request.session['resp'] = msg # set in session
        ret = redirect('/signupform/')

    return ret

rawDescription: Django - dictionary passed in redirect is not showing in template


code:
from datetime import datetime
now = datetime.now()
ts = '2015-03-01T17:09:00.000+0000'
ts = ts[:10]
f = '%Y-%m-%d'
date_from_sql = datetime.strptime(ts, f)
print(date_from_sql - now).days

rawDescription: Subtracting Dates of Different Formats and converting to Int


code:
import csv
file = open('file.txt', 'rb')
data = csv.reader(file, delimiter='\t')
table = [row for row in data]

rawDescription: Loading a file into a numpy array with python


code: c

rawDescription: numerical operation on two numpy ndarrays

description: Numerical operation on two numpy ndarrays


code:
@app.route('contact_msg/<contact>')
def contact_msg_page( contact ):
    session['contact_clicked'] = contact
    return redirect( url_for( 'home' ) )

rawDescription: How to set a variable from inside a for loop that can be accessed from outside the for loop [Jinja]

description: Set a variable from inside a for loop that can be accessed from outside the for loop [Jinja]


code: del type(foo).x

rawDescription: Define properties for object instances

description: Define properties for object instances


code:
...
logOutput = QTextEdit(parent)
logOutput.setReadOnly(True)
logOutput.setLineWrapMode(QTextEdit.NoWrap)

font = logOutput.font()
font.setFamily("Courier")
font.setPointSize(10)

theLayout.addWidget(logOutput)
...

rawDescription: pyqt - how to make a textarea to write messages to - kinda like printing to a console

description: Pyqt - how to make a textarea to write messages to - kinda like printing to a console


code:
print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.

rawDescription: Python: Usable Max and Min values

description: Python: Usable Max and Min values


code:
def openFile(file):
    if sys.platform == 'linux2':
        subprocess.call(["xdg-open", file])
    else:
        os.startfile(file)

rawDescription: Open file with pyQt

description: Open file with pyQt


code:
import importlib
m1 = importlib.import_module("C dir.E.m1")
m2 = importlib.import_module("C dir.F.m2")

m1.my_func1()
m2.my_func2()

rawDescription: Importing Modules from Multiple Parallel Subdirectories (Python)


rawDescription: Pandas Dataframe output to JSON

description: Pandas Dataframe output to JSON


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from physurlfetch.items import PhysurlfetchItem
from scrapy.http import Request

class PhysURLSpider(CrawlSpider):
    date = raw_input("Please iput a date in the format M-DD-YYYY: ")
    name = "PhysURLCrawlSpider"
    allowed_domains = ["phys.org"]
    start_url_str = ("http://phys.org/archive/%s/") % (date)
    start_urls = [start_url_str]

    rules = (
        Rule (SgmlLinkExtractor(allow=("\d\.html",)),
        callback="parse_items", follow = True),
    )

    #def parse_start_url(self, response):
        #request = Request(start_urls, callback = self.parse_items)

    def parse_items(self, response):
        selector = Selector(response)

        # selecting only using "news-detail-box" class
        # you could use "article.news-box.news-detail-box.clearfix > h4"
        titles = selector.css("article.news-detail-box > h4")

        items = []
        for titles in titles:
            item = PhysurlfetchItem()
            item ["title"] = titles.xpath("a/text()").extract()
            item ["link"] = titles.xpath("a/@href").extract()
            items.append(item)
        self.log("%d items in %s" % (len(items), response.url))
        return items

rawDescription: How do I make recursive scraping work?

description: Make recursive scraping work


rawDescription: Masking a list against a string in Python


code:
import serial
import io

ser = serial.serial_for_url('loop://', timeout=1)
serio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), newline='\r', line_buffering=True)
serio.write(u'A1A0\r'  # simulation of starting to listen halfway between 2 records
    '$\r'              # marks the end of the previous record
    '@\r'              # marks the start of a new sensor record
    'I0101010000000000001B\r'  # info about a sensor's probe
    'V0109470D\r'              # data matching that probe
    'I0202010000000000002B\r'  # other probe, same sensor
    'V021BB55C\r')             # data corresponding with 2nd probe

listen_on_serial(serio)

rawDescription: read and stock various data from various usb devices in python

description: Read and stock various data from various usb devices in python


code:
class TranslatedCharField(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()
    relation_field = models.CharField(max_length=255)

    class Meta:
        unique_together = ('object_id', 'lang', 'relation_field')

    lang = models.CharField(verbose_name="lingua", max_length=255, choices=LANGUAGES)
    text = models.CharField(verbose_name="testo", max_length=255)

def translatedFieldInlineAdminFormFactory(relation_field, translatemodel):
    class TranslatedFieldInlineAdminForm(forms.ModelForm):

        class Meta:
            model = translatemodel

        def clean(self):
            self.cleaned_data["relation_field"] = relation_field
            return self.cleaned_data

class TranslatedTabularInline(generic.GenericTabularInline):
    def __init__(self, *args, **kwargs):
        super(TranslatedTabularInline, self).__init__(*args, **kwargs)
        self.form = translatedFieldInlineAdminFormFactory(self._relation_field_filter, self.model)

    extra = 1
    max_num = len(LANGUAGES)
    exclude = ('relation_field',)
    model = None
    _relation_field_filter = None
    return TranslatedFieldInlineAdminForm

rawDescription: Django Multiple GenericRelation related_name in admin


code: tokens = word_tokenize(raw)

rawDescription: Extracting a word and its prior 10 word context to a dataframe in Python


code: re.search(r'/\d{0,3}$', st).group()

rawDescription: How to extract number from end of the string

description: Extract number from end of the string


code:
connection = util.get_db_connection()

with connection as cursor:
    cursor.execute(...)

# connection commit is issued if no exceptions were raised.

rawDescription: Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API?


code: np.nan == np.nan

rawDescription: Average of a numpy array returns NaN

description: Average of a numpy array returns NaN


code:
def __eq__(self, other):
    if self.__dict__.viewkeys() != other_keys.__dict__.viewkeys(): # .keys() in Python 3
        return False
    return all(other.__dict__[key] == self.__dict__[key] for key in self.__dict__)

rawDescription: Sort both elements of a tuple, ignoring case, within a list, so that the keys of a dictionary line up correctly


rawDescription: How does Python handle equality checking?


code: classes = {"MyClassName": MyClassName, "MyClass2": MyClass2}

rawDescription: Use class as string

description: Use class as string


code: DF3.drop(['K', 'L', 'inDF2'], axis=1, inplace=True)

rawDescription: Find common rows of 2 dataframe for 2 columns


rawDescription: python multiprocessing peculiar memory management

description: Python multiprocessing peculiar memory management


rawDescription: counting occurrence of consecutive elements in a list (python)

description: Counting occurrence of consecutive elements in a list (python)


rawDescription: Selecting all rows with dates in a unstructured csv


rawDescription: How to load a database of countries in a web application

description: Load a database of countries in a web application


code: Counter(people)

rawDescription: Object equallity in python collections.Counter


code:
api = MainClass()
api.build_API()
api.meth1()
api.meth2()

rawDescription: Find name of dynamic method in Python

description: Find name of dynamic method in Python


code:
from tkinter import *

win=Tk()

x = IntVar()
x.set(1)
def add():
    x.set(x.get()+1)

f = Frame(win)
b1 = Button(f,text="One")
b2 = Button(f,text="Two")
b3 = Button(f,text="Three")
b4 = Button(f,text="Four")
l = Label(win, textvariable=x)
b1.grid(row=0, column=0)
b2.grid(row=0, column=1)
b3.grid(row=0, column=2)
l.pack()
f.pack()
b1.configure(command=add)
win.mainloop()

rawDescription: How to make a Tkinter label update?

description: Make a Tkinter label update


code:
df['num'] = pd.factorize(df.subject)[0]
df

rawDescription: Process string-valued columns from a CSV file with Pandas


code:
def get_value(some_thing, some_key):
    if type(some_thing) in (dict,tuple,list):
        return some_thing[some_key]
    else:
        return getattr(some_thing, some_key)

rawDescription: python dictionary key Vs object attribute

description: Python dictionary key Vs object attribute


code: phoneNum += charToNum(char)

rawDescription: Python String Logic Error

description: Python String Logic Error


rawDescription: Multiline string parsing

description: Multiline string parsing


code:
groups = df.groupby('Date').indices
df = pd.DataFrame(data= groups.values(),index=groups.keys()).reset_index()

rawDescription: How do I update dataframe column values with Pandas?

description: Update dataframe column values with Pandas


code: [ord(i)-ord('a') for i in s]

rawDescription: working with lists and strings

description: Working with lists and strings


code: Lock

rawDescription: Can I 'wrap' an USB stick with Python?

description: 'wrap' an USB stick with Python


code:
def KNN(trainset, Ytrainvec, testset, k):
    eucdist = scidist.cdist(testset,trainset,'sqeuclidean')
    res=[]
    for dists in eucdist:
        distup = zip(dists, Ytrainvec)
        minVals = []
    sumLabel=0;
    for it in range(k):
        minIndex = index_min(dists)
        (minVal,minLabel) = distup[minIndex]
        del distup[minIndex]
        dists=numpy.delete(dists,minIndex,0)
        if minLabel == 1:
            sumLabel+=1
        else:
            sumLabel-=1
        if(sumLabel>0):
            res.append(1)
        else:
            res.append(0)
    return res

rawDescription: Classifiying a set of Images into Classes


code: df['median'] = data.groupby(['Date','SKU'])['Search Rank'].transform('median')

rawDescription: Find median of values based on multiple identifiers and add to row


rawDescription: Highly challenging queryset filtering, sorting and annotation (in Django-based app)


type: exam

type: quiz

type: projectwork

rawDescription: How to retrieve sub documents in a Array from mongoDB using python script

description: Retrieve sub documents in a Array from mongoDB using python script


code:
class voice(object):
  Voiced, Voiceless = range(2)

rawDescription: functional-style datatypes in Python

description: Functional-style datatypes in Python


rawDescription: How to do nested Django SELECT?

description: Do nested Django SELECT


code:
from collections import defaultdict

items = [{'category':'apple','item':'granny smith'},
 {'category':'apple','item':'cox'},
 {'category':'apple','item':'pixie'},
 {'category':'orange','item':'premier'},
 {'category':'orange','item':'queen'},
 {'category':'orange','item':'westin'},
 {'category':'tea','item':'breakfast'},
 {'category':'tea','item':'lady grey'},
 {'category':'tea','item':'builders'},
 {'category':'coffee','item':'colombia'},
 {'category':'coffee','item':'kenya'},
 {'category':'coffee','item':'brazil'}]

result = defaultdict(list)
for item in items:
    result[item['category']].append(item['item'])

rawDescription: having category headings for list dictionaries in python/django

description: Having category headings for list dictionaries in python/django


code: any(item in dct for item in lst)

rawDescription: Using set on Dictionary keys

description: Using set on Dictionary keys


rawDescription: Plotting bar charts by each two rows

description: Plotting bar charts by each two rows


rawDescription: how to apply functions to grouped dataframes in Python pandas?

description: Apply functions to grouped dataframes in Python pandas


code:
class MyClass:
    @staticmethod
    def say_hello():
       print('Hello!')

class MyException(Exception):
    def __init__(self, *args, **kwargs):
        MyClass.say_hello()
        super(MyException, self).__init__(*args, **kwargs)

rawDescription: Python3 - call method from parent class

description: Python3 - call method from parent class


code: result['streams']

rawDescription: Python accessing data in JSON object

description: Python accessing data in JSON object


rawDescription: row and column from "Itemchanged" signal

description: Row and column from "Itemchanged" signal


code: self.button1.configure(command=lambda btn=self.button1: self.chooseDice(btn, 1))

rawDescription: accessing the return value of function that was bound to an event (python/tkinter)

description: Accessing the return value of function that was bound to an event (python/tkinter)


rawDescription: Python Pandas groupby function with dynamic parameters for monthly, hourly means


code: [x for x in path.split("/") if x]

rawDescription: Splitting a url into a list in python

description: Splitting a url into a list in python


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

class AnimRect(object):
    '''Animate a rectangle'''
    def __init__(self):
        self.fig = plt.figure(figsize = (5,5))
        # create the axes
        self.ax = plt.axes(xlim=(0,100), ylim=(0,100), aspect='equal')
        # create rectangle
        self.rect = plt.Rectangle((70,20), 10, 10,
                                  fill=True, color='gold', ec='blue')
        self.ax.add_patch(self.rect)
        self.call_animation()
        plt.show()

    # animation function
    def animate(self, i):
        self.rect.set_xy((i,i))
        self.rect.set_visible(True)
        return self.rect,

    def call_animation(self):
        # call the animator function
        self.anim = animation.FuncAnimation(self.fig, self.animate, frames=91,
                                interval=20, blit=False, repeat=True)

def main():
    rect = AnimRect()

main()

rawDescription: pyplot rectangle animation leaves initial rectangle displayed

description: Pyplot rectangle animation leaves initial rectangle displayed


code: pd.DataFrame(data[1:], columns=data[0])

rawDescription: Python list to pandas dataframe

description: Python list to pandas dataframe


code: zip(*val)

rawDescription: Mapping a 2d list and a 1d list on to a dictionary


code:
x = 2
y = 3
nestedArray = [[0]*y for a in xrange(x)]

rawDescription: how to get the length of a 2-d counter

description: Get the length of a 2-d counter


code: mygconf['/path/to/key'];

rawDescription: access to gnome configuration information using python

description: Access to gnome configuration information using python


rawDescription: Django: how to get a dictionary with a related object as key from a querydict


code: [dataset2D[row_idx] for row_idx in row_indices]

rawDescription: Iterate over two nested 2D lists where list2 has list1's row numbers


code: fout.seek(len("%% this is the header line\n"))

rawDescription: file.write() the length of file without knowing the length of file beforehand - python

description: File.write() the length of file without knowing the length of file beforehand - python


code:
task_result = some_complex_task()
task_result.parent.parent.graph

rawDescription: Logging task relationships in Celery

description: Logging task relationships in Celery


code: name, ignored = 'bida.bombu.foo'.split('.', 1)

rawDescription: Reason for Assignment to " _ "

description: Reason for Assignment to " _ "


code:
cols = pd.MultiIndex.from_tuples([(x, y) for x in ['start', 'end'] for y in ['year', 'mon', 'day']])
pat = r'(\d*)-(\d*)-(\d*) - (\d*)-(\d*)-(\d*)'
xdf = pd.DataFrame(df.date.str.extract(pat).values, columns=cols, dtype=np.int64)
xdf

rawDescription: Parsing strings of date ranges in Pandas


code:
for item in submissions:
   os.system('youtube-dl -o {}.%(ext)s {}'.format(item.title, item.url))

rawDescription: YouTube-dl to download and name videos from Reddit


rawDescription: Linked List Operations

description: Linked List Operations


rawDescription: Is fortran-like print in python possible?


code:
def is_duplicate(l1, l2):
    return not any(a != b for a, b in zip(l1, l2))

#remove duplicates

for i in range(len(li)):
    j = i + 1
    for x in li[i + 1:]:
        if is_duplicate(li[i], x):
            li.pop(j)
        j += 1

rawDescription: How to add objects from different rows of a Python list?

description: Add objects from different rows of a Python list


code:
def auto_update_ratings(amounts, assessment_entries_qs, lowest_rating=-1):
    # assessment_entries_qs is an unevaluated QuerySet
    # from your calling code, it would probably generate a query like this:
    # SELECT * FROM assessments ORDER BY RANDOM()
    start = 0
    rating = lowest_rating
    ids = assessment_entries_qs.values_list('id', flat=True)
    # ids is a ValueQuerySet that adds "SELECT id"
    # to the query that assessment_entries_qs would generate.
    # So ids is now something like:
    # SELECT id FROM assessments ORDER BY RANDOM()

    # we omit the loop

    for amount in amounts:
        end_mark = start + amount
        entries = ids[start:end_mark]
        # entries is now another QuerySet with a LIMIT clause added:
        # SELECT id FROM assessments ORDER BY RANDOM() LIMIT start,(start+end_mark)
        # When filter() gets a QuerySet, it adds a subquery
        a = assessment_entries_qs.filter(id__in=entries).update(rating=rating)
        # FINALLY, we now actually EXECUTE a query which is something like this:
        # UPDATE assessments SET rating=? WHERE id IN
        # (SELECT id FROM assessments ORDER BY RANDOM() LIMIT start,(start+end_mark))
        start = end_mark
        rating += 1

rawDescription: Why/how does iterating over a list and calling 'pass' each time fix this function?


code:
# urls.py
urlpatterns = [
    url(r'^(?P<model>\w+)/(?P<id>[0-9]+)$', views.BaseView.as_view(), name='view_base'),
]

# views.py
class BaseView(View):

    type_map = {
        'xxxx': X,
        'yyyy': Y,
    }

    def dispatch(self, request, *args, **kwargs):
        model = kwargs.get('model')
        self.type = self.type_map.get(model)
        if self.type is None:
            raise Http404
        return super(BaseView, self).dispatch(request, *args, **kwargs)

rawDescription: Python reusing views and forms with model inheritance


rawDescription: hight resolution Reanalysis data

description: Hight resolution Reanalysis data


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

# define colors
grey1 = (0.5, 0.5, 0.5)
grey2 = (0.7, 0.7, 0.7)

plt.rcParams['lines.color'] = grey2
plt.rcParams['xtick.color'] = grey2
plt.rcParams['ytick.color'] = grey2
plt.rcParams['axes.labelcolor'] = grey2
plt.rcParams['axes.edgecolor'] = grey2

# the rest of your code goes here ....

rawDescription: How to adjust color of certain features for figure with transparent background

description: Adjust color of certain features for figure with transparent background


code:
import shelve

data = shelve.open("savegame")

rawDescription: Basic savegames for a text based game

description: Basic savegames for a text based game


code:
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)

rawDescription: Python Google Calendar API memory issue

description: Python Google Calendar API memory issue


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

def main():
    # Generate some random data
    nx, ny = 100, 100
    data = np.random.random((ny,nx))

    # Define a circle in the center of the data with a radius of 20 pixels
    radius = 20
    center_x = nx // 2
    center_y = ny // 2

    plot_masked(data, center_x, center_y, radius)
    plot_clipped(data, center_x, center_y, radius)
    plt.show()

def plot_masked(data, center_x, center_y, radius):
    """Plots the image masked outside of a circle using masked arrays"""
    # Calculate the distance from the center of the circle
    ny, nx = data.shape
    ix, iy = np.meshgrid(np.arange(nx), np.arange(ny))
    distance = np.sqrt((ix - center_x)**2 + (iy - center_y)**2)

    # Mask portions of the data array outside of the circle
    data = np.ma.masked_where(distance > radius, data)

    # Plot
    plt.figure()
    plt.imshow(data)
    plt.title('Masked Array')

def plot_clipped(data, center_x, center_y, radius):
    """Plots the image clipped outside of a circle by using a clip path"""
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # Make a circle
    circ = patches.Circle((center_x, center_y), radius, facecolor='none')
    ax.add_patch(circ) # Plot the outline

    # Plot the clipped image
    im = ax.imshow(data, clip_path=circ, clip_on=True)

    plt.title('Clipped Array')

main()

rawDescription: Fill OUTSIDE of polygon | Mask array where indicies are beyond a circular boundary?


code:
class C(metaclass=MyMetaClass, myArg1=1, myArg2=2):
  pass

rawDescription: Metaclass Arguments for Python 3.x

description: Metaclass Arguments for Python 3.x


code:
self.about_menu = wx.Menu()  # or whatever inherited class you have
self.Bind(wx.EVT_MENU_OPEN, self.on_menu_open)

rawDescription: Bind event to wx.Menu() instead of to the menu item in wxPython


code:
@dajaxice_register
def disable_button(request, song_id):
    update_votes(song_id)
    #disable the buttons
    return #whatever

rawDescription: Getting object value for AJAX call using Dajaxice


code:
with ShelveManager('/tmp/shelve.dat') as manager:
    manager.load(...)
    manager.store(...)

rawDescription: Does linux disk buffer cache make python cPickle more efficient than shelve?


code:
singleitem, = mylist
# Identical in behavior (byte code produced is the same),
# but arguably more readable since a lone trailing comma could be missed:
[singleitem] = mylist

rawDescription: Getting only element from a single-element list in Python?


code:
def __init__(self, master):
    ...
    self.variables = variables = []
    for text, value in OPTIONS:
        var = tk.StringVar()
        variables.append(var)
        tk.Checkbutton(self.typeFrame, text=text, variable=var,
                       onvalue=text, offvalue='').pack(anchor = 'w')
    ...

def exit(self):
    self.type_integration = ','.join(v.get() for v in self.variables if v.get())
    self.master.destroy()

rawDescription: Using tkinter I want to be able to get two inputs from the user using the same radiobuttons


code:
import itertools

def readWords(file_object):
    word = ""
    for ch in itertools.takewhile(lambda c: bool(c), itertools.imap(file_object.read, itertools.repeat(1))):
        if ch.isspace():
            if word: # In case of multiple spaces
                yield word
                word = ""
            continue
        word += ch
    if word:
        yield word # Handles last word before EOF

rawDescription: How to input a line word by word in Python?

description: Input a line word by word in Python


code:
print(sorted(names))
# ['IMG0.png', 'IMG3.png', 'img1.png', 'img10.png', 'img12.png', 'img2.png']

rawDescription: python equivalent to php natcasesort

description: Python equivalent to php natcasesort


code:
def f(x):
  return sin(x)*cos(x)

rawDescription: Use Boost-Python to calculate derivative of function defined in python


code:
from itertools import chain

y.extend(chain.from_iterable(z.splitlines() for z in ('a', 'b\nc', 'd')))

rawDescription: Can this generator expression be modified to match for loop result?


rawDescription: Find all words placed on a Scrabble board


code:
import json
weird_json = '{"x": 1, "x": 2, "x": 3}'
x = json.loads(weird_json)
x
y = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
y

rawDescription: Return data from html/js to python

description: Return data from html/js to python


code:
import json
textValue = '''
var page_data = {
   "default_sku" : "SKU12345",
   "get_together" : {
      "imageLargeURL" : "http://null.null/pictures/large.jpg",
      "URL" : "http://null.null/index.tmpl",
      "name" : "Paints",
      "description" : "Here is a description and it works pretty well",
      "canFavorite" : 1,
      "id" : 1234,
      "type" : 2,
      "category" : "faded",
      "imageThumbnailURL" : "http://null.null/small9.jpg"
   }
};
'''
jsonValue = '{%s}' % (textValue.split('{', 1)[1].rsplit('}', 1)[0],)
value = json.loads(jsonValue)
value
import pprint
pprint.pprint(value)

rawDescription: Parsing variable data out of a javascript tag using python


code:
import struct
year, month, day = struct.unpack('>HBB', "\x07\xdb\x0c\x01")

rawDescription: How to unpack binary formatted dates in python?

description: Unpack binary formatted dates in python


rawDescription: Python - Check if list of lists of lists contains a specific list


code:
import json

# open your jsonfile in read mode
with open('jsonfile') as f:
    # read the data as a dict use json.load()
    jsondata = json.load(f)

# add a new item into the dict
jsondata['players']['player_two'] = {'email': 'kevin@example.com', 'name': 'Kevin', 'age': '0'}

# open that file in write mode
with open('jsonfile', 'w') as f:
    # write the data into that file
    json.dump(jsondata, f, indent=4, sort_keys=True)

rawDescription: Store new JSON data to existing file in python


code:
# ....
while a:
    pygame.event.pump()
    keys2 = pygame.key.get_pressed()
    # do something ...

rawDescription: Pygame nested while loop: [Errno 10054] An existing connection was forcibly closed by the remote host


code:
import codecs
m = 0
f_out = codecs.open('C:/out_file.ini', "w", encoding='latin-1')
with codecs.open('C:/in_file.ini', encoding='latin-1') as f_in:
    lines = list(line for line in (l.strip() for l in f_in) if line)
    for i in lines:
        f_out.write('alm_siem_alarm' + str(m) + '=' + i.split(' "')[1].upper() + '\n')
        m = m + 1

f_in.close()
f_out.close()

rawDescription: Reading a file and uppercasing non-ascii characters before saving the content to other file


code:
H = G.subgraph(p.keys())
nx.draw_networkx_edges(H, pos, alpha = 0.4)
nx.draw_networkx_nodes(H, pos, node_size = 80, node_color = node_color,
                       cmap = plt.get_cmap('Reds_r'))

rawDescription: Networkx Random Geometric Graph limit nodes within radius r


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.clock import mainthread

NUMBER_OF_BUTTONS = 5

class MapScreen(Screen):

    @mainthread
    def on_enter(self):
        for i in xrange(NUMBER_OF_BUTTONS):
            button = Button(text="B_" + str(i))
            self.ids.grid.add_widget(button)

class Test(App):
    pass

Test().run()

rawDescription: How do I add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language?

description: Add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language


code:
data = [['dog', 'a'], ['mouse', 'a'], ['dog', 'b'], ['mouse', 'c'], ['dog', 'c']]
animals = {}

for animal, letter in data:
    animals.setdefault(animal, {})[letter] = 0

rawDescription: more on creating dictionaries of dictionaries

description: More on creating dictionaries of dictionaries


code:
5
True
'test'

rawDescription: How do I take output after giving the input in python?

description: Take output after giving the input in python


code: ''.join(c for c in str1 if c not in str2)

rawDescription: Filtering Characters from a String

description: Filtering Characters from a String


code:
e        = 2.71                                                   # SET e
y_series = range( 0, 16 )                                         # GEN y_series
x_series = [ 1000 * e**( -9.81 * y / 78351 ) for y in y_series ]  # GEN x_series

rawDescription: Is it plausible to plug in equations for series in python?


code:
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
      for row in array]))

rawDescription: How to store and print a list of numbers in matrix form(python)

description: Store and print a list of numbers in matrix form(python)


rawDescription: Python: Replacing NaN or MEAN instead of a -999 value in an array


code:
mylist=[[1,3,4],[3,5,6],[9,0,8],[8,6,3],[8,2,5]]
with open('tem2.txt', 'w') as f:
    f.write(repr(mylist))
with open('tem2.txt') as f:
    list2 = eval(f.read())
print(list2 == mylist)
# True

rawDescription: How to write a list of lists to a txt file in python without using pickle or other alternatives?

description: Write a list of lists to a txt file in python without using pickle or other alternatives


code:
b'\x00foo'
b'\x01bar'
b'\x02bazq'

rawDescription: Increment efficiently over a sequence of integers in byte representation


code:
import json

def my_view(request):
    # ...
    json_d = dict(...)
    return json.dumps(json_d)

rawDescription: python json boolean to lowercase string

description: Python json boolean to lowercase string


code:
assert sorted(['Silver', 'Bronze', 'Gold'], key=custom_key) == ['Gold', 'Silver', 'Bronze']
assert sorted([['Silver', 2], ['Silver', 1], ['Gold', 1]], key=custom_key) == [['Gold', 1], ['Silver', 1], ['Silver', 2]]
assert sorted([(2, 'Gold'), (2, 'Bronze'), (1, 'Gold')], key=custom_key) == [(1, 'Gold'), (2, 'Gold'), (2, 'Bronze')]
assert sorted([('Silver', 'Bronze'), ('Gold', 'Bronze'), ('Silver', 'Gold')], key=custom_key) == [('Gold', 'Bronze'), ('Silver', 'Gold'), ('Silver', 'Bronze')]

rawDescription: Python sorting key function supporting tuples and lists


code:
import ast
from collections import Counter

tree = ast.parse('''
"""
Author: Nobody
"""

def foo(*args, **kwargs):
    for i in range(10):
        if i != 2**2:
            print(i * 2 * 3 * 2)

def bar():
    pass
''')

counts = Counter(node.__class__ for node in ast.walk(tree))

print('The docstring says:', repr(ast.get_docstring(tree)))
print('You have', counts[ast.Mult], 'multiplication signs.')
print('You have', counts[ast.FunctionDef], 'function definitions.')
print('You have', counts[ast.If], 'if statements.')

rawDescription: returning specifics from a file, python

description: Returning specifics from a file, python


rawDescription: Python: adding value from list of lists

description: Python: adding value from list of lists


code:
class MyWebView(QWebView):
    def __init__(self, parent, xpath_widget):
        #QWebView.__init__(parent)
        QWebView.__init__(self, parent)
        #or: super(MyWebView, self).__init__(parent)

        self.xpath_widget = xpath_widget

    def contextMenuEvent(self,event):
        menu = QMenu()
        self.actionShowXpath = menu.addAction("Show Xpath")

        #QObject.connect(
        #    self.actionShowXpath,
        #    SIGNAL("triggered()"),
        #    self,SLOT("slotshowxpath()")
        #)

        self.actionShowXpath.triggered.connect(self.show_xpath)

        menu.exec_(self.mapToGlobal(QPoint(event.x(),event.y())))

    #@pyqtSlot()
    def show_xpath(self):
        frame = ...
        frame.evaluateJavaScript("var abc = function get()");
        result = frame.evaluateJavaScript("abc").toString()

        #some code code to put result in QLineEdit Widget**
        self.xpath_widget.setText(result)

rawDescription: Return value from PYQt slot of QwebView to main window widget (PYQt python)


code:
import wx

class BrightnessController(wx.Frame):
    def __init__(self, parent, title):
        super(BrightnessController, self).__init__(parent, title=title,
            size=(330, 100), style=wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX)

        self.Show()

if __name__ == '__main__':
    app = wx.App()
    BrightnessController(None, title='Brightness Controller')
    app.MainLoop()

rawDescription: How to disable resizing in wx python widget?

description: Disable resizing in wx python widget


code:
import os
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_dna

sequences = ['ctnngtggaccgacaagaacagtttcgaatcggaagcttgcttaacgtag',
             'ctaagtggactgacaggaactgtttcgaatcggaagcttgcttaacgtag',
             'ctacgtggaccgacaagaacagtttcgactcggaagcttgcttaacgtag',
             'ctacgtggaccgacaagaacagtttcgactcggaagcttgcttaacgccg',
             'ctgtgtggancgacaaggacagttccaaatcggaagcttgcttaacacag']

my_records = [SeqRecord(Seq(sequence, generic_dna),
              id='Species_{}'.format(letter), description='Species_{}'.format(letter))
              for sequence, letter in zip(sequences, 'ABCDE')]

root_dir = r"C:\Users\BioGeek\Documents\temp"
filename = 'my_sequences'
fasta_path = os.path.join(root_dir, '{}.fasta'.format(filename))

SeqIO.write(my_records, fasta_path, "fasta")

rawDescription: Create a Dendogram from Genome

description: Create a Dendogram from Genome


code:
# Setup output array and put 1s at places indexed by row and column indices.
# Here, anArray would be the column indices and [0,1,....N-1] would be the row indices
resultArray = np.zeros((N,M),int)
resultArray[np.arange(N),anArray] = 1

rawDescription: How to convert a series of index/category, into a classification array

description: Convert a series of index/category, into a classification array


code:
for x in something:
    do_something

rawDescription: how to feed string to pyparsing line by line?

description: Feed string to pyparsing line by line


code: cPickle.dump(instance, open(filename, 'wb'), HIGHEST_PROTOCOL)

rawDescription: serialize class instance for comparison

description: Serialize class instance for comparison


code:
def f():
    import B
    import inspect

    functions=inspect.getmembers(B,inspect.isfunction)

rawDescription: How can A.f defined in module A get list of function defined in B if A.f was called from B


code: from test1 import test1

rawDescription: Variable in other python file, how to load in?


code:
credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)

service = build('drive', 'v2', http=http)

files = service.files().list().execute()

rawDescription: Make calls to Drive API inside of a Google App Engine Cloud Endpoints


code:
a = np.random.rand(48, 90, 144)
b = np.random.rand(90,144)
np.testing.assert_almost_equal(np.average(a.reshape(48, -1),
                                          weights=b.ravel(), axis=1),
                               np.array([np.average(a[i],
                                                    weights=b) for i in range(48)]))

rawDescription: Numpy averaging with multi-dimensional weights along an axis


code:
# Get sliding blocks of shape same as match_array from field_array into columns
# Then, compare them with a column vector version of match array.
col_match = im2col(field_array,match_array.shape) == match_array.ravel()[:,None]

# Shape of output array that has field_array compared against a sliding match_array
out_shape = np.asarray(field_array.shape) - np.asarray(match_array.shape) + 1

# Now, see if all elements in a column are ONES and reshape to out_shape.
# Finally, find the position of TRUE indices
R,C = np.where(col_match.all(0).reshape(out_shape))

rawDescription: How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?

description: Check if one two-dimensional NumPy array contains a specific pattern of values inside it


first_name: John

last_name: Lennon

first_name: Hattori

last_name: Hanzo

super_power: fearless tactics

rawDescription: Multi table inheritance in django

description: Multi table inheritance in django


code: [{'1': 'value', '3': 'fifth_value', '2': 'third_value'}, {'1': 'second_value', '2': 'fourth_value'}]

rawDescription: Create a list of unique keys in Python

description: Create a list of unique keys in Python


code:
import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()

rawDescription: Reading the target of a .lnk file in Python?


code:
foo = []
foo.append('bar')
foo.append('spam')
foo

rawDescription: Creating an increasing list in Python

description: Creating an increasing list in Python


code: name, weeks_worked, weekly_payment = filecontent

rawDescription: remove specific characters from text file string

description: Remove specific characters from text file string


code:
use_function = "sqr"
function = functions[use_function]
for i in range(0, 100):
    a_list[i] = function(i)

rawDescription: Is there a way to avoid useless if-else clauses inside a loop when selectign from multiple functions?


rawDescription: Operation on column based on column name pandas


code:
def printOutput(start, end, makeList):
  if start == end == None:
      return
  else:
      outputFile = open('out'+uniprotID+'.txt','w')#file for result output
      for inRange in makeList[start:end+1]:
          outputFile.write(inRange)

rawDescription: file output error with correct values

description: File output error with correct values


rawDescription: Combining matplotlib quiver and elipses doesn't work


code:
df.columns = range(3, 9)
df

rawDescription: Convert datetime index in pandas to separate columns


rawDescription: How do I extract the labels from a MultiIndex?

description: Extract the labels from a MultiIndex


code:
from nltk.stem.snowball import FrenchStemmer
stemmer = FrenchStemmer
stemmer.stem('voudrais')
stemmer.stem('animaux')
stemmer.stem('yeux')
stemmer.stem('dors')
stemmer.stem('couvre')

rawDescription: Lemmatize French text

description: Lemmatize French text


code:
from collections import defaultdict
d1, d2 = defaultdict(list) , defaultdict(list)
for pxa in marker_array:
    d1[pxa[1]].extend(pxa[:1])
    d2[pxa[1]].extend(pxa[2:])

res = [[' '.join(d1[x]), x, ' '.join(d2[x])] for x in sorted(d1)]

rawDescription: Merge nested list items based on a repeating value


rawDescription: python list controlled increment

description: Python list controlled increment


rawDescription: python how to change element in nested list

description: Python how to change element in nested list


code: Cordi1 = [[int(i) for i in line.split()] for line in data]

rawDescription: list comprehension replace for loop in 2D matrix

description: List comprehension replace for loop in 2D matrix


code:
def calc_slow(L1, L2):
    result = 0
    for n, m in itertools.product(L1, L2):
        result += np.dot(n, m)
    return result

rawDescription: efficient algorithm instead of looping

description: Efficient algorithm instead of looping


code:
import subprocess
import os

app=[
    "ap01.ext",
    "-server",
    "-filename=c:/test.VS",
    "-display=1"
]

os.chdir('"C:/bin/')
subprocess.call(app, shell=True)

rawDescription: python run CMD command with options

description: Python run CMD command with options


code:
df.index.name = 'newhead'
df.reset_index(inplace=True)

rawDescription: Convert row names into a column in Pandas


code:
def start(request):
    survey_urls = ['/surveyone/', '/surveytwo/', '/surveythree/']
    survey_url = random.choice(surveys)
    return render(request, 'start.html', {'survey_url': survey_url})

rawDescription: Django: How to assign users one of three URLS at random?


rawDescription: concat two data frames using pandas

description: Concat two data frames using pandas


code: map(lambda c: c(), classArray)

rawDescription: How to use "map" function in Python? (How to rewrite a for loop?)

description: Use "map" function in Python? (How to rewrite a for loop?)


rawDescription: Parsing a message notification index in python using regular expressions


code:
import inspect
import re
def underscore_to_camel(modinput,modadd):
    """
       Find all functions in modinput and add them to modadd.
       In modadd, all the functions will be converted from name_with_underscore
       to camelCase
    """
    functions = inspect.getmembers(modinput,inspect.isfunction)
    for f in functions:
        camel_name = re.sub(r'_.',lambda x: x.group()[1].upper(),f.__name__)
        setattr(modadd,camel_name,f)

rawDescription: Renaming of functions with preservation of backward compatibility


code: np.diff(ts.index.year) != 0

rawDescription: Pandas Time Series - add a value to the first value in each year


code: init_p = numpy.array((init_a))

rawDescription: How to force zero interception in linear regression?

description: Force zero interception in linear regression


code: ttime_inds = np.around((tmax + origin_times[:,None] + ttable) / dt).astype(int)

rawDescription: Vectorizing for loops in python with numpy multidimensional arrays


code:
def isprime(n):
    if n==1:
        return None
    if n==2:
        return 2
    for i in range(3,int(math.sqrt(n))+1,2):
        if n%i==0:
            return None
    return n

rawDescription: removing "none" result from the function which prints the prime number

description: Removing "none" result from the function which prints the prime number


code: print((lambda a : a*2)(21))

rawDescription: Semicolon alternative in python

description: Semicolon alternative in python


code:
import botocore.session
client = botocore.session.Session().create_client('elasticache', verify=False)

rawDescription: How to view Boto3 HTTPS request string

description: View Boto3 HTTPS request string


code:
chunks = [foo[i:i+30] for i in range(0, len(foo), 30)]
chunks[0]
chunks[-1]

rawDescription: Chunking dates into mangeable groups w/ python


code:
from os import system, remove
system('gnuplot tmp.gp')
remove('tmp.gp')

rawDescription: Calling gnuplot from python

description: Calling gnuplot from python


rawDescription: Hierarchical index multi index containing edge values. Rearrange it?


rawDescription: python functions for beginners

description: Python functions for beginners


code:
import json

def record_print_format(record):
    return "{Year:4} {Id:6} {Gender:6} {Firstname:>20} {Lastname:<20} {Course:6}".format(**record)

def show_records(records, format_fn=record_print_format):
    for r in records:
        print(format_fn(r))
    num = len(records)
    print("{} records:".format(num))

def filter_records(records, field, value):
    return [r for r in records if r[field] == value]

def match_year(records, year):
    return filter_records(records, "Year", year)

def match_gender(records, gender):
    return filter_records(records, "Gender", gender)

def match_course(records, course):
    return filter_records(records, "Course", course)

def main():
    with open("student_list.json") as studentfile:
        all_students = json.load(studentfile)
        records = all_students

    while True:
        print("1: Filter by year")
        print("2: Filter by gender")
        print("3: Filter by course")
        print("8: Show results")
        print("9: Clear filters")
        print("0: Exit")

        option = input("Please pick an option: ").strip()

        if option == "1":
            year = input("Which year? ").strip()
            records = match_year(records, year)
        elif option == "2":
            gender = input("Which gender? [Male|Female] ").strip()
            records = match_gender(records, gender)
        elif option == "3":
            course = input("Which course? ").strip()
            records = match_course(records, course)
        elif option == "8":
            show_records(records)
        elif option == "9":
            records = all_students
        elif option == "0":
            print("Goodbye!")
            break
        else:
            print("I don't recognize that option.")

if __name__=="__main__":
    main()

rawDescription: Is this code simplified? Should I use more functions?


rawDescription: How to create Python function that sums values from 7 daily files into one weekly file?

description: Create Python function that sums values from 7 daily files into one weekly file


rawDescription: print python list of lists into string

description: Print python list of lists into string


code: new_len = 2

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
import re
s = " [[this is a page]]    goo hghg"
m = re.sub(r'\s(?=[^\[\]]*]])', "_", s)
m

rawDescription: Regex to select and replace spaces inside double brackets


code:
with open('file') as f:
    l = f.read().splitlines()
l
l = [l[0]] + [l[1][1:]] + [l[2][2:]]  # remove 'a' from `l[1]` and `zy` from `l[2]`
l
list(zip(*l))  # zip them
[''.join(i) for i in list(zip(*l))]  # also join them

rawDescription: Reading from a file diagonally and having the diagonal characters create a list


code:
class ProductForm(Form):
    name = StringField('Content Name', validators = [DataRequired()])
    url = URLField(validators=[url()])
    content = TextAreaField('Content Summary', validators = [DataRequired(),Length(max=140)])
    category = SelectField("Choose a category that your content fits in.", choices=CATEGORIES,coerce=int)

rawDescription: WTForm does not entirely repopulate form data upon editing a model


code: re.sub(regex, ",", original_string)

rawDescription: python regex to split by comma or space (but leave strings as it is)

description: Python regex to split by comma or space (but leave strings as it is)


code:
import ctypes
dll = ctypes.cdll.LoadLibrary('c/test.dll')
print(dll.test())

rawDescription: python unmanaged dll call, fails on win32 FindWindow api with Access Violation

description: Python unmanaged dll call, fails on win32 FindWindow api with Access Violation


code: d = [num if num else 0 for num in d]

rawDescription: Only nonzero values Python list

description: Only nonzero values Python list


code:
def separate(filename):
    all_integers = []
    all_strings = []
    with open(filename) as myfile:
        for line in myfile:
            for item in line.split(' '):
                try:
                    # Try converting the item to an integer
                    value = int(item, 10)
                    all_integers.append(value)
                except ValueError:
                    # if it fails, it's a string.
                    all_strings.append(item)
    return all_integers, all_strings

rawDescription: How to read a text file into separate lists python

description: Read a text file into separate lists python


code:
items = zip(*time_list)
x_val, y_val = next(items),next(items)

rawDescription: List index out of range when using more than one at the same time


code:
sm = tf.nn.softmax(x)
ce = cross_entropy(sm)

rawDescription: difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits

description: Difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits


code:
import re

expression = "(?P<id>\w+?)_INIT\s*?=.*?'h(?P<hexValue>[0-9a-fA-F]*)"
regex = re.compile(expression)

def getIdAndValueFromInitLine(line):
  mm = regex.search(line)
  if mm == None:
    return None # Not the ..._INIT parameter or line was empty or other mismatch happened
  else:
    return (mm.groupdict()["id"], "0x" + mm.groupdict()["hexValue"])

rawDescription: Splitting lines in a file into string and hex and do operations on the hex values


code:
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, Parameter, report_fit

# generate some data with noise
xData = np.linspace(0.01, 100., 50.)
aOrg = 0.08
Norg = 10.5
yData = Norg * xData ** (-aOrg) + np.random.normal(0, 0.5, len(xData))
plt.plot(xData, yData, 'bo')
plt.show()

# transform data so that we can use a linear fit
lx = np.log(xData)
ly = np.log(yData)
plt.plot(lx, ly, 'bo')
plt.show()

def decay(params, x, data):

    lN = params['lN'].value
    a = params['a'].value

    # our linear model
    model = a * x + lN
    return model - data # that's what you want to minimize

# create a set of Parameters
params = Parameters()
params.add('lN', value=np.log(5.5), min=0.01, max=100)  # value is the initial value
params.add('a', value=-0.5, min=-1, max=-0.001)  # min, max define parameter bounds

# do fit, here with leastsq model
result = minimize(decay, params, args=(lx, ly))

# write error report
report_fit(params)

# plot data
xnew = np.linspace(0., 100., 5000.)
# plot the data
plt.plot(xData, yData, 'bo')
plt.plot(xnew, np.exp(result.values['lN']) * xnew ** (result.values['a']), 'r')
plt.show()

rawDescription: SciPy Curve Fit Fails Power Law

description: SciPy Curve Fit Fails Power Law


rawDescription: Pythonic way to get list element when expectation is that list contains only a single element?


code:
def getMetaData(request):
    if is_invalid(request.POST):
        return redirect_url
    else:
        return None

rawDescription: Django wont redirect me on another view from view


code:
years, months, days = the_string.split('-')
days, time = days.split(' ')
time = time.split(':')

rawDescription: Splitting a string @ once using different seps


code: data.reshape(2, 56, 40).swapaxes(0,2)

rawDescription: Numpy: Reshaping this array in the least number of operations


code:
Serie
Threads
Socket
Kloksnelheid

rawDescription: Python Crawler Beatifulsoup decompose() function


rawDescription: How to construct a matrix of all possible differences of a vector in numpy

description: Construct a matrix of all possible differences of a vector in numpy


code:
import timeit
somelist = range(10000)
k = 1
timeit.timeit('sum(somelist[:k])', 'from __main__ import somelist, k')
timeit.timeit('sum(islice(somelist, k))', 'from __main__ import somelist, k; from itertools import islice')
k = len(somelist) // 2
k = len(somelist) // 2
timeit.timeit('sum(somelist[:k])', 'from __main__ import somelist, k')
timeit.timeit('sum(islice(somelist, k))', 'from __main__ import somelist, k; from itertools import islice')

rawDescription: Python oneliners: how to sum the first k elements of a list?


code:
explicitSystemAction = System.Action[IronPythonDelegates.Camera, System.Single](camActionPy)
IronPythonDelegates.CameraAnimation(explicitSystemAction);

rawDescription: How to pass a lambda expression to a C# constructor from an IronPython script?

description: Pass a lambda expression to a C# constructor from an IronPython script


code:
class NameDescriptor(object):

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

    def __get__(self, obj, objtype):
        return getattr(obj, self.key)

    def __set__(self, obj, val):
        setattr(obj, self.key, val.capitalize())

class User(object):

    firstname = NameDescriptor('_firstname')
    lastname = NameDescriptor('_lastname')

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

rawDescription: Why do we need property in Python?

description: Why do we need property in Python


code:
SOCIAL_AUTH_FACEBOOK_SCOPE = [
    'email',
    'user_friends',
    'friends_location',
]

rawDescription: How to retrieve Facebook friend's information with Python-Social-auth and Django

description: Retrieve Facebook friend's information with Python-Social-auth and Django


code: list1[:] = [x for x in list1 if os.path.splitext(x)[0] not in set2]

rawDescription: Python list.remove(x) 2.7.5

description: Python list.remove(x) 2.7.5


code:
import tkinter as tk
from twisted.internet import reactor

import tksupport

root = tk.Tk()

# Install the Reactor support
tksupport.install(root)

# at this point build Tk app as usual using the root object,
# and start the program with "reactor.run()", and stop it
# with "reactor.stop()".

rawDescription: Threading with Twisted with Tkinter

description: Threading with Twisted with Tkinter


code:
def bitsToFloat(b):
    s = struct.pack('>l', b)
    return struct.unpack('>f', s)[0]
bitsToFloat(0x432d5000)

rawDescription: Get the "bits" of a float in Python?

description: Get the "bits" of a float in Python


code:
def rfind_imp(s, t):
    fpos = -1
    while True:
         pos = s.find(t, fpos + 1)
         if pos == -1:
            return fpos
         fpos = pos

rawDescription: rfind implementation using find

description: Rfind implementation using find


code:
import numpy as NP
my_data = NP.random.random_integers(0, 9, 9).reshape(3, 3)
new_col = NP.array((5, 5, 5)).reshape(3, 1)
res = NP.append(my_data, new_col, axis=1)

rawDescription: Growing matrices columnwise in NumPy

description: Growing matrices columnwise in NumPy


rawDescription: python union of multiple ranges

description: Python union of multiple ranges


code:
def format_10Kth_time(time, pos=None):
    mins     = time // (10000 * 60)
    secs     = (time - (mins * 10000 * 60)) // (10000)
    fracsecs = time % 10000
    return "%d:%02d.%d" % (mins, secs, fracsecs)

rawDescription: How to chart times (mm:ss) in Matplotlib (formatting output values)

description: Chart times (mm:ss) in Matplotlib (formatting output values)


code:
# This SConstruct does nothing more than load the SConscript in this dir
# The Environment() is created in the SConstruct script
# This dir can be build standalone by executing scons here, or together
# by executing scons in the parent directory
env = Environment()
SConscript('SConscript', exports = ['env'])

rawDescription: Real Hierarchical Builds with SCons?

description: Real Hierarchical Builds with SCons


code:
def add_keyword():
    keywords = []
    for word in search_kw:
        keywords.append(word + keyword)
    return keywords

search_kw = add_keyword()
text_file = open("/Users/home/Projects/keyword_file.txt", "w")
text_file.write("%s" % search_kw)
text_file.close()

rawDescription: Trouble Getting a Function Result Written to External .txt Using Python


code:
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

rawDescription: Evaluating call expression

description: Evaluating call expression


rawDescription: Getting data from a comparison matrix in python


code:
def show_message_box(data):
    GUI.run(str("RECV'd message: %s" % data))
def handler_factory(callback):
    def createHandler(*args, **keys):
        return ThreadedTCPRequestHandler(callback, *args, **keys)
    return createHandler
server = ThreadedTCPServer((HOST, PORT), handler_factory(show_message_box))

rawDescription: Proper way to add functionality to handle() in a python TCP Server?


code:
import ctypes

ob_refcnt_p = ctypes.POINTER(ctypes.c_ssize_t)

class GIL:
    acquire = staticmethod(ctypes.pythonapi.PyGILState_Ensure)
    release = staticmethod(ctypes.pythonapi.PyGILState_Release)

class Ref:
    dec = staticmethod(ctypes.pythonapi.Py_DecRef)
    inc = staticmethod(ctypes.pythonapi.Py_IncRef)

class Tuple:
    setitem = staticmethod(ctypes.pythonapi.PyTuple_SetItem)
    @classmethod
    def self_reference(cls, array, index):
        if not isinstance(array, tuple):
            raise TypeError('array must be a tuple')
        if not isinstance(index, int):
            raise TypeError('index must be an int')
        if not 0 <= index < len(array):
            raise ValueError('index is out of range')
        GIL.acquire()
        try:
            obj = ctypes.py_object(array)
            ob_refcnt = ctypes.cast(id(array), ob_refcnt_p).contents.value
            for _ in range(ob_refcnt - 1):
                Ref.dec(obj)
            if cls.setitem(obj, ctypes.c_ssize_t(index), obj):
                raise SystemError('PyTuple_SetItem was not successful')
            for _ in range(ob_refcnt):
                Ref.inc(obj)
        finally:
            GIL.release()

rawDescription: Building Self-Referencing Tuples

description: Building Self-Referencing Tuples


code:
def time_since(self):
    time_since = timezone.now() - self.date_opened
    out = [time_since.days, time_since.seconds//3600, (time_since.seconds//60)%60]

    # As per Aamir Adnan's suggestion check whether day or days is applicable
    if x[0] == 1:
        return '{:d} day, {:d}:{:d}'.format(*x)
    else:
        return '{:d} days, {:d}:{:d}'.format(*x)

rawDescription: Transform multiple return values to a custom string in default django admin interface


code:
class Product(Form):
    product = TextField('name')
    category = SelectField('category', choices=[(1,'one'),(2,'two')])

# create instance with predefined value:
form1 = Product(category=2)
# form1.product == <input id="product" name="product" type="text" value="">
# form1.category == <select id="category" name="category">
#                     <option value="1">one</option>
#                     <option selected value="2">two</option>
#                   </select>
# from1.product.data == None
# form1.category.data == 2

# create own form if it need many times:
Product2 = type('Product2', (Product,), {
    'category': SelectField('category', default=2, choices=[(1,'one'),(2,'two')])
})
form2 = Product2()
# form2.product == <input id="product" name="product" type="text" value="">
# form2.category == <select id="category" name="category">
#                     <option value="1">one</option>
#                     <option selected value="2">two</option>
#                   </select>
# from2.product.data == None
# form2.category.data == 2

rawDescription: Setting a default value in the selectfield, using wtforms and flask


code:
from collections import defaultdict

with open("yourfile") as f:
    groups = defaultdict(list)
    for line in f:
        groups[line.rsplit("_r",1)[1]].append(line.rstrip())

from pprint import pprint as pp

pp(groups.values())

rawDescription: Python: Group a list of file names according to common name identifier


code:
import re
from simplejson import JSONDecoder
from simplejson.decoder import JSONDecodeError
#from cherrypy._cperror import HTTPError
from decimal import Decimal

class ValidationException(Exception):
    pass

class ArgumentException(ValidationException):
    pass

class MandatoryException(ValidationException):
    pass

class DenialException(ValidationException):
    pass

class ParameterTypeException(ValidationException):
    pass

class ParameterValueException(ValidationException):
    pass

def validate_parameters(args,kwargs,required_args=None
                                     ,deny_args=None
                                     ,requires=None
                                     ,deny=None
                                     ,deny_except=None
                                     ,types=None
                                     ,values=None
                                     ,filter=None
                                     ,json_decode=None
                                     ,defaults=None):
    """Validates input parameters of a callable

    @param required_arguments:   list of types, Required argument's types  & counts in order
    @param deny_args             string ,regex pattern, if any argument matches with the pattern, exception raises
    @param requires:             list of fields to check for mandatory
    @param deny:                 string ,regex pattern, if any parameter matches with the pattern, exception raises
    @param deny_except:          string ,regex pattern for excluding fields from deny
    @param types:                dict of key:name and value:type to check for types, if mismatch it will be raises exception
    @param values:               dict of key:name and value:regex pattern to check the values, & fire exception if mismatch
    @param filter:               string ,regex pattern of parameters to filter
    @param json_decode:          list of string: field to be decoded as json data
    @param defaults:             dict of key:name and value:default_value

    @raise MandatoryException:           if any param in requires does not provided
    @raise ArgumentException:            if arguments are invalid , short or mismatch type.
    @raise DenialException:              if found param in deny list
    @raise ParameterTypeException:       if parameter types invalid
    @raise ParameterValueException:      if values are not in correct format
    """

    #check deny arguments
    if deny_args:
        for arg in args:
            if re.match(deny_args, arg):
                raise DenialException('the argument %s was not allowed' % arg)

    #decoding json parameters
    if json_decode:
        decoder = JSONDecoder(parse_float=Decimal)
        def decode(d):
            try:
                return decoder.decode(d)
            except (JSONDecodeError,TypeError):
                return d

        if isinstance(json_decode,list):
            decoded_list =[(key,decode(kwargs[key])) for key in kwargs if key in json_decode]
        else:
            decoded_list =[(key,decode(kwargs[key])) for key in kwargs]
        kwargs.update(decoded_list)

    #check required arguments
    if required_args:
        try:
            new_args = list(args)
            for at in required_args:
                index = required_args.index(at)
                if not isinstance(new_args[index],at):
                    try:
                        #try to cast
                        new_args[index] = at(new_args[index])
                    except:
                        raise ParameterTypeException('argument at index:%s must be %s' % (required_args.index(at),at))
            args = tuple(new_args)
        except IndexError:
            raise ArgumentException('argument\'s length is too short')

    #check required parameters
    if requires:
        for name in requires:
            if name not in kwargs:
                raise MandatoryException('the parameter:"%s" is mandatory' % name)

    filtered_params = {}
    for param in kwargs:

        #checking requires
        if requires and param in requires and not kwargs[param]:
            raise MandatoryException('the parameter:"%s" is mandatory' % param)

        #checking for denial
        if deny and re.match(deny,param) and  (not deny_except or not re.match(deny_except, param)):
            raise DenialException('Parameter: %s was denied' % param)

        #value checking
        if values and param in values and not re.match(values[param], kwargs[param]):
            raise ParameterValueException('Parameter:%s does not meet value pattern: given value:%s' % (param,kwargs[param]))

        #checking for types
        if types and param in types:
            if kwargs[param] and not isinstance(kwargs[param],types[param]):
                try:
                    #try to cast the type too needed type
                    kwargs[param] = types[param](kwargs[param])
                except:
                    raise ParameterTypeException('Parameter:%s must be type:%s, given type:%s' % (param,types[param],type(kwargs[param])))

        #filtering parameters
        if not filter or not re.match(filter,param):
            filtered_params[param] = kwargs[param]

    #add defaults if not supplied
    if defaults:
        for param in defaults:
            if param not in filtered_params:
                filtered_params[param] = defaults[param]

    return args,filtered_params

def validate(**val_cfg):
    def validecorator(func):
        def wrapper(*args,**kwargs):
                if len(func.func_code.co_varnames) and func.func_code.co_varnames[0] == 'self':
                    new_args,filtered_params = validate_parameters(args[1:], kwargs,**val_cfg)
                    return func(*(args[0],)+new_args,**filtered_params)
                else:
                    new_args,filtered_params = validate_parameters(args, kwargs,**val_cfg)
                    return func(*new_args,**filtered_params)
            #calling the callable!

        return wrapper
    return validecorator

validate.__doc__ = validate_parameters.__doc__

rawDescription: Cherrypy form validation

description: Cherrypy form validation


rawDescription: Pandas groupby: How to get a union of strings


code:
class Parent(models.Model):
    parent_field = models.CharField(max_length=100)

class Child(Parent):
    child_field = models.CharField(max_length=100)

rawDescription: How to detect parent class fields

description: Detect parent class fields


code:
initial
compare

rawDescription: How to check if the next element in a text file is 1 more than the previous element?

description: Check if the next element in a text file is 1 more than the previous element


code:
f = Foo()
f.meth()
f.meth('blah', stuff='crud')

rawDescription: Python Decorator with arguments and accessing class instance


rawDescription: Create List of Single Item Repeated n Times in Python


code:
try:
    fin = gzip.open(phrasetablefile, 'rb')
except:
    fin = open(phrasetablefile, 'rb')

for line in fin:
    pass # do something
fin.close()

rawDescription: Checking for gzip or plain text and reading the file without checking extensions - python


code: df.groupby(level=0)[3].transform(lambda x: x[0]/ x[1])

rawDescription: Calculation between groups in a Pandas multiindex dataframe


rawDescription: Fast way to make list with same entry multiple times in Python?


rawDescription: Map a row index back to the original indexed dataframe


code:
for post in ...:
    post['author'] = post['author__username']
    del post['author__username']

rawDescription: Is there a way to choose a specific representation when serializing a `ForeignKey`?


code:
for row in datafile:
    x = row.strip().split(",")
    dict[x[0]] = x[1:]

rawDescription: .csv data into a dictionary in Python: Duplicate values


code:
momoisos = [row[0] for row in rows]
hist, bin_edges = np.histogram(monoisos, bins = 50)
mid = (bin_edges[1:] + bin_edges[:-1])/2
plt.plot(mid, hist, 'o')
plt.show()

rawDescription: Scatter plot of 10k record extracted from database


code:
import feedparser
from django.template import Template
d = feedparser.parse("http://example.com/feed.xml") # creating a FeedParserDict
# ... do stuff with d
t = Template(the_stuff_below) # compiling the template
output_atom_document = t.render(d)

rawDescription: How to modify an atom/rss feed in python?

description: Modify an atom/rss feed in python


code: ['work A', 'work A', 'work A', 'work B', 'work B', 'work C', 'laundry', 'nothing']

rawDescription: Get random element by given priority

description: Get random element by given priority


code: df

rawDescription: Applying a function to a pandas col

description: Applying a function to a pandas col


code:
import dis
def foo(s):
    c_string = "hello"
    if s == c_string:
        return True
    return False

dis.dis(foo)
foo.__code__.co_consts

rawDescription: Hard coded variables in python function

description: Hard coded variables in python function


rawDescription: pygtk for touchscreen devices

description: Pygtk for touchscreen devices


code: np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4') # or dtype=np.dtype('<f4'), or np.float32 on a little-endian system (which most computers are these days)

rawDescription: convert binary string to numpy array

description: Convert binary string to numpy array


code:
s = set([1,2,3])
strs = repr(s)
strs
eval(strs)

rawDescription: Python convert set to string and vice versa


code:
import numpy as np

# generate data
data = np.floor(np.random.randn(10000)*20+620)
data = dat[(560<dat) & (dat<650)]

# do what you're doing
heights,edges = np.histogram(data, bins=100, range=(data.min(),data.max()))
edges = edges[:-1]+(edges[1]-edges[0]) # shift first x coordinate to edges[1]
                                     # and drop last point: 1 more edge than bins

fig, ax = plt.subplots()
ax.plot(edges,heights)

rawDescription: Numpy.histogram joining bins

description: Numpy.histogram joining bins


code:
import csv

source = r'C:\Users\jk\Desktop\helloworld.csv'
dest = 'test.csv'

with open(source, newline='') as inf, open(dest, 'w', newline='') as outf:
    reader = csv.DictReader(inf)
    writer = csv.DictWriter(outf, fieldnames=reader.fieldnames)
    for row in reader:
        words = row['Keyword'].split()
        row['Keyword'] = words[0]
        writer.writerow(row)
        writer.writerows({'Keyword': w} for w in words[1:])

rawDescription: Find a specific header in a CSV file using python 3 code


code:
from struct import pack, unpack
pack_type = {'signed':'>h','unsigned':'>H',}
pack(self.pack_type[sign_type], data)

rawDescription: How to create a fixed size (unsigned) integer in python?

description: Create a fixed size (unsigned) integer in python


code:
functions = [None, func1, func2, func3, ...]
functions[int(self.function_to_select)]()

rawDescription: most efficient way to selection specific function based on input

description: Most efficient way to selection specific function based on input


code:
newlines = []
for subline in lines:
    tmp = []
    for x,y in subline:
        tmp.append((x, y+dy))
    tmp = tuple(tmp)
    newlines.append(tmp)

rawDescription: Python How to modify Y value in a list of X,Y points for lines


code:
from collections import Counter

freq = Counter(item[-1] for item in a)
result = sorted(a, key=lambda i: freq[i[-1]], reverse=True)

rawDescription: Sorting a List of List in Python by frequency


rawDescription: Methods of creating a structured array

description: Methods of creating a structured array


rawDescription: Reshape list of lists based on position of the element


rawDescription: Python - Get group names from aggregated results in pandas


code:
class Person(object):
    def opinion(self):
        print(type(self))
        print ("Time for a cup of tea")

class Programmer(Person):
    def opinion(self):
        super(Programmer, self).opinion()
        print ("There is no spoon")

if '__name__' == '__main__':
    programmer = Programmer()
    programmer.opinion()

p = Person()
p.opinion()
print('\n')
pg = Programmer()
pg.opinion()

rawDescription: Identifying the class in which code is running


code: latest = max(builds, key=version)

rawDescription: Python max() function doesnt give correct results when two strings are compared


code:
import numpy as np
import pylab as pl

for i in xrange(1, 5):
    pl.subplot(220+i)
    pl.pie([i,2], labels=["a","b"], autopct='%1.1f%%')

l = pl.legend(title="sample")
pl.show()

rawDescription: matplotlib - Legend in separate subplot

description: Matplotlib - Legend in separate subplot


code:
d = {'a': 100, 'b': 200, 'c': 300, 'd': 350}
dic = {}
dic.update(dict(sorted(d.items(), key=lambda x:x[1], reverse=True)[:2]))
dic

rawDescription: put top 2 biggest keys and values of dictionary in another dictionary

description: Put top 2 biggest keys and values of dictionary in another dictionary


code:
from itertools import chain
from collections import defaultdict
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 2, 'b': 3, 'd': 4}
d3 = defaultdict(list)
for k, v in chain(d1.items(), d2.items()):
    d3[k].append(v)

for k, v in d3.items():
    print(k, v)

rawDescription: Merging two dictionaries while keeping the original


rawDescription: gdata.data.PhoneNumber: How do I get the type of Phone Number?

description: Gdata.data.PhoneNumber: How do I get the type of Phone Number


rawDescription: How to restructure data using a loop (without crashing computer!) and write to csv in python

description: Restructure data using a loop (without crashing computer!) and write to csv in python


code:
class myNoneType(nt):
     def find(self): return 1

rawDescription: Adding method to Python's NoneType

description: Adding method to Python's NoneType


code:
# -*- coding: utf-8 -*-

tests = """
    # a regular line
    hello 1: -fred,123 (100 hello stack overflow)

    # a username with spaces
    hello 2: my name is brent (250 hello stack overflow)

    # a username with non-ASCII
    hello 3: äää + óóó (0 hello stack overflow)
"""

from pyparsing import *

COLON,LPAR,RPAR = map(Suppress, ":()")
integer = pyparsing_common.integer

leading = "hello" + integer + COLON
trailing = LPAR + integer + "hello" + "stack" + "overflow" + RPAR

strip = lambda t: t[0].strip()
line = leading + SkipTo(trailing).setParseAction(strip) + trailing

line.runTests(tests)

rawDescription: Parsing Unknown Length Unicode Name

description: Parsing Unknown Length Unicode Name


code:
import itertools
a = ['X', 'Y', 2]
for c in itertools.product(' -', repeat=2):
    print ('%s%s%s%s%s' % (a[0],c[0],a[1],c[1],a[2])).replace(' ', '')

rawDescription: Combine elements of a list with all possible separators


code:
plt.legend()
plt.show()

rawDescription: Best way to plot an angle between two lines in Matplotlib

description: Plot an angle between two lines in Matplotlib


code:
x = """<x></x>"""
s = bs4.BeautifulSoup(x)
for a in s.findChildren("a"):
    print(a["name"])

rawDescription: Getting Tag Names with BeautifulSoup

description: Getting Tag Names with BeautifulSoup


code:
import numpy as np

def find_offsets(row, col, size):
    """Return all valid pairs of offsets as [(row_offset, col_offset)...]."""
    offsets = ((-1, -1), (-1, 0), (-1, 1),
               (0, -1), (0, 1),
               (1, -1), (1, 0), (1, 1))

    return [(r_off, c_off) for r_off, c_off in offsets
            if row + r_off >= 0 and row + r_off < size
            if col + c_off >= 0 and col + c_off < size]

def find_odds(matrix, size):
    """Return all odd values in matrix as [(row_ind, col_ind, value)...]."""
    return [(row, col, matrix[row][col])
            for row in xrange(size)
            for col in xrange(size)
            if matrix[row][col] % 2 != 0]

def gen_matrix(source, size):
    """Filter source 2x2 matrix for odds and add each to valid neighbors."""

    out = np.zeros((size, size), dtype=int)

    # filter for location and value of all odd numbers
    odds = find_odds(source, size)
    for row, col, value in odds:
        # add odd number to all valid neighbors (by finding valid offsets)
        offsets = find_offsets(row, col, size)
        for r_off, c_off in offsets:
            out[row + r_off][col + c_off] += value

    return out

def sum_neighbors():
    """Sum neighbors as described in problem."""
    N = 5
    A = [[3,2,8,1,1],
         [1,2,4,1,1],
         [7,3,4,1,8],
         [1,8,0,6,4],
         [5,6,5,3,8]]
    return gen_matrix(A, N)

rawDescription: Is there a more efficient way to solve this?


rawDescription: How to remove all whitespaces in string and get exactly one number?( Python)

description: Remove all whitespaces in string and get exactly one number?( Python)


code:
def post(self):
    var_list = ['var1', 'var2']
    result_list = []
    for var in var_list:
        result_list.append(self.request.get(var))
    return result_list # etc.

rawDescription: Using a string as a variable name

description: Using a string as a variable name


rawDescription: BeautifulSoup: how to get children of div tab


code:
def get_occ(d): return d.occ
fullset.sort(key=get_occ)

rawDescription: Python: Sorting a list by class objects

description: Python: Sorting a list by class objects


code:
dictionary[0]['events'][0] = {
                         'eventType' : 'Goal',
                         'name' : 'Muchache Johansson',
                         }

rawDescription: Adding items to a dictionary in python (nested)


code:
import time

print("program entered")

def ispow2(n):
    return not n & n - 1

start = time.perf_counter()
ispow2(2**100000000)
end = time.perf_counter()

print(end - start)

rawDescription: Why does time incorrectly report such a fast time?


code:
import re
str = """
category/
categories/
categories
category"""
m = re.findall(r'^categor(?:y|ies)/$', str, re.MULTILINE)
m

rawDescription: Python regex to match 'category/' or 'categories/'?


code:
data = {}
for i in range(100):
    item = 'file' + str(i)
    data[item] = {}
    kind_like_file_of_nums = [float(x) for x in range(10)]
    data[item]['temps'] = kind_like_file_of_nums[0::2]
    data[item]['pres'] = kind_like_file_of_nums[1::2]

print(data)

rawDescription: Name of a list changing as I go through a loop


code:
df = pd.DataFrame({i: range(1000) for i in range(100)})
df.ix[:5, :10]

rawDescription: How to preview a part of a large pandas DataFrame?

description: Preview a part of a large pandas DataFrame


code:
from collections import OrderedDict
named_sets  = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at'])  }
OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))
_.keys()

rawDescription: How to do case insensitive sort of a dictionary and store them in OrderedDict

description: Do case insensitive sort of a dictionary and store them in OrderedDict


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

x = np.arange(-10, 361, 10, dtype = int)
y = np.sin(np.deg2rad(2*x))

fig, ax = plt.subplots(1, 1)
ax.plot(x, y)

ax.set_xticks(x, minor=True)        # set minor ticks for each x value
ax.grid(which='both', axis='both')  # show grid lines

plt.show()

rawDescription: Matpotlib Xtick Overlap

description: Matpotlib Xtick Overlap


code:
def application(environ, start_response):
    if platform.system() == 'Windows':
        close_fds=False
    else:
        close_fds=True

    p = Popen('python "C:\testing\long.py"', stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=close_fds, shell=True)

    status = '200 OK'
    output = "invoked (%d)" % (p.pid)
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

rawDescription: How to spawn Python2.5 process through Apache and return immediately under Windows

description: Spawn Python2.5 process through Apache and return immediately under Windows


code:
with open(filename, "r") as fin:
    for line_counter, line in enumerate(fin):
        line_items = line.split()
        line_list.append(line_items)
    # after the loop line_counter has counted the lines

rawDescription: Why aren't the lists populating in this code?


code:
def get_hit():
    while True:
        try:
            players_chosen_hit = input('Please tell me where the hit is: 1-9  (q to quit) ')
            if players_chosen_hit == "q":
                print("Goodbye")
                return
            players_chosen_hit = int(players_chosen_hit)
            if players_chosen_hit in possibleusershipplaces:
                return players_chosen_hit
        except ValueError:
            print("Invalid entry")

rawDescription: Python - Error Checking

description: Python - Error Checking


code: Dict_D = {k: v for k, v in A.items() if B.get(k) == v}

rawDescription: Hashing or dictionaries for Venn diagram of dictionaries?


rawDescription: Setting up stateChanged signal in QStackedWidget, pyqt


rawDescription: How to save a 3 channel numpy array as image

description: Save a 3 channel numpy array as image