code:
import datetime

hello = input("What is 10+9?")

if hello > 20:
   print(datetime.datetime.now)

rawDescription: I am trying to do an if statement with the input to be 21 and the result be Time printed out


code: info = soup.find('span', itemprop='name').contents

rawDescription: Getting text from a funky span object in html


code:
import re
onedollar = re.compile(r'^[^\$]*\$[^\$]*$')
onedollar.match('$1 off delicious ham.')
onedollar.match('$1 off delicious $5 ham.')

rawDescription: python regex: match a string with only one instance of a character

description: Python regex: match a string with only one instance of a character


code:
s = 'hello'
s.index('h')

rawDescription: Is there anyway to do a reverse index in Python


code:
df = DataFrame(np.random.randn(8,3))
store = HDFStore('test.h5')
store['df'] = df
store.get_storer('df').attrs.my_attribute = dict(A = 10)
store.get_storer('df').attrs.my_attribute

rawDescription: Storing Pandas objects along with regular Python objects in HDF5


code:
from BeautifulSoup import BeautifulSoup
url = "hhttp://0.0.0.0:3000/authenticate/login"
page = urlli2b.urlopen(page)
soup = BeautifulSoup(page)
token = soup.find("input", { 'name': 'authenticity_token'})

rawDescription: Pythonic way to find a regular expression match


code:
dict = {'a': 'one', 'b': 'two', }
qdict = QueryDict('', mutable=True)
qdict.update(dict)

rawDescription: Django: Can I create a QueryDict from a dictionary?


code:
from ast import literal_eval
literal_eval(u'229, 255, 66')

description: Convert '229, 255, 66' to (229, 255, 66) in Python


code:
msgBox = QMessageBox( QMessageBox.Warning, "My title", "My text.", QMessageBox.NoButton )

# Get the layout
l = msgBox.layout()

# Hide the default button
l.itemAtPosition( l.rowCount() - 1, 0 ).widget().hide()

progress = QProgressBar()

# Add the progress bar at the bottom (last row + 1) and first column with column span
l.addWidget(progress,l.rowCount(), 0, 1, l.columnCount(), Qt.AlignCenter )

msgBox.show()

rawDescription: How to subclass QMessageBox and add a progress bar in PySide

description: Subclass QMessageBox and add a progress bar in PySide


code:
import datetime
s = '2012265'
datetime.datetime.strptime(s, '%Y%j')
d = '41213'
datetime.date(1900, 1, 1) + datetime.timedelta(int(d))

rawDescription: Converting date formats python - Unusual date formats - Extract %Y%M%D


code:
import json
import urllib2

search_line = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=hello'
response = urllib2.urlopen(search_line)
search_results = json.loads(response.read())
print(search_results['responseData']['results'])

rawDescription: How do you use google's API to do a simple search in Python?

description: Use google's API to do a simple search in Python


code:
x = list(range(1, 101))  # python 3
x = range(1, 101)        # python 2

rawDescription: How to make a list of numbers

description: Make a list of numbers


code:
for address in guido.addresses:
    if address.type == 'work':
        address.street = "Main Street"
        address.city = "Timbuktu"

guido.put()

rawDescription: How does one retrieve and manipulate ndb StructuredProperty objects?

description: Retrieve and manipulate ndb StructuredProperty objects


code:
from subprocess import check_output, call
import pandas as pd
import numpy as np
import os

pad = 0.1
tablename = 'sandbox.max.pybcp_test'
overwrite=True
raise_exception = True
server = 'P01'
trusted_connection= True
username=None
password=None
delimiter='|'
df = pd.read_csv('D:/inputdata.csv', encoding='latin', error_bad_lines=False)

def get_column_def_sql(col):
   if col.dtype == object:
      width = col.str.len().max() * (1+pad)
      return '[{}] varchar({})'.format(col.name, int(width))
   elif np.issubdtype(col.dtype, float):
      return'[{}] float'.format(col.name)
   elif np.issubdtype(col.dtype, int):
      return '[{}] int'.format(col.name)
   else:
      if raise_exception:
         raise NotImplementedError('data type {} not implemented'.format(col.dtype))
      else:
         print('Warning: cast column {} as varchar; data type {} not implemented'.format(col, col.dtype))
         width = col.str.len().max() * (1+pad)
         return '[{}] varchar({})'.format(col.name, int(width))

def create_table(df, tablename, server, trusted_connection, username, password, pad):
    if trusted_connection:
       login_string = '-E'
    else:
       login_string = '-U {} -P {}'.format(username, password)

    col_defs = []
    for col in df:
       col_defs += [get_column_def_sql(df[col])]

    query_string = 'CREATE TABLE {}\n({})\nGO\nQUIT'.format(tablename, ',\n'.join(col_defs))
    if overwrite == True:
       query_string = "IF OBJECT_ID('{}', 'U') IS NOT NULL DROP TABLE {};".format(tablename, tablename) + query_string

    query_file = 'c:\\pybcp_tempqueryfile.sql'
    with open (query_file,'w') as f:
       f.write(query_string)

    if trusted_connection:
       login_string = '-E'
    else:
       login_string = '-U {} -P {}'.format(username, password)

    o = call('sqlcmd -S {} {} -i {}'.format(server, login_string, query_file), shell=True)
    if o != 0:
       raise BaseException("Failed to create table")
   # o = call('del {}'.format(query_file), shell=True)

def call_bcp(df, tablename):
    if trusted_connection:
       login_string = '-T'
    else:
       login_string = '-U {} -P {}'.format(username, password)
    temp_file = 'c:\\pybcp_tempqueryfile.csv'

    #remove the delimiter and change the encoding of the data frame to latin so sql server can read it
    df.loc[:,df.dtypes == object] = df.loc[:,df.dtypes == object].apply(lambda col: col.str.replace(delimiter,'').str.encode('latin'))
    df.to_csv(temp_file, index = False, sep = '|', errors='ignore')
    o = call('bcp sandbox.max.pybcp_test2 in c:\pybcp_tempqueryfile.csv -S "localhost" -T -t^| -r\n -c')

rawDescription: Write Large Pandas DataFrames to SQL Server database


code:
import unicodedata
files = [unicodedata.normalize('NFC', f) for f in os.listdir(u'.')]

rawDescription: UTF-8 and os.listdir()

description: UTF-8 and os.listdir()


code:
X = (df.index -  df.index[0]).days.reshape(-1, 1)
y = df['value'].values
linear_model.LinearRegression().fit(X, y)

rawDescription: Use Scikit Learn to do linear regression on a time series pandas data frame


code:
p["RestoreRamDisks"]["Update"]
# If your plist may not contain a key called "RestoreRamDisks"
# use this instead
p.get("RestoreRamDisks", dict(Update=None)).get("Update", None)
# This will get the value if available, otherwise it will
# evaluate to None

rawDescription: Save python plistlib data (revised)

description: Save python plistlib data (revised)


code:
def rand_float_range(start, end):
    return random.random() * (end - start) + start

rawDescription: random.randint for non integer number? [Python]

description: Random.randint for non integer number? [Python]


code:
def build(self):
    running = True
    while running:
        attempt = random.choice(sUpper)
        a = 0
        while a <= (self.length-1):
            attempt += random.choice(sLower)
            a += 1
        for i in vowels:
            if i in attempt:
                word = attempt
                running = False
                break
    return word

rawDescription: Why is my word generator not working?

description: Why is my word generator not working


code:
from setuptools import setup, find_packages

setup(name='scrapy-mymodule',
  entry_points={
    'scrapy.commands': [
      'my_command=my_scrapy_module.commands:MyCommand',
    ],
  },
 )

rawDescription: How we can get List of urls after crawling website from scrapy in costom python script?


code:
approved_origins = ['https://example.com', 'https://example.info']
if self.request.headers['Origin'] in approved_origins:
  self.response.headers.add_header('Access-Control-Allow-Origin', self.request.headers['Origin'])

rawDescription: CORS on GAE - Multiple Origins

description: CORS on GAE - Multiple Origins


code:
#!/bin/python

import sys
from colorama import *
from numpy import zeros

init()

inv_WHITE = Fore.WHITE[::-1]
inv_RED = Fore.RED[::-1]
inv_GREEN = Fore.GREEN[::-1]

def edDistDp(y, x):
        res = inv_WHITE
        D = zeros((len(x)+1, len(y)+1), dtype=int)
        D[0, 1:] = range(1, len(y)+1)
        D[1:, 0] = range(1, len(x)+1)
        for i in xrange(1, len(x)+1):
                for j in xrange(1, len(y)+1):
                        delt = 1 if x[i-1] != y[j-1] else 0
                        D[i, j] = min(D[i-1, j-1]+delt, D[i-1, j]+1, D[i, j-1]+1)
        #print D

        # iterate the matrix's values from back to forward
        i = len(x)
        j = len(y)
        while i > 0 and j > 0:
                diagonal = D[i-1, j-1]
                upper = D[i, j-1]
                left = D[i-1, j]

                # check back direction
                direction = "\\" if diagonal <= upper and diagonal <= left else "<-" if left < diagonal and left <= upper else "^"
                #print "(",i,j,")",diagonal, upper, left, direction
                i = i-1 if direction == "<-" or direction == "\\" else i
                j = j-1 if direction == "^" or direction == "\\" else j
                # Colorize caracters
                if (direction == "\\"):
                        if D[i+1, j+1] == diagonal:
                                res += x[i] + inv_WHITE
                        elif D[i+1, j+1] > diagonal:
                                res += y[j] + inv_RED
                                res += x[i] + inv_GREEN
                        else:
                                res += x[i] + inv_GREEN
                                res += y[j] + inv_RED
                elif (direction == "<-"):
                        res += x[i] + inv_GREEN
                elif (direction == "^"):
                        res += y[j] + inv_RED
        return res[::-1]

one_string =   "beep boop"
other_string = "beep boob blah"
print ("'%s'-'%s'='%s'" % (one_string, other_string, edDistDp(one_string, other_string)))
print ("'%s'-'%s'='%s'" % (other_string, one_string, edDistDp(other_string, one_string)))

other_string = "hola nacho"
one_string =   "hola naco"
print ("'%s'-'%s'='%s'" % (one_string, other_string, edDistDp(one_string, other_string)))
print ("'%s'-'%s'='%s'" % (other_string, one_string, edDistDp(other_string, one_string)))

rawDescription: How to diff two string sequences in Python?

description: Diff two string sequences in Python


code:
def validate_parkings(self, value):
    user_parkings = set(self.context['request'].user.parkings.all())
    post_parkings = set(value)
    if not post_parkings.issubset(user_parkings):
        raise serializers.ValidationError("parking doesn't belong to you")
    return value

rawDescription: Django restframework: Validate a related field with a list of IDs


code:
import datetime
today = datetime.datetime.now()
insummer = datetime.datetime(2009,8,15,10,0,0)
from pytz import reference
localtime = reference.LocalTimezone()
localtime.tzname(today)
localtime.tzname(insummer)

rawDescription: how to get tz_info object corresponding to current timezone?

description: Get tz_info object corresponding to current timezone


rawDescription: Plotting two lists with different lengths with interpolation


code:
series = pd.Series()
for l in b_list:
    series = series.append(l.get_results())
    print(l.get_results())
    count += 1
print(series)

rawDescription: Issue with adding elements to Series

description: Issue with adding elements to Series


code:
y2 = numpy.transpose([y])
y2
numpy.multiply(x, y2)

rawDescription: Elementwise multiplication of numpy matrix and column array


rawDescription: Create list from input

description: Create list from input


code:
theta = arccos(r/rho)
s_real = rho**(1./3.) * cos( theta/3)
t_real = rho**(1./3.) * cos(-theta/3)

rawDescription: Solving a cubic equation

description: Solving a cubic equation


code:
with open('thefile.mp3', 'rb') as f:
    thesocket.sendall(f.read())

rawDescription: How do i send a file with sockets in python?

description: Send a file with sockets in python


code:
import csv
import datetime as dt
import os

File = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/HiSAM1_data_160215_164858.csv'
root, ext = os.path.splitext(File)
output = root + '-new.csv'
with open(File,'r') as csvinput,open(output, 'w') as csvoutput:

    writer = csv.writer(csvoutput, lineterminator='\n')
    reader = csv.reader(csvinput)

    rows = [next(reader)]
    for line in reader:
        line[0] = str(dt.datetime.strptime(line[0],'%m/%d/%Y %H:%M:%S').time())
        rows.append(line)

    writer.writerows(rows)

rawDescription: Python- Can't overwrite first column of .csv file with new time stamp


code:
import csv
iterable = ['Reseller,cost', 'fred,100', 'joe,99']
reseller_csv = csv.DictReader(iterable)
map(lambda x: x.get('Reseller'), reseller_csv)
map(lambda x: x.get('Reseller'), reseller_csv)

rawDescription: Map over csv in python

description: Map over csv in python


code:
import time
x = time.localtime(time.time())
dir(x) # output below formatted for readability and removing _-prefixed things
x.tm_hour

rawDescription: How to Extract the Current Hour value for Integer arithmetic? (Python)


code:
from string import maketrans

"Abc".translate(maketrans("abcABC", "defDEF"))

rawDescription: case sensitive string replacement in Python

description: Case sensitive string replacement in Python


code:
class Storage(object):
    __slots__ = ('__keys__', '__vals__', '__separator__')
    def __init__(self):
        super(Storage, self).__setattr__('__separator__', "ANY OF ANYS")
        super(Storage, self).__setattr__('__keys__', [])
        super(Storage, self).__setattr__('__vals__', [])

    def __getattr__(self, key):
        try:
            vals = getattr(self, '__vals__')
            keys = getattr(self, '__keys__')
            return vals[keys.index(key)]
        except IndexError:
            raise AttributeError

    def __setattr__(self, key, val):
        vals = getattr(self, '__vals__')
        keys = getattr(self, '__keys__')
        vals.append(val)
        keys.append(key)

rawDescription: How to clear instance data without setattr?

description: Clear instance data without setattr


code:
#!/usr/bin/python

import mosquitto

def on_publish(mosq, userdata, mid):
  # Disconnect after our message has been sent.
  mosq.disconnect()

# Specifying a client id here could lead to collisions if you have multiple
# clients sending. Either generate a random id, or use:
#client = mosquitto.Mosquitto()
client = mosquitto.Mosquitto("image-send")
client.on_publish = on_publish
client.connect("127.0.0.1")

f = open("data")
imagestring = f.read()
byteArray = bytes(imagestring)
client.publish("photo", byteArray ,0)
# If the image is large, just calling publish() won't guarantee that all
# of the message is sent. You should call one of the mosquitto.loop*()
# functions to ensure that happens. loop_forever() does this for you in a
# blocking call. It will automatically reconnect if disconnected by accident
# and will return after we call disconnect() above.
client.loop_forever()

rawDescription: How can I publish a file using Mosquitto in python?

description: Publish a file using Mosquitto in python


code:
def getTickets(ticket, SEAT_LIMIT):
    ticket=int(input("Enter:"))
    return ticketsInvalid(ticket, SEAT_LIMIT)

rawDescription: Python homework help request

description: Python homework help request


code:
for posi in [0,1,2,3,4]:
    diagonal.append(matrix[posi][len(matrix)-1-posi])

rawDescription: Printing diagonal from top-right to bottom-left of matrix python 2


rawDescription: How to sort by value efficiently in PySpark?

description: Sort by value efficiently in PySpark


code: {{ content|safe }}

rawDescription: Escaping HTML in python. AppEngine

description: Escaping HTML in python. AppEngine


code:
from Selenium2Library import Selenium2Library
from selenium.webdriver.common.action_chains import ActionChains

class Selenium2Improved(Selenium2Library):
    '''Sometimes Selenium2Library just dont go far enough.'''

    def __init__(self, timeout=5.0, implicit_wait=0.0, run_on_failure='Capture Page Screenshot'):
        super(Selenium2Improved, self).__init__()

    def mouse_down_at(self, locator, coordx, coordy):
        element = self._element_find(locator, True, False)
        if element is None:
            raise AssertionError("ERROR: Element %s not found." % (locator))
        ActionChains(self._current_browser()).move_to_element(element).move_by_offset(coordx, coordy).click_and_hold().perform()

    def mouse_up_at(self, locator, coordx, coordy):
        element = self._element_find(locator, True, False)
        if element is None:
            raise AssertionError("ERROR: Element %s not found." % (locator))
        ActionChains(self._current_browser()).move_to_element(element).move_by_offset(coordx, coordy).release().perform()

rawDescription: Unable to use the command mouse_down_at in Selenium


code:
class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        toolMenu = QtGui.QMenuBar()
        toolMenu.setNativeMenuBar(False) # <--
        self.setMenuBar(toolMenu)

        for i in range(5):
            _ = toolMenu.addAction('Action {}'.format(i))

rawDescription: Show menu bar (always) using python Qt4 (pyqt) in ubuntu 14.04


code:
import Image
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

rawDescription: How to convert Numpy array to PIL image applying matplotlib colormap

description: Convert Numpy array to PIL image applying matplotlib colormap


code:
def __iter__(self):
    for datum in self.data:
        yield datum + 1

rawDescription: What is the point of the body of the __iter__ method?


code: A = coo_matrix((values, coords.T))

rawDescription: Scipy quickly initialise sparse matrix from list of coordinates


code:
print('Welcome to your currency converter\n Please choose your starting currency from the four options:')
currency1 = input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()

while currency1 not in ['gdp', 'eur', 'usd', 'jpy']:
    print('Sorry not accepted try again')
    currency1 = input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()

rawDescription: Re-run a code from a particular point

description: Re-run a code from a particular point


rawDescription: Concatenate 3 unidimensional arrays together in numpy


code:
def save(self, commit = False):
    User.objects.create_user(username = self.cleaned_data['username'],
                                email = self.cleaned_data['email'],
                                password = self.cleaned_data['password1'])

    return super(ExtendedUserForm, self).save(self, commit = commit)

rawDescription: Django access to attributes with self

description: Django access to attributes with self


rawDescription: Python: read txt file and make class from data


code:
args=[2,3]
sql="select * from sqlitetable where rowid in ({seq})".format(
    seq=','.join(['?']*len(args)))

cursor.execute(sql, args)

rawDescription: select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0

description: Select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0


code:
import sendgrid

sg = sendgrid.SendGridClient('sendgrid_apikey')

message = sendgrid.Mail()
message.add_to('John Doe <john@email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe@email.com>')

# This next section is all to do with Template Engine

# You pass substitutions to your template like this
message.add_substitution('-thing_to_sub-', 'Hello! I am in a template!')

# Turn on the template option
message.add_filter('templates', 'enable', '1')

# Tell SendGrid which template to use
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')

# Get back a response and status
status, msg = sg.send(message)

rawDescription: how to use designed template in django using sendgrid API?

description: Use designed template in django using sendgrid API


rawDescription: Django Custom image upload field with dynamic path


code:
# Classes are added here if they are important, because...
important_classes = []

def important(cls):
    important_classes.append(cls)
    return cls

@important
class ClassA(object):
    pass

class ClassB(object):
    pass

@important
class ClassC(object):
    pass

# Now you can use the important_classes list however you like.
print(important_classes)
# => [<class '__main__.ClassA'>, <class '__main__.ClassC'>]

rawDescription: Python: find classes in module before class is defined


code:
x = [True, False, True, True, False]
all(x)

rawDescription: Processing Boolean in a Python List

description: Processing Boolean in a Python List


code:
def hms_to_seconds(t):
    h, m, s = [int(i) for i in t.split(':')]
    return 3600*h + 60*m + s

rawDescription: Python Time conversion h:m:s to seconds

description: Python Time conversion h:m:s to seconds


code:
columns = ['Facility', 'Category', 'ID', 'Part', 'Text']

# It's always a good idea to sort after creating a MultiIndex like this
df = df.set_index(columns).sortlevel()
df1 = df1.set_index(columns).sortlevel()

# You don't have to use Yes here, anything will do
# The boolean True might be more appropriate
df['MatchingFlag'] = "Yes"
df1['MatchingFlag'] = "Yes"

# Add them together, matching rows will have the value "YesYes"
# Non-matches will be nan
result = df + df1

# If you'd rather not have NaN's
result.loc[:,'MatchingFlag'] = result.loc[:,'MatchingFlag'].replace('YesYes','Yes')
result.loc[:,'MatchingFlag'] = result['MatchingFlag'].fillna('No')

rawDescription: Pandas Compare between Two DataFrames, flag what matches


code:
#!/usr/bin/env python3
from gi.repository import Gtk,Gdk, GLib
import threading
import time

class Gui(Gtk.Window):
  def __init__(self):
      self.Window = Gtk.Window()
      self.Window.set_border_width(8)
      self.Window.set_title("Некий GUI")
      self.Window.connect('destroy', lambda x: self.stop())

      self.outBut = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
      self.outBut.set_size_request(150, 35)
      self.Window.connect('destroy', lambda x: self.stop())
      self.Window.add(self.outBut)

      self.Window.show_all()
      threading.Thread(target=loop_sleep).start()

  def stop(self):
      Gtk.main_quit()

  def passfun(self):
      pass

def loop_sleep():
      i = 1
      while True:
           print(i)
           i = i + 1
           #time.sleep(1)

app = Gui()
GLib.threads_init()
Gdk.threads_init()
Gdk.threads_enter()
Gtk.main()
Gdk.threads_leave()

rawDescription: Python. Doing some work on background with Gtk GUI


code:
from sympy import symbols, diff
x, y, z = symbols('x y z', real=True)
f = 4*x*y + x*sin(z) + x**3 + z**8*y
diff(f, x)

rawDescription: Python partial derivatives easy

description: Python partial derivatives easy


code:
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm

df = pd.read_csv('/home/Jian/Downloads/data.csv', index_col=[0])

# get part of the data
x = df.loc[df.House==1, 'Daylight']
# hp-filter, set parameter lamb=129600 following the suggestions for monthly data
x_smoothed, x_trend = sm.tsa.filters.hpfilter(x, lamb=129600)
fig, axes = plt.subplots(figsize=(12,4), ncols=3)
axes[0].plot(x)
axes[0].set_title('raw x')
axes[1].plot(x_trend)
axes[1].set_title('trend')
axes[2].plot(x_smoothed)
axes[2].set_title('smoothed x')

rawDescription: can not remove a trend components and a seasonal components

description: Can not remove a trend components and a seasonal components


code:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save)
def log_creation(sender, instance, created, **kwargs):
    if created and isinstance(instance, (ModelA, ModelB)):
        logger.info("created an instance of %s : %s", sender.__name__, instance)

rawDescription: What is the best way to add logging for creation of a Django Model instance?


code:
import SCons
import shutil
import os

env = Environment(tools=['default', 'textfile'])

def package_builder(target, source, env):
  cmdLine = 'python test.py'
  return os.system(cmdLine)

def copy(env, target, source):
  shutil.copy(source[0].path, target[0].path)
env.Append(BUILDERS = { 'copybuilder' : Builder(action = Action(copy, ' COPY $SOURCE -> $TARGET')) } )
env.Append(BUILDERS = { 'package' : Builder(action = Action(package_builder, ' PACKAGE $SOURCES -> $TARGET'), suffix='.zip' ) } )

env.Textfile(target='foo.txt', source='hello, world\n')

#
# Here the changes start
#

# The following line is not needed, SCons picks up the
# dependency bar.txt -> foo.txt automatically
#tclib = env.Alias('transcoderLib', 'foo.txt')
copyTarget = env.copybuilder('bar.txt', 'foo.txt')
# Defining Alias for later reference...
# important: don't create new Alias()es all over
#            the place, but pass a single reference around
tclib = env.Alias('transcoderLib', copyTarget)

# Main change: Your initial dependencies were wrong, it's
# the package (='python test.py') that depends on your
# transcoderLib (='bar.txt')...
package = env.package('#Test', [])
env.Depends(package, tclib)

# Create an Alias for the packages, you can pass
# a list of all your packages too here...
bp = env.Alias('build_packages', package)

# Finally, set the package Alias() as default target if
# requested by the config parameter...
config = int(ARGUMENTS.get('config', 0))
if config == 1:
  env.Default(bp)

rawDescription: How do I specify scons alias dependencies?

description: Specify scons alias dependencies


code:
data = [{u'name': u'xxx', u'age': u'11'}, {u'name': u'myname', u'age': u'2'}, {u'name': u'cat', u'age': u'8'}]
for obj in data:
    mydata.details.add(MyDetails.objects.create(name=obj['name']), age=obj['age'])

rawDescription: Iteration over dict in list

description: Iteration over dict in list


code:
image = np.random.rand(10,10,3)

fig, axs = plt.subplots(1,2, figsize=(8,6))

axs[0].set_title('RGB image with gray cmap')
axs[0].imshow(image, interpolation='none', cmap=plt.cm.gray)

axs[1].set_title('Single layer image with gray cmap')
axs[1].imshow(image[:,:,0], interpolation='none', cmap=plt.cm.gray)

rawDescription: Python Colormap

description: Python Colormap


code:
import re

PAT = re.compile(r'\[(?P<time>[^\]]+)\] \[(?P<level>[^\]]+)\] \[(?P<client>[^\]]+)\] (?P<message>\S+)')
LEVELS = ['critical', 'error', 'warning', 'info', 'debug']

def level_number(line):
    match = PAT.match(line)
    if match:
        level = PAT.match(line).groupdict()['level']
        return LEVELS.index(level)
    return len(LEVELS)

with open('log.txt') as f:
    result = sorted(f, key=level_number)

rawDescription: Sorting by compare values in Python

description: Sorting by compare values in Python


code:
class order(object) : pass

a = order()
a.id=3
"{order.id}".format(order=a)
"{order.id} and then a {foo} hit the {baz} ".format(baz="fan",foo="rocket",order=a)

rawDescription: Python: Inserting variables into a string without order


code:
with open("filename.txt", "r") as f:
    alldata = f.readlines()
    for i, line in enumerate(alldata):
        alldataLine = datetime.strptime(line.split('|')[0], "%d/%m/%Y")
        if alldataLine >= start and alldataLine <= end :
            print("{0} --> {1}".format(line.split('|')[0], line.split('|')[1]))
        try:
            if line.split('|')[0] == alldata[i - 1].split('|')[0] and line.split('|')[0] != alldata[i + 1].split('|')[0]:
                print("one date")
        except IndexError:
            pass

rawDescription: Print message if dates in file are the same


code:
data1 = arange(1000)
data2 = arange(1000)+1000
dataTransformed3 = data - mean(data)
data4 = numpy.zeros(1000)
data4[::10] = 1 #simulate a photon counter where a 1 indicates a photon came in at time indexed by array.
# we could assume that the sample rate was 10 Hz for example
ps1 = np.abs(np.fft.fft(data))**2
ps2 = np.abs(np.fft.fft(data))**2
ps3 = np.abs(np.fft.fft(dataTransformed))**2

figure()
plot(ps1) #shows the peak at 0 Hz
figure()
plot(ps2) #shows the peak at 0 Hz
figure()
plot(ps3) #shows the peak at 1 Hz this is because we removed the mean value but since
#the function is a step function the next largest component is the 1 Hz cosine wave.
#notice the order of magnitude difference in the two plots.

rawDescription: power spectrum by numpy.fft.fft

description: Power spectrum by numpy.fft.fft


code:
from PIL import Image, ImageChops

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

im = Image.open("bord3.jpg")
im = trim(im)
im.show()

rawDescription: Trim whitespace using PIL

description: Trim whitespace using PIL


code:
for N in Ns:
    As_avg.append( np.mean( np.array( [tA for tN, tA in zip(Ns0, As0) if tN == N]  ) ) )

rawDescription: Python one liner for multiple averages of unsorted list


code:
@mock.patch('builtins.input', side_effect=['11', '13', 'Bob'])
def test_bad_params(self, input):
    ask()
    output = sys.stdout.getline().strip()
    assert output == "You are too young"
    # Check the output after "13" and "Bob" are entered as well!
    assert sys.stdout.getline().strip() == "Welcome!"

rawDescription: Mock user input()

description: Mock user input()


rawDescription: How to subtract the next value from the previous value in Python?

description: Subtract the next value from the previous value in Python


code:
from itertools import combinations

n = 365
r = 20

for indexes in combinations(range(n), r):
    base = [0]*n
    for i in indexes:
        base[i] = 1
    print(base)

rawDescription: Python - Generate binary list with itertools


code: {s.split('/')[4] : s for s in list1}

rawDescription: python parse string and turn into dictionary input

description: Python parse string and turn into dictionary input


code:
_recognizer = win32com.client.Dispatch("SAPI.SpSharedRecognizer")

to

_recognizer = win32com.client.Dispatch("SAPI.SpInprocRecognizer")

rawDescription: How to remove pyspeech windows speech recognition commands?

description: Remove pyspeech windows speech recognition commands


code:
data=np.array(((3,0,0,.24),(4,1,1,.41),(2,1,1,.63),(1,1,3,.38))) #imagine rows of a spreadsheet
#now do sortrows(data,[3,-4])
ix=np.lexsort((data[:,3][::-1],data[:,2]))
#this yields [0,2,1,3]

#note that lexsort sorts first from the last row, so sort keys are in reverse order

data[ix]

rawDescription: Sortrows with multiple sorting keys in numpy


code:
import pandas as pd
import os
from os import path
dfs = [pd.read_csv(path.join('data',x)) for x in os.listdir("data") if path.isfile(path.join("data",x))]
df = pd.concat(dfs)

rawDescription: How to read multiple files and merge them into a single pandas data frame?

description: Read multiple files and merge them into a single pandas data frame


code:
import requests
r = requests.get('http://site.com/source.json', params={'s': 'somevalue/or other here'})
json_result = r.json()

rawDescription: Proper way to extract JSON data from the web given an API


code:
from sublime_plugin import TextCommand

class ExampleCommand(TextCommand):
    def run(self, edit):
        # If the user attempted to run the command while having a non-activatable
        # view selected, such as the console input view, don't run anything.
        if self.view.id() != self.view.window().active_view().id():
            return
        # Otherwise continue running the command as normal...

rawDescription: Prevent Sublime Plugin TextCommand from running on console?


code:
import os
filepath = os.path.join(request.folder,'static','mydata.json')

rawDescription: How to read a JSON static file in web2py

description: Read a JSON static file in web2py


code:
# ...
user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        state = "You're successfully logged in!"
        info = dict(username=username, email=user.email, fullname=user.get_full_name())
        return render_to_response('home.html', info)

rawDescription: Retrieve SQL entries from Django login

description: Retrieve SQL entries from Django login


code:
match = None # best match word so far
dist = None # best match distance so far
for word in NWORDS: #iterate over all words in ref
    i = jf.levenshtein_distance(candidate, word) #compute distance for each word with user input
    if dist is None or i < dist: # or <= if lowest freq. first in NWORDS
        match, dist = word, i
return match #function returns word from ref list with lowest dist and highest frequency of occurrence

rawDescription: Levenshtein Distance looping in Python

description: Levenshtein Distance looping in Python


code:
#Merge the tables together - making sure we keep the index column
mg = df1.reset_index().merge(df2, left_on = 'id', right_on = 'id_x')

#Select only the rows that are within the start and end
mg = mg[(mg['index'] > mg['dt_f']) & (mg['index'] < mg['dt_l'])]

#Finally count by id_x
mg.groupby('id_x').count()

rawDescription: How to slice pandas DataFrame based on values from another Dataframe without using for-loop?

description: Slice pandas DataFrame based on values from another Dataframe without using for-loop


code:
import numpy as np
from scipy.ndimage.interpolation import map_coordinates

A = np.random.random((10,10))
new_dims = []
for original_length, new_length in zip(A.shape, (100,100)):
    new_dims.append(np.linspace(0, original_length-1, new_length))

coords = np.meshgrid(*new_dims, indexing='ij')
B = map_coordinates(A, coords)

rawDescription: numpy interpolation to increase array size

description: Numpy interpolation to increase array size


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, width=400,  height=400)

        self.label = tk.Label(self, text="last key pressed:  ", width=20)
        self.label.pack(fill="both", padx=100, pady=100)

        self.label.bind("<w>", self.on_wasd)
        self.label.bind("<a>", self.on_wasd)
        self.label.bind("<s>", self.on_wasd)
        self.label.bind("<d>", self.on_wasd)

        # give keyboard focus to the label by default, and whenever
        # the user clicks on it
        self.label.focus_set()
        self.label.bind("<1>", lambda event: self.label.focus_set())

    def on_wasd(self, event):
        self.label.configure(text="last key pressed: " + event.keysym);

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: WASD input in python

description: WASD input in python


rawDescription: Count number of times certain characters appears in list


code:
def set_mac(self, newmac):
    ''' Set the device's mac address. Device must be down for this to
        succeed. '''
    macbytes = [int(i, 16) for i in newmac.split(':')]
    ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes)
    fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq)

rawDescription: How to call SIOCSIFHWADDR ioctl to change MAC address in Python?

description: Call SIOCSIFHWADDR ioctl to change MAC address in Python


rawDescription: XYZ format to Grid format using Python 3.4


rawDescription: open(file) from anywhere

description: Open(file) from anywhere


code:
import fileinput
for line in fileinput.input(filename, inplace=True):
    print(line.replace(string_to_replace, new_string))

rawDescription: replacing line in a document with Python

description: Replacing line in a document with Python


rawDescription: how to get total hours and minutes for timedelta in python

description: Get total hours and minutes for timedelta in python


code:
import pandas as pd

df = pd.read_excel(excel_file_path, sheetname="sheet_name")

rawDescription: How to open an excel file with multiple sheets in pandas?

description: Open an excel file with multiple sheets in pandas


code:
from operator import attrgetter

m1 = Model(name='Lamborghini Miura', price=910)
m2 = Model(name='Ferrari 458 Italia', price=580)
lst = [m1, m2]

lst.sort(key=attrgetter('name', 'price'))

rawDescription: How do i sort by groups?

description: Sort by groups


code:
df
df.groupby(['ID', 'EVENT']).size().unstack().fillna(0)
_.reindex_axis(['GO', 'LEAVE', 'COME', 'FLY', 'GET'], axis=1)

rawDescription: How to compute item histogram for a column for each particular id group?

description: Compute item histogram for a column for each particular id group


code:
STRAIGHT_FLUSH = 9
...
TWO_PAIR = 2
ONE_PAIR = 1
HIGH_CARD = 0

hand_score('A7532')  # I omit suits here
# => (HIGH_CARD, 14,7,5,3,2)
hand_score('KK333')
# => (FULL_HOUSE, 3, 13)
hand_score('33444')
# => (FULL_HOUSE, 4, 3)
hand_score('AKQJ0')
# => (STRAIGHT, 14)

# Tuples can be easily compared:
(HIGH_CARD, 14,7,5,3,2) < (STRAIGHT, 14)
# => True

rawDescription: How can I find the highest poker hand from a 9 card hand between 4 players?

description: Find the highest poker hand from a 9 card hand between 4 players


code:
s = 'FOO_FILENAME.cnf.FILENAME'
re.match(r'FOO.*\.cnf\..*', s)

rawDescription: Check the file name using pattern or regular expression matching in python


code:
@app.route('/')
def index():
    return render_template('index.html')

rawDescription: bundling not working

description: Bundling not working


code:
class Abs(object):
    def run(self, var):
        raise NotImplementedError

    def _common_things(self,var):
        pass

class Sub1(Abs):
    def run(self, var):
        self._common_things(var)
        # etc

class Sub2(Abs):
    def run(self, var):
        self._common_things(var)
        # etc

rawDescription: partial function overload in python

description: Partial function overload in python


code:
for col_num, col_val in enumerate(a):
    if col_val.strip():
        xlSheet.Cells(output_row, col_num + 1).Value = col_val.strip()

rawDescription: Exporting tab-delimited text files with Python


code:
def parse(self, response):

    saveWebpage()

    if checkHasNextButton():

        yield Request(
            url=getNextUrl(),
            callback=self.parse
        )

rawDescription: Can scrapy step through a website by following "next" button


code:
class department(models.Model):
    name = Models.CharField(max_length=100)
    number = Models.IntegerField

rawDescription: Review my Django Model - Need lots of suggestions


code: valid_kwargs = get_valid_kwargs(cls.__init__, config_dict)

rawDescription: How can I reference the __init__ method of a derived class in Python from the base class?

description: Reference the __init__ method of a derived class in Python from the base class


code:
from django.conf.urls.defaults import url, patterns

urlpatterns = patterns('app.blog.views',
    url(r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts(), name='latest-posts'),
    #snip...
)

rawDescription: How to reverse django feed url?

description: Reverse django feed url


code:
import os
os.environ["DISPLAY"]=":99"

rawDescription: Running Xvfb from Python

description: Running Xvfb from Python


rawDescription: How to count all ForeignKey models with exact field values in Django?

description: Count all ForeignKey models with exact field values in Django


code:
import csv

lookup = set(l.strip().lower() for l in open(path_to_file3))
map(csv.writer(open(path_to_file2, 'w')).writerow,
    (row for row in csv.reader(open(path_to_file))
    if row[1].lower() in lookup))

rawDescription: How to remove rows from a csv file when compared to a list in a txt file using Python?

description: Remove rows from a csv file when compared to a list in a txt file using Python


code:
class Parent1(object):
    def __init__(self):
        super(Parent1, self).__init__()
        self.var1 = 1

class Parent2(object):
    def __init__(self):
        super(Parent2, self).__init__()
        self.var2 = 2

class Child(Parent1, Parent2):
    def __init__(self):
        super(Child, self).__init__()

rawDescription: calling init for multiple parent classes with super?

description: Calling init for multiple parent classes with super


rawDescription: Sample size from mean() on groupby object


code:
import subprocess
subprocess.call('nircmd.exe win close class "CabinetWClass"' , shell=True)

rawDescription: How to close all windows7 folders using python

description: Close all windows7 folders using python


code:
for id in range(1,101):
    sgw.add_bearer(dpid=256, bearer_id=id, \
    saddr_ingress="10.1.1.10", \
    sport_ingress=2152)

rawDescription: Shell script to increment a value inside a python script


rawDescription: Get a foreign key field when using values and annotate


code:
# assumes Python 2.x
from random import sample
from time import sleep

NUM_QUESTIONS = 4

questions = [
    'What does it eat?',
    'How big is it?',
    'What color is it?',
    'How many letters are in it?',
    'Does it have scales?',
    'Does it swim?',
    'How many legs does it have?'
    # etc
]

def get_yn(prompt):
    while True:
        val = raw_input(prompt).strip().lower()
        if val in {'y', 'yes'}:
            return True
        elif val in {'n', 'no'}:
            return False

def play():
    for q in random.sample(questions, NUM_QUESTIONS):
        print(q)
        sleep(2.)

def main():
    while True:
        play()
        if not get_yn("Play again? "):
            break

if __name__=="__main__":
    main()

rawDescription: Python asking game

description: Python asking game


rawDescription: Django: How to check if user has already voted on ManyToManyField?


code:
ssh_proc = Popen(['ssh', '-f', '-N', '-L', '10000:gateway:11000', 'localhost'], stdin=PIPE, stdout=PIPE)
stat = ssh_proc.poll()
while stat == None:
    stat = ssh_proc.poll()

rawDescription: python subprocess.Popen and ssh port forwarding in the background

description: Python subprocess.Popen and ssh port forwarding in the background


code: [a, b] = deal(b, a)

rawDescription: 'Safe' Assignment in MATLAB

description: 'Safe' Assignment in MATLAB


rawDescription: Python regex - Problems with start and end tags


code:
LIMIT = 20000

prima = []  #empty list

def Bsearch(lsta,low,high,search):   #Binary search function to search a prime number
    if low>high:
        return 0
    else:
        mid = int((low+high)/2)

        if search<lsta[mid]:
            Bsearch(lsta,low,mid-1,search)
        if search>lsta[mid]:
            Bsearch(lsta,mid+1,high,search)
        if search==lsta[mid]:
            return 1
    return 0

def primes(LIMIT):   #sieve to create prime numbers upto LIMIT
    dic = {}    #empty dictionary
    for i in range(2,LIMIT):
        dic[i] = 1
    for i in range(2,LIMIT):
        for j in range(i,LIMIT):
            if i*j>LIMIT:
                break
            dic[i*j] = 0
    for i in range(2,LIMIT):
        if dic[i]==1:
            prima.append(i)

primes(LIMIT)

result = []

rawDescription: Python Program No Output

description: Python Program No Output


rawDescription: Django Query - Retrieving associated foreign keys


code:
keys = ["a", "b", "c"]
agg_d = {k:[] for k in keys}
agg_d["a"].append(1)
agg_d

rawDescription: Python: List as a key in dictionary -

description: Python: List as a key in dictionary -


code:
img = None

while True:
    with open(image_path, 'rb') as img_bin:
        buff = StringIO.StringIO()
        buff.write(img_bin.read())
        buff.seek(0)
        temp_img = numpy.array(PIL.Image.open(buff), dtype=numpy.uint8)
        img = cv2.cvtColor(temp_img, cv2.COLOR_RGB2BGR)

    if img is not None:
        break

rawDescription: Detect / Avoid "Premature end of JPEG" in cv2 - python


code:
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import axes3d
import numpy as np

# These will be (200, 4), (200, 4), and (4)
freq_data = np.linspace(0,300,200)[:,None] * np.ones(4)[None,:]
amp_data = np.random.rand(200*4).reshape((200,4))
rad_data = np.linspace(0,2,4)

verts = []
for irad in range(len(rad_data)):
    # I'm adding a zero amplitude at the beginning and the end to get a nice
    # flat bottom on the polygons
    xs = np.concatenate([[freq_data[0,irad]], freq_data[:,irad], [freq_data[-1,irad]]])
    ys = np.concatenate([[0],amp_data[:,irad],[0]])
    verts.append(list(zip(xs, ys)))

poly = PolyCollection(verts, facecolors = ['r', 'g', 'c', 'y'])
poly.set_alpha(0.7)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# The zdir keyword makes it plot the "z" vertex dimension (radius)
# along the y axis. The zs keyword sets each polygon at the
# correct radius value.
ax.add_collection3d(poly, zs=rad_data, zdir='y')

ax.set_xlim3d(freq_data.min(), freq_data.max())
ax.set_xlabel('Frequency')
ax.set_ylim3d(rad_data.min(), rad_data.max())
ax.set_ylabel('Radius')
ax.set_zlim3d(amp_data.min(), amp_data.max())
ax.set_zlabel('Amplitude')

plt.show()

rawDescription: Plotting using PolyCollection in matplotlib


code:
def check_names(path):
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname)

rawDescription: Determine if string input could be a valid directory in Python


code:
d = {
 "Laptop": {
            "sony": 1,
            "apple": 2,
            "asus": 5,
          },
 "Camera": {
            "sony": 2,
            "sumsung": 1,
            "nikon" : 4,
           },
}
with open("my.json","w") as f:
    json.dump(d,f)

rawDescription: How to write a nested dictionary to json

description: Write a nested dictionary to json


code:
coefs = clf.coef_
if len(set(labels)) == 2:
    coefs = np.array([coefs[0, :], (1-coefs)[0, :]])
for cls, coef in zip(sorted(set(labels)), coefs):
    top_k = reversed(np.argsort(coef)[-k:])
    keywords = [mapping[idx] for idx in top_k]
    print('%s: %s' % (cls, keywords))

rawDescription: Sorting in sparse matrix (Python 2.*)

description: Sorting in sparse matrix (Python 2.*)


code: test = [[None] * 3 for _ in range(3)]

rawDescription: Making a list of lists with no refrences in python


code:
def store_exception(exception, line_number, some_string):
    data = {
        'timestamp'  : datetime.now(),
        'line_number': line_number,
        'message'    : exception,
        'string'     : some_string
    }

    d_order = ['timestamp', 'line_number', 'message', 'string']

    with open('some/path.csv', 'w') as csvfile:
        linewriter = csv.DictWriter(csvfile, d_order, delimiter='|',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)
        linewriter.writerow(data)

rawDescription: Scraping a table into a dict and writing each row to CSV


code: cur.mogrify("SELECT * FROM foo WHERE foo.bar = %s", ("foo 'bar' \"baz",))

rawDescription: Python: get escaped SQL string

description: Python: get escaped SQL string


code:
import cherrypy

class AppRoot:
    def index(self):
        return "App root's index"
    index.exposed = True

    controller1 = Controller1Class()
    # controller2 = Controller2Class(), etc.

class Controller1Class:

     def index(self):
         return "Controller 1's index"
     index.exposed = True

     def action1(self, id):
         return "You passed %s to controller1's action1" % id
     action1.exposed = True

     # def action2(self, id): etc...

# ... the rest of the config stuff ...

cherrypy.tree.mount(AppRoot(), '/')

# ... the rest of the startup stuff....

rawDescription: CodeIgniter-like Routes in CherryPy

description: CodeIgniter-like Routes in CherryPy


code:
for val1, val2 in zip(aa, b):
   print(val1, val2)

rawDescription: Min method with length method

description: Min method with length method


code:
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

ActionChains(driver).send_keys(Keys.CONTROL, "p").perform()  # or Keys.COMMAND on Mac

rawDescription: Python Selenium add_extensions close install splash screen


rawDescription: Python integer to hexadecimal extra characters


code:
from shutil import copytree
import logging

def _logpath(path, names):
    logging.info('Working in %s' % path)
    return []   # nothing will be ignored

copytree(source, destination, ignore=_logpath)

rawDescription: Python shutil.copytree() is there away to track the status of the copying


code:
# match keys
for key in d:
  if key in g:
     print ('{}: {}'.format(key, d[key]))

rawDescription: Compare two dictionaries for matches

description: Compare two dictionaries for matches


code:
from time import sleep
p = subprocess.Popen(command,
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT,
                     bufsize=-1)
output = ''
while p.poll() is None:
    output += p.stdout.readline()+'\n'  # <--- This is your magic
    sleep(0.025)
output += p.stdout.read() # <--- And this is just to get the leftover data
print('Command finished')

p.stdout.close()

rawDescription: Limited buffer in Popen

description: Limited buffer in Popen


code: dict((vert, i) for (i, cl) in enumerate(clusters) for vert in cl.vertices)

rawDescription: Construct a dictionary merging multiple lists


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
ret = WebDriverWait(self.driver, seconds).until(
    expected_conditions.presence_of_element_located((By.XPATH, path)))
ret.click()

rawDescription: How to have WebDriverWait return element instead of boolean in Python using Selenium

description: Have WebDriverWait return element instead of boolean in Python using Selenium


code:
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]

filtered_list = [item for item in mylist if item[1]=='CA']

rawDescription: Splitting a Python list based on criteria


code:
import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'Parent')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child1')
        button2 = wx.Button(panel, -1, 'Open Child2')

        sizer.Add(button, 0, wx.CENTER | wx.ALL, 5)
        sizer.Add(button2, 0, wx.CENTER | wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.onButton, button)
        self.Bind(wx.EVT_BUTTON, self.onButton2, button2)

    def onButton(self, e):
        try:
            self.ChildF.Show()
        except:
            self.ChildF = ChildFrame1()
            self.ChildF.Show()

        self.ChildF.SetFocus()

    def onButton2(self, e):
        try:
            self.ChildF2.Show()
        except:
            self.ChildF2 = ChildFrame2()
            self.ChildF2.Show()

        self.ChildF2.SetFocus()

class ChildFrame1(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child1')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child2')
        sizer.Add(button, 0, wx.CENTER | wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.GetParent().onButton2, button)

class ChildFrame2(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child2')

if __name__ == '__main__':
    app = wx.App()
    frame = Frame().Show()
    app.MainLoop()

rawDescription: wxPython childframes interaction

description: WxPython childframes interaction


code:
while True:
    line = tn.read_until("\n")  # Read one line
    print(line)
    if 'abcd' in line:  # last line, no more read
        break

rawDescription: How to print telnet response line by line?

description: Print telnet response line by line


code:
from flask import Flask

from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/echo')
def echo_socket(ws):
    while True:
        message = ws.receive()
        ws.send(message)

@app.route('/')
def hello():
    return 'Hello World!'

rawDescription: Streaming uploads using Python Requests

description: Streaming uploads using Python Requests


code:
import requests
response = requests.get('http://your.graphite.host.com/render?target=queue.prod.high.total_queues&format=json')
data = response.json()

rawDescription: how to get values from a graph in a dashboard in grafana V 2.0

description: Get values from a graph in a dashboard in grafana V 2.0


rawDescription: How can I create a regular expression in Python?

description: Create a regular expression in Python


code:
for row in rows:
    id = ''.join([getattr(row, col) for col in columns])

rawDescription: Python accessing cell with column name dynamically obtained


code:
from fdfgen import forge_fdf
from subprocess import Popen, PIPE

fields = [("field1", "foo"),
          ("field2", "bar")]
fdf = forge_fdf("", fields, [], [], [])
pdftk = ["pdftk", "template.pdf", "fill_form", "-",
          "output", "out.pdf", "flatten"]
proc = Popen(pdftk, stdin=PIPE)
output = proc.communicate(input=fdf)
if output[1]:
    raise IOError(output[1])

rawDescription: Best way to fill out and flattern form in PDF using python on Linux

description: Fill out and flattern form in PDF using python on Linux


code:
def main():
    docs=[]
    with open("ap_docs2.txt") as f:
        lines = f.read().split("<NEW DOCUMENT>")[1:]
        for x in lines:
            docs.append(x.strip().lower())
        numOfDocs=len(docs)
        print (docs)
        print("Number of Documents:",numOfDocs)

    search = input("Enter search words: ")
    for x in docs:
        if search in x:
            print('Found in document %d' % (docs.index(x) + 1))

main()

rawDescription: Printing in which list or dictionary the word is located in


code:
class CellRendererAutoComplete(Gtk.CellRendererText):

    """ Text entry cell which accepts a Gtk.EntryCompletion object """

    __gtype_name__ = 'CellRendererAutoComplete'

    def __init__(self, completion):
        self.completion = completion
        Gtk.CellRendererText.__init__(self)

    def do_start_editing(
               self, event, treeview, path, background_area, cell_area, flags):
        if not self.get_property('editable'):
            return
        entry = Gtk.Entry()
        entry.set_completion(self.completion)
        entry.connect('editing-done', self.editing_done, path)
        entry.show()
        entry.grab_focus()
        return entry

    def editing_done(self, entry, path):
        self.emit('edited', path, entry.get_text())

rawDescription: Gtk.Entry in Gtk.TreeView (CellRenderer)


code:
class SeparatedIterator:
    def __init__( self, iterator, filter ):
        self.it = iterator
        self.f = filter
        #The buffer contains pairs of (value,filterIsTrue)
        self.valueBuffer = []

    def generate():
        value = next( self.it )
        filtered = self.f( value )
        self.valueBuffer.append(( value, filtered ))

    def nextValue( category ):
        #search in stored values
        for i in range(len(self.valueBuffer)):
            value, filtered = self.valueBuffer[i]
            if filtered == category:
                del self.valueBuffer[i]
                return value

        #else, if none of the category found,
        #generate until one of the category is made
        self.generate()
        while self.valueBuffer[-1][1] != category:
            self.generate()

        #pop the value and return it
        value, _ = self.valueBuffer.pop()
        return value

rawDescription: How to divert data in an iterator into two others?

description: Divert data in an iterator into two others


code:
import json
jsonstr = json.dumps({"script": """\
#!/bin/bash
set -e

readonly PRIMARY=/tech01/primary
readonly SECONDARY=/tech02/secondary
readonly LOCATION=(machineA machineB)
readonly MAPPED_LOCATION=/bat/data/snapshot
HOSTNAME=$hostname

dir1=$(ssh -o "StrictHostKeyChecking no" david@${LOCATION[0]} ls -dt1 "$MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)
dir2=$(ssh -o "StrictHostKeyChecking no" david@${LOCATION[1]} ls -dt1 "$MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)

echo $dir1
echo $dir2

length1=$(ssh -o "StrictHostKeyChecking no" david@${LOCATION[0]} "ls '$dir1' | wc -l")
length2=$(ssh -o "StrictHostKeyChecking no" david@${LOCATION[1]} "ls '$dir2' | wc -l")

echo $length1
echo $length2

if [ "$dir1" = "$dir2" ] && [ "$length1" -gt 0 ] && [ "$length2" -gt 0 ]
then
    rm -rf $PRIMARY/*
    rm -rf $SECONDARY/*
    for el in $primary_partition
    do
        scp david@${LOCATION[0]}:$dir1/weekly_8880_"$el"_5.data $PRIMARY/. || scp david@${LOCATION[1]}:$dir2/weekly_8880_"$el"_5.data $PRIMARY/.
    done
fi"""})

rawDescription: How to make a big shell script in a single line shell script in json document?

description: Make a big shell script in a single line shell script in json document


code:
def single_insert_or_delete(s1,s2):
    s1,s2 = s1.lower(), s2.lower()
    count = 0
    if s1 == s2:
        return 0
    elif len(s1) == len(s2):
        return 2
    elif len(s1) - len(s2) == -1:
        if s1 == s2[:-1]:
            return 1
        else:
            for i in range(len(s2)):
                if s1 == s2[:i] + s2[i+1:]:
                    return 1
            else:
               return 2
    elif len(s1) - len(s2) == 1:
        if s1[:-1] == s2 or s1[1:] == s2:
            return 1
        else:
            for i in range(len(s1)):
                if s2 == s1[:i] + s1[i+1:]:
                    return 1
            else:
                 return 2

    else:
        return 2

rawDescription: How to find whether to single insert or delete from a string would make two strings equal?

description: Find whether to single insert or delete from a string would make two strings equal


code:
import datetime
d = datetime.datetime.now()
print (d.strftime("%d-%b-%Y %H:%M:%S"))

rawDescription: Python datetime to Matlab datenum

description: Python datetime to Matlab datenum


code:
import openpyxl

import csv

import time

print(time.ctime())

importedfile = openpyxl.load_workbook(filename = "C:/Users/User/Desktop/Giant Workbook.xlsm", read_only = True, keep_vba = False)

tabnames = importedfile.get_sheet_names()

substring = "Keyword"

for num in tabnames:

    if num.find(substring) > -1:
        sheet=importedfile.get_sheet_by_name(num)
        name = "C:/Users/User/Desktop/Test/" + num + ".csv"
        with open(name, 'w', newline='') as file:
            savefile = csv.writer(file)
            for i in sheet.rows:
                savefile.writerow([cell.value for cell in i])
print(time.ctime())

rawDescription: Python : Reading Large Excel Worksheets using Openpyxl


code:
def return_supplied_field(self, issue, field_name):
    """ Essentially I need to return issue.fields.field_name here """
    return getattr(issue.fields, field_name)

rawDescription: How do I find a supplied field in jira-python

description: Find a supplied field in jira-python


code:
def items(self):
    return list(item for _, _, item in self.heap)

rawDescription: Get list of elements currently in heap using heapq in Python ?


code:
import pandas as pd
import seaborn as sns
data=pd.DataFrame({'a':[1,2,3,4,5,6],'b':[0,1,1,0,1,1],'c':[0,0,0,1,1,1]})
for i in ['b','c']:
    img=sns.boxplot(data.a, groupby=data[i])
    fig = img.get_figure()
    fig.savefig(i)
    fig.clf()

rawDescription: How to save multiple plot in a loop?

description: Save multiple plot in a loop


code:
exclude = set().union(nodes_to_exclude1, nodes_to_exclude2)
return (item.GetId() for item in Graph.Nodes() if item.GetId() not in exclude)

rawDescription: Why does this line take so long to run?

description: Why does this line take so long to run


code:
class NULL_NAMESPACE:
    bytes = b''
uuid.uuid3(NULL_NAMESPACE, 'TTCCPSIVARSNFNVCRLPGTPEAICATYTGCIIIPGATCPGDYAN')
# returns: UUID('c6a0deb5-0c4f-3961-9d19-3f0fde0517c2')

rawDescription: Reproduce uuid from java code in python

description: Reproduce uuid from java code in python


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *

import random

# Initiate some data, giving some randomness using random.random().
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([i**2 + random.random() for i in x])

x_err = np.array([random.random() for i in x])
y_err = np.array([random.random() for i in x])

# Define a function (quadratic in our case) to fit the data with.
def quad_func(p, x):
     m, c = p
     return m*x**2 + c

# Create a model for fitting.
quad_model = Model(quad_func)

# Create a RealData object using our initiated data from above.
data = RealData(x, y, sx=x_err, sy=y_err)

# Set up ODR with the model and data.
odr = ODR(data, quad_model, beta0=[0., 1.])

# Run the regression.
out = odr.run()

# Use the in-built pprint method to give us results.
out.pprint()
'''Beta: [ 1.01781493  0.48498006]
Beta Std Error: [ 0.00390799  0.03660941]
Beta Covariance: [[ 0.00241322 -0.01420883]
 [-0.01420883  0.21177597]]
Residual Variance: 0.00632861634898189
Inverse Condition #: 0.4195196193536024
Reason(s) for Halting:
  Sum of squares convergence'''

x_fit = np.linspace(x[0], x[-1], 1000)
y_fit = quad_func(out.beta, x_fit)

plt.errorbar(x, y, xerr=x_err, yerr=y_err, linestyle='None', marker='x')
plt.plot(x_fit, y_fit)

plt.show()

rawDescription: Linear fitting in python with uncertainty in both x and y coordinates


code:
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

rawDescription: How do Django REST api serializers know what model they are associated with?


code:
class DemoDescriptor:
    def __get__(self, instance, type_):
        if instance is None:
            print('Accesing descriptor on the class')
            return self
        print('Accessing descrtor on the instance')
        return 'Descriptor value for instance {!r}'.format(instance)

class DemoClass(object):
    foo = DemoDescriptor()

DemoClass.foo  # on the class
DemoClass.__dict__['foo']  # bypassing the descriptor protocol
DemoClass().foo  # on the instance

rawDescription: why do you need "if instance is None" in __get__ of a descriptor class?

description: Why do you need "if instance is None" in __get__ of a descriptor class


code:
def family_lineage(familytree, lineage):
    trees = [familytree]
    while trees:
        tree = trees.pop()
        trees.extend(t for t in tree.values() if t)
        for name in lineage:
            if name not in tree:
                break
            tree = tree[name]
        else:
            return True
    return False

rawDescription: Python iterating through nested dictionaries


code:
import struct
Arg1 = struct.pack('B', 255)

rawDescription: python single byte function

description: Python single byte function


code:
vector = numpy.array([x[0] for x in vector])
numpy.diff(vector)

rawDescription: derivative with numpy.diff problems

description: Derivative with numpy.diff problems


code:
def createtable(self):
     rows = self.tableName.rowCount()
     columns = self.tableName.columnCount()
     for i in range(rows):
         for j in range(columns):
             item = self.cell("text")
             # execute the line below to every item you need locked
             item.setFlags(QtCore.Qt.ItemIsEnabled)
             self.ui.tableName.setItem(i, j, item)

rawDescription: how to make a cell in a QTableWidget read only?

description: Make a cell in a QTableWidget read only


code: plt.plot(freqs, 10*np.log10(power))

rawDescription: matplotlib power spectral density (PSD) value discrepancy

description: Matplotlib power spectral density (PSD) value discrepancy


code:
def split_file(filename, tofile, othertofile, proportion):
    content = open(filename).readlines()
    number_of_lines = len(content)

    # Split content.
    first_portion = "\n".join(content[:number_of_lines * proportion])
    second_portion = "\n".join(content[number_of_lines * proportion:])

    # Write to files.
    open(tofile, "w").write(first_portion)
    open(othertofile, "w").write(second_portion)

rawDescription: Take a certain amount of data from a txt file


code:
import json
import re

def parse(v):
    # Remove newlines and replace "=" with ":"
    v1 =  v.replace('=', ':').replace("\n", "")
    # Enclose strings in double quotes
    v2 = re.sub(r'(\d*[a-zA-Z][a-zA-Z0-9]*)', r'"\g<1>"', v1)
    # If you want booleans
    v3 = re.sub(r'"(true|false)"', r'\g<1>', v2)
    # Create lists
    return json.loads(re.sub(r"{([^:]+)}", r'[\g<1>]', v3))

rawDescription: Convert pseudo Json string into a Python object


code:
totalbytes = 0
for pkt, (sec, usec, wirelen) in RawPcapReader(pcapfile):
    totalbytes += wirelen

rawDescription: Whole packet length Scapy

description: Whole packet length Scapy


code:
import os

strpath = '.'
strFileNameA = 'file1'
strFileNameB = 'file2'

testfile1 = open(os.path.join(strpath, '%s.csv'%(strFileNameA)), 'r')
testfile2 = open(os.path.join(strpath, '%s.csv'%(strFileNameB)), 'r')

testlist1 = testfile1.readlines()
testlist1 = [eachLine.rstrip("\n").split(",") for eachLine in testlist1]
testlist2 = testfile2.readlines()
testlist2 = [eachLine.rstrip("\n").split(",") for eachLine in testlist2]

#step 1
testlist1 = sorted(testlist1,key=lambda x: x[0])
testlist2 = sorted(testlist2,key=lambda x: x[0])

#step 2
def look_for_match(i,list1,j,list2):
    if i == len(list1):
        return i,j+1, ([],list2[j])
    elif j == len(list2):
        return i+1,j,(list1[i],[])
    elif list1[i][0] == list2[j][0]:
        return i+1, j+1,(list1[i],list2[j])
    elif list1[i][0] < list2[j][0]:
        return i+1,j,(list1[i],[])
    else:
        return i,j+1, ([],list2[j])

matched_rows = []
i=0
j=0
while i<len(testlist1) or j<len(testlist2):
    i, j, matched_row = look_for_match(i,testlist1,j,testlist2)
    if matched_row[0] == [] or matched_row[1] == []:
        matched_rows.append(matched_row)

for row_file_1, row_file_2 in matched_rows:
    print(row_file_1, row_file_2)

for row_file_1, row_file_2 in matched_rows:
    print(row_file_1, row_file_2)

rawDescription: Use Python to sort columns and order rows from csv files


code:
n1,n2 = map(int,raw_input().split())
n1
n2
n1,n2 = [int(x) for x in raw_input().split()]
n1
n2

rawDescription: How can I end input by enter a Blank Character in PYTHON ( raw_input() )?

description: End input by enter a Blank Character in PYTHON ( raw_input() )


code:
for control in self.controls():
  self.connect(control, SIGNAL('clicked()'), lambda control=control:
    self.button(control.objectName()))

rawDescription: Lambda function and variable scope

description: Lambda function and variable scope


code:
import sys
sys.path[0:0] = [
     '/some/thing1.egg',
     # and other things
     ]

rawDescription: Buildout and Virtualenv

description: Buildout and Virtualenv


code:
from django.contrib.sites.models import Site
obj = MyModel.objects.get(id=3)
obj.get_absolute_url()
Site.objects.get_current().domain
'http://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())

rawDescription: How does Django build URLs that depend on a site?


code:
EdgeFaces = {} # mapping from edge to adjacent faces
for ThisFace in TheMesh.faces :
    for ThisEdge in ThisFace.edge_keys :
        if not ThisEdge in EdgeFaces :
            EdgeFaces[ThisEdge] = []
        #end if
        EdgeFaces[ThisEdge].append(ThisFace.edge_keys)
    #end for
#end for

rawDescription: Detecting border of plane in Blender Python API


code:
import platform
import sys

if platform.system() != 'Linux':
    sys.stderr('Linux required\n')
    sys.exit(1)

rawDescription: Python limit usage to Linux only

description: Python limit usage to Linux only


rawDescription: Odd exponent on plotting narrow range of data


code: default_filters = sget('default_filters', 'h')

rawDescription: How to disable all filtering in a mako template with captures and defs?

description: Disable all filtering in a mako template with captures and defs


code:
response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

for listType in ('employeeList', 'contractWorkerList'):

    json_ver = jsonVersionOfAllData[listType]['list']
    directReports = len(json_ver)

    if directReports != 0:
        for i in range(0, directReports, 1):
            workerInfo = {}
            for wi_name, json_name in (('empLname', 'lastName'), ('empFname', 'firstName')):
                workerInfo[wi_name] = json_ver[i][json_name]
            listOfAllReports.append(workerInfo)

rawDescription: How to Reduce Code Duplication of If-Else Statements in Python


code: float_color = color / 255.0

rawDescription: convert rgba color codes 255,255,255,255 to kivy color codes in 1,1,1,1

description: Convert rgba color codes 255,255,255,255 to kivy color codes in 1,1,1,1


code:
import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = False
import matplotlib.pyplot as plt
import pandas

df = pandas.DataFrame(np.random.uniform(size=37)*100, columns=['A'])
threshold = 75
fig, ax = plt.subplots(figsize=(8,3))

good = df['A'][df['A'] >= threshold]
bad = df['A'][df['A'] < threshold]

ax.bar(left=good.index, height=good, align='center', color='ForestGreen', zorder=5)
ax.bar(left=bad.index, height=bad, align='center', color='Firebrick', zorder=5)

ax.axhline(y=threshold, linewidth=2, color='ForestGreen', zorder=0)

ax.set_xticks(df.index)
ax.set_xlim(left=df.index[0]-0.75, right=df.index[-1]+0.75)

def annotateBars(row, ax=ax):
    if row['A'] < 20:
        color = 'black'
        vertalign = 'bottom'
        vertpad = 2
    else:
        color = 'white'
        vertalign = 'top'
        vertpad = -2

    ax.text(row.name, row['A'] + vertpad, "{:.1f}%".format(row['A']),
            zorder=10, rotation=90, color=color,
            horizontalalignment='center',
            verticalalignment=vertalign,
            fontsize=8, weight='heavy')

junk = df.apply(annotateBars, ax=ax, axis=1)

rawDescription: matplotlib advanced bar plot

description: Matplotlib advanced bar plot


code:
for line in sys.stdin:
  if line.lower().strip() == 'bye':
    break
  sys.stdout.write(do_something(line))
  sys.stdout.flush()

rawDescription: Piping in Python 2.6 to a file with while loop


code:
def cans(layers):
    if layers == 0:
       return 0
    else:
       return layers**2 + cans(layers-1)

rawDescription: Confused about recursion and how to make return print


code:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

rawDescription: Function - Python Prgramming

description: Function - Python Prgramming


code:
nbTrain = []

if classifier.positiv > classifier.negativ:
    word = (input_text , 'pos')
else:
    word = (input_text , 'neg')

nbTrain.append(word)

rawDescription: How to create a list of tuples Python?

description: Create a list of tuples Python


code:
p1 = Point(0, L2.subs(x, 0))
p2 = Point(1, L2.subs(x, 1))
Line(p1, p2)

rawDescription: Convert equation in string format to Line(geometry) object


code:
import csv
result = [row for row in csv.reader(x.splitlines(), delimiter=';')]
import pprint
pprint.pprint(result)

rawDescription: How to read lines from a CSV variable into a multidimensional array in python?

description: Read lines from a CSV variable into a multidimensional array in python


code:
import atexit

class StatusWidgetWorker(QObject):

    def __init__(self):
        super().__init__()
        # code here
        atexit.register(self.cleanup)

    def cleanup(self):
        print("Doing some long cleanup")
        sleep(2)
        self.bla = "Done !"
        print(self.bla)

rawDescription: How to call a function when a QObject is about to be destroyed?

description: Call a function when a QObject is about to be destroyed


code:
import itertools
["".join(item) for item in itertools.product("10", repeat=5)]

rawDescription: Variations with repetition

description: Variations with repetition


code:
def poly(a_list, x):
    ans = 0
    for n,a in enumerate(a_list):
        ans += a*x**n
    return ans

rawDescription: Calculating polynomials

description: Calculating polynomials


code:
from pylab import *
from scipy.integrate import *

def RHS(t, x):
    return -x

min_t = 0.0
max_t = 10.0
num_t = 1e2
grid_t = linspace(min_t, max_t, num_t)
grid_dt = (max_t - min_t)/(num_t - 1)

y = zeros(num_t, dtype=complex)
y[0] = complex(1.0, 0.0)

solver = complex_ode(RHS)
solver.set_initial_value(y[0], grid_t[0]).set_integrator('dopri5')

for idx in range(1, int(num_t)):
    solver.integrate(solver.t + grid_dt)
    y[idx] = solver.y[0]

rawDescription: Differential equations in Python: Single time step


code:
def search_userinfo(**kwargs):
  qry = UserInfo.query(*(getattr(UserInfo, k)==v for (k,v) in kwargs.items()))
  return qry

rawDescription: Using keywords argument to query in GAE ndb


code:
import numpy as np
import matplotlib.pyplot as plt
from sympy.solvers import solve
from sympy import Symbol

def f1(x):
    return 4.0*x-2.0
def f2(x):
    return 0.5*x+2.0
def f3(x):
    return -0.3*x+7.0

x = Symbol('x')
x1, =  solve(f1(x)-f2(x))
x2, =  solve(f1(x)-f3(x))
x3, =  solve(f2(x)-f3(x))

y1 = f1(x1)
y2 = f1(x2)
y3 = f2(x3)

plt.plot(x1,f1(x1),'go',markersize=10)
plt.plot(x2,f1(x2),'go',markersize=10)
plt.plot(x3,f2(x3),'go',markersize=10)

plt.fill([x1,x2,x3,x1],[y1,y2,y3,y1],'red',alpha=0.5)

xr = np.linspace(0.5,7.5,100)
y1r = f1(xr)
y2r = f2(xr)
y3r = f3(xr)

plt.plot(xr,y1r,'k--')
plt.plot(xr,y2r,'k--')
plt.plot(xr,y3r,'k--')

plt.xlim(0.5,7)
plt.ylim(2,8)

plt.show()

rawDescription: Python Matplotlib: Drawing linear inequality functions


code:
from tagging.models import TagManager, Tag
import tagging

class MyTagManager(TagManager):
    def update_tags(self, obj, tag_names):
        # My actions
        return super(MyTagManager, self).update_tags(obj, tag_names)
    def add_tag(self, obj, tag_name):
        # My actions
        return super(MyTagManager, self).add_tag(obj, tag_name)

class MyTag(Tag):
    objects = MyTagManager()
    class Meta:
        proxy = True

tagging.models.Tag = MyTag
tagging.fields.Tag = MyTag

rawDescription: Django - Extending an app's model to override its manager


rawDescription: How can I use a regex subpattern with a named group in Python?

description: Use a regex subpattern with a named group in Python


code:
def index(request):
    lists = List.objects.filter(canView__user__id=request.user.id)
    return render(request, 'index.html', {'lists': lists})

rawDescription: Displaying all Many to Many relationships in one template


rawDescription: Forcing a sqlalchemy ORM get() outside identity map


code:
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.cross_validation import train_test_split

X = np.linspace(0,100,101)
y = np.array([(100*np.random.rand(1)+num) for num in (5*x+10)])

X_train, X_test, y_train, y_test = train_test_split(X, y)

svr = SVR(kernel='linear')
lm = LinearRegression()
svr.fit(X_train.reshape(-1,1),y_train.flatten())
lm.fit(X_train.reshape(-1,1), y_train.flatten())

pred_SVR = svr.predict(X_test.reshape(-1,1))
pred_lm = lm.predict(X_test.reshape(-1,1))

plt.plot(X,y, label='True data')
plt.plot(X_test[::2], pred_SVR[::2], 'co', label='SVR')
plt.plot(X_test[1::2], pred_lm[1::2], 'mo', label='Linear Reg')
plt.legend(loc='upper left');

rawDescription: Modeling-Support Vector Regression (SVR) vs. Linear Regression


code:
import zipfile
import os
import sys

def zipfolder(foldername, target_dir):
    zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED)
    rootlen = len(target_dir) + 1
    for base, dirs, files in os.walk(target_dir):
        for file in files:
            fn = os.path.join(base, file)
            zipobj.write(fn, fn[rootlen:])

zipfolder('thenameofthezipfile', 'thedirectorytobezipped') #insert your variables here
sys.exit()

rawDescription: ZIP folder with subfolder in python

description: ZIP folder with subfolder in python


rawDescription: ObjectID generated by server on pymongo

description: ObjectID generated by server on pymongo


code:
# ... skipped ...

if __name__ == "__main__":
    for i in range(5):
        unittest.main(exit=False)

rawDescription: running entire unit test in a loop

description: Running entire unit test in a loop


code: bank['bob'][1] = 10  # 'bob' is the key

rawDescription: Changing an value in a dictionary python 2.7


rawDescription: How to get the default page?

description: Get the default page


code: tags: ['linux', 'apached', 'wsgi']

rawDescription: Storing/working with tags in mongodb for a document management system


code:
myInteger += 1
myString += "more text"

rawDescription: Shorthand adding/appending in Python

description: Shorthand adding/appending in Python


code:
import random

def tryAgain(yesorno):
    yesOrNo = input(yesorno)
    return yesOrNo.lower() == 'y'

def playOneGame(low, high):
    secret = random.randint(low,high)
    response = int(input("I'm thinking of a number between 1 and 100: "))
    tries = 1
    while response != secret:
        if response < secret:
            print("Guess higher")
        else:
            print("guess lower")
        response = int(input("I'm thinking of a number between 1 and 100: "))
        tries += 1
    print("That took you ",tries,"tries!")
    return tries

def main():
    while True:
        playOneGame(1,100)
        if not tryAgain("Try again? y or n "):
            break
    print("Game over!")

main()

rawDescription: How do I end this program without repeating a string?

description: End this program without repeating a string


code:
#Create custom form with specific queryset:
class CustomBarModelForm(forms.ModelForm):
    class Meta:
        model = Bar
    def __init__(self, *args, **kwargs):
        super(CustomBarModelForm, self).__init__(*args, **kwargs)
        self.fields['foo'].queryset = Foo.objects.filter(title__isnull=False)# or something else

# Use it in your modelAdmin
class BarAdmin(admin.ModelAdmin):
    form = CustomBarModelForm

rawDescription: filtering dropdown values in django admin

description: Filtering dropdown values in django admin


code:
import json

# saving
with open("totals.txt", 'w') as f27:
    json.dump(totaldict, f27)

# loading
with open("totals.txt", 'r') as f27:
    totaldict = json.load(f27)

rawDescription: How to add to a dictionary through my text file

description: Add to a dictionary through my text file


code:
class complex_subset(object):
    def __init__(self, norm_below):
        self.norm_below=norm_below
    def __contains__(self, item):
        return abs(complex(item)) < self.norm_below

complex_below_norm_1=complex_subset(norm_below=1)
0 in complex_below_norm_1
3 in complex_below_norm_1
0.5+0.5j in complex_below_norm_1

rawDescription: Is there a way in Python to utilize infinite subsets of R or C?


code:
class Person(models.Model):
    z_pk = models.AutoField(primary_key=True)
    z_name = models.TextField()

class Spouserel(models.Model):
    z_person = models.ForeignKey(Person, db_column='z_pk', primary_key=True)
    z_spouserel = models.IntegerField()

rawDescription: Django: model for unusual table relationship in a legacy DB


code:
na_free = df.dropna()
only_na = df[~df.index.isin(na_free.index)]

rawDescription: Pandas dropna - store dropped rows

description: Pandas dropna - store dropped rows


code:
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')

name = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric])
email = models.EmailField(max_length=50, unique=True, validators=[alphanumeric])

rawDescription: How can I make a Django form field contain only alphanumeric characters

description: Make a Django form field contain only alphanumeric characters


code:
with open("in.txt") as f:
    cols = [float(row.split()[2]) for row in f.readlines()]
    maxVal = max(cols)
    #print maxVal

data = list()
f3 = open('out.txt', 'w')
with open('in.txt') as f2:
    for line in f2:
        items = line.split() # parse the columns
        tClass, feats, values = items[:3] # parse the columns
        #print items
        normalizedData = float(values)/float(maxVal)
        #print normalizedData

        f3.write("\t".join([tClass +"\t"+ feats, str(normalizedData), "\n"]))
f3.close()

rawDescription: dividing elements in list to normalize data in Python

description: Dividing elements in list to normalize data in Python


rawDescription: How to Fetch function using string?

description: Fetch function using string


code:
def OfsToHour(targetHour = 7):
    import datetime
    t = datetime.datetime.utcnow() #or your favored UTC call
    return (((targetHour - t.hour) + 12) % 24) - 12

rawDescription: I need create a variable that is the GMT offset where it's 7:XX AM right now


code:
batch = neo4j.WriteBatch(graph_db)
a = batch.create(node(name='Alice'))
batch.add_index_node("people","name","alice",a)
batch.submit()

rawDescription: Can indexes be created in batches using py2neo


code:
def main():
    with open('output.txt', 'w') as f:
        for i in range(len(sections)):
            date_row4 = sections[i].split("\n")[4].split(" ")
            date_row5 = sections[i].split("\n")[5].split(" ")

            print(date_row4)
            print(date_row5)

            month_row4 = date_row4[1]
            year_row4 = date_row4[3]

            month_row5 = date_row5[1]
            year_row5 = date_row5[3]

            if len(month_row4): # avoid to write empty lines in the output
                f.write("{} {}{}".format(month_row4,year_row4,'\n'))
            if len(month_row4):
                f.write("{} {}{}".format(month_row5,year_row5,'\n'))
main()

rawDescription: Creating list with dates

description: Creating list with dates


code:
shape = 1000
df_t = pd.DataFrame({'pC': np.random.rand(shape),
                     'Truth':np.random.choice([0,1],size=shape)})
df_t['factor'] = pd.cut(df_t.pC,5)
df_p = (df_t[['factor','Truth']]
        .pivot_table(columns='Truth',index='factor',aggfunc=len,fill_value=0)
        .reset_index())
df_p[['factor',0,1]].plot(kind='bar',stacked=True,x='factor');

rawDescription: Python Stacked Histogram

description: Python Stacked Histogram


code:
from wsgiref.simple_server import make_server

from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound

def hello1(request):
    raise HTTPFound(request.route_url('hello2'))

def hello2(request):
    return {'boom': 'shaka'}

def redirect_logger(handler, registry):
    def redirect_handler(request):
        response = handler(request)
        if response.status_int == 302:
            print("OMGZ ITS NOT GOING WHERE YOU THINK")

        return response
    return redirect_handler

def main():
    config = Configurator()

    config.add_route('hello1', '/', view=hello1)
    config.add_route('hello2', '/hi', view=hello2, renderer='json')
    config.add_tween('__main__.redirect_logger')

    app = config.make_wsgi_app()
    return app

if __name__ == '__main__':
    app = main()
    server = make_server('0.0.0.0', 8080, app)
    print("http://0.0.0.0:8080")
    server.serve_forever()

rawDescription: How to log redirects in Pyramid?

description: Log redirects in Pyramid


code:
import turtle

turtle.penup()
for i in range(1, 500, 50):
    turtle.right(90)    # Face South
    turtle.forward(i)   # Move one radius
    turtle.right(270)   # Back to start heading
    turtle.pendown()    # Put the pen back down
    turtle.circle(i)    # Draw a circle
    turtle.penup()      # Pen up while we go home
    turtle.home()       # Head back to the start pos

rawDescription: Python Turtle: Draw concentric circles using turtle's circle() method


code: my_num& 0xFFFFFFFF

rawDescription: Python Truncating to 32-bit

description: Python Truncating to 32-bit


code:
import re
matched = re.search(r'\d.*', "Standard delivery in 5 business days")
matched
matched.group()

rawDescription: how to extract portion of string in RegEx

description: Extract portion of string in RegEx


code:
a = [1,1,2,1,2,2,3]
d = dict(zip(sorted(set(a)), sorted(set(a), reverse=True)))
[d[x] for x in a]

rawDescription: Swapping maximum and minimum values in a list


code:
a = 'asdfghjklmn'
a[:len(a)//3*3]
len(a)
len(a[:len(a)//3*3])

rawDescription: finding substring

description: Finding substring


code:
def _file_thread_loop(self):
    while True:
    #... read files...
        for file in files:
            response = HtmlResponse(url=file['url'], body=file['body'])
            req = Request(
                url='http://example.com',
                meta={'items': self.parse_items(response)},
                callback=self.yield_item
            )
            self.crawler.engine.crawl(req, spider=self)

        time.sleep(10)

def yield_item(self, response):
    for item in response.meta['items']:
        yield item

rawDescription: Scrapy - generating items outside of parse callback


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

x = np.arange(10)
y = np.arange(10)

alphas = np.linspace(0.1, 1, 10)
rgba_colors = np.zeros((10,4))
# for red the first column needs to be one
rgba_colors[:,0] = 1.0
# the fourth column needs to be your alphas
rgba_colors[:, 3] = alphas

plt.scatter(x, y, color=rgba_colors)
plt.show()

rawDescription: Individual alpha values in scatter plot / Matplotlib


rawDescription: Number format with commas and one decimal


code:
from copy import deepcopy

pastmoves.append(deepcopy(gamelist))

rawDescription: Python: append copy of nested list to list


code:
def float32_wav_file(sample_array, sample_rate):
  byte_count = (len(sample_array)) * 4  # 32-bit floats
  wav_file = ""
  # write the header
  wav_file += struct.pack('<ccccIccccccccIHHIIHH',
    'R', 'I', 'F', 'F',
    byte_count + 0x2c - 8,  # header size
    'W', 'A', 'V', 'E', 'f', 'm', 't', ' ',
    0x10,  # size of 'fmt ' header
    3,  # format 3 = floating-point PCM
    1,  # channels
    sample_rate,  # samples / second
    sample_rate * 4,  # bytes / second
    4,  # block alignment
    32)  # bits / sample
  wav_file += struct.pack('<ccccI',
    'd', 'a', 't', 'a', byte_count)
  for sample in sample_array:
    wav_file += struct.pack("<f", sample)
  return wav_file

rawDescription: Create 32bit float wav file in python?

description: Create 32bit float wav file in python


code:
class Field(Leaf):
    """
    Field object.

    Field examples: User.name, User.age ..
    """

    def __init__(self, is_primarykey=False, is_foreignkey=False):
        self.is_primarykey = is_primarykey
        self.is_foreignkey = is_foreignkey

    # describe model's attr
    def describe(self, name, model):
        self.name = name
        self.model = model
        # fullname e.g. : User.id 's fullname is "user.id"
        self.fullname = self.model.table_name + "." + self.name
        # describe the attribute, reload its access control of writing, reading
        setattr(model, name, FieldDescriptor(self))

rawDescription: what does describe do in python?

description: What does describe do in python


code:
l=[]

for idx, row in df['Vals'].iteritems():
    temp_df = pd.DataFrame(row['Measures'][0]['MeasureValues'])
    temp_df['TradeId'] =  row['TradeId']
    l.append(temp_df)

pd.concat(l,axis=0)

rawDescription: Dictionary in Pandas DataFrame, how to split the columns


code:
from sqlachemy import func
expr = func.substring(Program.session, 8)  # for postgresql
programs = (
    session.query(Program, expr.label("season"))
    .order_by(expr.desc())
    .all()
)

rawDescription: Performing Sort on half Column Sqlalchemy


code:
with open("c:/achip.txt", "rU") as f:
  columns = f.readline().strip().split()
  sums = [0.0] * len(columns)
  row_counts = [0] * len(columns)

  for line in f:
    line = line.strip()
    if not line:
      continue

    for col, v in enumerate(line.split()):
      if v != "NA":
        sums[col] += int(v)
        row_counts[col] += 1

with open("c:/chipdone.txt", "w") as out:
  for name, sum, rows in zip(columns, sums, row_counts):
    print >>out, name,
    if rows == 0:
      print >>out, "NA"
    else:
      print >>out, sum / rows

rawDescription: Help with an if else loop in python

description: Help with an if else loop in python


code:
logger.debug("Message %s", 123)  # Works
logger.debug("Message {}", 123)  # Does not work.

rawDescription: Inserting string variables into print in python


code: sum(len(val) for val in dictionary.itervalues())

rawDescription: count of the multiple values in a dictionary python

description: Count of the multiple values in a dictionary python


code:
import wx
import wx.lib.scrolledpanel as scrolled

class MyPanel(scrolled.ScrolledPanel):
    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent, style=wx.VSCROLL)
        self.SetBackgroundColour('#f8f8f8')
        self.sizer = wx.WrapSizer()
        self.SetupScrolling(scroll_x = False)
        self.parent = parent

        self.addButton(self.sizer , 10)
        self.SetSizer(self.sizer )
        self.Bind(wx.EVT_SIZE, self.onSize)

    def onSize(self, evt):
        size = self.GetSize()
        vsize = self.GetVirtualSize()
        self.SetVirtualSize((size[0], vsize[1]))

        evt.Skip()

    def addButton(self, sizer, num):
        for i in range(1, num):
            btn =wx.Button( self, wx.ID_ANY, "btn"+str(i), wx.DefaultPosition, wx.DefaultSize, 0 )
            sizer.Add(btn, 0, wx.ALL, 10)

if __name__=='__main__':
    app = wx.App(redirect=False)
    frame = wx.Frame(None)
    MyPanel(frame)
    frame.Show()
    app.MainLoop()

rawDescription: ScrolledPanel with vertical scrollbar only and WrapSizer


code:
a = np.random.randint(low=1, high=4, size=10)   # example data
a
b = np.arange(10)
c = np.column_stack((a, b))
c[a == 3]

rawDescription: Join two python arrays via index

description: Join two python arrays via index


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

data = np.genfromtxt('eye_.txt',delimiter=',')

x=data[:,0]
y=data[:,1]
z=data[:,2]

## Equivalently, we could do that all in one line with:
# x,y,z = np.genfromtxt('eye_.txt', delimiter=',', usecols=(0,1,2))

x=np.unique(x)
y=np.unique(y)
X,Y = np.meshgrid(x,y)

Z=z.reshape(len(y),len(x))

plt.pcolormesh(X,Y,Z)

plt.show()

rawDescription: Plotting a Heat Map X,Y,Intensity From Three Lists


code:
import mock

class A(object):
    def meth(self, a):
        return a
a = A()
ma = mock.Mock(wraps=a)

rawDescription: Using Python mock to spy on calls to an existing object


code:
class ForceTLSV1Adapter(adapters.HTTPAdapter):
    """Require TLSv1 for the connection"""
    def init_poolmanager(self, connections, maxsize, block=False):
        # This method gets called when there's no proxy.
        self.poolmanager = poolmanager.PoolManager(
            num_pools=connections,
            maxsize=maxsize,
            block=block,
            ssl_version=ssl.PROTOCOL_TLSv1,
        )

    def proxy_manager_for(self, proxy, **proxy_kwargs):
        # This method is called when there is a proxy.
        proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1
        return super(ForceTLSV1Adapter, self).proxy_manager_for(proxy, **proxy_kwargs)

rawDescription: SSL and TLS in Python requests

description: SSL and TLS in Python requests


code:
def exact_change( target_amount, L ):
    if target_amount > sum(L):
        return False
    elif target_amount == 0:
        return True
    elif target_amount < 0:
        return False
    elif target_amount > 0 and not L:
        return False
    else:
        loseit = exact_change(target_amount, L[1:])
        # reduce target amount since we use current coin
        useit = exact_change(target_amount - L[0], L[1:])
        return loseit or useit

rawDescription: python function exact change won't work

description: Python function exact change won't work


code:
move_names = ['scissor', 'rock', 'paper']
winner_strings = ["It's a draw.", "You win.", "You lose."]

def get_result_string(player_move, computer_move):
    winner = player_move - computer_move % 3
    return 'You played {}. The computer played {}. {}'.format(
            move_names[player_move],
            move_names[computer_move],
            winner_strings[winner])

rawDescription: How do I make my code less redundant?

description: Make my code less redundant


code:
import string

s = "the qUiCk BROWN fox:: jumped. over , the lazy    dog."
s_correct = "The quick brown fox: jumped. Over, the lazy dog."

def chars_from_lines(lines):
    for line in lines:
        for ch in line:
            yield ch

start, in_sentence, saw_space = range(3)

punct = set(string.punctuation)
punct_non_repeat = punct - set(['.', '-'])
end_sentence_chars = set(['.', '!', '?'])

def edit_sentences(seq):
    state = start
    ch_punct_last = None

    for ch in seq:
        ch = ch.lower()

        if ch == ch_punct_last:
            # Don't pass repeated punctuation.
            continue
        elif ch in punct_non_repeat:
            ch_punct_last = ch
        else:
            # Not punctuation to worry about, so forget the last.
            ch_punct_last = None

        if state == start and ch.isspace():
            continue
        elif state == start:
            state = in_sentence
            yield ch.upper()

        elif state == in_sentence and ch in end_sentence_chars:
            state = start
            yield ch
            yield ' '
        elif state == in_sentence and not ch.isspace():
            yield ch
        elif state == in_sentence and ch.isspace():
            state = saw_space
            continue

        elif state == saw_space and ch.isspace():
            # stay in state saw_space
            continue
        elif state == saw_space and ch in punct:
            # stay in state saw_space
            yield ch
        elif state == saw_space and ch.isalnum():
            state = in_sentence
            yield ' '
            yield ch

#with open("input.txt") as f:
#    s_result = ''.join(ch for ch in edit_sentences(chars_from_lines(f)))

s_result = ''.join(ch for ch in edit_sentences(s))

print(s_result)
print(s_correct)

rawDescription: Casing text depending on punctuation

description: Casing text depending on punctuation


code:
print (tidx + pd.offsets.Day(15))
DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None)

rawDescription: add 15 days to every date in a pandas DatetimeIndex

description: Add 15 days to every date in a pandas DatetimeIndex


code:
self.a2.cla()
data = np.array(val['surface']['surface'])
x, y, z, colors = data[:,0], data[:,1], data[:,2], data[:,3],
grid_x, grid_y = np.mgrid[min(x):max(x):50j, min(y):max(y):50j]
z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
colors = griddata((x, y), colors, (grid_x, grid_y), method='cubic')
y, x = grid_y.ravel(), grid_x.ravel()

y_coords, x_coords = np.unique(y), np.unique(x)
y_centers, x_centers = [ arr[:-1] + np.diff(arr)/2 for arr in (y_coords, x_coords)]

# Convert back to a 2D grid, required for plot_surface:
Y = y.reshape(y_coords.size, -1)
X = x.reshape(-1, x_coords.size)
Z = z.reshape(X.shape)
C = colors.reshape(X.shape)

#Normalize the colors to fit in the range 0-1, ready for using in the colormap:
Z -= Z.min()
Z /= Z.max()

C -= C.min()
C /= C.max()

interp_func = RectBivariateSpline(x_coords, y_coords, C.T, kx=1, ky=1) # the kx, ky define the order of interpolation. Keep it simple, use linear interpolation.

self.a2.plot_surface(X,Y,Z, facecolors=cm.hot(interp_func(x_centers, y_centers).T), rstride=1,  cstride=1, linewidth=1, antialiased=False, shade=False) # only added because of this very limited dataset

self.canvas2.draw()

rawDescription: Changing Facecolors in four dimensional matplotlib surface


code:
# Pad the number 15 with zeros, up to 10 positions.
("%d" % 15).rjust(10, "0")

rawDescription: Can I achieve variable padding character and variable width with my beloved % formatter?

description: Achieve variable padding character and variable width with my beloved % formatter


code:
def test_stuff(self):
    myfile = open('....\file.csv','r')
    response = self.client.post('/', {'file':myfile})

rawDescription: django - how to unit test a post request using request.FILES

description: Django - how to unit test a post request using request.FILES


code: dict(zip(range(1, len(mydict) + 1), [j for j in mydict.values() if j != mydict[n]]))

rawDescription: Moving Keys in dictionary

description: Moving Keys in dictionary


rawDescription: How to combine two elements of two distinct lists in a specific manner

description: Combine two elements of two distinct lists in a specific manner


code:
slice = [data.pop(0)]
sliced_data = []
while data:
    if data[0] == slice[-1] + 1:
        slice.append(data.pop(0))
    else:
        sliced_data.append(slice)
        slice = [data.pop(0)]
sliced_data.append(slice)

rawDescription: Best way to split this list into smaller lists?

description: Split this list into smaller lists


code:
x = "foo(a) foo(something), foo(stuff)\n foo(1)"
re.sub(r'foo\(([^)]*)\)', r'\1', x)

rawDescription: Some tough string manipulation in Python


code:
import pandas as pd
import glob

fn = 'out.csv'
fns = glob.glob('*.csv') #goes through every CSV file in director
colname = 'ITEM'
rowname = 'NAME'
for csv in fns:
    s = pd.read_csv(csv, usecols=[colname], squeeze=True, skiprows=7, header=0)
    row_idx = pd.Index(s).get_loc(rowname)
    sub_items = s[row_idx + 1:]
    pd.Series(sub_items.unique()).to_csv(fn, mode='a')

rawDescription: Taking out bits of CSVs

description: Taking out bits of CSVs


code:
from matplotlib.ticker import LogFormatter
l_f = LogFormatter(10, labelOnlyBase=False)
cbar = plt.colorbar(CF, ticks=lvls, format=l_f)

rawDescription: matplotlib contour plot with lognorm - colorbar levels

description: Matplotlib contour plot with lognorm - colorbar levels


code:
cmd = 'select value from measurement where measurement_location is ?'
crs.execute(cmd, [location_id])
row = crs.fetchone()
print(row['value'])

print(row['value'] * 100)

rawDescription: Retrieve value from a fetchone() call in python 3


code:
hexstrings = ["DE", "AD", "BE", "EF"]   # big-endian 0xDEADBEEF

bytes = bytearray(int(x, 16) for x in hexstrings)
bytes = bytearray.fromhex("".join(hexstrings))     # Python 2.6 may need u""

rawDescription: Convert list of byte strings to bytearray (byte stream)