code:
from collections import defaultdict
from gc import get_objects
before = defaultdict(int)
after = defaultdict(int)
for i in get_objects():
    before[type(i)] += 1

rawDescription: Python - Working around memory leaks

description: Python - Working around memory leaks


code:
class Z(object):
    def __getattribute__(self, name):
            return "ham"

z = Z()
z.__class__
type(z)

rawDescription: Python type() or __class__, == or is

description: Python type() or __class__, == or is


code:
session = web.session.Session(app,web.session.DiskStore('sessions'), initializer={'message': ""})
render = web.template.render('templates/', globals={'context': session}, base='layout')

rawDescription: How to transfer message between different request in web.py?

description: Transfer message between different request in web.py


code: fL

rawDescription: Given an iterable, how to apply a function in every possible combination?


rawDescription: python: how to interrupt a regex match

description: Python: how to interrupt a regex match


code:
migrations = {}

def migrate(old_version, new_version):
    assert abs(new_version-old_version)==1

    def decorator(f):
        direction = 'up' if new_version > old_version else 'down'
        if old_version not in migrations:
            migrations[old_version] = {}
        migrations[old_version][direction] = f
        return f
    return decorator

@migrate(1, 2)
def upgrade():
    pass  # migration script here

@migrate(2, 1)
def downgrade():
    pass  # migration script here

@migrate(2, 3)
def upgrade():
    pass  # migration script here
# etc

print(migrations)

rawDescription: How to create a dict of functions in Python?

description: Create a dict of functions in Python


code:
from itertools import izip_longest
def blockwise(t, size=2, fillvalue=None):
    it = iter(t)
    return izip_longest(*[it]*size, fillvalue=fillvalue)

rawDescription: Pairs from single list

description: Pairs from single list


code:
label = pyglet.text.Label("Hello World!",
                            color=(255,255,255,255),
                            font_size=36,
                            x=window.width//2, y=window.height//2,
                            anchor_x="center", anchor_y="center")

rawDescription: Pyglet hello world example doesn't show label until a key is pressed


code: d

rawDescription: Averaging column 2D array python

description: Averaging column 2D array python


code:
import httplib
conn = httplib.HTTPConnection('www.google.com')
conn.send('GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n')
conn._HTTPConnection__state = httplib._CS_REQ_SENT
response = conn.getresponse()

rawDescription: Python send packet over 443

description: Python send packet over 443


code: sorted(str1) == sorted(str2)

rawDescription: How can I check if a string has the same characters? Python

description: Check if a string has the same characters? Python


code: myfield = forms.CharField()

rawDescription: When to use a django form and when to use a html one?


code:
def intersect(lists):
    return list(set.intersection(*map(set, lists)))

rawDescription: Intersection of variable number of lists


code:
import x
x.connect('url')

rawDescription: How do I marshal a pointer to a cstring between Python and C via SWIG

description: Marshal a pointer to a cstring between Python and C via SWIG


code:
class SharedTest(TestCase):
    def setUp(self):
        self.do_not_run = True

    def test_foo(self):
        if getattr(self, 'do_not_run', False):
            return
        # Rest of the test body.

class OneTestCase(SharedTest):
    def setUp(self):
        super(OneTestCase, self).setUp()
        self.do_not_run = False

rawDescription: How can I add a test method to a group of Django TestCase-derived classes?

description: Add a test method to a group of Django TestCase-derived classes


rawDescription: python variable contains three lists not one

description: Python variable contains three lists not one


code: '[contains(concat(" ", normalize-space(@class), " "), " btn-success ")]'

rawDescription: how to dynamically read a specific cell value in a table using selenium and python

description: Dynamically read a specific cell value in a table using selenium and python


code: [sum(x) for x in zip(*my_dict.values())[1:]]

rawDescription: Best way to reduce dictionary of lists

description: Reduce dictionary of lists


code:
words = { "apple" }
def isOK( fragment, letter ):
    word = fragment + letter
    if len( word ) <= 3: return True
    return word not in words and any( w.startswith( word ) for w in words )
isOK( "a", "p" )
isOK( "ap", "p" )
isOK( "app", "l" )
isOK( "appl", "l" )
isOK( "appl", "e" )

rawDescription: Python Logic Help:

description: Python Logic Help:


code:
from sympy import *
def inv_logit(p):
    return exp(p) / (1 + exp(p))
def logit(p):
    return log(p)- log(1 -p)

x=Symbol('x')
expr=logit(inv_logit(x))
# expr is now:
# -log(1 - exp(x)/(1 + exp(x))) + log(exp(x)/(1 + exp(x)))
# rewrite it: (there are many other ways to do this. read the doc)
# you may want to make an expansion (of some suitable kind) instead.
expr=cancel(powsimp(expr)).expand()
# it is now 'x'

# just evaluate any expression like this:
result=expr.subs(x,123.231)

# result is now an equation containing: 123.231
# to get the float:
result.evalf()

rawDescription: logit and inverse logit functions for extreme values

description: Logit and inverse logit functions for extreme values


code: answer = t_sec + (t_nsec / 10**9)

rawDescription: Optimize conversion to decimal representation


code: itertools.imap(lambda x,y: x+y, itertools.repeat(x), y)

rawDescription: map lambda x,y with a constant x

description: Map lambda x,y with a constant x


code:
from itertools import chain
list(chain.from_iterable(node.sons.values() for node in current_nodes))

rawDescription: How to propagate tree nodes in Python

description: Propagate tree nodes in Python


rawDescription: Mean value by equality of rows

description: Mean value by equality of rows


code:
i = 1523
total = 0
while i <= 10503:
    total += i
    i += 2
print (total)

total = 0
for i in range (1523, 10504, 2):
    total += i
print (total)

rawDescription: python while loop and for loop

description: Python while loop and for loop


code:
h,b = skin.shape[:2]

for i in xrange(h):
    for j in xrange(b):
        if bw_image[i][j] > threshold:
            new_image[i][j] = 255 #Setting the skin tone to be White
        else:
            new_image[i][j] = 0 #else setting it to zero.

rawDescription: Trying to convert HSV image to Black and white [opencv]


code:
class TestAdmin(admin.ModelAdmin):
    def get_inline_instances(self, request, obj=None):
        if obj.id > 3:
            self.inlines = [TestInfoInline, ]
        else:
            self.inlines = []
        return super(TestAdmin, self).get_inline_instances(request, obj)

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

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


code:
G = nx.Graph()
G.add_path([0,1,2])
spaths = nx.all_pairs_shortest_path(G)
spaths

rawDescription: Python: how to compute the number of shortest paths passing through one node?


code:
import difflib
difflib.SequenceMatcher(None,'no information available','n0 inf0rmation available').ratio()

rawDescription: Can I do a "string contains X" with a percentage accuracy in python?

description: Do a "string contains X" with a percentage accuracy in python


code:
def concat_app(b0,b1,r0,g0,r1,g1):
    out = np.zeros((size,8),dtype=b0.dtype)
    out[:,2:] = np.concatenate((b0,b1,r0,g0,r1,g1)).reshape(-1,size)[:,::-1].T
    return out.ravel().tolist()

def org_app(b0,b1,r0,g0,r1,g1):
    data_bin = []
    counter = 0
    for x in range(size):
        counter += 1
        data_bin.insert(0, 0)
        data_bin.insert(1, 0)
        data_bin.insert(2, b0[x])
        data_bin.insert(3, b1[x])
        data_bin.insert(4, r0[x])
        data_bin.insert(5, g0[x])
        data_bin.insert(6, r1[x])
        data_bin.insert(7, g1[x])
    return data_bin

rawDescription: sort multible numpy arrays into one like: [1,2,..n, 1,2..n]

description: Sort multible numpy arrays into one like: [1,2,..n, 1,2..n]


code:
env.sphinx_path = {
    'hosta': 'patha',
    'hostb': 'pathb',
}

@task
@hosts('hosta','hostb')
def foo(dummy_var):
    put('sphinx_stuff', env.sphinx_path%env.host)

rawDescription: Fabric: Set configuration variables per-host outside task


code:
from operator import itemgetter
sorted(m, key=itemgetter(2), reverse=True)[:3]

rawDescription: top 5 or N lists from nested lists "using one of the element" from nested list (little bit complex)

description: Top 5 or N lists from nested lists "using one of the element" from nested list (little bit complex)


code:
w, h = freqz(b, a, worN=n)
f = fs * w / (2*np.pi)

rawDescription: Matlab freqz function in Python

description: Matlab freqz function in Python


code:
inputs = {input1, input2}
found = None
for i, combo in enumerate(combinations(items, 2)):
    if set(combo) == inputs:
        found = i
        break

rawDescription: Comparing Permutation and Combinations

description: Comparing Permutation and Combinations


code:
from django.db.models import F
Model.objects.values('Date').distinct().annotate(name=F('Name'), status=F('Status'))

rawDescription: List per Date python

description: List per Date python


code: df

rawDescription: List Comprehension Loop

description: List Comprehension Loop


code:
r = re.compile(r'^(\s*)', re.MULTILINE)
def prettify_2space(s, encoding=None, formatter="minimal"):
    return r.sub(r'\1\1', s.prettify(encoding, formatter))

rawDescription: Custom indent width for BeautifulSoup .prettify()


code:
import keyword
keyword.iskeyword('break')
keyword.kwlist

rawDescription: Is the list of Python reserved words and builtins available in a library?


code:
import subprocess
cmd = [r'c:\python27\python.exe', 'main27.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

rawDescription: Python: How to import 2.7 module into 3.4 program?


rawDescription: Altering the Last Byte of a String

description: Altering the Last Byte of a String


code:
import struct
val # Generated using  binascii.unhexlify
struct.unpack_from('<H', val, 10)
struct.unpack_from('<H', val, 10)[0]

rawDescription: How to extract and change a sequence of bytes from a serial packet to the correct integer representation in python?

description: Extract and change a sequence of bytes from a serial packet to the correct integer representation in python


code:
from os import path, rename
from glob import glob

pth = 'C:/Users/acars/Desktop/b'
src_files = os.listdir(pth)

for file_name in src_files:
    new = file_name.split("_", 1)[1]
    file_name = path.join(pth, file_name)
    rename(file_name, path.join(pth, new))

rawDescription: Python Renaming Multiple Files in Directory


code:
import re
test = "This is foo."
any(word in d for word in re.findall("[A-Za-z0-9]+", test))

rawDescription: Python regex for something *not* in a dictionary?


code:
class Parent(object, metaclass=DecoMeta):
    ...

rawDescription: Inheritable Tracking Decorator

description: Inheritable Tracking Decorator


code: player = {"attack": lambda: random.randint(2, 4), "health": 50}

rawDescription: I want to turn the string "random.randint(2,4), into an integer


code: invert_dict = {v: k for k, v in orig_dict.items()}

rawDescription: Python printing single key/value pairs from a dict


code:
import struct
import numpy as np # for random string of ones and zeros

def chunks(s):
    for i in xrange(0, len(s), 32):
         yield s[i:i+32]

s =  ''.join(str(np.random.randint(2)) for x in xrange(32*2))
ints = (int(x, 2) for x in chunks(s)) # convert string from binary repr to integers
bins = (struct.pack('I', i) for i in ints) # pack to unsigned ints

rawDescription: Python write string "1001101" as binary stream to file


code: 'text1 foo bar text2 foobar baz'

rawDescription: How to grab item outside of tag using python+beautifulsoup

description: Grab item outside of tag using python+beautifulsoup


code:
class MyClass():
   @staticmethod
   def my_func():
       pass

   class_variable = my_func.__func__()

rawDescription: Assign Python class variable with a method of that class


code:
df = DataFrame(randn(10,2),columns=list('ab'),index=date_range('20130101 9:00',freq='T',periods=10))
df
df.index
df.append(Series(name=[Timestamp('20130101 09:15')]))
df.append(Series(name=[Timestamp('20130101 09:15')])).index
df.append(Series(name=[Timestamp('20130101 09:15')])).asfreq('T')
df.append(Series(name=[Timestamp('20130101 09:15')])).asfreq('T').index

rawDescription: Calculating averages of 15 records ahead of the current record as a new column


rawDescription: Tokenizing User Input in Python

description: Tokenizing User Input in Python


code: WelCome

rawDescription: List Slicing in Python 2

description: List Slicing in Python 2


code:
import pandas as pd
def front(self, n):
    return self.iloc[:, :n]

def back(self, n):
    return self.iloc[:, -n:]

pd.DataFrame.front = front
pd.DataFrame.back = back

df = pd.DataFrame(np.random.randint(10, size=(4,10)))

rawDescription: Is there a pandas function to display the first/last n columns, as in .head() & .tail()?


code:
import sys
import os

assert os.path.isfile(sys.argv[1])

with open(sys.argv[1]) as filelist:
    filenames = [line.strip() for line in filelist]
    for filename in filenames:
        if not os.path.isfile(filename):
            print >> sys.stderr , "{0} is not a valid file".format(filename)
            break
        with open(filename,'r') as f:
            for line in f:
                #do something
                pass

rawDescription: calling python script that requires an input from within bash for loop

description: Calling python script that requires an input from within bash for loop


code: s = "xxxxxxxx-abcdxxxxxxxxx"

rawDescription: How to extract 4 characters after '-' in a hostname

description: Extract 4 characters after '-' in a hostname


code:
for a in range(2):
  rules[a] = lambda t,a=a: a

rawDescription: Python for loop initialization of reference to function


code:
import requests
import pandas as pd
import bs4
import string
import matplotlib.pyplot as plt
url = "https://www.revisor.mn.gov/laws/?year=2014&type=0&doctype=Chapter&id=294"

result = requests.get(url)
soup = bs4.BeautifulSoup(result.content)
summary = soup.find("div", {"class":"bill_section","id": "laws.1.1.0"})
tables = summary.findAll('table')
data_table = tables[1]

Source, Amount = [], []
for row in data_table.findAll("tr"):
    cells = row.findAll("td")
    try :
        for char in cells[0].findAll("ins"):
             Source.append(char.text)   #This is where the issue is
        for char in cells[2].findAll("ins"):
             Amount.append(char.text)   #And here
    except:
        pass

rawDescription: Python 3.x - Create dataframe and specify column names


code:
from django.db import models
from model_utils import Choices
awesome_choices=('Choice 1', 'Choice 2',)
class SomeAwesomeModel(models.Model):
    myfield=models.CharField(max_length=255)
    field_not_in_front_end=models.Charfield(max_length=255, choices=Choices(*awesome_choices))

rawDescription: Multiselect dropdown/list in django admin panel only


code:
#custom.loaders.py
from os.path import join
from django.conf import settings
from django.template import TemplateDoesNotExist
from path.to.middleware import get_current_request

def load_template_source(template_name, template_dirs=None):
    request = get_current_request()
    host = request.get_host()
    path_to_template_dir = None
    for site in settings.SITE_TEMPLATE_FOLDERS:
        if site[0] == host:
            path_to_template_dir = site[1]
            break

    if path_to_template_dir:
        try:
            filepath = join(path_to_template_dir, template_name)
            file = open(filepath)
            try:
                return (file.read(), filepath)
            finally:
                file.close()
        except IOError:
                pass

    raise TemplateDoesNotExist(template_name)

rawDescription: Dynamically serve static content based on server name in Django


code: re.findall(r'"([^"]*)"', inputString)

rawDescription: Extract a string between double quotes

description: Extract a string between double quotes


code:
from functools import partial

[...]

for letter in self.letters:
    btn = QtWidgets.QRadioButton(letter, self)
    self.lay.addWidget(btn)
    btn.clicked.connect(partial(self.btnClicked, letter))

[...]

def btnCliked(self, letter):
    print(letter)

rawDescription: how do I create check box or radio button in python?

description: Create check box or radio button in python


code:
import os
import os.path
import zipfile

zip_filename = 'folder.zip'
base_dir = os.path.abspath('parent')

with zipfile.ZipFile(zip_filename, "w",
                     compression=zipfile.ZIP_DEFLATED) as zf:
    base_path = os.path.normpath(base_dir)
    for dirpath, dirnames, filenames in os.walk(base_dir):
        for name in sorted(dirnames):
            path = os.path.normpath(os.path.join(dirpath, name))
            zf.write(path, os.path.relpath(path, base_path))
        for name in filenames:
            path = os.path.normpath(os.path.join(dirpath, name))
            if os.path.isfile(path):
                zf.write(path, os.path.relpath(path, base_path))

rawDescription: Python zip folder without including './' (current directory)


code:
class Explosion:

    def __init__(self, rect, size, cb_func):

         self.animate_explosion(cb_func)

    ...

    def animate_explosion(self, cb_func):
         # start animation here

         ...

         # when animation finishes
         self.on_finished = cb_func()

rawDescription: Trying to do animation but the program would close before it


code:
import networkx as nx
import matplotlib.pyplot as plt

G = nx.grid_2d_graph(10,10)
pos = nx.graphviz_layout(G)

cf = plt.figure(1, figsize=(8,8))
ax = cf.add_axes((0,0,1,1))

for n in G:
    G.node[n]['draw'] = nx.draw_networkx_nodes(G,pos,nodelist=[n], with_labels=False,node_size=200,alpha=0.5,node_color='k')
for u,v in G.edges():
    G[u][v]['draw']=nx.draw_networkx_edges(G,pos,edgelist=[(u,v)],alpha=0.5,arrows=False,width=5)

plt.ion()
plt.draw()
plt.show()
sp = nx.shortest_path(G,(0,0),(9,9))
edges = zip(sp[:-1],sp[1:])

for u,v in edges:
    G.node[u]['draw'].set_color('r')
    G.node[v]['draw'].set_color('r')
    G[u][v]['draw'].set_alpha(1.0)
    G[u][v]['draw'].set_color('r')
    plt.draw()

rawDescription: Animating a network graph to show the progress of an algorithm


code: INSTALLED_APPS = ("someapp", )

rawDescription: Why do I have to put the project name when importing tasks when using Django with Celery?


rawDescription: Tkinter Canvas move item to top level

description: Tkinter Canvas move item to top level


code:
@contextlib.contextmanager
def timeit(*, loop=None):
    start = time.time()
    with patch_select() as context:
        yield
    total = time.time() - start
    io_time = context.iotime
    print("IO time: {:.3f}".format(io_time))
    print("CPU time: {:.3f}".format(total - io_time))
    print("Total time: {:.3f}".format(total))

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


rawDescription: Python string formatted in double qoutes for JS


code:
import csv
import re
from itertools import chain

with open('file') as f_input, open('output.csv', 'wb') as f_output:
    text = f_input.read()
    csv_output = csv.writer(f_output)

    for block in re.findall(r'Item Number:(.*?)\${5}', text, re.S):
        re_hostname =  re.search(r'host = (.*)', block)
        if re_hostname:
            data = re.findall(r'ttl=(\d+) time=([0-9.]+) ', block)
            csv_output.writerow([re_hostname.group(1)] + list(chain.from_iterable(data)))

rawDescription: Parsing the result of ping using regex with python


code:
field1_count = func.count(Table1.field1)

result = session.query(Table1.field1, Table1.field2, field1_count).filter(
    Table1.user_id == self.user_id).filter(Table1.timestamp > self.from_ts).group_by(
    Table1.field1, Travelog.field2).order_by(desc(field1_count)).first()

rawDescription: how use alias in sqlachemy

description: How use alias in sqlachemy


code:
if MyNewCube not in MyMoveCube:
    do_whatever()

rawDescription: Check if object is already in list (Python)


rawDescription: Formatting of MySQL data using python

description: Formatting of MySQL data using python


code:
ax_2 = fig.add_subplot(222, sharex=None, sharey=None)
ax_22 = ax_2.twinx()
ax_2.set_xlabel("AX2 X Lablel")
ax_2.plot([1, 3, 5, 7, 9])

# Becomes...

ax_2 = fig.add_subplot(222, sharex=None, sharey=None)
ax_2.set_xlabel("AX2 X Lablel")
ax_2.plot([1, 3, 5, 7, 9])
ax_22 = ax_2.twinx()

rawDescription: matplotlib - No xlabel and xticks for twinx axes in subploted figures

description: Matplotlib - No xlabel and xticks for twinx axes in subploted figures


code:
randomnumbers = np.random.normal((mu*(price/10)), (v*(price/10)), days) #This variable generates a series of random numbers based on the normal distribution and in accordance with the return and volatility specified.
randomwalk    = [simAssetPrice[i-1] + randomnumbers[i] + k for i in range(1,days)]

plt.plot(randomwalk)
plt.ylabel('Price')
plt.show()

rawDescription: Plotting in Python?

description: Plotting in Python


code: del lst[1::2]

rawDescription: Remove odd elements from list in Python

description: Remove odd elements from list in Python


rawDescription: py2neo: performance and return values of various commands

description: Py2neo: performance and return values of various commands


code:
def compress_list(alist):
    """Compress a list of colon-separated strings into a more compact
    representation.
    """
    components = [ss.split(':') for ss in alist]

    # Check that every string in the supplied list has the same number of tags
    tag_counts = [len(cc) for cc in components]
    if len(set(tag_counts)) != 1:
        raise ValueError("Not all of the strings have the same number of tags")

    # For each component, gather a list of all the applicable tags. The set
    # at index k of tag_possibilities is all the possibilities for the
    # kth tag
    tag_possibilities = list()
    for tag_idx in range(tag_counts[0]):
        tag_possibilities.append(set(cc[tag_idx] for cc in components))

    # Now take the list of tags, and turn them into slash-separated strings
    tag_possibilities_strs = ['/'.join(tt) for tt in tag_possibilities]

    # Finally, stitch this together with colons
    return ':'.join(tag_possibilities_strs)

rawDescription: Reversing (or simplifying) a Cartesian product?


code:
coefficients = numpy.polyfit(logB, logA, 1)
polynomial = numpy.poly1d(coefficients)
ys = polynomial(b)
plt.plot(logB, logA)
plt.plot(b, ys)

rawDescription: Fitting a straight line to a log-log curve in matplotlib


code:
import numpy as np

a = np.random.rand(10)            # Generate random data.
a = np.where(a > 0.8, np.nan, a)  # Set all data larger than 0.8 to NaN

a = np.ma.array(a, mask=np.isnan(a)) # Use a mask to mark the NaNs

a_norm  = a / np.sum(a) # The sum function ignores the masked values.
a_norm2 = a / np.std(a) # The std function ignores the masked values.

rawDescription: How to disregard the NaN data point in numpy array and generate the normalized data in Python?

description: Disregard the NaN data point in numpy array and generate the normalized data in Python


rawDescription: Select from numpy array by column with multiple logical conditions


rawDescription: Efficiently remove rows/columns of numpy image array


code:
highlightIndices = [100,169]
subtractFromIndex = 0
for sentence in sent_tokenize(paragraph):
    for index in highlightIndices:
        if 0 < index - subtractFromIndex < len(sentence):
            sentencesWithHighlights.append(sentence)
            break
    subtractFromIndex += len(sentence)

rawDescription: Finding the surrounding sentence of a char/word in a string


code: g.incident(root, mode="out")

rawDescription: selecting edges based on source/target in igraph

description: Selecting edges based on source/target in igraph


code:
def syf1(A, E=True):
    out = np.empty_like(A)
    out[:-1] = A[1:] - A[:-1] # Or np.diff(my_array,axis=0)
    if E == True:
        out[-1] = 0
    else:
        out[-1] = -A[-1]
    return out

rawDescription: Fastest way to shift a Numpy array

description: Fastest way to shift a Numpy array


rawDescription: Faster alternative to for loop in for loop


code:
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

rawDescription: Difference between two time intervals in Python


code:
class MyList(ULC.UltimateListCtrl, listmix.ColumnSorterMixin):
    def __init__(self, parent, data):
        ULC.UltimateListCtrl.__init__(self, parent, agwStyle=ULC.ULC_REPORT | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
        self.data = data
        self.IDoMyself()
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumn)

    def IDoMyself(self):
        self.itemDataMap = self.data
        listmix.ColumnSorterMixin.__init__(self, len(self.data))

        self.InsertColumn(0, "A")      # you should generalize this for any size
        self.InsertColumn(1, "B")
        self.InsertColumn(2, "C")

        for key, data in self.data.items():
            index = self.Append(data)
            self.SetItemData(index, key)

    def OnColumn(self, e):
        self.Refresh()
        e.Skip()

    def GetListCtrl(self):
        return self

rawDescription: How to allow UltimateListCtrl to rearrange itself, wxpython

description: Allow UltimateListCtrl to rearrange itself, wxpython


code:
from itertools import combinations_with_replacement, permutations
from operator import mul
from functools import reduce
results = set()
for digits in combinations_with_replacement(range(1, 10), 5):
    if sum(digits) == reduce(mul, digits):
        results.update(int(''.join(map(str, p))) for p in permutations(digits))

len(results)
for result in sorted(results):
    print(result)

rawDescription: Count numbers in range which sum of digits is same as product


code:
weight, *path = get_path_and_weight(data, "Abe", "Dan")

print(path, "with weight", weight)

rawDescription: Find path from a list of tuples in Python


code:
from_this = {"version":"0.0","response":[{"macAddress":"88:5A:92:A4:E7:C8","networkDeviceId":"e15789bd-47df-4df9-809f-daf81d15ff2a","lineCardId":"e5bddd56-2194-4b83-8ae5-597893800051","lastUpdated":"2014-06-03 01:39:19.855491-07","platformId":"C897VA-K9","vendor":"Cisco","numUpdates":1,"interfaceCount":"10","portRange":"ATM0, ATM0.1, BRI0, BRI0:1-2, Dialer1, Ethernet0, GigabitEthernet0-8, LISP0, Loopback0-1, NVI0, Virtual-Access1, Virtual-Template1, Vlan1","roleSource":"auto","chassisType":"C800","softwareVersion":"15.4(2)T","upTime":"2 weeks, 3 days, 18 hours, 2 minutes","imageName":"c800-universalk9-mz.SPA.154-2.T.bin","memorySize":"988236K/60339K","managementIpAddress":"192.168.2.1","family":"C897VA-K9","type":"UNKNOWN","serialNumber":"FGL175124DX","role":"Unknown","hostname":"chaney-xtr"}, {"macAddress":"88:5A:92:A4:E7:C8","networkDeviceId":"e15789bd-47df-4df9-809f-daf81d15ff2a","lineCardId":"e5bddd56-2194-4b83-8ae5-597893800051","lastUpdated":"2014-06-03 01:39:19.855491-07","platformId":"C897VA-K9","vendor":"Cisco","numUpdates":1,"interfaceCount":"10","portRange":"ATM0, ATM0.1, BRI0, BRI0:1-2, Dialer1, Ethernet0, GigabitEthernet0-8, LISP0, Loopback0-1, NVI0, Virtual-Access1, Virtual-Template1, Vlan1","roleSource":"auto","chassisType":"C800","softwareVersion":"15.4(2)T","upTime":"2 weeks, 3 days, 18 hours, 2 minutes","imageName":"c800-universalk9-mz.SPA.154-2.T.bin","memorySize":"988236K/60339K","managementIpAddress":"192.168.2.2","family":"C897VA-K9","type":"UNKNOWN","serialNumber":"XGL175124D3","role":"Unknown","hostname":"chaney-xtr2"}]}

dict1 = {}
dict2 = {}

for response_item in from_this['response']:
    dict1[response_item['managementIpAddress']] = response_item['hostname']
    dict2[response_item['managementIpAddress']] = response_item['platformId']

rawDescription: Creating lists and dictionaries from JSON data in Python


rawDescription: Access parent object from submodule

description: Access parent object from submodule


code:
df[['Measurements', 'Error']] = df[['Measurements', 'Error']].shift(-1)
df[['SampleID', 'OtherInfo', 'Notes']] = df[['SampleID', 'OtherInfo', 'Notes']].fillna()
df = df.dropna()
df

rawDescription: Convert excel or csv file to pandas multilevel dataframe


rawDescription: python sort list based on key sorted list

description: Python sort list based on key sorted list


code:
result = foo() # foo will return None if failure
if result:
    # deal with result.
    pass

rawDescription: Why python designed as str(None) return 'None' instead of an empty string?


code:
import time
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.satview.org/?sat_id=41186U")

while True:
    location = driver.find_element_by_css_selector("#sat_latlon .texto_track2").text
    latitude, longitude = location.split("\n")[:2]

    print(latitude, longitude)

    time.sleep(1)

rawDescription: Can scraping be applied to this page which is actively recalculating?


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

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


code:
import random

screen_width = 1000
screen_height = 800
rect_x = 500
rect_y = 250
rect_width = 100
rect_height = 75

valid_points = []
for x in range(screen_width):
    if rect_x <= x < (rect_x + rect_width):
        for y in range(rect_y):
            valid_points.append( (x, y) )
        for y in range(rect_y + rect_height, screen_height):
            valid_points.append( (x, y) )
    else:
        for y in range(screen_height):
            valid_points.append( (x, y) )

for i in range(10):
    rand_point = random.choice(valid_points)
    print(rand_point)

rawDescription: Generate random number outside of range in python


code:
class Event(ManagerBase):
    """Defines an event."""

    __tablename__ = 'eventing_events'

    id = Column(Integer, primary_key=True)
    device_id = Column(Integer, ForeignKey(EventingDevice.id), nullable=False)
    device = relation(EventingDevice)
    type_id = Column(Integer, ForeignKey(EventType.id), nullable=False)
    type = relation(EventType)
    datetime = Column(DateTime, nullable=False)
    summary = Column(String(500))

    fields = dict_proxy("field_values", "name", "value")

rawDescription: Change collection class key of reference in association_proxy


code:
def _createTag(tag, **attributes):
    out = "<" + tag
    if attributes:
        for attr, value in attributes.items():
            out += " " + attr.rstrip('_') + "=\"" + value + "\""
    out += ">"
    return out

rawDescription: Allowing the use of the token `class` as a named parameter in a method signature


code:
class OldStyleCar:
    ...

rawDescription: What' the meaning of the brackets in the class?


code:
from datetime import datetime

def get_dates(filename, A, B):
    with open(filename) as f:
        dates = [datetime.strptime(row.split()[2], format) for row in f.readlines()]
    dates = [dt for dt in dates if dt.year == A and dt.month == B]
    return [(dt, dates.count(dt)) for dt in set(dates)]

rawDescription: Dictionary conversion to list in Python

description: Dictionary conversion to list in Python


code:
x=timeit.Timer(stmt='import itertools;my_str = "abcdefgfaabbbffbbbbbbfgbb";max(len(list(y)) for (c,y) in itertools.groupby(my_str) if c=="b")')
x.timeit()
22.759046077728271

x=timeit.Timer(stmt='import re;my_str = "abcdefgfaabbbffbbbbbbfgbb";len(max(re.compile("(b+b)").findall(my_str)))')
x.timeit()
8.4770550727844238

rawDescription: Counting longest occurence of repeated sequence in Python


code:
input_files = ['file_1.txt', 'file_2.txt', ...]
outputs = {}
for file_name in input_files:
  outputs[file_name] = GetOutput(file_name)

rawDescription: Read files and count lengths for dictionary variable in python


code:
def list_replace(lst, source_sequence, target_sequence, limit=0):
    if limit < 0:
        raise Exception('A negative replacement limit is not supported')
    source_sequence_len = len(source_sequence)
    target_sequence_len = len(target_sequence)
    original_list_len = len(lst)
    if source_sequence_len > original_list_len:
        return list(lst)
    new_list = []
    i = 0
    replace_counter = 0
    while i < original_list_len:
        suffix_is_long_enough = source_sequence_len <= (original_list_len - i)
        limit_is_satisfied = (limit == 0 or replace_counter < limit)
        if suffix_is_long_enough and limit_is_satisfied:
            if lst[i:i + source_sequence_len] == source_sequence:
                new_list.extend(target_sequence)
                i += source_sequence_len
                replace_counter += 1
                continue
        new_list.append(lst[i])
        i += 1
    return new_list

rawDescription: Python: Find-replace on lists

description: Python: Find-replace on lists


rawDescription: Delete and index and associated data from a pandas dataframe


code: lst[:] = whatever

rawDescription: List assignment with [:]

description: List assignment with [:]


code: fltr(x, [])

rawDescription: Python filter nested dict given list of key names


code:
def permutateIndexes(array, perm):
    return array[np.ix_(*(perm[:s] for s in array.shape))]

rawDescription: Permuting numpy's 2d array indexes

description: Permuting numpy's 2d array indexes


code: x = func(a, b, c)

rawDescription: get slice from multi-dimensions in python

description: Get slice from multi-dimensions in python


code:
WordLenLi = [len(word) for word in st.split()]
print(WordLenLi)

rawDescription: how to implement a list of paragraph word lengths using a for loop

description: Implement a list of paragraph word lengths using a for loop


code: _ = plt.plot(a)

rawDescription: How to hide <matplotlib.lines.Line2D> in IPython notebook

description: Hide <matplotlib.lines.Line2D> in IPython notebook


code:
a = D1[L1.astype(bool)].sum()
b = D2[L2.astype(bool)].sum()

rawDescription: Is there any fastest way to execute For loops in python?


code: res = {col: t[col][t[col] != 0] for col in df.columns}

rawDescription: Filtering for row-wise patterns in columns with a sequence of 0 and 1


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

description: Do shortest path algorithm for unweighted graph


code:
import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

rawDescription: How to use matplotlib tight layout with Figure?

description: Use matplotlib tight layout with Figure


code:
# /settings.py

DUPEFILTER_CLASS = 'myproject.dupefilters.MyRFPDupeFilter'
SCHEDULER = 'myproject.scheduler.MyScheduler'

rawDescription: Scrapy - Retrieve spider object in dupefilter


rawDescription: Replacing column values in an array using putmask and preserving order


code:
from scapy.all import Packet, IntField, IntEnumField, FieldLenField, \
PacketListField, StrNullField, ConditionalField, Padding, bind_layers

class RecordLONG(Packet):
    fields_desc = [
        IntField("data_long_record", 0),
    ]

class RecordSZ(Packet):
    fields_desc = [
        StrNullField("data_sz_record", ""),
    ]

bind_layers(RecordLONG, Padding)
bind_layers(RecordSZ, Padding)

class MainPacket(Packet):
    fields_desc = [
        IntEnumField("record_type", 1, {
            3:"DATA_LONG",
            8:"DATA_SZ"}),
        FieldLenField("record_nb", 0, fmt="I", count_of="records"),
        ConditionalField(PacketListField("records", None, RecordLONG, count_from=lambda pkt:pkt.record_nb), lambda pkt: pkt.record_type == 3),
        ConditionalField(PacketListField("records", None, RecordSZ, count_from=lambda pkt:pkt.record_nb), lambda pkt: pkt.record_type == 8),
    ]

if __name__ == "__main__":
    p1 = MainPacket("\x00\x00\x00\x03" # Type is DATA_LONG
               "\x00\x00\x00\x04" # 4 records
               "\x00\x00\x00\x01"
               "\x00\x00\x00\x02"
               "\x00\x00\x00\x03"
               "\x00\x00\x00\x04")
    p1.show()
    p2 = MainPacket("\x00\x00\x00\x08" # Type is DATA_SZ
               "\x00\x00\x00\x02" # 2 records
               "Hello\x00"
               " world.\x00")
    p2.show()

rawDescription: Scapy: How to implement a list of conditional fields?


rawDescription: xpath search attribute with part of string

description: Xpath search attribute with part of string


code:
for foo in generator:
    yield directories.append(foo['name']) or foo

rawDescription: Capture-and-yield in a list comprehension


code:
from Products.Five import BrowserView
from plone.app.kss.plonekssview import PloneKSSView
class DDActions(PloneKSSView):
    def getTableColumns(self, table, currValue, currLabel):
        columns = self.context.getColumnNames(table)
        for (field, curr) in [('valueColumn', currValue), ('labelColumn',currLabel)]:
            self.replaceSelect(field, columns, (curr or self.context[field]))

rawDescription: Include Python scripts with Plone Add-on


rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code: df1.append(df2.loc[[i for i in df2.index if i not in df1.index], :])

rawDescription: Replace data from one pandas dataframe to another


rawDescription: Modifying a subset of rows in a pandas dataframe


rawDescription: Why does my webcrawler not follow into the next link containing keywords


rawDescription: Create a 100 % stacked area chart with matplotlib


code: form = EditEventForm(instance=event)

rawDescription: Fill Django Form Field Data with Db Data


code:
a=[u'1,2,3']
a
a = a[0]
a
a.split(',')    # I split this string on ','
[int(x) for x in [u'1,2,3'][0].split(',')]

rawDescription: How to convert unicode string into list using pandas python?

description: Convert unicode string into list using pandas python


code: my_array = np.load('my_array.npy')

rawDescription: By dumping a python list, creating a python ".py" file which returns the same python list


code: file1 = dict(l.strip().split(':') for l in open('file1', 'r'))

rawDescription: Text processing with two files

description: Text processing with two files


code:
def add_len(strlist):
    return [(s, len(s)) for s in strlist]

rawDescription: Append length of string for each string in list


rawDescription: Django Views Incrementing Variables

description: Django Views Incrementing Variables


code: state = (state % 4) + 1

rawDescription: Python one line if-else with different operators


code:
import math

class Vector(tuple):
    def magnitude(self):
        return math.sqrt( self[0]*self[0]+self[1]*self[1]+self[2]*self[2] )

rawDescription: Python: can a class instance evaluate to any type?


code:
files = []
file_index = 0
for filename in os.listdir("/mydirectory"):
    if filename.endswith(".mp3"):
        files.append(filename)
# files.sort() # do this if you want them in name order

pygame.mixer.init()
pygame.mixer.music.load(files[file_index])
pygame.mixer.music.play(15.0)

rawDescription: How can I play next mp3 file in directory?

description: Play next mp3 file in directory


rawDescription: Print tree with indentations

description: Print tree with indentations


rawDescription: How do I make relative importing work in Python using Eclipse with PyDev?

description: Make relative importing work in Python using Eclipse with PyDev


rawDescription: Zipping dynamic files in App Engine (Python)


code:
class ImageOrder(Model):
    """Keeps track ordering of images for a given user"""
    order = IntField()
    user = ForeignKey(User)
    image = ForeignKey(Image)

rawDescription: How to re-arrange the order of saved objects in Django database

description: Re-arrange the order of saved objects in Django database


code: value & flag == flag

rawDescription: Python equivalent of C# Enum.HasFlag

description: Python equivalent of C# Enum.HasFlag


code:
buttons = dict()
for k in range(len(info)):
    buttons[k] = Button(top, text=info[k], command=lambda: my_function(buttons[k]))

rawDescription: Tkinter: creating an arbitrary number of buttons/widgets


rawDescription: How to check a string matched with multiple patterns?

description: Check a string matched with multiple patterns


code:
# C:\test.py
import os
os.startfile(r"C:\sampleBatch.bat")

rawDescription: How to make scripts auto-delete at the end of execution?

description: Make scripts auto-delete at the end of execution


code:
import re

content = "...And this can be accomplished with the Awesome Method. Blah blah blah...."
links = [('awesome method', '/path/to/awesome-method')]

for keyphrase, url in links:
    content = re.sub('(%s)' % keyphrase, r'\1' % url, content, flags=re.IGNORECASE)

# content:
# '...And this can be accomplished with the Awesome Method. Blah blah blah....'

rawDescription: Convert phrases in HTML to links with Python


code:
from collections import Counter
import re

counts = Counter()
words = re.compile(r'\w+')

for sentence in sequence_of_sentences:
    counts.update(words.findall(sentence.lower()))

rawDescription: Count word occurrence in a list of strings


code:
#!/usr/bin/python
from scapy.all import *

stars = lambda n: "*" * n

def GET_print(packet):
    return "\n".join((
        stars(40) + "GET PACKET" + stars(40),
        "\n".join(packet.sprintf("{Raw:%Raw.load%}").split(r"\r\n")),
        stars(90)))

sniff(
    iface='eth0',
    prn=GET_print,
    lfilter=lambda p: "GET" in str(p),
    filter="tcp port 80")

rawDescription: HTTP GET packet sniffer in Scapy

description: HTTP GET packet sniffer in Scapy


code:
y = np.genfromtxt('/tmp/test.out')
y.shape

rawDescription: Numpy matrix from text file

description: Numpy matrix from text file


rawDescription: n-dimensional sliding window with Pandas or Numpy

description: N-dimensional sliding window with Pandas or Numpy


rawDescription: Different behaviour between python console and python script


code: i = word.find(letter)

rawDescription: Lists, conditionals and loops don't give the result expected


code: self._font = pygame.font.Font("/path/to/my/font/file", self._size)

rawDescription: Changing font in a livewires message

description: Changing font in a livewires message


code:
class Shape(object):
    # subclasses must provide a point_array instance attribute
    @property
    def lowest_z(self):
        return min(p.z for p in self.point_array)

class Line(Shape):
    def __init__(self, pos1, pos2):
        #pos1, pos2 are points
        self.point_array = [pos1, pos2]

class Circle(Shape):
    def __init__(self, center, radius):
        #center is a point
        self.point_array = [center]
        self.radius = radius

    @property
    def lowest_z(self):
        return self.point_array[0].z - self.radius

# etc.

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


code:
new, newref = zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))
new
newref

rawDescription: Python: Deleting Specific value from the list


code:
from itertools import compress
reason = [', '.join(compress(variables, x))
          for x in zip(narrative, subject, activity, filer)]

rawDescription: Filter a tuple with another tuple in Python


code:
r.match('January 30, 2001') is not None
r.match('January 31, 2001') is not None
r.match('January 32, 2001') is not None
r.match('February 32, 2001') is not None
r.match('February 29, 2001') is not None
r.match('February 28, 2001') is not None
r.match('February 29, 2000') is not None
r.match('April 30, 1908') is not None
r.match('April 31, 1908') is not None

rawDescription: Matching dates with regular expressions in Python?


code:
import pandas as pd

df = pd.read_csv('many_cols.csv')

for col in df.columns:
    print(col, df[col].drop_duplicates().tolist())

rawDescription: Is there a in built method from python csv module to enumerate all possible value for a specific column?


rawDescription: Numpy.unique - getting output with consistent depth


code:
class DataGen(object):
    def __init__(self):
        self.first_name = 'Storm' + str(timeGen.timeGen())
        self.last_name = 'Trooper' + str(timeGen.timeGen())
        self.email = DataGen.rand_email()
        self.empid = DataGen.rand_empid()
        self.ssn = DataGen.rand_ssn()

    @staticmethod
    def rand_string():
        r_int = random.randint(1,20)
        r_string = ''.join(random.choice(string.ascii_uppercase +
                         string.ascii_lowercase + string.digits)
                    for _ in range(r_int))
        return r_string

    @staticmethod
    def rand_email():
        email_a = DataGen.rand_string()
        email_b = DataGen.rand_string()
        items = ['.com','.net','.org']
        tld = random.choice(items)
        return str(email_a) + '@' + str(email_b) + str(tld)

    @staticmethod
    def rand_empid(size=20, chars=string.ascii_uppercase +
                                string.ascii_lowercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

    @staticmethod
    def rand_ssn():
        ssn = random.randint(100000000,999999999)
        return ssn

rawDescription: Getting Python to Create a new instance every time


code:
def find_ip(s, f):
    with open(f) as f:
        grouped = groupby(f, key=lambda x: x.startswith("lease "))
        for k, v in grouped:
            if k: # v is the lease line
                # get ip from lease line
                ip = next(v).rstrip().split()[1]
                # call next to get next element from our groupby object
                # which is each section after lease
                val = next(grouped)[1]
                # check for substring
                if any(sub.find(s) != -1 for sub in val):
                    return ip.rstrip("{")
    return "No match"

rawDescription: Extract Information From a File

description: Extract Information From a File


rawDescription: How to convert numpy.recarray to numpy.array?

description: Convert numpy.recarray to numpy.array


code:
from datetime import date
a = date(2011,11,24)
b = date(2011,11,17)
a-b
(a-b).days

rawDescription: Days between two dates in Python

description: Days between two dates in Python


code:
for item in tails:
    xposition = item[1]  # get item by index
    yposition = item[2]
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

rawDescription: Getting a specific value from a tuple within a list


code:
print(rows[0])  # debug statement to examine the content
"""

Leavenworth Summer Theater
LEAVENWORTH, WA
07/15/2015
08/28/2015

"""

rawDescription: Using Python to Automate Web Searches

description: Using Python to Automate Web Searches


code:
f1_in = open("f1.csv","r")
f1_dict = {}
for line in f1_in:
    l = line.split()
    f1_dict[l[0].strip()] = l[1].strip()
f1_in.close()

f2_in = open("f2.csv","r")
f2_dict = {}
for line in f2_in:
    l = line.split()
    f2_dict[l[0].strip()] = l[1].strip()
f2_in.close()

f_same = open("same.txt","w")
f_different = open("different.txt","w")

for k1 in f1_dict.keys():
    if k1 in f2_dict.keys() \
    and f2_dict[k1] == f1_dict[k1]:
        f_same.write("{0}, {1}\n".format(str(k1)+" "+str(f1_dict[k1]),
                                         str(k1)+" "+str(f2_dict[k1])))
    elif not k1 in f2_dict.keys():
        f_different.write("{0}, {1}\n".format(str(k1)+" "+str(f1_dict[k1]),
                                              "------"))
    elif not f2_dict[k1] == f1_dict[k1]:
        f_different.write("{0}, {1}\n".format(str(k1)+" "+str(f1_dict[k1]),
                                              str(k1)+" "+str(f2_dict[k1])))

f_same.close()
f_different.close()

rawDescription: Compare CSV files using python

description: Compare CSV files using python


rawDescription: More Digits in Irrational Numbers

description: More Digits in Irrational Numbers


code:
from collections import Counter
Counter('abbba')

rawDescription: How to iterate over the elements of a map in python

description: Iterate over the elements of a map in python


code:
sc = self_compose (lambda x: x*3, 3)

if sc(2) == 54:
  print ("SUCCESS")

rawDescription: Python lambda self composing function: How to return a function that is repeated n amount of times?


code: df = df.set_index(['TRX_DATE'])

rawDescription: how to slice a dataframe having date field as index?

description: Slice a dataframe having date field as index


rawDescription: Python: how to find common values in three lists


code:
i = my_listbox.get(0, END).index(old_breakfast_string)
my_listbox.delete(i)
my_listbox.insert(i, new_breakfast_string)

rawDescription: Loop over tkinter Listbox

description: Loop over tkinter Listbox


code: what_i_want = [objects[i+1:j] for i,j in zip(z, z[1:])]

rawDescription: Short way to extract sublist from list in python by given conditions


code:
pdf = mdf.price_y
pdf = pandas.DataFrame(pdf)
del mdf['price_y']
mdf.rename(columns = {'price_x':'price'},inplace=True)
pdf.rename(columns = {'price_y':'price'},inplace=True)
mdf
pdf

rawDescription: Partial merge in Pandas

description: Partial merge in Pandas


rawDescription: How to round to zero decimals if there is no decimal value with Jinja2?

description: Round to zero decimals if there is no decimal value with Jinja2


code:
knapsack = Knapsack([4,1,9,2,0,4,4,4,3,7],10)
print(knapsack.solveIt())

rawDescription: Turning my function into a class

description: Turning my function into a class


code:
value = d[(3,4)].get()
print("row 3, column 4 = %s" % value)

rawDescription: Python tkinter create buttons with loop and edit their parameters


code: keys = values_to_keys.get(value)

rawDescription: return key by value in dictionary

description: Return key by value in dictionary


code:
Model1.objects.raw('''SELECT * from myapp_model1
                   INNER JOIN myapp_model2
                   ON myapp_model1.field = myapp_model2.field
                   AND ...''')

rawDescription: Most efficient way to use the django ORM when comparing elements from two lists


code: "(//span[@class='odds black'])"

rawDescription: Scan through row elements whose classname is identical


code:
df = pd.read_csv("test.csv", sep=";")
df
c3 = df.pop("Column 3").str.split("|", expand=True)
c3.columns = ["ID", "Age", "Height"]
df.join(c3)

rawDescription: Delimit a specific column and add them as columns in CSV (Python3, CSV)


code:
def add_two(match):
    return str(int(match.group()) + 2)

s = 'Alex 28'
re.sub(r'(\d+)', add_two, s)

rawDescription: How to evaluate replacement part in re.sub?

description: Evaluate replacement part in re.sub


code:
def notifyChange(self, childKey, strChangeInChild):
    strChange = "[{0}]{1}".format(childKey, strChangeInChild)
    self.parent.notifyChange(self.id, strChange)

rawDescription: How to detect what element of a nested list has changed? (python)

description: Detect what element of a nested list has changed? (python)


code:
l2, l1 = ['_ru', '_uk', '_en'], ['1','2','3']
from itertools import product
["".join(items) for items in product(l1, l2)]

rawDescription: Concat each element of list with each element of second list


code:
import blah
x = blah.renameable()
x
x.rename_me('y')
x
y

rawDescription: distinct classes using `with` in Python

description: Distinct classes using `with` in Python


code:
class MGraph(object):
    def __init__(self):
        self.edgelist = []
        self.edgedict = defaultdict(list)
    def add(self, edge):
        self.edgedict[edge].append(len(self.edgelist))
        self.edgelist.append(edge)
    def remove(self, edge):
        for index in self.edgedict.get(edge, []):
            maxedge = len(self.edgelist) - 1
            lastedge = self.edgelist[maxedge]
            self.edgelist[index], self.edgelist[maxedge] = self.edgelist[maxedge], self.edgelist[index]
            self.edgedict[lastedge] = [i if i != maxedge else index for i in self.edgedict[lastedge]]
            del self.edgelist[-1]
        del self.edgedict[edge]
    def choice(self):
        return random.choice(self.edgelist)

rawDescription: Constant time random selection and deletion


code:
class Character(object):
     def __init__(name, type, category, strength, intelligence):
         self.strength = strength
         self.intelligence = intelligence
         self.name = name
         self.type = type
         self.category = category

     def make_smart_or_dumb(self, intelligence):
         self.intelligence += intelligence

     def make_strong_or_weak(self, strength):
         self.strength += strength

     def is_dead(self):
         return self.strength < 0

gunar_the_orc = Character('Gunar','Orc', 'Warrior', 10, 5)
smith_the_human = Character('Smith','Human','Warrior', 5, 10)

game_characters = [gunar_the_orc, smith_the_human]

rawDescription: How to add to dictionaries, but not dictionaries - Python

description: Add to dictionaries, but not dictionaries - Python


code: [elem.strip('()') for elem in "(A+B)*(C+D)".split("*")]

rawDescription: Python List Indexing and Returning the Item


code: xlbl = ax.xaxis.get_label()

rawDescription: How to access axis label object in matplotlib?

description: Access axis label object in matplotlib


code: user = partner.key.parent().get()

rawDescription: GAE Datastore ndb models accessed in 5 different ways


code:
from pygame import *
from pygame.locals import *
from math import *

#----------------------------------------------------------------------

class Clock(object):

    def __init__(self, hours, minutes, seconds, cx, cy, r, ticks):

        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
        self.cx = cx
        self.cy = cy
        self.r = r
        self.ticks = ticks
        self.time_to_move = 0

    def update(self, current_ticks):

        if current_ticks > self.time_to_move:
            self.time_to_move += self.ticks

            self.seconds_ang = 270 + 6 * self.seconds

            self.seconds_dx = self.cx + int(cos(radians(-self.seconds_ang))*self.r)
            self.seconds_dy = self.cy - int(sin(radians(-self.seconds_ang))*self.r)

            self.minutes_ang = 270 + 6 * (self.minutes + self.seconds/60.)

            self.minutes_dx = self.cx + int(cos(radians(-self.minutes_ang))*self.r)
            self.minutes_dy = self.cy - int(sin(radians(-self.minutes_ang))*self.r)

            self.hours_ang = 270 + 30 * (self.hours + self.minutes/60.)

            self.hours_dx = self.cx + int(cos(radians(-self.hours_ang))*self.r*.75)
            self.hours_dy = self.cy - int(sin(radians(-self.hours_ang))*self.r*.75)

            self.seconds += 1

            if self.seconds == 60:
                self.seconds = 0
                self.minutes += 1

                if self.minutes == 60:
                    self.minutes = 0
                    self.hours += 1

                    if self.hours == 12:
                        self.hours = 0

    def draw(self, screen):
        draw.circle(screen, (255,255,255), (self.cx,self.cy), self.r, 3)
        draw.line(screen, (0,255,255), (self.cx,self.cy), (self.hours_dx, self.hours_dy), 5)
        draw.line(screen, (255,255,0), (self.cx,self.cy), (self.minutes_dx, self.minutes_dy), 2)
        draw.line(screen, (255,0,255), (self.cx,self.cy), (self.seconds_dx, self.seconds_dy), 1)

#----------------------------------------------------------------------

init()

screen = display.set_mode((800,600))

clock = time.Clock()

clock1 = Clock(5, 59, 0, 400, 300, 200, 1000)
clock2 = Clock(5, 59, 0, 100, 100, 100, 100)
clock3 = Clock(3, 9, 0, 700, 100, 100, 100)
clock4 = Clock(7, 24, 0, 100, 500, 100, 10)
clock5 = Clock(11, 30, 0, 700, 500, 100, 10)

running=True
while running:

    # events

    for e in event.get():
        if e.type == QUIT:
            running = False

    # (variable) modifications

    clock1.update(time.get_ticks())
    clock2.update(time.get_ticks())
    clock3.update(time.get_ticks())
    clock4.update(time.get_ticks())
    clock5.update(time.get_ticks())

    # draw

    screen.fill((0,0,0))

    clock1.draw(screen)
    clock2.draw(screen)
    clock3.draw(screen)
    clock4.draw(screen)
    clock5.draw(screen)

    # flip

    display.flip()

    # FPS (Frames Per Seconds)

    #clock.tick(60)

quit()

rawDescription: Clock in Python

description: Clock in Python


code: map(list, generator_of_generators)

rawDescription: python generator of generators?

description: Python generator of generators


code:
import numpy as np
from mayavi import mlab

np.random.seed(1977)
x, y, z = np.random.random((3, 10))

mlab.points3d(x, y, z)
mlab.gcf().scene.parallel_projection = True
mlab.show()

rawDescription: Setting parallel prospective in mlab/mayavi/python


rawDescription: Conditionally grabbing column headings in pandas dataframe


code: df['Max_Val'] = df.groupby(['date','test']).transform(lambda x: x.max() if x.size > 1 else x)

rawDescription: Pandas GroupBy aggegate only some groups


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: Flattening a very nested loop

description: Flattening a very nested loop


code:
def slider1Update(self, event):
    self.tc_ZONEVOL1.SetValue(str(self.sliderZone1.GetValue()))

rawDescription: How to pass a wxWidget to a generic function?

description: Pass a wxWidget to a generic function


code: df = pd.DataFrame(data=[[34, 'null', 'mark'], [22, 'null', 'mark'], [34, 'null', 'mark']], columns=['id', 'temp', 'name'], index=[1, 2, 3])

rawDescription: pandas value_counts applied to each column

description: Pandas value_counts applied to each column


code:
# import the context under an app-specific name (so it can easily be replaced later)
from passlib.apps import custom_app_context as pwd_context

# encrypting a password...
hash = pwd_context.encrypt("somepass")

# verifying a password...
ok = pwd_context.verify("somepass", hash)

rawDescription: Python store values into binary code

description: Python store values into binary code


code:
import pandas as pd

df = pd.read_csv('file_name.csv')
y  =  df[[-1]]
X  =  df[df.columns[0:-1]]

rawDescription: Creating a X input matrix and y output vector via Python


code:
def clean(self, *args, **kwargs):
    if not self.open and not self.start_date:
        raise ValidationError('This course is not open, therefore you need a start date')
    return super(Post, self).clean()

rawDescription: In Django 1.7, how can I have one of two model fields required?


rawDescription: Python Regex for alpha(alpha|digit)*

description: Python Regex for alpha(alpha|digit)*


code:
fnmatch.fnmatch('a/b/d/c', 'a/*/c')
fnmatch.fnmatch('a/b/d/c', 'a/*************c')

rawDescription: fnmatch and recursive path match with `**`

description: Fnmatch and recursive path match with `**`


code:
regex = r'\w=(\d+)\|\w=(\d+)'
df[['a', 'b']] = df.metadata.str.extract(regex)
df

rawDescription: add multiple items to row using vectorized pandas function, not iterrows?

description: Add multiple items to row using vectorized pandas function, not iterrows


code:
single_list = []
with open(your_file) as f:
    for line in f.readlines():
        single_list.extend(line.rstrip().split())

list_of_rows = [single_list[i*10:i*10+10] for i in range(len(single_list)//10)]

with open(output_file) as f:
    for line in list_of_rows:
        f.write(' '.join(line) + '\n')

rawDescription: Efficient way to organise data file in columns with Python


code:
from django.core.mail import EmailMessage
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send as bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML
# message and the image. These are "related" (not "alternative")
# because they are different, unique parts of the HTML message,
# not alternative (html vs. plain text) views of the same content.
html_part = MIMEMultipart(_subtype='related')

# Create the body with HTML. Note that the image, since it is inline, is
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
body = MIMEText('
Hello
', _subtype='html')
html_part.attach(body)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edit
html_part.attach(img)

# Configure and send an EmailMessage
# Note we are passing None for the body (the 2nd parameter). You could pass plain text
# to create an alternative part for this message
msg = EmailMessage('Subject Line', None, 'foo@bar.com', ['bar@foo.com'])
msg.attach(html_part) # Attach the raw MIMEBase descendant. This is a public method on EmailMessage
msg.send()

rawDescription: creating a MIME email template with images to send with python / django

description: Creating a MIME email template with images to send with python / django


code:
import json

def remove_error_info(d):
    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [remove_error_info(v) for v in d]
    return {k: remove_error_info(v) for k, v in d.items()
            if k not in {'errMsg', 'errCode'}}

data = json.loads(json_string)
data = remove_error_info(data)
json_string = json.dumps(data)

rawDescription: python delete all specific keys in json

description: Python delete all specific keys in json


rawDescription: Get all disconnected pairs of nodes in a network


code:
textA = "stackoverflow is cool"
textb = "so is very cool"

rawDescription: Implementing Google's DiffMatchPatch API for Python 2/3


code:
def nsmallest(n, iterable, key=None):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable, key=key)[:n]
    """
    # Short-cut for n==1 is to use min() when len(iterable)>0
    if n == 1:
        it = iter(iterable)
        head = list(islice(it, 1))
        if not head:
            return []
        if key is None:
            return [min(chain(head, it))]
        return [min(chain(head, it), key=key)]

    # ... rest of function

rawDescription: Retrieving minimum value from a Python heapq


code:
from celery import Celery

def task_monitor(app):
    state = app.events.State()

    def announce_completed_tasks(event):
        state.event(event)
        task = state.tasks.get(event['uuid'])

        print('TASK SUCCEEDED: %s[%s] %s' % (task.name, task.uuid, task.info(), ))

    with app.connection() as connection:
        recv = app.events.Receiver(connection, handlers={'task-succeeded': announce_completed_tasks})
        recv.capture(limit=None, timeout=None, wakeup=True)

if __name__ == '__main__':
    app = Celery(broker='amqp://guest@REMOTEHOST//')
    task_monitor(app)

rawDescription: Implementing Twisted style local multiple deferred callbacks in Celery


code:
natural = natural_num_range()
all(i in natural for i in range(1, 10000000, 10000))
any(i in natural for i in range(-100000000, 0, 10000))

rawDescription: Variable that represents all numbers in Python?


code:
from __future__ import print_function

from string import Formatter

class CallFormatter(Formatter):
    try:  # deal with Py 2 & 3 difference
        NUMERICS = (int, long)
    except NameError:
        NUMERICS = int

    def get_value(self, key, args, kwargs):
        if key.endswith('()'):  # call?
            return kwargs[key[:-2]]()
        elif isinstance(key, self.NUMERICS):
            return args[key]
        else:
            return kwargs[key]

if __name__ == '__main__':
    fmt = CallFormatter()

    def cabbages():
        return 'hello'

    d = dict(name='Fred')

    class Thing(object):
        def __init__(self, value):
            self.attr = value
    th = Thing(42)

    print('d[name]:{d[name]}, th.attr:{th.attr}, '
          'cabbages:{cabbages}'.format(**locals()))
    print(fmt.format('d[name]:{d[name]}, th.attr:{th.attr}, '
                     'cabbages:{cabbages}, cabbages():{cabbages()}',
                     **locals()))

rawDescription: Modifying python's string Formatter

description: Modifying python's string Formatter


rawDescription: Right data structure for containing shapes and spatial relations between them


code:
def get_numbers():
    yield from range(10)

list(get_numbers())
def get_squares():
    yield from [num ** 2 for num in range(10)]

list(get_squares())

rawDescription: Is there any shorthand for 'yield all the output from a generator'?


code:
self.oranges = []

for x in range(10):
    self.oranges.append(SpriteOrange('orange.png'))

rawDescription: how to make a list of images and draw them in random position in pygame?

description: Make a list of images and draw them in random position in pygame


code:
def sample1(arg0=0, arg1=0, arg2=0, arg3=0, arg4=0):
  print(locals())

argument_dictionary = {'arg0': 1, 'arg4': 4}
sample1(**argument_dictionary)

rawDescription: Use dictionary in a variable as a set of arguments to a function


rawDescription: Identify the file extension of a URL

description: Identify the file extension of a URL


code:
import zmq
from threading import Thread

def send_req(request):
    context = zmq.Context()

    print("Connecting to hello world server...")
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:5556")
    print("Sending request %s ..." % request)

    socket.send_json({"ok" : "Hello"})

    message = socket.recv()
    print("Received reply %s [ %s ]" % (request, message))

#  Do 10 requests in parallel
for request in range(10):
    Thread(target=send_req, args=(request,)).start()

rawDescription: Multi core ZeroMQ?

description: Multi core ZeroMQ


code:
import networkx as nx
import matplotlib.pyplot as plt

def single_source_shortest_path(G,source):
    ax = plt.gca()
    canvas = ax.figure.canvas
    background = canvas.copy_from_bbox(ax.bbox)
    level=0                  # the current level
    nextlevel={source:1}       # list of nodes to check at next level
    paths={source:[source]}  # paths dictionary  (paths to key from source)
    G.node[source]['draw'].set_color('r')
    G.node[source]['draw'].set_alpha('1.0')
    while nextlevel:
        thislevel=nextlevel
        nextlevel={}
        for v in thislevel:
#            canvas.restore_region(background)
            s = G.node[v]['draw']
            s.set_color('r')
            s.set_alpha('1.0')
            for w in G[v]:
                if w not in paths:
                    n = G.node[w]['draw']
                    n.set_color('r')
                    n.set_alpha('1.0')
                    e = G[v][w]['draw']
                    e.set_alpha(1.0)
                    e.set_color('k')
                    ax.draw_artist(e)
                    ax.draw_artist(n)
                    ax.draw_artist(s)
                    paths[w]=paths[v]+[w]
                    nextlevel[w]=1
                    canvas.blit(ax.bbox)
        level=level+1
    return paths

if __name__=='__main__':

    G = nx.grid_2d_graph(10,10)
    pos = nx.graphviz_layout(G)
    cf = plt.figure(1, figsize=(8,8))
    ax = cf.add_axes((0,0,1,1))

    for n in G:
        G.node[n]['draw'] = nx.draw_networkx_nodes(G,pos,nodelist=[n], with_labels=False,node_size=200,alpha=0.2,node_color='k')
    for u,v in G.edges():
        G[u][v]['draw']=nx.draw_networkx_edges(G,pos,edgelist=[(u,v)],alpha=0.5,arrows=False,width=5)
    plt.ion()
    plt.show()

    path = single_source_shortest_path(G,source=(0,0))

rawDescription: Animating a network graph to show the progress of an algorithm


code: mapped = np.take(meanings, flags)

rawDescription: Create string ndarray from ndarray of int 'flags' using list of string meanings


code:
packages=[]
packages += ["setuptools","other"]
packages
packages=[]
packages.append(["setuptools","other"])
packages

rawDescription: Syntax confusion about code in pip installer, "get-pip.py"


rawDescription: Numpy: Get random set of rows from 2D array


rawDescription: Why doesn't collections.Counter override __iadd__ method?


code:
def gen_chunks():
    chunks = [["ABABA","ACA"],["AGAGA","AAVA"],["XBX","ARAA"],
              ["AADA","AAA"],["BABAB","ABA"]]
    for chunk in chunks:
        yield chunk

rawDescription: How to return nested list elements and use them in order in python?

description: Return nested list elements and use them in order in python


code:
type(L)
# <type 'numpy.ndarray'>
type(L[0,0])
# <type 'list'>

rawDescription: append the same element to several sublists in python

description: Append the same element to several sublists in python


code:
from werkzeug.routing import AnyConverter, Rule

class TranslateConverter(AnyConverter):

    def __init__(self, map, item):
        self.language_pairs = {language: translate_url(item, language)
                               for language in languages}
        AnyConverter.__init__(self, map, *tuple(self.language_pairs.values()))

class TranslateCorrelationRule(Rule):

    def match(self, path):
        result = Rule.match(self, path)
        if result is None:
            return result
        lang_code = result.get('lang_code')
        if lang_code is None:
            return result
        for name, value in self._converters.items():
            if not isinstance(value, TranslateConverter):
                continue
            if value.language_pairs[lang_code] != result[name]:
                return
        return result

app.url_map.converters['tr'] = TranslateConverter
app.url_rule_class = TranslateCorrelationRule

rawDescription: Format canonical URL structure correctly with URL Processors


code:
for a in soup.findAll('a'):
    p = Tag(soup, 'p') #create a P element
    a.replaceWith(p)   #Put it where the A element is
    p.insert(0, a)     #put the A element inside the P (between <p> and </p>)

rawDescription: Search and Replace in HTML with BeautifulSoup


rawDescription: Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?


code:
def square_sum_difference(n):
    return int((3*n**2 + 2*n) * (1 - n**2) / 12)

rawDescription: Function to calculate the difference between sum of squares and square of sums


code:
for car in cars:
    car.update()

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


rawDescription: Pandas sorting by value and then by index


code:
import json
box_0_string = request.POST.get('boxes[]')[0]
box_0_dict = json.loads(box_0_string)

rawDescription: Unable to retrieve an Array of objects posted to Django from jQuery


rawDescription: how to get all objects by instance in django

description: Get all objects by instance in django


code: from google.appengine.api import memcache

rawDescription: How do I store a fetched entity in memcache for App Engine?

description: Store a fetched entity in memcache for App Engine


code:
quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,0,0,0,0).strftime('" + time_format + "'));");

...

rawDescription: Changing the default times in the Django TimeInput


rawDescription: Adding up values in a specific column in a CSV file (in Sage Notebook)


code:
from itertools import groupby

[list(g) for k, g in groupby(list_of_dts, key=lambda d: d.hour)]

rawDescription: Split list of datetime by hours using python


rawDescription: Pandas: Average over the same hour

description: Pandas: Average over the same hour


code: float(c.rstrip(u'% \n\t\r\xa0'))

rawDescription: Most efficient way to strip a % from u'96.9%' and return a float


code:
def normalize(probs):
    prob_factor = 1 / sum(probs)
    return [prob_factor * p for p in probs]

normalize([0.0000000001,0.000000000003,0.000000000000005])

rawDescription: Normalize Small Probabilities in Python

description: Normalize Small Probabilities in Python


code:
collectn.find({'goods.H.' + k:v for k,v in d1.items()})
collectn.find({'goods.H.' + k:v for k,v in d2.items()})

rawDescription: Pymongo or Mongodb is treating two equal python dictionaries as different objects. Can I force them to be treated the same?


code:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""

position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5

letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]

rawDescription: Python while/if statements not working

description: Python while/if statements not working


code:
def test_sel(self):
     driver = self.driver
     delay = 3
     for reg in RegionIDArray:
         page = 0
         driver.get(self.base_url + str(reg))
         for i in range(1,4):
             driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
             time.sleep(2)

rawDescription: Crawl Multiple pages of a website with using Selenium (Python3)


code:
[x[-1] for x in myList]
# [None, None, None, None]

rawDescription: How to access tuple elements in a nested list

description: Access tuple elements in a nested list


code:
# build an empty df
df = pd.DataFrame()
# get a list of the unique products, could skip this perhaps
df['Product'] = other_df['Sku'].unique()

rawDescription: python, operation on big pandas Dataframe

description: Python, operation on big pandas Dataframe


code:
import numpy as np
def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
    """
    https://github.com/joferkington/numpy/blob/3a85c0a9af64b0296b9a4c97f43f2f209c849077/numpy/core/numeric.py
    Returns a boolean array where two arrays are element-wise equal within a
    tolerance.

    The tolerance values are positive, typically very small numbers.  The
    relative difference (`rtol` * abs(`b`)) and the absolute difference
    `atol` are added together to compare against the absolute difference
    between `a` and `b`.

    Parameters
    ----------
    a, b : array_like
        Input arrays to compare.
    rtol : float
        The relative tolerance parameter (see Notes).
    atol : float
        The absolute tolerance parameter (see Notes).
    equal_nan : bool
        Whether to compare NaN's as equal.  If True, NaN's in `a` will be
        considered equal to NaN's in `b` in the output array.

    Returns
    -------
    y : array_like
        Returns a boolean array of where `a` and `b` are equal within the
        given tolerance. If both `a` and `b` are scalars, returns a single
        boolean value.

    See Also
    --------
    allclose

    Notes
    -----
    For finite values, isclose uses the following equation to test whether
    two floating point values are equivalent.
     absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
    The above equation is not symmetric in `a` and `b`, so that
    `isclose(a, b)` might be different from `isclose(b, a)` in
    some rare cases.

    Examples
    --------
    >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
    array([True, False])
    >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
    array([True, True])
    >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
    array([False, True])
    >>> np.isclose([1.0, np.nan], [1.0, np.nan])
    array([True, False])
    >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
    array([True, True])
    """
    def within_tol(x, y, atol, rtol):
        result = np.less_equal(abs(x - y), atol + rtol * abs(y))
        if np.isscalar(a) and np.isscalar(b):
            result = result[0]
        return result
    x = np.array(a, copy=False, ndmin=1)
    y = np.array(b, copy=False, ndmin=1)
    xfin = np.isfinite(x)
    yfin = np.isfinite(y)
    if np.all(xfin) and np.all(yfin):
        return within_tol(x, y, atol, rtol)
    else:
        # Avoid subtraction with infinite/nan values...
        cond = np.zeros(broadcast(x, y).shape, dtype=bool)
        mask = xfin & yfin
        cond[mask] = within_tol(x[mask], y[mask], atol, rtol)
        # Check for equality of infinite values...
        cond[~mask] = (x[~mask] == y[~mask])
        if equal_nan:
            # Make NaN == NaN
            cond[isnan(x) & isnan(y)] = True
        return cond

rawDescription: How do I install numpy/core/numeric.py file on my machine; I want isclose()

description: Install numpy/core/numeric.py file on my machine; I want isclose()


code: [ 'abc', 'state', 'fsf', 'val' ]

rawDescription: python list of tuples to javascript array of arrays

description: Python list of tuples to javascript array of arrays


code:
class dbref:
    dbnumber=0

rawDescription: Placing custom class object in a list

description: Placing custom class object in a list


code:
from openerp.osv import osv
from openerp.osv import fields
from openerp.tools.translate import _

class ref_generic_request(osv.osv_memory):

    # create a table in osv_memory, with the columns you need
    # to fill in your wizard
    _name = 'ref.generic.request'

    _columns = {
        'reformulation_info': fields.text(
            'Reformulation instructions',
            help='Instructions for the requestor justification the reformulation needs'),
            }

    # create a function that will save the info from your wizard into
    # your model (active_id is the id of the record you called the wizard
    # from, so you will save the info entered in wizard in that record)
    def save_info(self, cr, uid, ids, context=None):
        if 'active_id' in context:
            info = self.browse(cr, uid, ids)[0].reformulation_info
            gen_req = self.pool.get('generic.request')
            gen_req.write(
                    cr, uid, context['active_id'],
                    {'reformulation_info':info, 'needs_reformulation':1}
                    )
        return {'type':'ir.actions.act_window_close'}
ref_generic_request()

rawDescription: OpenERP wizard syntax

description: OpenERP wizard syntax


code:
from sklearn.cross_validation import KFold

Xy = numpy.genfromtxt('yourfile.csv', delimiter=",")

# the next section provides the required
# training-validation set splitting but
# you can do it manually too, if you want

skf = KFold(len(Xy))

for train_index, valid_index in skf:
    ind_train, ind_valid = train_index, valid_index
    break

Xy_train, Xy_valid = Xy[ind_train], Xy[ind_valid]

X_train = Xy_train[:, 1:]
y_train = Xy_train[:, 0]

X_valid = Xy_valid[:, 1:]
y_valid = Xy_valid[:, 0]

...

# you can simply ignore the test sets in your case
return X_train, y_train, X_val, y_val #, X_test, y_test

rawDescription: numpy array from csv file for lasagne

description: Numpy array from csv file for lasagne


code:
import matplotlib
from matplotlib.cm import cool

def get_n_colors(n):
    return[ cool(float(i)/n) for i in range(n) ]

rawDescription: Convert categorical variable to color with Matplotlib


code:
from itertools import takewhile, count

def sum_func(func, n):
    return sum(takewhile(lambda x: x < n, (func(i) for i in count(1))))

rawDescription: Sum while in Python?

description: Sum while in Python


code:
def derivative2(input, axis, output, mode, cval):
    return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
return generic_laplace(input, derivative2, output, mode, cval)

rawDescription: What is the Laplacian mask/kernel used in the scipy.ndimage.filter.laplace()?


rawDescription: Python 3, Converting a string storing binary data to Int


rawDescription: Python regex endline

description: Python regex endline


code:
import unittest

class TestFoo(unittest.TestCase):
    def setUp(self): print('setup')
    def tearDown(self): print('teardown')
    def test_spam(self): pass
    def test_egg(self): pass
    def test_ham(self): pass

if __name__ == '__main__':
    import sys
    loader = unittest.loader.defaultTestLoader
    runner = unittest.TextTestRunner(verbosity=2)
    suite = loader.loadTestsFromModule(sys.modules['__main__'])
    for ts in suite:
        for t in ts:
            if t.id().endswith('am'): # To skip `test_spam` and `test_ham`
                setattr(t, 'setUp', lambda: t.skipTest('criteria'))
    runner.run(suite)

rawDescription: Skip unittest test without decorator syntax


code: timeit.timeit('1+1', 'import math', number=1000000)

rawDescription: Two very different but very consistent results from Python timeit


rawDescription: Parallel execution of class methods

description: Parallel execution of class methods


rawDescription: Numpy vectorize, using lists as arguments


code:
for i, item in enumerate(mylist):
    mylist[i] = item**2

rawDescription: for loop in Python

description: For loop in Python


rawDescription: get packet size in scapy / python

description: Get packet size in scapy / python


code:
[[x + y for x, y in zip(*row)] for row in zip(outgoing, incoming)]
from pprint import pprint
pprint(_)

rawDescription: Python - List comprehension with 2 for loops & a ADD AND operand


code:
from random import randint
from statistics import mean
from timeit import repeat
def standard(seq):
    """Trivial modification to standard method for removing duplicates."""
    seen = set()
    seen_add = seen.add
    return ["" if x in seen or seen_add(x) else x for x in seq]
def dedup(seq):
    seen = set()
    for v in seq:
        yield '' if v in seen else v
        seen.add(v)
def pedro(seq):
    """Pedro's iterator based approach to removing duplicates."""
    my_dedup = dedup
    return [x for x in my_dedup(seq)]
def srgerg(seq):
    """Srgerg's dict based approach to removing duplicates."""
    seen = dict()
    seen_setdefault = seen.setdefault
    return ["" if cell in seen else seen_setdefault(cell, cell) for cell in seq]
data = [randint(0, 10000) for x in range(100000)]
mean(repeat("standard(data)", "from __main__ import data, standard", number=100))
mean(repeat("pedro(data)", "from __main__ import data, pedro", number=100))
mean(repeat("srgerg(data)", "from __main__ import data, srgerg", number=100))

rawDescription: How do you remove duplicates from a list in Python whilst preserving order and length?

description: Remove duplicates from a list in Python whilst preserving order and length


code:
import datetime
datetime.datetime.now()
import time
def mytime(): return 120000000.0
time.time = mytime
datetime.datetime.now()

rawDescription: How to change the date/time in Python for all modules?

description: Change the date/time in Python for all modules


code: ssa_flat = set(ssa_flat)

rawDescription: compare two lists and return not matching items

description: Compare two lists and return not matching items


code:
import numpy as np
import pandas as pd

df = pd.read_csv('data')
df = df.replace(r' ', np.nan)
#    id   fruit1   fruit2   fruit3
# 0   1    apple   orange      NaN
# 1   2   orange      NaN      NaN
# 2   3   banana    apple      NaN

melted = pd.melt(df, id_vars=['id'])
result = pd.crosstab(melted['id'], melted['value'])
print(result)

rawDescription: How to build "many-hot" in Python/Pandas?

description: Build "many-hot" in Python/Pandas


code: df1.to_csv('myfile.csv', index=False)

rawDescription: Python: Calculating Average and Standard deviation for every hour in csv file


code:
import functools

@functools.total_ordering
class Compare(object):
    def __init__(self, chunk):
        self.x = chunk[7], int(chunk[5]) - int(chunk[6]), chunk[5]
        self.y = chunk[0]
    def __eq__(self, other):
        return (self.x==other.x) and (self.y==other.y)
    def __lt__(self, other):
        if self.x != other.x:
            return self.x < other.x
        return self.y > other.y

rawDescription: Python - Sorting Lists

description: Python - Sorting Lists


code: np.asarray([123], dtype='|S2')

rawDescription: Python/Numpy - Save Array with Column AND Row Titles


rawDescription: Python: extract MSB and LSB than convert in float


code:
def generate_with_padding(tobeiterated, n, pad = None):
     count = 0
     for x in tobeiterated:
         count = count + 1
         yield x
     for _ in xrange(n - count):
         yield pad

rawDescription: Iterating with padding

description: Iterating with padding


rawDescription: Merge dictionaries retaining values for duplicate keys


code:
def better_split(s, seprators):
    assert isinstance(seprators, str), 'seprators must be string'
    buf = [s]
    for sep in seprators:
        for loop, text in enumerate(buf):
            buf[loop:loop+1] = [i for i in text.split(sep) if i]
    return buf

rawDescription: Unexpected behavior of a function built to replace split ()


code:
class YearComparator(ColumnProperty.Comparator):
    def __eq__(self, year):
        if isinstance(year, int):
            column = self.prop.columns[0].get_children()[0].expr
            start = datetime.date(year, 1, 1)
            end = datetime.date(year, 12, 31)
            return column.between(start, end)
        else:
            # It can be a column or exression which we can't handle such way
            return ColumnProperty.Comparator.__eq__(self, year)
    # __lt__, __gt__ etc. are very similar to __eq__

def year_property(date_column, **kwargs):
    kwargs.setdefault('comparator_factory', YearComparator)
    return column_property(extract('year', date_column), **kwargs)

class Foo(Base):
    __tablename__ = 'Foo'
    id = Column(Integer, primary_key=True)
    date = Column(Date, index=True)
    year = year_property(date)

rawDescription: SA: can I have a 'year' column_property for a Date column?


code:
import inspect
inspect.getmembers('')[20]
inspect.getmembers('')[20][1].__name__

rawDescription: How to get name from method-wrapper, builtin_function_or_method types for inspect.getmembers predicate

description: Get name from method-wrapper, builtin_function_or_method types for inspect.getmembers predicate


rawDescription: Subdivide integers using a given ratio without producing floats


rawDescription: Python on windows, open plot windows next to each other


code:
st = os.stat(dest_file)
os.chmod(dest_file, st.st_mode & ~stat.S_IWUSR)

rawDescription: How to implement chmod u-w in python

description: Implement chmod u-w in python


code:
setup(...,
      download_url='https://github.com/USER/PROJECT/tarball/master')

rawDescription: How to configure setup.py to have pip install from GitHub master?

description: Configure setup.py to have pip install from GitHub master


code:
q = "MATCH (n:Node) RETURN n"
result = graph.cypher.execute(q)
my_node = result[0][0]

while True:
    my_node.pull()
    print(my_node)

rawDescription: Is py2neo caching burning me?

description: Is py2neo caching burning me


code: output = [num for char, num in zip(str1, ls1) if char != '-']

rawDescription: Masking a list against a string in Python


code:
import multiprocessing as mp
import time

def foo_pool(x):
    time.sleep(2)
    return x*x

result_list = []
def log_result(result):
    # This is called whenever foo_pool(i) returns a result.
    # result_list is modified only by the main process, not the pool workers.
    result_list.append(result)

def apply_async_with_callback():
    pool = mp.Pool()
    for i in range(10):
        pool.apply_async(foo_pool, args = (i, ), callback = log_result)
    pool.close()
    pool.join()
    print(result_list)

if __name__ == '__main__':
    apply_async_with_callback()

rawDescription: Python multiprocessing.Pool: when to use apply, apply_async or map?


code:
ns = {'ss': 'THE_VERY_SAME_REALLY_LONG_STRING_AS_ROOT', 'd': 'SOME_REALLY_LONG_STRING'}

element = root.xpath('//d:SomethingIWant', namespaces=ns)[0]
print(etree.tostring(element))

attribute = element.xpath('@ss:Name', namespaces=ns)[0]
print(attribute)

rawDescription: How to get an attribute of an Element that is namespaced

description: Get an attribute of an Element that is namespaced


code:
class TimeDeltaProperty(db.Property):
  def get_value_for_datastore(self, model_instance):
    value = self.__get__(model_instance, model_instance.__class__)
    if value is not None:
      return timedelta_to_microtime(value)

  def make_value_from_datastore(self, value):
    if value is not None:
      return datetime.timedelta(microseconds=value)

rawDescription: timedelta convert to time or int and store it in GAE (python) datastore

description: Timedelta convert to time or int and store it in GAE (python) datastore


rawDescription: Reverse a list without reversed command

description: Reverse a list without reversed command


code:
m = np.arange(12).reshape(3,4)
m = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype)))
m

rawDescription: Adding a new column to a list of matrixs(arrays)


code:
n = 1
while User.objects.exclude(pk=instance.pk).filter(username=username).exists():
    n += 1
    username = user_email[:(29 - len(str(n)))] + '-' + str(n)
instance.username = username

rawDescription: django-allauth set username the same as email

description: Django-allauth set username the same as email


code: b = [i[:] for i in a]

rawDescription: Two lists are printing the same thing when I expected them to print differently


code:
import re
myString = "No aprobó ni está inscripto a Sistemas Operativos (Ord. 1150)"
result = re.search('No aprobó ni está inscripto a ([^()]*)( \(Ord\. 1150\))?', myString)
course = result.group(1) # may have a trailing space, so maybe strip()

rawDescription: What's the correct regex for this?

description: What's the correct regex for this


code: ' '.join([i for i in query.split() if not any(w in i.lower() for w in seeds)])

rawDescription: python, remove words in a string from a list

description: Python, remove words in a string from a list


code:
trans_table = {ord(u'\u20ac'): None, ord(u','): u'.'}
my_prices = [price.text.translate(trans_table)
                for price in data.find_all("example", {"class":"example"})]

rawDescription: How to change text to digits and save into array in Python

description: Change text to digits and save into array in Python


code:
from ipaddress import ip_address
ip_dotted = str(ip_address(ip_dec))

rawDescription: Sqlalchemy change decimal IP address to dotted


code:
import scrapy
from scrapy.pipelines.images import ImagesPipeline

class NgaImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        # use 'accession' as name for the image when it's downloaded
        return [scrapy.Request(x, meta={'image_name': item["accession"]})
                for x in item.get('image_urls', [])]

    # write in current folder using the name we chose before
    def file_path(self, request, response=None, info=None):
        return '%s.jpg' % request.meta['image_name']

rawDescription: Change Naming Convention for Images Pipeline


code:
myList = ['a','b','c','d']
myString = ",".join(myList )

rawDescription: How would you make a comma-separated string from a list?


code:
collections.Counter(stringToData).most_common(1)[0]
#output: for example: ('f', 5)

rawDescription: Pretty-printing data from counter - Python


code:
import logging
import test2
import multiprocessing as mp

logger = mp.get_logger()

def main():
    logger.info('Script is running')
    logger.info('Calling script test2')
    proc = mp.Process(target = test2.main)
    proc.start()
    proc.join()

if __name__ == '__main__':
    formatter = logging.Formatter('[%(asctime)s] [%(filename)s]: %(message)s',
                                  datefmt = '%H:%M:%S')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    main()

rawDescription: How to print log messages from external modules to the main Python module's terminal window?

description: Print log messages from external modules to the main Python module's terminal window


code:
z=np.random.rand(10)
z
mask = (z >= 0.3) & (z < 0.6)
mask
z * mask
np.count_nonzero(z * mask)
np.extract(mask, z)
len(np.extract(mask, z))

rawDescription: Using Numpy to Count Numbers in a range

description: Using Numpy to Count Numbers in a range


code: Table(data, colwidths, rowheights)

rawDescription: What determines the vertical space in Reportlab tables?


code:
def fromcin(prompt=None):
  while True:
    try: line = raw_input(prompt)
    except EOFError: break
    for w in line.split(): yield w

rawDescription: How to simply read in input from stdin delimited by space or spaces

description: Simply read in input from stdin delimited by space or spaces


code:
import ctypes
import sys
import time
import threading

lib = ctypes.cdll.LoadLibrary('./test.so')
val = ctypes.c_uint64(0)

def loop():
    lib.dostuff(ctypes.byref(val))

t1 = threading.Thread(target=loop)
t1.start()

for i in range(1000):
    sys.stdout.write('%s ' % val.value)
    sys.stdout.flush()
    time.sleep(0.05)

rawDescription: How to call a dll function in parallel in Python

description: Call a dll function in parallel in Python


code: [int(val.img is not None) for val in row.find_all('td')]

rawDescription: Evaluate image in html table using Python


rawDescription: How to update the state of tkiner menu cascade or command?

description: Update the state of tkiner menu cascade or command


code:
def __init__(self, *args, **kwargs):
    context_key = hash('{0}{1}'.format(cPickle.dumps(args),cPickle.dumps(kwargs)))
    self.__dict__ = self.__shared_state.setdefault(context_key, {})

rawDescription: Singleton/Borg pattern based on different parameters passed while creating the object


code:
form = PageForm(request.form)
# Than, access fields as form.<FIELD_NAME>.data

rawDescription: Flask form processing

description: Flask form processing


rawDescription: pandas, combining multiple dataframes

description: Pandas, combining multiple dataframes


code:
import numpy as np

from numpy import array
from itertools import combinations_with_replacement

for t in combinations_with_replacement(range(1, 50), 3):
    if reduce(gcd, t) != 1: continue

    v = array(map(float, t))
    u = v / np.linalg.norm(v)

    w = recover_integer_vector(u)

    assert np.allclose(w, v) or np.allclose(w, -v)

rawDescription: Denormalize unit vector

description: Denormalize unit vector


code:
import csv
from collections import defaultdict
with open('file.txt', 'r') as f:
    next(f)
    d = defaultdict(list)
    r = csv.reader(f,delimiter=" ")
    for row in r:
       d[row[0]].extend(map(int,row[1:]))

rawDescription: Populating dictionary from text file PYTHON


code:
class botfactory(Factory):

    def buildProtocol(self, addr):
        protocol = bottalk()
        protocol.factory = self
        return protocol

factory = botfactory()
factory.clients = []

StandardIO(factory.buildProtocol(None))

reactor.listenTCP(8123, factory)

rawDescription: how to kill twisted protocol instances python

description: Kill twisted protocol instances python


code: value /=2

rawDescription: Understanding bit-manipulation function in Python


code:
with io.open('Assets.log', 'w', encoding='utf-8') as f,\
        io.open(pathname, encoding='utf-8') as fin:
    f.write(u'File Path|Brand\n')
    lines = fin.read()
    brand_start = lines.find(u"Brand Title")
    brand_end = lines.find(u"/>", brand_start)
    brand = lines[brand_start + 47:brand_end - 2]
    f.write(u'{}|{}\n'.format(pathname[4:35], brand))

rawDescription: Struggling with unicode in Python

description: Struggling with unicode in Python


rawDescription: numpy type conversions for arrays vs. scalars

description: Numpy type conversions for arrays vs. scalars


code:
get_version("pyodbc")
get_version("pandas")
get_version("requests")
get_version("foobar")

rawDescription: How to check version of python package if no __version__ variable is set

description: Check version of python package if no __version__ variable is set


rawDescription: Unique content identifier with Selenium: InvalidSelectorError


code:
#bottle.py

def route(your_route):  #your_route <= '/static/<filepath:path>'

    def my_decorator(func):  #The decorator syntax will cause python to call this function with server_static as the argument

        def do_stuff(filepath):
            func(filepath)  #Call the server_static() function with the part of the url that matched filepath

        return do_stuff  #This function will be called when your code calls server_static(...)

    return my_decorator

rawDescription: How to use decorators (bottle.py)

description: Use decorators (bottle.py)


code:
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):

        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(root, borderwidth=0, background="#ffffff")
        self.frame = tk.Frame(self.canvas, background="#ffffff")
        self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)

        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas.create_window((4,4), window=self.frame, anchor="nw",
                                  tags="self.frame")

        self.frame.bind("<Configure>", self.onFrameConfigure)

        self.populate()

    def populate(self):
        '''Put in some fake data'''
        for row in range(100):
            tk.Label(self.frame, text="%s" % row, width=3, borderwidth="1",
                     relief="solid").grid(row=row, column=0)
            t="this is the second column for row %s" %row
            tk.Label(self.frame, text=t).grid(row=row, column=1)

    def onFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

if __name__ == "__main__":
    root=tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Adding a scrollbar to a group of widgets in Tkinter


code:
def fibR(n):
    if n > len(fibR.values) - 1:
        for i in range(len(fibR.values), n+1):
            fibR.values.append(fibR(i-2) + fibR(i-1))
    return fibR.values[n]

fibR.values = [0, 1, 1]
for i in range(1,6):
    print(fibR(i))

rawDescription: Fibonacci series in python 3 displays only final number