code:
list_of_dicts = [{"this": "hi
", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty
", "good bye": "to all of that"}]
[{key: val.replace("
", " ") for key, val in dic.items()} for dic in list_of_dicts]

rawDescription: How to Alter a Dict's Values in a List Comprehension


code: self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'nexus_5', True, True)

rawDescription: Error of Script with MonkeyRunner and AndroidViewClient (Touch)


code:
for row_number, row_data in enumerate(info):
    self.variable = StringVar(...)

rawDescription: Changing textvariable for single OptionMenu in loop Tkinter


code: dont_name_your_variables_list = [i*2 for i in range(10)]

rawDescription: How do I create variables without declaration in python?

description: Create variables without declaration in python


code:
for word in element:
    if word in d:
        d[word].append([Count(int(element[1]), int(element[2]))])
    else:
        d[word] = [Count(int(element[1]), int(element[2]))]

rawDescription: Creating a dictionary from a text file Python


code:
def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''

    gameWord=''
    for c in secretWord:
        if c in lettersGuessed:
            gameWord += c
        else:
            gameWord += '_'

    return gameWord

print(getGuessedWord('stackoverflow', ['s','a','k', 'o', 'r','l']))

rawDescription: Code to edit a string with either '_' or a character hangs


code:
import requests
from bs4 import BeautifulSoup

URL_EPICURIOUS_SEARCH="http://www.epicurious.com/tools/searchresults?search="
SEARCH_TEXT="banana"

# Run the search and get the HTML result
response = requests.get(URL_EPICURIOUS_SEARCH + SEARCH_TEXT)
if response.status_code != 200:
    print("HTTP Status:" + response.status_code)
    exit()

soup = BeautifulSoup(response.text, 'html.parser')
# Search for all links with class "recipeLink"
recipes = soup.find_all("a", class_="recipeLnk")

# Loop through the set and print all hrefs.
for recipe in recipes:
    if recipe.has_attr('href'):
        print(recipe['href'])

rawDescription: When scraping a webpage that uses Javascript (and perhaps other things)


code:
# -*- coding: utf-8 -*-
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

DEBUG = True
TEMPLATE_DEBUG = DEBUG
#print ("base dir path", BASE_DIR)

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name_of_db',
        'USER': 'login_to_db',
        'PASSWORD': 'pass_to_db',
        'HOST': 'localhost',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ru-RU'

LANGUAGES = (
    ('ca', 'Catalan'),
    ('cs', 'Czech'),
    ('de', 'German'),
    ('en', 'English'),
    ('es', 'Spanish'),
    ('fo', 'Faroese'),
    ('fr', 'France'),
    ('it', 'Italian'),
    ('lt', 'Lithuanian'),
    ('mn', 'Mongolian'),
    ('nl', 'Dutch'),
    ('pl', 'Polish'),
    ('ru', 'Russian'),
    ('uk_UA', 'Ukrainian'),
    ('vi', 'Vietnamese'),
    ('zh_CN', 'Chinese'),
)

SITE_ID = 1

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Kiev'
USE_TZ = True

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# STATIC_ROOT is where the static files get placed from STATIC_URL and STATICFILES_DIRS
# when they are collected by "manage.py collectstatic". Static files are used by Apache\nginx
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
#When you’re developing using Django’s development server, you won’t have anything to do with this setting.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = "/home/antonio/projects/bugaga.com/static/"

# URL prefix for static files in your apps
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# STATICFILES_DIRS is a setting you use to declare non app-specific static files
# You can prefixes for templates, as STATICFILES_DIRS = (("downloads", "/opt/webfiles/stats"),)
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    #'/var/www/static/',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
     'django.contrib.staticfiles.finders.FileSystemFinder', # is default; responsible for STATICFILES_DIRS
     'django.contrib.staticfiles.finders.AppDirectoriesFinder', # is default; responsible for $app_name/static/
     'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/antonio/projects/bugaga.com/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'YOUR_SECRET_KEY GENERATED BY DJANGO'

# Make this unique, and don't share it with anybody.

if not hasattr(globals(), 'SECRET_KEY'):
    SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
    try:
        SECRET_KEY = open(SECRET_FILE).read().strip()
    except IOError:
        try:
            from random import choice
            import string
            symbols = ''.join((string.lowercase, string.digits, string.punctuation ))
            SECRET_KEY = ''.join([choice(symbols) for i in range(50)])
            secret = file(SECRET_FILE, 'w')
            secret.write(SECRET_KEY)
            secret.close()
        except IOError:
            raise Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    #DjangoBB_Forum part
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'pagination.middleware.PaginationMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',

    'djangobb_forum.middleware.LastLoginMiddleware',
    'djangobb_forum.middleware.UsersOnline',
    'djangobb_forum.middleware.TimezoneMiddleware',
)

ROOT_URLCONF = 'bugaga.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # Directories where the engine should look for template source files, in search order.
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

                #DjangoBB_Forum part
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',

                'django_messages.context_processors.inbox',
                #'allauth.account.context_processors.account', #not required since v0.21.0
                #'allauth.socialaccount.context_processors.socialaccount', #not required since v0.21.0

                'djangobb_forum.context_processors.forum_settings',
            ],
            #DjangoBB_Forum part
             #'loaders': [
             #    'django.template.loaders.filesystem.Loader', #is the same as DIRS [] not empty
             #    'django.template.loaders.app_directories.Loader', #is the same as APP_DIRS = True
             #    'django.template.loaders.eggs.Loader',
             #]
        },
    },
]

PREREQ_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MY_APPS = [
    'app_places',
    'app_shows_and_times',
]

DJANGOBB_APPS = [
    'django.contrib.sites', #required by django-allauth
    'django.contrib.sitemaps',
    'django.contrib.admindocs',
    'django.contrib.humanize',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.openid',
    #'allauth.socialaccount.providers.facebook', # at first you need to configure Facebook or
    # you will get Error: No Facebook app configured: please add a SocialApp using the Django admin
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.twitter',
    'allauth.socialaccount.providers.vk',

    'pagination',
    'haystack',
    'django_messages',
    'nocaptcha_recaptcha',

    'djangobb_forum',
]

INSTALLED_APPS = PREREQ_APPS + MY_APPS + DJANGOBB_APPS

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

try:
    import mailer
    INSTALLED_APPS += ('mailer',)
    EMAIL_BACKEND = "mailer.backend.DbBackend"
except ImportError:
    pass

try:
    import south
    INSTALLED_APPS += ('south',)
    SOUTH_TESTS_MIGRATE = False
except ImportError:
    pass

FORCE_SCRIPT_NAME = ''

# Haystack settings
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'djangobb_forum/djangobb_index'),
        'INCLUDE_SPELLING': True,
    },
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

# Account settings
ACCOUNT_ACTIVATION_DAYS = 10
LOGIN_REDIRECT_URL = '/forum/'
LOGIN_URL = '/forum/account/login/'
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
)

# Cache settings
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

# Allauth
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_SIGNUP_FORM_CLASS = 'bugaga.forms.SignupForm'

try:
    from local_settings import *
except ImportError:
    pass

rawDescription: How to integrate djangobb in an existing project?

description: Integrate djangobb in an existing project


code:
dt = datetime.datetime(1945, 1, 3, 11, 45, 0, 44000)
td = datetime.timedelta(hours=0, minutes=7, seconds=38.701)
dt + td

rawDescription: Adding a timedelta of the type "hh.mm.ss.ms" to a datetime object


code:
values = [7, 3, 2, 7, 1, 9, 8]

range_by_min, range_by_max = {}, {}

for v in values:
    range_by_min[v] = range_by_max[v] = [v, v]

for v in values:
    if v - 1 in range_by_max and v in range_by_min:
        p, q = range_by_max[v - 1], range_by_min[v]
        del range_by_min[q[0]]
        del range_by_max[p[1]]
        p[1] = q[1]
        range_by_max[p[1]] = p

print(range_by_min, range_by_max)

result = {k: v[1] - v[0] + 1 for k, v in range_by_min.iteritems()}
print(result)

rawDescription: Partitioning a set of values in Python

description: Partitioning a set of values in Python


code:
Input:         Module(None, Stmt([Assign([AssName('t', 'OP_ASSIGN')], Mul((Name('r'), Name('p'))))]))
Substituted:   Module(None, Stmt([Assign([AssName('t', 'OP_ASSIGN')], Mul((CallFunc(Name('sqrt'), [Add((Power((Name('x'), Const(2))), Power((Name('y'), Const(2)))))], None, None), Name('p'))))]))

rawDescription: Parsing an equation with sub-formulas in python


code: fig, ax = plt.subplots()

rawDescription: how to add a plot on top of another plot in matplotlib?

description: Add a plot on top of another plot in matplotlib


rawDescription: How do you change a list of integers and strings into a list of integers and floats in python?

description: Change a list of integers and strings into a list of integers and floats in python


code:
bins = numpy.unique(data)
bincounts = numpy.bincount(numpy.digitize(data, bins) - 1)
hist = dict(zip(bins, bincounts))

rawDescription: How can I generate a complete histogram with numpy?

description: Generate a complete histogram with numpy


rawDescription: Setting path directories for running files using command, python filename.py


code: set(l) - set(r)

rawDescription: How to delete elements from list of tuples?

description: Delete elements from list of tuples


code:
def function_logger(file_level, console_level = None):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(logging.DEBUG) #By default, logs all messages
    log_name = 'Test_log_' + getDate() + '.log'

    if not logger.handlers:
        if console_level != None:
            ch = logging.StreamHandler() #StreamHandler logs to console
            ch.setLevel(console_level)
            ch_format = logging.Formatter('%(message)s')
            ch.setFormatter(ch_format)
            logger.addHandler(ch)

        fh = logging.FileHandler(log_name.format(function_name), mode='w')
        fh.setLevel(file_level)
        fh_format = logging.Formatter('%(message)s')
        fh.setFormatter(fh_format)
        logger.addHandler(fh)

    return logger

rawDescription: How to avoid duplicate outputs using logging module

description: Avoid duplicate outputs using logging module


code: loader["ticketsLink"]

rawDescription: How to use scrapy.Request to load an element from another page into an item

description: Use scrapy.Request to load an element from another page into an item


code:
lat = 39.463744
long = -76.119411
weather.apply(
    lambda row: dist(lat, long, row['Latitude'], row['Longitude']),
    axis=1)

rawDescription: How to find the closest match based on 2 keys from one dataframe to another?

description: Find the closest match based on 2 keys from one dataframe to another


code: d = [x for x in a if any(y in x for y in b) and not any(y in x for y in c)]

rawDescription: Python Nested List Comprehensions on Multiple Lists


rawDescription: convert entire pandas dataframe to integers in pandas (0.17.0)

description: Convert entire pandas dataframe to integers in pandas (0.17.0)


code:
for link in soup.select('tr.deals span.hotel-name a'):
    print(link['href'])

rawDescription: Get value of attribute using CSS Selectors with BeutifulSoup


rawDescription: Combining two dictionaries into one with the same keys?


rawDescription: Protect commas on consecutive string.join() and string.split()


rawDescription: Is this a good approach to execute a list of operations on a data structure in Python?


code:
import config
import MySQLdb
import MySQLdb.cursors as mc
import _mysql_exceptions
DictCursor = mc.DictCursor
SSCursor = mc.SSCursor
SSDictCursor = mc.SSDictCursor
Cursor = mc.Cursor

class Cursor(object):
    def __init__(self,
                 cursorclass=Cursor,
                 host=config.HOST, user=config.USER,
                 passwd=config.PASS, dbname=config.MYDB,
                 driver=MySQLdb,
                 ):
        self.cursorclass = cursorclass
        self.host = host
        self.user = user
        self.passwd = passwd
        self.dbname = dbname
        self.driver = driver
        self.connection = self.driver.connect(
            host=host, user=user, passwd=passwd, db=dbname,
            cursorclass=cursorclass)
        self.cursor = self.connection.cursor()

    def __iter__(self):
        for item in self.cursor:
            yield item

    def __enter__(self):
        return self.cursor

    def __exit__(self, ext_type, exc_value, traceback):
        self.cursor.close()
        if isinstance(exc_value, Exception):
            self.connection.rollback()
        else:
            self.connection.commit()
        self.connection.close()

with Cursor() as cursor:
    print(cursor)
    connection = (cursor.connection)
    print(connection)

rawDescription: Context manager for Python's MySQLdb

description: Context manager for Python's MySQLdb


rawDescription: Python Wacom Interface

description: Python Wacom Interface


code:
for i in range(0,10,2):
    print(i)

rawDescription: Changing while and for loops in python

description: Changing while and for loops in python


code:
import example
f = example.Function()
f
example.spam(f)

rawDescription: Wrap derived template class with Boost::python


code:
import numpy as np
indi = ~np.abs(indexd)
wav = (np.sum(wv))/(len(wv)*(len(wv)-1))
thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2

rawDescription: Translating mathematical functions from MATLAB to Python


code: x = to_binary(int(x, 2) + 1)

rawDescription: Incrementing a binary number in python

description: Incrementing a binary number in python


code:
from dateutil import parser

dt = parser.parse('2014-02-06 13:30:00-05:00')

rawDescription: Python: time conversion

description: Python: time conversion


code:
items = ["Apple","Banana","Orange","Peach"]
inputs = {'Banana', 'Apple'}
next((i for i, c in enumerate(combinations(items, 2)) if set(c) == inputs), None)

rawDescription: Comparing Permutation and Combinations

description: Comparing Permutation and Combinations


code:
def coords_maker(num_x, num_y):
    return [[0]*num_x for x in range(num_y)]

rawDescription: python3 string to variable

description: Python3 string to variable


code:
#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')

strings = re.search(r"^\s*[^#]*IgnoreRhosts\s+yes", f.read(), flags=re.MULTILINE)
print(strings.group(0))

rawDescription: Python regex search for string at beginning of line in file


code:
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt

# Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)

# Coordinates of the line we'd like to sample along
line = [(-3, -1), (4, 3)]

# Convert the line to pixel/index coordinates
x_world, y_world = np.array(zip(*line))
col = z.shape[1] * (x_world - x.min()) / x.ptp()
row = z.shape[0] * (y_world - y.min()) / y.ptp()

# Interpolate the line at "num" points...
num = 1000
row, col = [np.linspace(item[0], item[1], num) for item in [row, col]]

# Extract the values along the line, using cubic interpolation
zi = scipy.ndimage.map_coordinates(z, np.vstack((row, col)))

# Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].pcolormesh(x, y, z)
axes[0].plot(x_world, y_world, 'ro-')
axes[0].axis('image')

axes[1].plot(zi)

plt.show()

rawDescription: Plot cross section through heat map

description: Plot cross section through heat map


rawDescription: Splitting comma delimited strings in python


code:
import asyncio

@asyncio.coroutine
def begin():
    print("Starting to wait.")
    asyncio.get_event_loop().call_later(10, end)

def end():
    print("completed")

if __name__ == "__main__":
    try:
        loop = asyncio.get_event_loop()
        loop.create_task(begin())
        loop.run_forever()
    except KeyboardInterrupt:
        print("Goodbye!")

rawDescription: asyncio's call_later raises 'generator' object is not callable with coroutine object

description: Asyncio's call_later raises 'generator' object is not callable with coroutine object


code: table = list(itertools.product([False, True], repeat=n))

rawDescription: python build a dynamic growing truth table

description: Python build a dynamic growing truth table


code:
X,Y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100))
A = np.sin(9.5*pi*X) + np.sin(9.5*np.pi*Y)

rawDescription: Nonuniform sampling for 2D image in Python


code:
class data:
    def __init__(self):
        # Contains list of x, y, z, time lists
        self.x = []
        self.y = []
        self.z = []
        self.time = []

rawDescription: Creating classes in dictionaries - values being duplicated between classes?


code:
data = []
target = []
with open('faban.txt') as fobj:
    for line in fobj:
        row = line.split()
        data.append(row[:-1])
        target.append(row[-1])

rawDescription: Python: How to read file and store certain columns in array


code:
from random import choice

numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

r1 = choice(numbers)
r2 = choice(numbers)

print("h = HIGHER ,, l = LOWER ,, s = SAME")
print(r1)
a = raw_input()
print(r2)

if r2 == r1 and a == 's':
    print("well done")
elif r2 < r1 and a == 'l':
    print("well done")
elif r2 > r1 and a == 'h':
    print("well done")
else:
    print("unlucky")

rawDescription: How to use random numbers properly in "Higher or Lower" game. I'm only a beginner

description: Use random numbers properly in "Higher or Lower" game. I'm only a beginner


code:
if isinstance(value,list):
    for v in value:
        parent = find_parent(search_term,v,key)
        if parent is not None: return parent

rawDescription: Why does my recursive function return "None"?


code:
def remove(x):
    for phrase in remove_l:
        if re.search(phrase, x):
            if phrase == '-':
                new = x.replace(phrase, ' ')
            else:
                new = x[re.search(phrase, x).span()[1]:].strip()
            return new  # <- returns here (in first phase)
        else:
            return x  # <- or returns here (in first phase)

rawDescription: using a for loop within a .apply() for pandas dataframes

description: Using a for loop within a .apply() for pandas dataframes


rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code: from uncertainties import sin

rawDescription: Definition of mathematical operations (sin…) on NumPy arrays containing objects


code:
from zmq import Stopwatch    # ok to use pyzmq 2.11 for [usec] .Stopwatch()
aStopWATCH =    Stopwatch()  # a performance measurement .Stopwatch() instance

sig    = np.abs(sig)         # self-destructive calc/assign avoids memalloc-OPs
aConst = ( 1 - alpha )       # avoids many repetitive SUB(s) in the loop

for thisPtr in range( 1, len( sig ) ): # FORWARD-SHIFTING-DEPENDENCE LOOP:
    prevPtr = thisPtr - 1              # prevPtr->"previous" TimeSlice in out[] ( re-used 2 x len(sig) times )
    if sig[thisPtr] < out[prevPtr]:                                    # 1st re-use
       out[thisPtr] = out[prevPtr] * beta                              # 2nd
    else:
       out[thisPtr] = out[prevPtr] * alpha + ( aConst * sig[thisPtr] ) # 2nd

rawDescription: Vectorize a python loop over a numpy array


code: list1 = read("file1.csv")

rawDescription: Condensing Repetitive Code

description: Condensing Repetitive Code


code:
M[I+3,J+2]=m.data
M.A

rawDescription: Scipy sparse matrix assignment using only stored elements


code: tokens = iter(filter(None, (i.strip() for i in resexp.split(s))))

rawDescription: converting nested parenthesis tree to nested list

description: Converting nested parenthesis tree to nested list


code:
for filename in filenames:
    with open(filename, 'r+') as f:
        data = f.read()
        f.seek(0)
        f.truncate()
        for k, v in mappings:
            data = data.replace(k, v)
        f.write(data)

rawDescription: Fastest way to compare and replace key value pairs in Python


code:
for row in reader:
    if row['gene_id'] == 'CG11710':
        writer.writerow(row)

rawDescription: Iteratively copy specific rows from CSV file to new file


code:
my_dict={}
with open('file.dat', 'rb') as csvfile:
    dataReader=csv.reader(csvfile)
    for name,item1,item2 in dataReader:
         my_dict.setdefault(name,[]).append([item1,item2])

rawDescription: Parse a file into a dictionary of arrays


code: filtered = [x for x in os.listdir('.') if not any(fnmatch.fnmatch(x, p) for p in excluded)]

rawDescription: Python: removing multiple values from a list where using filters is more awkward


code:
keys = groups.groups.keys()
for index in range(0, len(keys) - 1):
    g1 = df.ix[groups.groups[keys[index]]]
    g2 = df.ix[groups.groups[keys[index + 1]]]
    # Do something with g1, g2

rawDescription: Iterating over groups (Python pandas dataframe)


code:
A = np.array([[1, 1, 1, 0, 1, 1],
              [1, 2, 2, 0, 1, 2],
              [1, 3, 3, 0, 1, 3]])

def unique_columns2(data):
    dt = np.dtype((np.void, data.dtype.itemsize * data.shape[0]))
    dataf = np.asfortranarray(data).view(dt)
    u,uind = np.unique(dataf, return_inverse=True)
    u = u.view(data.dtype).reshape(-1,data.shape[0]).T
    return (u,uind)

rawDescription: Getting the indexes to the duplicate columns of a numpy array


code: max(list_of_iterables, key=min)

rawDescription: Find maximum value of minimum elements in tuple


rawDescription: How to filter a "}"

description: Filter a "}"


code: return final_img

rawDescription: Serving an image from PIL dynamically

description: Serving an image from PIL dynamically


code:
for i in range(len(position)):
    if position[i][0] > limit_x or position[i][0] < 0:
        velocity[i][0] = -velocity[i][0]
    if position[i][1] > limit_y or position[i][1] < 0:
        velocity[i][1] = -velocity[i][1]

rawDescription: Many particles in box - physics simulation


code:
def np_unpack(data) :
    # find where condition is met
    mask = (data & 0x01).astype(bool)
    # Keep only 1st, 3rd, 5th... consecutive occurrences of True in mask
    new_mask = mask[:]
    mult = -1
    while new_mask.sum() :
        new_mask = np.logical_and(new_mask,
                                  np.concatenate(([False], new_mask[:-1])))
        mask +=  new_mask * mult
        mult *= -1
    del new_mask
    cond = np.nonzero(mask)[0]
    result = np.empty(data.shape, dtype='int16')
    result[:] = data.astype('int8') >> 1
    result[cond] <<= 8
    result[cond] += data[cond + 1]
    mask = np.ones(data.shape, dtype=bool)
    mask[cond + 1] = False
    return result[mask]

rawDescription: Iterating over a numpy array, selectively picking one or two values, given a criterion


code: ['America/Anguilla', 'America/Antigua', 'America/Aruba', 'America/Barbados', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Campo_Grande', 'America/Cuiaba', 'America/Curacao', 'America/Dominica', 'America/Glace_Bay', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guyana', 'America/Halifax', 'America/Kralendijk', 'America/La_Paz', 'America/Lower_Princes', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Moncton', 'America/Montserrat', 'America/Port_of_Spain', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Santo_Domingo', 'America/St_Barthelemy', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Thule', 'America/Tortola', 'America/Virgin', 'Atlantic/Bermuda', 'Brazil/West', 'Canada/Atlantic', 'Etc/GMT+4']

rawDescription: Python - Timezone name given timestamp UTC and UTC offset


code:
var = 'I have a string I want GE and APPLES but nothing else'
[x for x in var.split() if x.isupper() and len(x) > 1 ]

rawDescription: Looking for a good way to split a string on all-capital words


thing: foo

thing: bar

rawDescription: How to assign one JSON key to all output dictionaries?

description: Assign one JSON key to all output dictionaries


code: l = len(v)

rawDescription: Declare and assign an amount of variables from an input?


code:
f = lambda x: x + 10
f(3)

rawDescription: How to use filter() on a string and get multiple word occurences?

description: Use filter() on a string and get multiple word occurences


code:
import pprint
pprint.pprint(data)

rawDescription: Error parsing JSON in python

description: Error parsing JSON in python


code:
import csv
from collections import defaultdict
from functools import partial
genes = defaultdict(partial(defaultdict, dict))
with open('mydata.txt', 'rb') as f:
    for row in csv.DictReader(f, delimiter='\t'):
        genes[row['geneid']][row['tx_id']]['colname1'] = row['colname1']
        genes[row['geneid']][row['tx_id']]['colname2'] = row['colname2']

rawDescription: Initialize/Create/Populate a Dict of a Dict of a Dict in Python


code:
df['direction'] = df['Close'].diff(3).abs()
df['volatility'] = pd.rolling_sum(df['Close'].diff().abs(), 3)

rawDescription: Calculating Kaufman's Efficiency Ratio in Python with Pandas?


code:
def __getattr__(self, attr):
    print("Calling __getattr__: "+attr)
    if hasattr(self.child, attr):
        def wrapper(*args, **kw):
            print('called with %r and %r' % (args, kw))
            return getattr(self.child, attr)(*args, **kw)
        return wrapper
    raise AttributeError(attr)

rawDescription: How are arguments passed to a function through __getattr__


code:
import module1
import module2

rawDescription: python import all modules to a python file which we can import in another file?

description: Python import all modules to a python file which we can import in another file


code:
from itertools import groupby
from operator import itemgetter

def extract_keys(mapping, prefix):
    prefix = '{}_'.format(prefix)

    # test for the `.._count` key first, if it's not there, bail out early
    if prefix + 'count' not in mapping:
        return None

    # find all matching keys, split out the counter for sorting and grouping
    keys = [(k, int(k.split('_', 2)[1]))
        for k in mapping if k.startswith(prefix) and k != prefix + 'count']
    keys.sort(key=itemgetter(1))

    # group keys on the counter, then generate a dictionary per counter value
    return [{k[0].split('_', 2)[-1]: mapping[k[0]] for k in group}
        for c, group in groupby(keys, itemgetter(1))]

rawDescription: dictionary that contains list

description: Dictionary that contains list


code:
class User(db.Model):
    __tablename__ = 'User'

    ID = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))

    friendships = db.relationship(
        'Friendship',
        foreign_keys='Friendship.User_id',
        backref='friender',
    )
    friendships_of = db.relationship(
        'Friendship',
        foreign_keys='Friendship.Friend_id',
        backref='friendee',
    )

class Friendship(db.Model):
    __tablename__ = 'Friendship'
    ID = db.Column(db.Integer, primary_key=True)
    User_id = db.Column(db.Integer, db.ForeignKey('User.ID'))
    Friend_id = db.Column(db.Integer, db.ForeignKey('User.ID'))

rawDescription: SQLAlchemy: exclude rows taken from a subquery on a query


rawDescription: printing list of categories as a column

description: Printing list of categories as a column


code:
letters = ['a','b','c','d','e']
drop(letters, 3)

rawDescription: User Defined Slice function in python script


code:
for i, e in enumerate(ells):
    ax.add_patch(e)
    e.set(clip_box=ax.bbox, alpha=rand(), facecolor=rand(3),
          label='Ellipse{}'.format(i+1))
ax.legend()

rawDescription: Label plotted ellipses

description: Label plotted ellipses


code: open(out, "+a").write()

rawDescription: Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines)


code: js_text = soup.find('script', type="text/javascript").text

rawDescription: Parsing JS with Beautiful soup

description: Parsing JS with Beautiful soup


code:
def original(values, items):
    l = np.empty(items.size, dtype=np.int32)
    k, K = 0, len(values)
    for i, item in enumerate(items):
        while k < K and values[k] < item:
            k += 1
        l[i] = k
    return l

def peter_e(values, items):
    l = np.empty(items.size, dtype=np.int32)
    last_idx = 0
    for i, item in enumerate(items):
        last_idx += values[last_idx:].searchsorted(item)
        l[i] = last_idx
    return l

rawDescription: searching sorted items into a sorted sequence

description: Searching sorted items into a sorted sequence


code: words = [word for line in f for word in line.split()]

rawDescription: Removing a space from a list element?

description: Removing a space from a list element


code:
nodes_list_nodes = Table(
    'nodes_list_nodes', metadata,
    Column('parent_id', None, ForeignKey('nodes_list.id'), nullable=False),
    Column('child_id', None, ForeignKey(Node.id), nullable=False),
    PrimaryKeyConstraint('parent_id', 'child_id'),
)

class ListNode(Node):
    __mapper_args__ = {'polymorphic_identity': 'list'}
    __tablename__ = 'nodes_list'
    id = Column(None, ForeignKey('nodes.id'), primary_key=True)
    items = relation(Node, secondary=nodes_list_nodes)

rawDescription: Creating container relationship in declarative SQLAlchemy


code:
s = 'The quick brown fox jumps over the lazy dog'
over = re.compile('over')
brown = re.compile('brown')
m_brown = brown.search(s)
m_brown.span()
m_over = over.search(s)
m_over.span()

rawDescription: Find length of string matched by regex

description: Find length of string matched by regex


code:
# ...
plt.gca().set_color_cycle(['black', 'pink', 'green'])

plt.plot(x,y)
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()

rawDescription: how to use matplotlib's set_cmap()?

description: Use matplotlib's set_cmap()


code: min([mincoinList[price-coin] for coin in coins if coin <= price]) + 1

rawDescription: Returning minimum of array with for loop iteration


code: result = numpy.einsum('...ij,...jk->...ik', X, Y)

rawDescription: Multiplying matrix A times multi-dimensional matrix "matrix-wise?"


code:
from operator import itemgetter

l = sorted(myHash.items(), key=itemgetter(1), reverse=True)
largestKey, largestNum = l[0]

rawDescription: Python printing single key/value pairs from a dict


code:
if glob is None:
    import sys
    glob = sys._getframe().f_back.f_globals

rawDescription: How to replace execfile() with exec() in Pydev on Ctrl+Alt+Enter key binding?

description: Replace execfile() with exec() in Pydev on Ctrl+Alt+Enter key binding


code:
from collections import namedtuple

@classmethod
def from_kws(cls, **kw):
    return cls(*(kw[k] for k in cls._fields))

def namedtuple(name, fields, namedtuple=namedtuple):
     nt = namedtuple(name, fields)
     nt.from_kws = from_kws
     return nt

rawDescription: Is it possible to specify attribute names when creating an instance of namedtuple?


code: r'"Postal Code":(\d+),'

rawDescription: Python capture group and quote it with regex


rawDescription: Can we use variable in name of variable in python


rawDescription: Find missing data in pandas dataframe and fill with NA


code:
df = df.reset_index()
df['group_min'] = df.groupby('i')['a'].transform('min')

rawDescription: Sort pandas DataFrame by multiple columns and duplicated index


code:
def set_color_cycle(self, clist):
    """
    Set the color cycle for any future plot commands on this Axes.

    *clist* is a list of mpl color specifiers.
    """
    self._get_lines.set_color_cycle(clist)
    self._get_patches_for_fill.set_color_cycle(clist)

rawDescription: Reset color cycle in Matplotlib

description: Reset color cycle in Matplotlib


code:
with open('testfile','r') as infile:
   parse2(parse1(infile,'4'))

rawDescription: Cancel last line iteration on a file

description: Cancel last line iteration on a file


code: ['Day','Date','Week']

rawDescription: Is it possible to display only first list element in for loop?


code:
from Tkinter import Tk, Text, DISABLED
r = Tk()
t = Text(r)
t.grid()
t.insert(0.0, "BLAH!")
# Just make sure you disable it AFTER you put the text in
t["state"] = DISABLED
r.mainloop()

rawDescription: Is there a way to make a Text widget in Tkinter non-clickable and non-editable?


rawDescription: Django JSONField filtering

description: Django JSONField filtering


code:
try:
    from local_settings import *
except ImportError:
    pass

rawDescription: Calling a script that contains solely an email address


code: arr_c = np.where((abs(arr_a - arr_b)/arr_b) > 0.3, 1, 0)

rawDescription: Create numpy array based on magnitude of difference between arrays


code:
array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
np.bincount(array_)
np.bincount(array_)[array_]

rawDescription: numpy fastest way to transform an array's elements to their frequency

description: Numpy fastest way to transform an array's elements to their frequency


code:
with open('filename', 'rb') as f:
    contents = f.read().decode('utf-8-sig')    # -sig deals with BOM, if present

rawDescription: Python open("x", "r") function, how do I know or control which encoding the file is supposed to have?


code:
for col, val in enumerate(mylist, start=1):
    sheet.cell(row=2, column=col).value = val

rawDescription: Writing to row using openpyxl?

description: Writing to row using openpyxl


code:
if context is None:
    context = globals()
for step_type in ('given', 'when', 'then', 'step'):
    step_decorator = registry.make_decorator(step_type)
    context[step_type.title()] = context[step_type] = step_decorator

rawDescription: How are Behave's decorators created/declared?


code:
application = Application([SomeService], 'tns',
    in_protocol=Soap11(validator='lxml'),
    out_protocol=Soap11(polymorphic=True)
)

rawDescription: How do you @rpc _returns polymorphic types in spyne?


code:
[{'account_id_credit': 695, 'account_id_debit': 476, 'amount': 76571.0, 'type': u'expense', 'name': 'Payment'},
 {'account_id_credit': 385, 'account_id_debit': 476, 'amount': 42140.0, 'type': u'expense', 'name': 'Payment'},
 {'account_id_credit': 695, 'account_id_debit': 641, 'amount': 43926.0, 'type': u'payable', 'name': 'Payment'},
 {'account_id_credit': 695, 'account_id_debit': 323, 'amount': 67357.0, 'type': u'payable', 'name': 'Payment'}]

rawDescription: Python: merge n-dictionaries depending on several values + sum


rawDescription: Python(pandas): removing duplicates based on two columns keeping row with max value in another column


code:
class MainSearchForm(FacetedSearchForm):

    def search(self):

        query = self.cleaned_data['q']
        g = geocoders.Google()
        place, (lat, lng) = g.geocode('%s' % query)
        pnt = fromstr('POINT(%s %s)' % (lng, lat), srid=4326)

rawDescription: Can Haystack filter by a geodjango PointField?


code:
def removestudent(elem,l):
    l.remove(elem)
    return l

l=[1,2,3,4]
removestudent(input("insert the user you wish to remove: "),l)

rawDescription: Python- Function which deletes an element from a list by name


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

x=np.linspace(0,np.pi*2,1000)
plt.plot(x,np.sin(x),hold=True)
plt.plot(x,np.sin(x)**2,hold=True)
plt.show()

rawDescription: What does the matplotlib `hold` keyword argument do?


code:
def __dir__(self):
    return sorted(self)

rawDescription: Extract methods of a class from the keys of a dictionary


code:
data = pd.DataFrame(np.random.randn(2,6), columns=pd.MultiIndex.from_product([['A', 'B', 'C'], ['a', 'b']]))
data
data2 = data[[column for column in data.columns if 'A' in column]]
data2
data2.columns.levels

rawDescription: Deep copy of DataFrame does not remove columns


code: c = get_confg()

rawDescription: How to import a python file at the start of ipython notebook

description: Import a python file at the start of ipython notebook


code: B.configure(command = mainprg1)

rawDescription: display a series of interfaces using Tkinter in python

description: Display a series of interfaces using Tkinter in python


code:
fid = open('out.txt')  # Just copy what you put in your question inside a file.
l = fid.readlines()  # Read the whole file into a list.
d = {}  # create a dictionary.
for i in l:
    s = i.split()  # split the list using spaces (default)
    d[s[0]] = [int(s[j]) for j in range(1,len(s))] # list comprehension to transform string into its for you number lists.

print(d)

rawDescription: Creating array from CSV in Python while limiting columns used


rawDescription: How can i find if the date lies between two dates

description: Find if the date lies between two dates


rawDescription: Override python logging for test efficiency


code:
class NoPropertyAdaptor(object):
    def __init__(self, obj):
        self.obj = obj

    def __getattr__(self, name):
        if name.startswith("get_"):
            return lambda: getattr(self.obj, name[4:])
        elif name.startswith("set_"):
            return lambda value: setattr(self.obj, name[4:], value)
        else:
            return getattr(self.obj, name)

rawDescription: Python: renaming method names on-the-fly


code:
class Root(object):
    def __init__(self):
        self.children = []

class Node(object):
   def __init__(self,parent):
        self.parent = parent
        parent.children.append(self)

rawDescription: best way to represent a bidirectional traversable hierarchy

description: Represent a bidirectional traversable hierarchy


code: idx = range(len(S))

rawDescription: Pairwise Set Intersection in Python

description: Pairwise Set Intersection in Python


rawDescription: Grouping consecutive dates together

description: Grouping consecutive dates together


rawDescription: Python mailbox encoding errors

description: Python mailbox encoding errors


rawDescription: pandas display results grouped by column

description: Pandas display results grouped by column


code:
i=0
s=set(df.index)
top=[]
while s :
    x,y = w.index[i]
    if x in s and y in s :
        top += (x,y),
        s -= {x,y}
    i+=1

rawDescription: Smallest Difference Between 2 object in Dataframe


rawDescription: Listing blog entries by year,month

description: Listing blog entries by year,month


code:
p = argparse.ArgumentParser()
p._add_action(ActionNoYes('foo', 'foo', help="Do (or do not) foo. (default do)"))
p.parse_args(['--no-foo', '--foo', '--no-foo'])
p.print_help()

rawDescription: In Python argparse, is it possible to have paired --no-something/--something arguments?


code: dict((n, [nested_dicts[i][n] for i in range(1,301)]) for n in ["name1","name2","name3"])

rawDescription: Python dictionaries: changing the order of nesting


code: [callable(x) for x in iterable]

rawDescription: question about filtering a dictionary using a list in python

description: Question about filtering a dictionary using a list in python


code:
from collections import Counter

counts = Counter()

for sentence in sequence_of_sentences:
    counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())

rawDescription: Count word occurrence in a list of strings


code:
def Calculate():
    global result
    op, resultName, result = ops[operation]
    for item in operandList:
        result = op(result, item)
    if result == int(result):
        print(int(result), '=', resultName)
    else:
        print(result, '=', resultName)
    print()

rawDescription: Pythonic way to write calculate function for a calculator - Python


rawDescription: python split all lines in columns, no spaces in lines

description: Python split all lines in columns, no spaces in lines


code:
import numpy as np

# select filtering indexes
filter_indexes = [1, 3]
# generate the test data
raw_data = np.random.randint(0, 4, size=(50,5))

# create a column that we would use for indexing
index_columns = raw_data[:, filter_indexes]

# sort the index columns by lexigraphic order over all the indexing columns
argsorts = np.lexsort(index_columns.T)

# sort both the index and the data column
sorted_index = index_columns[argsorts, :]
sorted_data = raw_data[argsorts, :]

# in each indexing column, find if number in row and row-1 are identical
# then group to check if all numbers in corresponding positions in row and row-1 are identical
autocorrelation = np.all(sorted_index[1:, :] == sorted_index[:-1, :], axis=1)

# find out the breakpoints: these are the positions where row and row-1 are not identical
breakpoints = np.nonzero(np.logical_not(autocorrelation))[0]+1

# finally find the desired subsets
subsets = np.split(sorted_data, breakpoints)

rawDescription: Python & Numpy - create dynamic, arbitrary subsets of ndarray


code: pingstatus = check_ping()

rawDescription: Python Function to test ping

description: Python Function to test ping


code:
class TestClass(object):
    def __init__(self, name):
        self.name = name
        self.state = 0
    def getName(self):
        self.state = self.state + 1
        return "%s -- %i" % (self.name, self.state)

class TestClassDict(dict):
    def __missing__(self, key):
        res = self[key] = TestClass(key)
        return res

db = TestClassDict()
db['charlie'].getName()
db

rawDescription: python: defaultdict with non-default argument

description: Python: defaultdict with non-default argument


code: pwds = [" ".join(random.choice(words) for _ in range(3)) for _ in range(100)]

rawDescription: Using Random in Python's list comprehension


code:
import pytest

def pytest_runtest_makereport(item, call):
    if "incremental" in item.keywords:
        if call.excinfo is not None:
            parent = item.parent
            parent._previousfailed = item

def pytest_runtest_setup(item):
    previousfailed = getattr(item.parent, "_previousfailed", None)
    if previousfailed is not None:
        pytest.xfail("previous test failed (%s)" %previousfailed.name)

rawDescription: Pytest: how to skip the rest of tests in the class if one has failed?


rawDescription: Know the depth of a dictionary

description: Know the depth of a dictionary


rawDescription: sleekxmpp pubsub example

description: Sleekxmpp pubsub example


code:
array = {
    'vertex': values[0],
    'visited': values[1],
    'letter': values[2],
}
# access via array['vertex']

rawDescription: Passing values to array indexes in Python


code:
x4 = np.sum(sm1-sm1[:,None,:], 0).reshape(N,M,L)
# = np.sum(sm1[None,:,:]-sm1[:,None,:], 0).reshape(N,M,L)

rawDescription: Despite many examples online, I cannot get my MATLAB repmat equivalent working in python


code:
offset = 0
data1 = np.memmap('tmp', dtype='i', mode='r+', order='F',
                  offset=0, shape=(size1))
offset += size1*byte_size
data2 = np.memmap('tmp', dtype='i', mode='r+', order='F',
                  offset=offset, shape=(size2))
offset += size1*byte_size
data3 = np.memmap('tmp', dtype='i', mode='r+', order='F',
                  offset=offset, shape=(size3))

rawDescription: Is it possible to map a discontiuous data on disk to an array with python?


code:
def alphabetical():
    scoreslist = []
    with open ("classa.txt") as f:
        # just iterate over the file object
        # line by line
        for line in f:
            # don't need to pass a delimiter
            split_line = line.split()
            name = split_line[0]
            score = split_line[1:]
            # use max to get the highscore and use int as the key
            # or "123" < "2"
            high_score =  max(score,key=int)
            scores_list.append("{} {}".format(name,high_score))
    # don't need lambda to sort alphabetically
    scores_list.sort()
    print(scores_list)

rawDescription: Python: Import from text file to list and sort/average based on multiple columns


rawDescription: What is a "good" palette for divergent colors in R? (or: can viridis and magma be combined together?)


code:
A
element

rawDescription: Find element by text with XPath in ElementTree


code:
averaged = my_panel.resample('24H', how='mean')
list(averaged.items)  # Show new time stamps for data

rawDescription: Timeseries average with python

description: Timeseries average with python


code: re.sub(r'(\d)', confirmSub(r"\1m"), "Each of the 2 cars is 5 long.")

rawDescription: Interactive substitution - re.sub() with pos?


code:
canvas = tkinter.Canvas(frame1, width=450, height=450)
raw_turtle = turtle.RawTurtle(canvas)

rawDescription: Put histogram in tkinter frame

description: Put histogram in tkinter frame


rawDescription: Python 3, how to convert a string into "iso-8859-1" to use in html


code:
idxs = list.range(4)
idxs.pop(2) #this removes elements from the list
a[:, idxs]

rawDescription: How to remove a column in a numpy array?

description: Remove a column in a numpy array


code:
from collections import defaultdict
counts = defaultdict(int)
for c in 'abbba':
  counts[c] += 1
counts

rawDescription: How to iterate over the elements of a map in python

description: Iterate over the elements of a map in python


code:
def f_it(f):
    for line in f:
        yield map(int, line.split())

connection = {}
with open("test.txt") as f:
    for a,b,c in f_it(f):
        connection[(a,b)] = c

rawDescription: Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary


code:
a = Example()
a.cl_print()
a[0].cl_print()

rawDescription: How to have a list in python which returns a default item on an invalid index or no index at all

description: Have a list in python which returns a default item on an invalid index or no index at all


code:
re.search('Quality\=(\d+/\d+)', n) #matches a number a slash and a number #/#
re.search('level\=([+-]?\d+)', n) #matches 1 or more numbers so ignore dbm

rawDescription: Python regex match issue and grouping multiple groups


rawDescription: Sorting data dynamically based upon key names and value combos


code:
def method(self, key):
    some_list = list(irrelevant_extraction_function(key, self.some_dict))
    self.storage[key] = [item['address'] for item in some_list]

rawDescription: Combine methods with identical structure but different parameters


code:
class Stack(list):
    push = list.append

def modify_stack(symbolString):
    stack=Stack()
    result = []
    for character in symbolString:
        if character != '*':
            stack.push(character)
        else:
            result.append(stack.pop())
    return ''.join(result)

rawDescription: stack, push and pop in python

description: Stack, push and pop in python


code: soFar = soFar[:index*2] + newChar + soFar[index*2+1:]

rawDescription: use .replace() on only one character of a string with repetitive characters

description: Use .replace() on only one character of a string with repetitive characters


code:
def find_maxmin_ratios(lines):
    lines = [row.split() for row in lines]  # the file should already break at each line break
    lines = [(int(row[0]), row[1]) for row in lines]
    lines = groupby(sorted(lines), lambda x: x[0])  # combine strings into their respective groups, sorting them first on int of first element
    group_minmax = dict()
    for index, group in lines:
        strings = list(group)  # need to convert group[1] from iterator into list
        if len(strings) > 1:  # if the number of strings is 1, then there is nothing to compare the string with in its group
            max_similarity = 1
            min_similarity = 0
            for line1, line2 in combinations(strings, 2):
                s = difflib.SequenceMatcher(None, line1[1], line2[1])  # need to compare second element in each list and exclude the first element (which is the group number)
                max_similarity = s.ratio() if s.ratio() < max_similarity else max_similarity
                min_similarity = s.ratio() if s.ratio() > min_similarity else min_similarity
            group_minmax[index] = (1 - max_similarity, 1 - min_similarity)  # gives max difference ratio and then min difference ratio
    return group_minmax

rawDescription: Calculate the greatest distance between any two strings in a group, using Python


code:
import clr
clr.AddReference("System")
from System.Diagnostics import Process
Process.Start("hh.exe", r"mk:@MSITStore:C:\planta\client\Help\Planta.chm::/D-KA-0044095.html")

rawDescription: ironpython: How to call a chm Helpfile on Windows with parameters

description: Ironpython: How to call a chm Helpfile on Windows with parameters


code: help(enumerate)

rawDescription: Build list of tuples from simple list

description: Build list of tuples from simple list


code:
CityFormSet = formset_factory(CityNameForm, min_num=1, max_num=5,
                              validate_min=True, validate_max=True,
                              formset=RequiredFormSet, extra=0)

rawDescription: FormSet rendering always two forms as default Django


rawDescription: Spark ALS predictAll returns empty

description: Spark ALS predictAll returns empty


rawDescription: Special Vector and Element-wise Multiplication


code:
class Business(db.Model):
  bus_contact_info_ = db.ReferenceProperty()

rawDescription: App Engine, Cross reference between two entities


code: driver = webdriver.Firefox()

rawDescription: Setting path to firefox binary on windows with selenium webdriver


code:
class Character:
    def go(self, direction, location):
        self.location = location
        self.direction = direction
        #call code based on direction

rawDescription: Turn user input strings into a function call


code:
print("These words are in both files:")
for word in exist_words.intersection(source_words):
    print(word)

rawDescription: How to find words inside two text files

description: Find words inside two text files


code:
# The default argument here is useless.
def Recocido(tour1 = []):

    # Make a copy of the list.
    tour1 = tour1[:]

    # Pick a random index.
    izquierda = random.randrange(len(tour1))

    # Unnecessary.
    derecha = 0

    while(True):

        # # Pick another random index
        derecha = random.randrange(len(tour1))

        # If it's not the same index you picked the first time,
        if (derecha != izquierda):

            # swap the elements of the copy at the two indices,
            tour1[izquierda], tour1[derecha] = tour1[derecha], tour1[izquierda]

            # and stop looping.
            break

    return tour1

rawDescription: Python TSP Berlin 52 with Simulated Annealing


code:
# get that array row
data[data['name']=='World'][0]
(2, 3.0, 'World')

# get individual value
data[data['name']=='World'][0][0]
2

rawDescription: cutting structured numpy arrays

description: Cutting structured numpy arrays


code:
nvals = 3  # -> RuntimeWarning
x = np.linspace(0,1,10)
y = np.random.randint(low=0,high=nvals,size=x.shape)
z = x
interp.interp2d(x,y,z)

nvals = 4  # -> no problem here
x = np.linspace(0,1,10)
y = np.random.randint(low=0,high=nvals,size=x.shape)
z = x
interp.interp2d(x,y,z)

rawDescription: scipy interp2d/bisplrep unexpected output when given 1D input

description: Scipy interp2d/bisplrep unexpected output when given 1D input


code:
mapping = {'count': int, 'leaf': dict}
mapping['branch'] = lambda: KeyBasedDefaultDict(mapping)
tree = KeyBasedDefaultDict(mapping)
tree['branch']['count'] += 23
tree['branch']['leaf']['tag1'] = 30
tree['branch']['leaf']['tag2'] = 10
tree

rawDescription: Python nested defaultdict with mix data types


code:
for row in data:
    row[set_col] = val

rawDescription: Python - best way to set a column in a 2d array to a specific value


code:
with open('words') as f3data:
    mydict = dict(enumerate(line.strip() for line in f3data))

rawDescription: Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?


code:
uniprot_id = 'P12345'
url = 'http://www.uniprot.org/uniprot/'+uniprot_id+'.xml'

rawDescription: Biopython: Getting XML-file by Protein accession


rawDescription: NumPy: array assignment issue when using custom dtype


code: drivenKeys = cmds.keyframe("myAnimCurve", q=True, valueChange=True)

rawDescription: How do I find the time of a particular keyframe using cmds.selectKey?

description: Find the time of a particular keyframe using cmds.selectKey


code:
df = pd.DataFrame(["LONG AAPL 2X CBZ", "SHORT GOOG 10X VON", "BULL AXP UN X3 VON","LONG AXP X3 VON"], columns=["Name"])

maps = {"AAPL": "Apple", "GOOG": "Google"}
signs = {"SHORT": "-"}

def split(i):
    spl = i.split()
    a, b, c = spl[0], spl[1], spl[-2]
    val = maps.get(b, b) # if name is not to be replaced keep original
    return "Tracks  {} with {}{} leverage".format(val, signs.get(a, ""), c)

df["Description"]  = df["Name"].map(split)

rawDescription: Pandas: Insert variable substrings into column B from column A with help of dictionary


code:
def results(funcs, xs, ys):
  for f in funcs:
    for x in xs:
      for y in ys:
        try:
          yield f(x,y)
        except ZeroDivisionError:
          pass

rawDescription: Building a variable that combines several enumerations in an enormous list


code:
if request.user.user_type == "A":
      foo = request.user.User1.profile_pic
else:
      foo = request.user.User1.avatar

rawDescription: Multiple users in django

description: Multiple users in django


rawDescription: Filtering DataFrame using the length of a column


code:
def ori(df):
    df['y']=df['x'].str.strip().str.split(' ').str.get(0)
    df['z']=df['x'].str.split(' ').str.get(1)

def lam(df):
    df["y"] = df.x.apply(lambda x:x.split()[0])
    df["z"] = df.x.apply(lambda x:x.split()[1] if len(x.split())>1 else "ND")

rawDescription: Splitting columns more efficiently

description: Splitting columns more efficiently


code: newlist = [int(x) for x in numbers if x > 0]

rawDescription: python list comprehension - learnpython.org

description: Python list comprehension - learnpython.org


code:
for worker in worker_list:
    total_hours += sum(worker_list[worker]) * 13

rawDescription: Looping and returning all values in a dictionary


rawDescription: Filter, group, and calculate statistics for Numpy matrix data


code:
import pandas as pd

df = pd.DataFrame({'ID': ['XY0001','ZZ1111','AA008','BB0234','ZZ9999','XY0333']})
print(df)

df = df[(df.ID.str[2:].astype(int) >= 1) & (df.ID.str[2:].astype(int) <= 879)]
print(df)

rawDescription: Select rows in pandas dataframe for which value in the column is in XY0001-XY0879 where X and Y can be any digit


rawDescription: Python remove couple of duplicates from List


code:
from twisted.internet import defer
from twisted.protocols.policies import TimeoutMixin
from twisted.protocols.basic import LineOnlyReceiver

class PingPongProtocol(LineOnlyReceiver, TimeoutMixin):

    def __init__(self):
        self.lock = defer.DeferredLock()
        self.deferred = None

    def sendMessage(self, msg):
        result = self.lock.run(self._doSend, msg)
        return result

    def _doSend(self, msg):
        assert self.deferred is None, "Already waiting for reply!"

        self.deferred = defer.Deferred()
        self.deferred.addBoth(self._cleanup)
        self.setTimeout(self.DEFAULT_TIMEOUT)
        self.sendLine(msg)
        return self.deferred

    def _cleanup(self, res):
        self.deferred = None
        return res

    def lineReceived(self, line):
        if self.deferred:
            self.setTimeout(None)
            self.deferred.callback(line)
        # If not, we've timed out or this is a spurious line

    def timeoutConnection(self):
        self.deferred.errback(
            Timeout("Some informative message"))

rawDescription: python twisted - Timeouting on a sent message that did not get a response

description: Python twisted - Timeouting on a sent message that did not get a response


code:
match
matcher.a[match.a:match.a+match.size]
match.a
match.b

rawDescription: Trying to find a match in two strings - Python


code: df.query("annual rate > 1")

rawDescription: Using dynamic lists in query in Pandas

description: Using dynamic lists in query in Pandas


code:
from decimal import Decimal
my_str_as_a_decimal = Decimal(my_str)
my_str_as_a_decimal + 1

rawDescription: get the value without ' '

description: Get the value without ' '


code:
import re
sum(len(c) == 1 for s in data for c in re.split(r'[^b]{1}', s)) # 9

rawDescription: Count specific characters with a specific condition in python


rawDescription: Making static methods explicitly reference the class


code:
from contextlib import contextmanager

class DbLink(object):
    """This class knows how to connect to the database."""
    # ...
    # Basically we wrap a sqlalchemy.orm.sessionmaker value here, in session_registry.
    # You might want to create sessions differently.

    @contextmanager
    def CommittingSession(self, **kwargs):
      """Creates a session, commits at the end, rolls back on exception, removes.

      Args:
        **kwargs: optional; supplied to session_registry while asking
          to construct a session (mostly for testing).

      Yields:
        a session object. The session will .commit() when a `with SimpleSession()`
        statement terminates normally, or .rollback() on an exception.
      """
      try:
        session = self.session_registry(**kwargs)  # this gives us a session
        # transaction has already begun here, so no explicit .begin()
        yield session
      except:
        session.rollback()
        raise
      else:
        session.commit()
      finally:
        # Note: close() unbinds model objects, but keeps the DB connection.
        session.close()
        self.session_registry.remove()

rawDescription: How to manage this pattern this sqlalchemy

description: Manage this pattern this sqlalchemy


code:
for flower in range(len(labels)):
        print (X[flower],labels[flower])

rawDescription: At what part does the iris data receive a labeled cluster?


rawDescription: Removing blank objects within a tuple

description: Removing blank objects within a tuple


rawDescription: Python equivalent for do.call(rbind, lapply()) from R


code:
f = open('file.pkl', 'r')
cfd = pickle.load(cfd)
f.close()

rawDescription: Storing conditional frequency distribution using NLTK


code:
@classmethod
def get_description(cls):
    desc = super(AdvancedGenerator, cls).get_description()
    return desc + ' Advanced(tm) ' + cls.adv_feature

rawDescription: How to call a parent class's @classmethod from an overridden @classmethod in Python?

description: Call a parent class's @classmethod from an overridden @classmethod in Python


code: [(item, dct[pattern]["age"]) for item in lst for pattern in dct if pattern in item]

rawDescription: match/search dict keys in elements of a list

description: Match/search dict keys in elements of a list


code:
desc = example.xpath(u'//description')
desc[0].tag
desc[0].attrib  # This node has no attributes.

rawDescription: Basic Python XML data extraction

description: Basic Python XML data extraction


code:
df.values[[np.arange(5)]*2] = 0
df

rawDescription: Set values on the diagonal of pandas.DataFrame


code:
# Messaging system table
class Message(db.Model):
    __tablename__ = 'message'

    emmiter_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    text = db.Column(db.Text, nullable=False)

rawDescription: Self-referential database with extra fields in sqlalchemy


code: pascalVals = raw_input('...').split()

rawDescription: How do I separate a space-delimited string into multiple variables?

description: Separate a space-delimited string into multiple variables


code:
marr = np.vectorize(np.array,otypes=[np.ndarray])
L=[[[1,2,3],[4,5]],[[6,7,8,9],[10]]]
L=marr(L) # L is a ndarray of ndarray
L+L
# array([[array([2, 4, 6]), array([ 8, 10])],[array([12, 14, 16, 18]), array([20])]], dtype=object)

rawDescription: append the same element to several sublists in python

description: Append the same element to several sublists in python


code:
class IpPort:
    def __init__(self, ip, port, time, status):
        self.ip = ip
        self.port = port
        self.time = time
        self.status = status

    def dump(self):
        return {"IpPortList": {'ip': self.ip,
                               'port': self.port,
                               'time': self.time,
                               'status': self.status}}

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

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


code:
macros = subprocess.check_output(['gcc', '-dM', '-E', '-', 'foo.h'])
for line in macros.splitlines():
    try:
        _, name, value = line.split(None, 2)
        constants[name] = ast.literal_eval(value)
    except Exception as e:
        pass # again, do something nicer

rawDescription: Is there a way to load the constant values stored in a header file via ctypes?


code: max(freqs)

rawDescription: Plotting power spectrum in python

description: Plotting power spectrum in python


code: LOGIN_URL = '/login/'  # hardcoded url

rawDescription: Is LOGIN_REDIRECT_URL deprecated?

description: Is LOGIN_REDIRECT_URL deprecated


code:
# Sorts an array of 4 coordinates, each an array w/ 2 numbers
#  into counter-clockwise order starting from top left

rawDescription: Python modules lib.util and lib.geom

description: Python modules lib.util and lib.geom


code:
points = ((p.x,p.y) for p in lasfile.File(inFile,None,'r'))

X_Max = float('-inf')
X_Min = float('+inf')
Y_Max = float('-inf')
Y_Min = float('+inf')

for p in points:
    X_Max = max(X_Max, p.x)
    X_Min = min(X_Min, p.x)
    Y_Max = max(Y_Max, p.y)
    Y_Min = min(Y_Min, p.y)

rawDescription: Python: How to improve performance of a script to obtain the Bounding Box of a set of points


code:
import matplotlib as mpl
mpl.rcParams['pdf.fonttype'] = 42

rawDescription: Cannot edit text in chart exported by Matplotlib and opened in Illustrator


code: x = [x for x in d if x <= cutoff]

rawDescription: transforming nested dictionaries into various lists

description: Transforming nested dictionaries into various lists


code: dict(random.sample(votes_selected.iteritems(), int(len(votes_selected) * DATA_PERCENTAGE / 100)))

rawDescription: Randomly Keep X Percent of Dictionary

description: Randomly Keep X Percent of Dictionary


code: cars = {driver: car(driver, sponsor) for driver, sponsor in drivers.items()}

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code: [x for i, x in enumerate(xs) if curp(x) or i>0 and prevp(xs[i-1])]

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


code: {u'postalcode': u'CA 90015', u'city': u'Los Angeles', u'geo:point': {u'geo:long': u'-118.259068', u'geo:lat': u'34.040729'}, u'street': u'1038 S. Hill St', u'country': u'United States'}

rawDescription: Retrieving Venue Information with pylast and last.fm


code:
def do_it(a=2, b=5, c=21, *args):
    args = (a,b,c)+args

rawDescription: default values for variable argument list in Python

description: Default values for variable argument list in Python


rawDescription: Numpy Compare unequal rows and make both array of same dimension


code:
def setIcon(self):
    icon = "icon.ico"

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


code:
name = re.sub(r"\.", r" ", name)
name = re.sub(r"C126", "Perception", name)
name = re.sub(r"Geo1", "Geography", name)

rawDescription: Multiple Re.Subs Python

description: Multiple Re.Subs Python


rawDescription: Finding in regex pattern the name of possible groups


code:
class Created():
    def __init__(self, creator):
        self.creator = creator
        self.parameter = self.creator.parameter

rawDescription: Can a class instance created by another class instance access the creator's members?


rawDescription: Concisely stack a constant with a Numpy array?


code:
name = 'George'
space = ' * '
space.join(name) + ' * .'

rawDescription: Taken username: how can I have only one space at the end when suggesting an alternative username?


code:
import argparse
import sys
import unittest

# this part copied from unittest.__main__.py
if sys.argv[0].endswith("__main__.py"):
    import os.path
    # We change sys.argv[0] to make help message more useful
    # use executable without path, unquoted
    # (it's just a hint anyway)
    # (if you have spaces in your executable you get what you deserve!)
    executable = os.path.basename(sys.executable)
    sys.argv[0] = executable + " -m leveltest"
    del os

def _id(obj):
    return obj

# decorator that assigns test levels to test cases (classes and methods)
def level(testlevel):
    if unittest.level < testlevel:
        return unittest.skip("test level too low.")
    return _id

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--level', type=int, default=3)
    ns, args = parser.parse_known_args(namespace=unittest)
    return ns, sys.argv[:1] + args

if __name__ == "__main__":
    ns, remaining_args = parse_args()

    # this invokes unittest when leveltest invoked with -m flag like:
    #    python -m leveltest --level=2 discover --verbose
    unittest.main(module=None, argv=remaining_args)

rawDescription: Passing arguments (for argparse) with unittest discover


code:
oldlist = ["asdf", "ghjk", "qwer", "tyui"]
removeset = set([1, 3])
[v for i, v in enumerate(oldlist) if i not in removeset]

rawDescription: Remove multiple items from list in Python


code: dstr = "".join(x + "(++info {0}++)".format(chr(y)) for x, y in zip(dstr.split("(++info++)"), range(ord('a'), ord('z'))))[:-len("(++info a++)")]

rawDescription: Replace a pattern in python

description: Replace a pattern in python


rawDescription: python list of tuples to javascript array of arrays

description: Python list of tuples to javascript array of arrays


code:
class dbref(object):

    def __init__(self, number):
        self.dbnumber = number

    def getdbref(self):
        return self.dbnumber

rawDescription: Placing custom class object in a list

description: Placing custom class object in a list


code:
cmd = 'ssh ubuntu@192.168.56.101 \'`sed -i -e s/property=\\"true\\"/property=\\"false\\"/g ~/cfg.cfg`\''
subprocess.call(['ssh', 'ubuntu@192.168.56.101', 'cat ~/cfg.cfg'])
subprocess.call(cmd, shell=True)
subprocess.call(['ssh', 'ubuntu@192.168.56.101', 'cat ~/cfg.cfg'])
shlex.split(cmd)

rawDescription: How to transport " for remote execution?

description: Transport " for remote execution


code: Brand

rawDescription: Retrieving the name of a class attribute with lxml


code:
from django.conf import settings
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.template.defaultfilters import slugify

User = settings.AUTH_USER_MODEL

class BaseUserManager(BaseUserManager):

    def create_user(self, useremail, display_name, password=None):
        if not useremail:
            raise ValueError('Users must have an email address')

        now = timezone.now()

        user = self.model(useremail=BaseUserManager.normalize_email(useremail))
        user.display_name = display_name
        user.email = useremail
        user.profile_slug = getUniqueValue(BaseUser,slugify(useremail.split("@")[0]),field_name="profile_slug")
        user.set_password(password)
        user.status='A'
        user.last_login = user.date_joined = now
        user.save(using=self._db)
        return user

    def create_superuser(self, useremail, display_name, password):
        user = self.create_user(useremail=useremail,
            display_name=display_name, password=password)
        user.email = useremail
        user.display_name = display_name
        user.is_superuser = True
        user.is_staff = True
        user.status='A'
        user.save(using=self._db)
        return user

class BaseUser(AbstractBaseUser, PermissionsMixin):
    display_name = models.CharField(max_length=25)
    profile_slug = models.CharField(max_length=25,null=True)
    gender = models.CharField(max_length=1, blank=True, choices=Gender)
    useremail = models.EmailField(unique=True)
    is_staff = models.BooleanField(default=False)
    user_status = models.CharField(max_length=1, default='A')
    USERNAME_FIELD = 'useremail'
    REQUIRED_FIELDS = ['display_name']
    objects = BaseUserManager()

    def __unicode__(self):
        return self.display_name

rawDescription: Django-rest: How to implement authentication and permissions for custom User models?


code:
import numpy as np
import pandas as pd
def tostr(series):
    return series.astype(str)

dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987], 'Wteam' :[9, 10, 11, 4, 5, 6], 'lteam': [ 1, 2, 3, 12, 13, 14] }
pdf = pd.DataFrame(dictionary)
pdf['result'] = np.where(pdf['Wteam'] > pdf['lteam'], 0, 1)
pdf['min'] = pdf[['Wteam','lteam']].min(axis=1)
pdf['max'] = pdf[['Wteam','lteam']].max(axis=1)

pdf['Season_value'] = tostr(pdf['Year'])+'_'+tostr(pdf['min'])+'_'+tostr(pdf['max'])

print(pdf[['Season_value', 'result']])

rawDescription: looping and transformation in pandas

description: Looping and transformation in pandas


code:
myvar = [1, 2, '3']
",".join(map(lambda x: str(x).strip(), myvar))
myvar = [1, 2, 3, ' 4 ']
",".join(map(lambda x: str(x).strip(), myvar))

rawDescription: Remove leading and trailing spaces from a Python list


rawDescription: Python : How do i get a new column for every file I read?


rawDescription: Clicking element in table based on condition on another element in the same row


code:
a1=np.arange(2)
a2=np.arange(10).reshape(2,5)
a3=np.arange(8).reshape(2,4)

np.hstack([a1.reshape(-1,1),a2,a3])
np.hstack([a1[:,None],a2,a3])
np.column_stack([a1,a2,a3])

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


code:
def Run(*args, **kwargs):
  return _Run(True, *args, **kwargs)

rawDescription: Wrap a function in python supplying an additional boolean


rawDescription: Apostrophe within Python lookbehind assertion


code:
#!/usr/bin/env python
# CommentedTreeBuilder.py
from xml.etree import ElementTree

class CommentedTreeBuilder(ElementTree.TreeBuilder):
    def __init__(self, *args, **kwargs):
        super(CommentedTreeBuilder, self).__init__(*args, **kwargs)

    def comment(self, data):
        self.start(ElementTree.Comment, {})
        self.data(data)
        self.end(ElementTree.Comment)

rawDescription: Faithfully Preserve Comments in Parsed XML (Python 2.7)


code:
import httplib2

class TokenFromOAuth2Creds:
  def __init__(self, creds):
    self.creds = creds
  def modify_request(self, req):
    if self.creds.access_token_expired or not self.creds.access_token:
      self.creds.refresh(httplib2.Http())
    self.creds.apply(req.headers)

rawDescription: Is it possible to use "Domain-wide Delegation of Authority" with gdata-python-client?


code:
for each, every in zip(string2, string1):
    m.select(each)
    every(each)

rawDescription: python execute list and list of functions

description: Python execute list and list of functions


code:
import re

financialData = """
David Meredith, Financial Director sold post-exercise 15,000 shares in the company on YYYY-mm-dd at a price of 1044.00p. The Director now holds 6,290 shares representing 0.01% of the...

Mark Brookes, Non Executive Director bought 811 shares in the company on  YYYY-mm-dd at a price of 76.75p. The Director now holds 189,952 shares representing 0.38% of the shares in...

Albert Ellis, CEO bought 262 shares in the company on YYYY-mm-dd at a price of 52.00p. The Director now holds 465,085 shares. NOTE: Purchased through Co's SIP Story provided by...
"""

print(re.findall('(.*?),\s(.*)\s(sold(?: post-exercise)?|bought|exercised)\s*([\d,]*).*price of\s*(\d*.\d+?p)',financialData))

rawDescription: Python regex to parse financial data

description: Python regex to parse financial data


code:
def sparse_row_normalize(sps_mat) :
    if sps_mat.format != 'csc' :
        msg = 'Can only row-normalize in place with csc format, not {0}.'
        msg = msg.format(sps_mat.format)
        raise ValueError(msg)
    row_norm = np.sqrt(np.bincount(sps_mat.indices, weights=mat.data * mat_data))
    sps_mat.data /= np.take(row_norm, sps_mat.indices)

rawDescription: Modify scipy sparse matrix in place

description: Modify scipy sparse matrix in place


rawDescription: Modified time using os.stat in Python gets lower when copying files


code:
l = [u'[190215]']
l = [item for value in l for item in literal_eval(value)]
l

rawDescription: Remove 'u' from a python list

description: Remove 'u' from a python list


code:
hash = hashlib.sha1(object_to_cache_as_string).hexdigest()
cache[hash] = object_to_cache

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


code:
class InspectorCheckAdmin(admin.ModelAdmin):
    list_display = ('id', 'check_address', 'check_form', 'check_target_name')

class InspectorCheckAdminDeleted(admin.ModelAdmin): # or inherit from other ModelAdmin
    list_display = ('id', 'check_address', 'check_form', 'check_target_name', 'editor', 'updated')
    def queryset(self, request):
        return InspectorCheck.trash

#and in last step create and register both classes:

InspectorCheckDeleted = create_proxymodel(InspectorCheck, 'InspectorCheckDeleted', meta={
    'verbose_name': u'Inspector check (deleted)',
    'verbose_name_plural': u'Inspector checks (deleted)'}
)
admin.site.register(InspectorCheck, InspectorCheckAdmin)
admin.site.register(InspectorCheckDeleted, InspectorCheckAdminDeleted)

rawDescription: Best practice for data-entry in Django admin site (different ModelAdmin on the same model)


rawDescription: Parsing and chopping a long string in Python


code:
from django.db import transaction
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from myapp.forms import FormA, FormB

@transaction.commit_on_success
def present_forms_to_user(request):
    if request.method == 'POST':
        form_a = FormA(request.POST)
        form_b = FormB(request.POST)

        if form_a.is_valid() and form_b.is_valid():
            # processing code

            return HttpResponseRedirect('/path/to/thank/you/page/')
    else:
        form_a = FormA()
        form_b = FormB()

    return TemplateResponse(request, 'templates/eggs.html', {
        'form_a': form_a,
        'form_b': form_b,
    })

rawDescription: Django forms question

description: Django forms question


code:
con = {'type': 'ineq',
       'fun': lambda x, a: a.dot(x) - 10,
       'jac': lambda x, a: a,
       'args': (a,)}

rawDescription: Scipy, optimize a function with argument dependent constraints


code:
d = Data["weight_factors"]
myvar = d["parameter1"] * d["parameter2"] + d["parameter3"]

rawDescription: Accessing the values of a key

description: Accessing the values of a key


code:
def get_pattern(length):
    template = [1, 2, 4, 8]
    output = []
    i = 0
    while True:
        num = template[i%4] * 10**(i//4)
        if num > length:
            break
        output += [num]
        i += 1
    return output

rawDescription: Using a pattern for making a list

description: Using a pattern for making a list


code: df.reset_index().pivot_table(index="industry", columns="Sector", values="Symbol").T.plot(kind='bar', stacked=True, figsize=(14, 6))

rawDescription: Stacked Bar Plot with Two Key DataFrame

description: Stacked Bar Plot with Two Key DataFrame


code:
import numpy as np
a = [[1,1],[1,1]]
a = np.array(a)
a * 0.1

rawDescription: How to multiply sequence by non-int of type 'float'?

description: Multiply sequence by non-int of type 'float'


code:
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)

rawDescription: How to make HTTP DELETE method using urllib2?

description: Make HTTP DELETE method using urllib2


code:
class MySettingsDict(dict):

    def __getitem__(self, item):
        function, arg = dict.__getitem__(self, item)
        return function(arg)

def expensive_to_compute(arg):
    return arg * 3

rawDescription: Setup dictionary lazily

description: Setup dictionary lazily


rawDescription: Split diary file into multiple files using Python


code:
import numpy
import time
from matplotlib import pyplot as plt

if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion()
    for loop in xrange(1, 4):
        y = numpy.dot(loop, x)
        plt.close()
        plt.figure()
        plt.plot(x,y)
        plt.draw()
        time.sleep(2)

rawDescription: Can I generate and show a different image during each loop with Matplotlib?

description: Generate and show a different image during each loop with Matplotlib


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

import tornado.ioloop
import tornado.web
import signal
import logging
from tornado.options import options

is_closing = False

def signal_handler(signum, frame):
    global is_closing
    logging.info('exiting...')
    is_closing = True

def try_exit():
    global is_closing
    if is_closing:
        # clean up here
        tornado.ioloop.IOLoop.instance().stop()
        logging.info('exit success')

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    tornado.options.parse_command_line()
    signal.signal(signal.SIGINT, signal_handler)
    application.listen(8888)
    tornado.ioloop.PeriodicCallback(try_exit, 100).start()
    tornado.ioloop.IOLoop.instance().start()

rawDescription: How to stop the tornado web server with ctrl+c?

description: Stop the tornado web server with ctrl+c


code:
# reads the forth line into 1x1 df being a string,
# then splits it and skips the first field:
col_names = pd.read_table('path', skiprows=3, nrows=1, header=None).iloc[0,0].split()[1:]
# reads the actual data:
df = pd.read_table('path', sep=' ', skiprows=4, names=col_names)

rawDescription: How to skip text being used as column heading using python

description: Skip text being used as column heading using python


code:
with open('highscores.txt', 'rb') as f:
    scores = [line.strip().split(',') for line in f]

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

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


code:
a_set = set(a) # using sets allows the `in` function to run in
i_set = set(i) # constant time vs. running in linear time (its faster for large data sets)
[x if x in i_set else "" for x in a] + [x for x in i if x not in a_set]

rawDescription: Creating Array with Comparison from Other Arrays in Python


code:
def b(df, row_mask):
    df.loc[row_mask,'b'] = 'foo'

rawDescription: Passing DataFrame slice as argument to function without 'SettingWithCopyWarning'


code:
{'test_nose.test1.TestExampleOne.test_one': 1.0009748935699463,
 'test_nose.test2.test_one': 2.0003929138183594,
 'test_nose.test3.TestExampleThree.test_one': 4.000233173370361,
 'test_nose.test3.TestExampleTwo.test_one': 3.001115083694458}

rawDescription: How to benchmark unit tests in Python without adding any code

description: Benchmark unit tests in Python without adding any code


code:
@classmethod
def cmd(cls, argv=ListProxy(sys.argv)):
    " Executes the command. "

rawDescription: Avoid expansion of sys.argv keyword argument in Sphinx documentation


code:
from datetime import date
import json

class DateEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, date):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

rawDescription: psycopg2 execute returns datetime instead of a string

description: Psycopg2 execute returns datetime instead of a string


code:
class Map(dict):
    """
    Example:
    m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
    """
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.iteritems():
                    self[k] = v

        if kwargs:
            for k, v in kwargs.iteritems():
                self[k] = v

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]

rawDescription: How to use a dot "." to access members of dictionary?

description: Use a dot "." to access members of dictionary


code: [[x for _ in xrange(y)] for x,y in zip(a,b)]

rawDescription: Creating list of individual list items multiplied n times


code: args = docopt.docopt(_(__doc__))

rawDescription: How to have the docstring respect the PEP257, while usable with docopt to comply with i18n using gettext?

description: Have the docstring respect the PEP257, while usable with docopt to comply with i18n using gettext


code:
def shape_preserving_mult(x, y):
    return x * y.reshape(x.shape)

shape_preserving_mult(x, y)
shape_preserving_mult(x, y.T)
shape_preserving_mult(x.T, y)
shape_preserving_mult(x.T, y.T)

rawDescription: Elementwise multiply 1D-numpy arrays (shapes (k,1) or (k,)) and have result have the shape of the first


code: new_dict[values[0]] = [key]

rawDescription: Get a string list from a word

description: Get a string list from a word


code:
with open("file.dat", "r") as data:
    for line in data:
        runFunction(line[0], line[1], line[2], line[3])

rawDescription: Given a large dataset in file A, how can I reference it in a simulation in file B?


code: unique = set(tuple(sorted(t)) for t in inputlist)

rawDescription: Set of string tuples in python

description: Set of string tuples in python


code:
import turtle

s = turtle.Screen()
t = turtle.Turtle()

length = None
while not length:
    try:
        length = float(input('Enter your preferred turtle line length: '))
    except ValueError:
        print('You need to enter a number')

width = None
while not width:
    try:
        width = int(input('Enter your preferred turtle line width: '))
    except ValueError:
        print('You need to enter a positive integer')
    else:
        if width < 1:
            print('You need to enter a positive integer')
            width = None
color = None
while not color:
    color = input('Enter your preferred turtle line color: ')
    try:
        t.pencolor(color)
    except:
        print('You need to enter a color that I know.')
        color = None
shape = None
while not shape:
    shape = input('Specify whether you want to draw a line, triangle, or square: ')
    if shape.lower() not in ['line', 'triangle', 'square']:
        shape = None
        print('I only draw lines, triangles and squares!')

t.pensize(width)
if shape == 'line':
    t.forward(length)
elif shape == 'triangle':
    t.forward(length)
    t.right(120)
    t.forward(length)
    t.right(120)
    t.forward(length)
else:
    t.forward(length)
    t.right(90)
    t.forward(length)
    t.right(90)
    t.forward(length)
    t.right(90)
    t.forward(length)

s.exitonclick()

rawDescription: Python: Write a program that asks the user for a color, a line width, a line length and a shape


rawDescription: Using Argparse and Json together

description: Using Argparse and Json together


code: 'FEDCBA'[score]

rawDescription: Generating several variable outputs without using if statements


code:
from itertools import combinations
r = [float(d['avgreturns']) * b for d, b in l]
p = combinations(r,2)
print(sum(r))

rawDescription: Python: get dictionary value from a dictionary within a tuple within a list and do something with it


code:
for row_number in range(len(table)):  # iterate over the row indices

    for column_number in range(len(table[row_number])):  # iterate over the column indices
                                                         # of the current row

        print("Row:", row_number, "- Column:", column_number)
        print(" --> Item:", table[row_number][column_number])

        # <-- jump back to the column loop head here, if elements remaining

    # <-- jump back to the row loop head here, if elements remaining

rawDescription: why does order of loop nesting matter python?

description: Why does order of loop nesting matter python


rawDescription: How to alter a part of an array

description: Alter a part of an array


code:
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
    response_headers.append((str('Set-Cookie'), str(c.output(header=''))))

rawDescription: Django cookies and headers

description: Django cookies and headers


code:
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if all(x in deltaa for x in strings): #Check if all items in strings exit in deltaa
            print (deltaa)

rawDescription: Match multiple strings containing lines from file python


code:
from ast import literal_eval
lines = []
with open(infile_path, 'r') as infile:
    for line in infile:
        line = literal_eval(line)
        lines.append(line)

rawDescription: How do i sort a lot of lists to get a top 10 in python?

description: Sort a lot of lists to get a top 10 in python


code:
@overload((str, int))
def h():
    return 0

rawDescription: Decorator for overloading in Python

description: Decorator for overloading in Python


code:
upper_bound = 1000

sqr = [i**2 for i in range(upper_bound+1)]

def solutions(p):
    result = []

    for a in range(1, p - 1):
        for b in range(1, p - a):
            c = p - (a + b)
            if a < b < c:
                d = sqr[a]
                e = sqr[b]
                f = sqr[c]

                if (d + e == f) or (e + f == d) or (f + d == e):
                    result.append((a, b, c))
    return len(result)

max_p = 0
max_solutions = 0

for p in range(3, upper_bound+1):
    print("Processing %d" % p)
    s = solutions(p)

    if s > max_solutions:
        max_solutions = s
        max_p = p

print("%d has %d solutions" % (max_p, max_solutions))

rawDescription: How to optimize this Python script?

description: Optimize this Python script


code:
from django import template

register = template.Library()

@register.filter('in_group')
def in_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

rawDescription: Django - Show/hide urls in base html dependant on user group?


code:
data = [('field', 'var1'), ('save', 'stringA'), ('field', 'var2'), ('save', ''), ('field', 'var3'), ('save', 'stringC')]
[(field[1], save[1]) for field, save in zip(*[iter(data)]*2)]

rawDescription: Compacting tuples from a QS

description: Compacting tuples from a QS


code:
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                showfliers=False)

rawDescription: Tweaking seaborn.boxplot

description: Tweaking seaborn.boxplot


code: classes_inverse = {v: k for k, v in classes.items()}

rawDescription: Unable to match tuples items to list items


code:
basicfile = open('membersofcongress.txt', 'r')

for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[+0:partyst-1]
   outfile = open('memberswcomma.txt','a')
   outp = name + "," + party + "\n"
   outfile.write(outp)
   outfile.close()

basicfile.close()

rawDescription: Making a loop to write new lines to a txt file using python


rawDescription: Convert Columns to String in Pandas

description: Convert Columns to String in Pandas


rawDescription: Special kind of row-by-row multiplication of 2 sparse matrices in Python


code:
def parseRange(rangeStr, i=0):
    # Recursion anchor, return empty set if we're out of bounds
    if i >= len(rangeStr):
        return set()

    # charSet will tell us later if we actually have a range here
    charSet = None

    # There can only be a range if we have more than 2 characters left in the
    # string and if the next character is a dash
    if i+2 < len(rangeStr) and rangeStr[i+1] == '-':

        # We might have a range. Valid ranges are between the following pairs of
        # characters
        pairs = [('a', 'z'), ('A', 'Z'), ('0', '9')]

        for lo, hi in pairs:
            # We now make use of the fact that characters are comparable.
            # Also the second character should come after the first, or be
            # the same which means e.g. 'a-a' -> 'a'
            if (lo <= rangeStr[i] <= hi) and \
               (rangeStr[i] <= rangeStr[i+2] <= hi):
                   # Retreive the set with all chars from the substring
                   charSet = parseRange(rangeStr, i+3)

                   # Extend the chars from the substring with the ones in this
                   # range.
                   # `range` needs integers, so we transform the chars to ints
                   # using ord and make use of the fact that their ASCII
                   # representation is ascending
                   charSet.update(chr(k) for k in
                           range(ord(rangeStr[i]), 1+ord(rangeStr[i+2])))
                   break

    # If charSet is not yet defined this means that at the current position
    # there is not a valid range definition. So we just get all chars for the
    # following subset and add the current char
    if charSet is None:
        charSet = parseRange(rangeStr, i+1)
        charSet.add(rangeStr[i])

    # Return the char set with all characters defined within rangeStr[i:]
    return charSet

rawDescription: How to get the corresponding chars with a pattern in Python

description: Get the corresponding chars with a pattern in Python


code: cnt = contours[0] # you're only checking the 1st contour here

rawDescription: Minimum Bounding Box for image regions?

description: Minimum Bounding Box for image regions


code:
fig, ax = plt.subplots()
imshow(im)
rect = Rectangle((x, y), tpl.shape[1], tpl.shape[0], edgecolor='r', facecolor='none')
ax.add_patch(rect)

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


code:
uniq = np.unique(idx)  # Or range(idx.max()+1)
uniq

rawDescription: getting median of particular rows of array based on index

description: Getting median of particular rows of array based on index


code:
import numpy as np
def solve(T, a, b):
    A = np.array([range(T), np.ones(T)])
    B = np.array([a, b])
    return np.linalg.lstsq(A, B)[0]

rawDescription: Using Python to Find Integer Solutions to System of Linear Equations


code:
GLOB_CONTENT = []

def read_file_content(path):
    global GLOB_CONTENT
    with open(path) as f:
        # get file content
        content = f.read()
        # do some content processing here
        GLOB_CONTENT.append(content)

rawDescription: Python statement as method's argument

description: Python statement as method's argument


rawDescription: removing last 4 characters in a file with python

description: Removing last 4 characters in a file with python


rawDescription: python how can I find out the duplicate elements in a three dimensional list

description: Python how can I find out the duplicate elements in a three dimensional list


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


code:
remainder = (value % cycle)
min(remainder, cycle - remainder) <= range

rawDescription: algorithm to determine whether a value is within a range of a multiple

description: Algorithm to determine whether a value is within a range of a multiple


code:
a = (session
     .query(
         Gift.gift_idea,
         Person.name.label("person_name"),
         Person.address.label("person_address"),
     )
     # .select_from(Gift)  # @note: optional, but will need it if the first column in the `.query(...)` above will be from table `Person`
     .join(Person)
     )

rawDescription: SQLAlchemy Join two tables in (1 to 0..1 ) relationship


rawDescription: Cython header directive and __future__

description: Cython header directive and __future__


code: return {'value':{'heat_degree_day':temp,'hw_degree_day':temp + 5}}

rawDescription: "TypeError: Cannot read property 'value' of null" in on_change event


rawDescription: Python list comprehensions: set all elements in an array to 0 or 1


code:
10
input_result

rawDescription: How do chained comparisons in Python actually work?


code:
import re

my_string = '438429834njnbjjj"28.30"98nj76789889jkljlkjllmm82'

matches = re.findall(r'".*?"', my_string)

rawDescription: How to print characters based on the surrounding characters

description: Print characters based on the surrounding characters


code:
import numpy as np
import pandas as pd

df1=pd.DataFrame(np.random.rand(10,3), columns=['val', 'X', 'Y'])
df2=pd.DataFrame(np.random.rand(10,3), columns=['val', 'X', 'Y'])

# dataframes to numpy arrays of complex numbers
p1 = (df1['X'] + 1j * df1['Y']).values
p2 = (df2['X'] + 1j * df2['Y']).values

# calculate all the distances, between each point in
# df1 and each point in df2 (using an array-broadcasting trick)
all_dists = abs(p1[..., np.newaxis] - p2)

# find indices of the minimal distance from df1 to df2,
# and from df2 to df1
nearest_idxs1 = np.argmin(all_dists, axis = 0)
nearest_idxs2 = np.argmin(all_dists, axis = 1)

# extract the rows from the dataframes
nearest_points1 = df1.ix[nearest_idxs1].reset_index()
nearest_points2 = df2.ix[nearest_idxs2].reset_index()

rawDescription: How to speed up nearest search in Pandas (perhaps by vectorizing code)

description: Speed up nearest search in Pandas (perhaps by vectorizing code)


rawDescription: Finding one transposition permutation from a list in Python and C