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

class myClass1(object):
    def __init__(self):
        self.x = np.random.random(100)
        self.y = np.random.random(100)

    def plotNReturn1(self, subplot):
        subplot.plot(self.x,self.y,'-*',label='randNxy')
        subplot.set_title('Plot No Return1')
        subplot.legend(numpoints = 1)
    def plotNReturn2(self, subplot):
        subplot.plot(self.y,self.x,'-x',label='randNzw')
        subplot.set_title('Plot No Return2')
        subplot.legend(numpoints = 2)

if __name__=='__main__':
    f = myClass1()
    p = plt.figure()

    p1 = p.add_subplot(122)
    f.plotNReturn2(p1)

    p2 = p.add_subplot(121)
    f.plotNReturn2(p2)

    plt.show()

rawDescription: Does method for plotting need return?

description: Does method for plotting need return


code:
urlpatterns = patterns('django.views.generic.simple',
    ('^$', 'redirect_to', {'url': '/first-page'}),
)
urlpatterns += patterns('myProject.myApp',
    ...
)

rawDescription: django redirecting '/' to a flat page

description: Django redirecting '/' to a flat page


code: companies = [link.text for link in links]

rawDescription: Extracting 'a' tags containing specific substring with Python's BeautifulSoup


code: df

rawDescription: Count occurences of a row with pandas in python


code: import q

rawDescription: Easier way to run Python program in Pdev console without typing commands?


code:
from datetime import date

def months_ago(count):
    today = date.today()
    return ((today.month - count - 1) % 12) + 1

rawDescription: Python 2.7 Get month from 2 months ago (i.e get '05' from todays date)


rawDescription: Why does padding an FFT in NumPy make it run much slower?


code:
def call_attrs(obj, attrs_list, *args):
    for attr in attrs_list:
        if hasattr(obj, attr):
            bound_method = getattr(obj, attr)
            return bound_method(*args)

    raise AttributeError

rawDescription: Nested try statements in python?

description: Nested try statements in python


code:
department = Department.objects.get(pk=1)
print(department.leader.salary)

rawDescription: How can I make a django query-set that uses two classes?

description: Make a django query-set that uses two classes


code: reduce(lambda s,t:s + t, lis, '')

rawDescription: How To Add List Elements and Convert Them To A String


rawDescription: Python list of tuples deduplication

description: Python list of tuples deduplication


code:
ax2 = ax1.twinx()
ax2.set_ylim(20000*km3yearToSv, 70000*km3yearToSv)
ax2.set_ylabel('Sv')

rawDescription: Plot single data with two Y axes (two units) in matplotlib


code:
from itertools import izip_longest

c = np.array(list(izip_longest(*b))).astype(float)

rawDescription: Pythonic and efficient way to do an elementwise "in" using numpy


code:
# File "./pyrun.py"

import os
here = os.path.dirname(os.path.abspath(__file__))

from twisted.internet import tksupport, reactor, protocol
from twisted.protocols.basic import LineReceiver

from Tkinter import Tk, Label, Entry, StringVar

# Protocol to handle the actual communication
class HsProtocol(protocol.ProcessProtocol):
    def __init__(self, text):
        self.text = text

    def connectionMade(self):
        # When haskell prog is opened
        towrite = self.text + '\n'

        # Write a line to the haskell side
        self.transport.write(towrite)

    def outReceived(self, data):
        # When haskell prog write something to the stdout
        # Change the label in the tk window to be the received data
        label_var.set(data[:-1])

def send_num_to_hs(_event):
    content = enternum.get()

    # The abspath of the haskell program
    prog = os.path.join(here, 'Hs')
    reactor.spawnProcess(HsProtocol(content), # communication protocol to use
                         prog, # path
                         [prog] # args to the prog
                         )

# Setting up tk
root = Tk()

# On main window close, stop the tk reactor
root.protocol('WM_DELETE_WINDOW', reactor.stop)

# Since I'm going to change that label..
label_var = StringVar(root, 'Enter a number')

# Label whose content will be changed
label = Label(root, textvariable=label_var)
label.pack()

# Input box
enternum = Entry(root)
enternum.pack()
enternum.bind('<Return>', send_num_to_hs)

# Patch the twisted reactor
tksupport.install(root)

# Start tk's (and twisted's) mainloop
reactor.run()

rawDescription: Connecting A Haskell Program to a Python Program via Pipelines (in Python)


code:
cog = []
for i in range(20201, 20705):
    cog.append({"money": i, "last": "0.001"})
...
p_c['params'] = json.dumps(cog)

rawDescription: Convert curl command into python code

description: Convert curl command into python code


code:
FORMS = {
    'foo': FooForm,
    'bar': BarForm,
}

validate_patterns = [url(r'^validate/%s' % label, 'validate', {'form_class': FORMS[label]}, name='validate-form-%s' % label) for label in FORMS.iterkeys()]

urlpatterns = patterns('ajax_validation.views', *validate_patterns)

rawDescription: Factoring Django URLs using Python wizardry


code:
list = []
for item in itertools.chain(q1, q2):
    list.append(item)

rawDescription: Django Combine a Variable Number of QuerySets


code:
string = 'ascjksdcvyp12nbvnzxcmgonbmbh12hjg23'
re.findall(r'(p\d{2}).*(s|go)\D*(\d+)(?:\D*(\d+))*', string)
string = 'ascjksdcvyp12nbvnzxcmsnbmbh12hjg23'
re.findall(r'(p\d{2}).*(s|go)\D*(\d+)(?:\D*(\d+))*', string)

rawDescription: Python regex: finding sequence of chars inside a string


code:
from itertools import chain
Counter(chain.from_iterable(adjectives))

rawDescription: Python :getting the count for the adjectives in a string


rawDescription: Python dictionary sum

description: Python dictionary sum


code:
records_array = array([1, 2, 3, 1, 1, 3, 4, 3, 2])
idx_sort = argsort(records_array)
sorted_records_array = records_array[idx_sort]
vals, idx_start, count = unique(sorted_records_array, return_counts=True,
                                return_index=True)

# sets of indices
res = split(idx_sort, idx_start[1:])
#filter them with respect to their size, keeping only items occurring more than once

vals = vals[count > 1]
res = filter(lambda x: x.size > 1, res)

rawDescription: Get a list of all indices of repeated elements in a numpy array


code:
tree = ET.parse('some_file.xml')
insert_new_els(tree, 'config', 'data', 'type')
tree.write('some_file_processed.xml')

rawDescription: Adding a parent tag to a nested structure with ElementTree (Python)


rawDescription: Get system date/time in Python after changing time zone


code:
import re
f = open('testtest.txt','r')

string = f.read()

words = re.split('\t|\n',string)

desired = [words[ind+1] for ind, word in enumerate(words) if word == "seven"]

rawDescription: Scan through txt, append certain data to an empty list in Python


rawDescription: Python look for pattern in string

description: Python look for pattern in string


code:
class NoSuper(object):
    def __getattribute__(self, attr):
        """Prevent accessing inherited attributes"""
        for base in self.__bases__:
            if hasattr(base, attr):
                raise AttributeError

        return object.__getattribute__(self, attr)

rawDescription: How to "hide" superclass methods in a subclass

description: "hide" superclass methods in a subclass


code: conc = np.array([A,B,C,D])

rawDescription: Double loops for "concatenation of subarrays in bigger array"


code:
from lxml.html import fromstring

data = 'link1'
tree = fromstring(data)
tree.xpath('//a[re:test(@id, "^hypProduct_[0-9]+$")]', namespaces={'re': "http://exslt.org/regular-expressions"})[0].attrib["id"]

rawDescription: How do i use regular expressions in python lxml, XPath

description: Use regular expressions in python lxml, XPath


code: i = np.argmax(df1.index >= t)

rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


rawDescription: 2 d interpolation with the arrays with different dimensions in python


code:
def change_address(row):
    if row.addr_ad1 == 0 and row.addr_ad2 > 0:
        row.aux_addr_line = row.addr_1
        row.addr_1 = row.addr_2
        row.addr_2 = ''
    elif row.addr_ad1 > 0 and re.sub(r'\s+', '', row.addr_2)[:4] == 'POBOX':
        row.aux_addr_line = ''
        row.addr_1 = row.addr_1
        row.addr_2 = ''
    elif row.addr_ad2 > 0 and re.sub(r'\s+', '', row.addr_1)[:4] == 'POBOX':
        row.aux_addr_line = ''
        row.addr_1 = row.addr_2
        row.addr_2 = ''
    return row

df = df.apply(change_address, axis=1)

rawDescription: Edit column values based on other column values


code:
class Executor(object):
    __metaclass__ = ABCMeta

    def before_execute(self):
        #call each function in the list
        return self.get_script() and self.get_input()

rawDescription: Call functions that have an attribute/characteristic


code:
collection_sub = collection_filter_row(
    catalogue.loc[catalogue.some_column != ''],
    index_dict,
    collection)

rawDescription: Selecting rows from a sparse matrix based on the index of a panda dataframe


code:
import prettytable

def printPiTable(an,bn,n,k):
    """Prints out a table for values n,2n,...,(2^k)n"""
    table = prettytable.PrettyTable(['t', 'a', 'b'])
    u = (2**k)*n
    power = 0
    t = ((2**power)*n)
    while t<=u:
        if power < 1:
            table.add_row((t,an,bn))
            power = power + 1
            t = ((2**power)*n)
        else:
            afrac = (1/2)*((1/an)+(1/bn))
            ann = 1/afrac
            bnn = sqrt(ann*bn)
            table.add_row((t,ann,bnn))
            an = ann
            bn = bnn
            power = power + 1
            t = ((2**power)*n)
    print(table)

printPiTable(4,2*sqrt(2),4,5)

rawDescription: How do I put data from a while loop into a table?

description: Put data from a while loop into a table


code: map(__import__, 'new_package_name')

rawDescription: Import python package after installing it with setup.py, without restarting?


code: new_df = OD[OD['type'].apply(lambda x: 'station' in x)]

rawDescription: Python Pandas filtering and creating new dataframe


code:
now_in_kuala_lumpur=now.astimezone(kuala_lumpur)
print(now_in_kuala_lumpur)
# 2011-09-19 18:58:46.342254+08:00

description: Get system date/time in Python after changing time zone


code:
original = "user1224 : Bob Realname"
original.split(':')[1]
original.split(':')[1].strip()  # remove leading whitespace.

rawDescription: How do I delete the first part of a string in python

description: Delete the first part of a string in python


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

glider = glider[1:-1]

templist = []

for i in glider:
    templist.append(i[1:-1])
glider = templist
del templist

rawDescription: Removing specific columns and rows from nested list


code:
def func(a, b=4):
    return a + b

rawDescription: python function in which a parameter is external if mentioned or internal if it is not mentioned

description: Python function in which a parameter is external if mentioned or internal if it is not mentioned


code:
class SettingManager(models.Manager):

    def get(self, *args, **kwargs):
        from modules.customer.proxies import *
        from modules.customer.models import *

        object = type('DomainSettings', (SettingProxy,), {'__module__' : 'modules.customer'})()
        for pair in self.filter(*args, **kwargs): setattr(object, pair.name, pair.value)

        setattr(object, 'domain', Domain.objects.get(id=int(kwargs['domain__exact'])))
        return object

rawDescription: Returning a custom model instance from a manager


code:
import os

lines = []
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
    x = [int(s) for s in line.split()]
    lines.append(x)

rawDescription: How can I import a string file into a list of lists?

description: Import a string file into a list of lists


code:
cursor = con.cursor()
cursor.execute("SELECT * FROM traffic")

#Retrieves data from SQL
rows = cursor.fetchall()

Month = list()
Traffic = list()

for row in rows:
    Month.append(row['Month'])          # guesswork - what does a row look like?
    Traffic.append(row['Traffic'])

rawDescription: How to use the variable from the python in rpy2?

description: Use the variable from the python in rpy2


code: ref_files = [open(filename, ...) for filename in reflist]

rawDescription: How to open files from a list

description: Open files from a list


code:
browser = Browser(self.layer['app'])
browser.open(self.portal.absolute_url() + '/login_form')
browser.getControl(name='__ac_name').value = TEST_USER_NAME
browser.getControl(name='__ac_password').value = TEST_USER_PASSWOR
browser.getControl(name='submit').click()

rawDescription: How to add Members folder in plone.app.testing?

description: Add Members folder in plone.app.testing


rawDescription: Counting instances a substring shows up

description: Counting instances a substring shows up


code: func = lambda x: x*x

rawDescription: pass function to function with different number of variables

description: Pass function to function with different number of variables


code:
bin_edges = [1,3,5,7,9,11]
bins = pd.cut(df.x, bin_edges, right=False)

df_new = pd.DataFrame({"LB": bin_edges[:-1], "RB": bin_edges[1:]})
binned = df.groupby(bins.values.codes)["y"]
df_new["N"] = binned.count()
df_new["N"] = df_new["N"].fillna(0)
df_new["Pcnt1"] = binned.mean()

rawDescription: How to partition dataframe rows into bins with calculations

description: Partition dataframe rows into bins with calculations


code:
def index(request):
    d = getVariables(request,dictionary={'page_name': "Home"})
    if request.method == "POST":
        form = DropdownSelectionForm(request.POST)

        if form.is_valid():
            selection = form.cleaned_data['selection']
            request.session["selection"] = request.POST['selection']

            return HttpResponseRedirect('/doclistings')
    else:
        form = DropdownSelectionForm()

    return render(request, 'meddy1/index.html', {'form': form})

rawDescription: Django 1.6: Pass dropdown value from one template another


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code: ''.join('{}{}'.format(key, val) for key, val in sorted(adict.items()))

rawDescription: How to convert dictionary into string

description: Convert dictionary into string


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))

colors = ['red', 'brown', 'yellow', 'green', 'blue']
cmap = LinearSegmentedColormap.from_list('name', colors)
norm = plt.Normalize(0, 5)

fig, axes = plt.subplots(ncols=2)
for ax, dat in zip(axes, [data1, data2]):
    im = ax.imshow(dat, cmap=cmap, norm=norm, interpolation='none')
    fig.colorbar(im, ax=ax, orientation='horizontal')
plt.show()

rawDescription: how to define colormap with absolute values with matplotlib

description: Define colormap with absolute values with matplotlib


code:
start = soup.find("td", text="B").parent
for tr in start.find_next_siblings("tr"):
    # exit if reached C
    if tr.find("td", text="C"):
        break

    # get all tds with a desired class
    tds = tr.find_all("td", class_="y")
    for td in tds:
        print(td.get_text())

rawDescription: Find all tags of certain class only after tag with certain text


code: x

rawDescription: scipy smart optimize

description: Scipy smart optimize


code:
a = a[:1] + ["{}:{}".format(x,y) for x,y in enumerate(a[1:], start=1)]
print(a)

rawDescription: Edit an element in a list - python

description: Edit an element in a list - python


code:
'foo' == str.isspace
'foo' == str.isspace()
str.isspace('  ')

rawDescription: Python Jinja2 post

description: Python Jinja2 post


code:
class User(Base):

  # ...

  grouped_comments = relationship(
    'Comment',
    collection_class=GroupedCollection
  )

rawDescription: How to construct query using the SQLAlchemy ORM

description: Construct query using the SQLAlchemy ORM


code: image = image.resize((x, y), Image.ANTIALIAS)

rawDescription: How to adjust the quality of a resized image in Python Imaging Library?

description: Adjust the quality of a resized image in Python Imaging Library


rawDescription: how to merge multiple lists in python

description: Merge multiple lists in python


code:
import Tkinter as tk

root= tk.Tk()

root.title("wm min/max")

# this removes the maximize button
root.resizable(0,0)

# # if on MS Windows, this might do the trick,
# # but I wouldn't know:
# root.attributes(toolwindow=1)

# # for no window manager decorations at all:
# root.overrideredirect(1)
# # useful for something like a splash screen

root.mainloop()

rawDescription: Removing minimize/maximize buttons in Tkinter


code:
import pandas as pd
from pandas.tseries.offsets import *
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

csv_file = '/home/Jian/Downloads/analyse vtr.csv'
df = pd.read_csv(csv_file, index_col=[0], sep='\t')
grouped = df.groupby('adserver_id')

def forecast_func(group):
    ts_log_data = np.log(pd.TimeSeries(group.c_start.values, index=pd.to_datetime(group.day)))
    # for some group, it raise convergence issue
    try:
        model = sm.tsa.ARMA(ts_log_data, order=(1,1)).fit()
        start_date = ts_log_data.index[-1] + Day(1)
        end_date = ts_log_data.index[-1] + Day(7)
        y_forecast = model.predict(start_date.isoformat(), end_date.isoformat())
        return pd.Series(np.exp(y_forecast).values, np.arange(1, 8))
    except Exception:
        pass

result = df.groupby('adserver_id').apply(forecast_func)

rawDescription: Forecasting with time series in python

description: Forecasting with time series in python


rawDescription: How to determine a logic part with python's beautiful soup when crawling

description: Determine a logic part with python's beautiful soup when crawling


code:
import thread
import pygame
from pykinect import nui

DEPTH_WINSIZE = 320,240

screen_lock = thread.allocate()
screen = None

tmp_s = pygame.Surface(DEPTH_WINSIZE, 0, 16)

def depth_frame_ready(frame):
    with screen_lock:
        frame.image.copy_bits(tmp_s._pixels_address)
        arr2d = (pygame.surfarray.pixels2d(tmp_s) >> 7) & 255
        pygame.surfarray.blit_array(screen, arr2d)

        pygame.display.update()

def main():
    """Initialize and run the game."""
    pygame.init()

    # Initialize PyGame
    global screen
    screen = pygame.display.set_mode(DEPTH_WINSIZE, 0, 8)
    screen.set_palette(tuple([(i, i, i) for i in range(256)]))
    pygame.display.set_caption('PyKinect Depth Map Example')

    with nui.Runtime() as kinect:
        kinect.depth_frame_ready += depth_frame_ready
        kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution320x240, nui.ImageType.Depth)

        # Main game loop
        while True:
            event = pygame.event.wait()

            if event.type == pygame.QUIT:
                break

if __name__ == '__main__':
    main()

rawDescription: Access Kinect Depth Data with Pykinect

description: Access Kinect Depth Data with Pykinect


rawDescription: Assigning multiple values to a dictionary key- Python


code: len(lines)

rawDescription: taking a character input in python from a file?

description: Taking a character input in python from a file


code:
file.write(target)
file.write(genstr)
file.flush() # flushes the output buffer to the file

rawDescription: Outputting loop data to a text document in python


rawDescription: How can I create a new project with tasks in Asana using Python?

description: Create a new project with tasks in Asana using Python


code:
e = []
e.append(t.total_seconds())
e

rawDescription: How to extract time and store in an Array/Structure

description: Extract time and store in an Array/Structure


code:
new_lst = []
for i in items:
    if i:
        new_lst.append(i)
items = new_lst

rawDescription: Get file content and make a list

description: Get file content and make a list


rawDescription: What is difference between root and base directory?


rawDescription: Extracting data using regex in python

description: Extracting data using regex in python


code:
import re
s = """MySQL-vm
Version 1.0.1

WARNING:: NEVER EDIT/DELETE THIS SECTION"""
re.search(r'Version\s*([\d.]+)', s).group(1)

rawDescription: Python regex to extract version from a string


rawDescription: Python - Declare two variable with the same values at the same time


code:
for name in obj.names(section):
    ...

rawDescription: Python: Return tuple or list?

description: Python: Return tuple or list


rawDescription: Read a list from a file in python

description: Read a list from a file in python


code: passwords = {row["service"]: row["password"] for row in cursor}

rawDescription: How to retrieve data using Python and MySQL connector

description: Retrieve data using Python and MySQL connector


code:
class cards(pygame.sprite.Sprite):
    def __init__(self,img,tar_posn):

        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.posn = tar_posn
        self.x = 0
        self.y= 0

    def start_shuffle(self,all_cards,target_surface):
        #shuffle the card and draw it on screen
        for one_card in all_cards:
            one_card.shuffle()
            one_card.update(target_surface)

    def shuffle(self):
        import random
        self.x = random.randint(0,12)
        self.y = random.randint(0,4)

    def update(self,target_surface):
        self.patch_rect = (self.x * 73, self.y*98,73, 98)

rawDescription: Pygame Displaying text while paused

description: Pygame Displaying text while paused


code: [i for i in range(n, m) if is_pali(str(i))]

rawDescription: How to write a recursive function for palindromic primes?

description: Write a recursive function for palindromic primes


code:
dict1 = {u'www.othersite.com': 2, u'www.site.com': 1}
dict2 = {u'www.greatsite.com': 1, u'www.site.com': 2}
dict3 = {u'www.othersite.com': 1, u'www.site.com': 2}

rawDescription: Comparing values of different python dictionaries with different keys & structures


code:
def age_matcher(age):
    return lambda p: p.age > age

rawDescription: Dynamic list comprehension

description: Dynamic list comprehension


code:
try:
    return self.get(key)
except KeyError as e:
    raise AttributeError(e)

rawDescription: Is there any trick to "overload the dot operator"?


code:
min_num = int(fs[0])              # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `min_num` variable.
max_num = int(fs[0])              # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `max_num` variable.
for number in fs[1:]:             # iterate over all the items in the list from second element.
    if int(number) > max_num:     # it converts the datatype of each element to int and then it check with the `max_num` variable.
        max_num = int(number)     # If the number is greater than max_num then it assign the number back to the max_num
    if int(number) < min_num:
        min_num = int(number)
print(max_num)
print(min_num)

rawDescription: How to find min and max in python?

description: Find min and max in python


rawDescription: How to count how many positions away an element is in a list?

description: Count how many positions away an element is in a list


code: directory = os.path.join(os.path.expanduser("~"), ".my_cache")

rawDescription: Good way (and/or platform-independent place) to cache data from web


rawDescription: Find second largest element in list with repeated elements


code: df.groupby(['team', 'grade']).agg({'cost':'mean', 'area':'mean', 'size':'sum'}).rename(columns={'cost':'mean_cost', 'area':'mean_area'})

rawDescription: Pandas: return a Dataframe with multiple aggregate values conditioned on another value


code:
from scipy.interpolate import UnivariateSpline
s = UnivariateSpline(x, y, s=x.size)  #larger s-value has fewer "knots"
plt.plot(x, s(x))

rawDescription: Fit a curve for data made up of two distinct regimes


code:
def tfact(n,acc=1):
    if n<=1: return acc
    else: return tfact(n-1,acc*n)

rawDescription: Using a list to synthesize a stack for recursion in Python? Examples?


code:
start_ts = '2000-01-01 00:00:00'

pd.DataFrame({'date': pd.date_range(start_ts, freq='1S', periods=10**4)}).to_csv('d:/temp/10k.csv', index=False)

pd.DataFrame({'date': pd.date_range(start_ts, freq='1S', periods=10**5)}).to_csv('d:/temp/100k.csv', index=False)

pd.DataFrame({'date': pd.date_range(start_ts, freq='1S', periods=10**6)}).to_csv('d:/temp/1m.csv', index=False)

pd.DataFrame({'date': pd.date_range(start_ts, freq='1S', periods=10**7)}).to_csv('d:/temp/10m.csv', index=False)

dt_parser = lambda x: pd.to_datetime(x, format="%Y-%m-%d %H:%M:%S")

rawDescription: Parsing large amount of dates with pandas - scalability - performance drops faster than linear


rawDescription: How to avoid '\n' and '\t' escaping sequence when string is assigned to a variable

description: Avoid '\n' and '\t' escaping sequence when string is assigned to a variable


code:
class MyInt(int):
    def difference(self, i):
        return self - i

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
P = Point(6, 15)
Q = Point(8, 1267)
R = Point(2, 3103)
TwoP = ec_add(P, P)
ThreeP = ec_add(TwoP, P)
# Compute 4P two different ways.
assert ec_add(P, ThreeP) == ec_add(TwoP, TwoP)
# Check the associative law.
assert ec_add(P, ec_add(Q, R)) == ec_add(ec_add(P, Q), R)

rawDescription: Elliptic curve point addition over a finite field in Python


rawDescription: Python: Taking an array and break it into subarrays based on some criteria


rawDescription: How can I translate from one file to another using a dictionary?

description: Translate from one file to another using a dictionary


code:
idx = df.eval('columns >= 1')
idx
df.loc[idx]

rawDescription: What's the meaning of keyword 'columns' in pandas query method?


code:
import sys

write_history = []
def write(*objects, sep=' ', end='\n', file=sys.stdout):
    print(*objects, sep=sep, end=end, file=file)
    write_history.append(file==sys.stdout)

rawDescription: Determining a functions output as print or write


code:
for i in idx:
    print(labmat[data_slices[i]])

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
url = 'https://www.tele2.no/Services/Webshop/FilterService.svc/ApplyPhoneFilters'
req = scrapy.Request(url,
                     method='POST',
                     body='{"filters": []}',
                     headers={'X-Requested-With': 'XMLHttpRequest',
                              'Content-Type': 'application/json; charset=UTF-8'},
                     callback=self.parser2)
yield req

rawDescription: Scrapy simulate XHR request - returning 400


code:
index = initial_list.index(item1)
initial_list.remove(item1)
other_list.remove(other_list[index])

rawDescription: How to remove specific element in an array using python

description: Remove specific element in an array using python


code:
def OnClick(self,event):
    button = event.GetEventObject()
    d = button.GetName()
    data[name_to_index[d]]['n'] += 1
    #    ^^^^^^^^^^^^^^^^

rawDescription: Disable buttons created dynamically based on their name in wxPython


code: f.write(', '.join('{}({:.4f})'.format(string, number) for string, number in zip(w, prob5[0])))

rawDescription: How can I output the data in a customized way?

description: Output the data in a customized way


code:
def doSomethingWithResult(result):
    PDF = result.content

    blobstore_data = PDFStore()

    blobstore_data.content = PDF

    blobstore_data.put()

rawDescription: Getting a file with urlfetch and saving it to the Google datastore


code:
cp /opt/hivemq/bin/init-script/hivemq /etc/init.d/hivemq
chmod +x /etc/init.d/hivemq

rawDescription: HiveMQ and IoT control

description: HiveMQ and IoT control


code:
class Foo:
 pass

x = numpy.array([Foo(), Foo()])
x.append(Foo())

rawDescription: numpy array of python objects

description: Numpy array of python objects


code: zip(*[(k,v['Eng']) for k,v in data.iteritems() if not 'Bio' in v and 'Eng' in v])

rawDescription: making arrays/lists of selected items from a dictionary in python

description: Making arrays/lists of selected items from a dictionary in python


code:
class User(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    verse = models.ForeignKey(Verse)

rawDescription: Django - Use one models primary key in another model


code:
friends = {'Matt' : {'phone' : '13579',
                  'birthday' : '2 Dec',
                  'address' : 'Sydney',
                  'interests' : ['a', 'b', 'c' ]},

       'Tim' : {'phone' : '24680',
                 'birthday' : '19 Feb',
                 'address' : 'Honolulu',
                 'interests' : ['x', 'y', 'z' ]},

       'Kate' : {'phone' :'12345',
                  'birthday' : '30 Jun',
                  'address' : 'Beijing',
                  'interests' : ['q', 'w', 'e' ]}
       }

rawDescription: Searching dictionaries in Python

description: Searching dictionaries in Python


rawDescription: file as an optional parameter

description: File as an optional parameter


code:
data = [[i.replace('%', '') if isinstance(i, basestring) else i
                                      for i in j] for j in data]

rawDescription: Find and Replace Percent Signs - Python

description: Find and Replace Percent Signs - Python


code:
from ctypes import *

class Info1(Structure):
    _fields_ = [("req_no", c_uint16),
                ("status", c_uint16),
                ("value_len", c_uint32),
                ("value", c_uint64)]

data = (
    '\x01\x00'
    '\x02\x00'
    '\x03\x00\x00\x00'
    '\x04\x00\x00\x00\x00\x00\x00\x00'
)
# Assumed data was received. I assumed both server, clients are little-endian.
# else, use socket.ntoh{s|l}, socket.hton{s|l} ....

header = Info1()
memmove(addressof(header), data, sizeof(header))
assert header.req_no == 1
assert header.status == 2
assert header.value_len == 3
assert header.value == 4

rawDescription: Convert string data received from network packet to Structure


code:
def ask_exit(self):
    """ Ask the shell to exit. Can be overiden and used as a callback. """
    self.exit_now = True

rawDescription: Why can't exit() terminate the program immediately while in the readlines loop?


rawDescription: Convert triplets to matrix/dataframe in python


code:
fp  = open('image.txt')
words= [word.strip() for line in fp.readlines() for word in line.split(',') if word.strip()]
print(", ".join(words)) # or `print(words)` if you want to print out `words` as a list

rawDescription: Reading text file word by word separated by comma


code:
if __name__ == '__main__':
    pool = Pool(processes=4, maxtasksperchild=10)
    keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = pool.map(f, keys)

rawDescription: How to limit the number of concurrent workers?

description: Limit the number of concurrent workers


code:
from mechanize import Browser
br = Browser()
br.open('http://news.bbc.co.uk')

rawDescription: check that a script is actually using a proxy from a ip list

description: Check that a script is actually using a proxy from a ip list


code:
leaves = []
for i in range(5):
    leaves.append(Leaf())

rawDescription: How to duplicate objects in Python/Pygame?

description: Duplicate objects in Python/Pygame


code: somefunction(lambda x, regexobject=re.compile(r'foobar'): regexobject.match(x))

rawDescription: Can I have anonymous function with "static" variables in Python?

description: Have anonymous function with "static" variables in Python


code:
def everythird(l):
    return l[0::3]

rawDescription: Python: How to return a list without modifying the original list using a while loop only?


code:
from pyparsing import Regex, Optional

number = Regex(r"\d+(\.\d*)?").setParseAction(lambda t: float(t[0]))

fraction = number("numerator") + "/" + number("denominator")
fraction.setParseAction(lambda t: t.numerator / t.denominator)

rawDescription: How can fractional number expressions be parsed using pyparsing?


code:
def some_helper():
    print(inspect.stack()[1][1])

rawDescription: Getting entry point scripts path in scripts called by it


rawDescription: Converting bytes to integer in Python

description: Converting bytes to integer in Python


code: plt.imshow = my_imshow

rawDescription: Matplotlib: using a figure object to initialize a plot


code:
from lxml import etree

bundles = etree.fromstring(data)

for node in bundles.xpath('bundle/name[.="FOO"]/../bitstreams/bitstream/id'):
    print(node.text)

rawDescription: Python, lxml - get a sibling tag's (grand)child's text


code:
class MyList(list):
    def sort(self, cmp=None, key=None, reverse=None):
        if cmp is None and key is None:
            key = int
        return super(MyList, self).sort(cmp, key, reverse)

rawDescription: How do you use redefine a method and still use the original unmodified inherited method in the method?

description: Use redefine a method and still use the original unmodified inherited method in the method


rawDescription: 'int' object has no attribute 'update' - dictionary within dictionary - python2.7


code:
for entry in inputlist:
    entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y']))

rawDescription: Python iterate list of dicts and create a new one


rawDescription: What would be a better implementation of all combinations in lexicographic order of a jagged list?


code: list1 = list2 = [x for x in list1 if x[1] in zip(*list2)[1]]

rawDescription: Removing non-matching items from datasets


code:
class MagicString(str):
    magicSplit = str.split

s = MagicString(' 1234    Q-24 2010-11-29         563   abc  a6G47er15')
s.magicSplit()

rawDescription: how in python to split a string with unknown number of spaces as separator?

description: How in python to split a string with unknown number of spaces as separator


key1: value

key2: value

key3: value

rawDescription: how do I import an array containing dictionary from a text file?

description: Import an array containing dictionary from a text file


code: digits = [randint(0, 9) for i in range(4)] # 4 calls in a list

rawDescription: Python function to create random numbers


rawDescription: How to check for key value metadata in markdown

description: Check for key value metadata in markdown


code:
## update value at a specific row x and column y?
def set_cell(connection, x_name, y_name, value):
    sql = 'UPDATE simple SET %s="%s" WHERE row_name="%s"' % (
        y_name, value, x_name
        )
    connection.execute(sql)

## select a value at a specific row x and column y?
def get_cell(connection, x_name, y_name):
    sql = 'SELECT %s FROM simple WHERE row_name="%s"' % (
        y_name, x_name
        )
    # Return the first row of results (there should be only one)
    # and the first column from that row
    return list(connection.execute(sql))[0][0]

rawDescription: How to insert and call by row and column into sqlite3 python

description: Insert and call by row and column into sqlite3 python


code:
from functools import reduce
import operator as op

print("The product of the list is", reduce(op.mul, numbertotal))

rawDescription: How can I multiply numbers in a list (after removing duplicates)?

description: Multiply numbers in a list (after removing duplicates)


code:
is_one = np.where(df == 1)
is_one
df.index[is_one[0]], df.columns[is_one[1]]

rawDescription: Extract array (column name, data) from Pandas DataFrame


rawDescription: Number of non-missing values in array? Len(x) excluding missing values?


code:
def main():
    parser = argparse.ArgumentParser(description='Python Grep.')
    parser.add_argument('--debug', action='store_true', help='Print debug messages')
    parser.add_argument('pattern', type=str, nargs='+', help='Pattern(s) for pgrepping')
    args = parser.parse_args()

    Grepper(args.pattern, args.debug).matchline()

rawDescription: Take multiple patterns from cli. argparse Python3


code:
from datetime import date, year
import calendar
def first_day(dt):
     # Simply copy year and month into new date instance
     return date(dt.year, dt.month, 1)
def last_day(dt):
     days_in_month = calendar.monthrange(dt.year, dt.month)[1]
     return date(dt.year, dt.month, days_in_month)
nth_day = 32
day_of_year = date(2012, 1, 1) + timedelta(days=nth_day - 1)
day_of_year
first_day(day_of_year), last_day(day_of_year)
day_of_year - first_day(day_of_year), last_day(day_of_year) - day_of_year

rawDescription: Python: Date manipulation code

description: Python: Date manipulation code


code:
@app.route("/")
def home():
    user_id = request.cookies.get('YourSessionCookie')
    if user_id:
        user = database.get(user_id)
        if user:
            # Success!
            return render_template('welcome.html', user=user)
        else:
            return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        # You should really validate that these fields
        # are provided, rather than displaying an ugly
        # error message, but for the sake of a simple
        # example we'll just assume they are provided

        user_name = request.form["name"]
        password = request.form["password"]
        user = db.find_by_name_and_password(user_name, password)

        if not user:
            # Again, throwing an error is not a user-friendly
            # way of handling this, but this is just an example
            raise ValueError("Invalid username or password supplied")

        # Note we don't *return* the response immediately
        response = redirect(url_for("do_that"))
        response.set_cookie('YourSessionCookie', user.id)
        return response

@app.route("/do-that")
def do_that():
    user_id = request.cookies.get('YourSessionCookie')
    if user_id:
        user = database.get(user_id)
        if user:
            # Success!
            return render_template('do_that.html', user=user)
        else:
            return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))

rawDescription: Python Flask: keeping track of user sessions? How to get Session Cookie ID?


code: clamp = lambda n, minn, maxn: max(min(maxn, n), minn)

rawDescription: How to limit a number to be within a specified range? (Python)

description: Limit a number to be within a specified range? (Python)


code:
df = pd.DataFrame({'Date' : pd.date_range('20130101', periods=100),
                   'Skew': 10+pd.np.random.randn(100)})
min_date = df.Date.min()
start = min_date.dayofweek

if start < 1:
    min_date = min_date - pd.np.timedelta64(6+start, 'D')
elif start > 1:
    min_date = min_date - pd.np.timedelta64(start-1, 'D')

df.groupby((df.Date - min_date).astype('timedelta64[D]')//7).mean()

rawDescription: How to sum over all values between 2 repeating values in pandas?

description: Sum over all values between 2 repeating values in pandas


code: result = np.array(result)

rawDescription: How to create a numpy array from two lists of tuples, but only when the tuples are the same

description: Create a numpy array from two lists of tuples, but only when the tuples are the same


code:
newlink = link['href']
# .. make replacements
link['href'] = newlink # store it back

rawDescription: How to save back changes made to a HTML file using BeautifulSoup in Python?

description: Save back changes made to a HTML file using BeautifulSoup in Python


code:
import datetime
import pickle

class PostCreateView(CreateView):

     model = Post
     form_class = PostForm
     template_name = 'main/add_post.html'

     def form_valid(self,form):

        if not hasattr(self.request.session['last_submitted']):
            last_submitted = pickle.dumps(datetime.datetime.now())
            self.request.session['last_submitted'] = last_submitted
            save_it = True
        else:
            last_submitted = pickle.loads(self.request.session['last_submitted'])
            delta = datetime.datetime.now() - last_submitted
            save_it = (delta.seconds > 60) # assume allow re-submit after 60 seconds

        if save_it:
          self.object = form.save(commit=False)
          # any manual settings go here

          #self.object.category =      Category.objects.filter(category__in=categories).all()

          self.object.moderator = self.request.user
          self.object.image = extract(self.object.url)
          self.object.thumbnail = extractt(self.object.content)
          self.object.save()
          return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
        else:
           # consider redirect as usual, if the user just clicked twice by mistake
           return self.form_invalid(form) # or Http error code

rawDescription: prevent multiple submissions when user clicks submit button multiple times before loading to the new page

description: Prevent multiple submissions when user clicks submit button multiple times before loading to the new page


code:
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())

bday_over_df = pd.date_range(start=df.index.min().date(),
                             end=df.index.max().date(), freq=bday_us)

rawDescription: Average hourly week profile for a year excluding weekend days and holidays


code:
from mysuper import MySuper

class King(MySuper):
  def __init__(self, fizz=None):
    if fizz is None:
      self.fizz = 'baz'
    else:
      self.fizz = fizz
    super().__init__()

rawDescription: How to dynamically create new python class files?

description: Dynamically create new python class files


code:
from functools import partial
b = Button(app_name, text="..." , command = partial(any_function, 7))

rawDescription: tkinter , python , buttons

description: Tkinter , python , buttons


code:
# my_variables.py
foo = "this is foo"
bar = "this is bar"

rawDescription: Call python file from suite setup in robot framework


rawDescription: extracting only texture filenames being used in maya file from the list of filename paths

description: Extracting only texture filenames being used in maya file from the list of filename paths


code:
halfway_idx = len(values)/2
med         = median([values[0], values[halfway_idx], values[-1]])
if med == values[0]:
   pass # median already is in the first position
elif med == values[halfway_idx]:
   values[0], values[halfway_idx] = values[halfway_idx], values[0] #swap middle and first
else:
   values[0], values[-1] = values[-1], values[0] # swap first and last

rawDescription: python if elif different result

description: Python if elif different result


code: max=max+2 ### due to the later code, it got offset by 2

rawDescription: Euler's pentagonal number function in python


code:
tgt='AGAGAGAGACGTACACAC'
re.match(r'{}'.format('ACGT'), tgt)
re.search(r'{}'.format('ACGT'), tgt)

rawDescription: Python: use string variable as search pattern in regex


code:
def rename_action(modeladmin, request, queryset):
    queryset.update(name='Ni')
make_published.short_description = "Rename selected objects to 'Ni'"

class FooAdmin(admin.ModelAdmin):
    actions = [rename_action, ...]

rawDescription: Customizing django admin site - in row buttons


code:
import urllib.request

urllib.request.urlretrieve('http://stackoverflow.com', 'so.html')

rawDescription: how to convert UTF-8 code to symbol characters in python

description: Convert UTF-8 code to symbol characters in python


code: [x*x for x in values if x > 15]

rawDescription: Learning Python from Ruby; Differences and Similarities


rawDescription: Using a tuple (i,j,k,...) to construct an intersection list_of_sets[i] & list_of_sets[j] & list_of_sets[k]


code:
import ast
for target in root.find("./Objects"):
    for i in ast.literal_eval(target.text):
        print(target.get('name'), i)

rawDescription: Parse XML attribute to variable with ElementTree


code:
def update_condition(self, type, params):
    self.conditions[:] = [helper(c,type,params) for c in self.conditions]

rawDescription: Modify values of a list while iterating over it in Python?


code:
for row in csvReader:
    if any('2015' in s for s in row): data.append(row)

rawDescription: Selecting lists which contain a string value


code: (line for _ in itertools.repeat(()) for line in open("filename"))

rawDescription: Re-reading file when cycling over a file object in Python


code:
rate_df = pd.DataFrame(rate_arr.T, index=['tx', 'ny'], columns=[2008, 2009])
rate_df

rawDescription: n-dimensional table lookup: array, dataframe, or dictionary?

description: N-dimensional table lookup: array, dataframe, or dictionary


code:
import asana
client = asana.Client.basic_auth('ASANA_KEY')
project = {'name':'test','workspace':'WORKSPACE_ID'}
client.projects.create(project)

rawDescription: How can I create a new project with tasks in Asana using Python?

description: Create a new project with tasks in Asana using Python


code:
from suds.client import Client
from suds.transport.https import HttpAuthenticated
from suds.xsd.doctor import ImportDoctor, Import
import os
import shutil
import time
from tempfile import gettempdir as tmp

class MyTransport(HttpAuthenticated):
    def __init__(self,*args,**kwargs):
        HttpAuthenticated.__init__(self,*args,**kwargs)
        self.last_headers = None
    def send(self,request):
        result = HttpAuthenticated.send(self,request)
        self.last_headers = result.headers
        return result

class TenaciousConnector():
    def init_client(self, wsdl_url):
        retries = 3
        services = None
        # Cached mode
        (client, services) = self._init_client(wsdl_url)
        while not services and retries > 0:
            nap_time = 6 - retries
            retries = retries - 1
            time.sleep(nap_time)
            # clear potentially rotten cache right before retrying
            shutil.rmtree(os.path.join(tmp(), 'suds'), True)
            (client, services) = self._init_client(wsdl_url)
        if not services:
            # No-cache mode
            retries = 3
            (client, services) = self._init_client(wsdl_url, False)
            while not services and retries > 0:
                nap_time = 6 - retries
                retries = retries - 1
                time.sleep(nap_time)
                (client, services) = self._init_client(wsdl_url, False)
        if not services:
            raise Exception("Failed at loading WSDL from {0}".format(wsdl_url))
        return client

    def _init_client(self, wsdl_url, cache=True):
        i_doc = ImportDoctor(Import('http://schemas.xmlsoap.org/soap/encoding/'))
        tx = MyTransport()
        if cache:
            client = Client(wsdl_url, doctor=i_doc, transport=tx)
        else:
            client = Client(wsdl_url, doctor=i_doc, transport=tx, cache=None)
        services = client.wsdl.services
        return (client, services)

rawDescription: Python, suds - dealing with rotten WSDL caches and responses


rawDescription: How to repeat characters in Python without string concatenation?

description: Repeat characters in Python without string concatenation


code:
def traverse(i):
    for d in i:
        childs = d.get('childs')
        for j in traverse(childs) if childs else ['']:
            yield d['kw']+' '+j

res = list(traverse(dirs))

rawDescription: Walk recursively through childs of a list in Python


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open(...).read())
states = {}
for i, table in enumerate(soup("table")):
    for city in table("span"):
        states.setdefault(i, []).append(city.text.strip())

rawDescription: Python regex by grouping elements belonging to same category


code:
def magic(lst):
    lst = lst[:] # create copy
    seen = set() # prior values as set
    for i in range(len(lst)):
        if any(lst[i] >= x for x in lst[:i]): # greter/equal than any prior
            lst[i] += 1      # first increment
            while lst[i] in seen:
                lst[i] += 1  # increment more
        seen.add(lst[i])     # add to prior set
    return lst

rawDescription: Check whether list element is greater than previous elements


code: filename = sys.argv[1] if len(sys.argv) >= 2 else 'defaultfile.txt'

rawDescription: Most compact way to store argv into variable with default value in Python


code:
class DirectorySelectionDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        editor = QtGui.QFileDialog(parent)
        editor.filesSelected.connect(
            lambda: editor.setResult(QtGui.QDialog.Accepted))
        ...

    def setModelData(self, editor, model, index):
        print(editor.result())
        if editor.result() == QtGui.QDialog.Accepted:
            model.setData(index, editor.selectedFiles()[0])

rawDescription: QFileDialog as editor for TableView: how to get result?


code:
X, Y = np.mgrid[x.min():x.max():GSIZE*1j, y.min():y.max():GSIZE*1j]

grid = np.c_[X.ravel(), Y.ravel()]
points = np.c_[df_points.x, df_points.y]

tree = KDTree(grid)
dist, indices = tree.query(points)

grid_values = df_points.groupby(indices).v.sum()

df_grid = pd.DataFrame(grid, columns=["x", "y"])
df_grid["v"] = grid_values

fig, ax = pl.subplots(figsize=(10, 8))
ax.plot(df_points.x, df_points.y, "kx", alpha=0.2)
mapper = ax.scatter(df_grid.x, df_grid.y, c=df_grid.v,
                    cmap="viridis",
                    linewidths=0,
                    s=100, marker="o")
pl.colorbar(mapper, ax=ax);

rawDescription: Find a easier way to cluster 2-d scatter data into grid array data


code:
app = Flask(__name__)
app.session_interface = MySessionInterface()

rawDescription: How to configure a single flask application to handle multiple domains?

description: Configure a single flask application to handle multiple domains


code:
s = '
some text
'
tree = etree.HTML(s)
imgs = tree.xpath('.//img')
thm = "new-value"
for img in imgs:
    img.set('src', thm)
    a = etree.Element('a', href="#")
    img.addprevious(a)
    a.insert(0, img)
    a.tail = img.tail
    img.tail = ''
etree.tostring(tree)

rawDescription: lxml python load html string without header and body and add element around targeted elements

description: Lxml python load html string without header and body and add element around targeted elements


rawDescription: Findall regex in python

description: Findall regex in python


rawDescription: pandas - groupby and filtering for consecutive values

description: Pandas - groupby and filtering for consecutive values


code:
all([True, True, True])
all([True, False, True])

rawDescription: How to write parallel loop iterations in one line (lists have unequal lengths)

description: Write parallel loop iterations in one line (lists have unequal lengths)


code: sTable = sTable + '\n' + sRow  # simplified, sRow is a function call

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


rawDescription: PYQT directory dialog opens twice

description: PYQT directory dialog opens twice


code: newstring = re.sub(r'\[\d+\]', replacement, yourstring)

rawDescription: find string with format '[number]' using regex

description: Find string with format '[number]' using regex


code:
a = print
a('magic') # prints 'magic'

def add_and_call(func, num):
    num += 1
    func(num)

add_and_call(print, 1) # prints 2

rawDescription: Variable printing in python

description: Variable printing in python


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox()
browser.implicitly_wait(30)
browser.get('https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier')
email = browser.find_element_by_xpath('//*[@id="Email"]')
email.clear()
email.send_keys("email@gmail.com")  # change email
email.send_keys(Keys.RETURN)
password = browser.find_element_by_xpath('//*[@id="Passwd"]')
password.clear()
password.send_keys("password")  # Change Password
password.send_keys(Keys.RETURN)
time.sleep(10)
browser.save_screenshot('screen_shot.png')
browser.close()

rawDescription: open a browser page and take screenshot every n hour in python 3

description: Open a browser page and take screenshot every n hour in python 3


code:
import argparse

class MultichoiceArgumentParser(argparse.ArgumentParser):
    def _get_values(self, action, arg_strings):
        if isinstance(action.nargs, int):
            value = [self._get_value(action, v) for v in arg_strings]
            for i, v in enumerate(value):
                self._check_value(action, v, arg_num=i)
            return value
        else:
            return super()._get_values(action, arg_strings)

    def _check_value(self, action, value, arg_num=None):
        # converted value must be one of the choices (if specified)
        if action.choices is not None:
            choices = action.choices
            if isinstance(action, MultichoiceAction):
                choices = choices[arg_num]
            if value not in choices:
                args = {'value': value,
                        'choices': ', '.join(map(repr, choices))}
                msg = argparse._('invalid choice: %(value)r (choose from %(choices)s)')
                raise argparse.ArgumentError(action, msg % args)

class MultichoiceAction(argparse._StoreAction):
    pass

class MultichoiceFormatter(argparse.HelpFormatter):
    def _metavar_formatter(self, action, default_metavar):
        if action.choices is not None and isinstance(action, MultichoiceAction):
            result = []
            for choices in action.choices:
                choice_strs = [str(choice) for choice in choices]
                result.append('{%s}' % ','.join(choice_strs))
            result = tuple(result)
            return lambda x: result
        else:
            return super()._metavar_formatter(action, default_metavar)

rawDescription: Python argparse second choices

description: Python argparse second choices


code:
def class_feature_importance(X, Y, feature_importances):
    N, M = X.shape
    X = scale(X)

    out = {}
    for c in set(Y):
        out[c] = dict(
            zip(range(N), np.mean(X[Y==c, :], axis=0)*feature_importances)
        )

    return out

rawDescription: Using scikit to determine contributions of each feature to a specific class prediction


code:
filter(None, (f(char) for char in string) )
# or, using itertools.imap,
filter(None, imap(f, string))

rawDescription: Ignore an element while building list in python


code:
for lst in (A,B,C): # put as many lists as you like into the parentheses
    print(min(lst))

rawDescription: How to pick the smallest value in a list when an iterative process is applied to the list

description: Pick the smallest value in a list when an iterative process is applied to the list


rawDescription: How to save and retrive Pandas dataframes with hierarchichal indexing?

description: Save and retrive Pandas dataframes with hierarchichal indexing


code: calc(val1, val2)

rawDescription: Python 3, Passing data from one function to another


code: suptitle('Bla Bla')

rawDescription: Pandas: boxplot of one column based on another column


code:
inputFile = open(path,'r')
for n, line in enumerate(inputFile):
    if n > given_number:
       variableX = line.split(' ')[5]
inputFile.close()

rawDescription: Open txt file, skip first lines and then monitor a given column of data


code:
import pandas as pd
pd.DataFrame(np.random.normal(means,sts))

rawDescription: Using data from pythons pandas dataframes to sample from normal distributions


code: lb = Listbox(self, yscrollcommand = lambda x, y, i=i: self.yscroll(i, x, y))

rawDescription: Which dynamically created object called the function?


rawDescription: PIL import png pixels as single value instead of 3 values vector


code:
class Node(object):
    def __init__(self, name, attributes, children):
        self.name = name
        self.attributes = attributes if attributes is not None else {}
        self.children = children if children is not None else []
    def add_node_attributes(self):
        self.attributes.update( { "test" : 5 } )

rawDescription: python subclasses have general functions shared across them

description: Python subclasses have general functions shared across them


code:
self.cursor1 = db.cursor(named_tuple=True)
# ...
self.cursor1.execute(
     '''SELECT title, availed_title, episode_number,
               platform_id_series, platform_id_season,
               platform_id_episode, season_number, url,
               provider_id, country, currency_code, est_hd_offer,
               est_sd_offer, vod_hd_offer, vod_sd_offer
     FROM main_googlecatalogtmp WHERE asset_type="episode"'''
)
item = cursor.fetchone()
print('My title is {}'.format(item.title))

rawDescription: Suggested formatting for SQL SELECT return


code:
# Save the listener instance in a local variable
network = listener()
reactor.listenUDP(10000, network)

# Use the local variable to connect a GUI event to the network
MyGUIApplication().connect_button("send_button", network.send_stuff)

# Use the local variable to implement a signal handler that sends data
def report_signal(*ignored):
    reactor.callFromThread(network.send_stuff, "got sigint")
signal.signal(signal.SIGINT, report_signal)

# Pass the object referenced by the local variable to the initializer of another
# network-related object so it can save the reference and later call methods on it
# when it gets events it wants to respond to.
reactor.listenUDP(20000, AnotherDatagramProtocol(network))

rawDescription: Sending arbitrary data with Twisted

description: Sending arbitrary data with Twisted


code: t = 'forward(90) or __import__("os").system("rm -rf ~")'

rawDescription: How can I execute a command inputted by the user as a turtle command?

description: Execute a command inputted by the user as a turtle command


code:
from itertools import chain, product
from PIL import Image, ImageDraw

flatten = chain.from_iterable

def closed_regions(image, test):
    """
    Return all closed regions in image who's pixel satisfy test.
    """
    pixel = image.load()
    xs, ys = map(xrange, image.size)
    todo = set(xy for xy in product(xs, ys) if test(pixel[xy]))
    while todo:
        region = set()
        edge = set([todo.pop()])
        while edge:
            region |= edge
            todo -= edge
            edge = todo.intersection(
                flatten(((x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)) for x, y in edge))
        yield region

# rest like above

rawDescription: How to determine regions of pixels with a shared value using PIL

description: Determine regions of pixels with a shared value using PIL


code:
from itertools import chain
import networkx as nx

def power_set(iterable):
    """Return an iterator over the power set of the finite iterable."""
    s = list(iterable)
    return chain.from_iterable(combinations(s, n) for n in xrange(len(s) + 1))

def enumerate_graphs(nodes):
    # create a list of possible edges
    possible_edges = list(combinations(nodes, 2))

    # create a graph for each possible set of edges
    for edge_set in power_set(possible_edges):
        g = nx.Graph()
        g.add_nodes_from(nodes)
        g.add_edges_from(edge_set)
        yield g

def enumerate_digraphs(nodes):
    # create a list of possible edges
    possible_edges = list(combinations(nodes, 2))

    # generate each edge set
    for edge_set in power_set(possible_edges):
        # for each set of `M` edges there are `M^2` directed graphs
        for swaps in power_set(xrange(len(edge_set))):
            directed_edge_set = list(edge_set)
            for swap in swaps:
                u,v = directed_edge_set[swap]
                directed_edge_set[swap] = v,u
            g = nx.DiGraph()
            g.add_nodes_from(nodes)
            g.add_edges_from(directed_edge_set)
            yield g

rawDescription: Efficient storage and use of large sets of graphs in Python w/ networkX, the aim being inference across the graphs?


code:
[py2exe]
compressed=1
bundle_files=2
dist_dir=my/dist/dir
dll_excludes=w9xpopen.exe

rawDescription: Is there a way to specify the build directory for py2exe


code:
from svc_bar import bar
from svc_foo import foo
import logging

# Add a StreamHandler for the root logger, so we get some console output in
# addition to file logging (for easy of testing). Also set the level for
# the root level to INFO so our messages don't get filtered.
logging.basicConfig(level=logging.INFO)

foo()
bar()

rawDescription: How to structure the Logging in this case (python)

description: Structure the Logging in this case (python)


code:
df = df.set_index('A')
pd.Index(np.arange(0, len(df))).equals(df.index)

rawDescription: checking if pandas dataframe is indexed?

description: Checking if pandas dataframe is indexed


code: res = db.query('SELECT count(*) FROM jobs WHERE person_id = 1 AND type = 2')

rawDescription: Python: data on many people - how to structure?


code:
data = [
    {
        'name': 'john',
        'age': 10
    },
    {
        'name': 'paul',
        'age': 20
    }
]
next((d['age'] for d in data if d['name'].lower() == 'john'), None)

rawDescription: How to search for the value of an element in a list of dict based on another value from the same element?

description: Search for the value of an element in a list of dict based on another value from the same element


code:
[r for r in listOfList
   for indexed in ({lst[i] for i in r},)
   if 1 not in indexed and 0 in indexed]

rawDescription: How to improve this list comprehension

description: Improve this list comprehension


code: ' '.join(line.split(None, 2)[:2])

rawDescription: python to search files and parse using regular expression

description: Python to search files and parse using regular expression


code:
with open("my_text_file.txt", "r") as f:
    items = f.read()
    items = items.replace('\n', '').replace(' ', '')
    items = items.split(",")

    items = [i for i in items if i]
    if items:

        if len(items) == 1:
            print('You have {}'.format(items[0]))

        if len(items) > 1:
            last_item = items[-1]
            items_ex_last_item = items[:-1]
            print("You have " + ', '.join(items_ex_last_item) + " and " + last_item + ".")

    else:
        print("There is no item.")

rawDescription: Get file content and make a list

description: Get file content and make a list


rawDescription: python sorting array of XYZ coordinates in table matrix

description: Python sorting array of XYZ coordinates in table matrix


code:
years = collections.defaultdict( list )
players = collections.defaultdict( list )
teams = collections.defaultdict( list )

rawDescription: Python data structure recommendation?

description: Python data structure recommendation


code: a = com/(1 + com)

rawDescription: Pandas EWMA not working as expected

description: Pandas EWMA not working as expected


rawDescription: How to get PMI scores for trigrams with NLTK Collocations? python

description: Get PMI scores for trigrams with NLTK Collocations? python


rawDescription: Exporting Beautiful Soup table scrape results to CSV


code: print("Your number is ", a)

rawDescription: Need assistance on Print function

description: Need assistance on Print function


code:
snakefield.table[self.x - 0 * b][self.y - 0 * c] = self.sign  # <-- this one
snakefield.table[self.x - 1 * b][self.y - 1 * c] = self.sign
snakefield.table[self.x - 2 * b][self.y - 2 * c] = self.sign

rawDescription: Python; Updating several positions in a list with "for x in range"


code:
animal,age,count,legs
dogs,3,5,4
cats,6,4,4
birds,2,1,2

rawDescription: Python csv to json column order

description: Python csv to json column order


code:
import logging
log = logging.getLogger('hello')
vars(log)
type(log)

rawDescription: Duck-typable classes, ABC, iheritance, __new__


rawDescription: Convert a string in a few int between commas in python


code:
d = {}

with open('D:/project/report.txt','r') as fob:
    for line in fob:
        for word in line.split():
            d[word] = d.get(word, 0) + 1

rawDescription: Storing the count of each word occurring in a text file


rawDescription: Scrapy crawling data from a forum

description: Scrapy crawling data from a forum


code:
def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp')

rawDescription: Boto3 to download all files from a S3 Bucket


code:
k = subprocess.Popen(['python', 'parser.py', '-f', r'C:\Report1\2011-03-14.txt'],
                     shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

rawDescription: Python on Windows: path as subprocess argument gets modified and generating error


code:
from lxml import etree
node = etree.fromstring("""<content>
Text outside tag
Text inside tag

</content>""")
stringify_children(node)

rawDescription: Get all text inside a tag in lxml

description: Get all text inside a tag in lxml


rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
class Node:
    def __init__(self, name):
        self.name = name
        self.links = []

    def link(self, other):
        #one of the following, depending if other methods of this base class will be used in the derived class
        self.links.append((other, None))
        #self.links.append(other)

class WeightedNode(Node):
    def link(self, other, weight):
        self.links.append((other, weight))

rawDescription: Give class instances different methods depending on instance variables


code:
def two_largest(sequence):
    first = second = 0
    for item in sequence:
        if item > second:
            if item > first:
                first, second = item, first
            else:
                second = item
    return first, second

rawDescription: More pythonic way to find first two greatest value in a list in python


code:
my_dict = defaultdict(dict)
#...
my_dict[seq]['sequences'] = read_seq
#And now your two strings:
my_dict[seq]['additional'] = ('string1','string2')

rawDescription: Add multiple values to python dictionary


code:
if symbol in reps:
    print("You already defined that symbol")

rawDescription: Updating dictionaries in python

description: Updating dictionaries in python


code: result = (array < 25) * array

rawDescription: threshold in 2D numpy array

description: Threshold in 2D numpy array


code:
from pybrain.datasets.classification import ClassificationDataSet
# below line can be replaced with the algorithm of choice e.g.
# from pybrain.optimization.hillclimber import HillClimber
from pybrain.optimization.populationbased.ga import GA
from pybrain.tools.shortcuts import buildNetwork

# create XOR dataset
d = ClassificationDataSet(2)
d.addSample([0., 0.], [0.])
d.addSample([0., 1.], [1.])
d.addSample([1., 0.], [1.])
d.addSample([1., 1.], [0.])
d.setField('class', [ [0.],[1.],[1.],[0.]])

nn = buildNetwork(2, 3, 1)
# d.evaluateModuleMSE takes nn as its first and only argument
ga = GA(d.evaluateModuleMSE, nn, minimize=True)
for i in range(100):
    nn = ga.learn(0)[0]

rawDescription: How to train a neural network to supervised data set using pybrain black-box optimization?

description: Train a neural network to supervised data set using pybrain black-box optimization


code:
import pandas as pd, numpy as np

factor_list = ['factor1', 'factor2', 'factor3']
method_list = ['method1', 'method2', 'method3']

grouping_list = ['group1', 'group2', 'group3']
strategy_list = ['s1', 's2', 's3']

parameter_list = [1, 5, 10, 20, 40]  # -999 mean not applicable

iterables = [factor_list, strategy_list, parameter_list, grouping_list]

axis_names = ['factor', 'method', 'param', 'grouping']

multi_index = pd.MultiIndex.from_product(iterables, names=axis_names)

column_list = ['a', 'b', 'c', 'd', 'e']

results = pd.DataFrame(np.arange(len(multi_index)*len(column_list)).reshape((len(multi_index),len(column_list))),
                       index=multi_index, columns=column_list)
results.sort_index(inplace=True)

rawDescription: assign values to dataframe defined by multiindex

description: Assign values to dataframe defined by multiindex


code:
import autopy

needle = autopy.bitmap.Bitmap.open('needle.png')

while True:
        haystack = autopy.bitmap.capture_screen()
        found = haystack.find_every_bitmap(needle)
        print(found)

rawDescription: Capture screen and find reference image

description: Capture screen and find reference image


code:
x = np.loadtxt('data', dtype={'names': ('time', 'magnitude'), 'formats': ('S12', 'f8')})
arr = np.char.split(x['time'], ':')
# http://stackoverflow.com/a/19459439/190597 (Jaime)
newarr = np.fromiter((tuple(row) for row in arr), dtype=[('', np.float)]*3,
                     count=len(arr)).view('float').reshape(-1, 3)
times = (newarr * [3600,60,1]).sum(axis=1)

y = np.empty_like(x, dtype={'names': ('time', 'magnitude'), 'formats': ('f8', 'f8')})
y['time'] = times
y['magnitude'] = x['magnitude']
print(y)

rawDescription: Parsing a data matrix containing HH:MM:SS.mmm times using numpy.loadtxt


code:
def listcomp_normal():
    l = [i*5 for i in range(100)]

def forloop_normal():
    l = []
    for i in range(100):
        l.append(i*5)

rawDescription: Why list comprehension can be faster than map() in Python?


rawDescription: How can I select a certain value based on 2(or more) other values in a pandas dataframe

description: Select a certain value based on 2(or more) other values in a pandas dataframe


code:
with open('spam.json') as f:
    for line in f:
        thing = json.loads(line)
        # blah blah

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
zipped = [...]
masked = [[num for num, b in zip(lst, mask) if b] for lst, mask in zipped]
print(masked)  # [[1, 1], [1, 1], [1, 1]]

rawDescription: python numpy get masked data without flattening

description: Python numpy get masked data without flattening


code:
for row, data in itertools.izip(reader, reader1):
    x, y = map(float, row[0:2])
    print [x,y, data]

rawDescription: Creating python list of floats from two files


code:
class MappingTestBase(unittest.TestCase):
    dictype = None
    # write all the tests using self.dictype

rawDescription: unittest tests reuse for family of classes

description: Unittest tests reuse for family of classes


code:
class DataSHAExtension(MapperExtension):
    def before_insert(self, mapper, connection, instance):
        instance.checksum = hashlib.sha1(instance.data).hexdigest()
    ...

rawDescription: Automatically add the SHA-1 checksum of a column as another column in a SQLAlchemy table


code:
from celery.signals import celeryd_after_setup

@celeryd_after_setup.connect
def add_dynamic_queue(sender, instance, **kwargs):
    # get the dynamic queue, maybe stored somewhere
    queue = 'dynamic_queue'
    instance.app.amqp.queues.select_add(queue)

rawDescription: Celery worker: How to consume from all queues?


code:
mutable_object = {}
fig = plt.figure()
def on_key(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    N=event.xdata
    mutable_object['key'] = N

rawDescription: how to return a value from button_press_event matplotlib?

description: Return a value from button_press_event matplotlib


code:
a = np.array([[1,2,3],[4,3,1]])
np.unravel_index(a.argsort(axis=None), dims=a.shape)

rawDescription: Getting the indices of the top k numbers by value in a numpy array?


code:
def wrapped_worker():
    worker()
    on_done()

rawDescription: Python threading on close callback

description: Python threading on close callback


code:
for key in yourdict:
   print(key)

rawDescription: Pick a key from a dictionary python

description: Pick a key from a dictionary python


code:
class Counter:

    def __init__(self, default_func=int):
        self.default = default_func

    def __getattr__(self, name):
        if name not in self.__dict__:
            self.__dict__[name] = self.default()
        return self.__dict__[name]

rawDescription: Python: Cleaner ways to initialize

description: Python: Cleaner ways to initialize


code:
container = {}
#inserting arbitrary amount of black people
container["black"] = 254
#inserting arbitrary amount of white people
container["white"] = getWhitePeople()
print(str(container["white"]))
#prints whatever getwhitePeople() returned
container.update(getPairNewCategory())
#getPairNewCategory() returns {nameOfTheCategoryStringOrHash:initialValueInt}
print(str(container[nameOfTheCategoryStringOrHash]))
#prints whatever was in initialValueInt

rawDescription: Changing variable names on the go, in Python


code:
import hashlib
s = 'something to hash'
hashlib.md5(s)
hashlib.md5(s).hexdigest()
hashlib.sha1(s).hexdigest()

rawDescription: Simple programming language with a md5/sha1 hash command?


code: sent = [' '.join(" ".join(v) for v in sent)]

rawDescription: Python - Remove Braces and Commas from a Tuple CSV File


code:
import urlparse
url = "https://website.com/donate?utm_source=site&utm_medium=email&utm_campaign=campaign1&uuid=999124&lang=en"
parsed_url = urlparse.urlparse(url)
parsed_url
parsed_url.query

rawDescription: Trying to find all unique values in specific part of string in Python


code:
epoch = datetime.datetime(1960, 1, 1)
# cast -s- to python int in case it's a string or a numpy.int
df['datetime'] = df['sastime'].apply(
    lambda s: epoch + datetime.timedelta(seconds=int(s))
)

rawDescription: Convert SAS numeric to python datetime

description: Convert SAS numeric to python datetime


rawDescription: Is there a way to mod a number so that it's in the range between -1 and 1?


code:
import itertools
mydict = {'item1':[1,2,3],'item2':[10,20,30]}
list(itertools.product(*mydict.values()))

rawDescription: Loop for each item in a list

description: Loop for each item in a list


rawDescription: Conditionally merge lists

description: Conditionally merge lists


code:
import pickle

with open("top_scores.pickle", "wb") as scores:
    pickle.dump(top_scores, scores)

rawDescription: Saving data in pickle

description: Saving data in pickle


code: mylist = chunkFromFile.split(b'\x00')

rawDescription: Python 3 null terminated string to list?

description: Python 3 null terminated string to list


code: name = in_string.split(',', 1)[0]    # => "Mary"

rawDescription: Indexing lines of text in a .txt file

description: Indexing lines of text in a .txt file


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-r", type=int, default=1, metavar='ROWS')
parser.add_argument("-c", type=int, default=2, metavar='COLUMNS')
args = parser.parse_args()

rawDescription: Python Argparse Adding Text To Usage Message


code:
from sklearn.metrics import mean_squared_error

mean_squared_error(y, predictions)

rawDescription: Plot sklearn RandomForestRegressor MSE

description: Plot sklearn RandomForestRegressor MSE


code:
print(x.__class__)
# __main__.Member

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


rawDescription: Face recognition in OpenCV Python FAR/FRR


code:
from collections import Counter

acount = Counter(a)
bcount = Counter(b)
result = list((acount - bcount).elements())

rawDescription: Remove elements of one list from another, while keeping duplicates


code: number = tree.xpath('//span[@class="number"]/text() | //div[@class="dddd13"]/span/text()')

rawDescription: Python : lxml xpath get two different classes


code:
def method3(request):
    logins = Login.objects.filter(
        person__in=Person.objects.all(),
        login_date__gt=date.today() - timedelta(days=90)
    ).order_by('person', 'login_date').select_related()
    return render_to_response('template.htm', {'logins': logins})

rawDescription: Python Django: in view is it better to add properties to an object or make a dictionary of the data?


code:
@view_config(route_name="info_ajax",renderer="json")
def info_ajax(self):

    #for the sake of this example, lets just return the information from the mouse click event

    A = self.request.POST.get('ajax_id')    #is the id of the mouse click event
    B = self.request.POST.get('ajax_name')   #is the name of the mouse click event

    return {
                'ID' : A,
                'Name' : B,
        }

rawDescription: Pyramid json view ajax call

description: Pyramid json view ajax call


code:
if len(strresult) > 16:
    dosomething

rawDescription: Get array count of specific document in Pymongo


code:
import ast
l = "['Hello', 'my', 'name', 'is', 'Apple']"
l1 = ast.literal_eval(l)

rawDescription: How to turn a string into a list in python?

description: Turn a string into a list in python


code:
def run_folder_chooser_dialog():
    result= []

    def run_dialog(_None):
        dialog = Gtk.FileChooserDialog("Please choose a folder", None,
        Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
            "Select", Gtk.ResponseType.OK))

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            result.append(dialog.get_filename())
        else:
            result.append(None)

        dialog.destroy()
        Gtk.main_quit()

    Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
    Gtk.main()
    return result[0]

rawDescription: Proper way to destroy a file chooser dialog in pygtk for python


rawDescription: what is a good way of setting up ranges on a number line?

description: What is a good way of setting up ranges on a number line


rawDescription: Structuring a fabric project with namespaces


code:
#!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals

import demo
import pi3d
import random
import numpy as np
from PIL import Image, ImageDraw
DISPLAY = pi3d.Display.create(x=150, y=150)
shader = pi3d.Shader("uv_flat")
im = Image.open("textures/PATRN.PNG")
#draw = ImageDraw.Draw(im) # there are various PIL libraries you could use
nparr = np.array(im)
tex = pi3d.Texture(im) # can pass PIL.Image rather than path as string
sprite = pi3d.ImageSprite(tex, shader, w=10.0, h=10.0)
mykeys = pi3d.Keyboard()
while DISPLAY.loop_running():
  #draw.line((random.randint(0,im.size[0]),
  #           random.randint(0,im.size[1]),
  #           random.randint(0,im.size[0]),
  #           random.randint(0,im.size[1])), fill=128) # draw random lines
  #nparr = np.array(im)
  nparr += np.random.randint(-2, 2, nparr.shape) # random noise
  tex.image = nparr
  tex._load_opengl()
  sprite.draw()
  if mykeys.read() == 27:
    mykeys.close()
    DISPLAY.destroy()
    break

rawDescription: Numpy (OpenCV) image array to OpenGL texture (pi3d)


code:
search = request.GET.get('search')
page = request.GET.get('page')

rawDescription: How to have multiple get params in an URL?

description: Have multiple get params in an URL


code:
main.py
import argparse
import xyz

parser = argparse.ArgumentParser(
    description="My program",
    parents=[xyz.parser("xyz1"), xyz.parser("xyz2")])
parser.add_argument("-s", "--sky")
parser.parse_args(["--help"])

rawDescription: How to specify multiple instances of same type of parent parser in argparse

description: Specify multiple instances of same type of parent parser in argparse


code:
with open('Input_Domains.txt','r') as f:
    full_spf=""
    for line in f:
        full_spf+=getspf(line.strip())+"\n"

rawDescription: Issue in Writing the contents of a variable to a file


rawDescription: NumPy: Execute function over each ndarray element


code:
def sign(p1, p2, p3): #all Points
    return (p1.getX() - p3.getX()) * (p2.getY() - p3.getY()) - (p2.getX() - p3.getX()) * (p1.getY() - p3.getY())

def inTriangle(pt, v1, v2, v3): #all Points, pt = mouse, v = triangle vertex
    b1 = sign(pt, v1, v2) < 0.0
    b2 = sign(pt, v2, v3) < 0.0
    b3 = sign(pt, v3, v1) < 0.0
    return ((b1 == b2) and (b2 == b3))

rawDescription: Verifying Mouse Position Within Triangle - Python


code:
fig.x_range = Range1d(x.max() - window_length, x.max())
push_notebook()

rawDescription: Set x_axis_limit in Bokeh live plot embedded in Jupyter notebook


rawDescription: How multiarray.correlate2(a, v, mode) is actually implemented?


code:
import re

text = '''
Dear Customer,

This notice serves as proof of delivery for the shipment listed below.

Weight:

18.00 lbs

Shipped/Billed On:

09/11/2015

Delivered On:

09/14/2015 11:07 A.M.

Signed By:

Odedra

Left At:

Office

Thank you for giving us this opportunity to serve you.
'''

re.findall(r'
Delivered On:<\/label><\/dt>
([0-9\.\/\s:APM]+)', text)

rawDescription: how to take date value from string in python?

description: Take date value from string in python


code:
class wait_for_text_not_to_end_with(object):
    def __init__(self, locator, text):
        self.locator = locator
        self.text = text

    def __call__(self, driver):
        try :
            element_text = EC._find_element(driver, self.locator).text.strip()
            return not element_text.endswith(self.text)
        except StaleElementReferenceException:
            return False

rawDescription: Executing a script in selenium python

description: Executing a script in selenium python


code:
x = json.dumps({'1': 2, '3': 4}, ensure_ascii=True, sort_keys=True)
y = json.loads(x)
print(y)
print(y['3']+1)

rawDescription: JSON data recognized as a string field instead of integer


code:
exponential_kernel = lambda x, y, params: params[0] * \
    np.exp( -0.5 * params[1] * np.sum((x - y)**2) )

rawDescription: Gaussian Process scikit-learn - Exception


code: import artman_pkg.util as util

rawDescription: How do unit tests import the modules they test?


code: b = [el[0] for el in a]

rawDescription: Get the nth element from the inner list of a list of lists in Python


code: df['Col3'] = (df['Col2'] <= 1).astype(int)

rawDescription: Add new column in Pandas DataFrame Python


code:
def foo(x):
    print('*** foo(%s)' % x)
    return x

rawDescription: Most efficient way to recode these multiple if statements


code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
import os

msg = MIMEMultipart()
msg['From'] = 'FakeEmail@hotmail.com'
msg['To'] = 'FakeEmail@hotmail.com'
msg['Subject'] = 'simple hotmail email'
message = os.environ['USERNAME']
#message = os.path.expandvars('%USERNAME%') # alternative
msg.attach(MIMEText(message))

rawDescription: Calling Upon An Enviromental Variable in a Path


code:
from inspect import getmro
[st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]

['This is ClassA or a subclass']

rawDescription: What's the best way to find the closest matching type to an existing type?


code:
import numpy

def find_max_index(xs):
    candidates = [((i,numpy.argmax(x))) for i, x in enumerate(xs)]
    return max(candidates, key=lambda pos: xs[pos[0]][pos[1]])

rawDescription: Index of max element from two lists

description: Index of max element from two lists


code:
def handle(self, *args, **options):
    for arg in args:
        try:
            first_name, last_name = arg.split('.')
        except ValueError:
            first_name, last_name = arg, None

        info = DEF(first_name, last_name)

rawDescription: Two arguments in django-admin custom command


code:
...
total_level_width = len(level[0])*32
total_level_height = len(level)*32

# Create Groups
camera = Camera(complex_camera, total_level_width, total_level_height)
shipGroup = CameraGroup(camera)
backgroundGroup = CameraGroup(camera)

# build the level
for row in level:
   ...
...

rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
class Terminator(BoxLayout):
    def DelButton(self):
        for child in self.children:
            self.remove_widget(child) # this will leave one child

rawDescription: kivy access child id

description: Kivy access child id


rawDescription: Class based directional indicator

description: Class based directional indicator


code:
group_ids = np.digitize(pos[:,2], limits)
datasets = [pos[group_ids == k,2] for k in range(1, len(limits))]

rawDescription: Python for & if loop not working?

description: Python for & if loop not working


code:
from kivy.app import App
from kivy.uix.label import Label

class MyLabel(Label): pass
class AwesomeApp(App):
    def build(self):
        return MyLabel()

if __name__ == "__main__":
    AwesomeApp().run()

rawDescription: Python not finding kv file

description: Python not finding kv file


code: a = b == c

rawDescription: What is the purpose of the '==' operator when comparing values vs '='?


code: p = subprocess.Popen(['myjavaapp', os.path.abspath('afilename.txt')])

rawDescription: Related to executing Java programs through Python


code: [x + y if chr(x).isalpha() else x for x, y in zip(msglist, keylist)]

rawDescription: Vigenere Cipher List Processing

description: Vigenere Cipher List Processing


code: system_path = settings.MEDIA_ROOT + s

rawDescription: View function is not being called in Django


code:
#!/usr/bin/env python3
from contextlib import ExitStack
from functools import partial

print("counting")
with ExitStack() as stack:
    for i in range(10):
        a = i
        stack.callback(partial(print, a, i))

    x = 42
    a = x
    print("done")

rawDescription: Python equivalent of golang's defer statement


code:
pl.imshow(im)
pl.gca().autoscale(False)
minX = np.where(green[:, 0] == green[:, 0].min())
maxX = np.where(green[:, 0] == green[:, 0].max())
minY = np.where(green[:, 1] == green[:, 1].min())
maxY = np.where(green[:, 1] == green[:, 1].max())
pl.plot(green[minX, 0], green[minX, 1], 'ro')
pl.plot(green[maxX, 0], green[maxX, 1], 'go')
pl.plot(green[minY, 0], green[minY, 1], 'bo')
pl.plot(green[maxY, 0], green[maxY, 1], 'yo')

rawDescription: detect 4 interesting pixels

description: Detect 4 interesting pixels


code:
def lenRecur(s):

    # ...

    def leng(s):
        if len(s)==0:
            return leng.count
        else:
            leng.count += 1
            return lenIter(s[1:])

    leng.count = 0

rawDescription: Global variables in recursion. Python

description: Global variables in recursion. Python


code:
import math

print(math.inf)
print(-math.inf)
print(math.nan)

rawDescription: Why aren't Inf, -Inf and NaN keywords in Python?


code:
m = df.apply(lambda x: Series(1,index=np.arange(x['created'].hour,x['closed'].hour+1)),axis=1).fillna(0)
m

rawDescription: pandas DataFrame - Getting hours in a Duration

description: Pandas DataFrame - Getting hours in a Duration


code:
first_list = [1,2,3,10]
second_list = [10,20,30,50]
special = {2, 3}
[first_list[i]+second_list[i] for i in range(len(first_list)) if first_list[i] not in special]

rawDescription: How to exempt a list item from iteration?

description: Exempt a list item from iteration


code:
df = pd.DataFrame({"cid": np.arange(64)//8, "price": np.arange(64)})
df["num"] = df.groupby("cid")["price"].cumcount() + 1
pivoted = df.pivot(index="cid", columns="num", values="price")
pivoted.columns = "price" + pivoted.columns.astype(str)
pivoted = pivoted.reset_index()

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


rawDescription: simple python list comprehension question

description: Simple python list comprehension question


code: thread = MyThread()

rawDescription: How to make mechanize script multthread in python

description: Make mechanize script multthread in python


rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
import pickle, hashlib, sys
if len(sys.argv) < 3:
    raise ValueError('Need two parameters, username and password')

def Encryption(data):
    return hashlib.sha224(data).hexdigest()

with open('database.db', 'rb') as fh:
    db = pickle.load(fh)

db[sys.argv[1]] = Encryption(sys.argv[2])

with open('database.db', 'wb') as fh:
    pickle.dump(db, fh)

rawDescription: Password Protection Python

description: Password Protection Python


code:
start = time.time()
subprocess.check_output(cmd, shell=True)
assert (time.time() - start) > 2

rawDescription: Python subprocess .check_call vs .check_output


code:
for x in lis:
    ops1.get(str(x), print)()

rawDescription: Python, run functions from lookup table

description: Python, run functions from lookup table


code:
from formencode import Schema, validators

class RegistrationForm(Schema):
    email = validators.Email(not_empty=True, strip=True)
    password = validators.UnicodeString(not_empty=True)
    password_confirm = validators.UnicodeString()
    chained_validators = [validators.FieldsMatch(
                    'password', 'password_confirm',
                    messages=dict(invalidNoMatch=u'Password does not match'))]

rawDescription: Determining if a simple_form object has been submitted yet


code:
def get_sparse(DATA, PORTION):
    x = np.unique(itertools.chain(*DATA) )
    A = np.zeros((len(DATA), max(x)+1))
    for a, d, p in zip(A, DATA, PORTION):
        a[d] = p
    return A[:,x]

rawDescription: How to avoid loops for sparse Matrix?

description: Avoid loops for sparse Matrix


code:
def wpad(A, begin_at, length):
    to_pad = max(length + begin_at - len(A), 0)
    return np.pad(A, (0, to_pad), mode='wrap')[begin_at:begin_at+length]

rawDescription: Extract a larger slice than the numpy array's size


code:
import contextlib
with contextlib.nested(open("a.txt"), open("b.txt")) as (a, b):
    do_many_amazing_things(a,b)

rawDescription: Multiple context `with` statement in Python 2.6


code:
with open("records.tsv", "w") as record_file:
    record_file.write("Record_Id    Record_Seq    Record_Qal\n")
    for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
        record_file.write(str(record.id)+"  "+str(record.seq)+"  "+ str(record.format("qual"))+"\n")

rawDescription: How to save output from python like tsv

description: Save output from python like tsv


code:
pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

rawDescription: How can I iterate multiple key from a dictionary in Django template

description: Iterate multiple key from a dictionary in Django template


code:
ub_tries = 20
tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
tries_dict.get(1, 'next')
tries_dict.get(4, 'next')
tries_dict.get(5, 'next')
tries_dict.get(20, 'next')
tries_dict.get(21, 'next')

rawDescription: use a range as a dictionary key in Python, what option do I have?

description: Use a range as a dictionary key in Python, what option do I have


rawDescription: Use multiple functions at once on a list


code:
class Name(object):
    def __get__(self, instance, owner):
        return self._name

    def __set__(self, instance, name):
        if not isinstance(name, basestring):
            raise ValueError('Name must be a string')
        self._name = name

class Human(object):
    name = Name()

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

rawDescription: Setting class attributes of the proper type


code:
table = plan1.find('table', id = 'planComparison')
pcp = table.find('td',text=' Doctor Visit - Primary Care ')
print(pcp.nextSibling.nextSibling.text)

rawDescription: Pull adjacent table cell using BeautifulSoup Python


code: fig = plt.gcf()

rawDescription: On handling the layout of subfigures

description: On handling the layout of subfigures


code: Potatoes

rawDescription: What's the opposite of \b character, i.e. a kind of non-erasing space?


code:
import email

original = email.message_from_string( ... )

for part in original.walk():
    if (part.get('Content-Disposition')
        and part.get('Content-Disposition').startswith("attachment")):

        part.set_type("text/plain")
        part.set_payload("Attachment removed: %s (%s, %d bytes)"
                         %(part.get_filename(),
                           part.get_content_type(),
                           len(part.get_payload(decode=True))))
        del part["Content-Disposition"]
        del part["Content-Transfer-Encoding"]

rawDescription: How do I reply to an email using the Python imaplib and include the original message?

description: Reply to an email using the Python imaplib and include the original message


code:
file_count_string = StringVar()
counter = Label(textvariable=file_count_string)
counter.pack()
file_count_string.set("Input Directory: " + str(file_count) + " files.")

rawDescription: Python: 'Refresh' specific variables within a script


code: longframe

rawDescription: How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores?

description: Convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores


code:
df.TIMESTAMP = pd.to_datetime(df.TIMESTAMP, unit='s')
df.set_index('TIMESTAMP', inplace=True)
df

rawDescription: How do you convert time series data with pandas and show graph via highstock

description: Convert time series data with pandas and show graph via highstock


code:
p = pd.Panel(d)
p.swapaxes()

rawDescription: create Panel at Pandas by multi-level dictionary

description: Create Panel at Pandas by multi-level dictionary


code: df['B'] = df.resample('s', how='ffill').tshift(5, freq='s').reindex_like(df)

rawDescription: Python Pandas value-dependent column creation


rawDescription: python re: match everything but a double linebreak

description: Python re: match everything but a double linebreak


code:
panel = wx.Panel(self, wx.ID_ANY, style= wx.WANTS_CHARS)
panel.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)

rawDescription: Why does wxPython panel masks key down event?


code:
pool=Pool()
results = []
for x in (1,2):
    r = pool.apply_async(myfunc, (x,), callback=mycallback)
    results.append(r)
for r in results:
    r.wait()

rawDescription: how does the callback function work in python multiprocessing map_async

description: How does the callback function work in python multiprocessing map_async


rawDescription: Sort datetime in double array list

description: Sort datetime in double array list


code:
i = b"\xd9\x88"
print(i.decode('utf-8'))

rawDescription: representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python

description: Representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python


code:
names = iter([1,2,3])
print(next(names))
print(next(names))
print(next(names))
1
2
3

rawDescription: Python function that rotates files per call


rawDescription: Adding zero in front of a character in Python


code:
from collections import Counter
new_list = []
for country, values in new_res.items():
    # elements are stored as dictionary keys and their counts are stored as dictionary values
    merge_values = Counter(values)

    # calculate percentage
    new_values = []
    total = sum(merge_values.values())
    for server_name, num in merge_values.items():
        #ex: Server1-40.0
        new_values.append("{0}-{1:.1f}".format(server_name, num*100/total))

    percent = merge_values["Server1"]*1.0*100/total

    new_list.append({"country": country,
                     "percent": percent,
                     "values": new_values})

rawDescription: How to carry out this aggregation in python

description: Carry out this aggregation in python


code:
string1 = string1[:2] + 'bb' + string1[2:]
string1
string2

rawDescription: Python: place a characters in string

description: Python: place a characters in string


code:
pairs = {}

for key in pairs1.keys():
    pairs[key] = pairs[key]

for key in pairs2.keys():
    try:
        pairs[key] = pairs[key] + pairs2[key]
    except KeyError:
        pairs[key] = pairs2[key]

for key in pairs3.keys():
    try:
        pairs[key] = pairs[key] + pairs3[key]
    except KeyError:
        pairs[key] = pairs3[key]

rawDescription: Matrix creation

description: Matrix creation


code:
def copyAndPaste(picture):
  height = getHeight(picture)
  width = getWidth(picture)
  newPicture = makeEmptyPicture(width+100, height+100)
  for x in range(width):
    for y in range(height):
      pxl = getPixel(picture,x,y)
      color = getColor(pxl)
      if (x>48 and x<59) and (y>58 and y<71):
        newPxl =getPixel(newPicture, x+100,y+100)
        setColor(newPxl,color)
      newPxl = getPixel(newPicture, x,y)
      setColor(newPxl,color)

rawDescription: Scaling Part of a Picture

description: Scaling Part of a Picture


code: from LDconfig import LDconfig

rawDescription: Creating a file to lookup paths and file names?


code:
class A(object): pass

class B(A): pass

a, b = A(), B()
type(a)
type(a) == A
type(b)
type(b) == B
type(b) == A

rawDescription: Recursively dump an object

description: Recursively dump an object


rawDescription: Converting a number in exponential form to decimal form in python


code:
import my_class

ca = my_class.MyClassA()

rawDescription: Importing an own python file, Class not defined


code:
Name,Time,Change
x_change,6,1
x_change,2,1
x_change,5,2

rawDescription: Pass list of different named tuples to different csv by tuple name


rawDescription: Python: str.split() - is it possible to only specify the "limit" parameter?


code: sum([word_count_dict["Britain"][file] if file in word_count_dict else 0 for file in ["74.txt", "75.txt"]])

rawDescription: how to find frequency of the keys in a dictionary across multiple text files?

description: Find frequency of the keys in a dictionary across multiple text files


code:
import matplotlib as mpl

grey = '#808080'

mpl.rcParams['axes.linewidth'] = 0.3
mpl.rcParams['axes.edgecolor'] = grey
mpl.rcParams['xtick.color'] = grey
mpl.rcParams['ytick.color'] = grey
mpl.rcParams['axes.labelcolor'] = "black"

rawDescription: Set tick egde color in matplotlib rc

description: Set tick egde color in matplotlib rc


rawDescription: plotting a range of data that satisfies conditions in another column in matplotlib python

description: Plotting a range of data that satisfies conditions in another column in matplotlib python


code:
splitmaptime = timeit.timeit("hours,minutes = map(int, s.split(':')); mins=hours*60 + minutes", "s='02:40'", number=100000)/100000
splitmaptime
splitmaptime/parsetime

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code: type(a)

rawDescription: Overflowing ints in python

description: Overflowing ints in python