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

def inWhichEllipse(x,y,rads):
    '''
    With a list of (r1,r2) pairs, rads, return the index of the pair in which
    the point x,y resides. Return None as the index if it is outside all
    Ellipses.
    '''
    xx = x*x
    yy = y*y

    count = 0
    ithEllipse =0
    while True:
        rx,ry = rads[count]
        ellips = xx/(rx*rx)+yy/(ry*ry)
        if ellips < 1:
            ithEllipse = count
            break
        count+=1
        if count >= len(rads):
            ithEllipse = None
            break

    return ithEllipse

rads = zip(np.arange(.5,10,.5),np.arange(.125,2.5,.25))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-15,15)
ax.set_ylim(-15,15)

# plot Ellipses
for rx,ry in rads:
    ellipse = patches.Ellipse((0,0),rx*2,ry*2,fc='none',ec='red')
    ax.add_patch(ellipse)

x=3.0
y=1.0
idx = inWhichEllipse(x,y,rads)
rx,ry = rads[idx]
ellipse = patches.Ellipse((0,0),rx*2,ry*2,fc='none',ec='blue')
ax.add_patch(ellipse)

if idx != None:
    circle = patches.Circle((x,y),.1)
    ax.add_patch(circle)

plt.show()

rawDescription: Counting points inside an ellipse

description: Counting points inside an ellipse


code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
from math import log
from math import exp
from matplotlib import colors

# Grab :
# % of electricity from renewable sources EG.ELC.RNWX.ZS
# 1960 - 2013

# Make fake data
Indicator_df = pd.DataFrame({'CountryName':['United States']*4+['Argentina']*4,
                             'Year':[1960, 1961, 1962, 1963]*2,
                             'Value':[5, 10, 20, 30]*2})

# setup colorbar stuff and shape files
norm = mpl.colors.Normalize(vmin=0, vmax=30)
colors_in_map = []
logbase = exp(1)
for i in range(30):
    val = log(i + 1, logbase) / log(31, logbase)
    colors_in_map.append((1 - val, val, 0))
cmap = colors.ListedColormap(colors_in_map)

shpfilename = shpreader.natural_earth(resolution='110m',
                                      category='cultural',
                                      name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
countries_map = reader.records()

# These don't need to constantly be redefined, especially edgecolor
facecolor = 'gray'
edgecolor = 'black'

fig, ax = plt.subplots(figsize=(12, 6),
                       subplot_kw={'projection': ccrs.PlateCarree()})

# Draw all the gray countries just once in an init function
# I also make a dictionary for easy lookup of the geometries by country name later
geom_dict = {}
def init_run():
    for n, country in enumerate(countries_map):
        ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                          facecolor=facecolor, edgecolor=edgecolor)
        geom_dict[country.attributes['name_long']] = country.geometry

def run(data):
    """Update the Dist"""
    # "data" in this setup is a frame number starting from 0, so it corresponds nicely
    # with your years
    year = 1960 + data

    # get a subset of the df for the current year
    year_df = Indicator_df[Indicator_df['Year'] == year]
    for i, row in year_df.iterrows():
        # This loops over countries, gets the value and geometry and adds
        # the new-colored shape
        geom = geom_dict[row['CountryName']]
        value = row['Value']
        greenamount = (log(float(value) + 1, logbase) /
                       log(31, logbase))
        facecolor = 1 - greenamount, greenamount, 0
        ax.add_geometries(geom, ccrs.PlateCarree(),
                          facecolor=facecolor, edgecolor=edgecolor)

    # I decreased the indent of this, you only need to do it once per call to run()
    ax.set_title('Percent of Electricity from Renewable Sources ' +
                 str(year))

cax = fig.add_axes([0.92, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm,
                               spacing='proportional')
cb.set_label('%')

ani = animation.FuncAnimation(fig, run, init_func=init_run, frames=4,
                              interval=500, blit=False)
plt.show()

rawDescription: Animation Using Cartopy

description: Animation Using Cartopy


code:
import wx
import wx.lib.iewin as iewin
class MyBrowser(wx.Dialog):
  def __init__(self, *args, **kwds):
    wx.Dialog.__init__(self, *args, **kwds)
    sizer = wx.BoxSizer(wx.VERTICAL)
    self.browser =  iewin.IEHtmlWindow(self)
    sizer.Add(self.browser, 1, wx.EXPAND, 10)
    self.SetSizer(sizer)
    self.SetSize((850, 730))
  def load(self,uri):
      self.browser.Navigate(uri)

if __name__ == '__main__':
  app = wx.App()
  dialog = MyBrowser(None, -1)
  dialog.browser.Navigate("https://www.google.com")
  dialog.Show()
  app.MainLoop()

rawDescription: loading https page into wx.html.HTMLWindow

description: Loading https page into wx.html.HTMLWindow


code:
class IceCream():
    # Flavor is a string
    # Toppings is a list of strings
    def __init__(self, flavor, toppings):
        self.name = flavor
        self.toppings = toppings

    # Return the number of toppings
    def __len__(self):
        return len(self.toppings)

    def __str__(self):
        return "{0} flavor ice cream".format(self.name)

vanillaToppings = ['chocolate chips', 'fudge', 'penuts']
vanilla = IceCream('Vanilla', vanillaToppings)
print(vanilla, 'with', len(vanilla), 'kind of toppings!')

rawDescription: Can I switch around this function vanilla.count()

description: Switch around this function vanilla.count()


code:
from selenium.webdriver.support.wait import WebDriverWait

...

def archive_link_is_active(driver):
    cls = driver.find_element_by_link_text("Archive").get_attribute('class')
    return cls and 'active' in cls

WebDriverWait(driver, 10).until(archive_link_is_active)

rawDescription: Wait until an element is active, selenium


code:
def __add__(self, target):
    if isinstance(target, (int, float)):
        return target + self.num/self.den
__radd__ = __add__

rawDescription: Can __radd__ work with the operands in any order?


code:
xs = np.array([1, 2, 3, 4, 5])
xs.shape
xs[:, np.newaxis].shape  # a matrix with only one column
xs[np.newaxis, :].shape  # a matrix with only one row
xs[:, np.newaxis, np.newaxis].shape  # a 3 dimensional array
np.squeeze(xs[:, np.newaxis, np.newaxis]).shape

rawDescription: one-dimensional array shapes (length,) vs. (length,1) vs. (length)

description: One-dimensional array shapes (length,) vs. (length,1) vs. (length)


code:
from django.db import models

class VerboseName(str):
    def __init__(self, func):
        self.func = func

    def decode(self, encoding, erros):
        return self.func().decode(encoding, erros)

class UsedCoupons(models.Model):
    name = models.CharField(max_length=10)

    class Meta:
        verbose_name_plural = VerboseName(lambda: u"Used Coupons (%d)" % UsedCoupons.objects.all().count())

rawDescription: Add a counter to Django admin home

description: Add a counter to Django admin home


rawDescription: How do I print a hex value?

description: Print a hex value


code:
def change_filename(instance, filename):
    return 'bucket_name/' + filename

# inside the model class
cover_image = models.ImageField(upload_to=change_filename, null=True, blank=True)

rawDescription: Django changes image name before uploading to Amazon S3 bucket


code:
import operator
import math
import random

import numpy as np
import pandas as pd

from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from deap import gp

def add_5(input_df):
    return input_df + 5.

def subtract_5(input_df):
    return input_df - 5.

def multiply_5(input_df):
    return input_df * 5.

def divide_5(input_df):
    return input_df / 5.

pset = gp.PrimitiveSet('MAIN', 1)
pset.addPrimitive(add_5, 1)
pset.addPrimitive(subtract_5, 1)
pset.addPrimitive(multiply_5, 1)
pset.addPrimitive(divide_5, 1)

creator.create('FitnessMin', base.Fitness, weights=(-1.0,))
creator.create('Individual', gp.PrimitiveTree, fitness=creator.FitnessMin)

toolbox = base.Toolbox()
toolbox.register('expr', gp.genHalfAndHalf, pset=pset, min_=1, max_=2)
toolbox.register('individual', tools.initIterate, creator.Individual, toolbox.expr)
toolbox.register('population', tools.initRepeat, list, toolbox.individual)
toolbox.register('compile', gp.compile, pset=pset)

def evalSymbReg(individual, points):
    # Transform the tree expression in a callable function
    func = toolbox.compile(expr=individual)
    result = func(points)
    return abs(result.column1.sum() + result.column2.sum()),

toolbox.register('evaluate', evalSymbReg, points=pd.DataFrame({'column1': [125] * 500, 'column2': [125] * 500}))
toolbox.register('select', tools.selTournament, tournsize=3)
toolbox.register('mate', gp.cxOnePoint)
toolbox.register('expr_mut', gp.genFull, min_=0, max_=2)
toolbox.register('mutate', gp.mutUniform, expr=toolbox.expr_mut, pset=pset)

if __name__ == '__main__':
    pop = toolbox.population(n=100)
    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register('avg', np.mean)
    stats.register('min', np.min)
    stats.register('max', np.max)
    pop, log = algorithms.eaSimple(pop, toolbox, 0.5, 0.1, 20, stats=stats, halloffame=hof)

rawDescription: Implementing GP that works on pandas DataFrames in DEAP


code:
days_left = 100
units_left = 50
ideal_daily_rate = units_left/days_left
spend = 1.2*ideal_daily_rate

while (days_left>0):
    print( "days_left: %4.1f unit_left: %4.1f ideal: %5.2f spend: %5.2f" % (days_left,units_left,ideal_daily_rate,spend))
    units_left -= spend
    days_left -= 1
    if (days_left>0):
        ideal_daily_rate = units_left/days_left
        spend = 1.2*ideal_daily_rate

rawDescription: Recursive subtraction in numpy

description: Recursive subtraction in numpy


code:
linedit = QtGui.QlineEdit()
linedit.setPlaceholderText("My grey text which disappear when I click on it")
linedit.setEnabled(False)

rawDescription: Some QLineEdit questions

description: Some QLineEdit questions


code:
import bisect

# Construct the search array
search_array = [(l.code.lower(), l) for l in locations] + [(l.name.lower(), l) for l in locations] + [(a.city.lower(), a) for a in airports] + [(a.state.lower(), a) for a in airports] + [(a.country.lower(), a) for a in airports]
search_array.sort()

# Now, assume the user enters 'S'; we do
new_entry = bisect.bisect_left(search_array, ('S'.lower(), None))

if new_entry < len(search_array):
  found = search_array[new_entry]
  if found[0].startswith('S'.lower()):
    entry = new_entry
    autocompletion = found[0]

# Let's say they now enter 'F'; we do
new_entry = bisect.bisect_left(search_array, ('SF'.lower(), None), entry)

if new_entry < len(search_array):
  found = search_array[new_entry]
  if found[0].startswith('SF'.lower()):
    entry = new_entry
    autocompletion = found[0]

rawDescription: How do I optimize tens of thousands of substring searches in instance attributes in Python?

description: Optimize tens of thousands of substring searches in instance attributes in Python


code: [int(x or 0) for x in mylist]

rawDescription: Python: string to int or zero on error, without try/except


code:
from io import StringIO, BytesIO

def parseMaybeBytes(string, parser):
    bufsize = len(string)
    stream_class = BytesIO if isinstance(string, bytes) else StringIO
    buf = stream_class(string)
    return xml.dom.pulldom.DOMEventStream(buf, parser, bufsize)

def parseString(string, parser=None):
    """Parse a file into a DOM from a string."""
    if parser is None:
        return xml.dom.minidom.parseString(string)

    return xml.dom.minidom._do_pulldom_parse(parseMaybeBytes, (string,),
                                             {'parser': parser})

rawDescription: Parsing XML using SAX Parser in Python 3


code:
inputElement = driver.find_element_by_id("q")
if len(inputElement.get_attribute('value')) > 0:
    inputElement.clear()

rawDescription: Check if element contains ANY and then clear (Selenium/Python)


code:
class Person(Base):
        __tablename__ = 'person'
        id = Column(Integer, primary_key=True, nullable=False)
        person_name = Column(String, nullable=False)

        accommodation_id = Column(Integer, ForeignKey("accommodation.id"))
        accommodation = relationship("Accommodation", backref="people")

class Accommodation(Base):
    __tablename__ = 'accommodation'
    __mapper_args__ = {
        'polymorphic_identity':'accommodation',
        # polymorphic_on determines the field that will have values like 'hotel' and 'apartment' depending on the table
        'polymorphic_on': 'accommodation_type'
    }

    id = Column(Integer, primary_key=True)
    accommodation_type = Column(String(32))
    address = Column(String)

class Hotel(Accommodation):
        __tablename__ = 'hotel'
        __mapper_args__ = {
            # all the records in this table will have accommodation_type = 'hotel'
            'polymorphic_identity': 'hotel'
        }

        id = Column(Integer, ForeignKey('accommodation.id'), primary_key=True)
        hotel_name = Column(String, nullable=False)

class Apartment(Accommodation):
        __tablename__ = 'apartment'
        __mapper_args__ = {
            # all the records in this table will have accommodation_type = 'apartment'
            'polymorphic_identity': 'apartment'
        }

        id = Column(Integer, ForeignKey('accommodation.id'), primary_key=True)

rawDescription: Working with an One-to-many relationship in SQLAlchemy efficient way


rawDescription: Array indexing in numpy

description: Array indexing in numpy


code:
with open('matrix.txt') as f:
    grid_data = [i.split() for i in f.readlines()]

rawDescription: How do you put data from a txt file into a Grid?

description: Put data from a txt file into a Grid


code:
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

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

result = add.delay(2, 2)

rawDescription: Python Flask timed queuing script

description: Python Flask timed queuing script


code:
import pandas as pd
import numpy as np
import pylab as pl
from sklearn.metrics import roc_curve, auc

df = pd.read_csv('filename.csv')

y_test = np.array(df)[:,0]
probas = np.array(df)[:,1]

# Compute ROC curve and area the curve
fpr, tpr, thresholds = roc_curve(y_test, probas)
roc_auc = auc(fpr, tpr)
print("Area under the ROC curve : %f" % roc_auc)

# Plot ROC curve
pl.clf()
pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
pl.plot([0, 1], [0, 1], 'k--')
pl.xlim([0.0, 1.0])
pl.ylim([0.0, 1.0])
pl.xlabel('False Positive Rate')
pl.ylabel('True Positive Rate')
pl.title('Receiver operating characteristic')
pl.legend(loc="lower right")
pl.show()

rawDescription: RoC curve from csv file

description: RoC curve from csv file


code:
lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
    json = simplejson.dumps({'name': a.name,
                             'area': "{replaceme}",
                             'id': a.id}),
    return HttpResponse(json.replace('"{replaceme}"', a.area.geojson),
                        mimetype='application/json')

rawDescription: Using Python simplejson to return pregenerated json


code:
def define_own_property(attr, key):
    def prop(self):
        return getattr(self, attr)[key]
    return property(prop)

class MyClass(object):
    def __init__(self, data):
        self.data = data

    version = define_own_property("data", "version")

rawDescription: python - setting property of class on module loading

description: Python - setting property of class on module loading


code:
list_of_dicts = [{'first_name':'greg', 'last_name':'schlaepfer'},
                 {'first_name':'michael', 'last_name':'lester'}]
list_of_dicts[0]['first_name']

description: Two-dimensional array/dictionary combination


code:
re.findall(r"([a-zA-Z]+[1-5]+)", "ape4banana3")
re.findall(r"([a-zA-Z]+[1-5]+)", "ape4 banana3")

rawDescription: Why do I get an extra empty hit when using regex to split a string?


code:
cnt = Counter()
for words in wordList:
      for letters in set(words):
          cnt[letters]+=1

rawDescription: Python- Count each letter in a list of words


code:
#...
class ScribPartAdmin(admin.ModelAdmin):
  class Media:
    css = {
      'all': ('css/mymarkup.css',)
    }
    js = ('javascript/mymarkup.js',)

admin.site.register(ScribPart, ScribPartAdmin)
#...

rawDescription: Django - ModelAdmin media definition

description: Django - ModelAdmin media definition


code:
def clean_email(self):
    email = self.cleaned_data['email']
    #If email was provided then only do validation
    if email:
        try:
            User.objects.get(email=self.cleaned_data['email'])
        except ObjectDoesNotExist:
            return email
        else:
            raise forms.ValidationError('Wrong Email!')
    return email

rawDescription: How don't call clean_<fieldname> method in 'required=False' field?


code:
colander.SchemaNode(colander.String(),
                    title='Complete name')

rawDescription: How to change the label content in a deform/colander form?

description: Change the label content in a deform/colander form


code:
csv_writer = csv.writer(csv_file,
                        doublequote=False,
                        escapechar='\\',
                        quoting=csv.QUOTE_NONNUMERIC)

rawDescription: Python write database to csv

description: Python write database to csv


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

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.dateEdit = QtGui.QDateEdit(self)
        self.dateEdit.setDateTime(QtCore.QDateTime.currentDateTime())
        self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
        self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
        self.dateEdit.setCalendarPopup(True)

        self.layoutHorizontal = QtGui.QHBoxLayout(self)
        self.layoutHorizontal.addWidget(self.dateEdit)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: PyQt DateEdit widget not defaulting to system time


code:
np.array([(k, np.array(list(g), dtype=grades.dtype).view(np.recarray)['score'].mean())
          for k, g in groupby(np.sort(grades, order='student').view(np.recarray),
                              itemgetter('student'))], dtype=grades.dtype)

rawDescription: Numpy Mean Structured Array

description: Numpy Mean Structured Array


code:
import pygame
import math

class Sierpinski():

    def __init__(self):

        h = w = int(input("Triangle size: "))

        level = int(input("Recursion level: "))

        margin = 50 # add to size to make margin around triangle

        # initializes pygame and setting screne

        pygame.init()

        self.screen = pygame.display.set_mode( (w + margin*2, h + margin*2) ) # self. - to make accessible in all function
        pygame.display.set_caption("Sierpinski Triangle - Recursion")

        # offset to move triangle to middle of window

        const_height = math.sqrt(3)/2  # h = a * sqrt(3)/2 = a * const_height
        invert_const_height = 1 - const_height

        offset = int(h * invert_const_height / 2) # to move triange up - to middle

        # main vertices A, B, C

        a = (margin, h + margin - offset)
        b = (w + margin, h + margin - offset)
        c = (w/2 + margin, int(h * invert_const_height) + margin - offset)

        self.screen.set_at(a, (255,255,255))
        self.screen.set_at(b, (255,255,255))
        self.screen.set_at(c, (255,255,255))

        # recursion

        self.drawTriangle(a, b, c, level)

        # main loop (in game)

        clock = pygame.time.Clock()
        running = True

        while running:

            # keyboard & mouse event
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False

            # move objects - nothing to do here

            # draw object & redraw on screen

            pygame.display.set_caption("Sierpinski Triangle - Recursion [FPS: %f]" % (clock.get_fps()))

            pygame.display.update()

            # frametime

            clock.tick(25) # max 25 Frames Per Second

        # end program

        pygame.quit()

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

    def drawTriangle(self, a, b, c, level):

        if level == 0:
            return

        ab = self.middlePoint(a, b)
        ac = self.middlePoint(a, c)
        bc = self.middlePoint(b, c)

        self.screen.set_at(ab, (255,255,255))
        self.screen.set_at(bc, (255,255,255))
        self.screen.set_at(ac, (255,255,255))

        self.drawTriangle(a, ab, ac, level-1)
        self.drawTriangle(b, ab, bc, level-1)
        self.drawTriangle(c, bc, ac, level-1)

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

    def middlePoint(self, a, b):
        x = (a[0] + b[0])/2
        y = (a[1] + b[1])/2

        return (x,y)

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

if __name__ == '__main__':
    Sierpinski()

rawDescription: Python pygame not responding. Sierpinski triangle and problems with randint


code:
class Blablabla(Model):

    def sort_key(self, e):
        return e

rawDescription: Python : how to prevent a class variable that is a function to be understood as a method?


code:
import tarfile

with tarfile.open(path) as tf:
    for entry in tf:  # list each entry one by one
        fileobj = tf.extractfile(entry)
        # fileobj is now an open file object. Use `.read()` to get the data.
        # alternatively, loop over `fileobj` to read it line by line.

rawDescription: python tar file how to extract file into stream

description: Python tar file how to extract file into stream


code:
A = '1, 2,,3,4  '
B = [int(x) for x in A.split(',') if x.strip()]

rawDescription: How do I do what strtok() does in C, in Python?

description: Do what strtok() does in C, in Python


code:
"""
This is my script.
"""

import argparse

def _make_parser():
    p = argparse.ArgumentParser()
    p.add_argument("foo", help="Specify foo")
    x = p.add_mutually_exclusive_group(required=True)
    x.add_argument('--uid')
    x.add_argument('--username')
    return p

_p = _make_parser()

__doc__ += _p.format_help()

if __name__ == '__main__':
    args = _p.parse_args()

rawDescription: display argparse help within pydoc

description: Display argparse help within pydoc


rawDescription: how to get projectID value from dictionary in python?

description: Get projectID value from dictionary in python


code:
def month(x):
     months = "JanFebMarAprMayJunJulAugSepOctNovDec"
     return months[3*(x-1):3*x]

rawDescription: How to store data in strings?

description: Store data in strings


code:
enumerated_set = enumerate(['tic','tac','toe'])
enumerated_set.next()
enumerated_set.next()
enumerated_set.next()
enumerated_set.next()

rawDescription: for/if loops and a scope of the variable in python

description: For/if loops and a scope of the variable in python


code:
class MyClass:
    def __int__(self, a, b, c=None):
        self.a = a
        self.b = b
        self.c = c

one = MyClass(1,2)
one.c # None
two = MyClass(1,2,3)
two.c # 3

rawDescription: Please help me in understanding Class in Python


code:
with open(filedir) as f:
    lines = [line.rstrip("\r\n") for line in f if line.startswith("@")]

rawDescription: Python list.remove() seems to malfunction


code:
import sys
import timeit

tmr = timeit.Timer("with open(r'partest2.txt','r') as fid:fid.readlines()")
res = tmr.timeit(number=20)
print(res)

rawDescription: File reading and parsing peformance for IronPython vs CPython


code:
SPN = np.random.randint(0, 100, (3, 6, 5))
SPN
SPN.shape
SPN[0].shape

rawDescription: Numpy array of random matrices

description: Numpy array of random matrices


code:
# dtStart, dtEnd are datetime values
message_keys = [r.key.parent() for r in receive]
query = Message.query(Message._key.IN(message_keys), Message.created>dtStart, Message.created<dtEnd)
query = query.order(Message.created) # or -Message.created for desc
messages = query.fetch()

rawDescription: Google app engine - Order listed item

description: Google app engine - Order listed item


code:
with open("filename", 'w') as outFile:
  for frame in frames:
    outFile.write(frame)

rawDescription: Recording and writing voice data as String in a file for Encryption


code:
import random
words = nltk.corpus.brown.words()
random_words = random.sample(words, 10000)

rawDescription: How to get specific ranged words from raw corpus?

description: Get specific ranged words from raw corpus


code:
import sys

def function_four():
    # Does Stuff
    return function_one

def function_three():
    # Does Stuff
    return function_two

def function_one():
    usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
    if usr_input == '1':
        return function_three
    elif usr_input == '2':
        return None
    else:
        print("Did not recognise command. Try again.")
        return function_one

def function_two():
    usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
    if usr_input == '1':
        return function_four
    elif usr_input == '2':
        return function_three
    elif usr_input == '3':
        return None
    else:
        print("Did not recognise command. Try again.")
        return function_two

state = function_one
while state is not None:
    state = state()

rawDescription: Revisiting Functions In Python 3

description: Revisiting Functions In Python 3


code:
def compose_contents(self, *lines):
    self.contents = '\n'.join([line for line in lines if line.strip()])
    return self.contents

rawDescription: remove blank lines from for loop python

description: Remove blank lines from for loop python


code:
file = open(filename, 'rb') # open in binary mode
text_file = io.TextIOWrapper(file, newline='') # text mode
# pass text_file to csv module
byte_offset = file.tell() # get position ± buffering

rawDescription: Read file in text mode but also count raw bytes in Python?


code: plt.subplot2grid((3,3), (1, 0), colspan=2)

rawDescription: matplotlib: non tabular subplots

description: Matplotlib: non tabular subplots


code:
from pymongo import MongoClient

db = MongoClient().mydb  # create a database called 'mydb'
for row_dict in list_of_rows:
    db.rows.save(row_dict)  # saves each row in collection called "rows"

rawDescription: How do you upload a .py file into mongodb through pymongo

description: Upload a .py file into mongodb through pymongo


code:
from datetime import datetime
a = datetime(2014, 11, 30)
b = datetime(2017, 8 ,30)
a + (b - a)/2

rawDescription: Finding mid-point date between two dates in Python?


code:
p = subprocess.Popen(['./test', '-' + a, '-' + b])
p.communicate()

rawDescription: Python script to run a visual studio C++ program multiple time with different arguments


code:
x1 = x.values.T
x1
x1 /= x1.sum(0)
x

rawDescription: In-place row-wise operation on pandas DataFrame


code:
struct.unpack('i', 'AAAA')[0]  # 'i' means "long" integer
hex(_)

rawDescription: how do I do the equivelant of casting to int, in python

description: Do the equivelant of casting to int, in python


code:
from io import StringIO
blobstring = blob_service.get_blob_to_text(CONTAINERNAME,BLOBNAME,LOCALFILENAME)
df = pd.read_csv(StringIO(blobstring))

rawDescription: How best to convert from azure blob csv format to pandas dataframe while running notebook in azure ml


code:
for key in dictionary.keys():
    if key[-9:] == 'BSTTHGIHG':
        print('I found it!!')
        break

rawDescription: Searching Python dictionary for matching key


code:
def submit_advanced_search():

    params = {
        '_nkw': "",
        '_in_kw': 1,
        '_ex_kw': "",
        '_sacat': 20081,
        'LH_Sold': 1,
        '_udlo': 20,
        '_udhi': 250,
        'LH_ItemCondition': 3,
        'LH_BIN': 1,
        'LH_FS': 1,
        'LH_Complete': 1,
    }

    content = requests.get("http://www.ebay.com/sch/i.html", params = params).content
    with open("search_result.html", "wb") as f:
        f.write(content)

rawDescription: Submitting advanced ebay searches with Python


code:
class B(A):
    def __init__(self, obj):
        self.__dict__.update(obj.__dict__)

rawDescription: Casting to other class in Python

description: Casting to other class in Python


code:
class myProxyHack(object):

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        environ['REMOTE_ADDR'] = environ.get('REMOTE_ADDR', '127.0.0.1')
        return self.app(environ, start_response)

app.wsgi_app = myProxyHack(app.wsgi_app)

app.test_client().post(...)

rawDescription: Get IP Address when testing flask application through nosetests


code:
def myextend(data, result):
    if isinstance(result, dict):
        data.append(result)
    elif isinstance(result, list):
        data.extend(result)

rawDescription: Python: Receiving dictionary or list of dictionaries


code:
import itertools
dataset = ['1','2','3A','4']
list(itertools.combinations(dataset, 3))

rawDescription: python random.sample stop sampling after all possible outcomes

description: Python random.sample stop sampling after all possible outcomes


code:
tcp_match = parser.OFPMatch(in_port=in_port, eth_dst=dst, ip_proto=6)
self.add_flow(datapath, 2, tcp_match, tcp_actions)
nontcp_match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
self.add_flow(datapath, 1, nontcp_match, nontcp_actions)

rawDescription: OpenFlow 1.3, Python RYU, OFPMatch to all non-tcp packets


code:
newx = (x1 - xorigin)*cos(45 * pi / 180)
newy = (y1 - yorigin)*sin(45 * pi / 180)

rawDescription: python: how to rotated a line 45 degrees

description: Python: how to rotated a line 45 degrees


code:
def list(self, request):
    items = {}
    for f in request.user.follower_set.all():
        items.setdefault(f.content_type_id, []).append(f.object_id)
    activities = Activity.objects.get_empty_queryset() # get_empty_query_set in <1.5
    for k, v in items.iteritems():
        activities |= Activity.objects.filter(content_type=k, object_id__in=v)

rawDescription: How to query across generic relations in Django

description: Query across generic relations in Django


code:
groups = ['a','b','c','a','b','b']
values = [1, 2, 3, 4, 5, 6]

d={}

for i,j in zip(groups,values):
  d.setdefault(i,[]).append(j)

d

rawDescription: Grouping values based on other list

description: Grouping values based on other list


code:
from Tkinter import *

class A:
    def __init__(self):
        self.var = True

obj = A()

def meth():
    obj.var = False
    paintGui()

def paintGui():
    if obj.var == False:
        w.itemconfig("rect", fill="red")

master = Tk()
w = Canvas(master, width=200, height=100)
w.pack()
w.create_rectangle(50, 25, 150, 75, fill="blue", tags="rect")

btn = Button(master, text="Cerrar Mesa",command=meth)
btn.pack(side=BOTTOM)
mainloop()

rawDescription: How do I update the screen (canvas) of a Tkinter window

description: Update the screen (canvas) of a Tkinter window


code:
from django.db import connection
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)

rawDescription: Get all table names in a Django app

description: Get all table names in a Django app


code:
def getitems(data, keys):
    return reduce(lambda a, b: a[b], [data]+keys)

getitems(b, c)

rawDescription: Access element in list using indexes stored in another list


code: get_serving_url(blob_key, size=None, crop=False, secure_url=None)

rawDescription: how to display images from the ndb datastore using data URI scheme (via passing data to template and not having to make another request)

description: Display images from the ndb datastore using data URI scheme (via passing data to template and not having to make another request)


code:
import pygame, sys
from pygame.locals import *

WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
TANK_SIZE = 20

BLACK = (0  ,0  ,0  )
WHITE = (255,255,255)

def drawArena():
    DISPLAYSURF.fill(BLACK)

def drawTank(tank):
    pygame.draw.rect(DISPLAYSURF, WHITE, tank)

def main():
    pygame.init()
    global DISPLAYSURF
    DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('Tanks')

    tankX = 200
    tankY = 200

    tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)

    drawArena()
    drawTank(tank)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    tankX -= 20
                if event.key == pygame.K_RIGHT:
                    tankX += 20

        tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)

        drawArena()
        drawTank(tank)

        pygame.display.update()

if __name__ == '__main__':
    main()

rawDescription: Keydown event for Pygame

description: Keydown event for Pygame


code:
TAG = '<Report name="test" xmlns:cm="http://www.domain.org/cm">'

tag_found = False
with open('tag_input.txt') as in_file:
    with open('tag_output.txt', 'w') as out_file:
        for line in in_file:
            if not tag_found:
                if line.strip() == TAG:
                    tag_found = True
            else:
                out_file.write(line)

rawDescription: remove string and all lines before string from file python

description: Remove string and all lines before string from file python


code:
class alert_is_not_present(object):
    """ Expect an alert to not to be present."""
    def __call__(self, driver):
        try:
            alert = driver.switch_to.alert
            alert.text
            return False
        except NoAlertPresentException:
            return True

rawDescription: Wait until alert is not present - Selenium/Python


code:
#!/usr/bin/python3

infile = open('columnfile','r')

title = ""
scaf = set()
scafs = []
for lines in infile:
    lines = lines.split()
    if lines[0] != title:
        title = lines[0]
        scafs.append(scaf)
        scaf = set()
        scaf.add(lines[1])
    else:
        scaf.add(lines[1])

scafs.append(scafs)
del scafs[0]
del scafs[-1]

infile.close()

def consolidate(sets):
    setlist = [s for s in sets if s]
    for i, s1 in enumerate(setlist):
        if s1:
            for s2 in setlist[i+1:]:
                intersection = s1.intersection(s2)
                if intersection:
                    s2.update(s1)
                    s1.clear()
                    s1 = s2
    return [s for s in setlist if s]

for i in consolidate(scafs):
    for a in i:
        print(a)
    print("---")

rawDescription: How can I optimize set matching in this case using python?

description: Optimize set matching in this case using python


code:
import praw, time

r = praw.Reddit(user_agent='ADNPost')

already_done = set()

while True:
    l = r.get_top(limit=1)
    submission = next(l,None)

    if not submission:
        continue

    while submission.id in already_done:
        submission=next(r.get_front_page(limit=1, params={'after':submission.fullname}),None)
        if not submission:
            break
    if submission:
        id = submission.id
        title = submission.title
        url = submission.short_link
        print (title, url)
        save_state = (id)
        already_done.add(submission.id)
    time.sleep(2)

rawDescription: Python PRAW Wrapper, Logic Problems

description: Python PRAW Wrapper, Logic Problems


rawDescription: how to create a random array from a list, each value in the array is not duplicate in python

description: Create a random array from a list, each value in the array is not duplicate in python


code:
a = 'ABCDEFGHIJKLMNOPQRSTUVWX'
"-".join([a[i:i+4] for i in range(len(a)/4)])

rawDescription: format string to be more human readable

description: Format string to be more human readable


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

x = np.arange(10)+1
y = np.arange(15)+10
px = np.random.normal(0.5,0.05,10)
py = np.random.normal(0.5,0.05,15)

p = px[None,:]*py[:,None]

plt.figure(figsize=[10,6])

plt.subplot(1,2,1)
plt.imshow(p, origin='lower', extent=[1,10, 10,24])
plt.colorbar()

plt.subplot(1,2,2)
plt.imshow(p, cmap='gray', vmin=0.1, vmax=0.4, interpolation=None,
           origin='lower', extent=[1,10, 10,24] )

plt.colorbar()

plt.savefig("twoDp")

plt.show()

rawDescription: Python - plot 2D probability distribution from vectors of different length


code:
def main():
    df = create_dateframe()  # Note you need to call your other function
    print(df)

if __name__ == "__main__":
    main()

rawDescription: Show python return in windows command line


rawDescription: How to set filename property in BlobStore?

description: Set filename property in BlobStore


code: int.from_bytes(b'hi', 'big', signed=False) % 3

rawDescription: Getting modulo of bytes-number in Python


code:
I=im2bw(I,graythresh(I));
imshow(I)

rawDescription: Removing background from image (MATLAB, Java, or Python preferred)


code:
wid = QtGui.QWidget()
grid = QtGui.QGridLayout(wid)
wid.setLayout(grid)

# setting the inner widget and layout
grid_inner = QtGui.QGridLayout(wid)
wid_inner = QtGui.QWidget(wid)
wid_inner.setLayout(grid_inner)

# add the inner widget to the outer layout
grid.addWidget(wid_inner)

# add tab frame to widget
wid_inner.tab = QtGui.QTabWidget(wid_inner)
grid_inner.addWidget(wid_inner.tab)

# create tab
new_tab = QtGui.QWidget(wid_inner.tab)
grid_tab = QtGui.QGridLayout(new_tab)
grid_tab.setSpacing(10)
new_tab.setLayout(grid_tab)
new_tab.tab_name_private = "test1"
wid_inner.tab.addTab(new_tab, "test1")

# create tab 2
new_tab2 = QtGui.QWidget(wid_inner.tab)
new_tab2.setLayout(grid_tab)
wid_inner.tab.addTab(new_tab2, "test2")

wid.show()
app.exec_()

rawDescription: How to add a tab in PySide

description: Add a tab in PySide


code:
from calendar import monthrange
monthrange(2011, 2)
(1, 28)
# Just to be clear, monthrange supports leap years as well:

from calendar import monthrange
monthrange(2012, 2)

rawDescription: get last day of the month from year month in python

description: Get last day of the month from year month in python


code:
def name_email(name):
   correct_email = False
   while correct_email == False:
      email = input('what is your email: ')
      if '@' in email:
          print('name and email accepted \n')
          print('name: ',name)
          print('email: ',email)
          correct_email = True
      else:
          print('email invalid, please try again \n')
   return email

rawDescription: returning to a select point in python 3

description: Returning to a select point in python 3


code:
img = plt.imshow(...)
img.set_rasterized(True)

rawDescription: export axes area only to bitmap using python matplotlib

description: Export axes area only to bitmap using python matplotlib


code:
import foo
foo.arbit = 'new value'

rawDescription: Python Changing module variables in another module


code:
import numpy as np
import pandas as pd

# Note I've changed it from random numbers to integers as I
# find it easier to read and see the differences :)
df = pd.DataFrame(np.arange(18).reshape((3,6)),
                  columns=['a', 'b', 'c', '2010', '2011', '2012'])

var = ['a', 'b', 'c']
melted = pd.melt(df, id_vars=var)

print(melted)
#     a   b   c variable  value
# 0   0   1   2     2010      3
# 1   6   7   8     2010      9
# 2  12  13  14     2010     15
# 3   0   1   2     2011      4
# 4   6   7   8     2011     10
# 5  12  13  14     2011     16
# 6   0   1   2     2012      5
# 7   6   7   8     2012     11
# 8  12  13  14     2012     17

rawDescription: How to transpose (stack) arbitrary columns in Dataframe?

description: Transpose (stack) arbitrary columns in Dataframe


code:
params = {'param1' : value1, 'param2' : value2, # ... etc
         }
url = "http://example.com"

# Referer must be correct
# To determine correct Referer url, prepare a request without actually sending it
req = requests.Request('POST', url, params=params)
prepped = session.prepare_request(req)
#r = session.send(prepped)   # don't actually send it

# add the Referer header by examining the prepared url
headers = { 'Referer': prepped.url }

# now send normally
r = session.post(url, params=params, data=data, headers=headers)

rawDescription: Requests - determine parameterised url prior to issuing request, for inclusion in Referer header


code:
tn.get_socket().shutdown(socket.SOCK_WR)
data = tn.read_all()
tn.close()

rawDescription: Python telnetlib ending session

description: Python telnetlib ending session


code:
data = np.array([xx, yy, z]).reshape(3, -1).T
data

rawDescription: Reshaping pandas DataFrame from Meshgrid


code:
class ReportForm(ModelForm):
    product_line = forms.ModelChoiceField(queryset=ProductLine.objects.all())

rawDescription: Django OneToOne field as a dropdown in a form


rawDescription: Groupby to Count Frequency of Unique Values in Set


code:
class Base(object):
    foo = "bar"

# Create a new class called `base_copy` with attributes and base classes
# from Base without inheriting from Base
base_copy = type('base_copy', Base.__bases__, dict(Base.__dict__))
# Will delete attribute on `base_copy` class
del base_copy.foo

base_again = type('base_again', Base.__bases__, dict(Base.__dict__))

print(hasattr(base_again, 'foo')) # True

rawDescription: Why doesn't deepcopy of classes preserve attributes?


rawDescription: python regex replace unicode

description: Python regex replace unicode


code:
class deduction_registration(osv.osv):

    def _check_unique_insesitive(self, cr, uid, ids, context=None):
        sr_ids = self.search(cr, 1 , [], context=context)
        lst = [x.name.lower() for x in self.browse(cr, uid, sr_ids, context=context) if x.name and x.id not in ids]
        for self_obj in self.browse(cr, uid, ids, context=context):
            if self_obj.name and self_obj.name.lower() in  lst:
                return False
            return True

    _name = "bpl.deduction.registration"
    _description = "Deduction Registration"
    _columns = {
        'name': fields.char('Deduction Name', size=256, required=True),
    }
    _sql_constraints = [('deduction_registration_name_unique', 'unique(name)', 'Deduction name already exists')]
    _constraints = [(_check_unique_insesitive, 'Deduction name already exists', ['name'])]

deduction_registration()

rawDescription: OpenERP 7 _constraints

description: OpenERP 7 _constraints


code:
import scipy.io as spio

def loadmat(filename):
    '''
    this function should be called instead of direct spio.loadmat
    as it cures the problem of not properly recovering python dictionaries
    from mat files. It calls the function check keys to cure all entries
    which are still mat-objects
    '''
    data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
    return _check_keys(data)

def _check_keys(dict):
    '''
    checks if entries in dictionary are mat-objects. If yes
    todict is called to change them to nested dictionaries
    '''
    for key in dict:
        if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):
            dict[key] = _todict(dict[key])
    return dict

def _todict(matobj):
    '''
    A recursive function which constructs from matobjects nested dictionaries
    '''
    dict = {}
    for strg in matobj._fieldnames:
        elem = matobj.__dict__[strg]
        if isinstance(elem, spio.matlab.mio5_params.mat_struct):
            dict[strg] = _todict(elem)
        else:
            dict[strg] = elem
    return dict

rawDescription: scipy.io.loadmat nested structures (i.e. dictionaries)

description: Scipy.io.loadmat nested structures (i.e. dictionaries)


code:
class StringBox(QtGui.QSpinBox):
    def __init__(self, strings, parent=None):
        super(StringBox, self).__init__(parent)
        self.setStrings(strings)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

rawDescription: PyQt4: QSpinBox strings

description: PyQt4: QSpinBox strings


code:
class FakeModule(object):
    def __getattribute__(self, name):
        return name

import sys
sys.modules[__name__] = FakeModule()

rawDescription: Hacking python's import statement

description: Hacking python's import statement


code:
def __init__(self,radius,*args,**kwargs):
     super().__init__(*args,**kwargs)
     self.radius = radius

rawDescription: python3 class __init__ inheritance without defining parameters again

description: Python3 class __init__ inheritance without defining parameters again


rawDescription: How to print a numpy array without brackets

description: Print a numpy array without brackets


code:
def text_return(self, event):
    self.st.Clear()
    self.st.Append('3')
    self.st.Append('4')

rawDescription: Dynamically change the choices in a wx.ComboBox()


rawDescription: Allow colon in Django urls

description: Allow colon in Django urls


code:
import os
os.environ['QT_API'] = 'pyqt5'

from PyQt5 import QtWidgets
from PyQt5 import QtGui
# ipython won't work if this is not correctly installed. And the error message will be misleading
from PyQt5 import QtSvg

# Import the console machinery from ipython
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager

def get_app_qt5(*args, **kwargs):
    """Create a new qt5 app or return an existing one."""
    app = QtWidgets.QApplication.instance()
    if app is None:
        if not args:
            args = ([''],)
        app = QtWidgets.QApplication(*args, **kwargs)
    return app

class QIPythonWidget(RichIPythonWidget):
    """ Convenience class for a live IPython console widget. We can replace the standard banner using the customBanner argument"""
    def __init__(self,customBanner=None,*args,**kwargs):
        super(QIPythonWidget, self).__init__(*args,**kwargs)
        if customBanner!=None: self.banner=customBanner
        self.kernel_manager = kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.kernel.gui = 'qt'
        self.kernel_client = kernel_client = self._kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            get_app_qt5().exit()
        self.exit_requested.connect(stop)

    def pushVariables(self,variableDict):
        """ Given a dictionary containing name / value pairs, push those variables to the IPython console widget """
        self.kernel_manager.kernel.shell.push(variableDict)
    def clearTerminal(self):
        """ Clears the terminal """
        self._control.clear()
    def printText(self,text):
        """ Prints some plain text to the console """
        self._append_plain_text(text)
    def executeCommand(self,command):
        """ Execute a command in the frame of the console widget """
        self._execute(command,False)

class ExampleWidget(QtWidgets.QMainWindow):
    """ Main GUI Window including a button and IPython Console widget inside vertical layout """
    def __init__(self, parent=None):
        super(ExampleWidget, self).__init__(parent)
        self.setWindowTitle('iPython in PyQt5 app example')
        self.mainWidget = QtWidgets.QWidget(self)
        self.setCentralWidget(self.mainWidget)
        layout = QtWidgets.QVBoxLayout(self.mainWidget)
        self.button = QtWidgets.QPushButton('Another widget')
        ipyConsole = QIPythonWidget(customBanner="Welcome to the embedded ipython console\n")
        layout.addWidget(self.button)
        layout.addWidget(ipyConsole)
        # This allows the variable foo and method print_process_id to be accessed from the ipython console
        ipyConsole.pushVariables({"foo":43,"print_process_id":print_process_id})
        ipyConsole.printText("The variable 'foo' and the method 'print_process_id()' are available. Use the 'whos' command for information.\n\nTo push variables run this before starting the UI:\n ipyConsole.pushVariables({\"foo\":43,\"print_process_id\":print_process_id})")
        self.setGeometry(300, 300, 800, 600)

def print_process_id():
    print('Process ID is:', os.getpid())

def main():
    app  = get_app_qt5()
    widget = ExampleWidget()
    widget.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Can't quit PyQt5 application with embedded iPython Qtconsole


code:
params = {
    'user': dbuser,
    'password': dbpassword,
    'host': dbhost,
    'database': dbdatabase
}

cnx = mysql.connector.connect(**params)

rawDescription: passing vars into mysql.connector.connect

description: Passing vars into mysql.connector.connect


code:
for item in s:
    words = item.split()
    for item in words:
        result.append(item.strip(",."))  # note the addition of .strip(...)

rawDescription: removing specific items from a list of strings

description: Removing specific items from a list of strings


code:
##import statements

NDENSITIES = 1000

def dowork(density):
    model = Prism(-1000, 1000, -1000, 1000, 1000, 1100, {'density': 300})
    ##other code
    return data   ## or whatever is important

densities = multivariate_normal([300], [[300]], NDENSITIES)
results = []
for density in range(densities):
    results.append(dowork(density))
results = np.vstack(results)   ## or hstack or dstack, depending on the dimensions of `data`
mean = results.mean()   # possibly: results.mean(axis=0) or with axis=1 etc. Again dependent on the dimensions
std = results.std()

rawDescription: Python: Creating a Gaussian distribution for a variable and running a program on a loop using the Gaussian values


code:
def create_logo(absolute_path):
    image = Image(absolute_path)
    image._restrictSize(2 * inch, 1 * inch)

rawDescription: How do i set the max size for an image in Reportlab, without rescaling?

description: Set the max size for an image in Reportlab, without rescaling


code:
data = sock.recv(BUFFER_SIZE)
result = bool(int(data.encode('hex'), 16))

rawDescription: Convert data received from a socket.recv (bytes) to a boolean value in ironpython


code:
dst= collections.defaultdict( list )
src= collections.defaultdict( list )
for k in original:
    for addr in original[k]['ip.dst']:
        dst[addr].append( k )
    for addr in original[k]['ip.src']:
        src[addr].append( k )

rawDescription: Python - Searching Dictionary

description: Python - Searching Dictionary


code:
import json
obj = json.loads(json_string)

# filter only the b16 objects
b16_objs = filter(lambda a: a['routeName'] == 'B16',  obj['arrivals'])

if b16_objs:
    # get the first item
    b16 = b16_objs[0]
    my_estimatedWait = b16['estimatedWait']
    print(my_estimatedWait)

rawDescription: Getting certain information from string

description: Getting certain information from string


code: 'a "quote" here'

rawDescription: Backslash in interactive interpreter

description: Backslash in interactive interpreter


rawDescription: make first values positive in a list of tuples

description: Make first values positive in a list of tuples


code:
Stuff = []
for row in Data:
    Stuff.append([i for i in [row['day'], float(row['a1']), float(row['a2']), float(row['a3'])]]);

rawDescription: Python: SQL query results to table

description: Python: SQL query results to table


code:
im = Image.open('image.png')
bands = im.split()
isBlank = all(band.getextrema() == (255, 255) for band in bands)

rawDescription: How can I check for a blank image in Qt or PyQt?

description: Check for a blank image in Qt or PyQt


code:
s = raw_input() # input() in Python 3
try:
  numbers = map(int, s.split())
except ValueError:
  print('Invalid format')

rawDescription: List from string of digits question

description: List from string of digits question


code: df.insert(idx, col_name, value)

rawDescription: how do I insert a column at a specific column index in pandas?

description: Insert a column at a specific column index in pandas


rawDescription: Join flat index with hierarchical indexed DataFrame


code:
class A(object) :
    def __init__(self) :
            self.__dict__['_odict'] = odict()
    def __getattr__(self, value) :
            return self.__dict__['_odict'][value]
    def __setattr__(self, key, value) :
            self.__dict__['_odict'][key] = value

a = A()
a
a.x = 1
a.x
a.y = 2
a.y
a.odict

rawDescription: Using an ordered dict as object dictionary in python


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

t = np.array([0.19641715476064042,
              0.25, 0.34, 0.42])
c = np.array([0.17, 0.21, 0.27, 0.36])

def my_plot(ax, tab, c="g", ls="-", marker="o", ms=6, mfc="w", mec="g", label="",
            zorder=2):
    """
    tab: array to plot
    c: line color (default green)
    ls: linestyle (default solid line)
    marker: kind of marker
    ms: markersize
    mfc: marker face color
    mec: marker edge color
    label: legend label
    """
    ax.plot(tab, c=c, ms=0, ls=ls, label=label, zorder=zorder-0.02)
    ax.plot(tab, c=c, marker=marker, ms=ms, mec=mec, mfc=mfc, ls="none",
            zorder=zorder)
    ax.plot(tab, c=c, marker=marker, ms=ms*4, mfc="w", mec="w", ls="none",
            zorder=zorder-0.01)

my_plot(plt, t, c="g", mec="g", ls="dashed", label="n=20")
my_plot(plt, c, c="b", mec="b", ls="dashed", label="n=22")

plt.legend(loc=2)
plt.show()

rawDescription: matplotlib: how to change colors, make little spaces and edit the legend

description: Matplotlib: how to change colors, make little spaces and edit the legend


code:
proc = subprocess.Popen(
            [r"C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild",
             r"D:\WebService\WebService.sln",
             r"/p:DeployOnBuild=true",
             r"/p:PublishProfile=D:\WebService\Properties\PublishProfiles\MyDeployment.pubxml",
             r"/p:AllowUntrustedCertificate=true",
             r"/p:UserName=name",
             r"/p:Password=PASSWORD"])

proc.wait()

rawDescription: Execute windows command from python3.4

description: Execute windows command from python3.4


code:
import re

indicators = ["therefore", "for", "since"]
phrase = "... therefore, I conclude I am awesome."

indicators_in_phrase = set(re.findall(r'\b(%s)\b' % '|'.join(indicators), phrase.lower()))

rawDescription: How do I check for if an exact string exists in another string?

description: Check for if an exact string exists in another string


rawDescription: Converting u"string" to "string" in Python without changing encoding


rawDescription: Python: Adress sub-tuples in tuple of tuples?


rawDescription: Split by columns of 2d list into new list


code:
for obj1 in some_list:
    dict1['key'] = value

    for obj2 in some_other_list:
        ...

    dict1['key'] = list2
    list2 = [] # create new list to fill next time
    list1.append(dict1)

rawDescription: How to build a list of nested dictionaries and lists

description: Build a list of nested dictionaries and lists


code:
window.setWindowIcon(QtGui.QIcon('/path/to/icon.png'))

languages = ['English', 'rus', 'uk', 'fr', 'germ']
s, ok = QtGui.QInputDialog.getItem(window, 'title', 'help', languages, current = 0, editable = False)

rawDescription: How can I set an icon to qinputdialog in pyqt4?

description: Set an icon to qinputdialog in pyqt4


code:
import importlib
modulename, funcname = string.rsplit('.', 1)

module = importlib.import_module(modulename)
function = getattr(module, funcname)

result = function()

rawDescription: Run a function identified by a string -> the right way


rawDescription: Split a string if there is space

description: Split a string if there is space


code:
class Room:
    def __init__(self, building, floor, number):
        self.building = building
        self.floor = floor
        self.number = number
    def __str__(self):
        return (str(self.building)+'.'+str(self.floor)+'.'+str(self.number))

class Occupant:
    def __init__(self, familyname, givenname, room):
        self.familyname = familyname
        self.givenname = givenname
        self.room = room

    def __str__(self):
        return '{f}, {g} -- {r}'.format(f = self.familyname, g = self.givenname, r = self.room)

room = Room('Building', 'Floor', 'Num')
occ = Occupant('Family', 'Given', room)
print(occ)
# Family, Given -- Building.Floor.Num

rawDescription: printing elements from superclass in python

description: Printing elements from superclass in python


rawDescription: What makes a wxpython TextCtrl fill horizontally


code:
class ConnectionChecker(sqlalchemy.interfaces.PoolListener):
    def checkout(self, dbapi_con, con_record, con_proxy):
        if not is_valid_connection(dbapi_con):
            # a new connection will be used
            raise sqlalchemy.exc.DisconnectionError

rawDescription: How can I check pooled connections in SQLAlchemy before handing them off to my application code?

description: Check pooled connections in SQLAlchemy before handing them off to my application code


code: short = [x for x in appliances if 'v' in x]

rawDescription: List of strings: looking for a particular character


rawDescription: PyCharm, what is python_stubs?

description: PyCharm, what is python_stubs


code: data = forms.DateTimeField(input_formats=['%Y-%m-%d %H:%M', '%Y-%m-%dT%H:%M'])

rawDescription: Django set value to POST form

description: Django set value to POST form


code:
import selenium
from selenium import webdriver

# I used Firefox, but you could use Chrome or IE
browser = webdriver.Firefox()

browser.get('http://www.SomeWebsite.com/login')
# I needed to stop the script here to actually login.
# I tried to use an existing profile w/ my username & password but the website
# rejected my profile info and locked me out of the account

browser.get('http://www.SomeWebsite.com/blah/blah/blah.html')

element = browser.find_element_by_id("TheElementYouNeed").text
# This downloads all the text from the article at this particle 'id' element

rawDescription: Using login info to scrape a website with python


code:
if not request.user == user_list.user:
    response = http.HttpResponse()
    response.status_code = 403
    return response

rawDescription: Django -- Allowing Users To Only View Their Own Page


code:
iter = range(np.shape(df.ix[:,6:])[1])
freq_val = np.zeros(np.shape(df.ix[:,6:])[1])
for i in iter:
    _, count = np.unique(df.ix[:,i+6], return_counts=True)
    freq_val[i] = count.argmax()
freq_val_series =  pd.Series(freq_val, df.ix[:,6:].columns.values)
df_imputed = df.ix[:,6:].fillna(freq_val_series)

rawDescription: increasing pandas dataframe imputation performance

description: Increasing pandas dataframe imputation performance


code:
# data is your original dict
output = {}
for row in data:
  key = (row['month'], row['year'], row['district'], row['organization'])
  if key in output:
    output[key].append(row['community'])
  else:
    output[key] = [row['community']]

output

rawDescription: Python Group By multiple keys in an array of dictionaries


code: path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html')

rawDescription: What's a good way to find relative paths in Google App Engine?


rawDescription: scipy -- how to convert a function result to array

description: Scipy -- how to convert a function result to array


code:
import signal
import sys

class S:
    cnt = 0

    def __call__(self, signum, frame):
        self.cnt += 1
        if (self.cnt == 5):
            sys.exit()

signal.signal(signal.SIGINT, S())

rawDescription: Python counting keyboard interrupts

description: Python counting keyboard interrupts


code:
class Health:
    def __init__(self): #Constructor initializing the variables.
        self.player_health = 10
        self.enemy_health = 10

class Combat:
    #Attack function receives a health object called "hitter"
    def attack(self, hitter):
        hitter.player_health -= 1   #Health Object hitter's player_health reduced by one.
        return hitter

bridge = Combat() #Combat Object
hitter = Health() #Health Object

bridge.attack(hitter) #hitter.player_health is now 9.

rawDescription: Python Class Location Variables

description: Python Class Location Variables


rawDescription: (x,y) pair for max z value in list

description: (x,y) pair for max z value in list


code:
reader     = sitk.ImageFileReader()
reader.SetFileName ( tensorVolumePath )

image      = reader.Execute()
dimes      = image.GetSize()
origin     = image.GetOrigin()

values     = sitk.GetArrayFromImage( image )
valuesFlat = values.reshape(dims[0]*dims[1]*dims[2], 3, 3)

arrayInv   = np.array(map(np.linalg.inv, valuesFlat))

imageInv = sitk.GetImageFromArray( valuesFlat.reshape(dims[0], dims[1], dims[2], -1) )
imageInv.SetOrigin(origin)

writer = sitk.ImageFileWriter()
writer.SetFileName ( tensorVolumeInversePath )
writer.Execute ( imageInv );

rawDescription: Python nested for loop on tensor-valued volume data


code:
@property
def message(self):
    return ugettext('{name} has sent you a message').format(name=self.foo.bar.name)

rawDescription: Django i18n: Translating database values where one word is a name that might change


code:
def custom_decorator(f):
    @wraps(f)
    def wrapper(arg, need_to_do_more):
        ...

    wrapper.__doc__ += "/n:param need_to_do_more: if True: do more"
    return wrapper

rawDescription: Signature-changing decorator: properly documenting additional argument


code:
import base64, lzw

def my_compress(x):
    # returns a single line, one trailing \n included
    return base64.encodestring("".join(lzw.compress(x)))

def my_decompress(line):
    return lzw.decompress(base64.decodestring(line))

rawDescription: python write strings of bytes

description: Python write strings of bytes


code:
root = TreeNode("Level " + str(i), Array[TreeNode](
    [TreeNode(x) for x in l[i]] + [root]))

rawDescription: Adding a separate element using list comprehensions


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("https://www.pelikan.sk/sk/flights/list?dfc=CVIE%20BUD%20BTS&dtc=CMAD&rfc=CMAD&rtc=CVIE%20BUD%20BTS&dd=2015-07-09&rd=2015-07-14&px=1000&ns=0&prc=&rng=1&rbd=0&ct=0")

wait = WebDriverWait(driver, 60)
wait.until(EC.invisibility_of_element_located((By.XPATH, '//img[contains(@src, "loading")]')))
wait.until(EC.invisibility_of_element_located((By.XPATH, u'//div[. = "Poprosíme o trpezlivosť, hľadáme pre Vás ešte viac letov"]/preceding-sibling::img')))

print(driver.page_source)

rawDescription: Python - javascript web scraping with selenium does not work properly


code: numChanges = sum(i != j for i, j in zip(x, y))

rawDescription: Calculating closest string match from a list of strings


code:
def fixlen (s, length):
    bs = s.encode ('utf-8')
    bs = bs [:length]
    while True:
        try:
            bs.decode ('utf-8')
            break
        except UnicodeDecodeError:
            bs = bs [:-1]
    return bs + b'\0' * (length - len (bs) )

s = 'LLegó cigüeña'
for length in range (0, 20):
    bs = fixlen (s, length)
    print (s, bs, bs.decode ('utf-8') )

rawDescription: Fit UTF-8 string to bytelength 32

description: Fit UTF-8 string to bytelength 32


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

x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0.01)) * 1000

plt.plot(x, f, '-')
plt.plot(x, g, '-')

idx = np.argwhere(np.isclose(f, g, atol=10)).reshape(-1)
plt.plot(x[idx], f[idx], 'ro')
plt.show()

rawDescription: Intersection of two graphs in Python, find the x value:


rawDescription: How to filter a query by property of user profile in Django?

description: Filter a query by property of user profile in Django


code:
from datetime import datetime

start = twf.CalendarDatePicker('StartDate', date_format = "%d/%m/%Y")
start.default = datetime.now() # or any valid datetime object

end = twf.CalendarDatePicker('EndDate', date_format = "%d/%m/%Y" )
start.default = datetime.now() # or any valid datetime object

form = twf.TableForm('dateSel', action='changeDate', children=[start, end])

rawDescription: ToscaWidgets CalendarDatePicker pylons

description: ToscaWidgets CalendarDatePicker pylons


rawDescription: Python: Load data into a dictionary of dictionaries


code:
numSt = []
numSti = 0
for i in xrange(0,2):
         for j in xrange(0,2):
             numSti += 1
             numSt.append(numSti)

numSt

rawDescription: double for loops counter in python

description: Double for loops counter in python


code:
from sys import argv
try:
    if argv[1] == 'install':
        from os.path import join
        from distutils.sysconfig import get_python_lib
        from shutil import copytree
        OrigSkeleton = join('src', 'skeleton')
        DestSkeleton = join(get_python_lib(), 'cumulus', 'skeleton')
        copytree(OrigSkeleton, DestSkeleton)

except IndexError: pass

rawDescription: Including static data in setup.py (setuptools)


code:
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QProcess

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    command = "./testCommand.py"
    args = [""]

    #"regular" startDetached : give two arguments, get a boolean
    process=QProcess()
    re=process.startDetached("ls",["."])
    print(re)
    print(type(re))

    #"overload" startDetached : give three arguments, get a tuple(boolean,PID)
    process2=QProcess()
    re,pid=process2.startDetached("ls",["."],".")
    print(re,pid)
    print(type(re),type(pid))

rawDescription: PyQt4 QProcess.startDetached() - can't get return value and PID of spawned process


code:
df = DataFrame(randn(10,1))
df['col1'] = '20130101'
df['col2'] = '20130102 9:01'
df
col_list = ['col1','col2']
df[col_list] = df[col_list].apply(lambda x: pd.to_datetime(x))
df

rawDescription: How to do multiple column conversions on a Pandas Row in a DF in one pass

description: Do multiple column conversions on a Pandas Row in a DF in one pass


code:
#!/usr/bin/python2

import os
import shutil

moddirs = os.listdir("/lib/modules")
moddirs.remove(os.uname()[2])

for d in moddirs:
    shutil.rmtree(os.path.join("/lib/modules", d))

rawDescription: How to get kernel version by using kernel name (not current kernel)

description: Get kernel version by using kernel name (not current kernel)


code:
if any(word in data for word in ('word1', 'word2', 'word3')):
    ...

rawDescription: Check if each element in a list match with a string in Python?


code: mytext.replace(r"\r\n", r"\n")

rawDescription: Replacing "\r\n" with "\n"

description: Replacing "\r\n" with "\n"


code:
class MType(type):
    instances = []    #list of instances of the metaclass

    def __init__(cls, name, bases, dct):
            MType.instances.append(cls)    #append to list of instances
            super(MType, cls).__init__(name, bases, dct)

class MClass(object):
    __metaclass__ = MType

rawDescription: Given a python 2.7.2 type is there anyway I can construct a class instance programmatically?


code:
import itertools

for O, T, I, S, P in itertools.permutations((1,2,3,4,5,6,7,8,9), 5):
    OTTO = 1000 * O + 100 * T + 10 * T + O
    STOP = 1000 * S + 100 * T + 10 * O + P
    if OTTO * I == STOP:
        print(O, T, I, S, P)
        break

rawDescription: Multiplication Digits Solver in Python

description: Multiplication Digits Solver in Python


code:
cols = [c for c in df.columns if c != 'MyMagicCol'] + ['MyMagicCol']
df = df[cols]

rawDescription: Change the order of DataFrame columns using column names


code:
def dob(me):
    # Create a list of ints containing only the
    # numbers from the user input
    me = [int(s) for s in me if s.isdigit()]

    # Add all numbers in me and print it.
    total = sum(me)
    print(total)

# Get user input and store it to answer
answer = input("enter your dob")

# Call dob function and pass it the answer / input
dob(answer)

rawDescription: Adding All The numbers in a DOB?

description: Adding All The numbers in a DOB


code:
def normalise_repeatable_options(options):
    parsed = []
    flat = defaultdict(list)

    for o in options:
        if isinstance(o, Option):
            # For the first instance of this object, add a placemarker
            if o.long not in flat:
                parsed.append(o.long)

            flat[o.long].append(o)
        else:
            parsed.append(o)

    return [Option.combine(*tuple(flat[o])) if isinstance(o, str) else o for o in parsed]

rawDescription: Is there a more pythonic way of combining duplicate objects in a list?


code:
with open("C:\\Users\\Tharix\\Desktop\\test.txt", mode="r") as users:
    for line in users:
       print(line)

rawDescription: Python: Read next line in a file in one simple line of code


code:
for exponent1 in self.polynom:
    for exponent2 in other.polynom:
        this_exponent = exponent1 + exponent2
        this_coeff = self.coefficient(exponent1) *  other.coefficient(exponent2)
        try:
            mult[this_exponent] += this_coeff
        except KeyError:
            mult[this_exponent] = this_coeff

rawDescription: Multiplying polynomials in Python with the use of dictionaries


code:
replacements = {'newlines': ' ',
                'deletions': ''}
pattern = re.compile(u'(?P<newlines>\n+)|'
                     u'(?P<deletions>\u201c|\u201d|\u2019[a-z]?|\u2013|\u2018)')

def lookup(match):
    return replacements[match.lastgroup]

text = pattern.sub(lookup, text_1)

rawDescription: Multiple distinct replaces using RegEx

description: Multiple distinct replaces using RegEx


code:
#! /usr/bin/python

import sys
import pycurl

class Test:
    def __init__(self):
        self.contents = ''

    def body_callback(self, buf):
        self.contents = self.contents + buf

sys.stderr.write("Testing %s\n" % pycurl.version)

t = Test()
c = pycurl.Curl()
c.setopt(c.URL, 'http://curl.haxx.se/dev/')
c.setopt(c.WRITEFUNCTION, t.body_callback)
c.perform()
c.close()

print(t.contents)

rawDescription: How to achieve CURL equivalent python code

description: Achieve CURL equivalent python code


code:
def json_equal(json1,json2):

   number_of_items = len(json1)
   for item in json1:
       for item2 in json2:
           if item["address"] == item2["address"]:
               if item["amount"] == item2["amount"]:
                   number_of_items -= 1
                   break
           else:
               continue
   if number_of_items == 0:
       return True
   else:
       return False

rawDescription: Python Check if two list of jsons are equal


code:
from config.common import *
from config.specific import *

rawDescription: importing configuration from subfolders

description: Importing configuration from subfolders


code:
accounts = "('Hyvaco','TLC')"

sql ='SELECT * FROM archive.incoming WHERE LastCapacity=%s AND Account IN '+ accounts

rawDescription: MySQL python normalization of tuple fails in query


code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy

n = numpy.random.normal(size=10000)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_aspect(1)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)

base_trans = ax.transData
tr = matplotlib.transforms.Affine2D().rotate_deg(-30) + base_trans

ax.hist(n, normed=True, transform=tr, bins=20)

fig.savefig('t.png')

rawDescription: How to change the orientation of axis to a direction given by tuple in matplotlib

description: Change the orientation of axis to a direction given by tuple in matplotlib


code:
import datetime
import pytz

IT = pytz.timezone('Europe/Rome')
oggi = datetime.now(IT).date()

rawDescription: Time zones in Python

description: Time zones in Python


code:
import urllib3

http = urllib3.PoolManager()
r = http.request('get', 'http://www.google.com')

with open('page_source.html', 'w') as fid:
    fid.write(r.data)

rawDescription: how to save page source using urllib3 in Python

description: Save page source using urllib3 in Python


code:
list().__reduce__()
set().__reduce__()

rawDescription: __getstate__ method not being called when pickling a subclass of set


code:
(Campaign.objects
         .filter(
             pk=self.campaign.pk,
             company=self.company)
         .exists())

rawDescription: How to test a model relationship in Django

description: Test a model relationship in Django


code:
# If in optimize mode, we write the lextab
if lextab and optimize:
    lexobj.writetab(lextab,outputdir)

return lexobj

rawDescription: How to prevent table regeneration in PLY

description: Prevent table regeneration in PLY


code:
results = Museum.objects.all()
if city:
   results = results.filter(address__city=city)
if keyword:
   results = results.filter(Q(name__contains = keyword) | Q(description__contains = keyword))

rawDescription: Refactoring Django query

description: Refactoring Django query


code:
from collections import defaultdict
paircount = defaultdict(int)
pairtime = defaultdict(float)

#get number of pair occrences and total time
with open('input.txt', 'r') as f:
  with open('output.txt', 'w') as o:
    for numline, line in enumerate(f, 1):
        line = line.split()
        pair = line[0], line[1]
        paircount[pair] += 1
        pairtime[pair] += float(line[2])

    for pair, c in paircount.iteritems():
        #print pair[0], pair[1], c, pairper[pair], pairtime[pair]
        o.write("%s, %s, %s, %s, %s\n" % (pair[0], pair[1], c, c * 100.0 / numline, pairtime[pair]))

rawDescription: Easy way to compute Large data file python


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

from PyQt4 import QtGui, QtCore

class ObservableVariable(QtCore.QObject):
    """ Represents variable with value, when value changes it emits
    signal: changed(new_value)
    """
    changed = QtCore.pyqtSignal(object)

    def __init__(self, initial_value=0):
        super(ObservableVariable, self).__init__()
        self._value = initial_value

    def get_value(self):
        return self._value

    def set_value(self, new_val):
        self._value = new_val
        self.changed.emit(new_val)

    value = property(get_value, set_value)

    def __str__(self):
        return str(self.value)

    # it can support more operators if needed
    def __iadd__(self, other):
        self.value += other
        return self

    def __isub__(self, other):
        self.value -= other
        return self

class MyClass(object):
    def __init__(self, referrer=None, value=1):
        self.referrer = referrer
        self.value = ObservableVariable(value)
        self._initial_value = value
        if referrer:
            # propagate referrer changes to subscribers
            referrer.value.changed.connect(
                lambda x: self.value.changed.emit(self.value.value)
            )

    @property
    def start(self):
        if not self.referrer:
            return self.value.value
        return self.referrer.end + 1

    @property
    def end(self):
        return self.start + self.value.value - 1

class GuiExample(QtGui.QWidget):
    def __init__(self):
        super(GuiExample, self).__init__()
        self.values = []
        layout = QtGui.QVBoxLayout(self)
        obj = None
        for i in range(5):
            obj = MyClass(obj, i)
            self.values.append(obj)
            # create gui elements
            hlayout = QtGui.QHBoxLayout()
            spinbox = QtGui.QSpinBox()
            spinbox.setValue(obj.value.value)
            start_label = QtGui.QLabel()
            end_label = QtGui.QLabel()
            hlayout.addWidget(start_label)
            hlayout.addWidget(spinbox)
            hlayout.addWidget(end_label)
            layout.addLayout(hlayout)

            # function called on value change
            def update_start_end(instance, start_label, end_label):
                start_label.setText(str(instance.start))
                end_label.setText(str(instance.end))

            action = functools.partial(update_start_end, obj, start_label,
                                       end_label)
            action()  # set initial start end text to labels
            # connect signals to gui elements
            obj.value.changed.connect(action)
            spinbox.valueChanged.connect(obj.value.set_value)
            obj.value.changed.connect(spinbox.setValue)
        layout.addWidget(QtGui.QPushButton('test',
                                           clicked=self.test_modification))

    def test_modification(self):
        self.values[1].value += 1

app = QtGui.QApplication([])
gui = GuiExample()
gui.show()

app.exec_()

rawDescription: pyqt: dynamically update properties for dynamically created widgets

description: Pyqt: dynamically update properties for dynamically created widgets


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

# Known ranges for the histogram and plot
xmin, xmax = 20, 220
ymin, ymax = -1, 1

# Generate some random data
x = np.random.normal(48, 5, 100)
y = np.random.normal(0.4, 0.1, 100)

# Create arrays specifying the bin edges
nbins = 50
xbins = np.linspace(xmin, xmax, nbins)
ybins = np.linspace(ymin, ymax, nbins)

# Create the histogram using the specified bins
data, _, _ = np.histogram2d(x, y, bins=(xbins, ybins))

# Plot the result
fig, ax = plt.subplots()
ax.imshow(data.T, origin='lower', cmap='cubehelix', aspect='auto',
          interpolation='nearest', extent=[xmin, xmax, ymin, ymax])

ax.axis([xmin, xmax, ymin, ymax])
plt.show()

rawDescription: spread imshow heatmap over limits of axis

description: Spread imshow heatmap over limits of axis


code: datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)

rawDescription: On Windows, how to convert a timestamps BEFORE 1970 into something manageable?


code: liststore = Gtk.ListStore(*([str] * size))

rawDescription: Python: calling a function with varying number of arguments


code:
class Child(Base):
    def __init__(self, something_else):
        Base.__init__(self, value = 20)
        self.something_else = something_else

rawDescription: How to correctly call base class methods (and constructor) from inherited classes in Python?

description: Correctly call base class methods (and constructor) from inherited classes in Python


code:
from pyspark import SparkFiles

t.save("index.ann")
sc.addPyFile("index.ann")

def find_neighbors(iter):
    t = AnnoyIndex(f)
    t.load(SparkFiles.get("index.ann"))
    return (t.get_nns_by_vector(vector=x[1], n=5) for x in iter)

sparkvectors.mapPartitions(find_neighbors).first()
## [0, 13, 12, 6, 4]

rawDescription: Broadcast Annoy object in Spark (for nearest neighbors)?


code:
# A function to generate the divisions list
def divisions(l, v):
    l.append(l[-1] * v)
    return l

# A function to reduce the divisions list
def reduction(l, v):
    q, r = divmod(l[-1], v)
    l[-1] = q
    l.append(r)
    return l

TIME_STEPS = (60, 60, 24, 7, 30, 12)
DIVISIONS = reduce(divisions, TIME_STEPS, [1])[1:]
DIVISIONS.reverse()

# The "seconds" variable holds the time interval in seconds
seconds = 6000
fragments = reduce(reduction, DIVISIONS, [seconds])

# Fragments is a list: [years, months, weeks, days, hours, minutes, seconds]
# In this example: [0, 0, 0, 0, 1, 40, 0]

# And here's the readability part
NAMES = ("years", "months", "weeks", "days", "hours", "minutes", "seconds")
readable = " ".join("%d %s" % (v, n) for v, n in zip(fragments, NAMES) if v > 0)

# Final result: readable = "1 hours 40 minutes"

rawDescription: A more elegant version of generating the time to be viewed by humans


code:
from datetime import datetime
datetime.now().strftime("%b%y")

rawDescription: How to display current time in a specific format in python?

description: Display current time in a specific format in python


rawDescription: numpy: working on a subset of matrix

description: Numpy: working on a subset of matrix


code:
def circle(self, x0, y0, radius, colour=black):
    f = 1 - radius
    ddf_x = 1
    ddf_y = -2 * radius
    x = 0
    y = radius
    self.set(x0, y0 + radius, colour)
    self.set(x0, y0 - radius, colour)
    self.set(x0 + radius, y0, colour)
    self.set(x0 - radius, y0, colour)

    while x < y:
      if f >= 0:
        y -= 1
        ddf_y += 2
        f += ddf_y
        x += 1
        ddf_x += 2
        f += ddf_x
        self.set(x0 + x, y0 + y, colour)
        self.set(x0 - x, y0 + y, colour)
        self.set(x0 + x, y0 - y, colour)
        self.set(x0 - x, y0 - y, colour)
        self.set(x0 + y, y0 + x, colour)
        self.set(x0 - y, y0 + x, colour)
        self.set(x0 + y, y0 - x, colour)
        self.set(x0 - y, y0 - x, colour)
        Bitmap.circle = circle

        bitmap = Bitmap(25,25)
        bitmap.circle(x0=12, y0=12, radius=12)
        bitmap.chardisplay()

rawDescription: Circle in pixel grid

description: Circle in pixel grid


code:
PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

rawDescription: How to set/edit password in django admin view?

description: Set/edit password in django admin view


code:
import xml.etree.ElementTree as ET

xml = ET.parse('yourfile.xml')
root = xml.getroot()

value = root.find('./setting').attrib['id']

rawDescription: How to get this value on xml file using python? (See the xml code)

description: Get this value on xml file using python? (See the xml code)


code: from my_module import chain

rawDescription: Global variables in Python to share variable across files


code:
def dispatch(self, request, *args, **kwargs):
   response = super(AboutView, self).dispatch(request, *args, **kwargs)
   self.has_action(request, self)
   return response

rawDescription: How to call a custom method within generic.view at the end of the request

description: Call a custom method within generic.view at the end of the request


code:
cv2.namedWindow("window", cv2.WINDOW_AUTOSIZE)
# or cv.namedWindow("window",cv.CV_WINDOW_AUTOSIZE)
cv2.imshow("window", yourimage)

rawDescription: OpenCV: Auomatic resize of the window to the image displayed


code:
class Model(models.Model):
  def save(self, *args, **kwargs):
    instance = super(Model, self).save(*args, **kwargs)
    # your logic here to change the file location
    return instance

rawDescription: Dynamic File Path in Django and South

description: Dynamic File Path in Django and South


code:
for x in range(0,n):
    print(x, x*x)

rawDescription: Printing number pairs (two numbers) in python3


code:
def strip_string(string, to_strip):
    if to_strip:
        while string.startswith(to_strip):
            string = string[len(to_strip):]
        while string.endswith(to_strip):
            string = string[:-len(to_strip)]
    return string

rawDescription: Strip an ordered sequence of characters from a string


code:
Inventory = [["Item","Quantity"],["Credits","5000"],["Item 1", 2],["Item 3",1]]
[i for i,j in enumerate(Inventory) if j[0]=='Credits']

rawDescription: Finding index of a list containing an item, also in a list


code:
L1=ax.plot((0, 10000000), (3, 3), linewidth = 2, markersize = 0, clip_on = True, aa = True)
L2=ax.plot((10000001, 200000001), (3, 3), linewidth = 1, markersize = 0, clip_on = True, aa = True)
for item in L1+L2:
    item.set_solid_capstyle('butt')

rawDescription: Matplotlib Line Overlap/Resolution

description: Matplotlib Line Overlap/Resolution


code:
import os
for dirname in os.listdir("."):
    if os.path.isdir(dirname):
        for i, filename in enumerate(os.listdir(dirname)):
            os.rename(dirname + "/" + filename, dirname + "/" + str(i) + ".bmp")

rawDescription: How rename the images in folder

description: How rename the images in folder


rawDescription: How to implemente oauth process in a different window and then reload caller window

description: Implemente oauth process in a different window and then reload caller window


code:
class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

rawDescription: Controlling getter and setter for a python's class


code:
class User(object):
    def action_attack(self):
        ...

    def handle_action(self, name):
        method = getattr(self, 'action_' + name)
        method()

class SpecialUser(User):
    def action_attack(self):
        ...

rawDescription: Python - How to change this design?

description: Python - How to change this design


code:
setup(
    options = {"py2exe": {"dist_dir": os.path.join("..", "foo", "bar")}},
    windows = ["pythonturtle.py"],
)

rawDescription: Specifying relative path in py2exe

description: Specifying relative path in py2exe


code:
from BeautifulSoup import BeautifulSoup as B
s = B("")
s.span.attrs

rawDescription: How would I extract the value of this HTML element attribute with Beautiful Soup?


code:
if user_device is not None:
    parameters["user_device"] = user_device

rawDescription: Conditional key in dictionary - python

description: Conditional key in dictionary - python


code:
with open("path/to/file.txt","r") as f:
    d = {}
    for line in f:
        content,gene  = line.strip().split()
        if d.has_key(gene):
            d[gene].append(content)
        else:
            d[gene] = []
            d[gene].append(content)

    for key,value in d.iteritems():
        f = open("path/to/destination/{}.txt".format(key), "w")
        for item in value:
            f.write("{}\n".format(item))
        f.close()

rawDescription: Read a file and output new files containing subsets of main file


code:
import Blender

def get_length(path):
    """
    Return the length (in Blender distance units) of the path.
    """
    mesh = Blender.Mesh.New()
    mesh.getFromObject(path)

    return sum(edge.length for edge in mesh.edges)

rawDescription: Measure Path Length in Blender Script?

description: Measure Path Length in Blender Script


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

# Make some fake data and a sample plot
x = np.arange(1,100)
y = x**2 * 1.0e6
ax = plt.axes()
ax.plot(x,y)

# Adjust the fontsizes on tick labels for this plot
fs = 14.0
[t.set_fontsize(fs) for t in ax.xaxis.get_majorticklabels()]
[t.set_fontsize(fs) for t in ax.yaxis.get_majorticklabels()]
ax.yaxis.get_offset_text().set_fontsize(fs)

# Here is the label and arrow code of interest
ax.annotate('SDL', xy=(0.5, 0.90), xytext=(0.5, 1.00), xycoords='axes fraction',
            fontsize=fs*1.5, ha='center', va='bottom',
            bbox=dict(boxstyle='square', fc='white'),
            arrowprops=dict(arrowstyle='-[, widthB=7.0, lengthB=1.5', lw=2.0))

rawDescription: Drawing brackets over plot

description: Drawing brackets over plot


rawDescription: python built-in function to do matrix reduction

description: Python built-in function to do matrix reduction


code:
import os, sys
import shutil
import random
from shutil import copyfile

#folder which contains the sub directories
source_dir = '/home/mrman/dataset-python/train/'

#list sub directories
for root, dirs, files in os.walk(source_dir):

#iterate through them
    for i in dirs:

        #create a new folder with the name of the iterated sub dir
        path = '/home/mrman/dataset-python/sub-train/' + "%s/" % i
        os.makedirs(path)

        #take random sample, here 3 files per sub dir
        filenames = random.sample(os.listdir('/home/mrman/dataset-python/train/' + "%s/" % i ), 3)

        #copy the files to the new destination
        for j in filenames:
            shutil.copy2('/home/mrman/dataset-python/train/' + "%s/" % i  + j, path)

rawDescription: loop through sub directories, to sample files

description: Loop through sub directories, to sample files


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

ln1, = ax1.plot([], [], 'r-')
ln2, = ax1.plot([], [], 'g-')
def animate(i):
    # do what ever you need to get your data out
    # assume that you have x1, y1, x2, y2
    ln1.set_data(x1, y1)
    ln2.set_data(x2, y2)
    return ln1, ln2

ani = animation.FuncAnimation(fig, animate, interval=1000)

rawDescription: Matplotlib Live Update Graph

description: Matplotlib Live Update Graph


rawDescription: Convert a column to an index in pandas

description: Convert a column to an index in pandas


code:
def replace_tab(s, tabstop = 4):
  result = str()
  for c in s:
    if c == '\t':
      while (len(result) % tabstop != 0):
        result += ' ';
    else:
      result += c
  return result

rawDescription: How to replace custom tabs with spaces in a string, depend on the size of the tab?

description: Replace custom tabs with spaces in a string, depend on the size of the tab


rawDescription: Find entry in dataset using dictionary

description: Find entry in dataset using dictionary


code:
import os
import shutil

filenames_i_want = set() # fill this with the filenames you want
dest_dir = 'whatever'
src_dir = 'whatever'

for (dirpath, dirnames, filenames) in os.walk(src_dir):
    for fname in filenames:
        if fname in filenames_i_want:
            shutil.copy(os.path.join(dirpath, fname), dest_dir)

rawDescription: Python : Searching a directory for files in a list


code:
import re
re.sub(r'0$', '', line)

rawDescription: Removing last character of JSON object

description: Removing last character of JSON object


code:
def get_list(self, term, offset=0, limit=DEFAULT_PAGE_SIZE):
    filters = list(
        field.ilike(u'%%%s%%' % term) for field in self._cached_fields
    )
    filters.append(Organisation.org_id == "Google")
    return (
        db.session.query(Product)
        .join(organisation_products_table)
        .join(Organisation)
        .filter(*filters)
        .all()
    )

rawDescription: flask admin custom QueryAjaxModelLoader

description: Flask admin custom QueryAjaxModelLoader


code:
import pickle

savelist = ["Example"]
namelist = ["Example2"]

obj_to_pickle = (savelist, namelist)

with open("path/to/savefile.pkl", 'wb') as p:
    pickle.dump(obj_to_pickle, p)
    # save data

with open('path/to/savefile.pkl', 'rb') as p:
    obj_from_pickle = pickle.load(p)
    savelist, namelist = obj_from_pickle
    # load data

rawDescription: Trying to access a list in a file and use it as a string


code:
class Buttons (QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.Widgets()
        self.arrange()
        self.close()
        self.button1.clicked.connect(self.messageBox)
        self.setWindowTitle ("test")

    @pyqtSlot()
    def messageBox(self):
        self.message = QMessageBox()
        self.message.setText ("submit ERROR")
        self.message.setStandardButtons(QMessageBox.Ok)

        self.message.exec_()

rawDescription: PyQt5: Validate LineEdit through QPushButton using signals and slots


code:
import sys
import io

out, err = io.StringIO(), io.StringIO()
sys.stdout = out
sys.stderr = err

# rest of your code here

# once your code is finished

results = out.getvalue()
errors = err.getvalue()

rawDescription: Python PSS/E get output as variable

description: Python PSS/E get output as variable


rawDescription: How can I test if Python http.server.HTTPServer is serving forever?

description: Test if Python http.server.HTTPServer is serving forever


code:
from itertools import chain
q1 = RssNewItem.objects.filter(author="author1").order_by("-published")[:3]
q2 = RssNewItem.objects.exclude(author="author1").order_by("-published")[:7]
q = list(chain(q1, q2))

rawDescription: Django, retrieving database news items promoting a certain author


code:
def wbbrowser():
    ...
    text = source.get()
    message = "
%s
</body" % text
    ...

rawDescription: Combining HTML and Tkinter Text Input

description: Combining HTML and Tkinter Text Input


code:
import shutil
shutil.copy(f.name, 'new-name')

rawDescription: Rename python tempfile

description: Rename python tempfile


code: q = db.session.query(Phrase.content, Meaning.content).join(Meaning).all()

rawDescription: Select attributes from different joined tables with Flask and SQLAlchemy


rawDescription: Django-model-utils Filter By Subclass

description: Django-model-utils Filter By Subclass


code:
import os

def overwrite(f):
    """Overwrite a file with zeroes.

    Arguments:
    f -- name of the file
    """
    stat = os.stat(f)
    with open(f, 'r+') as of:
        of.write('\0' * stat.st_size)
        of.flush()

rawDescription: Write zeros to file blocks

description: Write zeros to file blocks


rawDescription: How to get the size/length of sub-elements within an XML tag using python

description: Get the size/length of sub-elements within an XML tag using python


code:
x, y = A.groupby('one'), B.groupby('one')

res = {i[0]:i[1].two.corr(y.get_group(i[0]).two) for i in x}

pd.DataFrame(res.items())
#   0  1
#0  a -1
#1  b -1

rawDescription: Compute separate correlations, grouped by column value


code:
import os
import glob
for filename in glob.glob('*.apk'):
    os.system("java -Xmx4g -cp soot-trunk.jar;soot-infoflow.jar;soot-infoflow-android.jar;slf4j-api-1.7.5.jar;slf4j-simple-.7.5.jar;axml-2.0.jar soot.jimple.infoflow.android.TestApps.Test C:\\Users\\Admin\\Downloads\\DroidBench-master\\DroidBench-master\\apk\\nf\\%s C:\\Users\\Admin\\Downloads\\EnSoft\\EnSoft\\android-sdk\\platforms" % filename)

rawDescription: Can glob be used in conjuction with os.system?


code: increase = adder(increase)

rawDescription: Python global variables

description: Python global variables


code:
def similar(row):
    x = SequenceMatcher(None, row['FullName'], row['ScreenName']).ratio()
    score = x*100
    results = round(score, 2)
    return results

dataframe['result'] = dataframe.apply(lambda row: similar(row), axis=1)

rawDescription: Apply a function to two DataFrame columns and create new column from result


code:
with open('data.txt') as in_file, open('new.txt', 'w') as out_file:
    # get the dataset identifiers
    ID = in_file.next().strip()
    date_strong = in_file.next().strip()
    force_ratio = in_file.next().strip()
    force_ratio1, force_ratio2 = force_ratio.split()
    in_file.next()  # Garbage line
    # example data has two blank lines
    in_file.next()
    in_file.next()
    dataset_id = (ID, date_strong, force_ratio1, force_ratio2)
    # iterate over the records
    for line in in_file:
        # prepend the dataset id
        record = list(dataset_id)
        record.extend(line.split())
        # write to the new file
        out_file.write(','.join(record) + '\n')

rawDescription: Bad dataset layout

description: Bad dataset layout


code:
d = {1:2, 3:4, 5:6}
for key, value in d.items():
    print(key, value)

rawDescription: Python dict get value fastest way

description: Python dict get value fastest way


code:
from gi.repository import Gtk, Gdk

class MyTable(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Table")

        main_box=Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        button_add_rows=Gtk.Button(label="Add Rows")
        button_add_rows.connect("clicked", self.add_row)
        main_box.add(button_add_rows)

        self.grid = Gtk.Grid(column_spacing=1,row_spacing=1)
        self.grid.override_background_color(Gtk.StateFlags.NORMAL,Gdk.RGBA(0.0,0.0,0.0,0.5))
        main_box.add(self.grid)

        self.number_of_columns=5
        self.number_of_rows=10

        self.add(main_box)

        for column in range(self.number_of_columns):
            button=Gtk.Button(label=column)
            self.grid.attach(button,column,1,1,1)

        for column in range(self.number_of_columns):
            for row in range(self.number_of_rows):
                a=Gtk.Label()
                a.override_background_color(Gtk.StateFlags.NORMAL,Gdk.RGBA(0.95,0.95,0.95,1.0))
                self.grid.attach(a,column, row+1,1,1)

    def add_row(self, button, data=None):
        for column in range(self.number_of_columns):
            for row in range(self.number_of_rows+1, self.number_of_rows+2):
                a=Gtk.Label()
                a.override_background_color(Gtk.StateFlags.NORMAL,Gdk.RGBA(0.95,0.95,0.95,1.0))
                self.grid.attach(a,column, row+1,1,1)

        self.grid.show_all()
        self.number_of_rows+=1

table_window = MyTable()
table_window.connect("delete-event", Gtk.main_quit)
table_window.show_all()
Gtk.main()

rawDescription: Gtk.Grid(): how to dynamically modify the number of rows


code:
events = response.xpath('//ul[@class = "events"]/li')
for event in events:
    item = MyItem()

    item['cost'] = event.xpath(".//h4[. = 'Cost']/following-sibling::div/p/text()").extract_first()
    item['time'] = event.xpath(".//h4[. = 'Time']/following-sibling::div/p/text()").extract_first()

    yield item

rawDescription: Scrapy: traversing a document

description: Scrapy: traversing a document


code:
import sys
from setuptools import setup, find_packages
import os

setup(
    name = "santas-little-helper",
    version = "version",
    author = "Me",
    author_email = "Me@my.com",
    description = "Something descriptiv",
    packages=["toplevelpackage"],
    entry_points={
        "console_scripts" : [
            "santas-little-helper = toplevelpackage:main",
            ],
        },
)

rawDescription: Filesystem: Where would I place a program that makes a new project?


code:
a['C'] = a['A'].combine_first(a['B']).astype(int)
a

rawDescription: pandas: add new column with value from either of two other columns

description: Pandas: add new column with value from either of two other columns


code:
my_set = {x[0] for x in my_tuples}
my_sums = [(i,sum(x[1] for x in my_tuples if x[0] == i)) for i in my_set]

rawDescription: How to sum up a list of tuples having the same first element?

description: Sum up a list of tuples having the same first element