code:
class defaultlist(list):
    def __init__(self, fx):
        self._fx = fx

    def __setitem__(self, index, value):
        while len(self) <= index:
            self.append(self._fx())
        list.__setitem__(self, index, value)

rawDescription: defaultdict equivalent for lists

description: Defaultdict equivalent for lists


code:
[c.isdigit() or c == '/' for c in match]
[c.isdigit() or c == '/' for c in no_match]

rawDescription: How to I check that a string contains only digits and / in python?


code: print(sorted(([ele[0],sum((ele[1:])) /  len(l) - 1] for ele in l),key=itemgetter(1),reverse=True))

rawDescription: Sort tuple by averages

description: Sort tuple by averages


code:
life = dotdictify({'bigBang': {'stars': {'planets': {}}}})
life.bigBang.stars.planets
life.bigBang.stars.planets.earth = { 'singleCellLife' : {} }
life.bigBang.stars.planets
life['bigBang.stars.planets.mars.landers.vikings'] = 2
life.bigBang.stars.planets.mars.landers.vikings
'landers.vikings' in life.bigBang.stars.planets.mars
life.get('bigBang.stars.planets.mars.landers.spirit', True)
life.setdefault('bigBang.stars.planets.mars.landers.opportunity', True)
'landers.opportunity' in life.bigBang.stars.planets.mars
life.bigBang.stars.planets.mars

rawDescription: Python: Easily access deeply nested dict (get and set)


code:
from flask import Flask, Blueprint, render_template

# ADMIN
admin = Blueprint('admin', __name__, url_prefix='/admin')

@admin.route('/')
def admin_index():
    return 'Admin module'

@admin.route('/settings')
def settings():
    return 'Admin Settings'

# USER
user = Blueprint('user', __name__, url_prefix='/user')

@user.route('/')
def user_index():
    return 'User module'

@user.route('/profile')
def profile():
    return 'User Profile'

app = Flask(__name__)
app.register_blueprint(admin)
app.register_blueprint(user)

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

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=7000)

rawDescription: Flask Blueprint Initialization - Initializing some global variables


code:
from datetime import datetime
from flask import Flask, redirect, current_app
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.menu import MenuLink
from flask.ext.security import (
    current_user,
    url_for_security,
    UserMixin,
    RoleMixin,
    SQLAlchemyUserDatastore,
    Security
)
from flask.ext.security.utils import encrypt_password
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SECURITY_PASSWORD_HASH'] = 'pbkdf2_sha512'
app.config['SECURITY_PASSWORD_SALT'] = '16a0af319890f662055ba10aecff37e7e033db3fba737e55'
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'email'

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

class Role(db.Model, RoleMixin):
    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(length=64), unique=True)
    description = db.Column(db.Unicode(length=255), nullable=True)

    def __unicode__(self):
        return u"{name} ({role})".format(name=self.name, role=self.description or 'Role')

user_to_role = db.Table('user_to_role',
    db.Column('user_id', db.Integer(), db.ForeignKey('users.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('roles.id')))

class User(db.Model, UserMixin):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)

    first_name = db.Column(db.Unicode(length=255), nullable=False)
    last_name = db.Column(db.Unicode(length=255), nullable=False)

    email = db.Column(db.Unicode(length=254), unique=True, nullable=True)
    password = db.Column(db.Unicode(length=255), nullable=False)
    active = db.Column(db.Boolean(), default=False)

    roles = db.relationship('Role', secondary=user_to_role, backref=db.backref('users', lazy='select'))

    def __unicode__(self):
        return u"{first_name} ({last_name})".format(first_name=self.first_name, last_name=self.last_name)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    content = db.Column(db.Text, nullable=False)

    def __unicode__(self):
        return self.title

def get_current_user():
    from flask.ext.security import current_user
    try:
        return User.objects.get(id=current_user.id)
    except Exception as e:
        # logger.warning("No user found: %s", str(e))
        return current_user

def is_accessible(roles_accepted=None, user=None):
    user = user or get_current_user()
    # uncomment if "admin" has access to everything
    # if user.has_role('admin'):
    #     return True
    if roles_accepted:
        accessible = any(
            [user.has_role(role) for role in roles_accepted]
        )
        return accessible
    return True

class Roled(object):

    def is_accessible(self):
        roles_accepted = getattr(self, 'roles_accepted', None)
        return is_accessible(roles_accepted=roles_accepted, user=current_user)

    def _handle_view(self, name, *args, **kwargs):
        if not current_user.is_authenticated():
            return redirect(url_for_security('login', next="/admin"))
        if not self.is_accessible():
            # return self.render("admin/denied.html")
            return "
Access denied
"

class AdminView(Roled, ModelView):

    def __init__(self, *args, **kwargs):
        self.roles_accepted = kwargs.pop('roles_accepted', list())
        super(AdminView, self).__init__(*args, **kwargs)

class UserView(AdminView):
    form_excluded_columns = ('password')

class RoleView(AdminView):
    pass

class PostView(AdminView):
    pass

# Setup Flask-Security
security = Security(app, SQLAlchemyUserDatastore(db, User, Role))

@app.route('/')
def index():
    _login = url_for_security('login', next="/admin")
    _logout = url_for_security('logout', next="/admin")
    return '''
        Click me to get to Admin!

        Click me to get to login!

        Click me to get to logout!
        '''.format(login=_login, logout=_logout)

# Create admin
admin = Admin(app, name='Admin')
admin.add_view(UserView(model=User, session=db.session, category='Account', name='Users', roles_accepted=['admin']))
admin.add_view(RoleView(model=Role, session=db.session, category='Account', name='Roles', roles_accepted=['admin']))
admin.add_view(PostView(model=Post, session=db.session, category='Blog', name='Posts (Editor Only)', roles_accepted=['editor']))
admin.add_view(PostView(model=Post, session=db.session, category='Blog', name='Posts (Admins & Editors)', endpoint="post_special", roles_accepted=['editor', 'admin']))
admin.add_link(MenuLink(name='Public Website', category='', url='/'))

def build_db():
    users = [
        {
            'first_name': 'Super',
            'last_name': 'User',
            'email': 'admin@example.com',
            'active': True,
            'password' : encrypt_password('password'),
            'roles': ['admin']
        },
        {
            'first_name': u'Post',
            'last_name': u'Editor',
            'email': 'editor@example.com',
            'active': True,
            'password': encrypt_password('password'),
            'roles': ['editor']
        },

    ]

    posts = [
        {
            'title': "de Finibus Bonorum et Malorum - Part I",
            'content': "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"
        },
        {
            'title': "de Finibus Bonorum et Malorum - Part II",
            'content': "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque"
        },
        {
            'title': "de Finibus Bonorum et Malorum - Part III",
            'content': "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium"
        }
    ]

    db.drop_all()
    db.create_all()

    security = current_app.extensions.get('security')

    security.datastore.create_role(name=u"admin", description=u'Administers the system')
    security.datastore.create_role(name=u"editor", description=u'Can edit posts')

    for user in users:
        roles = user.pop('roles')
        user_db = security.datastore.create_user(**user)
        for role_name in roles:
            role_from_db = security.datastore.find_role(role_name)
            security.datastore.add_role_to_user(user_db, role_from_db)
        security.datastore.activate_user(user_db)
        user_db.confirmed_at = datetime.now()

    security.datastore.commit()

    for row in posts:
        post = Post(**row)
        db.session.add(post)

    db.session.commit()

@app.before_first_request
def create_user():
    build_db()

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: flask-admin is_accessible usage

description: Flask-admin is_accessible usage


rawDescription: Slicing and if statements (Python)

description: Slicing and if statements (Python)


code:
r = {
    'coh':   lambda: (my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)),
    'imcoh': lambda: (my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)),
    'cohy':  lambda: (my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)),
    'plv':   lambda: (my_plv(n_freqs, Rxy, Rxy_mean), my_plv(n_freqs, Rxy_s, Rxy_s_mean)),
    'pli':   lambda: (my_pli(n_freqs, Rxy, Rxy_mean), my_pli(n_freqs, Rxy_s, Rxy_s_mean)),
    'wpli':  lambda: (my_wpli(n_freqs, Rxy, Rxy_mean), my_wpli(n_freqs, Rxy_s, Rxy_s_mean)),
    }
return r[con_name]() + (freqs, freqs_surro)

rawDescription: Compromising Python if statement

description: Compromising Python if statement


rawDescription: Difficulty comparing generated and google cloud storage provided CRC32c checksums


code:
dlist=[]
for x, y in zip(list1, list2):
    d={'name': x.name, 'age': x.age, 'gender': y.gender}
    dlist.append(d)

rawDescription: Same output for a list in django

description: Same output for a list in django


code:
def print_range(start, stop, ncolumns, width=6):
    for i in range(start, stop, ncolumns):
        print(' '.join(['{:{}d}'.format(j, width)
                        for j in range(i, min(i + ncolumns, stop))]))

rawDescription: Can I format n numbers in Python

description: Format n numbers in Python


code:
lines = []
for key in self.cases.keys():
    a = key, self.cases[key].color, self.cases[key].thetype
    lines.append(str(a) + "\n")
return ''.join(lines)

rawDescription: how to return the iterations over keys as a string?

description: Return the iterations over keys as a string


code:
def sum_of_factors(x):
  return sum([n for n in xrange(1,x) if x % n == 0])

rawDescription: sum of factors of a given number

description: Sum of factors of a given number


code:
parser = argparse.ArgumentParser(description='details',
        usage='use "%(prog)s --help" for more information',
        formatter_class=argparse.RawTextHelpFormatter)

rawDescription: Multiple lines in python argparse help display


rawDescription: Pandas getting average of selected column


code:
hours = int(hours)
minutes = int(minutes)

rawDescription: 24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python


code: mylist = list(set(mylist))

rawDescription: Deleting repeats in a list python

description: Deleting repeats in a list python


code:
today = dt.today()
todays_midnigh = dt.combine(today,dt.max.time())

rawDescription: Django quering objects with timestamp delta


code:
my_list = ["This", "is", "an", "example", "list", "hehe"]
counter = 3
zip(*[iter(my_list)] * counter)

rawDescription: Getting every X word from list

description: Getting every X word from list


rawDescription: Limiting print output

description: Limiting print output


rawDescription: If path is symlink to another path

description: If path is symlink to another path


code:
def cvt_MIdx_tcklab(df):
    Midx_ar=np.array(df.index.tolist())
    Blank_ar=Midx_ar.copy()
    col_idx=np.arange(Midx_ar.shape[0])
    for i in range(Midx_ar.shape[1]):
        val,idx=np.unique(Midx_ar[:,i], return_index=True)
        Blank_ar[idx, i]=val
        idx=~np.in1d(col_idx, idx)
        Blank_ar[idx, i]=''
    return map('\n'.join, np.fliplr(Blank_ar))

plt.figure()
ax=plt.gca()
DF.plot(kind='bar', ax=ax)
ax.set_xticklabels(cvt_MIdx_tcklab(DF),rotation=0)

rawDescription: Group labels in matplotlib barchart using Pandas MultiIndex


code:
import re

def rename_file(filename):
  if filename.startswith('EPG') and ' ' in filename:
    # \s+       means 1 or more whitespace characters
    # [0-9]{2}  means exactly 2 characters of 0 through 9
    # \.        means find a '.' character
    # [0-9]{4}  means exactly 4 characters of 0 through 9
    newfilename = re.sub("\s+[0-9]{2}\.[0-9]{4}", '', filename)
    newfilename = newfilename.replace(" ","_")
    os.rename(filename, newfilename)

rawDescription: Python Regex or Filename Function

description: Python Regex or Filename Function


code:
import sh
output = sh.tail(sh.cat('file.log'), '-1')

rawDescription: Call a shell command containing a 'pipe' from Python and capture STDOUT


code:
binary = 'binaryfile.png'
data2d = np.fromfile(binary, count=10*10, dtype='int16').reshape(10, 10).astype('double')

rawDescription: Reading binary file in two dimension

description: Reading binary file in two dimension


code: df

rawDescription: Python: select most frequent using group by


code: next_configuration([5, 1, 3, 2])

rawDescription: Simple solitaire

description: Simple solitaire


code:
weightlist = [d for d in data]
weightlist.sort(key=lambda x: x[1])
weightlist

rawDescription: Doubly Linked list in Python

description: Doubly Linked list in Python


rawDescription: Add to custom class in Python

description: Add to custom class in Python


rawDescription: How to split string into collumn

description: Split string into collumn


code: num_for_loops = sum(line.strip().startswith("for ") for line in lines)

rawDescription: Combining for and if loops

description: Combining for and if loops


code: db = client["db_name"] #replace db_name with your database name

rawDescription: How do I construct a variable query with pymongo

description: Construct a variable query with pymongo


code: {{ wtf.quick_form(form, action=url_for("blueprint_name.fancy_url")) }}

rawDescription: Flask WTF – Forms always redirect to root


code:
class TestModelForm(ModelForm):
    class Meta:
        model = TestModel
        widgets = {
            'ref1': forms.HiddenInput(),
        }

rawDescription: How to hide a field in django modelform?

description: Hide a field in django modelform


code: tr_response = ftp.retrbinary('RETR README', open('README', 'wb').write)

rawDescription: ftplib capture and process ftp server response code

description: Ftplib capture and process ftp server response code


code:
class Master(SomeOtherClass):
    __flag = True

class Child(Master):
    pass

rawDescription: How to add attribute to python *class* that is _not_ inherited?

description: Add attribute to python *class* that is _not_ inherited


rawDescription: Quick comparison of numpy array elements, greater or less than each other


code: templates_path = ["templates"]

rawDescription: Adding a javascript script tag some place so that it works for every file in sphinx documentation


rawDescription: Python convert html tags in ampersand format


code: any(i >= size and results[i - size] for size in pen_sizes)

rawDescription: Find if a number is a possible sum of two or more numbers in a given set - python


rawDescription: .gz file to pandas DataFrame with hive delimiter


code:
def f2():
    x,y = f1()
    return 1, x, y

rawDescription: Python: easiest way to flatten a tupple containing another tupple from a function


code:
# Generate same data as Jianxun Li
np.random.seed(0)
df = pd.DataFrame(np.random.randint(50,100,(20,3)), columns=['tally', 'costs', 'other'])
df.costs = df.costs * 5

width = .3

df.tally.plot(kind='bar', color='#55A868', position=1, width=width, legend=True, figsize=(12,6))
df.costs.plot(kind='bar', color='#4C72B0', position=0, width=width, legend=True, secondary_y=True)

plt.show();

rawDescription: Creating legend in matplotlib after plotting two Pandas Series


code:
{k: {l.strip(): [n.strip() for n in nums.split(',')]
     for i in v.split(';')
     for l, nums in (i.split(':', 1),)}
 for k, v in tuplist}
def language_values(line):
    for entry in line.split(';'):
        lang, nums = entry.split(':', 1)
        yield lang.strip(), [n.strip() for n in nums.split(',')]

{k: dict(language_values(v)) for k, v in tuplist}

rawDescription: How to convert this tuple list to this dict in a Pythonic way?

description: Convert this tuple list to this dict in a Pythonic way


code:
country = session.query(Country).filter_by(name='Spain').one()
new_user = User(name='Johnny', country_id=country.id)

rawDescription: SQLAlchemy ORM Insertion based on related object


code:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

class BookmyshowSpider(CrawlSpider):
    name = "bookmyshow"
    start_urls = ['https://in.bookmyshow.com/movies']
    allowed_domains = ['bookmyshow.com']
    rules = (Rule(SgmlLinkExtractor(allow=('https://in\.bookmyshow\.com/movies/.*', )), callback="parse_items", follow= True),)

    def parse_items(self, response):
        for sel in response.xpath('//div[contains(@class, "movie-card")]'):
            item = Ex1Item()
            item['Moviename'] = sel.xpath('.//a[@class="__movie-name"]/text()').extract()
            item['Language'] = sel.xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/section[1]/div/div[2]/div[1]/div[1]/div/div/div[2]/div[2]/ul/li/text()').extract()
            item['Info'] = sel.xpath('.//div[@class="__rounded-box __genre"]/text()').extract()
            item['Synopsis'] = sel.xpath('/html/body/div[1]/div[2]/div[1]/div[2]/div[4]/div[2]/div[2]/blockquote/text()').extract()
            item['Release'] = sel.xpath('.//span[@class="__release-date"]/text()').extract()
            yield item

rawDescription: Getting data from multiple links using scrapy


code:
browser.select_form(nr=1)

choices=[item.attrs['value'] for item in browser.form.controls[-2].items]
print(choices)
# ['1576', '1581', '1594', '1595', '1596', '1598', '1597', '1593']

browser.form['name_ser']=['1576']
browser.submit()

browser.select_form(nr=2)

choices=[item.attrs['value'] for item in browser.form.controls[-2].items]
print(choices)
# ['32', '33', '34', '35', '36', '37', '38', '39', '40', '41']

browser.form['data_kind']=['33']
browser.submit()

browser.select_form(nr=3)
browser.form['ybegin']=['2010']
browser.form['mbegin']=['1']
browser.form['yend']=['2011']
browser.form['mend']=['5']
browser.submit()

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code:
def quote(col):
    if col is None:
        return ''
    # uses double-quoting style to escape existing quotes
    return '"{}"'.format(str(col).replace('"', '""'))

writer = csv.writer(fileobj, quoting=csv.QUOTE_NONE, escapechar='', quotechar='')

for row in rows:
    writer.writerow(map(quote, row))

rawDescription: csv writer in Python with custom quoting

description: Csv writer in Python with custom quoting


code:
def buildcomp(vvhh):
    vv, hh = vvhh
    return numpy.min((vv-precomp[...,0])**2+(hh-precomp[...,1])**2, axis=2)

if __name__=='__main__':
    from multiprocessing import Pool
    nthreads = 2
    p = Pool(nthreads)
    complist = p.map(buildcomp, np.column_stack((VV1,HH1)))
    comp = np.dstack(complist).sum(-1)

rawDescription: How to avoid using for-loops with numpy?

description: Avoid using for-loops with numpy


rawDescription: How many inverse numbers equal only odd numbers under 1 billion


code:
is_implemented_in_c(enumerate)
is_implemented_in_c(len)
is_implemented_in_c(np.vdot)
is_implemented_in_c(lambda x: True)
is_implemented_in_c(object)
class A(object):
    __slots__ = ('a', 'b')

is_implemented_in_c(A)

rawDescription: Determine whether a Python function is already implemented in C extension


code: ' '.join(e for t in sorted(d.keys(), key=int) for e in set(d[t]))

rawDescription: Extracting multiple substring from a string


code:
import sqlite3
from itertools import groupby

def is_empty_row(row):
    """ Return True if the row contains all None, False otherwise """
    return not any(row)

if __name__ == '__main__':
    db = sqlite3.connect('data.sqlite3')
    cursor = db.cursor()
    query = 'SELECT * FROM data'
    result = cursor.execute(query)
    for is_empty, rows_group in groupby(result, is_empty_row):
        if is_empty:
            # Skip the empty rows
            continue

        # At this point, the non empty rows are grouped together
        for row in rows_group:
            print(row)
        print('---')

rawDescription: Split sqlite table at NULL

description: Split sqlite table at NULL


code:
class DummyForm(forms.Form):
    pass

rawDescription: Dynamic FormWizard

description: Dynamic FormWizard


code:
from pprint import pprint

dict = {'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}
temporal_demand_distribution = {-60: 0.001187, -59: 0.001354}

result_dict = {}
for key, value in dict.items():
  for key2, value2 in temporal_demand_distribution.items():
    result_dict["{}:{}".format(key, key2)] = value * value2

pprint(result_dict)

rawDescription: Multiply Values of two dictionaries, while appending the Keys in Python


rawDescription: Not able to view all columns in Pandas Data frame


code:
def perms(elements, setLength=None):
    if setLength is None:
        setLength = elements

rawDescription: Is there a way to set a default parameter equal to another parameter value?


rawDescription: Getting the Max Value from a Dictionary

description: Getting the Max Value from a Dictionary


code: from .lib.lib_add_participant import LibAddParticipant

rawDescription: How to include class from another file(in another folder) - python

description: Include class from another file(in another folder) - python


rawDescription: XML file edit with Python script

description: XML file edit with Python script


code:
f = open('foo', 'a')
do_stuff(f)
do_more_stuff(f)
# ...
f.close()

rawDescription: How can I have my program read updates that it has just made to a text file?

description: Have my program read updates that it has just made to a text file


code:
import numpy as np
import scipy.sparse.linalg as sla
M = np.array([[0.5, 0.25, 0.25, 0], [0, 0.1, 0.9, 0], [0.2, 0.7, 0, 0.1], [0.2, 0.3, 0, 0.5]])
M
eval, evec = sla.eigs(M.T, k=1, which='LM')
eval
evec
np.dot(evec.T, M).T

rawDescription: find Markov steady state with left eigenvalues (using numpy or scipy)

description: Find Markov steady state with left eigenvalues (using numpy or scipy)


code:
import numpy as np

def unlink_wrap(dat, lims=[-np.pi, np.pi], thresh = 0.95):
    """
    Iterate over contiguous regions of `dat` (i.e. where it does not
    jump from near one limit to the other).

    This function returns an iterator object that yields slice
    objects, which index the contiguous portions of `dat`.

    This function implicitly assumes that all points in `dat` fall
    within `lims`.

    """
    jump = np.nonzero(np.abs(np.diff(dat)) > ((lims[1] - lims[0]) * thresh))[0]
    lasti = 0
    for ind in jump:
        yield slice(lasti, ind + 1)
        lasti = ind + 1
    yield slice(lasti, len(dat))

rawDescription: Preventing plot joining when values "wrap" in matplotlib plots


code:
from pysnmp.smi import builder

mibBuilder = builder.MibBuilder()
TruthValue, = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue')
print(TruthValue(1).prettyPrint()) # prints 'true'

rawDescription: Translate OID value pairs from MIB textual convention using pysnmp


rawDescription: iterating through a Django model field produces unwanted format

description: Iterating through a Django model field produces unwanted format


code:
from pathlib import Path
for fle in Path('./BM').glob('**/*.cplt.csv '):
    change_file(str(fle), (7, 3, 2, 1, 6))

rawDescription: Edit a csv to show 5 columns in a specific order while applying a format to the datetime field


code:
print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

rawDescription: Function overloading in Python: Missing

description: Function overloading in Python: Missing


code:
def user_profile_update(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/keenhome/accounts/login/')
    UserProfile = request.user.get_profile()
    if request.method == 'POST':
        form=UserProfileForm(request.POST)
        if form.is_valid():
            UserProfile.name = form.cleaned_data["name"]
            UserProfile.productNo = form.cleaned_data["productNo"]
            UserProfile.location = form.cleaned_data["location"]
            UserProfile.average_temp = form.cleaned_data["average_temp"]

            #problem happens here:
            UserProfile.home_type = form.cleaned_data["home_type"]

            UserProfile.save()
            return HttpResponseRedirect('/keenhome/accounts/user_profile/')
        else:
            form = UserProfileForm()
            return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

    else:
        form = UserProfileForm()
        return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

rawDescription: Django - pass a value from form to model


code:
def is_container_iterable(o):
    return iter(o) is not o

is_container_iterable([])
is_container_iterable(())
is_container_iterable({})
is_container_iterable(range(5))
is_container_iterable(iter([]))

rawDescription: how to check if an iterable allows more than one pass?

description: Check if an iterable allows more than one pass


code: c_list = c.split(',')

rawDescription: I want to cut variable on another variables using Python


rawDescription: Writing an ASCII string as binary in python


code:
import re

data = "Q 000 1111 00001 0001 00 //SOME_STRING"

digits = re.findall(r"\b\d+\b",data)

rawDescription: Adding digits in list in python

description: Adding digits in list in python


code:
from bs4 import BeautifulSoup
data = '
This text is my text
'

soup = BeautifulSoup(data)
original_string = soup.p.contents[0]

print(original_string)
# "This text is my "

import re
this, text, is_my = re.compile("(text)").split(original_string)

rawDescription: BeautifulSoup: How to replace value in an element with an element tag?


rawDescription: Parsing PickList values from AutotaskAPI


code:
with open(your_file, "r") as f:
   data = [x for x in csv.reader(f, delimiter='#')]

rawDescription: Replace column separation of # with comma or tab


code:
from collections import deque

def chained_zip(*iterables):
    iterables = deque(map(iter, iterables))
    while iterables:
        try:
            yield next(iterables[0])
        except StopIteration:
            iterables.popleft()
        else:
            iterables.rotate(-1)

rawDescription: Breadth-first version of itertools.chain()


code:
data = dict()
for covar_type in covs:
    data[covar_type] = values = []
    for num in num_comp:
        values.append(GMM(...))

rawDescription: Python: list iteration only returns last value


rawDescription: Most efficient way of comparing the contents of two class instances in python


rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


rawDescription: How to find the closest word to a vector using word2vec

description: Find the closest word to a vector using word2vec


code:
cached = open(CACHE_FILENAME, 'r')
cached = pickle.load(cache)
cached.close()

rawDescription: caching mysql query returned by Python script

description: Caching mysql query returned by Python script


rawDescription: iterating over lists finding standard deviation of each point

description: Iterating over lists finding standard deviation of each point


code: self.crhw = FlashableLabel(...)

rawDescription: How to flash tkinter label limited number of times, and only if conditions are met

description: Flash tkinter label limited number of times, and only if conditions are met


code:
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                           mapi.MAPI_LOGON_UI)

rawDescription: Python - Sending Outlook email from different address using pywin32


rawDescription: Dictionary Containing list data, filter based on value in list


code:
if len(names) >= 4:
    authors = '{} et al.'.format(names[0])
elif len(names) > 1:
    authors = '{} and {}'.format(', '.join(names[:-1]), names[-1])
else:
    authors = names[0]

rawDescription: Join author names with python: first ones by comma and last one by and


code:
def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    super(MyDict, self).update(newdict)

rawDescription: Overriding methods without falling into infinite recursion


code: axes = lm.axes

rawDescription: How to set some xlim and ylim in Seaborn lmplot facetgrid

description: Set some xlim and ylim in Seaborn lmplot facetgrid


rawDescription: regEx: To match two groups of chars

description: RegEx: To match two groups of chars


code: (bob_pub, bob_priv) = rsa.newkeys(512)

rawDescription: Decripting RSA in python

description: Decripting RSA in python


code: t1 = {v: k for k, v in t2.items()}

rawDescription: How can i overwrite the dictionary key names in python

description: Overwrite the dictionary key names in python


code:
class test(object):
    def __init__(self, name, number_array):
        self.name = name
        self.number_array = number_array
        #self.graph= barChart(number_array)

    def __eq__(self, other):
        try:
            return (self.name == other.name) and (self.number_array == other.number_array)
        except AttributeError:
            return self.name == other

    def __hash__(self):
        return hash(self.name)

sample_obj = test('test_object', [(0, 1), (2, 3)])

dict1 = {sample_obj: "Hurray"}
print("dict1[sample_obj]", dict1[sample_obj])
print("dict1['test_object']", dict1['test_object'])

dict2 = {'test_object': "Yippie"}
print("dict2[sample_obj]", dict2[sample_obj])
print("dict2['test_object']", dict2['test_object'])

rawDescription: Python, represent non-string object as string?


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import *

a=QApplication([])
document = QTextDocument()
html = """

    <title>Report</title>

REPORT

Sample

""".format('', '')

document.setHtml(html)

printer = QPrinter()
printer.setResolution(96)
printer.setPageSize(QPrinter.Letter)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("test.pdf")
printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter)
document.setPageSize(QSizeF(printer.pageRect().size()))
print(document.pageSize(), printer.resolution(), printer.pageRect())

document.print_(printer)

rawDescription: How to set QTextDocument margins and other properties (setHTML, print to pdf)?

description: Set QTextDocument margins and other properties (setHTML, print to pdf)


code:
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
import re

register = template.Library()

@register.filter
@stringfilter
def stripjs(value):
    stripped = re.sub(r'<script(?:\s[^>]*)?(>(?:.(?!/script>))*</script>|/>)', \
                      '', force_unicode(value), flags=re.S)
    return mark_safe(stripped)

rawDescription: Strip javascript code before rendering in django templates


code: "\n".join(["%s, %s, %s" % (a, b, c) for a, b, c in data])

rawDescription: How can I use python to display nested lists in separate lines in kv label?

description: Use python to display nested lists in separate lines in kv label


code:
from Tkinter import *
import numpy as np
import cv2
import Image, ImageTk

class Test:
    def __init__(self, parent):
        self.parent = parent
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste=[]
        self.maclasse = MaClasse(self.parent)
    def test(self):
        self.drawingArea=Canvas(self.parent)
        self.drawingArea.pack()
        self.drawingArea.bind("<Motion>",self.motion)
        self.drawingArea.bind("<ButtonPress-1>",self.b1down)
        self.drawingArea.bind("<ButtonRelease-1>",self.b1up)
    def b1down(self,event):
        self.b1="down"
    def b1up(self,event):
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste.append((self.xold,self.yold))
    def motion(self,event):
        if self.b1=="down":
            if self.xold is not None and self.yold is not None:
                event.widget.create_line(self.xold,self.yold,event.x,event.y,fill="red",width=3,smooth=TRUE)
                self.maclasse.dessiner_ligne(self.xold,self.yold,event.x,event.y)
            self.xold=event.x
            self.yold=event.y
            self.liste.append((self.xold,self.yold))

class MaClasse:
    def __init__(self, parent):
        self.s=600,600,3
        self.ma=np.zeros(self.s,dtype=np.uint8)
        self.top = Toplevel(parent)
        self.top.wm_title("OpenCV Image")
        self.label = Label(self.top)
        self.label.pack()
        self.show_image()

    def dessiner_ligne(self, xold, yold, x, y):
        cv2.line(self.ma,(xold, yold),(x,y),[255,255,255],2)
        self.show_image()

    def show_image(self):
        self.im = Image.fromarray(self.ma)
        self.imgtk = ImageTk.PhotoImage(image=self.im)
        self.label.config(image=self.imgtk)

if __name__=="__main__":
    root = Tk()
    root.wm_title("Test")
    v = Test(root)
    v.test()
    root.mainloop()

rawDescription: Displaying TkInter and OpenCV windows on the same time


rawDescription: Placing a histogram over scatter plot

description: Placing a histogram over scatter plot


code: data.write(data2)              #and here should it happen

rawDescription: How can I save output tho the same file that I have got the data from, in Python 3

description: Save output tho the same file that I have got the data from, in Python 3


code:
secret = "Apple"
secret.count('p')

rawDescription: How do i find out how many individual letters there are in a word in python?

description: Find out how many individual letters there are in a word in python


code: f = interpolate.UnivariateSpline(x, y, k=3, s=1)

rawDescription: how to interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program?

description: Interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program


code:
from __future__ import print_function
import sys
from textwrap import dedent
import timeit

N = 1000000  # number of executions of each "algorithm"
R = 3  # number of Repeations of executions

# common setup for all algorithms (not timed)
setup = dedent("""
    from collections import defaultdict

    new_dict = {'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5}
""")

algorithms = {
    "def_dict[k].append(v)": dedent("""
        def_dict = defaultdict(list)
        for k, v in new_dict.items(): def_dict[k].append(v)
    """),

    "def_dict[k] = [v]": dedent("""
        def_dict = defaultdict(list)
        for k, v in new_dict.items(): def_dict[k] = [v]
    """),

    "defaultdict(list, <gen-xprsn>)": dedent("""
        def_dict = defaultdict(list, ((k, [v]) for k, v in new_dict.items()))
        """),

    "defaultdict(list, <dict-comp>)": dedent("""
        def_dict = defaultdict(list, {k:[v] for k, v in new_dict.items()})
        """),
}

# collecting results of executing and timing each algorithm snippet
timings = [
    (label,
     min(timeit.repeat(algorithms[label], setup=setup, repeat=R, number=N)),
    ) for label in algorithms
]

# display results
print('fastest to slowest execution speeds (Python {}.{}.{})\n'.format(
        *sys.version_info[:3]),
        '  ({:,d} executions, best of {:d} repetitions)\n'.format(N, R))

longest = max(len(timing[0]) for timing in timings)  # length of longest label
ranked = sorted(timings, key=lambda t: t[1]) # ascending sort by execution time
fastest = ranked[0][1]
for timing in ranked:
    print("{:>{width}} : {:9.6f} secs, rel speed {:4.2f}x, {:6.2f}% slower".
            format(timing[0], timing[1], round(timing[1]/fastest, 2),
                   round((timing[1]/fastest - 1) * 100, 2), width=longest))

rawDescription: Copying a dictionary to defaultdict

description: Copying a dictionary to defaultdict


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

def distance_from_coast(lon,lat,resolution='l',degree_in_km=111.12):
    plt.ioff()

    m = Basemap(projection='robin',lon_0=0,resolution=resolution)
    coast = m.drawcoastlines()

    coordinates = np.vstack(coast.get_segments())
    lons,lats = m(coordinates[:,0],coordinates[:,1],inverse=True)

    dists = np.sqrt((lons-lon)**2+(lats-lat)**2)

    if np.min(dists)*degree_in_km<1:
      return True
    else:
      return False

rawDescription: Matplotlib Basemap Coastal Coordinates

description: Matplotlib Basemap Coastal Coordinates


code:
import sys
import paramiko

try:
    hostname, username, password, targetpath = sys.argv[1:5]
except ValueError:
    print("Failed, call with hostname username password targetpath")

command = "cd {};pwd".format(targetpath)
print("Command to send: {}".format(command))

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command("cd {};pwd".format(targetpath))
print(stdout.read())
ssh.close()

rawDescription: execute a program on a remote machine python

description: Execute a program on a remote machine python


rawDescription: Finding a pair of prime numbers with a given arithmetic average using Python


code: Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

rawDescription: Multilayer-perceptron, visualizing decision boundaries (2D) in Python


code:
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
it = (y for x in matrix for y in x)
[[next(it) for _ in range(3)] for _ in range(4)]

rawDescription: Rearranging a (list of lists) matrix using list comprehensions only


code:
doc.xpath('.//ul[@class="myclass"]/li[a]//text() | .//ul[@class="myclass"]/li/a/@href')
# out: ['I contain a ', 'http://example.com', 'link', '.']

rawDescription: Get bulletted list in lxml

description: Get bulletted list in lxml


code:
for handler in handlers:
    route, handler, args = (handler[0], handler[1], handler[2:])

rawDescription: elegant unpacking variable-length tuples

description: Elegant unpacking variable-length tuples


code:
def BTWcalculator():

    price = float(input("What is the products price?: "))
    btw = input("Please enter a valid BTW-class: 1 = 6%, 2 = 19%: ")
    if btw == "1":
        return price * 1.06
    elif btw == "2":
        return price * 1.19
    else:
        return BTWcalculator()

rawDescription: Python function struggles

description: Python function struggles


code: self.text.mark_set(INSERT, "%s+1c" % ...)

rawDescription: tkinter text widget: Setting the insertion curser

description: Tkinter text widget: Setting the insertion curser


code:
import csv
mycsv = csv.reader(open("ex4.csv"))
dct = {}
for lines in mycsv:
    dct[lines[0]] = lines[1:]
dct

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


code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# $Date: 2013-11-24 22:20:54 +0100 $
# $Revision: 3d4f750 $
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to update-modified-keywords.py. This work is
# published from the Netherlands.
# See http://creativecommons.org/publicdomain/zero/1.0/

"""Remove and check out those files that that contain keywords and have
changed since in the last commit in the current working directory."""

from __future__ import print_function, division
import os
import mmap
import sys
import subprocess

def checkfor(args):
    """Make sure that a program necessary for using this script is
    available.

    Arguments:
    args -- string or list of strings of commands. A single string may
            not contain spaces.
    """
    if isinstance(args, str):
        if ' ' in args:
            raise ValueError('No spaces in single command allowed.')
        args = [args]
    try:
        with open(os.devnull, 'w') as bb:
            subprocess.check_call(args, stdout=bb, stderr=bb)
    except subprocess.CalledProcessError:
        print("Required program '{}' not found! exiting.".format(args[0]))
        sys.exit(1)

def modifiedfiles():
    """Find files that have been modified in the last commit.

    :returns: A list of filenames.
    """
    fnl = []
    try:
        args = ['git', 'diff-tree', 'HEAD~1', 'HEAD', '--name-only', '-r',
                '--diff-filter=ACMRT']
        with open(os.devnull, 'w') as bb:
            fnl = subprocess.check_output(args, stderr=bb).splitlines()
            # Deal with unmodified repositories
            if len(fnl) == 1 and fnl[0] is 'clean':
                return []
    except subprocess.CalledProcessError as e:
        if e.returncode == 128:  # new repository
            args = ['git', 'ls-files']
            with open(os.devnull, 'w') as bb:
                fnl = subprocess.check_output(args, stderr=bb).splitlines()
    # Only return regular files.
    fnl = [i for i in fnl if os.path.isfile(i)]
    return fnl

def keywordfiles(fns):
    """Filter those files that have keywords in them

    :fns: A list of filenames
    :returns: A list for filenames for files that contain keywords.
    """
    # These lines are encoded otherwise they would be mangled if this file
    # is checked in my git repo!
    datekw = 'JERhdGU='.decode('base64')
    revkw = 'JFJldmlzaW9u'.decode('base64')
    rv = []
    for fn in fns:
        with open(fn, 'rb') as f:
            try:
                mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
                if mm.find(datekw) > -1 or mm.find(revkw) > -1:
                    rv.append(fn)
                mm.close()
            except ValueError:
                pass
    return rv

def main(args):
    """Main program.

    :args: command line arguments
    """
    # Check if git is available.
    checkfor(['git', '--version'])
    # Check if .git exists
    if not os.access('.git', os.F_OK):
        print('No .git directory found!')
        sys.exit(1)
    print('{}: Updating modified files.'.format(args[0]))
    # Get modified files
    files = modifiedfiles()
    if not files:
        print('{}: Nothing to do.'.format(args[0]))
        sys.exit(0)
    files.sort()
    # Find files that have keywords in them
    kwfn = keywordfiles(files)
    for fn in kwfn:
        os.remove(fn)
    args = ['git', 'checkout', '-f'] + kwfn
    subprocess.call(args)

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

rawDescription: Best way to have a python script copy itself?

description: Have a python script copy itself


code:
a = numpy.array(a)
b = numpy.array(b)
c = a+b
d = a*b

rawDescription: Adding 2 matrix and Multiplying 2 matrix in python by using scipy/numpy


code: np.genfromtxt('abc.txt', delimiter=',', dtype=None, names=True)

rawDescription: Query about np.loadtext() function

description: Query about np.loadtext() function


code:
import collections
takes = collections.defaultdict(list)

for x in range(0, len(meta_array)):
    camera_number = meta_array[x][0]    # String between "01" and "16"
    file_name = meta_array[x][1]        # Filename
    duration_ms = meta_array[x][2]      # Video length in milliseconds

    takes[camera_number].append([file_name, int(duration_ms)])

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


code:
import PyCmdMessenger

# set up serial connection at proper baud rate
a = PyCmdMessenger.ArduinoBoard('/dev/ttyACM0',baud_rate=115200)

# list of commands at top of sketch, with argument formats
commands = [["kReadTemperature","f"],
            ["kSendTemperature","f"],
            ["kStatus","s"]]

cmd = PyCmdMessenger.CmdMessenger(a,commands)
cmd.send("kReadTemperature")
print(cmd.receive())

rawDescription: Communicating with Arduino and Python via CmdMessenger, not working


code:
def foo(bin_seq, y):
    from itertools import combinations
    bin_seq = list(bin_seq)
    y = bin_seq.count('1') - y
    indexes = [i for i in range(len(bin_seq)) if bin_seq[i] == '1']
    for index in combinations(indexes,  y):
        vec = bin_seq[:]
        for i in index:
            vec[i] = '0'
        yield ''.join(vec)

rawDescription: Determining all sub-vector combinations of a binary vector for a certain hamming weight


code:
dict1 = ...
namespace = {'dict1': dict1}

string = ...
namespace[string[2]]["2"]

rawDescription: Python: Linking to a dictionary through a text string


code:
class proto(parentProtocol):
    def callback(self):
        next_command = self.command_queue.pop()
        # do stuff
    def connectionMade(self):
        from twisted.internet import task
        self.task_id = task.LoopingCall(self.callback)
        self.task_id.start(1.0)

rawDescription: How to properly trigger a python twisted transport?

description: Properly trigger a python twisted transport


code:
from collections import namedtuple
class MyTuple(namedtuple('MyTuple', 'field1 field2')):
    __slots__ = ()
    def __new__(cls, field1, field2):
        """Create a new instance of MyTuple(field1, field2)"""
        return super(MyTuple, cls).__new__(cls, field1.lower(), field2)
    def __str__(self):
        return '{}:{}'.format(self.field1, self.field2)

mt = MyTuple('FOO', 'BAR')
mt
print(mt)
mt.field1
mt.field2

rawDescription: Lowercase a field in namedtuple in python


code:
symbol,ev_ebitda,asset
msft,40,60
cvx,40,60
baba,40,60

rawDescription: Outputting Multi-row CSV Files from Multiple Dictionaries


code:
Bob, Keyboard, 8
Bob, Pen, 14
Bob, TV, 16
John, Book, 22
John, Chair, 8
John, TV, 4

rawDescription: Python - Create total sum of items per person from a csv file


code:
temp = []
mylist[:] = sorted(merge_types(mylist, temp), key=atof_pre) + sorted(temp)
print(mylist)

rawDescription: Sort numeric lines with thousand separators


code:
def bytes2int(str):
    res = ord(str[0])
    for ch in str[1:]:
        res <<= 8
        res |= ord(ch)
    return res

def int2bytes(n):
    res = []
    while n:
        ch = n & 0b11111111
        res.append(chr(ch))
        n >>= 8
    return ''.join(reversed(res))

bytes = 'abcdefghijklmnopqrstuv'
assert int2bytes(bytes2int(bytes)) == bytes

rawDescription: Python: convert a byte to binary and shift its bits?


code:
for word in words:
    combos = product(*([""] + sublist for sublist in lists))
    next(combos)   # skip n=0
    for combo in combos:
        print(word + "".join(combo))

rawDescription: want to combine every element of a list with every element of n lists

description: Want to combine every element of a list with every element of n lists


rawDescription: Bash can't find right directory in script


code:
# ask user for an input until an integer is provided
prompt = "Please, enter the gematric value of the word: "
while True: # infinite loop
    try:
        # ask user for an input; convert it to integer immediately
        userinput = int(raw_input(prompt))
    except ValueError: # `int()` can't parse user input as an integer
        print('the gematric value must be an integer. Try again')
    else:
        break # got an integer successfully; exit the loop

# use `with` statement to close the file automatically
# `'r'` is default; you don't need to specify it explicitly
with open(r'c:\school\dictionarytest.txt') as inputfile:
    #XXX inputfile.lower() # WRONG!!! file object doesn't have .lower() method

    # assuming `dictionarytest.txt` has one word per line
    for word in inputfile: # read the file line by line
        word = word.strip() # strip leading/trailing whitespace
        if gematric_value(word) == userinput:
           print(word) # print words that match user input

rawDescription: Gematria with a list of words

description: Gematria with a list of words


code:
with open('output.csv', 'wb') as f:
    w = csv.writer(f, delimiter='\t')
    for key in keys:
        w.writerow(chain([key], (dct[item].get(key, '') for item in lst)))

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


rawDescription: Python: Parsing a colon delimited file with various counts of fields


code:
if ((search(x+1, y, mazeList))
        or (search(x, y-1, mazeList))
        or (search(x-1, y, mazeList))
        or (search(x, y+1, mazeList))):
        return True

rawDescription: Python Maze solving program: how to mark correct path


rawDescription: Separate float into digits

description: Separate float into digits


code:
import threading
import time

class StoppableThread(threading.Thread):
    def __init__(self):
        super(StoppableThread, self).__init__()
        self.daemon = True
        self.__monitor = threading.Event()
        self.__monitor.set()
        self.__has_shutdown = False

    def run(self):
        '''Overloads the threading.Thread.run'''
        # Call the User's Startup functions
        self.startup()

        # Loop until the thread is stopped
        while self.isRunning():
            self.mainloop()

        # Clean up
        self.cleanup()

        # Flag to the outside world that the thread has exited
        # AND that the cleanup is complete
        self.__has_shutdown = True

    def stop(self):
        self.__monitor.clear()

    def isRunning(self):
        return self.__monitor.isSet()

    def isShutdown(self):
        return self.__has_shutdown

    ###############################
    ### User Defined Functions ####
    ###############################

    def mainloop(self):
        '''
        Expected to be overwritten in a subclass!!
        Note that Stoppable while(1) is handled in the built in "run".
        '''
        pass

    def startup(self):
        '''Expected to be overwritten in a subclass!!'''
        pass

    def cleanup(self):
        '''Expected to be overwritten in a subclass!!'''
        pass

rawDescription: Tracking *maximum* memory usage by a Python function


code:
import cv2
cap = cv2.VideoCapture('david.mpg')
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

def onChange(trackbarValue):
    cap.set(cv2.CAP_PROP_POS_FRAMES,trackbarValue)
    err,img = cap.read()
    cv2.imshow("mywindow", img)
    pass

cv2.namedWindow('mywindow')
cv2.createTrackbar( 'start', 'mywindow', 0, length, onChange )
cv2.createTrackbar( 'end'  , 'mywindow', 100, length, onChange )

onChange(0)
cv2.waitKey()

start = cv2.getTrackbarPos('start','mywindow')
end   = cv2.getTrackbarPos('end','mywindow')
if start >= end:
    raise Exception("start must be less than end")

cap.set(cv2.CAP_PROP_POS_FRAMES,start)
while cap.isOpened():
    err,img = cap.read()
    if cap.get(cv2.CAP_PROP_POS_FRAMES) >= end:
        break
    cv2.imshow("mywindow", img)
    k = cv2.waitKey(10) & 0xff
    if k==27:
        break

rawDescription: In Python/OpenCV is there a way to quickly scroll through frames of a video, allowing the user to select the start and end frame to be processed?


rawDescription: Sorting a NumPy array

description: Sorting a NumPy array


code: [x for x in my_str.split(';') if x]

rawDescription: python split function -avoids last empy space

description: Python split function -avoids last empy space


code:
# Get a copy of input as the output
out = initial_values.copy()

# Get sorted indices
sorted_index = np.argsort(out)

# Last index in sorted indexed indices for setting elements in input array to 0's
idx = np.where(out.sum() < out[sorted_index].cumsum())[0][-1]

# Set until idx indexed into sorted_index in turn indexed into input array t0 0's
out[sorted_index[:idx+1]] = 0

# There might be one element left to make the sum absolutely zero.
# Make it less negative to make the absolute sum zero.
out[sorted_index[idx+1]] -= out.sum()

rawDescription: Limit sum of entries in numpy array by adjusting negative entries


code:
def updateMap(self ,x ,y , Val):
        oldval = self.RobotMap[x][y]
        self.RobotMap[x][y]=self.RobotMap[x][y] + Val

        if self.RobotMap[x][y] > self.mapMaxOcc:
            self.RobotMap[x][y] = self.mapMaxOcc
        elif self.RobotMap[x][y] < self.mapMaxFree:
            self.RobotMap[x][y] = self.mapMaxFree
        return oldval, self.RobotMap[x][y]

rawDescription: python script speed improvements

description: Python script speed improvements


code:
from lxml.html import fromstring

data = """
<description>
the thing stuff is very important for various reasons, notably other things.
</description>
"""

tree = fromstring(data)

print(tree.xpath("//description")[0].text_content().strip())

rawDescription: ElementTree text mixed with tags

description: ElementTree text mixed with tags


code:
if len(players) > 1:
    print('The player(s) with the most pars are', ', '.join(players))
elif len(players) == 1:
    print('The player with the most pars is %s' % players[0])

rawDescription: Using a for loop to select items and put them into a list


code:
def count_zeros(matrix):
    total = 0
    for row in matrix:
        total += row.count(0)
    return total

rawDescription: Counting elements matching a pattern in a tuple of tuples


code:
a = X
for value in list_a:
    if value == "three":
        a += 30
    else:
        a += 10
    print(a)

rawDescription: Irregular cumulative sum in python

description: Irregular cumulative sum in python


code:
A = np.array(Lst) # this step may take a while now ... maybe you should have Lst as a np.array before you get to this point

sliced = A[:,[j]] # this should be really quite fast

rawDescription: Fast way of slicing columns from tuples

description: Fast way of slicing columns from tuples


code:
a, b, c, d = return_args()
call(a, b, c, d)

rawDescription: Using variables from a returned function as arguments in another function


code:
a = ['qw', 'wq', 'test']

def merge (tgt, letter):
    for i, _ in enumerate (tgt):
        yield tgt [:i] + letter + tgt [i:]
    yield tgt + letter

b = [x for tgt in a for x in merge (tgt, 'e') ]
print (b)

rawDescription: Create new set of subsets out of set of subsets (python)


code:
split_lst = zip(*c_layer_points)
dict(gps_time=list(split_lst[0]), twtt=list(split_lst[1]))

rawDescription: Most Efficient Way to get list of values from Django Queryset


code:
import numpy as np

# introduce bases
freq_min, freq_max, freq_spacing = 75., 300., 5.
freqs = np.arange(freq_min, freq_max + freq_spacing, freq_spacing)

t_min, t_max, t_spacing = 0.1, 5., 0.1
ts = np.arange(t_min, t_max + t_spacing, t_spacing)

# do calculation
F, T = np.meshgrid(freqs, ts)
Z = F / T * 2

rawDescription: how test all the possible outcomes of a formula in Python?

description: How test all the possible outcomes of a formula in Python


code:
bp = plt.boxplot(data, whis=[5, 95], showfliers=True)

# Get a list of Line2D objects, representing a single line from the
# minimum to the maximum flier points.
fliers = bp['fliers']

# Iterate over it!
for fly in fliers:
    data = fly.get_data()
    fly.set_data([data[0][0],data[0][-1]],[data[1][0],data[1][-1]])

rawDescription: Matplotlib boxplot show only max and min fliers


rawDescription: python: retrieve names of all builtins

description: Python: retrieve names of all builtins


code: df['g'] = df.apply(base_count, axis=1)

rawDescription: Occurence frequency from a list against each row in Pandas dataframe


code:
serial_filter = df1['Serial N'].value_counts().lt(2).reindex(df1['Serial N'])
df1.loc[serial_filter.values, ['year', 'current']] = np.nan

rawDescription: Getting the content of a pandas row based on some conditions of other row


code:
outFile = open('output.txt', 'w')
for element in data['results']:
    tempList = data['results'][element]
    for dict in tempList:
        #print(dict['string'])
        out.write(dict['string']+'\n')

out.close()

rawDescription: python extract list from json data to text

description: Python extract list from json data to text


rawDescription: How can i print list of dict values, one value in list for each key

description: Print list of dict values, one value in list for each key


code: spl.integral(-1, 1)

rawDescription: Integral function of a interpolating polynomial in python


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


code:
class BuildInfo(object):
    def __init__(self, objectFiles = [], sourceFiles = []):
        self.objectFiles = objectFiles
        self.sourceFiles = sourceFiles
    def append(self, build_info):
        self.objectFiles.extend(build_info.objectFiles)
        self.sourceFiles.extend(build_info.sourceFiles)

rawDescription: python/scons help: maintaining lists of source files + object files

description: Python/scons help: maintaining lists of source files + object files


code:
from itertools import takewhile, accumulate
PARENS_MAP = {'(': 1, ')': -1}
def parse_tree(tree, string):
    string = iter(string)
    while string:
        current = next(string)
        if current == "(":
            child = iter(string)
            child = ((c, PARENS_MAP.get(c, 0)) for c in child)
            child = accumulate(child, lambda a,b: (b[0], a[1]+b[1]))
            child = takewhile(lambda c: c[1] >= 0, child)
            child = (c[0] for c in child)
            tree[-1][1] = "".join(child)
        else:
            tree.append([current, None])
print(parse_tree('abc(abc(defg)d)de(f)gh'))

rawDescription: Optimizing string parsing with Python

description: Optimizing string parsing with Python


code:
destinationImage.composite(sourceImage, leftPosition, topPosition)
# versus
destinationImage.composite_channel(channel='all_channels',
                                   image=sourceImage,
                                   operator='replace',
                                   left=leftPosition,
                                   top=topPosition)

rawDescription: Draw an image into another one in imagemagick?


code:
Lorem_list=['Lorem Ipsum','Lorem Ipsum','Lorem Ipsum']
[f.write('\n      '+x) for x in Lorem_list]

rawDescription: Remove multiple lines from a text file after a specific string, then replace with new text


code:
from itertools import chain
filter(lambda e: e not in punctuation, chain(*a))

rawDescription: How do I remove common elements from two lists?

description: Remove common elements from two lists


code:
def enteredMonth():
    month = int(input("Enter a month in terms of a number: "))
    return month

def enteredYear():
    year = int(input("Enter a year: "))
    return int(year)

def leapYear(year):
    if year % 4 == 0:
        return True
    else:
        return False

def numberOfDays(month):
    if month == 1:
        return 31
    elif month == 2:
        return 28
    # etc. Actually, the Pythonic implementation would be to use a dict
    # that maps month numbers to their usual number of days.

def main():
   month = enteredMonth()
   year = enteredYear()
   is_leapyear = leapYear(year)
   number_of_days = numberOfDays(month)
   print(month, year, "has", number_of_days, "days")

if __name__ == '__main__':
   main()

rawDescription: Converting the number of days in a month in Python?


code: [name for name, method in Class.__dict__.items() if hasattr(method,'__call__')]

rawDescription: How can I list methods directly defined in a class (not inherited)?

description: List methods directly defined in a class (not inherited)


code:
index
a = pd.Series([1,4,5,7,8], index = index)
b = pd.Series([2,3,6,7,8], index = index)
a
b
df = DataFrame({ 'a' : a, 'b' : b })
df

rawDescription: Get min and max elements for 2 corresponding series in pandas


code:
def readPolygons(path):
  polygons = []
  with open(path) as f:
    for line in f:                                         # (1)
      words = [ float(y) for y in (line.split())[2:] ]     # (2)
      poly = zip (words[::2], words[1::2])                 # (3)
      if len(poly):                                        # (4)
        polygons.append(poly)
  return polygons

rawDescription: Removing points inside several polygons

description: Removing points inside several polygons


rawDescription: Extract word from a list of synsets in NLTK for Python


code:
def foo(obj, name):
    # the fixed API
    setattr(obj, name, 1 + getattr(obj, name))

def bar():
    myloc = 11

    # magic class...
    class MyClass:
        def __getattr__(self, name):
            # accessing any member returns the current value of the local
            return myloc
        def __setattr__(self, name, value):
            # writing any member will mutate the local (requires Python3)
            nonlocal myloc
            myloc = value

    foo(MyClass(), "myloc")
    print(myloc) # here myloc will have been incremented

bar()

rawDescription: An object that describes the current scope


code:
from M2Crypto.EVP import HMAC
import base64

hmac = HMAC(session_id,'sha1')
hmac.update(decypted_challenge)

auth_response = base64.encodestring(hmac.digest()) #Base64 format

rawDescription: python M2Crypto HMAC SHA1

description: Python M2Crypto HMAC SHA1


rawDescription: Removing array in matrix if specific value shows up


rawDescription: Python logging won't set a logging level using basicConfig


rawDescription: list of dicts to/from dict of lists

description: List of dicts to/from dict of lists


code:
nums=set(nums)
pairs= filter(nums.isdisjoint, pairs)

rawDescription: How to exclude points from a set quickly

description: Exclude points from a set quickly


rawDescription: Compare elements of a list of lists and return a list


rawDescription: Multiple hash assignments in perl - translated to python? Why equal 1 always?


code: a. symmetric_difference(b)

rawDescription: Opposite of set.intersection in python?

description: Opposite of set.intersection in python


code:
hImageList: 4411024
hIcon: 10617107
iIcon: 7
dwAttributes: 1078497655
szDisplayName: 'desktop.ini'
szTypeName: 'Configuration settings'

rawDescription: How to use SHGetFileInfo with SHGFI_PIDL in python

description: Use SHGetFileInfo with SHGFI_PIDL in python


code:
def ndmesh(*xi,**kwargs):
    if len(xi) < 2:
        msg = 'meshgrid() takes 2 or more arguments (%d given)' % int(len(xi) > 0)
        raise ValueError(msg)

    args = np.atleast_1d(*xi)
    ndim = len(args)
    copy_ = kwargs.get('copy', True)

    s0 = (1,) * ndim
    output = [x.reshape(s0[:i] + (-1,) + s0[i + 1::]) for i, x in enumerate(args)]

    shape = [x.size for x in output]

    # Return the full N-D matrix (not only the 1-D vector)
    if copy_:
        mult_fact = np.ones(shape, dtype=int)
        return [x * mult_fact for x in output]
    else:
        return np.broadcast_arrays(*output)

rawDescription: Creating a numpy array of 3D coordinates from three 1D arrays


rawDescription: How to add columns and rows of a dataframe as keys and values of a dictionary in python

description: Add columns and rows of a dataframe as keys and values of a dictionary in python


code: amr = dview.map(f, allzeniths, allazimuths)

rawDescription: Parallelise nested for-loop in IPython

description: Parallelise nested for-loop in IPython


code:
def complement(l, universe=None):
    """
    Return the complement of a list of integers, as compared to
    a given "universe" set. If no universe is specified,
    consider the universe to be all integers between
    the minimum and maximum values of the given list.
    """
    if universe is not None:
        universe = set(universe)
    else:
        universe = set(range(min(l), max(l)+1))
    return sorted(universe - set(l))

rawDescription: Python: How do I find the complement of a list?


code: Pxx[np.greater(np.sum(Pxx, axis=1), 2955), :] = 0.

rawDescription: Python - Removing specific frequencies between a range


code:
# Open the file
file = open('log_file.csv')
# readlines() will return the data as a list of strings, one for each line
log_data = file.readlines()
# close the log file
file.close()

rawDescription: Python parsing log file for IP address and Protocol


code:
box = browser.find_element_by_xpath("//input[@type='button' and @value='go']/preceding-sibling::input[@type='text'] ")
driver.execute_script("arguments[0].value = '123'", box)

rawDescription: how to reach a specialized page in selenium of Python?

description: Reach a specialized page in selenium of Python


rawDescription: Python list manipulation: Add an item to a string element to make it a 2 item list


code:
with open('file.enc', 'wb') as f:
    f.write(iv)
    f.write(salt)
    f.write(key)

rawDescription: Writing and retrieving bytes to/from a file in Python


code:
def __unicode__(self):
    return "[%s(%s)]" % (self.__class__.__name__, ', '.join('%s=%s' % (k, self.__dict__[k]) for k in sorted(self.__dict__) if '_sa_' != k[:4]))

rawDescription: method of iterating over sqlalchemy model's defined columns?

description: Method of iterating over sqlalchemy model's defined columns


code:
types = inspect(Animal).polymorphic_map.keys()
user_input = 'cat'
new_cat = inspect(Animal).polymorphic_map[user_input]()

rawDescription: List polymorphic inheritance choices and create an instance based on that choice


code:
[int(f) for f in lloyd['homework']]
Out[53]: [90, 97, 75, 92]

rawDescription: convert list of dict to int [Python Code Academy]

description: Convert list of dict to int [Python Code Academy]


code: raw_input("Enter Equation:")

rawDescription: How to pop up the python console?

description: Pop up the python console


code:
class UserResource(object):
    def test(self):
        pass

rawDescription: Decorate all class methods without redecorating each time


code:
Edges = []
for item in matches:
    for vertex in Vertices:
        if vertex[1] == item[0]:
            i = vertex[0]
            break
    for vertex in Vertices:
        if vertex[1] == item[1]:
            j = vertex[0]
            break
    Edges.append((i,j))
Edges

rawDescription: Replacing values in two dimensional list


code:
res = df.pivot_table('value', 'String3', ['String1', 'String2'])
res

rawDescription: Efficient matricization of a pandas dataframe


code:
post_dict = {'': '', 'item_data[username]': ['johndoe'], 'item_data[email]': ['johndoe@gmail.com'], 'item_data[campus]': ['madison']}
item_data = {}

for key, value in post_dict.items():
    strlist = key.split('[')
    if len(strlist) == 1:
        continue

    new_key = strlist[1].replace(']', '')
    new_value = ''.join(value)

    # add to the dict if both new_key and new_value are non-empty
    if all([new_key, new_value]):
        item_data[new_key] = new_value

print(item_data)
# Output
{'username': 'johndoe', 'campus': 'madison', 'email': 'johndoe@gmail.com'}

rawDescription: How to remove dict keys if value is empty

description: Remove dict keys if value is empty


code:
df = pd.DataFrame(data)
means = df.groupby('DATE').mean()

rawDescription: Using pandas to find daily averages

description: Using pandas to find daily averages


code:
def strfdelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    return fmt.format(**d)

rawDescription: formatting python timedelta objects

description: Formatting python timedelta objects


code:
screen.blit(wood, spots[0])
screen.blit(brick, spots[1])
screen.blit(wheat, spots[2])

rawDescription: How can i use the value of one variable to call another in python?

description: Use the value of one variable to call another in python


code:
with data as f:     # f is the file object
    for line in f:  # you can iterate over a file object line-by-line
        xi, yi, ei = line.split()
        x.append(xi)
        y.append(yi)
        e.append(ei.strip()) # ei will have a \n on the end

rawDescription: Creating lists from a text file by splitting it vertically


code:
## Create the "map"
warehouse = Room("warehouse",{'n':'house','w':'pond'})
pond = Room("pond",{'e':'warehouse'})
house = Room("house",{'s':'warehouse'})

rawDescription: Relationships between variables

description: Relationships between variables


code:
class PluginMount(type):
    """
    A plugin mount point derived from:
        http://martyalchin.com/2008/jan/10/simple-plugin-framework/
    Acts as a metaclass which creates anything inheriting from Plugin
    """

    def __init__(cls, name, bases, attrs):
        """Called when a Plugin derived class is imported"""

        if not hasattr(cls, 'plugins'):
            # Called when the metaclass is first instantiated
            cls.plugins = []
        else:
            # Called when a plugin class is imported
            cls.register_plugin(cls)

    def register_plugin(cls, plugin):
        """Add the plugin to the plugin list and perform any registration logic"""

        # create a plugin instance and store it
        # optionally you could just store the plugin class and lazily instantiate
        instance = plugin()

        # save the plugin reference
        cls.plugins.append(instance)

        # apply plugin logic - in this case connect the plugin to blinker signals
        # this must be defined in the derived class
        instance.register_signals()

rawDescription: Plugin architecture - Plugin Manager vs inspecting from plugins import *


code:
from __future__ import print_function

import os
import re

def shortname(s):
    # An ugly regular expression that finds your date time string.
    m = re.search(r'_\d{1,2}_[a-zA-Z]{3}_\d{4}_\d{1,2}_\d{1,2}_\d{1,2}\Z', s)
    # Get your file name without the date time string
    if m is not None:
        return s[:m.start()]
    print("No match found - return original string")
    return s

s = r'C:\test\This_a_folder_with_long_name_20_Oct_2015_07_10_20'
s2 = r'C:\test\This_another_folder_with_long_name_11_Oct_2014_2_1_25'

# Test the output
newname = shortname(s)
print("Long name:", s)
print("New name:", newname)
newname = shortname(s2)
print("Long name:", s2)
print("New name:", newname)
# Only rename if the name is different
if newname != s:
    # You should do error checking before renaming.
    # Does the directory already exist?
    os.rename(s, newname)

rawDescription: python rename a folder name and remove extra information

description: Python rename a folder name and remove extra information


code:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM users')
rowcount = cursor.fetchone()[0]

rawDescription: how to make a rowcount in ponyorm? Python

description: Make a rowcount in ponyorm? Python


code:
from slimit import ast  # $ pip install slimit
from slimit.parser import Parser as JavascriptParser
from slimit.visitors import nodevisitor

soup = BeautifulSoup(html, 'html.parser')
tree = JavascriptParser().parse(soup.script.string)
obj = next(node.right for node in nodevisitor.visit(tree)
           if (isinstance(node, ast.Assign) and
               node.left.to_ecma() == 'window.blog.data'))
# HACK: easy way to parse the javascript object literal
data = json.loads(obj.to_ecma())  # NOTE: json format may be slightly different
assert data['activity']['type'] == 'read'

rawDescription: How to extract a JSON object that was defined in a HTML page javascript block using Python?

description: Extract a JSON object that was defined in a HTML page javascript block using Python


code: today = datetime.datetime.now()

rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


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

class simulation_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
        self.grid()

    def initialize(self):

        self.c2_low =Tkinter.StringVar()
        self.c3_low =Tkinter.StringVar()
        self.ic4_low =Tkinter.StringVar()
        self.nc4_low =Tkinter.StringVar()
        self.ic5_low =Tkinter.StringVar()
        self.nc5_low =Tkinter.StringVar()
        self.neoc5_low =Tkinter.StringVar()
        self.n2_low = Tkinter.StringVar()

        self.c2_high =Tkinter.StringVar()
        self.c3_high =Tkinter.StringVar()
        self.ic4_high =Tkinter.StringVar()
        self.nc4_high =Tkinter.StringVar()
        self.ic5_high =Tkinter.StringVar()
        self.nc5_high =Tkinter.StringVar()
        self.neoc5_high=Tkinter.StringVar()
        self.n2_high = Tkinter.StringVar()

        self.entry = Tkinter.Entry(self, textvariable = self.c2_low).grid(column=0,row=1,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.c2_high).grid(column=0,row=2,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.c3_low).grid(column=0,row=3,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.c3_high).grid(column=0,row=4,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.ic4_low).grid(column=1,row=1,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.ic4_high).grid(column=1,row=2,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.nc4_low).grid(column=1,row=3,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.nc4_high).grid(column=1,row=4,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.ic5_low).grid(column=0,row=5,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.ic5_high).grid(column=0,row=6,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.nc5_low).grid(column=0,row=7,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.nc5_high).grid(column=0,row=8,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.neoc5_low).grid(column=1,row=5,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.neoc5_high).grid(column=1,row=6,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.n2_low).grid(column=1,row=7,sticky='EW')
        self.entry = Tkinter.Entry(self, textvariable = self.n2_high).grid(column=1,row=8,sticky='EW')

        self.resizable(False,False)

        button = Tkinter.Button(self,text=u"simulate", command =self.simulation)
        button.grid(column=3,row=9)

    def simulation(self):

        sample_runs =10000     # Sample Population needs to be higher than exporting population
        export_runs = 1000    # How many samples we actually take

        c2_low = float(self.c2_low.get())
        c2_high = float(self.c2_high.get())
        c3_low = float(self.c3_low.get())
        c3_high = float(self.c3_high.get())
        ic4_low = float(self.ic4_low.get())
        ic4_high = float(self.ic4_high.get())
        nc4_low = float(self.nc4_low.get())
        nc4_high = float(self.nc4_high.get())
        ic5_low = float(self.ic5_low.get())
        ic5_high = float(self.ic5_high.get())
        nc5_low = float(self.nc5_low.get())
        nc5_high = float(self.nc5_high.get())
        neoc5_low = float(self.neoc5_low.get())
        neoc5_high = float(self.neoc5_high.get())
        n2_low = float(self.n2_low.get())
        n2_high = float(self.n2_high.get())

        c2 = np.random.uniform(c2_low,c2_high,sample_runs)
        c3 = np.random.uniform(c3_low,c3_high, sample_runs)
        ic4 = np.random.uniform(ic4_low,ic4_high,sample_runs)
        nc4 = np.random.uniform(nc4_low,nc4_high,sample_runs)
        ic5 = np.random.uniform(ic5_low,ic5_high,sample_runs)
        nc5 = np.random.uniform(nc5_low,nc5_high,sample_runs)
        neoc5 = np.random.uniform(neoc5_low ,neoc5_high,sample_runs)
        n2 = np.random.uniform(n2_low, n2_high,sample_runs)

        # SETS CONSTRAINTS BASED ON RANGES

        # masked = np.where((c3>=c3_low) & (c3<=c3_high) & (c2>=c2_low) & (c2<= c2_high) & (ic4>=ic4_low) &
        #                   (ic4<= ic4_high) & (nc4>= nc4_low) & (nc4<= nc4_high) & (ic5>= ic5_low) & (ic5<= ic5_high)& (nc5>= nc5_low)&
        #                   (nc5<= nc5_high)& (neoc5>= neoc5_low)& (neoc5<=neoc5_high) & (n2>=n2_low) & (n2<= n2_high))

        # MASKED CREATES AN INDEX (Where constraints are held) FOR LOOKING THROUGH DATA

        c2 = c2[:export_runs]
        c3 = c3[:export_runs]
        ic4 = ic4[:export_runs]
        nc4 = nc4[:export_runs]
        ic5 = ic5[:export_runs]
        nc5 = nc5[:export_runs]
        neoc5 = neoc5[:export_runs]
        n2 = n2[:export_runs]

        # DETERMINES CONC FROM METHANE BY BALANCE

        c1 = 100-c2-c3-nc4-ic4-nc5-ic5-neoc5-n2

        #CREATES A SERIES FOR EACH COMPONENET AND ADDS COLUMNS TO A FINAL DATAFRAME

        c1_ser = pd.Series(c1)
        c2_ser = pd.Series(c2)
        c3_ser = pd.Series(c3)
        ic4_ser = pd.Series(ic4)
        nc4_ser = pd.Series(nc4)
        ic5_ser = pd.Series(ic5)
        nc5_ser = pd.Series(nc5)
        neoc5_ser = pd.Series(neoc5)
        n2_ser = pd.Series(n2)

        #EXPORTS DATAFRAME TO .CSV FILE NAMED LNG_DATA

        df = pd.DataFrame([c1_ser, c2_ser, c3_ser, ic4_ser, nc4_ser, ic5_ser, nc5_ser, neoc5_ser, n2_ser]).T
        df.columns = ['C1','C2','C3','nC4','iC4','nC5','iC5','neoC5','N2']
        df.to_csv('output.csv')

if __name__ == "__main__":
    app = simulation_tk(None)
    app.title('Simulation')
    app.mainloop()

rawDescription: Using Tkinter user input for variables in functions


code: char = ''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')])

rawDescription: Correct way to octal escape a UTF-8 character in Python


code:
from bs4 import BeautifulSoup
html = element.get_attribute('outerHTML')
attrs = BeautifulSoup(html, 'html.parser').a.attrs
pprint(attrs)

rawDescription: Selenium webdriver: How do I find ALL of an element's attributes?


code:
# call delay on the task and pass it the same params you would pass to the fnc itself
bulk_create_notifications.delay(fans)

rawDescription: The right way to perform a task asynchronously in Django, via Celery


code:
[i for i,j in enumerate(fullList) if j[0]=='c']
[i for i,j in enumerate(fullList) if 'c' in j]

rawDescription: Python find the index of a multi value List?


code:
def changeNumber():
    global number  # will not possibly work w/o this, the way you posted!
    number += 1
    with open('changeFile.txt', 'w') as f:
        f.write('number = {}\n'.format(number))

rawDescription: How to save a changed item to an external file? (Python 3)

description: Save a changed item to an external file? (Python 3)


code:
def foo():
  return 'bar', 42

a, b = foo()

rawDescription: Is it possible to assign two different returned values from a python function to two separate variables?


code: a = np.zeros((row.max()+1, col.max()+1), dtype=values.dtype)

rawDescription: Convert row-column-value data to an array - numpy


code:
env = Environment()
env.Replace(DLIBCOM='my custom lib command')
env.Library('name', ['source'])

rawDescription: What is the construction variable used for creating libraries in SCons?


code:
result['B','mean']
result[[('B', 'mean'), ('C', 'mean')]]

rawDescription: How to use groupby to apply multiple functions to multiple columns in Pandas?

description: Use groupby to apply multiple functions to multiple columns in Pandas


code:
'Hellk howg ars youf poday, [name]?'
'Heylo how arer y,u todab, [name]?'
'Hrllo hfw  are zyou totay, [name]?'

rawDescription: Place random character in string if not a certain word


code:
top_points = r["fliers"][0].get_data()[1]
bottom_points = r["fliers"][2].get_data()[1]
plot(np.ones(len(top_points)), top_points, "+")
plot(np.ones(len(bottom_points)), bottom_points, "+")

rawDescription: Finding the outlier points from matplotlib : boxplot


code:
import re

exp = re.compile(r'(\d+\.?\d+)')

with open('mainfile.txt') as f, open('names.txt','w') as out:
   for line in f:
      line = line.strip()
      if len(line):
           try:
               out.write('{}\n'.format(re.split(exp, line)[0].strip()))
           except:
               print('Could not parse {}'.format(line))

rawDescription: python 2.7 select words in list prior to number

description: Python 2.7 select words in list prior to number


code:
import random

def any_intro(self):
    cls = random.choice(type(self).__mro__[:-1])
    return cls.intro(self)

rawDescription: Call a method on the parent class of an initialized object


code:
import tkinter as tk

root = tk.Tk()
fontfamily = tk.font.families()

#you don't need to define a function to change highlight color.

fontlist = tk.Listbox (root, bg='white', selectbackground='yellow') #add selectbackground='yellow' here.
fontlist.grid()

for eachfont in fontfamily:
    fontlist.insert(tk.END, eachfont)

#So it is necessary to bind a function now :)

tk.mainloop()

rawDescription: How to refresh the tkinter Listbox

description: Refresh the tkinter Listbox


code:
defaultd=dict(int=20, strwdef='DEFAULTSTRING',snd=None,flag=False)
defaultd
defaultd.update(dd)
defaultd

rawDescription: Python: how can I ingest arguments from JSON file?


rawDescription: How to join 2 lists of dicts in python?

description: Join 2 lists of dicts in python


code:
import logging
import textwrap

class WrappedFixedIndentingLog(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None, style='%', width=70, indent=4):
        super().__init__(fmt=fmt, datefmt=datefmt, style=style)
        self.wrapper = textwrap.TextWrapper(width=width, subsequent_indent=' '*indent)

    def format(self, record):
        return self.wrapper.fill(super().format(record))

# standard stuff
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.DEBUG)
consLogger = logging.StreamHandler()
rootLogger.addHandler(consLogger)

# indent=18 matches fixed width of asctime + levelname + spaces
consLogger.setFormatter(WrappedFixedIndentingLog(
    '%(asctime)-8s %(levelname)-8s %(message)s', '%H:%M:%S', indent=18))

message = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
rootLogger.log(logging.DEBUG, message)

rawDescription: wrapped output for python logging.StreamHandler()

description: Wrapped output for python logging.StreamHandler()


code: print(solve(initial_guess=(1, 1), a=1, c=1.1))

rawDescription: Dynamically choose argument for which to minimize a function in python using scipy.optimize


code:
def rshift(val, n): return val>>n if val >= 0 else (val+0x100000000)>>n

rshift(-1000, 3)
rshift(1000, 3)

rawDescription: How to get the logical right binary shift in python

description: Get the logical right binary shift in python


rawDescription: Tuple Numpy Data Type

description: Tuple Numpy Data Type


rawDescription: Using Python to generate URLs with names from txt


code:
from itertools import izip
from collections import defaultdict
r = defaultdict(list)

for k, v in izip(b, a):
    r[k] += [v]

rawDescription: How to map key values using lists?

description: Map key values using lists


code: user = None

rawDescription: Carry a variable across two files in different classes


rawDescription: Parsing Sentences (or other longer strings) in Python (ProblemSetQuestion) How to proceed?


code:
s='\nm222 some stuff \n more stuff'
re.split(r'(\n(?! ))', s)

rawDescription: Split on delimiter except when followed by space


rawDescription: Arduino - python read serial layout

description: Arduino - python read serial layout


code:
infile1 = open(r'C:\pythontmp\numpyArray.pkl', 'r+b')
file1 = pickle.load(infile1)                           # This is a list
infile1.close()

numpyArray = numpy.array(file1)                        # This is a numpy array

rawDescription: Is there an alternative to numpy.save(file, arr) that will work with pypy?


code:
class Task(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        ordering = ['name']

rawDescription: How to order a reverse foreign key in django

description: Order a reverse foreign key in django


rawDescription: Copying mutable lists in python

description: Copying mutable lists in python


rawDescription: Python: File empty while script is running with sequential write operations


code:
import re
sentence = "foo bar @match don't match @success;"
re.findall('@([a-zA-Z0-9_])*[:;, ]', sentence)

rawDescription: Matching @user with regex

description: Matching @user with regex


code:
indices = []
for i, c in enumerate(encoded):
    if c == old:
        indices.append(i)

rawDescription: Deleting from a python array and restoring to previous state


code: data

rawDescription: Plotting of 2D data : heatmap with different colormaps


code: [(dt - datetime.timedelta(hours=int(dt.hour % 3))).strftime('%Y%m%d%H') for dt in ts.index]

rawDescription: Time-series boxplot in pandas

description: Time-series boxplot in pandas


code:
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose')
parser.add_argument('cmd', nargs='?', default='open',
    choices=['open', 'edit', 'new'])
parser.add_argument('filename', nargs='+')

rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


code:
from __future__ import print_function

from threading import Timer

def hello():
    print("Hello World!")

class RepeatingTimer(object):

    def __init__(self, interval, f, *args, **kwargs):
        self.interval = interval
        self.f = f
        self.args = args
        self.kwargs = kwargs

        self.timer = None

    def callback(self):
        self.f(*self.args, **self.kwargs)
        self.start()

    def cancel(self):
        self.timer.cancel()

    def start(self):
        self.timer = Timer(self.interval, self.callback)
        self.timer.start()

t = RepeatingTimer(3, hello)
t.start()

rawDescription: Timer cannot restart after it is being stopped in Python


code: arith_expr('lhs') + Optional('=' + arith_expr('rhs'))

rawDescription: pyparsing: how to find string of form a + b = c OR c = a + b

description: Pyparsing: how to find string of form a + b = c OR c = a + b


rawDescription: Representing version number as regular expression


code:
def stutter(q):
    q.items = sorted([elm for elm in q.items] + [elm for elm in q.items])

rawDescription: Taking a queue of integers and making copies of that element


code: l = [t for t in l if t[0] != 100]

rawDescription: How to check for a value in a list of tuples?

description: Check for a value in a list of tuples


code:
class MyClass:
    SomeStr = "Any Val"

A = MyClass
A.SomeStr = "Bob"
B=A
B.SomeStr = "Alice"

print(A.SomeStr)
print(B.SomeStr)

rawDescription: Can I add a second name to a variable

description: Add a second name to a variable


rawDescription: Python: given list of columns and list of values, return subset of dataframe that meets all criteria


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

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


code: from __future__ import with_statement

rawDescription: Python how to read and split a line to several integers


code:
def stop_keylogger():
    process.send_signal(signal.SIGUSR1)
    process.wait()
    return process.stderr.read()

rawDescription: Retrieve a value from subprocess after kill()


code: L = [s + '.txt' for s in L]

rawDescription: How to modify list entry in python 2.x, using loop

description: Modify list entry in python 2.x, using loop


rawDescription: Mapping a json file to excel with python


code:
{'Province': 'Ont', 'City': 'Scarborough', 'First_Name': 'John', 'Last_Name': 'Sanderson', 'Postal_Code': 'M9C2C7', 'Customer_ID': '474', 'Street_Address': '17 Chestwood Ave'}

{'Business_Phone': '416/997-2923', 'Home_Phone': '416/227-3297'}

rawDescription: Replace parts of string that occur within a list


code:
means = pd.rolling_mean(test, 50, 50)
means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]
test = pd.concat([test, means], axis=1)

rawDescription: rolling mean in Pandas with fixed time window (instead of fixed nb. of observations)

description: Rolling mean in Pandas with fixed time window (instead of fixed nb. of observations)


rawDescription: Compute each element of matrix

description: Compute each element of matrix


rawDescription: Replace escape characters like \n \t etc with \\t , \\n


rawDescription: numpy's complex128 conversion

description: Numpy's complex128 conversion


rawDescription: Applying functions to multidimensional numpy arrays without loops


code:
k = ['a', 'b']
result = {i: {} for i in df[k[0]].unique()}
for vals, data in df.set_index(k).groupby(list(df.drop(k, axis=1).columns)):
    for a, df_a in data.groupby(level=k[0]):
        res = df_a.reset_index(k[0], drop=True).to_dict('index')
        keys = ','.join(map(str, tuple(res.keys())))
        result[a].update({keys: list(res.values())[0]})

rawDescription: Group and merge similar entries together using Pandas


code:
arr   # Original 2D array
df
oldval = np.array(df['country_codes'])
newval = np.array(df['continent_codes'])
mask = np.in1d(arr,oldval)
idx = np.searchsorted(oldval,arr.ravel()[mask])
arr.ravel()[mask] = newval[idx]
mask.reshape(arr.shape)  # Mask array depiciting which elements were updated
arr  # Updated 2D array

rawDescription: Replace values in numpy 2D array based on pandas dataframe


code:
import csv
import sys
infh = '''\
A,500
B,3.0
C,87
A,200
A,300
B,3.5
D,CALL
E,CLEAN
F,MADRID
G,28000
H,SPAIN
A,150
B,1.75
C,103
D,PUT
'''.splitlines()
outfh = sys.stdout
fields = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
if True:
    reader = csv.reader(infh)
    writer = csv.DictWriter(outfh, fields)
    writer.writeheader()
    row = {}
    for key, value in reader:
        if key in row:
            # new row found, write old
            writer.writerow(row)
            row = {}
        row[key] = value
    # write last row
    if row:
        writer.writerow(row)

rawDescription: How to restart an iterator?

description: Restart an iterator


code:
loc = rep.split(' ')[-1].strip()
uni = rep.split(' ').index(loc)

rawDescription: how to get string values using index method in Python

description: Get string values using index method in Python


code: df['Location'] = zip(df.Lat, df.Long)

rawDescription: How to use Pandas to take multi year average in Python

description: Use Pandas to take multi year average in Python


rawDescription: Partitioning a superset and getting the list of original sets for each partition


rawDescription: Python: Pandas DataFrame for tuples

description: Python: Pandas DataFrame for tuples


code:
def process_sent(sent):
    tagged = nltk.pos_tag(nltk.word_tokenize(sent))

    for word, tag in tagged:
        pre, _, post = sent.partition(word)
        if "\n" in pre:
            print("\n", end="")
        print(tag, end=" ")
        sent = post # advance to the next word
    if "\n" in post:
        print("\n", end="")

rawDescription: Map line breaks in sentence to another list


code:
import itertools as IT

def process_a(lines):
    for line in lines:
        line = line.strip()
        if not line: continue
        print('processing A: {}'.format(line))

def process_b(lines):
    for line in lines:
        line = line.strip()
        if not line: continue
        print('processing B: {}'.format(line))

def header_func(line):
    if line.startswith('Header_A'):
        return process_a
    elif line.startswith('Header_B'):
        return process_b
    else: return None  # you could omit this, but it might be nice to be explicit

with open('data', 'r') as f:
    for key, lines in IT.groupby(f, key=header_func):
        if key is None:
            if func is not None:
                func(lines)
        else:
            func = key

rawDescription: Most pythonic way to break up highly branched parser


rawDescription: Find matching rows in 2 dimensional numpy array


code:
stripped = "".join(c for c in normalized if unicodedata.category(c) != "Mn")
stripped

rawDescription: Regex - match a character and all its diacritic variations (aka accent-insensitive)


code:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(...);
# do not touch the modelview matrix anymore!

rawDescription: How do I use gluLookAt properly?

description: Use gluLookAt properly


code:
import ctypes

INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39

internet_set_option = ctypes.windll.Wininet.InternetSetOptionW

internet_set_option(0, self.INTERNET_OPTION_REFRESH, 0, 0)
internet_set_option(0, self.INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)

rawDescription: Change browser proxy settings from Python?


code:
from __future__ import print_function
import numpy as np

amount = 1000
int_rate = 4.5/100
term = 5
nper = 12
mtly_pmt = -np.pmt(int_rate/nper, term*nper, amount)

fmt = 'year {0:2d} {1:8.2f} {2:8.2f}'

for y in range(1, term + 1):
    print(fmt.format(
            y,
            np.fv(int_rate/nper, y*nper, mtly_pmt, -amount),
            mtly_pmt * y * nper
          )
    )

rawDescription: Python 3.5 - Yearly balance on loan

description: Python 3.5 - Yearly balance on loan


code:
L=[['a','b'],['foo','bar'],['spam','eggs'],['b','c'],['spam','bar']]
R={'a','foo'}
[[y for y in x if y not in R] for x in L]

rawDescription: Remove all the words from a list of lists which occur in a given set


code:
assert_equal(test_parser.filename.name, 'filename.p')
assert_equal(test_parser.filename.mode, 'r')

rawDescription: How to test opened files in argparse using nose

description: Test opened files in argparse using nose


code:
def get_by_address(address):
    return [x for x in globals().values() if id(x)==address]

var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = get_by_address(address)

rawDescription: How to access variable by id in Python?

description: Access variable by id in Python


code:
import os
from ctypes import POINTER, c_int, cast, pythonapi

def in_interactive_inspect_mode():
    """Whether '-i' option is present or PYTHONINSPECT is not empty."""
    if os.environ.get('PYTHONINSPECT'): return True
    iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
    #NOTE: in Python 2.6+ ctypes.pythonapi.Py_InspectFlag > 0
    #      when PYTHONINSPECT set or '-i' is present
    return iflag_ptr.contents.value != 0

rawDescription: tell whether python is in -i mode

description: Tell whether python is in -i mode


rawDescription: Finding the highest value

description: Finding the highest value


code:
from ctypes import windll
dc= windll.user32.GetDC(0)

def getpixel(x,y):
    return windll.gdi32.GetPixel(dc,x,y)

rawDescription: Faster method of reading screen pixel in Python than PIL?


code: d = [ i for i in range(0,10)]

rawDescription: How do I declare list in python using for loop in one line?

description: Declare list in python using for loop in one line


rawDescription: Python: speed up removal of every n-th element from list


code: [[a[i] for i in (1, 5, 7)] for a in matrix]

rawDescription: Extract variable number of columns for a matrix


code:
def save(self, force_insert=False, force_update=False, using=None):
        super(QuestionAnswer, self).save(force_insert=force_insert, force_update=force_update, using=using)

        try:
            record = LatestQuestionAnswer.objects.get(question=self.question, answer_set=self.answer_set)

            if record.question_answer == self:
                return#nothing to do no point updating the record as it is already correct

        except ObjectDoesNotExist:
            record = LatestQuestionAnswer(question=self.question, answer_set= self.answer_set)

        record.question_answer = self
        record.save()

rawDescription: Django getting only the most recent object after filtering


code:
result = pd.concat([df, df['Data'].apply(json_to_series)], axis=1)
result

rawDescription: Pandas expand json field across records

description: Pandas expand json field across records


code:
p = subprocess.Popen(['echo', '640x360'], stdout=subprocess.PIPE)
p.communicate()

rawDescription: Redirect subprocess to a variable as a string


rawDescription: Force implementation of a method in all inheriting classes


code:
def put(self, indata):
    newnode = BinTree(indata)

    if self.root is None:
        self.root = newnode
        return self.root

    current = self.root
    while True:
        if indata > current.item:
            # if bigger, go right
            if current.right is None:
                # if right slot is empty, make one
                current.right = newnode
                return newnode
            else:
                current = current.right
        elif indata < current.item:
            # if smaller, go left
            if current.left is None:
                # if left slot is empty, make one
                current.left = newnode
                return newnode
            else:
                # if left slot is full, go deeper
                current = current.left
        else:
            # if equal
            return False

rawDescription: Method isEmpty for binary tree

description: Method isEmpty for binary tree


rawDescription: Assigning integers to strings

description: Assigning integers to strings


code:
words_count = dict()
for file in files:
    for word,value in file.items():
        try: words_count[word].append(value)
        except KeyError: words_count[word] = [value]

rawDescription: List of dictionaries - tracking words frequency per file


code: oldest_files_in_tree("/home/user", 20, (".avi", ".mov"))

rawDescription: Find the oldest file (recursively) in a directory


code:
l1 = [1,2,3]
l2 = ['a','b','c','d','e','f','g']
[i for i in itertools.chain(*itertools.izip_longest(l1,l2)) if i is not None]

rawDescription: fatest way to mix two lists in python

description: Fatest way to mix two lists in python


code:
def __repr__(self):
    return '{0}({1})'.format(str(self.__class__.__name__), self.version)

rawDescription: python __repr__

description: Python __repr__


code:
td = tupledict()
td['foo', 'bar'] = 'spam'
td['foo', 'eggs']   # KeyError

key = 'foo', 'bar'
td[key]    # 'spam'

rawDescription: Nested dictionaries in python with error when accessing non-existent key


code:
X = Q(var1__lte=10, var2=True) & ~(Q(var4=10) | Q(var5=20))
MyModel.objects.filter(X)

rawDescription: Django: extend queryset or exclude from exclude method