code:
# my_module.py
import os
import csv

def bar(path, filename, list):
    full_path = os.path.join(path, filename)
    with open(full_path, 'w') as f:
        csv_writer = csv.writer
        csv_writer.writerows(list)

rawDescription: Can I import a built-in module twice in both my script and custom module


code:
K
sorted(range(len(K)), key=lambda x: K[x])
sorted(range(len(K)), key=lambda x: K[x])[-5:]

rawDescription: How to find the index of n largest elements in a list or np.array, Python

description: Find the index of n largest elements in a list or np.array, Python


code:
with open(infile, 'rb') as in_strm:
    datastruct = dill.load(in_strm)

rawDescription: Loading a pkl file using dill

description: Loading a pkl file using dill


rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code:
def print_item(item):
    print(item)

if __name__ == '__main__':
    import dis
    dis.dis(print_item)

rawDescription: input and print in python 3

description: Input and print in python 3


code: a * b[:, None]

rawDescription: Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?


code:
from django.utils.dateparse import parse_datetime
naive = parse_datetime("2012-02-21 10:28:45")
import pytz
pytz.timezone("Europe/Helsinki").localize(naive)

rawDescription: How to store a naive datetime in Django 1.4

description: Store a naive datetime in Django 1.4


code:
grouped = df.groupby(['Year', 'ageGrp'], as_index=False)
final = grouped.agg(np.sum)

rawDescription: Python pandas.cut

description: Python pandas.cut


code:
import os
import logging
import logging.handlers

class TruncatedFileHandler(logging.handlers.RotatingFileHandler):
    def __init__(self, filename, mode='a', maxBytes=0, encoding=None, delay=0):
        super(TruncatedFileHandler, self).__init__(
            filename, mode, maxBytes, 0, encoding, delay)

    def doRollover(self):
        """Truncate the file"""
        if self.stream:
            self.stream.close()
        dfn = self.baseFilename + ".1"
        if os.path.exists(dfn):
            os.remove(dfn)
        os.rename(self.baseFilename, dfn)
        os.remove(dfn)
        self.mode = 'w'
        self.stream = self._open()

rawDescription: Limit Python log file

description: Limit Python log file


code:
False
True

rawDescription: Avoid chained numbers when printing lists


rawDescription: How do I fill in unused ip addresses in a python sublist?

description: Fill in unused ip addresses in a python sublist


code:
value1
value2

rawDescription: Using python requests module to hit API, how do I filter what's returned when using 'print r.json'?


code:
assert not os.path.isabs('log.html')
dstdir =  os.path.join(dstroot, os.path.dirname('log.html'))
shutil.copy('log.html', dstdir)

rawDescription: I would like to copy a file to a new directory and then rename it using the datetime :: Python


code:
i_expect_an_array = some_json_data['companies']
if not isinstance(i_expect_an_array, list):
    i_expect_an_array = (i_expect_an_array,)

# Now, you can process the data as you normally would

rawDescription: FOR loop in object/array

description: FOR loop in object/array


code:
class ThreadForm(ModelForm):

    def __init__(self, forum, user, *args, **kwargs):
        super(ThreadForm, self).__init__(*args, **kwargs)
        self.forum = forum
        self.user = user

    def save(self):
        thread = super(ThreadForm, self).save(commit=False)
        thread.forum = self.forum
        thread.creator = self.user
        thread.save()
        return thread

    class Meta:
        model = Thread
        exclude = ('slug', 'created', 'creator', 'forum')

rawDescription: How do I write a form in django

description: Write a form in django


code:
from collections import defaultdict

def aggregate(docs, label):
    bow = defaultdict(int)
    for doc in docs:
        if doc.label == label:
           for (word, counter) in doc.bowdict.items():
                bow[word] += counter
    return bow

rawDescription: I need a neat data structure suggestion to store a very large dataset (to train Naive Bayes in Python)


rawDescription: mongodb: insert if not exists

description: Mongodb: insert if not exists


code:
import pandas as pd
from pandas import Series

# Create test dataframe
df = pd.DataFrame({'col1': ['a, b'], 'col2': [100]}, index=['A'])

#split the values in column 1 and then stack them up in a big column
s = df.col1.str.split(', ').apply(Series, 1).stack()

# get rid of the last column from the *index* of this stack
# (it was all meaningless numbers if you look at it)
s.index = s.index.droplevel(-1)

# just give it a name - I've picked yours from OP
s.name = 'idx_2'

del df['col1']
df = df.join(s)
# At this point you're more or less there

# If you truly want 'idx_2' as part of the index - do this
indexed_df = df.set_index('idx_2', append=True)

rawDescription: Create multi-level index pandas dataframe from delimited string column


code: [sorted(map(int, i)) for i in lst]

rawDescription: How do I get the correct result in the list of lists sorting in python

description: Get the correct result in the list of lists sorting in python


code:
import numpy as np
a = np.ones((1,2,2,2))
print(a.shape) # (1, 2, 2, 2)

rawDescription: adding matrices to n dimensional array with numpy

description: Adding matrices to n dimensional array with numpy


rawDescription: Exporting a 2D array with 0-values into a txt/csv file


code:
def replace_commas(s):
    return s.replace(',', '')

with open('orig.csv', newline='') as fin, open('new.csv', newline='') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    for row in reader:
        writer.writerow(map(replace_commas, row))

rawDescription: python load csv file with quoted fields where commas are used as 1000s separator

description: Python load csv file with quoted fields where commas are used as 1000s separator


code:
s = "objQuery Barack Obama expandableMapFoo"
m = re.findall(r'\b[a-z]+(?:[A-Z][a-z]+)+\b', s)
m

rawDescription: Removing words with CAPITAL letters in between


code:
import pwd
import grp
import os

uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid

rawDescription: How to set a files owner in python?

description: Set a files owner in python


code: ["http://www.fetise.com/" + i if "http://www.fetise.com/" not in i else i for i in lista]

rawDescription: How to use Python condensed For loop with if else

description: Use Python condensed For loop with if else


code:
for name in tree.iter('name'):
    if name.text.lower() == nome.lower():
        c = Context({'id' : name.text})
        r1 = HttpResponse(t.render(c), mimetype='application/xml')
    else:  r1 = HttpResponse(t.render(Context({'id' : 'prova'})), mimetype='application/xml')
return r1

rawDescription: if statement in django

description: If statement in django


rawDescription: Efficiently check if numpy ndarray values are strictly increasing


rawDescription: Can't Import Bigrams From NLTK Library

description: Can't Import Bigrams From NLTK Library


code:
import re
for score, name in re.findall("(\d+) (\w+)", f.read()):  # using regular expressions module to parse the scores and names
    scores[name.strip()].append(int(score))

# Set highest scores first in list and print those sorted
# sort the individual scores high to low, list format[(name, scores),...,]
score_list = [(name, sorted(scores[name], reverse=True)) for name in scores]
# sort the named scores high to low by highest score(x[0] sorts names alphabetic)
score_list = sorted(score_list, key=lambda x: x[1], reverse=True)
print("Highest sorted")
for name, v in score_list:  # v contains the individual scores
    print(v[0], name)  # Print highest score which is at 0 index and print the name

print()
print("highest to lowest")
for name, v in score_list:  # v contains the individual scores
    print(v, name)  # Print scores and name

print()
print("highest average")
average_scores = []
# iterate through the ordered score list and append the average score to the average_scores list
for name, v in score_list:  # v contains the individual scores
    average_scores.append((name, sum(v) / len(v)))
# sort average_scores high to low
sorted_average_scores = sorted(average_scores, key=lambda x: x[1], reverse=True)
# iterate through sorted_average_scores and print the rounded average, non-sorted individual scores, and name
for name, average in sorted_average_scores:
    print(round(average), scores[name], name)

rawDescription: to alphabetically order a name and score from a textfile which joins the users name and their highest score

description: To alphabetically order a name and score from a textfile which joins the users name and their highest score


code:
def yourfunc(x, y, _hack=[0]):
    for i in range(x):
        for j in range(y):
            _hack[0] += 1

rawDescription: Static variable in python?

description: Static variable in python


code:
def int_factory(fields):
    return type("Int", (Structure,), {"_fields_": fields})

rawDescription: Setting _fields_ dynamically in ctypes.Structure


code:
filenames = ('babyQld2010.csv',
    'babyQld2011.csv',
    'babyQld2012.csv',
    'babyQld2012.csv',
    'babyQld2014.csv')

with open('babyQldAll.csv','w') as outFile:

    csvFile_out = csv.writer(outFile, delimiter=',')

    for filename in filenames:
        name, ext = filename.split('.')
        year = name.split('.')[0][-4:]     #extract year from  file names
        records = extract_names(filename)
        for record in records:
            csvFile_out.writerow([year] + record)

rawDescription: Python: add value and write output

description: Python: add value and write output


code: grammar = maybe_some([LineFilter,StringLiteral]), optional(BooleanLiteral)

rawDescription: pypeg2 - can this expression be parsed using peg grammar?

description: Pypeg2 - can this expression be parsed using peg grammar


code:
pygame.Color("black")
pygame.Color(3, 255, 3)

rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
import copy

class Parent(object):
   def __init__(self, name, number):
       self.name = name
       self.number = number

class Child(object):
    def __init__(self, parent, other):
        # only copy instance attributes from parents
        # and make a deepcopy to avoid unwanted side-effects
        for k, w in parent.__dict__.items():
            self.__dict__[k] = copy.deepcopy(v)
        self.other = other

rawDescription: How to copy all attributes of one Python object to another?

description: Copy all attributes of one Python object to another


code:
import re
url1 = 'www.lamp.com/;alskfjdlkfja;sdlkfjasldfj-209'
url2 = 'www.lamp.com/a;slkfja;sdlkfjas;dflkj'

re.search(r'/[^-]+-', url1) is not None
re.search(r'/[^-]+-', url2) is not None

rawDescription: Characters following a slash and ending before a hyphen


code:
int(h.digest().encode('hex'), 16)
int(binascii.hexlify(h.digest()), 16)

rawDescription: Operations on Python hashes

description: Operations on Python hashes


code:
class PaymentsForm(forms.Form):
    invoice = forms.CharField(widget=forms.HiddenInput())
    total = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super(PaymentsForm, self).__init__(*args, **kwargs)
        for i in xrange(10):
            self.fields['item_name_%d' % i] = forms.CharField(widget=forms.HiddenInput())

rawDescription: Django - Repeating a form field n times in one form


code: x1,y1,z1 = np.argwhere(points_sphere)[:,0], np.argwhere(points_sphere)[:,1], np.argwhere(points_sphere)[:,2]

rawDescription: Python : fill cuboid with spheres

description: Python : fill cuboid with spheres


code:
media = entry['media']
sorted_media = sorted(media, key=lambda m:m['rank'])

rawDescription: Sort on sub document python bottle

description: Sort on sub document python bottle


code:
i2 = sorted(i)
i2

rawDescription: How to obtain different types of range in an array

description: Obtain different types of range in an array


code:
from collections  import defaultdict

audio = defaultdict(list)

if elementTree.find('./connections') is None:
    return
else:
    for connection_element in elementTree.findall('.//connections/connection'):
        # Get the type for this connection.
        controlType = connection_element.find('type')
        # Get the id for this connection.
        connectionID = connection_element.find('id')
        if controlType is not None and str(controlType.text) == '6':
            # Now find all of the classname(s) in this specific connection element.
            for class_name in connection_element.findall('classes/class/classname'):
                audio[connectionID.text].append(class_name.text)
    return audio

rawDescription: How to add multiple values to the same key in a Python Dictionary

description: Add multiple values to the same key in a Python Dictionary


code:
positive = [2, 3]
negative = [4, 5]

positive_query = db.session.query(Property.user_id)\
    .filter(Property.property_number.in_(positive))\
    .group_by(Property.user_id)\
    .having(func.count()==len(positive))

negative_query = db.session.query(Property.user_id)\
    .filter(Property.property_number.in_(negative))\
    .distinct()

final_result = positive_query.except_(negative_query).all()

rawDescription: Sqlalchemy single query for multiple rows from one column in one table


code: positions = nx.spring_layout(G)

rawDescription: Python: Network Spring Layout with different color nodes


code:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(2, 10),
                  columns='Time A_x A_y A_z B_x B_y B_z C_x C_y C-Z'.split())
X = df.filter(regex='_x')
Y = df.filter(regex='_y')

rawDescription: Splitting pandas data frame based on column name


code: [sorted(set(l)) for l in g]

rawDescription: Using sublists to create new lists where numbers don't repeat


code:
a = 'a\tb\tc\t\te'
a.split()
a.split('\t')

rawDescription: Python loops to check columns

description: Python loops to check columns


code: ranpak_dict = {row['SN']: row for row in reader if int(row['CHARGE']) > 0}

rawDescription: Add key/values to dictionary using condition


code:
class Thing(object):
    id_iter = None
    def __init__(self, num=1):
        if Thing.id_iter is None:
            Thing.id_iter = itertools.count(num)
        self.id = next(self.id_iter)

rawDescription: initialize itertools count in library from database query

description: Initialize itertools count in library from database query


code:
def find(self, path, namespaces=None):
    return ElementPath.find(self, path, namespaces)

rawDescription: ElementTree: What is the syntax for the 'match' argument to the 'find' method?


rawDescription: List comprehension with an accumulator

description: List comprehension with an accumulator


code:
from scrapy.item import Item, Field
from scrapy.spider import BaseSpider

class TableItem(Item):
    row = Field()

class TestSider(BaseSpider):
    name = "tabletest"
    start_urls = ('http://scrapy.org?finger', 'http://example.com/toe')

    def parse(self, response):
        item = TableItem()

        row = dict(
            foo='bar',
            baz=[123, 'test'],
        )
        row['url'] = response.url

        if 'finger' in response.url:
            row['digit'] = 'my finger'
            row['appendage'] = 'hand'
        else:
            row['foot'] = 'might be my toe'

        item['row'] = row

        return item

rawDescription: Scrapy: Define items dynamically

description: Scrapy: Define items dynamically


code:
import xml.dom.minidom as minidom
content = '''<root xmlns:f="foo"><f:test/><f:test/></root>'''
dom = minidom.parseString(content)
for n in dom.getElementsByTagNameNS('*', 'test'):
    print(n.toxml())
    # <f:test/>
    # <f:test/>

rawDescription: How to search for XML elements in python?

description: Search for XML elements in python


code:
#base.py
import sys
import unittest2 as unittest

class BaseTestClass(unittest.TestCase):

    def setUp(self):
        device = "Type that blocks"
    def tearDown(self):
        pass

rawDescription: Python unittest, skip tests when using a base-test-class


rawDescription: convert delimited string to hierarchical JSON in python

description: Convert delimited string to hierarchical JSON in python


code:
def floater(lstlst):
    return [map(float, items) for items in lstlst]

rawDescription: Dealing with a list of lists in Python and selecting a subset of lists


code:
False
True
False

rawDescription: Identifying that a variable is a new-style class in Python?


code: df

rawDescription: Merging 2 list of dicts based on common values


code:
# construct list of msg_ids
msg_ids = [ r['msg_id'] for r in rc.db_query({'client_uuid': client_uuid}, keys=['msg_id']) ]
# use client.get_result to retrieve the actual results:
results = rc.get_result(msg_ids)

rawDescription: IPython parallel : how to recover job IDs from IPcontroller


code: len(d[ip])

rawDescription: How to get unique keys and list of unique values in python dictionary?

description: Get unique keys and list of unique values in python dictionary


code:
import time

start = time.time()  # seconds since the UNIX epoch

# upload your file

elapsed = time.time() - start

rawDescription: How can I upload/download a file with python and log the time it takes in each operation?

description: Upload/download a file with python and log the time it takes in each operation


code:
result = df.set_index('date_closed').reindex(hourly_date_rng).fillna(0).reset_index()

# maybe convert date_closed column to string first
result['date_closed'] = pd.DatetimeIndex(result['date_closed']).to_native_types()
# to json function
json_result = result.to_json(orient='records')

# print out the data with pretty print
from pprint import pprint
pprint(json.loads(json_result))

[{'amount': 0.0, 'date_closed': '2012-08-04 12:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 13:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 14:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 15:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 16:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 17:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 18:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 19:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 20:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 21:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 22:00:00'},
 {'amount': 0.0, 'date_closed': '2012-08-04 23:00:00'}]

rawDescription: Is there an efficient way to fill date gaps in python?


code:
from datetime import datetime, timedelta

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def select_date(calendar, mininum_date=None):
    try:
        # check if "Your Date" is there
        your_date_elm = calendar.find_element_by_class_name("your-date")

        your_date = your_date_elm.get_attribute("data-date")
        print("Found 'Your Date': " + your_date)
        your_date_elm.click()

        # check if your_date against the minimum date if given
        your_date = datetime.strptime(your_date, "%Y-%m-%d")
        if mininum_date and your_date < mininum_date:
            raise NoSuchElementException("Minimum date violation")
        return your_date
    except NoSuchElementException:
        flight_date = None
        flight_date_elm = None
        while True:
            print("Processing " + calendar.find_element_by_css_selector("div.subheader > p").text)

            try:
                if mininum_date:
                    flight_date_elms = calendar.find_elements_by_class_name("flights")
                    flight_date_elm = next(flight_date_elm for flight_date_elm in flight_date_elms
                                           if datetime.strptime(flight_date_elm.get_attribute("data-date"), "%Y-%m-%d") >= mininum_date)
                else:
                    flight_date_elm = calendar.find_element_by_class_name("flights")
            except (StopIteration, NoSuchElementException):
                calendar.find_element_by_partial_link_text("Next month").click()

            # if found - print out the date, click and exit the loop
            if flight_date_elm:
                flight_date = flight_date_elm.get_attribute("data-date")
                print("Found 'Flight Date': " + flight_date)
                flight_date_elm.click()
                break

        return datetime.strptime(flight_date, "%Y-%m-%d")

driver = webdriver.Firefox()
driver.get("http://www.jet2.com/cheap-flights/leeds-bradford/antalya/2016-03-01/2016-04-12?adults=2&children=2&infants=1&childages=4%2c6")

wait = WebDriverWait(driver, 10)

# get the outbound date
outbound = wait.until(EC.visibility_of_element_located((By.ID, "outboundsearchresults")))
outbound_date = select_date(outbound)

# get the inbound date
inbound = driver.find_element_by_id("inboundsearchresults")
inbound_minimum_date = outbound_date + timedelta(days=7)
inbound_date = select_date(inbound, mininum_date=inbound_minimum_date)

print(outbound_date, inbound_date)

driver.close()

rawDescription: How to check current date and move to next date

description: Check current date and move to next date


code:
# Third column will be all 9's
cov[:,2] = 9

# Second row will be all 1's (will overwrite the 9 in col3)
cov[1,:] = 1

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
class Greeter:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print('Hello, {.name}'.format(self))

rawDescription: Anonymous Inner Class in Python

description: Anonymous Inner Class in Python


rawDescription: Django cannot access all objects in a model


code: re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), quoted)

rawDescription: Javascript unescape() vs. Python urllib.unquote()


code: alignSeq('MAT--LA-B','MATATLAB')

rawDescription: Inserting missing portions of a sequence in python


code: sum([item['Weight'] for item in data])/len(data)

rawDescription: average list of dictionaries in python

description: Average list of dictionaries in python


rawDescription: Is there a faster way to use @property for multiple properties in a class?


code:
from myapp.models import MyModel # <- This is bad in datamigration
MyModel.objects.filter(...)

rawDescription: Django South: Adding a model field after a datamigration


rawDescription: Changing matshow xticklabel position from top to bottom of the figure


code: [item for subl in m for item in subl]

rawDescription: Converting matrix to an array in python

description: Converting matrix to an array in python


rawDescription: Parsing a string with defined data dictionary into a list efficiently


rawDescription: Sorting data for plotting in mplot3d

description: Sorting data for plotting in mplot3d


code:
from ghost import Ghost
ghost = Ghost()
page, resources = ghost.open('http://academic.research.microsoft.com/Search?query=lander')
result, resources = ghost.evaluate(
    "document.getElementsByClassName('inline-text-org');")

rawDescription: web scraping dynamic content with python

description: Web scraping dynamic content with python


code:
@logged
def my_func(arg1,arg2):
   # your code here
   pass

rawDescription: What kind of things can be done with Java but not Python?


code:
from collections import defaultdict
import re

comment_line = re.compile(r"\s*#")
matches = defaultdict(dict)

with open('path/to/file.txt') as inf:
    d = {} # should catch and dispose of any matching lines
           # not related to a class
    for line in inf:
        if comment_line.match(line):
            continue # skip this line
        if line.startswith('class '):
            classname = line.split()[1]
            d = matches[classname]
        if line.startswith('model'):
            d['model'] = line.split('=')[1].strip()
        if line.startswith('fields'):
            d['fields'] = line.split('=')[1].strip()
        if line.startswith('write_once_fields'):
            d['write_once_fields'] = line.split('=')[1].strip()
        if line.startswith('required_fields'):
            d['required_fields'] = line.split('=')[1].strip()

rawDescription: Regex that grabs variable number of groups


code: pprint.pprint(authors, width=200)

rawDescription: Grouping characters in Python

description: Grouping characters in Python


rawDescription: How do you convert a string to a function in python?

description: Convert a string to a function in python


code:
input_name = raw_input("Enter variable name:") # User enters "orange"
globals()[input_name] = 4
print(orange)

rawDescription: setting user input to variable name

description: Setting user input to variable name


code:
orig = [ 'a', 'b', 'c', 'd', 'c' ]
rep = {'c': ['x', 'y', 'z']}
list(chain.from_iterable(rep.get(c, [c]) for c in orig))

rawDescription: Replacing list item with contents of another list


code:
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import sys
import codecs

symbols = ('♠','♥','♦','♣')

print(' '.join(symbols))
print(*symbols)
with codecs.open('test.txt','w','utf-8') as testfile:
    print(*symbols, file=testfile)

rawDescription: Unicode not printing correctly to cp850 (cp437), play card suits


rawDescription: How to remove the line breaks in front of a tag in Xpath

description: Remove the line breaks in front of a tag in Xpath


code:
folders = []
for root, dirs, files in os.walk(here):
    if not dirs:
        folders.append(root)

rawDescription: Printing final (leaf?) nodes in directory listing Python


code: prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value

rawDescription: how to check if a cell is empty in openpyxl python

description: Check if a cell is empty in openpyxl python


rawDescription: Merging rows when counting - Django/SQL

description: Merging rows when counting - Django/SQL


rawDescription: Automatically truncate numpy arrays

description: Automatically truncate numpy arrays


code: date,link

rawDescription: Extract relevant links and storing them as .csv file


code:
class StatsTrackerSingleton(metaclass=Singleton):
    def __init__(self):
        self.data = {}

    # ... methods to update data, summarize it, etc. ...

rawDescription: Python Singleton design pattern tracking application stats


code:
def _create_testcase_tag(testsuite, elem):
    """Add elem to testsuite.

    testsuite --> xml.etree.ElementTree
    elem --> list

    return xml.etree.ElementTree
    """

    level1, level2, level3, elem4, elem5, elem6 = elem
    level1 = level1.replace(' ','_')
    level2 = level2.replace(' ','_')
    level3 = level3.replace(' ','_')

    # -- testsuite (level1)
    testsuite_level1 = testsuite.find(level1)
    if not testsuite_level1:
        testsuite_level1 = ET.SubElement(testsuite, level1)

    # -- testsuite (level2)
    testsuite_level2 = testsuite_level1.find(level2)
    if not testsuite_level2:
        testsuite_level2 = ET.SubElement(testsuite_level1, level2)

    # -- testsuite (level3)
    testsuite_level3 = testsuite_level2.find(level3)
    if not testsuite_level3:
        testsuite_level3 = ET.SubElement(testsuite_level2, level3)

    # -- testcase
    testcase = ET.SubElement(testsuite_level3, "testcase")
    testcase.set("name", "TBD")
    summary = ET.SubElement(testcase, "summary")
    summary.text = "Test Type= {}, Automated= {}, Available={}".format(elem4, elem5, elem6)

    return testsuite

# testsuite (root)
testsuite = ET.Element('testsuite')
testsuite.set("name", "Tests")

with open(input_file) as in_file:
    for line in in_file:
        line = line.strip().rstrip(';').split(';')
        testsuite = _create_testcase_tag(testsuite, line)

rawDescription: Merging elements inside a xml.etree.ElementTree


code:
dict1
{0: 'initValue0', 1: 'initValue1', 2: 'initValue2', 3: 'initValue3', 4: 'initValue4', 5: 'initValue5', 6: 'initValue6', 7: 'initValue7', 8: 'initValue8', 9: 'initValue9'}

dict2
{3: 'address3', 4: 'address4', 5: 'address5', 6: 'address6', 7: 'address7', 8: 'address8', 9: 'address9', 10: 'address10', 11: 'address11', 12: 'address12'}

dict3 (combined)
{'address5': 'initValue5', 'address4': 'initValue4', 'address7': 'initValue7', 'address6': 'initValue6', 'address3': 'initValue3', 'address9': 'initValue9', 'address8': 'initValue8'}

rawDescription: Compare two dictionaries with one key in common and form a new dictionary combining the remaining keys associated with this common key


code:
def fix_url(producer_data):
    return (producer_data[0], producer_data[1], producer_data[2].replace(".images", ".servers"))

def images_custom_list(args, producer_data):
    tenant, token, url = fix_url(producer_data)

    # stuff ...

def image_list_detail(args, producer_data):
    tenant, token, url = fix_url(producer_data)

    # stuff ...

rawDescription: Python Function Decoration In This Instance


code:
with open('test.txt','rb') as myfile:
    mylist = list(csv.reader(myfile, delimiter='|'))

mylist
with open('test.txt','r') as myfile:
    mylist = [line.strip().split('|') for line in myfile]

mylist

rawDescription: Python operation with delimited texts in text file


rawDescription: Getting two values from one range

description: Getting two values from one range


code:
from OpenSSL import crypto

cert_file = '/path/to/your/certificate'
cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert_file).read())
subject = cert.get_subject()
issued_to = subject.CN    # the Common Name field
issuer = cert.get_issuer()
issued_by = issuer.CN

rawDescription: How can i get Certificate issuer information in python?

description: Get Certificate issuer information in python


code:
def strip_ns_prefix(tree):
    #iterate through only element nodes (skip comment node, text node, etc) :
    for element in tree.xpath('descendant-or-self::*'):
        #if element has prefix...
        if element.prefix:
            #replace element name with it's local name
            element.tag = etree.QName(element).localname
    return tree

rawDescription: How can I strip namespaces out of an lxml tree?

description: Strip namespaces out of an lxml tree


code:
firstlist = [{'fld':'a1', 'sortkey':'k2'}, {'fld':'b1', 'sortkey':'k3'}, {'fld':'c1', 'sortkey':'k1'},{'fld':'d1', 'sortkey':'k3'}]
secondlist = [{'sortkey':'k1', 'value':9}, {'sortkey':'k2', 'value':10}, {'sortkey':'k3', 'value':7}]
sort_map = {d['sortkey']: d['value'] for d in secondlist}
sorted(firstlist, key=lambda d: sort_map[d['sortkey']])

rawDescription: Sorting list of dictionaries using the values from another list of dictionaries


code:
hand = [{'rank':10, 'suit':'Spade'}, {'rank':11, 'suit':'Heart'}, {'rank':9, 'suit':'Spade'}, {'rank':12, 'suit':'Spade'}, {'rank':7, 'suit':'Spade'}]
rank_set = set([card['rank'] for card in hand])
is_straight = (max(rank_set) - min(rank_set) + 1) == len(hand) and len(rank_set) == len(hand)
is_straight

rawDescription: Identifying a 'straight' (from Poker) using Python


code:
filt_df = filt_df.apply(lambda x: x[(x>quant_df.loc[low,x.name]) &
                                    (x < quant_df.loc[high,x.name])], axis=0)

rawDescription: Remove Outliers in Pandas DataFrame using Percentiles


code:
# module_a.py
import module_b

def foo():
    return "bar"

def bar():
    return module_b.baz()

# module_b.py
def baz():
    import module_a
    return module_a.foo()

rawDescription: Patterns for dealing with memcache Caching in Django


code: file_qs = file_qs.order_by('-order')

rawDescription: How do you get Django's filer app to list new files at the top of the list?

description: Get Django's filer app to list new files at the top of the list


code:
while not parent.stopped:
    do_some_maintenance_work

rawDescription: terminate/restart python script if all children are stopped and prevent other children from spawning

description: Terminate/restart python script if all children are stopped and prevent other children from spawning


code:
from itertools import groupby
from collections import defaultdict
lst.sort(key=lambda x: x[3])
d = defaultdict(list)
for x, y in groupby(lst, key=lambda x: x[3]):
    y = list(y)
    d[len(y)].extend(y)

print(d)

rawDescription: Finding occurence in list of lists

description: Finding occurence in list of lists


rawDescription: Limiting print output

description: Limiting print output


rawDescription: python lxml can't find table

description: Python lxml can't find table


code:
import sys
import ruamel.yaml

with open('new.yaml') as fp:
    newvars = ruamel.yaml.round_trip_load(fp)
with open('old.yaml') as fp:
    oldvars = ruamel.yaml.round_trip_load(fp)
for key in newvars:
    if key in oldvars:
        # this copies the value from the old file if the key exists in there
        value =  oldvars[key]
    else:
        # ask the user for a new value
        value = raw_input("Enter the value ")
    # update the value in newvars
    newvars[key] = value
ruamel.yaml.round_trip_dump(newvars, sys.stdout)

rawDescription: Copy content from one YAML to another YAML after comparison of keys


code:
class Meta(type):
    def __new__(cls, clsname, bases, dct):
        res = type.__new__(cls, clsname, bases, dct)
        for cls in bases:
            if isinstance(cls, Meta):
                try:
                    cls.extending(res)
                except AttributeError:
                    pass
        return res

rawDescription: Execute code when extending a class in Python


code:
import urllib3
user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) ..'}
http = urllib3.PoolManager(10, headers=user_agent)
r1 = http.urlopen('GET', 'http://httpbin.org/headers')
print(r1.data)

rawDescription: urllib3 download a file using specified user agent

description: Urllib3 download a file using specified user agent


code:
@property
def site(self):
    return self.gallery.site

rawDescription: Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?


code:
def handlePrint(self):
    dialog = QtGui.QPrintDialog()
    if dialog.exec_() == QtGui.QDialog.Accepted:
        self.handlePaintRequest(dialog.printer())

def handlePreview(self):
    dialog = QtGui.QPrintPreviewDialog()
    dialog.paintRequested.connect(self.handlePaintRequest)
    dialog.exec_()

rawDescription: How can I print data from my database while in QTableWidget?

description: Print data from my database while in QTableWidget


rawDescription: How to look only at entire words with regex?

description: Look only at entire words with regex


code: val = ''.join(filter(lambda c: c.isdigit() or c in ',.', val))

rawDescription: how to clean or convert unknown characters in an otherwise integer field in python?

description: Clean or convert unknown characters in an otherwise integer field in python


code:
df['number of searches'] = df['number of searches'].astype(int)

(df.groupby(df.keyword.str.split().apply(len))['number of searches']
   .sum()
   .to_frame()
   .reset_index()
   .apply(lambda x: '{0[0]} words: {0[1]}'.format(x), axis=1)
)

rawDescription: How to sum numbers in Dataframe based on length of keywords?

description: Sum numbers in Dataframe based on length of keywords


code:
#Test if each element of `b` is also an element of `a`
def contains(a, b):
    for v in b:
        ok = False
        for u in a:
            if v == u:
                ok = True
                break
        if not ok:
            return False
    return True

rawDescription: How can I use python code which will iterate into two list and will find out whether they matches or not

description: Use python code which will iterate into two list and will find out whether they matches or not


rawDescription: What does the python re.template function do?


code: print(timeit.Timer(..., ...).timeit(n))

rawDescription: Timeit not returning actual time

description: Timeit not returning actual time


code:
df['newdayofweek'] = df['newDate'].apply(lambda x: x.dayofweek)
df

rawDescription: Pandas Column operation with dates

description: Pandas Column operation with dates


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

from ctypes import windll

def main():
    find_window = windll.user32.FindWindowW
    send_message = windll.user32.SendMessageW

    window_name = u""
    window_handle = find_window(0, window_name)

    if window_handle > 0:
        show_menu(handle)
    else:
        print("Window handle not found")

if __name__ == "__main__":
    main()

rawDescription: Display menu bar items of IE using Python


rawDescription: Remove duplicate from list which is used as value in dictionary


rawDescription: Python Nested For Loop Counting Backwards


rawDescription: How do I get a row of a 2d numpy array as 2d array

description: Get a row of a 2d numpy array as 2d array


code:
{u'body, html': u'color: blue',
 u'h1, h2': u'font-size: 1.5em;\ncolor: red',
 u'h3, h4, h5': u'font-size: small'}

rawDescription: python how to parse css file as key value

description: Python how to parse css file as key value


code:
class SortQuerysetMixin(object):
    def get_queryset(self):
        queryset = super(SortQuerysetMixin, self).get_queryset()
        sortmethod = self.request.GET.get('sort', self.default_sort)
        if hasattr(queryset, 'order_by'):
            queryset = queryset.order_by(sortmethod)
        return queryset

rawDescription: Django Coding Style: Should I be using class decorators here?


code:
def gcd(a, b):
    while b != 0:
        (a, b) = (b, a % b)
    return a

rawDescription: Where should print function be used here?


code:
dict( (i+1, my_list[2*i : 2*i+2]) for i in xrange(0, len(my_list)/2) )
#                   ^

rawDescription: Create ranked dict with list comprehension


code:
from urllib.request import urlopen
key = "mykey"
URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey={key}&appver=1.0&pver=3.0&url={url}"

def is_safe(key, url):
    response = urlopen(URL.format(key=key, url=url))
    return response.read().decode("utf8") != 'malware'

print(is_safe(key, "http://www.gumblar.cn/599")) #This should return False

rawDescription: Unable to use google search browsing api lookup in python


rawDescription: Newick tree representation to scipy.cluster.hierarchy linkage matrix format


code:
a = filter_list()
mainlist[1][0][1] = 'L'
a

rawDescription: Python: Get new list without items in other list


code:
import random
[int(random.expovariate(0.2)) for i in range(10)]

rawDescription: how to generate integer inter arrival times using random.expovariate() in python

description: Generate integer inter arrival times using random.expovariate() in python


code:
def f1():
    return {x for x in [True, 1]}

def f2():
    return set([True, 1])
def f3():
    return {True, 1}
print(f1())
print(f2())
print(f3())
import dis

print("f1")
dis.dis(f1)

print("f2")

dis.dis(f2)

print("f3")
dis.dis(f3)

rawDescription: Dict/Set Parsing Order Consistency

description: Dict/Set Parsing Order Consistency


code:
today = datetime.date.today()
start = datetime.date(2007, 1, 31)
period = relativedelta(months=1)

delta = period
while start + delta < today:
    delta += period

next = start + delta

rawDescription: Divide two timespans by eachother in Python/dateutil


code:
z = [x.split(',')[1].strip().strip(')') for x in s.split('),')]
d = defaultdict(list)
for i in z:
   b = i.split('-')
   d[b[1]].append(b[0])
' '.join(' '.join(d[t]) for t in sorted(d.keys(), key=int))

rawDescription: Extracting multiple substring from a string


code:
def f():
    " some doc"
    pass

f.__doc__

rawDescription: custom print statement for python function objects

description: Custom print statement for python function objects


code:
result = funcy.rcompose(
    get_monthly_historical_returns,
    calculate_returns,
    calculate_excess_returns
)('./assets/monthly_historical_returns.csv')

rawDescription: Python 3 control flow in script with lots of steps


code:
import itertools
[next(t) for _, t in itertools.groupby(lot, lambda x: x[0])]

rawDescription: Removing duplicates from a list of tuples based on one of values


code:
import itertools as IT

with open(filename, 'r') as f:
    lines = IT.chain(IT.islice(f, 46), IT.islice(f, 4, None))
    arr = np.genfromtxt(lines)

rawDescription: numpy.loadtxt Skipping multiple rows

description: Numpy.loadtxt Skipping multiple rows


code:
import numpy as np
from StringIO import StringIO   # to create example file
s = """ viola.jpg  0.81 1.0693461723  100
        viola.jpg  0.44 1.31469086921  18
        viola.jpg  0.8  3.92096084523  73
        vlasta.jpg 0.88 1.36559123399 110
        vlasta.jpg 0.88 1.88126493001  45
        vlasta.jpg 0.76 1.0510328514   88"""
f = StringIO(s) # creates example file with content above
a = np.genfromtxt(f, names = "image, someval, another, someid", dtype=['S12', float, float, int])

rawDescription: Calculate mean of elements in array with same "identifier"


code:
import Tkinter as tk
import re

def timeclock():
    result = re.match('Month: (\d+), Year: (\d+)', clock['text'])
    m, y = int(result.group(1)), int(result.group(2))
    if m < 12:
        m += 1
        clock.configure(text = "Month: "+str(m)+", Year: "+str(y))
    else:
        m = 1
        y += 1
        clock.configure(text = "Month: "+str(m)+", Year: "+str(y))
    root.after(100, timeclock)

def reset():
    m = 1
    y = 0
    clock.configure(text = "Month: "+str(m)+", Year: "+str(y))

root = tk.Tk()
m = 1
y = 0
clock = tk.Label(root, text="Month: "+str(m)+", Year: "+str(y))
clock.pack()
button = tk.Button(root, text='Reset clock', command=reset)
button.pack()
root.after(100, timeclock)
root.mainloop()

rawDescription: Month/Year clock ingame stopping the rest of my game


code: df.index.name = None

rawDescription: Manually constructing dataframe from transposed data


rawDescription: Pandas (Python) reading and working on Java BigInteger/ large numbers


rawDescription: Nested float arrays in Python

description: Nested float arrays in Python


code:
def saving_res_pandas():
    global df_res, df_max_res
    df_res = df_res.append({'Ticker':ticker,'Strategy':strategy, 'ROI':stratROI,}, ignore_index = True)

    return df_res

rawDescription: Save vars pr iteration to df and when done save df to csv


code:
def has_repeats(L):
    if len(L) <= 1:
        return False
    if L[0] == L[1]:
        return True
    if has_repeats([L[0]] + L[2:]):
        return True
    if has_repeats(L[1:]):
        return True
    return False

rawDescription: Python Recursively check for repeats

description: Python Recursively check for repeats


code:
import re
p = re.compile(r'\s*((?:(?:Mr|Dr|Ms|Jr|Sr)\.|\.(?!\s+[A-Z0-9])|[^.!?])*[.?!]|[^.!?]+)')
test_str = "Mr. Smith bought cheapsite.com for 1.5 million dollars i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't.23 is the ish. My name is! Why wouldn't you... this is.\nAndrew"
print(p.findall(test_str))

rawDescription: How do I delimit my input by this capture group?

description: Delimit my input by this capture group


code:
def checkconnection(widget, ip):
    while True:
        self.response = os.system("ping -c 1 -W 10 " + self.ip + " > /dev/null 2> /dev/null")
        if self.response==0:
            widget.config(text="connected", bg='green')
        else:
            widget.config(text="no connection", bg='red')
        time.sleep(1)

th = threading.Thread(target=checkconnection, args=(labelobj, ip))
th.start()

rawDescription: Is this a valid way to subclass a python thread to accept a variable update?


rawDescription: Reading data separated by colon per line in Python


code:
from PySide import QtCore, QtGui
from mainwindow import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow.setupUi(self)

rawDescription: How to import mainwindow (.ui file) using PySide

description: Import mainwindow (.ui file) using PySide


code:
import win32com.client
import win32api
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
shell.SendKeys("1{+}2{=}^C")
win32api.Sleep(500)
import win32clipboard
import win32con
win32clipboard.OpenClipboard()
r = win32clipboard.GetClipboardData(win32con.CF_TEXT).rstrip('\x00')
win32clipboard.CloseClipboard()
print(r)

rawDescription: Get result from Calculator with WScript.Shell


code:
q = (Photo.query
     .filter(Photo.tags.any(Tag.id == 1))
     .filter(Photo.tags.any(Tag.id == 2))
     )

rawDescription: Flask-SQLAlchemy: multiple filters through one relation


code:
df1
df1.resample("W", how="size")

rawDescription: Python Pandas, groupby() and sum() values without column values


code: threading.Thread(target = shutdown, args = (5,)).start()

rawDescription: Python thread holds up the rest of the script


code: wrapper.flag = False

rawDescription: Changing values in decorator for nested functions


rawDescription: Group spark dataframe by date

description: Group spark dataframe by date


code:
start_date = '07_Nov_2011'
end_date = '10_Jan_2012'

first = datetime.datetime.strptime(start_date, '%d_%b_%Y')
last = datetime.datetime.strptime(end_date, '%d_%b_%Y')
for i in xrange((last-first).days):
    print (first+datetime.timedelta(i)).strftime('%d_%b_%Y')

rawDescription: How to get the intermediate dates given the start date and end date?

description: Get the intermediate dates given the start date and end date


rawDescription: How to find Term frequency of a particular sets of tags in a document

description: Find Term frequency of a particular sets of tags in a document


code:
if len(problem) == len(solution):
    for p_ch, s_ch in zip(problem, solution):
        if p_ch == "#":  # wildcard
            continue  # so we skip testing this character
        if p_ch != s_ch:
            return False  # This logic works now that we're skipping testing the "#"
    else:  # if we fall off the bottom here
        return True  # then it must be equal
else:
    return False

rawDescription: Comparing similarity of two strings in Python


rawDescription: How to find and select a table in html code with xpath

description: Find and select a table in html code with xpath


code:
class OrExpression:
    def __init__(self, left, right):
        self.left = left
        self.right = right

class EqualsExpression:
    def __init__(self, left, right):
        self.left = left
        self.right = right

class Literal:
    def __init__(self, value):
        self.value = value

class Variable:
    def __init__(self, name):
        self.name = name

rawDescription: Create python functions from expression trees


code:
img = cv2.imread('/Users/anmoluppal/Desktop/cAMDX.jpg')

img_thresholded = cv2.inRange(img, (60, 60, 60), (140, 140, 140))

rawDescription: How to detect bullet holes on the target using python

description: Detect bullet holes on the target using python


code:
import numpy as np

hits = np.array([100, 500, 300, 800, 900])

def predict(hits, weights):
    return np.average(hits[-len(weights) :], weights=weights)

rawDescription: How to use scikit-learn to predict the rate of change in a site's hit counts

description: Use scikit-learn to predict the rate of change in a site's hit counts


code:
l = [1, 1, 2, 3]
inds, unq = [],[]
seen = set()
for i, ele in enumerate(l):
    if ele not in seen:
        inds.append(i)
        unq.append(ele)
    seen.add(ele)

rawDescription: Remove duplicates in python list but remember the index


code:
result = root.xpath("//tag[1]/*[starts-with(local-name(), 'TEXT')]")
assert(' '.join(e.text for e in result) == 'one two three')

rawDescription: lxml find tags by regex

description: Lxml find tags by regex


code:
class ArticleYearArchiveView(YearArchiveView):
    model = Article
    paginate_by = 100
    context_object_name = 'article_list'
    date_field = 'date'
    allow_empty = True

rawDescription: Django Paginate by Year

description: Django Paginate by Year


code:
res = left_a.loc[:, left_a.columns.union(right_a.columns)]
res.update(right_a)
res

rawDescription: pandas left join and update existing column

description: Pandas left join and update existing column


code: x / abs(maximum) * scale

rawDescription: re-scaling the values between given maximum and minimum, where max is positive and min is negative

description: Re-scaling the values between given maximum and minimum, where max is positive and min is negative


rawDescription: Creating a tuple with n entries for n lists


code:
nonSortedNonFiltered
sortedNonFiltered
listOfValues
sortedNonFiltered[:,np.in1d(sortedNonFiltered[0],listOfValues)]

rawDescription: Filter a 2D numpy array from an array of values


code: {{url_for('newRestaurant', restaurant_id = restaurant_id)}}

rawDescription: Flask - UndefinedError: 'restaurant_id' is undefined


code:
instances = []

for _ in range(10):
    image = pygame.image.load("image.png").convert()
    image_rect = image.get_rect()
    image_rect.x = random.randint(10,700)
    image_rect.y = random.randint(10,500)
    screen.blit(image, image_rect)
    instances.append( (image, image_rect) )

rawDescription: How to create many instances with same attributes in pygame

description: Create many instances with same attributes in pygame


code:
from ctypes import c_int32, c_uint32, Structure, Union

class _bits(Structure):
    _fields_ = [
        ("odd", c_uint32, 1),
        ("half", c_uint32, 31),
    ]

class Int(Union):
    _fields_ = [
        ("bits", _bits),
        ("number", c_uint32),
    ]

a = Int(number=12345)
a.bits.odd, a.bits.half

rawDescription: python packet sniffer using raw socket

description: Python packet sniffer using raw socket


code:
super_threshold_indices = a > thresh
a[super_threshold_indices] = 0

rawDescription: Set numpy array elements to zero if they are below a specific threshold


rawDescription: Float to String Round-Trip Test

description: Float to String Round-Trip Test


rawDescription: understanding functools.wraps

description: Understanding functools.wraps


rawDescription: How to require login for django generic views?

description: Require login for django generic views


code: Area = (right - left) * (top - bottom);

rawDescription: How to make rect from the intersection of two?

description: Make rect from the intersection of two


code:
x = '"2","black,white","more","stuff"'
x
x.split(',"')
[y.strip('"') for y in x.split(',"')]

rawDescription: Python Split With Delimiter In Field Value


code:
for day in days:
    total_campaigns[day] = Email.objects.filter(day_of_week=day).count()
    # recipients
    total_recipients[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('recipients')).get('recipients__sum', 0.00)
    # unsubscribes
    total_unsubscribes[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('unsubscribes')).get('unsubscribes__sum', 0.00)
    # bounces
    total_bounces[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('bounces')).get('bounces__sum', 0.00)
    # open
    total_open[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('open')).get('open__sum', 0.00)
    # clicks
    total_clicks[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('clicks')).get('clicks__sum', 0.00)

rawDescription: Nesting multiple 'for' loops

description: Nesting multiple 'for' loops


code:
from urllib.parse import urlparse # in 2.x it's from urlparse
url = 'wss://domain.tld'
bits = urllib.parse.urlparse(url)
netloc = bits.netloc
netloc

rawDescription: Resolve host name of wss protocol with socket?


code: f = open('file.ppm', 'rb') # b: binary mode

rawDescription: How does struct.unpack and struct.pack works?


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

result=[['122', '109', '2343', '220', '19'],
 ['15', '407', '37', '10', '102'],
 ['100', '100', '100', '100', '100'],
 ['113', '25', '19', '31', '112'],
 ['43', '219', '35', '33', '14'],
 ['132', '108', '256', '119', '14'],
 ['22', '48', '352', '51', '438']]

result = np.array(result, dtype=np.int)

fig=plt.figure(figsize=(5, 5), dpi=150)
ax1=fig.add_subplot(111, projection='3d')

xlabels = np.array(['10/11/2013', '10/12/2013', '10/13/2013',
                    '10/14/2013', '10/15/2013'])
xpos = np.arange(xlabels.shape[0])
ylabels = np.array(['A1','C1','G1','M1','M2','M3','P1'])
ypos = np.arange(ylabels.shape[0])

xposM, yposM = np.meshgrid(xpos, ypos, copy=False)

zpos=result
zpos = zpos.ravel()

dx=0.5
dy=0.5
dz=zpos

ax1.w_xaxis.set_ticks(xpos + dx/2.)
ax1.w_xaxis.set_ticklabels(xlabels)

ax1.w_yaxis.set_ticks(ypos + dy/2.)
ax1.w_yaxis.set_ticklabels(ylabels)

values = np.linspace(0.2, 1., xposM.ravel().shape[0])
colors = cm.rainbow(values)
ax1.bar3d(xposM.ravel(), yposM.ravel(), dz*0, dx, dy, dz, color=colors)
plt.show()

rawDescription: Matplotlib 3D Bar chart: axis issue

description: Matplotlib 3D Bar chart: axis issue


code:
class B(A):
  def __init__(self, other):
    # Copy attributes only if other is of good type
    if isintance(other, A):
      self.__dict__  = other.__dict__.copy()
  def hello(self):
    print('Hello, I am an object of type B')

rawDescription: Cast an object to a derived type in Python


code:
import itertools, numpy as np
a = np.array(list(itertools.product((1, 11, 12, 13), repeat=4)))
for arr in a[a.sum(axis=1) == 21]:
    print(arr)

rawDescription: combination of numpy array satisfying condition

description: Combination of numpy array satisfying condition


code:
class Triangle:
    def __init__(self, a, b, c):
        self.__side1 = a
        self.__side2 = b
        self.__side3 = c

    def getPerimeter(self):
        return self.__side1 + self.__side2 + self.__side3

    def __str__(self):
        return "side1 : " + str(self.__side1) + " side2 : " + str(self.__side2) + " side3 : " + str(self.__side3)

def main():
    side1 = input("Enter first side: ")
    side2 = input("Enter second side: ")
    side3 = input("Enter third side: ")
    t1 = Triangle(int(side1), int(side2), int(side3))
    print("The Perimeter of Triangle : ", t1.getPerimeter())
    print(t1)

main()

rawDescription: How to make the input into a parameter in a class for Python

description: Make the input into a parameter in a class for Python


code: df = df1.append(df2)

rawDescription: Reshaping pandas DataFrame

description: Reshaping pandas DataFrame


code:
class Finalize(object):
    '''
    Class which supports object finalization using weakrefs
    '''
    def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None):
        ...
        if obj is not None:
            self._weakref = weakref.ref(obj, self)

rawDescription: multiprocessing Pool.imap broken?

description: Multiprocessing Pool.imap broken


code:
class WrapExtension(jinja2.ext.Extension):
    tags = set(['wrap'])
    template = None

    def parse(self, parser):
        tag = parser.stream.current.value
        lineno = parser.stream.next().lineno
        args, kwargs = self.parse_args(parser)
        body = parser.parse_statements(['name:end{}'.format(tag)], drop_needle=True)

        return nodes.CallBlock(self.call_method('wrap', args, kwargs), [], [], body).set_lineno(lineno)

    def parse_args(self, parser):
        args = []
        kwargs = []
        require_comma = False

        while parser.stream.current.type != 'block_end':
            if require_comma:
                parser.stream.expect('comma')

            if parser.stream.current.type == 'name' and parser.stream.look().type == 'assign':
                key = parser.stream.current.value
                parser.stream.skip(2)
                value = parser.parse_expression()
                kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))
            else:
                if kwargs:
                    parser.fail('Invalid argument syntax for WrapExtension tag',
                                parser.stream.current.lineno)
                args.append(parser.parse_expression())

            require_comma = True

        return args, kwargs

    @jinja2.contextfunction
    def wrap(self, context, caller, template=None, *args, **kwargs):
        return self.environment.get_template(template or self.template).render(dict(context, content=caller(), **kwargs))

rawDescription: How do you parse and inject additional nodes in a Jinja extension?

description: Parse and inject additional nodes in a Jinja extension


code: temp2 = temp.copy(order='C')

rawDescription: Force numpy array to physically match striding in memory


code:
@register.inclusion_tag("tags/products_list.html")
def all_products():
    return {'product_list': Product.objects.order_by('name') }

rawDescription: Custom django tag returning a list?

description: Custom django tag returning a list


code:
import math
from functools import partial
def euclidean(x1, y1, x2, y2):
    return math.sqrt((x1-x2)**2 + (y1-y2)**2)
euc = partial(euclidean, 20, 30) #beginning coordinates

rawDescription: Find closest location from a list of locations in csv file Python


code:
from collections import Counter
L=['a','b','a','b']
print(Counter(L))
print(Counter(L).items())

rawDescription: Most Efficient way to calculate Frequency of values in a Python list?


code:
pair = pairs.most_common(1) # when using collections.Counter
pair = [p for p, c in pairs.items() if c == 3] # otherwise

rawDescription: extract repeated elements in a list in python

description: Extract repeated elements in a list in python


code: passage = soup.find("div", class_="placeholder").extract()

rawDescription: Beautiful Soup - inserting before extracted portion of parse tree


code:
for key in myDict:
    if key not in myList:
        print(key+"\t"+myDict[key])

rawDescription: Python List Exclusions

description: Python List Exclusions


code:
j = hash % 32
perturb = hash

rawDescription: Why is early return slower than else?

description: Why is early return slower than else


code:
import socket
host = "192.168.0.204" #Device IP
port = 12002
PACKET_SIZE=1024 # how many characters to read at a time
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port)) #connect to the device
while True: #continuously read and handle data
    data = sock.recv(PACKET_SIZE)
    processData(data)

rawDescription: working with NMEA data sent to URL/IP

description: Working with NMEA data sent to URL/IP


code:
J
JTildeIDX
mask = np.arange(J.shape[0])[:,None] >= JTildeIDX
mask
out = (J*mask).sum(0)
out

rawDescription: Cumsum and vectorized slicing

description: Cumsum and vectorized slicing


rawDescription: Using matplotlib how could I plot a histogram with given data in python


code:
test = TailedElement("testel",{"testing":"yes"},tail="Tail Value")
ET.tostring(test)
# b'<testel testing="yes"/>Tail Value'

rawDescription: Adding a tail to lxml.etree.Element upon creation


rawDescription: Convert a hashcode to its binary representation


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

rawDescription: python regex - Dashes match as digits when using re.IGNORECASE

description: Python regex - Dashes match as digits when using re.IGNORECASE


code:
for tag in soup.findAll():
  if tag.name in TAGS_TO_EXTRACT:
    tag.replaceWith(tag.text)
soup

rawDescription: Python filter list to remove certain links from html source code


code:
from MyMeta import MyMeta

class Basic(object):
    __metaclass__ = MyMeta

    def __init__(self):
        self.allInstances.add(self)

    def __del__(self):
        self.allInstances.remove(self)

rawDescription: inheritance of set class attribute in python

description: Inheritance of set class attribute in python


code:
FILE_ATTRIBUTE_ARCHIVE              = 32
FILE_ATTRIBUTE_ATOMIC_WRITE         = 512
FILE_ATTRIBUTE_COMPRESSED           = 2048
FILE_ATTRIBUTE_DEVICE               = 64
FILE_ATTRIBUTE_DIRECTORY            = 16
FILE_ATTRIBUTE_ENCRYPTED            = 16384
FILE_ATTRIBUTE_HIDDEN               = 2
FILE_ATTRIBUTE_NORMAL               = 128
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED  = 8192
FILE_ATTRIBUTE_OFFLINE              = 4096
FILE_ATTRIBUTE_READONLY             = 1
FILE_ATTRIBUTE_REPARSE_POINT        = 1024
FILE_ATTRIBUTE_SPARSE_FILE          = 512
FILE_ATTRIBUTE_SYSTEM               = 4
FILE_ATTRIBUTE_TEMPORARY            = 256
FILE_ATTRIBUTE_VIRTUAL              = 65536
FILE_ATTRIBUTE_XACTION_WRITE        = 1024

rawDescription: python os.listdir() shows protected files

description: Python os.listdir() shows protected files


code:
dic3 = {}
for k in dic1.viewkeys() & dic2.viewkeys():
    dic3[k] = (dic1[k], dic2[k])

rawDescription: Match keys from two dictionaries, and make new dictionary with matched key and two associated values


code: ' OR '.join('Case: {}'.format(i) for i in a)

rawDescription: Python: concatenate string and int in a loop


rawDescription: Python Pandas, Resampling only specific hours


code: plt.xlabel('Wavelength ($\mu$)')

rawDescription: Matplotlib greek symbols differ in show() and savefig()


code:
class NargsTypeChecker(object):
    def __init__(self, types):
        self.types = types
        self.index = 0
    def __repr__(self):
        return self.types[self.index].__name__
    def __call__(self, arg):
        value = self.types[self.index](arg)
        self.index = (self.index + 1) % len(self.types)
        return value

rawDescription: Argparser and complex types

description: Argparser and complex types


rawDescription: Checking for Hex Code Type

description: Checking for Hex Code Type


rawDescription: minimizing a given vector of components with a dataframe

description: Minimizing a given vector of components with a dataframe


code:
from random import uniform
cities = [(uniform(-90, 90), uniform(0, 360)) for _ in range(50000)]
ecef_cities = [geodetic2ecef(lat, lon) for lat, lon in cities]

rawDescription: Python - how to speed up calculation of distances between cities


code:
payments = {
    "jan": 200, "feb":   0, "mar": 150, "apr": 275,
    "may": 275, "jun":  20, "jul": 275, "aug": 186,
    "sep":   0, "oct":  20, "nov": 275, "dec": 200
}

MONTHLY = 275

paid = sum(payments.values())
should_be = MONTHLY * len(payments)

pct = (paid / should_be) * 100.0

print("Customer paid {:0.1f}% of their bill".format(pct))

rawDescription: Python - Script for payment degree

description: Python - Script for payment degree


code:
# Construct a tuple for this row
row_data = tuple(text)
data.append(row_data)

rawDescription: Parsing of table from .docx file

description: Parsing of table from .docx file


code:
class Parent(object):
    def __init__(self, *args, **kwargs):
        print("You've called Parent.__init__")

class Child(Parent):
    def __init__(self, child_arg, *args, **kwargs):
        print("You've called Child.__init__ with child_arg={}".format(child_arg))
        super().__init__(*args, **kwargs)

rawDescription: Pass arguments from a class to another class that inherits from threading.Thread


code:
Hello

Stack

Overflow

rawDescription: refer to specific parameter by object in array?

description: Refer to specific parameter by object in array


code:
project = Project('conf.py')
project.area

rawDescription: Import variables (with evaluation) to class namespace (i.e. self.varName)


code:
def linear(x, m):
    return x.dot(m)

x = np.random.randn(100, 5)
m = np.random.randn(5)

y = linear(x, m)

rawDescription: Better way to create fit functions with changing number of parameters in Python with Scipy curve_fit


rawDescription: Averaging a specific number of rows in DataFrame array


code:
import pandas as pd
df = pd.read_csv('data')
result = df.groupby(['G', 'User'])['C'].value_counts()
result[:] = 1
result = result.groupby(level=['G',-1]).sum()
result = result.unstack()
result = result.fillna(0)
result['nU'] = result.sum(axis=1)
result = result[['nU', 'ar', 'es']]

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
class MyDict(dict):
    def __getitem__(self, key):
        if key == 'c':
            return self['a'] + self['b']
        return super(MyDict, self).__getitem__(key)

my_dict = MyDict()
my_dict['a'] = 1
my_dict['b'] = 2
assert my_dict['c'] == 3
my_dict['b'] = 3
assert my_dict['c'] == 4
assert isinstance(my_dict, dict)

rawDescription: derived value in a python map

description: Derived value in a python map


code: #!/usr/bin/env python2.6

rawDescription: Python subprocess: How to run a python script using a different intepreter than the main thread


code:
import timeit
import random
A = [chr(random.randrange(33, 127)) for _ in range(1000)]
choice = [random.randrange(2) for _ in range(1000)]
def with_mult(A, choice):
    return ''.join([c * i for c, i in zip(A, choice)])

def with_compress(A, choice):
    return ''.join(compress(A, choice))

timeit.timeit('f(A, choice)', 'from __main__ import A, choice, with_mult as f', number=10000)
timeit.timeit('f(A, choice)', 'from __main__ import A, choice, with_compress as f', number=10000)

rawDescription: Python multiplication of two list

description: Python multiplication of two list


code:
from nose.plugins import Plugin
import doctest

class CustomName(Plugin):
    def describeTest(self, test):
        if isinstance(test, doctest.DocTestCase):
            return "Doctest: %s" % test
        else:
            return "Unittest: %s" % test

rawDescription: Print the test type in Python Nose

description: Print the test type in Python Nose


code:
import pylab
import numpy as np

x = [[1,2],[2,1]]

fig = pylab.figure()

axes_list = []
table_list = []

for i in xrange(5):
    axes_list.append( fig.add_subplot(2,3,i+1) )
    axes_list[i].set_xticks([])
    axes_list[i].set_yticks([])
    axes_list[i].set_frame_on(False)
    table_list.append(pylab.table(cellText=x,colLabels = ['col']*2,rowLabels=['row']*2,colWidths = [0.3]*2,loc='center'))

pylab.savefig('my_fig.pdf')
pylab.show()

rawDescription: Subplot of tables in pylab

description: Subplot of tables in pylab


code:
class Enumerate(object):
  def __init__(self, names):
    for number, name in enumerate(names.split()):
      setattr(self, name, number)

rawDescription: Is there a better way to get a named series of constants (enumeration) in Python?


code:
dct = {'a':0, 'b':1}
dct.get('a')
dct.get('b')
dct.get('c')  # Returns None with non-existent keys
bool(dct.get('a'))  # 0 evaluates to False
bool(dct.get('b'))  # 1 evaluates to True
bool(dct.get('c'))  # The None returned by dict.get evaluates to False

rawDescription: Testing presence and non-emptyness of dict element


code: dists[(dists >= r) & (dists <= r + dr)]

rawDescription: Numpy where function multiple conditions


code:
def __repr__(self):
    return [x for x in self].__repr__()

rawDescription: Print class that uses __getitem__ in python as list


rawDescription: Skipping an unknown number of words in python


code:
b = driver.find_element_by_xpath("//a/following-sibling::b")
print(b.text)

rawDescription: How to select all tags with selenium and python

description: Select all tags with selenium and python


code:
from collections import defaultdict

merged = defaultdict(lambda: defaultdict(list))
for d in list_of_dicts:
    for k in d:
        for competition, medal in d[k].iteritems():
            merged[k][competition].append(medal)

rawDescription: How would I merged nested dictionaries in a list in python?


code:
from collections import Counter
import string
words = Counter(word.lower().strip(string.punctuation) for word in values)

rawDescription: Count number of occurences of specific words in Excel sheet using python & xlrd


code: pButton = Button(root, text="Play", command="playButton").grid(row=1)

rawDescription: 'NoneType' object has no attribute 'config'


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

from __future__ import with_statement
import SimpleHTTPServer, BaseHTTPServer
import os
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

class SourceViewer(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        path = os.path.join(os.getcwdu(), self.path[1:])
        if os.path.exists(path) and path.endswith(u'.py'):
            with open(path) as file:
                code = file.read()
                hl = highlight(code, PythonLexer(), HtmlFormatter(noclasses=True, linenos=u'table'))
                self.send_response(200)
                self.end_headers()
                self.wfile.write(hl)
                return
        else:
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

if __name__ == u"__main__":
    server = BaseHTTPServer.HTTPServer((u'localhost', 8080), SourceViewer)
    server.serve_forever()

rawDescription: pydoc-like program to browse content/code of Python files in a browser?

description: Pydoc-like program to browse content/code of Python files in a browser


code: a = sps.csr_matrix((a.data, a.indices, a.indptr), shape=(10000, 10020))

rawDescription: Adding a column of zeroes to a csr_matrix


code:
isdark = True

if isdark:
    print('bt')
else:
     print('dasd')

rawDescription: Python3 defining room conditions

description: Python3 defining room conditions


code: output = inputstr.rsplit('.', 1)[0]

rawDescription: Remove the last part of string separated with dot in Python


code:
lst = ['foo', 'bar', 'foo bar']
lst2 = []

for l in lst:
    if ' ' in l:
        lst2.append(repr(l))

rawDescription: String inside a string

description: String inside a string


code: log = os.popen("log.sh").readlines()

rawDescription: Finding a line in a Python string (not file)


code:
for i, (x,y) in enumerate(coords):
    # make text label: 'A', 'B', 'C', ...
    label = chr(i+65)
    pyplot.text(x, y, label, fontsize=20)

rawDescription: How to use pyplot.text() in a cycle to print different string on plot after each cycle

description: Use pyplot.text() in a cycle to print different string on plot after each cycle


code:
import re
spacereplace = re.compile(r'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I)
q = "a b (c or d)"
spacereplace.sub(" and ", q)

rawDescription: Lookarounds in python

description: Lookarounds in python


code: [x for t in zip(a, reversed(a)) for x in t][:len(a)]

rawDescription: Python standard library function for rearranging a list


rawDescription: Hiding axis text in matplotlib plots

description: Hiding axis text in matplotlib plots


code:
def circle(x, y, ans=None):
    if ans is None:
        ans = random.randint(1, 100)
    ...
    tr.write(ans, font=("Arial", 20))
    return ans

C = [None] * 3
C[1] = circle(150, 245)
C[2] = circle(245, 150)

# C is now [None, *C1's random number*, *C2's random number*]

rawDescription: Get a parameter

description: Get a parameter


rawDescription: Finding groups of increasing numbers in a list


rawDescription: Pass multiple arguments to a function in tkinter


code: sum(map(len, d['childs'].itervalues()))

rawDescription: Count the number of items from a dictionary inside another dictionary in Python


code:
from PIL import Image

im = Image.open("cat2.png")
px=im.load()
im2 = im.copy()
px2=im2.load()
sx,sy=im.size
def turnpixel(Nix,Niy):
    for ix in range(sx):
        for iy in range(sy):
            r2=(Nix-ix)**2+(Niy-iy)**2
            if r2<5:
                if sum(px[ix,iy])>100: # rgb sum>100 is considered ON.
                    px2[Nix,Niy]=(255,255,255)
                    return
                    # we turned a pixel on, so we are done with it.

for Nix in range(sx):
    for Niy in range(sy):
        px2[Nix,Niy]=(0,0,0)
        turnpixel(Nix,Niy)

im.show()
im2.show()

rawDescription: Simple "blurring" of an array representing an image in python from first principles


code:
data = in_df
data.rename(columns=in_df.iloc[2,:], inplace=True) # rename your columns
data = data[5:]                    # you want just the data body
data = data.reset_index(drop = True)  # reindex

#DO WHATEVER WITH DATA

rawDescription: Pandas - read_table read selected lines

description: Pandas - read_table read selected lines


code:
s = 'string(15) "Ivor Abeysekera"'
temp = s.split('"')[1]
# temp is 'Ivor Abeysekera'

rawDescription: Splitting or stripping a variable number of characters from a line of text in Python?


code:
from django.db.models import Count
articles = Article.objects.annotate(num_likes=Count('like'))

rawDescription: Efficient counting of related objects in Django


code:
class Cell(int):
    def __init__(self, value, color='white'):
        super().__init__(value)
        self.color = color

mat = [[1,2,4,5], [2,3,4,1], [4,1,1,2], [1,1,1,0]]
mat = [[Cell(i) for i in l] for l in mat]

rawDescription: I want to have a 2D list with value and color attributes in Python


code:
import re
string = '192.00.00.00 - WWW.WEBSITE.COM GET /random/url/link'
re.search('-\s+(.+?)\s+GET', string).group(1)

rawDescription: Python regular expression to get URL

description: Python regular expression to get URL


code:
import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []

for row in matrix:
    tempRow = restrictedNumbers #first add the restricted numbers since they must appear once
    while len(tempRow) < len(row): #keep adding numbers from unrestricted till lengths are equal
        tempRow.append(random.choice(unrestrictedNumbers))
    random.shuffle(tempRow)
    newMatrix.append(tempRow[:]) #finally add the shuffled row to newMatrix
pprint.pprint(newMatrix)

rawDescription: randomly fill 2d matrix with conditions

description: Randomly fill 2d matrix with conditions


code:
x = xtp - mu  # move this out of the loop
ddot = [i.dot(inv).dot(i) for i in x]
temp = const * np.exp(-0.5 * ddot)

rawDescription: How to write this numpy code in vectorized form?

description: Write this numpy code in vectorized form


code:
class LoginForm(Html5Mixin, forms.Form):
    """
    username: phone or email
    """
    username = forms.CharField(label='phone or email')
    password = forms.CharField(label='password',
                               widget=forms.PasswordInput(render_value=False))

    def clean(self):
        """
        Authenticate the given phone/email and password. If the fields
        are valid, store the authenticated user for returning via save().
        """
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = None
        if validate_phone(username):
            user = authenticate(phone=username, password=password)
        elif validate_email(username):
            user = authenticate(email=username, password=password)
        if user:
            self._user = user
            return self.cleaned_data
        else:
            raise forms.ValidationError('please enter valid account and password')

    def save(self):
        """
        Just return the authenticated user - used for logging in.
        """
        return getattr(self, '_user', None)

rawDescription: How to make custom authentication not based on User model

description: Make custom authentication not based on User model


rawDescription: Adding column In table with Python

description: Adding column In table with Python


rawDescription: Sleekxmpp Managing Stanzas

description: Sleekxmpp Managing Stanzas


code:
import inspect

def get_identifiers(obj):
    source = inspect.getsource(obj)
    tree = ast.parse(source)
    order = ClassOrder()
    order.visit(tree)
    return order.identifiers

rawDescription: How to read order of declared members in Python class with use reflection or parsing (metaclass replace is forbidden)?

description: Read order of declared members in Python class with use reflection or parsing (metaclass replace is forbidden)


code: ['#include <stdlib.h>', '#include "mylib.h"']

rawDescription: Python regex matching pair of quotes or "<>"


code:
import threading
from subprocess import call
import os
import time
import RPi.GPIO as GPIO

PIR = 9 # data pin of PIR sensor (in)
LED = 7 # positive pin of LED (out)
SOUND = '/home/pi/events/sounds/Hello.wav' # reaction sound

COUNTLIMIT = 160
countThread = None
WATCHTIME = 600 #Run for 10 minutes

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LED,GPIO.OUT)

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

class CounterThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.count = 0
        self.start()

    def run(self):
        call(['/home/pi/bin/kitchenlights.sh', '-1'])     # turn light on
        while self.count < COUNTLIMIT:
            time.sleep(0.1)
            self.count += 0.1

        call(['/home/pi/bin/kitchenlights.sh', '-0'])
        threadKiller()
        return

    def newSig(self):
        self.count = 0

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

def my_callback(channel):
    '''function which gets called when motion is reported (sensor includes own delay-until-hot again and sensibility settings'''

    global countThread

    try:
        countThread.newSig()
    except:
        countThread = CounterThread()

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

def threadKiller():
    global countThread
    countThread = None

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

def main():
    GPIO.add_event_detect(PIR, GPIO.RISING,callback=my_callback,bouncetime=100)  # add rising edge detection on a channel
    t = 0
    while t < WATCHTIME:
        t += 0.1
        time.sleep(0.1)

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

if __name__ == "__main__": main()

rawDescription: How do I schedule a one-time script to run x minutes from now? (alternative for 'at')

description: Schedule a one-time script to run x minutes from now? (alternative for 'at')


code:
from collections import namedtuple
Node = namedtuple('Node', 'val left right')
Node.__new__.__defaults__ = (None,) * len(Node._fields)
Node()

rawDescription: Named tuple and optional keyword arguments


code: lazy_f = lazy(f, tuple)

rawDescription: How do I use django @lazy decorator?

description: Use django @lazy decorator


code:
class requests(object):
    @my_function
    def post(self, *args):
        pass

rawDescription: I want to decorate a method in a class but without editing class.py -- details inside


rawDescription: Sparksql filtering (selecting with where clause) with multiple conditions


code:
regex = re.compile('TOTAL:.*?C2\n', re.DOTALL)
regex.sub("XXX", content)

rawDescription: dealing with \n characters at end of multiline string in python

description: Dealing with \n characters at end of multiline string in python


code: matrix = transpose_matrix(matrix)

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


code: area_result = cleanup(area_result).split('>')[3].replace(';', '>')

rawDescription: python strip function not working properly

description: Python strip function not working properly


code: lambda x: x > 15

rawDescription: Python: Search a text file and then output specific data


rawDescription: making a flat list out of a list of lists where the elements are strings

description: Making a flat list out of a list of lists where the elements are strings


rawDescription: Why I can't read anything with File.open in python when I open the file to write first?


code:
try:
    for ln, k in enumerate(map(float, reductions)):
        with open(filename, "r") as f:
            for key, group in groupby(f, key=getkey):
                outfile[ln].writelines(choose_random(group, fraction=k))

finally:
    for f in outfile:
        f.close()

rawDescription: Python File Reduction - part 2

description: Python File Reduction - part 2


code:
with open('rosalind.txt', 'r') as ros:
    rosa = {line[1:].split(' ')[0]:my_function(line.split(' ')[1].strip()) for line in ros if line.strip()}
top_key = max(rosa, key=rosa.get)
print(top_key, rosa.get(top_key))

rawDescription: Wit's end with file to dict

description: Wit's end with file to dict


code:
_, idx = tree.query((3, 3), k=2)
points_ref[idx]

rawDescription: Scipy cKDTree nearest neighbor including zeros distance


code:
new = np.empty(shape = data.shape[0]-1)

for i in range(0, new.shape[0]):
    new[i] = np.abs(data[i+1] - data[i])

rawDescription: Using Python to create a new Numpy array from an existing one


rawDescription: String formatting : Replace "%0 %1 %2" with tuple with 0,1,2 indexes


rawDescription: Splitting up a list into different length parts under special condition


code:
html_tags = [{i:['@{}="{}"'.format(*x) for x in j] if i=='attribs' else j for i,j in html_tags[0].items()}]
html_tags

rawDescription: How to do two-level nested map

description: Do two-level nested map


code:
def test_say_hello():
    output = say_hello(lambda: "test")
    assert(output == "Hello test")

rawDescription: Supply inputs to Python unit tests

description: Supply inputs to Python unit tests


rawDescription: Fastest way to filter a numpy array by a set of values


code:
counts = np.sum(binary_image==0, axis=1)

plt.plot(counts)

rawDescription: Plot number of black pixels per row using python


rawDescription: Return the closest value in a list

description: Return the closest value in a list


code:
wekjb
success

rawDescription: Re.match() returns always none

description: Re.match() returns always none


code: my_list = [ self.labelVariable, self.entryVariable ]

rawDescription: python to add variables to list by identifying from a line

description: Python to add variables to list by identifying from a line


code: self.Scraper.GetSubUrls(url, lambda url: self.UI.addLink(url[0], url[1]))

rawDescription: Using an anonymous function in Python

description: Using an anonymous function in Python


code:
ar = [2, 3, 45, 5556, 6, 'empty', 4]
new_ar = [0 if x == 'empty' else x for x in ar]

rawDescription: Normalize Array in Python

description: Normalize Array in Python


code: device = serial.Serial(get_serial_port(), baudrate=9600, timeout=3)

rawDescription: How to get arduino port with python

description: Get arduino port with python


code:
from tkinter import *

def on_click():
    print("on_click was called!")

root = Tk()

# The callback will pass in the Event variable,
# but we won't send it to `on_click`
root.bind("<Return>", lambda event: on_click())
b = Button(root, text="Click Me", command=frob)
b.pack()

root.mainloop()

rawDescription: Call the same function when clicking the Button and pressing enter


code:
alist in alist
any(i is alist for i in alist)

rawDescription: What does Python mean by printing "[...]" for an object reference?


code: phone_number = int(phone_number)

rawDescription: Convert List to Int with Python

description: Convert List to Int with Python


code:
input_seq = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]]
i = 1
o = [1 if idx == i else 0 for idx, l in enumerate(input_seq) for _ in l]

rawDescription: Python map a value to each i-th sublist's element


code:
fr = Frame(boot)
fr.pack()
but=Button(boot, text= ...)

rawDescription: Two related windows not displaying properly


rawDescription: Scrapping and string-formatting issue : one time scrap with '' another time with ""


code:
groups = db.Table('groups',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('group_id', db.Integer, db.ForeignKey('group.id'))
)

group_to_group = db.Table('group_to_group',
    db.Column('parent_id', db.Integer, db.ForeignKey('group.id'), primary_key=True),
    db.Column('child_id', db.Integer, db.ForeignKey('group.id'), primary_key=True)
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    email = db.Column(db.String(120), unique=True)
    display_name = db.Column(db.String(120))
    created_at = db.Column(db.DateTime)
    last_login = db.Column(db.DateTime, default=db.func.now())

    def __init__(self, name, email, display_name):
        self.name = name
        self.email = email
        self.display_name = display_name
        self.created_at = datetime.datetime.now()
        self.order_by = User.display_name

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return self.display_name

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    users = db.relationship('User',
                            secondary=groups,
                            backref=db.backref('groups',
                                               lazy='dynamic',
                                               order_by=name
                            )
    )
    parents = db.relationship('Group',
                              secondary=group_to_group,
                              primaryjoin=id==group_to_group.c.parent_id,
                              secondaryjoin=id==group_to_group.c.child_id,
                              backref="children",
                              remote_side=[group_to_group.c.parent_id])

    def __repr__(self):
        return self.name

rawDescription: python group/user management packages

description: Python group/user management packages


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from extra.items import *

class extraSpider(CrawlSpider):

    name = 'extraSpider'
    allowed_domains = ['extratorrent.cc']
    start_urls = ['http://www.extratorrent.cc/torrent']
    rules = [Rule(LinkExtractor(allow=['/\d+/\S+']), 'parse_torrent')]

    def parse_torrent(self, response):
        url = response.url
        name = response.xpath(
            "//h1/b/text()").extract()
        name = name[0].strip() if name else 'N/A'
        description = response.xpath(
            '//div[@class="borderdark"]//text()').extract()
        description = ' '.join(
            ' '.join(description).split()) if description else 'N/A'
        size = response.xpath(
            '//td[@class="tabledata1" and contains(text(), "Total Size:")]/following-sibling::td[@class="tabledata0" and position()=1]/text()').extract()
        size = size[0].strip().replace(u'\xa0', ' ') if size else 'N/A'
        torrent = TorrentItem(
            url=url,
            name=name,
            description=description,
            size=size)
        yield torrent

rawDescription: Crawling extratorrent.cc using Scrapy

description: Crawling extratorrent.cc using Scrapy


rawDescription: Removing word and replacing character in a column of strings


code:
def rle(input_string):
            """ takes input as string and checks repeating bit
                return repeating bit with their counts.
            """
            count = 1
            prev = ''
            lst = []
            for character in input_string:
                if character != prev:
                    if prev:
                        entry = (prev,count)
                        lst.append(entry)
                        #print lst
                    count = 1
                    prev = character
                else:
                    count += 1
            else:
                entry = (character,count)
                lst.append(entry)

            return lst

rawDescription: Image compression by def compress(S) function using run-length codig


code:
rise_p['ts'] = (rise_p.time / 100).astype('int')

ts_grouped = rise_p.groupby('ts')

...

rawDescription: Convert float Series into an integer Series in pandas


rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


code:
class ValueAttributeExtension(AttributeExtension):
  ...

class Child(Base):
  ...
  value = ColumnProperty(Column(Integer, nullable=False, default=0),
                         extension=ValueAttributeExtension())

rawDescription: Updating a de-normalized attribute automatically with an AttributeExtension


code:
entries = [(5, 'foo'), (6, 'eggs'), (7, 'spam'), (6, 'bar')]
sorted(entries, reverse=True)
sorted(entries, key=lambda t: (-t[0], t[1]))

rawDescription: How to sort this text file in descending order in python?

description: Sort this text file in descending order in python


code:
class MainPageLocators(object):
    """A class for main page locators. All main page locators should come here"""
    GO_BUTTON = (By.ID, 'submit')

rawDescription: Selenium Webdriver Python page object MainPageLocators class why does it use an asterisk infront of the class name


code:
mydict={}
mydict.update(mydict).update(mydict) # Throws error 'NoneType' object has no attribute 'update'

rawDescription: Return statement in method that modifies in-place


code:
int_array[:] = [3, 4, 1, 2]
double_array[:]

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


rawDescription: Django slice template tag not working with negative indices


rawDescription: Tuple Numpy Data Type

description: Tuple Numpy Data Type


code:
import xml.etree.ElementTree as ET
s="""<root>      <key name="modifiable">1</key>
      <key name="sharing">global</key>
      <key name="app">search</key>
      <key name="can_write">1</key>
      <key name="ttl">600</key></root>"""
root = ET.fromstring(s)
root.find('.//key[@name="app"]').text

rawDescription: Python XML Parsing: Returning a specific Attribute Tag Value


code:
define() & app_initialized.NotebookApp
define() & notebook_loaded.Notebook
require() & notebook_loaded.Notebook

rawDescription: IPython 3 to Jupyter migration, custom.js and events


code: maxlist = max(myDict[item] for item in myDict.keys())

rawDescription: How to pass a dynamic number of arguments to a function?

description: Pass a dynamic number of arguments to a function


code:
from itertools import chain
r = Counter(l2) - Counter(l1)
list(chain(*[p*[k] for k,p in r.items()]))

rawDescription: Python list difference with number of ocurrences


code:
def zero_fill_right_shit(data, bits):
    return (data & 0xffffffff) >> bits

rawDescription: Special JS operators in python

description: Special JS operators in python


code:
## @package pyexample
#  Documentation for this module.
#
#  More details.

## Documentation for a function.
#
#  More details.
def func():
    pass

rawDescription: Can I document Python code with doxygen (and does it make sense)?

description: Document Python code with doxygen (and does it make sense)


code:
time = getColumn("filename",0)
volt = getColumn("filaname",1)

plt.figure("Time/Volt")
plt.xlabel("Time(ms)")
plt.ylabel("Volt(mV)")
plt.plot(time,volt)

rawDescription: Python: Reading CSV file and plotting a scatter


code: A[:] = [None if item == 1 else item for item in A]

rawDescription: Delete elements in a list and retaining the size of a list in Python?


code:
def fct_in_extern_module(where):
    where['A'] = 42

rawDescription: exec a global variable from an extern module

description: Exec a global variable from an extern module


code:
def binoMixtureDrawer(minimum,maximum):
    global binoInitiated
    global centers
    sam=binoMixture(minimum,maximum,50000)
    # this create the kernel, given an array it will estimate the probability over that values
    kde = gaussian_kde( sam )
    # these are the values over wich your kernel will be evaluated
    dist_space = linspace( min(sam), max(sam), 500 )
    # plot the results
    fig.plot( dist_space, kde(dist_space),'g')

rawDescription: Generating a mixture of binomial distributions


rawDescription: Flex: detecting user idle?

description: Flex: detecting user idle


code: set(i for i in a if a.count(i)>1)

rawDescription: Testing whether a string has repeated characters


code:
for i,url in enumerate(urls):
    try:
        image = urllib.URLopener()
        image.retrieve(url, filepaths[i])
    except ValueError:
        pass

rawDescription: Urllib and saving multiple urls to different filenames


code:
import myWrapper
import cv2

def myFunct():
    cap = cv2.VideoCapture(0)
    while(1):
        ret,frame = cap.read()
        myWrapper.fromPython(frame)

rawDescription: Call C++ opencv functions from Python ( Send a cv :: Mat to C++ dll which is using opencv )


code:
def checkfile(code):
    found = None # This seems redundant?
    with open('products.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for line in reader:
            print(line) # To see what you're getting
            if code == line[0]:
                print("We found your product ", code)
                return line
        '''
        EDIT: Outside of the question, but the below probably doesn't do what you expect
        data = code, "is not found. Please try again"
        print (data)
        '''
        # Use this instead
        print(code, "is not found. Please try again")

rawDescription: Finding A Total Cost

description: Finding A Total Cost


rawDescription: change character set for tempfile.NamedTemporaryFile

description: Change character set for tempfile.NamedTemporaryFile


code: re.sub(r'[A-Z]\S+\s*', ' #NE# ', the_rest)

rawDescription: How to Include accented words in regex

description: Include accented words in regex


code:
xmlfile = open('Output.xml', 'wb')
xmlfile.write(response_text)
xmlfile.close()

rawDescription: Write Python NTLM XML response to local XML file


code:
from collections import Counter
with open('alice.txt') as file:  # with can auto close the file
    wordcount = Counter(file.read().split())

for k, v in wordcount.most_common(5):
    print(k, v)

rawDescription: Python word count program from txt file

description: Python word count program from txt file


code:
barRef = White(' \t') + Keyword('bar') + nestedExpr()('barargs') + ','
def skipEndingIn85(tokens):
    if tokens.barargs[0][-1].endswith('85'):
        raise ParseException('ends with 85, skipping...')
barRef.setParseAction(skipEndingIn85)

rawDescription: Removing/replacing multi-line code sections with python


rawDescription: Writing contents to json file which already has headers


code:
import textwrap
import pprint
import itertools

mystr=r"""
First line.
Second line.
The third line is a very long line, which I would like to somehow wrap; wrap at 80 characters - or less, or more! ... can it really be done ??"""

wrapper = textwrap.TextWrapper(width = 80)
mylist = [wrapper.wrap(i) for i in mystr.split('\n') if i != '']
mylist = list(itertools.chain.from_iterable(mylist))

pprint.pprint(mylist)

rawDescription: Wrap multiline string (preserving existing linebreaks) in Python?


rawDescription: Frequency of common elements between lists in python 2.7


code:
from django.contrib.auth.models import User
from django.contrib.auth import login, get_backends
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def view_inside_a_view(request):
    return HttpResponse('hello %s' % request.user)

def view(request):
    # login dummy user
    user = User.objects.get(id=2)
    backend = get_backends()[0]
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    login(request, user)
    # change request's user
    request.user = user
    # get response from view
    response = view_inside_a_view(request)
    return HttpResponse('rendered view: %s' % response.content)

rawDescription: Creating a fake request to render a view to a string in django


rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


code:
# your other program
import Filter

# ...

Filter.main(some, args)

rawDescription: Python - Supplying Command Line Arguments - in "from X import A"


code: data, _, _ = line.strip().partition("#")

rawDescription: In Python: how do I say: if line.partition('#' or 'tab') ... do something


code:
x  = [ 1, 2, 3, 5, 10, 100, 1000 ]
y1 = [ 1, 0.822, 0.763, 0.715, 0.680, 0.648, 0.645 ]
y2 = [ 1, 0.859, 0.812, 0.774, 0.746, 0.721, 0.718 ]

import matplotlib.pyplot as plt
from matplotlib.transforms import BlendedGenericTransform
# mode 01 from one case
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
line1, = ax1.plot( x, y1, label='mode 01' )
# mode 01 from other case
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
line2, = ax2.plot( x, y2, label='mode 01' )

# Create new figure and two subplots, sharing both axes
fig3, (ax3, ax4) = plt.subplots(1,2,sharey=True, sharex=True,figsize=(10,5))

# Plot data from fig1 and fig2
line3, = ax3.plot(line1.get_data()[0], line1.get_data()[1])
line4, = ax4.plot(line2.get_data()[0], line2.get_data()[1])
# If possible (easy access to plotting data) use
# ax3.plot(x, y1)
# ax4.lpot(x, y2)

ax3.set_ylabel('y-axis')
ax3.grid(True)
ax4.grid(True)

# Add legend
fig3.legend((line3, line4),
            ('label 3', 'label 4'),
            loc = 'upper center',
            bbox_to_anchor = [0.5, -0.05],
            bbox_transform = BlendedGenericTransform(fig3.transFigure, ax3.transAxes))
# Make space for the legend beneath the subplots
plt.subplots_adjust(bottom = 0.2)
# Show only fig3
fig3.show()

rawDescription: matplotlib: combine different figures and put them in a single subplot sharing a common legend

description: Matplotlib: combine different figures and put them in a single subplot sharing a common legend


code:
from collections import Counter
liste = [1,2,3,5,10]
liste2 = [[1,2,3,5,10], [1,2], [1,5,10], [3,5,10], [1,2,5,10]]
c = Counter()
for elt in liste2:
    syn = elt # identify each sublist of liste2 as syn
    nTuple = len(syn)   # number of elements in the syn
    for i in liste:
        myTuple = ()
        if syn.count(i): # check if an item of liste is in liste2
               myTuple = (i, nTuple)
               if len(myTuple) == 0: # remove the empty tuples
                  del(myTuple)
               else:
                   result = myTuple
                   c[result] += 1
for item in c.items():
    print(item)

rawDescription: Count how many times a tuple appears in ouput results