code:
# thread queue
threadQueue = Queue()

# thread numbering
threadNumber = 0

# thread start
threadCanStart = True

rawDescription: Start one thread at a time with queqe

description: Start one thread at a time with queqe


code:
import your_module
the_result = your_module.f_var_1(23, 46)

rawDescription: Get values from module

description: Get values from module


rawDescription: How to carry out this aggregation in python

description: Carry out this aggregation in python


rawDescription: How to merge multiple dictionaries from separate lists if they share any key-value pairs?

description: Merge multiple dictionaries from separate lists if they share any key-value pairs


code:
import os.path

def mkdir_p(sftp, remote_directory):
    """Change to this directory, recursively making new folders if needed.
    Returns True if any folders were created."""
    if remote_directory == '/':
        # absolute path so change directory to root
        sftp.chdir('/')
        return
    if remote_directory == '':
        # top-level relative directory must exist
        return
    try:
        sftp.chdir(remote_directory) # sub-directory exists
    except IOError:
        dirname, basename = os.path.split(remote_directory.rstrip('/'))
        mkdir_p(sftp, dirname) # make parent directories
        sftp.mkdir(basename) # sub-directory missing, so created it
        sftp.chdir(basename)
        return True

sftp = paramiko.SFTPClient.from_transport(transport)
mkdir_p(sftp, remote_path)
sftp.put(local_path, '.')    # At this point, you are in remote_path
sftp.close()

rawDescription: Upload files using SFTP in Python, but create directories if path doesn't exist


code:
#pandas 0.17.0 and above
s.plot.bar()
#pandas below 0.17.0
s.plot('bar')

rawDescription: How to plot a bar graph from a pandas series?

description: Plot a bar graph from a pandas series


code:
tests = [
    ("class hi()", "hi"),
    ("class hi(dff)", "hi"),
    ("class hi   (  dff  )  :", "hi"),
    ("  class        hi       (  dff  )  :", "hi"),
    ("class hi", "hi"),
    ("classf hi", None),
    ("fclass hi", None),
    ("'class hi(dd)'", None),
    ('"class hi(dd)"', None),
    ("'''class hi(dd)'''", None),
    ('"""class hi(dd)"""', None),
    ('"""\n\n\n\nclass hi(dd)\n\n\n\n"""', None),
    ("'class' hi()", None),
    ("a = ''; class hi(object): pass", "hi")
]

def run_tests(fn, tests=tests):
    for inp,outp in tests:
        res = fn(inp)
        if res == outp:
            print("passed")
        else:
            print("FAILED on {} (gave '{}', should be '{}')".format(inp, repr(res), repr(outp)))

rawDescription: Looking for a way to get a word after another word, Python


code:
while True:
    euser = input("Enter Gmail Username: ")
    epass = input("Enter Gmail Password: ")
    try:
        user.login(euser, epass)
        break
    except smtplib.SMTPAuthenticationError:
        print ("Invalid Credentials!")

while True:
    if end == "true" or end2 == "true": # better use booleans and `if end or end2:`
        break
    # unnecessary: user.login(euser, epass)
    print ("Retrieving Files")

rawDescription: Why does python ask me to input the same thing over and over again after it has been already entered - (smtpib - gmail)


code:
input = [('dog', 'dog', 'cat', 'mouse'), ('cat', 'ruby', 'python', 'mouse')]
outputlist, outputmapping = build_catalog(input)
outputlist
outputmapping

rawDescription: efficient list mapping in python

description: Efficient list mapping in python


code: fitfunc = lambda params, x: params[0] * x + params[1]

rawDescription: How to force zero interception in linear regression?

description: Force zero interception in linear regression


code:
from collections import defaultdict

d = defaultdict(list)

rawDescription: Save dictionary to file

description: Save dictionary to file


code:
from mwlib import parser, expander, uparser
from mwlib.expander import DictDB
from mwlib.xfail import xfail
from mwlib.dummydb import DummyDB
from mwlib.refine import util, core

parse = uparser.simpleparse

def test_headings():
    r=parse(u"""
= 1 =
== 2 ==
= 3 =
""")

    sections = [x.children[0].asText().strip() for x in r.children if isinstance(x, parser.Section)]
    assert sections == [u"1", u"3"]

rawDescription: How to parse/extract data from a mediawiki marked-up article via python

description: Parse/extract data from a mediawiki marked-up article via python


code:
for index in range(0,1000):
    worker('http://example.com/managament.php?', {'UserID' : '', 'Action':'Delete'}, [i for i in range(1,4)])

rawDescription: Python multi-threading missing jobs

description: Python multi-threading missing jobs


rawDescription: How to split on two items in a string?

description: Split on two items in a string


code:
import urllib2
from time import time

stream = urllib2.urlopen('http://www.rarlab.com/rar/winrar-x64-420.exe')
start_time = time()
output = stream.read()
end_time = time()
stream.close()
print(end_time-start_time)

rawDescription: measuring the time to load a page - Python

description: Measuring the time to load a page - Python


code:
import zipfile
import configparser

zf = zipfile.ZipFile("compressed.zip")
zf_config = zf.open("config_data.conf", "rU")
zf_config_data = zf_config.read().decode('ascii')

config = configparser.ConfigParser()
config.read_string(zf_config_data)
assert config['today']['lunch']=='cheeseburger'

rawDescription: configparser loading config files from zip

description: Configparser loading config files from zip


code:
import inspect
import linecache
import traceback
import unittest.case
import sys

SKIPPED_MODULES = [
    unittest.case
]

def test_skip_frame(frame):
    module = inspect.getmodule(frame)
    return module in SKIPPED_MODULES

def tb_skipper(tb):
    tbnext = tb.tb_next
    while tbnext is not None:
        if test_skip_frame(tbnext.tb_frame):
            tbnext = tbnext.tb_next
        else:
            yield tbnext
    yield None

def new_extract_tb(tb, limit = None):
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    list = []
    n = 0
    new_tb_order = tb_skipper(tb) # <-- this line added
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        if line: line = line.strip()
        else: line = None
        list.append((filename, lineno, name, line))
        tb = next(new_tb_order) # <-- this line modified, was tb = tb.tb_next
        n = n+1
    return list
traceback.extract_tb = new_extract_tb

rawDescription: py.test: hide stacktrace lines from unittest module

description: Py.test: hide stacktrace lines from unittest module


code:
import re
s = "xxxx.yyyy.zzzzz.mystring"
m = re.search(r'(?<=\.)[^.]*$', s)
m
m.group()
s.split('.')[-1]

rawDescription: Regular expression which gets the last part after a special character


code:
shape = np.maximum(x.shape, y.shape)
x1 = np.zeros(shape)

rawDescription: Extend different shapes/dimension matrices in python


code:
from subprocess import check_call

with tempfile.NamedTemporaryFile() as file:
    check_call(["generate_kmers", str(kmer)], stdout=file)
    file.delete = False

rawDescription: Bash style process substitution with Python's Popen


code:
yesbutton = wx.Button(panel, label="Yes,  I wish to log in", pos=(50,150), size=(150,60))
log = Login()
self.Bind(wx.EVT_BUTTON, log.login, yesbutton)

nobutton = wx.Button(panel, label="No,  I wish to register", pos=(270,150), size=(150,60))
reg = Register()
self.Bind(wx.EVT_BUTTON, reg.register, nobutton)

class Login:

    def login(self, evt):
        print("login")

class Register:

    def register(self, evt):
        print("register")

rawDescription: Error when attempting to call function from button in wxpython


code:
False
True
False

rawDescription: Defining Function Python

description: Defining Function Python


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

def makeFirstPattern(ax, d, verticies, scale=True):
    Pn = Custom_Polygon(verticies)
    direction = 1
    divisions = d
    if scale: Pn.scale_with_orgin(2.0/(divisions+1), Pn.verticies[-1])
    for i in range(divisions, 0, -2):
        for _ in range(i):
            ax.add_patch(Polygon(Pn.verticies, closed=True, fill=True, ec='none'))
            Pn.translate([direction * Pn.get_width()/2, 0])
        direction *= -1
        Pn.translate([direction * Pn.get_width(), Pn.get_height()])

el = 1
dfv = 1/np.sqrt(3)*el
dfe = 1/(2*np.sqrt(3))*el
vertices1 = [(0,0),(0.5*el,-dfe),(0,dfv),(-0.5*el,-dfe)]
vertices2 = [(0.5*el,-dfe),(0,dfv),(-0.5*el,-dfe)]

fig = plt.figure()
ax1 = fig.add_subplot(111)

makeFirstPattern(ax1, 7, vertices2)

ax1.set_xlim([-1, 1])
ax1.set_ylim([-1, 1])
ax1.set_aspect('equal')
plt.show()

rawDescription: How to create a repetitive image pattern programmatically?

description: Create a repetitive image pattern programmatically


rawDescription: python: break list into pieces when an empty entry is found

description: Python: break list into pieces when an empty entry is found


rawDescription: Python: how to count collaborations between pairs in pandas dataframe?


rawDescription: Cycling through a list of list, checking and removing?


code:
import re
string = "text <tag>some texts</tag> <tag> text</tag> some text"
regex = re.compile(r"\s*(<[^<>]+>)\s*")
regex.sub("\g<1>", string)

rawDescription: Strip white-space from HTML before parsing


code:
from threading import Thread, Event

def worker1(events):
    a,b,c = events
    while True:
        a.wait() # sleep here if 'a' event is set, otherwise continue

        # do work here

        if some_condition:
            c.clear() # put c to sleep
            b.set() # wake up, b

def worker2(events):
    a,b,c = events
    while True:
        b.wait()
        #do work
        if some_condition:
            a.clear()
            c.set()

def worker3(events):
    a,b,c = events
    while True:
        c.wait()
        #do work
        if some_condition:
            b.clear()
            a.set()

rawDescription: Python - start and stop multiple threads


code:
self.SetColumnWidth(colNum, wx.LIST_AUTOSIZE_USEHEADER)

self.__columnWidth[colNum] = self.GetColumnWidth(c)

rawDescription: How to set and preserve minimal width?

description: Set and preserve minimal width


code:
mask_ext = np.pad(mask,1,'constant',constant_values=(1))
out = mask_ext | binary_closing(mask_ext, structure=np.ones(threshold))
out = out[1:-1]

rawDescription: Find consecutive unmasked values

description: Find consecutive unmasked values


code: D

rawDescription: Averaging out sections of a multiple row array in Python


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', legend=False, ax=ax, autopct='%0.2f', title=col,
                 colors=colors)
    ax.set(ylabel='', aspect='equal')

axes[0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png')
plt.show()

rawDescription: How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib

description: Make MxN piechart plots with one legend and removed y-axis titles in Matplotlib


code:
import os
import subprocess

def startfile(filename):
  try:
    os.startfile(filename)
  except:
    subprocess.Popen(['xdg-open', filename])

rawDescription: Make OS open directory in Python

description: Make OS open directory in Python


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-mode', choices=['download', 'upload'], required=True)
parser.add_argument('-d', required=True)
parser.add_argument('-f')

args = parser.parse_args()
if args.mode == 'download' and not args.f:
    parser.error('-f argument is required in "download" mode.')

rawDescription: Add arguments to argparse depending on value of initial arguments


code:
assert sparse.shape == dense.shape
dense[:] = 0

rawDescription: Load sparse scipy matrix into existing numpy dense matrix


rawDescription: If test on Pandas DataFrame

description: If test on Pandas DataFrame


code: re.findall(r'^(\w+):(.*?)(?=^\w+:|\Z)', text, flags=re.DOTALL | re.MULTILINE)

rawDescription: Unable to find the correct regex in python


code: four == four+1

rawDescription: Python dice rolling simulation

description: Python dice rolling simulation


code:
def parsesection(snapshot):
    if snapshot == 'all':
        return slice(None)
    try:
        section = int(snapshot)
    except ValueError:
        section = [int(s) if s else None for s in snapshot.split(':')]
        if len(section) > 3:
            raise ValueError('snapshots input incorrect')
        section = slice(*section)
    return section

print(parsesection(':5'))
print(parsesection('5:15'))
print(parsesection('5:15:3'))
print(parsesection('3'))
print(parsesection('5::3'))
print(parsesection('::2'))
print(parsesection('all'))

rawDescription: numpy.array indices via argparse - How to do it properly?

description: Numpy.array indices via argparse - How to do it properly


code:
from itertools import chain
from collections import Counter
counter = Counter({k: 0 for k in string.ascii_lowercase})
counter.update(Counter(c for w in words for c in set(w.lower())))

rawDescription: How to improve permutation algorithm efficiency with python

description: Improve permutation algorithm efficiency with python


code:
net_dict = {}

# ...

name = name_list.pop(0)
net_dict[name] = Net(userIP, userMask)
print(net_dict[name])

rawDescription: Python- Use value of pop as object name

description: Python- Use value of pop as object name


code:
import numpy as np

def unique_rows(a, p):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.ones(len(a), 'bool')
    diff[1:] = (a[1:] != a[:-1]).any(-1)
    sums = np.bincount(diff.cumsum() - 1, p[order])
    return a[diff], sums

rawDescription: Identify duplicate rows in an array and sum up corresponding values in another array


code: order = [i for i,_ in sorted(enumerate(vertex), key = lambda x: x[1])]

rawDescription: Sorting a list based on another list with DSU


code:
class MyForm(forms.ModelForm):
    # ...

    def clean(self):
        return my_custom_clean_function(super(MyForm, form_instance).clean())

def my_custom_clean_function(cleaned_data):
    # other validation routines
    return cleaned_data

rawDescription: Using super() from outside a class in Django (or alternative to it, if any)


code:
#!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Kiseliov Roman

from xlwt import *
from datetime import datetime

w = Workbook()
ws = w.add_sheet('Hey, Dude')

fmts = [
    'M/D/YY',
    'D-MMM-YY',
    'D-MMM',
    'MMM-YY',
    'h:mm AM/PM',
    'h:mm:ss AM/PM',
    'h:mm',
    'h:mm:ss',
    'M/D/YY h:mm',
    'mm:ss',
    '[h]:mm:ss',
    'mm:ss.0',
]

i = 0
for fmt in fmts:
    ws.write(i, 0, fmt)

    style = XFStyle()
    style.num_format_str = fmt

    ws.write(i, 4, datetime.now(), style)

    i += 1

w.save('dates.xls')

rawDescription: pyExcelerator date format

description: PyExcelerator date format


code:
import threading, thread
mylock = threading.Lock()
type(mylock)
thread.LockType
type(mylock) is thread.LockType

rawDescription: python - AttributeError: 'module' object has no attribute 'lock'

description: Python - AttributeError: 'module' object has no attribute 'lock'


code:
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings"

rawDescription: Use only some parts of Django?

description: Use only some parts of Django


status: Bad Request

explanation: The server could not comply with the request since it is either malformed or otherwise incorrect.

rawDescription: How can I return JSON output when repoze.who authentication fails?

description: Return JSON output when repoze.who authentication fails


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

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


code:
import wx.lib.agw.aui as aui

class MyNotebook(aui.AuiNotebook):
    def __getitem__(self, index):
        ''' More pythonic way to get a specific page, also useful for iterating
            over all pages, e.g: for page in notebook: ... '''
        if index < self.GetPageCount():
            return self.GetPage(index)
        else:
            raise IndexError

rawDescription: Python/wxPython: auinotebook get all pages


code:
import sklearn

c1_train, c1_test, c2_train, c2_test = sklearn.cross_validation.train_test_split(c1, c2, test_size=0.5, random_state=0)
c3_train, c3_test, c4_train, c4_test = sklearn.cross_validation.train_test_split(c3, c4, test_size=0.5, random_state=0)

rawDescription: Split CSV data in python

description: Split CSV data in python


code:
A = arange(25).reshape((5,5))
X = arange(5)
A
dot(A, X) # Sum_j A[i,j] * X[j] for all i

rawDescription: Computing complex math equations in python


code:
with open('test.csv', 'rb') as old_csv:
    reader = csv.reader(old_csv, delimiter=',')
    filters = {(row[0].lower(), row[1][:3].upper(), row[2][:-6].strip().upper())
               for row in reader
               if row[2].endswith('(BIPL)')}

rawDescription: Editing a code to create a filter based on a condition and then stripping the condition


code:
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
    # Directory: The path length to the directory where the output file is
    #            to be stored
    # Title:     The name of the output plot, which should end with .eps or .png
    # X_Label:   The X axis label
    # Y_Label:   The Y axis label
    # X_Data:    X axis data points (usually time at which Yaxis data was acquired
    # Y_Data:    Y axis data points, usually amplitude

    import matplotlib
    from matplotlib import rcParams, pyplot as plt

    rcParams.update({'figure.autolayout': True})
    Output_Location = Directory.rstrip() + Title.rstrip()
    fig,fft_plot = plt.subplots()
    matplotlib.rc('xtick',labelsize=18)
    matplotlib.rc('ytick',labelsize=18)
    fft_plot.set_xlabel(X_Label,fontsize=18)
    fft_plot.set_ylabel(Y_Label,fontsize=18)
    plt.plot(X_Data,Y_Data,color='red')
    plt.savefig(Output_Location)
    plt.close()

rawDescription: What is the preferred way to import pylab at a function level in Python 2.7?


code:
s = ",itemA,itemB,Central California\r\n"
re.findall(r',?([^,]+)(?:,|\r\n)', s)
s = "BASE,itemA,itemB,Central California\r\n"
re.findall(r',?([^,]+)(?:,|\r\n)', s)

rawDescription: Python regex: exclude \r\n

description: Python regex: exclude \r\n


code:
for var in ('F10', 'F11', 'F12'):
    sorted(getattr(X_train_num, var).unique())==sorted(getattr(X_test_num, var).unique())

rawDescription: how to loop over below statement

description: Loop over below statement


code: [k for k in d if d[k] > 6]

rawDescription: How to filter dictionary keys based on its corresponding values

description: Filter dictionary keys based on its corresponding values


code:
def fast_iter(context, func, *args, **kwargs):
    """
    http://lxml.de/parsing.html#modifying-the-tree
    Based on Liza Daly's fast_iter
    http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    See also http://effbot.org/zone/element-iterparse.htm
    """
    for event, elem in context:
        func(elem, *args, **kwargs)
        # It's safe to call clear() here because no descendants will be
        # accessed
        elem.clear()
        # Also eliminate now-empty references from the root node to elem
        for ancestor in elem.xpath('ancestor-or-self::*'):
            while ancestor.getprevious() is not None:
                del ancestor.getparent()[0]
    del context

rawDescription: Why is lxml.etree.iterparse() eating up all my memory?


rawDescription: Python lambdas in Jinja2

description: Python lambdas in Jinja2


code:
def getClientIPaddress(request):
    http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if http_x_forwarded_for:
        ip_address = http_x_forwarded_for.split(',')[0]
    else:
        ip_address = request.META.get('REMOTE_ADDR')
    return ip_address

rawDescription: Read IP address from api call in Tastypie?


code:
initInProgress = None

def initSharedMemory():
    global initInProgress
    if initInProgress is None:
        initInProgress = _reallyInit()
        def initialized(result):
            global initInProgress, SomeSharedMemory
            initInProgress = None
            SomeSharedMemory = result
        initInProgress.addCallback(initialized)
    d = Deferred()
    initInProgress.chainDeferred(d)
    return d

rawDescription: Waiting on events in other requests in Twisted


code:
L = [''.join(str(x) for x in s[i*n: i*n + n]) for i in range(len(s)/n)]
with open("file", 'w') as f:
 for v in L:
  f.write(v + ', ')

rawDescription: Parse simple array and save it on a file


rawDescription: Python 3: Demystifying encode and decode methods


code:
class Foo(object):

    def __init__(self, data):
        self._data = data

    def __dir__(self):
        return dir(object) + self.__dict__.keys() + [k for k in self._data]

foo = Foo({'bar': 'baz'})

rawDescription: Alter list of attributes listed by dir function


code:
import numpy as np
b = np.array(a)
sys.getsizeof(b)
b.itemsize    # number of bytes per element

rawDescription: python loads more memory than the actual size of the file

description: Python loads more memory than the actual size of the file


code:
import inspect
def foo(bar, baz, spam='eggs', *monty, **python): pass

inspect.getargspec(foo)

rawDescription: Listing variables expected by a function in Python?


rawDescription: Filter by row sum and value

description: Filter by row sum and value


code:
def get_cars(self, request, page=1):
    cars_per_page = 10
    search_term = request.REQUEST.get('car_type')  #car_type 'car bmw' will still be kept in request
    all_cars = Car.objects.filter(car_type__contains=search_term)
    paginator = Paginator(all_cars, cars_per_page)
    page_ = paginator.page(page)
    result_cars = page_.object_list
    return render(request, "search_cars.html", {'search_term': search_term})

rawDescription: django pagination understanding issue

description: Django pagination understanding issue


code:
colors = [item['color'] for item in get_prop_cycle()]
c = np.take(colors, c, mode='wrap')

rawDescription: Using matplotlib's color cycle as a colormap


code:
# Split data because rnn cell needs a list of inputs for the RNN inner loop
_X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)

rawDescription: what's the difference between two implentations of RNN in tensorflow

description: What's the difference between two implentations of RNN in tensorflow


code:
from bs4 import BeautifulSoup
collection = BeautifulSoup(open("foo.xml").read(),"lxml")
e1 = collection.find('doc').find_all('a')
e2 = collection.find_all('doc')[1].find_all('a')
len(e1)
len(e2)
len(collection.find_all("a"))
len(collection.find('doc').text)
len(collection.text)

rawDescription: BeautifulSoup first element incorrect

description: BeautifulSoup first element incorrect


code:
ndict = dict()
numbers = []
numbers.append(1.00)
numbers.append(2.00)
numbers.append(3.00)
numbers.append(18.00)
ndict['numbers'] = numbers

rawDescription: How to create a dictionary in python from a set of values

description: Create a dictionary in python from a set of values


code:
row = [5, 5, 5]
for vert in row:
    print(row.index(vert))

rawDescription: Append overwrites values even when copying list


code:
a = np.ones(a.shape,dtype=bool)
a[1::2,1::2] = False
a

rawDescription: Return rows and columns from a 2d array using values from a 1d array in Numpy


code:
from difflib import SequenceMatcher
list1 = [['Code', 'sID', 'dID', 'cID', 'sID'], ['ABCD-00', 'ABCD-00-UNK', '358', '1234', '9999'], ['ABCD-01', 'ABCD-00-UNK', 160, '993', '587']]
list2 = [['Code', 'sID', 'dID', 'cID', 'sID', 'AddedColumn'], ['ABCD-00', 'ABCD-00-UNK', '358', '1234', '9999', 'AddedValue1'], ['ABCD-01', 'ABCD-00-UNK', 160, '993', 'ChangedValue', 'AddedValue2']]
matcher = SequenceMatcher()
for a, b in zip(list1, list2):
    matcher.set_seqs(a, b)
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == 'equal': continue
        print('{:>7s} {} {}'.format(tag, a[i1:i2], b[j1:j2]))

rawDescription: Print differences between list of lists using Python


code: np.hypot(dx, dy)

rawDescription: calculating distance between two numpy arrays

description: Calculating distance between two numpy arrays


rawDescription: How to check if a group of numbers are represented from each decile?

description: Check if a group of numbers are represented from each decile


code: stream = stream | Transformer('.//head/script["functionName()"]').remove()

rawDescription: How do I test if a string exists in a Genshi stream?

description: Test if a string exists in a Genshi stream


rawDescription: Joining two list whereby the last element of list "A" and first element of list "B" are concatenated


code:
import pandas as pd
import numpy as np
rows = [(u'KY', [u'McConnell'], [u'Grimes'], [u'Rep']),
        (u'AR', [u'Cotton'], [u'Pryor'], [u'Dem']),
        (u'MI', [u'Land'], [u'Peters'], [])]

def get(r, nth):
    '''helper function to retrieve item from nth list in row r'''
    return r[nth][0] if r[nth] else np.nan

def remove_list_items(list_of_records):
    for r in list_of_records:
        yield r[0], get(r, 1), get(r, 2), get(r, 3)

rawDescription: how to convert a list into a pandas dataframe

description: Convert a list into a pandas dataframe


code: sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brRight'})]

rawDescription: How to get next page link in python beautifulsoup?

description: Get next page link in python beautifulsoup


rawDescription: python qt4 - passing arguments in QtCore.QObject.connect

description: Python qt4 - passing arguments in QtCore.QObject.connect


code:
Program
############################### Declarations ##############################################

import os
from pydub import AudioSegment
import speech_recognition as sr

#Read main audio file to be processed. Assuming in the same folder as this script
sound = AudioSegment.from_wav("0-100.wav")

#slice time are in seconds
tenSecSlice = 10 * 1000

#Total Audio Length
audioLength = len(sound)

#Get quotient and remainder
q, r = divmod(audioLength, tenSecSlice)

#Get total segments and rounds to next greater integer
totalSegments= q + int(bool(r))

exportPath = "\\tempDir\\"

####################################################
#Function for Speech Recognition
#downloaded & modified  from above mentioned site
####################################################

def processAudio(WAV_FILE):
    r = sr.Recognizer()
    with sr.WavFile(WAV_FILE) as source:
        audio = r.record(source) # read the entire WAV file

    # recognize speech using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

############################### Slice Audio and Process ################################

#Declare empty List

exportPath = "tempDir\\"
segmentList = []
n=0

#Iterate through slices  and feed to speech recognition function
while n < totalSegments:
    firstPart = (tenSecSlice * n)
    secondPart =  (tenSecSlice * (n + 1))

    print ("Making slice  from %d to %d  (sec)" % (firstPart /1000 , secondPart /1000))
    print ("Recognizing words from  %d to %d " % (firstPart /1000 , secondPart /1000))
    tempObject = sound[ firstPart :secondPart ]
    myAudioFile = exportPath + "slice" + str(n) +".wav"
    tempObject.export(myAudioFile , format="wav")
    n += 1
    processAudio(myAudioFile)
    print ("")

############################### End Program ##############################################

rawDescription: how to get frequency of audio at specific time in python?

description: Get frequency of audio at specific time in python


code:
why
an
cool
cool
cool
apple
cool
apple
am
am
apple
apple
apple
why
cool
cool
cool
am
am
apple

rawDescription: Select one element from a list using python following the normal distribution


code: dir(A)

rawDescription: Why does python put 'A' in global namespace when I import A.B.C


code:
FRAMERATE = 30 #(The framerate used in this example is 30 FPS)
clock = pygame.time.Clock()
counter = 0
not_pressed = True

rawDescription: How to only get a key entry once per second? (or delay the time in between two keyboard entry)

description: Only get a key entry once per second? (or delay the time in between two keyboard entry)


code:
def semisupervised_stratified_kfold(y, *args, **kwargs):
    labeled_idx = np.flatnonzero(y != -1)
    unlabeled_idx = np.flatnonzero(y == -1)
    for train, test in StratifiedKFold(y[labelled_idx], *args, **kwargs):
        train = np.concatenate([unlabeled_idx, labeled_idx.take(train)])
        test = labeled_idx.take(test)
        yield train, test

from sklearn.utils.metaestimators import if_delegate_has_method
class StripUnlabelled(sklearn.base.BaseEstimator):
    def __init__(self, estimator):
        self.estimator = sklearn.base.clone(estimator)
    def fit(self, X, y, **kwargs):
        return self.estimator.fit()
    @if_delegate_has_method(delegate='estimator')
    def predict(self, X):
        return self.estimator.predict(X)
    # and similar for decision_function, predict_proba, score, etc.

rawDescription: Parameters grid search with different text sets for dictionary creation and cross validation


code: [row.text for row in rows]

rawDescription: Python: BeautifulSoup extract string between div tag by its class


rawDescription: grouping pandas dataframe by two columns (or more)?

description: Grouping pandas dataframe by two columns (or more)


code:
shipped
info

rawDescription: Inner joining two columns in Pandas

description: Inner joining two columns in Pandas


code: (['Hello', 'Hello', 'Hello', 'Hello'], ['World', 'World', 'World', 'World'])

rawDescription: can ipython parallel operate across different sets of nodes

description: Can ipython parallel operate across different sets of nodes


rawDescription: How do I operate on the actual object, not a copy, in a python for loop?

description: Operate on the actual object, not a copy, in a python for loop


code:
class ChangeHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        print(event)

rawDescription: python watchdog runs more than once

description: Python watchdog runs more than once


code:
import subprocess
import time

# open file
with open("Clean.txt", "r") as fo:

     # read line by line
     for line in fo:

         # remove ENTER and SPACES from single line
         line = line.strip()

         # call "python pump.py"
         p = subprocess.Popen(["python","pump.py"], stdin=subprocess.PIPE)

         # or "python3 pump.py"
         #p = subprocess.Popen(["python3","pump.py"], stdin=subprocess.PIPE)

         #time.sleep(2)

         # send line to standard input
         #p.stdin.write(bytes(line, 'ascii')) # python 3
         p.stdin.write(line) # python 2

         print("injected string:", line)

rawDescription: Passing argument from one python script to another


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

rawDescription: Combine elements of a list with all possible separators


rawDescription: Split a string with whitespaces following a template


code:
import os
os.system("ls -1")

rawDescription: How to run a python script that takes command line arguments with a double click

description: Run a python script that takes command line arguments with a double click


code: corner_indices = np.random.choice(len(llcorners), size=size)

rawDescription: Pythonic way to generate random uniformly distributed points withing hollow square lamina


code:
c = pycurl.Curl()
c.setopt(c.URL, str(GEOSERVER_URL + '/rest/styles?name=' + path.basename(sldFile)))
c.setopt(pycurl.POST, 1)
filesize = path.getsize(sldFile)
f = open(sldFile,'rb')
c.setopt(pycurl.POSTFIELDSIZE, filesize)
c.setopt(pycurl.READFUNCTION, FileReader(f).read_callback)
c.setopt(pycurl.HTTPHEADER, ["Content-type: application/vnd.ogc.sld+xml"])
c.setopt(pycurl.USERPWD, GEOSERVER_USER + ':' + GEOSERVER_PASSWORD)

c.perform()
f.close()

rawDescription: POSTing a file and passing a parameter using pycurl


rawDescription: Looping through a 2D numpy array (e.g. to create a line)


code:
import multiprocessing as mp
from nose import with_setup

pool = None
out  = None

def f(i):
    return i ** 2

def setup_func():
    global pool
    global out
    pool = mp.Pool()
    out  = pool.map(f, range(10))

@with_setup(setup_func)
def test_pool():
    """Really simple test that relies on the output of pool.map.
    The actual tests are much more complicated, but this is all
    that is needed to produce the problem."""
    global out
    ref_out = map(f, range(10))
    assert out == ref_out

if __name__ == '__main__':
    test_pool()

rawDescription: testing python multiprocessing pool code with nose

description: Testing python multiprocessing pool code with nose


rawDescription: Python Program gets hung up on certain numbers


rawDescription: filter the values of dictionary items in a list by their key in python

description: Filter the values of dictionary items in a list by their key in python


code:
def find_element(nested_lst, what):
    for idx, sublst in enumerate(nested_lst):
        try:
            idx2 = sublst.index(what)
            return (idx, idx2)
        except ValueError:
            pass

birds = ['duck', 'chicken', 'goose']
cats = ['tiger', 'lion']
humans = ['human']
find_element([birds, cats, humans], 'human')
find_element([birds, cats, humans], 'gator')  # returns None if not found.
find_element([birds, cats, humans], 'tiger')

rawDescription: In python, given a list of lists, how do you identify the index of a matching element?


code: return 'Decimal("%s")' % str(self)

rawDescription: string quoting issues in doctests

description: String quoting issues in doctests


code: {key: value for key, value in d1.items() if value > 0}

rawDescription: Filter values of dictionary

description: Filter values of dictionary


rawDescription: Efficiently reduce a big np.array

description: Efficiently reduce a big np.array


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

f.__doc__ = """
Return the square of the function argument.

Arguments: x - number to square

Return value: x squared

Exceptions: none

Global variables used: none

Side effects: none

Limitations: none
"""

rawDescription: Is there a way to keep docstrings separate from the functions they document?


rawDescription: Speeding up reading of very large netcdf file in python


code: re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)

rawDescription: Python Regex replace multiple occurencies of parts of a string


code:
outputs = np.matrix(outputs)
(sum(exp(outputs), axis=1) * ones((1,shape(outputs)[0]))).shape

rawDescription: Numpy: multiplying by a vector of ones

description: Numpy: multiplying by a vector of ones


code:
if "a":
    print ("True!")
else:
    print("False!")

if "aadasgabherbasdvc23d3wv":
    print ("True!")
else:
    print("False!")

if "":
    print ("True!")
else:
    print("False!")

if None:
    print ("True!")
else:
    print("False!")

rawDescription: Sorting a csv file alphabetically on Python


rawDescription: Simple MongoDB query slow

description: Simple MongoDB query slow


code:
url='https://scholar.google.gr/citations?user=aFYdVoYAAAAJ&hl=el&view_op=citations_histogram'
webpage=urlopen(url)
soup=BeautifulSoup(webpage)
len(soup.find_all('span', class_='gsc_g_al'))
[el.string for el in soup.find_all('span', class_='gsc_g_al')]
[el.string for el in soup.find_all('span', class_='gsc_g_t')]

rawDescription: beautiful soup doesn't find all the tags

description: Beautiful soup doesn't find all the tags


rawDescription: Alternatives to Qt.escape in PySide?

description: Alternatives to Qt.escape in PySide


code:
measurements = [
    {'city=Dubai': True, 'city=London': True, 'temperature': 33.},
    {'city=London': True, 'city=San Fransisco': True, 'temperature': 12.},
    {'city': 'San Fransisco', 'temperature': 18.},
]

rawDescription: How can i vectorize list using sklearn DictVectorizer

description: Vectorize list using sklearn DictVectorizer


rawDescription: Get index of the top n values of a list in python


rawDescription: How to get enumerated results from a query in Django?

description: Get enumerated results from a query in Django


code:
Solution
def someFunction(a, b):
    return a + b

def f(df):
    df = df.copy()
    ismi = isinstance(df.columns, pd.MultiIndex)
    if ismi:
        df = df.stack()

    df['c'] = someFunction(df['a'], df['a'])

    if ismi:
        df = df.unstack()

    return df

rawDescription: Operating on pandas dataframes that may or may not be multiIndex


code:
import pycurl

with open('test.json') as json:
    data = json.read()

    c = pycurl.Curl()
    c.setopt(pycurl.URL, 'https://api.smartsheet.com/1.1/sheets')
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDS, data)
    c.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer 26lhbngfsybdayabz6afrc6dcd',
                                 'Content-Type: application/json'])
    c.perform()

rawDescription: How can i execute the following code using pycurl

description: Execute the following code using pycurl


code:
def main():
    dictionary("words.txt")
    anagramsinput = anagrams(input("unjumble words here: "))
    for anagram in anagramsinput:
        if anagram in dic_list: # don't break, loop over every possibility
            print(anagram)

rawDescription: Anagram not matching up (string to list), Python


code:
def groupby(seq, func):
    groups = {}
    for x in seq:
        y = func(x)
        groups.setdefault(y, []).append(x)
    return groups

rawDescription: Filter latest items in a list

description: Filter latest items in a list


rawDescription: Python: simplest way to get list of values from dict?


code: __all__ = ['A'] + [name for name in iterable if condition(name)]

rawDescription: False Unused Import Statement in PyCharm?


code:
def createFreeSpacesNew(first_byte, last_byte):
    return ['555555 0 0 "FREE: [{}.{}]"'.format(x,y) for x in range(first_byte + 1, last_byte) for y in range(8)]
pprint.pprint(createFreeSpacesNew(4,7))

rawDescription: Modifying this simple array creation function on a more Pythonic way


code:
[
    [u'Harlem-148 Street', u'7 Avenue'],
    [u'145 Street', u'Lenox Avenue'],
    ...
    [u'Van Siclen Avenue', u'Livonia Avenue'],
    [u'New Lots Avenue', u'Livonia Avenue']
]

rawDescription: Scrape MTA Subway data?

description: Scrape MTA Subway data


code:
url(r'^login/$',
    'django.contrib.auth.views.login',
    {'template_name': '<your template>'}
    )

rawDescription: Django 1.6: Redirect to last page after login not working


code:
from subprocess import PIPE, Popen

p = Popen(['/path/to/myapp', '-i', '-'], stdin=PIPE, stdout=PIPE)
stdout, _ = p.communicate('\n'.join(inbuff).encode('utf-8'))
outbuff = stdout.decode('utf-8').splitlines()

rawDescription: Can you open stdin as a file on MS Windows in Python?

description: Open stdin as a file on MS Windows in Python


rawDescription: Unique value in list of lists in Python

description: Unique value in list of lists in Python


rawDescription: Convert float into time (hour.minute) in python


rawDescription: how to merge some columns data from different txt files in Python?

description: Merge some columns data from different txt files in Python


code: df['end_date'] = np.nan

rawDescription: Modifying a column depending on multiple conditions from another column, Pandas


code:
from timeit import timeit
timeit("[]")
timeit("list()")
timeit("{}")
timeit("dict()")

rawDescription: [] and {} vs list() and dict(), which is better?


code: formReview = SQLFORM(db.reviews,fields = ['game_id', 'title','review']).process()

rawDescription: Web2Py getting/posting values

description: Web2Py getting/posting values


code:
#!py

import yaml

def run():
  systems = []
  with open('systems.yml', 'r') as f:
    data = yaml.safe_load(f)

    for system in data:
      if not 'name' in system:
        system['name'] = "%s_%s_%s" % (system['project'], system['customer'], system['stage'])

      if not 'home' in system:
        system['home'] = "/home/%s" % name

      systems.append(system)

  return {"systems": systems}

rawDescription: SaltStack: Properties (computed values) for data from SLS files?


code:
from mock import MagicMock

class my_read_side_effect():
    def __init__(self,data=""):
        self._data = data
    def __call__(self, l=0): #That make my_read_side_effect a callable
        if not self._data:
            return ""
        if not l:
            l = len(self._data)
        r, self._data = self._data[:l], self._data[l:]
        return r

mock_file = MagicMock(spec=file)
mock_file.read.side_effect = my_read_side_effect("abcdefghijklmnopqrs")
assert "abcdef" == mock_file.read(6)
assert "ghijklm" == mock_file.read(7)
assert "nopqrs" == mock_file.read()

rawDescription: Mock file read method using size variable


code:
input_string = "this is a sample test"
words = input_string.split()
nwords = []
for i in words:
    rword = ""
    for c in reversed(word):
        rword += c
    nwords.append(rword)
output_string = " ".join(nwords)
print(output_string)

rawDescription: How to preserve and reverse a string?

description: Preserve and reverse a string


rawDescription: How to sort a structured list of stock data for later access in Python?

description: Sort a structured list of stock data for later access in Python


code:
student1: 45
student2: 7986

rawDescription: How Do I Change the Data Stored in a Text File in Python?


code:
B = np.zeros(A.max() + 1)
B[ind] = ind
B

rawDescription: Rearrange row elements using numpy in Python


code:
numpy_surface = numpy.frombuffer(surface.get_buffer())
numpy_surface[...] = numpy.frombuffer(base)
del numpy_surface

rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


code:
from kivy.utils import platform
...
if platform() == 'android':
    BlaClass = autoclass('java.bla.BlaClass')
...

rawDescription: Pyjnius import jar file

description: Pyjnius import jar file


code:
four = "laup"
from collections import Counter
four = Counter(four)

folder = ["paul","joshua","other","asdf","joshua","aa","hello"]

for word in folder:
    wordstrings = Counter(word)
    if not wordstrings - four:
            print(word)

rawDescription: sets operations on lists

description: Sets operations on lists


code:
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.4.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(629, 451)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.tab)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout_3.addLayout(self.gridLayout, 1, 0, 1, 1)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.pushButton_4 = QtWidgets.QPushButton(self.tab)
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout_7.addWidget(self.pushButton_4)
        self.pushButton_2 = QtWidgets.QPushButton(self.tab)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_7.addWidget(self.pushButton_2)
        self.pushButton_15 = QtWidgets.QPushButton(self.tab)
        self.pushButton_15.setObjectName("pushButton_15")
        self.horizontalLayout_7.addWidget(self.pushButton_15)
        self.gridLayout_3.addLayout(self.horizontalLayout_7, 0, 0, 1, 1)
        self.tableView = QtWidgets.QTableView(self.tab)
        self.tableView.setObjectName("tableView")
        self.gridLayout_3.addWidget(self.tableView, 2, 0, 1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab_2)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_11.setObjectName("horizontalLayout_11")
        self.pushButton_6 = QtWidgets.QPushButton(self.tab_2)
        self.pushButton_6.setObjectName("pushButton_6")
        self.horizontalLayout_11.addWidget(self.pushButton_6)
        self.pushButton_5 = QtWidgets.QPushButton(self.tab_2)
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout_11.addWidget(self.pushButton_5)
        self.pushButton_3 = QtWidgets.QPushButton(self.tab_2)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_11.addWidget(self.pushButton_3)
        self.verticalLayout.addLayout(self.horizontalLayout_11)
        self.verticalLayout_3.addLayout(self.verticalLayout)
        self.tableView_2 = QtWidgets.QTableView(self.tab_2)
        self.tableView_2.setObjectName("tableView_2")
        self.verticalLayout_3.addWidget(self.tableView_2)
        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.tab_3)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_13 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_13.setObjectName("horizontalLayout_13")
        self.pushButton_19 = QtWidgets.QPushButton(self.tab_3)
        self.pushButton_19.setObjectName("pushButton_19")
        self.horizontalLayout_13.addWidget(self.pushButton_19)
        self.pushButton_18 = QtWidgets.QPushButton(self.tab_3)
        self.pushButton_18.setObjectName("pushButton_18")
        self.horizontalLayout_13.addWidget(self.pushButton_18)
        self.pushButton_7 = QtWidgets.QPushButton(self.tab_3)
        self.pushButton_7.setObjectName("pushButton_7")
        self.horizontalLayout_13.addWidget(self.pushButton_7)
        self.verticalLayout_4.addLayout(self.horizontalLayout_13)
        self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_12.setObjectName("horizontalLayout_12")
        self.verticalLayout_4.addLayout(self.horizontalLayout_12)
        self.tableView_3 = QtWidgets.QTableView(self.tab_3)
        self.tableView_3.setObjectName("tableView_3")
        self.verticalLayout_4.addWidget(self.tableView_3)
        self.tabWidget.addTab(self.tab_3, "")
        self.horizontalLayout.addWidget(self.tabWidget)
        self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout_5.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout_5.addWidget(self.lineEdit)
        self.gridLayout_2.addLayout(self.horizontalLayout_5, 1, 0, 1, 1)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem)
        self.pushButton_17 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_17.setObjectName("pushButton_17")
        self.horizontalLayout_6.addWidget(self.pushButton_17)
        self.pushButton_16 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_16.setObjectName("pushButton_16")
        self.horizontalLayout_6.addWidget(self.pushButton_16)
        self.gridLayout_2.addLayout(self.horizontalLayout_6, 2, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 629, 21))
        self.menubar.setObjectName("menubar")
        self.menu_File = QtWidgets.QMenu(self.menubar)
        self.menu_File.setObjectName("menu_File")
        self.menuEdit = QtWidgets.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        self.menuVer = QtWidgets.QMenu(self.menubar)
        self.menuVer.setObjectName("menuVer")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menu_File.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuVer.menuAction())

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(2)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_4.setText(_translate("MainWindow", "Agregar profesor"))
        self.pushButton_2.setText(_translate("MainWindow", "Borrar profesor"))
        self.pushButton_15.setText(_translate("MainWindow", "Editar profesor"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Profesores"))
        self.pushButton_6.setText(_translate("MainWindow", "Agregar seccion"))
        self.pushButton_5.setText(_translate("MainWindow", "Editar seccion"))
        self.pushButton_3.setText(_translate("MainWindow", "Borrar seccion"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Secciones"))
        self.pushButton_19.setText(_translate("MainWindow", "Agregar clase"))
        self.pushButton_18.setText(_translate("MainWindow", "Editar clase"))
        self.pushButton_7.setText(_translate("MainWindow", "Borrar clase"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Horarios"))
        self.label.setText(_translate("MainWindow", "TextGoesHere"))
        self.pushButton_17.setText(_translate("MainWindow", "Aceptar"))
        self.pushButton_16.setText(_translate("MainWindow", "Cancelar"))
        self.menu_File.setTitle(_translate("MainWindow", "&File"))
        self.menuEdit.setTitle(_translate("MainWindow", "Edit"))
        self.menuVer.setTitle(_translate("MainWindow", "Ver"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

rawDescription: Can't make PyQt5 Gui work, python3

description: Can't make PyQt5 Gui work, python3


rawDescription: Django – Use a template tag within a template tag?


code: np.sum(A.conj()*B, axis=0)

rawDescription: Is there an equivalent Matlab dot function in numpy?


code: all(i in B for i in A)

rawDescription: Comparing 2 lists out of order

description: Comparing 2 lists out of order


rawDescription: python print in format way unknow list length

description: Python print in format way unknow list length


code: joined_string = ','.join(l)

rawDescription: Combining elements of a list in python to a single element


code:
self.comboBox_2.clear()
for pixmap, text in list1:
    self.comboBox_2.addItem(QIcon(pixmap), text)

rawDescription: In pyqt how do I add items in a combobox?


rawDescription: remove rows which have a specific attribute less than or equal to 0

description: Remove rows which have a specific attribute less than or equal to 0


code:
import re
pat = re.compile(r'\[.*\]')
b = pat.search(a).group(0)
b

rawDescription: Extract square-bracketed text from a string


code:
class Wildcard(object):
    def __eq__(self, other):
        return True

w = Wildcard()
w == 10
10 == w
class Joker(object):
    def __eq__(self, other):
        return False

j = Joker()
w == j
j == w

rawDescription: How can I make a Python object always return true for an equality test?

description: Make a Python object always return true for an equality test


code:
ts = TimeStamp.get_by_id("TIMESTAMP")
ts.put()

rawDescription: Easiest way to store a single timestamp in appengine


code:
from winreg import *
import os
import platform

import sys, time
import win32api as wa, win32con as wc, win32service as ws

def registrySetKey(hive, regpath, key, type, value):
    try:
        reg = OpenKey(hive, regpath, 0, KEY_ALL_ACCESS)
    except EnvironmentError:
        try:
            reg = CreateKey(hive, regpath, 0, KEY_ALL_ACCESS)
            SetValueEx(reg, key, None, type, value)
            CloseKey(reg)
        except:
            print("*** Unable to register path %s, key %s!" % (regpath, key))
            return
        print("--- Python", version, "is now registered!")
        return
    try:
        if (QueryValue(reg, key) == value):
            return
        else:
            SetValueEx(reg, key, None, type, value)     # added
    except:
        SetValueEx(reg, key, None, type, value)
    CloseKey(reg)

reg = CreateKey(HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf')

registrySetKey(HKEY_LOCAL_MACHINE,
               r'Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf',
               '', REG_SZ, '@SYS:Does_Not_Exist')

rawDescription: creating a "@" entry with python using winreg

description: Creating a "@" entry with python using winreg


code:
#! /usr/bin/env python
from flask_root import applicaiton

if __name__ == '__main__':
    application.manager.run()

rawDescription: Python clean imports for models - SQL Alchemy


code:
def memoize(f): # Memoize a given function f
    def memf(*x):
        print("Memoized call.")
        if x not in memf.cache:
            print("Filling cache.")
            memf.cache[x] = f(*x)
        else:
            print("Cache retrieve.")
        return memf.cache[x]
    memf.cache = {}
    return memf

rawDescription: Memoization python function

description: Memoization python function


code:
from django.conf.urls import url, patterns

urlpatterns = patterns('your_app.views',
    url(r'^some-path/(?P<devise>[-\w]+)/$', 'affiche_all', name='affiche_all'),
)

rawDescription: python redirect to another view

description: Python redirect to another view


code:
def f(t, x):
    return -2 * x

rawDescription: How to find the number of times the ODE's derivative is called in one invocation.

description: Find the number of times the ODE's derivative is called in one invocation.


code:
import bs4
s= bs4.BeautifulSoup("<asd><xyz>asd</xyz>")
s
s.body.contents[0]

rawDescription: How to auto-close xml tags in truncated file?

description: Auto-close xml tags in truncated file


code: result = [v[2] for k in sorted(my_dict) for v in my_dict[k]]

rawDescription: Getting a list of values from dictionary when values are tuples within lists?


code: "C:\Program Files\Windows NT\Accessories\Wordpad.exe" "%1"

rawDescription: Python script losing arguments when run from PATH on Windows


code:
for i in range(len(a)):
    for j in range(len(a[i])):
        b[i][j] = a[i][j] + 1

rawDescription: numpy iterating over multidimensional array

description: Numpy iterating over multidimensional array


rawDescription: More numpy way of iterating through the 'orthogonal' diagonals of a 2D array


rawDescription: Python: Detect number separator symbols and parse into a float without locale


code:
from itertools import groupby
# sort posts by date descending first
# should be done with database query, but here's how otherwise
posts = sorted(posts, key=lambda: post.posted_on, reverse=True)
by_date = groupby(posts, key=post.posted_on.date)
return render_template('posts.html', by_date=by_date)

rawDescription: Render lists of posts grouped by date

description: Render lists of posts grouped by date


code:
d = defaultdict(int)
for w in words: d[w] += 1

rawDescription: Python: count occurrences in a list using dict comprehension/generator


code:
class MetaTask(type):
    def __init__(cls, name, bases, clsdict):
        if 'run' in clsdict:
            def new_run(self):
                print('before')
                clsdict['run'](self)
                print('after')
            setattr(cls, 'run', new_run)

class Task(object):
    __metaclass__ = MetaTask

class MyTask(Task):
    def run(self):
        #successful override!
        pass

task = MyTask()
task.run()

rawDescription: Python: Decorating a class method that is intended to be overwritten when inherited


code:
import os
import magic

for dirpath, dirnames, filenames in os.walk('/path/to/directory'):
    for filename in filenames:
        fullpath = os.path.join(dirpath, filename)
        if 'text' in magic.from_file(fullpath):
            print(fullpath)

rawDescription: How to use os.walk to only list text files

description: Use os.walk to only list text files


code: session['key'] = your_login_function(request.form.get('username'), request.form.get('password'))

rawDescription: Flask: Login without authentication

description: Flask: Login without authentication


rawDescription: Using lists to sort

description: Using lists to sort


code:
x = np.genfromtxt("example.txt", dtype=None)
print(x[0])

rawDescription: Reading ASCII file in Python (numpy-array?)


code:
from subprocess import check_output
cmd = 'find /media/pi/*/config.txt'
out = check_output(cmd,shell=True)

rawDescription: python check output find command not working

description: Python check output find command not working


code:
import csv
writer = csv.writer(open("file.csv","w"))
for row in array:
     writer.writerow(str(row))

rawDescription: Save tuple of numpy arrays to disk?

description: Save tuple of numpy arrays to disk


code: result = oRS.GetRows(1)

rawDescription: How do I change ADO ResultSet format in python?

description: Change ADO ResultSet format in python


rawDescription: How do I generate a file using the mac os9 line terminators?

description: Generate a file using the mac os9 line terminators


code:
import lxml.html
import urllib

response = urllib.urlopen('http://www.codecademy.com/username')
tree = lxml.html.parse(response)
# tree.write('/tmp/test.html')
root = tree.getroot()
print(root.find_class('stat-count'))

rawDescription: Why is lxml not finding this class?

description: Why is lxml not finding this class


rawDescription: How to retrieve all indexes from pandas DataFrame

description: Retrieve all indexes from pandas DataFrame


code:
for dir in list2:
    for path in list1:
        if dir in path:
            print(path)

rawDescription: Matching substring in another string

description: Matching substring in another string


rawDescription: Finding common elements from two lists of lists


code:
def process_list(_list):
    return map( lambda x: process_list(x) if type(x)==list else x+1, _list )

rawDescription: matching list structure other than map() in python

description: Matching list structure other than map() in python


code:
z, fig = myfun(2,3)  #  nothing is shown
plt.show(fig)        #  now show the figure

rawDescription: Python controlling figure outputs from functions


code:
files = sorted((f for f in os.listdir(path) if f.find(name) != -1),
               key=lambda f: os.stat(os.path.join(path, f)).st_mtime)
recent = files[-1]

rawDescription: Python Find the most recent file with a specific string in the filename


code:
from subprocess import Popen, PIPE
pipe = Popen('ls', shell=True, stdout=PIPE)

for line in pipe.stdout:
    print(line.strip())

rawDescription: Python: Nice way to iterate over shell command result


code:
with open(r'C:\test.csv', 'a', newline='') as write_file:
    sevwrite = csv.DictWriter(write_file, ('High', 'Severity', 'Medium', 'Info', 'Low'))
    sevwrite.writerow(severity)

rawDescription: Counting occurence of words in CSV column and writing to another CSV?


code:
with open(filename, 'a') as f:
    [f.write(line + '\n') for line in new]

rawDescription: How to compare all lines in some file with another line?

description: Compare all lines in some file with another line


code: (lambda i: lambda x: x+i)(i)

rawDescription: Have Python 2.7 functions remember value and not reference? Closure Weirdness


code:
def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

rawDescription: Can you list the keyword arguments a Python function receives?

description: List the keyword arguments a Python function receives


rawDescription: How to import and create my class from my module?

description: Import and create my class from my module


code: [row[x] for x in range(1, len(row) - 1)]

rawDescription: A single CSV column includes commas - Python


code: name = getattr(callable, '__name__', 'Unknown')

rawDescription: Do all callables have __name__?

description: Do all callables have __name__


code:
# TODO: bound/error checking
tile_under_mouse = map[w_y][w_x]

rawDescription: Python 3: Find Index of Square in grid, based on Mouse Coordinates


rawDescription: Profiling self and arguments in python?

description: Profiling self and arguments in python


code:
MedicalFile.objects.annotate(
    maxdate=Max(
        'patient__files__date'
        )).filter(
            maxdate=F('date'),
            diagnosis="flu").select_related(
                'patient'
            )

rawDescription: Django ORM: filter primary model based on chronological fields from related model


code:
for index, row in enumerate(data):
    print('Row %d: %f' % (index + 1, sum(float(num) for num in row)))

rawDescription: return index for rows in csv module python

description: Return index for rows in csv module python


code: common = [k  for k in Dict if len(set(inp).intersection(Dict[k].values())) == len(inp)]

rawDescription: dictionary of dictionaries, get keys in common for values

description: Dictionary of dictionaries, get keys in common for values


rawDescription: What does '[0]' mean in Python?

description: What does '[0]' mean in Python


rawDescription: BeautifulSoup not finding parents

description: BeautifulSoup not finding parents


code:
import ast
ast.literal_eval("0xaf")
int("af", 16)

rawDescription: How does the following code snippet work?


code: value = convert("5", "int")

rawDescription: use type() information to cast values stored as strings

description: Use type() information to cast values stored as strings


code:
from lxml.html import fromstring
s = """<input type="hidden" name="question" value="1234">"""
doc = fromstring(s)
doc.value

rawDescription: value attribute for lxml.html

description: Value attribute for lxml.html


rawDescription: A Transpose/Unzip Function in Python (inverse of zip)


code:
with open('grocery_stock.txt','r') as file:
    grocery_stock = {key: value for key, *value in (line.split() for line in file if line.strip())}

rawDescription: Adding a '\n' to the end of my dictionary when writing it to file


code:
...
porsche_container = { myPorsche1, myPorsche2 }

rawDescription: Create and retrieve object list in Python


rawDescription: Groupby complex function

description: Groupby complex function


code:
while True:
    elm = driver.find_element_by_class_name('next')
    if 'inactive' in elm.get_attribute('class'):
        break;
    elm.click()

rawDescription: Python Selenium clicking next button until the end


code:
x_data = tbdata[condition]['g0-r0']
y_data = tbdata[condition]['g0']
plt.plot(x_data, y_data, '.')

rawDescription: Conditions with Numpy

description: Conditions with Numpy


code:
g = self.session.query(Group).\
filter(Group.group_name == group_name).one()
...
g.append(user) # append not found

rawDescription: Removing/Adding an Object from a Collection in SQLAlchemy


rawDescription: Python index min value list of list

description: Python index min value list of list


code:
import numpy
numpy.random.seed(29)
d = numpy.random.randint(0, 2, size=(3,3,3))
d

rawDescription: Creating a 3D plot from a 3D numpy array


code:
class Delegate:
    def __init__(self, cls, obj):
        self._delegate_cls = cls
        self._delegate_obj = obj
    def __getattr__(self, name):
        if name in vars(self._delegate_obj):
            return getattr(self._delegate_obj, name)
        x = getattr(self._delegate_cls, name)
        if hasattr(x, "__get__"):
            return x.__get__(self)
        return x

rawDescription: python: super()-like proxy object that starts the MRO search at a specified class

description: Python: super()-like proxy object that starts the MRO search at a specified class


code:
def doppelstring(s):
    max_vs = (''.join(itertools.islice(g, 2)) for k, g in itertools.groupby(s))
    components = ([s[:l + 1] for l in range(len(s))] for s in max_vs)
    return [''.join(letters) for letters in itertools.product(*components)]

rawDescription: python limit repeating letters

description: Python limit repeating letters


rawDescription: Stuck at comparing date of birth in the form yyyy/mm/dd


code:
import json
from django.db.models.fields.files import ImageFieldFile

class EnhancedJSONEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode Django "ImageFieldFile"s.
    """

    def default(self, o):
        if isinstance(o, ImageFieldFile):
            # Treat ImageFieldFile as a unicode string
            return super(EnhancedJSONEncoder, self).default(unicode(o))
        else:

            return super(EnhancedJSONEncoder, self).default(o)

rawDescription: json.dumps in python over a list of user-defined objects

description: Json.dumps in python over a list of user-defined objects


code:
print("Getting anagrams and saving them... {}/{} or: {:.0%} done.".format(
          progress, total, progress / total),
      end="\r")

rawDescription: Displaying a floor division

description: Displaying a floor division


code:
from bs4 import BeautifulSoup
import urllib2
import re

html = urllib.urlopen('someURL').read()
soup = BeautifulSoup(html)
texts = soup.findAll(text=True)

def visible(element):
    if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
        return False
    elif re.match('<!--.*-->', str(element)):
        return False
    return True

visible_texts = filter(visible, texts)

rawDescription: How do you convert Python's urllib2.urlopen() to text?

description: Convert Python's urllib2.urlopen() to text


code:
with open('Supercars', 'rb') as f:
   data = []
   while True:
       try:
           data.append(pickle.load(f))
       except EOFError:
           break
print(x for x in data if x.Color == 'red')

rawDescription: Iterating over particular attributes of instances of objects in python


code:
for thing in Thing.List.values():
            if thing:
                if "person" in thing.attrs:
                    if "spawner" in thing.attrs:
                        thing.tick()

rawDescription: Python too slow - Can I rewrite engine in lower level and cp scripts?


code:
ss="""
def foo(x):
    return 5+x
"""

a=5
func=run_user(ss)
result=func(a)     #result = 10

rawDescription: Python: have a user-defined function as an input while keeping the source-code inaccessible?


code:
[['ServerA', 'Envname1,Envname2', 'abc', 'xyz'],
 ['ServerB', 'Envname3,Envname5', 'aaa', 'bbb'],
 ['ServerC', 'EnvName4', 'uuu', 'vvv'],
 ]

rawDescription: grouping list of list in python for a particular element

description: Grouping list of list in python for a particular element


rawDescription: How to get id from url to use in relationship database?

description: Get id from url to use in relationship database


code:
def find_nearest(elt):
    preceding = elt.xpath('preceding::*/@href')[::-1]
    following = elt.xpath('following::*/@href')
    parent = elt.xpath('parent::*/@href')
    for href in roundrobin(parent, preceding, following):
        return href

rawDescription: Find nearest link with BeautifullSoup (python)


code:
def my_property(method):
    name = method.__name__
    return MyDescriptor(name, postprocess)

class Example(object):
    @my_property
    def prop1(self): pass
    @my_property
    def prop2(self): pass

rawDescription: Implementing Python persistent properties


code:
def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines
with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable (list).
    print(contents)

rawDescription: How to Open a file through python

description: Open a file through python


code:
locale1 = Locale('C')
locale2 = Locale('mk_MK.UTF-8')

a_list = ['а', 'б', 'в', 'ј', 'ќ', 'џ', 'ш']
import random
random.shuffle(a_list)

assert sorted(a_list, key=locale1.strxfrm) == ['а', 'б', 'в', 'ш', 'ј', 'ќ', 'џ']
assert sorted(a_list, key=locale2.strxfrm) == ['а', 'б', 'в', 'ј', 'ќ', 'џ', 'ш']

rawDescription: Sorting list of string with specific locale in python


code:
1 - file1file
2 - fi2le
3 - fileeee3
4 - fou4r
5 -  donttouch
6 -  donttouch5either
script.pl

rawDescription: Batch rename directories in reverse order


rawDescription: Only allow one to one mapping between two columns in pandas dataframe


code:
import numpy as np
rows = 200000
cols = 66
new_cols = 69
x = np.random.rand(rows, cols)
x.sort(axis=-1)
y = np.random.rand(rows, cols)
nx = np.random.rand(new_cols)
nx.sort()

rawDescription: Fast interpolation over 3D array for 3D origin x


code: f = lambda y: y + 4

rawDescription: Function parameter semantics (with nested functions)


rawDescription: Python convert wav to mp3

description: Python convert wav to mp3


code:
def somefunction(event):
    global fruit # add this
    blahblahblah
    fruit = 'apples'
    return fruit

rawDescription: Modifying a variable in a function has no result


code:
melted = pd.melt(df, id_vars=['country', 'year', 'men_ed_yrs', 'women_ed_yrs', 'total_ed_yrs'], var_name='year_col')
melted

rawDescription: iterate through df column and return value in dataframe based on row index, column reference

description: Iterate through df column and return value in dataframe based on row index, column reference


code:
from collections import defaultdict
factory = lambda: defaultdict(factory)
defdict = factory()
defdict['one']['two']['three']['four'] = 5
defdict
default_to_regular(defdict)

rawDescription: How to convert defaultdict of defaultdicts [of defaultdicts] to dict of dicts [of dicts]?

description: Convert defaultdict of defaultdicts [of defaultdicts] to dict of dicts [of dicts]


code:
def myfunction():
    start = time.time()
    while time.time() < start + 5:
        do1()
        do2()
        do3()

rawDescription: How to make a function return after 5 seconds passed in Python?

description: Make a function return after 5 seconds passed in Python


code:
s = 'A1:::x1:::B1.A2:::x2::x3::x4:::B2.A3:::x5::x6::x7:::B3.'
slist = (substr for substr in s.split('.') if substr)
result = [x.split(":::",1)[1] for x in slist]

rawDescription: Splitting in python

description: Splitting in python


code:
import os
import sys

module_name = 'foo.bar'
__import__(module_name)
print(os.path.abspath(sys.modules[module_name].__file__))

rawDescription: How to find the location of a python package installed via egg-link?

description: Find the location of a python package installed via egg-link


rawDescription: Is there a one-liner to list a directory two levels deep where the second level is an only-child, but not known?


code:
G = nx.Graph()
G.add_node("ONE", color='red')
G.node["ONE"] # dictionary of attributes
G.add_node("ONE",custom_object=one)
G.node["ONE"] # dictionary of attributes

rawDescription: NetworkX how to access attributes of objects as nodes


code:
for input in raw_input.split():
    if input.lower().strip() in command: # Check to see if input is defined in the dictionary.
       os.chdir(command[input][0]) # Gets Tuple item 0 (e.g. C:\Program Files.....)
       os.startfile(command[input][4]) # Gets Tuple item 1 (e.g. Skype.exe)

rawDescription: Organizing a large python script

description: Organizing a large python script


code:
#plt.hist(myData) # Not necessary if you haven't showed it before.
plt.scatter(bin_centers, func(bin_centers, *popt))
plt.show()

rawDescription: Fit a curve to a histogram in Python

description: Fit a curve to a histogram in Python


code:
Mixin
def properties_mixin(classname, properties):
    #note: create a new class by whatever means necessary
    # e.g., even using exec() as namedtuple does
    # http://hg.python.org/cpython/file/3.2/Lib/collections.py#l235

    # reuse class decorator here
    return set_properties(properties)(type(classname, (), {}))

rawDescription: Can anyone help condense this Python code?


code:
a
cleaver
cleaver[:,None] <= np.arange(a.shape[1])

rawDescription: Different starting indices for slices in NumPy


code:
class TimeForm(forms.Form):
    def build_choices(self, start, stop, incr=1):
        # Form/class method that builds a list of tuples of identical i, i values for forms.ChoiceField
        choice_list = []
        temp_list   = [i for i in range(start, stop, incr)]

        for i in temp_list:
            choice_list.append(('%02d' % i, '%02d' % i))

        return choice_list

    hour_choices   = build_choices(None, 1, 13) # E.g., [('01', '01'), ('02', '02') ... ]
    minute_choices = build_choices(None, 0, 60, 15)
    hour     = forms.ChoiceField(choices=hour_choices)
    minute   = forms.ChoiceField(choices=minute_choices)

rawDescription: Proper way to build Django form/class method


code:
class CustomDateTimeField(models.DateTimeField):
    def to_python(self, value):
        if isinstance(value, DateTimeField):
            return value.rstrip("0")

rawDescription: Django model query truncate column's value


rawDescription: Preventing race condition with ncurses+python


code: df

rawDescription: Averaging unequal length x-y pair data

description: Averaging unequal length x-y pair data


code:
import math
nan = float('nan')
nan
math.isnan(nan)
math.isnan(1)

rawDescription: Getting rid of 'nan' from list value of dictionary , python


code:
fname = raw_input("Enter file name: ")
with open(fname) as f:
    all_data = [float(line[20:50]) for line in f if line.startswith ("X-DSPAM-Confidence:")]
    avg =  sum(all_data) / len(all_data)
    print(all_data)
    print(avg)

rawDescription: work with files, how to calculate Avrg

description: Work with files, how to calculate Avrg


code:
from __future__ import print_function
import time
import gmpy2

def prime_numbers(limit=1000000):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    sub_limit = int(limit**0.5)
    flags = gmpy2.xmpz(1)
    flags[(limit>>1)+1] = 1
    f_scan0 = flags.bit_scan0
    current = 0
    prime = 2
    while prime <= sub_limit:
        yield prime
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1
        flags[2*current*(current+1):limit>>1:prime] = -1
    while prime <= limit:
        yield prime
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1

start = time.time()
result = list(prime_numbers(1000000000))
print(time.time() - start)

rawDescription: Speed up bitstring/bit operations in Python?


rawDescription: Accessing array elements by internal data index and order


code:
def save_file(filename, new_list):
    with open(filename, 'w') as f:
        f.writelines(new_list)

rawDescription: Python, adding a file into another file

description: Python, adding a file into another file


code:
seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

rawDescription: How to convert datetime.timedelta to minutes, hours in Python?

description: Convert datetime.timedelta to minutes, hours in Python


code:
for number in range(start_number, max_number + start_number):
    page = requests.get('http://www.google.com/page' + str(number))

rawDescription: request url with number increase

description: Request url with number increase


code:
g_student = body.create_groups_edges_std(g_groups)
g_groups = body.create_vertex_groups(my_groups)
g_researcher = body.create_groups_edges_res(g_groups)
g_groups = body.create_vertex_groups(my_groups)
g_company = body.create_groups_edges_company(g_groups)
g_groups = body.create_vertex_groups(my_groups)
g_groups_all = body.create_groups_edges(g_groups)

rawDescription: How to assign different colors to different edges using igraph in Python?

description: Assign different colors to different edges using igraph in Python


rawDescription: Losing dimensions of a numpy array

description: Losing dimensions of a numpy array


rawDescription: Finding unique solution puzzle python

description: Finding unique solution puzzle python


code:
def make_tree(task_dict, node):
    tree = {"name": node}
    if task_dict[node]:
        tree["children"] = [make_tree(task_dict, child) for child in task_dict[node]]
    return tree

rawDescription: python: how to convert a dependency dictionary into a dependency tree dictionary to be later converted into json

description: Python: how to convert a dependency dictionary into a dependency tree dictionary to be later converted into json


rawDescription: How to pass an argument to function in a signal?

description: Pass an argument to function in a signal


rawDescription: Python- Function not accepting number as 2 numbers, despite it having a comma


rawDescription: Counting number of strings in a List with Python


code:
class Foo(object):
    def __getattribute__(self, attr):
        myDict = object.__getattribute__(self, '__dict__')
        if attr in myDict and hasattr(myDict[attr], '__get__'):
            return myDict[attr].__get__(self, type(self))
        else:
            return super(Foo, self).__getattribute__(attr)

class D(object):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        pass
    def __get__(self, obj, objtype=None):
        return 5

rawDescription: Why descriptors (in Python) cannot be inserted (placed) in ALREADY initialized object?


code:
def load_sections(filename):
    with open(filename, 'r') as infile:
        line = ''
        while True:
            while not line.startswith('****'):
                line = next(infile)  # raises StopIteration, ending the generator
                continue  # find next entry

            entry = {}
            for line in infile:
                line = line.strip()
                if not line: break

                key, value = map(str.strip, line.split(':', 1))
                entry[key] = value

            yield entry

rawDescription: Parsing data from text file

description: Parsing data from text file


rawDescription: Searching with regex for a number of names in a list?


code:
mylist = ['apple','banana','pear','orange']
values = [3,1,2,4]
[i[1] for i in sorted(zip(values, mylist))]

rawDescription: How to order list according to array values in python?

description: Order list according to array values in python


code:
data = [{'count': 3}, {'day': '2013-07-14'}, {'count': 5}, {'day': '2013-04-14'}]

group=dict()
for d in data:
    for item in d:
        try:
            group[item].append(d[item])
        except KeyError:
            group[item] = [d[item]]

newlist = []
for item in group:
    newlist.append( {'name' : item, 'data' : group[item]} )

rawDescription: Transform a list of dicts to a new list of dicts with a different format


code:
import os
os.system('reboot now')

rawDescription: restart local computer from python

description: Restart local computer from python


code:
gene = lines[0]
sample = lines[11].split(",")
repeat = lines[8]

rawDescription: Python lists, csv, duplication removal

description: Python lists, csv, duplication removal


rawDescription: Convert function arguments to lists

description: Convert function arguments to lists


code:
import numpy as np

def ecdf(sample):

    # convert sample to a numpy array, if it isn't already
    sample = np.atleast_1d(sample)

    # find the unique values and their corresponding counts
    quantiles, counts = np.unique(sample, return_counts=True)

    # take the cumulative sum of the counts and divide by the sample size to
    # get the cumulative probabilities between 0 and 1
    cumprob = np.cumsum(counts).astype(np.double) / sample.size

    return quantiles, cumprob

rawDescription: Empirical cdf in python similiar to matlab's one


code:
from functools import partial

class class_and_instance_method(object):

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

    def __get__(self, obj, type=None):
        first_arg = obj if obj is not None else type
        return partial(self.func, first_arg)

class Parser(object):

    @class_and_instance_method
    def parseFile(self):
        if isinstance(self, type):
            print('using default parser')
        else:
            print('using the current instance')

rawDescription: Python classmethod and(?) instancemethod


code:
import re
name = "Test with-name and_underscore"
print(''.join(x.capitalize() for x in re.compile(r'[^a-zA-Z0-9]').split(name)))

rawDescription: convert strings from special char to no special char

description: Convert strings from special char to no special char


code: morse = encode[c - 'A'];

rawDescription: Predefined text replacements in C++ and Python


code:
for ii,i in enumerate(df.index):
    for jj,j in enumerate(df.keys()):
        plt.text(ii+0.5,jj+0.5,df[i][j])

rawDescription: Labels on pcolormesh

description: Labels on pcolormesh


rawDescription: Creating PPT presentation with Python vs C#


rawDescription: Python removing items from a list that exist in another list but keeping duplicates that aren't in that intersect


code:
def unique(l):
    st, it = set(), iter(l)
    for tup in map(tuple, l):
        if tup not in st:
            yield next(it)
        else:
            next(it)
        st.add(tup)

rawDescription: Removing duplicate lists within another list


code: word_dict = dict.fromkeys(word, False)

rawDescription: Initializing Python dictionary with special pair keys


code: list(percentage_split(x, [0.25]*4))

rawDescription: Separate a list into four parts based on percentage even if the list is not divisible by 10. Python


code:
f = open('test.txt')
f.read()
f.read()
f.seek(0)
f.read()

rawDescription: For loop position in csv reader_Python

description: For loop position in csv reader_Python


code:
ref_key = item[0]
metadata_value = item[1]

rawDescription: Pyramid / SQLAlchemy trouble with joined models


code:
if ser.inWaiting:
   ser.read(len(ser.inWaiting()))

rawDescription: pySerial: port only works the first I use it after I power it on

description: PySerial: port only works the first I use it after I power it on


code:
import maya.cmds as cmds

message = u"File operation cancelled by user supplied callback."

keys = cmds.displayString("_", q=True, keys=True)
for k in keys:
    value = cmds.displayString(k, q=True, value=True)
    if value == message:
        print("Found matching displayString: {}".format(k))

rawDescription: Customize Maya's addCheckCallback pop up message


code:
import wx

class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, pos=(150,150), size=(350,200))

        m_print = wx.Button(self, label="Print")
        m_print.Bind(wx.EVT_BUTTON, self.OnPrint)

    def OnPrint(self, event):
        topobj = objc_object(top.GetHandle())
        topobj.print_(None)

app = wx.App()
top = Frame(title="ObjC Test")
top.Show()

app.MainLoop()

rawDescription: Getting pyobjc object from integer id

description: Getting pyobjc object from integer id


code:
from numpy import zeros
from scipy import io as sio

R = zeros([8,8,530],float)
R += 12.3

sio.savemat('R.mat', {'R': R})

S = sio.loadmat('R.mat')
S
S['R']

rawDescription: Creating a Three Dimensional Matrix structure and writing in mat file in Python


code: mask = summary.iloc[-1] > 220

rawDescription: pandas: dropping columns based on value in last row

description: Pandas: dropping columns based on value in last row


code:
a
v
np.argmax(a == v[:,None],axis=1)

rawDescription: Row wise element search in an array

description: Row wise element search in an array


code:
@c.setter
def c(self,value):
    self.__c

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code: ' AND '.join([ "my_id = '{}'".format(id) for id in ids ])

rawDescription: Combine a list items and string

description: Combine a list items and string


code:
ts = 1340241300
import datetime
from dateutil import tz
dt = datetime.datetime.fromtimestamp(ts).replace(tzinfo=tz.tzutc())
dt

rawDescription: How do you create numpy.datetime64 object from a unix timestamp and set the timezone to UTC?

description: Create numpy.datetime64 object from a unix timestamp and set the timezone to UTC


rawDescription: Pythonic way to "run X before Y if Y fails"?


code:
v1.stop()
v2.stop()

rawDescription: Killing or stopping an active thread

description: Killing or stopping an active thread


code:
import logging
import logging.config

logging.fileConfig('mylog.conf')
logger = logging.getLogger('root')

rawDescription: what is the python(2.5.2)'s logging mechanism? is there log4j look a like library or standard class of python/geodjango will do?

description: What is the python(2.5.2)'s logging mechanism? is there log4j look a like library or standard class of python/geodjango will do


code: kwargs['key_name'] = kwargs['name']

rawDescription: Custom keys for Google App Engine models (Python)


code:
def addtwo (a, b):
    if b == 0:
        return a
    return addtwo (a+1, b-1)

rawDescription: recursive search boolean return function

description: Recursive search boolean return function


rawDescription: Python 2D list slice

description: Python 2D list slice


code:
import itertools

# Adapted from Python Cookbook 2nd Ed. 19.7.
def windows(iterable, length=2, overlap=0):
    """
    Return an iterator over overlapping windows of length <length> of <iterable>.
    """
    it = iter(iterable)
    results = list(itertools.islice(it, length))
    while len(results) == length:
        yield results
        results = results[length-overlap:]
        results.extend(itertools.islice(it, length-overlap))

def magic_function(seq):
    return [' '.join(window) for n in range(len(words)) for window in windows(seq, n + 1, n)]

rawDescription: Given a list of words, make a subset of phrases with them


code: a='value1, value2, value3(a, b, c)', 'value4'

rawDescription: Python nested comma in csv

description: Python nested comma in csv


code: img = Image.open(i)

rawDescription: Convert pyBarcode output to PIL Image file


code:
@do
def write_lines_to_file(lines, filename):
    file_handle = yield open_file(filename)
    for line in lines:
        yield write_data(file_handle, line)
    # alternatively:
    # from effect.fold import sequence; from functools import partial
    # yield sequence(map(partial(write_data, file_handle), lines))
    yield close_file(file_handle)

rawDescription: Python: writing files in functional programming style


code:
# Python 2.7
import Tkinter as tki
from ScrolledText import ScrolledText

class App(object):

    def __init__(self):
        self.root = tki.Tk()

    # create a Text widget with a Scrollbar attached
        self.txt = ScrolledText(self.root, undo=True)
        self.txt['font'] = ('consolas', '12')
        self.txt.pack(expand=True, fill='both')

app = App()
app.root.mainloop()

rawDescription: How to attach a Scrollbar to a Text widget?

description: Attach a Scrollbar to a Text widget


code:
Signal.send(sender, **kwargs)

Signal.send_robust(sender, **kwargs)

rawDescription: how to pass args to a signal

description: Pass args to a signal


code:
# new style method 1; unpack the axes
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax1.plot(x)

rawDescription: plotting autoscaled subplots with fixed limits in matplotlib

description: Plotting autoscaled subplots with fixed limits in matplotlib


code:
from itertools import izip_longest
url_params = dict(izip_longest(*[iter(t)] * 2))

rawDescription: Is there a better way to assign a default value for next()


code: p = (b - a)*p + a*p.ceil()

rawDescription: Sparse random matrix in Python with different range than [0,1]


code:
import numba
@numba.jit("void(i4[:,::1], i4[:,::1], i4[:,::1])")
def computeSumInboundingbox3(bitmap, lines, integral):
    for row in range(lines.shape[0]):
        minX, minY, maxX, maxY = lines[row, 2], lines[row, 3], lines[row, 4], lines[row, 5]
        sumBox = integral[minY,minX] + integral[maxY, maxX] - integral[maxY,minX] - integral[minY,maxX]
        if sumBox != 0:
            bitmap[lines[row, 0],lines[row, 1]] = float(sumBox) / ((maxX - minX) * (maxY - minY))

rawDescription: Python performance using Boost Python doesn't improve


code:
mat = np.empty(shape=(5,6))
mat.fill(np.nan)
mat

rawDescription: How to create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N?

description: Create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N


rawDescription: Confused about list variable assigment

description: Confused about list variable assigment


code: self.data[:] = self.data[1:]

rawDescription: Confusion over how to share and modify class level data between instances.


rawDescription: limit plot title to only show a certain number of decimal places

description: Limit plot title to only show a certain number of decimal places


code:
def intergralFunc(bc):
   integral,err = quad(integrand, 0, 100, args=(bc[0], bc[1]))
   return np.array([100 - integral] * 2)

def solveFunction():
   sol= fsolve(intergralFunc, [5, 5])
   return sol

rawDescription: get all solutions (2 unkowns) from fsolve in python 3.2

description: Get all solutions (2 unkowns) from fsolve in python 3.2


rawDescription: Python - Group neighbor elements into tuples in a list?


code: d.get('foo', {}).get('bar')

rawDescription: Is there a recursive version of Python's dict.get() built-in?


code:
def ols_res(df, xcols,  ycol):
    return sm.OLS(df[ycol], df[xcols]).fit().predict()

rawDescription: Python pandas: how to run multiple univariate regression by group


code: foo, bar = map(d.get, ('foo', 'bar'))

rawDescription: Elegant way to unpack limited dict values into local variables in Python


rawDescription: Grid Permutation Algorithm - Fixed Row Order


code:
d = {
  'name': 'name',
  'date': 'date',
  'amount': 'amount',
}
not d.viewkeys() & {'amount', 'name'}
del d['name']
not d.viewkeys() & {'amount', 'name'}
del d['amount']
not d.viewkeys() & {'amount', 'name'}

rawDescription: python: what is best way to check multiple keys exists in a dictionary?

description: Python: what is best way to check multiple keys exists in a dictionary


code:
import matplotlib.pyplot as plt

COLOR1='r'
COLOR2='b'

def addconnection(i,j,c):
  if(c==1):
    plt.gca().add_patch( plt.Rectangle((j-0.1,-i-0.1),0.2,0.2,fc='y'))
  if(c==2):
    plt.gca().add_patch( plt.Circle((j,-i),radius=0.1,fc='y'))

def drawnodes(s,i):
  global ax
  if(i==1):
    color=COLOR1
    vx=1
    vy=0
  else:
    color=COLOR2
    vx=0
    vy=1

  step=1
  for n in s:
    posx=step*vx
    posy=step*vy

    plt.gca().add_patch( plt.Circle((posx,-posy),radius=0.1,fc=color))
    ax.annotate(n,xy=(posx-len(n)*0.1,-posy+0.15))
    step+=1

f=open('input.txt')
t=f.readlines()
t=map(lambda x: x.replace('(',' ').replace(')',' ').split(':'),t)

set1=set([])
set2=set([])

for x in t:
  s=x[1].split()
  set1.add(s[0])
  set2.add(s[1])

set1=list(set1)
set2=list(set2)

dic={}
for e in zip(set1,xrange(1,len(set1)+1)): dic[(e[0],1)]=e[1]
for e in zip(set2,xrange(1,len(set2)+1)): dic[(e[0],2)]=e[1]

ax=plt.figure(figsize=(max(len(set1),len(set2))+1,max(len(set1),len(set2))+1)).add_subplot(111)
plt.axis([-1,max(len(set1),len(set2))+1,-max(len(set1),len(set2))-1,1])
frame=plt.gca()
frame.axes.get_xaxis().set_ticks([])
frame.axes.get_yaxis().set_ticks([])

drawnodes(set1,1)
drawnodes(set2,2)

for x in t:
  s=x[1].split()
  addconnection(dic[(s[0],1)],dic[(s[1],2)],int(x[2]))

plt.show()

rawDescription: How do i visualize a connection Matrix with Matplotlib?

description: Visualize a connection Matrix with Matplotlib


rawDescription: Convert timestamp since epoch to datetime.datetime


code: "".join([(((c in this.d) and this.d[c]) or c) for c in this.s])

rawDescription: Dissecting a line of (obfuscated?) Python


code: re.findall(r'@(\w+)', ' I want to tell @susan and @rick that I love you all')

rawDescription: python string parse with @ and space

description: Python string parse with @ and space


code:
from collections import Counter
import requests
import bs4
from bs4 import BeautifulSoup
url = "http://www.amazon.in"
r = requests.get(url)
html = BeautifulSoup(r.content)
Counter(tag.name for tag in html.descendants if isinstance(tag, bs4.element.Tag))

rawDescription: Extract the data rich nodes of a webpage using beautifulsoup in python


code:
class MultipleMacroFor(object):
    def __init__(self, macro, names):
        self._macro = macro
        self._names = names

    def get_renderable(self, macro_var):
        return get_template_attribute(self.macro, macro_var)

    def __getattr__(self, name):
        if name in self._names:
            return self.get_renderable(name)
        raise AttributeError(
            "object %s has no attribute '%s'" % (
                type(self).__name__, name)
            )

rawDescription: Python passing in a list of parameters to be used as dynamic properties


code:
nodes = soup.findAll(text=re.compile('[sS]maller.*[rR]eporting.*[cC]ompany'))
nodes[-1].next.next  # last item in list is the only good one... kinda crap

rawDescription: Python BeautifulSoup parsing specific text


code: root.after(100, thread1.start)

rawDescription: Issue with Redirecting stdout to Tkinter text widget with threads


code:
import argparse

class UserAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if len(namespace.passwords) < len(namespace.users):
            parser.error('Missing password')
        else:
            namespace.users.append(values)

class PasswordAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if len(namespace.users) <= len(namespace.passwords):
            parser.error('Missing user')
        else:
            namespace.passwords.append(values)

parser = argparse.ArgumentParser()
parser.add_argument('--password', dest='passwords', default=[], action=PasswordAction, required=True)
parser.add_argument('--user', dest='users', default=[], action=UserAction, required=True)

print(parser.parse_args())

rawDescription: argparse argument dependency

description: Argparse argument dependency


code: 'MATCH(trans.lang_name) AGAINST (%s IN BOOLEAN MODE)' % str_to_match

rawDescription: SQLAlchemy Match Against clause

description: SQLAlchemy Match Against clause


code:
class GetData(object):

    #report_date = '3/1/2016'
    states = ['AL', 'AZ', 'GA', 'IA', 'ID', 'IL', 'MN', 'MS',
              'MT', 'NE', 'NM', 'NV', 'TN', 'UT', 'WI']

    def __init__(self, df_or_file=None, read_func=pd.read_excel, **kwargs):
        if df_or_file is not None:
            if isinstance(df_or_file, (pd.DataFrame, pd.Series, pd.Panel)):
                self.data = df
            elif(os.path.isfile(df_or_file)):
                self.data = read_func(df_or_file, **kwargs)
        else:
            self.data = pd.DataFrame()

    def save(self, filename, savefunc=pd.DataFrame.to_excel, **kwargs):
        savefunc(df, filename, **kwargs)

rawDescription: Python 3.5 - Pandas - Call a method with a for loop from another method


code:
import time
time.sleep(6)

rawDescription: Total time for executing the code--python


code:
list_data = list(range(1, 20))
list_data
arr_index = np.asarray([3, 5, 12])
np.take(list_data,arr_index)

rawDescription: NumPy: 1D numpy array to slice a list

description: NumPy: 1D numpy array to slice a list


code:
data = dataToPython('test.txt')
searchByYear(data,1957)
searchByYear(data,1956)

rawDescription: Write average weather data from a year given by user to a text file


rawDescription: parsing meta tag with Beautiful Soup and Python

description: Parsing meta tag with Beautiful Soup and Python


code: [{i} for i in range(5)]

rawDescription: How can I write a list comprehension to create a list of sets?

description: Write a list comprehension to create a list of sets


code:
largest = None
i = 1024

for k in range(i):
    a = (k ** 4 - 74 * k ** 2 + 173) % 1000033
    if not largest or largest[1] < a:
        largest = (k, a)

print(largest)

rawDescription: Python List Help (Find Biggest number)

description: Python List Help (Find Biggest number)


code:
import codecs
import vdf
d = vdf.load(codecs.open('dota_english.txt', 'r', encoding='utf-16'))

rawDescription: Problems parsing a text file (encoding?)