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

class Neuralnet:
    def __init__(self, neurons, activation):
        self.weights = []
        self.inputs = []
        self.outputs = []
        self.errors = []
        self.rate = 0.2
        self.activation = activation    #sigmoid or tanh

        self.neurons = neurons
        self.L = len(self.neurons)      #number of layers

        eps = 0.12;    #range for uniform distribution   -eps..+eps
        for layer in range(len(neurons)-1):
            self.weights.append(np.random.uniform(-eps,eps,size=(neurons[layer+1], neurons[layer]+1)))

    ###################################################################################################
    def train(self, X, Y, iter_count):

        m = X.shape[0];

        for layer in range(self.L):
            self.inputs.append(np.empty([m, self.neurons[layer]]))
            self.errors.append(np.empty([m, self.neurons[layer]]))

            if (layer < self.L -1):
                self.outputs.append(np.empty([m, self.neurons[layer]+1]))
            else:
                self.outputs.append(np.empty([m, self.neurons[layer]]))

        #accumulate the cost function
        J_history = np.zeros([iter_count, 1])

        for i in range(iter_count):

            self.feedforward(X)

            J = self.cost(Y, self.outputs[self.L-1])
            J_history[i, 0] = J

            self.backpropagate(Y)

        #plot the cost function to check the descent
        #plt.plot(J_history)
        #plt.show()

    ###################################################################################################
    def cost(self, Y, H):
        J = np.sum(np.sum(np.power((Y - H), 2), axis=0))/(2*m)
        return J

    ###################################################################################################
    def cost_online(self, min_x, max_x, iter_number):
        h_arr = np.zeros([iter_number, 1])
        y_arr = np.zeros([iter_number, 1])

        for step in range(iter_number):
            x = np.random.uniform(min_x, max_x, 1).reshape(1, 1)

            self.feedforward(x)
            h_arr[step, 0] = self.outputs[-1]
            y_arr[step, 0] = np.sin(x)

        J = np.sum(np.sum(np.power((y_arr - h_arr), 2), axis=0))/(2*iter_number)
        return J

    ###################################################################################################
    def feedforward(self, X):

        m = X.shape[0];

        self.outputs[0] = np.concatenate(  (np.ones([m, 1]),   X),   axis=1)

        for i in range(1, self.L):
            self.inputs[i] = np.dot( self.outputs[i-1], self.weights[i-1].T  )

            if (self.activation == 'sigmoid'):
                output_temp = self.sigmoid(self.inputs[i])
            elif (self.activation == 'tanh'):
                output_temp = np.tanh(self.inputs[i])

            if (i < self.L - 1):
                self.outputs[i] = np.concatenate(  (np.ones([m, 1]),   output_temp),   axis=1)
            else:
                self.outputs[i] = output_temp

    ###################################################################################################
    def backpropagate(self, Y):

        self.errors[self.L-1] = self.outputs[self.L-1] - Y

        for i in range(self.L - 2, 0, -1):

            if (self.activation == 'sigmoid'):
                self.errors[i] = np.dot(  self.errors[i+1],   self.weights[i][:, 1:]  ) *  self.sigmoid_prime(self.inputs[i])
            elif (self.activation == 'tanh'):
                self.errors[i] = np.dot(  self.errors[i+1],   self.weights[i][:, 1:]  ) *  (1 - self.outputs[i][:, 1:]*self.outputs[i][:, 1:])

        for i in range(0, self.L-1):
            grad = np.dot(self.errors[i+1].T, self.outputs[i]) / m
            self.weights[i] = self.weights[i] - self.rate*grad

    ###################################################################################################
    def sigmoid(self, z):
        s = 1.0/(1.0 + np.exp(-z))
        return s

    ###################################################################################################
    def sigmoid_prime(self, z):
        s = self.sigmoid(z)*(1 - self.sigmoid(z))
        return s

    ###################################################################################################
    def predict(self, X, weights):

        m = X.shape[0];

        self.inputs = []
        self.outputs = []
        self.weights = weights

        for layer in range(self.L):
            self.inputs.append(np.empty([m, self.neurons[layer]]))

            if (layer < self.L -1):
                self.outputs.append(np.empty([m, self.neurons[layer]+1]))
            else:
                self.outputs.append(np.empty([m, self.neurons[layer]]))

        self.feedforward(X)

        return self.outputs[self.L-1]

###################################################################################################
#                MAIN PART

activation1 = 'sigmoid'     #the input should be scaled into [0..1]
activation2 = 'tanh'        #the input should be scaled into [-1..1]

activation = activation1

net = Neuralnet([1, 6, 1], activation) # structure of the NN and its activation function

method1 = 'online'
method2 = 'offline'

method = method1

kx = 0.1 #noise parameter

###################################################################################################
#                TRAINING

if (method == 'offline'):

    m = 1000 #size of the training set
    X = np.linspace(0, 4*math.pi, num = m).reshape(m, 1); #input training set

    Y = np.sin(X) #target

    noise = (2.0*np.random.uniform(0, kx, m) - kx).reshape(m, 1)
    Y = Y + noise #noisy target

    #scaling of the target depending on the activation function
    if (activation == 'sigmoid'):
        Y_scaled = (Y/(1+kx) + 1)/2.0
    elif (activation == 'tanh'):
        Y_scaled = Y/(1+kx)

    #number of the iteration for the training stage
    iter_count = 20000
    net.train(X, Y_scaled, iter_count) #training

elif (method == 'online'):

    sampling_count = 100000 # number of samplings during the training stage

    m = 1 #batch size

    iter_count = sampling_count/m

    for layer in range(net.L):
        net.inputs.append(np.empty([m, net.neurons[layer]]))
        net.errors.append(np.empty([m, net.neurons[layer]]))

        if (layer < net.L -1):
            net.outputs.append(np.empty([m, net.neurons[layer]+1]))
        else:
            net.outputs.append(np.empty([m, net.neurons[layer]]))

    J_history = []
    step_history = []

    for i in range(iter_count):
        X = np.random.uniform(0, 4*math.pi, m).reshape(m, 1)

        Y = np.sin(X) #target
        noise = (2.0*np.random.uniform(0, kx, m) - kx).reshape(m, 1)
        Y = Y + noise #noisy target

        #scaling of the target depending on the activation function
        if (activation == 'sigmoid'):
            Y_scaled = (Y/(1+kx) + 1)/2.0
        elif (activation == 'tanh'):
            Y_scaled = Y/(1+kx)

        net.feedforward(X)
        net.backpropagate(Y_scaled)

        if (np.remainder(i, 1000) == 0):
            J = net.cost_online(0, 4*math.pi, 1000)
            J_history.append(J)
            step_history.append(i)

    plt.plot(step_history, J_history)
    plt.title('Batch size ' + str(m) + ', rate ' + str(net.rate) + ', samples ' + str(sampling_count))
    #plt.ylim([0, 0.1])

    plt.show()

#gained weights
trained_weights = net.weights

##########################################################################################
#                 PREDICTION

m_new = 40 #size of the prediction set
X_new = np.linspace(0, 4*math.pi, num = m_new).reshape(m_new, 1);

Y_new = net.predict(X_new, trained_weights) #prediction

#rescaling of the result
if (activation == 'sigmoid'):
    Y_new = (2.0*Y_new - 1.0) * (1+kx)
elif (activation == 'tanh'):
    Y_new = Y_new * (1+kx)

#visualization

#fake sine curve to show the ideal signal
if (method == 'online'):
    X = np.linspace(0, 4*math.pi, num = 100)
    Y = np.sin(X)

plt.plot(X, Y)

plt.plot(X_new, Y_new, 'ro')
if (method == 'online'):
    plt.title('Batch size ' + str(m) + ', rate ' + str(net.rate) + ', samples ' + str(sampling_count))
plt.ylim([-1.5, 1.5])
plt.show()

raw_input('press any key to exit')

rawDescription: Neural network backpropagation algorithm not working in Python


code:
for filename in city:
    data = pd.read_table(filename, sep='\s+', usecols=(6,7,8,9), parse_dates=[0],
                         index_col=[0])
    data[['precip', 'tmax', 'tmin']] /= 10.0
    avg = data.resample('A', how='mean')

rawDescription: Averaging Parts of An Array In Python

description: Averaging Parts of An Array In Python


code:
from sqlalchemy.sql import exists, and_

pt1 = exists().where(and_(PostTag.tag_id == Tag.id, PostTag.post_id == id1))
pt2 = exists().where(and_(PostTag.tag_id == Tag.id, PostTag.post_id == id2))
tags = session.query(Tag.name).filter(pt1, pt2).all()

rawDescription: SQLAlchemy: Return list of associated records shared by two given records


code:
print( [sub[ind] for sub in myList for ind, ele in enumerate(sub,1) if ele == "RND"])
['20.5', '40', '35']

rawDescription: Getting more than one number after specific string


code:
def drawGradient(self, canvas, x, y, w, h):
    factor = 255./w
    for offset in range(0, w):
        gradColor = '#%02x%02x%02x' % (offset*factor, offset*factor, offset*factor)
        canvas.create_line(x + offset, y, x + offset, y + h, fill=gradColor)

rawDescription: Color of the drawn gradient is always uniform


code:
class Account(models.Model):
    ...
    objects = AccountManager()

rawDescription: override Django Get or Create

description: Override Django Get or Create


rawDescription: Python For Loop includes the end of the range


code:
POST /demo/doc/_search
{
    "query": {
        "multi_match": {
            "fields": [
                "title",
                "title.simple"
            ],
            "query": "testing"
        }
    }
}

rawDescription: Elasticsearch - Not require an exact match


code:
import numpy as np
import scipy.signal as sg

AveragingLengthAmp = 10
AveragingLengthPhase = 10
PhaseFixLength = 60
averaging_length = channel_sampling_freq1*PhaseFixLength

def fix_phasedata180(data_phase, averaging_length):
    data_phase = np.reshape(data_phase,len(data_phase))
    x = np.exp(1j*data_phase*2./180.*np.pi)
    N = float(averaging_length)
    b, a = sg.butter(10, 1./np.sqrt(N))
    y = sg.filtfilt(b, a, x)
    output_phase = data_phase - np.array(map(round,((data_phase/180*np.pi-np.unwrap(np.angle(y))/2)%(2*np.pi))*180/np.pi/180))*180
    temp = output_phase[0]%90
    output_phase = output_phase-output_phase[0]+temp
    s = output_phase[output_phase >= 180]
    for s in range(len(output_phase)):
        output_phase[s] = output_phase[s]-360
    return output_phase

out1 = fix_phasedata180(data_phase, averaging_length)

def fix_phasedata90(data_phase, averaging_length):
    data_phase = np.reshape(data_phase,len(data_phase))
    x = np.exp(1j*data_phase*4./180.*np.pi)
    N = float(averaging_length)
    b, a = sg.butter(10, 1./np.sqrt(N))
    y = sg.filtfilt(b, a, x)
    output_phase = data_phase - np.array(map(round,((data_phase/180*np.pi-np.unwrap(np.angle(y))/4)%(2*np.pi))*180/np.pi/90))*90
    temp = output_phase[0]%90
    output_phase = output_phase-output_phase[0]+temp
    output_phase = output_phase%360
    s = output_phase[output_phase >= 180]
    for s in range(len(output_phase)):
        output_phase[s] = output_phase[s]-360
    return output_phase

offset = 0
data_phase_unwrapped = np.zeros(len(out2))
data_phase_unwrapped[0] = out2[0]
for jj in range(1,len(out2)):
    if out2[jj]-out2[jj-1] > 180:
        offset = offset + 360
    elif out2[jj]-out2[jj-1] < -180:
        offset = offset - 360
    data_phase_unwrapped[jj] = out2[jj] - offset

rawDescription: MATLAB fftfilt equivalent for Python

description: MATLAB fftfilt equivalent for Python


code:
from datetime import datetime, time, timedelta

def value_to_time(val):
    if val == 'now':
        return datetime.now().time()
    if val.endswith('min'):
        return (datetime.now() + timedelta(minutes=int(val[:-3]))).time()
    hours, minutes = map(int, val.split(':'))
    return time(hours, minutes)

rawDescription: Python - sorting a tuple, characters over numbers


code:
import binascii
x = bytearray(b'\xc0\x00\x00\xfe\xb4\xf0\xfe\xb4\xb0\xfe\xb4\xce\xfe\xb4l\xfe\xb6\x8fxfe\xb56\xfe\xb5u\xfe\xb4\xb1')

[binascii.hexlify(x[i:i+3]) for i in range(0, len(x), 3)]

rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


code: lowess(y, x)

rawDescription: How to visualize a nonlinear relationship in a scatter plot

description: Visualize a nonlinear relationship in a scatter plot


code:
def listdir_nohidden(path):
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

rawDescription: How to ignore hidden files using os.listdir()? - Python

description: Ignore hidden files using os.listdir()? - Python


code: connreq = sniff(filter=connfilter, prn=handshake, timeout=4)

rawDescription: Send a new packet without waiting for the previous packet reply


rawDescription: Convert dict with mixed values to flat dict


code:
# objects:  QuerySet that you get from your initial filters. Not yet executed.
if rtd:
    # Method `as_nested_sql` removes the `order_by` clase, unlike `as_sql`
    subquery3 = objects.values('id').query \
            .get_compiler(connection=connection).as_nested_sql()
    subquery2 = ("""SELECT profile_id, category, avg(points) AS points_avg
          FROM myapp_ratings
          WHERE profile_id in
          ( %s
          ) GROUP BY profile_id, category
            """ % subquery3[0], subquery3[1]
    )
    where_sql = ' OR '.join(
            'category = %d AND points_avg >= %%s' % cat for cat in rtd.keys()
    )
    subquery = (
        """SELECT profile_id
        FROM
        ( %s
        ) subquery2
        WHERE %s
        GROUP BY profile_id
        HAVING count(*) = %s
        """ % (subquery2[0], where_sql, len(rtd)),
        subquery2[1] + tuple(rtd.values())
    )
    assert order_by_ranking_level in ('asc', 'desc')
    mainquery = ("""SELECT myapp_profile.* FROM myapp_profile
      INNER JOIN
      ( %s
      ) subquery ON subquery.profile_id=myapp_profile.id
      ORDER BY ranking_level %s"""
        % (subquery[0], order_by_ranking_level), subquery[1]
    )
    objects = Profile.objects.raw(mainquery[0], params=mainquery[1])
return objects

rawDescription: Django - Complex query

description: Django - Complex query


code:
class PatchContextManager:

    def __init__(self, method, enter_return, exit_return=False):
        self._patched = patch(method)
        self._enter_return = enter_return
        self._exit_return = exit_return

    def __enter__(self):
        res = self._patched.__enter__()
        res.context = MagicMock()
        res.context.__enter__.return_value = self._enter_return
        res.context.__exit__.return_value = self._exit_return
        res.return_value = res.context
        return res

    def __exit__(self, type, value, tb):
        return self._patched.__exit__()

rawDescription: Python 3 urlopen context manager mocking


code:
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

rawDescription: Python openCV detect parallel lines

description: Python openCV detect parallel lines


code:
def translation(seq):
    l = list(set(sorted([x[1] for x in seq])))
    return [(x[0], l.index(x[1])) for x in seq]

rawDescription: Python sequence translation

description: Python sequence translation


code:
from collections import defaultdict

out = defaultdict(list)
for e in mylist:
    out[f(e)].append(e)

rawDescription: python : generate sublists depending on the elements values

description: Python : generate sublists depending on the elements values


code:
import OpenGL.GL as GL
import OpenGL.GLU as GLU
import OpenGL.GLUT as GLUT

window = 0
width, height = 500,400

def draw():
    GL.glClear(GL.GL_COLOR_BUFFER_BIT |GL.GL_DEPTH_BUFFER_BIT)
    GL.glLoadIdentity()
    GLUT.glutSwapBuffers()

#initialization
GLUT.glutInit()
GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_ALPHA |
GLUT.GLUT_DEPTH)
GLUT.glutInitWindowSize(width,height)
GLUT.glutInitWindowPosition(0,0)
window = GLUT.glutCreateWindow(b"noobtute")
GLUT.glutDisplayFunc(draw)
GLUT.glutIdleFunc(draw)
GLUT.glutMainLoop()

rawDescription: NameError when running pyOpenGL

description: NameError when running pyOpenGL


code:
import os
import hashlib
import pygame
import time
import base64

def create_assets(asset_dict, asset_dir):

    """
    hand this function a dictionary of assets (images, mp3s, whatever)
    and an absolute path to the data/asset folder.
    The function creates the folder and files from the base64 strings
    if they don't exist. If the files exist, an md5 check is run
    instead to ensure integrity
    """

    first_run = False
    if not os.path.isdir(asset_dir):
        os.mkdir(asset_dir)
        first_run = True
    for label in asset_dict:
        asset = asset_dict[label]
        filename = os.path.join(asset_dir, asset["filename"])
        rewrite = False
        # no need to check file if we just created the data folder
        if not first_run:
            if not os.path.isfile(filename):
                # the file doesn't exist
                rewrite = True
            else:
                # file exists - make sure it's intact via md5
                with open(filename, "rb") as f:
                    if not hashlib.md5(f.read()).hexdigest() == asset["md5"]:
                        # the filename exists but the contents is wrong
                        rewrite = True
        if first_run or rewrite:
            # one of our checks failed or first run - write file
            print ("Writing file: ",filename)
            with open(filename, "wb") as f:
                f.write(base64.b64decode(asset["data"]))
        else:
            print ("File exists: ",filename)

"""
This the data dictionary. It's very easy to save
the whole thing as json should you feel like it.
The images are just small, random icons at the moment

"""

assets = {
    "background": {
        "filename": "bg1.png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAACOUlEQVQ4je2VQUhTcRzHP3szJyHiwbH5aCzpMCJ6NHIjWmzFtCBwKkEX7RYN2g4eAyF2jLRLzE5GoIegOgQNEarJCBwtYeQgPEQ0dC+fDNK5yFD3OuR7zL13WNCx7/ED3x8/vr8/379FVVWVA5WVZZY/TCEXMxxtdxLou082PU61sgpgYKI7hFzM4BD99A/PACBog9KpKPMvruvDwpEnlJUC4YFp2jtcpkzyxQBQ5BxKKQeANdj7LZHPTrK9VQTA7vTiD95lfe09+ewEtrZOTp29xbHjlwysyyFR3iiwvVXkR6XEiZPDtMjFjD5I8sfpdgV4OdtPeGCa/b2f9HgGWUhFqdV2DSwyMofkiyEXM/qWgt3pJRx5zJVrT+l2BQCoVlZ5++omojvIQipKZfOLKQPockiI7hAAy7kkltmkRzU7QLNq9ApmYQMIwhEkXxyr1aabG5mZ1/ow+SzRGPbnT8853XsbyR9HEFpZX1sEMLCLVx8ZDmUNnPma8J4bw9bWSY9nkHfzY/za+U5Z+YggtFJYmqJW2z14p4fZhrxEo9cym/So7R0uLlx+wOKbO3rYzarRKwDUarvs7+3om/yNGr3/j/IPjiK6Q1Qrq+QXJ4mMzDEaW9Hz6R+a0TM1Y6OxFYZuvKbLIXG+7x6iO4RgVkHN1tefGA5Xn0VVVTWdih4qSqWUo6wUyGcnkHxxRHeQ/b0dA9PKWJPd6aUFMFRQNj3eVH1peddXn0X7Auq3VOScIWyzA9QP0vQbENbTigXxO1gAAAAASUVORK5CYII=",
        "md5": "12f7eb2eea8992a2644de649dfaf00b3"
        },
    "player_sprite": {
        "filename": "player_img.png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAACh0lEQVQ4jZWUS2gTURiFv5lkmiZpk5KmNWmbIFratLWlCiq2blwILly4EFSsG3EjCK5EFITiQhFXbgRBXbXgouBe3GkRKTaYvtLWR01sa5M0j8nDpK9xEWZIwqStZ3nuzLmX/7v3CIE7HxR5KobvwUkaB9wApAIx7H1O5h5+Jv5pFYAjT05r3maygHfIR8OxZlTJs+uERoKI3iEf1kN2HKdc2mJoJEjme1ILK/WyP1IcvNFTFpZfy7H0coaUP4qgKIqSC6exeOrJr2YxuSxM3x1nM5Hn7+8MpTK31Wme/WgTnsud2Puc2npyMlIMVI3p++O0XDiM44SLVCDGt2d+8itZdpOt10n77X7MrXUAGEtnkPJH2c5uItlNLI8t7hlW19FA68V2alusmickv0aVSgD7lR4oUQ8AgGAU8Vz1IdaIVT09UIabg9eHo+9DbMkbZYGeK514h3wIkkjKH9X1CpEcciBGfjVL5F0IeXa9CEUPgFgj4rnWRXg0yE5+u6pXKUEOxpXwaJDExNp/za+ahI/n3ip7f7a36rscRShVd9oHFFWmZosGxWjrdSJPxYoLLguFPzkA2i51FHesNfDr1UxVD6AQybHw9AtmtxXD8/HXw/Y+J/LsOu23+tlKb5BfyZKZjyNIIuHRIMpWcSp6nirfveNkFpIY0/MJlscWkRpMxXtklUhMrLGzsVN2CkDXU+en/lv2ltUKUu9dNakAwm8WqKw+7S2rFZSei+8apgKwdTciGEV+vpgqqz7tLatKTka0naEclBbqsmB2W+l5NEhl9RnOLw0MpwIxbN0OJFsNtW4rB8560QOlSgXQdMaDZDcBEHw8gWSrwahXQdVAVQIonb1aff8A8A1zY9iTMCcAAAAASUVORK5CYII=",
        "md5": "79f25f0784a7849415f9c3d0d9d05267"
        },
    "weapon": {
        "filename": "sword1.png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAACzUlEQVQ4jZWVX0hTYRjGfydHZJb5J03SrIarrQaNEhKERgT25yaiIjEGQUWB0U03BUHWRVS3BUUOHGkUFg2LjW5bQkUjs6bNHcskJZRVplHTzs7bxdphy0Ot5+Ycnu99n3O+5/l4P+Q32u7FxO0JyOWOPvkbWjujouu68e72BOTqrX5j3UIG9mxdQXOTA4BI7AvB0Aca6itxOUoNruPBW5y2Yupc5RzauxoALakbGkrbvZgA1FQXUr++HEVR8PlVfH7VKGrcYeVoo51L3lcEQyNsql3CueMbjPWnL8eJDn0FIG9i7raWmuWF7G5YgaIoALgcpThtRWiacGSfnZ1bqlEUhYJ8Cw+7Rzm8dzXVSxcYglUVBYQjcW50DcLljj7Dk1zwt/rWzqgoIiL8gSs3+4m+myCiTmC3LqJ27WISM8lZXNpD750BDu5ZldqhiMjrgc9ysbVXevrjIiJy5Ey36Louw6NTouu6nLjwzJRL97o9AXnSM5ZKOTOAYGiExh1Wou++MjQyhXVZIeOffhDuiwOYcsHQB+NZ5yrHcmCXDaetiOCjERrqK9m4roxwJM7KqoWMf/pBeWk+LnsJ375rsziAhvpKgqFUL4Cph9duv2FweIpwXxyXvQSXo5TEtDaLO7DLZnje3ORAURTmpEW8dwZIa2tJITGjAZCYSaJpuimXxrH9a4wjh5mx/xtKZqAWM2NzDcUsUIuZsTXVhTmFYhaoEUqmsf8bShZaO6M5japc0N6lSt7kvO0tmqazfu3irA9FYl+44H2Fw1pEVUWBwfn8KgX5FirK5mfVd9wfxHs3Rt7JU6dbdBE0TYxGAJ9fRR2eZOZnks0bl+Lzq5y/3os6PMnD7lES00lqnamfCEfivB+dwmkrTh0bkdTEztx+T39c3J6APA5/NLjnr8fl7JUX8qRnzLCivUvNmthZgm5PIEv0X6OtvUuddQX8Ag5COzDf7kUwAAAAAElFTkSuQmCC",
        "md5": "92485d36b8ac414cc758d9a6c6f28d23"
        },
}

# get absolute path to asset directory
asset_dir = "data"
asset_dir_path = os.path.join(os.getcwd(), asset_dir)

# create files in asset directory using the assets dictionary
create_assets(assets, asset_dir_path)

pygame.init()

WIDTH = 800
HEIGHT = 600

SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))

loaded_images = {}

# initalize/load all the newly created images
for label in assets:
    file_path = os.path.join(asset_dir_path,assets[label]["filename"])
    loaded_images[label] = pygame.image.load(file_path)

pos1 = 0
pos2 = 0
t_start = time.time()

while time.time() - t_start < 5:
    for img in loaded_images:
        SCREEN.blit(loaded_images[img], (pos1, pos2))
        time.sleep(0.2)
        pos1 += 20
        pos2 += 20
        pygame.display.update()

rawDescription: How can I pack images? -Pygame -PyInstaller

description: Pack images? -Pygame -PyInstaller


code:
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.template.context_processors.i18n',
            'django.template.context_processors.media',
            'django.template.context_processors.static',
            'django.template.context_processors.tz',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},]

rawDescription: Empty {{ MEDIA_URL }} tag, caused by transitioning from Django 1.7.2 to 1.8


rawDescription: Using python regex to exclude '.' at the end but not inside a string


code:
is_first = np.empty_like(sorted_is_first)
is_first[idx] = sorted_is_first
is_first

rawDescription: Indirect-ish sort with Numpy

description: Indirect-ish sort with Numpy


code:
from django.db import models
from app.settings import AUTH_USER_MODEL
class Base(models.Model):
    owner = models.ForeignKey(AUTH_USER_MODEL)
class ChildA(Base):
    name = models.CharField(max_length=5)
class ChildB(Base):
    location = models.CharField(max_length=5)

rawDescription: Django Admin Non Staff Access Data Filtering


rawDescription: Retrieving flickr favorites

description: Retrieving flickr favorites


code:
X = range(6)
Y = ["abc","def","ghi"]
p = [(X[-1 + (index + 6) / 6], Y[-3 + (index) / 6], X[index % 6], Y[index % 3]) for index in range(36)]

rawDescription: R nested for loop in Python?

description: R nested for loop in Python


code:
print('Enter the base path of the images: ', end='')
sys.stdout.flush()

rawDescription: Curious behaviour of print_function in __future__ module on Python 3


code:
from pprint import pprint as pp
pp(by_discount[:2])

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


code:
xpath = ("//td[text()='activeThreadCount']"
         "/following-sibling::*"
         "/text()")

rawDescription: Usage of """ instead of " on variables with long text inside


code:
sets = [set([1]), set([2])]
sets
[sets[i].add(set_) for i, set_ in enumerate(li)]  #could be expanded in proper loop
sets

rawDescription: adding elements to different sets from a list in python

description: Adding elements to different sets from a list in python


code:
def sum_view(request, numbers):
    processed_numbers = [int(x) for x in number.split('/') if x]
    ...

rawDescription: Django urlpattern with infinite number of parameters


rawDescription: How to get Employee --> Manager without separate tables (pandas or SQL)?

description: Get Employee --> Manager without separate tables (pandas or SQL)


code: ['animals|fish|salmon', 'furniture', 'animals|big cats|lions', 'animals|birds|fisher bird']

rawDescription: Identifying elements that occur within strings in a list


rawDescription: Truncating multi-indexed dataframe

description: Truncating multi-indexed dataframe


code: re.findall('(A[^A]+)', s, re.IGNORECASE | re.MULTILINE)

rawDescription: Python regex char pattern group

description: Python regex char pattern group


code:
all_keys = list(set(a.keys()+b.keys()))
l = list()
for key in sorted(all_keys):
    try:
        l.append(diff_unique(a[key][1],b[key][1]))
    except KeyError:
        l.append("whatever you want")
return l

rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


code:
window_days = 3
ids = []
for _, df_gb in df.groupby('id'):
    df_gb = df_gb.set_index('time').resample('D')
    df_gb = pd.rolling_count(df_gb[['dummy_numeric']], window_days).reset_index()
    ids.append(df_gb)

rawDescription: Count repeating events in pandas timeseries


rawDescription: Python: How to know if two dictionary have the same keys


code: df = pd.merge(df1, df2, left_index=True, right_on=['STATE_PROV_CODE', 'COUNTY'])

rawDescription: Pandas join on 2 columns

description: Pandas join on 2 columns


code:
import os

ans = os.environ.get('ans')
if ans is None:  # it was not set, so ask user
    ans = input("How you doin' (Say Yes/No)")

if ans == "Yes":
    print("Nice to hear")
elif ans == "No":
    print("Oh Too Bad")

rawDescription: How to make a script auto-provide arguments to another without passing via command line?

description: Make a script auto-provide arguments to another without passing via command line


code:
from gevent import monkey; monkey.patch_socket()
import urllib2 # it's usable from multiple greenlets now

rawDescription: Monkey Patching in python: When we need it?


code: [(a+b+c) for a in range(100,400,100) for b in range(10,40,10) for c in range(1,4,1)]

rawDescription: Generating Difficult List in Python

description: Generating Difficult List in Python


code: "Date range: {0[0]:{1}} to {0[1]:{1}}".format(daterange, fmt)

rawDescription: Formatting multiple datetimes into a string


code:
def notify_subscribers(changes):
    new_posts = [target for target, op in changes if isinstance(target, Post) and op in ('insert', 'update')]
    # notify about new and updated posts

# pass all the callbacks (if you have more than notify_subscribers)
mce = ModelChangeEvent(db.session, notify_subscribers)
# or you can append more callbacks
mce.callbacks.append(my_other_callback)

rawDescription: Run function after a certain type of model is committed


code: A_flat = A.flatten()

rawDescription: Access individual elements of an array of several arrays, Python


rawDescription: Why is numpy/pandas returning only the first character when I use .astype(str)


code:
z = defaultdict(Counter)

for k,v in chain(x.iteritems(), y.iteritems()):
    z[k].update(v)

rawDescription: How to combine multiple defaultdict(Counter)?

description: Combine multiple defaultdict(Counter)


rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


code:
def op24 (ns1, op, ns2):
    if op == 'a':
        return ns1 + ns2
    elif op == 's':
        return ns1 - ns2
    ...

rawDescription: 24 game using Python

description: 24 game using Python


rawDescription: Getting Pandas dataframe value

description: Getting Pandas dataframe value


rawDescription: Suppressing Output of Paramiko SSHClient Class


code:
n = len(str_list)
values = unpack("d" * n, "".join(str_list))

a = data[file_idx]

# Just to shorten this code sample
q = NBR_DATA_POINTS_PER_BUFFER_INT

for i in xrange(n):
    a[i / q][i % q] = values[i]

rawDescription: assigning elements to buffer and specific position in buffer - how to speed up / why are the different implementations so slow?

description: Assigning elements to buffer and specific position in buffer - how to speed up / why are the different implementations so slow


code:
from collections import defaultdict
tokenDict = defaultdict(lambda: 0)

rawDescription: Analyze MySQL Text Data

description: Analyze MySQL Text Data


rawDescription: python regex: match a char surrounded by exactly 2 chars

description: Python regex: match a char surrounded by exactly 2 chars


code: p = subprocess.Popen("some-program")

rawDescription: Subprocess calls are they done in parallel?


code: _changedFiles = [os.path.abspath(file) for file in repo[_node].changeset()[3]]

rawDescription: Get list selected for commit files in hg hook


code:
lst = [1,2,4,6,3,8,0,5]
for n in lst:
    if n % 2 == 0:
        lst.remove(n)
lst

rawDescription: Find all text files not containing some text string


code:
from collections import defaultdict

byvalue = defaultdict(list)

for i, x in enumerate(data):
    byvalue[x].append(i)

rawDescription: Fast membership in slices of lists

description: Fast membership in slices of lists


rawDescription: Passing arguments to views in Django from constrained choices


code:
import math
a = max(player.pos[0]-enemy.pos[0], enemy.pos[0]-player.pos[0]) # on x-axis (dunno, if abs would do the same)
b = max(player.pos[1]-enemy.pos[1], enemy.pos[1]-player.pos[1]) # on y-axis
distance = math.sqrt(a**2 + b**2)

rawDescription: Movement in 2D Map in Python

description: Movement in 2D Map in Python


code:
import re
import json

#...your code...

content = wgetUrl(url)
matches = re.findall(r'quoteDataObj\s\=\s\[(\{.+\})\]', content)
if len(matches) > 0:
    python_dict = json.loads(matches[0])

rawDescription: Extracting between specific <script> </script> tag


rawDescription: How to summarise data over several years into one dataframe

description: Summarise data over several years into one dataframe


code:
d =[{'name': 'fire', 'command': '1;2;3;4'},
    {'name': 'brain', 'command': '2;2;3;4'},
    {'name': 'word', 'command': '1;3;4;5'},
    {'name': 'cellphone', 'command': '6;1;3;4'},
    {'name': 'ocean', 'command': '9;3;7;4'}]

import itertools
groups = itertools.groupby(d, lambda i: i['command'].split(';')[1:3])

for key, group in groups:
    print(list(group))

rawDescription: how to goup items in a list of dictionaries by matching values in python

description: Goup items in a list of dictionaries by matching values in python


code:
c1 = []

for p in itertools.product(L1b, L2b, L3b):
    multiply_all = reduce(operator.mul, p)
    c1.append((multiply_all, p))

c2 = []

for p in itertools.product(OM, L1a, L2a):
    multiply_all = reduce(operator.mul, p)
    c2.append((multiply_all, p))

RPL = []

for p in itertools.product(c1, c2):
    calculation = (p[0][0] / p[1][0]) * LR
    RPL.append((calculation, p[0][1], p[1][1]))

rawDescription: For loop, how can i use loop variable outside loop


rawDescription: How to export a list with different size from python to excel

description: Export a list with different size from python to excel


code: data[(data['dif'] < 0) & (data['dif'] > -100)].groupby('date')['Close', 'dif'].first()

rawDescription: How to run a conditional query that selects for the first occurrence only in Pandas?

description: Run a conditional query that selects for the first occurrence only in Pandas


code:
self.connect("delete-event", lambda the_widget, the_event: \
    self.__instance_b.manage_event(the_widget, the_event))

rawDescription: Connecting signal with lambda does not work in some cases?


rawDescription: Palindrome generator

description: Palindrome generator


code:
d = {'keyname': ['foo', 'bar']}
[(k, v)] = d.items()
k
v

rawDescription: Unpack dictionary without knowledge of its key name


code:
a = MyList()
a
a.append(5)
a
a + [2,3,4]
a.extend(range(4))
a
a[1:2] =  range(10,12)
a

rawDescription: Can you easily create a list-like object in python that uses something like a descriptor for it's items?

description: Easily create a list-like object in python that uses something like a descriptor for it's items


code: np.choose(a<b, [b,a])

rawDescription: Numpy: vectorizing two-branch test (ternary-operator like)


code: reference

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code:
dummy_matrix[x][i] = 2
other_matrix[x][i] = 1   # overwrites the previous value

rawDescription: Python - Erroneous result for two different matrixes in nested for loop


code:
workerThread = QThread()
workerObject = Worker(cmdlist)
workerObject.moveToThread(workerThread)
workerThread.started.connect(workerObject.run)
workerObject.finished.connect(workerThread.quit)

# create a progressbar with min/max according to
# the length of your cmdlist
progressBar = QProgressBar()
progressBar.setRange(0, len(cmdlist))

# connect the worker's progress signal with the progressbar
workerObject.madeProgress.connect(progressBar.setValue)

# start the thread (starting your worker at the same time)
workerThread.start()

rawDescription: Python PyQT: How to call a GUI function from a worker thread?


code: data[row[0]] = int(row[1])

rawDescription: Extracting data from a text file

description: Extracting data from a text file


code:
c = Counter()
strs = "foo bat foo"
c.update(set(strs.split()))
strs = "foo spam foo"
c.update(set(strs.split()))
c

rawDescription: word frequency calculation in multiple files

description: Word frequency calculation in multiple files


code: readfile = open("fileName","w")

rawDescription: python Writing to a file

description: Python Writing to a file


code:
def is_emoji(s):
    emojis = "◼" # add more emojis here
    count = 0
    for emoji in emojis:
        count += s.count(emoji)
        if count > 1:
            return False
    return bool(count)

rawDescription: Find there is an emoji in a string in python3


code:
def Count_Word(word, data, leading=[], trailing=["'s", "s"]):
    c = 0
    tokens = word_tokenize(data)
    for token in tokens:
        token = token.lower()
        for lead in leading:
            if token.startswith(lead):
                token = token.partition(lead)[2]
        for trail in trailing:
            if token.endswith(trail):
                token = token.rpartition(trail)[0]
        if token == word:
            c += 1
    return c

rawDescription: Counting words in a text file

description: Counting words in a text file


code:
x = 'hello'
list(x)

rawDescription: How can I allow users to reference variables and other data structures via input?

description: Allow users to reference variables and other data structures via input


rawDescription: Combine two columns under one header in Numpy array


code: tableau = [ extraire(line) for line in re.findall( ".*?I Doc ):.*", fichier.read() ) ]

rawDescription: Read only lines that contain certain specific string and apply regex on them


code:
pt1 = geopy.Point(48.853, 2.349)
pt2 = geopy.Point(52.516, 13.378)
# distance.distance() is the  VincentyDistance by default.
dist = geopy.distance.distance(pt1, pt2).km

rawDescription: Calculate point based on distance and direction


code:
player.__class__
player.__class__ == Character
player2 = Character()
player2.__class__
player2.__class__ == Character

rawDescription: Saving and Loading a Class Instance

description: Saving and Loading a Class Instance


code:
import theano
import theano.tensor as T
X = T.matrix("X")
Y = T.matrix("Y")
results, updates = theano.scan(lambda x_i: ((x_i - Y)**2/(x_i+Y)).sum(axis=1)/2., sequences=X)
chi_square_norm = theano.function(inputs=[X, Y], outputs=[results])
chi_square_norm(A,B)  # same result

rawDescription: Optimizing histogram distance metric for two matrices in python


code:
import pandas as pd
from sqlalchemy import create_engine

# create a connection engine using sqlalchemy
engine = sqla.create_engine('postgresql+psycopg2://postgres:xxx@localhost/import', echo=False)

# read the results file into a pandas DataFrame
df = pd.read_csv('C:/Users/berend/Desktop/record_schoon.txt', delimiter='\t') # or whatever your delimiter is
dfFill = df.fillna("") # "" will be blank space when any record is missing data or 'nan'
dfFill.to_sql("tablename", engine, if_exists="append") #change tablename to the name of your table in import

rawDescription: dynamical list from site into postgres python

description: Dynamical list from site into postgres python


code: main('foo', 'arg1', 'arg2')

rawDescription: Use *args without putting the arguments into a tuple?


code: filter(None, myList)

rawDescription: Python 3: Removing an empty tuple from a list of tuples


code:
def run(self):
    result = TS(aux)
    mutex.acquire()
    output.append(result)
    mutex.release()

rawDescription: Complete a multithreading parallelize process with k threads


code:
from datetime import datetime
dt = datetime.fromtimestamp(1360287003083988472 // 1000000000)
dt

rawDescription: Python - Convert epoch time with nanoseconds to human-readable?


code:
from .views import test_view

urlpatterns = patterns('',
    ('^test/$', test_view),
)

rawDescription: Django class based generic view redirect


code:
ax = a3.Axes3D(pl.figure())
we1 = WEdge(ax)
we2 = WEdge(ax)

rawDescription: multiple objects on the same plot (MATPLOTLIB)

description: Multiple objects on the same plot (MATPLOTLIB)


code: sum(len(list(binomial_choice(range(100), 0.05))) for i in range(100000)) / 100000

rawDescription: Given iterable, select each element independently with probability p


code:
class Routing_Table:
    def set (self, key, value):
        with self.lock: self.table[key] = value

    def get(self, key):
        with self.lock: return self.table[key]

    def __init__(self):
        self.table = {}
        self.lock = Lock ()

rawDescription: Python Dictionaries and Threading Concurreny


code:
import random
r = lambda: random.randint(1, 10)
inputlist = [(0,0), (r(),r()), (r(),r()), (0,0), (0,0), (r(),r()), (0,0)]
sorted(inputlist, key=lambda t: t == (0, 0))

rawDescription: For Python, how to sort and lump elements in a fixed-sized list


rawDescription: How do I generate 8 different random numbers in python?

description: Generate 8 different random numbers in python


rawDescription: Extracting string with BeautifulSoup

description: Extracting string with BeautifulSoup


code:
for name in sorted(user_scores):
    print(name, '-', user_scores[name])

rawDescription: Displaying only a person's highest score from a .txt file (Python 3)


rawDescription: Pandas df.to_records() returns a 1d numpy array


code: new_image= image.point(lambda argument: argument*16)

rawDescription: Rescale intensities of a PIL Image

description: Rescale intensities of a PIL Image


code:
# http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
xslt='''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<xsl:template match="/|comment()|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>
'''

xslt_doc=ET.parse(io.BytesIO(xslt))
transform=ET.XSLT(xslt_doc)
dom=transform(dom)

rawDescription: lxml etree xmlparser namespace problem

description: Lxml etree xmlparser namespace problem


code:
def create_my_function(x):
    def local_function():
        print(x)
    global my_function
    my_function = local_function

create_my_function("Hello")

rawDescription: why does importing a module executes all statements in python?

description: Why does importing a module executes all statements in python


code: s='Tomato4439, >gi|224089052|ref|XP_002308615.1| predicted protein [Populus trichocarpa]'

rawDescription: strip sides of a string in python

description: Strip sides of a string in python


code:
import collections
freqDict = collections.defaultdict(int)
...
freqDict[word] += 1

rawDescription: Converting a Doc object into a string in python


code:
def f(j, ls):
    output = [ls[:] for _ in xrange(len(ls) + 1)]
    for i, sublist in enumerate(output):
        output[i].insert(i, j)
    return output

rawDescription: Insert an element into a list in python

description: Insert an element into a list in python


code: #!/usr/bin/env python

rawDescription: What do I use on linux to make a python program executable


rawDescription: Python3/Classes/OOP/ How do you change a objects self values with a method?


code:
def extrema(value, deltas):
    max_value = min_value = value
    for delta in deltas:
        value += delta
        if value < min_value:
            min_value = value
        elif value > max_value:
            max_value = value
    return min_value, max_value

rawDescription: Maxima and Minima Point of a Curve in Python


code:
url = urlresolvers.reverse('admin:%s_%s_changelist' % (app_label, model_name))
url += '?all'

rawDescription: Overidde queryset filters while generating django admin URLs


code:
import datetime

today = datetime.date.today()
yourdate = datetime.datetime.strptime(inputstring, '%d %b')
yourdate = yourdate.date().replace(year=today.year)

if yourdate >= today:
    # date not before today, attach *last* year
    yourdate = yourdate.replace(year=today.year - 1)

rawDescription: Python: How can I see if a given month and day have already passed this year?


code:
key = list(d)[0]
value = list(d.values())[0]

rawDescription: How to fetch the key/value pair of a dictionary only containing one item?

description: Fetch the key/value pair of a dictionary only containing one item


code:
def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

rawDescription: How to check if the current time is in range in python?

description: Check if the current time is in range in python


code: digits = digits.replace('\n', '')

rawDescription: Largest product in a series in python

description: Largest product in a series in python


code: tempArray = [list(reversed(x)) for x in reversed(self.topArea)]

rawDescription: Inversing a twodimensional array in python


code:
# again, untested so use with care.
def require_POST(view_func, required_fields=None):
    def wrap(request, *args, **kwargs):
        if request.method != "POST":
            return HttpResponseBadRequest("Expecting POST request")
        if required_fields:
            for f in required_fields:
                if f not in request.POST:
                    return HttpResponseBadRequest("Expecting field %s" % f)
        return view_func(request, *args, **kwargs)
    wrap.__doc__ = view_func.__doc__
    wrap.__dict__ = view_func.__dict__
    wrap.__name__ = view_func.__name__
    return wrap

rawDescription: Django url validation

description: Django url validation


rawDescription: Add lists in a certain range

description: Add lists in a certain range


code:
#!/usr/bin/env python2
import os
from glob import glob

dest_dir = 'C:/Users/Manvendra/Dropbox/Python'
for html_filename in glob('C:/Users/Manvendra/Dropbox/PRI/Data/AP/*.html'):
    basename = os.path.splitext(os.path.basename(html_filename))[0]
    with open(html_filename, 'rb') as html_file, \
         open(os.path.join(dest_dir, basename + '.txt'), 'wb') as csv_file:
        html2csv(html_file, csv_file)

rawDescription: Iterate a piece of code over a set of files


code:
data1 = [int(line.strip()) for line in open("a.txt", 'r')]
data2 = [int(line.strip()) for line in open("b.txt", 'r')]
res = list((set(data1) - set(data2)).union(set(data2) - set(data1)))

rawDescription: how can we compare two lists which are in two different files?

description: How can we compare two lists which are in two different files


code:
text = '''\
# -*- coding: utf-8 -*-
{
    'name': "DHL connector",
    # used as subtitle
    'summary': "Configuration for DHL connector ",
    'description': """ DHL connector
    """,
    'author': "me",
    'website': "mysite.com",
    'category': 'Technical Settings',
    # Change the version every release for apps.
    'version': '0.0.1',
    # any module necessary for this one to work correctly
    'depends': [],
    # always loaded
    'data': ['views/dhl.xml', ],
    # only loaded in demonstration mode
    'demo': [],
    # only loaded in test
    'test': [],
    'installable': True,
    'application': True,
}
'''
eval(text)

rawDescription: Import dict without name from a module

description: Import dict without name from a module


code:
filename = "simple" + str(minLength) + str(minBF) + ".csv"
resfile = open(filename,"w")

rawDescription: Include changing variables into name of output file in Python


rawDescription: how to return image in python file? for django

description: Return image in python file? for django


code:
from audiolazy import *
resonator
resonator.default

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
import bottle

class AAA(object):
    def __init__(self, static_file_root):
        self.static_file_root = static_file_root

    def assign_routes(self):
        bottle.route('/aaa', 'GET', self.aaa)
        bottle.route('/static/<filename:path>', 'GET', self.send_static)

    def aaa(self):
        return ['this is aaa\n']

    def send_static(self, filename):
        return bottle.static_file(filename, self.static_file_root)

aaa = AAA('/tmp')
aaa.assign_routes()
bottle.run(host='0.0.0.0', port=8080)

rawDescription: How to convert @bottle.route to bottle.route() when serving static files?

description: Convert @bottle.route to bottle.route() when serving static files


rawDescription: How to apply a logical operator to all elements in a python list

description: Apply a logical operator to all elements in a python list


code: str_array.sort(key = mykey)

rawDescription: python string array sorting

description: Python string array sorting


code:
levels = [df.index.get_level_values(i) for i in range(df.index.nlevels)]
levels
levels[1] = levels[1].str.decode('iso-8859-1').str.encode('utf-8')
df.index = pd.MultiIndex.from_arrays(levels)

rawDescription: Change string encoding of pandas MultiIndex


rawDescription: Converting multiple columns with timestamp values to GMT time without using DateTimeIndex in pandas


code:
def square(x):
    return square.func_globals['mul'](x, x)

rawDescription: Query on local frame and global frame in python Environment


code:
key2offset = {}
with open(secondfile) as f:
    offset = 0
    for line in f:
        new_offset = f.tell()
        key2line[getkey(line)] = offset
        offset = new_offset

rawDescription: Iterate through a file multiple times

description: Iterate through a file multiple times


code:
import numpy as np
import pandas as pd
df.apply(acf)

rawDescription: how to apply a function which takes the caller as its arugment

description: Apply a function which takes the caller as its arugment


code:
import numpy as np

def dist(p1, p2):
    # Initially, p1.shape() == (n, 2) and p2.shape() == (m, 2)
    # Now, p1.shape() == (1, n, 2) and p2.shape() == (m, 1, 2)
    p1 = p1[np.newaxis, :, :]
    p2 = p2[:, np.newaxis, :]

    # get all the vectory things
    from numpy import sin, cos, radians, sqrt, arctan2 as atan2

    # do the same math as before, but use `p[..., 0]` instead of `p.x` etc
    dlat = radians(p2[..., 0] - p1[..., 0])
    dlon = radians(p2[..., 1] - p1[..., 1])
    a = sin(dlat/2) * sin(dlat/2) + cos(p1[..., 0])*cos(p2[..., 0]) * sin(dlon/2) * sin(dlon/2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = 6371 * c
    return d

def distanceQuery(neighbor_pts):
    return np.max(dist(neighbor_pts, neighbor_pts))

rawDescription: Speed up python code - can I vectorize double for loop?


rawDescription: convert string into int()

description: Convert string into int()


rawDescription: Inserting rows into dataframe by reindexing


code: inner_has_been_true = inner_has_been_true | True

rawDescription: Python: Concise way to toggle boolean "once" (i.e., in one direction)


code:
def draw(self):
    for actor in self._actors:
        self._screen.blit(resource_manager[actor.image_key], actor.pos)

rawDescription: How should I serialize game objects containing pygame surfaces?


code: ax.bar(x, data, color=colors)

rawDescription: multi colored plots in matplotlib plt based on certain properties of data

description: Multi colored plots in matplotlib plt based on certain properties of data


code:
from lxml import etree as ET
from pprint import pprint
data = """<?xml version="1.0"?>
<d:data xmlns:d="dns">
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor d:name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</d:data>"""
root = ET.fromstring(data)
my_namespaces = {'x':'dns'}
xp=root.xpath("/x:data/country/neighbor/@x:name", namespaces=my_namespaces)
pprint(xp)
xp=root.xpath("//@x:name", namespaces=my_namespaces)
pprint(xp)
xp=root.xpath("/x:data/country/neighbor/@name", namespaces=my_namespaces)
pprint(xp)

rawDescription: How can I make my code more readable and DRYer when working with XML namespaces in Python?

description: Make my code more readable and DRYer when working with XML namespaces in Python


code:
for e in s:
    break
# e is now an element from s

rawDescription: How to retrieve an element from a set without removing it?

description: Retrieve an element from a set without removing it


code:
import numpy as np
img = [0x00, 0x01, 0x02, 0x03]
img
x = y = 2
aimg = np.array(img).reshape(x, y)
aimg
np.flipud(aimg)

rawDescription: Flip (reverse) image vertically given its string?


code:
import pandas
data_2010 = pandas.read_csv("/path/to/2010.csv")
data_2010.groupby("category").agg([len, sum])

rawDescription: Simple cross-tabulation in pandas

description: Simple cross-tabulation in pandas


code:
import csv
with open('file.csv', 'wb') as f:
    writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    writer.writerows(B)

rawDescription: How to reshape a list of tuples in Python?

description: Reshape a list of tuples in Python


code: target = np.array([x[1] for x in data])

rawDescription: How to feed numeric data into a classifier?

description: Feed numeric data into a classifier


code:
_end = '_end_'

def make_trie(*words):
    root = dict()
    for word in words:
        current_dict = root
        for letter in word:
            current_dict = current_dict.setdefault(letter, {})
        current_dict[_end] = _end
    return root

make_trie('foo', 'bar', 'baz', 'barz')

rawDescription: How to create a TRIE in Python

description: Create a TRIE in Python


code:
dict_features = defaultdict(dict)
def regexp_features(fileids):
    for fileid in fileids:
        if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)):
            dict_features[fileid]['oskorblenie'] = '1'
        else:
            dict_features[fileid]['oskorblenie'] = '0'

        if re.search(r'честны*|труд*', agit_corpus.raw(fileid)):
            dict_features[fileid]['samoprezentacia'] = '1'
        else:
            dict_features[fileid]['samoprezentacia'] = '0'
    return dict_features

rawDescription: Dictionary of dictionaries in loop in Python


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

fig  = plt.figure()
ax   = fig.add_subplot(111)
my_values = np.cumsum(np.random.random(100)-0.5).reshape(-1, 2)
lines = ax.plot(my_values)
ax.legend(lines, ['eenie', 'meenie'], loc='best')
plt.show()

rawDescription: Adding legends to plots when not using the pyplot interface


code:
checkNameSet = set(map(tuple, checkNameArr))
found = []
notfound = []
for i in queryNameArr:
    if tuple(i) in checkNameSet:
        found.append(i)
    else:
        notfound.append(i)

rawDescription: Iterating and comparing list of lists in Python


code:
class file_with_pos(object):
    def __init__(self, fp):
        self.fp = fp
        self.pos = 0
    def read(self, *args):
        data = self.fp.read(*args)
        self.pos += len(data)
        return data
    def tell(self):
        return self.pos

rawDescription: How to get byte offset in a file in python

description: Get byte offset in a file in python


code:
# Import the json library
import json

# Get the Json data from the question into a variable...
data_from_api = """{
"response_code": 200,
  "train_number": "12229",
  "position": "at Source",
  "route": [
    {
      "no": 1,
      "has_arrived": false,
      "has_departed": false,
      "scharr": "Source",
      "scharr_date": "15 Nov 2015",
      "actarr_date": "15 Nov 2015",
      "station": "LKO",
      "actdep": "22:15",
      "schdep": "22:15",
      "actarr": "00:00",
      "distance": "0",
      "day": 0
    },
    {
      "actdep": "23:40",
      "scharr": "23:38",
      "schdep": "23:40",
      "actarr": "23:38",
      "no": 2,
      "has_departed": false,
      "scharr_date": "15 Nov 2015",
      "has_arrived": false,
      "station": "HRI",
      "distance": "101",
      "actarr_date": "15 Nov 2015",
      "day": 0
    }
  ]
}"""

# Convert that data into a python object...
info = json.loads(data_from_api)

rawDescription: Converting "true" (JSON) to Python equivalent "True"


code: restore = []

rawDescription: How do I copy only the values and not the references from a Python list?

description: Copy only the values and not the references from a Python list


code:
if seconds > 300 or get_update_count(myClass) < 2:
    #and update updatecount
    update(myClass)
else:
    #reset update count
    retrieveFromCache(myClass)

rawDescription: How to improve a simple caching mechanism in Python?

description: Improve a simple caching mechanism in Python


code:
import pathlib
import sys

def get_module_name(path):
    f = pathlib.Path(path).resolve()
    for i in map(pathlib.Path, sys.path):
        try:
            f.relative_to(i)
        except ValueError:
            pass
        else:
            *parts, fname = f.relative_to(i).parts
            return ".".join(parts), [f.stem]

module, fromlist = get_module_name("Programming/Python/kernprof.py")

print(module, fromlist)

imported_module = __import__(module, fromlist=fromlist)

print(imported_module)
print(getattr(imported_module, fromlist[0]))

rawDescription: Given a path to a Python source file, how do I find which package the file belongs to?


rawDescription: how to skip blocks of text when writing file in python

description: Skip blocks of text when writing file in python


rawDescription: Efficient manipulations of binary matrix in numpy


code:
import numpy as np
x = np.arange(200).reshape((4,5,10))
np.savetxt('test.txt', x)

rawDescription: How to write a multidimensional array to a text file?

description: Write a multidimensional array to a text file


code:
def bekkers_cdf(x,a,m,d,range_start,range_end):
    values = []
    for value in x:
        integral = integrate.quad(lambda k: bekkers(k,a,m,d),range_start,value)[0]
        normalized = integral/integrate.quad(lambda k: bekkers(k,a,m,d),range_start,range_end)[0]
        values.append(normalized)
    return np.array(values)

rawDescription: How to perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python?

description: Perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python


code:
dfs = dict(list(df.groupby(df["col5"].isnull())))
dfs[False]
dfs[True]

rawDescription: How to filter NA values and add it to a new DataFrame

description: Filter NA values and add it to a new DataFrame


code: cursor.execute("""insert into Tableimport(name) values (?)""", (k,))

rawDescription: How to import access table to another access table using Python

description: Import access table to another access table using Python


code:
class Enemy:
    def __init__(self, name, health):
        self.name = name
        self.health = health
    def __repr__(self):
        return self.name

rawDescription: Python - Can't create instances from a list or random instances


code:
from django.conf.urls import patterns, include, url
from solid_i18n.urls import solid_i18n_patterns

# urls without language, this can be skipped
urlpatterns = patterns(''
    # ...
)

# urls, that must have default language at root url and prefixes for other languages
urlpatterns += solid_i18n_patterns('',
    url(r'^about/$', 'about.view', name='about'),
    # ...
)

rawDescription: Default language when using i18n_patterns


code:
DISPLAY_DT_TIMEOUT = 10
MAX_DISPLAY_COUNT = 3
COUNT_TIMEOUT = 4

rawDescription: How to cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout

description: Cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout


rawDescription: Printing unicode characters to stdout in python prints wrong glyphs


code:
import multiprocessing

workers = multiprocessing.cpu_count()
bind = "127.0.0.1:5000"
worker_class = 'gevent'
worker_connections = 30

rawDescription: Flask with gevent multicore

description: Flask with gevent multicore


code:
c1=c0.tocsr()
c1.data
c1.A

rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


code: collect(a*x**2 + b*x**2 + a*x - b*x + c, x)

rawDescription: coefficient grouping: coefficient equation from a longer expression

description: Coefficient grouping: coefficient equation from a longer expression


code: [x[0] == 'good' for x in df.index]

rawDescription: Get boolean array (or generator) from pandas DataFrame index


code:
t = threading.Thread(name = 'dial', target = contact_user, args = (A,B,C))
t.start()

rawDescription: python pygame threading

description: Python pygame threading


rawDescription: how to select tables with scrapy?

description: Select tables with scrapy


code: from mymodules import *

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

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


code:
from collections import defaultdict
import re

def humantime2seconds(s):
    d = {
      'w':      7*24*60*60,
      'week':   7*24*60*60,
      'weeks':  7*24*60*60,
      'd':      24*60*60,
      'day':    24*60*60,
      'days':   24*60*60,
      'h':      60*60,
      'hr':     60*60,
      'hour':   60*60,
      'hours':  60*60,
      'm':      60,
      'min':    60,
      'mins':   60,
      'minute': 60,
      'minutes':60
    }
    mult_items = defaultdict(lambda: 1).copy()
    mult_items.update(d)

    parts = re.search(r'^(\d+)([^\d]*)', s.lower().replace(' ', ''))
    if parts:
        return int(parts.group(1)) * mult_items[parts.group(2)] + humantime2seconds(re.sub(r'^(\d+)([^\d]*)', '', s.lower()))
    else:
        return 0

df['seconds'] = df.driving_duration_text.map(humantime2seconds)

rawDescription: Convert Varied Text Fields of Duration to Seconds in Pandas


code:
mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5

rawDescription: How to remove the square brackets from a list when it is printed/output

description: Remove the square brackets from a list when it is printed/output


code:
from autobahn.twisted import wamp
from autobahn.wamp import types
from twisted.internet.defer import inlineCallbacks

class Server(wamp.ApplicationSession):
    def __init__(self, *args, **kwargs):
        wamp.ApplicationSession.__init__(self, *args, **kwargs)
        self.sessions = {}

    def onJoin(self, details):
        def on_client_join(details):
            client_id = details['session']
            self.sessions[client_id] = {}

        def on_client_leave(client_id):
            self.sessions.pop(client_id)

        self.subscribe(on_client_join, 'wamp.session.on_join')
        self.subscribe(on_client_leave, 'wamp.session.on_leave')

        def get_session(details):
            return self.sessions[details.caller]

        @inlineCallbacks
        def append(data, details):
            session = yield self.call('get_session', details)
            d = session.setdefault('data', [])
            d.append(data)

        @inlineCallbacks
        def get(details):
            session = yield self.call('get_session', details)
            return ''.join(session['data'])

        reg_options = types.RegisterOptions(details_arg='details')
        self.register(get_session, 'get_session')
        self.register(append, 'append', options=reg_options)
        self.register(get, 'get', options=reg_options)

rawDescription: Crossbar.io/Autobahn server side session storage


code:
env = config.get_jinja2_environment()
env.filters['sort_multi'] = sort_multi

rawDescription: Stable sorting in Jinja2

description: Stable sorting in Jinja2


code:
import argparse

parser = argparse.ArgumentParser(description="A dummy program")
parser.add_argument('positional', nargs="+", help="A positional argument")
parser.add_argument('--optional', help="An optional argument")

args = parser.parse_args()

rawDescription: Optparser-print Usage Help when no argument is given


code:
class1.a
class1.func1()

rawDescription: Access a Python variable which is inside a function, in another function


code:
import ast
ast.literal_eval('(1,2,3)')

rawDescription: Simple way to convert tuple wrapped as a string to a tuple in python


code:
values = ((book["rw"], book["rg"]) for book in books)
avg_review, avg_rating = [sum(xs) / len(books) for xs in zip(*values)]

rawDescription: Can I do a reduce on a list comprehension into two lists, based on two values?

description: Do a reduce on a list comprehension into two lists, based on two values


code:
def jsd_loopy(A,I):
    dists = np.empty((A.shape[0],I.shape[0]))
    for i, x in enumerate(A):
        for j, y in enumerate(I):
            dists[i,j] = jsd(x, y)
    ID = dists.argmax(1)
    return np.vstack((dists[np.arange(dists.shape[0]),ID],ID)).T

rawDescription: Applying a function for all pairwise rows in two matrices under Numpy


code:
with open("myfile.txt") as afile:
    line_lengths = [len(line) - len(line.lstrip()) for line in afile]

rawDescription: Python check string indentation

description: Python check string indentation


code: p - y

rawDescription: Inverse function of numpy.polyval()

description: Inverse function of numpy.polyval()


code:
def bitwise_or(num1, num2):
    new_num1 =list(num1[2:])
    new_num2 = list(num2[2:])
    if len(num1) > len(num2):
        new_num2[:0] = '0' * (len(num1) - len(num2))
    elif len(num1) < len(num2):
        new_num1[:0] = '0' * (len(num2) - len(num1))

    new_num = []
    for c1, c2 in zip(new_num1, new_num2):
        if c1 == "1" or c2 == "1":
            new_num.append("1")
        else:
            new_num.append(c1)
    return '0b' + ''.join(new_num)

rawDescription: What is wrong with this alternative bitwise operator function?


rawDescription: How to generate scale-independent random floating point numbers?

description: Generate scale-independent random floating point numbers


code:
class Rectangle(object):
  def __init__(self, top_corner, width, height):
    self._x = top_corner[0]
    self._y = top_corner[1]
    self._width = width
    self._height = height

  def get_bottom_right(self):
    d = self._x + self.width
    t = self._y + self.height
    return (d,t)

rawDescription: Defining a class in python in python

description: Defining a class in python in python


code:
# This buffer for the bluk insertion
global products_buffer

products_buffer = []

# Append product to the list
def add_to_products_buffer(product):
  global products_buffer
  products_buffer.append(product)

# Get the length of the product
def get_products_buffer_len():
  global products_buffer
  return len(products_buffer)

# Get the products list
def get_products_buffer():
  global products_buffer
  return products_buffer

# Empty the list
def empty_products_buffer():
  global products_buffer
  products_buffer[:] = []

rawDescription: Batch/Bulk SQL insert in Scrapy Pipelines [PostgreSQL]


rawDescription: plotting coordinate as a matrix matplotlib python

description: Plotting coordinate as a matrix matplotlib python


rawDescription: BeautifulSoup: Extract "img alt" content Web Scraping in Python


code:
import re
import sys

text = sys.stdin.read()

# using str.find()
result = text[:text.find('\n\n') + 1]

# using re
result2 = re.match(r'(.*?)$^$', text, flags=re.DOTALL | re.MULTILINE).group(1)

# check that the result is the same
for r in [result, result2]:
     print(repr(r))
assert result == result2

rawDescription: Match multi-line using python in linux

description: Match multi-line using python in linux


code: time.sleep(_sleep_time + 30) # sleep 30 seconds more so some other files might be outdated during that time too...

rawDescription: Limiting the lifetime of a file in Python


code: generate_link = lambda link: 'http://www.youtube.com/v/'+re.compile(r'watch\?v=(.*?)(?:&|$)').search(link).group(1)+'?version=3&hl=en_US'

rawDescription: Generating Links to Youtube Audio

description: Generating Links to Youtube Audio


code:
cities = {"London": (10, 15), "New York": (20, 50)}
def find_closest_city(location):
    ...

city_count = collections.Counter([find_closest_city(el) for el in elements])

rawDescription: Incrementing variable counter when iterating through a list


code:
names = [i['name'] for i in rows]
heights = [float(i['height']) if i['height'] else 0.0 for i in rows]
weights = [float(i['weight']) if i['weight'] else 0.0 for i in rows]

rawDescription: creating lists from text file using pandas in python

description: Creating lists from text file using pandas in python


code:
payload = {'format': 'json', 'key': 'site:dummy+type:example+group:wheel'}

payload_str = "&".join("%s=%s" % (k,v) for k,v in payload.items())
# 'format=json&key=site:dummy+type:example+group:wheel'

r = requests.get(url, params=payload_str)

rawDescription: How to prevent python requests from percent encoding my URLs?

description: Prevent python requests from percent encoding my URLs


code:
def search(req):
    if req.GET:
        search_term = req.GET['term']
        results = ModelToSearch.objects.filter(field__istartswith=search_term)
        return render_to_response('search.html', {'results': results})
    return render_to_response('search.html', {})

rawDescription: search form with django+python

description: Search form with django+python


code:
class Block(models.Model):
    lesson = models.ForeignKey('Lesson')
    name = models.CharField(max_length=100)

    @property
    def contents(self):
        return [bc.content for bc in self.blockcontents_set.all()]

rawDescription: Calling fields in added set in Django

description: Calling fields in added set in Django


code: sum(rate[g] * amount[g] / sum(amount) for g in range(len(rate)))

rawDescription: Python - Weighted averaging a list

description: Python - Weighted averaging a list


rawDescription: how to disable windows speech recognition commands?

description: Disable windows speech recognition commands


code:
import re
from bs4 import BeautifulSoup as BS

def freeze_html(path):
    '''pass in absolute path of your html'''
    with open(path, 'rb') as f:
        soup = BS(f.read())
    for img in soup.find_all('img'):
        m = re.search(r"data:image/png;base64,b'(.*)'", img['src'])
        if m:
            # remove '\n'
            s = m.group(1).replace(r'\n', '')
            img['src'] = 'data:image/png;base64,' + s
    with open(path, 'wb') as f:
        f.write(soup.encode('utf-8'))

rawDescription: ipython notebook .png figures after nbconvert not loaded by latest chrome/firefox

description: Ipython notebook .png figures after nbconvert not loaded by latest chrome/firefox


code:
import os
import grp
gid = grp.getgrnam('foo').gr_gid

file_list = []
for fle in os.listdir('dir'):
    if os.stat(fle).st_gid == gid:
        file_list.append(fle)

rawDescription: Python - list files that belong to specific 'group'


rawDescription: Can I make PyYAML apply one %TAG directive to multiple documents in one stream?

description: Make PyYAML apply one %TAG directive to multiple documents in one stream


code:
a
b = remove_fields(a, ['i', 'j'])
b

rawDescription: How to remove a column from a structured numpy array *without copying it*?

description: Remove a column from a structured numpy array *without copying it*


code:
def vectorized_interaction(s,alpha,kprop):

    im = complex(0,1)
    I = np.array([[1,0,0],[0,1,0],[0,0,1]])
    k2 = kprop*kprop

    # Vectorized calculations for dx, R, n, kR, A
    sd = s[:,None] - s
    Rv = np.sqrt((sd**2).sum(2))
    nv = sd/Rv[:,:,None]
    kRv = Rv*kprop
    Av = (1./(kRv*kRv)) - im/kRv

    # Vectorized calculation for: "nxn = np.outer(n, n)"
    nxnv = nv[:,:,:,None]*nv[:,:,None,:]

    # Vectorized calculation for: "(3*A-1)*nxn + (1-A)*I"
    P = (3*Av[:,:,None,None]-1)*nxnv + (1-Av[:,:,None,None])*I

    # Vectorized calculation for: "-alpha*(k2*np.exp(im*kR))/R"
    multv = -alpha*(k2*np.exp(im*kRv))/Rv

    # Vectorized calculation for: "nxn *= -alpha*(k2*np.exp(im*kR))/R"
    outv = P*multv[:,:,None,None]

    # Simulate ELSE part of the conditional statement"if i != j:"
    # with masked setting to I on the last two dimensions
    outv[np.eye((N),dtype=bool)] = I

    return outv.transpose(0,2,1,3).reshape(N*3,-1)

rawDescription: Cython speedup isn't as large as expected


rawDescription: How to remove decimal points in pandas

description: Remove decimal points in pandas


code:
thelist = [ [pay_number, pay_date, pay_amount], [pay_number, pay_date, pay_amount], ... ]

for sub_list in thelist:
    current_pay_date = sub_list[1]
    # do something with current_pay_date

rawDescription: Python, Get element from list

description: Python, Get element from list


code:
try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3 made maketrans a static method
    maketrans = str.maketrans

vowels = 'aeiouy'
upper_map = maketrans(vowels, vowels.upper())
mystring.translate(upper_map)

rawDescription: python how to uppercase some characters in string

description: Python how to uppercase some characters in string


code: property()

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code:
a = np.array([[[1, 1],
               [2, 2]],

              [[3, 3],
               [4, 4]]])

for items in np.ndenumerate(a):
    print(items)

rawDescription: Writing a 3D numpy array to files including its indices


code:
import numpy as np

C = [[1,1], [10,10]]
X = [[1,2], [1,3], [2,1], [10,11], [10,12], [11,11], [12,11], [9,11]]

def F(C,X):
    Carr = np.array(C)
    Xarr = np.array(X)
    distances = [np.sum( (Xarr - Carr[i])**2, axis=1) for i in range(len(C))]
    closests = np.argmin( np.array(distances), axis=0 )
    return list( np.bincount(closests) )

print(F(C,X))

rawDescription: finding nearest points in python

description: Finding nearest points in python


rawDescription: python - comparing order of list without sorting existing data

description: Python - comparing order of list without sorting existing data


code:
transitionFunction('A')
transitionFunction('B')

# is equivalent to
transitionFunction('B')
transitionFunction('A')

rawDescription: Using multiprocessing with multiple return values and ordered dictionaries


code:
class MyTimeDelta:
    __div__ = divtd

rawDescription: How can I perform divison on a datetime.timedelta in python?

description: Perform divison on a datetime.timedelta in python


code:
h = format(data, 'x')
import binascii
print(binascii.unhexlify(h))

rawDescription: Changing Vabinary(Max) back to text<MS SQL "2005">


code:
# zeroMQ_settings.py keep the settings for zeroMQ, for example port, IP, and topics that
# we need to subscribe

# Set the Port to 5558
server_subscriber_ports = ["5556", "5558"]

# Set IP to localhost
server_subscriber_IP = "localhost"

# Set Message to Subscribe: metrics.dat
server_subscriber_topic_metrics = "metrics.dat"

# Set Message to Subscribe: test-010
server_subscribe_topics_test_010 = "test-010"

# List of Subscriptions
server_subscribe_list = [server_subscriber_topic_metrics, server_subscribe_topics_test_010]

rawDescription: Python Tornado - How to create background process?


code:
list(treeGet(zipcode1, 'PostalCodeNumber'))
list(treeGet(zipcode2, 'PostalCodeNumber'))

rawDescription: Python: Searching a multi-dimensional dictionary for a key


code: denomination = forms.ModelChoiceField(queryset=Denomination.objects.all(), widget=forms.RadioSelect)

rawDescription: Django RadioSelect Choices From Model

description: Django RadioSelect Choices From Model


code:
df.xs('a', level='chart', axis=1)
df.xs('a', level='chart', axis=1).plot()  # win

rawDescription: Commodity Futures Hierarchical Data Structure


code: zip(*[i.split('_') for i in l])

rawDescription: How do I split the lists in python

description: Split the lists in python


rawDescription: ZMQ: No subscription message on XPUB socket for multiple subscribers (Last Value Caching pattern)


rawDescription: Python regex expression to match pattern in sentences


code:
d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
    orig_vals=d[key]
    new_vals=[]
    count = 0
    for val in orig_vals:
        try:
            new_vals+=d[val]
            count+=1
            if count >= yournumberhere: break
        except KeyError:
            pass
    d[key] = list(set(new_vals)-set(orig_vals))

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


code:
contours = ax.contourf(data)
for pathcoll in contours.collections:
    pathcoll.set_rasterized(True)

rawDescription: Reducing size of vectorized contourplot

description: Reducing size of vectorized contourplot


code:
for x in first10000:
    do_something_with(x)

rawDescription: Is there a way to read 10000 lines from a file in python?


rawDescription: Filter a dict of dict

description: Filter a dict of dict


code:
pandas.tools.plotting.scatter_matrix(df, alpha=0.2,
c='red', hist_kwds={'color':['burlywood']})

rawDescription: How to use color coding for intervals for scatter plot matrix in a python pandas code?

description: Use color coding for intervals for scatter plot matrix in a python pandas code


code:
repl = {'*': 'star', '%': 'pct', '&': 'and'}
for a, b in repl.items():
    string = string.replace(a, b)

rawDescription: Replacing a string's content with something from a list or dictionary in Python 3


code:
def ScalarMult(A,s):
    As = []
    for row in A:
        Arow = []
        for i in row:
            Arow.append(s*i)
        As.append(Arow)
    return As

rawDescription: How do nested list comprehensions work in python?


rawDescription: Pandas dataframe: how to find missing years in a timeseries?


rawDescription: Pandas multi-index slices for level names


rawDescription: Resize QMainWindow to minimal size after content of layout changes


rawDescription: Read an undefined number of columns in Python and plot data with matplotlib


code:
def get_col_0(row):
    return row[0]
max_row = max(csv.reader(f), key=get_col_0)

rawDescription: CSV find max in column and append new data


code:
EXTENSIONS = ('doc', 'docx')
soup.find("td", text=lambda text: text and text.endswith(EXTENSIONS)).get_text()

rawDescription: BeautifulSoup4 table

description: BeautifulSoup4 table


code:
# copy of /usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py
# with fix:
class FigureCanvasTkAggFix(FigureCanvasTkAgg):
  def __init__(self, figure, master=None, resize_callback=None):
    matplotlib.backends.backend_tkagg.FigureCanvasAgg.__init__(self, figure)
    self._idle = True
    t1,t2,w,h = self.figure.bbox.bounds
    w, h = int(w), int(h)
    self._tkcanvas = tk.Canvas(
      master=master, width=w, height=h, borderwidth=4)
    self._tkphoto = tk.PhotoImage(
      master=self._tkcanvas, width=w, height=h)
    self._tkcanvas.create_image(int(w/2), int(h/2), image=self._tkphoto) # fix
    self._resize_callback = resize_callback
    self._tkcanvas.bind("<Configure>", self.resize)
    self._tkcanvas.bind("<Key>", self.key_press)
    self._tkcanvas.bind("<Motion>", self.motion_notify_event)
    self._tkcanvas.bind("<KeyRelease>", self.key_release)
    for name in "<Button-1>", "<Button-2>", "<Button-3>":
      self._tkcanvas.bind(name, self.button_press_event)
    for name in "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>":
      self._tkcanvas.bind(name, self.button_release_event)
    for name in "<Button-4>", "<Button-5>":
      self._tkcanvas.bind(name, self.scroll_event)
    root = self._tkcanvas.winfo_toplevel()
    root.bind("<MouseWheel>", self.scroll_event_windows)
    self._master = master
    self._tkcanvas.focus_set()
    self.sourced = dict()
    def on_idle(*ignore):
      self.idle_event()
      return True
  def resize(self, event):
    width, height = event.width, event.height
    printse("WH", width, height, "\n")
    if self._resize_callback is not None:
      self._resize_callback(event)
    # compute desired figure size in inches
    dpival = self.figure.dpi
    winch = width/dpival
    hinch = height/dpival
    self.figure.set_size_inches(winch, hinch)
    self._tkcanvas.delete(self._tkphoto)
    self._tkphoto = tk.PhotoImage(
      master=self._tkcanvas, width=width, height=height)
    self._tkcanvas.create_image(width/2,height/2,image=self._tkphoto)
    self.resize_event()
    self.show()

rawDescription: Matplotlib - _tkinter.TclError: bad screen distance "320.0"


code:
def a_func(handle,color):
   ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

a_func(handle,AQUA)

rawDescription: Color Function in Python

description: Color Function in Python


code:
import numpy as np
import scipy.optimize as opt

#Some variables
cost = np.array([1.800, 0.433, 0.180])
p = np.array([0.480, 0.080, 0.020])
e = np.array([0.744, 0.800, 0.142])

#Our function
fun = lambda x: np.sum(x*cost)

#Our conditions
cond = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 100},
        {'type': 'ineq', 'fun': lambda x: np.sum(p*x) - 24},
        {'type': 'ineq', 'fun': lambda x: np.sum(e*x) - 76},
        {'type': 'ineq', 'fun': lambda x: -1*x[2] + 2})

bnds = ((0,100),(0,100),(0,100))
guess = [20,30,50]
opt.minimize(fun, guess, method='SLSQP', bounds=bnds, constraints = cond)

rawDescription: Migrating from PuLP to Scipy

description: Migrating from PuLP to Scipy


code:
root = tkinter.Tk()
input = tkinter.Text(root)
input.configure(state=tkinter.DISABLED)

rawDescription: Python Tkinter read only text field

description: Python Tkinter read only text field


code:
from scrapy.utils.misc import walk_modules
from scrapy.utils.spider import iter_spider_classes

def _load_spiders(module='spiders.SomeSpider'):
    for module in walk_modules(module):
        for spcls in iter_spider_classes(module):
            self._spiders[spcls.name] = spcls

rawDescription: How does Scrapy find Spider class by its name?


code:
#! /usr/bin/python2.7
import random
import sys
from PIL import Image, ImageDraw

im, pattern, samples = sys.argv [1:]
samples = int (samples)

im = Image.open (im)
walnut = Image.open (pattern)
pixels = []
while len (pixels) < samples:
    x = random.randint (0, walnut.size [0] - 1)
    y = random.randint (0, walnut.size [1] - 1)
    pixel = walnut.getpixel ( (x, y) )
    if pixel [-1] > 200:
        pixels.append ( ( (x, y), pixel [:-1] ) )

def diff (a, b):
    return sum ( (a - b) ** 2 for a, b in zip (a, b) )

best = []

for x in range (im.size [0] ):
    for y in range (im.size [1] ):
        d = 0
        for coor, pixel in pixels:
            try:
                ipixel = im.getpixel ( (x + coor [0], y + coor [1] ) )
                d += diff (ipixel, pixel)
            except IndexError:
                d += 256 ** 2 * 3
        best.append ( (d, x, y) )
        best.sort (key = lambda x: x [0] )
        best = best [:3]

draw = ImageDraw.Draw (im)
for best in best:
    x, y = best [1:]
    draw.rectangle ( (x, y, x + walnut.size [0], y + walnut.size [1] ), outline = 'red')
im.save ('out.png')

rawDescription: Finding the position of an object in an image


code:
IS_IN_SET(('sunday','monday','tuesday','wednesday','thursday','friday','saturday'),
          multiple=(2, 2))

rawDescription: How to define list of enumerated values in Web2Py

description: Define list of enumerated values in Web2Py


code:
def get_nic_data():
    lshw_cmd = ['lshw', '-json']
    proc = subprocess.Popen(lshw_cmd, stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
    return proc.communicate()[0]

def find_class(data, class_):
    for entry in data.get('children', []):
        if entry.get('class') == class_:
            yield entry

        for child in find_class(entry, class_):
            yield child

def read_data(proc_output, class_='network'):
    import json

    for entry in find_class(json.loads(proc_output), class_):
        yield entry['vendor'], entry['description'], entry['product']

rawDescription: Python iterate a subprocess that returns json?


code:
from IPython.core.debugger import Pdb
ipdb = Pdb()

rawDescription: Is the python ipdb package available inside another package?


code: ['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep']

rawDescription: In python, how would I sort a list of strings where the location of the string comparison changes?


code:
import requests
token = xxx-xxxx
stopcode = 70142
query_args = {"token":token, "stopcode":stopcode}
r = request.get(url, params = query_args)
r.text

rawDescription: Using Urllib2 with 511 api that requires token


code:
from pygame.draw import circle, rectangle
circle(args)
rectangle(args)

#  or
from pygame import draw
draw.circle(args)
draw.rectangle(args)

#  or
import pygame
pygame.draw.circle(args)

rawDescription: How can I organize my functions to get something like class.draw.line() instead of class.drawLine

description: Organize my functions to get something like class.draw.line() instead of class.drawLine


code:
mystr = "long" \
"str"
mystr

rawDescription: breaking up long path names

description: Breaking up long path names


rawDescription: Regex Python findall. Making things nonredundant


code:
import xml.etree.ElementTree as ET
xml = '<tag>Some example text</tag>'
tree = ET.fromstring(xml)
print(''.join(tree.itertext()))

rawDescription: Python element tree - extract text from element, stripping tags


code:
def are_coplanar(plane1, plane2):
  # planes are given as [a, b, c, d], ax+by+cz=d
  return numpy.all(plane1 / length(plane1) - plane2 / length(plane2) == 0)

rawDescription: coplanar equations of a plane

description: Coplanar equations of a plane


code:
import grequests
import requests_cache

session = requests_cache.CachedSession('bla')

urls = [
    'http://www.heroku.com',
    'http://python-tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u, session=session) for u in urls)
results = grequests.map(rs)

rawDescription: Is it possible to make grequests and requests_cache work together?


rawDescription: Python memory mapping

description: Python memory mapping


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

nx = 150
ny = 50

fig = plt.figure()
data = np.zeros((nx, ny))
im = plt.imshow(data, cmap='gist_gray_r', vmin=0, vmax=1)

def init():
    im.set_data(np.zeros((nx, ny)))

def animate(i):
    xi = i // ny
    yi = i % ny
    data[xi, yi] = 1
    im.set_data(data)
    return im

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=nx * ny,
                               interval=50)

rawDescription: How to update matplotlib's imshow() window interactively?

description: Update matplotlib's imshow() window interactively


rawDescription: python how to make a simple countdown program

description: Python how to make a simple countdown program


code: ['apple 1', 'banana 1']

rawDescription: adding arrays inside dictionaries, inside more arrays?

description: Adding arrays inside dictionaries, inside more arrays


code:
def serialize_queryset(resource_class, queryset):
    # hand me a queryset, i give you dehydrated resources
    resource = resource_class()
    dd = {}

    # make meta
    dd['meta'] = {}
    dd['meta']['limit'] = 1000
    dd['meta']['next'] = None
    dd['meta']['offset'] = 0
    dd['meta']['previous'] = None
    dd['meta']['total_count'] = len(queryset)

    # objects
    dd['objects'] = []
    for obj in queryset:
        bundle = resource.build_bundle(obj=obj)
        dehydrated_obj = resource.full_dehydrate(bundle)
        dd['objects'].append(dehydrated_obj)

    # return dict
    return dd

rawDescription: How to add data to tastypie resources in regular django views

description: Add data to tastypie resources in regular django views


code: cs0, cs1, cs2, cs3, cs4 = [list_cs[i][1] for i in range(5)]

rawDescription: create variable for one tuple item at the end of a list

description: Create variable for one tuple item at the end of a list


code:
import mechanize
br = mechanize.Browser()
br.open('http://www.w3schools.com/html/html_forms.asp')

rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python


rawDescription: Python - sparse vectors/distance calculation


code:
class UserViewSet(viewsets.ModelViewSet):
    lookup_field = 'email'
    lookup_url_kwarg = 'email'

rawDescription: How to delete a User with particular email using Django REST framework

description: Delete a User with particular email using Django REST framework


code: header = np.fromfile(fobj, dtype=dt, count=1)[0]

rawDescription: numpy fromfile and structured arrays

description: Numpy fromfile and structured arrays


code:
SERIALIZATION_MODULES = {
    'json': 'wadofstuff.django.serializers.json'
}

rawDescription: Serializing Foreign Key objects in Django


code:
seen = set()
original, modified = zip(*((o, m) for (o, m) in zip(original, modified) if m not in seen and not seen.add(m)))

rawDescription: Deduping a complex list using a simplified copy of itself


code:
import numpy as np

# Convert to numpy array
arr = np.asarray(a,float)

# Pad around the input array to take care of boundary conditions
arr_pad = np.lib.pad(arr, (1,1), 'wrap')

R,C = np.where(arr==0)   # Row, column indices for zero elements in input array
N = arr_pad.shape[1]     # Number of rows in input array

offset = np.array([-N, -1, 1, N])
idx = np.ravel_multi_index((R+1,C+1),arr_pad.shape)[:,None] + offset

arr_out = arr.copy()
arr_out[R,C] = arr_pad.ravel()[idx].sum(1)/4

rawDescription: Python get get average of neighbours in matrix with na value


code: df

rawDescription: python pandas: Rename a series within a dataframe?

description: Python pandas: Rename a series within a dataframe


code:
#!/usr/bin/env python3

def generate_ints_nth_digit_divisible_by_n(n=1, number=0):
    number *= 10
    if n == 10:
        yield number  # divisible by 10
    else:
        for digit in range(not number, 10):
            candidate = number + digit
            if candidate % n == 0:  # divisible by n
                yield from generate_ints_nth_digit_divisible_by_n(n + 1, candidate)

print("\n".join(map(str, generate_ints_nth_digit_divisible_by_n())))

rawDescription: Python: Code to find a number where first N digits are divisible by N (from 0-9)


code:
x = list((v[:3], v[3:]) for v in l)
x

rawDescription: Ordering a nested dictionary by the frequency of the nested value


code: struct.pack('<l10s', 1234, bytearray([0]*10)) # In Python 3.x

rawDescription: Convert an int and bytearray into a ByteString Python struct Socket


code: x = raw_input("blablabla")

rawDescription: Why isn't my while loop, looping?

description: Why isn't my while loop, looping


code: ['Hello', 'my', 'name', 'is', 'Gareth', 'and', 'in', 'this', 'video', 'I', 'm', 'going', 'to', 'talk', 'about', 'list', 'comprehensions', 'in', 'Python']

rawDescription: Python program to extract text from a text file?


code:
def array_equal(a1, a2):
    try:
        a1, a2 = asarray(a1), asarray(a2)
    except:
        return False
    if a1.shape != a2.shape:
        return False
    return bool(asarray(a1 == a2).all())

rawDescription: Numpy C-Api array_equal

description: Numpy C-Api array_equal


code:
import sympy as sym

U,X = sym.symbols('U,X')
pplus_sym = sym.lambdify(X,sym.integrate((3*U+2)*(-4*(X-U)-4),(U,0,X)))
dic = {'Min': sp.minimum}; #it's best if we tell lambdify what to use for Min
pdivide_sym = sym.lambdify(X,sym.integrate(U*(3*U+2)*(-4*(U/X)-4),(U,0,sym.Min(X,1)))/(X**2),dic)

rawDescription: How to compute integrals dependent upon two variables with SciPy?

description: Compute integrals dependent upon two variables with SciPy


code:
self._morse_char_map = {
    code: letter
    for letter, code in self._char_morse_map.items()
}

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


code:
def check_future_pants(x, df):
    date_condition = x.date < df.date
    pant_condition = df.item == "'pants'"
    return (date_condition & pant_condition).any()

def check_df_pants(df):
    return df.apply(lambda x: check_future_pants(x, df), axis=1)

df['will_buy_pants'] = df.groupby('id', group_keys=False).apply(check_df_pants)

rawDescription: Pandas check for future condition by group


code: df.groupby('Letters').filter(lambda x: len(x) > 2).groupby('Letters').Bool.sum()

rawDescription: How to filter based on a boolean in a column and return a groupby obj

description: Filter based on a boolean in a column and return a groupby obj


code:
import inspect
inspect.getargspec(foo)

rawDescription: Get the order of parameters for python function?


rawDescription: Python ftplib - any way to shut it up?

description: Python ftplib - any way to shut it up


rawDescription: Speeding up outliers check on a pandas Series


rawDescription: Sum item inside a tuple

description: Sum item inside a tuple


code: list(itertools.product(x, repeat=5))

rawDescription: Finding combinations where the length of the combination is more then the variables being used


rawDescription: Python regex: How to match an empty string?


code:
my_set = set()
my_set
my_set.update([1,2,3])
my_set
my_set.update(["this","is","stuff"])
my_set
my_set.add('apricot')
my_set
my_set.remove("is")
my_set

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
locations = []
locations.append("London")
locations

rawDescription: Transforming a checkboxGroupInput object into a vector


code:
Import('env')

env.Program("test", ["#/object/test.o"])
env.Program("sdl-test", ["#/object/sdl_test.o"], LIBS=["SDL2"])

rawDescription: scons: objects, sources, executables, all in separate directories

description: Scons: objects, sources, executables, all in separate directories


code:
@coroutine
def do_something_else():
    future = asyncio.Future()
    result = yield from some_function()
    future.set_result(result)
    return future # Now yield from do_something_else() returns 5.

rawDescription: Python asyncio: return vs set_result

description: Python asyncio: return vs set_result


code:
md1 = '''
# Hello world

I am text

* No really

'''

md2 = '''
# Hi world

I am text

* No really

'''

rawDescription: How to compare two models to be rendered with Markdown using Django?

description: Compare two models to be rendered with Markdown using Django


code:
import time
import multiprocessing as mp
import random
import Queue

def process_messages(q):
    messages = []
    start = time.time()
    while True:
        try:
            message = q.get(timeout=1)
        except Queue.Empty:
            pass
        else:
            messages.append(message)
            print('Doing data analysis on {}'.format(message))
        end = time.time()
        if end-start > 60:
            print('Updating database: {}'.format(messages))
            start = end
            messages = []

def get_messages(q):
    while True:
        time.sleep(random.uniform(0,5))
        message = random.randrange(100)
        q.put(message)

if __name__ == "__main__":
    q = mp.Queue()

    proc1 = mp.Process(target=get_messages, args=[q])
    proc1.start()

    proc2 = mp.Process(target=process_messages, args=[q])
    proc2.start()

    proc1.join()
    proc2.join()

rawDescription: Consume Kafka continuously and update queue at specific intervals using multiprocessing


rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code: GPIO.add_event_detect(GPIO_ONOFF, GPIO.FALLING, callback=quit_loop, bouncetime=300)

rawDescription: Python GPIO wait for either of two buttons to be pressed


rawDescription: How to create an 'contact book' in python using dictionaries?

description: Create an 'contact book' in python using dictionaries


code:
class Enum:
    __metaclass__ = EnumMetaclass

rawDescription: Unexpected: flufl.enum prints integer value


code:
with open('nameOfYourSaveFile', 'w') as saveFile:
    #.write() does not automatically add a newline, like print does
    saveFile.write(myString + "\n")

rawDescription: Python- Saving Results to a File and Recalling Them


rawDescription: Regarding ascii and python packing

description: Regarding ascii and python packing


code: df['Probability'] = np.where(df.index < 10, 's', 'f')

rawDescription: Pandas map by index value without dummy column


code:
words = ("audino bagon baltoy banette bidoof braviary bronzor carracosta "
         "charmeleon cresselia croagunk darmanitan deino emboar emolga "
         "exeggcute gabite girafarig gulpin haxorus")

words = frozenset(words.split())

rawDescription: Python word game. Last letter of first word == first letter of second word. Find longest possible sequence of words


code:
def page_number(item, items_per_page):
    # 1-based numbering assumed; first item is 1, first page is 1
    return (item - 1) // items_per_page + 1

rawDescription: Iterate over double values to produce page numbers


code:
json_pkloads = functools.partial(json.loads, object_hook=as_python_object)

pyobj = json_pkloads(json_str)

rawDescription: Making object JSON serializable with regular encoder


code:
# Python 2.x only
import codecs
import csv

class Recoder(object):
    def __init__(self, stream, decoder, encoder, eol='\r\n'):
        self._stream = stream
        self._decoder = decoder if isinstance(decoder, codecs.IncrementalDecoder) else codecs.getincrementaldecoder(decoder)()
        self._encoder = encoder if isinstance(encoder, codecs.IncrementalEncoder) else codecs.getincrementalencoder(encoder)()
        self._buf = ''
        self._eol = eol
        self._reachedEof = False

    def read(self, size=None):
        r = self._stream.read(size)
        raw = self._decoder.decode(r, size is None)
        return self._encoder.encode(raw)

    def __iter__(self):
        return self

    def __next__(self):
        if self._reachedEof:
            raise StopIteration()
        while True:
            line,eol,rest = self._buf.partition(self._eol)
            if eol == self._eol:
                self._buf = rest
                return self._encoder.encode(line + eol)
            raw = self._stream.read(1024)
            if raw == '':
                self._decoder.decode(b'', True)
                self._reachedEof = True
                return self._encoder.encode(self._buf)
            self._buf += self._decoder.decode(raw)
    next = __next__

    def close(self):
        return self._stream.close()

with open('test.csv','rb') as f:
    sr = Recoder(f, 'utf-16', 'utf-8')

    for row in csv.reader(sr):
        print (row)

rawDescription: Python UTF-16 CSV reader

description: Python UTF-16 CSV reader


rawDescription: Case insensitive sort with peewee

description: Case insensitive sort with peewee


rawDescription: python all combinations of subsets of a string

description: Python all combinations of subsets of a string


code:
try:
    # Python 3
    from collections.abc import MutableSet
except ImportError:
    # Python 2
    from collections import MutableSet

class CasePreservingSet(MutableSet):
    def __init__(self, *values):
        self._values = {}
        for v in values:
            self.add(v)

    def __repr__(self):
        return '<{}{} at {:x}>'.format(
            type(self).__name__, tuple(self._values.values()), id(self))

    def __contains__(self, value):
        return value.lower() in self._values

    def __iter__(self):
        try:
            # Python 2
            return self._values.itervalues()
        except AttributeError:
            # Python 3
            return iter(self._values.values())

    def __len__(self):
        return len(self._values)

    def add(self, value):
        self._values[value.lower()] = value

    def discard(self, value):
        try:
            del self._values[value.lower()]
        except KeyError:
            pass

rawDescription: How to get Case Insensitive Python SET

description: Get Case Insensitive Python SET


code:
def musical_chairs(people, steps):
    index = 0
    people = list(people)
    while len(people) > 1:
        index = (index + steps) % len(people)
        del people[index]
        index -= 1
    return people

rawDescription: Controlling the flow of for loop in python