code:
from tkinter import *

class Application(object):
    def __init__(self, parent):
        self.x = list(range(1000))
        self.labels = []
        self.parent = parent
        self.navigation_frame = Frame(self.parent)
        self.canvas =  Canvas(self.parent, bg='black', width = 200, height = 500)
        self.mainFrame = Frame(self.canvas)
        self.navigation_frame.pack()
        for i in range(100):
            self.labels.append(Label(self.mainFrame, text=str(i)))
            self.labels[i].grid()
        self.back_button = Button(self.navigation_frame, text='Back', command=lambda: self.move(-2))
        self.quick_nav = Entry(self.navigation_frame, width=3)
        self.quick_nav.bind('<Return>', lambda x: self.move(self.quick_nav.get()))
        self.forward_button = Button(self.navigation_frame, text='Forward', command=lambda: self.move(0))

        temp = divmod(len(self.x), len(self.labels))
        self.pages = temp[0] + (1 if temp[1] else 0)

        self.you_are_here = Label(self.navigation_frame, text='Page 1 of ' + str(self.pages))
        self.current_page = 1
        self.back_button.grid(row=0, column=0)
        self.quick_nav.grid(row=0, column=1)
        self.forward_button.grid(row=0, column=2)
        self.you_are_here.grid(row=0, column=3)
        self.scroll = Scrollbar(self.parent, orient = VERTICAL, command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.scroll.set)
        self.scroll.pack(side='right', fill='y')
        self.canvas.pack(side='left', fill='both')
        self.canvas.create_window((4,4), window=self.mainFrame, anchor="nw", tags="frame")

        self.canvas.configure(yscrollcommand = self.scroll.set)
        self.mainFrame.bind("<Configure>", self.update)

    def update(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def move(self, direction):
        if (self.current_page == 1 and direction == -2) or (self.current_page == self.pages and direction == 0):
            return
        if direction in (-2, 0):
            self.current_page += direction + 1
        else:
            try:
                temp = int(direction)
                if temp not in range(1, self.pages+1):
                    return
            except ValueError:
                return
            else:
                self.current_page = temp
        for i in range(len(self.labels)):
            try:
                location = str(self.x[len(self.labels)*(self.current_page - 1) + i])
            except IndexError:
                location = ''
            self.labels[i].config(text=location)
        self.you_are_here.config(text='Page ' + str(self.current_page) + ' of ' + str(self.pages))

if __name__ == '__main__':
    root = Tk()
    app = Application(root)
    root.mainloop()

rawDescription: Display of a large amount of data in a Canvas with a Scrollbar


code:
def zipMap(func, iterable):
    for x in iterable:
        yield x,func(x)

rawDescription: Combine variable and for each loop python


code:
x.data.c = 0
x.data
x.save('d:/temp/new.xlsx', index=False)
x.save('d:/temp/new.csv', savefunc=pd.DataFrame.to_csv, sep=';', index=False)

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


rawDescription: How to display the variable in a tkinter window?

description: Display the variable in a tkinter window


code: df['A_perc'] = df['A']/df['sum']

rawDescription: pandas dataframe create new columns and fill with calculated values from same df

description: Pandas dataframe create new columns and fill with calculated values from same df


code:
def get_counts(Vec1, Vec2):
    c = 0
    counts = []
    counting = False
    for v1, v2 in zip(Vec1, Vec2):
        counts.append(c)
        if v1:
            counting = True
            c = 0
        if v2:
            counting = False
            c = 0
        if counting:
            c += 1

rawDescription: Algorithm to count how many obs there are between two events


code:
import multiprocessing, sys, time

def f(icount, _sleepTime = 1):
    for i in range(icount):
        time.sleep(_sleepTime)
        print(_sleepTime)

def main(args):
    m = multiprocessing.Process(target = f, args=(4, ))
    m.start()
    # f should be sleeping for 1 second so this print statement should come first
    print(m.is_alive())
    m.join()

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

rawDescription: time.sleep hangs multithread function in python

description: Time.sleep hangs multithread function in python


code:
from collections import defaultdict
a = defaultdict(dict)
a['abc']
a['abc']['def'] = 1
a
a['abc']['fgh'] = 2
a

rawDescription: Dictionary of dictionaries in loop in Python


code: alt('hello', 'bye')

rawDescription: Return Alternating Letters in Two Strings of Different Lengths


code: pos = moves[move](pos)

rawDescription: Python dictionaries and select case

description: Python dictionaries and select case


code:
def unzip():
    os.chdir("C:/Users/Luke/Desktop/Cache")
    files = os.listdir(".")
    for x in (files):
        ifh = open((x), "rb")
        byte1 = ifh.read(1)
        byte2 = ifh.read(1)
        if byte1 == b'\x1f' and byte2 == b'\x8b':
            os.rename((x), (x) + ".gz")
            file = gzip.open((x), "rb")
            contents = file.read()
            with open('output.file','w') as ofh:
                ofh.write(contents)

rawDescription: Python: how to create a new file and write contents of variable to it?


code:
def _getfailureheadline(self, rep):
    if hasattr(rep, 'location'):
        fspath, lineno, domain = rep.location
        return '::'.join((fspath, domain))
    else:
        return super()._getfailureheadline(rep)

rawDescription: Change the name of py.test tests

description: Change the name of py.test tests


code:
import json

print(json.loads(ipa))

rawDescription: Python: print unicode string stored as a variable


code:
words, counts = zip(*[('want', 3), ('dtype', 1), ('object', 1)])
pd.Series(counts, words)

rawDescription: How to plot a bar chart if the input data is of type list?

description: Plot a bar chart if the input data is of type list


rawDescription: Extracting a feature by feature name in scikit dict vectorizer


code:
letters={'ł':'l', 'ą':'a', 'ń':'n', 'ć':'c', 'ó':'o', 'ę':'e', 'ś':'s', 'ź':'z', 'ż':'z'}
trans=str.maketrans(letters)
result=text.translate(trans)

rawDescription: Translating letters not in 7bit ASCII to ASCII (like ń to n and ą to a)


code: from first.second import abc

rawDescription: Importing through folders

description: Importing through folders


code: df['diff'] = scalar - df['data']

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
data = (0, 2, 3, 5, 5, 5, 9, 7, 8, 6, 6)
ax.plot(data, 'r-', linewidth=4)

plt.axvline(x=5, ymin=0, ymax=4.0 / max(data), linewidth=4)
plt.text(5, 4, 'your text here')
plt.show()

rawDescription: Using matplotlib to annotate certain points


code:
def statement(bank):
    deposit = 0
    withdrawal = 0
    for transaction in bank:
        if transaction > 0:
            deposit += transaction
        else:
            withdrawal += transaction
    return [deposit, withdrawal]

rawDescription: Function statement() that outputs the sum of the deposit and the sum of the withdraw


code:
score += child.points*math.pow(.1, get_ancestors(child))
score += get_score(child)

rawDescription: Calculate score in a pyramid score system


code:
class BaseListView(MultipleObjectMixin, View):
    """
    A base view for displaying a list of objects.
    """
    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()

        # [snip]
        # some code not related to this omitted
        # [snip]

        context = self.get_context_data()
        return self.render_to_response(context)

rawDescription: Modify context after using form

description: Modify context after using form


rawDescription: Distance between numpy arrays, columnwise


code:
a = np.arange(50)
b = a.reshape((5, 10))
print (b.base is a)

rawDescription: How can I tell if NumPy creates a view or a copy?

description: Tell if NumPy creates a view or a copy


code:
from random import randint

def roll_dice(count, sides=6):
    initial_mins = None
    result = 0
    while count:
        dice = [randint(1, sides) for die in range(count)]
        if initial_mins == None: initial_mins = dice.count(1)
        result += sum(result for result in dice if result != sides)
        count = 2 * dice.count(sides) # number to roll the next time through.
    return (initial_mins, result)

rawDescription: How can I keep track of specific values rolled in a dice-rolling script?

description: Keep track of specific values rolled in a dice-rolling script


code:
# Check each factor to see if it is prime or compound
for i in range(0,len(factors)):
    print (factors[i])
    # Why can't I call checkprime here, like this? It works in the console.
    checkprime(factors[i])

rawDescription: Why does my Python function work in the console, but not when called within code?


code:
import wx
from wx.lib.pubsub import Publisher

class PanelA(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        name = "none, please select an item"
        self.txt = wx.StaticText(self, -1, "You have selected " + name,
                                 (50, 100))
        self.hbox.Add(self.txt, 1, wx.EXPAND|wx.ALL, 30)

    def changeName(self, name):
        self.hbox.Hide(self.txt)
        self.hbox.Remove(self.txt)
        self.txt = wx.StaticText(self, -1, "You have selected " + name, (50, 100))
        self.hbox.Add(self.txt, 1, wx.EXPAND|wx.ALL, 30)

class PanelB(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        self.vbox = wx.BoxSizer(wx.VERTICAL)

        self.listbox = wx.ListBox(self, -1)
        self.hbox.Add(self.listbox, 1, wx.EXPAND|wx.ALL, 20)

        self.btnPanel = wx.Panel(self, -1)
        self.new = wx.Button(self.btnPanel,label='Add', size=(90, 30))
        self.new.Bind(wx.EVT_BUTTON, self.NewItem)

        self.vbox.Add((-1, 20))
        self.vbox.Add(self.new)

        self.btnPanel.SetSizer(self.vbox)
        self.hbox.Add(self.btnPanel, 0.6, wx.EXPAND|wx.RIGHT, 20)
        self.SetSizer(self.hbox)

        self.Bind(wx.EVT_LISTBOX, self.onSelect)

    def onSelect(self, event):
        name_selected = self.listbox.GetStringSelection()
        Publisher().sendMessage("ListBox", name_selected)

    def NewItem(self, event):
        text = wx.GetTextFromUser('Nombre', 'Programa a salvar')
        if text != '':
            self.listbox.Append(text)

class MainFrame(wx.Frame):

   def __init__(self, parent, id, title, *args, **kw):

       wx.Frame.__init__(self, parent, id, title, size = (800,300))
       self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D)
       Publisher().subscribe(self.OnSelect, "ListBox")

       self.lc1 = PanelB(self.splitter)
       self.lc2 = PanelA(self.splitter)
       self.splitter.SplitVertically(self.lc1, self.lc2)

       self.sizer = wx.BoxSizer(wx.HORIZONTAL)
       self.sizer.Add(self.splitter, 1, wx.EXPAND)
       self.SetSizer(self.sizer)
       self.Layout()

       self.Centre()

   def OnSelect(self, name_selected):
       name = name_selected
       self.lc2.changeName(name.data)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MainFrame(None,-1,'Mi aplicacion')
    frame.Show()
    app.MainLoop()

rawDescription: How to rebuild panels in wxpython in function of a variable?

description: Rebuild panels in wxpython in function of a variable


code:
# again, assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_css_selector("a[href='http://www.testsite.com/pageOne.html']")

rawDescription: Python selenium webdriver click functionality


code:
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train = count_vect.fit_transform(your_text)

rawDescription: Text Categorization Python with pre-trained data


rawDescription: How to realize a very big int matrix with 5 string columns in numpy (python3)?

description: Realize a very big int matrix with 5 string columns in numpy (python3)


code: c2.sort(key = lambda row: (row[2],row[1],row[0]))

rawDescription: Sorting a list of lists in Python

description: Sorting a list of lists in Python


code:
m = min(dist(y, x) for y in l)
[y for y in l if dist(x, y) == m]

rawDescription: python - filter minimum element for given condition

description: Python - filter minimum element for given condition


rawDescription: How to append a vector to a matrix in python

description: Append a vector to a matrix in python


code:
grow = GrowingList()
grow[10] = 4
len(grow)
grow

rawDescription: Automatically growing lists in Python

description: Automatically growing lists in Python


rawDescription: print sum of strings as float

description: Print sum of strings as float


code:
def zeroify_if_has_zero(matrix):
    matrix[:] = [[0]*len(row) if 0 in row else row for row in matrix]

rawDescription: How Can One Make This Code More Pythonic?


code:
import re
def cleanUpWords(string):
    only_alpha = re.sub("[^a-zA-Z]", " ", string)
    single_spaces = re.sub("\s+", " ", only_alpha)
    return single_spaces

rawDescription: Trying to use output of one function to influence the next function to count words in text file


code:
"""
IPython launch script
Author: Ely M. Spears
"""

import re
import os
import abc
import sys
import mock
import time
import types
import pandas
import inspect
import cPickle
import unittest
import operator
import warnings
import datetime
import dateutil
import calendar
import copy_reg
import itertools
import contextlib
import collections
import numpy as np
import scipy as sp
import scipy.stats as st
import scipy.weave as weave
import multiprocessing as mp
from IPython.core.magic import (
    Magics,
    register_line_magic,
    register_cell_magic,
    register_line_cell_magic
)
from dateutil.relativedelta import relativedelta as drr

###########################
# Pickle/Unpickle methods #
###########################

# See explanation at:
# < http://bytes.com/topic/python/answers/
#   552476-why-cant-you-pickle-instancemethods >
def _pickle_method(method):
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)

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

#############
# Utilities #
#############
def interface_methods(*methods):
    """
    Class decorator that can decorate an abstract base class with method names
    that must be checked in order for isinstance or issubclass to return True.
    """
    def decorator(Base):
        def __subclasshook__(Class, Subclass):
            if Class is Base:
                all_ancestor_attrs = [ancestor_class.__dict__.keys()
                                      for ancestor_class in Subclass.__mro__]
                if all(method in all_ancestor_attrs for method in methods):
                    return True
            return NotImplemented
        Base.__subclasshook__ = classmethod(__subclasshook__)
        return Base

def interface(*attributes):
    """
    Class decorator checking for any kind of attributes, not just methods.

    Usage:

    @interface(('foo', 'bar', 'baz))
    class Blah
       pass

    Now, new classes will be treated as if they are subclasses of Blah, and
    instances will be treated instances of Blah, provided they possess the
    attributes 'foo', 'bar', and 'baz'.
    """
    def decorator(Base):
        def checker(Other):
            return all(hasattr(Other, a) for a in attributes)

        def __subclasshook__(cls, Other):
            if checker(Other):
                return True
            return NotImplemented

        def __instancecheck__(cls, Other):
            return checker(Other)

        Base.__metaclass__.__subclasshook__ = classmethod(__subclasshook__)
        Base.__metaclass__.__instancecheck__ = classmethod(__instancecheck__)
        return Base
    return decorator

rawDescription: ipython startup config for spyder IDE

description: Ipython startup config for spyder IDE


code: function(*fields)

rawDescription: Feed python function with a variable number of arguments


rawDescription: How this operation is called?

description: How this operation is called


code:
d = Der1()
d.OwnFoo()
d.OwnFoo2()
d.Foo()

d = Der2()
d.OwnFoo()
d.OwnFoo2()
d.Foo()

rawDescription: Question about python and classes

description: Question about python and classes


code: list([next(it) for _ in _range(s)] for it in (iter(my_list),) for s in count(1))

rawDescription: Python grouping elements in a list in increasing size


rawDescription: Generating a list of combinations with repetition... with a twist


code:
class Photo(Base):
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey(User.id), nullable=False)

    user = relationship(User, backref='photos')

class Tag(Base):
    id = Column(Integer, primary_key=True)
    photo_id = Column(Integer, ForeignKey(Photo.id), nullable=False)

    photo = relationship(Photo, backref='tags')

rawDescription: How to create an SQLAlchemy nested filter

description: Create an SQLAlchemy nested filter


code:
expected_files=os.listdir('expected/path')
actual_files = os.listdir('actual/path')
diff_files=os.listdir('diff/path')
cr=['base.txt','final.txt']
j=1

for files in expected_files:
    tst=os.path.join('expected/path',files)
    with open(tst,'r')as Expected:
        #i=0
        for i, actualfile in enumerate(actual_files):

            actualpath=os.path.join('actual/path',actualfile)
            with open(actualpath,'r') as actual:
                diff=difflib.unified_diff(Expected.readlines(),
                                          actual.readlines(),
                                          fromfile=Expected,
                                          tofile=actual,)

                diffpath=os.path.join('diff/path',cr[i])
                with open(diffpath, 'w') as diff_file:
                    for line in diff:
                        diff_file.write(line)
                #diff_file.close()
                #i=i+1

rawDescription: Python-comparing mutliple files from different folders and generating diff files


code: sorted(map(abs, lista))

rawDescription: How to sort a list and put it in absolute value

description: Sort a list and put it in absolute value


rawDescription: Remove all items of same name from list of sublists


code:
from os import path

pth = 'home/user/directory/filename'
print(path.basename(pth))
filename

rawDescription: extract substring from string, python

description: Extract substring from string, python


code:
with open('retweet.csv', 'rb') as inputfile:
    read=csv.reader(inputfile, delimiter=',')
    for row in read:
        text = row[0]
        text = re.sub(r'@\s\w+', ' ', text)
        text = re.sub(another_expression, another_replacement, text)
        # etc.
        f.write(text + '\n')

rawDescription: Using multiple re.sub() calls in one file with Python


code: del productObj.count #from the object

rawDescription: update an object after deleting a value from it

description: Update an object after deleting a value from it


code:
return 1, 2
return [1,2,3],{'one':1}
etc

rawDescription: return an array instead of a tuple from a NumPy function

description: Return an array instead of a tuple from a NumPy function


code: low_weight_items = (transform(as_item(item)) for item in items if is_in_stock(as_item(item)) and as_item(item).weight < 1000)

rawDescription: What is the Python way of chaining maps and filters?


code:
df = get_merged_csv(glob.glob(fmask))
df
cols = ['{0[0]}{0[1]}'.format(t) for t in zip(df.columns[1:], range(1, len(df.columns)))]
cols
df.columns = df.columns.tolist()[:1] + cols
df

rawDescription: Use pandas (and glob?) to merge numerous (csv) data text files from a directory.


code:
with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, delimiter='\t', quoting=csv.QUOTE_ALL)
    writer.writerows(reader)

rawDescription: Adding quotes and a tab to each element in a csv file


rawDescription: Get the first element of each tuple in a list in Python


rawDescription: How to get the list of options that Python was compiled with?

description: Get the list of options that Python was compiled with


code:
root = ET.XML('<root><elm key="value">Some text</elm>More text</root>')
([root.text] if root.text else []) + [child.tail for child in root]
root = ET.XML('<root>Text 1<elm key="value">Text</elm>Text 2<elm2 />Text 3</root>')
([root.text] if root.text else []) + [child.tail for child in root]

rawDescription: How to get all text children of an element in cElementTree?

description: Get all text children of an element in cElementTree


rawDescription: Pandas: parse merged header columns from Excel


rawDescription: Python: Elementwise comparison of same shaped arrays


code:
def flatten(dct, separator='_'):
    """A fast way to flatten a dictionary,"""
    res = {}
    queue = [('', dct)]

    while queue:
        prefix, d = queue.pop()
        for k, v in d.items():
            key = prefix + k
            if not isinstance(v, dict):
                res[key] = v
            else:
                queue.append((key + separator, v))

    return res

def records_from_json(fh):
    """Yields the records from a file object."""
    rows = csv.reader(fh, delimiter='|')
    header = next(rows)
    for ident, dist, data in rows:
        rec = flatten(json.loads(data))
        rec['id'] = ident
        rec['dist'] = dist
        yield rec

def from_records(path):
    with open(path) as fh:
        return pd.DataFrame.from_records(records_from_json(fh))

rawDescription: Extract nested JSON embedded as string in Pandas dataframe


code: df['ANI/IP'] = df['ANI/IP'].str.replace(r'\d{10}', '').astype('str')

rawDescription: Replacing pandas column with a subset of itself through regex


code:
high = lambda x: isinstance(x, (int, float)) and x > 10
ty = TreeYielder(high)
for val in ty.run(myList):
    print(val, ty.currentLevel())

rawDescription: Recursively dir() a python object to find values of a certain type or with a certain value


code: scipy.stats.kstest(data, lambda x: scipy.stats.norm.cdf(x, loc=5, scale=10))

rawDescription: Using Scipy's stats.kstest module for goodness-of-fit testing


code:
slices = np.ma.notmasked_contiguous(am)
[slice(0, 1, None), slice(3, 3, None), slice(5, 7, None), slice(9, 9, None)]

rawDescription: Python - slice array until certain condition is met


code:
a = 'foo,bar,baz,hello,world'
print(a.split(',', 2))
# ['foo', 'bar', 'baz,hello,world']  #only splits string twice
print(a.split(',', 2)[:-1])  #removes last element (leftover)
# ['foo', 'bar']

rawDescription: python split by number of times specified

description: Python split by number of times specified


rawDescription: python 3 remove before and after on string

description: Python 3 remove before and after on string


rawDescription: Not able to log to two different places using Python logging module


rawDescription: Using queryset to 'filter' within form to display results from DB depending on option selected


code: session.query(Model).filter(Model.col == "Iuri Diniz").first()

rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code:
from itertools import chain, izip, repeat
def interleave(my_list, filler):
    return chain.from_iterable(izip(my_list, repeat(filler)))

rawDescription: Memory efficient padding a list

description: Memory efficient padding a list


rawDescription: Matching Nested Structures With Regular Expressions in Python


code: numbers = list(map(int, input().split()))

rawDescription: Reading a line of integers in Python

description: Reading a line of integers in Python


code:
class QuitAction(argparse.Action):
    def __call__(self, parser, *args, **kwargs):
        parser.exit(message="QUITTING\n")

p=argparse.ArgumentParser()
sp=p.add_subparsers(dest='cmd')
p1=sp.add_parser('quit')
p1.add_argument('foo', action=QuitAction, nargs='?', help=argparse.SUPPRESS)
p.parse_args(['quit'])

rawDescription: python argparse - add action to subparser with no arguments?

description: Python argparse - add action to subparser with no arguments


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo!" in browser.title
elem = browser.find_element_by_name("p") # Find the query box
elem.send_keys("seleniumhq" + Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API
try:
    browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]")
except NoSuchElementException:
    assert 0, "can't find seleniumhq"
browser.close()

rawDescription: Embed a web browser in a Python program

description: Embed a web browser in a Python program


code:
import re

print(re.sub('T.*$', '', 'YR-MM-DDT00:00:10'))

rawDescription: Delete a repeating pattern in a string using Python


rawDescription: Python: Appending to a list in a dictionary


code:
for i in range(0,100):
  if i:
    pass

rawDescription: in python why if rank: is faster than if rank != 0:

description: In python why if rank: is faster than if rank != 0:


rawDescription: How do I open a .py file in python from a .py file in pypy?

description: Open a .py file in python from a .py file in pypy


code:
import numpy as np
import scipy as sp
from scipy import integrate,stats

def bekkers(x, a, m, d):
    p = a*np.exp((-1*(x**(1/3) - m)**2)/(2*d**2))*x**(-2/3)
    return(p)

def bekkers_cdf(x,a,m,d,range_start,range_end):
    values = []
    for value in x:
        integral = integrate.quad(lambda k: bekkers(k,a,m,d),range_start,value)[0]
        normalized = integral/integrate.quad(lambda k: bekkers(k,a,m,d),range_start,range_end)[0]
        values.append(normalized)
    return np.array(values)

my_start = 1
my_end = 10
my_a,my_m,my_d = 1,1,1
my_data = [1.5,1.6,1.8,2.1,2.2,3.3,4,6,8,9]
stats.kstest(my_data,lambda x: bekkers_cdf(x,my_a,my_m,my_d,my_start,my_end))

rawDescription: How to perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python?

description: Perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python


rawDescription: How to get the values from a NumPy array using multiple indices

description: Get the values from a NumPy array using multiple indices


code:
c = c.astype(np.float)  # needs to accept NaN
c.iloc[0] = np.nan
frame['c'] = c
frame

rawDescription: doing calculations in pandas dataframe based on trailing row

description: Doing calculations in pandas dataframe based on trailing row


code:
class test:
    def __iter__(self):
        return self
    def next(self):
        return "next"
    def __next__(self):
        return "__next__"

x = test()
for i,thing in enumerate(x):
    print(thing)
    if i>4:
        break

rawDescription: Python 2: someIterator.next() vs. next(someIterator) :Python 3


code:
timeit.Timer('for i in xrange(len(seq)): x = i + seq[i]', 'seq = range(100)').timeit()
timeit.Timer('for i, e in enumerate(seq): x = i + e', 'seq = range(100)').timeit()

rawDescription: How to enumerate a list of non-string objects in Python?

description: Enumerate a list of non-string objects in Python


rawDescription: how to split .csv data in python?

description: Split .csv data in python


code:
[section]
couples = [("somekey1", "somevalue1"), ("somekey2", "somevalue2"), ("somekey3", "somevalue3")]

rawDescription: Python argparser. List of dict in INI

description: Python argparser. List of dict in INI


rawDescription: logit and inverse logit functions for extreme values

description: Logit and inverse logit functions for extreme values


code:
from gevent import monkey
monkey.patch_all()

unicode('foo').encode('idna')

...

rawDescription: Gunicorn+flask+pymongo+gevent hangs on initialization


rawDescription: Where to write parallelized program output to?


code:
def OnButtonClick(self, button_id):
    if button_id == 1:
        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=1,row=0,sticky='EW')
        self.entryVariable.set(u"Enter Decimal Number Here")

        self.button1.grid_remove() # Remove the button

rawDescription: Where to place the code to remove a tkinter widget from a window


code:
class TestAdmin(admin.ModelAdmin):
    inlines_foo = []
    inlines_bar = [TestInfoInline, ]

    def get_inline_instances(self, request, obj=None):
        self.inlines = self.inlines_foo if obj.id <= 3 else self.inlines_bar
        return super(TestAdmin, self).get_inline_instances(request, obj)

rawDescription: How to check object before adding 'inline = []' in Django

description: Check object before adding 'inline = []' in Django


code: atoms = [Element(1), Element(1), Element(-2), Element(-2)]

rawDescription: Is it possible to create unique instances that have the same input?


code:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1,1,1) # Or we could call plt.gca() later...
im = ax.imshow(np.random.random((10,10)))
ax.set_xticklabels(['a','b','c','d'])  # Or we could use plt.xticks(...)

rawDescription: customize ticks for AxesImage?

description: Customize ticks for AxesImage


code:
def f(*args):
    result = args[0]

    for func in args[1:]:
        result = func(result)

    return result

rawDescription: Better Function Composition in Python

description: Better Function Composition in Python


rawDescription: Python/Pandas: add random forest predictions as column into test file


code:
def customized_box_plot(percentiles, axes, redraw = True, *args, **kwargs):
    """
    Generates a customized boxplot based on the given percentile values
    """

    box_plot = axes.boxplot([[-9, -4, 2, 4, 9],]*n_box, *args, **kwargs)
    # Creates len(percentiles) no of box plots

    min_y, max_y = float('inf'), -float('inf')

    for box_no, (q1_start,
                 q2_start,
                 q3_start,
                 q4_start,
                 q4_end,
                 fliers_xy) in enumerate(percentiles):

        # Lower cap
        box_plot['caps'][2*box_no].set_ydata([q1_start, q1_start])
        # xdata is determined by the width of the box plot

        # Lower whiskers
        box_plot['whiskers'][2*box_no].set_ydata([q1_start, q2_start])

        # Higher cap
        box_plot['caps'][2*box_no + 1].set_ydata([q4_end, q4_end])

        # Higher whiskers
        box_plot['whiskers'][2*box_no + 1].set_ydata([q4_start, q4_end])

        # Box
        box_plot['boxes'][box_no].set_ydata([q2_start,
                                             q2_start,
                                             q4_start,
                                             q4_start,
                                             q2_start])

        # Median
        box_plot['medians'][box_no].set_ydata([q3_start, q3_start])

        # Outliers
        if fliers_xy is not None and len(fliers_xy[0]) != 0:
            # If outliers exist
            box_plot['fliers'][box_no].set(xdata = fliers_xy[0],
                                           ydata = fliers_xy[1])

            min_y = min(q1_start, min_y, fliers_xy[1].min())
            max_y = max(q4_end, max_y, fliers_xy[1].max())

        else:
            min_y = min(q1_start, min_y)
            max_y = max(q4_end, max_y)

        # The y axis is rescaled to fit the new box plot completely with 10%
        # of the maximum value at both ends
        axes.set_ylim([min_y*1.1, max_y*1.1])

    # If redraw is set to true, the canvas is updated.
    if redraw:
        ax.figure.canvas.draw()

    return box_plot

rawDescription: Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?


code:
parser.add_argument('--solr', default='http://localhost:8983/solr/',
    help='Address of Solr server (ex: %(default)s)')

rawDescription: python argsparse data types

description: Python argsparse data types


code:
glider = [[1, 2, 3], [1, 2, 3]]

glider.insert(0, [0] * len(glider[0]))
glider.append([0] * len(glider[0]))

rawDescription: Adding lists to existing nested lists

description: Adding lists to existing nested lists


code:
import datetime
import calendar

def meetup_day(year, month, day_name, week_num):
    year_int = int(year)
    month_int = int(month)
    day_int = list(calendar.day_name).index(day_name)
    relevant_mdays = [i for i in zip(*calendar.monthcalendar(year_int, month_int))[day_int] if i != 0]
    return datetime.date(year_int, month_int, relevant_mdays[week_num])

rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
data_file = [{"name":"python", "downloads":23456876, "version": "3.4.2", "version_downloads": 345653 }]

titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]

for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(titles[key.index(k)], val))

rawDescription: how to format only the numbers of items in a loop python

description: Format only the numbers of items in a loop python


code:
import math

def tfidf(docs,doc_freqs):
    res = {}
    t = sum(isinstance(i, list) for i in docs)
    for key,val in doc_freqs.items():
        res[key] = math.log10(t/val)
    pos = defaultdict(lambda:[])
    for docID, lists in enumerate(docs):
        for element in set(lists):
            pos[element].append([docID, res[element]])
    return pos

docs = [['a', 'b', 'a'], ['a']]
doc_freqs = {'a': 2., 'b': 1., 'c': 1.}

index = tfidf(docs, doc_freqs)

rawDescription: tf-idf function in python need help to satisfy my output

description: Tf-idf function in python need help to satisfy my output


code:
class A(Subject):
    ''' A is just a subject '''
    def __init__(self, name):
        super(A,self).__init__()
        self.name = name

    def __str__(self):
        return "A[ {0} ]".format(self.name)

rawDescription: Using the observer pattern to delete an Observer when a Subject has been "deleted" in Python


code: from numpy.lib import recfunctions

rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
a = numpy.arange(9).reshape(3, 3)
b = numpy.arange(60).reshape(20, 3)
numpy.dot(b, a.T)

rawDescription: Python/Numpy - Matrix Multiply a 2D Array and Each Row of another 2D Array


code:
with codecs.open('test1.txt', 'w', encoding='latin1') as fh:
    # iterate through all rows
    for row_index, row in df.iterrows():
       # iterate through all elements in the row
       for colname in df.columns:
           row_element = row[colname]
           fh.write('%s = {%s},\n' % (colname, str(row_element)))

rawDescription: Python Pandas iterrows method

description: Python Pandas iterrows method


code:
import pandas as pd

df = pd.DataFrame({
    'Pairing': ['1001_1234_1235', '1001_1233_1236'],
    'Result': [1, 0],
})

# split at '_', each result will become a new column
df2 = df['Pairing'].str.split('_', expand=True)

# convert to numbers
df2 = df2.astype(int)

#rename columns back to something useful
df2.columns = ['Pairing{}'.format(col) for col in df2.columns ]

# add the columns back to the old DataFrame
df = df.join(df2)

rawDescription: How to extract multiple ints from string and append to dataframe in Pandas?

description: Extract multiple ints from string and append to dataframe in Pandas


code:
with open('hash.txt', 'w') as f:
    f.write('\n'.join(passwords))

rawDescription: Python: Exporting text list to a text file


rawDescription: pandas memory usage when reindexing

description: Pandas memory usage when reindexing


code:
for br in soup.find_all('br'): br.extract()

soup

rawDescription: Splitting a BeautifulSoup into 2 Soup-Trees


rawDescription: Algorithm to acquire location id from piece number


code:
import eventlet
eventlet.monkey_patch(socket=True, thread=True)
import time
time.sleep.__module__

rawDescription: eventlet.greenthread.sleep VS time.sleep in monkey-patched environment

description: Eventlet.greenthread.sleep VS time.sleep in monkey-patched environment


code:
def key_fix_decorator(f):
    def wrapped(self, *args, **kwargs):
        if args and isinstance(args[0], str):
            args = (args[0].lower(),) + args[1:]
        return f(self, *args, **kwargs)
    return wrapped

class LowerDict(dict):
    pass

for method_name in '__setitem__', '__getitem__', '__delitem__', '__contains__', 'get', 'pop', 'setdefault':
    new_method = key_fix_decorator(getattr(LowerDict, method_name))
    setattr(LowerDict, method_name, new_method)

d = LowerDict(potato=123, spam='eggs')
d['poTATo']
d.pop('SPAm')
d['A']

rawDescription: Why doesn't my idea work in python2?

description: Why doesn't my idea work in python2


rawDescription: append rows to a Pandas groupby object

description: Append rows to a Pandas groupby object


code: fubar.myMethod = lambda self, calls = iter([myMethod, (lambda: 'MyMock'), myMethod]): next(calls)()

rawDescription: Mock only a subset of all calls to a method


code:
c = Crawler()
c.name = "crazy crawler"
c.Id = "abc"
c.active = True
c.update_total_news_crawled()
c.save()

rawDescription: Getting field value counts and pushing values to other field of other model


code:
#!/usr/bin/env python
from pyquery import PyQuery # $ apt-get install python-pyquery or
                            # $ pip install pyquery

# d is like the $ in jquery
d = PyQuery(url='http://stackoverflow.com/q/11939631', parser='html')
for tr in d("#question table > tr"):
    for td in tr.iterchildren('td'):
        print(td.text_content())

rawDescription: Is there an easy way to parse an HTML document and remove everything except a particular table?


code:
for words in dictionary:
    outfile.write('%15s : %s\n' % (words, dictionary[words]))

rawDescription: How to use for loop in the write method?

description: Use for loop in the write method


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

# Some data:
dat = np.array([[5, 3, 4, 4, 6],
                [1, 5, 3, 2, 2]])

# This is the point you want to point out
point = dat[:, 2]

# Make the figure
plt.figure(1, figsize=(4, 4))
plt.clf()
ax = plt.gca()
# Plot the data
ax.plot(dat[0], dat[1], 'o', ms=10, color='r')
ax.set_xlim([2, 8])
ax.set_ylim([0, 6])

rawDescription: How do I put a circle with annotation in matplotlib?

description: Put a circle with annotation in matplotlib


code:
import math
math.factorial(10)

rawDescription: Is there a built-in product() in Python?

description: Is there a built-in product() in Python


rawDescription: How do I know what python scripts are running in Windows?

description: Know what python scripts are running in Windows


rawDescription: Add Multiple DataFrames and Drop Mismatched Indices


code:
df = pd.read_csv("avito_trend.csv",
                      parse_dates=[2])

def f(df):
    dfs = []
    for x in [list(x) for x in itertools.combinations(df['address'].unique(), 2)]:

        c1 = df.loc[df['address'].isin([x[0]]), 'ID']
        c2 = df.loc[df['address'].isin([x[1]]), 'ID']
        c = pd.Series(list(set(c1).intersection(set(c2))))
        #add inverted intersection c2 vs c1
        c_invert = pd.Series(list(set(c2).intersection(set(c1))))
        dfs.append(pd.DataFrame({'common users':len(c), 'pair of websites':' and '.join(x)}, index=[0]))
        #swap values in x
        x[1],x[0] = x[0],x[1]
        dfs.append(pd.DataFrame({'common users':len(c_invert), 'pair of websites':' and '.join(x)}, index=[0]))
    return pd.concat(dfs)

common_users = df.groupby([df['used_at'].dt.year]).apply(f).reset_index(drop=True, level=1).reset_index()

rawDescription: Different sequence of names with pandas

description: Different sequence of names with pandas


code:
# @note: this is the subquery using *sqlalchemy.orm.over* function to limit number of rows
# this subquery is used for both queries below
# @note: the code below sorts Bs by id, but you can change it in order_by
subq = (session.query(
            B.__table__.c.id.label("b_id"),
            over(func.row_number(), partition_by="a_id", order_by="id").label("rownum")
       ).subquery())
# this produces the following SQL (@note: the RDBMS should support the OVER...)
# >> SELECT b.id AS b_id, row_number() OVER (PARTITION BY a_id ORDER BY id) AS rownum FROM b

rawDescription: How to load a collection with limited number in Sqlalchemy?

description: Load a collection with limited number in Sqlalchemy


rawDescription: Storing a list of results in a list

description: Storing a list of results in a list


rawDescription: Can I use dtype to find the elements of an numpy array are strings?

description: Use dtype to find the elements of an numpy array are strings


code:
#threadtimer.py

import threading
import time
import wx

wxEVT_THREAD_TIMER = wx.NewEventType()
EVT_THREAD_TIMER = wx.PyEventBinder(wxEVT_THREAD_TIMER, 1)

class ThreadTimer(object):
   def __init__(self, parent):
        self.parent = parent
        self.thread = Thread()
        self.thread.parent = self
        self.alive = False

   def start(self, interval):
       self.interval = interval
       self.alive = True
       self.thread.start()

   def stop(self):
       self.alive = False

class Thread(threading.Thread):
    def run(self):
       while self.parent.alive:
           time.sleep(self.parent.interval / 1000.0)
           event = wx.PyEvent()
           event.SetEventType(wxEVT_THREAD_TIMER)
           wx.PostEvent(self.parent.parent, event)

rawDescription: wxPython: wx.CallLater being very late

description: WxPython: wx.CallLater being very late


code:
from pyparsing import *

term = Word(alphas)

AND = Keyword("and")
OR = Keyword("or")

expr = infixNotation(term,
    [
    (AND, 2, opAssoc.LEFT),
    (OR, 2, opAssoc.LEFT),
    ])

sample = '(A or B) and ((C and D) or E)'

result = expr.parseString(sample)

from pprint import pprint
pprint(result.asList())

rawDescription: Expanding a logical statement (multiplying out)


code:
class FormResource(ModelResource):
    class Meta:
        serializer = FormPostSerializer()

    def dispatch(self, request_type, request, **kwargs):
        cth = request.META.get('CONTENT_TYPE') or \
            request.META.get('Content-type') or \
            self._meta.serializer.content_types['json']
        self.Meta.serializer.form_boundary = self.parse_content_type_header(cth)
        return super(FormResource, self).dispatch(request_type, request, **kwargs)

    def parse_content_type_header(self, content_type_header):
        parts = cgi.parse_header(content_type_header)
        rv = {}
        for p in parts:
            if isinstance(p, dict):
                rv = dict(rv.items() + p.items())
        return rv

rawDescription: TastyPie: is it possible to post multiple files in a bulk request


code:
if form.is_valid():
    user = User.objects.create_user(username = form.cleaned_data['username'],
                                    email = form.cleaned_data['email'],
                                    password = form.cleaned_data['password'],
                                    )

rawDescription: Inheriting django.contrib.auth.models leads to not hashing passwords


code:
if len(self.__value) > 2:
    widgetName.delete(2,4)
    return "break" # add this line

rawDescription: Help with <key> event in python Entry widget


code:
class WorkoutSchedule(database.Document):
    """ Defines a workout schedule """
    user = database.ReferenceField(User)
    title = database.StringField(
        required=True,
        min_length=3,
        max_length=30,
        unique_with=['user'])

rawDescription: Is it possible to use unique_with on ReferenceFields?


code:
df = data.groupby(...).agg(...)
df.columns = df.columns.droplevel(0)

rawDescription: Naming returned columns in Pandas aggregate function?


code:
class Test1(object):
    __slots__ = ["prop"]
    prop = property(lambda self: "property")

class Test2(object):
    __slots__ = ["prop"]

t = Test1()
t.prop
t.__class__ = Test2
t.prop = 5
t.prop
t.__class__ = Test1
t.prop

rawDescription: Built-in function to read __slots__

description: Built-in function to read __slots__


rawDescription: How do I click Enter using Splinter?

description: Click Enter using Splinter


code: print(*a)

rawDescription: How to use this for loop to get expected result in python

description: Use this for loop to get expected result in python


code:
Giraffe
14
7

rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code:
for i in range(len(df.columns)):
    df[i] = df[i].map('${:,.2f}'.format)

rawDescription: Pandas set format for single dataframe

description: Pandas set format for single dataframe


code:
def must_contain_all(*strings):
    def must_contain(markup):
        return markup is not None and all(s in markup for s in strings)
    return must_contain

rawDescription: Find different strings and return containing tag in BeautifulSoup


code:
from MyConfig import config
# ...

rawDescription: Creating a class with all the elements specified in a file using ConfigParser


code: hc.loc[hc["ID"] == '','ID'] = hc["First Name"] + hc["Last Name"]

rawDescription: Fill empty cells in column with value of other columns


code: np.equal(Predictions, Labels).nonzero()

rawDescription: How to find the set of indices where two vectors have equal elements in Python

description: Find the set of indices where two vectors have equal elements in Python


code:
'abcde'[1:-1]
'*' + 'abcde'[1:-1] + '$'  # Add the characters we want on each end

rawDescription: Replacing selected parts of an item in Python list


code:
def fix(s):
    has_qmark = [part for part in s.split("|") if '?' in part]
    return has_qmark[0] if len(has_qmark) == 1 else s

rawDescription: Find characters within substring using Python regex


code:
short_suit = ['c', 'd', 'h', 's']
long_suit = ['clubs', 'diamonds', 'hearts', 'spades']

rawDescription: Poker hand string display

description: Poker hand string display


code:
yourdict = {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'}
[v for key in yourdict for v in key]
from itertools import chain
list(chain.from_iterable(yourdict))
sorted(v for key in yourdict for v in key)
sorted(chain.from_iterable(yourdict))

rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


code:
def find(x, L):
    return x in L or any(find(x, sublist)
                         for sublist in L
                         if isinstance(sublist, list))

rawDescription: Finding elements in list of lists

description: Finding elements in list of lists


code:
to_json = {"status": "success"}
response = HttpResponse(simplejson.dumps(to_json), mimetype="application/json")
response['Access-Control-Allow-Origin'] = "*"
return response

rawDescription: JQuery Success/Failure Callback is not called


code:
def fib(n):
  a, b = 0, 1
  while n > 0:
    a, b = b, a+b
    n -= 1
  return a

rawDescription: Tail Recursion Fibonacci

description: Tail Recursion Fibonacci


code:
with open("ted.csv") as f1, open("ted2.csv") as f2, open('foo.csv', 'w') as out:
    r1, r2 = csv.reader(f1), csv.reader(f2)
    st = set((row[0], row[3]) for row in r1)
    wr = csv.writer(out)
    for row in (row for row in r2 if (row[0],row[3]) not in st):
          wr.writerow(row)

rawDescription: Manipulating csv files with Python

description: Manipulating csv files with Python


code:
class SemLock(object):

    def __init__(self, kind, value, maxvalue):
        sl = self._semlock = _multiprocessing.SemLock(kind, value, maxvalue)
        debug('created semlock with handle %s' % sl.handle)
        self._make_methods()

        if sys.platform != 'win32':
            def _after_fork(obj):
                obj._semlock._after_fork()
            register_after_fork(self, _after_fork)

    def _make_methods(self):
        self.acquire = self._semlock.acquire
        self.release = self._semlock.release
        self.__enter__ = self._semlock.__enter__
        self.__exit__ = self._semlock.__exit__

    def __getstate__(self):  # This is called when you try to pickle the `Lock`.
        assert_spawning(self)
        sl = self._semlock
        return (Popen.duplicate_for_child(sl.handle), sl.kind, sl.maxvalue)

    def __setstate__(self, state): # This is called when unpickling a `Lock`
        self._semlock = _multiprocessing.SemLock._rebuild(*state)
        debug('recreated blocker with handle %r' % state[0])
        self._make_methods()

rawDescription: Understanding Multiprocessing: Shared Memory Management, Locks and Queues in Python


rawDescription: how to remove positive infinity from numpy array...if it is already converted to num a number?

description: Remove positive infinity from numpy array...if it is already converted to num a number


code:
single_elements = []
double_elements = []
for i, ele in enumerate(arr[:-1], 1):
    if ele == arr[i] or ele == arr[i-2]:
        double_elements.append(ele)
    else:
        single_elements.append(ele)
ele = arr[-1]
if ele == double_elements[-1]:
    double_elements.append(ele)
else:
    single_elements.append(ele)
single_elements.extend(double_elements)

rawDescription: arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list

description: Arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list


rawDescription: How to understand the recursion in a particular nested list?

description: Understand the recursion in a particular nested list


rawDescription: How to get the time we shot the aliens?

description: Get the time we shot the aliens


code:
from collections import defaultdict

nameindex = defaultdict(list)
for person in people:
    nameindex[person.name.lower()] = person

nameindex['bob']  # a list of people named Bob.

rawDescription: Python - testing if an object attribute is equal to a given value


rawDescription: Force integers of a given size with bin?

description: Force integers of a given size with bin


code:
Panasonic
DMC-TZ20

rawDescription: Getting Camera model information of an image using Python


code:
for i in range(len(motifs[0])):
            seq = ''.join([motifs[j][i] for j in range(len(motifs))])
            profile.append([(best.count(bseq)+1)/float(len(seq)) for base in 'ACGT'])

rawDescription: How to break down an expression into for-loops

description: Break down an expression into for-loops


code:
alist=[x, np.ones((2,3)), np.zeros((1,4)),x]
alist
[y for y in alist if 0 not in y.shape]

rawDescription: remove empty numpy array

description: Remove empty numpy array


code:
import re
from datetime import datetime
datetime(*map(int, re.findall(r'\d+', ' ٢٠١٥-١٠-٠٣ ١٩:٠١:٤٣')))
str(_)

rawDescription: Convert Arabic Characters (Eastern Arabic Numerals) to Arabic Numerals in Python


code:
a
newoutput = []
for item in a:
  if len(item) == 1:
    newoutput[-1][-1] += item[0]
  else:
    newoutput.append(item)
newoutput

rawDescription: Concatenating Broken Strings Across Lists - Python


rawDescription: Django reverse url to onetoonefield on success


code:
cache = apt.cache.Cache()
package = cache[package_name]
candidate = package.versions.get(version)
package.candidate = candidate
package.mark_install()
cache.commit()

rawDescription: Python-apt: install package with specific version


code:
for i, value in enumerate(to_flip):
    to_flip[i] = value[::-1]

rawDescription: Specific Python reverse function questions


code:
def GetFrame(ProcessedMatrix):
    if ProcessedMatrix.shape == (3584, 32):
        return np.unpackbits(ProcessedMatrix[13::14]).reshape(256, 256)
    return False

rawDescription: High-speed alternatives to replace byte array processing bottlenecks


code:
def build(self):
    return Hello() #That's what is done here

rawDescription: Update label's text when pressing a button in Kivy for Python


code:
movie_sets = [movies, rest_movies, other_movies, ...]

for movie_set in movie_sets:
    if movie_to_find in movie_set:
        print(movie_set[movie_to_find])

rawDescription: Efficient way to find unique value in one of few lists


rawDescription: Escape filenames for applescript

description: Escape filenames for applescript


code: data

rawDescription: How do I get a scipy.csr sparse-matrix as a normal dense matrix without toDense()?

description: Get a scipy.csr sparse-matrix as a normal dense matrix without toDense()


code:
def sim(haystack, needle):
    if needle in haystack:
        return needle

rawDescription: why the output is not good in some cases?

description: Why the output is not good in some cases


code: pickle.dump(obj, output, -1)

rawDescription: Saving an Object (Data persistence in Python)


code:
def get_address(row):#row is a pandas series with col names as indexes
    title=""
    gender = row['gender']     #extract gender from pandas series
    first = row['first_name']  #extract firstname from pandas series
    second = row['last_name']  #extract lastname from pandas series

    if gender=='male':
        title='Mr'
    elif gender=='female':
        title='Ms'

    if title=='':
        return first + ' '+ last
    else:
        return title + ' ' + first[0] + '. ' + last

rawDescription: Is there a multiple column map function for dataframes?


code:
import matplotlib.pyplot as plt

x, y = [0, 10, 20], [10, 0, 0]
fig, ax = plt.subplots()
ax.plot(x, y, 'ko')
plt.show()

rawDescription: Markers hidden by axis

description: Markers hidden by axis


code:
#import pygame and randint function from random module
import pygame
from random import randint

pygame.init()

screen = pygame.display.set_mode((800,800)) #create screen

while True:
    #get events from the event queue
    for ev in pygame.event.get():
        if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                pygame.quit()
                exit()

    #create random variables r, g and b
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)

    #fill screen
    screen.fill((r, g, b))

    #update whole screen
    pygame.display.flip()

    #set timout for 500ms (i.e. pause game for 500ms)
    pygame.time.delay(500)

rawDescription: Python timer on randint

description: Python timer on randint


code: newstrides = attempt_reshape(numpy.zeros((3,4)), (4,3), False)

rawDescription: When will numpy copy the array when using reshape()


code: [(datetime.today().month - i - 1) % 12 + 1 for i in range(6)]

rawDescription: Last six months number in python

description: Last six months number in python


rawDescription: How to get a vector from a list in list in python?

description: Get a vector from a list in list in python


code:
class Pattern(object):
    def __init__(self, text='', escape=None):
        self.text = text
        self.matchers = []

        escape = not self.text.startswith('!') if escape is None else False

        if escape:
            self.regex = re.sub(r'([\[\].?+\-()\^\\])', r'\\\1', self.text)
        else:
            self.regex = self.text[1:]

        self.size = len(re.findall(r'(\$[A-Za-z0-9\-_]+)', self.regex))

        self.regex = re.sub(r'(\$[A-Za-z0-9\-_]+)', Replacer(), self.regex)
        self.regex = re.sub(r'\s+', r'\\s+', self.regex)

    def search(self, text):
        return re.search(self.regex, text)

    def findall(self, text, max_depth=1.0):
        results = []
        length = float(len(text))

        for result in re.finditer(self.regex, text):
            if result.start() / length < max_depth:
                results.extend(result.groups())

        return results

    def match(self, text):
        result = map(lambda x: (x.groupdict(), x.start()), re.finditer(self.regex, text))

        if result:
            return result
        else:
            return []

rawDescription: Processing malformed text data with machine learning or NLP


code: method_dict = {{}}

rawDescription: Python - Dynamically naming variables

description: Python - Dynamically naming variables


code:
union_find = UnionFind()
clusters = set([0,1,2,3,4])
for i in clusters:
    union_find[i]

rawDescription: Implementing Disjoint Set Data Structure in Python


rawDescription: How Can I Set the Interpolation of a F-Curve via Python? (Blender)


code:
import wave

def stereo_to_mono(hex1, hex2):
    """average two hex string samples"""
    return hex((ord(hex1) + ord(hex2))/2)

wr = wave.open('piano2.wav','r')

nchannels, sampwidth, framerate, nframes, comptype, compname =  wr.getparams()

ww = wave.open('piano_mono.wav','wb')
ww.setparams((1,sampwidth,framerate,nframes,comptype,compname))

frames = wr.readframes(wr.getnframes()-1)

new_frames = ''

for (s1, s2) in zip(frames[0::2],frames[1::2]):
    new_frames += stereo_to_mono(s1,s2)[2:].zfill(2).decode('hex')

ww.writeframes(new_frames)

rawDescription: Python Wave byte data

description: Python Wave byte data


code:
res = []
seen = set()

for x in g:
    x_set = frozenset(x)
    if x_set not in seen:
        res.append(x)
        seen.add(x_set)

rawDescription: Remove duplicated lists in list of lists in Python


code:
date_times = pd.date_range(datetime.datetime(2011, 4, 1, 9, 30),
                           datetime.datetime(2011, 4, 16, 0, 0),
                           freq='10s')
VOL = np.random.sample(date_times.size) * 10000.0

df = pd.DataFrame(data={'VOL': VOL,'time':date_times}, index=date_times)
df['h'] = df.index.hour
df['m'] = df.index.minute
df1 = df.resample('5Min', how={'VOL': np.mean})
times = pd.to_datetime(df1.index)
df2 = df1.groupby([times.hour,times.minute]).VOL.mean().reset_index()
df2.columns = ['h','m','VOL']
df.merge(df2,on=['h','m'])
df_norm = df.merge(df2,on=['h','m'])
df_norm['norm'] = df_norm['VOL_x']/df_norm['VOL_y']

rawDescription: Pandas: De-seasonalizing time-series data


code: wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, (24, 24))

rawDescription: How to make a wx Toolbar buttons larger?

description: Make a wx Toolbar buttons larger


code: nx.dijkstra_path_length(g, 'b', 'c')

rawDescription: How to do shortest path algorithm for unweighted graph?

description: Do shortest path algorithm for unweighted graph


rawDescription: resample gives different final dates in pandas

description: Resample gives different final dates in pandas


code:
import urllib2
import lxml.etree
url = 'http://www.tv3.ie/3player'
data = urllib2.urlopen(url)
parser = lxml.etree.HTMLParser()
tree = lxml.etree.parse(data,parser)
elem = tree.xpath("//div[@id='slider1']")
elem[0].attrib

rawDescription: Python iterate through section using lxml


code:
from random import choice

def get_random_sample(a, b):
    return (choice(a), choice(b))

rawDescription: Fastest way to sample from product of two lists


code:
__len__
__iter__
__getitem__

rawDescription: How to wrap a python dict?

description: Wrap a python dict


rawDescription: Why is this python generator returning the same value everytime?


code:
import bs4

html = '''

example

foo

bar

'''

soup = bs4.BeautifulSoup(html)
soup(attrs={'class' : ['prod', 'roundedBox']})

rawDescription: Find multiple words with regex in Beautifulsoup4


rawDescription: How to find dict value by Key in list

description: Find dict value by Key in list


code:
writeString = ""
for item in zip(col1, col2):
    writeString += str(item[0]) + " " + str(item[1]) + "\n"

with open("outfile.txt", "w") as f:
    f.write(writeString)

rawDescription: how to split a very long row data into two column by python (from txt file)

description: Split a very long row data into two column by python (from txt file)


code: labels = ["%.2f" % i for i in dayspeed['Download']]

rawDescription: Python variable to float list

description: Python variable to float list


code:
def coins(num_coins):
    ...
    return num_coins

rawDescription: Python 2.6, global variable wont change, calling functions in another function


code: perlCmd = 'C:\perl\perl.exe c:/.../MyPerl.pl'

rawDescription: How to set environment variables and call a perl script with parameters in python subprocess.popen?

description: Set environment variables and call a perl script with parameters in python subprocess.popen


rawDescription: How to remove duplicate lists that contain elements in different order?

description: Remove duplicate lists that contain elements in different order


code: from dataProxy import Integer

rawDescription: Sharing model between Camelot and non-Camelot apps


code:
import timeit
dct = {1:1, 2:2}
timeit.timeit('1 in dct', 'from __main__ import dct')
timeit.timeit('len(dct) <= 2', 'from __main__ import dct')

rawDescription: What is faster in Python3? len or dictionary lookup?


code:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

rawDescription: Upload Image using POST form data in Python-requests


code:
from numpy.core.records import fromarrays
from scipy.io import savemat

myrec = fromarrays([[1, 10], [2, 20]], names=['field1', 'field2'])
savemat('p.mat', {'myrec': myrec})

rawDescription: How can I create a Matlab struct array from scipy.io?

description: Create a Matlab struct array from scipy.io


code:
d2[keys[i]] =  copy.copy(data)
d2[keys[i]] =  dict(data)
d2[keys[i]] =  data.copy()

rawDescription: Values assigned differently in seemingly identical dictionaries


rawDescription: How do I convert a python string to ucs2 hex?

description: Convert a python string to ucs2 hex


code:
import argparse

def foo(path):
    print('Running foo(%r)' % (path, ))

def bar(path):
    print('Running bar(%r)' % (path, ))

dispatch = {
    'foo': foo,
    'bar': bar,
}

parser = argparse.ArgumentParser()
parser.add_argument('function')
parser.add_argument('arguments', nargs='*')
args = parser.parse_args()

dispatch[args.function](*args.arguments)

rawDescription: Python - passing parameters in a command line app


code:
rword = ""
for c in reversed(word):
    rword += c
nwords.append(rword)

rawDescription: How to preserve and reverse a string?

description: Preserve and reverse a string


code:
class IndexView(ListView):
    model = EmployeeProfiles
    paginate_by = 5
    template_name = 'ppm/ppm.html'

rawDescription: Pagination not showing page numbers in ListView


code:
N += 1
f = 1.0/N
dx = x - xbar
dt = t - tbar
xbar += f*dx
tbar += f*dt
V = (1.0-f)*(V + f*dt*dt)
C = (1.0-f)*(C + f*dx*dt)

rawDescription: Recursive least squares in python?

description: Recursive least squares in python


code:
all_lines = list(axes.lines)  # Copy
# ...
axes.lines[:] = all_lines  # All lines put back

rawDescription: matplotlib plt.show() only selected objects

description: Matplotlib plt.show() only selected objects


code:
from bs4 import BeautifulSoup
import requests

resp = requests.get("http://www.yahoo.com")

soup = BeautifulSoup(resp.text)

# Pull the linked images (note: will grab base64 encoded images)
images = [img['src'] for img in soup.findAll('img') if img.has_key('src')]

# Checking for src ensures that we don't grab the embedded scripts
scripts = [script['src'] for script in soup.findAll('script') if script.has_key('src')]

# favicon.ico and css
links = [link['href'] for link in soup.findAll('link') if link.has_key('href')]

rawDescription: Load all third party scripts using requests or mechanize in Python


code:
import datetime
datetime.datetime.strptime('Mon, 29 Oct 2012 13:07:07 GMT', '%a, %d %b %Y %H:%M:%S %Z')

rawDescription: Parsing the string to Dates in python

description: Parsing the string to Dates in python


code:
import time
import threading

from queue import Queue
NUM_WORKER_THREADS = 8

def worker():
    for item in iter(items.get, None):
        try:
            print("{} items left to process".format(items.qsize()))
            print("Processing {}".format(item))
        except Exception as inst:
            print("---------------EXCEPTION OCCURRED----------------")
            print(type(inst))
            print(inst.args)
            print(inst)
        finally:
            items.task_done()
    print("Got sentinel, shut down")
    items.task_done()

# start counter to monitor performance
start = time.perf_counter()

items = Queue()
# get the items we need to work on for allocations
searchResults = getSearchResults() # external call to webservice

# add results of search to a collection
for itemid in searchResults:
    if itemid['recordtype'] == 'inventoryitem':
        items.put(itemid['id'])

for _ in range(NUM_WORKER_THREADS):
   items.put(None) # Load a sentinel for each worker thread

for i in range(NUM_WORKER_THREADS):
    try:
        t = threading.Thread(target=worker)
        t.daemon = True
        t.start()
    except Exception as inst:
        print("---------------EXCEPTION OCCURRED----------------")
        print(type(inst))
        print(inst.args)
        print(inst)

items.join()

# print end of execution performance counter
print('time:', time.perf_counter() - start)

rawDescription: Deadlock when calling task_done() as the task has been pulled by a new thread


code: A[(slice(None),)+tuple(ll)]

rawDescription: Numpy extract values along a dimension for a given point


code: sock = socket()

rawDescription: Query about Creating a Socket in Python

description: Query about Creating a Socket in Python


rawDescription: How to view crawled unicoded arabic string?

description: View crawled unicoded arabic string


code:
wb2 = openpyxl.Workbook()
ws = wb2.active
ws.title = 'CombinedCount'
ws['B3'] = x
wb2.save('CombinedCount.xlsx')

rawDescription: Adding cell values from multiple sheets in Excel workbook via Python


code:
from unidecode import unidecode
unidecode(u"İstanbul")

rawDescription: Dealing with foreign characters in django query


code:
from operator import attrgetter

sorted(list_of_objects, key=attrgetter('lowest_z'))

rawDescription: Python, sort a list of objects by lowest sub-object attribute


code:
import pandas as pd

num_ticks = 15

index=pd.date_range('2011-9-1 00:00:03', '2012-09-01  00:00:03', freq='10min')
df=pd.DataFrame(np.random.rand(len(index),3),index=index)
df2 = df.groupby(lambda x: x.month)
for key, group in df2:
    step = len(group) / num_ticks
    reset = group.reset_index()
    reset.plot()
    plt.xticks(reset.index[::step],
               reset['index'][::step].apply(
                    lambda x: x.strftime('%Y-%m-%d')).values,
               rotation=70)

rawDescription: Plot groupby data by month

description: Plot groupby data by month


code: # Result: ['Merge3', 'Merge2', 'Merge1']

rawDescription: Get selected node names into a list or tuple in Nuke with Python


code:
[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

rawDescription: How to read a config file using python

description: Read a config file using python


code:
import numpy as np

a = np.array([1,2,3,4])
print("Array {0} has shape {1}.".format(a, a.shape))

print(a[:, None].shape)
print((a[:, None].T).shape)
print(a[:, None].squeeze().shape)

rawDescription: How to revert a vertical numpy array (1D) to its usual horizontal default form?

description: Revert a vertical numpy array (1D) to its usual horizontal default form


code:
from app import create_app
from extensions import celery

app = create_app()

if __name__ == '__main__':
    with app.app_context():
        celery.start()

rawDescription: How to use Flask-SQLAlchemy in a Celery task

description: Use Flask-SQLAlchemy in a Celery task


rawDescription: Pygame Sprite Moving at Constant Speed

description: Pygame Sprite Moving at Constant Speed


code:
def my_zip_sort(W, L):
    srt = argsort(W)
    return [(L[i], W[i]) for i in srt]

rawDescription: 1d list indexing python: enhance MaskableList


code:
for k, toremove in values_to_remove.viewitems():
    t_dict.get(k, set()).difference_update(toremove)

rawDescription: Remove values from lists of values in a dictionary


code:
def ContinSubSeq(lst):
  size=len(lst)
  for start in range(size):
    for end in range(start+1,size+1):
      yield (start,end)

def getsubmat(mat,start_row,end_row,start_col,end_col):
  return [i[start_col:end_col] for i in mat[start_row:end_row] ]

def get_all_sub_mat(mat):
  rows = len(mat)
  cols = len(mat[0])
  for start_row,end_row in ContinSubSeq(list(range(rows))):
    for start_col,end_col in ContinSubSeq(list(range(cols))):
      yield getsubmat(mat,start_row,end_row,start_col,end_col)

rawDescription: Find all submatrices of a given matrix

description: Find all submatrices of a given matrix


code: TEXT

rawDescription: Python->BeautifulSoup, get some text

description: Python->BeautifulSoup, get some text


code:
@richter.route("/adauga/<denumire_med>,<producator>", methods=["POST"])
def adauga(denumire_med, producator):
    unitati = request.form["unitati"]
    fractii = request.form["fractii"]
    g.db.execute("INSERT INTO stocuri_disponibile (denumire_med, producator, cant_fl, fractie) VALUES(?, ?, ?, ?)", [denumire_med, producator, unitati, fractii])
    return redirect(request.referrer)

rawDescription: Flask submit data outside of form input fields


code:
import bisect

def nearest(x, d):
    index = bisect.bisect(d, x)
    if not index:
        return d[index]  # left-most x coordinate
    if index == len(d):
        return d[-1]  # right-most x coordinate
    return min(d[index - 1:index + 1], key=lambda v: abs(v - x))

rawDescription: Python X-axis nearest point

description: Python X-axis nearest point


code:
box = BoxWithOranges()
box['color'] = 'red'
box['weight'] = 10.0
print(box['color'])
print(box['weight'])

rawDescription: Way to iterate though object in python

description: Way to iterate though object in python


rawDescription: find_all() not finding any results when using Beautiful Soup + Requests

description: Find_all() not finding any results when using Beautiful Soup + Requests


rawDescription: Stream stdout from subprocess to python function, and back to subprocess


code: sorted({item.split(':')[0] for item in l}, key=int)

rawDescription: How can I split the strings and get only the first part of it?

description: Split the strings and get only the first part of it


rawDescription: Hashing uncertain objects

description: Hashing uncertain objects


code:
class A: pass

class B( A ):
    def foo( self ): print( 'B.foo')
    def bar( self ): print( 'B.bar')

class C( A ):
    def foo( self ): print( 'C.foo')
    def bar( self ): print( 'C.bar')

class D( B, C ):
    def foo( self ): return B.foo( self )
    def bar( self ): return C.bar( self )

rawDescription: Python multiple inheritance questions

description: Python multiple inheritance questions


code: days_as_num = len(days.split())

rawDescription: How do I subtract from an array and an user input?

description: Subtract from an array and an user input


code:
def check(g,s):
    for keys, value in g.items():
        for w, val in enumerate(value):
            print(s, val, w)
            if(s==val):
                return 1
    return 0

rawDescription: Code not iterating over whole dictionary


code: obj[key] = value # this equals to obj.__setitem__(key, value)

rawDescription: Why is __setitem__ not invoked when changing list type data?


code:
def plot(x, y1, y2):
    plt.plot(x, y1)
    plt.plot(x, y2, scalex=False, scaley=False)

rawDescription: secant line too long, trying not to use y limits

description: Secant line too long, trying not to use y limits


rawDescription: parsing string - regex help in python

description: Parsing string - regex help in python


code: sorted(mytuple)

rawDescription: Sorting a tuple that contains lists

description: Sorting a tuple that contains lists


code:
def record_indexer(record):
    if record.that_field == 'bad value':
        return dbf.DoNotIndex             # record is ignored
    return record.this_field, record.other

rawDescription: Opening and searching dBase III (DBF) databases in Python


code:
non_empty_params = dict((field, value)
                        for field, value in request.GET.iteritems() if value)

rawDescription: How to find not null variables from URL query string? or can we get the variable in URL query string from request in python

description: Find not null variables from URL query string? or can we get the variable in URL query string from request in python


code: pd.read_table("cusip.txt", header=None, delimiter=" ", converters={0: str})

rawDescription: read_table pandas python numeric error

description: Read_table pandas python numeric error


code: [(i,s.count(i)) for i in vowels]

rawDescription: Python, counting from an inputted string. Needs to be returned in a specific order?


code: logger.debug(_F("foo {0} {quux}", bar, quux=baz))

rawDescription: How to use modern string formatting options with Python's logging module?

description: Use modern string formatting options with Python's logging module


code:
for url_key in URLDict:
    URL = URLDict[url_key]

    sourcepage = urllib.urlopen(URL)
    sourcetext = sourcepage.read()

rawDescription: How do I access a dictionary value for use with the urllib module in python?

description: Access a dictionary value for use with the urllib module in python


code:
import script1
import script2
import script3
__all__ = ['script1', 'script2', 'script3']

rawDescription: How to import all submodules?

description: Import all submodules


code: np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)

rawDescription: Numpy array filled with random numbers so that you only change the value by one along the x/y axis


code: MyApp

rawDescription: Regex to select a file extension

description: Regex to select a file extension


code:
def select(df, substring):
    return df[df.index.to_series().str.contains("|".join(substring))]

rawDescription: select Pandas Dataframe rows with for-loop for different substrings in index

description: Select Pandas Dataframe rows with for-loop for different substrings in index


code:
from collections import Counter
counts = Counter(tag for word,tag in tagged)
counts

rawDescription: Count verbs, nouns, and other parts of speech with python's NLTK


code:
def get_A_with_Bs_hack_relation(b_limit=10):
    """
    @return: dict(A, [list of top *b_limit* A.b_s])
    @note: the Bs are loaded as relationship A.b_s, but with the limit.
    """
    qry = (session.query(A)
            .outerjoin(B)
            # @note: next line will trick SA to load joined Bs as if they were *all* objects
            # of relationship A.b_s. this is a @hack: and one should discard/reset a session after this
            # kind of hacky query!!!
            .options(contains_eager(A.b_s))
            .outerjoin(subq, and_(subq.c.b_id == B.id, subq.c.rownum <= b_limit))
            # @note: next line is required to make both *outerjoins* to play well together
            # in order produce the right result
            .filter(or_(B.id == None, and_(B.id != None, subq.c.b_id != None)))
            )
    res = dict((a, a.b_s) for a in qry.all())
    return res

rawDescription: How to load a collection with limited number in Sqlalchemy?

description: Load a collection with limited number in Sqlalchemy


code:
import sys
from colorama import Back, Fore, Style, init # $ pip install colorama
init(strip=not sys.stderr.isatty())

def max_water_heldover_bruteforce(heights):
    if not heights: return 0
    BUILDING, AIR, WATER = ['B', ' ',
            Back.BLUE + Fore.WHITE + 'W' + Fore.RESET + Back.RESET + Style.RESET_ALL]
    matrix = [[WATER] * len(heights) for _ in range(max(heights))]
    for current_floor, skyscrapers in enumerate(matrix, start=1):
        outside = True
        for building_number, building_height in enumerate(heights):
            if current_floor <= building_height:
                outside = False
                skyscrapers[building_number] = BUILDING
            elif outside:
                skyscrapers[building_number] = AIR
        for i, building_height in enumerate(reversed(heights), 1):
            if current_floor > building_height:
                skyscrapers[-i] = AIR
            else:
                break
    if '--draw-skyscrapers' in sys.argv:
        print('\n'.join(map(''.join, matrix[::-1])), file=sys.stderr)
        print('-'*60, file=sys.stderr)
    return sum(1 for row in matrix for cell in row if cell == WATER)

rawDescription: Algorithm to solve for water accumulation given building heights


code:
from string import ascii_letters, digits
s = "app-_l#e"
s.translate(None, "-_" + ascii_letters + digits)

rawDescription: How to address/check whether a character in a string isn't a disallowed character?

description: Address/check whether a character in a string isn't a disallowed character


code:
F = eval('lambda x :'+fie)
DF = eval('lambda x :'+dfie)

rawDescription: How use the newton function for root finding of the Scipy's optimize package


code: inner_function = lambda x: sum(range(1, x + 1))

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


code:
def make_adder(x):
    def adder(y):
        return x + y
    return adder

rawDescription: Python Object via Function

description: Python Object via Function


rawDescription: Nth Fibonacci number for n as big as 10^19?


code:
from matplotlib.dates import WeekdayLocator

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers

    fig.autofmt_xdate()

    # For tickmarks and ticklabels every fourth week
    ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=4))

    # For tickmarks (no ticklabel) every week
    ax.xaxis.set_minor_locator(WeekdayLocator(byweekday=MO))

    # Grid for both major and minor ticks
    plt.grid(True, which='both')
    plt.show()

rawDescription: Custom date range (x-axis) in time series with matplotlib


rawDescription: How to remove a list value from a dictionary?

description: Remove a list value from a dictionary


code:
random_fruit()
random_fruit(['kiwi'])

rawDescription: How do I patch or modify a list inside of a function when running a unit test?

description: Patch or modify a list inside of a function when running a unit test


rawDescription: Scraping a page with awkwardly formatted JSON in python


code:
dt=np.dtype('f,f')
x.view(dt)

rawDescription: convert (nx2) array of floats into (nx1) array of 2-tuples

description: Convert (nx2) array of floats into (nx1) array of 2-tuples


code:
schema = [ #define a schema
    SizedInput("ages",int),
    SizedInput("names",str),
    MatrixInput("matrix",int),
]

rawDescription: Programming contest like input validator


code:
def insertionSort(list):
    numOfComp = 0
    for i in range(1,len(list)):
        value = list[i]
        j = i - 1
        while j>=0:
            if value<list[j]:
                flag=True
            else :
                flag=False
            numOfComp += 1
            if flag:
                list[j+1] = list[j]
                list[j] = value
                j = j - 1
            else:
                break
    print("Number of data comparisons:",numOfComp)
    print("Sorted list:",list)

rawDescription: Number of comparisons in insertion sort

description: Number of comparisons in insertion sort


code:
def Struct(*args, **kwargs):
    def init(self, *iargs, **ikwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "MyStruct")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()})

rawDescription: Python Class Factory to Produce simple Struct-like classes


code:
class Operation(object):
    def __init__(self, tokens):
        self._tokens = tokens[0]
        self.assign()

    def assign(self):
        """
        function to copy tokens to object attributes
        """

    def __repr__(self):
        return self.__class__.__name__ + ":" + repr(self.__dict__)
    __str__ = __repr__

class BinOp(Operation):
    def assign(self):
        self.op = self._tokens[1]
        self.terms = self._tokens[0::2]
        del self._tokens

class AndOp(BinOp):
    pass

class OrOp(BinOp):
    pass

expr = infixNotation(term,
    [
    (AND, 2, opAssoc.LEFT, AndOp),
    (OR, 2, opAssoc.LEFT, OrOp),
    ])

sample = '(A or B) and ((C and D) or E)'

result = expr.parseString(sample)
pprint(result.asList())

rawDescription: Expanding a logical statement (multiplying out)


code: temp = []

rawDescription: Parsing text with regular expression into list with empty string in result


code:
book = Book.objects.create(title=dictionary['title'],
                           subtitle=dictionary['subtitle'])
book.subjects = dictionary['subjects']

rawDescription: django how to create an object with the dictionary with m2m data

description: Django how to create an object with the dictionary with m2m data


code:
iterables = [[1, 2, 3], "abc", [True, False, None]]
zip(*iterables)

rawDescription: Zipping multiple lists together?

description: Zipping multiple lists together


code:
from base import YourBaseClass

class StudentClass(YourBaseClass):
    pass

if __name__ == "__main__":
    c = StudentClass()
    c.method_that_is_hidden()
    c.method_that_shows()

rawDescription: In Python, can I hide a base class's members?


code: ret_group = matches.groupby(['year', 'winner']).apply(lambda x: (x['score'].str.contains('RET').fillna(False)).sum())

rawDescription: create new dataframe based on group by and aggregates

description: Create new dataframe based on group by and aggregates


code:
from enum import IntEnum

class Color(IntEnum):
   RED = 1
   BLUE = 2

print(int(Color.RED))   # prints 1

rawDescription: How to get all values from python enum class?

description: Get all values from python enum class


rawDescription: python equivelant to $(which) in make

description: Python equivelant to $(which) in make


code:
['asdf.red', 'asdf.blue', 'asdf.alpha']
['test.green', 'test.alpha']

rawDescription: Custom order list python

description: Custom order list python


rawDescription: How to read a text file with mixed data_types automatically in Python?

description: Read a text file with mixed data_types automatically in Python


code:
from datetime import datetime
import time
import os

def clearDirectory():
    while True:
        _time_list = []
        _now = time.mktime(datetime.now().timetuple())
        for _f in os.listdir('/path/to/your/directory'):
            if os.path.isfile(_f):
                _f_time = os.path.getmtime(_f) #get file creation/modification time
                if _now - _f_time < 300:
                    os.remove(_f) # delete outdated file
                else:
                    _time_list.append(_f_time) # add time info to list
        # after check all files, choose the oldest file creation time from list
        _sleep_time = (_now - min(_time_list)) if _time_list else 300 #if _time_list is empty, set sleep time as 300 seconds, else calculate it based on the oldest file creation time
        time.sleep(_sleep_time)

rawDescription: Limiting the lifetime of a file in Python


code:
allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
usedletters = set() # update this as you go
availletters = allletters.difference(usedletters) #s - t    new set with elements in s but not in t

rawDescription: letter/word guessing game in python

description: Letter/word guessing game in python


rawDescription: Removing duplicates from tuples within a list


code:
def test_stuff(self):
    with tempfile.NamedTemporaryFile() as temp_csv:
        self.write_csv_test_data(temp_csv)  # Create this to write to temp_csv file object.
        temp_csv.flush()
        temp_csv.seek(0)

        spread_sheet = SpreadSheet(temp_csv.name)
        # spread_sheet = SpreadSheet(temp_csv)  Use this if Spreadsheet takes a file-like object
        ...

rawDescription: Writing a csv temporary file using tempfile


code:
mx_len = len(max([list1,*list2]))

mx_len
[x+['']*(mx_len-len(x)) for x in itertools.chain([list1], list2)]
#another way by unpacking list2 in a list with list1
[x+['']*(mx_len-len(x)) for x in itertools.chain([list1, *list2])]

rawDescription: Best way to merge a 2d list and a 1d list in Python?

description: Merge a 2d list and a 1d list in Python


code:
while True:
    getch() # this also returns the key pressed, if you want to store it
    input = raw_input("Enter input")
    do_whatever_with_it

rawDescription: How can I read keyboard input in Python

description: Read keyboard input in Python


rawDescription: Getting the root (head) of a DiGraph in networkx (Python)


code:
import MyTables
my_string = 'item'
table = getattr(MyTables, my_string.capitalize() + 'Table')

rawDescription: Form a variable from a string without dictionary


pack: blast

rawDescription: pymong group and count

description: Pymong group and count


code:
import os
class MainClass:
    def __init__(self):
        self.myVar = "a variable"
        self.listOfLoadedModules = []

        for f in os.listdir("."):
            fileName, extension = os.path.splitext(f)
            if extension == ".py":
                self.listOfLoadedModules.append(__import__(fileName))

    def callMe(self):
        for currentModule in self.listOfLoadedModules:
            currentModule.__dict__.get("callMe")(self)

myMain = MainClass()
myMain.callMe()

rawDescription: Python - Plugins to Main Program

description: Python - Plugins to Main Program


code:
import numpy as np
import pandas as pd

df = pd.read_table('data', sep='\s{2,}', parse_dates=[0])
table = pd.crosstab(index=[df['timestamp']], columns=[df['colA'], df['colB']])

rawDescription: Resampling, grouping, pivoting a pandas dataframe


code: Namespace(files=[['a', 'b'], ['c', 'd']], l=False, v=True)

rawDescription: argparse optional parameter within positional

description: Argparse optional parameter within positional


code: soup.select('a > img')

rawDescription: Get immediate parent tag with BeautifulSoup in Python


rawDescription: Expanding a numpy array of matrices with zeros


code: [[i * j for i, j in zip(*row)] for row in zip(matrix1, matrix2)]

rawDescription: element-wise operations of matrix in python

description: Element-wise operations of matrix in python


code:
import pandas as pd
import numpy as np

y = np.array([2012, 2013])
m = np.array([1, 3])
d = np.array([5, 20])
H = np.array([10, 20])
M = np.array([30, 40])
S = np.array([0, 30])

start = np.array(["0000-01-01"], dtype="M8[Y]")

date = start + y.astype("m8[Y]") + (m - 1).astype("m8[M]") + (d-1).astype("m8[D]")
datetime = date.astype("M8[s]") + H.astype("m8[h]") + M.astype("m8[m]") + S.astype("m8[s]")

pd.Series(datetime)

rawDescription: Vectorized construction of DatetimeIndex in Pandas


rawDescription: append the same element to several sublists in python

description: Append the same element to several sublists in python


code:
import numpy
# setup example data
x = numpy.arange(9)
data_with_minimum = numpy.array(
    [[ 5,  3,  1,  2,  5,  8, 10, 14, 16],
     [ 8,  6,  5,  3,  1,  3,  4,  7, 10],
     [ 3,  1,  5,  8, 10, 13, 15, 18, 20]])

mi = numpy.argmin(data_with_minimum, axis = 1)

rawDescription: Shift several graphs under each other

description: Shift several graphs under each other


code:
def count_words(text, words):
    text = text.lower()
    answer = 0
    for i in range(len(text)):
        if any(text[i:].startswith(word) for word in words):
            answer += 1
    return answer

rawDescription: Find particular words in a string, Python


code:
import matplotlib.pyplot as plt
grid = np.zeros((n, n), dtype=np.bool)
grid[coords] = True
plt.imshow(grid)
plt.savefig('result.png')

rawDescription: Random sampling of non-adjacent cells in a pixel grid


code:
# Now extract the data
x_values = data[:, :, 0]
y_values = data[:, :, 1]
values = data[:, :, 2]

rawDescription: Setting arbitrary axis value for a contour plot of form (x,y,f(x,y))?


code:
from pathlib import Path
d = str(Path(__file__).resolve().parent.parent) # '/home/kristina/desire-directory'

rawDescription: Get parent of current directory from Python script


code:
['AA', 'AA BB', 'AA BB CC', 'AA BB CC DD',
 'BB', 'BB CC', 'BB CC DD', 'BB CC DD EE',
 'CC', 'CC DD', 'CC DD EE', 'CC DD EE FF',
 'DD', 'DD EE', 'DD EE FF', 'DD EE FF GG',
 'EE', 'EE FF', 'EE FF GG', 'EE FF GG HH',
 'FF', 'FF GG', 'FF GG HH',
 'GG', 'GG HH',
 'HH']

rawDescription: Use python regex to match all possible groups of 1, 2, 3, and 4 words


rawDescription: Editing all text in childNodes of XML file with Python


code:
dups = u[counts > 1]
dups

rawDescription: Finding the difference between two numpy structured arrays


code:
class Unique:
    def __init__(self, iterable):
        self.__it = iter(iterable)
        self.__seen = set()

    def __iter__(self):
        return self

    def __next__(self):
        while True:
            next_item = next(self.__it)
            if next_item not in self.__seen:
                self.__seen.add(next_item)
                return next_item

for item in Unique((1, 2, 3, 3, 4, 4, 5)):
    print(item)

rawDescription: Iterator Object for Removing Duplicates in Python


code:
class myTest:
    def __init__(self, str):
        self.str = str

    def __unicode__(self):
        return self.str
    def __str__(self):
        return unicode(self).encode('utf-8')

rawDescription: __unicode__() doesn't return a string

description: __unicode__() doesn't return a string


code:
from collections import OrderedDict

mydict = OrderedDict()
for item in ...:
    mydict[item] = True

rawDescription: check if a number already exist in a list in python

description: Check if a number already exist in a list in python


code:
while(count != 0):
    guess = input("Take a guess: \n")
    if not guess in word:
        count -= 1
        print("No.\nTurns left: \n", count)
    else:
        count -= 1
        print("Yes.\n")

rawDescription: Python while/if statements not working

description: Python while/if statements not working


code:
from collections import Counter

def only_uniques_ordered(seq):
    counts = Counter(seq)
    return [k for k in seq if counts[k] == 1]

rawDescription: Fastest way to remove all multiple occurrence items from a list?


code:
Da=random.choice([clubs,diamonds,hearts,spades])
#Da is now the dict for the selected suit
Fa = random.choice(tuple(Da))

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code: courses = {}

rawDescription: How to add values to existing dictionary key Python

description: Add values to existing dictionary key Python


code:
tree.xpath('//html')
# []

tree.xpath('//x:html')
# XPathEvalError: Undefined namespace prefix

rawDescription: XPath Child Traversal Methods and Performance


code:
def search(a, x):
    right = 0
    h = len(a)
    while right < h:
        m = (right+h)//2
        if x < a[m]: h = m
        else:
            right = m+1
    # start binary search for left element only
    # including elements from 0 to right-1 - much faster!
    left = 0
    h = right - 1
    while left < h:
        m = (left+h)//2
        if x > a[m]: left = m+1
        else:
            h = m
    return left, right-1

search(daysSick, 5)
(10, 12)

search(daysSick, 2)
(5, 5)

rawDescription: How to do a binary search for a range of the same value?

description: Do a binary search for a range of the same value


code:
prog = re.compile(r"""
    ^
    (?P<PS_BLOCK>
      (?P<PS_LINE>\\ps.*\n)
      (?:                   # Zero or more lines that
        (?!\\(?:ps|lx|ge))  # don't start with
        .*\n                # '\ps', '\lx', or '\ge'...
      )*
      \\ge.*\n              # ...followed by a '\ge' line.
    )
    (?P<GE_BLOCK>
      (?:                   # Again, zero or more lines
        (?!\\(?:ps|lx|ge))  # that don't start with
        .*\n                # '\ps', '\lx', or '\ge'...
      )*
      \\ge.*\n              # ...followed by a '\ge' line.
    )
    """, re.MULTILINE | re.VERBOSE)

rawDescription: Capturing negative matches in Python regular expressions


code:
import __builtin__
__builtin__.foobar = 'barbaz'
foobar

rawDescription: Python: setting __globals__ for modules and their imports


code:
import numpy as np

class Data(np.ndarray):

    def __new__(cls, inputarr):
        obj = np.asarray(inputarr).view(cls)
        return obj

    def remove_some(self, col, val):
        return self[self[col] != val]

z = np.array([(1,2,3), (4,5,6), (7,8,9)],
    dtype=[('a', int), ('b', int), ('c', int)])
d = Data(z)
d = d.remove_some('a', 4)
print(d)

rawDescription: Subclassing numpy ndarray problem

description: Subclassing numpy ndarray problem


code:
import re

with open("myfile") as f:
    data = f.read().split('\n')
    for line in data:
        if line.startswith('#'): continue
        m = re.search(r"^([^ ]*) ([^ ]*) \[([^]]*)\] \/(.*)\/$", line)
        if m:
            print(m.groups())

rawDescription: How to capture all regex groups in one regex?

description: Capture all regex groups in one regex


code:
# This connects signal to the instance of worker located in main thread
workingThread.started.connect(loadingWorker.process)

# Creates a copy of worker in the different thread
loadingWorker.moveToThread(workingThread)

# Signal reaches the instance of worker it was connected to -
# the instance belonging to main thread!
workingThread.start()

rawDescription: PyQt Dialog not responsible while thread running


code:
run = vertically_adjusted_run()  # however you get ahold of it
print(run._element.xml)

rawDescription: How to vertically align picture in line using python-docx

description: Vertically align picture in line using python-docx


code: [(x, y) for x, y in pairs if x != y]

rawDescription: Comparing 2 lists consisting of dictionaries with unique keys in python


code:
def main():
    player = Character()
    player.battle()

rawDescription: Python inheritance with functions without running function


code:
route_id
E1
E2
N
N1
N2
N3
170
S1
S2
S3
S4
W1
W2
W3
W4
C

rawDescription: Python: csv.DictWriter returning blank strings if value is alphanumeric


code:
from scipy import optimize
import numpy as np
def f(x,p1,p2,p3,p4):
    return p1 + p2*np.sin(2*np.pi*p3*x + p4)
sx = 50  # size x
sy = 200 # size y
sz = 100 # size z
# creating the reference parameters
tmp = np.empty((4,sy,sz))
tmp[0,:,:] = (1.2-0.8) * np.random.random_sample((sy,sz)) + 0.8
tmp[1,:,:] = (1.2-0.8) * np.random.random_sample((sy,sz)) + 0.8
tmp[2,:,:] = np.ones((sy,sz))
tmp[3,:,:] = np.ones((sy,sz))*np.pi/4
param_ref = np.empty((4,sy,sz,sx))     # param_ref in this shape will allow an
for i in range(sx):                    # one-shot evaluation of f() to create
    param_ref[:,:,:,i] = tmp           # the data sample
# creating the data sample
x = np.linspace(0,2*np.pi)
factor = (1.1-0.9)*np.random.random_sample((sy,sz,sx))+0.9
data = f(x, *param_ref) * factor       # the one-shot evalution is here
# finding the adjusted parameters
func1d = lambda y, *args: optimize.curve_fit(f, xdata=x, ydata=y, *args)[0] #<-- [0] to get only popt
param = np.apply_along_axis( func1d, axis=2, arr=data )

rawDescription: Fitting a 3D array of data to a 1D function with numpy or scipy


rawDescription: Using File IO to create matrix

description: Using File IO to create matrix


code:
abc
de:f
ghi

rawDescription: How to delete a line from a file using python

description: Delete a line from a file using python


code: dupe_free = dict((freeze(x), x) for x in dupe_list).values()

rawDescription: Most pythonic way of ensuring a list of objects contains only unique items


code:
seen = set()
[x if x not in seen and not seen.add(x) else '' for x in ax]

rawDescription: Remove following duplicates in a tuple

description: Remove following duplicates in a tuple


code:
A_concat_B_notin_A = pd.concat([df['A'], B_notin_A]).order().reset_index(drop=True)
A_concat_B_notin_A

rawDescription: Merging two columns in a DataFrame while preserving first column values


code:
if __name__ == "__main__":
    t1 = threading.Thread(name="Hello1", target=testForThread1()) # <<-- here
    t1.start()

rawDescription: Python parallel threads

description: Python parallel threads


rawDescription: Parallel execution of class methods

description: Parallel execution of class methods


code:
adders = [0,1,2,3]
for i in [0,1,2,3]:
    adders[i] = (lambda b: lambda a: b + a)(i)

adders[1](3)
adders[2](3)

rawDescription: What do (lambda) function closures capture in Python?


code:
my_collection = db['collection_name']
my_collection.drop()

# Or...

db.drop_collection('collection_name')

rawDescription: pymongo (python+mongodb) drop collection/gridfs?

description: Pymongo (python+mongodb) drop collection/gridfs


code: Child.list_attribute = ['foo', 'bar']

rawDescription: Changing immutable type class attributes by way of an inherited static method


code:
d = Device.objects.all()[0]
d.settings.manager_status()

rawDescription: How to create a custom manager for related objects?

description: Create a custom manager for related objects


code:
class BlockContent(models.Model):
    block = models.OneToOneField('Block')
    content = models.TextField()
    type = models.IntegerField(default=1)
    revision = models.IntegerField(default=0)
    latest = models.BooleanField(default=True)

rawDescription: Calling fields in added set in Django

description: Calling fields in added set in Django


rawDescription: Use Pandas string method 'contains' on a Series containing lists of strings


code:
import geneec3
geneec3.geneec3(1,1,1,1)
array([ 1.    ,  0.0116,  1.    ], dtype=float32)

rawDescription: FORTRAN77 function returns an array

description: FORTRAN77 function returns an array