code:
soup = BeautifulSoup(open("test.html"))
pages = []
h2tags = soup.find_all('h2')

def next_element(elem):
    while elem is not None:
        # Find next element, skip NavigableString objects
        elem = elem.next_sibling
        if hasattr(elem, 'name'):
            return elem

for h2tag in h2tags:
    page = [str(h2tag)]
    elem = next_element(h2tag)
    while elem and elem.name != 'h2':
        page.append(str(elem))
        elem = next_element(elem)
    pages.append('\n'.join(page))

rawDescription: How to split a html page to multiple pages using python and beautiful soup

description: Split a html page to multiple pages using python and beautiful soup


code:
x = np.random.rand(100)
y = np.random.rand(100, 25)
fit = np.polynomial.polynomial.polyfit(x, y, 2)
fit.shape # 25 columns of 3 polynomial coefficients
xx = np.random.rand(50)
interpol = np.polynomial.polynomial.polyval(xx, fit)
interpol.shape # 25 rows, each with 50 evaluations of the polynomial

rawDescription: NumPy PolyFit and PolyVal in Multiple Dimensions?


rawDescription: Creating correct for-loop/iteration for a unique list


rawDescription: Python extract top user name from json

description: Python extract top user name from json


rawDescription: Pandas group by operations on a data frame


rawDescription: How can I encode and decode percent-encoded (URL encoded) strings in Python?

description: Encode and decode percent-encoded (URL encoded) strings in Python


rawDescription: Determine number of row in matrix with duplicate rows


code:
s_port,
time, date,
s_sitename, s_ip,
cs_user_agent, sc_status, sc_substatus, sc_win32_status,
c_ip,
cs_username,
cs_method, cs_uri_stem, cs_uri_query = line_spliter(line)

rawDescription: Creating a dynamic "variable layout" for split() in Python


code:
for i in hwy:
    i[3] = sorted(i[3], key=lambda x: int(x.split('-')[-1]))
    #the key here may be necessary if your format for the lists wasn't consistent

rawDescription: How to sort string in ascending order based upon the integers that are part of this string

description: Sort string in ascending order based upon the integers that are part of this string


code: string

rawDescription: Difference between .string and .text BeautifulSoup


code:
import pytest
exit_code = pytest.main("smoke_test_suite.py")
test_failures = bool(exit_code)

rawDescription: How to make a py.test failure trigger outside functions?

description: Make a py.test failure trigger outside functions


code:
source = """This is a sentence... This is a second sentence.
         Is this a sentence? Sure it is!!!"""

stop = ('...', '.', '?', '!', '!!!')

i = 0
M = max(len(s) for s in stop)
L = len(source)

while i <= L:
    m = M
    while m > 0:
        chunk = source[i:i + m]
        if chunk in stop:
            print("end of sentence with: %s" % chunk)
            break
        m -= 1
    else:
        m = 1
    i += m

rawDescription: how do you determine the end of a sentence in a python serial parser?

description: Determine the end of a sentence in a python serial parser


code:
def image_img(self):
    if self.image:
        return u'<img src="%s" />' % self.image.url_125x125
    else:
        return '(Sin imagen)'
image_img.short_description = 'Thumb'
image_img.allow_tags = True

rawDescription: How to show image in django admin

description: Show image in django admin


code: not all(str(s).strip('-').isdigit() for s in a)

rawDescription: How to detect non-number of the list?

description: Detect non-number of the list


code:
import json
from collections import defaultdict

# read JSON data
with open("input.json") as input_file:
    old_data = json.load(input_file)

# regroup data
d = defaultdict(dict)
for item in old_data:
    d[item["id"]].update(item)

# write JSON data
with open("output.json", "w") as output_file:
    json.dump(list(d.values()), output_file, indent=4)

rawDescription: How to filter JSON data using Python?

description: Filter JSON data using Python


code:
#note the uuid without parenthesis
eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4)

rawDescription: Generate unique id in django from a model field


code:
from itertools import izip_longest
list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}]
keys = list_of_dict[0].keys()
[dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values())]

rawDescription: Write a list of dictionaries to csv where the dictionary values are lists


code:
for i, char in enumerate(str1):
    if str2[0] == char:
        print("found first instance of letter at,", i)
        print(str2 == str1[i:i + len(str2)])

rawDescription: Recreating builtin s.find('substring') function


code:
for i in msrange(0, 0.00003):
    print(i)

rawDescription: Make a counter in Python

description: Make a counter in Python


code:
class Logger:
    def __init__(self, prefix):
        self.prefix = prefix
    def log(self, msg):
        print('[{}] {}'.format(self.prefix, msg))

class Base:
    def set_logger(self, logger):
        self.logger = logger

class Test(Base):
    def do_something(self):
        self.logger.log('Hey !!')

test = Test()

test.set_logger(Logger('simulated'))
test.do_something()

test.set_logger(Logger('very real'))
test.do_something()

rawDescription: Inheritance and customisation of class

description: Inheritance and customisation of class


code:
arr = np.array([dictionary[key] for key in ('key1', 'key2', 'key3')]).T
arr

rawDescription: Python: Pulling data out of dictionary like a 2D array


code:
import itertools

def encode(v1, v2, d):
    return (v1 + v2 + d) % 26 + 1

def decode(v1, v2, d):
    return (v1 - v2 - d + 50) % 26 + 1

all_combinations = map(tuple, itertools.product(
    range(1, 27), range(1, 27), range(1, 11)))

all(decode(encode(v1, v2, d), v2, d) == v1 for v1, v2, d in all_combinations)
# => True

rawDescription: Issue with Decryption Algorithm

description: Issue with Decryption Algorithm


code:
import re
from itertools import groupby
from operator import itemgetter
from pprint import pprint

LINES = """\
@model:2.4.0=Skeleton "Skeleton"
@compartments
 Cell=1.0 "Cell"
@species
 Cell:[A]=100.0 "A"
 Cell:[B]=1.0 "B"
 Cell:[C]=0.0 "C"
 Cell:[D]=0.0 "D"
@parameters
kcat=4000
km = 146
v2_k = 88
@reactions
@r=v1 "v1"
 A -> C : B
 Cell * kcat * B * A / (km + A)
@r=v2 "v2"
 C -> C+D
 Cell * v2_k * C
""".splitlines(True)

SECTION_RE = re.compile(
    '@(?P<name>model|units|compartments|species|parameters|rules|reactions|events)'
)

def parse_sections(lines):

    result = dict()

    def stamp():
        section = None
        for line in lines:
            match = SECTION_RE.match(line)
            if match:
                section = match.group('name')
            yield (section, line)

    for key, group in groupby(stamp(), itemgetter(0)):
        result[key] = [x for _, x in group]

    return result

def main():
    pprint(parse_sections(LINES))

if __name__ == '__main__':
    main()

rawDescription: Create python dictionary from text using regex to distinguish between specific sections


code:
import re
st='Paragraph 4-2 says. i am going home$ early- Yes.'
[m.group(1) for m in re.finditer(r'(.*?[.$\-])(?:\s+|$)',st)]

rawDescription: Splitting a String using multiple delimiters


code:
class Lifesupport(object):
    def __init__(self, oxygen, nitrogen):
        self.oxygen = oxygen
        self.nitrogen = nitrogen
    def __str__(self):
        return "Your air has {0}% oxygen and {1}% nitrogen".format(self.oxygen, self.nitrogen)

rawDescription: What are the main advantages of using a class over a callable function?


code:
import dis
def foo():
    a = 5 * 6

dis.dis(foo)

rawDescription: Bytecode optimization

description: Bytecode optimization


code:
# Define 'simple' types
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)

def to_dict(model):
    output = {}

    for key, prop in model.properties().iteritems():
        value = getattr(model, key)

        if isinstance(value, SIMPLE_TYPES) and value is not None:
            output[key] = value
        elif isinstance(value, datetime.date):
            # Convert date/datetime to ms-since-epoch ("new Date()").
            ms = time.mktime(value.utctimetuple())
            ms += getattr(value, 'microseconds', 0) / 1000
            output[key] = int(ms)
        elif isinstance(value, db.GeoPt):
            output[key] = {'lat': value.lat, 'lon': value.lon}
        elif isinstance(value, db.Model):
            # Recurse
            output[key] = to_dict(value)
        else:
            raise ValueError('cannot encode ' + repr(prop))

    return output

rawDescription: Converting GAE model into JSON

description: Converting GAE model into JSON


code:
soup = BeautifulSoup.BeautifulSoup()
soup.feed(yourhtml)
[txt for txt in soup.findAll(text=True) if 'identified' in txt.lower()]

rawDescription: Beautiful Soup to Find and Regex Replace text 'not within  '


code: objects = [Stored_url(url=u) for u in urls]

rawDescription: Encapulated object creation in python

description: Encapulated object creation in python


rawDescription: Python and Numeric/numpy Array Slicing Behavior


code:
try:
    next
except NameError:       # doesn't show up until python 2.6
    def next(iter):
        return iter.next()

Empty = object()

class Iterator(object):
    """Adds the abilities
    True/False tests:  True means there are items still remaining to be used
    peek(): get the next item without removing it from the sequence
    """
    def __init__(self, iterator):
        self._iter = iter(iterator)
        self._peek = Empty
        self.peek()
    def __next__(self):
        peek, self._peek = self._peek, Empty
        self.peek()
        if peek is not Empty:
            return peek
        raise StopIteration
    next = __next__                     # python 2.x
    def __bool__(self):
        return self._peek is not Empty
    __nonzero__ = __bool__              # python 2.x
    def peek(self):
        if self._peek is not Empty:
            return self._peek
        self._peek = next(self._iter, Empty)
        return self._peek

rawDescription: How can I get generators/iterators to evaluate as False when exhausted?

description: Get generators/iterators to evaluate as False when exhausted


code:
import datetime
from matplotlib.finance import date2num

float_days = date2num(datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S%f'))

rawDescription: Converting date to float days format for Matplotlib


code:
order_dict = {color: index for index, color in enumerate(listOne)}
listTwo.sort(key=lambda x: order_dict[x["eyecolor"]])

rawDescription: Sorting a list of dictionaries based on the order of values of another list


code: indices = [list(x) for x in np.tril_indices_from(ar)]

rawDescription: fast way to get the indices of a lower triangular matrix as 1 dimensional list in python

description: Fast way to get the indices of a lower triangular matrix as 1 dimensional list in python


code:
tweets_lines = ['one two other', 'four other six', 'nothing matches']

scores = {
    'one': 1,
    'two': 2,
    'four': 4,
    'six': 6,
    }

for line in tweets_lines:
    total = line.split()
    line_score = {}
    for word in total:
        if word in scores:
            line_score[word] = scores[word]

    if line_score:  ## NEW: If line_score is empty, we skip this.
      line_sentiment = sum(line_score.itervalues())
      print (line_score, line_sentiment)

rawDescription: Python 2.7 - Conditional passing empty k,v pairs to dict instead of moving to next iterator


rawDescription: Matplotlib, plot and bar chart don't align against the same index


rawDescription: Python global variable changes itself.... Why?


rawDescription: Find all combination that sum to N with multiple lists


code:
entries = sorted(result.items())
intervals = [(end - start) for _, (start, end) in entries]
print(max(intervals[-5:]) > max(intervals[-5-14:-5]))
# -> False

rawDescription: Finding time intervals per day from a list of timestamps in Python


code: [(u'olive', u'leaf', u'plucked'), (u'rider', u'falls', u'backward'), (u'sewed', u'fig', u'leaves'), (u'yield', u'royal', u'dainties'), (u'during', u'mating', u'season'), (u'Their', u'hearts', u'failed'), (u'doing', u'forced', u'labor'), (u'El', u'Beth', u'El'), (u'own', u'droves', u'apart'), (u'sandal', u'strap', u'nor')]

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code: b_reshaped = b.reshape(dim_array)

rawDescription: multiply numpy ndarray with 1d array along a given axis

description: Multiply numpy ndarray with 1d array along a given axis


code:
multi_players = []
multi_players_pos = []

for i in range(10):
    temp = pygame.image.load("player_"+str(i)+".png").convert()
    temp.set_colorkey(white)
    multi_players.append(temp)
    pos = [random.randint(60,220+1), random.randint( 0, 475+1)]
    multi_players_pos.append(pos)

rawDescription: Pygame display multiple images randomly

description: Pygame display multiple images randomly


code:
print("Test")
eprint("Test")
eprint("foo", "bar", "baz", sep="---")

rawDescription: How to print to stderr in Python?

description: Print to stderr in Python


code:
import weakref

class Foo(object):
    def __init__(self):
        self.text = "Hello World"
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = weakref.ref(parent)    # <= garbage-collector safe!
        self.newText = parent.text

foo = Foo()

rawDescription: Getting container/parent object from within python


code:
"""Tests for checking database sanity checks functions correctly."""

from pyramid_web20.system.model.sanitycheck import is_sane_database
from sqlalchemy import engine_from_config, Column, Integer, String
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import ForeignKey

def setup_module(self):
    # Quiet log output for the tests
    import logging
    from pyramid_web20.system.model.sanitycheck import logger
    #logger.setLevel(logging.FATAL)

def gen_test_model():

    Base = declarative_base()

    class SaneTestModel(Base):
        """A sample SQLAlchemy model to demostrate db conflicts. """

        __tablename__ = "sanity_check_test"

        #: Running counter used in foreign key references
        id = Column(Integer, primary_key=True)

    return Base, SaneTestModel

def gen_relation_models():

    Base = declarative_base()

    class RelationTestModel(Base):
        __tablename__ = "sanity_check_test_2"
        id = Column(Integer, primary_key=True)

    class RelationTestModel2(Base):
        __tablename__ = "sanity_check_test_3"
        id = Column(Integer, primary_key=True)

        test_relationship_id = Column(ForeignKey("sanity_check_test_2.id"))
        test_relationship = relationship(RelationTestModel, primaryjoin=test_relationship_id == RelationTestModel.id)

    return Base, RelationTestModel, RelationTestModel2

def gen_declarative():

    Base = declarative_base()

    class DeclarativeTestModel(Base):
        __tablename__ = "sanity_check_test_4"
        id = Column(Integer, primary_key=True)

        @declared_attr
        def _password(self):
            return Column('password', String(256), nullable=False)

        @hybrid_property
        def password(self):
            return self._password

    return Base, DeclarativeTestModel

def test_sanity_pass(ini_settings, dbsession):
    """See database sanity check completes when tables and columns are created."""

    engine = engine_from_config(ini_settings, 'sqlalchemy.')
    conn = engine.connect()
    trans = conn.begin()

    Base, SaneTestModel = gen_test_model()
    Session = sessionmaker(bind=engine)
    session = Session()
    try:
        Base.metadata.drop_all(engine, tables=[SaneTestModel.__table__])
    except sqlalchemy.exc.NoSuchTableError:
        pass

    Base.metadata.create_all(engine, tables=[SaneTestModel.__table__])

    try:
        assert is_sane_database(Base, session) is True
    finally:
        Base.metadata.drop_all(engine)

def test_sanity_table_missing(ini_settings, dbsession):
    """See check fails when there is a missing table"""

    engine = engine_from_config(ini_settings, 'sqlalchemy.')
    conn = engine.connect()
    trans = conn.begin()

    Base, SaneTestModel = gen_test_model()
    Session = sessionmaker(bind=engine)
    session = Session()

    try:
        Base.metadata.drop_all(engine, tables=[SaneTestModel.__table__])
    except sqlalchemy.exc.NoSuchTableError:
        pass

    assert is_sane_database(Base, session) is False

def test_sanity_column_missing(ini_settings, dbsession):
    """See check fails when there is a missing table"""

    engine = engine_from_config(ini_settings, 'sqlalchemy.')
    conn = engine.connect()
    trans = conn.begin()

    Session = sessionmaker(bind=engine)
    session = Session()
    Base, SaneTestModel = gen_test_model()
    try:
        Base.metadata.drop_all(engine, tables=[SaneTestModel.__table__])
    except sqlalchemy.exc.NoSuchTableError:
        pass
    Base.metadata.create_all(engine, tables=[SaneTestModel.__table__])

    # Delete one of the columns
    engine.execute("ALTER TABLE sanity_check_test DROP COLUMN id")

    assert is_sane_database(Base, session) is False

def test_sanity_pass_relationship(ini_settings, dbsession):
    """See database sanity check understands about relationships and don't deem them as missing column."""

    engine = engine_from_config(ini_settings, 'sqlalchemy.')
    conn = engine.connect()
    trans = conn.begin()

    Session = sessionmaker(bind=engine)
    session = Session()

    Base, RelationTestModel, RelationTestModel2  = gen_relation_models()
    try:
        Base.metadata.drop_all(engine, tables=[RelationTestModel.__table__, RelationTestModel2.__table__])
    except sqlalchemy.exc.NoSuchTableError:
        pass

    Base.metadata.create_all(engine, tables=[RelationTestModel.__table__, RelationTestModel2.__table__])

    try:
        assert is_sane_database(Base, session) is True
    finally:
        Base.metadata.drop_all(engine)

def test_sanity_pass_declarative(ini_settings, dbsession):
    """See database sanity check understands about relationships and don't deem them as missing column."""

    engine = engine_from_config(ini_settings, 'sqlalchemy.')
    conn = engine.connect()
    trans = conn.begin()

    Session = sessionmaker(bind=engine)
    session = Session()

    Base, DeclarativeTestModel = gen_declarative()
    try:
        Base.metadata.drop_all(engine, tables=[DeclarativeTestModel.__table__])
    except sqlalchemy.exc.NoSuchTableError:
        pass

    Base.metadata.create_all(engine, tables=[DeclarativeTestModel.__table__])

    try:
        assert is_sane_database(Base, session) is True
    finally:
        Base.metadata.drop_all(engine)

rawDescription: Check database schema matches SQLAlchemy models on application startup


code: ' '.join(filter(bool, map(unicode.strip, hxs.select('id("breadcrumbs")//text()').extract())))

rawDescription: How to extract only text from the div containing more divs using scrapy

description: Extract only text from the div containing more divs using scrapy


code:
from requests import Session

s = Session()
s.cookies["s_cc"] = "your_session_cookie" # replace this with your actual login cookie

page_signed_in = s.get("http://www.surfline.com") # you're logged in :)

rawDescription: How to stay logged into a website using a Python script (requests library)?

description: Stay logged into a website using a Python script (requests library)


code:
t_3am = datetime.time(hour=3, minute=0)
t_630am = datetime.time(hour=6, minute=30)

rawDescription: Time comparison in python

description: Time comparison in python


code: list(reduce(operator.add, s, ()))

rawDescription: Python list comprehensions: Is it possible to specify the inclusion of two elements at a time?


code:
from django.conf.urls import patterns

urlpatterns = patterns('',
  url(r'^admin/', include(admin.site.urls)),
  url(r'^', include('cms.urls')),
)

rawDescription: How to remove language from the address?

description: Remove language from the address


code:
with open('file2.bin', 'wb') as f:
    f.write(myArr)

rawDescription: Create binary file in python

description: Create binary file in python


rawDescription: LXML, how to get multiple set of attributes to lists


code:
dicts = [dict1, dict2]
keys = reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), [])
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(keys)])

rawDescription: Updating or adding keys to dicts

description: Updating or adding keys to dicts


code:
import time
start = time.time()
end = time.time()
elapsed = end - start
elapsed

rawDescription: Paradoxical time intervals in Python

description: Paradoxical time intervals in Python


code: a = [[[[] for j in xrange(2)] for i in xrange(4)] for k in xrange(3)]

rawDescription: Initialize empty list with same shape as array


code:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
list(overlapping_sublists(l, 4))
list(overlapping_sublists(l, 4, 2, 3))

rawDescription: python generate sublist with offset and condition

description: Python generate sublist with offset and condition


code:
for path in st:
    params = path.split("?")[1].split("&")
    out = list(map(lambda v: v.split("=")[0] +"=" + fuzz_vectors, params))
    dictpath[path] = out

print(dictpath)

rawDescription: Replace resulting values with python split method


code:
x_idx = np.searchsorted(xi, xx)
x_idx

rawDescription: How to coarse grain xy coordinates

description: Coarse grain xy coordinates


code: shortest_length = min(len(correctanswer), len(userinput))

rawDescription: How to compare words in two lists according to same order in python?(I have def a function)

description: Compare words in two lists according to same order in python?(I have def a function)


rawDescription: Python - Pandas - Dataframe: Row Specific Conditional Column Offset


code:
class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    expiry_date = models.DateTimeField()

    def colored_name(self):
        if datetime.datetime.now() >= self.expiry_date:
            return '%s %s' % (self.first_name, self.last_name)
    colored_name.allow_tags = True

class PersonAdmin(admin.ModelAdmin):
    list_display = ('colored_name', 'first_name', 'last_name')

rawDescription: Create alerts in django application

description: Create alerts in django application


code:
people_by_age = {}
for person in people:
    age = person.pop('age')
    people_by_age.setdefault(age, []).append(person)

rawDescription: Map a list of dicts into a dict of lists of dicts


code:
def recursive_me(mystring, total = 0):
    if mystring: # recursive case
        newtotal = total + int(mystring[0])
        print(newtotal)
        return recursive_me(mystring[1:], newtotal)
    else:        # base case
        return total

rawDescription: Python recursive function that retain variable values


code: numpy.dot(a, a, out=c)

rawDescription: NumPy Matrix operation without copying

description: NumPy Matrix operation without copying


code:
from Products.CMFCore.utils import getToolByName

catalog = getToolByName(context, 'portal_catalog')
contents = catalog(path=dict(query='/root/Members/' + myname, depth=1))

rawDescription: Plone - getting and listing objects from member folder in a view


code:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Address(models.Model):
    object_id    = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    of           = generic.GenericForeignKey('content_type', 'object_id' )

class Person(models.Model):
    pass

class Store(models.Model):
    pass

class Company(models.Model):
    pass

rawDescription: Reverse Inlines in Django Admin with more than one model


code:
app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/')
def index():
  return render_template('index.html', message = 'Hello')

if __name__ == '__main__':
  app.run(host = '0.0.0.0')

rawDescription: File Upload and Processing using Python

description: File Upload and Processing using Python


code: Z = X*Y.T

rawDescription: performing sum of outer products on sparse matrices

description: Performing sum of outer products on sparse matrices


code:
browser['__ac_name'] = Username
browser['__ac_password'] = Password

rawDescription: Creme 96, Python, Mechanize.py

description: Creme 96, Python, Mechanize.py


code:
import warnings
warnings.warn("deprecated", DeprecationWarning)

rawDescription: How to "fake" a module safely in a Python package


code:
import numpy as np
from scipy import stats
from mayavi import mlab
import multiprocessing

def calc_kde(data):
    return kde(data.T)

mu, sigma = 0, 0.1
x = 10*np.random.normal(mu, sigma, 5000)
y = 10*np.random.normal(mu, sigma, 5000)
z = 10*np.random.normal(mu, sigma, 5000)

xyz = np.vstack([x,y,z])
kde = stats.gaussian_kde(xyz)

# Evaluate kde on a grid
xmin, ymin, zmin = x.min(), y.min(), z.min()
xmax, ymax, zmax = x.max(), y.max(), z.max()
xi, yi, zi = np.mgrid[xmin:xmax:30j, ymin:ymax:30j, zmin:zmax:30j]
coords = np.vstack([item.ravel() for item in [xi, yi, zi]])

# Multiprocessing
cores = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=cores)
results = pool.map(calc_kde, np.array_split(coords.T, 2))
density = np.concatenate(results).reshape(xi.shape)

# Plot scatter with mayavi
figure = mlab.figure('DensityPlot')

grid = mlab.pipeline.scalar_field(xi, yi, zi, density)
min = density.min()
max=density.max()
mlab.pipeline.volume(grid, vmin=min, vmax=min + .5*(max-min))

mlab.axes()
mlab.show()

rawDescription: How to plot a 3D density map in python with matplotlib

description: Plot a 3D density map in python with matplotlib


code:
self.widgetTable = []
for row in dataSet:
   self.widgetTable.append([wx.TextCtrl(self,-1,value) for value in row])

rawDescription: Proper way to access items in FlexGridSizer in wxPython?


code:
grouped = df.groupby('A')
grouped

rawDescription: Python pandas group by aggregate statement print


code:
print("Cryptography")
userInput = str(input("Write anything that you'd like to encrypt here: "))
n = 0
spacesLocation = []
while(True):
    try:
        spacesLocation.append(userInput.index(' '))
        userInput = userInput.replace(' ', '', 1)
        n+=1
    except:
        n = 0
        break
userNumberInput = int(input("Please choose a number without decimals here: "))
userInput = userInput.lower()
wordCount = userInput.split()
loopRunner = int(0)
letterCount = list()
for word in range(len(wordCount)):
    letterCount.insert(loopRunner,len(wordCount[loopRunner]))
    print(letterCount[loopRunner])
    loopRunner = loopRunner + 1

outputString = "" .join((chr(97 + (ord(letter) -97 + userNumberInput) % 26) for letter in userInput))
loopRunner = 0
for word in range(len(wordCount)):
    outputString2 = [outputString[i:i+letterCount[loopRunner]] for i in range (0, len(outputString), letterCount[loopRunner])]
    loopRunner = loopRunner + 1
finalResult = " " .join(outputString2)
while(n < len(spacesLocation)):
    finalResult = finalResult[:spacesLocation[n]+n] + ' ' +finalResult[spacesLocation[n]+n:]
    n+=1
print(finalResult)

rawDescription: Python: Moving letters within the alphabet in a string


rawDescription: Finding superstrings in a set of strings in python


rawDescription: Explain this python string operation s[:6][::-1]


code:
from textwrap import wrap

def getAbstract(text, lines=5, screenwidth=100):
    width = len(' '.join([
               line for block in text.splitlines()
               for line in wrap(block, width=screenwidth)
            ][:lines]))
    return text[:width] + '...'

rawDescription: Computing article abstracts

description: Computing article abstracts


code:
import json
jdict = json.decoder.JSONDecoder().decode('''{
  "status": "",
  "list": [
    {
      "host": "118.26.147.119:80",
      "ip_address": "118.26.147.119",
      "port": 80,
      "country_code": "CN",
      "uptime": 86.2,
      "connectionTime": 1.2633587,
      "type": "http",
      "lastValidatedDate": "2014-12-09T15:06:26",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    },
    {
      "host": "111.13.109.52:80",
      "ip_address": "111.13.109.52",
      "port": 80,
      "country_code": "CN",
      "uptime": 99.9,
      "connectionTime": 1.4086116,
      "type": "http",
      "lastValidatedDate": "2014-12-09T14:49:31",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    }
  ]
}''')

rawDescription: Convert JSON to Python Array

description: Convert JSON to Python Array


code:
list1=[comb for comb in combinations(range(1,10),3)]
print (len(list1))

rawDescription: Count the number of results

description: Count the number of results


code:
# importer.py
import config
config.param = 4
import importee

rawDescription: Is there a way to get importer's variable in importee?


code:
from operator import attrgetter

class Product:
    def __init__(self, price, height, width):
        self.price = price
        self.height = height
        self.width = width

    def __eq__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) == attrgetter(*attrs)(val)

    def __ne__(self, val):
        attrs = ('width', 'price', 'height')
        return attrgetter(*attrs)(self) != attrgetter(*attrs)(val)

rawDescription: Check if an object (with certain properties values) not in list


code:
for param in ['text', 'another', 'option']:
    if param in kwargs:
        initparms[param] = kwargs[param]

rawDescription: how to pythonically pass arguments to methods of subclassed widgets?

description: Pythonically pass arguments to methods of subclassed widgets


rawDescription: Python: Slicing a String based on Indicies and character


code:
import multiprocessing

def f(shared_list):
    shared_list.append(1)

if __name__ == "__main__":
    normal_list = []
    p = multiprocessing.Process(target=f, args=(normal_list,))
    p.start()
    p.join()
    print(normal_list)

    m = multiprocessing.Manager()
    shared_list = m.list()
    p = multiprocessing.Process(target=f, args=(shared_list,))
    p.start()
    p.join()
    print(shared_list)

rawDescription: Python/Multiprocessing : Processes does not seem to start


code:
class PlaceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Place
        fields = ('id', 'name')

class MapSerializer(serializers.ModelSerializer):
    places = PlaceSerializer(many=True)
    class Meta:
        model = Map
        fields = ('id', 'name')

rawDescription: Django REST - How can I get a JSON with two models?


rawDescription: Python 2.7 rounding vs Python 3

description: Python 2.7 rounding vs Python 3


code:
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
   groups.append(list(g))    # Store group iterator as a list
   uniquekeys.append(k)

rawDescription: How do I use Python's itertools.groupby()?

description: Use Python's itertools.groupby()


code:
# core/forms.py
class IntranetForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(IntranetForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'

# app/forms.py
class ComplaintForm(IntranetForm):
    def __init__(self, *args, **kwargs):
        super(ComplaintForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
            Field(
                'case',
                css_class='input-xlarge',
                template='complaints/related_case.html',
            ),
            Field('date_received', css_class = 'input-xlarge'),
            Field('stage', css_class = 'input-xlarge'),
            Field('tags', css_class = 'input-xlarge'),
            Field('team', css_class = 'input-xlarge'),
            Field('handler', css_class = 'input-xlarge'),
            Field('status', css_class = 'input-xlarge'),
            FormActions(
                Submit(
                    'save_changes',
                    'Save changes',
                    css_class = "btn-primary"
                ),
                Button(
                    'cancel',
                    'Cancel',
                    onclick = 'history.go(-1);'
                ),
            ),
        )

    class Meta:
        model = Complaint
        fields = (
            'case',
            'date_received',
            'stage',
            'tags',
            'team',
            'handler',
            'status',
        )

rawDescription: How to use a CreateView and include fields in form for new ForeignKey model?

description: Use a CreateView and include fields in form for new ForeignKey model


code:
import os
import wmi
import collections
import ctypes
from ctypes import wintypes

SE_OWNER_DEFAULTED        = 0x0001
SE_GROUP_DEFAULTED        = 0x0002
SE_DACL_PRESENT           = 0x0004
SE_DACL_DEFAULTED         = 0x0008
SE_SACL_PRESENT           = 0x0010
SE_SACL_DEFAULTED         = 0x0020
SE_DACL_AUTO_INHERIT_REQ  = 0x0100
SE_SACL_AUTO_INHERIT_REQ  = 0x0200
SE_DACL_AUTO_INHERITED    = 0x0400
SE_SACL_AUTO_INHERITED    = 0x0800
SE_DACL_PROTECTED         = 0x1000
SE_SACL_PROTECTED         = 0x2000
SE_SELF_RELATIVE          = 0x8000

OBJECT_INHERIT_ACE         = 0x01
CONTAINER_INHERIT_ACE      = 0x02
NO_PROPAGATE_INHERIT_ACE   = 0x04
INHERIT_ONLY_ACE           = 0x08
INHERITED_ACE              = 0x10
SUCCESSFUL_ACCESS_ACE_FLAG = 0x40
FAILED_ACCESS_ACE_FLAG     = 0x80

ACCESS_ALLOWED_ACE_TYPE = 0
ACCESS_DENIED_ACE_TYPE  = 1
SYSTEM_AUDIT_ACE_TYPE   = 2

DELETE                 = 0x00010000 # DE
READ_CONTROL           = 0x00020000 # RC
WRITE_DAC              = 0x00040000 # WDAC
WRITE_OWNER            = 0x00080000 # WO
SYNCHRONIZE            = 0x00100000 # S
ACCESS_SYSTEM_SECURITY = 0x01000000 # AS
GENERIC_READ           = 0x80000000 # GR
GENERIC_WRITE          = 0x40000000 # GW
GENERIC_EXECUTE        = 0x20000000 # GE
GENERIC_ALL            = 0x10000000 # GA

FILE_READ_DATA         = 0x00000001 # RD
FILE_LIST_DIRECTORY    = 0x00000001
FILE_WRITE_DATA        = 0x00000002 # WD
FILE_ADD_FILE          = 0x00000002
FILE_APPEND_DATA       = 0x00000004 # AD
FILE_ADD_SUBDIRECTORY  = 0x00000004
FILE_READ_EA           = 0x00000008 # REA
FILE_WRITE_EA          = 0x00000010 # WEA
FILE_EXECUTE           = 0x00000020 # X
FILE_TRAVERSE          = 0x00000020
FILE_DELETE_CHILD      = 0x00000040 # DC
FILE_READ_ATTRIBUTES   = 0x00000080 # RA
FILE_WRITE_ATTRIBUTES  = 0x00000100 # WA

FILE_GENERIC_READ      = (FILE_READ_DATA        |
                          FILE_READ_EA          |
                          FILE_READ_ATTRIBUTES  |
                          READ_CONTROL          |
                          SYNCHRONIZE)

FILE_GENERIC_WRITE     = (FILE_WRITE_DATA       |
                          FILE_APPEND_DATA      |
                          FILE_WRITE_EA         |
                          FILE_WRITE_ATTRIBUTES |
                          READ_CONTROL          |
                          SYNCHRONIZE)

FILE_GENERIC_EXECUTE    = (FILE_EXECUTE         |
                           FILE_READ_ATTRIBUTES |
                           READ_CONTROL         |
                           SYNCHRONIZE)

FILE_ALL_ACCESS         = 0x001F01FF

FILE_MODIIFY_ACCESS     = FILE_ALL_ACCESS & ~(FILE_DELETE_CHILD |
                                              WRITE_DAC         |
                                              WRITE_OWNER)

FILE_READ_EXEC_ACCESS   = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE

FILE_DELETE_ACCESS      = DELETE | SYNCHRONIZE

rawDescription: Python - Get windows folder ACL permissions


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

randBinList = lambda n: [np.random.randint(0,2) for b in range(1,n+1)]
rng = pd.date_range('1/1/2011', periods=72, freq='H')
ts = pd.DataFrame({
    'Value1': np.random.randn(len(rng)),
    'Value2': np.random.randn(len(rng)),
    'OnOff': randBinList(len(rng))
}, index=rng)

rawDescription: Matplotlib axvspan shading for pandas DataFrame subplots based on one of the columns


rawDescription: PyQt5 sending a signal to QMediaPlayer

description: PyQt5 sending a signal to QMediaPlayer


code:
def fast_samp_2(refs, lim=10000, blocksize=10000):

    samp = np.random.choice(refs, size=blocksize, replace=True)
    samp_sum = np.cumsum(samp)

    # is the sum of our current block of samples >= lim?
    while samp_sum[-1] < lim:

        # if not, we'll sample another block and try again until it is
        newsamp = np.random.choice(refs, size=blocksize, replace=True)
        samp = np.hstack((samp, newsamp))
        samp_sum = np.hstack((samp_sum, np.cumsum(newsamp) +  samp_sum[-1]))

    last = np.searchsorted(samp_sum, lim, side='right')
    return samp[:last + 1]

rawDescription: Speed up loop to fill an array with closest values from another array


code:
class SamAccount(models.Model):
   account = models.ForeignKey('Account', on_delete=models.CASCADE)
   sam = models.ForeignKey('Sam', on_delete=models.CASCADE)

   def __unicode__(self):
       return u'%s' % self.account

rawDescription: How to edit/update a model via Django form with manytomany field?

description: Edit/update a model via Django form with manytomany field


code:
@register.filter
def myfilter(value):
    return value
myfilter.is_safe = True

rawDescription: How to prevent auto escape in Django templates?

description: Prevent auto escape in Django templates


rawDescription: Making a dict of a list with more then 1 value


code: np.where(np.isclose(a,b) == False)

rawDescription: Numpy: how to get the items that are different of 2 matrices?


code:
def __init__(self, parent, controller):

    ...

    self.position = 0 #the index of the pages list

rawDescription: tkinter - Going Back and Forth Between Frames Using Buttons

description: Tkinter - Going Back and Forth Between Frames Using Buttons


code:
thefile = open("output.txt","wb")
for item in output:
  thefile.write("%s\n" % item)

rawDescription: Python concatenate recursively strings in files


code: inputfile = codecs.open(filename, 'r', encoding='latin1')

rawDescription: Writing accented characters to Oracle

description: Writing accented characters to Oracle


code:
record_on = False
playback_on = False

recorded_frames = queue.Queue()

def callback_play_sine(in_data, frame_count, time_info, status):
    if record_on:
        global recorded_frames
        recorded_frames.put(in_data)

    if playback_on:
        left_channel_data = mysine.next_block(frame_count) * MAX_INT24 * gain
        right_channel_data = ((np.random.rand(frame_count) * 2) - 1) * MAX_INT24 * gain
        data = interleave_channels(max_nr_of_channels, (left_output_channel, left_channel_data), (right_output_channel, right_channel_data))
        data = convert_int32_to_24bit_bytestream(data)
    else:
        data = np.zeros(frame_count*max_nr_of_channels).tostring()

    if stop_callback:
        callback_flag = pyaudio.paComplete
    else:
        callback_flag = pyaudio.paContinue

    return data, callback_flag

rawDescription: PyAudio Responsive Recording

description: PyAudio Responsive Recording


code:
points = grouped['Goal'] + grouped['Assits']
points

rawDescription: How to generate continuous record from incomplete data in Pandas Dataframe

description: Generate continuous record from incomplete data in Pandas Dataframe


code:
from django import template
register = template.Library()

def dict_get(value, arg):
    #custom template tag used like so:
    #{{dictionary|dict_get:var}}
    #where dictionary is duh a dictionary and var is a variable representing
    #one of it's keys

    return value[arg]

register.filter('dict_get',dict_get)

rawDescription: Django | sort dict in template

description: Django | sort dict in template


code:
from StringIO import StringIO
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = process.communicate()
log_subprocess_output(StringIO(output))

rawDescription: Run subprocess and print output to logging


code:
config = {'db' : 'database_1'}

variables = {'threshold' : [1,2,3,4]}

rawDescription: Is there a Python test framework suitable to run simulations


code:
import uuid

def generate_guid(username):
    class NULL_NAMESPACE:
        bytes = b''

    guid = uuid.uuid3(NULL_NAMESPACE, username.encode('utf-8'))
    return guid

rawDescription: Creating GUID by Python from bytes

description: Creating GUID by Python from bytes


code:
MyClass().id
MyClass().id
MyClass().id
MyClass().id

rawDescription: How can I determine the number of objects that exist of a specific class?

description: Determine the number of objects that exist of a specific class


code:
import glob
import javalang

# look at all .java files in the working directory
for fname in glob.glob("*.java"):
    # load the sourcecode
    with open(fname) as inf:
        sourcecode = inf.read()

    try:
        # parse it to an Abstract Syntax Tree
        tree = javalang.parse.parse(sourcecode)
        # get package name
        pkg = tree.package.name

        # look at all class declarations
        for path, node in tree.filter(javalang.tree.ClassDeclaration):
            # if class extends Applet
            if node.extends.name == 'Applet':
                # print the class name
                print("{}: package {}, main class is {}".format(fname, pkg, node.name))

    except javalang.parser.JavaSyntaxError as je:
        # report any files which don't parse properly
        print("Error parsing {}: {}".format(fname, je))

rawDescription: How to find a special word inside a file using Python?

description: Find a special word inside a file using Python


code:
all_files = [ [t[0] for t in v] for v in takes.values() ]
all_durations = [ [t[1] for t in v] for v in takes.values() ]
num_attempts = min(len(d) for d in all_durations)

successes = 0

for attempt in range(num_attempts):
    # get lengths for all cameras
    durations = [d[attempt] for d in all_durations]
    discrepancy = max(durations) - min(durations)
    if discrepancy > 1000: continue
    successes += 1
    dest_dir = 'take{}'.format(successes)
    for filename in [f[attempt] for f in all_files]:
        shutil.copy(filename, dest_dir)

rawDescription: Python - Check List Data to Store Files in Folder Structure


rawDescription: R equivalent of Python's heapq.heapify()?


code:
def some_function(iter):
    import sqlite3
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    query = ...

    for x in iter:
        # fetch some data from a database
        c.execute(query, (x, ))
        for y in c.fetchall():
            yield (x, y)

rdd.mapPartitions(some_function)

rawDescription: Upper triangle of cartesian in spark for symmetric operations: `x*(x+1)//2` instead of `x**2`


rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code: hour = hour if AM_PM == 'AM' else hour + 12

rawDescription: Parse timestamps containing different lengths Python


code:
import matplotlib.plt
fig = plt.figure()
size = fig.get_size_inches()*fig.dpi # size in pixels

rawDescription: How to get matplotlib figure size

description: Get matplotlib figure size


rawDescription: divide ways on a map in parts of length one

description: Divide ways on a map in parts of length one


code: bins

rawDescription: How to partition dataframe rows into bins with calculations

description: Partition dataframe rows into bins with calculations


rawDescription: Python 2.7 Local Variables are acting like global variables


code:
class State( object ):
    def transitionRule( self, input ):
        next_states = [ s for f,s in self.map if f(input)  ]
        assert len(next_states) >= 1, "faulty transition rule"
        return eval(next_states[0])()

class S1( State ):
    map = [ (lambda x: x == "input", "S2"), (lambda x: x == "other", "S3" ) ]

class S2( State ):
    map = [ (lambda x: "bar" <= x <= "foo", "S3"), (lambda x: True, "S1") ]

rawDescription: Python state-machine design

description: Python state-machine design


code:
def prefix_with_length(length, phonenum):
    return phonenum.replace('-','')[:length]
    # I also drop hyphens for a more robust code

rawDescription: getting the prefix of a number in python

description: Getting the prefix of a number in python


code: [x for x in a.reshape(-1,2)]

rawDescription: Convert a numpy array to an array of numpy arrays


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

nan = np.nan

trades = pd.DataFrame({'ticker' : ['IBM', 'MSFT', 'GOOG', 'AAPL'],
                       'date' : pd.date_range('1/1/2000', periods = 4),
                       'cusip' : [nan, nan, 100, nan]
                       })
trades = trades.set_index(['ticker', 'date'])
print(trades)
#                    cusip
# ticker date
# IBM    2000-01-01    NaN
# MSFT   2000-01-02    NaN
# GOOG   2000-01-03    100  # <-- We do not want to overwrite this
# AAPL   2000-01-04    NaN

config = pd.DataFrame({'ticker' : ['IBM', 'MSFT', 'GOOG', 'AAPL'],
                       'date' : pd.date_range('1/1/2000', periods = 4),
                       'cusip' : [1,2,3,nan]})
config = config.set_index(['ticker', 'date'])

# Let's permute the index to show `DataFrame.update` correctly matches rows based on the index, not on the order of the rows.
new_index = sorted(config.index)
config = config.reindex(new_index)
print(config)
#                    cusip
# ticker date
# AAPL   2000-01-04    NaN
# GOOG   2000-01-03      3
# IBM    2000-01-01      1
# MSFT   2000-01-02      2

rawDescription: Updating pandas DataFrame by key

description: Updating pandas DataFrame by key


code:
d = collections.defaultdict(list)
d['js'].append({'foo': 'bar'})
d['js'].append({'other': 'thing'})

rawDescription: Update and create a multi-dimensional dictionary in Python


rawDescription: Numpy 3D array transposed when indexed in single step vs two steps


code:
s = df.to_json(orient='records')
s = s.replace( '[{','{')
s = s.replace( '},{', '}{')
s = s.replace( '}]','}')

rawDescription: Pandas Dataframe to JSON with Custom Encoding


code:
with open(filename, 'wb') as fd:
    while True:
        chunk = await r.content.read(chunk_size)
        if not chunk:
            break
        fd.write(chunk)

rawDescription: What is the equivalent method of request.iter_content() in aiohttp?


rawDescription: Selenium/python - fails to find partial link text


code: select([True], some_expression_object)

rawDescription: Sqlalchemy select condition

description: Sqlalchemy select condition


code:
x = np.arange(12).reshape(3, 4)
x
n = x.shape[1] - 1
y = np.repeat(x, (n,)+(1,)*n, axis=1)
y
y.reshape(-1, 2, n).transpose(0, 2, 1).reshape(-1, 2)

rawDescription: Efficient way of making a list of pairs from an array in Numpy


code:
urlpatterns = patterns('',
    url(r'^(?P<website_slug>[\w]+)$', ProductView.as_view(), name='products_list'),
)

rawDescription: Django 1.6: Displaying a particular models Objects in another template


code:
def f(a):
    b,c,d = a
    ...

rawDescription: Assigning a name to a pattern-matched item in Python


code:
t1 = Test()
t2 = Test()
t1.num
Test.num
Test.__dict__['num']
t1.num = 10
t1.num
t2.num
Test.num

rawDescription: getting pythons __set__ working

description: Getting pythons __set__ working


code:
for _ in range(10):
    # generate number1 and number2 here

    validated = False
    while not validated:
        try:
            answer = int(input("your input prompt goes here"))
            validated = True # your code will error before here
        except ValueError:
            print("Your answer must be an integer")

    # the rest of your code

rawDescription: Repeating questions to user ten times in Python


code:
def lazy_func(func):
    class LazyComparer(object):
        def __init__(self, x):
            self.x = x
        def __lt__(self, other):
            return func(self.x) < func(other.x)
        def __eq__(self, other):
            return func(self.x) == func(other.x)
    return lambda x: LazyComparer(x)

rawDescription: Avoiding unnecessary key evaluations when sorting a list


code:
import argparse

def func1(): pass
def func2(): pass
def func3(): pass

parser = argparse.ArgumentParser()
parser.add_argument(
    "-l", "--list",
    dest='funcs', action="append_const", const=func1,
    help="Create CSV of images", )
parser.add_argument(
    "-i", "--interactive",
    dest='funcs', action="append_const", const=func2,
    help="Run script in interactive mode",)
parser.add_argument(
    "-d", "--dimensions",
    dest='funcs', action='append_const', const=func3,
    help="Copy images with incorrect dimensions to new directory")
args = parser.parse_args()
if not args.funcs:
    args.funcs = [func1, func2, func3]

for func in args.funcs:
    print(func.func_name)
    func()

rawDescription: python argparse set behaviour when no arguments provided

description: Python argparse set behaviour when no arguments provided


rawDescription: Calculating "generating functions" with numpy


rawDescription: matplotlib show many images in single pdf page

description: Matplotlib show many images in single pdf page


code:
df_dict = {}
df_dict['nba'] = get_merged_csv(path, '*nba.csv')
df_dict['basketball'] = get_merged_csv(path, '*basketball.csv')
df_dict['soccer'] = get_merged_csv(path, '*soccer.csv')

rawDescription: Reading multiple csv files, concatenate list of file names them into a singe DataFrame


code:
import json

terms = {
     'root':      {'p': [],          'c': ['branch1', 'branch2', 'branch3']},
     'branch1':   {'p': ['root'],    'c': ['branch1.1']},
     'branch2':   {'p': ['root'],    'c': []},
     'branch3':   {'p': ['root'],    'c': []},
     'branch1.1': {'p': ['branch1'], 'c': []}
}

def transform(d, parent):
    return (
        {'name': parent}
            if not d[parent]['c'] else
        {'name': parent,
         'children': [transform(d, child) for child in d[parent]['c']]}
    )

print(json.dumps(transform(terms, 'root'), indent=2))

rawDescription: dictionary to JSON?

description: Dictionary to JSON


rawDescription: TypeError: string indices must be integers - Parsing JSON


code: re.findall(ultimate_pattern, text)

rawDescription: Regular expressions in python (multiple variables)


code:
string = "testing\n"
string
string = string[:-1]
string

rawDescription: Delete newline / return carriage in file output


rawDescription: pamie How to access variables in framset

description: Pamie How to access variables in framset


code:
tree.selection()  # ('I003',)
tree.item(tree.selection())
tree.item(tree.selection())['values']  # [u'A3', u'B3', u'C3']
tree.item(tree.selection())['values'][0]  # u'A3'
if tree.item(tree.selection())['values'][0]:
    # test for zero, empty string or None
    pass  # do stuff

rawDescription: value tree item python tkinter

description: Value tree item python tkinter


code:
import sys
from PySide import QtGui
from model.Model import Model
from ctrls.MainController import MainController
from views.MainView import MainView

class App(QtGui.QApplication):
    def __init__(self, sys_argv):
        super(App, self).__init__(sys_argv)
        self.model = Model()
        self.main_ctrl = MainController(self.model)
        self.main_view = MainView(self.model, self.main_ctrl)
        self.main_view.show()

if __name__ == '__main__':
    app = App(sys.argv)
    sys.exit(app.exec_())

rawDescription: MVC design with QtDesigner and PySide

description: MVC design with QtDesigner and PySide


rawDescription: Monitoring variable access and object creation in Python


rawDescription: Typing Greek letters etc. in Python plots


code:
def do_stuff(self):
    # make plausible data
    fig = pyplot.gcf()
    fig.clf()
    self.ax = fig.add_subplot(111)
    # etc.

rawDescription: Control of the figure when using matplotlib


code: i = {v: k for (k, v) in d.items()}

rawDescription: python query keys in a dictionary based on values

description: Python query keys in a dictionary based on values


code:
result = sympy.polys.polyfuncs.interpolate(data,x)
coefficients = sympy.Poly(result).coeffs()
print(coefficients)

rawDescription: How to recognize which mathematical function generated a curve given by X and Y arrays in sympy

description: Recognize which mathematical function generated a curve given by X and Y arrays in sympy


code: data['Telecom Circle / State'], data['Network Operator / Service Provider']

rawDescription: extract only a few lines from output

description: Extract only a few lines from output


code:
def filtermax(g, filter_on, filter_items, max_over):
    infilter = g.index.isin(filter_items).sum() > 0
    if infilter:
        return g[g[max_over] == g.ix[filter_items][max_over].max()]
    else:
        return g[g[max_over] == g[max_over].max()]
    return g

rawDescription: How to filter results of a groupby in pandas

description: Filter results of a groupby in pandas


rawDescription: plot entire row on pandas

description: Plot entire row on pandas


rawDescription: Python Pandas counting and summing specific conditions


code:
def checkEqual3(lst):
   return lst[1:] == lst[:-1]

rawDescription: check if all elements in a list are identical

description: Check if all elements in a list are identical


code:
class Feline(models.Model):
    objects = models.Manager()

class Cat(Feline):
    #n.b. Cat now inherits from Feline, not models.Model
    objects = models.Manager()

    feline = models.OneToOneField(Feline, parent_link = True)
    name = models.CharField(max_length=255)
    miaow_factor = models.IntegerField()

rawDescription: How to create a superclass (for an existing model) with Django and South

description: Create a superclass (for an existing model) with Django and South


code: ' this is a very\n        long string if I had the\n        energy to type more and more ...'

rawDescription: Pythonic way to create a long multi-line string


rawDescription: Reversing the elements of lists which are in list


code: product = itertools.product(L, repeat=n)

rawDescription: Python: shortest way to compute cartesian power of list


code:
for r in range(0,25):
    for c in range(0,25):
        idd=str(r)+","+str(c)
        spots[idd]=idd
        s = spot(text=idd)
        self.m.add_widget(s)

        s.bind(on_press=self.spottouched)

rawDescription: Events passing in python with kivy

description: Events passing in python with kivy


code:
import re
names = ['g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt',
'g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt',
'g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt',
'g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt',
'g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt',
'g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt',
'g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt']

expression = 'g18_84pp_2A_MVP(.*?)_Goodies(.*?)_MIX(.*?)\.txt'
f = lambda x: re.findall(expression, x)
_f = lambda x: len(re.findall(expression, x))==3

for x in names:
    print(f(x))

rawDescription: How to extract a common name from multipal filenames and delete something I don't want

description: Extract a common name from multipal filenames and delete something I don't want


code:
import timeit

userplays = { "Alice"   : { "AC/DC" : 2,
                            "The Raconteurs" : 3,
                            "Mogwai" : 1
                          },
              "Bob"     : { "The XX" : 4,
                            "Lady Gaga" : 3,
                            "Mogwai" : 1,
                            "The Raconteurs" : 1
                          },
              "Charlie" : { "AC/DC" : 7,
                            "Lady Gaga" : 7
                          }
            }

def f1():
    set(b for v in userplays.values() for b in v.keys())

def f2():
    {k:v for v in userplays.values() for k in v.keys()}.keys()

t1=timeit.Timer(f1).timeit(10000)
t2=timeit.Timer(f2).timeit(10000)
faster=abs(t1-t2) / max(t1,t2)
print("""
set:                {:.4} seconds
dict:               {:.4} seconds
faster of those is  {:.4%} faster

""".format(t1,t2,faster))

rawDescription: Build list using only list comprehensions, no function


rawDescription: unexpected result in numpy array slicing (view vs copy)

description: Unexpected result in numpy array slicing (view vs copy)


code:
# modulea.py
import moduleb

rawDescription: How to import appropriately

description: Import appropriately


code:
def get_colour(prompt, valid_colours):
    """Allow the user to enter a single valid colour."""
    while True:
        colour = input(prompt)
        if colour in valid_colours:
            return colour
        print("Not a valid colour.")

def get_colours(n, valid_colours):
    """Get n valid colours from the user."""
    return [get_colour("Input colour {}: ".format(i+1), valid_colours)
            for i in range(n)]

colours = get_colours(4, {"red", "green", "blue", "yellow", "magenta", "cyan"})

rawDescription: how can i modify my code so that the user can input the same colour four times but not anything outside my list range?

description: Modify my code so that the user can input the same colour four times but not anything outside my list range


code:
data = {}
for file in files:
   data[file] = {}
   with open(file,'r') as f:
      lines=[int(line.strip()) for line in f]
      data[file]['temps'] = lines[::2]            #even lines just read
      data[file]['pressures'] = lines[1::2]       #odd lines

rawDescription: Name of a list changing as I go through a loop


code:
import numpy as np
data = np.genfromtxt('data.csv', delimiter=',', names=True)

rawDescription: Most Pythonic way to read csv values into dict of lists


code: ['appserver-mgr2', 'appserver-wkr2', 'appserver-wkr3', 'appserver-wkr4']

rawDescription: Python config parser array sort according to file content sequence


rawDescription: Python regex to match IP range

description: Python regex to match IP range


code:
import unittest

import project

class Config(object):
    DEBUG = False
    TESTING = True
    CACHE_NO_NULL_WARNING = True  # silence Flask-Cache warning
    SECRET_KEY = 'SECRET_KEY'

class ProjectCoreViewCase(unittest.TestCase):
    """Base test case for the Project core app"""

    def setUp(self, **kwargs):
        config = Config()
        config.__dict__.update(kwargs)
        app = project.create_app(config)
        self.app = app.test_client()

rawDescription: Flask initialisation for unit test and app


code:
d2 = {}
for k, v in d1.items():
    d2[k] = f(v)

rawDescription: Applying a function to values in dict

description: Applying a function to values in dict


code: shared_path = multiprocessing.sharedctypes.RawArray("c", path)

rawDescription: Lock free read only List in Python?

description: Lock free read only List in Python


code: del mylist[:]

rawDescription: Erase whole array Python

description: Erase whole array Python


rawDescription: String creation: Differences between two syntaxes ' ' and " "?


code: users = [user._data for user in users._iter_results()]

rawDescription: How to get dictionary object in Mongoengine Python?

description: Get dictionary object in Mongoengine Python


code:
from tempfile import TemporaryFile
from itertools import chain

rawDescription: Sorting csv by number of columns in each row


code:
for elem in chain.from_iterable(test):
    print(elem, end=' ')   # prints 1 2 3 4 5 1 2 3 4 5 6

rawDescription: More "pythonic" way of expanding list of lists to one joined list


code:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0)'}
requests.get(url, headers=headers).raise_for_status()

rawDescription: Python requests package returning different HTTP status than browser


code:
def type_one_only(user):
    if hasattr (user, 'usertypeone'):
        return True
    else:
        return False

def type_two_only(user):
    #same thing without if/else
    return hasattr(user, 'usertypetwo')

rawDescription: Django related User Model - Permissions and Decorators


code:
digits = '0123456789ABCDEF'
while number:
    number, digit = divmod(number, 16)
    myResult = digits[digit] + myResult

rawDescription: List prints two values instead of one

description: List prints two values instead of one


code:
tpl = '''
    "unaltered": "{{foo}}",
    "replaced": "{{test}}"
'''

rawDescription: Python template safe substitution with the custom double-braces format


rawDescription: How to check existence of a sequence in a sorted list?

description: Check existence of a sequence in a sorted list


code:
with open(file) as f:
    for chunk in lines_per_n(f, 7):
        jfile = json.loads(chunk)

        # do something with jfile

rawDescription: Python: Trying to Deserialize Multiple JSON objects in a file with each object spanning multiple but consistently spaced number of lines


code:
from collections import Counter
items = ['a', 'b', 'c', 'c', 'b', 'a']
counter = Counter()
counter.update(items)
counter.update(['foo', 'bar', 'baz', 'baz', 'bar'])
print(counter)

rawDescription: Comparing List to Dictionary in Python

description: Comparing List to Dictionary in Python


code:
p = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?')
m = p.match('ab')
m.group(0);
m.group(2);

rawDescription: Python regex: Matching a URL

description: Python regex: Matching a URL


code: first_name, last_name, address, date_of_birth, favourite_icecream = ... # you get the idea.

rawDescription: Use parentheses or not for multiple variable assignment in Python?


code:
def ntuples(lst, n):
    return zip(*[lst[i:]+lst[:i] for i in range(n)])

rawDescription: Iterate over pairs in a list (circular fashion) in Python


rawDescription: Ifilter together with lambda expression

description: Ifilter together with lambda expression


code:
@csrf_exempt
def process(request):
   ...

rawDescription: Django POST request to my view from Pyres worker - CSRF token


code:
import re

import requests
from bs4 import BeautifulSoup

search = "Godfather"

token_pattern = re.compile(r'var token_key="(.*?)";')
with requests.Session() as session:  # maintaining web-scraping session
    session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    # extract token
    response = session.get("http://movietv.to/")
    soup = BeautifulSoup(response.content, "html.parser")

    script = soup.find("script", text=token_pattern).get_text()
    match = token_pattern.search(script)
    if not match:
        raise ValueError("Cannot find token!")

    token = match.group(1)

    # search for the movies
    response = session.post("http://movietv.to/index/loadmovies", data={
        "loadmovies": "showData",
        "page": "1",
        "abc": "All",
        "genres": "",
        "sortby": "Popularity",
        "quality": "All",
        "type": "movie",
        "q": search,
        "token": token
    })

    soup = BeautifulSoup(response.content, "html.parser")

    for movie in soup.select("div.item"):
        title = movie.find("h2", class_="movie-title")

        print(title.get_text())

rawDescription: Issue scraping dynamic content with mechanize


code:
if sys.version_info[0] <= 2:
    _call = '''\
def _call(self, *args, **kwargs):
    # [...]
    try:
        self.f(*args, **kwargs)
    except:
        t, v, tb = sys.exc_info()
        raise v, None, tb.tb_next
'''
    exec(_call)
else:
    def _call(self, *args, **kwargs):
        # [...]
        try:
            self.f(*args, **kwargs)
        except:
            t, v, tb = sys.exc_info()
            raise v.with_traceback(tb.tb_next)

class SneakyDecorator:
    def __init__(self, f):
        self.f = f

    __call__ = _call
    # niceties, patch up name and qualified name. Optional.
    __call__.__name__ = '__call__'
    __call__.__qualname__ = 'SneakyDecorator.__call__'

rawDescription: Python 2 and 3 compatible way of hiding a decorator from stacktrace


code:
P = dict(zip('a b c d'.split(),[1,2,3,4]))
E = dict(zip('a b e f'.split(),[6,7,8,9]))
set(P)-set(E)
set(E)-set(P)

rawDescription: How do I find the keys in one dictionary that do not have a counterpart in another dictionary?

description: Find the keys in one dictionary that do not have a counterpart in another dictionary


code:
import collections
myDict = collections.defaultdict(list)
myDict[myKey].append(value)

rawDescription: How can duplicate values be allowed in dictionary when using set


code: A, B = map(list, zip(*sorted(zip(A, B))))

rawDescription: Sort list B by the sort of list A?

description: Sort list B by the sort of list A


code:
int_array = np.r_[int_colors.ravel(), int_keys]
uniq, index = np.unique(int_array, return_inverse=True)
index
uniq

rawDescription: Convert a 3D array to 2D array based on dictionary


code:
transmap = str.maketrans(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ?!.-()<>%$',:_/\\",
    "ɐqɔpǝɟƃɥᴉɾʞ˥ɯuodbɹsʇnʌʍxʎz∀qƆpƎℲפHIſʞ˥WNOԀΌɹS┴∩ΛMX⅄Z0ƖᄅƐㄣϛ9ㄥ86 ¿¡˙-)(><%$,':‾\\/")

result = inputstring.translate(transmap)

rawDescription: How to replace every character from input? (python3.x)

description: Replace every character from input? (python3.x)


code:
from base64 import b64encode
from urllib.parse import urlencode
from urllib.request import Request, urlopen

user, password = 'foo', 'bar'
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
data = urlencode(dict(From='+17035551212', To='+17035551212',
                      Body='This is a test')).encode('ascii')
headers = {'Authorization': b'Basic ' +
        b64encode((user + ':' + password).encode('utf-8'))}
cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
response = urlopen(Request(url, data, headers), cafile=cafile)

print(response.info())
print(response.read().decode()) # assume utf-8 (likely for application/json)

rawDescription: Convert this curl cmd to Python 3

description: Convert this curl cmd to Python 3


code:
from datetime import datetime as dt
import time

def toYearFraction(date):
    def sinceEpoch(date): # returns seconds since epoch
        return time.mktime(date.timetuple())
    s = sinceEpoch

    year = date.year
    startOfThisYear = dt(year=year, month=1, day=1)
    startOfNextYear = dt(year=year+1, month=1, day=1)

    yearElapsed = s(date) - s(startOfThisYear)
    yearDuration = s(startOfNextYear) - s(startOfThisYear)
    fraction = yearElapsed/yearDuration

    return date.year + fraction

rawDescription: python how to convert datetime dates to decimal years

description: Python how to convert datetime dates to decimal years


code:
x
lognfit(x, ddof=1)

rawDescription: Fitting lognormal distribution using Scipy vs Matlab


rawDescription: Sorting a group of words inside a list

description: Sorting a group of words inside a list


code:
class Test2:
    def __init__(self, a):
        self.a = a
        self.b()
    def b(self, a):
        print('Running b of Test2')
        self.a.z()

rawDescription: Call method in a class which called the current class


code:
from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        select()
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            moveDown()
        elif key == 72: #Up arrow
            moveUp()

rawDescription: Python method for reading keypress?

description: Python method for reading keypress


code:
class A():
    def __init__(self, frozen, *args, **kwds):
        self.frozen = frozen
        self.args = args
        self.kwds = kwds

    def call(self):
        self.frozen(*self.args, **self.kwds)

rawDescription: <method-wrapper '__call__' of functools.partial object at 0x1356e10> is not a Python function


rawDescription: bottle.py URL routing & reverse howto?

description: Bottle.py URL routing & reverse howto


code: from __future__ import division

rawDescription: How do I generate a list like the one in the example using a non-inclusive range? (Python)

description: Generate a list like the one in the example using a non-inclusive range? (Python)


code: __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_url_as_char_ptr + idx1, idx2 - idx1)

rawDescription: Cython wrapper not fast enough, how to speed it up?


code:
import tkinter

root = tkinter.Tk(  )
root.title("My First Game")

tkinter.Label(root, text= '3', borderwidth=20 ).grid(row=1,column=1)
tkinter.Label(root, text= '6', borderwidth=20 ).grid(row=1,column=2)
tkinter.Label(root, text= '4', borderwidth=20 ).grid(row=1,column=3)
tkinter.Label(root, text= '2', borderwidth=20 ).grid(row=2,column=1)
tkinter.Label(root, text= '7', borderwidth=20 ).grid(row=2,column=2)
tkinter.Label(root, text= ' ', borderwidth=20 ).grid(row=2,column=3)
tkinter.Label(root, text= '5', borderwidth=20 ).grid(row=3,column=1)
tkinter.Label(root, text= '1', borderwidth=20 ).grid(row=3,column=2)
tkinter.Label(root, text= '8', borderwidth=20 ).grid(row=3,column=3)

def mainprg():

    tkinter.Label(root, text= '3', borderwidth=20 ).grid(row=1,column=1)
    tkinter.Label(root, text= '6', borderwidth=20 ).grid(row=1,column=2)
    tkinter.Label(root, text= ' ', borderwidth=20 ).grid(row=1,column=3)
    tkinter.Label(root, text= '2', borderwidth=20 ).grid(row=2,column=1)
    tkinter.Label(root, text= '7', borderwidth=20 ).grid(row=2,column=2)
    tkinter.Label(root, text= '4', borderwidth=20 ).grid(row=2,column=3)
    tkinter.Label(root, text= '5', borderwidth=20 ).grid(row=3,column=1)
    tkinter.Label(root, text= '1', borderwidth=20 ).grid(row=3,column=2)
    tkinter.Label(root, text= '8', borderwidth=20 ).grid(row=3,column=3)

    B.configure(command = mainprg1)

B = tkinter.Button(root, text = "Run", command = mainprg)
B.grid(row = 4, column = 1)

def mainprg1():
    tkinter.Label(root, text= '3', borderwidth=20 ).grid(row=1,column=1)
    tkinter.Label(root, text= ' ', borderwidth=20 ).grid(row=1,column=2)
    tkinter.Label(root, text= '6', borderwidth=20 ).grid(row=1,column=3)
    tkinter.Label(root, text= '2', borderwidth=20 ).grid(row=2,column=1)
    tkinter.Label(root, text= '7', borderwidth=20 ).grid(row=2,column=2)
    tkinter.Label(root, text= '4', borderwidth=20 ).grid(row=2,column=3)
    tkinter.Label(root, text= '5', borderwidth=20 ).grid(row=3,column=1)
    tkinter.Label(root, text= '1', borderwidth=20 ).grid(row=3,column=2)
    tkinter.Label(root, text= '8', borderwidth=20 ).grid(row=3,column=3)

    B.configure(command = mainprg)

root.mainloop()

rawDescription: display a series of interfaces using Tkinter in python

description: Display a series of interfaces using Tkinter in python


code:
# Class SMTPHandler...
def emit(self, record):
    """
    Emit a record.

    Format the record and send it to the specified addressees.
    """
    try:
        import smtplib
        from email.utils import formatdate
        port = self.mailport
        if not port:
            port = smtplib.SMTP_PORT
        smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)
        msg = self.format(record)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                        self.fromaddr,
                        ",".join(self.toaddrs),
                        self.getSubject(record),
                        formatdate(), msg)
        if self.username:
            if self.secure is not None:
                smtp.ehlo()
                smtp.starttls(*self.secure)
                smtp.ehlo()
            smtp.login(self.username, self.password)
        smtp.sendmail(self.fromaddr, self.toaddrs, msg)
        smtp.quit()
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        self.handleError(record)

description: Logging.handlers.SMTPHandler raises smtplib.SMTPAuthenticationError


rawDescription: Alternating sum of integers in Python using lambda


code: x = raw_input("Enter the full path + file name + file extension you wish to use: ")

rawDescription: Write strings to another file

description: Write strings to another file


code:
entering
exiting

rawDescription: Is there a meaningful way to use context managers inside generators?


code:
from collections import defaultdict

keep = ['P2', 'P4', 'G6']
tmp_dict = defaultdict(str)

# a function to handle formatting of output
def output_format(the_dict):
    return '\t'.join([the_dict[k].rstrip() for k in keep]) + '\n'

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    for line in infile:

        # if there's non-whitespace text on this line
        if line.strip():
            k, v = line.split(' : ')

            # store the data if the key is relevant,
            # appending if the key has already been hit
            if k in keep:
                tmp_dict[k] += v.rstrip() + ' '

        # when there's a blank line, write the data to
        # the output file and clear the temporary dict
        else:
            outfile.write(output_format(tmp_dict))
            tmp_dict = defaultdict(str)

    # one last time, in case file doesn't end in newline
    outfile.write(output_format(tmp_dict))

rawDescription: Python text file data extraction

description: Python text file data extraction


code:
from string import punctuation
from collections import Counter
def mwl(text):
    text = text.lower().translate(str.maketrans(" "*len(punctuation),punctuation))
    return Counter(text).most_common()[0][0]

rawDescription: Most Common letter in a string

description: Most Common letter in a string


code:
#PowerTreadFunction
def askPowerTread():
    choice = none
    while choice not in ['A','B','C']:
        print("Invalid choice.")
    choice = input("""Your Power Treads offer the following configurations which each                give distinct bonuses, choose now:\n
 a) DAMAGE\nb) DEFENSE\nc) ARMOR CLASS\n""")

rawDescription: Looking for help designing a While loop in Python


code:
for name in listname[len(listname)//2:]: # iterate on a slice from middle to end
    print(name)

for name in listname[len(listname)//2::-1]: # slice from the middle back to the start
    print(name)

rawDescription: How to loop over a list incrementally

description: Loop over a list incrementally


code: from __future__ import print_function

rawDescription: How do i overwrite the previous line?

description: Overwrite the previous line


code: searchfun(my_dict, my_queries)

rawDescription: Returning key of value found in dictionary using 'value in dict.values()'


code:
e = ast.parse('''a and b and c''').body[0].value
e.op
e.values

rawDescription: When has ast.BoolOp more than two values?


code: lambda x: x.replace("\\","")

rawDescription: BeautifulSoup doesn't read html within javascript with the right encoding


rawDescription: Unexpected output for numpy.arange with step size of 0.005


rawDescription: Fastest way to sorting a corpus dictionary into an OrderedDict - python


code: Jack Clubs

rawDescription: How to approach implementing 'class Card' as required by Python textbook

description: Approach implementing 'class Card' as required by Python textbook


code:
s = pca_obj.explained_variance_ratio_
sum=0.0
comp=0

for _ in s:
    sum += _
    comp += 1
    if(sum>=0.95):
        break

rawDescription: selecting optimum no of features using PCA/LDA/MDS in scikit

description: Selecting optimum no of features using PCA/LDA/MDS in scikit


code:
opts, args = parser.parse_args()

if len(args) != 1:

    sys.stderr.write("Error: one input ui-file must be specified\n")

    sys.exit(1)

sys.exit(invoke(Driver(opts, args[0])))

rawDescription: Qt Designer - Generate only one .ui file with several widgets


rawDescription: Сut zeros from the end of the list

description: Сut zeros from the end of the list


code:
school = None
headers = None
data = {}
for line in text.splitlines():
    if line.startswith("school id"):
        school = line.split('=')[1].strip()
        headers = None
        continue
    if school is not None and headers is None:
        headers = line.split('|')
        continue

    if school is not None and headers is not None and line:
        if not school in data:
            data[school] = []
        datum = dict(zip(headers, line.split('|')))
        data[school].append(datum)

rawDescription: How can I store data to a data dictionary in Python when headings are in mixed up order

description: Store data to a data dictionary in Python when headings are in mixed up order


code: map(f, iterable)

rawDescription: Understanding the map function

description: Understanding the map function


code:
colors = fields.Selection([
   ('red', 'Red'),
   ('green', 'Green'),
   ('blue', 'Blue'),
], 'Colors')

rawDescription: how fill Selection field in tryton

description: How fill Selection field in tryton


code:
df_event = df[mask]
df_event["event_id"] = evt_id[mask]

rawDescription: Filtering a panda dataframe based on value and time


code:
months_list = ["January", "February", "March", "April", "May", "June", "July"]

while True:
    answer = raw_input("Month? ")
    if any(item.lower() == answer.lower() for item in months_list): break
    print("Sorry, didn't recognize your answer, try again")

rawDescription: How to check if a variable matches any item in list using the any function?

description: Check if a variable matches any item in list using the any function


code:
mf = StringIO.StringIO()
with zipfile.ZipFile(mf, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
    zf.writestr('file1.txt', "hi")
    zf.writestr('file2.txt', "hi")

with open("C:/path/my_zip.zip", "wb") as f: # use `wb` mode
    f.write(mf.getvalue())

rawDescription: Python, write in memory zip to file

description: Python, write in memory zip to file


code:
from collections import Counter
from collections import namedtuple
Obj   = namedtuple('Obj', ['x', 'y'])
items = [Obj(1,1), Obj(1,2), Obj(1,3), Obj(1,3), Obj(1,3)]
y_counts = Counter(obj.y for obj in items)
[obj for obj in items if y_counts[obj.y] > 1]

rawDescription: Count with respect to a particular attribute


code: trimmed_text = text.strip()

rawDescription: Beautiful Soup [Python] and the extracting of text in a table


code:
def flatten(items):
    from itertools import chain
    def flatten_link(link):
        if isinstance(link, list):
            yield link[0]
            for item in flatten_link(link[1]):
                yield item
        elif link is not None:
            yield link
    return list(tuple(chain(item[:1], flatten_link(item[1]))) for item in items)

a = [
    ('Maria', [1, [2, {'teste': (2, 1.0)}]]),
    ('Lisa ', [2, [4, {'field': (4, 0.75), 'bola': (4, 0.25)}]]),
    ('John ', [4, [5, {'engine': (5, 0.2), 'wheel': (5, 0.4), 'wheels': (5, 0.2)}]]),
    ('Tracy', [4, [6, {'pizza': (6, 0.16), 'fish': (6, 0.1), 'animals': (6, 0.1)}]]),
]
print(flatten(a))

rawDescription: Flattening a complex list of tuples

description: Flattening a complex list of tuples


code:
import re
import collections, json

status = """
Object train {
Name electric_train;
From Seattle;
To Tacoma;
Distance 100;
Configuration train_travel;
}

Object car {
Name honda;
From Richland;
To Seattle;
Distance 160;
Configuration road_travel;
}

Object bus {
Name greyhound;
From pasco;
To richland;
Distance 15;
Configuration road_travel;
}

Object aeroplane {
Name united;
From miami_airport;
To pasco;
Distance 1000;
Configuration air_travel;
}

Object train {
Name gas_train;
From beach;
To miami_airport;
Distance 30;
Configuration train_travel;
}

Object car {
Name toyota;
From apartment;
To beach;
Distance 14;
Configuration road_travel;
}
"""

def Status2dict(status):
    # Keeps track of how many times each Object has been seen already
    keys_count = {}

    result = {}
    current = {}
    lines = status.splitlines()

    for line in lines:
        line = line.strip()
        if not line:
            continue
        mo = re.match(r'Object (\w+) {', line)
        if mo:
            curk = mo.group(1)

            # If Object has not been seen before, start tracking it
            if not curk in keys_count:
                keys_count[curk] = 1

            # Get the current counter value, which we will append
            # to the Object name (e.g. car_<counter>)
            curk_counter = str(keys_count[curk])

            # Increment our running count for this Object
            keys_count[curk] += 1

            # Rewrite the Object name to have the counter now
            curk = curk + '_' + curk_counter

            # Use OD to maintain order of the fields (As requested)
            current = {curk: collections.OrderedDict()}
        elif re.match('}', line):
            result.update(current)
            current = {}
        else:
            mo = re.match(r'(\w+)\s+([\w\s]+);', line)
            if not mo:
                raise ValueError('cannot match {!r}'.format(line))
            current[curk][mo.group(1)] = mo.group(2)
    if current:
        result.update(current)
    return result

print(json.dumps(Status2dict(status), indent=2))

rawDescription: dictionary keys in JSON output is overwritten: how to index each uniquely? how to make sure the values format not changed?

description: Dictionary keys in JSON output is overwritten: how to index each uniquely? how to make sure the values format not changed


code:
import requests
from bs4 import BeautifulSoup

s = requests.Session()

login_data = {'email':'me@example.com', 'password':'pw'}
s.post("http://forum.bazicenter.com/login", login_data)

result = s.get("http://forum.bazicenter.com/members/59765/").text
soup = BeautifulSoup(result)

rawDescription: Crawling a members-only page with BeautifulSoup


code: {{ form.as_table_with_label_classes }}

rawDescription: Add class to Django label_tag() output

description: Add class to Django label_tag() output


code:
u = np.linspace(-1, 2, 60)
v = np.linspace(0, 2*np.pi, 60)

rawDescription: Ploting solid of revolution in Python 3 (matplotlib maybe)


rawDescription: How to get one number specific times in an array python

description: Get one number specific times in an array python


code: truth = word.startswith(('^','@'))

rawDescription: Is there a one line way of saying this?

description: Is there a one line way of saying this


code:
class Beta(Alpha):
    def fie(self):
        super(Beta, self).fie()

rawDescription: Python inheritance - referring to specific levels


rawDescription: Numpy: Multiple Outer Products

description: Numpy: Multiple Outer Products


code:
boatID = [342, 343, 344, 345, 346]
i = 0
while i < len(boatID):
    df1 = df[(df['boat_id']==boatID[i])]
    #run some code, i'm printing DF.head to test it works
    print(df1.head())
    i = i + 1

#   boat_id  activity  speed  heading
#0      342         1   3.34      270
#   boat_id  activity  speed  heading
#1      343         1   0.02        0
#   boat_id  activity  speed  heading
#2      344         1   0.01      270
#   boat_id  activity  speed  heading
#3      345         1   8.41   293.36
#   boat_id  activity  speed  heading
#4      346         1   0.03       90

rawDescription: Filter Pandas DataFrame using a while loop


code:
for g in Game.objects.all():
    ...

rawDescription: Django: Saving old QuerySet for future comparison


code:
import csv
writer = csv.writer(filename)
writer.writerows(data)

rawDescription: Suggestions for passing large table between Python and C#


rawDescription: A list contains another list with repetition


code:
car1 = Car('foo', 'bar', 23)
car2 = Car('baz', 'bar', 34)
car3 = Car('baz', 'bar', 14)
car_list = [car1, car2, car3]

car_list.sort(key=lambda c: c.hp)

rawDescription: Python collections of non-base type?

description: Python collections of non-base type


code:
if box_plot:
    plt.subplot(1, 2, 1)
    plt.boxplot(data.data)
    plt.subplot(1, 2, 2)

rawDescription: Matplotlib boxplot + imageshow (subplots)


code:
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
    content = fp.read()

date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
    do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
    content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )

p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
    fp.write(content)

rawDescription: Change Date Format In Python

description: Change Date Format In Python


code:
from collections import Counter
s = "abdicator"
Counter(s)
map(Counter(s).__getitem__, map(chr, range(ord('a'), ord('z')+1)))

rawDescription: Match letter frequency within a word against 26 letters in R (or python)


code:
def g(i):
    return f(i, 20)

rawDescription: Python multiprocessing a function with several inputs


rawDescription: Sklearn - How to add custom stopword list from txt file


code:
import subprocess
output = subprocess.check_output('sudo -u myuser crontab -l', shell=True)

rawDescription: Using pexpect to get output of 'ls' command


rawDescription: Python regex to parse semi-fixed width file


code: debug(slow_processing, 1)

rawDescription: Options to avoid executing code on __debug__


code: conf.env['VERSION'] = '0.7.0'

rawDescription: Waf: How to output a generated file?

description: Waf: How to output a generated file


code:
'001 abcdef 001'.split(None, 1)[1]
'abcdef 001'.split(None, 1)[1]

rawDescription: Different cut method python 2.6 to 2.7

description: Different cut method python 2.6 to 2.7


rawDescription: Python access to first element in dictionary


code:
import argparse
class Once(argparse.Action):
    def __call__(self, parser, namespace, values, option_string = None):
        # print '{n} {v} {o}'.format(n = namespace, v = values, o = option_string)
        if getattr(namespace, self.dest) is not None:
            msg = '{o} can only be specified once'.format(o = option_string)
            raise argparse.ArgumentError(None, msg)
        setattr(namespace, self.dest, values)

cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-o', dest='outfile', action=Once)
cmd_line = cmd_parser.parse_args()
print(cmd_line.outfile)

rawDescription: Only one command line argument with argparse


code:
from collections import defaultdict
d = defaultdict(int)
d
d.default_factory
d = defaultdict(list)
d.default_factory

rawDescription: How to obtain the type of the values in a defaultdict

description: Obtain the type of the values in a defaultdict


code:
def dec(input_, output_):
    if type(input_) is list:
        for subitem in input_:
            dec(subitem, output_)
    else:
        output_.append(input_)

rawDescription: Decompose list of lists into single list with non-iterable list elements


code:
current = repo.active_branch
current

rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code:
x_min, x_max = ax.get_xlim()
x_0 = x_min
x_1 = x_max

rawDescription: Adding a line to a matplotlib scatterplot based on a slope


code:
class Operator:
    def __init__ (self, argc, f):
        self.argc = argc
        self.f = f

    def __call__ (self, *args):
        return self.f (*args)

rawDescription: recursively computing expression python

description: Recursively computing expression python


rawDescription: check for existence and active state in django filter

description: Check for existence and active state in django filter


code: solve(y - 0.1222*x**0.8628, x, rational=False)

rawDescription: How to quickly invert a power function in Sympy

description: Quickly invert a power function in Sympy


code:
import Tkinter as tk
from Tkinter import *
import database

root = Tk()
root.geometry("800x600+0+0")

bluetooth = database.Bluetooth()

button1 = tk.Button(text="Get Name", height=10, width=10, command=bluetooth.text_field)#Entry
button1.pack()

def my_function(entry, output):
    #print entry()
    output( entry() ) # bluetooth.connect( bluetooth.retrieve_input() )

button = tk.Button(text="Connect", height=10, width=10, command=lambda:my_function(bluetooth.retrieve_input, bluetooth.connect))#bluetooth test
button.pack()

root.mainloop()

rawDescription: Replacing a string with text from Entry box


code:
def foo(): pass

foo.__name__
foo.__name__ = '<lambda>'
foo.__name__
foo

rawDescription: What is islambda function in python

description: What is islambda function in python


code:
from collections import Counter
from itertools import chain
Counter(chain.from_iterable(d.itervalues()))

rawDescription: Count items in defaultdict

description: Count items in defaultdict


code:
import threading

class _State(threading.local):
    """State keeps track of request info"""
    user = None

_state = _State()

rawDescription: Store objects at "request scope" in google app engine


code:
from math import cos

def myfunc():
    """ documentation"""
    pass

rawDescription: Using pydoc on modules with imported functions


code: any([item in A_list for item in B_list])

rawDescription: How to judge a list and list have the same value

description: Judge a list and list have the same value


rawDescription: How to use sprite groups in pygame

description: Use sprite groups in pygame


code:
def skip_last(iterator):
    prev = next(iterator)
    for item in iterator:
        yield prev
        prev = item

rawDescription: Skip the last row of CSV file when iterating in Python


code:
items = ['a11', 'a2']
sorted(items)

rawDescription: How to do a "Filing cabinet" sort on alphanumeric strings

description: Do a "Filing cabinet" sort on alphanumeric strings


code:
import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a

rawDescription: How to add an extra column to an numpy array

description: Add an extra column to an numpy array


code: servqual != "great" and servqual != "good" and servqual != "lacking" and servqual != "poor"

rawDescription: Python: Repeating a function when raw_input is not valid


code:
from Tkinter import *

root = Tk()
frame = Frame(root)
frame.configure(width=300,height=300)

def onmotion(event):
    root.title("Mouse at %s,%s"%(event.x, event.y))

frame.bind("<Motion>", onmotion)
frame.pack()
root.title("Event test")
root.mainloop()

rawDescription: How to access external object within event handler?

description: Access external object within event handler


code:
import os
BASE_DIR = os.path.dirname(os.path.realpath(__file__))

rawDescription: Python: Check if data file exists relative to source code file


code:
d = {'secondly': 2, 'pardon': 6, 'saves': 1, 'knelt': 1}
a = sorted(d.iteritems(), key=lambda x:x[1], reverse=True)

rawDescription: Search and sort through dictionary in Python


code: yield request

rawDescription: How to call Parse_page2 method for every item

description: Call Parse_page2 method for every item


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', '-b',  help='do something')

parser.parse_args(['--help'])

rawDescription: How to use argsparse so the script options with the same affect will appear in the same 'help' line

description: Use argsparse so the script options with the same affect will appear in the same 'help' line


rawDescription: write csv row (from within for loop) out to csv file without using python csv module

description: Write csv row (from within for loop) out to csv file without using python csv module


code:
setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("example", sourcefiles), Extension("example2", sourcefiles2), Extension("example3", sourcefiles3)]
)

rawDescription: How to compile and link multiple python modules (or packages) using cython?

description: Compile and link multiple python modules (or packages) using cython


code:
import json

with open('data.json') as f:
    data = json.load(f)

rawDescription: Python Dictionary Stored as String in List


code: home, away = map(int, re.findall(r'\d+', lp))

rawDescription: Most Pyhthonic way to convert element of list get with re


rawDescription: How can I capture return value with Python timeit module?

description: Capture return value with Python timeit module


code: [list(elem) for elem in product([1, 0], repeat =2)]

rawDescription: How to generate list combinations in Python

description: Generate list combinations in Python


code:
def agent_loc(a_maze):
    coor_list = str()
    for row, i in enumerate(a_maze):
         for column, j in enumerate(i):
             if j == "E":
                 coor_list = coor_list + str(row) + ";" + str(column) + "|"
    print(coor_list)

rawDescription: (Python) Index stops after finding one element in the row


rawDescription: How to make List from Numpy Matrix in Python

description: Make List from Numpy Matrix in Python


code:
DEVSERVER_MODULES = (
    'devserver.modules.sql.SQLRealTimeModule',
    'devserver.modules.sql.SQLSummaryModule',
    'devserver.modules.profile.ProfileSummaryModule',

    # Modules not enabled by default
    'devserver.modules.ajax.AjaxDumpModule',
    #'devserver.modules.profile.MemoryUseModule',
    'devserver.modules.cache.CacheSummaryModule',
    #'devserver.modules.profile.LineProfilerModule',
)

rawDescription: Django. Business Logic Bottlenecks.

description: Django. Business Logic Bottlenecks.


rawDescription: Matplotlib: Saved files in a loop aren't the same as in show()


code:
def decipher(s):
    options = [[rot(c, n) for c in s] for n in range(26)]
    best_option = max(options, key=lambda x: sum(map(letter_prob, x)))
    return ''.join(best_option)

rawDescription: Deciphering My Cipher: Python Wizardry

description: Deciphering My Cipher: Python Wizardry


code:
xx1, xx2 = np.meshgrid(np.arange(3), np.arange(2))
coord1, coord2 = xx1.ravel(), xx2.ravel()
coord1
coord2
coord1, coord2 = zip(*itertools.product(np.arange(3), np.arange(2)))
coord1
coord2

rawDescription: Scikit-learn and data visusalisation: Why do I have to use ravel when I use predict?


code:
def main():
    tsvfile_input = sys.argv[1]
    data = csv.reader(open(tsvfile_input), delimiter = '\t')
    for index, row in enumerate(data):
        print('Row %d: %f' % (index + 1, sum(float(num) for num in row)))

rawDescription: return index for rows in csv module python

description: Return index for rows in csv module python


code:
def function1(self, x, y):
    function2 = lambda y: doSomethingWithY(y)
    localVar = 'a local variable'

rawDescription: Python Inheritance with closures

description: Python Inheritance with closures


code:
from app.forms import AppForm
AppForm.base_fields['fieldname'].initial="your default value"

rawDescription: Form interceptor, populate a form field without touching the original application


code: not m.mask.all()

rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


code:
sq_reviews = db_session.query(CookbookReview.cookbook_id,
    func.avg(CookbookReview.rating).label('rating'),\
    func.count('*').label('review_count')).\
    group_by(CookbookReview.cookbook_id).subquery()

object_list = db_session.query(
    Cookbook, sq_reviews.c.rating, sq_reviews.c.review_count).\
    outerjoin(sq_reviews, Cookbook.id==sq_reviews.c.cookbook_id).\
    order_by(Cookbook.name).limit(20)

rawDescription: SQLAlchemy conversion of Django annotate


rawDescription: Break out of double while loops?

description: Break out of double while loops


code:
import numpy as np
import pandas as pd

df = pd.DataFrame({'Location': ['Canada', 'Canada', 'Canada', 'Canada', 'US', 'US', 'Canada', 'Canada', 'US', 'US'], 'Payment': ['CreditC', 'Cash', 'Cash', 'Cash', 'Cash', 'CreditC', 'CreditC', 'Cash', 'CreditC', 'Cash'], 'Time': ['10:03:18', '10:08:38', '10:24:46', '11:16:35', '10:00:16', '11:52:12', '2:08:38', '4:01:48', '13:32:02', '14:07:03'], 'item': ['X', 'X', 'X', 'X', 'X', 'X', 'Y', 'Y', 'Y', 'Y']})

df['start'] = pd.to_datetime(df['Time'])
grouped = df.groupby(['item', 'Location'])
interval = 60
df['end'] = (grouped['start'].transform(lambda grp: grp.min()+pd.Timedelta(minutes=interval)))

# isolate just the rows where the transaction occurs within an hour of first sale
df2 = df.loc[(df['start'] < df['end'])]
result = pd.crosstab(index=[df2['item'], df2['Location']], columns=[df2['Payment']])
result['count'] = result['Cash'] + result['CreditC']
result['first sale'] = grouped['Time'].first()

rawDescription: How to sumarize flattables using Python

description: Sumarize flattables using Python


code:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Read in data from an ASCII data table
data = np.genfromtxt('data.txt')

ax.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
#ax.imshow(data, cmap=plt.cm.gray)
ax.set_title('My Title')
plt.show()

rawDescription: Gnuplot command to matplotlib

description: Gnuplot command to matplotlib


code:
inputstring = "hiسلامaliعلی"
re.split(r'([a-zA-Z]+)', inputstring)

rawDescription: python split string into strings with same language characters

description: Python split string into strings with same language characters


code:
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
        self.setWindowOpacity(.9)
        text_widget = text(self)
        self.setCentralWidget(text_widget)
        self.setStyleSheet("QMainWindow { background: 'black'}");

class text(QtGui.QWidget):
    def __init__(self, parent=None):
        super(text, self).__init__(parent)
        self.label1 = QtGui.QLabel('Welcome', self)
        self.label1.move(100, 10)
        self.label1.setStyleSheet("QLabel { color : red; font-size: 28px; }")

rawDescription: PyQt - Widget in QtGui.QtMainWindow

description: PyQt - Widget in QtGui.QtMainWindow


code:
sorted_groceries = {
    store1 : [item1, item2],
    store2 : [item3, item4],
}

rawDescription: Pattern to organize related items into groups


rawDescription: Django form as_table(), as_p() methods not working


code:
from cPickle import dump, load
import os

if os.path.exists('metadata.cache'):
    metadata = load(open('metadata.cache'))
    metadata.bind = create_engine(database_url)
else:
    metadata = MetaData(create_engine(database_url), reflect=True)
    dump(metadata, open('metadata.cache', 'w'))

rawDescription: Entity Framwework-like ORM NOT for .NET

description: Entity Framwework-like ORM NOT for .NET


code:
for a in ax:
    # get all the labels of this axis
    labels = ax.get_yticklabels()
    # remove the first and the last labels
    labels[0] = labels[-1] = ""
    # set these new labels
    a.set_yticklabels(labels)

rawDescription: Remove first and last ticks label of each y-axis subplot