code:
import numpy as np
import pandas as pd

df_a = pd.DataFrame({ 'N0_YLDF': [11.79, 7.86, 5.78, 5.35, 6.32, 11.79, 6.89, 10.74]})
df_b = pd.DataFrame({ 'N0_YLDF':[6.29, 2.32, 9.10, 4.89, 10.22, 3.80, 5.55, 6.36] })

edges, labels = np.unique(df_b['N0_YLDF'], return_index=True)
edges = np.r_[-np.inf, edges + np.ediff1d(edges, to_end=np.inf)/2]
df_a['N0_DWOC'] = pd.cut(df_a['N0_YLDF'], bins=edges, labels=df_b.index[labels])
print(df_a)

rawDescription: Pandas merge dataframes based on closest match


rawDescription: pyqt and table widget clear contents

description: Pyqt and table widget clear contents


code:
class Position:
    def __init__(self, x, y):
        self.x = int(x)
        self.y = int(y)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    def __ne__(self, other):
        return not self == other

rawDescription: Python 3.2.2 custom object comparation fails


code:
def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

rawDescription: Removing html image tags and everything in between from a string


code:
from django.db import migrations

def lazy_discover_foreign_id_choices():
    if getattr(migrations, 'MIGRATION_OPERATION_IN_PROGRESS', False):
        return []
    # Leave the rest as is.

rawDescription: Detect whether code is being run in the context of migrate/makemigrations command


code:
def format_timedelta(td):
    minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

rawDescription: How can I display timedelta in hours:min:sec?

description: Display timedelta in hours:min:sec


rawDescription: Python3 Fast Way To Find If Any Elements In Collections Are Substring Of String


code:
class example(object):

    def __init__(self):
        self.veryImportantDict = {'A': 0}

test.veryImportantDict['A'] = 'foo'

rawDescription: unittest testcase setup new object

description: Unittest testcase setup new object


code:
print("*" * width_number)
for _ in range(length_number):
    print("*" + (" " * (width_number-2)+ "*") )
print("*" * width_number)

rawDescription: How can i make it draw a rectangle with dots?

description: Make it draw a rectangle with dots


code:
def solution(formation):
    return len([i for i in formation[formation.index(fCamel) + 1:] if i == bCamel]) == 0

rawDescription: How to proceed with this python program

description: Proceed with this python program


code:
expr1 = func.sum(
           case([(and_
             ((cast(pvr_svc.end_dt,DATE) == cast(func.getdate(),DATE)),
               pvr_svc.status.in_(['CLOSED','VOID'])
             ),1)],else_=0)
           ).label('com')

session.query(expr1).all()

rawDescription: SQLAlchemy : Convert to date type

description: SQLAlchemy : Convert to date type


code:
import xml.etree.cElementTree as ET
import numpy as np
e = ET.parse('trip_049.rou.xml')
root = e.getroot()

tdlist = []
for vehicle in root.findall('vehicle'):
    id = vehicle.get('id')
    origin = vehicle.get('fromTaz')
    destination = vehicle.get('toTaz')
    tdlist.append([id,origin,destination])

arraylst = np.array(tdlist)

rawDescription: python for loop output as array

description: Python for loop output as array


code:
from functools import reduce

reduce(lambda a,b: b(a), func_list, FIRST_ARG)

rawDescription: Call a list of functions recursively in python?


code:
graph = defaultdict(lambda: defaultdict(list))

with open('inputfile', 'rb') as infh:
    reader = csv.reader(infh, delimiter='\t')
    next(reader, None)  # skip header

    for source, target, edge in reader:
        graph[source][target].append(edge)

rawDescription: Python - directed edge list to dictionary of dictionaries


code: np.concatenate((np.arange(-5, 6)[None,...], np.correlate(x, y, 'full')[None,...]), axis=0)

rawDescription: Interpreting (and comparing) output from numpy.correlate


rawDescription: Reindex without changing order

description: Reindex without changing order


code:
from django.db.models.fields.related import ManyToManyField

def to_dict(instance):
    opts = instance._meta
    data = {}
    for f in opts.concrete_fields + opts.many_to_many:
        if isinstance(f, ManyToManyField):
            if instance.pk is None:
                data[f.name] = []
            else:
                data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
        else:
            data[f.name] = f.value_from_object(instance)
    return data

rawDescription: Convert Django Model object to dict with all of the fields intact


code:
ns = {"mvn":"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("mvn:version", ns))

rawDescription: Python ElementTree default namespace?

description: Python ElementTree default namespace


rawDescription: How to populate shelf with existing dictionary

description: Populate shelf with existing dictionary


code:
patterns = ["abc", "123"]
# initialize one Counter for each pattern
results = {pattern:Counter() for pattern in patterns}
for line in myfile:
   for pattern in patterns:
       if pattern in line:
           results[pattern][line] += 1

rawDescription: Count lines matching different patterns in one pass


code: sorted(nums, key=lambda x: tuple(reversed(list(map(int, x.split("/"))))))

rawDescription: How to sort tire sizes in python

description: Sort tire sizes in python


code:
xnew = np.arange(0,9, 0.1)
ynew = f(xnew)   # use interpolation function returned by `interp1d`

rawDescription: retrieve values from interpolation object

description: Retrieve values from interpolation object


code:
t0 = t.time()
esfera.add_orientation()
t1 = t.time()
dif = t1-t0
dif
Out[18]: 0.34514379501342773

t0 = t.time()
esfera.add_orientation2()
t1 = t.time()
dif = t1-t0
dif
Out[20]: 0.291456937789917

rawDescription: How to efficiently compute orientation of 3D normals in large pointclouds

description: Efficiently compute orientation of 3D normals in large pointclouds


code: print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + re.escape(r'C:\Path\To\File.iss'), '#define RootDir foo/bar/baz'))

rawDescription: Python 3: How can I get os.getcwd() to play nice with re.sub()?


code:
if isinstance(x, int):
    y = [x]
else:
    y = list(x)

rawDescription: converting an int to a list containing the int

description: Converting an int to a list containing the int


code:
import re

chevrons = re.compile("(?m)^[> ]*")
stripped = re.sub(chevrons, "", decoded)

rawDescription: Regex to Filter out ">" and "=20" from email.message_from_string


code: df

rawDescription: associating entries from one pandas data frame to a second one based on time

description: Associating entries from one pandas data frame to a second one based on time


code:
class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ABCD:
    def __init__(self, abc, d):
        # How to initialize the base class with abc in here?
        self.abc = abc

abc = ABC(1, 2, 3)
abcd = ABCD(abc, 4)
print(abcd.abc.a)

rawDescription: Copy constructing a base class from an instance in Python


code:
lst=['3a', '4a', '5a', '6a', 'Ca', 'Da', '4b','5b', '6b', '7b', '7c', '8c']
prev = lst[0][-1]
streak = 1
streaklst = [lst[0]]
matches = []
for x in lst[1:]:
    if x[-1] == prev and streak < 4:
        streak += 1
        streaklst.append(x)
    else:
        if streak == 4:
            matches.append(streaklst)
        streaklst = [x]
        streak = 1
        prev = x[-1]

print(matches)

rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


rawDescription: How to mixing two dictionaries in Python?

description: Mixing two dictionaries in Python


code:
data['beta'][1]
data[1]['beta']

rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


code:
s = '''
<Departments orgID="123" name="xmllist">
    <Department>
        <orgID>124</orgID>
        <name>A</name>
        <type>type a</type>
        <status>Active</status>
            <Department>
                <orgID>125</orgID>
                <name>B</name>
                <type>type b</type>
                <status>Active</status>
                <Department>
                    <orgID>126</orgID>
                    <name>C</name>
                    <type>type c</type>
                    <status>Active</status>
                </Department>
            </Department>
    </Department>
    <Department>
        <orgID>109449</orgID>
        <name>D</name>
        <type>type d</type>
        <status>Active</status>
    </Department>
</Departments>
'''

rawDescription: get all parents of xml node using python

description: Get all parents of xml node using python


code:
url(
    r'^account/login/$',
    login,
    {'template_name': 'login.html'},
    name='login'
)

rawDescription: url patterns like in two scoops of django

description: Url patterns like in two scoops of django


code:
from itertools import islice

headers_count = 5
chunk_size = 250000

with open('file') as fin:
  headers = list(islice(fin, headers_count))

  part = 1
  while True:
    line_iter = islice(fin, chunk_size)
    try:
      first_line = line_iter.next()
    except StopIteration:
      break
    with open('part%d' % part, 'w') as fout:
      for line in headers:
        fout.write(line)
      fout.write(first_line)
      for line in line_iter:
        fout.write(line)
    part += 1

rawDescription: chunk a text database into N equal blocks and retain header

description: Chunk a text database into N equal blocks and retain header


code:
path = ["Work", "Python Workspace", "Android_API_Parser", "test.txt"]
f = 'D:'
for p in path:
  f = os.path.join(f, p)
  print(f)
  assert os.path.exists(f)
assert os.path.isfile(f)

rawDescription: Python os.isfile assert failing

description: Python os.isfile assert failing


code:
word = input("What's the word ?")
if len(word)<7:
    raise ValueError("Please enter a word greater than 6 characters")
print(word[:3] + '.'*(len(word)-6) + word[-3:])

rawDescription: Parameter Expansion With Python

description: Parameter Expansion With Python


code: avg_price = float( data['average_price']['value'] )

rawDescription: Trouble parsing API JSON output with python using 'requests'


code:
def f(n):
    return n**2
sqr = f

def f(n):
    return n**3
cube = f

rawDescription: How to get function object inside a function (Python)

description: Get function object inside a function (Python)


code:
g=np.random.randint(0,5,(4,4))
g
k=np.arange(5)*-1
k
k[g]   #Uses indices of g to select values from k. Also same as np.take(k,g)

rawDescription: Getting indices from numpy array and applying to 2nd lower dimensional array to create new array


code:
plot(x,y)
xlim(0,1000)

x_av = movingaverage(interval, r)
plot(x_av, y)

xlabel("Months since Jan 1749.")
ylabel("No. of Sun spots")
show()

rawDescription: Finding moving average from data points in Python


code: [Record(*t) for t in zip(*(d[k] for k in keys))]

rawDescription: 'Zip' dictionary of lists in Python

description: 'Zip' dictionary of lists in Python


code:
locations.apply(
    lambda row: find_station(row['Latitude'], row['Longitude']),
    axis=1)

rawDescription: How to find the closest match based on 2 keys from one dataframe to another?

description: Find the closest match based on 2 keys from one dataframe to another


code: ('.png' or '.jpg' or 'jpeg')

rawDescription: Python logical or operator acting strange


rawDescription: Need Help Writing Recursive function that find cheapest route through a list of numbers


code:
n, isodd = divmod(len(L), 2)
print(zip(L[:n], reversed(L[n + isodd:])))
if isodd: # number is perfect square
   print((L[n], L[n]))

rawDescription: All possible pairs of factors

description: All possible pairs of factors


code:
def dot(X, Y, d):
    total = 0
    for x, y in zip(X, Y):
        total += x * y
        if total > d:
            return -1
    return total

rawDescription: solve particular symbolic equation in python

description: Solve particular symbolic equation in python


rawDescription: Right way to SkipTo not empty tokens with ZeroOrMore in pyparsing


code:
from itertools import chain

per_id = {}
for info in chain(list1, list2):
    per_id.setdefault(info['id'], {}).update(info)

output = list(per_id.values())  # Python 2 and 3 compatible

rawDescription: How to remove a json string from list in python

description: Remove a json string from list in python


rawDescription: In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?


code:
class parent(object):
    findMe = False

class childone(parent):
    ...

rawDescription: How can one locate where an inherited variable comes from in Python?


code:
class Planet(object):
    def __init__(self, *args, **kwargs):
        self.name = args[0]
        self.distance = args[1]
        # ... etc ...

rawDescription: Turning list of lists into objects

description: Turning list of lists into objects


code:
import iscpy

# Read in an existing config file
with open('/tmp/named.conf') as input_config_file:
    config_string = input_config_file.read()
config_dict = iscpy.ParseISCString(config_string)

# Modify the configuration
config_dict['zone "example.com"'] = {
    'file':'"zone/example.com"',
    'type':'master'
}

# Write out the new config
config_string = iscpy.MakeISC(config_dict)
with open('/tmp/named-new.conf', 'w') as output_config_file:
    output_config_file.write(config_string)

rawDescription: Using python iscpy module

description: Using python iscpy module


code:
workers = [pool.apply_async(f, args=(i,)) for i in range(num_workers)]
for w in workers:
    w.get()

rawDescription: My python multiprocessing program runs the worker programs sequentially


code: super(InfoOT, self).__init__(parent)

rawDescription: Use class variable in another class

description: Use class variable in another class


code:
def empty():
    pass

empty_code = empty.__code__.co_code

def is_empty(func):
    return hasattr(func, '__code__') and func.__code__.co_code == empty_code

rawDescription: Detecting blank/empty function in cpython calls?


code:
class Parent(object, metaclass=AllVMeta):
    V_1 = set()
    V_2 = set()

class Child1(Parent):
    V_1 = {1, }
    V_2 = {4, 7, 10}

class Child2(Parent):
    V_1 = {'a', 'b'}
    V_2 = {'a', 'c'}

rawDescription: Class variable V3 dependent on V1 and V2. How to define V3 in children classes


code:
from matplotlib.ticker import *
figure(num=None, figsize=(20, 10))

plt.title('Cumulative Distribution Function for ALABAMA population')
plt.xlabel('City')
plt.ylabel('Percentage')
plt.plot(al_df.pop_cum_perc)

#set the tick size of y axis
ax = plt.gca()
ax.yaxis.set_major_locator(MultipleLocator(0.1))

#set the labels of y axis and text orientation
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.set_xticklabels(labels, rotation =90)

rawDescription: plotting & formatting seaborn chart from pandas dataframe

description: Plotting & formatting seaborn chart from pandas dataframe


code: from package.subpackage2 import module2b

rawDescription: Is it really possible to use a different convention to lay out source directory without breaking intra-package references?


rawDescription: reshaping ndarrays versus regular arrays in numpy?

description: Reshaping ndarrays versus regular arrays in numpy


code:
import numpy as np
from scipy.optimize import nnls

A = np.array([[1, 2, 0],
              [0, 4, 3]])
b = np.array([-1, -2])

print(nnls(A, b))
# (array([ 0.,  0.,  0.]), 2.23606797749979)

rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
class Class1(object):
    def __init__(self):
        self.list1, self.list2, self.list3, self.list4 = [], [], [], []
    def func3 (value):
        self.list3=[]
        self.list4=[]
        #do some operations based on value (that presumably modify list3/list4)
    def func2(self, value):
        self.list1=[]
        self.list2=[]
        #do some operations based on value (that presumably modify list1/list2)
        self.func3(value) # this sets self.list3 and self.list4
    def func1(self):
        value =20
        self.func2(value)
        #func1 now has access to the same self.list3 and self.list4 as func2

rawDescription: Returning function values based on argument?


code:
class TeamAdmin(admin.ModelAdmin):
    form = TeamAdminForm

rawDescription: How can I extend a django admin widget so it's still optional?

description: Extend a django admin widget so it's still optional


code: df.replace({'prefix': {r'^(H|HR|H\*)$': 'h', r'^(S|SR|S\*)$': 's'}}, regex=True, inplace=True)

rawDescription: Pandas: How to edit values in a column

description: Pandas: How to edit values in a column


code:
s = df.groupby(level='A').cumcount() / df.groupby(level='A').size()
df['new'] = 'H'
df.loc[s>=0.5, 'new'] = 'L'

rawDescription: Spliting multi-index indices around a given level


code:
from operator import itemgetter
[key for key,value in sorted(dic.items() ,key= itemgetter(1) ) if value < threshold]

rawDescription: in Python, dictionary sort by value, but only return key

description: In Python, dictionary sort by value, but only return key


code: [item for item in iterable if function(item)]

rawDescription: Python 3.4 nested loop using lambda filter working weirdly


code:
ignore = frozenset([5, 17])
b = word in (w for i, w in enumerate(wordList) if i not in ignore)

rawDescription: python check if word is in certain elements of a list

description: Python check if word is in certain elements of a list


code: __builtins__.help = partialhelper

rawDescription: Allow help() to work on partial function object


rawDescription: Escape string to be valid python expression


code:
import subprocess

def get_stdout(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    result = []
    p.stdout.readline() # reads the first line
    line = p.stdout.readline() # reads the second line
    tag = line.split(' ')[0]
    print(tag)
get_stdout('show images')

rawDescription: How do I capture a specific word on a bash screen using Python?

description: Capture a specific word on a bash screen using Python


code:
def function_reader(path):
    line_no = 0
    with open(path, "r") as myfile:
        def readline():
            nonlocal line_no
            line_no += 1
            return myfile.readline()

rawDescription: Scope of nested function declarations

description: Scope of nested function declarations


code:
for line in iter(sys.stdin.readline, ''):
    print(line, end='')

rawDescription: python cat (echo) equivalent for stdin

description: Python cat (echo) equivalent for stdin


code: pygame.draw.rect(self.surface, (100, 10, 10), (self.pos[0], self.pos[1], self.size, self.size))

rawDescription: Pygame doesn't draw

description: Pygame doesn't draw


code:
def to_nested_dict(row):
    res = {}
    for col in row.index:
        outer_key, inner_key = col.split('_')
        outer = res.setdefault(outer_key, {})
        outer[inner_key] = row[col]
    return res

list(df.apply(to_nested_dict, axis=1))

rawDescription: Pandas Group Columns into Level

description: Pandas Group Columns into Level


code:
from collections import defaultdict
lst = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
dct = defaultdict(list)
for x, y in lst:
    dct[x] += y
dct

rawDescription: How would I make a dictionary from a list of tuples?


code: Enum('boolean_enum', [('TRUE', True), ('FALSE', False)])

rawDescription: Python Enum for Boolean variable

description: Python Enum for Boolean variable


code: qs={k:v for k,v in [l.split('=') for l in os.environ['QUERY_STRING'].split('&')]}

rawDescription: Access Request Parameters in invoked script of Python CGIHTTPServer


code:
def rotated_integrand(rs):
    R, r = rs
    x = R + r/2.0
    y = R - r/2.0
    return integrand(np.array([x,y]))

rawDescription: efficiently caclulating double integral

description: Efficiently caclulating double integral


code:
import re

options = re.DOTALL | re.MULTILINE
contents = open('parsexample.txt').read()
m = re.search('ga_group_create(.*)ga_group_create', contents,
              options)
lines_in_between = m.groups(0)[0].split()

rawDescription: A rather special parsing of a txt file

description: A rather special parsing of a txt file


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code: cln['Record Number'].astype(float)

rawDescription: python drop non-integer rows, convert to int

description: Python drop non-integer rows, convert to int


code: text = "\n\n#bogus\nTags: #foo #bar\n"

rawDescription: Regex to Extract #hashtags from MMD metadata in Python


code:
df = read_csv(StringIO(data),sep='\s+',header=None,parse_dates=[1],names=['num','date']).set_index('num')
df
df.dtypes

rawDescription: Converting column from int64 to datetime in hdf5 file using Python's Pandas package


code:
import heapq

class ExpiringCache(object):
    def __init__(self):
        self._dict = {}
        self._heap = []

    def add(self, key, expiry):
        self._dict[key] = expiry
        heapq.heappush(self._heap, (expiry, key))

    def contains(self, key):
        return key in self._dict

    def collect(self, maxage):
        while self._heap and self._heap[0][0] <= maxage:
            expiry, key = heapq.heappop(self._heap)
            if self._dict.get(key) == expiry:
                del self._dict[key]

    def items(self):
        return self._dict.items()

rawDescription: Ideal data structure with fast lookup, fast update and easy comparison/sorting


code:
for rline in revOut.stdout:
    if "Nmap scan report for " in rline:
        ...
    elif "MAC Address: " in rline:
        ...
    yield revNmapName, rip, rnmapmac

rawDescription: Python 2.7 returning values each time through the loop


code: a.repeat(2, axis=1)

rawDescription: stretch, scale, or double up an array with numpy?

description: Stretch, scale, or double up an array with numpy


code:
def org_app(gr,t):
    new_gr = np.zeros((height,width))
    for h in xrange(1, height-1):
        for w in xrange(1, width-1):
            new_gr[h][w] = gr[h][w] + gr[h][w-1] + gr[h-1][w] + t * gr[h+1][w-1]-2 * (gr[h][w-1] + t * gr[h-1][w])
    return new_gr

def proposed_app(gr,t):
    kernel = -np.array([[0,1-2*t,0],[-1,1,0,],[t,0,0]])
    out = np.zeros((height,width))
    out[1:-1,1:-1] = signal.convolve2d(gr, kernel, mode='same')[1:-1,:-2]
    return out

rawDescription: Converting a nested loop calculation to Numpy for speedup


code:
import csv
with open(csvfile, 'rb') as contactsfile:
    # sniff for dialect of csvfile so we can automatically determine
    # what delimiters to use
    try:
        dialect = csv.Sniffer().sniff(contactsfile.read(2048))
    except:
        dialect = 'excel'
    # get_total_jobs(contactsfile, dialect)
    contactsfile.seek(0)
    contacts = csv.DictReader(contactsfile, dialect=dialect, skipinitialspace=True,
                              quoting=csv.QUOTE_MINIMAL, doublequote=True)
    # Start reading the rows
    for row in contacts:
        for key, value in row.iteritems():
            print("{}={}".format(key,value))

rawDescription: Python CSV module handling comma within quote inside a field


code:
@cache.cached(timeout=50)
def big_foo():
    return big_bar_calc()

rawDescription: Using render_templete and static file, which one is faster in Flask


code:
class MockQuery(object):
    def all(self):
        return [1,2]

rawDescription: Mocks or Stubs?

description: Mocks or Stubs


code:
def reach(node_tree, path):
   tokens = path.split("/")
   current_node = node_tree
   for name in tokens:
      if len(current_node.children) == 0 and current_node.state != "expanded":
         current_node.expand()
      candidates = [child for child in current_node.children if child.item.GetText() == name]
      if len(candidates) == 0:
         print("did not find '{}'".format(name))
         return
      current_node = candidates[0]
   current_node.select()

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
from binascii import unhexlify

def long_to_bytes (val, endianness='big'):
    """
    Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
    convert ``val``, a :func:`long`, to a byte :func:`str`.

    :param long val: The value to pack

    :param str endianness: The endianness of the result. ``'big'`` for
      big-endian, ``'little'`` for little-endian.

    If you want byte- and word-ordering to differ, you're on your own.

    Using :ref:`string formatting` lets us use Python's C innards.
    """

    # one (1) hex digit per four (4) bits
    width = val.bit_length()

    # unhexlify wants an even multiple of eight (8) bits, but we don't
    # want more digits than we need (hence the ternary-ish 'or')
    width += 8 - ((width % 8) or 8)

    # format width specifier: four (4) bits per hex digit
    fmt = '%%0%dx' % (width // 4)

    # prepend zero (0) to the width, to zero-pad the output
    s = unhexlify(fmt % val)

    if endianness == 'little':
        # see http://stackoverflow.com/a/931095/309233
        s = s[::-1]

    return s

rawDescription: Convert python long/int to fixed size byte array


code:
x = random_mixture_model()
r1 = ROCData(x)
y = random_mixture_model()
r2 = ROCData(y)
lista = [r1,r2]
plot_multiple_roc(lista,'Multiple ROC Curves',include_baseline=True)

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


rawDescription: Putting biographical data in order from 4 parameters using python 3.3


code: re.compile('|'.join(['text' + str(i) + '.txt' for i in range(19, 22)]))

rawDescription: Python regex equivalent of bash's {1..4}


rawDescription: Pythonic way to split comma separated numbers into pairs


code: [x[0] for x in os.walk(directory)]

rawDescription: Getting a list of all subdirectories in the current directory


rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
num = 5
tag = 'input_%d' % num

rawDescription: Accessing unknown query arguments in Python


code:
mcmc = pm.MCMC([x, y_gen])
mcmc.sample(n_total_samples, n_burn_in)

x_trace = mcmc.trace('x')[:]
y_trace = mcmc.trace('y_gen')[:]

rawDescription: Getting the statistics of deterministic variables in PyMC


code:
import ast
ast.literal_eval('None') is None

rawDescription: Is there a simple way to convert the string "None" to a proper None variable in python?


code:
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]

rawDescription: Python : How to remove duplicate lists in a list of list?


code:
import matplotlib.pyplot as plt

def check_axes(plot_fn):
    def _check_axes_wrapped_plot_fn(axes=None, x=None, y=None):
        if not axes:
            fig = plt.figure()
            axes = fig.add_subplot(111)
            return plot_fn(axes, x, y)
        else:
            return plot_fn(axes, x, y)
    return _check_axes_wrapped_plot_fn

@check_axes
def line_plot(axes, x=None, y=None):
    axes.plot(x, y)

@check_axes
def bar_plot(axes, x=None, y=None):
    axes.bar(left=x, height=y)

rawDescription: use python decorator to automatically replace function argument default value?

description: Use python decorator to automatically replace function argument default value


code:
items_formset = inlineformset_factory(Parent, Item, form=ItemForm, extra=1)
item_forms = items_formset()

rawDescription: Add a dynamic form to a django formset using javascript in a right way


code:
for item in l:
   print(BeautifulSoup(item, "html.parser").get_text())

rawDescription: regex substitute html href and u tags in list (python)

description: Regex substitute html href and u tags in list (python)


code:
urlpatterns = patterns('social.views',
    url(
        r'^twitter/login/$',
        "twitter_login",
        name="twitter_login"
    ),

    url(r'^twitter/callback/$',
        "twitter_callback",
        name="twitter_callback"
    ),
)

rawDescription: How can I use Django Social Auth to connect with Twitter?

description: Use Django Social Auth to connect with Twitter


rawDescription: Attaching intensity to 3D plot

description: Attaching intensity to 3D plot


code:
def display_board(variable):
    """Display game board on screen."""
    print("\n\t", variable[0], "|", variable[1], "|", variable[2])
    print("\t", "---------")
    print("\t", variable[3], "|", variable[4], "|", variable[5])
    print("\t", "---------")
    print("\t", variable[6], "|", variable[7], "|", variable[8], "\n")

rawDescription: Return statements in python

description: Return statements in python


code:
{'team_link': u'http://espn.go.com/nba/team/_/name/bos/boston-celtics', 'team_name': u'Boston Celtics', 'team_stats_link': u'/nba/teams/stats?team=bos'}
{'team_link': u'http://espn.go.com/nba/team/_/name/bkn/brooklyn-nets', 'team_name': u'Brooklyn Nets', 'team_stats_link': u'/nba/teams/stats?team=bkn'}
...

rawDescription: Extract href given text of anchor tag using Xpath


code:
def blank_fn(*args, **kwargs):
    pass

rawDescription: lambda *args, **kwargs: None

description: Lambda *args, **kwargs: None


code: file_name = '%s.smil' % row['file_root_name']

rawDescription: Write file to directory based on variable in Python


code:
# Color matrix for RGB
RGBcolorMatrix = (
    x1, y1, z1, 0,
    x2, y2, z2, 0,
    x3, y3, z3, 0
)
img1 = img1.convert("RGB", RGBcolorMatrix)

rawDescription: Performing Photoshop's "Luminosity" filter programmatically


rawDescription: How to change the dtype of a numpy recarray?

description: Change the dtype of a numpy recarray


code: np.dot(X_test, res_wls.params)

rawDescription: How to add regression functions in python, or create a new regression function from given coefficients?

description: Add regression functions in python, or create a new regression function from given coefficients


code:
def test(event=None):
    button_map_set(x, y)
    button_map()

Button(..., command=test) # run `test(None)`
btn.bind("<Button-2>", test) # run `test(event)`

rawDescription: Button parameter “command” executes when declared, but not when pressed


rawDescription: NumPy reading file with filtering lines on the fly


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

rawDescription: Setting properties programmatically

description: Setting properties programmatically


code:
Entry.objects.bulk_create([
    Entry(headline="Django 1.0 Released"),
    Entry(headline="Django 1.1 Announced"),
    Entry(headline="Breaking: Django is awesome")
])

rawDescription: What is an efficent way of inserting thousands of records into an SQLite table using Django?


rawDescription: Compare equal length lists to find positions that share the same element


code:
import numpy as np

def my_sum(l, i):
    a, b, n = [v[0] for v in lst], np.array([v[1] for v in lst]), len(l)
    sums = np.zeros(n, dtype=np.int)
    for j in xrange(1, i + 1):
        sums[:n - j] += b[j: n]
    return zip(a[:-i], sums[:-i])

rawDescription: Data type for summing next few items

description: Data type for summing next few items


code:
@pyqtSlot()
def click_my_btn(self, sender):
    main_window.btn.hide()

rawDescription: PyQt change element in .ui file

description: PyQt change element in .ui file


code:
import ast
tuples1 = map(ast.literal_eval, tuples1)
tuples2 = map(ast.literal_eval, tuples2)

rawDescription: Comparing two tuples in two different file


code:
self.file_path = None
self.Button_open.clicked.connect(self.OpenTextFile)

rawDescription: Return value from button click

description: Return value from button click


code:
import weakref
class memo(DryDescriptor):
    _memo = None
    def __call__(self, method):
        self.getter = method
        return self

    def annotate(self, attr, attrs):
        if self.alias is not None:
            attrs[self.alias] = self

    def annotate_class(self, cls): pass

    def __get__(self, instance, owner):
        if instance is None:
            return self
        if self._memo is None:
            self._memo = weakref.WeakKeyDictionary()
        try:
            return self._memo[instance]
        except KeyError:
            return self._memo.setdefault(instance, self.getter(instance))

rawDescription: OO design: an object that can be exported to a "row", while accessing header names, without repeating myself


code: reap(lambda: sum(sow(x**2 + 1) if (x**2 + 1) % 2 == 0 else x**2 + 1 for x in xrange(1, 11)))

rawDescription: Python equivalent of Mathematica's Sow/Reap


code:
import math

class Point(object):
    def __init__(self, x, y, name=None):
        self.name = name
        self._x, self._y = x, y
        self.observers = []

    def observe(self, observer):
        self.observers.append(observer)

    def __repr__(self):
        return 'Point({}, {})'.format(self.x, self.y)

    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, value):
        self._x = value
        for o in self.observers:
            o.notify()

    @property
    def y(self):
        return self._y
    @y.setter
    def y(self, value):
        self._y = value
        for o in self.observers:
            o.notify()

class Segment(object):
    def __init__(self, p0, p1):
        self._p0, self._p1 = p0, p1
        p0.observe(self)
        p1.observe(self)

    def __repr__(self):
        return 'Segment({}, {})'.format(self.p0, self.p1)

    def notify(self):
        print('Length of {} changed to {}'.format(self, self.length()))

    def length(self):
        return math.sqrt((self.p0.x - self.p1.x)**2
                         + (self.p0.y - self.p1.y)**2)

    @property
    def p0(self):
        return self._p0
    @p0.setter
    def p0(self, point):
        self._p0 = point

    @property
    def p1(self):
        return self._p1
    @p1.setter
    def p1(self, point):
        self._p1 = point

rawDescription: Setting the property of a property

description: Setting the property of a property


code: num_true = sum(1 for condition in d.values() if condition)

rawDescription: Counting booleans in dictionary

description: Counting booleans in dictionary


code:
corners = []
for x in range(edgeRight, edgeLeft, interval):
  for y in range(edgeTop, edgeBottom, interval):
    corners.append((x,y))

rawDescription: Pygame: Snap-to-grid/board in chess

description: Pygame: Snap-to-grid/board in chess


code:
l = lambda x,y: (x if isinstance(x,list) else [x]) + (y if isinstance(y,list) else [y])
reduce(l, my_list)

rawDescription: Flatten a list and a string

description: Flatten a list and a string


code:
contents = open('example.json', 'rb').read()
r = requests.post(url, data=contents, headers=headers)

rawDescription: how to POST contents of JSON file to RESTFUL API with Python using requests module


code:
def find_or_add(model, session, **kwargs):
    if len(kwargs) > 0:
         obj = session.query(model).filter_by(**kwargs).first()
         if not obj:
             obj = model(**kwargs)
             session.add(obj)
    else:
         # Otherwise, let's create an empty one and add it to the session...
         obj = model()
         session.add(obj)
    return obj

def find_and_delete(model, session, **kwargs):
    deleted = False
    obj = session.query(model).filter_by(**kwargs).first()
    if obj:
        session.delete(obj)
        deleted = True
    return deleted

rawDescription: Proxy pattern idiom

description: Proxy pattern idiom


rawDescription: Building a general numpy array index dynamically


code:
@staticmethod
def foo():
    print(Foo.foo_string)

rawDescription: How to access class-scope variables without self?

description: Access class-scope variables without self


code:
a = Node("a")
b = Node("b")
a.add_child(a)
a.add_child(b)

rawDescription: Python - How do I write a more efficient, Pythonic reduce?


code:
import scipy.optimize as optimize
import numpy as np

A = np.array([(19,20,24), (10,40,28), (10,50,31)])

def func(data, a, b):
    return data[:,0]*data[:,1]*a + b

guess = (1,1)
params, pcov = optimize.curve_fit(func, A[:,:2], A[:,2], guess)
print(params)
# [ 0.04919355  6.67741935]

rawDescription: Fitting 3D points python

description: Fitting 3D points python


code:
import binascii
macbytes = binascii.unhexlify(addr.replace(b':', b''))

rawDescription: MAC address conversion into byte array in python


code:
day = tk.Entry(self,width=2)
self.day.grid(row=4,column=1,sticky="W",padx=2,pady=5)

rawDescription: Python 3.4 tkinter checkbutton variable handling not working / responding


code:
for p in intersect:
    columns_data.append( (n,el) )
    geoms.append(p)

rawDescription: Intersection of Two LineStrings Geopandas


code:
['# coding = utf-8\n', '\xe2\x80\x9chello se\xc3\xb1nor\xe2\x80\x9d']
['# coding = cp1252\n', '\xe2\x80\x9chello se\xc3\xb1nor\xe2\x80\x9d']

rawDescription: Read a unicode file in python which declares its encoding in the same way as python source


code:
def limit_files(file_list, at_a_time=10):
    d, r = divmod(len(file_list), at_a_time)
    num_keys = d + 1 if r > 0 else d

    iterator = iter(file_list)
    dictionary = {}
    for chunk_id in xrange(num_keys):
        chunk = list(itertools.islice(iterator, at_a_time))
        if not chunk:
            break
        dictionary[chunk_id] = chunk
    return dictionary

rawDescription: Split list into dictionary

description: Split list into dictionary


code:
i = np.r_[0, 1 + np.nonzero(np.diff(np.floor(t / .5)))[0]]
i

rawDescription: Digitize numpy array

description: Digitize numpy array


code:
text = 'the flory of gthys inhibition in this proffession by in aquaporin protein-1 its inhibition b , aquaporin protein-1'
a = 'aquaporin protein-1'
b = 'inhibition'
k1 = "_KEYWORD_1_"
k2 = "_KEYWORD_2_"
text = text.replace(a, k1)
text = text.replace(b, k2)
l = text.split()

d_idx = {k1:[], k2:[]}
for k,v in enumerate(l):
    if v == k1:
        d_idx[k1].append(k)
    elif v == k2:
        d_idx[k2].append(k)

distance = 5
data = []
for idx1 in d_idx[k1]:
    for idx2 in d_idx[k2]:
        d = abs(idx1 - idx2)
        if d<=distance:
            data.append((d,idx1,idx2))

rawDescription: [tricky]Searching for multiple occurrences of word pairs based on vicinity. Python


rawDescription: Python extract text data in dynamic text format


code:
import theano
import theano.tensor as T
import numpy as np

theano.config.exception_verbosity='high'
theano.config.optimizer='None'

def f(seq_v, prev_v):
    return seq_v*prev_v, seq_v+1

a = T.vector('a')

ini = T.constant(1, dtype=theano.config.floatX)

result, updates = theano.scan(fn=f,
                              outputs_info=[ini,None],
                              sequences=[a])

fn  = theano.function(inputs=[a], outputs=result)

A = np.arange(1,5, dtype=T.config.floatX)
out = fn(A)

print('Values:\nf:\t{}'.format(out))

rawDescription: Python - theano.scan() - return function values without feeding back into the loop


code:
res = df.set_index([cont, df.index])
res.index = res.index.set_levels(df.index[cont], 0)

rawDescription: Promote certain rows to index in an ordered pandas dataframe


code:
from flask import session, request

app = Flask(__name__)

@app.route('/getEmployees/<userid>')
def all(userid):

    # Allow the user to specify an offset via querystring
    offset = request.args.get('offset')

    # Allow user to specify limit but default to 50
    limit = request.args.get('limit', 50)

    if offset is None:
        # Look in the session and default to 0 if not defined
        offset = session.get('offset', 0)

    # Do your query
    g.db = connect_db()
    cur = g.db.execute('select * from employees limit %d offset %d' % (limit, int(offset)))
    entry = [dict(emp_no=row[0],birth_date=row[1],first_name=row[2],last_name=row[3],gender=row[4],hire_date=row[5]) for row in cur.fetchall()]
    g.db.close()

    # Store the current offset in the session so it is available next request
    session['offset'] = offset + limit;

    return str(entry)

rawDescription: flask , breaking query?

description: Flask , breaking query


rawDescription: Joining Words in String In-Place

description: Joining Words in String In-Place


code:
def load_object(d):
    if 'songid' in d:
        return d['label']
    keys = sorted(d)
    return namedtuple('X', keys)(*(d[k] for k in keys))

resultObject = json.loads(resultQuery, object_hook=load_object)

rawDescription: Creating a list from lists inside a namedtuple


code:
df.groupby('id', as_index=False).agg(lambda x: x.tolist())
df1.reset_index()

rawDescription: Concatenate rows of pandas DataFrame with same id


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

# Generate Data.
nobs, nvars = 100, 5
data = np.random.random((nobs, nvars))
columns = ['Variable {}'.format(i) for i in range(1, nvars + 1)]

# Make a pairplot:
fig, axes = plt.subplots(ncols=nvars, nrows=nvars, sharex='col', sharey='row')
for (i, j), ax in np.ndenumerate(axes):
    if i == j:
        ax.annotate(columns[i], (0.5, 0.5), xycoords='axes fraction',
                    ha='center', va='center', size='large')
    else:
        ax.scatter(data[:,i], data[:,j], color='lightblue')
    ax.locator_params(nbins=6, prune='both')

plt.show()

rawDescription: Python: Grid of 2D scatter plots (seaborn.PairGrid)


code:
def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':
   return 1/2*m*v**2

kinetic_energy.__annotations__

rawDescription: -> in python function definition

description: -> in python function definition


code:
G = numpy.bmat('C3, -numpy.eye(n), numpy.eye(n)')
h = numpy.bmat('C4, -C7, C8')

rawDescription: Python: porting to cvxopt quadratic programming from MATLAB's quadprog


code:
SPLASH_URL = 'http://192.168.59.103:8050'

DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

DUPEFILTER_CLASS = 'scrapyjs.SplashAwareDupeFilter'

rawDescription: Scraping dynamic content using python-Scrapy


code:
from scipy.sparse import coo_matrix
m = coo_matrix([[1, 2, 3], [4, 5, 6]])
m1 = m.tocsr()
m1[1, 2]
m1

rawDescription: Accessing elements in coo_matrix

description: Accessing elements in coo_matrix


code:
from django.db.models import Q

qstring = "%s|%s" % (probe_id, genotype)

subjects = Subject.objects.filter(Q(probe_results__pg_c_genotypes__contains=',%s,' % qstring) | \
                               Q(probe_results__pg_c_genotypes__startswith='%s,' % qstring) | \
                               Q(probe_results__pg_c_genotypes__endswith=',%s' % qstring))

rawDescription: Using Django with MySQL for storing and looking up Large DNA Microarray Results


code: [{'Description': '"The logging level for outputting to console. (1 - Critical, 2 - Warning, 3 - Info, 4 - Debug, 5 - Trace)"', 'PropertyName': 'com.bs.ConsoleLogLevel', 'Default': '3', 'Min': '1', 'Type': 'Integer', 'DependsOn': 'com.rim.bs.ConsoleLogEnable', 'Sample': 'com.bs.ConsoleLogLevel=5', 'Max': '5'}, {'Description': '"The supported protocols are: 1. udp -- The original syslog UDP protocol, pointed to 104.0.0.21 (localhost) 2. tcp -- An implementation of the de-facto TCP/IP syslog protocol, which points to a TCP-capable syslog server, defaulted to 104.0.021 (localhost). 3. unix_syslog -- Native syslog support for Unix platforms 4. unix_socket -- Native socket support for Unix platforms, pointed to the "/var/log" socket", ', 'PropertyName': 'com.rim.bs.SyslogProtocol', 'Default': 'tcp', 'Type': 'String', 'DependsOn': 'com.rim.bs.SyslogEnable', 'Sample': 'com.bs.SyslogProtocol=tcp'}]

rawDescription: converting list of list to list of dictionaries with a special case in it

description: Converting list of list to list of dictionaries with a special case in it


code:
def resizeEvent(self, event):
    # move to top-right corner
    self.widget.move(self.width() - self.widget.width() - 1, 1)
    super(Canvas, self).resizeEvent(event)

rawDescription: Relative QWidget position in parent - incorrect Y


code:
def mapNumber(a):
    return int(a + 1000) / 10

rawDescription: Mapping numbers

description: Mapping numbers


code: set(l)

rawDescription: Reducing pandas series with multiple nan values to a set gives multiple nan values


code:
#from itertools import ifilter as filter  # in python2

def iter_apply(func, value):
    while True:
        yield value
        value = func(value)

def until2(cond, func, starting):
    return next(filter(cond, iter_apply(func, starting)))

# or:

from itertools import dropwhile
def until3(cond, func, starting):
    iterated_values = iter_apply(func, starting)
    return next(dropwhile(lambda x: not cond(x), iterated_values))

rawDescription: Equivalent of Haskell "until" in Python

description: Equivalent of Haskell "until" in Python


code:
brown = LazyCorpusLoader(
    'brown', CategorizedTaggedCorpusReader, r'c[a-z]\d\d',
    cat_file='cats.txt', tagset='brown', encoding="ascii")

rawDescription: NLTK Brown Corpus - adding own tagged sentences


code:
write(self, file, encoding=None, method="xml",
          pretty_print=False, xml_declaration=None, with_tail=True,
          standalone=None, compression=0,
          exclusive=False, with_comments=True, inclusive_ns_prefixes=None)

rawDescription: Python 2.7 Etree/lxml minimizing

description: Python 2.7 Etree/lxml minimizing


rawDescription: numpy: syntax/idiom to cast (n,) array to a (n, 1) array?

description: Numpy: syntax/idiom to cast (n,) array to a (n, 1) array


code: gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))

rawDescription: pass dict by reference to bit encoded list of functions

description: Pass dict by reference to bit encoded list of functions


code:
def HexToByte( hexStr ):
    """
    Convert a string hex byte values into a byte string. The Hex Byte values may
    or may not be space separated.
    """
    # The list comprehension implementation is fractionally slower in this case
    #
    #    hexStr = ''.join( hexStr.split(" ") )
    #    return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
    #                                   for i in range(0, len( hexStr ), 2) ] )

    bytes = []

    hexStr = ''.join( hexStr.split(" ") )

    for i in range(0, len(hexStr), 2):
        bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )

    return ''.join( bytes )

rawDescription: How to parse .bin into list?

description: Parse .bin into list


code:
mything = B(your_parameters)
mything.do_that()

rawDescription: using a variable from a method of another class in python

description: Using a variable from a method of another class in python


code:
import time

filename = 'my_file.txt'
max_i = 10

for i in xrange(max_i):
    try:
        with open(filename, 'rb') as _:
            break
    except IOError:
        time.sleep(3)
else:
    raise IOError('Could not access {} after {} attempts'.format(filename, str(max_i)))

rawDescription: Python wait and check if file is created completely by external program


code: map(values.__getitem__, indices)

rawDescription: Extract list from given list and given indices


code:
from collections import defaultdict, OrderedDict
coring = defaultdict(OrderedDict)

for i,j in zip(score, match):
    coring[i][j]=None

coring

coring[7]
coring[7].keys()

rawDescription: if key, value pair exist in a dictionary skip python

description: If key, value pair exist in a dictionary skip python


code:
ListOf5=['one','two','three','four','five']
_,_,Third,_,Fifth=ListOf5
Third, Fifth

rawDescription: Is there a Python equivalent to Erlang's pattern matching?


rawDescription: Extracting 2 strings from regular expression Python


code:
s = 'Man learns not to give himself headaches using regex to deal with HTML'
from bs4 import BeautifulSoup
soup = BeautifulSoup(s)
soup.get_text()

rawDescription: Want to get part of string using regular expression


code:
import math
a = 1.23
math.modf(a)

rawDescription: How do you index a float value in Python?

description: Index a float value in Python


code:
monster_name = "Monster" + str(monster_id)
monster_id += 1
monsters[monster_name] = Monster()

rawDescription: Python: Name instance based on variable

description: Python: Name instance based on variable


code:
from django.db import models

class Users(models.Model):
    name = models.CharField(max_length=50)

rawDescription: How many time can django objects.filter Q() be used in one query?


code:
s = "Flat 12A High Rise 101B"
padding = 5
re.sub('\d+', lambda x:x.group().zfill(padding), s)

rawDescription: How to pad all the numbers in a string

description: Pad all the numbers in a string


code:
line = ['The', 'cat', 'chased', 'the', 'dog','the','dog']
from collections import Counter
output = {}
for i, item in enumerate(line):
    print(i, item, len(line))
    if i != len(line) - 1:
        output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1}))

print(output)

rawDescription: Making a dictionary for value in a dictionary in Python


code:
from pprint import pprint
[range(i, i + 10) for i in range(1, 102, 10)]
pprint(_)

rawDescription: How to generate groups of 10 consecutive numbers in a list?

description: Generate groups of 10 consecutive numbers in a list


code:
def line(bottles, ending):
    return "{0} {1} {2}".format(bottles,
                                plural("bottle", bottles),
                                ending)

rawDescription: How to reverse an int in python?

description: Reverse an int in python


code:
def split(self, arg=' '):
    result = []
    for item in super(Mine, self).split(arg):
        i = Mine(item)
        i.__dict__ = self.__dict__
        result.append(i)
    return result

rawDescription: How can I set and retain attributes on characters in a Python 2 string?

description: Set and retain attributes on characters in a Python 2 string


rawDescription: What is the best way to copy a list?

description: What is the best way to copy a list


rawDescription: Python Multiprocessing DictProxy append to dict of list not working


code:
theSum = df1.A + df1.B
theAverage = (df1.A + df1.B + df2.C + df3.D) / 4.
theProduct = df1.B * df2.C * df3.D
theResult = pd.concat([theSum, theAverage, theProduct])
theResult.columns = ['Sum', 'Average', 'Product']

rawDescription: Pandas: Applying Lambda to Multiple Data Frames


rawDescription: Using lambda expression to filter a string


rawDescription: Using ARPACK solving eigenvalueproblem, but getting inconsistent results with Matlab


code:
a,b  = 'abc abc','abc abc'
id(a)
id(b)
a is b

rawDescription: Why does a space effect the identity comparison of equal strings?


code:
#! python3
print('Hello World!')

rawDescription: How can I make the "python" command in terminal, run python3 instead of python2?

description: Make the "python" command in terminal, run python3 instead of python2


code: ret = pex.expect([r'^((?!' + re.escape(line) + ').)*$', pexpect.EOF, pexpect.TIMEOUT], timeout)

rawDescription: How do I get pexpect to match everything BUT a given line?

description: Get pexpect to match everything BUT a given line


code:
def __init__(self):
    self.counter = 0
    self.root = tk.Tk()
    self.frame = tk.Frame(self.root)
    # WRONG
    # self.frame = tk.Frame(self.root).grid(row=0, column=0)
    # RIGHT
    self.frame.grid() # row=0, column=0 comes by default

rawDescription: How to erase the contents of a Frame

description: Erase the contents of a Frame


code:
with open("/filepath/some_file_name.txt", "rb") as data:
    my_function(data)

rawDescription: How can I pass a .txt file as a function parameter

description: Pass a .txt file as a function parameter


code: self.countrychoice[-1] + "/" + self.citychoice[-1]

rawDescription: How do I get input out of a class and into the main script

description: Get input out of a class and into the main script


code:
lens = [len(item) for item in data]
A = np.concatenate((column_data,np.concatenate(data)))
_,idx = np.unique(A,return_inverse=True)

R = np.repeat(np.arange(len(lens)),lens)
C = idx[len(column_data):]

out = np.zeros((len(data), len(column_data)))
out[R,C] = 1

rawDescription: Efficiently filling NumPy array using lists of indices


code:
positive_nums_to_1M = range(1, 1000001)
1 in positive_nums_to_1M
1000000 in positive_nums_to_1M
0 in positive_nums_to_1M

rawDescription: Variable that represents all numbers in Python?


rawDescription: Create a bit mask

description: Create a bit mask


code:
brr=boundedlist(rr)
brr[4,3]
brr[4,6]
brr[-1,6]
brr[10,4]

rawDescription: Handling out of range list index in Python 2.7


code:
for item in range(*some_slice.indices(len(sequence))):
    print(sequence[item])

rawDescription: How do I access the elements of a slice object in python

description: Access the elements of a slice object in python


code: ','.join([s.strip() for s in list_of_strings])

rawDescription: Formatting an unordered string in python


code:
import sys
from PyQt4 import QtGui, QtSvg

app = QtGui.QApplication(sys.argv)
svgWidget = QtSvg.QSvgWidget('Zeichen_123.svg')
svgWidget.setGeometry(50,50,759,668)
svgWidget.show()

sys.exit(app.exec_())

rawDescription: Simple way to display SVG image in a PyQt window


code:
def generate_combinations( *args, **kwargs ):
    print("called with", args)
    #terminate recursion
    if len(args) == 1:
        return list(set(args[0]))

    #recursion
    else:
        result = []
        args = list(args)
        heads = args.pop(0)
        tails = generate_combinations( *args, **kwargs )
        for head in heads:
            for tail in tails:
                result.append(head + tail)
        return result

if __name__ == '__main__':
    allDigits = [ '1', '2', '3' ]
    lastDigit = [ '4', '5' ]
    letters   = [ 'a', 'b' ]
    print("{}".format( generate_combinations( allDigits, lastDigit, letters , Useless='parameter')))

rawDescription: Variable number of arguments and recursion in Python


rawDescription: Python: Compare Filenames in Folder

description: Python: Compare Filenames in Folder


code:
# Local code:
win = pg.GraphicsWindow()
p1 = win.addPlot()
p2 = win.addPlot()

# Remote code:
win = rpg.GraphicsWindow()
p1 = win.addPlot()
p2 = win.addPlot()

rawDescription: implementing pyqtgraph for live data graphing

description: Implementing pyqtgraph for live data graphing


code: ['test.py', 'some string', 'some string2', '']

rawDescription: How to pass empty argument to Popen (with shell=False)?

description: Pass empty argument to Popen (with shell=False)


rawDescription: Calculate probabilities in a probability tree


code:
#" = {}" create a dictionnary
cities = {}
#put the files you want to parse in this list
file_list = ("city1.txt", "city2.txt")
for file_name in file_list:
    file = open(file_name, 'r')
    #we don't want the .txt in the name, so we'll cut it
    #split splits the file_name into a list, removing all dots
    city_name = file_name.split('.')[0]
    #"= []" create an empty list
    cities[city_name] = []
    for line in file:
        #strip will remove all unnecessary spaces
        values = line.strip().strip(' ')
        #verify the length, we don't want to use empty lines
        if len(values) == 2:
            cities[city_name] = values[1]
    file.close()

rawDescription: Creating a list of lists using append function


code:
try:
    from itertools import izip_longest  # added in Py 2.6
except ImportError:
    from itertools import zip_longest as izip_longest  # name change in Py 3.x

try:
    from itertools import accumulate  # added in Py 3.2
except ImportError:
    def accumulate(iterable):
        'Return running totals (simplified version).'
        total = next(iterable)
        yield total
        for value in iterable:
            total += value
            yield total

def make_parser(fieldwidths):
    cuts = tuple(cut for cut in accumulate(abs(fw) for fw in fieldwidths))
    pads = tuple(fw < 0 for fw in fieldwidths) # bool values for padding fields
    flds = tuple(izip_longest(pads, (0,)+cuts, cuts))[:-1]  # ignore final one
    parse = lambda line: tuple(line[i:j] for pad, i, j in flds if not pad)
    # optional informational function attributes
    parse.size = sum(abs(fw) for fw in fieldwidths)
    parse.fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw < 0 else 's')
                                                for fw in fieldwidths)
    return parse

line = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n'
fieldwidths = (2, -10, 24)  # negative widths represent ignored padding fields
parse = make_parser(fieldwidths)
fields = parse(line)
print('format: {!r}, rec size: {} chars'.format(parse.fmtstring, parse.size))
print('fields: {}'.format(fields))

rawDescription: Efficient way of parsing fixed width files in Python


code:
with open("listofwords.txt", "rb") as myfile:
    com = myfile.read()
sentence = zlib.decompress(com)

rawDescription: How do I compress an input into a txt file?

description: Compress an input into a txt file


code: count = len([name for name in os.listdir(DIR) if name != ".DS_Store"])

rawDescription: How to exclude .DS_Store from file count?

description: Exclude .DS_Store from file count


rawDescription: Finding which rows have all elements as zeros in a matrix with numpy


rawDescription: Predicting time series data with python

description: Predicting time series data with python


code:
def getOverlap(a, b):
    return max(0, min(a[1], b[1]) - max(a[0], b[0]))

nodes     = sorted(np.unique(np.array(dates).flatten()))
intervals = zip(nodes[:-1], nodes[1:])
# [(1100, 1200), (1200, 1300), (1300, 1400)]

m = np.array([[bool(getOverlap(i, d)) for d in dates] for i in intervals])

m.sum(axis=1)
# array([2, 5, 2])

rawDescription: Create categories from array of intervals


code: print(first.lower() <= second.lower() <= third.lower())

rawDescription: Creating a program that prints true if three words are entered in dictionary order


code:
from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)

rawDescription: What are "named tuples" in Python?

description: What are "named tuples" in Python


code:
def average(lst):
    return 1.0*sum(lst)/len(lst) if lst else 0.0
[(i[0],average([j[1] for j in i[1]])) for i in itertools.groupby(sorted(ls),key=lambda i:i[0])]

rawDescription: Groupby in a list for python

description: Groupby in a list for python


code:
class JobsHandler(BaseHandler):
    def parseRestArgs(self, args):
        idList = []
        extension = None
        if len(args) and not args[0] is None:
            for arg in range(len(args)):
                match = re.match("[0-9]+", args[arg])
                if match:
                    slave_id = int(match.groups()[0])

            match = re.match("(\.[a-zA-Z]+$)", args[-1])
            if match:
                extension = match.groups()[0][1:]

        return idList, extension

    def get(self, *args):
        ### Read
        job_id, extension = self.parseRestArgs(args)

        if len(job_id):
            if extension == None or "html":
               #self.render(html) # Show with some ID voodoo
               pass
            elif extension == 'json':
                #self.render(json) # Show with some ID voodoo
                pass
            else:
                raise tornado.web.HTTPError(404) #We don't do that sort of thing here...
        else:
            if extension == None or "html":
                pass
                # self.render(html) # Index- No ID given, show an index
            elif extension == "json":
                pass
                # self.render(json) # Index- No ID given, show an index
            else:
                raise tornado.web.HTTPError(404) #We don't do that sort of thing here...

rawDescription: Rendering requested type in Tornado

description: Rendering requested type in Tornado


code: stars * grid

rawDescription: Python: Binning one coordinate and averaging another based on these bins


code: {('some domain', 'some date'): 'some ip'}

rawDescription: How can I add a dictionary inside an existing dictionary ,Python

description: Add a dictionary inside an existing dictionary ,Python


code:
mydict = {'a' : {'c' : 1}, 'b' : {'c' : 2}}
max(mydict, key=lambda k: mydict[k]['c'])

rawDescription: Grabbing key of dictionary in dictionary with highest value


code:
def refresh(self):
    self.variable4 = self.variable1 + self.variable2 + self.variable3
    self.variable5 = self.variable3 - self.variable2 / self.variable1

rawDescription: Refreshing a list of variables with one command


code:
file1 = open('filename1.txt')
file2 = open('filename2.txt')

d1 = {}
d2 = {}

for row in file1:
    cols = row.split(',')
    key = cols[0] + cols[1]
    d1[key] = cols

for row in file2:
    cols = row.split(',')
    key = cols[0] + cols[1]
    d2[key] = cols

file1.close()
file2.close()

rawDescription: Merge two files with some data manipulation Python


code: resrc = self.site.getResourceFor(self)

rawDescription: How to plot tree of resources in twisted.web python

description: Plot tree of resources in twisted.web python


code: result = [x for i, x in enumerate(main_list) if get_indices[i]]

rawDescription: Use bool list to retrieve elements from another list - Python


code:
handID = rightmost.id

hand = frame.hand(handID)

rawDescription: How does LeapMotion specify which hand is left and which is right?


code:
import re
test="y1.0 -iE:\CIDK\DDP\Test_Materials\Test_Signals\ITAF_Tests\acmod\LFE7.ec3 -19.wav"
resultat = re.sub('E:.*\\\\','',test)
print( resultat )

rawDescription: Remove directory path from a text file

description: Remove directory path from a text file


code:
import networkx as nx

def absorbing_classes(g):
    internal = set()

    # Tarjan is approximately linear O(|V| + |E|)
    cpts = list(nx.strongly_connected_component_subgraphs(g))
    for sg in cpts:
        for e in sg.edges():
            internal.add(e)

    # find all the edges that aren't part of the strongly connected components
    # ~ O(E)
    transient_edges = set(g.edges()) - internal

    # find the start of the directed edge leading out from a component
    # ~ O(E)
    transient_srcs = set([ e[0] for e in transient_edges ])

    # yield everything that don't have a vertex in transient_srcs
    for sg in cpts:
        if transient_srcs - set(sg.nodes()):
            yield sg

rawDescription: Identifying absorbing classes in a sparse graph


code: lst = [x for x in list if sum(x) in spectrum]

rawDescription: How to filter a list of sublists

description: Filter a list of sublists


rawDescription: Create GCE instance using Python API

description: Create GCE instance using Python API


code:
def N(d, memo={1:1, 2:1}):
    # http://oeis.org/A112915
    if d not in memo:
        memo[d] = sum(i * (d - i) * N(i) * N(d - i) for i in range(1, d))
    return memo[d]

rawDescription: Coding summation formula and recursive function


code:
data = [item for sublist in token_counts for item in sublist.values()]
rows = [item for sublist in token_counts for item in sublist.keys()]
cols = [i for i,sublist in enumerate(token_counts) for item in sublist.keys()]
M=sparse.csr_matrix((data,(rows,cols)))
M
M.A

rawDescription: pointers in sparse matrix in python scipy

description: Pointers in sparse matrix in python scipy


code:
import sys
import shlex   # thanks Matt

old_argv = sys.argv
sys.argv = shlex.split('foo.py is a happy camper')

execfile('foo.py')

rawDescription: Run Python program from shell and keep variables in scope


rawDescription: Obtaining an elasticsearch query from Kibana


code:
with open('input.txt') as f: # use the real filename
    exons = dict(read_exons(line) for line in f
                 if not line.strip().startswith('#'))
exons.keys()

rawDescription: Reinitializing numbers in file (with differing amounts of columns?)


rawDescription: Python: Pandas - Delete the first row by group


code: rules = [Rule(SgmlLinkExtractor(deny=[r'logout/']), follow=True),]

rawDescription: scrapy avoid crawler logging out

description: Scrapy avoid crawler logging out


code: map(int, MyList)

rawDescription: Mapping Int to a List - Python

description: Mapping Int to a List - Python


code:
def __new__(cls, *args, **kwargs):
    # do allocation to get an object, say, obj
    return obj

rawDescription: __new__ and __init__ in Python

description: __new__ and __init__ in Python


code: go --abc

rawDescription: Difference between single dash and double dash in argparse


rawDescription: Is there a more pythonic way to build this dictionary?


code:
class Foo(object): # new-style classes (which extend from object) are preferred
    def __init__(self):
        self.myvar = 1

rawDescription: How do I import a variable from another class?

description: Import a variable from another class


code:
bob : 10
fred : 3
george : 5

rawDescription: python split and reverse text file

description: Python split and reverse text file


code:
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_SERIALIZER_CLASS': {
        'full.path.to.CustomPaginationSerializer',
    }
}

rawDescription: Where to change the form of json response in django rest framework?


code:
if xx >= screenWidth:
    xx = 0

rawDescription: How to change speed of scrolling background pygame?

description: Change speed of scrolling background pygame


code:
ax1.set_yticks(np.linspace(0, ax1.get_ybound()[1]+1, 5))
ax2.set_yticks(np.linspace(0, ax2.get_ybound()[1]+1, 5))

rawDescription: matplotlib align twinx tick marks

description: Matplotlib align twinx tick marks


code: gdk_pixbuf_save(pb, "screenshot.png", "png", NULL, NULL);

rawDescription: Convert a GTK python script to C

description: Convert a GTK python script to C


code:
import requests
beginning = requests.get('http://example.com/').iter_content(1024).next()

rawDescription: Is it possible to fetch the first few, say 1K, of a webpage using python?


code: df.groupby(['Col X','Col Y']).size().unstack('Col Y').fillna(0)

rawDescription: Pivot Tables or Group By for Pandas?

description: Pivot Tables or Group By for Pandas


code:
class UserCreate(generic.CreateView):

    def form_valid(self, form):
        base_user = BaseUser.objects.create(
            enabled=form.cleaned_data['enabled']
        )
        form.instance.base = base_user
        return super(UserCreate, self).form_valid(form)

rawDescription: Django : ModelForm with OneToOneField

description: Django : ModelForm with OneToOneField


code:
input.configure(state=tkinter.DISABLED,
    borderwidth=0,
    background=root.cget('background'))

rawDescription: Python Tkinter read only text field

description: Python Tkinter read only text field


code:
import lxml.etree as et
tree= et.parse("test.xml")
ns = {'ns': 'http://schemas.microsoft.com/developer/msbuild/2003'}
opts = tree.xpath("""//ns:ItemDefinitionGroup[@Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"]/ns:ClCompile/ns:Optimization""", namespaces=ns)
opts
opts[0].text

rawDescription: lxml : How to verify tag value in different nodes

description: Lxml : How to verify tag value in different nodes


rawDescription: Use Column and Row Multi-Index values in Pandas Groupby without unstacking


code:
import os
os.fstat(f.fileno()).st_size

rawDescription: Size of an open file object

description: Size of an open file object


rawDescription: What is the shortest way to get argument passed into program?


code:
@receiver(m2m_changed, sender=Files.tags.through)
def handle_tags(sender, **kwargs):

    action = kwargs['action']

    if action == "pre_clear":
        tags_pk_set = kwargs['instance'].tags.values_list('pk')
    elif action == "pre_remove":
        tags_pk_set = kwargs.get('pk_set')
    else:
        return

    # I'm using Count() just so I don't have to iterate over the tag objects
    annotated_tags = Tags.objects.annotate(n_files=Count('files'))
    unreferenced = annotated_tags.filter(pk__in=tags_pk_set).filter(n_files=1)
    unreferenced.delete()

rawDescription: How to delete many to many when unassociated in Django?

description: Delete many to many when unassociated in Django


code:
import datetime
date_str = input("Date: ")
try:
    date = datetime.datetime.strptime(date_str,'%m/%d/%Y')
except ValueError:
    print ("Bad date")

rawDescription: how do i write a statement if there is a character or negative in the date string?

description: Write a statement if there is a character or negative in the date string


code: CONFIG_MODE = 'base'   # or 'local' or 'production'

rawDescription: Split configuration files using django-configurations


rawDescription: Python Split Operator

description: Python Split Operator


code:
def insertIntoDataStruct(country, state,job,count,dict):
    if country not in dict:
         dict[country] = {state: {job: count}}
    elif state not in dict[country]:
         dict[country][state] = {job: count}
    elif job not in dict[country][state]:
         dict[country][state][job] = count
    else:
         dict[country][state][job] += count

rawDescription: Inserting values to nested dictionaries

description: Inserting values to nested dictionaries


code:
from PIL import Image
from numpy import*

temp=asarray(Image.open('test.jpg'))
x=temp.shape[0]
y=temp.shape[1]*temp.shape[2]

temp.resize((x,y)) # a 2D array
print(temp)

rawDescription: import image to python as 2D array

description: Import image to python as 2D array


code:
def add_cols(a, b, c):
    return a+b+c

rawDescription: Unpack NumPy array by column

description: Unpack NumPy array by column


rawDescription: How to run one python webdriver test in multiple browsers

description: Run one python webdriver test in multiple browsers


rawDescription: Plotting pandas groupby

description: Plotting pandas groupby


code:
import re
class Sequence(list):
    def __init__(self, s):
        if isinstance(s, str):
            self.extend(re.findall(r'[^\[\]]|\[\d+\]', s))
        else:
            list.__init__(self, s)
    def __str__(self):
        return ''.join(self)
    def __getslice__(self, i, j):
        l = list(self)
        return Sequence(l[i:j])

rawDescription: How to parse ambiguous characters with BioPython

description: Parse ambiguous characters with BioPython


code:
import os, struct, socket

def main():
    # Take screenshot and load the data.
    os.system('scrot image.bmp')
    with open('image.bmp', 'rb') as file:
        data = file.read()
    # Construct message with data size.
    size = struct.pack('!I', len(data))
    message = size + data
    # Open up a server socket.
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('', 65000))
    server.listen(5)
    # Constantly server incoming clients.
    while True:
        client, address = server.accept()
        print('Sending data to:', address)
        # Send the data and shutdown properly.
        client.sendall(message)
        client.shutdown(socket.SHUT_RDWR)
        client.close()

if __name__ == '__main__':
    main()

rawDescription: Data lost on receiver side in python socket programming


code:
from enthought.chaco.scales.formatters import TimeFormatter
TimeFormatter._formats['days'] = ('%d/%m', '%d%a',)

rawDescription: python chaco axis labels time formatting

description: Python chaco axis labels time formatting


rawDescription: Read list from text file

description: Read list from text file


code:
def change_view(self, request, object_id, extra_context=None):
    extra_context = extra_context or {}
    extra_context['ID'] = object_id
    return super(QuestionAdmin, self).change_view(request, object_id,
        extra_context=extra_context)

rawDescription: Django how to make a reverse foreign key reference


code: [a for a,_ in sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)][:3]

rawDescription: Python Converting a sorted dictionary to list?


code:
from config import ACCESS_TOKEN

some_api.do_request(token=ACCESS_TOKEN)

rawDescription: How do I use an access token in modules?

description: Use an access token in modules


code:
s = " There was a boat in the rain near the shore, by some mysterious lake"
vowels = "aeiouAEIOU"
print([x for x in s.split() if any(len(set(x[i:i+2]).intersection(vowels))==  2 for i in range(len(x))) ])
['boat', 'rain', 'near', 'mysterious']

rawDescription: Delete words which have 2 consecutive vowels in it


code:
np.random.seed = 1
beta = pd.Series(np.random.randn(5))
data = pd.DataFrame(np.random.randn(20, 5))

rawDescription: Python numpy or pandas equivalent of the R function sweep()


code:
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52

rawDescription: Print file age in seconds using Python

description: Print file age in seconds using Python


code:
import re

# Function that will match any of the given prefixes returning a match obj on hit
area_code_matcher = re.compile(r'|'.join(map(re.escape, area_codes))).match
for line in txt:
    is_number = phonenumbers.parse(line,"GB")
    if phonenumbers.is_valid_number(is_number):
        # Returns None on miss, match object on hit
        m = area_code_matcher(line)
        if m is not None:
            # Whatever matched is in the 0th grouping
            print(line, m.group())

rawDescription: In Python,if startswith values in tuple, I also need to return which value


code:
class Base(object):
    def do( self ):
        self._member1 = 0
        self._member2 = 1

def make_do(a, b):
    def do(self):
        Base.do(self)
        self._member3 = a
        self._member4 = b
    return do

def make_derived(name, a, b):
    return type(name, (Base,), {'do': make_do(a,b)})

Derived1 = make_derived('Derived1', 0, 1)
Derived2 = make_derived('Derived2', 2, 3)
Derived3 = make_derived('Derived3', 9, 3)

rawDescription: Python: Simplify inheritor method

description: Python: Simplify inheritor method


code:
import dis
def foo():
    # in the interpreter, comments will do the same job as newlines
    baz
    # extra newlines or comments push the bytecode offsets
    return 42

def bar():
    baz
    return 42

dis.dis(foo)
dis.dis(bar)

rawDescription: Is the resulting bytecode generated in Python deterministic?


code:
dti = pd.DatetimeIndex(s)
s.groupby(dti.year).size()
s.groupby(dti.month).size()

rawDescription: .json extension file + timestamp + Pandas + Python


code:
xy.shape
z.shape
data.shape

rawDescription: Using scipy's kmeans2 function in python


code:
A = [1, 2, 3]
B = ['a', 'b', 'c']

for a, b in zip(A, B):
    print(a)
    print(b)

rawDescription: Loop print of 2 columns in to 1

description: Loop print of 2 columns in to 1


rawDescription: Combine data frames while adding values in Pandas


rawDescription: Remove duplicate values from entire dataframe


rawDescription: asked to calculate the logical matrix P=mn

description: Asked to calculate the logical matrix P=mn


rawDescription: Extract row with maximum value in a group pandas dataframe


code: df

rawDescription: Merge of more than 2 python pandas data frames


code:
import requests
response = requests.get(url)
html = response.text

rawDescription: Force python http request to refresh

description: Force python http request to refresh


rawDescription: Python: Using regex stored in CSV

description: Python: Using regex stored in CSV


code:
import numpy as np

def vectorized_approach(V,H,E,F,Q,n):

    # Create a copy of V to store output values into it
    V_vectorized = V.copy()

    # Calculate v1 in a vectorized fashion
    E1 = (E[None,:n,:]*H[:n,:n,None] + E[:n,None,:]).reshape(-1,n)
    E2 = np.dot(E1,F)
    v1_vectorized = np.einsum('ij,ji->i',E2,E1.T).reshape(n,n)
    np.fill_diagonal(v1_vectorized, np.nan)

    # Calculate v2 in a vectorized fashion
    Q_diag = np.diag(Q[:n,:n])
    v2_vectorized = Q_diag[:,None] + H[:n,:n]**2*Q_diag[None,:]

    # Finally, get vectorized version of output V
    V_vectorized[:n,:n] = v1_vectorized/np.sqrt(v2_vectorized)
    return V_vectorized

rawDescription: optimizing matrix operations in python, numpy

description: Optimizing matrix operations in python, numpy


rawDescription: Miscalculating recursive state probability


code: key = self.caseload.keys()[int(userchoice) - 1]

rawDescription: Ordered dictionaries

description: Ordered dictionaries


code:
class Defuse(MustBeMixed):
    def __init__(self):
        super().__init__()

rawDescription: In Python 3, how to prevent direct creation of a mixin class?


code:
with open("fileA.txt", "rt") as f:
    lines = [line for index, line in enumerate(f.readlines()) if classes[index] == 1]

rawDescription: Python: How to extract data in text file based on class information from another text file?


code:
for line in inputfile:
    outputfile.write(line.split(',', 1)[1])  # split(..., 1) only splits once!

rawDescription: How to remove a word declared in a variable in .csv file with python?

description: Remove a word declared in a variable in .csv file with python


code:
class Victim(object):
    @Decor
    def sum(self, a, b):
        return a+b

v = Victim()
v.sum
v.sum(1, 2)

rawDescription: Callable object decorator applied to method doesn't get self argument on input


rawDescription: Passing a Javascript variable to Django view


code:
if order_type=='a':
    order = [Population.method1, Population.method2, Population.method3]
    arguments = [(), (), (the_argument,)]
elif order_type=='b':
    order = [Population.method2, Population.method1, Population.method3]
    arguments = [(), (), (the_argument,)]
else :
    order = [Population.method3, Population.method2, Population.method1]
    arguments = [(the_argument, ), (), ()]

my_pop = Population(3)

while iteration < 100:
    iteration +=1
    for method_to_use, args in zip(order, arguments):
        method_to_use(my_pop, *args)

rawDescription: Using a dictionary to control the flow of methods


code:
import re
data = open('input.txt').read()
data = re.sub(r"    'Step([0-9]+)' =>\s+{\s+action\s+=> ", r"    '\1'     => ", data)
data = re.sub(r"',\s+pass\s+[^,]+,", "", data)
data = re.sub(r"',\s+accept_multi_match\s+[^,]+,", "", data)
data = re.sub(r"\n +#.*\n", "\n", data)
data = re.sub(r"',\s+fail\s+[^,]+,", "", data)
data = re.sub(r"',\s+matchtype\s+[^,]+,", "", data)
data = re.sub(r"',\s+inputstring\s+=> '", ",", data)
data = re.sub(r"\s+matchstring\s+=> '", ",", data)
data = re.sub(r"\n        },", "',", data)
open('output.txt', 'w').write(data)

rawDescription: tips on Parsing a custom file format python

description: Tips on Parsing a custom file format python


code:
adjyear = np.where(df.season == 'SPRING', df.year + 1, df.year)
adjyear.name = 'year'

grouped = df.groupby(['method', 'replicate', 'site', adjyear])
grouped = grouped['sp1', 'sp2', 'sp3']

grouped.sum()[grouped.size() > 1]

rawDescription: better method to aggregate pandas dataframe by non matching criteria

description: Better method to aggregate pandas dataframe by non matching criteria


code:
def Display(self):
    self.imageDisplay = PhotoImage(file='C:\image.gif')
    for x in xrange(0, self.imageDisplay.width()):
        for y in xrange(0, self.imageDisplay.height()):
            raw = self.imageDisplay.get(x, y)
            rgb = tuple(255 - int(component) for component in raw.split())
            self.imageDisplay.put('#%02x%02x%02x' % rgb, (x, y))
    c = Canvas(self, width=700, height=700); c.pack()
    c.grid(padx=0,pady=0, column=0, row=0)
    c.create_image(0,0, image = self.imageDisplay, anchor = NW)

rawDescription: Optimization of color inversion - Python Tkinter library


code:
def transposeDict(listOfDicts):
    """Turn a list of dicts into a dict of lists.  Assumes all dicts in the list have the exact same keys."""

    keys = listOfDicts[0].iterkeys()
    return dict((key, [d[key] for d in listOfDicts]) for key in keys)

rawDescription: Python: DictReader returning a list of dictionaries?


code: d = dict.fromkeys(l, 1)

rawDescription: How to make a dictionary from list

description: Make a dictionary from list


hello

surname: world

rawDescription: python convert custom object to json using properties

description: Python convert custom object to json using properties


code:
c = a*(b.max()+1) + b
c[b==0] = 0
_,idx = np.unique(c,return_inverse= True)
out = idx.reshape(b.shape)

rawDescription: Label regions with unique combinations of values in two numpy arrays?


code:
class MyString(str):
    def __getitem__(self, i):
        return type(self)(super(MyString, self).__getitem__(i))

rawDescription: Inheriting from "str" class

description: Inheriting from "str" class


code:
"b_SET"
{'.test3': 'gol\nolo', '.test1': 'hmm bl\n      abla\tbla', '.tes\nt\t2': 'ehm\tehm'}

"a_SET"
{'.test1': 'blabla', '.test2': 'blablabla'}

rawDescription: Python multiline regex + multi entries reading a file in one go


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

data = np.linspace(-10,5,20).reshape(5,4)

cmap = {name:plt.get_cmap(name) for name in ('gnuplot', 'cool')}
N = 50

vmin, vmax = (np.nextafter(min(data.min(), -1), -np.inf),
              np.nextafter(max(data.max(), 1), np.inf))              # 1

levels = np.concatenate([np.linspace(vmin, 0, N, endpoint=False),
                         np.linspace(0, vmax, N+1, endpoint=True)])  # 2
colors = np.concatenate([cmap[name](np.linspace(0, 1, N))
                         for name in ('cool', 'gnuplot')])           # 3

cmap, norm = mcolors.from_levels_and_colors(levels, colors)

plt.imshow(data, cmap=cmap,
           norm=norm,
           interpolation='nearest')
bar = plt.colorbar()
plt.show()

rawDescription: Join two colormaps in imshow

description: Join two colormaps in imshow


code:
import datetime as dt
ds = '0104160F'
parsed = dt.datetime.strptime(ds, "%y%m%d0F")
parsed
reformatted = dt.datetime.strftime(parsed, "%Y-%m-%d")
reformatted

rawDescription: python string to date ISO 8601

description: Python string to date ISO 8601


code: item = next((item for item in collection if item.id == 1), None)

rawDescription: Select an element that satisfies a condition


code:
from collections import Counter
import re

with open('test.txt') as f:
    res = sum((Counter({x.group(1): int(x.group(2))})
               for x in (re.search('(.*?):.*\s(\d+)', line) for line in f) if x),
              Counter())

with open('output.txt', 'w') as f:
    f.writelines('{0}:00 - {1}:00 {2}\n'.format(k, int(k.split()[-1]) + 1, v)
                 for k, v in sorted(res.iteritems()))

rawDescription: data extraction and its summation using python

description: Data extraction and its summation using python


code:
points = np.array([(1,2), (3,4), (5,6)],float)
points
points.view(point_type)
points.view(point_type).view(np.recarray).x

rawDescription: Namedtuple in Numpy

description: Namedtuple in Numpy


code:
import re
with open("input.txt") as infile, open("output.txt", "w") as outfile:
    outfile.write(re.sub(r"(?s)<cmd>.*?</cmd>", "<cmd>\n</cmd>", infile.read()))

rawDescription: Updating multiple lines of a text file python


code:
txt='''\
RX[0]
qpn : 0x48
cqn : 0x80
rxBytes : 179531811
rxPackets : 296242
rxPacketsDropped : 0
rxCheckSumOk : 225257
rxCheckSumNone : 200
RX[1]
qpn : 0x49
cqn : 0x81
rxBytes : 0
rxPackets : 0
rxPacketsDropped : 0
rxCheckSumOk : 0
rxCheckSumNone : 0**
'''
import re
re.search(r'RX\[(\d+)\].*?rxPackets\s+:\s+(\d+)', txt, re.S).groups()

rawDescription: Catch multiple string occurrences in multiline text


code:
import random

print('1. Flip a coin')
print('2. Pick a card')

choice = int(input('Enter a choice: '))

if choice == 1:
    outcomes = ('heads', 'tails')
    print('You got {}.'.format(random.choice(outcomes)))

else:
    suits = ('Hearts', 'Clubs', 'Diamonds', 'Spades')
    print()
    for index, element in enumerate(suits, start=1):
        print('{}. {}'.format(index, element))

    suitno = int(input('Choose a suit: '))
    value = random.randint(1, 13)
    print('\nYou picked', value, 'of', suits[suitno-1])

rawDescription: Coin Flipping/Card picking program not working


code:
def my_template_function():
    start = timezone.now().date()
    end = timezone.now().date()+datetime.timedelta(days=1)
    # rest of the code goes here

rawDescription: In django how to have the template tag to load current date everyday?


code: groups = zip(mylist,mylist[1:],mylist[2:],mylist[3:]) #there are many ways of doing this i picked this way

rawDescription: Writing program to choose values from a list of integers


code:
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
if os.sep != '/':
    # Django says, "Always use forward slashes, even on Windows."
    TEMPLATE_DIR = TEMPLATE_DIR.replace(os.sep, '/')
TEMPLATE_DIRS = (TEMPLATE_DIR,)

rawDescription: Template directory logic in Django

description: Template directory logic in Django


code:
from datetime import datetime
t = [(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955)), (datetime(2015, 2, 2, 14, 49, 6, 185955), datetime(2015, 10, 23, 14, 49, 6, 185955))]
def time_overlap(t):
    overlap = (min(t[0][1], t[1][1]) - max(t[0][0], t[1][0]))
    days = overlap.days+1
    hours, remainder = divmod(overlap.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    hours += days*24
    return (hours,minutes,seconds)
print(time_overlap(t))

rawDescription: Python - How to find datetime overlapping?


code:
def func_of_func(func):
  return fund()

def main():
  a = A()
  func_of_func(a.some_func) # no parentheses after some_func

rawDescription: Class defintion and methods

description: Class defintion and methods


rawDescription: how do I make a 2.7 python context manager threadsafe

description: Make a 2.7 python context manager threadsafe


code:
dct = dict(light=['on', 'off'], lock=['lock', 'unlock'])
dct

rawDescription: PHP like array handling in Python: Indexing multidimensional array


code:
def get_implementation(name):
    return globals()[name]

rawDescription: Dynamically return a class implementation in Python


code:
from celery import shared_task

@shared_task
def delete_model(model_pk):
    try:
        MyModel.objects.get(pk=model_pk).delete()
    except MyModel.DoesNotExist:
        pass

rawDescription: Django Scheduled Deletion

description: Django Scheduled Deletion


code: dict(elem.strip().split('=', 1) for elem in x)

rawDescription: How to parse a tuple of "x=y" strings into a dictionary in python?

description: Parse a tuple of "x=y" strings into a dictionary in python


code: result[:a.shape[0],:a.shape[1]] = a

rawDescription: python how to pad numpy array with zeros

description: Python how to pad numpy array with zeros


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

ns = range(2,8)
cm = plt.cm.get_cmap('spectral')
cmap = [cm(1.*i/len(ns)) for i in range(len(ns))]
for i,n in enumerate(ns):
    x = np.linspace(0, 10, num=n)
    y = np.zeros(n) + i
    c = mpl.colors.rgb2hex(cmap[i])
    alpha = cmap[i][3]
    plt.scatter(x, y, c=c, edgecolor='none', s=50, label=n, alpha=alpha)
plt.legend(loc='lower left')
plt.show()

rawDescription: Matplotlib colormap bug with length-4 arrays


code:
import os
import numpy as np
arr = np.memmap('mm', dtype='float32', mode='w+', shape=(1,10000000))
arr[:] = np.zeros((1,10000000))
os.system("md5sum mm")
arr += 1.1
os.system("md5sum mm")
arr[:] = np.argsort(arr)
os.system("md5sum mm")
arr += 1.3
os.system("md5sum mm")

rawDescription: Correct way to do operations on Memmapped arrays


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

X = np.array([[3,2,1],[4,5,6]])
Y = np.array([[1,2,1],[2,3,4]])
Z = np.array([[10,11,12],[13,12,16]])

# Create figure outside the loop
fig = plt.figure()

for i in range(0,X.shape[0]):

    # Add the i+1 subplot of the x.shape[0] x 1 grid
    ax = fig.add_subplot(X.shape[0], 1, i+1, projection='3d')

    ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')

    ax.set_xlabel('Z')
    ax.set_ylabel('X')
    ax.set_zlabel('Y')
# Show it outside the loop
plt.show()

rawDescription: Matplotlib - Plot 3D with for loop

description: Matplotlib - Plot 3D with for loop


code: y.reshape(2,1) - x

rawDescription: Python and numpy : subtracting line by line a 2-dim array from a 1-dim array


code:
mul = lambda i, val: i * val
add = lambda i, val1, val2: i + val1 + val2

def functions(lst, *fns):
    for fn, args in fns:
        lst = [fn(i, *args) for i in lst]
    return lst

rawDescription: Applying a series of functions to a list


code:
fixedString = re.sub(">\s*(\!--|\!DOCTYPE|\
                           a|abbr|acronym|address|applet|area|\
                           b|base|basefont|bdo|big|blockquote|body|br|button|\
                           caption|center|cite|code|col|colgroup|\
                           dd|del|dfn|dir|div|dl|dt|\
                           em|\
                           fieldset|font|form|frame|frameset|\
                           head|h1|h2|h3|h4|h5|h6|hr|html|\
                           i|iframe|img|input|ins|\
                           kbd|\
                           label|legend|li|link|\
                           map|menu|meta|\
                           noframes|noscript|\
                           object|ol|optgroup|option|\
                           p|param|pre|\
                           q|\
                           s|samp|script|select|small|span|strike|strong|style|sub|sup|\
                           table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|\
                           u|ul|\
                           var)>", "><\g<1>>", s)
bs = BeautifulSoup(fixedString)

rawDescription: Beautiful Soup - how to fix broken tags

description: Beautiful Soup - how to fix broken tags


rawDescription: Combine columns from several CSV files into a single file


code:
class Card:
    def __init__(self):
        rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
        suit = ['s', 'h', 'c', 'd']
        card = choice(rank) + choice(suit)
        self.rank = rank
        self.suit = suit
        self.card = card

rawDescription: Python 2.7.x - trying to get the hang of OOP and classes


code:
# dateutil's parser is very good for converting from string to date
from dateutil.parser import parse

date_strs = ['20150502', '20150504', '20150522']

for date_str in date_strs:
    d = parse(date_str)
    month_start = datetime.datetime(d.year, d.month, 1)
    week = d.isocalendar()[1] - month_start.isocalendar()[1] + 1
    print(date_str + ':', week)

rawDescription: how to get week number on python?

description: Get week number on python


code:
class Vector(object):
    # rest of the class

    def __getitem__(self, index):
        return (self.x, self.y)[index]

rawDescription: How do you control how an object is "seen" by other functions when passed as an argument?

description: Control how an object is "seen" by other functions when passed as an argument


code:
def com():
    entry.config(state='disabled')

rawDescription: In Tkinter, How I disable Entry?

description: In Tkinter, How I disable Entry


code:
for i in range(1, len(abcstring)):
    c = abcstring[i]
    previous = abcstring[i-1]
    if values(c) < values(previous):
        do_something()

rawDescription: How does one talk about comparing positions of characters in a string?

description: Talk about comparing positions of characters in a string


code:
import datetime as date
import re
import calendar

future = input("Enter a date(dd/mm/yyyy): ")
#eg: future="02/03/2015"
#print future

mat=re.match('(\d{2})[/](\d{2})[/](\d{4})$', str(future))
if mat is None:
    print("Invalid Date Entered, try to enter a date in this form(dd/mm/yyyy) ")
else:
    daystring,monthstring,yearstring= mat.groups()

    today= str(date.datetime.now()).split(" ")[0]
    year, month, day = today.split("-")

    months = ["Jan", "Feb", "Mar", "Apr", "May", "June","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    daysinmonth = [31, 29, 31, 30, 31, 30, 31, 31, 30,31, 30, 31]

    if int(daystring)>0 and int(daystring)<=31 and int(monthstring)>0 and int(monthstring) <= 12 and int(yearstring)>0:
        if monthstring  in ["01", "03", "05" ,"07","08","10", "12"]:
            if int(daystring) > 31:
                print("Invalid Date Entered - Number of days can't exceed 31.")
        if monthstring in ["04","06","09","11"]:
            if int(daystring) > 30:
                print("Invalid Date Entered - Number of days can't exceed 31.")
        if monthstring == "02":
            t= calendar.monthrange(int(yearstring), 2) # This is to check if February has 29 or 28 (is leap year or no), you can do that by checking the day number of "datetime.date (int(yearstring), 3, 1) - datetime.timedelta (days = 1)"
            if int(daystring) !=t: #You forget faberuary
                print("Invalid Date Entered - of days can't exceed 28 or 29")

        a = date.datetime.strptime(future, "%d/%m/%Y").date()
        b = date.datetime.strptime(today, "%Y-%m-%d").date()
        delta = a-b   # The future - Today ::> to get a positive number
        if delta.days >0:
            print ("The difference between the inputted date and todays date is: ",delta.days, "days")
        else:
            print("Date is in the past")

    else:
        print("Invalid Date Entered")

rawDescription: difference between two dates python

description: Difference between two dates python


rawDescription: using Crontab to run simple Python file

description: Using Crontab to run simple Python file


code:
ip_start, _, end_value = iprange.partition('-')
first_three = ip_start.rpartition('.')[0]
ip_end = '{}.{}'.format(first_three, end_value)

rawDescription: Python Beginner split String in two strings


code:
def angle(x1,y1):
    #  Returns angle of each segment along an (x,y) track
    return array([math.atan2(y,x) for (y,x) in zip(diff(y1),diff(x1))])

def simplify(x,y, tolerance=40, min_angle = 60.*pi/180.):
    """
    Use the Ramer-Douglas-Peucker algorithm to simplify the path
    http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
    Python implementation: https://github.com/sebleier/RDP/
    """
    from RDP import rdp
    points=vstack((x,y)).T
    simplified = array(rdp(points.tolist(), tolerance))
    sx, sy = simplified.T

    theta=abs(diff(angle(sx,sy)))
    # Select the index of the points with the greatest theta
    # Large theta is associated with greatest change in direction.
    idx = where(theta>min_angle)[0]+1
    return sx,sy,idx

sx1,sy1,i1 = simplify(x1[ind1],y1[ind1])
sx2,sy2,i2 = simplify(x2[ind2],y2[ind2])
fig = plt.figure(figsize=(10,6))
ax =fig.add_subplot(111)

ax.plot(x1, y1, 'b-', x2, y2, 'g-',label='original path')
ax.plot(sx1, sy1, 'ko-', sx2, sy2, 'ko-',lw=2, label='simplified path')
ax.plot(sx1[i1], sy1[i1], 'ro', sx2[i2], sy2[i2], 'ro',
    markersize = 10, label='turning points')
ax.invert_yaxis()
plt.legend(loc='best')

rawDescription: Affine transformation between contours in OpenCV


code: (large.cumsum() < limit).argmin()

rawDescription: Find index in array to which the sum of all elements is smaller than a limit, quickly


code:
for j in xrange(0,len(sign)):
  for k in xrange(0,len(sign)):
    first = a + sign[k] + b
    second = first + sign[j] + c
    print(second)

rawDescription: Getting info out of each loop for use in the next without terminating the loop (Python)


code: driver=webdriver.PhantomJS('your pahtomjs exe file location')

rawDescription: How can i get html from selenium.webdriver in Python?

description: Get html from selenium.webdriver in Python


code: a += a.T

rawDescription: Numpy: Why doesn't 'a += a.T' work?

description: Numpy: Why doesn't 'a += a.T' work


code:
T3 = [int(x) for x in T1]
T3

rawDescription: Convert string to integer using map()

description: Convert string to integer using map()


code: con.execute("SELECT STR_TO_DATE(date_recieved, '%%m/%%d/%%Y') from raw_table", ())

rawDescription: Escaping % in MySQLdb

description: Escaping % in MySQLdb


code:
cache = {'a': 1, 'b': 2}
cache.setdefault('a', 0)
cache.setdefault('b', 0)
cache.setdefault('c', 0)
cache

rawDescription: Best idom to get and set a value in a python dict


code:
seaborn.kdeplot(df['col1'], ax=ax)
seaborn.kdeplot(df['col2'], ax=ax)

rawDescription: How can I overlay two graphs in Seaborn?

description: Overlay two graphs in Seaborn


code:
def make_panes(arr, window):
    arr = np.asarray(arr)
    r,c = arr.shape
    s_r, s_c = arr.strides
    w_r, w_c = window

    if c % w_c != 0 or r % w_r != 0:
        raise ValueError("Window doesn't fit array.")

    shape = (r / w_r, c / w_c, w_r, w_c)
    strides = (w_r*s_r, w_c*s_c, s_r, s_c)

    return np.lib.stride_tricks.as_strided(arr, shape, strides)

def max_in_panes(arr, window):
    w_r, w_c = window
    r, c = arr.shape
    panes = make_panes(arr, window)
    v = panes.reshape((-1, w_r * w_c))

    ix = np.argmax(v, axis=1)
    max_vals = v[np.arange(r/w_r * c/w_c), ix]

    i = np.repeat(np.arange(0,r,w_r), c/w_c)
    j = np.tile(np.arange(0, c, w_c), r/w_r)
    rel_i, rel_j = np.unravel_index(ix, window)
    max_ix = i + rel_i, j + rel_j

    return max_vals, max_ix

rawDescription: What is a pythonic way of finding maximum values and their indices for moving subarrays for numpy ndarray?


code:
def exclusion_generator(base_list, to_excludes):
    for item in base_list:
        if item not in to_excludes:
            yield item

rawDescription: How to exclude an object from a list in Python while looping

description: Exclude an object from a list in Python while looping


code:
#!/usr/bin/env python
import json
import urllib2
from datetime import datetime

local_dt = datetime.now()
data = json.load(urllib2.urlopen(server_url))
# -> [{"status":"waiting","createdate":"2013-11-12 15:35:44"}]
server_dt = datetime.strptime(data[0]["createdate"], "%Y-%m-%d %H:%M:%S")
# -> datetime(2013, 11, 12, 15, 35, 44)
print(server_dt - local_dt)
# -> 3:00:00

rawDescription: Python - how do calculate the time difference between local and server


rawDescription: Determine if given class attribute is a property or not, Python object


code: np.where(np.diff(x) > .5)[0] + 1

rawDescription: Splitting lists by short numbers

description: Splitting lists by short numbers


rawDescription: Can someone explain to me what python is doing here?