code: message = Message(text="dsf", sender=sender , receiver=receiver)

rawDescription: Self-referential database with extra fields in sqlalchemy


code: ip_ports = [IpPort(**attrs) for attrs in json.loads(dumped_ipports)]

rawDescription: how to convert a list of object to json format in python

description: Convert a list of object to json format in python


code:
set1 = set(u for u in users if users[u]['Location'] == 'Boston')
set2 = set(u for u in users if users[u]['Type'] == 'Primary')
result = set1.union(set2)

rawDescription: Small Tables in Python?

description: Small Tables in Python


rawDescription: Matlab equivalent of Python's 'reduce' function


code:
# set time out to 5, so that the command will be killed after 5 second
command = ['perl', '-e', "'alarm shift @ARGV; exec @ARGV'", "5"]

command += ["ping", "www.google.com"]

exec_proc = subprocess.Popen(command)

rawDescription: How to limit program's execution time when using subprocess?

description: Limit program's execution time when using subprocess


code: [x for i, x in enumerate(xs) if 'AB' not in X or i>0 and 'CD' in xs[i-1]]

rawDescription: "If...or..." statement inside list comprehension?


code: {u'website': u'http://www.clubmayan.com', u'name': u'Mayan Theatre', u'url': u'http://www.last.fm/venue/8901088+Mayan+Theatre', u'image': u'http://userserve-ak.last.fm/serve/500/14221419/Mayan+Theatre+outside.jpg', u'phonenumber': u'213-746-4287', u'location': {u'postalcode': u'CA 90015', u'city': u'Los Angeles', u'geo:point': {u'geo:long': u'-118.259068', u'geo:lat': u'34.040729'}, u'street': u'1038 S. Hill St', u'country': u'United States'}, u'id': u'8901088'}

rawDescription: Retrieving Venue Information with pylast and last.fm


code:
new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(0,len(self.path)-2):
    direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
    direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1])
    if direction1 != direction2:
        new_path.append(self.path[node+1])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path

rawDescription: How to only output turning points of a path for maze

description: Only output turning points of a path for maze


code:
list1=[1,2,3,4]
list2=[0,1,1,2]

new_list = [{'original': v1, 'updated': v2} for v1, v2 in zip(list1, list2)]

print(new_list)

rawDescription: Efficiently merge lists into a list of dictionaries


rawDescription: Diagonal sparse matrix obtained from a sparse coo_matrix


code: (n,l,k) = [int(v) for v in raw_input().split()]

rawDescription: Typed input in python?

description: Typed input in python


code:
def __init__(self, url="http://url.com", icon="icon.ico"):
    self.url = url
    self.icon = icon

rawDescription: Python - most convenient way to define constant variables used just once


code:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static').replace('\\', '/')
ADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/admin').replace('\\', '/')

rawDescription: Where to put a Django template's dependent files?


code:
unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]

rawDescription: Filter dict to contain only certain keys?


rawDescription: Passing variables from Jinja to database


code: res = requests.get(url, allow_redirects=False)

rawDescription: different results with python requests module and curl

description: Different results with python requests module and curl


code:
def ngrams(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
    """
    A utility that produces a sequence of ngrams from a sequence of items.
    For example:

    >>> ngrams([1,2,3,4,5], 3)
    [(1, 2, 3), (2, 3, 4), (3, 4, 5)]

    Use ingram for an iterator version of this function.  Set pad_left
    or pad_right to true in order to get additional ngrams:

    >>> ngrams([1,2,3,4,5], 2, pad_right=True)
    [(1, 2), (2, 3), (3, 4), (4, 5), (5, None)]

    @param sequence: the source data to be converted into ngrams
    @type sequence: C{sequence} or C{iterator}
    @param n: the degree of the ngrams
    @type n: C{int}
    @param pad_left: whether the ngrams should be left-padded
    @type pad_left: C{boolean}
    @param pad_right: whether the ngrams should be right-padded
    @type pad_right: C{boolean}
    @param pad_symbol: the symbol to use for padding (default is None)
    @type pad_symbol: C{any}
    @return: The ngrams
    @rtype: C{list} of C{tuple}s
    """

    if pad_left:
        sequence = chain((pad_symbol,) * (n-1), sequence)
    if pad_right:
        sequence = chain(sequence, (pad_symbol,) * (n-1))
    sequence = list(sequence)

    count = max(0, len(sequence) - n + 1)
    return [tuple(sequence[i:i+n]) for i in range(count)]

rawDescription: Simple implementation of N-Gram, tf-idf and Cosine similarity in Python


rawDescription: Filtering a DataFrame based on multiple column criteria


code: abc state fsf val

code: pqr state efg val2

rawDescription: python list of tuples to javascript array of arrays

description: Python list of tuples to javascript array of arrays


code:
reader = csv.reader(f)
chunks = itertools.groupby(reader, keyfunc)

rawDescription: Chunking data from a large file for multiprocessing?


rawDescription: Python 3 tkinter: dynamically set an element's state to "normal"?


code:
for parent in queryset:
    print(parent.num_ok)
    print(parent.num_fail)

rawDescription: Django ORM grouped count of children

description: Django ORM grouped count of children


code: objects = model.objects.all()

rawDescription: Dynamically generate import in Python, specifically for a Django model


code: globals()['f%d'%inp]()

rawDescription: Python doubts about calling func and Syntax


code:
def printer(**kwargs):
    print(kwargs)

d = FrozenDict({'a': 1, 'b': 2})
printer(**d)

rawDescription: How to define self-made object that can be unpacked by `**`?

description: Define self-made object that can be unpacked by `**`


code:
set_b = set(list_b)
for a in list_a:
    if a not in set_b:
         writeFile(...)

rawDescription: Comparing large list of hashes to other large list of hashes


code:
with open('somefile.txt') as f:
    data = ','.join(line.replace('{','[').replace('}',']')
        for line in f if line.strip())
    return ast.literal_eval(data)

rawDescription: Parse list of numbers into list in python


rawDescription: How can I calculate the average of a list of tuples in python?

description: Calculate the average of a list of tuples in python


rawDescription: Redundant If Statement and Regex

description: Redundant If Statement and Regex


rawDescription: Python - buildung an Index

description: Python - buildung an Index


code:
import importlib
problem = importlib.import_module(sys.argv[1])

rawDescription: How can I import a python file through a command prompt?

description: Import a python file through a command prompt


code: ['cube']

rawDescription: Getting a list of locally-defined functions in python


code:
import re
string = "The brown fox jumped over the red barn, and found the chickens."
res = re.findall(r'(\b[a-z]+\b)?[^a-z]*(\b[a-z]+\b)?[^a-z]*(\b[a-z]+\b)?[^a-z]*,\s*(\b[a-z]+\b)?[^a-z]*(\b[a-z]+\b)?[^a-z]*(\b[a-z]+\b)?', string, re.IGNORECASE)
res

rawDescription: Python regex endline

description: Python regex endline


code:
arr = np.array([1,2,3,4,5]).reshape(-1,1)  # saves the use of len()
arr = np.array([1,2,3,4,5])[:,None]  # adds a new dim at end
np.array([1,2,3],ndmin=2).T  # used by column_stack

rawDescription: Numpy: get 1D array as 2D array without reshape


code:
def upload_file(request):
    if request.method == "POST":
        my_uploaded_file = request.FILES['my_uploaded_file'].read() # get the uploaded file
        # do something with the file
        # and return the result
    else:
        return render(request, 'directory/index.html')

rawDescription: Python Django- How do I read a file from an input file tag?


code:
three
four

rawDescription: Passing inputs from a text file to python program using batch file


code:
def foo_tuple():
    return (2,)

def bar_tuple():
    return (2,)

def foo_string():
    return 'foo'

def bar_string():
    return 'foo'

print(foo_tuple() is foo_tuple())  # True
print(foo_tuple() is bar_tuple())  # False

print(foo_string() is bar_string())  # True

rawDescription: In Python, when are two objects the same?


code:
Python3
import importlib.machinery, imp
namespace = 'external_lib'
loader = importlib.machinery.SourceFileLoader(namespace, '/home/user/external_lib_folder/external_lib.py')
external_lib = loader.load_module(namespace)

# How to use it:
external_lib.function(data_or_something)

rawDescription: Python: include a third party library in a personal Python package


rawDescription: Check if a list of numbers is in a certain range?


code:
string1 = [len, type, max]
string2 = ['hello', 5, [1,3,7]]
for func, param in zip(string1, string2):
    func(param)

rawDescription: python execute list and list of functions

description: Python execute list and list of functions


rawDescription: How to combine a numpy array and a text column and export to csv

description: Combine a numpy array and a text column and export to csv


code:
# ... model class

def __unicode__(self):
    return "%s %s" % (self.id, self.date)

rawDescription: How do I retrieve timedate from the database and display in template?

description: Retrieve timedate from the database and display in template


rawDescription: Can we force run the jobs in APScheduler job store?


rawDescription: Git pre-commit hook not working on windows


code:
def sha1(s):
    return hashlib.sha1(s).hexdigest()
def sha512(s):
    return hashlib.sha512(s).hexdigest()
t1 = timeit.Timer("sha1('asdf' * 100)", "from __main__ import sha1")
t512 = timeit.Timer("sha512('asdf' * 100)", "from __main__ import sha512")
t1.timeit()
t512.timeit()

rawDescription: Is there a significant overhead by using different versions of sha hashing (hashlib module)


code:
import itertools

def testtree(values, levels):
    if len(values) == 1:
        # Last element, always true!
        return True
    vs_ls = zip(values, levels)
    test_v, test_l = next(vs_ls)
    next_v, next_l = next(vs_ls)
    if next_l > test_l:
        subtree = [v for v,l in itertools.takewhile(
            lambda v_l: v_l[1] > test_l,
            itertools.chain([(next_v, next_l)], vs_ls))
                   if l == test_l+1]
        if sum(subtree) != test_v and subtree:
            #TODO test if you can remove the "and subtree" check now!
            print("{} != {}".format(subtree, test_v))
            return False
    return testtree(values[1:], levels[1:])

if __name__ == "__main__":
    vs = [40, 20, 15, 5, 10, 10]
    ls = [0, 1, 2, 2, 1, 1]
    assert testtree(vs, ls) == True

rawDescription: How do I test a sum tree?

description: Test a sum tree


code:
if args.a:
    action = 'a value'
elif args.b:
    action = 'another value'
else:
    parser.print_usage()
    sys.exit(1)

rawDescription: Check for certain arguments and assign values to an arbitrary variable


rawDescription: Combine and compare two sets of stacked data in pygal


code: df

rawDescription: Fama Macbeth Regression in Python (Pandas or Statsmodels)


code:
from bisect import bisect_left

odd_list = range(3, 50, 2)
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
for each_odd in odd_list:
    ind = bisect_left(primes, each_odd)
    print(each_odd, primes[ind - 1])

rawDescription: Subtracting the Nearest Prime Given Two Lists using for loop and max


code:
def attack(origin,target):
    '''Origin is where you are attacking from,
    target is who you are attacking'''
    x=origin.upper()
    y=target.upper()
    if x not in REGION_DATA:
        print("You must attack from somewhere!")
    elif y not in REGION_DATA[x]['Bordering']:  # extra indexing by x here
        print("Not a valid target")
    else:
        print("Attack is underway!")

rawDescription: How do I loop this?

description: Loop this


code:
class LoopExecutor(concurrent.futures.Executor):
    """An Executor subclass that uses an event loop
    to execute calls asynchronously."""

    def __init__(self, loop=None):
        """Initialize the executor with a given loop."""
        self.loop = loop or asyncio.get_event_loop()

    def submit(self, fn, *args, **kwargs):
        """Schedule the callable, fn, to be executed as fn(*args **kwargs).
        Return a Future object representing the execution of the callable."""
        coro = asyncio.coroutine(fn)(*args, **kwargs)
        return asyncio.run_coroutine_threadsafe(coro, self.loop)

rawDescription: Submit a job to an asyncio event loop

description: Submit a job to an asyncio event loop


rawDescription: Narrowing XPath in Beautiful Soup

description: Narrowing XPath in Beautiful Soup


code:
def login_cancelled(request):
    ...
    custom_logic
    ...

rawDescription: Custom redirect for django-allauth social login cancel


code:
class MySettingsDict(dict):

    def __getitem__(self, item):
        value = dict.__getitem__(self, item)
        if not isinstance(value, int):
            function, arg = value
            value = function(arg)
            dict.__setitem__(self, item, value)
        return value

rawDescription: Setup dictionary lazily

description: Setup dictionary lazily


code:
lst = [] #This is the rows and columns, assuming the rows contain the columns
column = 2
temp = 0
for row in range (len(lst)):
    temp += lst [row][column]
mean = temp / len (lst)

rawDescription: In pure python (no numpy, etc.) how can I find the mean of certain columns of a two dimensional list?


code:
f(1, 2, a=3, b=4)  # is equivalent to
args, kwargs = (1, 2), {"a":3, "b":4}
f(*args, **kwargs)

rawDescription: Run function with positional and optional arguments in parallel in python (follow up)


code: top_points = choose(lines, ntop)

rawDescription: Sorting points on multiple lines

description: Sorting points on multiple lines


code: rgb = rgb.ravel()

rawDescription: Speed up a delta filter in python/numpy

description: Speed up a delta filter in python/numpy


code:
def parse_dir_contents(self, response):
    for sel in response.xpath('//h1[@itemprop="name"]'):
        item = thisItem()
        ...
        request = scrapy.Request("https://www.this-site.com.au/something?listing_id="+propID,callback=self.parse_other_content)
        request.meta['item'] = item
        yield request

def parse_other_content(self, response):
    item = response.meta['item']
    # do something with the item
    return item

rawDescription: Passing class between functions

description: Passing class between functions


code:
def chooseBest(s):
    return max(s[0], chooseBest(s[1:])) if s else None

rawDescription: Recursive comparison, can you point out my mistake?


code:
class Quadrant(object):
    def __init__(self):
        self.klingonCount = 0
        self.baseHere = 0
        self.starCount = 0

rawDescription: Creating 2d array of classes in Python

description: Creating 2d array of classes in Python


code: sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)

rawDescription: how to append particular excel cell value using python?

description: Append particular excel cell value using python


code:
'

Lenovo Z580 15.6" Core i7 500GB HDD Notebook PC

'

rawDescription: Why does this code not work? Python RE (regular expression)


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    scores = (int(row[-1]) for row in reader)
    top10 = heapq.nlargest(10, scores)

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
@register.simple_tag(takes_context=True)
def lessonapp_preserved_filters(context, url, dayofweek):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

        preserved_filters['dayofweek__exact'] = dayofweek

        merged_qs.update(preserved_filters)

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url)

rawDescription: How to create link for django filter

description: Create link for django filter


rawDescription: Iterative summation of output generated by a function in a for loop (python)


code:
from django.db import transaction

@transaction.atomic
def viewfunc(request):
    # This code executes inside a transaction.
    do_stuff()

rawDescription: Avoiding race conditions, Django + Heroku + PostgreSQL


code:
true_values = []
false_values = []
for bit, val in zip(bits, values):
    if bit:
        true_values.append(val)
    else:
        false_values.append(val)

rawDescription: How to efficiently extract specific subsets of list elements in Python

description: Efficiently extract specific subsets of list elements in Python


code: from toplevel_package import moduleA

rawDescription: Import Script from a Parent Directory

description: Import Script from a Parent Directory


code: ' '.join("I went \n to the store\n".split())

rawDescription: Regex to remove newline character from string


code:
class bad:
    """ Dont do this, even if coerce was a good idea this simply
        makes itself int ignoring type of other ! """
    def __init__(self, s):
            self.s = s
    def __coerce__(self, other):
            return (other, int(self.s))

coerce(10, bad("102"))

rawDescription: What is Python's coerce() used for?

description: What is Python's coerce() used for


rawDescription: html5lib/lxml examples for BeautifulSoup users?

description: Html5lib/lxml examples for BeautifulSoup users


rawDescription: Python - Decoding Binary to Boolean

description: Python - Decoding Binary to Boolean


code: itertools.repeat(0, 10)

rawDescription: Create List of Single Item Repeated n Times in Python


code:
icon = '\u25b2'
print(icon)

rawDescription: How to use Unicode characters in a python string

description: Use Unicode characters in a python string


rawDescription: Is there a Python equivalent to Matlab's makelut, applylut?


code: return

rawDescription: What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check failes)?


code: owner_cals = [x for x in cal_items if x["access_role"]=="owner"]

rawDescription: An easier way of referring to the index of a desired dictionary (Python)?


code:
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
with open('my_text_file.txt', 'w') as f:
    f.write('ArticleID|CreatedDate|MeSH|IsMajor\n')
for pubmed_article in root.findall('PubmedArticle'):
    ArticleID = pubmed_article.find('MedlineCitation').find('PMID').text
    year = pubmed_article.find('MedlineCitation').find('DateCreated').find('Year').text
    month = pubmed_article.find('MedlineCitation').find('DateCreated').find('Month').text
    day = pubmed_article.find('MedlineCitation').find('DateCreated').find('Day').text
    CreatedDate = year + month + day
    for mesh_heading in pubmed_article.find('MedlineCitation').find('MeshHeadingList').findall('MeshHeading'):
        MeSH = mesh_heading.find('DescriptorName').text
        IsMajor = mesh_heading.find('DescriptorName').get('MajorTopicYN')
        line_to_write = ArticleID + '|' + CreatedDate + '|' + MeSH + '|' + IsMajor + '\n'
        with open('my_text_file.txt', 'a') as f:
            f.write(line_to_write)

rawDescription: Python parse XML and save as txt

description: Python parse XML and save as txt


code:
import itertools

numbers = range(lower, upper + 1)
words = "a, b, c".split(", ")

data = (numbers, words) if numbers_first else (words, numbers)
for n, w in itertools.product(*data):
    if not numbers_first: n, w = w, n
    print("Player %d likes %s." % (n, w))

rawDescription: Refactoring code/consolidating functions (e.g. nested for-loop order)


code:
while the_window_has_not_been_destroyed():
    event = wait_for_next_event()
    process_event(event)

rawDescription: How is tkinter code executed?

description: How is tkinter code executed


code:
from array import array

def reverse_array(letters, first=0, last=None):
    "reverses the letters in an array in-place"
    if last is None:
        last = len(letters)
    last -= 1
    while first < last:
        letters[first], letters[last] = letters[last], letters[first]
        first += 1
        last -= 1

def reverse_words(string):
    "reverses the words in a string using an array"
    words = array('c', string)
    reverse_array(words, first=0, last=len(words))
    first = last = 0
    while first < len(words) and last < len(words):
        if words[last] != ' ':
            last += 1
            continue
        reverse_array(words, first, last)
        last += 1
        first = last
    if first < last:
        reverse_array(words, first, last=len(words))
    return words.tostring()

rawDescription: How do you reverse the words in a string using python (manually)?

description: Reverse the words in a string using python (manually)


code:
one = DataFile('file1.csv')
two = DataFile('file2.csv')
one.get_header()
comb = set(one.get_header() + two.get_header())
final = list(one.with_header(comb)) + list(two.with_header(comb))
final

rawDescription: Merge multiple csv file based on a template header in python


rawDescription: How to alter a part of an array

description: Alter a part of an array


code:
index = pd.DatetimeIndex(start='2012', end='2013', freq='1D')
index
df = pd.DataFrame(np.random.randn(len(index),1), index=index)
df
df.index

rawDescription: How to fetch timestamp in Pandas DataFrame

description: Fetch timestamp in Pandas DataFrame


code:
source
import bisect
from datetime import datetime
from datetime import timedelta

data_dict = {'times':[], 'data':[]}

#Generate sample data
start_datetime = datetime(2014, 8, 23, 15, 17, 17, 392943)
for i in range(10000):
    data_dict['times'].append(start_datetime+timedelta(minutes = 5*i))
    data_dict['data'].append(i)

startTime = datetime.now()

def data_select_search(data_dict, time_range):
    start = 0
    end = 1
    times = data_dict['times']
    for x in times:
        if x - time_range[0] < timedelta(seconds = 0):
            start += 1
        if x - time_range[1] <= timedelta(seconds = 0):
            end += 1
    # print 'search:',start,end
    data_dict['times'] = list(data_dict['times'][start:end])
    data_dict['data'] = list(data_dict['data'][start:end])
    return data_dict

def data_select_bisect(data_dict, time_range):
    times = data_dict['times']
    start = bisect.bisect_left(times, time_range[0])
    end = bisect.bisect_right(times, time_range[1], lo=start) + 1
    # print 'bisect:',start,end
    return dict(
        times=data_dict['times'][start:end],
        data=data_dict['data'][start:end],
        )

drange = [
        datetime(2014, 8, 30, 0, 0, 0, 0),
        datetime(2014, 9, 5, 0, 0, 0, 0)
    ]
data_sub_dict = data_select_search(data_dict.copy(), drange)
_dict2 = data_select_bisect(data_dict.copy(), drange)

import timeit
mysetup = "from __main__ import data_select_bisect, data_select_search, data_dict, drange"
num = 100

print('search:', timeit.timeit(
    "data_select_search(data_dict.copy(), drange)",
    setup=mysetup,
    number=num
    ))
print('bisect:', timeit.timeit(
    "data_select_bisect(data_dict.copy(), drange)",
    setup=mysetup,
    number=num,
    ))

rawDescription: Getting data from specific datetime range


code:
dic_name, dic_items = zip(*data.items())
dic_name
dic_items

rawDescription: How do I turn list values into an array with an index that matches the other dic values?

description: Turn list values into an array with an index that matches the other dic values


code:
ax.text(0,0,'0,0 transAxes',transform=ax.transAxes)
ax.text(0,1,'0,1 transAxes',transform=ax.transAxes)
ax.text(.5,0,'.5,0 transAxes',transform=ax.transAxes)

ax.text(0,1,'0,1 transData', transform=ax.transData)
ax.text(0,0,'0,0 transData', transform=ax.transData)
ax.text(np.pi/2,1,'pi/2,1 transData', transform=ax.transData)
ax.text(np.pi,0.5,'pi,0.5 transData', transform=ax.transData)
ax.text(np.pi*3/2,1,'3pi/2,1 transData', transform=ax.transData)

rawDescription: insert text in the sections of circle in matplotlib

description: Insert text in the sections of circle in matplotlib


code:
from collections import defaultdict

def determine_types(args, kwargs):
    return tuple([type(a) for a in args]), \
           tuple([(k, type(v)) for k,v in kwargs.iteritems()])

function_table = defaultdict(dict)
def overload(arg_types=(), kwarg_types=()):
    def wrap(func):
        named_func = function_table[func.__name__]
        named_func[arg_types, kwarg_types] = func
        def call_function_by_signature(*args, **kwargs):
            return named_func[determine_types(args, kwargs)](*args, **kwargs)
        return call_function_by_signature
    return wrap

rawDescription: Decorator for overloading in Python

description: Decorator for overloading in Python


code:
(_, x, y) = max((cell[k], x, y)
                for (y, row) in enumerate(m)
                for (x, cell) in enumerate(row))

rawDescription: How to pick the largest number in a matrix of lists in python?

description: Pick the largest number in a matrix of lists in python


code: words = t.split()

rawDescription: Python string replacement

description: Python string replacement


code: (numMsgs, totalSize) = self.conn_pop3.stat()

rawDescription: Get emails with Python and pop lib

description: Get emails with Python and pop lib


rawDescription: Plotting implicit equations in 3d

description: Plotting implicit equations in 3d


code:
#!/usr/bin/env python
import os
import pty
import sys
from select import select
from subprocess import Popen, STDOUT

master_fd, slave_fd = pty.openpty()  # provide tty to enable line buffering
process = Popen("./main", stdin=slave_fd, stdout=slave_fd, stderr=STDOUT,
                bufsize=0, close_fds=True)
timeout = .1 # ugly but otherwise `select` blocks on process' exit
# code is similar to _copy() from pty.py
with os.fdopen(master_fd, 'r+b', 0) as master:
    input_fds = [master, sys.stdin]
    while True:
        fds = select(input_fds, [], [], timeout)[0]
        if master in fds: # subprocess' output is ready
            data = os.read(master_fd, 512) # <-- doesn't block, may return less
            if not data: # EOF
                input_fds.remove(master)
            else:
                os.write(sys.stdout.fileno(), data) # copy to our stdout
        if sys.stdin in fds: # got user input
            data = os.read(sys.stdin.fileno(), 512)
            if not data:
                input_fds.remove(sys.stdin)
            else:
                master.write(data) # copy it to subprocess' stdin
        if not fds: # timeout in select()
            if process.poll() is not None: # subprocess ended
                # and no output is buffered <-- timeout + dead subprocess
                assert not select([master], [], [], 0)[0] # race is possible
                os.close(slave_fd) # subproces don't need it anymore
                break
rc = process.wait()
print("subprocess exited with status %d" % rc)

rawDescription: Python C program subprocess hangs at "for line in iter"


code:
def main():
    for caseNumber in xrange(4):
        Vcm = raw_input("Enter vcm for case#{}:".format(caseNumber))
        #Calculate the two velocities and store them in 2 variables
        Vcmi1, Vcmi1U = calculate_velocities(Vcm, VcmU, Vi1, Vi1U, Pi1, Pi1U, Pi2, Pi2U, m1, m1U, m2, m2U)

        #Now simply pass these two variables onto the next function
        p1, p2 = initial_momentum_cm_1(m1, m1U, Vcmi1, Vcmi1U, Vcm, VcmU, Vf2, Vf2U, Pi1, Pi1U, Pi2, Pi2U, m2, m2U)

rawDescription: Making a variable global makes it a tuple


code: d

rawDescription: grouping elements into new list from two lists using python

description: Grouping elements into new list from two lists using python


code:
import subprocess
try:
    out_bytes = subprocess.check_output(["./rti", '1', '0.05', fileForRTI])
except subprocess.CalledProcessError as e:
    out_bytes = e.output # Output generated before error
    code= e.returncode # Return code

rawDescription: Redirect screen output to text file

description: Redirect screen output to text file


code:
import gspread
import json
from oauth2client.client import SignedJwtAssertionCredentials

# your auth here
with open("credentials.json") as f:
    json_key = json.load(f)
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(
    json_key['client_email'],
    bytes(json_key['private_key'],'UTF-8'),
    scope
)

# your spreadsheet have to be shared with json_key['client_email']

gc = gspread.authorize(credentials)
# end of auth

spreadsheet = gc.open_by_url(my_url) # url to your spreadsheet here
ws = spreadsheet.sheet1 # or select any other sheet

table = [['one', 'two', 'three'], [4, 5, 6]]

# you may need to resize your worksheet so it have the neccessary cells
# ws.resize(len(table),len(table[0]))

update_sheet(ws, table)

rawDescription: How to write a table (list of lists) to Google Spreadsheet using gspread

description: Write a table (list of lists) to Google Spreadsheet using gspread


code:
for benchmark in benchmarks:
   readFile = open(benchmark+'.txt')
   text = readFile.read()
   x = re.findall(r"(\d+)",text)
   x = [int(i) for i in liveRatio]

   #clear the figure
   pylab.clf()

   pylab.plot(x)
   F = pylab.gcf()
   F.savefig('benchmark',dpi=200)

rawDescription: Matplotlib: plot multiple individual plots in a loop


code:
tags
classes

rawDescription: Unable to match tuples items to list items


code:
matrix = [
    var1, var2,
    var2, var1
]

rawDescription: How variables work in Python?

description: How variables work in Python


code: [threed(*x) for x in itertools.product(range(1, 3), range(1,3), range(1,3))]

rawDescription: Naming coordinates in python

description: Naming coordinates in python


code:
import re
credits = """Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Glenn Howerton (Gary, Brad), with
 Stephen Root and Laura Dern (Delilah, Stacy)"""

# split on commas (only if outside of parentheses), "with" or "and"
splitre = re.compile(r"\s*(?:,(?![^()]*\))|\bwith\b|\band\b)\s*")

# match the part before the parentheses (1) and what's inside the parens (2)
# (only if parentheses are present)
matchre = re.compile(r"([^(]*)(?:\(([^)]*)\))?")

# split the parts inside the parentheses on commas
splitparts = re.compile(r"\s*,\s*")

characters = splitre.split(credits)
pairs = []
for character in characters:
    if character:
        match = matchre.match(character)
        if match:
            actor = match.group(1).strip()
            if match.group(2):
                parts = splitparts.split(match.group(2))
                for part in parts:
                    pairs.append((actor, part))
            else:
                pairs.append((actor, ""))

print(pairs)

rawDescription: Using regex to extract information from a string


code:
element = driver.find_element_by_class_name('sbSelector')
driver.execute_script("arguments[0].click();", element)

rawDescription: How do I select from drop down menu with changing id on reload of webpage

description: Select from drop down menu with changing id on reload of webpage


code:
def isSimilar (s, t):
    return compute_jaccard_index(s, t) > .4

rawDescription: How to remove duplicates from a list in python

description: Remove duplicates from a list in python


code:
@nb.njit
def abs_contact_order3(xyz, atoms_residue, cutoff_nm=.6):
    """Return the absolute contact order."""
    contact_count = 0
    seq_distance_sum = 0
    cutoff_2 = cutoff_nm*cutoff_nm
    N = len(atoms_residue)
    for i in xrange(N):
        for j in xrange(i+1,N):
            seq_dist = atoms_residue[j] - atoms_residue[i]
            if seq_dist > 0:
                d = 0.0
                for k in xrange(3):
                    d += (xyz[j,k] - xyz[i,k])**2
                if d < cutoff_2:
                    seq_distance_sum += 2*seq_dist
                    contact_count += 2

    if contact_count==0.:
        return 0.

    return seq_distance_sum/float(contact_count)

rawDescription: Calculate protein contact order in Python


rawDescription: numpy.equal with nested lists

description: Numpy.equal with nested lists


code:
to_shift = pd.isnull(df2.iloc[-1])
df2.loc[:,to_shift] = df2.loc[:,to_shift].shift(1)

rawDescription: For any rows with a NaN in a Pandas DataFrame, shift by 1


rawDescription: Python generator function/object naming convention


code:
row_counts=pd.DataFrame({'ROW_COUNT':[len(x) for x in np.split(df,notnull.index)]})
"""
   ROW_COUNT
0          2
1          3
2          5
3          5
4          2
"""

rawDescription: How to count rows in a data frame in Pandas conditionally against values in another column of the same data frame?

description: Count rows in a data frame in Pandas conditionally against values in another column of the same data frame


code:
class WriteOnceDict(dict):
    def __setitem__(self, key, value):
        if key in self:
            raise KeyError('{} has already been set'.format(key))
        super(WriteOnceDict, self).__setitem__(key, value)

rawDescription: Write-once dictionary?

description: Write-once dictionary


code:
class MyDialog(wx.Dialog):
    def __init__(self, *args, **kwargs):
        wx.Dialog.__init__(self, *args, **kwargs)

        sizer = wx.BoxSizer(wx.VERTICAL)

        for i in range(5):
            description = wx.StaticText(self, -1, "This is a long description \
that may span several lines. Filler filler filler filler filler. More filler \
filler filler filler filler.")
            description.Wrap(500)

            questionSizer = wx.BoxSizer(wx.HORIZONTAL)
            question = wx.StaticText(self, -1, "Are you sure?")
            yes = wx.RadioButton(self, -1, "Yes", style = wx.RB_GROUP)
            no = wx.RadioButton(self, -1, "No")

            sizer.Add(description)
            questionSizer.Add(question)
            questionSizer.AddStretchSpacer()
            questionSizer.Add(yes)
            questionSizer.Add(no)
            sizer.Add(questionSizer, flag=wx.EXPAND)

        self.SetSizerAndFit(sizer)
        self.Show()

rawDescription: Filling available space with a column in GridBagSizer


code: {sampe: Yes}

rawDescription: yes or no dumping as 'yes' or 'no' in PyYAML

description: Yes or no dumping as 'yes' or 'no' in PyYAML


code:
def bool(boolean):
    if boolean == "True":
        return True
    else:
        return False

rawDescription: How to change values/types of Dictionary and put them back

description: Change values/types of Dictionary and put them back


rawDescription: Pandas: Aggregate by month for every subgroup


code: merge=pd.merge(df,d, how='inner', left_index=True, right_index=True)

rawDescription: Pandas: Merge data frames on datetime index: = Solved


code:
import calendar
calendar.weekday(2016, 1, 14)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
days[calendar.weekday(2016, 1, 14)]

rawDescription: dd/mm/yyyy and day python without library at python

description: Dd/mm/yyyy and day python without library at python


code:
el1 = ['Bob', 'Mary', 'Sue', 'George']
el2 = ['Bob', 'Sue', 'Jill', 'Isaac', 'George']
dict( (val, idx) for idx, val in enumerate(d1, start=1) if val in set(el2) )
#{'Bob': 1, 'Sue': 3, 'George': 4}

rawDescription: Python: Applying common keys from one Dictionary to another


code:
import lxml.etree as ET
import io

content='''<?xml version="1.0" encoding="utf-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tp1="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpx="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
    <Activities>
        <Activity Sport="Other">
            <Id>2012-01-17T11:44:35Z</Id>
            <Lap StartTime="2012-01-17T11:44:35Z">
                <TotalTimeSeconds>0</TotalTimeSeconds>
                <DistanceMeters>0</DistanceMeters>
                <Calories>0</Calories>
                <Intensity>Active</Intensity>
                <TriggerMethod>Manual</TriggerMethod>
                <Track>
                    <Trackpoint>
                        <Time>2012-01-17T11:44:35Z</Time>
                        <Position>
                            <LatitudeDegrees>59.920211518183351</LatitudeDegrees>
</Position>
</Trackpoint>
</Track>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
'''

doc = ET.fromstring(content)

ns = {'ns':'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'}
for trackpoint in doc.xpath('//ns:Trackpoint', namespaces = ns):
    print(trackpoint.xpath('(ns:Time|ns:Position/ns:LatitudeDegrees)/text()', namespaces = ns))

rawDescription: python 3.x xml parsing similar to plistlib?

description: Python 3.x xml parsing similar to plistlib


code:
input_result
1

rawDescription: How do chained comparisons in Python actually work?


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided
a = np.arange(10, dtype=np.int8)
as_strided(a, shape=(3, 10 - 2), strides=(1, 1))

rawDescription: Efficiently slice windows from a 1D numpy array, around indices given by second 2D array


code: {{ form.as_p }}

rawDescription: django-forms-builder. How do I update a form?

description: Django-forms-builder. How do I update a form


code:
from scrapy.command import ScrapyCommand
from scrapy.utils.project import get_project_settings
from scrapy.crawler import Crawler

class Command(ScrapyCommand):

    requires_project = True

    def syntax(self):
        return '[options]'

    def short_desc(self):
        return 'Runs all of the spiders'

    def run(self, args, opts):
        settings = get_project_settings()

        for spider_name in self.crawler.spiders.list():
            crawler = Crawler(settings)
            crawler.configure()
            spider = crawler.spiders.create(spider_name)
            crawler.crawl(spider)
            crawler.start()

        self.crawler.start()

rawDescription: Locally run all of the spiders in Scrapy


code:
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode

rawDescription: How to get exit code when using Python subprocess communicate method?

description: Get exit code when using Python subprocess communicate method


code:
import re

def glob2re(pat):
    """Translate a shell PATTERN to a regular expression.

    There is no way to quote meta-characters.
    """

    i, n = 0, len(pat)
    res = ''
    while i < n:
        c = pat[i]
        i = i+1
        if c == '*':
            #res = res + '.*'
            res = res + '[^/]*'
        elif c == '?':
            #res = res + '.'
            res = res + '[^/]'
        elif c == '[':
            j = i
            if j < n and pat[j] == '!':
                j = j+1
            if j < n and pat[j] == ']':
                j = j+1
            while j < n and pat[j] != ']':
                j = j+1
            if j >= n:
                res = res + '\\['
            else:
                stuff = pat[i:j].replace('\\','\\\\')
                i = j+1
                if stuff[0] == '!':
                    stuff = '^' + stuff[1:]
                elif stuff[0] == '^':
                    stuff = '\\' + stuff
                res = '%s[%s]' % (res, stuff)
        else:
            res = res + re.escape(c)
    return res + '\Z(?ms)'

rawDescription: Python glob but against a list of strings rather than the filesystem


rawDescription: Copying excel data into a python list in IPython using clipboard?


code:
import pkgutil

for module_loader, name, ispkg in pkgutil.iter_modules(["/path/to/module"]):
    ...

rawDescription: Importing all modules in a package?

description: Importing all modules in a package


code:
text = wx.StaticText(panel, -1, 'my text', (20, 100))
font = wx.Font(18, wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
text.SetFont(font)

rawDescription: wxPython StaticText Widget Font

description: WxPython StaticText Widget Font


code:
from bs4 import BeautifulSoup
data = 'PLN 371'
soup = BeautifulSoup(data)
soup.find('span', class_='hc_pr_cur').next_sibling.strip()

rawDescription: Python BeautifulSoup - how to extract text between <a> tags


code: my_list.sort(key=lambda x: abs(x[0] - x[3]))

rawDescription: Sort list of lists by expression in Python


code:
msg = MIMEText(
"The nightly build status was a SUCCESS\n\n"
"Build File: http://www.python.org\n\n"
"Build Results File: http://10.51.54.57/sandboxes/"
, project
, "\n"
)

rawDescription: String manipulation in Python

description: String manipulation in Python


rawDescription: Partitioning multiline string in python

description: Partitioning multiline string in python


rawDescription: Python web Automation to get Email from Webpage


code: MyClass.mymethod = self.m.mock()

rawDescription: Why mocking is still effective after existing a code in nosetests multiple tests?


code:
from itertools import takewhile
takewhile(lambda m: m.start() < len(string), re.finditer(find, string+string))

rawDescription: In python: How to perform regular expression search on "circular" string


rawDescription: What's the best way to initialize a dict of dicts in Python?


code:
import multiprocessing as mp
import Queue
import random
import logging

# logger=mp.log_to_stderr(logging.DEBUG)
logger = logging.getLogger(__name__)

qsize = mp.Value('i', 1)
def check_one(args):
    total, package, version = args
    i = qsize.value
    logger.info('\r[{0:.1%} - {1}, {2} / {3}]'.format(
        i / float(total), package, i, total))
    new_version = random.randrange(0,100)
    qsize.value += 1
    if new_version > version:
        return (package, version, new_version, None)
    else:
        return None

def update():
    logger.info('Searching for updates')
    set_len=10
    data = ( (set_len, 'project-{0}'.format(i), random.randrange(0,100))
             for i in range(set_len) )
    pool = mp.Pool()
    results = pool.map(check_one, data)
    pool.close()
    pool.join()
    for result in results:
        if result is None: continue
        package, version, new_version, json = result
        txt = 'A new release is avaiable for {0}: {1!s} (old {2}), update'.format(
            package, new_version, version)
        logger.info(txt)
    logger.info('Updating finished successfully')

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG)
    update()

rawDescription: multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed

description: Multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed


code:
color_list = ['red','red','red','red','green','green','red','blue','green','red','blue','red','blue','blue']
colors = ['red', 'green', 'blue']
sorted(color_list, key= colors.index)
colors = ['green', 'blue', 'red']
sorted(color_list, key= colors.index)

rawDescription: Rearranging list in python

description: Rearranging list in python


rawDescription: How to do this operation in numPy?

description: Do this operation in numPy


rawDescription: Python String to Bool conversion yields True for all cases


code:
from bs4 import BeautifulSoup, SoupStrainer

only_box = SoupStrainer(class_="box")
BeautifulSoup(driver.page_source, "html5lib", parse_only=only_box)

rawDescription: Beautiflsoup Create Soup With A Snippet of Page Source


code:
import csv
sample = '''\
col1,col2,col2,col4,col5
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
a3,b3,c3,d3,e3
'''
reader = csv.reader(sample.splitlines())
next(reader)
{tuple(row[:3]): row[4] for row in reader}

rawDescription: Create a dictionary from CSV file, with multiple keys


code: GetFormUploadToken

rawDescription: Unable to upgrade YouTube session token without logging into Google Accounts user API


code:
line = 'Hello, world!\n'
line.rstrip('\n')
additional = 'END'
print(line + additional)
print(line.rstrip('\n') + additional)

rawDescription: Printing output in one line from standard input in python


rawDescription: Removing elements from pandas series in python


code:
#! /usr/bin/env python
"""Usually a ready made file parser like csv module or even panda
et al. for more complete service is the way to go here but one may
want to know how to basically iterate and parse a little one self.
This is also for the date time parsing which one typically also
delegates to datetime module or the like."""
from __future__ import print_function
import sys

def hourly_maxima(in_file, out_file):
    """Extract calendar hourly maximum readings from in_file,
    write to out_file. If files do not exist or are
    not accessible exceptions will happily raise ;-).
    Input is expected to be ordered ascending by time
    stamp."""

    field_sep = ','
    with open(in_file, 'rt') as f_i, open(
            out_file, 'wt') as f_o:  # May raise here
        f_i.readline()  # Ignore header, be optimistic

        ts_raw = None
        hourly_maximum = None
        current_hour = None  # Group by calendar hour stored in tuples
        date_sep = '-'
        # Expect sample data line to document flow:
        # '2014-04-25 00:04:48',3.35
        for line in f_i.readlines():  # Digest rest of lines
            if not line:
                break  # stop on first empty line
            ts, reading = line.strip().split(field_sep)  # May raise ...
            r_float = float(reading)  # May raise ...

            # Map timestamp ts to calendar hour
            ts_raw = ts.strip("'")
            year, month, day = ts_raw[:10].split(date_sep)
            hour = ts_raw[11:13]
            cand_hour = (year, month, day, hour)
            if current_hour is None:
                current_hour = cand_hour

            if cand_hour == current_hour:  # We seek the maximum
                if hourly_maximum is None or r_float > hourly_maximum:
                    hourly_maximum = r_float
            else:  # report hourly maximum of previous hour and reset
                print(ts_raw, hourly_maximum)  # Also report matching hour?
                f_o.write('%s\n' % (str(hourly_maximum)))
                current_hour = cand_hour
                hourly_maximum = r_float

        # Flush the last result kept in hourly_maximum:
        print(ts_raw, hourly_maximum)  # Also report matching hour?
        f_o.write('%s\n' % (str(hourly_maximum)))

def main():
    """Drive the extraction."""
    in_file = 'dataV.csv' if len(sys.argv) < 2 else sys.argv[1]
    out_file = 'dataV-max.csv' if len(sys.argv) < 3 else sys.argv[2]

    hourly_maxima(in_file, out_file)

if __name__ == '__main__':
    sys.exit(main())

rawDescription: Python nested loop working with data file


code:
import itertools as IT
def get_cells(size):
    return list(IT.product(range(size), repeat=size))

rawDescription: Python: returning the cell coordinates

description: Python: returning the cell coordinates


code: left = recursion(a,l,m-1)

rawDescription: Theta(n**2) and Theta(n*lgn) algorithm perform unproperly


code:
def mergefill(to_fill, fill_char, fill_from):
    for filler in fill_from:
        it = iter(filler)
        yield [c if c != fill_char else next(it) for c in to_fill]

rawDescription: Replacing List values sequentially with values from another list


code:
result = could_return_none(x)

if result is None:
    result = DEFAULT_VALUE

rawDescription: python how to convert Nonetype to int or string

description: Python how to convert Nonetype to int or string


code: pg_cur.execute('alter table table_name add "AATag" varchar')

rawDescription: SQL : Insert and Update a new column from existing column


code:
measurement = np.array([1,2,3,4,5,5,6,7,8,5,4,5])
m2D = measurement[np.arange(N) + np.arange(len(measurement)-N+1)[:,None]]
m2D # Notice that is a 2D array (shifted) version of input
np.nonzero(np.all((lower_bound < m2D) & (higher_bound > m2D),axis=1))[0][0]

rawDescription: Find range of length N in a numpy array where some condition is satisfied


code:
# Draw Everything
allsprites.draw(screen)

rawDescription: Understand object orientated python - initialization of objects in pygame


code:
def deep_list(self):
    """fully copies trees of tuples to a tree of lists.
       deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(self)!=type( () ):
        return self
    return map(deep_list, self)

rawDescription: Python calling map() with 'self'

description: Python calling map() with 'self'


code:
outerlist = [["195", "106", "100", "95"]]
total = sum(int(i) for sublist in outerlist for i in sublist)
length = sum(len(sublist) for sublist in outerlist)
total / length

rawDescription: Average of imported list (python)

description: Average of imported list (python)


code:
from pprint import pprint
from bs4 import BeautifulSoup

data = """

noun the joining together of businesses which deal with different stages in the production or sale of the same product, as when a restaurant chain takes over a wine importer

"""

def get_info(elm):
    label = elm.find("span")
    return {
        "label": label.text,
        "meaning": "".join(getattr(sibling, "text", sibling) for sibling in label.next_siblings).strip(),
        "related_to": [a.text for a in elm.find_all("a")],
        "utag": [u.text for u in elm.find_all("u")]
    }

soup = BeautifulSoup(data, "html.parser")
pprint(get_info(soup.li))

rawDescription: How to extract and ignore span in markup? - python

description: Extract and ignore span in markup? - python


code:
p = numpy.empty((len(x), 3))
for i, a in enumerate((x, y, z)):
    p[:,i] = a

rawDescription: reshaping an arbitrary collection numpy arrays

description: Reshaping an arbitrary collection numpy arrays


code:
def registerScriptToContextMenu ():
    # http://support.microsoft.com/kb/310516
    cmdLine = 'regedit.exe registerOne.reg'
    import os
    os.system(cmdLine)

def one_main (*args):
    pass

rawDescription: Adding context menu option through Python


code: file_menu.add_command(label="Open    ", command=my_obj.my_func)

rawDescription: Inheritance. (A function calling something in a class)


code:
db = MySQLdb.connect(host="localhost",
use_unicode = True, charset = "utf8",
user=username, passwd=password, db=database)

rawDescription: How to insert and select greek words in mysqldb

description: Insert and select greek words in mysqldb


code:
class layOut(tkinter.Tk):
    volts = 0
    amps = 0
    ohms = 0

    def updizzle(self):
        self.volts = self.ve.get()
        self.amps = self.ie.get()
        self.ohms = self.re.get()

    def __init__(self, *args, **kwargs):
        tkinter.Tk.__init__(self, *args, **kwargs)
        container = ttk.Frame(self)
        container.grid(columns=3, rows=3, sticky='nsew')
        tkinter.Tk.title(self, 'Ohms Law v2')

        v = ttk.Label(container, text='Volts')
        v.grid(column=0, row=0)

        i = ttk.Label(container, text='Amperes')
        i.grid(column=1, row=0)

        r = ttk.Label(container, text='Ohms')
        r.grid(column=2, row=0)

        self.ve = ttk.Entry(container)
        self.ve.grid(column=0, row=1)

        self.ie = ttk.Entry(container)
        self.ie.grid(column=1, row=1)

        self.re = ttk.Entry(container)
        self.re.grid(column=2, row=1)

        button = ttk.Button(container, text='Button', command=layOut.updizzle)
        button.grid(column=2, row=2,pady=6)

        answer = ttk.Label(container, text='32095782hirjfkebfesfme')
        answer.grid(column=0, row=2, columnspan=2)

rawDescription: Python 3.4/Tkinter cross class variable accessing


code:
def on_pushbutton_clicked(self):
    dlg = DialogWindow(self)
    if dlg.exec_():
        value = dlg.getValue()

rawDescription: Communicate between two windows without violating class encapsulation


code:
def f(x):
  return x and x.isdigit() and int(x) or None

rawDescription: Lambda instead of "if" statement

description: Lambda instead of "if" statement


code:
doc = ET.fromstring(xmlTemplate)
print(doc)
# <Element {http://foo}root at 0xb741866c>

rawDescription: How to build an xml template with variable attributes from scratch

description: Build an xml template with variable attributes from scratch


code:
formats = {
    'Price': '{0.good} is worth {0.price} at {0.location}',
    'Wormhole': '{0.fromsys} has a wormhole to {0.tosys}',
}

return formats[self.memtype].format(self)

rawDescription: Evaluating a string-producing statement 'later' when stored in a dict


code: [map(int, elem.split()) for elem in originallist]

description: List of strings in ints ['123 121','42 23','23 23']


code: dict(max(stats.iteritems(), key=lambda kv: kv[1]))

rawDescription: Generate a new dictionary from the maximum values in a dictionary with ties


code:
N = col.shape[0]
sqr = col.copy() # take a copy of the col
sqr.data **= 2 # square the data, i.e. just the non-zero data
variance = sqr.sum()/N - col.mean()**2

rawDescription: (Python) How do you get the mean and std of a column in a csr_matrix?


code:
def files(a):
    entries =  [os.path.join(a,i) for i in os.listdir(a)]
    if len(entries) == 0:
            return

    for e in entries:
        if os.path.isfile(e):
            fi.append(e)

        elif os.path.isdir(e):
            files(e)

rawDescription: Recursively list all files in directory (Unix)


code:
class HTTPSudsPreprocessor(urllib2.BaseHandler):

    def http_request(self, req):
        req.add_header('Content-Type', 'text/xml; charset=utf-8')
        return req

    https_request = http_request

rawDescription: How to add http headers in suds 0.3.6?

description: Add http headers in suds 0.3.6


code:
# file: main.py
import foo
import bar

foo.foo()
bar.bar()
# OUTPUTS: 'baz'

rawDescription: Define a constructor in full classmethod class


code:
for xx in bigbadlistofcontours:
    cv2.drawContours(contourimage,xx,-1,(0,0,0),-1)

rawDescription: why are my contours not being totally filled in opencv?

description: Why are my contours not being totally filled in opencv


code:
with open("questions.txt", "r") as questions:
    keys = questions.read().split('|')
    answers = keys[3]
    keys[3] = keys[3].split('/', 1)[0]

    answers = answers.split('/')[1:]

    answer = [x for x in answers if '!' in x][0].strip('!')

    answers = [x.strip('!') for x in answers]

    print(keys)
    print(answers)
    print(answer)

rawDescription: Split a string by three delimiters, and adding them to different lists


code:
pattern = np.ones((24,16), float)
for i in xrange(2):
    pattern[i::4] = -1

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


code:
# Using both methods of registering URLs here
# just to show that both work

@app.route('/x/')
def handle_route1():
    return X().route1()

def handle_route2():
    return X().route2()

app.add_url_rule('/y/', view_func=handle_route2)

rawDescription: Define manually routes using Flask

description: Define manually routes using Flask


code:
indices = [0, 3, 4]
arr[:, indices]

rawDescription: How to slice a numpy array by a list of column indices

description: Slice a numpy array by a list of column indices


code: colors = [x for facet in facets for x in facet['color']*3]

rawDescription: OpenGL giving triangles colors in a list


code:
def writerows(self, rowdicts):
    return self.writer.writerows(map(self._dict_to_list, rowdicts))
    # or:
    #return self.writer.writerows(self._dict_to_list(row) for row in rowdicts)

rawDescription: csv.writer.writerows takes iterator?

description: Csv.writer.writerows takes iterator


code:
@login_required
def select_discipline(request):
    if request.method == 'POST':
        interest = request.POST.get('interest')
        context = RequestContext(request)
        interests = Interest.objects.order_by('name')
        disciplines = Discipline.objects.filter(parentInterest=interest)

        return render(
            'selectdiscipline.html',
            {
                'interest': interest,
                'interests': interests,
                'disciplines': disciplines
            },
            context
        )

rawDescription: Django - Pass a <select> form POST data from one view to another


code:
import numpy as np

data = np.array(data)

rawDescription: How do I separate a data set on a scatter plot

description: Separate a data set on a scatter plot


code:
class FakeMutableString(object):
    def __init__(self, s=""):
        self.s = [s]

    def __str__(self):
        return self.s[0]

    def get(self):
        return self.s[0]

    def set(self, new):
        self.s[0] = new

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code: df = pd.DataFrame({'Demande' : p2['VALUE_DEMANDE'],'Forcast' :p2['VALUE_FORCAST']})

rawDescription: Pandas / SQLITE DataFrame plot

description: Pandas / SQLITE DataFrame plot


code:
class MagicCounter(collections.Counter):
    def __setitem__(self, key, val):
        # see how much is being "added"
        diff = val - self[key]
        super(MagicCounter, self).__setitem__(key, val)
        if len(key) > 1:
            for item in key:
                self[item] += diff

rawDescription: Attach callback to Counter() value

description: Attach callback to Counter() value


code: tk.Button(root, text="Speed up!", command=speedup)

rawDescription: How to make a text button which speeds up text animation

description: Make a text button which speeds up text animation


code: crypto = Chiper("zenitpolar", "polarzenit", "criptografia")

rawDescription: OO Aproach python

description: OO Aproach python


code:
def animate(i,chosenEnergyLine):
    chosenEnergy = (0.0 + (i-1)*(0.02))
    chosenEnergyLine.set_xdata([chosenEnergy, chosenEnergy])
    return chosenEnergyLine,

chosenEnergyLine = ax2.axvline(0.0,0,1, linestyle='dashed')
ani = animation.FuncAnimation(f, animate, np.arange(1,10),
       fargs=(chosenEnergyLine,), interval=25, blit=False, repeat = False)

rawDescription: FuncAnimation() : remove/update old lines


code:
from stemming.porter2 import stem

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
             "The EPS user interface management system",
             "System and human system engineering testing of EPS",
             "Relation of user perceived response time to error measurement",
             "The generation of random binary unordered trees",
             "The intersection graph of paths in trees",
             "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]

documents = [[stem(word) for word in sentence.split(" ")] for sentence in documents]

rawDescription: How to stem words in python list?

description: Stem words in python list


code:
manager = RequestManager.getInstance()
# Rest same as before, register some requests, etc.

manager2 = RequestManager.getInstance() # This is actually the same manager ie. the same instance!

rawDescription: Creating a set of Python classes

description: Creating a set of Python classes


code:
df2 = pd.DataFrame ([d2, d2])**2
df2.columns = pd.MultiIndex.from_tuples (df2.columns)
df2
df1

rawDescription: Joining MultiIndexed Pandas Dataframes for Another MultiIndexed Dataframe


code:
@property
@memoize
def bar(self):
    row = db.execute('SELECT bar FROM bars where id=?', (self.id, )).fetchone()
    return row['bar'] if row else None

rawDescription: Efficient pooling/caching of expensive objects


code: vertices = g.vs[sorted(vertices)]

rawDescription: Find all vertices with the same edge attribute


code:
import wx
import sys
import traceback

def show_error():
    message = ''.join(traceback.format_exception(*sys.exc_info()))
    dialog = wx.MessageDialog(None, message, 'Error!', wx.OK|wx.ICON_ERROR)
    dialog.ShowModal()

class MyPanels(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent)
        self.parent = parent

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(1000, 480))
        self.parent = parent

        self.panel = wx.Panel(self, -1)
        self.panel.SetBackgroundColour("grey")

        self.leftpanel = MyPanels(self.panel, 1)
        self.rightpanel = MyPanels(self.panel, 1)
        self.leftpanel.SetBackgroundColour("red")
        self.rightpanel.SetBackgroundColour("green")

        self.basicsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.basicsizer.Add(self.leftpanel, 1, wx.EXPAND)
        self.basicsizer.Add(self.rightpanel, 1, wx.EXPAND)
        self.panel.SetSizer(self.basicsizer)

        button =  wx.Button(self.leftpanel, 1, 'DIE DIE DIE', (50, 130))
        buttonres = wx.Button(self.leftpanel, 2, 'Resurrect', (50, 230))
        buttonextra = wx.Button(self.leftpanel, 3, 'Test', (50, 330))

        self.Bind(wx.EVT_BUTTON, self.destroyPanel, button)
        self.Bind(wx.EVT_BUTTON, self.CreateNewPanel, buttonres)

    def CreateNewPanel(self, event):
        self.rightpanel = MyPanels(self.panel, 1)
        self.rightpanel.SetBackgroundColour("green")
        self.basicsizer.Add(self.rightpanel, 1, wx.EXPAND)
        self.panel.Layout()

        self.Show(True)
        self.Centre()

    def destroyPanel(self, event):
        self.rightpanel.Hide()
        self.panel.Layout()

def main():
    app = wx.App()
    try:
        frame = MyFrame(None, -1, 'Die.py')
        frame.Show()
        app.MainLoop()
    except:
        show_error()

if __name__ == '__main__':
    main()

rawDescription: Destroying and Recreating a Panel wx.Python


code:
def twoscomp( x ) :
    """This returns a 16-bit signed number (two's complement)"""
    if (0x8000 & x):
        x = - (0x010000 - x)
    return x

rawDescription: Trying to read a two's complement 16bit into a signed decimal


code:
import csv

with open("file.csv") as f:
  reader = csv.reader(f)

  titles = next(reader)
  while titles[-1] == '':
    titles.pop()
  num_titles = len(titles)
  totals = { title: 0 for title in titles }

  for row in reader:
    for i in range(num_titles):
      totals[titles[i]] += int(row[i])

print(totals)

rawDescription: Python: Effective reading from a file using csv module


code: rec_dd = lambda: defaultdict(rec_dd)

rawDescription: defaultdict of defaultdict, nested

description: Defaultdict of defaultdict, nested


code: z = za.reshape(za.shape + (1,)*z0.ndim) + z0

rawDescription: How can I broadcast between 1D and nD arrays to obtain a (1+n)D array output?

description: Broadcast between 1D and nD arrays to obtain a (1+n)D array output


code:
statements = """
DROP TABLE IF EXISTS `tableA`;
CREATE TABLE `tableA`(
some_code
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `tableB`;
CREATE TABLE `tableB`(
some_code
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `tableC`;
CREATE TABLE `tableC`(
some_code
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
"""
regex = r"((?:CREATE|DROP) TABLE (?:IF (?:NOT )?EXISTS )?`tableB`(?:[^;]|(?:'.*?'))*;)"
re.findall(regex, statements, re.I)

rawDescription: How can I parse sql file from within Python?

description: Parse sql file from within Python


code: a = {key: {0: key} for key in range(3)}

rawDescription: Using dict.fromkeys(), assign each value to an empty dictionary


rawDescription: Removing nan elements from matrix

description: Removing nan elements from matrix


code:
master = {i: [alleles[j] for j in vals] for i, vals in ind_pop.items()}
counters = {i: collections.Counter(al) for i, al in master.items()}

rawDescription: How to link two depended inputs of unknown size with variables

description: Link two depended inputs of unknown size with variables


code: globals()["var_name"] = value

rawDescription: What is the pythonic way to setattr() for a module?


code:
# using the `sorter=` argument rather than `a[a_to_as]` avoids making a copy of `a`
as_to_b = a.searchsorted(b, sorter=a_to_as)

rawDescription: Finding a set of indices that maps the rows of one NumPy ndarray to another


code:
from itertools import chain

def reduceat_solution(X, nbrs):
    ind, j = np.transpose([[i, len(v)] for i, v in nbrs.items()])
    i = list(chain(*(nbrs[i] for i in ind)))
    j = np.concatenate([[0], np.cumsum(j)[:-1]])
    return np.add.reduceat(X[i], j)[ind]

np.allclose(original_solution(X, nbrs),
            reduceat_solution(X, nbrs))
# True

rawDescription: Code optimization - number of function calls in Python


code: serv,msg = foo(myinput)

rawDescription: Can sphinx napoleon document function returning multiple arguments?


code:
@mock.patch("subprocess.check_output", mock.MagicMock(return_value='True'))
def test_mockCheckOutput(self):
    self.assertTrue(subprocess.check_output(args=[])=='True')

rawDescription: How does @mock.patch know which parameter to use for each mock object?


code:
lines = open("/path/to/file.xml").readlines()
lines.insert(0, "<something>")
lines.append("</something>")
xml = "".join(lines)
tree = ElementTree.fromstring(xml)

rawDescription: Modifying a Python file object without writing a new file


code:
class ItemPersistencePipeline(object):
    def process_item(self, item, spider):
        try:
             item_model = item_to_model(item)
        except TypeError:
            return item

        model, created = get_or_create(item_model)

        update_model(model, item_model)

        return item

rawDescription: How to update DjangoItem in Scrapy

description: Update DjangoItem in Scrapy


code: do_something( lambda x: x.endswith('.exe'), some_file )

rawDescription: How to pass an 'if' statement to a python method?

description: Pass an 'if' statement to a python method


code:
df_decomp = df_decomp.groupby(level=[0,1]).apply(lambda x: x.set_index('date').resample('D').fillna(method='pad'))
df_decomp = df_decomp.reset_index(level=1, drop=True)

rawDescription: Pandas: decompress date range to individual dates


code: ABC+DE(FG+IH)

rawDescription: python - representing boolean expressions with lists

description: Python - representing boolean expressions with lists


code:
@consumer
def thumbnail_pager(pagesize, thumbsize, destination):
    while True:
        page = new_image(pagesize)
        rows, columns = pagesize / thumbsize
        pending = False
        try:
            for row in xrange(rows):
                for column in xrange(columns):
                    thumb = create_thumbnail((yield), thumbsize)
                    page.write(
                        thumb, col*thumbsize.x, row*thumbsize.y
                    )
                    pending = True
        except GeneratorExit:
            # close() was called, so flush any pending output
            if pending:
                destination.send(page)

            # then close the downstream consumer, and exit
            destination.close()
            return
        else:
            # we finished a page full of thumbnails, so send it
            # downstream and keep on looping
            destination.send(page)

@consumer
def jpeg_writer(dirname):
    fileno = 1
    while True:
        filename = os.path.join(dirname,"page%04d.jpg" % fileno)
        write_jpeg((yield), filename)
        fileno += 1

# Put them together to make a function that makes thumbnail
# pages from a list of images and other parameters.
#
def write_thumbnails(pagesize, thumbsize, images, output_dir):
    pipeline = thumbnail_pager(
        pagesize, thumbsize, jpeg_writer(output_dir)
    )

    for image in images:
        pipeline.send(image)

    pipeline.close()

rawDescription: Circular Programming in Python (corecursion) - is it possible?


code:
def imshow(img, scale_val=1, ax=None, *args, **kwargs):
    if ax is None:
         ax = plt.gca()
    im = ax.imshow(img, *args, **kwargs)
    ax.format_coord = lambda x, y: 'r=%d,c=%d' % (scale_val * int(x + .5),
                                             scale_val * int(y + .5))
    ax.figure.canvas.draw()
    return im

rawDescription: In a matplotlib figure window (with imshow), how can I remove, hide, or redefine the displayed position of the mouse?


code:
query = Category.select().order_by(Category.name).dicts()
return jsonify({'rows':list(query)})

rawDescription: Get full result back from PeeWee query (for conversion to JSON)


code: sorted(m, key= lambda x: y.get(x), reverse=True)

rawDescription: Python: Sorting list based on the values of dictionary


code:
def myview(request):
  conn = MySQLdb.connect("connection info here")
  try:
    cursor = conn.cursor()
    cursor.execute("select * from mytable")
    rows = cursor.fetchall()
  finally:
    conn.close()

  return render_to_response("mytemplate.html", {"rows" : rows})

rawDescription: Pulling data to the template from an external database with django


code:
def subtime(a,b):
    subtract = datetime.timedelta(hours=b)
    difference = a - subtract
    return difference

rawDescription: Doctest with datetime

description: Doctest with datetime


code:
from collections import Counter

find_it = {"be", "do", "of", "the", "to"}

keys = Counter()

with open("inputfile.txt") as f:
    for line in f:
        matches = Counter(w for w in line.split() if w in find_it)
        keys += matches

print(keys)

rawDescription: Integers in defaultdict

description: Integers in defaultdict


code: [('BBBSDC', 'FEKGG', 'SDFGF'), ('SDFGF', 'KETGG', None)]

rawDescription: Find word infront and behind of a Python list


code:
p = re.compile(r'_ab(?![a-zA-Z0-9])')

test_str = "_ab_ab"

re.findall(p, test_str)

rawDescription: Python regular expressions match end of word


code: words = tuple(x for x in re.split(r'\)?[, .]\(?', line) if x)

rawDescription: Python: Splitting a string into words, saving separators


code:
s = "abcdefghijklmnopqrstuvwxyz"
it = iter(s)
''.join(next(it, '') + c for c in it )

rawDescription: Switch every pair of characters in a string


rawDescription: python2.7.6 Initialize a big dictionary but Memory would be used up

description: Python2.7.6 Initialize a big dictionary but Memory would be used up


code: [int(char) for char in str(634)]

rawDescription: Split three-digit integer to three-item list of each digit in Python


code:
c = [x for x in a if x < b]
c

rawDescription: Extract values from a list based on a condition


code: _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)

rawDescription: Printing an object in TensorFlow

description: Printing an object in TensorFlow


rawDescription: Example of implementation of Baum-Welch

description: Example of implementation of Baum-Welch


code:
dtype=[('TradeDate', datetime), ('Expiry', datetime),
       ('Moneyness', float), ('Volatility', float)]
dt = lambda v: datetime.strptime(v, "%Y-%m-%d")
filtered_rows = ((dt(r[0]), dt(r[1]) + r[2:]) for r in cursor)
all_values = np.asarray(filtered_rows, dtype=dtype)

rawDescription: Correct way to fill a list from a SQL query using pyodbc


code:
from xlrd import open_workbook

input_wb = open_workbook('input.xls', formatting_info=True)

rawDescription: Conditionally formatting text strings from Excel using python


code: [{'country': country, 'wins': wins} for country, wins in zip(a, b)]

rawDescription: two Lists to Json Format in python

description: Two Lists to Json Format in python


rawDescription: MongoEngine: Limiting number of responses from DBRef


code:
import ipyparallel as ipp

rc = ipp.Client()
dview = rc[:]
lbview = rc.load_balanced_view()

rawDescription: Sharing queues with ipyparallel cluster

description: Sharing queues with ipyparallel cluster


code:
def length_similarity(c1, c2):
    lenc1 = sum(c1.itervalues())
    lenc2 = sum(c2.itervalues())
    return min(lenc1, lenc2) / float(max(lenc1, lenc2))

rawDescription: Compute the similarity between two lists


code:
s = input()
# input() is a function that gets input from the user
len(s.split())
# len() checks the length of a list, s.split() splits the users input into a word list.

rawDescription: How to count how many words are in a text string inputted by the user in python

description: Count how many words are in a text string inputted by the user in python


code: np.allclose(f(space_old), f(space))

rawDescription: Creating variables in loop for dynamicly creating griddata()


code: fx()

rawDescription: Python: Passing a function and calling it recursively


rawDescription: apply both vectorized and non-vectorized function on numpy array

description: Apply both vectorized and non-vectorized function on numpy array


code:
from sklearn import cross_validation as cval
# Then we create a 10-fold cross validation iterator:
cv = cval.StratifiedKFold(y, 10)

rawDescription: Face recognition in OpenCV Python FAR/FRR


code:
pd.melt(df, id_vars=['-'], value_vars=df.columns.values.tolist()[1:],
        var_name='Dest', value_name='Distance').rename(columns={'-': 'Origin'})

rawDescription: Convert an nxn matrix to a pandas dataframe


code:
def min_max(n,s):

    _min = int(floor(float(n)/float(s)))
    if int(n%s) > 0:
        _min +=1

    return _min

rawDescription: An algorithm for randomly generating integer partitions of a particular length, in Python?


code:
import subprocess
if condition:
    subprocess.call(['python', 'fileA.py'])
else:
    subprocess.call(['python', 'fileB.py'])

rawDescription: run another .py file when condition is true

description: Run another .py file when condition is true


code:
data
unq_data, idx = np.unique(data,return_index=True)
data

rawDescription: Set duplicate elements as zeros

description: Set duplicate elements as zeros


code: hex(ord('A'))

rawDescription: Generate a list of hex bytes in Python

description: Generate a list of hex bytes in Python


code:
import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()

rawDescription: In Python, how do I read the exif data for an image?


rawDescription: scatter plot same point repeated several times python

description: Scatter plot same point repeated several times python


code:
import xml.etree.ElementTree as ET
xml = """..."""
doc = ET.fromstring(xml)
doc.findall(".//rank")

rawDescription: Python-3.x SIMPLE XPath Library

description: Python-3.x SIMPLE XPath Library


code: fig, ax = plt.subplots()

rawDescription: Hierarchy in matplotlib

description: Hierarchy in matplotlib


code:
import pygame
import math
from itertools import cycle

# some simple vector helper functions, stolen from http://stackoverflow.com/a/4114962/142637
def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

pygame.init()
quit = False

path = [(26, 43),
        (105, 110),
        (45, 225),
        (145, 295),
        (266, 211),
        (178, 134),
        (250, 56),
        (147, 12)]
path = cycle(path)
target = next(path)
ball = pygame.rect.Rect(target[0], target[1], 10, 10)
speed = 3.6

while not quit:
    quit = pygame.event.get(pygame.QUIT)
    pygame.event.poll()

    if ball.topleft == target:
        target = next(path)

    target_vector = sub(target, ball.topleft)

    if magnitude(target_vector) < 2:
        target = next(path)
    else:
        move_vector = [c * speed for c in normalize(target_vector)]
        ball.move_ip(move_vector)

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), ball)
    pygame.display.flip()
    clock.tick(60)

rawDescription: Bouncing an image in a polygonal way with pygame


code: from pygal.util import deg, cached_property, compute_scale, is_major

rawDescription: How to monkey-patch an internal private function in a python package?

description: Monkey-patch an internal private function in a python package


code:
struct.calcsize(">I4Q")
struct.calcsize("=I4Q")
struct.calcsize("<I4Q")
struct.calcsize("!I4Q")

rawDescription: Python struct.calcsize doesn't work for QWord


code:
apple,  orange
2,      345
4,      667

rawDescription: Get the dictionary values for every key in a list


code:
t = test()
np.arange(4) - t
t - np.arange(4)

rawDescription: Argument types differ in normal and reflected operator overload (__sub__ / __rsub__)


code:
[buildout]
extends = conf/buildout.cfg

rawDescription: How to specify where to place buildout bootstrap generated folders?

description: Specify where to place buildout bootstrap generated folders


code:
vertices = [(0,0,0),(0,0,-1),(0,-1,0),(0,-1,-1),(-1,-1,-1),(-1,-1,0),(-1,0,0),(-1,0,-1)]
indices = list(zip(*vertices))  #Can store this for later use.
a = np.arange(27).reshape((3,3,3)) #dummy array for testing.  Can be any shape size :)
vertex_values = a[indices].reshape((2,2,2))

rawDescription: Pythonic way to get the first AND the last element of the sequence


code:
# Global variables.
a_handlers = []
b_handlers = []
c_handlers = []

rawDescription: Keeping a list of websocket connections in Tornado


code:
import scipy.sparse as sps
import numpy as np

class MSK:
    # DD is a dict of dict, whose values are of type float.
    # features - the set of possible features keys
    def __init__(self, DD, features):
        self.features = {k: j for (j, k) in enumerate(features)}
        self.strings = DD.keys()
        n = len(self.strings)
        d = len(self.features)
        self.M = sps.dok_matrix((n, d), dtype=np.float64)
        for (i, s) in enumerate(self.strings):
            v = DD[s]
            for k in v:
                j = self.features[k]
                self.M[i, j] = v[k]

rawDescription: How to efficiently compute the inner product of two dictionaries

description: Efficiently compute the inner product of two dictionaries


code: reduce(numpy.dot, [A1, A2, ..., An])

rawDescription: Multiply several matrices in numpy

description: Multiply several matrices in numpy


code:
import re

EXAMPLES = [
    "6x^2",
    "5x",
    "4",
    "x^2 - 3x - 4",
    "6x^2 + 11x - 35",
    "x^2 - 7x",
    "2x^2 + 5x + 3",
    "5x - 3",
    "x^2 - 3",
]

QUADRATIC_PATTERN = r"(?:(\d*)[a-z]\^2)?" r"(?:\s*[-+]\s*)?" r"(?:(\d*)[a-z])?" r"(?:\s*[-+]\s*)?" r"(\d*)?"

for equation in EXAMPLES:
    matchobj = re.search(QUADRATIC_PATTERN, equation)

    if (matchobj):
        print(equation, ": a =", matchobj.group(1), "b =", matchobj.group(2), "c =", matchobj.group(3))
    else:
        print("misread equation:", equation)

rawDescription: How to make a "Regular Expression Template" that gets values in between certain places. Python 3

description: Make a "Regular Expression Template" that gets values in between certain places. Python 3


rawDescription: Converting String to List

description: Converting String to List


code:
# polls/views.py
from django.views.generic import ListView
from .models import Poll

class PollList(ListView):
    model = Poll
    template_name = 'any/path/you/choose/any_name.html'

rawDescription: Elegant way to namespace templates in Django


code:
text = '''mylib|C://desktop//baseicmylib.lib
    randlib|C://desktop//randlib.lib'''

libs = dict(line.split('|', 1) for line in
    (s.strip() for s in text.split('\n')))

rawDescription: Python regular expression to match a path


code: a,b = zip(*y)

rawDescription: How to split a list of 2-tuples into two lists?

description: Split a list of 2-tuples into two lists


code:
from collections import defaultdict

result = defaultdict(lambda: defaultdict(list))

for row in reader:
    epitope = row.pop('Epitope')
    entry = result[epitope]
    for key, value in row.items():
        entry[key].append(value)

rawDescription: Nested dictionary from csv python

description: Nested dictionary from csv python


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

# generate some noisy data
x = np.arange(1000)
y = 0.0001234 * x**2 + 3*np.random.randn(len(x))

# do fit
M = np.column_stack((x**2,)) # construct design matrix
k, _, _, _ = np.linalg.lstsq(M, y) # least-square fit of M * k = y

# quick plot
plt.plot(x, y, '.', x, k*x**2, 'r', linewidth=3)
plt.legend(('measurement', 'fit'), loc=2)
plt.title('best fit: y = {:.8f} * x**2'.format(k[0]))
plt.show()

rawDescription: numpy.polyfit with adapted parameters

description: Numpy.polyfit with adapted parameters


code:
class MyClass(Base):
    @classmethod
    def from_dict(cls, **kwargs):
        # Let any KeyErrors propagate back to the caller.
        # They're the one who forgot to make sure **kwargs
        # contained the right keys.
        value1 = kwargs['attr1']
        value2 = kwargs['attr2']
        return cls(value1, value2)

new_instance = MyClass.from_dict(**dict)

rawDescription: Is there any way to get class instance attributes without creating class instance?


code:
def fun(n):
    l = []
    for i in range(n +1):
        k = i**1
        l.append(k)
    return l

rawDescription: Return a values into a list

description: Return a values into a list


code:
rows = [('1', '2'),
        ('Jack London', 'Son of the Wolf'),
        ('Jack London', 'Chris Farrington'),
        ('Jack London', 'The God of His Fathers'),
        ('Jack London', 'Children of the Frost'),
        ('William Shakespeare', 'Venus and Adonis'),
        ('William Shakespeare', 'The Rape of Lucrece'),
        ('Oscar Wilde', 'Ravenna'),
        ('Oscar Wilde', 'Poems')]
# I'm not sure how you get here, but that's where you get

from itertools import groupby
from operator import itemgetter

grouped = groupby(rows, itemgetter(0))
result = {group:', '.join([value[1] for value in values]) for group, values in grouped}

rawDescription: find duplicates in a column, return the unique item and list its corresponding values from another column in python

description: Find duplicates in a column, return the unique item and list its corresponding values from another column in python


code: soup = BeautifulSoup(xml, "lxml", from_encoding='latin-1')

rawDescription: Despite utf8 encoding some characters fail to be recognized


rawDescription: Python: change "- hrs - min - sec' string into minutes decimal


code:
try:
    # Python 2
    from future_builtins import zip
except ImportError:
    # Python 3, it is built-in
    pass

rawDescription: What is faster? minimum of list then index of minimum, vs iterating through list


code: data = open("banklist.csv", "rU").readlines()[1:]

rawDescription: Python - CSV read as one big line

description: Python - CSV read as one big line


code:
url = "https://youtube.com/watch?v=TESTURLNOTTOBEUSED"
url = url.replace("watch?v=", "embed/")

rawDescription: Convert YouTube link into an embed link

description: Convert YouTube link into an embed link


code:
indices = [offset + i for offset,length in offset_length for i in xrange(length)]
a[indices]

rawDescription: Numpy Array Slicing

description: Numpy Array Slicing


rawDescription: Write nested lists column wise to CSV

description: Write nested lists column wise to CSV


code:
def pre(s1, s2):
    if any(bool(s.strip())==False for s in (s1, s2)):
        return 0

    for i, (c1, c2) in enumerate(zip(s1, s2)):
        if c1!=c2:
            return i

    return i+1

rawDescription: How to create a new string with the prefix of 2 given strings?

description: Create a new string with the prefix of 2 given strings


code:
df = DataFrame(np.arange(25).reshape(5,5))
df

rawDescription: Python pandas: get elements (index,col) below diagonal in dataframe


code:
import os
dir = "E:\\test"
files = os.listdir(dir)
for file in files:
    if file.endswith(".txt"):
        os.remove(os.path.join(dir,file))

rawDescription: Delete files with python through OS shell


code:
['spade:A',
 'spade:2',
 'spade:3',
 'spade:4',
 'spade:5',
 'spade:6',
 'spade:7',
 'spade:8',
 'spade:9',
 'spade:10',
 'spade:J',
 'spade:Q',
 'spade:K',
 'clover:A',
 'clover:2',
 'clover:3',
 'clover:4',
 'clover:5',
 'clover:6',
 'clover:7',
 'clover:8',
 'clover:9',
 'clover:10',
 'clover:J',
 'clover:Q',
 'clover:K',
 'diamond:A',
 'diamond:2',
 'diamond:3',
 'diamond:4',
 'diamond:5',
 'diamond:6',
 'diamond:7',
 'diamond:8',
 'diamond:9',
 'diamond:10',
 'diamond:J',
 'diamond:Q',
 'diamond:K',
 'heart:A',
 'heart:2',
 'heart:3',
 'heart:4',
 'heart:5',
 'heart:6',
 'heart:7',
 'heart:8',
 'heart:9',
 'heart:10',
 'heart:J',
 'heart:Q',
 'heart:K']

rawDescription: Python list and for loop

description: Python list and for loop


code:
from datetime import datetime
dt1 = datetime(2008, 1, 1, 16, 0, 0)
dt2 = datetime(2008, 4, 7, 13, 30, 0)

print(dt1.time() > dt2.time())    # True

rawDescription: How to store time without date in Python so it's convenient to compare?

description: Store time without date in Python so it's convenient to compare


code:
string = "PHOTOThe text which should be present\n"
string[5:-1]

rawDescription: Python regex remove string

description: Python regex remove string


code: html = open('led.html','r').read()

rawDescription: How to display text on the web page using python and HTML

description: Display text on the web page using python and HTML


code:
import pprint
pprint.pprint(customer)

rawDescription: Dynamically add lists as embedded document in Python pymongo mongodb


code:
with open('foo.xml', 'w') as f:
    x.firstChild.writexml(f)

rawDescription: Create xml file without prologue with python dom minidom


code:
def min(*args):
    min = None
    for v in args:
        if min is None or v < min:
            min = v
    return min

print(min(1, 7, 8, 9, 2, 1, 0))

rawDescription: Is there any benefits for using * or ** in python?


code: df = df.set_index(['date', 'group', 'colour'])

rawDescription: Use existing columns as index

description: Use existing columns as index


rawDescription: How can I improve this many-to-many Django ORM query and model set?

description: Improve this many-to-many Django ORM query and model set


code: tuple(li)

rawDescription: Is there anyway to convert a list into a variable for use as a dictionary key?


code:
def split_paths(path):
    def split_paths_reverse(path):
        head, tail = os.path.split(path)
        while head and tail:
            yield tail
            head, tail = os.path.split(head)
        yield head

    return reversed(tuple(split_paths_reverse(path)))

rawDescription: How do I flatten nested lists of lists in python?

description: Flatten nested lists of lists in python


code:
class C:
  red = 2
  def __init__(self):
    self.blue = 2

C.red
C.blue
C().red
C().blue
#OOOOH!

z = C()
z.red
z.blue
D = C
D.red
D().red
D().red = "over 9000!"
D.red
D.red = "No, really over 9000!"
D.red
C.red
#OOOOOOHHHH!

rawDescription: Why can't I change attribute of a class in Python


rawDescription: Converting text to columns

description: Converting text to columns


rawDescription: django custom filter - replace line break with line space

description: Django custom filter - replace line break with line space


rawDescription: Explain how Python decorator works

description: Explain how Python decorator works


code:
lt = t.lower()
any(lt==w.lower() for w in L)

rawDescription: Project Gutenberg Python problem?

description: Project Gutenberg Python problem


code: aGrid = aML_GS.GridSearchCV( aClassifierOBJECT, param_grid = aGrid_of_parameters, cv = cv, n_jobs = n_JobsOnMultiCpuCores, verbose = 5 )

rawDescription: GridSearchCV extremely slow on small dataset in scikit-learn


code: cdf.swaplevel(0, 1, axis=1)

rawDescription: indexing several csv files with pandas from records?

description: Indexing several csv files with pandas from records


rawDescription: Using sleep in VB.net while running external process


code:
# Read the file as a list of strings, each string is a line.
with open('urls.txt', 'r') as f:
    lines = f.readlines()

# Add http:// if necessary:
lines = ['http://'+ln if not ln.startswith('http://') else ln for ln in lines]

# loop over all the URLs
for url in lines:
    parseAddress(url)

rawDescription: Pull a line from a file and then delete it


code:
from bs4 import BeautifulSoup, SoupStrainer # pip install beautifulsoup4

player_links = SoupStrainer('a', 'playerLink', subtab=False)
soup = BeautifulSoup(html, parse_only=player_links)
names = [a.get_text().strip()
         for a in soup.find_all(player_links)]
print(names)

rawDescription: Parse 'a' tags based on attribute using Python and BeautifulSoup


code:
from __future__ import absolute_import

from mymodule.celery import app

@app.task
def add(x, y):
    return x + y

rawDescription: Can i use celery without django

description: Use celery without django


code:
import copy
classOne = copy.deepcopy(classTwo)

rawDescription: Python: How to set class vars to another class of the same type


code:
from app.forms import ProfileForm
from app.models import Profile

class ProfileCreate(CreateView):
    form_class = ProfileForm
    model = Profile

rawDescription: Form, Create and Update View for Many-To-Many Relationship


code:
from itertools import Counter
values = Counter()
for o in my_object:
    values += Counter({o.day: o.seconds})

rawDescription: Appending to a list of lists in Python, with conditions


code:
for i in xrange(m_swapped.shape[-1]):
    assert np.all(m[:,i,:] == m_swapped[...,i])

rawDescription: Iterate across arbitrary dimension in numpy


code:
s = 'cat dog cow dog' # Note 'dog' occurs multiply
s.find('dog')
4
s.find('cow')
8
s.find('cat')
0

rawDescription: How to iterate with index elegantly in Python, for string-matching a list of substrings inside text?

description: Iterate with index elegantly in Python, for string-matching a list of substrings inside text


code:
import inspect

class Meta(type):
    def __repr__(cls):
        return cls.__name__

rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code:
if user.favoriters.filter(pk=my_gallery.pk).exists():
    pass

rawDescription: Django ORM - querying many to many through models?


code:
from random import *
x = 0
while True:
    random1 = randint(1,20)
    random2 = randint(1,20)
    print("h = higher, l = lower, s = same, q = quit")
    print(random1)
    a = input().lower()
    if a == 'q':
        break

    print(random2)

    if ((a == 'h' and random1 < random2) or
        (a == 'l' and random1 > random2) or
        (a == 's' and random1 == random2)):
        x += 10
        print("Well done. Your current score is: {0}".format(x))
    else:
        print("Loser")

rawDescription: how to add score to higher or lower game

description: Add score to higher or lower game


rawDescription: wxPython: program quits but window remaines not responding after calling sys.exit

description: WxPython: program quits but window remaines not responding after calling sys.exit


rawDescription: Know when directory copy is complete

description: Know when directory copy is complete


code: 1 - indexTag

rawDescription: What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1?


code: var = defaultdict(set)

rawDescription: Making a dictionary from a list of strings (creating keys from the elements of the list)


code:
for i, file in enumerate(os.listdir(directoryPath)):
    if file.endswith(".csv"):
       array1[i] = numpy.genfromtxt(file, delimiter=',')[:,2]

rawDescription: On using a string as an integer counter (aka index) in a for loop


code: display(fig)

rawDescription: How to check that pylab backend of matplotlib runs inline?

description: Check that pylab backend of matplotlib runs inline


rawDescription: Python - How to get total no of style attributes of a specific div


code:
def get_initial(self):
    category = None
    if self.request.method == "GET" :
        # this method sets the initial value for the fields
        try:
            category = Category.objects.get(pk=self.request.GET.get('category_id'))
        except Category.DoesNotExist:
            raise Http404(_(u"Destination not found."))

    return {'category': category}

rawDescription: Django Model form with read only properties


code:
import itertools
import collections

q1 = 'q1'
q2 = 'q2'
q3 = 'q3'

dic_list = {
     q1:[1,2,3,4,5],
     q2:[2,3,5],
     q3:[2,5]
     }

#sets are much more efficient for this sort of thing.  Create a dict
#of the same structure as the old one, only with `set` as values
#instead of `list`
dic_set = {k:set(v) for k,v in dic_list.items()}

new_dic = collections.defaultdict(dict)
for k1,k2 in itertools.combinations(dic_set,2):
     #to get the count, we just need to know the size of the intersection
     #of the 2 sets.
     value = len(dic_set[k1] & dic_set[k2])
     new_dic[k1][k2] = value
     new_dic[k2][k1] = value

print (new_dic)

rawDescription: how to get the common items count of lists

description: Get the common items count of lists


code:
for point_and_mag in pm.points_mag:
    mag = point_and_mag[1]
    point = point_and_mag[0]

rawDescription: Python - How to track (add/remove) lots of class instances over mulitple iterations?


code:
# How I set up your dataframe (please include a reproducible df next time)
df = pd.DataFrame(np.random.rand(6,31), index=["ID" + str(i) for i in range(6)],
columns=['first'] + ['mes{0}.{1}'.format(i, j) for i in range(1,4) for j in range(1,11)])
df['first'] = 'john'

rawDescription: Moving columns down and replicating keys in pandas


rawDescription: Operation with Arrays in Python

description: Operation with Arrays in Python


code:
def f(x, y):
    return x*y

a, b = 1, 2

c = f(a, b)

rawDescription: How can you output a varying argument in Python?

description: Output a varying argument in Python


code:
d = data['Date'].values
plt.fill_between(d, data['A'], data['B'],
                where=data['A'] >= data['B'],
                facecolor='green', alpha=0.2, interpolate=True)

rawDescription: Pandas and Matplotlib - fill_between() vs datetime64


rawDescription: Transform an array of count data into a matrix of ones and zeroes


rawDescription: Pandas: How to convert column of string objects representing categories to integers?


code:
@uses_file(default_prefix="RESPONE_")
def writeFile(self, someHtml, prefix):
   '''...'''
   h.write(someHtml)

@uses_file(default_prefix="mechList_")
def writeList(self, someList, prefix):
    '''...'''
    h.writelines(someList)

rawDescription: Can I specify another class's instance-method as a variable for my method?

description: Specify another class's instance-method as a variable for my method


code:
import mylib
l = mylib.MyLib()
l.assign1(globals())

rawDescription: Assign methods from class in imported module to current namespace


code:
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
   ...

rawDescription: In Python, is there a concise way of comparing whether the contents of two text files are the same?


code: x, y = (xin, yin)

rawDescription: how to manipulate a list in python

description: Manipulate a list in python


code:
import csv

with open("file.csv") as f:
    csvfile = csv.reader(f)
    names = dict()
    for row in csvfile:
        curname = row[0]  # get the name on first col
        new_nums = row[1:4]  # get the values as a list
        name_nums = names.get(curname)  # get the stored values for the name
        if name_nums:  # true when the name had been encountered already
            del name_nums[:len(new_nums)]  # pop as many values as the new ones
            name_nums.extend(new_nums)  # append the new values
        else:
            names[curname] = new_nums  # new name so just add it to the dict

print(names)

rawDescription: How do i append a list with new data?

description: Append a list with new data


code:
import ctypes
tid = ctypes.CDLL('libc.so.6').syscall(186)

rawDescription: ID of a Python thread as reported by top


code:
p = re.search(r'Profile\t+(\w+)',s)
d = re.search(r'BuildDate\t+([A-z0-9-]+)',s)

return (p.group(1) if p is not None else None,
        d.group(1) if d is not None else None)

rawDescription: Better way to return any match in a python regex search?


code: name == line.partition('|')[0]

rawDescription: Deleting a line in file containing exact string (Python)


code: df = pd.DataFrame({'Demande' : p2['VALUE_DEMANDE'].values,'Forcast' : p2['VALUE_FORCAST'].values},index=p2['DT_COMPUTE_FORCAST'])

rawDescription: Pandas / SQLITE DataFrame plot

description: Pandas / SQLITE DataFrame plot


rawDescription: Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?


rawDescription: Convert list items to defined data type

description: Convert list items to defined data type


code:
import string
secret = "this is my hangman"
guesses = ['a', 'c', 'g']
"".join([l if l not in set(string.ascii_lowercase) - set(guesses) else '_' for l in secret])
guesses.append('i')
"".join([l if l not in set(string.ascii_lowercase) - set(guesses) else '_' for l in secret])

rawDescription: How can I replace specific characters in python?

description: Replace specific characters in python


code:
import datetime as DT
DT.datetime.strptime('2014-12-15', '%Y-%m-%d')

rawDescription: adding and subtracting from a date

description: Adding and subtracting from a date


rawDescription: Python - BeautifulSoup findParent by attribute


code:
def process_asyncs(cls):

    def create_method(async_method):

        @class_or_instance
        def newmethod(self, *args, **kwargs):
            if 'verbose' in kwargs:
                verbose = kwargs.pop('verbose')
            else:
                verbose = False
            response = async_method(*args,**kwargs)
            result = self._parse_result(response, verbose=verbose)
            return result
        return newmethod

    methods = cls.__dict__.keys()
    for k in methods:
        methodname = k.replace("_async","")
        if 'async' in k and methodname not in methods:
            async_method = getattr(cls, k)
            setattr(cls, methodname, create_method(async_method))

    return cls

rawDescription: Add methods to a class generated from other methods