code:
import os
import pickle
import pickletools
import sys
import zlib

SETTINGS_FILE = 'settings.sav'

def main():
    """Present the user with a cleaning application."""
    settings = load_settings(SETTINGS_FILE)
    print('Hello, Jacob!')
    while True:
        if show_menu(settings,
                     select_cleaners,
                     edit_cleaning_information,
                     reserved,
                     close_program):
            break
    settings.save(SETTINGS_FILE)

def load_settings(path):
    """Create the settings schema and load them from file is possible."""
    settings = Namespace(mares=Parameter(1, is_positive_int),
                         andres=Parameter(2, is_positive_int),
                         austin=Parameter(3, is_positive_int),
                         al=Parameter(3, is_positive_int),
                         jacob=Parameter(3, is_positive_int))
    if os.path.isfile(path):
        settings.load(path)
    return settings

def is_positive_int(value):
    """Ensure that the value is valid for the settings."""
    return isinstance(value, int) and value >= 0

def show_menu(context, *args):
    """Help display a menu to the user."""
    for option, function in enumerate(args, 1):
        print(option, '-', function.__doc__)
    while True:
        number = get_int('Please enter an option: ') - 1
        if 0 <= number < len(args):
            return args[number](context)
        else:
            print('Your number was out of range.')

def get_int(prompt):
    """Get a valid number from the user."""
    while True:
        try:
            text = input(prompt)
        except EOFError:
            sys.exit()
        else:
            try:
                return int(text)
            except ValueError:
                print('You did not enter an integer.')

def select_cleaners(context):
    """Choose this to select your cleaner."""
    print('Selecting Cleaning Function')

def edit_cleaning_information(context):
    """You can edit the cleaning information."""
    show_menu(context, check_cleaning_info, enter_new_cleaning_info)

def reserved(context):
    """This is reserved for future use."""
    print('NOT AVAILABLE')

def close_program(context):
    """Close the program."""
    return True

def check_cleaning_info(context):
    """Show all cleaning info."""
    print('Mares:', context.mares)
    print('Andres:', context.andres)
    print('Austin:', context.austin)
    print('Al:', context.al)
    print('Jacob:', context.jacob)

def enter_new_cleaning_info(context):
    """Enter in additional cleaning information."""
    while True:
        name = input('Who needs cleaning info adjusted? ').capitalize()
        if name == 'Mares':
            context.mares += get_int('Add to Mares: ')
        elif name == 'Andres':
            context.andres += get_int('Add to Andres: ')
        elif name == 'Austin':
            context.austin += get_int('Add to Austin: ')
        elif name == 'Al':
            context.al += get_int('Add to Al: ')
        elif name == 'Jacob':
            context.jacob += get_int('Add to Jacob: ')
        else:
            continue
        break

###############################################################################

class _Settings:

    """_Settings(*args, **kwargs) -> _Settings instance"""

    @staticmethod
    def _save(path, obj):
        """Save an object to the specified path."""
        data = zlib.compress(pickletools.optimize(pickle.dumps(obj)), 9)
        with open(path, 'wb') as file:
            file.write(data)

    @staticmethod
    def _load(path):
        """Load an object from the specified path."""
        with open(path, 'rb') as file:
            data = file.read()
        return pickle.loads(zlib.decompress(data))

class Namespace(_Settings):

    """Namespace(**schema) -> Namespace instance"""

    def __init__(self, **schema):
        """Initialize the Namespace instance with a schema definition."""
        self.__original, self.__dynamic, self.__static, self.__owner = \
            {}, {}, {}, None
        for name, value in schema.items():
            if isinstance(value, _Settings):
                if isinstance(value, Namespace):
                    if value.__owner is not None:
                        raise ValueError(repr(name) + 'has an owner!')
                    value.__owner = self
                self.__original[name] = value
            else:
                raise TypeError(repr(name) + ' has bad type!')

    def __setattr__(self, name, value):
        """Set a named Parameter with a given value to be validated."""
        if name in {'_Namespace__original',
                    '_Namespace__dynamic',
                    '_Namespace__static',
                    '_Namespace__owner',
                    'state'}:
            super().__setattr__(name, value)
        elif '.' in name:
            head, tail = name.split('.', 1)
            self[head][tail] = value
        else:
            attr = self.__original.get(name)
            if not isinstance(attr, Parameter):
                raise AttributeError(name)
            attr.validate(value)
            if value == attr.value:
                self.__dynamic.pop(name, None)
            else:
                self.__dynamic[name] = value

    def __getattr__(self, name):
        """Get a Namespace or Parameter value by its original name."""
        if '.' in name:
            head, tail = name.split('.', 1)
            return self[head][tail]
        if name in self.__dynamic:
            return self.__dynamic[name]
        attr = self.__original.get(name)
        if isinstance(attr, Namespace):
            return attr
        if isinstance(attr, Parameter):
            return attr.value
        raise AttributeError(name)

    __setitem__ = __setattr__
    __getitem__ = __getattr__

    def save(self, path):
        """Save the state of the entire Namespace tree structure."""
        if isinstance(self.__owner, Namespace):
            self.__owner.save(path)
        else:
            self._save(path, {Namespace: self.state})

    def load(self, path):
        """Load the state of the entire Namespace tree structure."""
        if isinstance(self.__owner, Namespace):
            self.__owner.load(path)
        else:
            self.state = self._load(path)[Namespace]

    def __get_state(self):
        """Get the state of this Namespace and any child Namespaces."""
        state = {}
        for name, types in self.__static.items():
            box = state.setdefault(name, {})
            for type_, value in types.items():
                box[type_] = value.state if type_ is Namespace else value
        for name, value in self.__original.items():
            box = state.setdefault(name, {})
            if name in self.__dynamic:
                value = self.__dynamic[name]
            elif isinstance(value, Parameter):
                value = value.value
            else:
                box[Namespace] = value.state
                continue
            box.setdefault(Parameter, {})[type(value)] = value
        return state

    def __set_state(self, state):
        """Set the state of this Namespace and any child Namespaces."""
        dispatch = {Namespace: self.__set_namespace,
                    Parameter: self.__set_parameter}
        for name, box in state.items():
            for type_, value in box.items():
                dispatch[type_](name, value)

    def __set_namespace(self, name, state):
        """Set the state of a child Namespace."""
        attr = self.__original.get(name)
        if not isinstance(attr, Namespace):
            attr = self.__static.setdefault(name, {})[Namespace] = Namespace()
        attr.state = state

    def __set_parameter(self, name, state):
        """Set the state of a child Parameter."""
        attr = self.__original.get(name)
        for type_, value in state.items():
            if isinstance(attr, Parameter):
                try:
                    attr.validate(value)
                except TypeError:
                    pass
                else:
                    if value == attr.value:
                        self.__dynamic.pop(name, None)
                    else:
                        self.__dynamic[name] = value
                    continue
            if not isinstance(value, type_):
                raise TypeError(repr(name) + ' has bad type!')
            self.__static.setdefault(name, {}).setdefault(
                Parameter, {})[type_] = value

    state = property(__get_state, __set_state, doc='Namespace state property.')

class Parameter(_Settings):

    """Parameter(value, validator=lambda value: True) -> Parameter instance"""

    def __init__(self, value, validator=lambda value: True):
        """Initialize the Parameter instance with a value to validate."""
        self.__value, self.__validator = value, validator
        self.validate(value)

    def validate(self, value):
        """Check that value has same type and passes validator."""
        if not isinstance(value, type(self.value)):
            raise TypeError('Value has a different type!')
        if not self.__validator(value):
            raise ValueError('Validator failed the value!')

    @property
    def value(self):
        """Parameter value property."""
        return self.__value

###############################################################################

if __name__ == '__main__':
    main()

rawDescription: Preset Variable with Pickle

description: Preset Variable with Pickle


code:
from collections import Counter
code_list= ['ab','ca','gc','ab','we','ca']
points = [30, 20, 40, 20, 10, -10]
c = Counter()
for key, val in zip(code_list, points):
    c[key] += val

c.most_common(1)

rawDescription: Python: searching maximum data

description: Python: searching maximum data


code:
for line in output.splitlines():  # Read lines from CPU MEM TEMP
    if "example1" in line:
        for word in line.split():
            array.append(word)

rawDescription: Parse through variable in python

description: Parse through variable in python


rawDescription: Python tk scrollbar behavior (Windows to blame?)


code: df2 = pd.DataFrame(index=df1.index)

rawDescription: Create an empty data frame with index from another data frame


code:
field = missing_vals['field'][i]
data[field].replace(missing_vals['key'][i], np.nan)

rawDescription: Python pandas: updating dataframe series values based on values contained in another dataframe


rawDescription: How to split python list into chunks of equal size?

description: Split python list into chunks of equal size


code:
import json
import pymongo
import tweepy

consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        super(tweepy.StreamListener, self).__init__()

        self.db = pymongo.MongoClient().test

    def on_data(self, tweet):
        self.db.tweets.insert(json.loads(tweet))

    def on_error(self, status_code):
        return True # Don't kill the stream

    def on_timeout(self):
        return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
sapi.filter(track=['Gandolfini'])

rawDescription: How can I consume tweets from Twitter's streaming api and store them in mongodb

description: Consume tweets from Twitter's streaming api and store them in mongodb


code: process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb'))

rawDescription: is there a quiet version of subprocess.call?

description: Is there a quiet version of subprocess.call


code:
df['press'].astype('float')
df['temp'].astype('float')

df['proc']  = np.where((df['press'] > 1100) & (df['temp'] < 40),'dilute', "pressurized")

rawDescription: Amend column values according to timedelta and index


code:
if current_day >= set_week_day:
    week = current_week
else:
    week = current_week - 1

rawDescription: Algorithm for getting current week number after changing the starting day of the week in python?


code:
import json

def getdata():
    rows = db().select(db.realtimedata.id, db.realtimedata.FlowRate,
                       limitby=(0, 3), orderby=~db.realtimedata.id)
    return json.dumps([[r.id, r.FlowRate] for r in rows])

rawDescription: Transforming db data to json in web2py for visualization with flot.js


rawDescription: how to get the absolute url of a view in django?

description: Get the absolute url of a view in django


code:
import math
list=[0.0,-0.0,1.0,-1.0,2.0,-2.0,3.0,-3.0]
objects={}
while list:
    d = round(list.pop(),10)
    if d not in objects:
        objects[d]=1.0
    objects[d] *= math.copysign(1.0,d)

rawDescription: Python: how can this code use negative integer 0 as a distinct index value?


code:
s = "\WWWW$$$$"
splitter = re.compile('\\W*')   # Match non-alphanumeric characters
re.findall(splitter, s)
splitter = re.compile('\\\\W*') # Match `\` followed by 0 or more `W`
re.findall(splitter, s)
splitter = re.compile(r'\W*')   # Same as first one. You need a single `\`
re.findall(splitter, s)
splitter = re.compile(r'\\W*')  # Same as 2nd. Two `\\` needed.
re.findall(splitter, s)

rawDescription: Confused about regular expression

description: Confused about regular expression


code:
df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}, index=list('abcd'))
df
idx = pd.Index(df['A']).get_indexer([3,4,5]); idx
df.iloc[idx]

rawDescription: How to use a list of values to select rows from a pandas Dataframe in specific order

description: Use a list of values to select rows from a pandas Dataframe in specific order


code: extensions = ['sphinx.ext.intersphinx']

rawDescription: How can I link/reference another reST file in the documentation?

description: Link/reference another reST file in the documentation


code:
#service.py
class Status(ComplexModel):
    statusCode = Integer
    statusMsg = String

class ResponseData(ComplexModel):
    status = Array(Status)
    version = Integer

class SoapService(ServiceBase):
    @rpc(String, _returns=ResponseData)
    def doSomething(ctx, name):

        obj_data = Servers.objects.get(host=name)
        if obj_data.status:
            my_statusCode = 1
            my_statusMsg = 'online'
        else:
            my_statusCode = 0
            my_statusMsg = 'offline'

        retval = ResponseData()
        retval.status = [{'statusCode': my_statusCode, 'statusMsg': my_statusMsg}]
        retval.version = 1
        return retval

rawDescription: Spyne/RPClib - How to respond with ComplexModel?


code:
x = 5
while True:
    if True:
        x = -x

rawDescription: if statement handling-manipulation

description: If statement handling-manipulation


code:
import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)
data1 = [random.random() for i in range(10)]
data2 = [random.random()*1000 for i in range(10)]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

ax = fig.add_subplot(gs[0])
ax.plot(data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

ax = fig.add_subplot(gs[1])
ax.plot(data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

rawDescription: matplotlib: Aligning y-axis labels in stacked scatter plots

description: Matplotlib: Aligning y-axis labels in stacked scatter plots


code:
needed_reads = []

reads_array = []

chosen_array = []

for x in Bio.SeqIO.parse("F1.fastq","fastq"):

        reads_array.append(x)

for y in Bio.SeqIO.parse("F2.fastq","fastq"):

        chosen_array.append(y)

needed_reads = list(set(reads_array) - set(chosen_array))

output_handle = open("DIFF.fastq","w")

SeqIO.write(needed_reads,output_handle,"fastq")

output_handle.close()

rawDescription: getting records which are different from two fastq files

description: Getting records which are different from two fastq files


code:
class p(Protocol):
    factory = None
    ...
class f(Factory):
    protocol = p
    data = None
    def buildProtocol(self, addr):
        returnValue = p()
        returnValue.factory = self
        return returnValue

rawDescription: twisted and more clients in script

description: Twisted and more clients in script


code:
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))

rawDescription: Python - how do delete content in a complicated folder without changing its structure?


rawDescription: How to change 2nd level index into 2nd level column in pandas DataFrame?

description: Change 2nd level index into 2nd level column in pandas DataFrame


rawDescription: Python "Every Other Element" Idiom

description: Python "Every Other Element" Idiom


code:
import pandas as pd
df = pd.DataFrame({"A":[1,2,3], "B":[4,5,6]}, index=list("xyz"))
df.ix["t"] = [10, 20]

rawDescription: Insert data into Pandas DataFrame without index or column overhead (so not concat or append)


code:
dfa = dfa.set_index('block_id')
dfb = dfb.set_index('block_id')
dfb.rename(columns={'number':'const'}, inplace=True) # maybe not needed
dfa.loc[:, 'const'] = dfa.const.where(dfa.t<=0.01, dfb.const)

rawDescription: Python condition aggregation

description: Python condition aggregation


code:
def update(dictionary, key, newvalue, func=max):
    dictionary[key] = func(dictionary[key], newvalue)

rawDescription: Is there a pythonic way to update a dictionary value when the update is dependent on the value itself?


code:
def process_request(self, request):

    if 'locale' in request.cookies:
        request.locale = request.cookies.locale
    else:
        request.locale = None

def process_response(self, request, response):

    if getattr(request, 'locale', False):
        response.cookies['locale'] = request.locale

rawDescription: How to run a python function on every Admin page load in Django

description: Run a python function on every Admin page load in Django


code:
from A.a import something
from A.b import something

# or

import A
A.a.something
A.b.something

rawDescription: Acess modules from different directory

description: Acess modules from different directory


rawDescription: how to remove whitespace inside bracket?

description: Remove whitespace inside bracket


code:
def tree(branchLen,t):
    if branchLen > 5:
        t.forward(branchLen)
        t.right(20)
        little_tree(branchLen-15,t)
        t.left(40)
        little_tree(branchLen-10,t)
        t.right(20)
        t.backward(branchLen)

def little_tree(littleBranchLen,lt):
    if littleBranchLen > 5:
        lt.forward(littleBranchLen)
        lt.right(20)
        lt.left(40)
        lt.right(20)
        lt.backward(littleBranchLen)

rawDescription: Drawing a Fractal Tree in Python using Recursion


code: a.__dict__ = dict(b.__dict__)

rawDescription: assignment in python

description: Assignment in python


code:
def max_and_min(*arg):
    return (max(arg), min(arg))

rawDescription: How to write a function max_and_min that accepts a tuple containing integer elements as an argument?

description: Write a function max_and_min that accepts a tuple containing integer elements as an argument


code:
import os
from xml.etree import cElementTree

workingDir = "C:\\Users\\Vince\\Test"
tree = cElementTree.parse(os.path.join(newStrWorkingDir, "test.xml"))
root = tree.getroot()
tab = []

for entry in root.findall('Entry'):
    entry_name = entry.findtext("./DisplayName")
    scalar_names = [e.text for e in entry.findall('Scalar/DisplayName')]
    tab.append((entry_name, scalar_names))
print(tab)

rawDescription: XML file parsing - Get data from each parent and their own children


code:
first_i, first_j = sequence_indices[0]
board[first_i][first_j]

rawDescription: Optimize tic tac toe checks

description: Optimize tic tac toe checks


code:
from matplotlib.pyplot import *
gca().set_xticklabels(['']*10)
plot(range(10))

rawDescription: Python - Remove axis tick labels, keeping ticks and axis label


code:
class Student(ndb.Model):
    name = ndb.StringProperty()

class Course(ndb.Model):
    students = ndb.KeyProperty(repeated=True)

def create_course(students):
    """Create a new course object and return it.

    Args:
        students: iterable of `Student` model instances.
    """
    c = Course()
    c.students = [s.key for s in students]
    return c

rawDescription: Creating a List in python for Google App Engine


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

z = (z-np.nanmin(z)) /(np.nanmax(z) - np.nanmin(z))

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

ax.scatter(x,y,z,cmap='hot',c=z)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

rawDescription: Matplotlib 3D plot use colormap

description: Matplotlib 3D plot use colormap


code: table.where('where(a==b, 1, 0) == c')

rawDescription: Conditional expression in PyTables where method


code:
lock = DeferredLock()
d1 = lock.run(agent.request, url, ...)
d2 = lock.run(agent.request, url, ...)

rawDescription: Maximum number of connections per host with twisted.web.client.Agent


code:
with open('ids.txt', 'rU') as f:
    interesting_ids = set('>' + line.lower()[0:4] + "_" + line[4] for line in f)  # Get all ids in a set.

found_id = None
with open('seqres.txt', 'rU') as g:
    for line in g:
        if found_id is not None:
            with open(found_id+'.fasta','w') as h:
                h.write(line)

        id = line[:7]
        if id in interesting_ids: found_id = id
        else: found_id = None

rawDescription: Loop over a file and write the next line if a condition is met


code:
if __name__ == "__main__":
    import sys
    lexer = lex.lex()
    yacc.yacc()

    with open(sys.argv[1], 'r', encoding="UTF-8") as inputfile:
        contents = inputfile.read()
        lexer.input(contents)
        for token in lexer: #for this part, the file is read correctly
            print("line %d : %s (%s) " % (token.lineno, token.type, token.value))

        result = yacc.parse(contents, debug=True)
        print(result) #Stack immediatly contains . $end and the p_error(p) I've defined confirms EOF was reached
        tmp = "{{var1 := 'some text' ; var2 := 'some other text' ; var3 := ( 'text', 'text2') ; }}" #Same contents as the input file
        result = yacc.parse(tmp, debug=True)
        print(result) #correct results

rawDescription: Python YACC EOF reached immediately

description: Python YACC EOF reached immediately


code: return render(request, u'clients/models/%s-%s.json' % (client, report), ...)

rawDescription: Make render call using a URL argument to construct the template file name


code:
def max_r(l: [int]) -> int:
    if len(l) == 1:
        return l[0]
    else:
        result = max_r(l[1:])
        return l[0] if result < l[0] else result

rawDescription: Infinite Recursion in Python Function if Argument Too Long


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

fig, ax = plt.subplots()
ax.set_xlabel('Time (s)')
ax.set_ylabel('Temperature (F)')
ax.set_title("Your drink's current temperature")

xs = np.linspace(0, 2*np.pi, 512)
ys = np.sin(xs)

ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)

ln, = ax.plot([], [], lw=3)

def init(*args, **kwargs):
    ln.set_data([], [])
    return ln,

def animate(i):
    ln.set_data(xs[:i], ys[:i])
    return ln,

ani = manimation.FuncAnimation(fig, animate,
                               frames=512, blit=True,
                               init_func=init)
plt.show()

rawDescription: How do I show x and y labels to a live graph in Python?

description: Show x and y labels to a live graph in Python


code:
from RecursionException import RecursionException
from RecursionResult import RecursionResult
from Recursor import Recursor

rawDescription: Python: Define Classes in Packages

description: Python: Define Classes in Packages


code:
response = HttpResponse()
response.write("
Here's the text of the Web page.
")
response.write("
Here's another paragraph.
")

rawDescription: Multiple HttpResponses in Django

description: Multiple HttpResponses in Django


code:
from itertools import repeat, cycle

for i in repeat('abcd'): print(i)
# abcd, abcd, abcd, abcd, ...

for i in cycle('abcd'): print(i)
# a, b, c, d, a, b, c, d, ...

rawDescription: itertools.repeat VS itertools.cycle

description: Itertools.repeat VS itertools.cycle


rawDescription: Combinations of MultiIndex levels which occur in a DataFrame


code:
np.add.at(h, [x,y,z], q)
for i, val in np.ndenumerate(h):
    if val: print(i, val)

rawDescription: numpy / python - indexing by arrays with duplicates

description: Numpy / python - indexing by arrays with duplicates


code:
class MaxTriesExceededError(Exception):
    pass

def tries(max_tries=3, error_message="failure"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for try_count in range(max_tries):
              try:
                return func(*args,**kwargs)
              except:
                pass
            raise MaxTriesExceededError(error_message)
        return wrapper
    return decorator

import unittest

class TestDecorator(unittest.TestCase):

  def setUp(self):
      self.count = 0

  def test_success_single_try(self):
      @tries(1)
      def a():
          self.count += 1
          return "expected_result"
      self.assertEqual(a(), "expected_result")
      self.assertEqual(self.count, 1)

  def test_success_two_tries(self):
      @tries(2)
      def a():
          self.count += 1
          return "expected_result"
      self.assertEqual(a(), "expected_result")
      self.assertEqual(self.count, 1)

  def test_failure_two_tries(self):
      @tries(2)
      def a():
           self.count += 1
           raise Exception()
      try:
        a()
        self.fail()
      except MaxTriesExceededError:
        self.assertEqual(self.count,2)

  def test_success_after_third_try(self):
      @tries(5)
      def a():
           self.count += 1
           if self.count==3:
             return "expected_result"
           else:
             raise Exception()
      self.assertEqual(a(), "expected_result")
      self.assertEqual(self.count, 3)

if __name__ == '__main__':
    unittest.main()

rawDescription: How to test a decorator in a python package

description: Test a decorator in a python package


code:
import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)

rawDescription: Print to standard printer from Python?

description: Print to standard printer from Python


code:
def foo():
    from validators import some_validations

rawDescription: Cross references with Django

description: Cross references with Django


code: all(is_okay(s) for s in some_array)

rawDescription: increasing expressiveness in array elements test

description: Increasing expressiveness in array elements test


rawDescription: How to know which request comes from which sessions python

description: Know which request comes from which sessions python


code: from functions import foo

rawDescription: Include fileson python

description: Include fileson python


code:
matlab_eigvec = np.array([[0.0896+0.6789j, 0.0953+0.7225j],
                          [-0.7288+0.j, 0.6848+0.j]])

f1, f2 = matlab_eigvec.T # matlab eigenvectors
e1, e2 = eig_vec.T # numpy eigenvectors
f1/e1
f2/e2

rawDescription: Conflicting eigen vector outputs between Matlab and Numpy


code:
import skimage
image_data = request.files['image_data']
image = skimage.io.imread(image_data)

rawDescription: Pass an uploaded file in Flask directly to scikit-image


code:
flagJson = requests.post(fburl, data=payload)
flagDict = json.loads(flagJson)

rawDescription: Handling Response from Python POST Request


code:
winning_combinations = ((0,1,2), (3,4,5), (6,7,8), (6,3,0), (7,4,1), (8,5,2), (6,4,2), (8,4,0))
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
whose_move = 1

class Node():
    def __init__(self, board, whose_move):
        self.board = board
        self.whose_move = whose_move

    def create_tree(self, board=None, whose_move=None):

        if board is None:
            board = self.board
        if whose_move is None:
            whose_move = self.whose_move

        child_nodes = []

        for index, square in enumerate(board):
            if square == index + 1:  # if square not taken
                new_board = list(board)  # make a shallow copy

                if whose_move == 1:
                    new_board[index] = "X"
                    whose_move = 0
                else:
                    new_board[index] = "O"
                    whose_move = 1

                if self.available_moves(new_board):
                    child_nodes.append(self.create_tree(new_board, whose_move))
                else:
                    child_nodes.append(new_board)
        return child_nodes

    def available_moves(self, board):
        for index, square in enumerate(board):
            if square == index + 1:  # if square not taken
                return True
        return False

node = Node(board, whose_move)

print(node.create_tree())

rawDescription: Recursion within Class, Python

description: Recursion within Class, Python


code:
import Tkinter

class TkExample(Tkinter.Frame):
   def __init__(self, parent):
      Tkinter.Frame.__init__(self, parent)
      self.init_ui()

   def init_ui(self):
      self.pack()
      text_box = Tkinter.Text(self)
      text_box.pack()
      text_box.bind("<Key>", self.update_size)

   def update_size(self, event):
      widget_width = 0
      widget_height = float(event.widget.index(Tkinter.END))
      for line in event.widget.get("1.0", Tkinter.END).split("\n"):
         if len(line) > widget_width:
            widget_width = len(line)+1
      event.widget.config(width=widget_width, height=widget_height)

if __name__ == '__main__':
    root = Tkinter.Tk()
    TkExample(root)
    root.mainloop()

rawDescription: Tkinter Resize text to contents

description: Tkinter Resize text to contents


code:
with open('foo.txt', 'rb') as f:
    contents = f.read().decode('utf-8-sig')   # -sig takes care of BOM if present

rawDescription: Python Text Encoding

description: Python Text Encoding


code:
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
import django
django.setup()

for item in django.apps.all_models:
    print(item)

rawDescription: getting django.apps from shell but not script

description: Getting django.apps from shell but not script


code:
def FindFirstMatch(list1, list2):
    """
    Returns the first element in list "list1" for which there is a matching
    element in list "list2" or None if there is no match
    """

    setb = set(list2)

    return next((item for item in list1 if item in setb),None)

rawDescription: Returning the first item in a Python list which is contained in another list


code:
# create a Profile object
new_profile = Profile()

for name in dir(incoming):
    # loop on each method for incoming object
    attribute = getattr(incoming, name)
    if not ismethod(attribute):
        # get the value of the attribute
        value = attribute
    setattr(new_profile, name, value)

new_profile.save()

rawDescription: Store a class method in django model

description: Store a class method in django model


code:
for i in range(n) :
     num[i] += 1
     lst.append(num)

rawDescription: Do I need to use list() to append a list into another list in Python?


code: prop = property(memoized(prop.fget), prop.fset, prop.fdel, prop.__doc__)

rawDescription: Applying a decorator to a property getter


code:
for i in range(0,2):
    cmd = lambda i=i: sys.stdout.write(str(i))
    tk.Button(text="print '%d'" % i,command=cmd).pack()

rawDescription: Python's lambda iteration not working as intended


code:
import pynotify
p = pynotify.Notification("Notice", "", "/usr/share/pixmaps/firefox.png")
p.show()

rawDescription: How to set a local image in pynotify?

description: Set a local image in pynotify


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
text =  soup.get_text()

rawDescription: Is there a way to use readability and python to extract just text, not HTML?


code:
import operator
try:
    largestBlob = max((blob for blob in blobs if blob['color'] == 'red'),key=operator.itemgetter('size'))
except ValueError:
    largestBlob = None

rawDescription: Is there a shorthand for querying a dictionary in python?


code:
star_pos = my_string.find('*')
my_string = my_string[:star_pos] + '*' + checksum_str + my_string[star_pos + 3:]

rawDescription: The elegant way to replace specific characters in Python


code:
# Configuration file for ipython.

c = get_config()

c.InteractiveShellApp.exec_lines = [
    'from __future__ import print_function, division',
    '%matplotlib inline',
    'import sys, os',
    'sys.path.append(os.environ[\'PYTHONPATH\'])',
    'os.chdir(\'path/to/your/working/dir\')',
    'import pandas as pd',
    'import numpy as np',
    'pd.options.display.notebook_repr_html = False',
    'pd.options.display.max_rows = 20',
    'pd.options.display.max_columns = 20',
    'pd.options.display.expand_frame_repr = False',
    'pd.options.display.max_colwidth = 28',
    'pd.options.display.precision = 5',
    'np.set_printoptions(precision=4, linewidth=90, threshold=25)',
    'import datetime as dt',
    'import matplotlib.pyplot as plt'
]
c.NotebookApp.notebook_dir = u'path/to/your/notebook/dir'
c.IPythonWidget.font_size = 12
c.IPythonWidget.font_family = "Ubuntu Mono"
c.ZMQInteractiveShell.colors = "LightBG"

rawDescription: ipython notebook startup file

description: Ipython notebook startup file


code:
fields = ["reference_link", "rss_link"] # define fields to use
with open(filename,'a+') as f: # handle the source file
    f.write("{}\n".format('\t'.join(str(field)
                              for field in fields))) # write header
    for item in items:
        f.write("{}\n".format('\t'.join(str(item[field])
                              for field in fields))) # write items

rawDescription: Write to a csv file scrapy

description: Write to a csv file scrapy


code:
def ravel_index(x, dims):
    i = 0
    for dim, j in zip(dims, x):
        i *= dim
        i += j
    return i

rawDescription: Mapping a 3-dimensional coordinate to a 1-dimensional index


code:
import re
re.findall(r'@(\w+)', "sometext@aaaa sometext @bbbb sometext@cccc")

rawDescription: python split string and get words after some character

description: Python split string and get words after some character


code:
alttrue = []
altfalse = []

rawDescription: Extracting multimedia tags with alt in Python


code:
def callback():
    abc = askopenfilename()
    execfile("abc.py")

rawDescription: Browse files to open and run using GUI python


code:
ts_shiftedPlus = ts.shift(1)
ts_shiftedMinus = ts.shift(-1)

ts_smooth = 1/3 * ts_shiftedMinus + 1/3 * ts + 1/3 * ts_shiftedPlus
ts_smooth.ix[0] = 1/2 * ts.ix[0] + 1/2 * ts.ix[1]
N = len(ts)
ts_smooth.ix[N] = 1/2 * ts.ix[N-1] + 1/2 * ts.ix[N]

rawDescription: Pandas: Using rolling_mean() with maximum information criteria as a Smoothing Function?


code:
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Preformatted, XPreformatted
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch

PAGE_HEIGHT = defaultPageSize[1]; PAGE_WIDTH = defaultPageSize[0]
BottomMargin = 0.4 * inch
TopMargin = 0.4 * inch
LeftMargin = .1 * inch
RightMargin = .1 * inch
ContentBottomMargin = TopMargin + 0.25 * inch
ContentTopMargin = BottomMargin + 0.35 * inch
ContentLeftMargin = LeftMargin
ContentRightMargin = RightMargin

rawDescription: reportlab - cannot set top margin to zero in physically printed page

description: Reportlab - cannot set top margin to zero in physically printed page


code:
class LoginForm(Form):
    username = ...
    password = ...

class ReigsterForm(LoginForm):
    confirm_password = ...

rawDescription: How to remove fields from parent form?

description: Remove fields from parent form


code:
def main():
    millis=input("Enter time in milliseconds ")
    millis = int(millis)
    seconds=(millis/1000)%60
    seconds = int(seconds)
    minutes=(millis/(1000*60))%60
    minutes = int(minutes)
    hours=(millis/(1000*60*60))%24

    print ("%d:%d:%d" % (hours, minutes, seconds))

main()

rawDescription: Convert milliseconds to hours, min, and seconds python


code:
a = np.arange(100)
breaks = np.linspace(0, 100, 11, dtype=np.intp)
counts = np.diff(breaks)
counts
sums = np.add.reduceat(a, breaks[:-1], dtype=np.float)
sums
sums / counts  # i.e. the mean

rawDescription: Vectorizing a Numpy slice operation

description: Vectorizing a Numpy slice operation


code: titles = [hxs.select('//tr[@class="index class_tr group-6487"] | //tr[@class="index class_tr group-6488"] | //tr[@class="index class_tr group-6489"]')]

rawDescription: Scrapy crawl Multiple XPathSelector on same page


code:
def get_urls(self, page=1, site=None):
    if site is None:
        if Site._meta.installed:
            try:
                site = Site.objects.get_current()
            except Site.DoesNotExist:
                pass
        if site is None:
            raise ImproperlyConfigured("In order to use Sitemaps you must either use the sites framework or pass in a Site or RequestSite object in your view code.")

    urls = []
    for item in self.paginator.page(page).object_list:
        loc = "http://%s%s" % (site.domain, self.__get('location', item))
        priority = self.__get('priority', item, None)
        url_info = {
            'location':   loc,
            'lastmod':    self.__get('lastmod', item, None),
            'changefreq': self.__get('changefreq', item, None),
            'priority':   str(priority is not None and priority or '')
        }
        urls.append(url_info)
    return urls

rawDescription: How do you extend Django's sitemap module to create more complex sitemaps?

description: Extend Django's sitemap module to create more complex sitemaps


code:
from google.appengine.ext.ndb import metadata
class RestCustomers(webapp2.RequestHandler):
    customers = metadata.get_properties_of_kind(Customers)
    self.response.headers['Content-Type'] = "application/json"
    self.response.write(json.dumps(customers))

rawDescription: Convert a string to another Python class


code:
if request.method == 'POST':
    images = request.POST.getlist('images[]')
    other_field = request.POST.get('other_field')

    for i in range(len(images)):
        data = MyModel()
        data.images = images[i]
        data.other_field = other_field
        data.save()

rawDescription: Post more files and save them into db - django


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

driver = webdriver.Firefox()
driver.maximize_window()

wait = WebDriverWait(driver, 10)

url = 'https://www.homeaway.pt/arrendamento-ferias/p1418427a?uni_id=1590648'
driver.get(url)

# pick start date
start_date = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".quotebar-container input[name=startDateInput]")))
start_date.click()

first_available_date = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ui-datepicker-div td.full-changeover > a")))
ActionChains(driver).move_to_element(first_available_date).perform()
driver.find_element_by_css_selector("#ui-datepicker-div td.full-selected.full-changeover > a").click()

# pick end date (TODO: violates DRY principle, refactor!)
end_date = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".quotebar-container input[name=endDateInput]")))
end_date.click()

first_available_date = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ui-datepicker-div td.full-changeover > a")))
ActionChains(driver).move_to_element(first_available_date).perform()
driver.find_element_by_css_selector("#ui-datepicker-div td.full-selected.full-changeover > a").click()

# get the calculated price
price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".price-quote .price-total")))
print(price.text)

driver.close()

rawDescription: Python Selenium + Datepicker Click

description: Python Selenium + Datepicker Click


code:
import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('/tmp/spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

rawDescription: Python logging file is updated, but nothing is printed to stdout although level is set


code:
from collections import defaultdict
res = defaultdict(dict)

for title, x, y in my_list:
    res[title][x] = y

rawDescription: Rearrange a Python List

description: Rearrange a Python List


code:
class MainGUI(HasTraits):
  GUIWidgetsForMainGUI = Any
  user_window = Instance(UserInput)
  button = Button('Get User Input')

  traits_view=View(Item('GUIWidgetsForMainGUI'),
    Item('button'))

  def _button_fired(self):
    self.user_window.edit_traits()

  @on_trait_change('button')
  def or_alternately_you_can_use_listeners(self):
    self.user_window.edit_traits()

MainGUI().configure_traits()

rawDescription: Multi-Window GUI using Python Traits (Solved)


code:
idx = pd.IndexSlice
x.loc[:,idx[:,'a']]
x.loc[:,idx[:,['a','c']]]

rawDescription: Selecting a column with multiple levels of column naming


code:
import pyfits
import numpy as np

hdulist = pyfits.open(filename)
header = hdulist[0].header
data = hdulist[0].data
data = np.nan_to_num(data)
new_data = data[0]

for i in range(1,84):                #this depends on number of layers or pages
    new_data += data[i]

hdu = pyfits.PrimaryHDU(new_data)
hdu.writeto(new_filename)

rawDescription: Collapsing / Flattening a FITS data cube in python


rawDescription: Python regex remove all before a certain point


code:
self.cells_canvas[i][0].columnconfigure(0, weight=1)
self.cells_canvas[i][1].columnconfigure(1, weight=1)
self.cells_canvas[i][2].columnconfigure(2, weight=1)

rawDescription: Tkinter: Extend labels to the edge of the column


code:
import random

with open("datafile.txt", "rb") as f:
    data = f.read().split('\n')

random.shuffle(data)

train_data = data[:50]
test_data = data[50:]

rawDescription: How to split data into trainset and testset randomly?

description: Split data into trainset and testset randomly


code:
for line in infile:
    line = line.strip().split(',')
    outfile.write(','.join(line[:3]) + '\n')

rawDescription: Writing only part of a line to a file

description: Writing only part of a line to a file


code:
def __init__(self):
    self.filename = "highscores.dat"
    self.numScores = 5

    if not os.path.isfile(self.filename):
        self.scores = [100 for i in range(self.numScores)]
        self.names = ["A", "B", "C", "D", "E"]
        self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
    else:
        with open(self.filename, "rb") as f:
            self.highscores = pickle.load(f)
        self.names = [highscore[0] for highscore in self.highscores]
        self.scores = [highscore[1] for highscore in self.highscores]

def updateFile(self):
    with open(self.filename, 'wb') as f:
        pickle.dump(self.highscores, f)

rawDescription: Python Pickling Problems

description: Python Pickling Problems


code: final_string = ''.join(substring for substring in my_generator())

rawDescription: Efficient string building with immutable strings


code:
def a():
    b = 1
    def x():
        # indicate we want to be modifying b from the containing scope
        nonlocal b
        b -= 1
    if something is something:
        x()

a()

rawDescription: Python3 variables in functions

description: Python3 variables in functions


code: soup = BeautifulSoup('...Baby One More Time (Digital Deluxe Version…', convertEntities="html")

rawDescription: Escaping … with BeautifulSoup

description: Escaping … with BeautifulSoup


code:
while True:
    # this will block until at least one socket is ready
    ready_socks,_,_ = select.select([private, public], [], [])
    if private in ready_socks:
        privateResponse += private.recv()
    if public in ready_socks:
        channelResponse += public.recv()

    # check privateResponse buffer, do stuff
    # check channelResponse buffer, do stuff

rawDescription: I am creating a Twitch-focused IRC bot in Python, however it is getting the responses slowly. What am I doing wrong?


code:
import matplotlib.pyplot as plt

plt.plot(range(1000), range(1000))
plt.xticks([80,150,300])
plt.show()

rawDescription: How to set axis ticks

description: Set axis ticks


code:
s = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef'
r = ['ApplC3LDJXGEDCP7', '10']
print(re.sub(r'{.+?}', lambda match: r.pop(0), s, count=len(r)))
# deviceId=ApplC3LDJXGEDCP7&deviceGroupID=10&abcd=dkef

rawDescription: How to iterate a list over re.sub and replace variables in a string using python?

description: Iterate a list over re.sub and replace variables in a string using python


rawDescription: Regular Expression Parsing Key Value Pairs in Namelist Input File


code:
import subprocess
...
filename = ...
cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName]
f = open(filename)
subprocess.call(cmd, stdin=f)

rawDescription: Run shell command with input redirections from python 2.4?


code: domain = email.split('@')[1]

rawDescription: Counting Organizations by using Python and Sqlite


code:
def add42(fn):
    def wrap(i):
        return fn(i) + 42
    wrap.unwrapped = fn
    return wrap

@add42
def mult3(i):
    return i * 3

mult3(1) # 45
mult3.unwrapped(1) # 3

rawDescription: How to Make Decorators Optionally Turn On Or Off


code:
import matplotlib.pyplot as plt
import numpy as np
from time import sleep
x1,x2,n,m,b = -50.,150.,11,0.,0.
x = np.r_[x1:x2:n*1j]
plt.ion()
plt.axis([ -50, 150, -50, 150])
line, = plt.plot(x, m*x + b)    # comma is needed because plot returns a tuple
for m in np.r_[1:0:-0.1]:
    line.set_ydata(m*x + b)
    plt.draw()
    sleep(0.5)

rawDescription: Draw, then re-draw lines in python code

description: Draw, then re-draw lines in python code


code:
context = {'user': request.user}  # assign the current user to the context 'user'
return render_to_response('my_template.html', context)

rawDescription: How do I create global elements in a Django template that reference a database?

description: Create global elements in a Django template that reference a database


rawDescription: Pandas: conversion to/from cvxopt matrices


code:
#!/usr/bin/env python
import random
import itertools

numname={1:'Ace',11:'Jack',12:'Queen',13:'King'}
suits=['Clubs','Diamonds','Hearts','Spades']
numbers=range(1,14)
cards=['%s-%s'%(numname.get(number,number),suit)
       for number,suit in itertools.product(numbers,suits)]
print(cards)
random.shuffle(cards)
print(cards)
hand=random.sample(cards,5)
print(hand)

rawDescription: Random selection ideas

description: Random selection ideas


code:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test-database']
coll = db.test_collection
# the collection is ready now
from bson.binary import Binary
import pickle
# create a sample object
myObj = {}
myObj['demo'] = 'Some demo data'
# convert it to the raw bytes
thebytes = pickle.dump(myObj)
coll.insert({'bin-data': Binary(thebytes)})

rawDescription: Is there a way to store python objects directly in mongoDB without serializing them


code:
if (device_props.Get('org.freedesktop.UDisks.Device', 'DeviceIsRemovable') and
        device_props.Get('org.freedesktop.UDisks.Device', 'DeviceIsMounted')):
    output.extend(device_props.Get('org.freedesktop.UDisks.Device',
                                   'DeviceMountPaths'))

rawDescription: How to get "mounted on" in python for external devices

description: Get "mounted on" in python for external devices


code:
import numpy as np
from multiprocessing import Pool

def myhdf(date):
    year    = date[0:4]
    month   = date[4:6]
    day     = date[6:8]
    rootdir = 'data/mydata/'
    filename = 'no2track'+year+month+day
    records = read_my_hdf(rootdir,filename)
    if records.size:
        return np.mean(records)

dates = ['20080105','20080106','20080107','20080108','20080109']

pool = Pool(len(dates))
results = pool.map(myhdf,dates)
results = [ result for result in results if result ]
results = np.array(results)

rawDescription: Multiprocess Python/Numpy code for processing data faster


code:
qa = session.query(ChildA)
qb = session.query(ChildB)
# @note: *qa* and *qb* may include other filters etc,
# but assuming they do not contain joins on *Parent*
subquery = qb.subquery()
qry = qa.join(Parent).join(subquery)

rawDescription: How can I join two queries on a common relationship in sqlalchemy?

description: Join two queries on a common relationship in sqlalchemy


code:
val_cols = ['val_1', 'val_2']
def minmax(data):
    mins, maxs = [], []
    for vc in val_cols:
        data= data.sort(vc)  # use sort_values() with newer Pandas version
        mins.append(pd.Series(data.iloc[0][[vc, '%s_entry' % vc]], name='min'))
        maxs.append(pd.Series(data.iloc[-1][[vc, '%s_entry' % vc]], name='max'))
    min = pd.concat(mins)
    max = pd.concat(maxs)
    return pd.DataFrame([min, max])
df.groupby('person').apply(minmax).unstack(-1)

rawDescription: Applying aggregation with multiple arguments


code:
mysets = [set([0, 1, 2]),
          set([3, 2]),
          set([4, 1]),
          set([5, 6]),
          set([7, 8])]

# Require at least one set in the output.
output = [mysets.pop(0)]

while mysets:
  test = mysets.pop(0)
  for idx, other in enumerate(output):
    if test & other:
      output[idx] |= test
      break
  else:
    output.append(test)

# output -> [set([0, 1, 2, 3, 4]), set([5, 6]), set([8, 7])]

rawDescription: What's the pythonic way to unite all the intersecting sets in a list?


code:
import urlparse
base="http://somesite.com/level1/"
path="../page.html"
urlparse.urljoin(base,path)
base="http://somesite.com/"
urlparse.urljoin(base,path)

rawDescription: urllib.urlretreive getting images, but images are broken

description: Urllib.urlretreive getting images, but images are broken


code:
import urllib.request
from tkinter import *
from tkinter.tix import *

root = Tk()
root.iconbitmap(default='icon.ico')
root.wm_title('Got Skills\' Skill Tracker')
frame = Frame(width="500",height="500")
frame.pack()
swin = ScrolledWindow(frame, width=500, height=500)
swin.pack()
win = swin.window

def show():
  name = "zezima"
  page = urllib.request.urlopen('http://hiscore.runescape.com/index_lite.ws?player=' + name)
  page = page.readlines()

  skills = []
  for line in page:
    skills.append([line.decode("utf-8").replace("\n", "").split(",")])

  skills = skills[0:25]

  for item in skills:
    toPrint = item[0][0],"-",item[0][1],"-",item[0][1]
    w = Message(win, text=' '.join(toPrint), width=500)
    w.pack()

menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="Commands", menu=filemenu)
filemenu.add_command(label="Show Skills", command=show)

root.mainloop()

rawDescription: How to add a scrollbar to a window with tkinter?

description: Add a scrollbar to a window with tkinter


code:
df
df.mean(axis=1)

rawDescription: calculating averages of multiple columns, ignoring NaN pandas numpy

description: Calculating averages of multiple columns, ignoring NaN pandas numpy


code:
wtype=np.dtype([('x',x.dtype),('y',y.dtype),('z',z.dtype)])
w=np.empty(len(x),dtype=wtype)
w['x']=x
w['y']=y
w['z']=z

rawDescription: numpy Stacking 1D arrays into structured array

description: Numpy Stacking 1D arrays into structured array


code:
class Student:

    # Constructor
    def __init__(self, name, homework, quizzes, tests):
        self.name = name
        self.homework = homework
        self.quizzes = quizzes
        self.tests = tests

    # Function to return average for this student
    def get_average(self):
        h = average(self.homework)
        ...
        return total_average

rawDescription: Working in and out of classes and functions


code:
import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')

rawDescription: Insert image in openpyxl

description: Insert image in openpyxl


code:
class RunArgs(object):
    '''
    A placeholder for processing arguments passed to program execution.
    '''

    def __init__(self):
        self.getArgs()
        #self.pause = self.args.pause  # old assignment
        self.pause = self.args[0].pause  # new assignment
        #...

    def __repr__(self):
        return "<RunArgs(t=%s, #=%s, v=%s)>" % (str(x) for x in (self.pause,self.numreads,self.verbose))

    def getArgs(self):
        global PAUSE_TIME
        global NUM_READS
        parser = argparse.ArgumentParser()
        parser.add_argument('-p', '--pause', required=False,
            type=self.checkPauseArg, action='store', default=PAUSE_TIME)
        parser.add_argument('-n', '--numreads', required=False,
            type=self.checkNumArg, action='store', default=NUM_READS)
        parser.add_argument('-v', '--verbose', required=False,
            action='store_true')
        #self.args = parser.parse_args()  # old parse call
        self.args = parser.parse_known_args()  # new parse call
        #...

rawDescription: How to use nosetests in python while also passing/accepting arguments for argparse?

description: Use nosetests in python while also passing/accepting arguments for argparse


code:
def instructions():
    print("You will be playing with an ai and whoever lays down the highest number wins that round.")
    print("The points you get are determined by how much higher your card was from your opponents card.")
    print("The person with the most points wins!")

def getUserInput():
    global roundNumber, My_Deck, PlayerPoints, AIPoints
    My_Deck = []
    roundNumber = 0
    AIPoints = 0
    PlayerPoints = 0
    print ("\nDo you want to play?: ")
    print("\nChoices")
    print("1. Yes")
    print("2. No\n")

    Choice = input()

    if(Choice == 'Yes') or (Choice == 'yes'):
        print("\nOkay, lets get started!")
        startGame()
    elif(Choice in ['No', 'no']):
        print("Okay, bye!")
        quit()
    else:
        print("That is not a Choice!")
        print("Choose 'Yes' or 'No'")
        getUserInput()

def startGame():
    global roundNumber, My_Deck, PlayerPoints, AIPoints
    print("\nAIPoints = %d PlayerPoints = %d" % (AIPoints, PlayerPoints))
    roundNumber = roundNumber + 1
    print("\nRound %d!" % (roundNumber))
    cardChoosen = None
    import random

    if(roundNumber == 1):
        print("\nHere are your 9 cards.\n")

        for Cards in range(9):
            Cards = random.randint(1, 100)
            My_Deck.append(Cards)

        while True:
            print("Select one of your cards: "),
            print(My_Deck)
            Select = int(input())
            try:
                if (Select in My_Deck):
                    My_Deck.remove(Select)
                    print("You choose", Select)
                    print("Your deck now is:")
                    print(My_Deck)
                    cardChoosen = Select
                    break
                else:
                    print("You don't have that card in your deck!")
            except ValueError as e:
                print(e)
    elif(roundNumber == 10):
        if(PlayerPoints > AIPoints):
            print("\nCongratulations you won with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
            getUserInput()
        elif(PlayerPoints < AIPoints):
            print("\nUnfortunately you lost with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
            getUserInput()
        else:
            print("\nWow this is basicaly impossible you tied with the AI with you both ahving a score of %d and %d... " % (PlayerPoints, AIPoints))
            getUserInput()
    else:
        print("\nHere are your %d cards.\n" % (9 - roundNumber + 1))

        while True:
            print("Select one of your cards: "),
            print(My_Deck)
            Select = int(input())
            try:
                if (Select in My_Deck):
                    My_Deck.remove(Select)
                    print("You choose", Select)
                    print("Your deck now is:")
                    print(My_Deck)
                    cardChoosen = Select
                    break
                else:
                    print("You don't have that card in your deck!")
            except ValueError as e:
                print(e)

    AINumber = random.randint(1, 100)

    if(cardChoosen > AINumber):
        print("\nYou won! Your number %d was higher than the AI's number %d" % (cardChoosen, AINumber))
        print("\nYou scored %d points" % (cardChoosen - AINumber))
        PlayerPoints = PlayerPoints + (cardChoosen - AINumber)
        startGame()
    elif(cardChoosen < AINumber):
        print("\nYou Lost! Your number %d was lower than the AI's number %d" % (cardChoosen, AINumber))
        print("\nAI scored %d points" % (AINumber - cardChoosen))
        AIPoints = AIPoints + (AINumber - cardChoosen)
        startGame()
    else:
        print("\nYou tied with the AI! Your number %d was the same as the AI's number %d" % (cardChoosen, AINumber))
        print("\nNobody scored points!")
        startGame()

My_Deck = []
roundNumber = 0
AIPoints = 0
PlayerPoints = 0
instructions()
getUserInput()

rawDescription: Python: CARD GAME BOT - Remastering (How do you make a line continue regardless of where it is?)


code:
import datetime
too_old = datetime.datetime.today() - datetime.timedelta(days=1)
for table in reversed(meta.sorted_tables):
    engine.execute(table.delete().where(table.c.timestampinserted <= too_old))

rawDescription: Delete all data in all tables older than period using date column


code:
from plotly.offline import plot
from plotly.graph_objs import Scatter, Box

plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], filename='/your/file/path')

rawDescription: Change the path of the offline plotly plot


code:
import scipy.stats as stats
import pandas as pd
import numpy as np

df = pd.DataFrame({'value':stats.norm.rvs(0, 1, size=1000),
           'start':np.abs(stats.norm.rvs(0, 20, size=1000))})
df['end'] = df['start'] + np.abs(stats.norm.rvs(5, 5, size=1000))

def get_value(df, target):
    value = df["value"].values
    idx = np.argsort(value)[::-1]
    start = df["start"].values[idx]
    end = df["end"].values[idx]
    value = value[idx]

    mask = (target[:, None] >= start[None, :]) & (target[:, None] <= end[None, :])
    index = np.argmax(mask, axis=1)
    flags = mask[np.arange(len(target)), index]
    result = value[index]
    result[~flags] = np.nan
    return result

get_value(df, np.arange(10, 71, 2))

rawDescription: How to efficiently join a list of values to a list of intervals?

description: Efficiently join a list of values to a list of intervals


rawDescription: Count number of files with certain extension in Python


code:
class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY)
        global castLog, count, ax1, dvls
        fig = Figure()
        canvas = FigureCanvasWxAgg(self, -1, fig)
        ax1 = fig.add_subplot(111)

        # Create empty dict that will hold new V-line Data
        castLog = { }
        dvls = [ ]
        count = 0

        # Instantiate New Vline Listener
        NVL = NewVLineListener(fig)
        NVL.connect()
        dvls.append(NVL) # This keeps NVL reference from being garbage collected?

rawDescription: Wx Matplotlib Event Handling

description: Wx Matplotlib Event Handling


rawDescription: Efficiently find indices of nearest points on non-rectangular 2D grid


rawDescription: What is an open tuple in python?

description: What is an open tuple in python


code:
def foo(x, y):
    return x*y

rawDescription: Python: understanding lambda expressions with two variables


code: pd.DataFrame(np.tile(coef, (len(df.index), 1)), columns=['Coef']*5)

rawDescription: Python/Pandas - Merging dataframe with numpy array in a peculiar way


code:
import json
from collections import OrderedDict

json_data = open('example3.json')
data = json.load(json_data, object_pairs_hook=OrderedDict)

rawDescription: Python JSON input order

description: Python JSON input order


code:
soup.find(lambda tag: tag.name == 'b' and
          "Particulate Matter" in tag.text)

rawDescription: How could I search a tag that contain <sup> in a Python beautifulsoup find() call


code: a.swapaxes(1, 2).reshape(4, 4)

rawDescription: Python/Numpy: rearrange N4xN3xN2xN1 4D array into an (N4.N2)x(N3.N1) 2D array


code: r = re.compile(r'/foo/bar(?!/)')

rawDescription: String matching in python with re

description: String matching in python with re


code:
import time
import logging

def profile(func):
    def wrap(*args, **kwargs):
        started_at = time.time()
        result = func(*args, **kwargs)
        logging.info(time.time() - started_at)
        return result

    return wrap

@profile
def foo():
    pass

rawDescription: A decorator that profiles a method call and logs the profiling result


code:
def instancer(cls):
    return cls()

@instancer
class SysProps(object):
    def __getattribute__(self, key):
        return key # dummy

rawDescription: Is there a method like '__getattribute__' for class (not instance) variables?


code: pd.merge(df1[['Gene_Id' , 'log2FoldChange', 'pvalue' , 'padj']] , df2 , left_on='Gene_Id' , right_on= 'Gene_id')

rawDescription: Annotating one dataFrame using another dataFrame, if there is matching value in column


code:
flag = False; # do this before the game loop starts

if event.type == pygame.KEYUP:
    # checking flag prevents resetting the timer
    if flag == False and event.key == pygame.K_w:
        starttime = pygame.time.get_ticks()
        ychange = -6
        flag = True

# wait 2000 milliseconds before executing this
if flag == True and pygame.time.get_ticks() - starttime >= 2000:
    ychange = 6
    flag = False

rawDescription: How to make a delay in a keypress in pygame?

description: Make a delay in a keypress in pygame


rawDescription: How do I add my project to 'sys.path' on windows? (trying to use disqus_export.py)

description: Add my project to 'sys.path' on windows? (trying to use disqus_export.py)


code:
from tkinter import *

root = Tk()
root.withdraw()

filedialog.askopenfile()

rawDescription: Python 3.3 tkinter.filedialog.askopenfile() leaves an unresponsive Tk window


code:
a = numpy.random.random((10, 10))
numpy.unravel_index(a.argmax(), a.shape)
a[6, 7] == a.max()

rawDescription: Argmax of numpy array returning non-flat indices


code:
import serial
s = serial.Serial(port='/dev/tty.usbmodemfa141', baudrate=9600)

s.write('text')
s.read()
s.readline()

rawDescription: Python + Arduino with Mac OS X

description: Python + Arduino with Mac OS X


code:
from ftplib import FTP
import os

ftp = FTP()
ftp.connect(server, port)
ftp.login(user, pwd)

files = ftp.nlst() # get a list of files on the server
# decide which file we want

fn = 'test.py' # filename on server and for local storage
d = 'c:/temp/' # local directory to store file
path = os.path.join(d,fn)
r = ftp.retrbinary('RETR %s' % fn, open(path, 'wb').write)
print(r) # should be: 226 Transfer OK

f = open(path, 'rb') # send file at path
r = ftp.storbinary('STOR %s' % fn, f) # call it fn on server
print(r) # should be: 226 Transfer OK
f.close()

ftp.quit()

rawDescription: Simple file transfer over wifi between computer and mobile phone using python


code:
from sys import stdout

def error(string, is_tty=stdout.isatty()):
    return ('\033[31;1m' + string + '\033[0m') if is_tty else string

def standout(string, is_tty=stdout.isatty()):
    return ('\033[34;1m' + string + '\033[0m') if is_tty else string

rawDescription: Printing to STDOUT and log file while removing ANSI color codes


code:
class Foo:
    """A class for foo-ing bazs.

    Args:
      baz: the baz to foo

    Attributes:
      bar: we keep the baz around

    """

    def __init__(self, baz):
        self.bar = baz

rawDescription: How to properly declare instance fields in Python

description: Properly declare instance fields in Python


code:
import random
num = random.randint(0, 4)
context['showItem'] = True if num <= 1 else False

rawDescription: Python: How to make a variable true 40% of the time


code:
lastSubplot = plt.subplot(subcol,subrow,subcol*subrow)
lastSubplot.set_frame_on(False)
lastSubplot.get_xaxis().set_visible(False)
lastSubplot.get_yaxis().set_visible(False)
plt.plot(0, 0, marker='o', color='r', label = 'line1')
plt.plot(0, 0, marker='o', color='b', label = 'line2')
lastSubplot.legend(loc = 'lower right')

rawDescription: Adding a legend outside of multiple subplots with matplotlib


code:
import Tkinter as tk
import ttk

class ConstrainedEntry(ttk.Entry):
    def __init__(self, *args, **kwargs):
        ttk.Entry.__init__(self, *args, **kwargs)

        vcmd = (self.register(self.on_validate),"%P")
        self.configure(validate="key", validatecommand=vcmd)

    def disallow(self):
        self.bell()

    def on_validate(self, new_value):
        try:
            if new_value.strip() == "": return True
            value = int(new_value)
            if value < 0 or value > 999:
                self.disallow()
                return False
        except ValueError:
            self.disallow()
            return False

        return True

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        l = ttk.Label(self, text="Enter a number between 0 and 999:", anchor="w")
        e = ConstrainedEntry(self, width=4)
        l.pack(side="top")
        e.pack(side="top")

root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()

rawDescription: Set maximum length of data in ttk.entry and limit to integer only


code: user_id = self.request.user.id

rawDescription: Retrieve Current User in Django Outside Template


code:
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

rawDescription: How to read csv into record array in numpy?

description: Read csv into record array in numpy


code:
# google/appengine/ext/ndb/model.py:1711

class UserProperty(Property):
  """A Property whose value is a User object.

  Note: this exists for backwards compatibility with existing
  datastore schemas only; we do not recommend storing User objects
  directly in the datastore, but instead recommend storing the
  user.user_id() value.
  """

rawDescription: Storing User Objects in Google App Engine


rawDescription: Removing first x characters from string?

description: Removing first x characters from string


code:
from pymongo import UpdateOne
from mongoengine import Document, ValidationError

class Foo(Document):
    ...

bulk_operations = []

for entity in entities:
    try:
        entity.validate()
        bulk_operations.append(
            UpdateOne({'_id': entity.id}, {'$set': entity.to_mongo().to_dict()}))

    except ValidationError:
        pass

if bulk_operations:
    collection = Foo._get_collection() \
        .bulk_write(bulk_operations, ordered=False)

rawDescription: Mongoengine bulk update without objects.update()


code:
def contact(request):
    if request.method == 'POST':
        form = contact_form(data=request.POST)
        if form.is_valid():
            ...
    else:
        form = contact_form() # An unbound form
        return render_to_response('contact.html', {'form' : form}, context_instance=RequestContext(request))

rawDescription: Form not generated by template

description: Form not generated by template


code:
def SUBS(path, parent):
    for p in os.listdir(path):
        abspath = os.path.join(path, p)
        parent_element = tree.insert(parent, 'end', text=p, open=True)
        if os.path.isdir(abspath):
            SUBS(abspath, parent_element)

path = "C:/"
WinT = Tk()
tree = ttk.Treeview(WinT ,height=15)
tree.pack(expand=YES,fill=BOTH)
tree.heading("#0" ,text="Directory")
root = tree.insert('', 'end', text=path, open=True)
SUBS(path, root)
WinT.mainloop()

rawDescription: Tree tk (file explorer)

description: Tree tk (file explorer)


code:
def scrabble_score(word,score): # score doesn't need to be global
    total = 0
    t = word.lower()
    for key in t:
        total += score[key]
    return total

x = raw_input("Enter word: ")
# declare what score is here
print(srabble_score(x,score))

rawDescription: Trouble understanding where a variable is defined


code:
from bs4 import BeautifulSoup
from urllib.request import urlopen
bs = BeautifulSoup(urlopen('http://www.samair.ru/proxy/ip-address-01.htm'))
print(bs.find('pre').text)
[l.split()[0] for l in bs.find('pre').text.split('\n')[1:]][1:]

rawDescription: how to extract info out of a column in a table in a website?

description: Extract info out of a column in a table in a website


code:
def visible_cb(self, model, iter, data):
    return model.iter_has_child(iter) or data.lower() in model.get_value(iter, 0).lower()

rawDescription: Filtering treeview content recursively

description: Filtering treeview content recursively


code: value = [v[0] - v[1] for v in value]

rawDescription: How would I accomplish this with nested list comprehension?


code:
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8

rawDescription: How do I treat an integer as an array of bytes in Python?

description: Treat an integer as an array of bytes in Python


code:
import re

def lookup(d, s):
  mo = re.match(r"\['([a-z]+)'\]\['([a-z]+)'\]", s)
  if mo and len(mo.groups()) == 2:
    return d[mo.group(1)][mo.group(2)]
  return None

rawDescription: How to get a value within a dictionary within a dictionary with just a string?

description: Get a value within a dictionary within a dictionary with just a string


code:
df
df["COL3"] = df["COL1"].fillna(df["COL2"])
df

rawDescription: Pandas Use Value if Not Null, Else Use Value From Next Column


code:
joined_string = "".join(testbuf for index in range(1000))
# or building the list of strings to join separately
strings = []
for i in range(1000):
    strings.append(testbuf)
joined_string = "".join(strings)

rawDescription: Python cStringIO take more time than StringIO in writing (performance of string methods)


code:
import urllib2
import shutil

headers = {'User-Agent': 'Mozilla'}
urlfile = "http://www.equibase.com/premium/eqbLateChangeXMLDownload.cfm"

request = urllib2.Request(urlfile, headers=headers)
response = urllib2.urlopen(request)
with open("c:\\test.xml", 'wb') as outfile:
    shutil.copyfileobj(response, outfile)

rawDescription: How Can I download this XML file from given URL

description: Download this XML file from given URL


code:
import random
random.choice (mylist)

rawDescription: How do I select a random element from an array in Python?

description: Select a random element from an array in Python


code:
import random
ranking = [0] * 10
for _ in range(100):
    ranking[(random.randint(1, 100) - 1) // 10] += 1

ranking

rawDescription: Python - making a histogram with ranges every 10


code:
from werkzeug._compat import BytesIO

filename = data = None
if file_upload.filename is None:
    data = file_upload.read()  # in-memory stream, so read it out.
else:
    filename = file_upload.filename

rawDescription: Python3 Flask upload file in server memory


rawDescription: Retrieve UNIX TIMESTAMP in django api call


code:
from gevent import monkey
monkey.patch_all()
import bottle
import urllib2

@bottle.route(...)
def callback():
   urllib2.open(...)

bottle.run(server='gevent')

rawDescription: Python gevent+bottle. Querying an API. How to use gevent to prevent timeout locks?


code:
from collections import defaultdict

animals = defaultdict(list)

for p in infile:
    animals[p[0]].append(p[1])

rawDescription: python 3 csv data structure problems

description: Python 3 csv data structure problems


code:
from datetime import date

from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter

class IsClosedFilter(SimpleListFilter):
    title = _('Closed')

    parameter_name = 'closed'

    def lookups(self, request, model_admin):
        return (
            (None, _('No')),
            ('yes', _('Yes')),
            ('all', _('All')),
        )

    def choices(self, cl):
        for lookup, title in self.lookup_choices:
            yield {
                'selected': self.value() == lookup,
                'query_string': cl.get_query_string({
                    self.parameter_name: lookup,
                }, []),
                'display': title,
            }

    def queryset(self, request, queryset):
        if self.value() == 'closed':
            return queryset.filter(isClosed=True)
        elif self.value() == None:
            return queryset.filter(isClosed=False)

class Admin(admin.ModelAdmin):
    list_filter = [isClosedFilter]

rawDescription: Default filter in admin site

description: Default filter in admin site


code:
def cmd1(event):
    print("Command One")
    event.cmdRegion.stopObserver()
    waitCmdAppear()

def cmd2(event):
    print("Command Two")
    event.cmdRegion.stopObserver()
    waitCmdAppear()

def cmd3(event):
    print("Command Three")
    event.cmdRegion.stopObserver()
    waitCmdAppear()

def waitCmdAppear():
    cmdRegion.onAppear(Pattern("1.png").exact(), cmd1)
    cmdRegion.onAppear(Pattern("2.png").exact(), cmd2)
    cmdRegion.onAppear(Pattern("3.png").exact(), cmd3)
    cmdRegion.observe(FOREVER)

waitCmdAppear()

rawDescription: Python - Code ignores `if`-statement?

description: Python - Code ignores `if`-statement


code:
#! /usr/bin/python3

class Character:
        class AbilityScoreOutOfBoundsException (Exception): pass

        def __init__ (self, name):
            self.name = name
            self.stats = {k: 1 for k in ['STR', 'DEX', 'WIS', 'INT'] }

        @property
        def strength (self): return self.stats ['STR']

        @property
        def dexterity (self): return self.stats ['DEX']

        @property
        def wisdom (self): return self.stats ['WIS']

        @property
        def intelligence (self): return self.stats ['INT']

        @strength.setter
        def strength (self, amount): self.setStat ('STR', amount)

        @wisdom.setter
        def wisdom (self, amount): self.setStat ('WIS', amount)

        @dexterity.setter
        def dexterity (self, amount): self.setStat ('DEX', amount)

        @intelligence.setter
        def intelligence (self, amount): self.setStat ('INT', amount)

        def setStat (self, which, amount):
            if amount < 1: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou wert about to smite thyself.')
            if self.total + amount - self.stats [which] > 30: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou shalt not grow too mighty.')
            self.stats [which] = amount

        @property
        def total (self): return sum (self.stats.values () )

        def __repr__ (self):
            return '{}\n{}'.format (self.name, '\n'.join ('{}{:>4}'.format (which, self.stats [which] ) for which in ['STR', 'DEX', 'WIS', 'INT'] ) )

a = Character ('Daggeroth')
a.strength += 9
a.dexterity += 9
a.wisdom += 5
a.intelligence += 3
print (a)

rawDescription: Dictionary vs Variable

description: Dictionary vs Variable


code:
def func(self, args):
    defaultargs = (1, 2, 3)
    args = tuple(map(lambda x, y: y if y is not None else x, defaultargs, args))

rawDescription: Python default values for tuple in function arguments


code:
#!/usr/bin/python
from subprocess import Popen, PIPE, call

cat = Popen("cat", stdin=PIPE)
for line in ["First line", "Last line"]:
    call(["echo", line], stdout=cat.stdin)
cat.communicate() # close stdin, wait

rawDescription: How to concatenate the output of several processes into the input of another?

description: Concatenate the output of several processes into the input of another


code:
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})

rawDescription: Can I use Django's template language to construct HTML for use in a JSON response field?

description: Use Django's template language to construct HTML for use in a JSON response field


code:
import psycopg2
conn = psycopg2.connect(database='postgis', user='postgres')
curs = conn.cursor()

# Find the distance within 1 km of point-of-interest
poi = (-124.3, 53.2)  # longitude, latitude

# Table 'my_points' has a geography column 'geog'
curs.execute("""\
SELECT gid, ST_AsGeoJSON(geog), ST_Distance(geog, poi)
FROM my_points, (SELECT ST_MakePoint(%s, %s)::geography AS poi) AS f
WHERE ST_DWithin(geog, poi, 1000);""", poi)

for row in curs.fetchall():
    print(row)

rawDescription: Using PostGIS on Python 3

description: Using PostGIS on Python 3


code:
return render_to_response('my_template.html',
                      my_data_dictionary,
                      context_instance=RequestContext(request))

rawDescription: Incluing csrf context inside of every render_to_response?


code:
def estimated_autocorrelation(x):
    """
    http://stackoverflow.com/q/14297012/190597
    http://en.wikipedia.org/wiki/Autocorrelation#Estimation
    """
    n = len(x)
    variance = x.var()
    x = x-x.mean()
    r = np.correlate(x, x, mode = 'full')[-n:]
    assert np.allclose(r, np.array([(x[:n-k]*x[-(n-k):]).sum() for k in range(n)]))
    result = r/(variance*(np.arange(n, 0, -1)))
    return result

rawDescription: Estimate Autocorrelation using Python

description: Estimate Autocorrelation using Python


code:
block_1 = [
    [1, 6, 11],
    [2, 7, 12],
    [3, 8, 13],
    [4, 9, 14],
    [5, 10, 15]
]

block_2 = [
    [17, 22, 27],
    [18, 23, 28],
    [19, 24, 29],
    [20, 25, 30],
    [21, 26, 31]
]

all_numbers = []

new_block = []

rows = len(block_1) # Since the column length is the same.
                    # Either block_1 or block_2 works here.

# Get all numbers and sort.
for row in block_1:
    all_numbers.extend(row)

for row in block_2:
    all_numbers.extend(row)

all_numbers.sort()

# Build the matrix.
matrix = []
for i in range(0, len(all_numbers), rows):
    matrix.append(all_numbers[i:i+rows])

# Set the correct place for collumns.
for i in range(len(matrix[0])):
    r = []
    for j in range(len(matrix)):
        r.append(matrix[j][i])
    new_block.append(r)

print(new_block)

rawDescription: Arrange a list of multiple columns into a matrix in Python


code:
import sys
import re
import csv
import os

searchdata = open("c:\\dev\\in\\1.txt", "r")
# Certfile = csv.writer(open('c:\\dev\\Certfile.csv', 'ab'), delimiter=',') #moved to later to ensure the file will be closed

lines = open("c:\\dev\\in\\2.txt", 'r')
pats = []   # An array of patterns
for line in lines:
    line.rstrip()
    lines.seek(0)
    # Add additional conditioning/escaping of input here.
    for nam in lines:
         pats.append(re.compile(nam))

with open('c:\\dev\\Certfile.csv', 'ab') as outfile:    #This line opens the file
    Certfile = csv.writer(outfile, delimiter=',')       #This line interprets the output into CSV
    for f in searchdata.readlines():
        for pat in pats:    #A loop for processing all of the patterns
            if pat.search(f) is not None:
                fields = f.strip().split(',')
                Certfile.writerow([pat.pattern, fields[3], fields[4]])
lines.close()
searchdata.close()

rawDescription: Python - Calling lines from a text file to compile a pattern search of a second file


code:
from Tkinter import *
import math

master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
x1=0
y1=0
x2=100
y2=100
delta=10
i=w.create_line(x1, y1, x2, y2)

def click(event):
# event.x is the x coordinate and event.y is the y coordinate of the mouse
    D = math.fabs((event.y-event.x))/math.sqrt(2)
    if D < delta and x1 - delta < event.x < x2 + delta:
            w.delete(i)
w.bind("<Button-1>", click)

mainloop()

rawDescription: How To Delete Previously Drawn Line With a Mouse Click in Python?


code:
import os
import sys

CWDPATH = os.path.abspath(os.path.dirname(sys.argv[0]))

rawDescription: How do I get compiled python(with cxFreeze) to get the current working directory as the directory where the executable is in?

description: Get compiled python(with cxFreeze) to get the current working directory as the directory where the executable is in


code:
import numpy as np
from matplotlib import pyplot as pp
from scipy.misc import lena

# some 'intensity' data, normalized between 0 and 1
intensity = lena().astype(np.float32)
intensity = (intensity - intensity.min()) / (intensity.max() - intensity.min())

# some 'spectrum' data, normalized between 0 and 1
x,y = np.mgrid[-1:1:intensity.shape[0]*1j,-1:1:intensity.shape[1]*1j]
spectrum = 0.5*(np.sin(20*(x**2 + y**2)) + 1)

# look up RGB values from the 'jet' colormap
RGBA = pp.cm.jet(spectrum)
# fill the A(lpha) channel with the array of intensity data
RGBA[...,3] = intensity

# another way to represent spectral and intensity data is using a 2D
# HSV color space
HSV = np.ones(intensity.shape + (3,))

# we represent the spectral information using hue...
HSV[...,0] = spectrum
# ... and the intensity data as brightness and saturation
HSV[...,1] = intensity
HSV[...,2] = intensity
# convert back into rgb color space
HSV = matplotlib.colors.hsv_to_rgb(HSV)

# plotting
fig, ax = pp.subplots(2, 2, figsize=(10,10), sharex=True, sharey=True)
ax[0,0].imshow(intensity, cmap=pp.cm.gray)
ax[0,0].set_title('Intensity data', fontsize=14)
ax[0,1].imshow(spectrum, cmap=pp.cm.gray)
ax[0,1].set_title('Spectral data', fontsize=14)
ax[1,0].imshow(RGBA)
ax[1,0].set_title('Jet with varying alpha', fontsize=14)
ax[1,1].imshow(HSV)
ax[1,1].set_title('HSV', fontsize=14)
for aa in ax.flat:
    aa.set_axis_bgcolor((0,0,0,1))
    aa.xaxis.set_visible(False)
    aa.yaxis.set_visible(False)
fig.tight_layout()

pp.show()

rawDescription: Matplotlib: Colorize grayscale image using another image


code:
import sqlite3 as db
from PyQt4 import QtCore, QtGui
import sys

con = db.connect('results.db', isolation_level=None)
cur = con.cursor()
cur.execute("SELECT * FROM Results")
all_data = cur.fetchall()

class UiDialog(object):
    def setupUi(self, datadb):
        datadb.setObjectName("Dialog")
        datadb.resize(404, 304)
        datadb.setWindowTitle("Database results")
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(datadb.sizePolicy().hasHeightForWidth())
        datadb.setSizePolicy(sizePolicy)
        datadb.setMinimumSize(QtCore.QSize(404, 304))
        datadb.setMaximumSize(QtCore.QSize(404, 304))
        self.table = QtGui.QTableWidget(datadb)
        self.table.setGeometry(QtCore.QRect(2, 2, 400, 261))
        self.table.setObjectName("table")
        self.show = QtGui.QPushButton(datadb)
        self.show.setGeometry(QtCore.QRect(2, 270, 400, 31))
        self.show.setObjectName("show")
        self.show.setText("Show results")
        QtCore.QObject.connect(self.show, QtCore.SIGNAL("clicked()"), self.populate)
        QtCore.QMetaObject.connectSlotsByName(datadb)
        self.table.itemChanged.connect(self.updateDB)

    def populate(self):
        self.table.blockSignals(True)
        #all_data = [["1","2","3","4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"]]
        self.table.setRowCount(len(all_data))
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(['Number', 'Keys', 'Time', 'Tries'])
        for i, item in enumerate(all_data):
            number = QtGui.QTableWidgetItem(str(item[0]))
            #if we need old data then
            number.setData(QtCore.Qt.UserRole,QtCore.QVariant(str(str(item[0]))))
            keys = QtGui.QTableWidgetItem(item[1])
            keys.setData(QtCore.Qt.UserRole,QtCore.QVariant(str(str(item[1]))))
            time = QtGui.QTableWidgetItem(str(item[2]))
            time.setData(QtCore.Qt.UserRole,QtCore.QVariant(str(str(item[2]))))
            tries = QtGui.QTableWidgetItem(str(item[3]))
            tries.setData(QtCore.Qt.UserRole,QtCore.QVariant(str(str(item[3]))))
            self.table.setItem(i, 0, number)
            self.table.setItem(i, 1, keys)
            self.table.setItem(i, 2, time)
            self.table.setItem(i, 3, tries)
        self.table.blockSignals(False)

    def updateDB(self, itmWid):
        updatedVal = str(itmWid.text())
        oldValue = itmWid.data(QtCore.Qt.UserRole).toString()
        with con:
            cur.execute("UPDATE Results SET Number='%s' WHERE Number='%s'" % (updatedVal, oldValue))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main_conf = QtGui.QDialog()
    ui = UiDialog()
    ui.setupUi(main_conf)
    main_conf.show()
    ret = app.exec_()
    sys.exit(ret)

rawDescription: Python PyQT4 Simple database GUI

description: Python PyQT4 Simple database GUI


rawDescription: Python - Why is my list turning into a tuple when passing it to a method with varargs (keywordonly)


code:
import types
listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType]

rawDescription: List all the classes that currently exist


code:
categories = [item.category for item in my_list]
my_list.sort(key = lambda item: categories.index(item.category))

rawDescription: Sort by grouping using first occurence in python?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

freqs = np.arange(2, 20, 3)

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = plt.plot(t, s, lw=2)

class Index(object):
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

callback = Index()
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()

rawDescription: Image tabs with OpenCV or Matplotlib

description: Image tabs with OpenCV or Matplotlib


code:
from tkinter import *
import sys
from tkinter.scrolledtext import ScrolledText

#Setup GUI

#Create main window
main = Tk()
#Create title of main window
main.title = "Waterizer 1.0"
#Create default size of main window
main.geometry("1024x768")
#Lets get a fram to stick the data in we plan on using
mainApp = Frame(main)
#Snap to grid
mainApp.grid(row=0, column=0, sticky='nsew')
#main grid stretching properties
main.grid_columnconfigure(0, weight=1)
main.grid_rowconfigure(0, weight=1)
#Font for main labels
labelFont = ('times', 20, 'bold')
#Label for the Power
powerLabel = Label(mainApp, text="Power  Status")
powerLabel.config(fg="Red", bd="1")
powerLabel.config(font=labelFont)
powerLabel.grid( row=0,column=20, sticky = W)
#Label for Water
waterLabel = Label(mainApp, text="Water Status")
waterLabel.config(fg="Blue", bd="1")
waterLabel.config(font=labelFont)
waterLabel.grid(row=20, column=20, sticky = W)
#ScrollText to fill in between space
ScrollText = ScrolledText(mainApp)
ScrollText.grid(row=1, column=20,sticky = 'nsew')
#mainApp grid stretching properties
mainApp.grid_rowconfigure(1, weight=1)
mainApp.grid_columnconfigure(20, weight=1)

main.mainloop()

rawDescription: Tkinter grid() alignment issue in python


code:
while True:
    print('Please type your name.')
    name = input()
    if name == 'Mahmoud':
        break
    print('Please try again')
print('Thank you!')

rawDescription: Is there a use of break statement in python?


code:
x = np.array([1000,2000])
data1 = np.array([np.random.normal(loc=0.5,size=100),np.random.normal(loc=1.5,size=100)]).T
data2 = np.array([np.random.normal(loc=2.5,size=100),np.random.normal(loc=0.75,size=100)]).T
plt.figure()
plt.boxplot(data1,0,'',positions=x-100,widths=150)
plt.boxplot(data2,0,'',positions=x+100,widths=150)
plt.xlim(500,2500)
plt.xticks(x)
plt.show()

rawDescription: Creating double boxplots- i.e two boxes for each x-value


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

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap, extent=extent)
plt.show()

rawDescription: Generate a heatmap in MatPlotLib using a scatter data set


code:
start_date = datetime.date(2005, 8, 9)
end_date = datetime.date(2005, 8, 11)
Model.objects.filter(name__icontains="hello").filter(date__range(start_date,end_date))

rawDescription: Django-models. Complex request to database


rawDescription: How to match non-printable characters in a python regular expression?

description: Match non-printable characters in a python regular expression


code:
import subprocess
ffmpeg_command1 = ["ffmpeg", "-i", "/home/xincoz/test/connect.webm", "-acodec", "copy", "-ss", "00:00:00", "-t", "00:00:30", "/home/xincoz/test/output1.webm"]
ffmpeg_command2 = ["ffmpeg", "-i", "/home/xincoz/test/connect.webm", "-acodec", "copy", "-ss", "00:00:30", "-t", "00:00:30", "/home/xincoz/test/output2.webm"]
ffmpeg_command3 = ["mencoder", "-forceidx", "-ovc", "copy", "-oac", "pcm", "-o", "/home/xincoz/test/output.webm", "/home/xincoz/test/output1.webm", "/home/xincoz/test/output2.webm"]

subprocess.call(ffmpeg_command1)
subprocess.call(ffmpeg_command2)
subprocess.Popen(ffmpeg_command3)

rawDescription: How to join two video files using Python?

description: Join two video files using Python


code:
import time
import threading

def test_run():
    time.sleep(5)

def run_update():
    with Update():
        test_run()

class Update(object):
    def __init__(self):
        pass
    def __enter__(self):
        print('enter')
    def __exit__(self, *_):
        print('exit')

if __name__ == "__main__":
    th = threading.Thread(target=run_update)
    th.start()
    for i in range(100):
        print(i)

rawDescription: Context Manager thread safe

description: Context Manager thread safe


code:
from scipy import sparse
xys=[(1,2),(3,4),(6,9),(7,3)]

coords = zip(*xys)
mask = sparse.coo_matrix((numpy.ones(len(coords[0])), coords ), shape= master_array.shape, dtype=bool)
draws=numpy.random.choice( master_array[~mask.toarray()].flatten(), size=10)

rawDescription: numpy create 2D mask from list of indices [+ then draw from masked array]

description: Numpy create 2D mask from list of indices [+ then draw from masked array]


code:
from news.models import Comment as NewsComment
from article.models import Comment as ArticleComment

...

NewsComment.objects.filter(author=someauthor).delete()
ArticleComment.objects.filter(author=someauthor).delete()

rawDescription: How to delete objects from two apps with the same model name?

description: Delete objects from two apps with the same model name


code:
import wx

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Show Caret Position", size=(400, 140))
        panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        text = wx.StaticText(panel, -1, "Text:", (10, 22))
        self.textCtrl = wx.TextCtrl(
                panel,
                -1, "",
                (50,5),
                size=(250, 50),
                style=wx.TE_MULTILINE
            )
        self.textCtrl.SetInsertionPoint(0)
        self.textCtrl.Bind(wx.EVT_KEY_UP,self.onTextKeyEvent)
        self.textCtrl.Bind(wx.EVT_LEFT_UP,self.onTextKeyEvent)
        self.statusbar = self.CreateStatusBar(1)
        panel.SetSizerAndFit(sizer, wx.VERTICAL)

    def onTextKeyEvent(self, event):
        statusText = "Caret Position: "+str(self.textCtrl.GetInsertionPoint())
        self.SetStatusText(statusText,0)
        event.Skip()

#Run application
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython caret move event

description: WxPython caret move event


code:
class my_lil_matrix(sparse.lil_matrix):
    def __init__(self, *args, **kwargs):
        if len(args) >= 2 and isinstance(args[1], list):
            try:
                data, rows = args
            except:
                raise TypeError("Invalid input format")

            if kwargs.get('shape') is None:
                # Column count will just be the largest value in rows
                M, N = (len(rows), max(np.array(rows).max()) + 1)
            else:
                M, N = shape

            super(my_lil_matrix, self).__init__((M, N), **kwargs)

            self.data = np.array(data, copy=kwargs.get('copy'),
                                 dtype=kwargs.get('dtype'))
            self.rows = np.array(rows, copy=kwargs.get('copy'),
                                 dtype=kwargs.get('dtype'))
        else:
            super(my_lil_matrix, self).__init__(*args, **kwargs)

rawDescription: Initialize lil_matrix given data and coordinates


code:
bodies += [fill(stats['coords'],
                            -vals + pos,
                            vals + pos,
                            facecolor='y',
                            alpha=0.3)]
(...)
artists['cmeans'] = perp_lines(means, pmins, pmaxes, colors='r')

rawDescription: Matplotlib's violinplot doesn't follow rcParam


rawDescription: Replace special characters in a file with their unicode code (Python)


code:
from itertools import groupby
from operator import itemgetter

res = {key: sum(t[1] for t in group)
       for key, group in groupby(sorted(data, key=itemgetter(0)), key=itemgetter(0))}

rawDescription: Is it possible to access current object while doing list/dict comprehension in Python?


code: tuple([] for _ in range(list_length))

rawDescription: Initialising an n-length tuple of lists

description: Initialising an n-length tuple of lists


code:
class SuperFoo(models.Model):
    name = models.CharField('name of SuperFoo instance', max_length=50)
    ...

class Foo(SuperFoo):
    ... # do something that changes verbose_name of name field of SuperFoo
Foo._meta.get_field('name').verbose_name = 'Whatever'

rawDescription: how to override the verbose name of a superclass model field in django

description: Override the verbose name of a superclass model field in django


code: p = soup.find(text="Annual Report Expense Ratio (net):").parent.next_sibling.string

rawDescription: Beautifulsoup: Retrieve specific value in table


code:
class PopUp_Window(QWidget):
    def __init__(self, parent):
        self.parent = parent
        self.accepted = False
        self.accept_button.clicked.connect(self.on_accept)

    def on_accept(self):
        self.accepted = True
        self.close()

    def closeEvent(self, event):
        if self.accepted:
            event.accept()
        else:
            event.ignore()

rawDescription: Handling closeEvent accept/ignore

description: Handling closeEvent accept/ignore


code:
identifiers = soup.find_all(attrs={'class': "identifier"})
descriptions = soup.find_all(attrs={'class': "description"})

for identifier, description in zip(identifiers, descriptions):
    print(identifier.getText(), description.getText())

rawDescription: How to print multiple values from BeautifulSoup with Python

description: Print multiple values from BeautifulSoup with Python


code: from PYTHON_MODULE_FILE import *

rawDescription: How can I include a variable to a module

description: Include a variable to a module


rawDescription: Python Dot-Product with Matrix-elements

description: Python Dot-Product with Matrix-elements


code:
from shapely import wkt
poly = wkt.loads('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))')
pt = wkt.loads('POINT(20 20)')

# The point is in the polygon, so the distance will always be 0.0
poly.distance(pt)  # 0.0

# The distance is calculated to the nearest boundary
poly.boundary.distance(pt)  # 4.47213595499958

# or exterior ring
poly.exterior.distance(pt)  # 4.47213595499958

rawDescription: distance from point to polygon (when inside)

description: Distance from point to polygon (when inside)


code:
parts_set = car.parts_set.exclude(pk=new_part.pk)
price_qs = Price.objects.all()
for part in parts_set:
    price_qs = price_qs.filter(excluded_parts=part)

rawDescription: Django filter __contains=queryset?

description: Django filter __contains=queryset


code:
client.post('/tracks/%d/comments' % track.id, comment={
    'body': 'This is a timed comment'
})

rawDescription: Is there a way to comment on a track using Soundcloud Python?


code: result = getattr(myclient.service, 'some_method')(...)

rawDescription: Invoke an run-time SOAP method via Python/SUDS


code:
def save_cookies(driver, file_path):
    LINE = "document.cookie = '{name}={value}; path={path}; domain={domain}; expires={expires}';\n"
    with open(file_path, 'w') as file :
        for cookie in driver.get_cookies() :
            file.write(LINE.format(**cookie))

def load_cookies(driver, file_path):
    with open(file_path, 'r') as file:
        driver.execute_script(file.read())

from selenium import webdriver

driver = webdriver.PhantomJS()

# load the domain
driver.get("https://stackoverflow.com/users/login")

# save the cookies to a file
save_cookies(driver, r"cookies.js")

# delete all the cookies
driver.delete_all_cookies()

# load the cookies from the file
load_cookies(driver, r"cookies.js")

rawDescription: Adding Cookies working with Firefox webdriver but not in PhantomJS


code:
year = 2013
days = [datetime.datetime(year, 1, 1) + datetime.timedelta(days=i) for i in range(366)]
days = [day for day in days if day.year == year and day.weekday() in (0, 5)]
formatted = [day.strftime("%Y-%m-%d") for day in days]
len(formatted)
formatted[:10]

rawDescription: Matrix of the entire year in calendar module