code:
from django.db.models import IntegerField, Sum
Client.objects.aggregate(
    num_object_raw=Sum(
        Case(
            When(object_raw='foo', then=1),
            output_field=IntegerField()
        )
    )
)

rawDescription: Django - Aggregate equal values of fields in model


code:
class Bunch(dict):
    __getattr__, __setattr__ = dict.get, dict.__setitem__

rawDescription: Does Python have anonymous classes?

description: Does Python have anonymous classes


code:
import msvcrt

def funkeypress():
    """
    Waits for the user to press any key including function keys. Returns
    the ascii code for the key or the scancode for the function key.
    """
    while 1:
        if msvcrt.kbhit():                  # Key pressed?
            a = ord(msvcrt.getch())         # get first byte of keyscan code
            if a == 0 or a == 224:          # is it a function key?
                b = ord(msvcrt.getch())     # get next byte of key scan code
                x = a + (b*256)             # cook it.
                return x                    # return cooked scancode
            else:
                return a                    # else return ascii code

rawDescription: Simple UI to capture data

description: Simple UI to capture data


code:
vc = AR.PNR.value_counts()
bad_values = vc[vc > 1].index.tolist()

rawDescription: Automating this: Finding and deleting rows in several dataframes


rawDescription: How to plot values for multiple factors from one column across several dates in pandas + matplotlib?

description: Plot values for multiple factors from one column across several dates in pandas + matplotlib


code:
def total(np_array):
    return sum(np_array)

rawDescription: Iterate through a list of numpy arrays

description: Iterate through a list of numpy arrays


code: somelist = [x for x in somelist if not determine(x)]

rawDescription: Remove items from a list while iterating in Python


code:
class SomeModel(MyDocument):
    # fields...

    _pre_save_hooks = [
        some_callable,
        another_callable
    ]

rawDescription: Using MongoEngine Document class methods for custom validation and pre-save hooks


rawDescription: How can lists in a list be overwritten by new lists in a new list in Python?


rawDescription: Python: Access nested datastructures

description: Python: Access nested datastructures


code:
import re
f1 = open('name.xml', 'r')
f2 = open('result.txt', 'w')
data = f1.readlines()
f1.close()
n = 5000
rex = re.compile('<StartNum>(.*)</StartNum>')
for line in data:
    f2.write(rex.sub(r'<StartNum>%s</StartNum>' % str(n), line))
    if "<StartNum>" in line:
        n += 1
f2.close()

rawDescription: python debug: replace string between two unknown substrings

description: Python debug: replace string between two unknown substrings


code:
import pandas as pd
import numpy as np

np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
print('{}\n'.format(df))
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

rawDescription: How to append rows in a pandas dataframe in a for loop?

description: Append rows in a pandas dataframe in a for loop


rawDescription: What is the fastest way to initialize an integer array in python?


code:
class ActivityForm(ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ActivityForm, self).__init__(*args, **kwargs)
        if 'initial' in kwargs:
            self.fields['participants'].queryset = initial.group.members.all()

    class Meta:
        model = Activity

rawDescription: Django ModelForm Field Filtering with multiple model dependancies


rawDescription: python- finding total number of items of certain range in a list

description: Python- finding total number of items of certain range in a list


code:
import os
path = 'C:/'
files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i:
        files.append(i)

rawDescription: Choose a file starting with a given string


rawDescription: Python specify popen working directory via argument


code:
import sys
import fileinput

for line in fileinput.input(inputfilename):
    if line.startswith('for(') and line.endswith(';'):
        line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)
    sys.stdout.write(line)

rawDescription: How do I check for next to next line while reading a file in python and strip the newline character at its end?

description: Check for next to next line while reading a file in python and strip the newline character at its end


code: c.execute("commit ")

rawDescription: python codes works with mysql,'drop table ' takes too long

description: Python codes works with mysql,'drop table ' takes too long


code: self.__dict__[attr] == type(self)(attr)

rawDescription: python enumeration class for ORM purposes

description: Python enumeration class for ORM purposes


code:
def make(name='', street='', city='', state='', zip='', count=0):
    dic[count]=User(name='', street='', city='', state='', zip='')

rawDescription: Python: Accessing object attributes from objects stored in a dictionary


code: ['WEP', 'WPA2-PSK']

rawDescription: Selecting text nodes with text not equal to a value


code:
def print_final(self, thing1, thing2):
    final_page_content = self.final
    final_page_content = final_page_content.format(**locals())
    return final_page_content

rawDescription: Use variables from another class

description: Use variables from another class


code:
df["CRASH_DAY_NO"].value_counts()
df["CRASH_DAY_NO"].value_counts().items()
for value, count in df["CRASH_DAY_NO"].value_counts().items():
    print(value, count)

rawDescription: Pandas: count unique value in each column, by looping through them?


code:
[y for x, y in zip(a, b) if x[:2] == y[:2]]
arr_a = np.array(a)
arr_b = np.array(b)
arr_b[(arr_b[:,:2] == arr_a[:,:2]).all(axis=1)]

rawDescription: Python merge two arrays on specific columns


rawDescription: Splitting arrays python

description: Splitting arrays python


code:
# define the range for the color mapping
# make sure the color map is centered on 0
# >> use maximum absolute value and not the real min and max (default behaviou)
vmax = np.abs(my_weights).max()

plt.imshow(my_weights.reshape((-1,1)), cmap="seismic", vmin=-vmax, vmax=vmax)

# add feature names
feature_names = ['foo', 'bar', ...]
tick_marks = np.arange(len(feature_names))
plt.yticks(tick_marks, feature_names)

rawDescription: Heat map of features and weights

description: Heat map of features and weights


rawDescription: What is the difference between the following two statements?


code:
def InRange(number):
    return 1 <= number <= 5

rawDescription: Chained comparison number range in Python


code: data

rawDescription: TEXT compression in python

description: TEXT compression in python


code:
class Article(models.Model):
    optional_attribute = models.CharField(max_length = 250)

    def save(self, *args, **kwargs):
        if not self.optional_attribute:
            self.optional_attribute = 'Default'
        super(Article, self).save(*args, **kwargs)

rawDescription: How can I call a clean method before get_or_create saves to the database?

description: Call a clean method before get_or_create saves to the database


code: T = {k:( reduce(np.add, v)/len(v) ) for k,v in S.iteritems()}

rawDescription: Python: Mean of several dictionaries with the same keys


code:
BOT_NAME = 'furiousme'

SPIDER_MODULES = ['furiousme.spiders']
NEWSPIDER_MODULE = 'furiousme.spiders'

ITEM_PIPELINES = [
    'furiousme.pipelines.FuriousmePipeline',
]

rawDescription: Scrapy Passing Arguments and Writing to MySQL


code:
def delete(self, _id):
    try:
        model = Model()
        model.delete(_id)
        self.set_status(204)
    except Exception as e:
        logging.error(e)
        self.set_status(500)
    return

rawDescription: Python Tornado: Delete request never ends


rawDescription: How to create array and initialize string values in python in one step?

description: Create array and initialize string values in python in one step


code:
sys.path.append(os.path.join(os.path.dirname(__file__), 'dir2/dir3'))
import packages

rawDescription: Python -- import a module from a directory that's not a package


code:
with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print('Stack Overflow')

rawDescription: Loop over rows of csv.DictReader more than once


code:
def split_name(file_name):
   '''
    Returns root_filename, 'middle tokens', and extension
   '''
   tokens = file_name.split('.')

   return (tokens[0], ".".join(tokens[1:-1]), tokens[-1]) if len(tokens) >1 else file_name

rawDescription: How To Include "part#+.rar" In "Extensions


rawDescription: Skip first two characters in (key=lambda) sorting


code:
import foo.baz

assert(hasattr(foo, 'baz') and hasattr(foo.baz, 'worked'))
assert(foo.baz.worked)

import bar
assert(foo is bar)

rawDescription: Python how to alias module name (rename with preserving backward compatibility)


code:
for w in file2_words:
    file1_raw = file1_raw.replace(w, "")

rawDescription: comparing two text files and remove duplicates in python

description: Comparing two text files and remove duplicates in python


code:
class PeekIterator(object):
    def __init__(self, iterable, sentinel=None):
        self.iterator = iter(iterable)
        self.sentinel = sentinel
        self.next_val = self.sentinel

    def peek(self):
        if self.next_val is self.sentinel:
            try:
                self.next_val = next(self.iterator)
            except StopIteration:
                pass # the sentinel will be returned if there's nothing left in the iterator
        return self.next_val

    def __iter__(self):
        return self

    def __next__(self):
        if self.next_val is self.sentinel:
           return next(self.iterator) # StopIteration is deliberately allowed to bubble out!
        val = self.next_val
        self.next_val = self.sentinel
        return val

    next = __next__ # Python 2 compatibility

rawDescription: Python: Sorted merge using list comprehension


code:
views.py
from django.views.generic.edit import CreateView

class EventCreate(CreateView):
    model = Event
    form_class = EventForm
    template = "events/event_edit.html"
    success_url = "/events/invite/" # XXX use reverse()

    def get_form(form_class):
        return form_class(self.request.user, **self.get_form_kwargs())

    def form_valid(form):
        form.user = self.request.user

        messages.success(request, 'Event has been created.')
        super(EventCreate, self).form_valid(form)

    def form_invalid(form):
        messages.error(request, 'Error')
        super(EventCreate, self).form_invalid(form)

rawDescription: Best practices on saving in a view, based on example code


code:
import itertools as IT
a = "253+9"
''.join(IT.takewhile(str.isdigit, a))

rawDescription: moving integers from one string to another?

description: Moving integers from one string to another


code: from models import *

rawDescription: deleting a name from a list input by user and averaging a class score

description: Deleting a name from a list input by user and averaging a class score


code:
class Post(models.Model):
    account = models.ForeignKey(Account)
    message = models.CharField(max_length=1024)
    timestamp = models.DateTimeField('post timestamp')

    def upvote_count(self):
        return self.postvote_set.filter(vote=VOTE_CHOICES[0][0]).count()

    def downvote_count(self):
        return self.postvote_set.filter(vote=VOTE_CHOICES[1][0]).count()

rawDescription: Django count specific items of a many-to-one relationship


code:
new_df = pd.DataFrame()
new_df ['winners'] = df.groupby(df.index.year, as_index=True)['winners'].sum()
new_df ['losers'] = df.groupby(df.index.year, as_index=True)['losers'].sum()

rawDescription: groupby by years and generate new columns

description: Groupby by years and generate new columns


code:
class MultiIndexList(list):
    def multi_index(self, val):
        return [i for i,v in enumerate(self) if v == val]

rawDescription: Something in python similar to index method for multiple ocurrences


rawDescription: Can't *copy* an index from list to another with a twist in Python


code:
word
word[4]
word[0:2]
word[2:4]

rawDescription: How to split a single word using split()

description: Split a single word using split()


code:
regexb = re.compile(r'>OCTU(\d+)')  #matches ">OCTU" followed by digits, captures digits
for line in b:
    m = regexb.match(line)
    if m:
        sequence = b.next()
        if m.group(1) in seta:
            c.write(line)
            c.write(sequence)

rawDescription: regex python Fasta

description: Regex python Fasta


code: sorted(words, key=lambda x: 'a'+x if x[:1] == 's' else 'b'+x)

rawDescription: sorting a list in python

description: Sorting a list in python


code:
def mean_graph(graphs):
    return graphs[0][0], [sum(v) / float(len(graphs)) for v in zip(*[g[1] for g in graphs])]

rawDescription: Mean function given a list of graphs

description: Mean function given a list of graphs


rawDescription: Sorting a list from a file, outputting in another file


code:
import numpy as np

# Convert images to 4d ndarray, size(n, nrows, ncols, 3)
imgs = np.asarray(imgs)

# Take the median over the first dim
med = np.median(imgs, axis=0)

rawDescription: Find median of list of images

description: Find median of list of images


code:
import string

class FormatDict(dict):
    def __missing__(self, key):
        return "{" + key + "}"

s = '{foo} {bar}'
formatter = string.Formatter()
mapping = FormatDict(foo='FOO')
print(formatter.vformat(s, (), mapping))

rawDescription: partial string formatting

description: Partial string formatting


code:
def splittedname(s):
    return tuple(int(x) for x in s.split('.'))

splittedname(s1) > splittedname(s2)

rawDescription: compare two python strings that contain numbers

description: Compare two python strings that contain numbers


code:
email_f = "Your email address was {email}".format
print(email_f(email="bob@example.com"))

rawDescription: Are there other ways to format strings other then comma, percent, plus sign?


code:
import re

soup.find('a', href=re.compile('^http://get.cm/get'))['href']

rawDescription: Get only the first link of a URLs list with BeautifulSoup


rawDescription: How can i access gtk.Entry() in my GUI script from my other script? Python

description: Access gtk.Entry() in my GUI script from my other script? Python


code: z.reshape(2, 3*3, order='F').reshape(2*3, 3)

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


rawDescription: uv mapping python OpenGL triangles

description: Uv mapping python OpenGL triangles


rawDescription: python split by number of times specified

description: Python split by number of times specified


code:
from operator import itemgetter
matches.sort(key=itemgetter(1))
matches.sort(key=itemgetter(0))

rawDescription: Overlapping regex matches

description: Overlapping regex matches


rawDescription: Efficient way of appending / extracting list elements


code:
#!/home/user/Desktop/generate_keys.py

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)
public_key = key.publickey().exportKey()               #export public key
private_key = key.exportKey()                          #export private key

data = public_key + "||" + private_key
print(data)

rawDescription: Passing Encryption/Decryption Keys from Python to PHP?


code: from urllib.parse import unquote

rawDescription: Turn URL into String (decode URL)

description: Turn URL into String (decode URL)


code:
unique_vectors = set(map(tuple, Corr))

array_of_unique_vectors = np.array(list(unique_vectors))

rawDescription: Comparing vectors in an array of vectors


code:
import numpy as np
import h5py
import os

path = 'file1.hdf5'
with h5py.File(path, "w") as myfile:
    data = np.random.rand(int(1e6))
    myfile.create_dataset("MyDataSet", data=data)
    print(os.path.getsize(path))

with h5py.File(path, "a") as myfile:
    del myfile["MyDataSet"]
    try:
        myfile["MyDataSet"].value
    except KeyError as err:
        # print(err)
        pass

print(os.path.getsize(path))

rawDescription: Delete subgroup from HDF5 file in Python


code:
from bs4 import BeautifulSoup

data = """

    test1
    test2

"""

soup = BeautifulSoup(data, "html.parser")

for b in soup.find_all("b"):
    b.replace_with("'''%s'''" % b.text)

for i in soup.find_all("i"):
    i.replace_with("''%s''" % i.text)

print(soup.prettify())

rawDescription: BeautifulSoup replace_with for non-standard tags


code:
import numpy as np
import scipy.weave

X = np.random.random(1000000)

def my_filter_c(X):
    x_len = len(X)
    Y = np.empty(x_len)

    c_source = """
        #include <math.h>

        int i;
        double a, x;

        Y(0) = X(0);
        a = .99 * Y(0);
        for (i = 1; i < x_len; i++)
            {
            x = X(i);
            if (x > a)
                a = x;
            Y(i) = a;
            a *= .99;
            }
        """

    scipy.weave.inline(c_source, ["X","Y","x_len"],
        compiler="gcc",
        headers=["<math.h>"],
        type_converters=scipy.weave.converters.blitz)

    return Y

rawDescription: Iteratively-defined Numpy Array Creation


rawDescription: How do you sort a list which is inside a dictionary?

description: Sort a list which is inside a dictionary


code: cos_sim = float( np.dot( Rip, Rjp ) ) / np.sqrt( np.dot( Rip,Rip ) * np.dot( Rjp,Rjp ) )

rawDescription: Special cosine between scipy sparse matrices


code:
from Queue import Queue

q = Queue()

rawDescription: How to wakeup thread from thread pool in python?

description: Wakeup thread from thread pool in python


rawDescription: Compare string of bits with elements of a table python


code:
counts = {}
for value in L:
    if value[0] in counts:
        counts[value[0]] += value[1]
    else:
        counts[value[0]] = value[1]

rawDescription: weighted counting in python

description: Weighted counting in python


code: ['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ; part" 5']

rawDescription: How to split but ignore separators in quoted strings, in python?

description: Split but ignore separators in quoted strings, in python


code: from SimpleCV.ImageClass import Image

rawDescription: SimpleCV Code Completion with Eclipse

description: SimpleCV Code Completion with Eclipse


code:
def parse_dt():
    def _parse(dt):
        return datetime.strptime(dt, '%d-%b-%y %I.%M.%S.%f %p')
    return udf(_parse, TimestampType())

df_with_timestamp = df.withColumn("timestamp", parse_dt()(df.datetime))

def in_last_5_minutes(now):
    def _in_last_5_minutes(then):
        return then > now - timedelta(minutes=5)
    return udf(_in_last_5_minutes, BooleanType())

df_with_timestamp.where(in_last_5_minutes(now)(col("timestamp")))

rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


code:
def validated_pincode():
    pincode = CharField(widget=TextInput(attrs={'type':'number'}),
                  validators=[RegexValidator(regex='^.{6}$',message='Pincode can have 6 digits')],
                    required=False, min_length=6)
    return pincode

rawDescription: How to create generic modelform field validator for inherited model attributes in django?

description: Create generic modelform field validator for inherited model attributes in django


code:
import itertools
import csv
import operator
import random

with open("test.csv") as file:
    data = csv.DictReader(file)
    key = operator.itemgetter("Name")
    for name, items in itertools.groupby(sorted(data, key=key), key):
        print(name+":", random.sample(list(items), 3))

rawDescription: Python: Get multiple random lines for a given category


code:
import numpy as np
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
np.random.seed(2016)

def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples.
      - Every float is sandwiched between two RGB values.
      - The floats indicate locations (on a scale from 0.0 to 1.0) where the
        color map transitions from one RGB color to the next.
      - The floats should be in increasing order
      - The first and last values in the sequence are the first and last
        colors in color map.
    http://stackoverflow.com/q/16834861/190597 (unutbu)
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)

c = mcolors.ColorConverter().to_rgb
cmap = make_colormap([(0,1,0), c('dark green')])
cmap.set_under('burnt red')
cmap.set_over('yellow green')

arr = np.random.randint(0, 102, size=(11, 11))
# modify arr so that 0 is mapped to a negative number (-2) and 1 is mapped to a
# positive number greater than 100, (say, 102), and all other values are
# decreased by 2
arr -= 2
arr = np.where(arr==-1, 102, arr)

plt.imshow(arr, interpolation='nearest', cmap=cmap, vmin=0, vmax=100)
plt.colorbar(extend='both')
plt.show()

rawDescription: Discrete then linear colormap in matplotlib


code:
from setuptools import setup
from Cython.Distutils.extension import Extension

ext = Extension(
    name,
    include_dirs=include_dirs,
    cython_compile_time_env={'OPENMP': True},
    sources=['test.pyx'])

setup(name=name,
      cmdclass={"build_ext": build_ext},
      ext_modules=[ext])

rawDescription: Cython conditional compile based on external value given via setuptools


code:
import math
def hexToDec(hexi):
    result = 0
    for i in range(len(hexi)):
        cur_pow = len(hexi) - i  - 1
        if hexi[i] == 'A':
            result = result + (10 * math.pow(16,cur_pow))
        elif hexi[i] == 'B':
            result = result + (11 * math.pow(16,cur_pow))
        elif hexi[i] == 'C':
            result = result + (12 * math.pow(16,cur_pow))
        elif hexi[i] == 'D':
            result = result + (13 * math.pow(16,cur_pow))
        elif hexi[i] == 'E':
            result = result + (14 * math.pow(16,cur_pow))
        elif hexi[i] == 'F':
            result = result + (15 * math.pow(16,cur_pow))
        else:
            result = result + (int(hexi[i]) * math.pow(16,cur_pow))
    return result

rawDescription: python hex to decimal using for loop

description: Python hex to decimal using for loop


code:
import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy

inBook = xlrd.open_workbook(r"/tmp/format_input.xls", formatting_info=True, on_demand=True)
inSheet = inBook.sheet_by_index(0)

# Copy the workbook, and get back the style
# information in the `xlwt` format
outBook, outStyle = copy2(inBook)

# Get the style of _the_ cell:
xf_index = inSheet.cell_xf_index(0, 0)
saved_style = outStyle[xf_index]

# Update the cell, using the saved style as third argument of `write`:
outBook.get_sheet(0).write(0,0,'changed!', saved_style)
outBook.save(r"/tmp/format_output.xls")

rawDescription: Issues in preserving Excel formatting with Python's xlrd and xlutils


code:
ops = '+-*/'
operationsCount= sum(expr.count(op) for op in ops)
operandsCount = len(expr) - operationsCount

rawDescription: How to find the operand and the operation in a string

description: Find the operand and the operation in a string


code: (last_key, tot_cnt) = (None, 0)

rawDescription: How to get the Reducer to emit according to key type

description: Get the Reducer to emit according to key type


code:
sum(1 for i in xrange(14, len(lis)) if lis[i]==0)
sum(1 for i in xrange(14, 17) if lis[i]==0)

rawDescription: Count number of values in python

description: Count number of values in python


code:
executor = ProcessPoolExecutor(2)

async def extract_links(url):
    data = await download(url)
    links = parse(data)
    # Now your main process can handle another async functions while separate process running
    links_found = await loop.run_in_executor(executor, search_in_very_big_file, links)

rawDescription: When to use and when not to use Python 3.5 `await` ?


code:
import matplotlib.pyplot as plt

import multiprocessing

def do_plot(y_pos):
    fig = plt.figure()
    ax = plt.axes()
    ax.axhline(y_pos)
    fig.savefig('%s.pdf' % y_pos)

pool = multiprocessing.Pool()

for i in xrange(40):
    pool.apply_async(do_plot, [i])

pool.close()
pool.join()

rawDescription: matplotlib: faster PDF generation?

description: Matplotlib: faster PDF generation


code:
"TASTY"
[1, [2, "three"], "TASTY"]

rawDescription: custom object list json serialize in python

description: Custom object list json serialize in python


code:
import logging # Debug logging framework
logging.basicConfig(filename='c:\\loggggggmeee.txt')
logger = logging.getLogger('simulation')
logger.setLevel(logging.INFO)

#--------------- etc-------------------#

logger.info('This is sent to the console')

rawDescription: How can I send the output of a Logger object in python to a file?

description: Send the output of a Logger object in python to a file


code:
from pyspark.sql.functions import col

combined = (df1
    .join(df2, col("id2") == col("id2_"))
    .join(df3, col("item_id") == col("item_id_")))

rawDescription: Spark: Manipulation of Multiple RDDs

description: Spark: Manipulation of Multiple RDDs


rawDescription: Python subprocess to Bash: curly braces

description: Python subprocess to Bash: curly braces


code: nums = re.findall('\d+', line)

rawDescription: Extracting digits in line and storing them to list in Python


code: ''.join(x for x in s if ord(x) < 128)

rawDescription: Howto Remove Garbage Data from String

description: Howto Remove Garbage Data from String


code:
scaled_array = scale(readings_array, copy=True)
# do stuff like learning with scaled_array
plt.plot(readings_array)

rawDescription: matplotlib: Rescale axis labels

description: Matplotlib: Rescale axis labels


code:
class a(object):
    def __init__(self,x=10):
        self.x = x
    def __iter__(self):
        return self
    def next(self):
        if self.x > 0:
            self.x-=1
            return self.x
        else:
            raise StopIteration

rawDescription: i don't know why iter(not __iter__) function use in this place,what is the mean of iter in this code

description: I don't know why iter(not __iter__) function use in this place,what is the mean of iter in this code


code:
from AppKit import NSSpeechSynthesizer

NSSpeechSynthesizer.availableVoices()

rawDescription: calling Objective C functions from Python?

description: Calling Objective C functions from Python


code:
import functools

def countcalls(f):
    f.__callcount = 0

    @functools.wraps(f)
    def _countcalls(*args, **kwds):
        f.__callcount += 1
        print('  Called {0} time(s).'.format(f.__callcount))
        return f(*args, **kwds)
    return f, _countcalls

def fib(n):
    if n < 0:
        raise ValueError('n must be > 0')
    if n == 0 or n == 1:
        return 1

    return fib(n-1) + fib(n-2)

if __name__ == '__main__':
    counter, fib = countcalls(fib)

    print('Calling fib(3)...')
    x = fib(3)
    print('fib(3) = {0}'.format(x))

    print('Calling fib(3) again...')
    x = fib(3)
    print('fib(3) = {0}'.format(x))

    print('fib was called a total of {0} time(s).'.format(counter.__callcount))

rawDescription: Accessing function attribute created in a decorator outside that decorator


rawDescription: Repeat elements of list between each other until we reach a certain length


code:
import funcy
data = b'abcdefghijklmnopqrstuvwxyz'
list(funcy.chunks(6, data))

rawDescription: Chunking bytes (not strings) in Python 2 and 3


rawDescription: How do I separate words using regex in python while considering words with apostrophes?

description: Separate words using regex in python while considering words with apostrophes


code: df_out.to_csv('processed_data_out.csv', columns=['Output'], header=False, index=False)

rawDescription: CSV Pandas PYTHON

description: CSV Pandas PYTHON


code: self.helper.form_action = ''

rawDescription: Django Open / Edit record instead of Creating new


code:
with open(filename, 'rb') as f:
    things = list(iter(partial(parser, f), None))

rawDescription: Copying dicts from csv to a new dict-python


code:
a.ax_marg_x
a.ax_marg_y

rawDescription: Add data to a seaborn jointplot

description: Add data to a seaborn jointplot


code: x, y = data

rawDescription: Assign part of a string to a variable [Python]


code:
with open('strings.txt') as f:
   odds = [''.join(i) for i in zip(*(chars for chars in zip(*f)
                                   if len(set(chars)) != 1))]
odds

rawDescription: Python Diferences between lines of strings


code:
ff = foo.Foo()

foo.Foo.zap = lambda self,x: x + foo.Foo.y
dill.dumps(ff, byref=False)
dill.dumps(ff, byref=True)

rawDescription: Why dill dumps external classes by reference, no matter what?


code:
def mmatrix(rows, cols):
    return [[None for i in range(cols)] for j in range(rows)]

rawDescription: Inserting a new line in a 2D matrix

description: Inserting a new line in a 2D matrix


code:
def my_np_func(x):
    return np.where(x<5, 2, 2*x)

rawDescription: Including logic in a numerical function

description: Including logic in a numerical function


code:
system_a_unique = [tup for tup in system_a_devices.items() if tup[0] not in system_b_devices]
system_b_unique = [tup for tup in system_b_devices.items() if tup[0] not in system_a_devices]
both_systems = [tup for tup in system_b_devices.items() if tup[0] in system_a_devices]

rawDescription: Comparing Two Lists of Tuples Based On Each Tuple's First Value (But Returning ALL Tuple Values)


rawDescription: What is the most efficient way to subdivide a large list?


code:
from os import listdir

path = 'path/to/your/csv/files/'

for filename in listdir(path):
    if is_dated_csv(filename):
        # Do something with the desired .csv file
        pass

rawDescription: Using Python, I want to parse each file in one directory with format YY-MM-DD.CSV but ignore all others


code:
from functools import wraps

class hybridmethod(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls):
        context = obj if obj is not None else cls

        @wraps(self.func)
        def hybrid(*args, **kw):
            return self.func(context, *args, **kw)

        # optional, mimic methods some more
        hybrid.__func__ = hybrid.im_func = self.func
        hybrid.__self__ = hybrid.im_self = context

        return hybrid

rawDescription: python: hybrid between regular method and classmethod

description: Python: hybrid between regular method and classmethod


code:
class A():
    dictionary={'item1':'value1','item2':'value2'}

class B(A):
    dictionary = dict(A.dictionary, key='value')

A.dictionary
B.dictionary

rawDescription: Alter superclass' variable from subclass on Python


code:
from nltk.corpus import wordnet as wn
wn.synsets('dog')

rawDescription: How to get all the meanings of a word using python NLTK?

description: Get all the meanings of a word using python NLTK


code: import pandas as pd

rawDescription: Python: beautify numerical and dict outputs


code:
import numpy as np
from scipy.cluster.hierarchy import linkage
import matplotlib.pyplot as plt
from augmented_dendrogram import augmented_dendrogram

# Generate a random sample of `n` points in 2-d.
np.random.seed(12312)
n = 100
x = np.random.multivariate_normal([0, 0], np.array([[4.0, 2.5], [2.5, 1.4]]),
                                  size=(n,))

plt.figure(1, figsize=(6, 5))
plt.clf()
plt.scatter(x[:, 0], x[:, 1])
plt.axis('equal')
plt.grid(True)

linkage_matrix = linkage(x, "single")

plt.figure(2, figsize=(10, 4))
plt.clf()

plt.subplot(1, 2, 1)
show_leaf_counts = False
ddata = augmented_dendrogram(linkage_matrix,
               color_threshold=1,
               p=6,
               truncate_mode='lastp',
               show_leaf_counts=show_leaf_counts,
               )
plt.title("show_leaf_counts = %s" % show_leaf_counts)

plt.subplot(1, 2, 2)
show_leaf_counts = True
ddata = augmented_dendrogram(linkage_matrix,
               color_threshold=1,
               p=6,
               truncate_mode='lastp',
               show_leaf_counts=show_leaf_counts,
               )
plt.title("show_leaf_counts = %s" % show_leaf_counts)

plt.show()

rawDescription: how to plot and annotate hierarchical clustering dendrograms in scipy/matplotlib

description: Plot and annotate hierarchical clustering dendrograms in scipy/matplotlib


code:
import x
i = x.getMyClassInstance()
i.somePureVirtualMethod()
i=2       # reassign i

rawDescription: How do I invoke a method on a C++ class pointer with swig wrappers?

description: Invoke a method on a C++ class pointer with swig wrappers


code:
def second_smallest(list):
    if len(list) < 2:
        raise ValueError("too few elements to find second_smallest")
    a, b = list[0], list[1]
    a, b = min(a,b), max(a,b)
    if len(list) == 2:
        return b
    c, rest = list[2], list[3:]
    if c < a:
        return second_smallest([c,a]+rest)
    if c < b:
        return second_smallest([a,c]+rest)
    return second_smallest([a,b]+rest)

rawDescription: Find the second smallest number in a list using recursion


code:
from mako import TemplateLookup

template_lookup = TemplateLookup(directories=['.'])
template = template_lookup.get_template("index.mako")
whitespace_mess = template.render(somevar="no whitespace here")
return whitespace_mess # Why stop here?

rawDescription: Strip whitespace from Mako template output (Pylons)


code:
from contextlib import contextmanager
@contextmanager
def cwd(path):
    from os import getcwd, chdir
    cwd = getcwd()
    chdir(path)
    yield
    chdir(cwd)

rawDescription: Can you set cwd for abspath?

description: Set cwd for abspath


rawDescription: How to replace consecutive spaces in a string in python

description: Replace consecutive spaces in a string in python


code: return max(usa_date, canada_date).strftime('%Y-%m-%d %H:%M')

rawDescription: How do I quickly compare dates from parsed XML in Python?

description: Quickly compare dates from parsed XML in Python


code: listobject = [1, 'two']

rawDescription: Python 'Functions are objects'

description: Python 'Functions are objects'


code: map(" ".join,zip(list1,list2))

rawDescription: How would one add two lists in this way in Python?


code:
from scipy.ndimage import find_objects,label
import scipy.misc
img=scipy.misc.imread('filename.jpg')
labeled,number=label(img) # (label) returns the lebeled objects while
signs=find_objects(labeled)  #this will extract the signs in your image

rawDescription: Python Image Library two color image to black and white


rawDescription: Selecting 3D surfaces with a selection box (in two different ways)


code:
def fizz_count(x, search_string, case_insensitive=False):
    if case_insensitive:
        x = [item.lower() for item in x]
    return x.count(search_string)

rawDescription: python list as function parameter

description: Python list as function parameter


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

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


code:
dct = {'cheese':'stilton', 'swallow':'african', 'ride':'coconuts'}
def mystr(self):
    return str(pd.Series(self))

dct.__str__ = mystr

rawDescription: How to print dict as a pandas.Series

description: Print dict as a pandas.Series


code: new_array = my_array[np.r_[2, 4, 6:len(my_array):3]]

rawDescription: Custom slicing in numpy arrays (get specific elements, then every n-th) possible?


code:
info = input('Line: ').split()
setdict[info[0]] = set(info[1:])

rawDescription: Input Defines Multiple Set Names & Content in Python


code: [x[0] for x in l1 if any(x[0]==y[0] for y in l2)]

rawDescription: Comparing elements between elements in two lists of tuples


code:
m=np.array(m)
inds = np.triu_indices_from(m,k=1)
m[(inds[1], inds[0])] = m[inds]
m

rawDescription: transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format

description: Transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format


rawDescription: Sum Lists' value with corresponding index value in Python


code:
def round_down(x, a):
    return math.floor(x / a) * a

rawDescription: Python rounding a floating point number to nearest 0.05


rawDescription: Set a value deep in a dict dynamically

description: Set a value deep in a dict dynamically


rawDescription: Python how to change the value of a variable on the fly


code:
import Tkinter as Tk

class App(object):
    def __init__(self):
        self.root = Tk.Tk()
        self.root.wm_title("Fibonacci Calculator")
        #self.root.wm_iconbitmap("@icon2.xbm")
        Tk.Label(self.root, text="Set the digit number you want.").pack()

        self.digits = Tk.StringVar()
        Tk.Entry(self.root, textvariable=self.digits).pack()
        Tk.Button(self.root, text="Calculate", command=self.clicked).pack()

        self.result = Tk.Label(self.root, text=" ")
        self.result.pack()

        self.root.mainloop()

    @staticmethod
    def fibonacci(idx):
        # Your function here
        # Make sure this function accepts as its only argument the index
        return idx ** 2

    def clicked(self):
        idx = int(self.digits.get())
        out = App.fibonacci(idx)
        self.result['text'] = out

App()

rawDescription: Taking input from user and returning an answer in TKinter


code:
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', Paragraph('Here is large field retrieve from database', styles['Normal']), '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data)
elements.append(t)
doc.build(elements)

rawDescription: How to resize column to content in ReportLab?

description: Resize column to content in ReportLab


code:
# Since order of the names doesn't matter, we can use the set() option
matching_names = set(sheet_one_names) & set(sheet_one_names)
...
# Here, order does matter since we're comparing rowdata..
# not just if they match at some point.
matching_rowdata = [i for i, j in zip(columndata_one, columndata_two) if i != j]

rawDescription: Excel diff with python

description: Excel diff with python


code:
df['e-mail'], df['date'] = zip(*map(process_index, df.index))
df.set_index(['e-mail', 'date'])

rawDescription: Coverting Index into MultiIndex (hierachical index) in Pandas


code:
import scipy.stats

crosstab = ...
scipy.stats.chi2_contingency(
  crosstab.drop(crosstab.columns[0]).toPandas().as_matrix()
)

rawDescription: Use the result from Cross tab (spark dataframe) for chi-square test in SparkMlib


code:
# Gang of monsters
monsters = [Monster() for x in range(10)]
magician = Magician()

# Prepare for battle
while magician.magic > 0:
    magician.magic_armor()

# Put on some chain mail
magician.armor += 5

while magician.hp > 0:
    for m in monsters:
            m.punch(magician)

rawDescription: Sharing Class Variables

description: Sharing Class Variables


code:
# Generate a binary array of matches for all elements in i_mask against
# an array of indices going from 0 to numCells
matches = i_mask.ravel() == np.arange(numCells)[:,None]

# Do elementwise multiplication against s_image and sum those up for
# each such index going from 0 to numCells. This is essentially doing
# matix multiplicatio. Finally elementwise divide by pixel_counts
out = matches.dot(s_image.ravel())/pixel_counts

rawDescription: Vectorized version of array calculation

description: Vectorized version of array calculation


code:
('Steve', 'Brett', 'Dan')
('Steve', 'Brett', 'Phil')
('Steve', 'Mick', 'Dan')
('Steve', 'Mick', 'Phil')
('Steve', 'Foo', 'Dan')
('Steve', 'Foo', 'Phil')
('Mark', 'Brett', 'Dan')
('Mark', 'Brett', 'Phil')
('Mark', 'Mick', 'Dan')
('Mark', 'Mick', 'Phil')
('Mark', 'Foo', 'Dan')
('Mark', 'Foo', 'Phil')
('Tom', 'Brett', 'Dan')
('Tom', 'Brett', 'Phil')
('Tom', 'Mick', 'Dan')
('Tom', 'Mick', 'Phil')
('Tom', 'Foo', 'Dan')
('Tom', 'Foo', 'Phil')

rawDescription: Python combinatorials w/o repetition - Pyncomb?


code:
for sel in response.css('nav.subcategorynav li'):
    item = AhLinksItem()
    item['title'] = sel.xpath('.//a/@href').extract()
    yield item

rawDescription: Not getting the right result using XPath with python scraper


code: np.sum(np.isclose(adj1, adj2))

rawDescription: Python: Count similar elements of two matrices


code: newline = (oldline+" "+(str(score)))

rawDescription: Python: Storing data in a text file and appending particular/individual lines


code: ''.join(map(codes.get, text))

rawDescription: What's an efficient way to encode a (very long) string from a dictionary? (Python)


code: self.wstdwnbtn = wx.StaticBitmap(self.wbtn, -1, self.shutdownbtn)

rawDescription: wxPython - Bitmap button won´t be destroyed

description: WxPython - Bitmap button won´t be destroyed


code:
import Image

from math import cos
from math import pi
from math import sin
from numpy import array
from numpy import uint8
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from sys import argv

# Classes ----------------------------------------------------------------------
class AppGL(object):
    def __init__(self, title, position=(100, 100), size=(400, 400)):
        # Properties -----------------------------------------------------------
        self.angle_delta = 4.0
        self.position = position
        self.rotateX = [0, 1.0, 0.0, 0.0]
        self.rotateY = [0, 0.0, 1.0, 0.0]
        self.size = size
        self.translate = [0.0, 0.0, 0.0]
        self.textures = dict()

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

        # GLUT initialization --------------------------------------------------
        glutInit(argv)
        glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowPosition(*self.position)
        glutInitWindowSize(*self.size)
        glutCreateWindow(title)
        #-----------------------------------------------------------------------

        # Callbacks ------------------------------------------------------------
        glutDisplayFunc(self.onDisplayEvent)
        glutKeyboardFunc(self.onKeyEvent)
        glutMotionFunc(self.onMouseMotionEvent)
        glutMouseFunc(self.onMouseButtonEvent)
        glutReshapeFunc(self.onReshapeEvent)
        glutSpecialFunc(self.onSpecialKeyEvent)
        #-----------------------------------------------------------------------

        # Arrays ---------------------------------------------------------------
        self.tablelegmodel = array( list(table_leg_model()), "f")

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

    def loadTexture(self, path):
        if path in self.textures.keys():
            glBindTexture(GL_TEXTURE_2D, self.textures[path])
            return

        glDrawBuffer(GL_FRONT)
        glClearColor(0.25, 0.25, 0.75, 1.)
        glClear(GL_COLOR_BUFFER_BIT)

        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()

        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        glRasterPos3f(-0.9, 0.9, 0)
        glDisable(GL_TEXTURE_2D)
        glDisable(GL_LIGHTING)
        glutBitmapString(GLUT_BITMAP_HELVETICA_18, "Loading Texture " + path)
        glFinish()
        glDrawBuffer(GL_BACK)

        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
        glMatrixMode(GL_MODELVIEW)
        glPopMatrix()

        img = Image.open(path)
        texture_data = array(list(img.getdata()), uint8)

        texID = array([0], uint8)
        glGenTextures(1, texID)
        texID = texID[0]

        self.textures[path] = texID
        glBindTexture(GL_TEXTURE_2D, texID)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, texture_data)

    def onDisplayEvent(self):
        width, height = self.size
        aspect = float(width) / float(height)

        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glViewport(0, 0, width, height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(60.0, aspect, 1.0, 100.0)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluLookAt(0, 0, 4, 0, 0, -1, 0, 1, 0)

        glTranslatef(*self.translate)
        glRotatef(*self.rotateX)
        glRotatef(*self.rotateY)

        # Visual scene ---------------------------------------------------------
        glEnable(GL_DEPTH_TEST)

        glPushMatrix()
        glTranslatef(-0.1, -0.1, 0)

        self.loadTexture('textures/wood1.png')

        glEnable(GL_TEXTURE_2D)

        glInterleavedArrays(GL_T2F_V3F, 0, self.tablelegmodel)
        glDrawElements(GL_QUAD_STRIP, 10, GL_UNSIGNED_INT, array(xrange(0, 10), "d"))

        glPopMatrix()
        #-----------------------------------------------------------------------

        glutSwapBuffers()

    def onKeyEvent(self, key, x, y):
        if key == 'a':
            self.translate[0] += 1

        elif key == 'd':
            self.translate[0] -= 1

        elif key == 's':
            self.translate[1] += 1

        elif key == 'w':
            self.translate[1] -= 1

        elif key == 'q':
            self.translate[2] += 1

        elif key == 'e':
            self.translate[2] -= 1

        else:
            return

        glutPostRedisplay()

    def onMouseMotionEvent(self, x, y):
        pass

    def onMouseButtonEvent(self, button, state, x, y):
        pass

    def onReshapeEvent(self, width, height):
        self.size = width, height
        glutPostRedisplay()

    def onSpecialKeyEvent(self, key, x, y):
        if key == GLUT_KEY_UP:
            self.rotateX[0] += self.angle_delta

        elif key == GLUT_KEY_DOWN:
            self.rotateX[0] -= self.angle_delta

        elif key == GLUT_KEY_LEFT:
            self.rotateY[0] += self.angle_delta

        elif key == GLUT_KEY_RIGHT:
            self.rotateY[0] -= self.angle_delta

        else:
            return

        glutPostRedisplay()

    def run(self):
        glutMainLoop()
#-------------------------------------------------------------------------------

def table_model(radius, number_of_points):
    delta = 2 * pi / (number_of_points - 1)
    points = []

    for i in xrange(number_of_points):
        points.append((radius * cos(i * delta), radius * sin(i * delta), 0.05))
        points.append((radius * cos(i * delta), radius * sin(i * delta), 0))

    return points

def table_leg_model():
    return (
        0, 0,   0, 0.2, 0,
        0, 1,   0, 0.2, 1.0,
        1, 0,   0, 0, 0,
        1, 1,   0, 0, 1.0,
        #0, 0,   0.2, 0, 0,
        #0, 1,   0.2, 0, 1.0,
        #1, 0,   0.2, 0.2, 0,
        #1, 1,   0.2, 0.2, 1.0,
        #0, 0,   0, 0.2, 0,
        #0, 1,   0, 0.2, 1.0,
    )
#-------------------------------------------------------------------------------

# Main -------------------------------------------------------------------------
if __name__ == '__main__':
    AppGL("Moe's Tavern", (300, 100), (800, 600)).run()
#-------------------------------------------------------------------------------

rawDescription: May anyone explain to me why the texture doesn't show? [PyOpenGL]


rawDescription: Find closer number of a value considering given intervals - Python


code:
from string import ascii_lowercase
from itertools import count

lookup = dict(zip(ascii_lowercase, count(1)))
# or depending on taste
lookup = {letter: idx for idx, letter in enumerate(ascii_lowercase, start=1)}

rawDescription: Python: Use variable as a lookup reference in CSV and return value


code:
@ensure(a=positive,b=negative)
def foo(a,b):
    return a-b

rawDescription: Examples of open-source projects using Python 3 function annotations


code:
for key, values in result.items():
    result[str(key)] = ','.join(str(v) for v in values)

rawDescription: Map list to dictionary according to value from other list


code: d = lambda x: pd.datetime.strptime(x, '%d-%b-%y')

rawDescription: pandas reading dates from csv in yy-mm-dd format

description: Pandas reading dates from csv in yy-mm-dd format


code:
now = datetime.datetime.now()
if 0 <= now.weekday() <= 4:
    print ("It's a weekday!")
print (start <= now.time() <= end) # with start & end defined as above

rawDescription: How to check in python if I'm in certain range of times of the day?

description: Check in python if I'm in certain range of times of the day


rawDescription: Add multiple columns to a Pandas dataframe quickly


code:
def intersection(iterableA, iterableB, key=lambda x: x):
    """Return the intersection of two iterables with respect to `key` function.

    """
    def unify(iterable):
        d = {}
        for item in iterable:
            d.setdefault(key(item), []).append(item)
        return d

    A, B = unify(iterableA), unify(iterableB)

    return [(A[k], B[k]) for k in A if k in B]

rawDescription: Case-insensitive comparison of sets in Python


code:
# or calling from a script
bpy.ops.wm.simple_multi_operator(param_one='A')
bpy.ops.wm.simple_multi_operator(param_one='B')

# with more than one parameter pass the keywords and values
bpy.ops.wm.simple_multi_operator(param_one='B', param_two='Mode Y')

rawDescription: Call a function in a class from different class


code:
mx = max(b)
print(all(x >= mx for x in a))

rawDescription: Python: pairwise comparison between two lists: list a >= list b?


code:
def best_wild_hand(hand):
    dictSuit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}

    blackJoker = "?B"
    cards = [x + "S" for x in dictSuit]

    finalList = []
    if blackJoker in hand:
        hand.remove(blackJoker)
        for c in cards:
            finalList.append(hand + [c])
    return finalList

rawDescription: python can't seem to get a list to return properly

description: Python can't seem to get a list to return properly


code:
class met(type):
    def __init__(cls, name, bases, dct):
        super(met, cls).__init__(name, bases, dct)
        cls._test_member = "test_value"

object = met('object', (object,), {})

class someothertype(type): pass

class B(object):
    __metaclass__ = someothertype

rawDescription: Python default metaclasses

description: Python default metaclasses


code:
dups = [tuple(names) for names in dups.values()]
dups

rawDescription: In a list of tuples, return tuple[1] if tuple[0] is a duplicate of another tuple[0] in the list


code:
s.update({4})
s

rawDescription: Difference between union() and union_update() in sets, and others?


code:
class Counter(object):
    def __init__(self):
        self.count = 0
        # initialize count at zero
    def increment(self, by=1):
        self.count += by
    def decrement(self, by=1):
        self.count -= by

rawDescription: Why do we use classes in Python?

description: Why do we use classes in Python


code:
self.thread = threading.Thread(target=self.run, args=())
self.thread.setDaemon(True)
self.thread.start()

def run(self):
    while self.is_listening:
        cmd = ['application.exe']
        self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        self.proc.wait()
        data = ""
        while True:
            txt = self.proc.stdout.readline()
            data = txt[5:].strip()
            txt += data

rawDescription: How to run another process in a loop on a different thread

description: Run another process in a loop on a different thread


code:
from datetime import datetime
date1 = datetime.now()
'title="%(x)" % {"x": date1.strftime("%A")}'
'title="{}"'.format(date1.strftime("%A"))

rawDescription: Using line.rfind to find a changing variable


code: randomizedItems = map(items.__getitem__, indices)

rawDescription: Shuffle two lists in the same order in python


code: np.einsum('ijklmm->ijklm', arr)

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


code:
f = open('yourfile.txt', 'w')
f.write(listBox)
f.close()

rawDescription: Write wxListBox to .txt file in Python

description: Write wxListBox to .txt file in Python


rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


code:
df = pd.DataFrame({"C1": np.random.randint(10, size=100), "C2": np.random.choice(["X", "Y", "Z"], size=100)})
print(df.groupby(['C2']).agg(lambda x: tuple(stats.mode(x)[0])))

rawDescription: group by with mode as aggregator

description: Group by with mode as aggregator


code:
with open('listOfFruits.txt', 'r') as f:
    fruits = set([line.rstrip() for line in f])

with open('outfile.txt', 'w') as outf, open('allFruitData.txt', 'r') as inf:
    for line in inf:
        words = set(line.rstrip().split())
        # you can replace this `if` with `if fruits & words == set()`
        if not fruits & words:
            outf.write(line)

rawDescription: Comparing 2 txt files and creating a new txt file from what is absent in 1 or the files


code:
import poplib
import email
import os

class GmailTest(object):
    def __init__(self):
        self.savedir="/tmp"

    def test_save_attach(self):
        self.connection = poplib.POP3_SSL('pop.gmail.com', 995)
        self.connection.set_debuglevel(1)
        self.connection.user("<munged>")
        self.connection.pass_("<munged>")

        emails, total_bytes = self.connection.stat()
        print("{0} emails in the inbox, {1} bytes total".format(emails, total_bytes))
        # return in format: (response, ['mesg_num octets', ...], octets)
        msg_list = self.connection.list()
        print(msg_list)

        # messages processing
        for i in range(emails):

            # return in format: (response, ['line', ...], octets)
            response = self.connection.retr(i+1)
            raw_message = response[1]

            str_message = email.message_from_bytes(b'\n'.join(raw_message))

            # save attach
            for part in str_message.walk():
                print(part.get_content_type())

                if part.get_content_maintype() == 'multipart':
                    continue

                if part.get('Content-Disposition') is None:
                    print("no content dispo")
                    continue

                filename = part.get_filename()
                if not(filename): filename = "test.txt"
                print(filename)

                fp = open(os.path.join(self.savedir, filename), 'wb')
                fp.write(part.get_payload(decode=1))
                fp.close

        #I  exit here instead of pop3lib quit to make sure the message doesn't get removed in gmail
        import sys
        sys.exit(0)

d=GmailTest()
d.test_save_attach()

rawDescription: Save email attachment (python3, pop3_ssl, gmail)


code:
dt_clf = dt_clf.fit(np.hsplit(np.dstack(rgb).flatten(), len(face.flatten())),
                    face.flatten())

rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


code:
datetime.datetime.now(pytz.utc)
# returns datetime.datetime(2013, 4, 4, 10, 39, 1, 303329, tzinfo=<UTC>)

rawDescription: What does a utc replace do on a utc timestamp?


code:
funcList = [f0, f1, f2, f3, f4]
for idx, test in enumerate(myList[0:5]):
  if test: funcList[idx]()

rawDescription: Python: How to access only some boolean elements of a list with a loop?


rawDescription: Regex for matching block of text having a similar first line


code: line = "MECN3010 PREREQ MECN2011 COREQ TIMES1 TIMES2 MO3, MO4, FR5, TH1, TH2"

rawDescription: Extracting a specific PIECE of a line from a textfile(Python)


code:
team_with_user = Team.objects.filter(players__name="hello")
user_in_team = User.objects.filter(team__name="world")

rawDescription: Implementing a model for "teams" in django


code:
a = np.zeros((2))
a.shape
a.ndim

rawDescription: missing dimension in numpy array shape

description: Missing dimension in numpy array shape


rawDescription: How to use Pandas to keep most recent data from Series with overlapping times

description: Use Pandas to keep most recent data from Series with overlapping times


code:
merged = df1.merge(df2.rename_axis({"Mon-id": "NAME"}))
merged

rawDescription: Comparing two files and printing similar lines


code:
cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})
res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons,
                        options={'disp': False})
xbest = res['x']
# array([ 0.30000717,  1.89998823, -1.1999954 ])

rawDescription: Solving system using linalg with constraints


code: '= cap_net_raw+p'

rawDescription: How to read file capabilities using Python?

description: Read file capabilities using Python


rawDescription: Python function for removing zeroes right of decimal, including decimal point?


code:
import cutils_ext
import cutils_ext.cutils_ext

rawDescription: Can't load python extension module that exists


code: dTest.d = {'blah': 'blah'}

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


code:
for course in request.session['selected_courses']:
    if course['course_id'] == course_id:
        course['attendees'] = [
            a for a in course['attendees']
            if a['first_name'] != first_name and a['last_name'] != last_name
        ]
        break

rawDescription: Deleting Session Variables Django

description: Deleting Session Variables Django


code:
import re

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [ atoi(c) for c in re.split('(\d+)', text) ]

alist=[
    "something1",
    "something12",
    "something17",
    "something2",
    "something25",
    "something29"]

alist.sort(key=natural_keys)
print(alist)

rawDescription: How to correctly sort a string with a number inside?

description: Correctly sort a string with a number inside


rawDescription: How to find actual unique values in pandas DataFrame that match a regex

description: Find actual unique values in pandas DataFrame that match a regex


code:
import re
s = 'id=186 s_id=0  channel_name=[cspacer0]---BlaBla--- number=2'
re.findall(r'=(\S+)', s)

rawDescription: python regex finditer

description: Python regex finditer


rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code:
def drawSet (imgs,locs):
    for(i,l) in (imgs,locs):
        i.pos = l
        i.draw()
        window.flip()
        core.wait(0.25)

rawDescription: Duplicating random visual stimuli in Python/Psychopy


code:
targets = ('ABC', 'JKL')

def fuzzy_match(target, some_text):
    return target in some_text # or something fancier

found_header = False
for i in xrange(1, sheet.nrows):
    row_text = [
        v.upper()
        for v, t in zip(sheet.row_values(i), sheet.row_types(i))
        if t == xlrd.XL_CELL_TEXT # avoid non-text cells; see note below
        ]
    found_header = all(
        any(fuzzy_match(target, item) for item in row_text)
        for target in targets
        )
    if found_header:
        header_row = i
        break

rawDescription: Parsing for Column Headings in Excel worksheet with Python


rawDescription: Long long data type python

description: Long long data type python


code:
plt.text(0.5, 0.5,
         r'$\mathsf{sin\left(\frac{\pi}{180} f_1 \theta + \varphi_1\right)'
         r'     + B sin\left(\frac{\pi}{180} f_2 \theta + \varphi_2\right)}$')

rawDescription: matplotlib raw string line break in code

description: Matplotlib raw string line break in code


code:
blokk = [[]]*15
blokk
blokk[0].append(1)
blokk
blokk = [[] for _ in range(15)]
blokk
blokk[0].append(1)
blokk

rawDescription: How can I add different elements to a list in a list? Python 3

description: Add different elements to a list in a list? Python 3


code:
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def save_user(self, request, sociallogin, form=None):
        user = super(SocialAccountAdapter, self).save_user(request, sociallogin, form)

        url = sociallogin.account.get_avatar_url()

        avatar = download_file_from_url(url)  # here you should download file from provided url, the code is below
        if avatar:
            profile = user.user_profile  # access your profile from user by correct name
            profile.user_avatar.save('avatar%d.jpg' % user.pk, avatar)

        return user

rawDescription: django-allauth: Check whether user signed up using a social account

description: Django-allauth: Check whether user signed up using a social account


code:
alphabet = "bafmxpzv"
a = ['af', 'ax', 'am', 'ab', 'zvpmf']

rawDescription: Sorting string values according to a custom alphabet in Python


rawDescription: Longest strings from list

description: Longest strings from list


code: sorted(li, key=lambda k: di.get(k[0], 0))

rawDescription: How to sort a list based on dictionary values?

description: Sort a list based on dictionary values


code:
import pefile
pe = pefile.PE('./psfile.exe')
for section in pe.sections:
  print (section.Name, hex(section.VirtualAddress),
    hex(section.Misc_VirtualSize), section.SizeOfRawData )

rawDescription: How can i get .text section from PE file using pefile

description: Get .text section from PE file using pefile


code:
C = {'foo': {'spam': 1, 'ham': 2}, 'bar': {'spam': 43, 'eggs': 81}}
D = {'baz': {'vikings': 'singing'}, 'bar': {'monty': 'python'}}
{k: dict(C.get(k, {}), **D.get(k, {})) for k in C.viewkeys() | D.viewkeys()}

rawDescription: How can I merge two nested dictionaries together?

description: Merge two nested dictionaries together


code:
def __init__(self, master):
    ...
    self.variables = []
    self.checkboxs = []
    for text, value in OPTIONS:
        var = tk.StringVar()
        cb = tk.Checkbutton(self.typeFrame, text=text, variable=var,
                            onvalue=text, offvalue='', command=self.limit2)
        cb.pack(anchor = 'w')
        self.variables.append(var)
        self.checkboxs.append(cb)
    ...

def limit2(self):
    if sum(bool(v.get()) for v in self.variables) >= 2:
        # Disable non-selected items to limit selection
        for cb, v in zip(self.checkboxs, self.variables):
            if not v.get():
                cb['state'] = 'disabled'
    else:
        for cb in self.checkboxs:
            cb['state'] = 'normal'

rawDescription: Using tkinter I want to be able to get two inputs from the user using the same radiobuttons


code:
l=re.findall(r'\[([^\]]*)\]|,([^}]*)}',s)
[i.strip() for j in l for i in j if i]

rawDescription: Python string split multiple brackets

description: Python string split multiple brackets


code:
class StatusWriter(object):
    def write(self, msg):
        statusbar.config(text=msg[1:])

def count():
    sys.stdout = StatusWriter()
    i = 0
    def step():
        nonlocal i
        sys.stdout.write("\r{} of {}".format(i, 50))
        i += 1
        if i == 50:
            sys.stdout = sys.__stdout__
        else:
            root.after(100, step)
    root.after(100, step)

rawDescription: Using sys.stdout.write("\r...") in tkinter


code: all(len(b)==c for (c,b) in zip(counts,blocks))

rawDescription: How to parse block data from a text file into an 2D array in Python?

description: Parse block data from a text file into an 2D array in Python


code:
if form == 'a': #if form entered is a
    with open ('classa.csv','a',newline='') as keerthan:
        foo = csv.writer(keerthan,delimiter=',',)

        if keerthan.tell() == 0:                        # add this test!
            bar = ['Name', 'Surname', 'Score']
            foo.writerow(bar)

        bar = [[user,surname, score]]
        foo.writerows(bar)

rawDescription: writing string to a new row

description: Writing string to a new row


code:
s = '''I'm listening to "I Can Make It Better" by Luther Vandross on Pandora #pandora http://t.co/ieDbLC393F.'''
import re
m = re.search('to "?(.*?)"? by (.*?) on #?Pandora', s)
m
m.groups()

rawDescription: Regex expression after quotation on python


code:
import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.domcop.com/domains/great-expired-domains/',
                 headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36"})

soup = BeautifulSoup(r.text, 'html.parser')
for domain in soup.select("tbody#domcop-table-body tr td a.domain-link"):
    print(domain.get_text())

rawDescription: Python not getting text between html tags


code: option.setAttribute('selected', 'true')

rawDescription: How to choose value from an option list using PyQt4.QtWebKit

description: Choose value from an option list using PyQt4.QtWebKit


rawDescription: Retrieving python module path

description: Retrieving python module path


code: l = map(lambda x: x * 2, l)

rawDescription: How to multiply all integers inside list

description: Multiply all integers inside list


code:
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x-1)))
ax.xaxis.set_major_locator(ticker.FixedLocator(x))

rawDescription: Matplotlib logarithmic scale with zero value


code:
ny_tz = timezone('America/New_York')
ny_time = ny_tz.localize(datetime(2014, 9, 4, 10, 30, 2, 294757))

rawDescription: why does python new york time zone display 4:56 instead 4:00?

description: Why does python new york time zone display 4:56 instead 4:00


rawDescription: How to compress a data frame within a range?

description: Compress a data frame within a range


code:
def printNumberDoubleSize(num):
    num= str(num)
    for linenum, linetype in enumerate(typeforline) :
        line= ""
        for d in num :
            line+= digits[int(d)].lines[linenum]
        print( line )

printNumberDoubleSize(3475649560458)

rawDescription: Calculator 7 Segment Display w/ Width

description: Calculator 7 Segment Display w/ Width


code:
class GroupedAttribute(object):
    def __init__(self, group, obj):
        self.group = group
        self.obj = obj
    def __get__(self, obj, owner):
        return self.obj
    def __set__(self, obj, value):
        self.obj = value

rawDescription: python decorator for field

description: Python decorator for field


code:
def __call__(self, cls):
    def init(cls_self, *args, **kw):
        for param, value in zip(self.params, args):
            if param in kw:
                raise TypeError("Multiple values for %s"%param)
            kw[param]=value
        unexpected_args = list(set(kw)-set(self.params))
        if unexpected_args:
            raise TypeError("Unexpected args %s"%unexpected_args)
        missing_args = list(set(self.params)-set(kw))
        if missing_args:
            raise TypeError("Expected args %s"%missing_args)
        vars(cls_self).update(kw)
    cls.__init__ = init
    return cls

rawDescription: Create a python function procedurally (specifically the arguments)


code:
datetime.strftime(original_time, "%I") # '12'
datetime.strftime(original_time, "%I:30%p") # '12:30PM'
datetime.strftime(shifted_time, "%I:30%p") # '12:30AM'
datetime.strftime(shifted_time, "%Y %H %M %S") # '2015 00 32 46'
datetime.strftime(original_time, "%Y %H %M %S") # '2015 12 32 46'

rawDescription: getting the hour from current time

description: Getting the hour from current time


rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code:
aaaaaa
aaaaaa
aaaaaa

rawDescription: Displaying a tree in ASCII

description: Displaying a tree in ASCII


rawDescription: A copy of a list is altered on operations on the original list


code:
it = iter(iterable)
head = it.next()
tail = list(it)

rawDescription: python head and tail in one line

description: Python head and tail in one line


code:
with open(csvfile, "w") as csvfile:
    link_writer = csv.writer(csvfile)
    for tup in data_dict.items():
        link_writer.writerow(tup) # write key and value mfr/price in each column

rawDescription: Exporting Beautiful Soup table scrape results to CSV


code:
num_integers = int(input('How many integers do you want to input? '))
for x in range(num_integers):
    print(input('Integer {}: '.format(x)))

rawDescription: exec in Python 3

description: Exec in Python 3


code:
import numpy
import example
assert(42 == example.test_generic_uint8(42))
assert(42 == example.test_generic_uint8(numpy.uint8(42)))
assert(42 == example.test_specific_uint8(42))
assert(42 == example.test_specific_uint8(numpy.uint8(42)))
assert(42 == example.test_specific_int32(numpy.int32(42)))
example.test_specific_int32(numpy.int8(42))
example.test_generic_uint8(numpy.int8(42))

rawDescription: Extracting unsigned char from array of numpy.uint8


code: list_final = [l1 + l2 for l1, l2 in zip(list_1, list_2)]

rawDescription: Adding ith element of two lists

description: Adding ith element of two lists


code:
import csv

with open('somefile.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    total_us = [row[0] for row in reader]

print(total_us)

rawDescription: Append only numbers to a list from a mixed file


code:
while len(macTable) < numOfMACs:
    mac = input("Enter the MAC of the phone: "+".cfg")
    macTable.append(mac)

rawDescription: Creating new text files with names from an array in Python


code: np.rollaxis(np.rollaxis(a, ax, a.ndim), ax, a.ndim)[tuple(np.r_[b,c])]

rawDescription: How to return a subarray of a multidimensional array in Python?

description: Return a subarray of a multidimensional array in Python


rawDescription: How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?

description: Randomly pick an item from one of the lists inside a dictionary, and also get the key for the list


code:
from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def render_article(context, article):
    t = template.Template(article.text)
    return t.render(context)

rawDescription: Insert content in the middle of a Django template variable


rawDescription: Cannot forward an email with attachments using imap and smtplib


code:
import os
v = [i for i in os.environ.iteritems()]
pl('env is %s' %(repr(v)))

rawDescription: Access Request Parameters in invoked script of Python CGIHTTPServer


code:
parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
parsed.columns

rawDescription: Reading an Excel file in python using pandas


code:
def customRange(lst):
    if lst[0][0] != lst[1][0]:
        for c in range(ord(lst[0][0]), ord(lst[1][0])+1):
            yield chr(c) + lst[0][1]
    else:
        for n in range(int(lst[0][1]), int(lst[1][1])):
            yield lst[0][0] + str(n)

rawDescription: Range with alphabets Python

description: Range with alphabets Python


code: image.put("#%02x%02x%02x" % (red, green, blue), (x, y))

rawDescription: How to change the pixel color of a PhotoImage python

description: Change the pixel color of a PhotoImage python


code:
# some fake data (has values between 0 and 255 for r, g, and b)
H, W = 20, 20
a = np.random.randint(0, 256, (H,W,3))
b = np.random.randint(0, 256, (H,W,3))

# clean the images:
ac = clean(a)
bc = clean(b)

# build a list of all pairs of all 8 colors using itertools.product:
col_combos = itertools.product(itertools.product((0,255), repeat=3), repeat=2)

# now apply the comparison to the images for each pair of colors
col_dict = { (c1,c2): compare_colors(ac, bc, c1, c2) for c1,c2 in col_combos }

rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


code:
class MyAdminSite(AdminSite):
    app_index_template = "my/new/admin/app_index.html"

rawDescription: Two instances of django admin site - templates


code:
def extract_chunks(tagged_sent, chunk_type):
    grp1, grp2, chunk_type = [], [], "-" + chunk_type
    for ind, (s, tp) in enumerate(tagged_sent):
        if tp.endswith(chunk_type):
            if not tp.startswith("B"):
                grp2.append(str(ind))
                grp1.append(s)
            else:
                if grp1:
                    yield " ".join(grp1), "-".join(grp2)
                grp1, grp2 = [s], [str(ind)]
    yield " ".join(grp1), "-".join(grp2)

rawDescription: How to extract chunks from BIO chunked sentences? - python

description: Extract chunks from BIO chunked sentences? - python


code:
import boto

conn = boto.connect_s3()
bucket_name = 'mybucket'
key_name = 'mykey'

bucket = conn.lookup(bucket_name)
for k in bucket.list_versions(key_name):
    print(k.name, k.version_id, k.last_modified)

rawDescription: Mass Restore a Prior Version on Amazon's S3


rawDescription: How to change the color of ttk button

description: Change the color of ttk button


code:
from StringIO import StringIO
s = StringIO()
z = np.array([1,2,3])
np.savetxt(s,z[None, :],delimiter='hi')
s.getvalue()

rawDescription: Delimiter of numpy.savetxt

description: Delimiter of numpy.savetxt


code: data.pivot_table(index="A", columns="B", aggfunc="count", fill_value=0)

rawDescription: Get count of all unique rows in pandas dataframe


rawDescription: Converting string to datetime object in Python (GAE)?


rawDescription: Python: how to avoid writing numerous if/elifs in a function?


code:
import scipy.sparse as sps
cfq = np.array([(1,4),(3,2),(9,8)])
cfq_sps = sps.coo_matrix((cfq[:,1], ([0]*len(cfq), cfq[:,0])))
cfq_sps
cfq_sps.A # convert to dense array
weights = np.array([4,4,4,3,3,3,2,2,2,1])
cfq_sps.dot(weights)

rawDescription: Efficient way to decompress and multiply sparse arrays in python


code:
from operator import itemgetter
import pprint
pprint.pprint(sorted(((i,k) for i,j in INPUT for k in j), key=itemgetter(1)))

rawDescription: merging n sorted lists of tuples in python

description: Merging n sorted lists of tuples in python


code:
from kivy.base import runTouchApp
from kivy.lang import Builder

kv = '''
<ButImage@ButtonBehavior+AsyncImage>

FloatLayout:
    # we don't specify anything here so float layout takes the entire size of the window.
    ButImage:
        id: but
        # take 50% size of the FloatLayout
        size_hint: .5, .5
        # Make Button change it's opacity when pressed for visual indication
        opacity: 1 if self.state == 'normal' else .5
        source: 'http://www.victoriamorrow.com/sitebuildercontent/sitebuilderpictures/enter_button.gif'
        # Introduce Label incase you want text on top of the image
        Label:
            center: but.center
            # change text acc to but state
            text: "Normal" if but.state == 'normal' else 'down'
'''

if __name__ == '__main__':
    runTouchApp(Builder.load_string(kv))

rawDescription: Changing background of a Button to a different shape and Styles like shadow effect etc in kivy python


code:
from collections import OrderedDict
od = OrderedDict((('A', 0.25), ('C', 0.25), ('G',0.25), ('T', 0.25)))

def W(od):
    ran = random.uniform(0, 1)
    tot = 0
    for k, v in od.items():
        if tot <= ran < v + tot:
            return k
        tot += v

rawDescription: Python Dictionary, make range associated with its values and return them


code: somelist.sort(key = lambda x: x.resultType)

rawDescription: Python sorting - A list of objects

description: Python sorting - A list of objects


code:
import cv2, platform
import numpy as np
import urllib
import os

cam2 = "http://localhost:8090/cam2.mjpeg"

stream=urllib.urlopen(cam2)
bytes=''
while True:
    # to read mjpeg frame -
    bytes+=stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a!=-1 and b!=-1:
        jpg = bytes[a:b+2]
        bytes= bytes[b+2:]
    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
    # we now have frame stored in frame.

    cv2.imshow('cam2',frame)

    # Press 'q' to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

rawDescription: How to Capture Video Stream with OpenCV (Python)


rawDescription: How to add a matrix to itself in an iterative way?

description: Add a matrix to itself in an iterative way


rawDescription: bs4: search for special characters like 'ä'

description: Bs4: search for special characters like 'ä'


code:
import numpy as np
import cv2

im = cv2.imread('old_image.png')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
i=0
for cnt in contours:
     [x,y,w,h] = cv2.boundingRect(cnt)
     if h>60:
      cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)
      im3=im[y:y+h,x:x+w]
      cv2.imwrite('objects/pix%i.png'%i,im3)
      i+=1
cv2.imshow('norm',im)
cv2.imwrite('objects/shhh.jpg',im)
key = cv2.waitKey(0)

rawDescription: How segment image in python?

description: How segment image in python


rawDescription: How to change value of existing item's string in wxPython ObjectListView list_ctrl

description: Change value of existing item's string in wxPython ObjectListView list_ctrl


code:
def org_app(x0,y0,dirrad,length):
    x1 = x0 + np.rint(np.cos(dirrad) * length).astype(np.int32)
    y1 = y0 + np.rint(np.sin(dirrad) * length).astype(np.int32)

def new_app(x0,y0,dirrad,length):
    x1 = x0 + np.rint(ne.evaluate("cos(dirrad) * length")).astype(np.int32)
    y1 = y0 + np.rint(ne.evaluate("sin(dirrad) * length")).astype(np.int32)

rawDescription: Time-efficient way for creation of many random stick coordinates with numpy


code:
def f_():
    for func in reversed(functions):
        func()

rawDescription: Executing a function in reverse in Python


code: ['Cat', 'Mouse', 'Dog']

rawDescription: undestanding csv module delimiter

description: Undestanding csv module delimiter


code:
import sympy as sy
M = sy.Matrix(2,3, [1,2,3,4,5,6])
N = M.H * (M * M.H) ** -1
N.evalf(4)
M * N

rawDescription: Computing pseudo inverse of a matrix using sympy


rawDescription: Finding partial subsets python

description: Finding partial subsets python


code:
def count_seconds():
    for i in range (10,0,-1):
        time.sleep(1)
        yield 'Wait for %d seconds \r' % i,

rawDescription: Django 1.9 show a countdown for HttpResponse/Render response


code: subprocess.call("cmd /c cscript MyScript.vbs")

rawDescription: My Visual Basic scripts Open instead of running


code: y

rawDescription: Python/Numpy - Fill gaps between non-consecutive points?


code:
list_of_strings = ['foo', 'barbaz', 'spam-ham']
''.join([format(el, '<10') for el in list_of_strings])

rawDescription: Is there is way to justify substrings while performing join operation


rawDescription: What is the right way to organize python unittests into suites?


rawDescription: Fastest way to sort list of dates when adding to the list


code: env = env.Clone()

rawDescription: scons construction environment inheritance

description: Scons construction environment inheritance


code: d1.add(d2, fill_value=0)

rawDescription: Combine data frames while adding values in Pandas


code: map(max, zip(map(abs, entry[1][0]), map(abs, entry[1][1])))

rawDescription: Exporting a modified list to CSV

description: Exporting a modified list to CSV


rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
def treeview_changed(self, widget, event, data=None):
    adj = self.scrolled_window.get_vadjustment()
    adj.set_value( adj.upper - adj.page_size )

rawDescription: How to auto-scroll a gtk.scrolledwindow?

description: Auto-scroll a gtk.scrolledwindow


code: OrderedSet([1, 2, 3])

rawDescription: Does Python have an ordered set?

description: Does Python have an ordered set


code:
import jsonrpclib, json
from nltk.parse import DependencyGraph
server = jsonrpclib.Server("http://localhost:8080")
parses = json.loads(
   server.parse(
      'John loves Mary. '
      'I saw a man with a telescope. '
      'Ballmer has been vocal in the past warning that Linux is a threat to Microsoft.'
   )
)['sentences']
def transform(sentence):
    for rel, _, head, word, n in sentence['dependencies']:
        n = int(n)
        word_info = sentence['words'][n - 1][1]
        tag = word_info['PartOfSpeech']
        lemma = word_info['Lemma']
        if rel == 'root':
            # NLTK expects that the root relation is labelled as ROOT!
            rel = 'ROOT'
        # Hack: Return values we don't know as '_'.
        #       Also, consider tag and ctag to be equal.
        # n is used to sort words as they appear in the sentence.
        yield n, '_', word, lemma, tag, tag, '_', head, rel, '_', '_'
dgs = [
    DependencyGraph(
        ' '.join(items)  # NLTK expects an iterable of strings...
        for n, *items in sorted(transform(parse))
    )
    for parse in parses
]
# Play around with the information we've got.
pprint(list(dgs[0].triples()))
print(dgs[1].tree())
print(dgs[2].to_conll(4))  # doctest: +NORMALIZE_WHITESPACE

rawDescription: Stanford Universal Dependencies on Python NLTK


code:
import csv
from collections import defaultdict

def default_factory():
    return [0, None, None, 0]

reader = csv.DictReader(open('test.csv', newline=''))
cities = defaultdict(default_factory)
for row in reader:
    amount = int(row["AMOUNT"])
    cities[row["CITY"]][0] += amount
    max = cities[row["CITY"]][1]
    cities[row["CITY"]][1] = amount if max is None else amount if amount > max else max
    min = cities[row["CITY"]][2]
    cities[row["CITY"]][2] = amount if min is None else amount if amount < min else min
    cities[row["CITY"]][3] += 1
for city in cities:
    cities[city][3] = cities[city][0]/cities[city][3] # calculate mean

writer = csv.writer(open('out.csv', 'w', newline = ''))
writer.writerow(["CITY", "AMOUNT", "max", "min", "mean"])
writer.writerows([city] + cities[city] for city in cities)

rawDescription: Parse CSV file and aggregate the values

description: Parse CSV file and aggregate the values


code:
def __get__(self, instance, owner):
    return functools.partial(self.function, instance)

rawDescription: How to add property to a python class dynamically?

description: Add property to a python class dynamically


rawDescription: Why does s[len(s)-1:-1:-1] not work?

description: Why does s[len(s)-1:-1:-1] not work


rawDescription: Resizing an image in PIL

description: Resizing an image in PIL


rawDescription: Avoiding double counting in pandas merge


rawDescription: Python counter key value

description: Python counter key value


code:
from cmd import Cmd

class MyInterpreter(Cmd):

    prompt = '> '

    def do_prompt(self, line):
        "Change the interactive prompt"
        self.prompt = line + ': '

    def do_EOF(self, line):
        return True

    def do_foo(self, line):
        print('Running foo {l}'.format(l=line))

    def do_bar(self, line):
        print('Running bar {l}'.format(l=line))

if __name__ == '__main__':
    MyInterpreter().cmdloop()

rawDescription: Python - passing parameters in a command line app


code:
for ch in character:
    for ch in lowerLetters:
        lowerCount += 1
    for ch in upperLetters:
        upperCount += 1
    for ch in digits:
        digitCount += 1
    else:
        nonAlphaCount += 1

rawDescription: How to determine if character is uppercase, lowercase, digit, or non-alphanumeric without string methods

description: Determine if character is uppercase, lowercase, digit, or non-alphanumeric without string methods


code:
new_data = map(int, data.readlines())
new_data = [int(line) for line in data.readlines()]

rawDescription: How to extract numerical data from a text file

description: Extract numerical data from a text file


code:
counter = 0

def B_C():
    global counter
    counter += 1
    if counter == 1:
        print("1")
    elif counter == 2:
        print("2")
    else:
         if counter == 3:
             print("3")

B_C()
B_C()
B_C()

rawDescription: takes exactly 1 positional argument (0 given)

description: Takes exactly 1 positional argument (0 given)


code: keys_and_data = [dict(zip(list_keys, data)) for data in list_data]

rawDescription: Python: convert 2 lists to dict and repeat the keys with each set of data


code:
ssh_executable = os.path.join(rw_dir, 'my_ssh_executable.sh')
with repo.git.custom_environment(GIT_SSH=ssh_executable):
    repo.remotes.origin.fetch()

rawDescription: GitPython and SSH Keys?

description: GitPython and SSH Keys


code:
from pandas.tseries.offsets import BDay

d = pd.Timestamp('1/5/2015')
two_bdays_before = d - BDay(2)   # business days
two_bdays_later = d + BDay(2)

rawDescription: python pandas Slicing datetime dates by number of rows

description: Python pandas Slicing datetime dates by number of rows


code: pd.pivot_table(df, values='Value', index='Schoolname', columns='Attribute')

rawDescription: How to convert rows values in dataframe to columns labels in Python after groupby?

description: Convert rows values in dataframe to columns labels in Python after groupby


rawDescription: How can I detect last digits in python string

description: Detect last digits in python string


code:
sp_mat[0,:].getnnz()
# 3

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


rawDescription: How to convert a file path into treeview?

description: Convert a file path into treeview


code: tmp_keys = list(keys)

rawDescription: Removing current element from a list

description: Removing current element from a list


code:
arr = np.asarray(img, dtype=float)   # also simplified
value = math.floor(255*float(50)/100)
arr += value                           # the same as doing this in three separate lines

rawDescription: Image from array and image using point

description: Image from array and image using point


code:
def readFromFile(fileName): # Just declaring the function
    f = open(fileName, "r") # You once again open the file but this time in "r" or read mode. Make sure that the file already exists or you will get an error
    data = f.read()         # You read the file and store it's contents in to a variable data
    f.close()               # Once again, because you opened the file you have to close it
    return data             # Since this is a function that reads data, it has to reeturn (or 'give back') the data

rawDescription: Save variable a user input

description: Save variable a user input


rawDescription: Python equivalent for Perl's pack(H*, $string)


code: cols

rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


rawDescription: Insert missing elements in a nested list based on a condition - Python


code:
import operator
e1(3)

rawDescription: How to transform a arithmetic expression to a Python arithmetic function?

description: Transform a arithmetic expression to a Python arithmetic function


code: df.loc[df['size'].notnull() & df['value'] == 0].value = np.nan

rawDescription: Pandas: writing to original data frame. SettingWithCopyWarning


code:
body.append(paragraph("Hi."))
body.append(paragraph("My name is Alice."))
body.append(paragraph("Let's code"))

rawDescription: Python Docx Carriage Return

description: Python Docx Carriage Return


rawDescription: Metaclasses in Python: a couple of questions to clarify


code:
windows = [
        {
            "script": "myscript.py",
            "icon_resources": [(1, "icon.ico")]
        }
    ],

rawDescription: How to set icon on wxFrame?

description: Set icon on wxFrame


code:
df['ids'] = df['ids'].apply(lambda x: list(set(x)))
df

rawDescription: How to merge two list columns when merging DataFrames?

description: Merge two list columns when merging DataFrames


code:
with open('kmeans.dat', 'r') as f:
    kmeans = pickle.load(f)

rawDescription: i want to classify data by distance from centroids in python

description: I want to classify data by distance from centroids in python


code: render.hello("1 < 2")

rawDescription: why web.py template could not display <br>?

description: Why web.py template could not display <br>


code: [func(x) for x in lis]

rawDescription: Converting a text file to a list

description: Converting a text file to a list


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code: STATIC_URL = "https://aws.domain.com/"

rawDescription: How load Static Files in Models Admin File from Django?


code:
# First build a list of your cars
car1 = Car(3, "Red", "1996"),
car2 = Car(4, "Blue", "2001"),
car3 = Car(4, "Black", "2006")
cars = [car1, car2, car3]

# Then loop over it calling paint()
for car in cars:
    car.paint()

# I can can also still access them directly
car1.paint()

# And since Python uses references for everything, the version in the list will be updated as well
cars[0].color == car1.color # will be True

rawDescription: Do something for every instance of a class


rawDescription: Convert List of Numbers to String Ranges


rawDescription: using dictionaries and linked list python

description: Using dictionaries and linked list python


code:
x = np.arange(1,10).reshape(3,3)
print(np.array2string(x, separator=', '))

rawDescription: numpy save 2d array to text file

description: Numpy save 2d array to text file


code: re.sub(pattern, repl, string, count=0, flags=0)

rawDescription: Replacing a RegEx with a string of characters with the same length


code:
import string

with open('words.txt') as file:
    # List to store the capitalised lines.
    lines = []
    for line in file:
        # Split words by spaces.
        words = line.split(' ')
        for i, word in enumerate(words):
            if len(word.strip(string.punctuation + string.whitespace)) > 3:
                # Capitalise and replace words longer than 3 (without punctuation).
                words[i] = word.capitalize()
        # Join the capitalised words with spaces.
        lines.append(' '.join(words))
    # Join the capitalised lines.
    capitalised = ''.join(lines)

# Optionally, write the capitalised words back to the file.
with open('words.txt', 'w') as file:
    file.write(capitalised)

rawDescription: How to capitalize some words in a text file?

description: Capitalize some words in a text file


rawDescription: Matplotlib Image fit to equation?

description: Matplotlib Image fit to equation


code: result = [any(x in items for x in matches) for items in x_faces]

rawDescription: Matching array with elements in rows of matrix


rawDescription: Leibniz formula for π - Is this any good? (Python)


code:
def dotit(A,v, test=False):
    n,m = A.shape
    res = np.zeros(n)
    if test:
        for i in range(n):
            for j in range(m):
                if v[j]:
                    res[i] += A[i,j]*v[j]
    else:
        for i in range(n):
            for j in range(m):
                res[i] += A[i,j]*v[j]
    return res

rawDescription: Numpy: does matrix-vector multiplication not skip computation when some vector elements are equal to zero?


code:
compose1 = lambda fnlist: reduce(lambda fn1,fn2: lambda x : fn1(fn2(x)),
                                  fnlist or [lambda x:x])

rawDescription: Python lambda expression compose iterator script


rawDescription: Python: How to generate a full rank square binary matrix in which each row only has 3 bits 1


code:
import time, pexpect, os

newpid = os.fork()
if newpid == 0:
    # Child
    p = pexpect.spawn('sleep 123')
    p.sendintr()
else:
    # parent
    time.sleep(1000)

rawDescription: How to send signals from a backgrounded process using pexpect

description: Send signals from a backgrounded process using pexpect


code:
from mixer import fakers as f
from models import User

name = f.get_name()
country = f.get_country()
email = f.get_email()
city = f.get_city()

s = db.session
user = User(name=name, email=email, city=city, country=country)
s.add(user)
s.commit()
s.close()

rawDescription: Realistic data generator package available for Django


code: X = X + list(reversed(X))

rawDescription: Printing X-type pattern in Python 2.7

description: Printing X-type pattern in Python 2.7


code:
server = HTTPServerV6(('::', 8080), MyHandler)
server.serve_forever()

rawDescription: Python 3: Does http.server support ipv6?

description: Python 3: Does http.server support ipv6


code:
plotted = 10 * np.log10(values)

fig, ax = plt.subplots()
mesh = ax.pcolormesh(xbins, ybins, plotted, cmap='gist_earth')

ax.axis('tight')
ax.set(title='Plot of $10 * log_{10}(values)$')
fig.colorbar(mesh)

plt.show()

rawDescription: python, matplotlib: specgram data array values does not match specgram plot

description: Python, matplotlib: specgram data array values does not match specgram plot


code: return reduced_list[i]

rawDescription: Generate random numbers without using the last n values in Python


code:
import csv
from collections import OrderedDict

with open("in.csv") as f, open("average.csv", "w") as out:
    wr = csv.writer(out)
    d = OrderedDict()
    head = next(f)
    out.write(head)
    for row in csv.reader(f):
        d.setdefault(tuple(row[:2]), []).append(int(row[-1]))

    for k, v in d.items():
        out.write("{},{},{}\n".format(k[0], k[1], sum(v, 0.0) / len(v)))

rawDescription: Using python, I need to average value based on two keys in two columns from a CSV file


code:
import numpy as np
arr1 = - np.random.random((2,2))
arr2 = np.random.random((2,2))
arr = np.where(-arr1 < arr2, arr1, arr2)

rawDescription: Correct usage of numpy.nditer?

description: Correct usage of numpy.nditer


code:
import numpy
def makewalk(N):
  steps = numpy.random.randint(0, 2, N) * 2 - 1
  # an array of length N with random integers between 0 (inclusive) and 2 (exclusive)
  # multiplying it by two and subtracting 1 the numbers 0 and 1 become -1 and 1 respectively
  walk = numpy.cumsum(steps) # what it says, a cumulative sum
  return walk

rawDescription: how i can repeat loop for random walk?

description: How i can repeat loop for random walk


code: np_pix = numpy.array(srx_pix)

rawDescription: Python: Iterate over a sub-2d (nested) array to calculate its sum


code: theupdatedvalue

rawDescription: Freezing Function Arguments

description: Freezing Function Arguments


code:
Second
Third

rawDescription: XPath - Selecting preceding and following sibling of a specific node in a single query


code:
def begin_grab(self):
    self.GrabIm=MyDialog(self)
    self.GrabIm.exec_()  # exec_() for modal dialog
                           # show() for non-modal dialog

rawDescription: PyQt4 - closing a dialog window, exec_() not working


code:
import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']

rawDescription: Creating an empty Pandas DataFrame, then filling it?


code:
point_abc = Point(1,2)
point_def = Point(3,4)
point_abc.dist_to_point(point_def)

rawDescription: Python Class Desgin

description: Python Class Desgin


code:
f = foo(6)
f
next(f)
next(f)
next(f)

rawDescription: Is it possible to call a function, process some of its conditionals, break out, call it again and have it pickup where it left off?


code:
for link, title, date in zip(items['link'], items['title'], items['date']):
    print(link)
    print(title)
    print(date)
    print('------')

rawDescription: Turning list into dict

description: Turning list into dict


code:
import numpy as np
num_groups = 5
dfs = [grp for key, grp in df.groupby(np.random.randint(num_groups, size=len(df)))]

rawDescription: Divide pandas DataFrame rows in specific number of random sets


code:
sent = '''
The/AT grand/JJ jury/NN commented/VBD on/IN a/AT number/NN of/IN
other/AP topics/NNS ,/, AMONG/IN them/PPO the/AT Atlanta/NP and/CC
Fulton/NP-tl County/NN-tl purchasing/VBG departments/NNS which/WDT it/PPS
said/VBD ``/`` ARE/BER well/QL operated/VBN and/CC follow/VB generally/RB
accepted/VBN practices/NNS which/WDT inure/VB to/IN the/AT best/JJT
interest/NN of/IN both/ABX governments/NNS ''/'' ./.
'''
[nltk.tag.str2tuple(t) for t in sent.split()]

rawDescription: exracting chunks in python using nltk

description: Exracting chunks in python using nltk


rawDescription: Python, Math, and Latex: Display + Compute?


rawDescription: Multiply Series by distributing across MultiIndex levels


rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
class Thingy(object):
    def __init__(self, key, notkey):
        self.key, self.notkey = key, notkey
    def __eq__(self, other):
        return self.key == other.key
    def __hash__(self):
        return hash(self.key)

rawDescription: Custom comparison functions for built-in types in Python