code:
from gi.repository import Gio, GLib
import gi
import ctypes

class _PyGObject_Functions(ctypes.Structure):
   _fields_ = [
       ('register_class',
        ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p,
                          ctypes.c_int, ctypes.py_object,
                          ctypes.py_object)),
       ('register_wrapper',
        ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)),
       ('lookup_class',
        ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_int)),
       ('newgobj',
        ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_void_p)),
       ]

class PyGObjectCPAI(object):
   def __init__(self):
       PyCObject_AsVoidPtr = ctypes.pythonapi.PyCObject_AsVoidPtr
       PyCObject_AsVoidPtr.restype = ctypes.c_void_p
       PyCObject_AsVoidPtr.argtypes = [ctypes.py_object]
       addr = PyCObject_AsVoidPtr(ctypes.py_object(
           gi._gobject._PyGObject_API))
       self._api = _PyGObject_Functions.from_address(addr)

   def pygobject_new(self, addr):
       return self._api.newgobj(addr)

capi = PyGObjectCPAI()

rawDescription: Create python object from memory address (using gi.repository)


code:
while 1:
    try:
        url = queue.get_nowait()
    except Empty:
        # Check that all threads are done.
        if pool.free_count() == pool.size:
            break
    ...

rawDescription: Python Thread Communication Solution

description: Python Thread Communication Solution


rawDescription: Pythonic way to find highest values (and indexes) in list


code: s[s % 3 == 0].index.tolist()

rawDescription: Inverse lookup in pandas

description: Inverse lookup in pandas


code:
bytearray(e.elementB)
import numpy as np
np.frombuffer(e.elementB, dtype='uint8')

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

rawDescription: Is it possible to use 'else' in a python list comprehension?


code:
from django.db import models

class Model1(models.Model):
    name = models.CharField(max_length=20, primary_key=True)
    description = models.CharField(max_length=200)

class Model2(models.Model):
    name = models.CharField(max_length=20, primary_key=True)
    description = models.CharField(max_length=200)

rawDescription: How do I populate a ModelChoiceField from two Models

description: Populate a ModelChoiceField from two Models


code: output = cv2.filter2D(image[1:-1, 1:-1], -1, kernel)

rawDescription: OpenCV - altering the filter2D function

description: OpenCV - altering the filter2D function


rawDescription: Pythonic way to write a for loop that doesn't use the loop index


code: array.array('i', [0 if e == 1 else e for e in a])

rawDescription: Python: how do I replace all of the same elements in an int array?


rawDescription: Numpy - create matrix with rows of vector


code:
from google.appengine.ext import webapp

register = webapp.template.create_template_register()

rawDescription: Getting django's humanize working on App Engine


code:
obj = SampleUsage()
obj.process_data()

rawDescription: How do I design this procedural code as class based (object oriented)?

description: Design this procedural code as class based (object oriented)


code:
cur_cab = pd.read_csv(
            path,
            sep=";",
            header=None,
            parse_dates=[1],
            names=['cab_id', 'datetime', 'point'],
            skiprows=1)

rawDescription: How can I add columns in a data frame?

description: Add columns in a data frame


code:
class ReadOnlySelect(Select):
    def render(self, name, value, attrs=None, choices=()):
        final_attrs = self.build_attrs(attrs, name=name)
        display = "None"
        for option_value, option_label in chain(self.choices, choices):
            if utf8_encode(option_value) == utf8_encode(value):
                display = option_label
        output = format_html('<p>%s</p><input type="hidden" value="%s"  %s> ' % (display, value, flatatt(final_attrs)))
        return mark_safe(output)

rawDescription: Django Model form with read only properties


code:
class generalObjectLikeA:
    def some_method_in_b_but_bellows_classA(self):
        pass

rawDescription: How can I define a class in multi file(or module) in python

description: Define a class in multi file(or module) in python


code:
class Child(Parent):
    def f(self):
        return 2

rawDescription: How can I return a value to a superclass without overriding the parent function?

description: Return a value to a superclass without overriding the parent function


code: df

rawDescription: pandas to_html no value representation

description: Pandas to_html no value representation


code:
def convert(val):
    """
    Attempt to coerce type of val in following order: int, float, str
    """
    for type in (int, float, str):
        try:
            return type(val)
        except ValueError:
            pass
    return val

def make_config(*args, **kwargs):
    for arg in args:
        try:
            key,val = arg.split('=')
            kwargs[key.strip()] = convert(val.strip())
        except ValueError:   # .split() didn't return two items
            pass
    return kwargs

s1 = 'DataFile=scan1.dat'
s2 = 'NumberOfChannels=32'
config = make_config(s1, s2)

rawDescription: Extracting variables from set of strings in python


code:
"""Calculator using docopt

Usage:
  calc_docopt.py <operation> <num1> <num2>
  calc_docopt.py (-h | --help)

Arguments:
  <operation>  Math Operation
  <num1>       First Number
  <num2>       Second Number

Options:
  -h, --help     Show this screen.

"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Calculator with docopt')
    print(arguments)

rawDescription: Python - Difference between docopt and argparse


code:
def f():
    return 777

def g():
    return 777

print(f() is g())

rawDescription: Why is complex class not optimized to cache objects in Python?


rawDescription: More efficient way to iterate groupby Pandas dataframe?


code: tuple(tuple(int(j) for j in i.split()) for i in f.readlines())

rawDescription: How to read a text file and group them in tuple?

description: Read a text file and group them in tuple


code: return restful.request.form, 201, {'Access-Control-Allow-Origin': '*'}

rawDescription: Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods


code:
from timeit import timeit
d = {'keyname': ['foo', 'bar']}
timeit('[(k, v)] = d.items()', 'from __main__ import d')
timeit('[(k, v)] = d.iteritems()', 'from __main__ import d')

rawDescription: Unpack dictionary without knowledge of its key name


code:
answer = set()
for fname in myFiles:
    name, version = fname.rsplit('.', 1)[0].rsplit("_",1)
    if version.startswith('v'): # this is a versioned file
        answer.add(
          max((fname for fname in myFiles if fname.startswith(name) and not fname.rsplit('.', 1)[0].endswith('d')),
              key=lambda fname: int(
                     fname.rsplit('.', 1)[0].rsplit("_",1)[1].strip('v')) ))
    else:
        answer.add(fname)

rawDescription: Determining the latest version of a file (python)


code: os.system("explorer C:")

rawDescription: wxPython. How to open a folder with wxWidget (python) hyperlink?

description: WxPython. How to open a folder with wxWidget (python) hyperlink


code:
header = 'en-us,en;q=0.5'
from webob.acceptparse import Accept
lang = Accept(header)
'en' in lang
'fr' in lang
lang.best_match(('en', 'de', 'fr'))

rawDescription: Python - Extract Main Language Code from HTTP / Browser


rawDescription: How to save JSON string into CSV or TXT in Python?

description: Save JSON string into CSV or TXT in Python


code:
import numpy
import time
from os import urandom
from scipy import weave

SIZE = 2**20

def faster_slow_xor(aa,bb):
    b = numpy.fromstring(bb, dtype=numpy.uint64)
    numpy.bitwise_xor(numpy.frombuffer(aa,dtype=numpy.uint64), b, b)
    return b.tostring()

code = """
const __m128i* pa = (__m128i*)a;
const __m128i* pend = (__m128i*)(a + arr_size);
__m128i* pb = (__m128i*)b;
__m128i xmm1, xmm2;
while (pa < pend) {
  xmm1 = _mm_loadu_si128(pa); // must use unaligned access
  xmm2 = _mm_load_si128(pb); // numpy will align at 16 byte boundaries
  _mm_store_si128(pb, _mm_xor_si128(xmm1, xmm2));
  ++pa;
  ++pb;
}
"""

def inline_xor(aa, bb):
    a = numpy.frombuffer(aa, dtype=numpy.uint64)
    b = numpy.fromstring(bb, dtype=numpy.uint64)
    arr_size = a.shape[0]
    weave.inline(code, ["a", "b", "arr_size"], headers = ['"emmintrin.h"'])
    return b.tostring()

rawDescription: Simple Python Challenge: Fastest Bitwise XOR on Data Buffers


code:
import inspect

class AttributeInitType(type):
    def __call__(self, *args, **kwargs):
        obj = super(AttributeInitType, self).__call__(*args, **kwargs)
        argspec = inspect.getargspec(obj.__init__)
        defaults = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
        defaults.update(kwargs)
        for key, val in defaults.items():
            setattr(obj, key, val)
        return obj

rawDescription: Python metaclass default attributes

description: Python metaclass default attributes


code:
import urllib2,urllib
import re,os
import datetime
import time

mylist={
0:'http://www.trt.tv/baba-candir/bolumler/80212',
1:'http://www.trt.tv/filinta/bolumler/20198',
2:'http://www.trt.tv/dirilis-ertugrul/bolumler/20196',
}

today = datetime.datetime.today().weekday()
if today in mylist:
    # Forgotten?
    url = mylist[today]
    # Forgotten?

    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; az-AZ; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()
else:
    print('error: today (day %s) was not found in mylist.' % today)

rawDescription: import only day specified from url list

description: Import only day specified from url list


code:
def extrema(value, deltas):
    values = [value]
    for delta in deltas:
        value += delta
        values.append(value)
    average = sum(values)/len(values)
    threshold = (max(values) - min(values))/6
    min_threshold = average - threshold
    max_threshold = average + threshold
    min_value = max_value = None
    for value in values:
        if value < min_threshold:
            if min_value is None or value < min_value:
                min_value = value
        elif value > max_threshold:
            if max_value is None or value > max_value:
                max_value = value
        elif min_value is not None and max_value is not None:
            yield min_value, max_value
            max_value = min_value = None

rawDescription: Maxima and Minima Point of a Curve in Python


rawDescription: python regular expression for Extracting URL in between matched quotes whether it may be single,double or (

description: Python regular expression for Extracting URL in between matched quotes whether it may be single,double or (


code:
class Report(models.Model):
    report_name = models.CharField(max_length=140)
    report_description = models.TextField(null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)
    metric = models.ManyToManyField(Metric, through='MetricAssociation')

    @property
    def latest_status(self):
        return self.status_set.order_by("date").last()

rawDescription: Getting exclusive (only one) latest related object from relationship


code:
from bs4 import BeautifulSoup

with open('input') as fin, open('output', 'w') as fout:
    soup = BeautifulSoup(fin.read())
    for tag in soup.find_all('input', {'name': 'this is a test'}):
        tag['name'] = tag['name'].replace(' ', '')
    fout.write(str(soup))

rawDescription: bash script to replace spaces in html

description: Bash script to replace spaces in html


code:
def previousmonth(adate):
    m = adate.month - 1
    return m if m else 12

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
def find_substring(string, substring):
    pos = string.find(substring)
    return string[pos: pos + len(substring)]

rawDescription: Does python function str.find() returns string rather than index num


code:
from rest_framework import viewsets, mixins

class SampleViewSet(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    viewsets.GenericViewSet):
    ...

rawDescription: Disable a method in a ViewSet, django-rest-framework


rawDescription: python access variable by name-as-string -inverse eval

description: Python access variable by name-as-string -inverse eval


rawDescription: python re.search (regex) to search words who have pattern like {{world}} only

description: Python re.search (regex) to search words who have pattern like {{world}} only


code: os.chmod('test', 0o2770)

rawDescription: chmod with group inheritance rights rwx for user & group only

description: Chmod with group inheritance rights rwx for user & group only


code:
import yaml
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--names', action='append')
parser.add_argument('--ages', action='append')
parser.add_argument('--county', dest='county')
parser.add_argument('--config-file')   # automatic - to _ conversion

sample = "--config-file=stack28220581.yaml --name Ralph --age 40".split()
args = parser.parse_args(sample)
# add test that len(args.names)==len(args.ages) ??
with open(args.config_file) as f:
    ydict = yaml.load(f)
# {'county': 'somewhere', 'names': ['Bob', 'Jill'], 'ages': [22, 31]}

# add list attributes from args to the corresponding ydict values
for k,v in ydict.items():
    av = getattr(args,k,None)
    if av and isinstance(v, list):
        v.extend(av)
print(ydict)
# {'names': ['Bob', 'Jill', 'Ralph'], 'ages': [22, 31, '40'], 'county': 'somewhere'}

rawDescription: How can I append the values from an input file to the command line options using argparse?

description: Append the values from an input file to the command line options using argparse


code: "//option[contains(@value, '%s')]" % oracledata

rawDescription: Finding element by a variable

description: Finding element by a variable


code:
class C(B):
    def print_num(self):
        return self.num

rawDescription: Changing the bases of an object based on arguments to __init__


code:
def simple_method(in_data=SAMPLE_DATA, person='1', fill_gap_days=31, printit=False):
    date_format_str = "%m/%d/%Y"
    dat = np.array(in_data)
    dat = dat[dat[:, 0] == person, 1:]  # just this person's data
    # assume date intervals are already sorted by start date
    new_intervals = []
    cur_start = None
    cur_end = None
    gap_days = timedelta(days=fill_gap_days)
    for (s_str, e_str) in dat:
        dt_start = datetime.strptime(s_str, date_format_str)
        dt_end = datetime.strptime(e_str, date_format_str)
        if cur_end is None:
            cur_start = dt_start
            cur_end = dt_end
            continue
        else:
            if cur_end + gap_days >= dt_start:
                # merge, keep existing cur_start, extend cur_end
                cur_end = dt_end
            else:
                # new interval, save previous and reset current to this
                new_intervals.append((cur_start, cur_end))
                cur_start = dt_start
                cur_end = dt_end
    # make sure final interval is saved
    new_intervals.append((cur_start, cur_end))

    if printit:
        print_it(person, new_intervals, date_format_str)

    return new_intervals

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
def get_block_range (filename, lookupValue):
    with open(filename, 'r') as file:
        for num, line in enumerate(file, 1):
            if lookupValue in line:
                return num
        return num

rawDescription: How to find the line number of the end of file in python?

description: Find the line number of the end of file in python


code: dir(object)

rawDescription: Attribute assignment to built-in object

description: Attribute assignment to built-in object


code: [e[:6] + ''.join(pr) for e in lst for pr in itertools.product(string.digits, string.digits, string.digits)]

rawDescription: Append itertools.product() results to variable in Python


code:
result = vals[inv]
result

rawDescription: Numpy: Convert values in a 1-D array based upon dictionary


rawDescription: Python regular expression?

description: Python regular expression


code:
xx = x.reshape(2,-1).T  # faster, minor issue though
yy = y.reshape(2,-1).T
results = [pearsonr(a,b)[0] for a,b in zip(xx,yy)]
results = np.array(results).reshape(x.shape[1:])

rawDescription: Any faster way to get the same results?

description: Any faster way to get the same results


code:
#it will determine whether there is a same a in row or not
def search_row(sudoku_map_search, a, row):
    for i in range(9):
        if sudoku_map_search[row][i] == a:
            return 0;
    else:
        return 1;

rawDescription: Sudoku with python

description: Sudoku with python


code:
tokens = nltk.wordpunct_tokenize("Hei på deg øyerusk, du er meg en gammel dust, neida neida, det er ikke helt sant da."
                             "Men du, hvorfor så brusk, ikke klut i din susk på en runkete lust")

rawDescription: Utf-8 issues with python and nltk

description: Utf-8 issues with python and nltk


code:
class my_update(tk.Frame):
    def __init__(self,parent, friend):
        #                     ^^^^^^
        # accept another child reference as `freind` as save it as self.friend
        tk.Frame.__init__(self,parent)
        self.friend = friend # <-- save reference to another child

        self.b=tk.Button(self,text="update",command=self.ButtonPushed)
        self.b.grid()
        self.grid()

    def ButtonPushed(self):
        self.friend.ButtonPushed() # <-- call another child's method freely.

rawDescription: tkinter : how to call a method of a child from another child

description: Tkinter : how to call a method of a child from another child


code:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
    entry = {'name': args.name, 'url': args.url}
    feeds.append(entry)
    json.dump(feeds, feedsjson)

rawDescription: Appending data to a json file in Python

description: Appending data to a json file in Python


code:
def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join(instance.directory_string_var, filename)

class Archivo(models.Model):
    archivo = models.FileField(upload_to = get_file_path)
    directory_string_var = 'default_directory_string_var'

rawDescription: Change filename before save file in Django


code:
def calc(grp):
    return DataFrame([(grp.ID2.iloc[0],grp.score[:2].mean())],columns=['ID2','top3avg'])

rawDescription: Outputting a DataFrame instead of Series from a multiple return value groupby-apply operation


code:
pandas_data["Day of the Week"] = pandas_data["Date"].dt.dayofweek
grouped_data = pandas_data.groupby('Day of the Week').aggregate(np.mean)
print(grouped_data)

rawDescription: Categorize Data by Day of Week Python

description: Categorize Data by Day of Week Python


code:
set_condition = threading.Condition()
current_args = set()

def fn_set(arg):
    set_condition.acquire()
    try:
        while arg in current_args:
            set_condition.wait()
        current_args.add(arg)
    finally:
        set_condition.release()
    # do stuff
    set_condition.acquire()
    try:
        current_args.remove(arg)
        set_condition.notifyAll()
    finally:
        set_condition.release()

rawDescription: python conditional lock

description: Python conditional lock


code:
unq, idx, inv_idx, cnt = np.unique(user_data, return_index=True,
                                   return_inverse=True, return_counts=True)

print(unq)
# ['User0' 'User1' 'User2' 'User3' 'User4']

print(label_user[idx])
# [0, 1, 1, 0, 0]

rawDescription: Attach label information when averaging predictions across users


rawDescription: List conversion/transformation

description: List conversion/transformation


rawDescription: pandas: groupby and unstack to create feature vector for classification

description: Pandas: groupby and unstack to create feature vector for classification


code:
class myStr(str):
    def __add__(self, other):
        return len(self) + len(other)

foo = myStr('foo')
foo
foo + 'bar'

rawDescription: Classes: Alternative way of adding len()


code:
from sys import stdin
vl_list = []
for line in stdin.readlines():
    vl_list.extend(line.split(","))

rawDescription: Split values and store into a list

description: Split values and store into a list


code:
top_border_height                : 15
bottom_border_height             : 15
corrected_top_border_height      : 8
corrected_bottom_border_height   : 8

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


code:
high, low = bytes(0x607F)
hex(high)
hex(low)

rawDescription: Best way to split a hexadecimal in python?

description: Split a hexadecimal in python


code:
def index():
    return "Hello from yourapp.index.index!"

def test_endpoint():
    return "Got a post request at yourapp.index.test_endpoint"

rawDescription: How to have different py files to handle different routes?

description: Have different py files to handle different routes


code:
n = 100
filter = (df.groupby(['movie title'])['age']
          .transform(lambda group: group.count()) >= n)

rawDescription: Finding count of duplicate values and ordering in a Pandas dataframe


code:
deck = [{
         'name': 'drew',
         'lvl': 23,
         'items': ['sword', 'axe', 'mana_potion']},{
         'name': 'john',
         'lvl': 23,
         'items': ['sword', 'mace', 'health_potion']},{
         'name': 'somethingelse',
         'lvl': 10,
         'items': ['health_potion']}]
filter_cards(deck, {'lvl':23, 'items':['sword','mace']})

rawDescription: filter items by value in dict

description: Filter items by value in dict


code:
all_pats = [...]
combined_pat = r'|'.join(map(r'(?:{})'.format, all_pats))

rawDescription: Python Regex sub() with multiple patterns


code: res = data.reshape(data.shape[0], data.shape[1], -1).mean(axis=2)

rawDescription: How to get a mean array with numpy

description: Get a mean array with numpy


rawDescription: Python - while all list elements result in true for .isalpha issue


code:
from cartopy import crs

rp = crs.RotatedPole(pole_longitude=180.0,
                     pole_latitude=36.0,
                     central_rotated_longitude=-106.0,
                     globe=crs.Globe(semimajor_axis=6370000,
                                     semiminor_axis=6370000))

print(rp.proj4_params)

rawDescription: Plotting rotated pole projection in cartopy


code:
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace([0,1],['Female','Male'],inplace=True)
data

rawDescription: Pandas - replacing column values

description: Pandas - replacing column values


rawDescription: Python: Unexpected regex behaviour for {n} match


code:
def groupings(lst, min_size):

    lst = list(lst)

    # List for storing our final groupings
    results = []

    # Unfinished grouping, tuple storing the group and remaining sub-list
    # Initialize with the empty group and original list
    remaining = [([], lst)]

    # Continue as long as we have unfinished groupings
    while len(remaining):

        # Get an unfinished grouping
        current_group, current_lst = remaining.pop()
        n = len(current_lst)

        # If the last part of the list is big enough,
        # then record the grouping
        if n >= min_size:
            results.append(current_group + [current_lst])

        # Otherwise, discard it
        else:
            continue

        # Helper set for getting remainder below
        all_indices = set(range(n))

        # Iterate the group length from min_size to the length of our current list
        for r in range(min_size, n - 1):

            # This is a modified version of itertools.combinations()
            # http://docs.python.org/3.3/library/itertools.html#itertools.combinations

            # Add the first combination to our remaining list
            indices = list(range(r))
            remainder = current_lst[r:]
            group = current_group + [current_lst[:r]]
            remaining.append((group, remainder))

            while True:
                for i in reversed(range(r)):
                    if indices[i] != i + n - r:
                        break
                else:
                    break

                indices[i] += 1
                for j in range(i+1, r):
                    indices[j] = indices[j-1] + 1

                # If one of the remaining indexes is less than the minimum used index,
                # then a different iteration will handle it, so discard this one
                min_index = min(indices)
                remainder = []
                for i in all_indices.difference(indices):
                    remainder.append(current_lst[i])
                    if i < min_index:
                        break
                else:
                    # Add this combination to our remaining list
                    group = current_group + [[current_lst[i] for i in indices]]
                    remaining.append((group, remainder))

    return results

rawDescription: How to get all combinations of list groupings of at least a certain size?

description: Get all combinations of list groupings of at least a certain size


code: X * y.sum()

rawDescription: Multiplying each element of a numpy array and summing it up


code:
def parallel_dumb_prime(N, v, max_outstanding=10, dt=0.1):
    """dumb_prime where each factor is checked remotely

    Up to `max_outstanding` factors will be checked in parallel.

    Submission will halt as soon as we know that N is not prime.
    """
    tasks = set()
    # factors is a generator
    factors = generate_possible_factors(N)
    while True:
        try:
            # submit a batch of tasks, with a maximum of `max_outstanding`
            for i in range(max_outstanding-len(tasks)):
                f = factors.next()
                tasks.add(v.apply_async(is_factor, f, N))
        except StopIteration:
            # no more factors to test, stop submitting
            break
        # get the tasks that are done
        ready = set(task for task in tasks if task.ready())
        while not ready:
            # wait a little bit for some tasks to finish
            v.wait(tasks, timeout=dt)
            ready = set(task for task in tasks if task.ready())

        for t in ready:
            # get the result - if True, N is not prime, we are done
            if t.get():
                return False
        # update tasks to only those that are still pending,
        # and submit the next batch
        tasks.difference_update(ready)
    # check the last few outstanding tasks
    for task in tasks:
        if t.get():
            return False
    # checked all candidates, none are factors, so N is prime
    return True

rawDescription: How to use IPython.parallel map() with generators as input to function

description: Use IPython.parallel map() with generators as input to function


code: flattened= ([x for y in  l for x in y])

rawDescription: Extracting data from a list

description: Extracting data from a list


code: paragraphs = re.split(r"\n\n", DATA)

rawDescription: How match a paragraph using regex

description: How match a paragraph using regex


rawDescription: Parsing datetime in Python..?

description: Parsing datetime in Python..


code:
CELERY_RESULT_BACKEND = "redis"
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_CONNECT_RETRY = True

rawDescription: Django design pattern for web analytics screens that take a really long time to calculate


code:
List1 = sorted(List1)
List1

rawDescription: Can anyone explain why this sorting won't work?


code:
#concat column KEYS to df3
df2 = pd.concat([df2['KEYS'], df3], axis=1)

#stack - rows to one column for merging
df2 = df2.set_index('KEYS').stack().reset_index(level=1,drop=True).reset_index(name='TC_NUM')

rawDescription: Python CSV joining columns

description: Python CSV joining columns


code:
exp = 20 # the line where text need to be added or exp that calculates it for ex %2

with open(filename, 'r') as f:
    lines = f.readlines()

with open(filename, 'w') as f:
    for i,line in enumerate(lines):
        if i == exp:
            f.write('------')
        f.write(line)

rawDescription: How to add a string to a specific line

description: Add a string to a specific line


code:
appname_device
appname_data_point

rawDescription: Django data logging front end - phidgets


code:
# foo/daily_report.py
import logging_setup # side effect!
def main():
    ...

rawDescription: Logging in a Framework

description: Logging in a Framework


code:
soapProdAPI.objects.extra(
    select = {
        'rest_id'   : "(select rest_id from app_restProdAPI where app_restProdAPI.rest_host = app_soapProdAPI.soap_host OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip)",
        'rest_host' : "(select rest_host from app_restProdAPI where app_restProdAPI.rest_host = app_soapProdAPI.soap_host OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip)",
        'rest_ip'   : "(select rest_ip from app_restProdAPI where app_restProdAPI.rest_host = app_soapProdAPI.soap_host OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip)",
        'rest_mode' : "(select rest_mode from app_restProdAPI where app_restProdAPI.rest_host = app_soapProdAPI.soap_host OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip)",
        'rest_state': "(select rest_state from app_restProdAPI where app_restProdAPI.rest_host = app_soapProdAPI.soap_host OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip)"
    },
)

rawDescription: Converting LEFT OUTER JOIN query to Django orm queryset/query


rawDescription: To use BeautifulSoup to extract parts of texts in webpage title


rawDescription: How can I iterate over Pandas pivot table? (A multi-index dataframe?)

description: Iterate over Pandas pivot table? (A multi-index dataframe?)


code:
devnull = open('/dev/null', 'w')
subprocess.Popen(shlex.split(command_line), stdout=devnull)

rawDescription: python subprocess hide stdout and wait it to complete

description: Python subprocess hide stdout and wait it to complete


code:
def calc_sync(i):
    with histo_shared.get_lock():
        calc_histo(i)

rawDescription: Using numpy array in shared memory slow when synchronizing access


code:
class Foo(object):

    # ... same as it ever was ...

    def change_immutable(self):
        """If instance has list length of 1, change immutable_attr for all insts."""
        if len(self.instance_attr) == 1:
            type(self).immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


rawDescription: How to find first non-uppercase letter in the string using python

description: Find first non-uppercase letter in the string using python


rawDescription: python regex to match multi-line preprocessor macro

description: Python regex to match multi-line preprocessor macro


code:
changedstrings = []
for pos in range(2, len(liststring) - 2):
    liststring = list(string1)  # Move this line here
    if liststring[pos] != 'A':
        liststring[pos] = 'A'
        random1 = "".join(liststring)
        changedstrings.append(random1)
print(changedstrings)

rawDescription: Changing multiple positions in a list

description: Changing multiple positions in a list


code:
import pandas as pd

org = ['doclist[0]', 'doclist[0]', 'doclist[1]', 'doclist[4]', 'doclist[4]']
np = [0, 1, 1, 1, 0]
pr = [0, 0, 0, 0, 1]
df = pd.DataFrame({'Organization':org, 'NP':np, 'Pr':pr})

# Make a "lookup" dataframe of the sums for each category
lookup = df.groupby('Organization').agg(lambda x: x['NP'].sum() + x['Pr'].sum())

# Lookup the result based on the contents of the "Organization" row
# The "lookup" dataframe will have the relevant sum in _both_ "NP" and "Pr"
def func(row):
    org = row['Organization']
    group_sum = lookup.ix[org]['NP']
    return group_sum
df['Sum'] = df.apply(func, axis=1)

rawDescription: Using groupby to operate only on rows that have the same value for one of the columns pandas python


code:
def countSubStringMatch(target, key):
    index = 0
    instance_list = []

    while index <= len(target) - len(key):
        match = target.find(key, index)
        if match == -1:
            break
        instance_list.append(match)
        index = match + 1

    return instance_list or None

rawDescription: If-else inside a while statement

description: If-else inside a while statement


code:
admin.py
from django.contrib import admin

from .forms import CheckListForm
from .models import CheckList, CheckListType, CheckListOption

class CheckListAdmin(admin.ModelAdmin):
    form = CheckListForm

admin.site.register(CheckList, CheckListAdmin)
admin.site.register(CheckListType)
admin.site.register(CheckListOption)

rawDescription: Django Model Design - Many-To-Many Fields


code: p = subprocess.Popen(['bash', '-c', 'set -o pipefail; ' + command_str])

rawDescription: How to avoid passing shell constructs to executable using Popen

description: Avoid passing shell constructs to executable using Popen


code:
primes = gen_primes()
for _ in range(10):
    next(primes)

rawDescription: Python prime numbers generators in terminal


rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


rawDescription: group by on scipy sparse matrix

description: Group by on scipy sparse matrix


code:
from PIL import Image
img = Image.open('path/to/image')
square_one = white_bg_square(img)
square_one.resize((100, 100), Image.ANTIALIAS)
square_one.save('path/to/result')

rawDescription: Python adding extra area to image

description: Python adding extra area to image


code: mssql_cur.execute("SELECT * FROM mytable WHERE colx = ? AND coly = ?", (x, y))

rawDescription: Does pyodbc support any form of named parameters?


rawDescription: Key:Value Pairs from txt file into a dictionary


rawDescription: Add item to list in txt file using json (python)


code:
font_options = dict(ha='center', labelpad=28)

ax1.set_ylabel('Label1', **font_options)

...

ax2.set_ylabel('Label2', **font_options)

rawDescription: Matplotlib, Set multiple parameters at once?


code:
format(example)
from pprint import pprint
pprint(format(example))

rawDescription: Failing to append to dictionary. Python

description: Failing to append to dictionary. Python


code:
with open('myfile.txt', 'w') as f:
    f.write(rUsername)

rawDescription: How can I save input to a file and then check the input from the file?

description: Save input to a file and then check the input from the file


code:
import numpy as np
A = np.ones((5,5), dtype=int)
B = [1, 3, 7, 23]
A.put(B, [0]*len(B))
A

rawDescription: Python: multidimensional array masking

description: Python: multidimensional array masking


code:
from itertools import combinations
from os.path import dirname

imageHashes = {}
imageHashes['/directorya/jim.txt'] = 7
imageHashes['/directorya/nigel.txt'] = 68
imageHashes['/directoryb/ralph.txt'] = 17
imageHashes['/directoryb/baba.txt'] = 43

for path_a, path_b in combinations(imageHashes, 2):
    if dirname(path_a) == dirname(path_b):
        continue

    print("They're different!: {} vs. {}".format(path_a, path_b))

rawDescription: Using Python combinations in multilevel data


code:
for i in range(len(theta_degrees)):
    while theta_degrees[i] > 360:
        theta_degrees[i] -= 360

rawDescription: Simple loop for making sure angle is less than 360 [Python]


code:
xs
rolling_prod1(xs, 3)
rolling_prod2(xs, 3)

rawDescription: Fast numpy rolling_product

description: Fast numpy rolling_product


code:
l = [{'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}, {'followupdate': datetime.date(2013, 3, 29)}]
l
l.sort(key=lambda item:item['followupdate'], reverse=True)
l

rawDescription: Deduplicate and reorder dictionary

description: Deduplicate and reorder dictionary


code:
# initialize example data
import numpy as np
B = 1
dt = 1
position =  np.array([4, 4.34, 4.69, 5.02, 5.3, 5.7])

# do calculation
A = np.cumsum((B/position**2)*dt)
A = A - A[0]

rawDescription: How to make numpy.cumsum start after the first value [Python]

description: Make numpy.cumsum start after the first value [Python]


rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


code:
s_list2 = set(list2)
all_present = all(l in s_list2 for l in list1)

rawDescription: fast dict lookup

description: Fast dict lookup


rawDescription: grouping lines from a file with regular expression

description: Grouping lines from a file with regular expression


code:
import datetime
datetime.datetime.combine(
    datetime.date.today(),
    datetime.time(17, 0))

rawDescription: How do I get the datetime object of today's 5pm in Python?

description: Get the datetime object of today's 5pm in Python


code:
testmodule.py
""" my module test does x and y
"""
class myclass(object):
    ...

rawDescription: Can a python module have a __repr__?

description: Can a python module have a __repr__


code:
class A(object):
    pass

rawDescription: Limit which classes in a .py file are importable from elsewhere


code:
def primes(upper):
    n = 2; found = []
    while n < upper:
        # If a number is not divisble through all preceding primes, it's prime
        if all(n % div != 0 for div in found):
            yield n
            found.append( n )
        n += 1

rawDescription: Can this be made more pythonic?

description: Can this be made more pythonic


rawDescription: Python - finding same elements in three lists (ignoring empty list)


code: messages.success(request, 'Profile details updated.')

rawDescription: How to send message to django form

description: Send message to django form


code:
questions = []
with open("questions.txt") as inf:
    for l in inf:
        question, hints, answer = l[:-1].split("\t")
        questions.append(Question(question, hints.split("/"), answer))

rawDescription: How to fix this iterative python code and reduce repetition?

description: Fix this iterative python code and reduce repetition


rawDescription: Python: hex conversion always two digits


code:
def main():
    import doctest
    print(doctest.testmod())

    pubkey, privkey = keygen(2 ** 64)
    msg = input('Please type your message: ')
    h = encode(msg, pubkey, True)
    p = decode(h, privkey, True)
    print('-' * 20)
    print('message:', msg)
    print('encoded:', b64encode(h).decode())
    print('decoded:', p)
    print('private key:', key_to_str(privkey))
    print('public key:', key_to_str(pubkey))

rawDescription: Using user input in RSA code in Python

description: Using user input in RSA code in Python


code:
lst = [("This", 4), ("is", 2), ("a", 1), ("string", 6)]
new_string = ' '.join(item[0] for item in lst)
print(new_string)

rawDescription: How can I return a string from the list of pairs?

description: Return a string from the list of pairs


rawDescription: How to clear cookies in scrapy?

description: Clear cookies in scrapy


code:
import math
#import numpy as np
from pylab import plot, show

def model_generator(fun, initial=0, t_ini=0, t_end=30, t_step=1 ):
    """Generator of all the values of the given function in the given
       time interval

       fun: function of 2 arguments time and a previous value that
            return a new value
       initial: initial value
       t_ini: initial time
       t_end: end time
       t_step: time interval"""
    yield initial
    new_value = initial
    for t in range(t_ini, t_end+1, t_step):
        new_value = fun(t, new_value)
        yield new_value

def model_plot(mod_gen):
    """plot a given model in the form of a iterable"""
    result = list( mod_gen )
    plot(result)
    show()

def model_fun(t, SS_a, speed_SS_a=1, steepness_SS_a=1, w1=1, WS_a=1, threshold_SS_a=1  ):
    """function that represent my model of ..."""
    return SS_a + speed_SS_a * (
                (
                    (1/(1+math.exp(-steepness_SS_a * (w1 * WS_a - threshold_SS_a))))
                    -
                    (1/(1+math.exp(steepness_SS_a *threshold_SS_a)))
                )
                *
                (1+math.exp(-steepness_SS_a*threshold_SS_a))
                -
                SS_a
            )

def model_1():
    """original model"""
    model_plot( model_generator(model_fun) )

def model_2():
    """original model but with speed_SS_a=2"""
    fun = lambda t,SS_a: model_fun(t, SS_a, speed_SS_a=2)
    model_plot( model_generator(fun) )

def model_3():
    """random test model """
    fun = lambda t,p: t**2
    model_plot( model_generator(fun) )

model_1()
model_2()
model_3()

rawDescription: Accessing a value from an np.array from a while loop


rawDescription: Detect the column and row number where whitespace is occuring using Python programmatically


code:
for item in markList:
   if item in lowercase:
      lowercase = lowercase.replace(item, '')

rawDescription: I need help finishing my palindrome checking python code


code:
vars()[team_name] = team(team_name)
list_of_teams.append(team_name)

rawDescription: In python. How do I have a user change a dictionary value, when that dictionary is in a class?


rawDescription: Merge 3 Textfiles with python

description: Merge 3 Textfiles with python


code:
xml = '
{text}
'
def to_xml(start, end, text):
    return xml.format(start=start, end=end, text=text)

rawDescription: Replacing and ading text in text files in Python


code:
def my_round(n):
    if n <= 700:
        return round(n, -1)
    elif n <= 1000:
        return nearest_50(n)
    elif n <= 10000:
        return round(n, -2)
    else:
        return round(n, -3)

rawDescription: Rounding separate values in a list at the same time


code:
def create_grid(grid):
    y = 0
    size = LENGTH * WIDTH
    table = ''
    while y < size:
        x = 0
        while x < WIDTH:
            if x:
                table += '|'
            table += grid[y + x]
            x += 1
        table += '\n'
        y += WIDTH

    return table

rawDescription: Python: Using two while loops to create grid. No for loops


rawDescription: read and display raw image using python

description: Read and display raw image using python


code: likes = UserLikes(parent=user)

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


code:
for stanza in stanza1:
        oldMac = oldMac + stanza + "\n"

rawDescription: Beginner python: Formatting Lines

description: Beginner python: Formatting Lines


code: pd.concat(objs, axis=1)

rawDescription: Pandas groupby apply how to speed up

description: Pandas groupby apply how to speed up


rawDescription: combining lists: three lists into one new list

description: Combining lists: three lists into one new list


code:
means = np.arange(10).reshape(2,5) # make it multidimensional with shape 2, 5
stddevs = np.ones(10).reshape(2,5)

samples = np.random.normal(means, stddevs)

rawDescription: Python: NxM array of samples drawn from NxM normal distributions


rawDescription: I need to generate x random numbers in an interval from 1 to x but each number have to occur only once


code: a = b if b is not None else {}

rawDescription: What is the official name of this construct?


code:
print('You entered {:.1f}" which converts into '
      '{:.2f}m.'.format(imp_height_flt, imp_height_converted))

rawDescription: How to eliminate white space after backslash (Python 3.4)

description: Eliminate white space after backslash (Python 3.4)


code: ['Regex', 'How ', 'Capital ', 'Capital ', 'International Business Machine']

rawDescription: Getting rid of few entities using regex python


code:
B=np.array([a>.2 for a in A])
B

rawDescription: Python: compare an array element-wise with a float


code:
from random import seed, shuffle

r = range(5)
key = 'zap'
seed(key)
shuffle(r)

rawDescription: Influence of choosing string as seed of random on the output


code: logger = logging.getLogger(__name__)

rawDescription: Adding magic global methods to modules

description: Adding magic global methods to modules


code:
from tkinter import *

class Application(Frame):
    def __init__(self, master=None, on_reload=None):
        Frame.__init__(self, master)
        self.pack()
        self.my_reload = Button(self)
        self.my_reload["text"] = "Reload",
        self.my_reload["command"] = on_reload
        self.my_reload.pack()

rawDescription: how can I re-execute my Python program by clicking a button

description: Re-execute my Python program by clicking a button


code:
t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
[i for i, x in enumerate(t) if x]

rawDescription: Getting indices of True values in a boolean list


code:
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from add_location.forms import LocationForm, RegionForm

# The ID of the 'Create New Region' region
CREATE_NEW_REGION_ID = 1

def add_location(request):
    if request.method == 'POST':
        display_form = LocationForm(request.POST)
        region_form = RegionForm(request.POST)

        # Check if the form is a valid LocationForm
        if display_form.is_valid():
            location = display_form.save()
            # If region is the default 'Create new region' region, render the
            # page with a new RegionForm
            if location.region.id == CREATE_NEW_REGION_ID:
                # Note that the location is saved above, so if the region isn't
                # created in the next form, its region will stay
                # 'Create New Region'
                display_form = RegionForm(initial={'location': location})
            else:
                return HttpResponseRedirect('/thanks/')

        # If not a valid LocationForm, check if it is a valid RegionForm
        elif region_form.is_valid():
                # Save the region, get the location and update the
                # region of the location
                region = region_form.save()
                location = region_form.cleaned_data['location']
                location.region = region
                location.save()
                return HttpResponseRedirect('/thanks/')
    else:
        display_form = LocationForm()

    return render(request, 'form.html', {'form': display_form})

def thanks(request):
    return render(request, 'thanks.html')

rawDescription: Django: Creating a forgeinkey in a form on the spot.


code:
import inspect
import re

def foo(bar):
    # get the current call stack
    my_stack = inspect.stack()
    # get the outer frame object off of the stack
    outer = my_stack[1][0]
    # get the calling line of code; see the inspect module documentation
    #   only works if the call is not split across multiple lines of code
    calling_line = my_stack[1][4][0]
    # get this function's name
    my_name = my_stack[0][3]
    # do a regular expression search for the function call in traditional form
    #   and extract the name of the first parameter
    m = re.search(my_name + "\s*\(\s*(\w+)\s*\)", calling_line)
    if m:
        # finally, set the variable in the outer context
        outer.f_locals[m.group(1)] = 2 * outer.f_locals[m.group(1)]
    else:
        raise TypeError("Non-traditional function call.  Why don't you just"
                        " give up on pass-by-reference already?")

# now this works like you would expect
a = 15
foo(a)
print(a)

# but then this doesn't work:
baz = foo_bar
baz(a)  #  raises TypeError

# and this *really*, disastrously doesn't work
a, b = 15, 20
foo_bar, baz = str, foo_bar
baz(b) and foo_bar(a)
print(a, b)  # prints 30, 20

rawDescription: Send by ref/by ptr in python?

description: Send by ref/by ptr in python


code:
def setValue(derived, Input):
    derived.value = 0
    for elem in Input:
        derived.value += elem.value
    return derived

rawDescription: Assigning classes as variables

description: Assigning classes as variables


code:
objID = np.array([0, 0, 5, 5, 5, 7, 8, 8])
unique_objIDs, idx_unique_objIDs = np.unique(objID, return_index=True)

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
n = int(input("Please enter a number to find the times tables:"))
["{0} X {1} => {2}".format(n, i, n*i) for i in range(1,13)]

rawDescription: Multiplication Table program won't work

description: Multiplication Table program won't work


rawDescription: How do you join all models that reference a model into one table in Django?

description: Join all models that reference a model into one table in Django


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

mu=np.array([1,10,20])
sigma=np.matrix([[4,10,0],[10,25,0],[0,0,100]])
data=np.random.multivariate_normal(mu,sigma,1000)
values = data.T

kde = stats.gaussian_kde(values)
density = kde(values)

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
x, y, z = values
ax.scatter(x, y, z, c=density)
plt.show()

rawDescription: Multivariate kernel density estimation in Python


code: webbrowser.open ('file:///home/nobody') #your path here

rawDescription: Opening File Directory by using a button


rawDescription: Resampling a time series of events + duration into concurrent events


code: ts

rawDescription: Convert dataframe with odd timestamp to timeseries with pandas


code: soup = BeautifulSoup(features='xml')

rawDescription: Creating an XML document with BeautifulSoup


code:
all_challenges = session.query(Challenge).\
                  join(Challenge.attempts).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


rawDescription: Using NumPy in the correct way to apply a function to specific points in an array


code:
o1 = Other()
o1.content_object = a
o1.save()
o2 = Other()
o2.content_object = b
o2.save()

rawDescription: Django Releationship between multiple fields


rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


rawDescription: checkin python if a list of dictonaries does NOT contain a specific value

description: Checkin python if a list of dictonaries does NOT contain a specific value


code:
import pymongo

class mongoDB():  # you don't need ()'s here - only if you are inheriting classes
                  # you could inherit from object here, which is a good practice
                  # by doing class mongoDb(object):, otherwise you can just take
                  # them out

    conn = object # here, you're defining a class member - global for all instances
                  # generally, you don't instantiate an object pointer like this,
                  # you would set it to None instead.  It won't fail doing this,
                  # but it's not "right"

    def __init__(self):
        # the __init__ method is the constructor method - this will
        # allow you to initialize a particular instance of your class, represented
        # by the self argument.  This method is called when you call the class, i.e.
        # inst = mongoDb()

        # in this case, the conn variable is not a global.  Globals are defined
        # at the root module level - so in this example, only pymongo is a global
        # conn is a class member, and would be accessed by doing mongoDB.conn
        global conn

        # with that being said, you're initializing a local variable here called conn
        # that is not being stored anywhere - when this method finishes, this variable
        # will be cleaned up from memory, what you are thinking you're doing here
        # should be written as mongoDB.conn = pymongo.Connection("localhost", 27017)
        conn = pymongo.Connection("localhost",27017)

    def CreateCollection(name =""):
        # there is one of two things you are trying to do here - 1, access a class
        # level member called conn, or 2, access an instance member called conn

        # depending on what you are going for, there are a couple of different ways
        # to address it.

        # all methods for a class, by default, are instance methods - and all of them
        # need to take self as the first argument.  An instance method of a class
        # will always be called with the instance first.  Your error is caused because
        # you should declare the method as:

        # def CreateCollection(self, name = ""):

        # The alternative, is to define this method as a static method of the class -
        # which does not take an instance but applies to all instances of the class
        # to do that, you would add a @staticmethod decorator before the method.

        # either way, you're attempting to access the global variable "conn" here,
        # which again does not exist

        # the second problem with this, is that you are trying to take your variable
        # argument (name) and use it as a property.  What python is doing here, is
        # looking for a member variable called name from the conn object.  What you
        # are really trying to do is create a collection on the connection with the
        # inputed name

        # the pymongo class provides access to your collections via this method as a
        # convenience around the method, create_collection.  In the case where you
        # are using a variable to create the collection, you would call this by doing

        # conn.create_collection(name)

        # but again, that assumes conn is what you think it is, which it isn't
        dbCollection  = conn.name
        return dbCollection

if __name__ == '__main__':
    # here you are just creating a pointer to your class, not instantiating it
    # you are looking for:

    # database = mongoDB()
    database = mongoDB

    # this is your error, because of the afore mentioned lack of 'self' argument
    collection = database.CreateCollection("Hello")

rawDescription: Writing a simple MongoDB module in python


rawDescription: Is there a simpler way to change 0xff01 into \\uff01?


code:
instagram.authorize(callback=url_for(".oauth_authorized",
                                                next=redirect_url(),
                                                _external=True))

rawDescription: Redirect back in Flask

description: Redirect back in Flask


code:
for i in list1:
    for j in list2_dict[i]:
        # here j is a tuple in the form (name, value)
        function()

rawDescription: Looping at specified indexes

description: Looping at specified indexes


code:
import json
from urllib.request import urlopen

response = urlopen('https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json')
# the default encoding for JSON is UTF-8, but the response can give you
# a different codec
encoding = response.info().get_content_charset('utf-8')

data = json.loads(response.read().decode(encoding))

rawDescription: How do I go about parsing the contents of a large JSON file with patterns as opposed to having to manually access each entry?

description: Go about parsing the contents of a large JSON file with patterns as opposed to having to manually access each entry


code:
import types

def change_func_args(function, new_args):
    """ Create a new function with its arguments renamed to new_args. """
    code_obj = function.func_code
    assert(0 <= len(new_args) <= code_obj.co_argcount)
    # the arguments are just the first co_argcount co_varnames
    # replace them with the new argument names in new_args
    new_varnames = tuple(list(new_args[:code_obj.co_argcount]) +
                         list(code_obj.co_varnames[code_obj.co_argcount:]))
    # type help(types.CodeType) at the interpreter prompt for information
    new_code_obj = types.CodeType(code_obj.co_argcount,
                                  code_obj.co_nlocals,
                                  code_obj.co_stacksize,
                                  code_obj.co_flags,
                                  code_obj.co_code,
                                  code_obj.co_consts,
                                  code_obj.co_names,
                                  new_varnames,
                                  code_obj.co_filename,
                                  code_obj.co_name,
                                  code_obj.co_firstlineno,
                                  code_obj.co_lnotab,
                                  code_obj.co_freevars,
                                  code_obj.co_cellvars)
    modified = types.FunctionType(new_code_obj, function.func_globals)
    function.__code__ = modified.__code__  # replace code portion of original

if __name__ == '__main__':

    import inspect

    def f(x, y):
        return x+y

    def g(a, b):
        return f(a, b)

    print('Before:')
    print('inspect.getargspec(g).args: {}'.format(inspect.getargspec(g).args))
    print('g(1, 2): {}'.format(g(1, 2)))

    change_func_args(g, ['p', 'q'])

    print('')
    print('After:')
    print('inspect.getargspec(g).args: {}'.format(inspect.getargspec(g).args))
    print('g(1, 2): {}'.format(g(1, 2)))

rawDescription: creating a python function at runtime with specified argument names

description: Creating a python function at runtime with specified argument names


code:
import re

def repl(match):
    start, end = match.groups()
    return ','.join(str(i) for i in range(int(start), int(end)+1))

def expand(s):
    return re.sub('(\d+)-(\d+)', repl, s)

rawDescription: Expand certain substrings elegantly inside a larger string in python


code:
def split_on_angle_brackets(words):
    para = []
    bracket_stack = 0
    for word in words:
        if bracket_stack:
            if word == 'gt':
                bracket_stack -= 1
            elif word == 'lt':
                bracket_stack += 1
        else:
            if word == 'lt':
                if len(para) >= 7:
                    yield ' '.join(para)
                para = []
                bracket_stack = 1
            else:
                para.append(word)
    if para:
        yield ' '.join(para)

rawDescription: Looking for dictionary words in text file using dictionary in python


code:
a = "node1 ip up ether 40  46 server low".split()
b = "node1 ip <down> ether server <status>".split()

rawDescription: find indices where 2 list differ

description: Find indices where 2 list differ


code:
# Doc A
cursor1.execute("SELECT token, tfidf_norm FROM index WHERE doc_id = %s", (docid[i][0]))
doca = cursor1.fetchall()
# Doc B
cursor2.execute("SELECT token, tfidf_norm FROM index WHERE doc_id = %s", (docid[j][0]))
docb = cursor2.fetchall()
if len(doca) < len(docb):
    short_doc, long_doc = doca, docb
else:
    short_doc, long_doc = docb, doca
long_dict = dict(long_doc) # yes, it should be that simple
similarity = 0
for key, value in short_doc:
    if key in long_dict:
        similarity += long_dict[key] * value

rawDescription: Document Similarity: Comparing two documents efficiently


code:
def reverseList(listXS):
    return [] if not listXS else [listXS.pop()] + reverseList(listXS)

rawDescription: Using recursion to reverse a list in python?


rawDescription: Python regex, fetch names from a string

description: Python regex, fetch names from a string


code:
class arr(object):
    @staticmethod
    def mylog2(x):
        lx = 0
        while x > 1:
            x >>= 1
            lx += 1
        return lx
    def __init__(self, array):
        self.array = array
    def __getitem__(self, index):
        return self.array[arr.mylog2(index+1)]
    def __len__(self):
        return 1 << len(self.array)

rawDescription: How to plot an image with non-linear y-axis with Matplotlib using imshow?

description: Plot an image with non-linear y-axis with Matplotlib using imshow


code:
from operator import itemgetter
from itertools import groupby

[{'perms': dict.fromkeys((p['perm'] for p in group), True), 'id': key[0], 'user': key[1]}
 for key, group in groupby(inputlist, itemgetter('id', 'name'))]

rawDescription: Group by a list of dicts by two values in python


code:
maxval, i, j = max((item, i, j)  for i, row in enumerate(P)
                                 for j, item in enumerate(row))

print(maxval)
# 88.0

print(i, j)
# (2, 7)

rawDescription: I am using Python and I would like to find the maximum value(s) and position(s) of that(those) value(s) in a multidimensional list


code: yaml.dump({'foo': u'τί ἐστίν; 統一碼!!! ✢✪✺'})

rawDescription: YAML as failsafe file dump format (using pyyaml)?


code:
# A very simple representation for Nodes. Leaves are anything which is not a Node.
class Node(object):
  def __init__(self, left, right):
    self.left = left
    self.right = right

  def __repr__(self):
    return '(%s %s)' % (self.left, self.right)

# Given a tree and a label, yields every possible augmentation of the tree by
# adding a new node with the label as a child "above" some existing Node or Leaf.
def add_leaf(tree, label):
  yield Node(label, tree)
  if isinstance(tree, Node):
    for left in add_leaf(tree.left, label):
      yield Node(left, tree.right)
    for right in add_leaf(tree.right, label):
      yield Node(tree.left, right)

# Given a list of labels, yield each rooted, unordered full binary tree with
# the specified labels.
def enum_unordered(labels):
  if len(labels) == 1:
    yield labels[0]
  else:
    for tree in enum_unordered(labels[1:]):
      for new_tree in add_leaf(tree, labels[0]):
        yield new_tree

rawDescription: Enumerate all full (labeled) binary tree


code:
class Foo(object):
    global_cache={}
    @classmethod
    def set(cls, key, value):
        cls.global_cache[key] = value

rawDescription: Execute function without sending 'self' to it


code:
urls = open("c:/a2.txt", "r") # file with rss urls
results = []
for lines in urls:
    results.append(feedparser.parse(lines))
contents = []
for r in results:
    statusupdate = r.entries[0].description
    soup = BeautifulStoneSoup(statusupdate)
    for e in r.entries:
        contents.append((e.title, e.link, soup.find("img")["src"]))
with open(r'c:\a.txt', 'a') as f:
    for c in contents:
        f.writelines('"')
        f.writelines(c[0])
        f.writelines('"')
        f.writelines(",")
        f.writelines('"')
        f.writelines(c[1])
        f.writelines('"')
        f.writelines(",")
        f.writelines('"')
        f.writelines(c[2])
        f.writelines('"')
        f.writelines(",")
        f.writelines("\n")

rawDescription: Python: looping through urls in file

description: Python: looping through urls in file


code:
x = []
for i in range(10):
    x.append(pd.DataFrame(dict(zip(list('abc'), [i + 1, i + 2, i + 3])), index = list('ind')))

rawDescription: Pandas appending Series to DataFrame to write to a file


code:
import io
import zipfile

zipped_file = io.BytesIO()
with zipfile.ZipFile(zipped_file, 'w') as f:
    for i, file in enumerate(files):
        f.writestr("{}.csv".format(i), file.getvalue())

zipped_file.seek(0)

rawDescription: Sending multiple .CSV files to .ZIP without storing to disk in Python


code:
if len(filestocopy.keys()) == 0:
    return None

rawDescription: Is there a better way to feed different parameters into a function with if-statements?


code:
class MyWidget(QWidget):
    signal = pyqtSignal(int)

rawDescription: PyQt5 signal-slot decorator example

description: PyQt5 signal-slot decorator example


code:
import uuid
import weakref

class Foo(object):
    ident_cache = weakref.WeakValueDictionary()

    def __new__(cls, identity=None, **kwargs):
        if identity is None:
            identity = uuid.uuid1()
        try:
            self = cls.ident_cache[identity]
        except KeyError:
            self = super(Foo, cls).__new__(cls)
            self.__identity = identity
            self.__init__(**kwargs)
            cls.ident_cache[identity] = self
        return self

    def __getnewargs__(self):
        return (self.__identity,)

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

rawDescription: Python pickling keep object identity

description: Python pickling keep object identity


code: return ''.join([i if ord(i) < 128 else ' ' for i in text])

rawDescription: Replace non-ASCII characters with a single space


code:
#This file mainly exists to allow python setup.py test to work.
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)

from django.test.utils import get_runner
from django.conf import settings

def runtests():
    test_runner = get_runner(settings)
    failures = test_runner([], verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests()

rawDescription: Running Django test with setup.py test and tox


code:
while current_frame <= max_frames:
    start = time.time()
    # ... do stuff that might take significant time
    time.sleep(max(1./25 - (time.time() - start), 0))

rawDescription: Limit loop frame rate

description: Limit loop frame rate


rawDescription: Why the syntax for open() and .read() is different?


code:
import odbc

source =  odbc.SQLDataSources(odbc.SQL_FETCH_FIRST)
while source:
    print(source)
    source =  odbc.SQLDataSources(odbc.SQL_FETCH_NEXT)

rawDescription: How to connect to a SQL Server database in Anaconda

description: Connect to a SQL Server database in Anaconda


code:
def simpsons_rule(f, a, b, n):
    """
    Implements simpsons_rule
    :param f: function to integrate
    :param a: start point
    :param b: end point
    :param n:  number of intervals, must be even.
    :return: integral of the function
    """

    if n & 1:
        print ("Error: n is not a even number.")
        return 0.0

    h = float(b - a) / n
    integral = 0.0

    x = float(a)
    for i in range(0, n / 2):
        integral += f(x) + (2.0 * f(x + h))
        x += 2 * h

    integral = (2.0 * integral) - f(a) + f(b)
    integral = h * integral / 3.0
    return integral

import math

def f_of_t(t):
    # Note: guard against singular behavior at t = 0.
    # L'Hospital says value should be 1.0.  NAN if you don't check.
    if x == 0:
        return 1.0
    else:
        return (math.sin(t)) / t

n = 10000
a = 0
b = 2

print(simpsons_rule(f_of_t, a, b, n))

rawDescription: how to solve integration using simpsons rule in python?

description: Solve integration using simpsons rule in python


code:
d = { 'token': 10,'custid':100,'cycle':"yes" }
select_stmt = "SELECT * FROM kart_user WHERE"
allowed_col = ['token', 'custid'] # Predefined column names to allow from coming dictionary.
for key, value in d.iteritems():
    if  key in allowed_col:
        condition = "{key} = '{value}'".format(key=key, value=value)
        select_stmt = select_stmt + " and " + condition
cursor.execute(select_stmt, dist)
# Further fetching code you can execute. Here you will get select statement for particular key and value.

rawDescription: Python string substitution for dynamic column name and values


rawDescription: Gettings point coordinates from matplotlib.pyplot.plot


code:
import string
ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \
           string.digits + '-_'
ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'

def num_encode(n):
    if n < 0:
        return SIGN_CHARACTER + num_encode(-n)
    s = []
    while True:
        n, r = divmod(n, BASE)
        s.append(ALPHABET[r])
        if n == 0: break
    return ''.join(reversed(s))

def num_decode(s):
    if s[0] == SIGN_CHARACTER:
        return -num_decode(s[1:])
    n = 0
    for c in s:
        n = n * BASE + ALPHABET_REVERSE[c]
    return n

rawDescription: How to convert an integer to the shortest url-safe string in Python?

description: Convert an integer to the shortest url-safe string in Python


code:
count = 0
Input1 = True
while True:
    if Input1:
        print("Doing Input1 stuff...")
        count = count + 1
        if count == 1: #if the count is 1 it is the FIRST iteration of the loop so we switch on!
            Output1 = True
            print("Output 1 switched ON")
    if Output1:
        print("Out-putted")
        Output1 = False #switch if OFF, and since count will never = 1 again, this code block won't activate again.
        print("Output 2 switched OFF")
    #break the loop sometime (this is just for demonstration)
    if count == 4:
        print("I've done 4 iterations")
        break;

rawDescription: if == True, make True for one moment while in loop

description: If == True, make True for one moment while in loop


code:
import abc

class Base(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def value(self):
        return 'Should never get here'

class Implementation1(Base):

    @property
    def value(self):
        return 'concrete property'

class Implementation2(Base):
    pass # doesn't have the required property

rawDescription: Enforcing Class Variables in a Subclass

description: Enforcing Class Variables in a Subclass


code:
import tkFont
font = tkFont.Font(size=32, weight="bold")

button['bg'] = "red"
button['fg'] = "white"
button['font'] = font

rawDescription: How to execute python tkinter button without clicking mouse

description: Execute python tkinter button without clicking mouse


code:
def semivoice(char):
    return unicodedata.normalize('NFC', char + '\u309a')

rawDescription: Is there any way to do "logical" transformations between Japanese kana characters with different diacritical marks?


code:
def trimFloat(fl):
    if fl is not None:
      res = "{0:.10f}".format(float(fl))
      return res
    else:
      return None

floatCols  = ['a', 'b ']
for col in floatCols:
    reportDF[col] = reportDF[col].apply(trimFloat)

def removePct(reportDF):
  reportDF['c'] = reportDF['c'].apply(lambda x: x.translate(None, '%'))
  return reportDF

rawDescription: fastest way in python to read csv, process each line, and write a new csv

description: Fastest way in python to read csv, process each line, and write a new csv


rawDescription: How to find first byte of a serial stream with python?

description: Find first byte of a serial stream with python


code:
fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='kde', ax=ax)
y.plot(kind='kde', ax=ax, color='red')

rawDescription: Pandas: plotting two histograms on the same plot


code:
from inspect import ismethod

class MethodTracker(object):
    def collect_data(self):
        data = {}
        for attr in dir(self):
            if not attr.startswith('_') and not hasattr(MethodTracker, attr):
                possible_method = getattr(self, attr)
                if ismethod(possible_method):
                    data.update(possible_method())
        return data

    def decoy_method(self):
        return 'This is not added to data.'

class Example(MethodTracker):
    def method_a(self):
        return [('key_a1', 'val_a1'), ('key_a2', 'val_a2')]

    def method_b(self):
        return [('key_b1', 'val_b1'), ('key_b2', 'val_b2')]

rawDescription: Calling methods inside class to modify list


code: os.system('ssh -t -t myname@myserver "ls > ~/x.txt && nice -11 screen -U"')

rawDescription: SSH and Screen with a Python script

description: SSH and Screen with a Python script


code: ut.sort(key=lambda x: x.date, reverse=True)

rawDescription: python - parsing and sorting dates

description: Python - parsing and sorting dates


code:
names = []
for el in hotels:
    names.append(el.find('span').get_text(strip=True))

names

rawDescription: Parsing HTML span with Beautiful Soup

description: Parsing HTML span with Beautiful Soup


code:
int(var)
return int

rawDescription: Testing if Python string variable holds number (int,float) or non-numeric str?


code:
from babel import Locale
from babel.dates import get_timezone_name, get_timezone
tz = get_timezone('Europe/Berlin')
get_timezone_name(tz, locale=Locale.parse('pt_PT'))

rawDescription: Python timezone full names

description: Python timezone full names


rawDescription: Django -- Multiple Databases -- Data Migration


code:
names = ['Bob', 'Colin']

replace = {}
for name, nums in zip(names, array):
    replace.update({num: name for num in nums})

rawDescription: How to compare the elements of a list to a 2-dimensional list (without using a huge amount of if/elif/else statements)

description: Compare the elements of a list to a 2-dimensional list (without using a huge amount of if/elif/else statements)


code: pairs = [(a, b) for a in main_streets for b in main_streets if a.nodes[-1] == b.nodes[0]]

rawDescription: How to classify a list of objects having an intersecting list of values

description: Classify a list of objects having an intersecting list of values


rawDescription: ARCGIS: open feature into TOC

description: ARCGIS: open feature into TOC


rawDescription: How can I call all items in a list item?

description: Call all items in a list item


code:
humidity = soup.find(text='Average Humidity')
next_cell = humidity.find_parent('td').find_next_sibling('td')
humidity_value = next_cell.string

rawDescription: How to use beautifulsoup when HTML element doesn't have a class name?

description: Use beautifulsoup when HTML element doesn't have a class name


code: desired_fields = deserialized.map(lambda x: (x['key1'] + x['key2']).split(' '))

rawDescription: Spark and Python use custom file format/generator as input for RDD


code: ['banana', 'anana', 'nana', 'ana', 'n', 'a', 'ana', 'nana', 'anana', 'banana']

rawDescription: Scheme to Python: most elegant translation of a recursive procedure?


rawDescription: Python: split a large text file by many headers


rawDescription: Add the same point to all subplots

description: Add the same point to all subplots


rawDescription: When IDLE does implicit print?

description: When IDLE does implicit print


code:
class Episode(models.Model):
    air_time = models.DateTimeField()
    end_time = models.DateTimeField()

    @property
    def air_status(self):
        if self.air_time < now():
            return 'UPCOMNG'
        elif self.air_time >= now() and self.end_time < now():
            return 'LIVE'
        else:
            return 'VOD'

rawDescription: Best way to keep data in an object updated based on some logic?

description: Keep data in an object updated based on some logic


code:
aWgt = 0.3
bWgt = 0.7

print (np.where(a1.mask, 0., a1.data * aWgt) +
       np.where(b1.mask, 0., b1.data * bWgt)) / (np.where(a1.mask, 0., aWgt) +
                                                 np.where(b1.mask, 0., bWgt))

# array([ 3.1,  2. ,  5. ,  5.1])

rawDescription: How to aggregate timeseries in Python?

description: Aggregate timeseries in Python


code:
from collections import defaultdict

mf_collection = defaultdict(list)

def pop():
    ## populate the collection with MovieFile objects
    m = MovieFile(title=t, year=y, dir=d, filename=f)
    mf_collection[str(m)].append(m)

class MovieFile():

    def __init__(self, title, dir, filename, year=0):
        self.title = title
        self.year = year
        self.fulltitle = title if year == 0 else title + ' (' + year + ')'
        self.dir = dir
        self.filename = filename

    def __str__(self):
        return repr(self.title + ' (' + self.year + ') at ' + self.dir)

rawDescription: Passing Custom Class in Python

description: Passing Custom Class in Python


code:
screen = Wnck.Screen.get_default()
screen.force_update()  # recommended per Wnck documentation
window_list = screen.get_windows()

for window in window_list:
    if window.get_name() == 'My Application':
        print(window.transient_is_most_recently_activated())

rawDescription: How to test if GTK+ dialog has been created?

description: Test if GTK+ dialog has been created


rawDescription: Python: How to check if a variable is equal to one string or another string


code:
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self._rcwin = None

    @property
    def rcwin(self):
        if self._rcwin is None:
            self._rcwin = RigControlWindow()
        return self._rcwin

    def showRigControlWindow(self):
        self.rcwin.show()

rawDescription: PyQt4 : check the window is existing or not


code: decorated = decorator(original)

rawDescription: Memoization python function

description: Memoization python function


code:
import foobar
foobar.main()

rawDescription: module as script without .py in Python?

description: Module as script without .py in Python


code:
input_dict = {"a":"b", "c":1 , "d" : {1,2,3}}
for key, value in input_dict.items():
    try:
            exec( "{} = {}".format(key, value))
    except:
            exec( "{} = {}".format(key, "'" + str(value) + "'"))

d
a
c

rawDescription: How to convert dict to expressions in python

description: Convert dict to expressions in python


code:
df1 = df.T
df1.iloc[:, df1.columns.get_level_values('A') == 1]

rawDescription: selecting from multi-index pandas

description: Selecting from multi-index pandas


code:
def to_base(n, bse):
    digs = "0123456789abcdefghijklmnopqrstuvwxyz"
    tmp = []
    while n:
        n, i = divmod(n, bse)
        tmp.append(digs[i])
    return "".join(tmp[::-1])

def chng_frm_base(s, frm_bse, to_bse):
    if to_bse < 2 or to_bse > 36 or frm_bse < 2 or frm_bse > 36:
        raise ValueError("bases must be between 2-36")
    try:
        return to_base(int(s, frm_bse), to_bse)
    except ValueError:
        try:
            n = int("".join([ch for ch in s if ch.isdigit()]),frm_bse)
            return to_base(n, to_bse)
        except ValueError:
            return 0

rawDescription: Base convert in python given a string

description: Base convert in python given a string


code: defaultdict(int)

rawDescription: initialize defaultdict in Python

description: Initialize defaultdict in Python


code:
s="""{"httpStatus": "OK", "payload": {"status": "OK", "sts":{"nested":{"config": {}}}}, "httpCode": 200}"""

js=json.loads(s)
checker(js,'config')

rawDescription: Regex substring not in string

description: Regex substring not in string


rawDescription: How to parse empty value of parameter in HTTP request in python?

description: Parse empty value of parameter in HTTP request in python


code:
out = np.empty(masks.shape,dtype=object)
out[masks] = vals[:masks.sum()]

rawDescription: "Unsparsing" numpy Arrays with Given Masks


code:
names = []
numbers = []

for item in months:
    names.append(item[0])
    numbers.append(item[1])

rawDescription: Creating a sum from a list within a list in Python?


code:
elements = [x for x in dom.getElementsByTagName("paths")[0].childNodes if isinstance(x, minidom.Element)]
elements

rawDescription: Python xml Trying to show a if statement on a tag


code: jdf = df._jdf

rawDescription: How to use a Scala class inside Pyspark

description: Use a Scala class inside Pyspark


code:
set_mean = -10
#calculated_mean = None

energy = []
calculated_mean = float('inf')
x = 1
while calculated_mean > set_mean:
    for i in range(x, x+4):  # you can change step size here by passing it as last argument
        energy.append(i-i*i)
        print(energy)
        calculated_mean =  sum(energy[-2:])/2
        print(calculated_mean)
    x = x + 1

rawDescription: iterate the range in for loop to satisfy the condition

description: Iterate the range in for loop to satisfy the condition


rawDescription: Python 2.7 regex with format multiple list items


code: map(lambda v: v['ev_id'], data[2])

rawDescription: Scrapy hxs.select() not selecting all results


code:
class StateChoices(AutoModelSelect2Field):
    queryset = State.objects
    def get_results(self, request, term, page, context):
        country =  request.GET.get('country', '')

        states = State.objects.filter(country=country, name__istartswith=term)
        s2_results = [(s.id, s.name, {}) for s in states]

        return ('nil', False, s2_results)

rawDescription: Update the Queryset of a Django-Select2 AutoModelSelect2Field


code:
# myproject/myapp/management/commands/runfleet.py
from mpi4py import MPI
from optparse import make_option

from django.core.management.base import BaseCommand

import sys

class Command(BaseCommand):
    help = 'Launches the example manager and workers.'

    option_list = BaseCommand.option_list + (
        make_option('--workers', '-w', type='int', default=1), )

    def handle(self, *args, **options):
        self.stdout.write("Manager launched.")

        worker_count = options['workers']
        manage_script = sys.argv[0]
        comm = MPI.COMM_SELF.Spawn(sys.executable,
                                   args=[manage_script, 'fleetworker'],
                                   maxprocs=worker_count).Merge()
        self.stdout.write('Manager rank {}.'.format(comm.Get_rank()))

        start_data = [None] # First item is sent to manager and ignored
        for i in range(worker_count):
            start_data.append("Item {}".format(i))
        comm.scatter(start_data)

        end_data = comm.gather()
        self.stdout.write('Manager received data {!r}.'.format(end_data))

        comm.Disconnect()

rawDescription: Launch MPI worker processes in a Django app


rawDescription: Fill in missing values in pandas dataframe


code: p = ax.scatter(xs, ys, zs, c=cs, marker=m)

rawDescription: Matplotlib 3D Scatter Plot with Colorbar


code: listname.sort(key=lambda x:x[0])

rawDescription: Python 3.3: Sorting a List of Objects/Methods


code:
xyz1.py
import argparse

parser = argparse.ArgumentParser(description="XYZ1 args", add_help=False)
parser.add_argument("-xyz1-cat", action='store_true')
parser.add_argument("-xyz1-dog", action='store_true')

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

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


code:
def my_polyfit(data):
    return np.polyfit(data.squeeze(), ...)[:, None, None, None]

rawDescription: Applying a function along an axis of a dask array


rawDescription: Finding unique elements in cells of pandas DF and expanding DF to include columns with the names of those unique elements


rawDescription: Numpy - Matrix Generation from list comprehension


code:
class Result(dict):
    def __iter__(self):
        for key in self.keys():
            if not(isinstance(key, str) and key.startswith("_")):
                yield key

rawDescription: Custom iteration behavior in dict subclass


code:
from operator import itemgetter
g = itemgetter( 'a', 'b' )
a_loaded, b_loaded = g(np.load('file.npz'))

rawDescription: Storing and loading numpy arrays as files


code:
def iter_targets(path):
    for dirparent, dirname in walk_tree(path):
        if is_a_match(dirparent, dirname):
            yield os.path.join(dirparent, dirname)

rawDescription: Python code to search a folder(not file) inside another folder


code:
v = cmp(ayy, byy)
if v != 0: return v
v = cmp(amm, bmm)
if v != 0: return v
return cmp(add, bdd)

rawDescription: Simplify a date comparison

description: Simplify a date comparison


code:
import math

millnames = ['',' Thousand',' Million',' Billion',' Trillion']

def millify(n):
    n = float(n)
    millidx = max(0,min(len(millnames)-1,
                        int(math.floor(0 if n == 0 else math.log10(abs(n))/3))))

    return '{:.0f}{}'.format(n / 10**(3 * millidx), millnames[millidx])

rawDescription: python human readable large numbers

description: Python human readable large numbers


code:
import numpy as np

class SonarFile(object):
    # These define the format of the file header
    header_fields = ('num_frames', 'name1', 'name2', 'name3')
    header_formats = ('i4', 'f4', 'S10', '>I4')

    def __init__(self, filename):
        self.infile = open(filename, 'r')
        dtype = dict(names=self.header_fields, formats=self.header_formats)

        # Read in the header as a numpy array (count=1 is important here!)
        self.header = np.fromfile(self.infile, dtype=dtype, count=1)

        # Store the position so we can "rewind" to the end of the header
        self.header_length = self.infile.tell()

        # You may or may not want to do this (If the field names can have
        # spaces, it's a bad idea). It will allow you to access things with
        # sonar_file.Name1 instead of sonar_file.header['Name1'], though.
        for field in self.header_fields:
            setattr(self, field, self.header[field])

    # __iter__ is a special function that defines what should happen when we
    # try to iterate through an instance of this class.
    def __iter__(self):
        """Iterate through each frame in the dataset."""
        # Rewind to the end of the file header
        self.infile.seek(self.header_length)

        # Iterate through frames...
        for _ in range(self.num_frames):
            yield Frame(self.infile)

    def close(self):
        self.infile.close()

class Frame(object):
    header_fields = ('width', 'height', 'name')
    header_formats = ('i4', 'i4', 'S20')
    data_format = 'f4'

    def __init__(self, infile):
        dtype = dict(names=self.header_fields, formats=self.header_formats)
        self.header = np.fromfile(infile, dtype=dtype, count=1)

        # See discussion above...
        for field in self.header_fields:
            setattr(self, field, self.header[field])

        # I'm assuming that the size of the frame is in the frame header...
        ncols, nrows = self.width, self.height

        # Read the data in
        self.data = np.fromfile(infile, self.data_format, count=ncols * nrows)

        # And reshape it into a 2d array.
        # I'm assuming C-order, instead of Fortran order.
        # If it's fortran order, just do "data.reshape((ncols, nrows)).T"
        self.data = self.data.reshape((nrows, ncols))

rawDescription: Writing to numpy array from dictionary

description: Writing to numpy array from dictionary


code:
for i,marker in enumerate(interlace_markers):
    marker.marker_number = i+1 #indexing is 1 based instead of zero based

rawDescription: Interlacing two lists of objects based on attributes of the list objects in python


code: dsnStr = cx_Oracle.makedsn("oracle.sub.example.com", "1521", "ora1")

rawDescription: cx_Oracle doesn't connect when using SID instead of service name on connection string

description: Cx_Oracle doesn't connect when using SID instead of service name on connection string


code:
invcount = 0

def inv_sort (listIn):
    global invcount

    invcount += 1

    # do stuff

rawDescription: Python - using a shared variable in a recursive function


rawDescription: re.sub not working for a particular regex pattern

description: Re.sub not working for a particular regex pattern


code:
def cyclic_equiv(u, v):
    n, i, j = len(u), 0, 0
    if n != len(v):
        return False
    while i < n and j < n:
        k = 1
        while k <= n and u[(i + k) % n] == v[(j + k) % n]:
            k += 1
        if k > n:
            return True
        if u[(i + k) % n] > v[(j + k) % n]:
            i += k
        else:
            j += k
    return False

rawDescription: Check if a list is a rotation of another list that works with duplicates


code:
field=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
[''.join(map(str, c)) for c in reversed(list(zip(*field)))]
'\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))])
print('\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))]))

rawDescription: Python, slicing lists?

description: Python, slicing lists


code: elems = [e.strip() for e in elem.split(',')]

rawDescription: How can I format a list into a tuple with sub-tuples?

description: Format a list into a tuple with sub-tuples


code: df

rawDescription: Creating Horizontal Bar Plot With Time-Series Data in Python


rawDescription: sort an array by row in pyhton

description: Sort an array by row in pyhton


code:
class Location(models.Model):
    name = models.CharField(max_length = 100, blank = True)
    coords = models.PointField()

rawDescription: Calculating near gps coordinates in django


rawDescription: Performing operations on a NumPy arrray but masking  values along the diagonal from these operations


code: lambda num1,num2: num1 + num2

rawDescription: How do you read a lambda function as a string?

description: Read a lambda function as a string


code:
#!/usr/bin/env python3
# coding: utf-8

from collections import defaultdict

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

d = defaultdict(int)
for word in word_list:
    d[word] += 1

print(d.items())

rawDescription: How to count elements in a list and return a dict?

description: Count elements in a list and return a dict


code:
import json

from django.core import serializers

products = Product.objects.all()
# data is a python list
data = json.loads(serializers.serialize('json', products))
# d is a dict
d = {}
# data is a list nested in d
d['results'] = data
# more keys for d
d['totalPages'] = 10
d['currentPage'] = 1
# data is a json string representation of the dict
data = json.dumps(d)

rawDescription: Add Property to Django Result Object

description: Add Property to Django Result Object


code:
res
res[1]
res[2]

rawDescription: How to sum value of integers based on position?

description: Sum value of integers based on position


code:
#!/usr/bin/env python
import requests

res = requests.get('http://url/feed.json')
json_res = res.json()

keywords = ['key', 'key2', 'key3']
for k, v in json_res.iteritems():
    if k in keywords:
        print(v)
        break

rawDescription: Parsing json and searching through the output


code: self.button1_rex = tk.Button(..., command=functools.partial(self.new_window, resNum))

rawDescription: How to determine which button is pressed out of Button grid in Python TKinter?

description: Determine which button is pressed out of Button grid in Python TKinter


code: all(y == first for first in gen for y in gen)

rawDescription: Lazy way to check if all generated elements are equal


code:
import yaml
with open(FILE_PATH, 'r') as f:
   users_dict = yaml.load(f)
print(users_dict)
print(users_dict['admin'])
### {passwd: 123, user: admin@admin.com}
print(users_dict['admin']['passwd'])
### 123

rawDescription: Variables from txt file

description: Variables from txt file


rawDescription: Compare element with previous along axis


code:
def calc_angle(pressure, min_p=1000, max_p=1200):
    return 360 * ((pressure - min_p) / float(max_p - min_p))

angle = calc_angle(pressure)

rawDescription: programming a servo thru a barometer

description: Programming a servo thru a barometer


code:
import unittest

class Test(unittest.TestCase):
    def __init__(self, methodName = 'runTest'):
        unittest.TestCase.__init__(self, methodName)
        self.data = range(5)

    def test_getitem(self):
        self.assertEqual(self.data[1],1)

    def test_reversed(self):
        self.assertEqual(list(reversed(self.data)),[4,3,2,1,0])

if __name__ == '__main__':
    import sys
    sys.argv.insert(1,'--verbose')
    unittest.main(argv = sys.argv)

rawDescription: unittest Passing Variable as Parameter

description: Unittest Passing Variable as Parameter


code: [li[i+1] for i in range(len(li)-1) if li[i]=='she']

rawDescription: Getting a sub-list containing list[i+1] where list[i] is a specific value


code:
def custom_rename(lvl1, lvl2):
    if lvl1 == 'End Qty.':
        return lvl2
    elif lvl1 == 'Sales Qty.' and lvl2 == 'Total':
        return 'Sales Qty.'
    elif lvl2 == '':
        return lvl1
    else:
        return '_'

rawDescription: Multiindex in pandas pivot table

description: Multiindex in pandas pivot table


rawDescription: Substrings from string in python

description: Substrings from string in python


code:
blacklist = [0]
blacklist = set(blacklist)
myList = [e for e in myList if int(e) not in blacklist]

rawDescription: Remove all occurrences of an integer from a list of floats


code: ids = [id.text for id in Reel.findall(".//Id")]

rawDescription: XML parsing in Python using Python 2 or 3


code:
class ClipboardMonitor(object):
    [...]

    def __init__(self):
        self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
        self.signal_id = self.clip.connect("owner-change", self._clipboard_changed)

    def close(self):
        self.clip.disconnect(self.signal_id)

rawDescription: How to connect to a GObject signal in python, without it keeping a reference to the connecter?

description: Connect to a GObject signal in python, without it keeping a reference to the connecter


code: kernel.derp(queue, (4, 1), None, buffarr.data, global_offset=[2, 0])

rawDescription: pyopencl global_work_offset kernel argument

description: Pyopencl global_work_offset kernel argument


code:
start_path    = 'ABC0123/Comp/Scripts'
searching_for ='Some_File'

rawDescription: Traversing a directory tree bottom-up using Python


code:
pprint(zip(data, a))
[ (av, dv) for av, dv in zip(a, data) if len(av) > 1 and tempstring in av]

rawDescription: making python itertools work on multiple conditions

description: Making python itertools work on multiple conditions


code:
pattern = input("Insert pattern ")
if len(pattern) < 4:
    sys.exit('pattern too short')

with open(file, "r") as f:
    for line in f:
        line = line.strip()
        match = re.search(pattern, line)
        if match:
            selection.append(line[match.end():match.end()+5])

rawDescription: Selecting item in a string from a starting point retrieved via regex (Python)


code:
type(converted.iloc[0])
str

type(converted.iloc[1])
float

rawDescription: python: convert numerical data in pandas dataframe to floats in the presence of strings

description: Python: convert numerical data in pandas dataframe to floats in the presence of strings


rawDescription: Matplotlib Legend for Scatter with custom colours


rawDescription: Sum of the elements in a CSR matrix

description: Sum of the elements in a CSR matrix


rawDescription: Why only can get the whole sliced reverse list ommiting start and end?


code:
somespider.py
# -*- coding: utf-8 -*-
import scrapy
import re
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from scrapy.spider import BaseSpider
from demo.items import DemoItem
from selenium import webdriver

def removeUnicodes(strData):
        if(strData):
            strData = strData.encode('utf-8').strip()
            strData = re.sub(r'[\n\r\t]',r' ',strData.strip())
        return strData

class demoSpider(scrapy.Spider):
    name = "domainurls"
    allowed_domains = ["domain.com"]
    start_urls = ['http://www.domain.com/used/cars-in-trichy/']

    def __init__(self):
        self.driver = webdriver.Remote("http://127.0.0.1:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNITWITHJS)

    def parse(self, response):
        self.driver.get(response.url)
        self.driver.implicitly_wait(5)
        hxs = Selector(response)
        item = DemoItem()
        finalurls = []
        while True:
            next = self.driver.find_element_by_xpath('//div[@class="showMoreCars hide"]/a')

            try:
                next.click()
                # get the data and write it to scrapy items
                item['pageurl'] = response.url
                item['title'] =  removeUnicodes(hxs.xpath('.//h1[@class="page-heading"]/text()').extract()[0])
                urls = self.driver.find_elements_by_xpath('.//a[@id="linkToDetails"]')

                for url in urls:
                    url = url.get_attribute("href")
                    finalurls.append(removeUnicodes(url))

                item['urls'] = finalurls

            except:
                break

        self.driver.close()
        return item

rawDescription: scrapy crawl spider ajax pagination

description: Scrapy crawl spider ajax pagination


code:
xmldoc = minidom.parse(filename)
nodes = xmldoc.documentElement.childNodes
commentIdx = next(i for i,n in enumerate(nodes) if
                n.nodeType == n.COMMENT_ELEMENT and n.data == ' AUTOMATEDSTUFF ')
automatedNodes = nodes[commentIdx+1:]
print(automatedNodes) # or do something else with them

rawDescription: Python XML processing after a specific comment


code: re.sub(r'(' + '|'.join(sorted(sfxs, key=lambda x:len(x), reverse=True)) + r')$', '',s)

rawDescription: Python: what's a more compact/efficient way to strip string of a suffix from list?


code:
import pyparsing as pp
#relationship will refer to 'track' in all of your examples
relationship = pp.Word(pp.alphas).setResultsName('relationship')

number = pp.Word(pp.nums + '.')
variable = pp.Word(pp.alphas)
# an argument to a relationship can be either a number or a variable
argument = number | variable

# arguments are a delimited list of 'argument' surrounded by parenthesis
arguments= (pp.Suppress('(') + pp.delimitedList(argument) +
            pp.Suppress(')')).setResultsName('arguments')

# a fact is composed of a relationship and it's arguments
# (I'm aware it's actually more complicated than this
# it's just a simplifying assumption)
fact = (relationship + arguments).setResultsName('facts', listAllMatches=True)

# a sentence is a fact plus a period
sentence = fact + pp.Suppress('.')

# self explanatory
prolog_sentences = pp.OneOrMore(sentence)

rawDescription: prolog fact lexical analyser in python

description: Prolog fact lexical analyser in python


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

x = np.arange(10000, 10011)
fig, ax = plt.subplots(1)
ax.plot(x)
formatter = mticker.ScalarFormatter(useMathText=True)
ax.yaxis.set_major_formatter(formatter)
plt.show()

rawDescription: standard form matplotlib -- change e to \times 10

description: Standard form matplotlib -- change e to \times 10


code:
def add_vote(self,choice):
    attname = self.votes[choice].attname
    value = getattr(self, attname) # get the value
    setattr(self, attname, value+1) # set the value

rawDescription: Django: How to get/set model field value if it is put into any data structure?


code:
import re

contigDict={}
with open('file1') as c1:
    text=c1.readlines()
for line in text:
    key,value = line.split()
    contigDict[key]=value
with open('file2') as c2:
    scrambled_text=c2.read()

contigs = re.findall(r'contig\d+',scrambled_text)
output = {}
for contig in contigs:
    output[contig]=contigDict[contig]
with open('file3',w) as w:
    for key in output.keys():
        w.write(key+'\t'+output[key]+'\n')

rawDescription: associate dictionary to a .txt file

description: Associate dictionary to a .txt file