code:
import subprocess

product    = '765377'
scriptPath = './uploadImageToBigcommerce.ps1'

def qq(s):
    return "'%s'" % s

def process_image(sku, fileType, searchDirectory, destinationPath, scriptPath):
    psCode = '. ' + scriptPath + '; Process-Image ' + qq(fileType) + ' ' + \
             qq(searchDirectory) + ' ' + qq(destinationPath)
    subprocess.call(['powershell', '-Command', '& {'+psCode+'}'], shell=True)

process_image(product, '.jpg', 'C:\Images', 'C:\webDAV', scriptPath)

rawDescription: How to run a line in Powershell in Python 2.7?

description: Run a line in Powershell in Python 2.7


code:
import json
import pytest
import smtplib

def load_params_from_json(json_path):
    with open(json_path) as f:
        return json.load(f)

@pytest.fixture(scope="module", params=load_params_from_json('path/to/file.json'))
def smtp(request):
    smtp = smtplib.SMTP(request.param)
    def fin():
        print ("finalizing %s" % smtp)
        smtp.close()
    request.addfinalizer(fin)
    return smtp

rawDescription: pytest parametrized fixture - parameters from json?

description: Pytest parametrized fixture - parameters from json


rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


code: env.hosts = [str(server_ip_var)]

rawDescription: Class 'list' does not define '__mod__', so the '%' operator cannot be used


code: newlist = alist[:]

rawDescription: python lists, appending something to the list changes the entire thing?

description: Python lists, appending something to the list changes the entire thing


code:
with open('A.txt') as f1, open('B.txt') as f2:
   #create a dict from fileB and don't forget to convert the count to an integer
   dic = {word : int(val)  for word, val in (line.split() for line in f2)}
   #now iterate over each line in fileA
   for line in f1:
      words = line.split()
      #get the count using `sum()`
      #dict.get would return 0 if key is not found in dic
      count = sum(dic.get(word, 0) for word in words)
      if count == 5:
         print (line, end='')  #or `print (line.strip())`

rawDescription: opening 2 files and adding values python

description: Opening 2 files and adding values python


code:
import re
import codecs

with codecs.open("test.unicode.txt","rb", "utf-8") as f:
    words = []
    for line in f.readlines():
        matches = re.match(b"solution:.+\[(?P<word>\w+).*\]", line, flags=re.U)
        if matches:
            words.append(matches.groups()[0])

print(words)

rawDescription: how to remove all staff by using regular Expression

description: Remove all staff by using regular Expression


code:
# Split Names and Pivot.
df['NAME_NBR'] = df['NAMES'].str.split('_').str.get(1)
df['NAMES'] = df['NAMES'].str.split('_').str.get(0)
df = df.pivot(index='NAMES', columns='NAME_NBR', values='VALUE')

# Rename columns and reset the index.
df.columns = ['VALUE{}'.format(c) for c in df.columns]
df.reset_index(inplace=True)

rawDescription: How to move duplicate rows into columns with python

description: Move duplicate rows into columns with python


code: map(data.get, order)

rawDescription: sort dict by key list

description: Sort dict by key list


code:
try:
    idx[0]
except AttributeError:
    idx = (idx, slice(None, None, None))

rawDescription: Implementing 2D slicing in Python

description: Implementing 2D slicing in Python


code:
from django.contrib import admin
from localsite.models import MyOrganization
from satchmo_store.contact.models import Organization
from satchmo_store.contact.admin import OrganizationOptions

admin.site.unregister(Organization)
admin.site.register(MyOrganization, OrganizationOptions)

rawDescription: Insert a new field in a specific admin view?


code:
def anno():
    for idx in xrange(248956422):
        elm = "0"

        for j in range(0, len(whole_st_gen)):
            if whole_st_gen[j] <= idx < whole_end_gen[j]:
                elm = "1"

        for j in range(0, len(whole_st_ex)):
            if whole_st_ex[j] <= idx < whole_end_ex[j]:
                elm = "2"

        for j in range(0, len(whole_st_mr)):
            if whole_st_mr[j] <= idx < whole_end_mr[j]:
                elm = "3"

        for j in range(0, len(whole_st_nc)):
            if whole_st_nc[j] <= idx < whole_end_nc[j]:
                elm = "4"

        yield elm

rawDescription: Memoryerror with too big list

description: Memoryerror with too big list


rawDescription: Python: Click by coordinate inside a window


rawDescription: Python spliting a list based on a delimiter word


code:
print >> f, '>', alignment.title
print >> f, hsp.sbjct

rawDescription: Saving output of a for-loop to file

description: Saving output of a for-loop to file


code: angles = 2 * math.pi * np.random.rand(N)

rawDescription: Defining velocity in a boid simulation

description: Defining velocity in a boid simulation


code: [v.split('=') for v in s.split('&')]

rawDescription: Looking for a Python shorthand way of parsing a url encoded string into tuples


code:
#import for 3d
from mpl_toolkits.mplot3d import Axes3D

import numpy as np
import matplotlib.pyplot as plt

rawDescription: Python: How to revolve a surface around z axis and make a 3d plot?


code:
# You have
class CatListView(LoginRequiredMixin, ListView):
    # You could use this view for the complete list
    ...

# You can create a new one
# And modify get_queryset method

class OwnedByUserCatListView(CatListView):
    def get_queryset(self):
        max_price = self.request.GET.get('max_price')
        if max_price is None or max_price == '':
            max_price = 1000000000
        min_price = self.request.GET.get('min_price')
        if min_price is None or min_price == '':
            min_price = min(Cat.objects.filter().values_list('cat_price'))[0]

        cat_list = Cat.objects.filter(cat_price__gte=min_price) \
            .filter(cat_price__lte=max_price).filter(cat_owner__exact=self.request.user).order_by('-cat_pub_date')

        paginator = Paginator(cat_list, 20)
        page = self.request.GET.get('page')
        try:
            cat_list = paginator.page(page)
        except PageNotAnInteger:
            cat_list = paginator.page(1)
        except EmptyPage:
            cat_list = paginator.page(paginator.num_pages)

        return cat_list

rawDescription: What is the best way to write two similiar ListView or render to similar lists in different templates in django?


code:
import unittest

class Food(object):
    def __init__(self):
        self.consumed = False

    def consume(self):
        self.consumed = True

class Fruit(Food):
    def __init__(self):
        super(Fruit, self).__init__()
        self.been_cut = False

    def cut(self):
        print("cut the fruit")
        self.been_cut = True

class Consumer(object):
    def __init__(self):
        self.apple = Fruit()
        self.banana = Fruit()

    def consume_food(self):
        food = self.pick_food()
        food.cut()
        print("consuming the food")
        food.consume()

    def pick_food(self):
        return self.apple

rawDescription: Python unittesting for a class method

description: Python unittesting for a class method


code:
chunk = 10
sz = 235

lst = list(range(sz - chunk, 0, -chunk))
print(lst)

rawDescription: Reading a binary file on backwards using python


code:
a: 1   # comment 1
b: 2
c: 3   # comment 2
d: 4
e: 5    #  comment 3

rawDescription: Ruamel.yaml: How to access merge keys and comments in loaded OrderedDict


code: matline = yentry

rawDescription: Python: array values somehow getting changed


code:
class Volunteer(models.Model):
    def __unicode__(self):
        return self.fname + self.lname
    fname = models.CharField(max_length=200)
    lname = models.CharField(max_length=200)
    bio = models.TextField(max_length=400)
    number = models.CharField(max_length=15)
    email = modesl.CharField(max_length=255)

rawDescription: django forms into database

description: Django forms into database


code: pmf = ts.value_counts().sort_index() / len(ts)

rawDescription: How to plot a PMF of a sample?

description: Plot a PMF of a sample


code:
txt_demo = QtGui.QLineEdit()
txt_demo.mousePressEvent = lambda _ : txt_demo.selectAll()

rawDescription: Pyside - Select all text when QLineEdit gets focus


rawDescription: libavg custom event handler

description: Libavg custom event handler


code:
def profile(f):
    is_evaluating = False
    def g(x):
        nonlocal is_evaluating
        if is_evaluating:
            return f(x)
        else:
            start_time = time.clock()
            is_evaluating = True
            try:
                value = f(x)
            finally:
                is_evaluating = False
            end_time = time.clock()
            print('time taken: {time}'.format(time=end_time-start_time))
            return value
    return g

rawDescription: Python: Counting executing time of a recursion function with decorator


code:
class CommentAdd(AjaxableResponseMixin, CreateView):
    form_class = CommentForm
    ...

rawDescription: Is any way to create hidden form field in CreateView form?


code:
x = 32
y = 48

for m in range(0, 6):

    print('chr:', end='')
    for i in range(x, y):
        print('  %s ' % chr(i), end='')
    print('')

    print('asc:', end='')

    if (m == 5):
        print(' ', end='')

    for j in range(x, y):

        if (m == 4 and j == 100):
            print(' ', end='')

        print('{:^4}'.format(j), end='')

    print('')

    x = x + 16
    y = y + 16

rawDescription: How can I fix the spacing of this ASCII table?

description: Fix the spacing of this ASCII table


rawDescription: How to extract a number from a request.path in Django

description: Extract a number from a request.path in Django


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

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 1

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
                return

def playerHasHitShoot(playerRect, shootRect):
    if playerRect.colliderect(shootRect):
        return True
    return False

def baddieHasHitShoot(baddieRect, shootRect):
    if baddieRect.colliderect(shootRect):
        return True
    return False

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def fire(shoot):
    shootRect.topleft = ((playerRect / 2), 101)
    shootRect.move_ip(5, 1)

pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
icon = pygame.image.load('icon.bmp').convert_alpha()
pygame.display.set_icon(icon)
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gamestart.wav')
pygame.mixer.music.load('background.wav')

playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()

drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()

topScore = 0
while True:

    score = 10000
    playerRect.topleft = (0, 100)
    baddieRect.topright = (600, 100)
    moveUp = moveDown = False
    pygame.mixer.music.play(-1, 0.0)

    UPDOWN = False# if true go up, else go down DEFINE UPDOWN
    while True:
        #I ADDED IN THE BELOW lines. They were just not positioned correctly in your code
        #update the position
        print ("got here #1")
        if UPDOWN:
            baddieRect.move_ip(0, -5)
        elif not UPDOWN:
            baddieRect.move_ip(0, 5)
        print ("got here #2")
        # where your code is not quite right
        if baddieRect.bottom > WINDOWHEIGHT: #correct
            UPDOWN = True
        #yours baddieRect.bottom < WINDOWHEIGHT
        #mine elif baddieRect.top < 0
        elif baddieRect.top < 0: # tests if the 'baddie' hits the top
            UPDOWN = False

        score -= countBy

        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                if event.key == ord(' '):
                    fire
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True

            if event.type == KEYUP:
                if event.key == ord(' '):
                    fire
                if event.key == K_ESCAPE:
                        terminate()
                if event.key == K_UP or event.key == ord('w'):
                    moveUp = False
                if event.key == K_DOWN or event.key == ord('s'):
                    moveDown = False

        if moveUp and playerRect.top > 0:
            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerRect.move_ip(0, PLAYERMOVERATE)

        sb = pygame.image.load('sb.png')
        screen.blit(sb, (600, 600))
        screen.fill(BGC)

        #got rid of the next line which is why I commented it out. as main is no longer a function
        #main()

        drawText('Score: %s' % (score), font, screen, 10, 0)
        drawText('Top Score: %s' % (topScore), font, screen, 10, 40)

        screen.blit(playerImage, playerRect)
        screen.blit(shootImage, shootRect)
        screen.blit(baddieImage, baddieRect)
        pygame.display.update()

        if playerHasHitShoot(playerRect, shootRect):
            score = 0
            break

        if baddieHasHitShoot(baddieRect, shootRect):
            if score > topScore:
                score = topscore
                break
        mainClock.tick(FPS)

    pygame.mixer.music.stop()
    gameOverSound.play()
    drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
    drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    pygame.display.update()
    waitForPlayerToPressKey()
    gameOverSound.stop()

rawDescription: how to get a sprite to move top to bottom in a loop

description: Get a sprite to move top to bottom in a loop


code:
import dbf
some_table = dbf.Table('dbf_file')
some_table.rename_field('oldname', 'newname')

rawDescription: How can I rename the field names of a .dbf file when reading it with dbfpy?

description: Rename the field names of a .dbf file when reading it with dbfpy


code:
if os.path.exists(adresse) :
    with open(adresse,"r") as f:
        reader = list(csv.reader(f , delimiter = ","))
        reader.pop(1)
        with open(adresse,"w") as out:
            writer = csv.writer(out,delimiter = ",")
            for row in reader:
                writer.writerow(row)

rawDescription: How to remove the second line of a CSV file using Python

description: Remove the second line of a CSV file using Python


code:
dis.dis(compile('list()', '', 'eval'))
dis.dis(compile('dict()', '', 'eval'))

rawDescription: Why is [] faster than list()?

description: Why is [] faster than list()


code:
index = sum(x.index for x in frames)
res = pd.DataFrame(index=index, columns=cols)

rawDescription: Concatenate Pandas DataFrames with Multiindex columns and irregular timestamps


code:
statement = "SELECT * FROM table"
if filterList:
    statement += " WHERE column IN ({0})".format(
        ', '.join(['%s'] * len(filterList)))
cursor.execute(statement, filterList)

rawDescription: MySQL and PYTHON. How to query an WHERE 'column' IN tuple


code:
def setup_default_flat_pages_db(db):
    class Page(db.Model):
        name = db.Column(db.String(255), primary_key=True)
        title = db.Column(db.String(255))
        content = db.Column(db.String(255))

        def __init__(self, name, title, content):
            self.name = name
            self.title = title
            self.content = content

    class FlatPagesDBO(object):
        def find_page_by_name(self, name):
            return Page.query.filter_by(name=name).first()

    return FlatPagesDBO()

rawDescription: Using Flask-SQLAlchemy in Blueprint models without reference to the app


rawDescription: Can't read file after split line?

description: Can't read file after split line


code:
specials = np.any(condition, axis=1)
print(table[specials, :2])

rawDescription: How can I assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python?

description: Assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python


code:
def extract_data(s):
    check_set = set(['E1', 'E2', 'E7', 'E3', 'E9', 'E10', 'E12',
                     'IN1', 'IN2', 'IN4', 'IN10'])
    result = []
    for match in re.finditer(r'\b(E|IN)[-\d]+', s):
        for digits in re.findall(r'\d+', match.group(0)):
            item = match.group(1) + digits
            if item in check_set:
                result.append(item)
    return result

rawDescription: Extracting data according to a list

description: Extracting data according to a list


code:
import Tkinter as tk
import getpass
import time

class WelcomeClock(tk.Frame):
    def __init__(self,parent):
        tk.Frame.__init__(self,parent)
        self.parent = parent
        self.timevar = tk.StringVar()
        self.__set_time()
        self.initialize()

    def initialize(self):
        message = "Welcome %s!\nThe time is currently"%(getpass.getuser().capitalize())
        self.welcome = tk.Label(self,text=message)
        self.welcome.pack(anchor=tk.N)
        self.clock = tk.Label(self,textvar=self.timevar)
        self.clock.pack()

    def __set_time(self):
        self.timevar.set(time.strftime("%Y-%m-%d %H:%M:%S"))
        self.after(499,self.__set_time)

if __name__ == "__main__":
    root = tk.Tk()
    clock = WelcomeClock(root)
    clock.pack()
    root.mainloop()

rawDescription: Python GUI and Class Structure

description: Python GUI and Class Structure


code:
from shapely.geometry import LineString, MultiPolygon
from shapely.ops import polygonize, unary_union

# original data
ls = LineString(np.c_[x, y])
# closed, non-simple
lr = LineString(ls.coords[:] + ls.coords[0:1])
lr.is_simple  # False

rawDescription: Splitting self-intersecting polygon only returned one polygon in shapely in Python


rawDescription: How to webscrape this website

description: Webscrape this website


code:
import struct
def binary(num):
    return ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') for c in struct.pack('!f', num))

rawDescription: Binary representation of float in Python (bits not hex)


code:
def changeColour(event):
    event.widget.config(bg="white")

#...

LT = Button(root, width=16, height=8, bg = "blue")
LT.bind("<1>", changeColour)
LT.place(x=10, y=10)

rawDescription: How can I configure multiple buttons with one function in Tkinter?

description: Configure multiple buttons with one function in Tkinter


code:
def flattenlen(a):
    total = 0
    stack = [a]
    while stack:
        lst = stack.pop()
        for i in lst:
            if isinstance(i, list):
                stack.append(i)
            else:
                total += 1
    return total

rawDescription: Retrieving the length of a list after flattening


rawDescription: Trying to write my own Neural Network in Python


code:
from petsc4py import PETSc
import scipy.sparse
csr_mat = scipy.sparse.rand(1000, 1000, density=0.001, format='csr')
petsc_mat = PETSc.Mat().createAIJ(size=csr_mat.shape,
                                  csr=(csr_mat.indptr, csr_mat.indices,
                                       csr_mat.data))

rawDescription: scipy sparse matrices as an input for petsc4py

description: Scipy sparse matrices as an input for petsc4py


rawDescription: How to properly parse request strings with Twisted (python)

description: Properly parse request strings with Twisted (python)


code:
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

rawDescription: What is the most "pythonic" way to iterate over a list in chunks?


code:
with open('file1.txt') as in_:
    mapping = {}
    for line in in_:
        key,value = line.strip().split(',')
        mapping[key] = int(value)

rawDescription: Manipulating text files

description: Manipulating text files


code: print(varulista)

rawDescription: function and classes, usage of __str__

description: Function and classes, usage of __str__


code:
@pytest.fixture()
def test_package(request, version='1.0'):
    ...
    request.addfinalizer(fin)
    ...
    return package

rawDescription: py.test: Pass a parameter to a fixture function

description: Py.test: Pass a parameter to a fixture function


rawDescription: Unexpected behaviour of np.sum which acts as np.ravel


rawDescription: set modalities as new columns

description: Set modalities as new columns


code:
df = pd.DataFrame([ {'kw_0' : 0, 'kw_1' : 0, 'kw_2' : 0, 'x' : i, 'y': i} for i in range(10) ])
df
df.columns = MultiIndex.from_tuples([('kw',0),('kw',1),('kw',2),('value','x'),('value','y')])
df

rawDescription: mixing 3 dimenional and 2 dimensional data in a pandas dataframe

description: Mixing 3 dimenional and 2 dimensional data in a pandas dataframe


code:
## Matplotlib Sample Code using 2D arrays via meshgrid
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')
plt.show()

rawDescription: How to surface plot/3d plot from dataframe?

description: Surface plot/3d plot from dataframe


rawDescription: Use same string format for multiple items in Python 3


code:
from class2_file import class2
class class1:
    def dummy(self, obj):      # To avoid confusion changed the variable name
        obj.dummy()

class1().dummy(class2())       # import is needed for `class2()` part only

rawDescription: Python Passing Class Object in to anther Class


code: return (line for line in open(file_path1) if key(line.lower()) not in key_set)

rawDescription: Compare two text files and return the difference (case insensitive)


code: return [[y,x]] + getConnectedZeros(x+1, y) + getConnectedZeros(x-1, y) + getConnectedZeros(x, y+1) + getConnectedZeros(x, y-1)

rawDescription: How do I break out of this recursive loop?

description: Break out of this recursive loop


code: job_json = job_list.values()

rawDescription: Using jquery variable to get specific ajax request


code: ['sample', 'sentence', 'such', 'as', 'well-being']

rawDescription: python regular expressions -- split on non-word char or consecutive dashes, but not on single dash

description: Python regular expressions -- split on non-word char or consecutive dashes, but not on single dash


code:
import tkinter as tk
from matplotlib.mathtext import math_to_image
from io import BytesIO
from PIL import ImageTk, Image

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):

        #Creating buffer for storing image in memory
        buffer = BytesIO()

        #Writing png image with our rendered greek alpha to buffer
        math_to_image('$\\alpha$', buffer, dpi=1000, format='png')

        #Remoting bufeer to 0, so that we can read from it
        buffer.seek(0)

        # Creating Pillow image object from it
        pimage= Image.open(buffer)

        #Creating PhotoImage object from Pillow image object
        image = ImageTk.PhotoImage(pimage)

        #Creating label with our image
        self.label = tk.Label(self,image=image)

        #Storing reference to our image object so it's not garbage collected,
        # as TkInter doesn't store references by itself
        self.label.img = image

        self.label.pack(side="bottom")
        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="top")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

rawDescription: How can I use matplotlib's mathtext rendering outside of matplotlib in another tk widget?

description: Use matplotlib's mathtext rendering outside of matplotlib in another tk widget


code: my_stream = open('config.ini', 'r')

rawDescription: Reading raw section with ConfigParser

description: Reading raw section with ConfigParser


code:
df2 = df.set_index('index').stack().reset_index()
df2['cumcnt'] = df2.groupby('index',as_index=False).cumcount()

rawDescription: reshape dataframe from multiple columns to one

description: Reshape dataframe from multiple columns to one


code: args_dict['foo'] = 'bar'

rawDescription: Confusing code involving lambda function


code:
driver = webdriver.Firefox()
e = driver.find_element_by_xpath("//someXpath")
location = e.location
size = e.size
print(location)
print(size)

rawDescription: Selenium: get coordinates or dimensions of element with Python


code:
df = sc.parallelize([
    (10, 0, 0), (20, 0, 0), (None, 1, 0), (None, 0, 1)
]).toDF(["age", "missing_age", "unknown_age"])

df.na.fill(df.na.drop().agg(avg("age")).first()[0], ["age"])

rawDescription: Pyspark Dataframe Imputations -- Replace Unknown & Missing Values with Column Mean based on specified condition


rawDescription: "tkinter.filedialog" does not recognize files without a suffix in its name


code:
class Client(object):
    def __init__(self, addr, sock, number):
        self.sock = sock
        self.name = '<{}> (not logged in)'.format(addr)
        self.number = number
        self.lock = threading.Lock()
        self.thread = threading.Thread(target=self.serve)
        self.thread.start()

    def send(self, msg):
        with self.lock:
            self.sock.send(msg)

    def run(self):
        for line in self.sock.makefile():
            args = line.rstrip().split()
            cmd = args.pop().upper()
            method = getattr(self, 'do_{}'.format(cmd), None)
            if method is none:
                self.write('ERROR unknown command {}\n'.format(cmd))
            else:
                try:
                    method(*args)
                except Exception as e:
                    self.send('ERROR in {}: {}\n'.format(cmd, e))
                else:
                    self.send('OK\n')

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
import world
import fakeworld
world.show = fakeworld.show
execfile('example1.py')

rawDescription: How to suppress execution of statement in script called with execfile?

description: Suppress execution of statement in script called with execfile


code:
# e.g., test("gupshup", "Gupshup")
def test(modulename, classname):
    module = import_module(module_name)
    cls = getattr(module, classname)
    instance = cls()  # maybe pass arguments to the constructor
    instance.test()

rawDescription: How do I import a module only when needed?

description: Import a module only when needed


code:
times = zip(start_times, end_times)
query = reduce(lambda a, b: a | b,
               [(db.booking.booking_end > start) &
                (db.booking.booking_start < end) for start, end in times])
conflicts = db(query).select()

rawDescription: How to check conflicts on multiple dates from a single query

description: Check conflicts on multiple dates from a single query


code:
my_string = 'hello'
my_string = my_string[-1] + my_string[:-1]
print(my_string)

rawDescription: Python - How to move characters in string by X amount


code:
# the sum of elements in an array
def sumArray(A):
    return sumArray(A, len(A)-1)

# a helper for the above
def sumArray(A, i):
    if i < 0:
        return 0
    else:
        return A[i] + sumArray(A, i-1)

print(sumArray([1,2,3]))

rawDescription: if Python doesn't support method overloading, then why does this method overload work while this other does not?

description: If Python doesn't support method overloading, then why does this method overload work while this other does not


code:
for i, v in enumerate(b):
  try:
    a[i][1] = v
  except IndexError:
    a.append([None, v])

rawDescription: filling one dimension of two-dimensional array with other array

description: Filling one dimension of two-dimensional array with other array


rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


rawDescription: Python the simplest way to plot 3d surface


code: (np.unique(a)[..., None] == a).astype(np.int)

rawDescription: Convert 1-D array of discrete values to n-D array of continuous values in Numpy


code:
...
option_group.add_argument('-a',
                      dest='cmd',
                      action='store_const',
                      const=lambda args: method_user(args.sometext))

option_group.add_argument('--list',
                      '-l',
                      dest='cmd',
                      action='store_const',
                      const=lambda args: method_list(args.sometext))
args = parser.parse_args()
args.cmd(args)

rawDescription: Python: Access argument while ArgParsing


rawDescription: python 3 print generator

description: Python 3 print generator


rawDescription: python find if newline is in string

description: Python find if newline is in string


code:
from __future__ import division

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

reducedVec = []
for chunk in grouper(ratio, vec):
    if sum(1 for x in chunk if x == 'F') > ratio / 3:
        reducedVec.append('F')
    else:
        reducedVec.append('T')

rawDescription: itertools.islice compared to list slice

description: Itertools.islice compared to list slice


code:
term = 'a'
term_counts = [chunk.count(term) for chunk in chunks]
# zip them together to make it nicer (not that zip returns an iterator with python 3.4)
chunks_with_counts = zip(chunks, term_counts)

rawDescription: How can I look inside of different chunks of strings in my Python program?

description: Look inside of different chunks of strings in my Python program


code:
from collections import defaultdict
actual_plays = defaultdict(int)
for song in required_playlist: actual_plays[song] += 1

rawDescription: Python script, runs well, but not perfectly, debugging help


code:
print("How many ducks are there?")
question(input(), "14")

rawDescription: Where to define variable working with function


code:
random = self.random
u = random()
while u <= 1e-7:
    u = random()
return -_log(u)/lambd

rawDescription: Python's random: What happens if I don't use seed(someValue)?


code: self.files = self.options.get('--files', "").split(",") or None

rawDescription: In Python, what is a minimal way of assigning a value to a variable depending on whether a dictionary contains a key?


code:
customRound(9.34)
customRound(9.4)
customRound(9.98)
customRound(9.8)

rawDescription: Python Rounding

description: Python Rounding


code: for k, v in od.items(): print(k, v)

rawDescription: How can I sort a dictionary by key?

description: Sort a dictionary by key


code:
#Context.sublime-menu
[
    { "command": "openserver", "caption": "Open on Server" }
]

#Default (Windows).sublime-keymap
[
        { "keys": ["ctrl+shift+b"], "command": "openserver" }
]

#Main.sublime-menu
[
    {
        "caption": "Tools",
        "mnemonic": "T",
        "id": "tools",
        "children":
        [
            { "command": "openserver", "caption": "Open on Server" }
        ]
    }
]

#Openserver.sublime-commands
[
    {
        "caption": "Open file on Server in Browser",
        "command": "openserver"
    }
]

#Openserver.sublime-settings
{
    "file_path_prefix": "E:/Server/htdocs",
    "url_prefix": "http://localhost"
}

rawDescription: Replace string in Python and open browser with result


code:
import os
import time

'''Find if a file was modified in the last x seconds given by writeFrequency.'''
def isFileBeingWrittenInto(filename,
                       writeFrequency = 180, overheadTimePercentage = 20):

    overhead = 1+float(overheadTimePercentage)/100 # Add some buffer time
    maxWriteFrequency = writeFrequency * overhead
    modifiedTimeStart = os.stat(filename).st_mtime # Time file last modified
    time.sleep(writeFrequency)                     # wait writeFrequency # of secs
    modifiedTimeEnd = os.stat(filename).st_mtime   # File modification time again
    if 0 < (modifiedTimeEnd - modifiedTimeStart) <= maxWriteFrequency:
        return True
    else:
        return False

if not isFileBeingWrittenInto('fileForSafeWrites.txt'):
    handle = open('fileForSafeWrites.txt', 'a')
    handle.write("Text written safely when no one else is writing to the file")
    handle.close()

rawDescription: Ensuring that my program is not doing a concurrent file write


code:
cols_to_include = df.columns[~df.columns.str.contains('foo')]
df[cols_to_include].apply(pd.Series.nunique)

rawDescription: Conditionally iterate over columns in Pandas


code:
A1
A2
B1
B2
A3
A4

rawDescription: SQLite Python printing in rows?

description: SQLite Python printing in rows


code:
index = pd.MultiIndex(levels=[['Growth %'], ['One', 'Two']], labels=[[0, 0], [0, 1]], names=[None, 'Years'])
df = pd.DataFrame(np.random.randn(2,6), index=index)
df
df.mean(axis=1)

rawDescription: How to access multiindex levels in pandas?

description: Access multiindex levels in pandas


code:
def hex2(n):
    return "0x%x"%(n&0xffffffff)

def hex3(n):
    return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]

rawDescription: How to get hex string from signed integer

description: Get hex string from signed integer


rawDescription: Using numpy loadtext

description: Using numpy loadtext


code:
def spin(s):
    while True:
        s, n = re.subn('{([^{}]*)}',
                       lambda m: random.choice(m.group(1).split("|")),
                       s)
        if n == 0: break
    return s.strip()

rawDescription: How to make article spinner regex?

description: Make article spinner regex


code: newlist = [(x - min_val)/(max_val - min_val) for x in mylist]

rawDescription: List is not showing up

description: List is not showing up


code:
dates = [md.date2num(t) for t in bars.Date]
bars['Dates'] = dates
days = np.unique(np.floor(bars['Dates']), return_index=True)
iso_days= []
for n in np.arange(len(days[0])):
    iso_days.append(datetime.date.isoformat(md.num2date(days[0][n])))

rawDescription: Issue with rotating x tick labels in matplotlib subplots


code: robot=" World"

rawDescription: Hook the global name lookup in a python interpreter


code:
import random

def gen_prime(N=10**8, bases=range(2,20000)):
    # XXX replace with a more sophisticated algorithm
    p = 1
    while any(pow(base, p-1, p) != 1 for base in bases):
        p = random.SystemRandom().randrange(N)
    return p

def multinv(modulus, value):
    '''Multiplicative inverse in a given modulus

        >>> multinv(191, 138)
        18
        >>> 18 * 138 % 191
        1

    '''
    # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
    x, lastx = 0, 1
    a, b = modulus, value
    while b:
        a, q, b = b, a // b, a % b
        x, lastx = lastx - q * x, x
    result = (1 - lastx * modulus) // value
    return result + modulus if result < 0 else result

def keygen(N):
    '''Generate public and private keys from primes up to N.

        >>> pubkey, privkey = keygen(2**64)
        >>> msg = 123456789012345
        >>> coded = pow(msg, 65537, pubkey)
        >>> plain = pow(coded, privkey, pubkey)
        >>> assert msg == plain

    '''
    # http://en.wikipedia.org/wiki/RSA
    prime1 = gen_prime(N)
    prime2 = gen_prime(N)
    totient = (prime1 - 1) * (prime2 - 1)
    return prime1 * prime2, multinv(totient, 65537)

rawDescription: Private/Public Encryption in Python with Standard Library


code: [i * 3 for i in dictionary.keys()]

rawDescription: Extracting keys-values from dictionary

description: Extracting keys-values from dictionary


code:
def get_user_pw(parent, message, title=''):
    # Returns user input as a string or None
    # If user does not input text it returns None, NOT AN EMPTY STRING.
    dialogWindow = Gtk.MessageDialog(parent,
                          Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
                          Gtk.MessageType.QUESTION,
                          Gtk.ButtonsType.OK_CANCEL,
                          message)

    dialogWindow.set_title(title)

    dialogBox = dialogWindow.get_content_area()
    userEntry = Gtk.Entry()
    userEntry.set_visibility(False)
    userEntry.set_invisible_char("*")
    userEntry.set_size_request(250,0)
    dialogBox.pack_end(userEntry, False, False, 0)

    dialogWindow.show_all()
    response = dialogWindow.run()
    text = userEntry.get_text()
    dialogWindow.destroy()
    if (response == Gtk.ResponseType.OK) and (text != ''):
        return text
    else:
        return None

rawDescription: Python/Gtk3 : How to add a Gtk.Entry to a Gtk.MessageDialog?


code:
nrow, ncol = 5, 5
uarray = (np.random.permutation(nrow * ncol) + 1).reshape(nrow, ncol)

rawDescription: Using Numpy Array to Create Unique Array


code:
def findFullURL(d, e, s):
    d = s.rfind('/', 0, d + 1)
    # You probably want to handle the condition where '/' is not found here.
    return "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"

rawDescription: Python 3.2.2 Function Returns None on Non-Empty Variable


code:
from registration.backends.default import DefaultBackend
class RedirectBackend(DefaultBackend):
    def register(self, request, **kwargs):
        request.session['redirect'] = request.GET.get("next",None)
        super(RedirectBackend, self).register(request, **kwargs)

    def post_activation_redirect(self, request, user):
        return(request.session['redirect'], (), {})

rawDescription: Getting `django-registration` to send you to the page you were originally trying to visit


code:
def left(i):
    return 2 * i + 1

def right(i):
    return 2 * i + 2

def parent(i):     # your 'left' and 'right' function is good practice, keep it
    return (i - 1) // 2

def MaxHeapify(A, heap_size, i):
    l = left(i)
    r = right(i)
    if l <= heap_size and A[l] > A[i]:
        largest = l
    else:
        largest = i
    if r <= heap_size and A[r] > A[largest]:
        largest = r
    if largest != i:
        A[i], A[largest] = A[largest], A[i]
        MaxHeapify(A, heap_size, largest)      # important: don't always sort the whole array (size of heap keeps decreasing in 'HeapSort')

def BuildMaxHeap(A):
    heap_size = len(A) - 1    # index of last element of the heap
    for i in range(parent(heap_size), -1, -1):    # don't miss i=0 iteration
        MaxHeapify(A, heap_size, i)

def HeapSort(A):
    BuildMaxHeap(A)
    heap_size = len(A) - 1
    for i in range(heap_size, 0, -1):    # ends at i=1. You don't swap A[0] with A[0], right?
        A[i], A[0] = A[0], A[i]
        MaxHeapify(A, i-1, 0)     # careful here: MaxHeapify which part of the array

rawDescription: Buggy Heap Sort

description: Buggy Heap Sort


rawDescription: How to concatenate 2 np.ndarray's?

description: Concatenate 2 np.ndarray's


code: y, zo = lfilter(b, a, s, zi=zi)

rawDescription: python recursive vectorization with timeseries

description: Python recursive vectorization with timeseries


rawDescription: Pandas - datetime format of miliseconds

description: Pandas - datetime format of miliseconds


rawDescription: python regular expression to remove u'some text' from the unicode output

description: Python regular expression to remove u'some text' from the unicode output


code:
today = dt.date.today()
prices = web.DataReader(df.symbol, 'yahoo',
                        start=today + dt.timedelta(-5), end=today)['Close'].iloc[-1, :]

rawDescription: How to iterate DataFrame column of stock symbols and add a column with the stock price?

description: Iterate DataFrame column of stock symbols and add a column with the stock price


rawDescription: Conjoin function made in functional style


code:
import multiprocessing
cores = multiprocessing.cpu_count()

rawDescription: Change the number of processes to spawn depending on the CPU usage in Python


code:
from collections import deque

with open('somefile') as fin:
    last3 = deque(fin, 3)

rawDescription: Copy the last three lines of a text file in python?


rawDescription: how to parse Flickr using flickrapi in python

description: Parse Flickr using flickrapi in python


code: return list(set(links))

rawDescription: Get list of all paginated URL's from links in txt file in python requests


code: re.findall(r'\b[this]{4}\b', st)

rawDescription: Python Regex: set combinations of prefix length


code:
import pickle

unique_genes_list = ["a", "ab", "ac", "ad"]
with open('some/path', 'rb') as in_pickle:
    old_data = pickle.load(in_pickle) ## ["a", "ab", "ac"]

## Gets just 'ad' or any other unique in a new list
new_genes = [x for x in unique_genes_list if not x in old_data] ##['ad']

## Save the new unique data
with open('some/new/path', 'wb') as out_pickle:
    pickle.dump(new_genes, out_pickle) ## dumps ["ad"]

rawDescription: python pickle: dump only unique list to pickled file

description: Python pickle: dump only unique list to pickled file


code:
# non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    bytes = in_f.read()
    out_f.write(bytes)

# also non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    lines = in_f.readlines()
    for line in lines:
        out_f.write(line)

# lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    for line in in_f:  # only gets one line at a time
        out_f.write(line) # write each line as we get it

rawDescription: Seeking guidelines for lazy-izing Python data


rawDescription: Python: While Loops, Executing the same code under different conditions. Elegance and overhead


code: ['{}{}{}'.format(e[:6], i, j) for e in lst for i, j in itertools.product(string.digits, string.digits)]

rawDescription: Append itertools.product() results to variable in Python


code:
with open('file.txt') as input_file:
    long_list = input_file.readlines()

rawDescription: Python List Maker

description: Python List Maker


code:
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=%s" % quote(recoded)
data = json.loads(urllib2.urlopen(url).read())
pprint.pprint(data)

rawDescription: How to decode string to use with Google Language Detection API?

description: Decode string to use with Google Language Detection API


rawDescription: adding values to default dict list of values

description: Adding values to default dict list of values


code: ['sony', 'samsung', 'apple', 'toshiba', 'cant recall', 'dont know', 'no answer']

rawDescription: Python - Always append certain strings to the end of a list


code:
class MainApp(App):
    def build(self):
        app_layout = AppLayout()
        AppController(app_layout)
        return app_layout

rawDescription: Separate layout and controller in kivy gui


code: x = np.reshape(list_data, (100, 28)).T

rawDescription: Python reshape list to ndim array

description: Python reshape list to ndim array


code:
import re
strs = "RED REDD REDDD REDDDDD ABCDeeeeDDDDDDDD ABCD"
[re.sub(r'[^D]+', r'', item) for item in strs.split()]

rawDescription: Filtering part of a list?

description: Filtering part of a list


code:
for (x1, y1), (x2, y2) in pairs(filter_duplicates(coords)):
   distance = getDistance(x1, y1, x2, y2)

rawDescription: Python, efficient way to operate on pair of coordinates


code:
res = wrapper([1, 2, 3])
res[0] is res[1]
res[0] is res[2]
res[0][0] = 42
res

rawDescription: Python generator cannot be converted to list


code:
def get_nums(lst):
    letters = 'abcdefghijklmnopqrstuvwxyz' # also string.ascii_lowercase
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
               17, 18, 19, 20, 21, 22, 23, 24, 25, 26] # range(1, 27)
    mapping = dict(zip(letters,numbers))
    return [mapping[lett] for lett in lst]

rawDescription: swapping inside the list in python

description: Swapping inside the list in python


code:
sort_l = []

def combine (l1,l2):
    if l1 == []:
        return l2
    elif l2 == []:
        return l1
    elif l1 == [] and l2 == []:
        return []
    index = 0
    for num in l1:
        if num <= l2[0]:
            sort_l.append(num)
            index += 1
        else:
            return combine(l2, l1[index:])
    return sort_l + l2

rawDescription: combine two list and sort recursively

description: Combine two list and sort recursively


code: s.unpack('bytes:4, 2*uint:12, uint:4')

rawDescription: Python module for implementing binary file formats?


code:
sortC = [(n, float(sum(s))/len(s)) for n,s in scores.items()]
sortC.sort(key=lambda x: x[1], reverse=True)
for name, avgScore in sortC:
    print(name, avgScore)

rawDescription: Outputting Highest/Average Score From List Of 3 (Value) For Each Student (Key) In A Dictionary Sorted From Highest To Lowest?


code:
# Equal
durations = MyModel.objects.filter(duration=datetime.timedelta(*args, **kwargs))

# Greater than or equal
durations = MyModel.objects.filter(duration__gte=datetime.timedelta(*args, **kwargs))

# Less than or equal
durations = MyModel.objects.filter(duration__lte=datetime.timedelta(*args, **kwargs))

rawDescription: How should I use DurationField in my model?


code:
list(mix_lists('abcdefg', [1, 2, 3, 4], offset=0))
list(mix_lists('abcdefg', [1, 2, 3, 4], offset=2))
list(mix_lists('abcdefg', [1, 2, 3, 4], offset=5))
list(mix_lists('abcdefg', [1, 2, 3, 4], offset=9))
mix_lists('abcdefg', [1, 2, 3, 4], offset=10)

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


code:
tree = Inner(initial_context, initial_hierarchy)
while tree:
    tree.do_something()
    tree.prune()

rawDescription: Workarounds to suspend (serialize) and resume a recursive generator stack?


rawDescription: Merging part of tuples in Python

description: Merging part of tuples in Python


code:
conditions = {
    flag1: lambda: cond1,
    flag2: lambda: cond2,
    flag3: lambda: cond3}

while conditions[flag]():
    do_stuff(parameters)

rawDescription: Python: While Loops, Executing the same code under different conditions. Elegance and overhead


code:
m = re.search(r"-0+(\d+)@", item)
found = m and m.group(1) == element

rawDescription: searching string, exclude certain substrings

description: Searching string, exclude certain substrings


code: text = u"ånd ånd med fløde... :)asd "

rawDescription: python re.compile and split with ÆØÅ charcters

description: Python re.compile and split with ÆØÅ charcters


code: Location = [x for x, y in enumerate(Master) if y in List_check]

rawDescription: Append index of items in one list to another in Python 2.7


code: setattr(obj, prop, value)

rawDescription: Python achieve pointer like behaviour

description: Python achieve pointer like behaviour


code:
class Tree(object):

    def __init__(self, data=None, left=None, right=None):
        self.left = left
        self.right = right
        self.data = data

    # The former method filler()
    @classmethod
    def from_list(cls, lista):
        if lista:
            # All non-empty lists are the same.
            # Specifially, nr = 0 for a single-element list,
            # and lista[:nr] and lista[nr+1:] are empty lists
            # in the edge cases.
            nr = len(lista) // 2
            return cls(lista[nr],
                        cls.from_list(lista[:nr]),
                        cls.from_list(lista[nr+1:]))
        else:
            return None

tree = Tree.from_list([1,2,3,4,5,6])

rawDescription: Python passing instance of class by reference


code:
def truncateToApproximateArialWidth(st, width):
    size = 0 # 1000 = 1 inch
    width = width * 1000 / 6 # Convert from picas to miliinches
    for i, s in enumerate(st):
        if s in 'lij|\' ': size += 37
        elif s in '![]fI.,:;/\\t': size += 50
        elif s in '`-(){}r"': size += 60
        elif s in '*^zcsJkvxy': size += 85
        elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
        elif s in 'BSPEAKVXY&UwNRCHD': size += 112
        elif s in 'QGOMm%W@': size += 135
        else: size += 50
        if size >= width:
            return st[:i+1]
    return st

rawDescription: Roughly approximate the width of a string of text in Python?


rawDescription: Python linesplitting into sections

description: Python linesplitting into sections


code:
for i in range(10):
    text.bind('<Control-Key-'+str(i)+'>',  key)

rawDescription: tkinter shortcuts impossible to enable

description: Tkinter shortcuts impossible to enable


code:
for files in([glob.glob(arg) for arg in sys.argv[1:]]):
    for file in files:
        with open(file, 'r') as f:
            do_something_to(f)

rawDescription: Running python from windows command prompt on many files


code:
import Tkinter
root = Tkinter.Tk()

def autosave():
    # do something you want
    root.after(60000 * 5, autosave) # time in milliseconds

autosave()
root.mainloop()

rawDescription: Auto-save function implementation with Python and Tkinter


code: orig_array[[slice(o, o+e) for o, e in zip(offset, extent)]]

rawDescription: How to get numpy sub-array view when array ndim is not known until runtime?

description: Get numpy sub-array view when array ndim is not known until runtime


code:
self.assertIsInstance(myprogram_database.create_sqla_engine(),
                      sqlalchemy.engine.base.Engine)

rawDescription: Python unit tests: type checking custom class type


code:
new_li=[t for t in li if t[1] not in 'bdeg']
new_li

rawDescription: Mapping modified string indices to original string indices in Python


code:
def callsomething(x):
    if x in (3,4,5,6): pass

import dis
dis.dis(callsomething)

rawDescription: Does program really created the inner object each time?


code:
def smooth(value, target):
    # maximum acceleration is 2
    delta_max = 2
    # minimun acceleration is 0.5
    delta = max(0.5, (abs(target) - abs(target-value)) / 10.)
    delta = min(delta, delta_max)
    if value < target:
        value = min(value + delta, target)
    else:
        value = max(value - delta, target)
    return value

rawDescription: Ramping Joystick values over time

description: Ramping Joystick values over time


code: d = {key: value for (key, value) in iterable}

rawDescription: Create a dictionary with list comprehension in Python


code:
from numpy.lib.stride_tricks import as_strided

def strided_rescale(g, bin_fac):
    strided = as_strided(g,
        shape=(g.shape[0]//bin_fac, g.shape[1]//bin_fac, bin_fac, bin_fac),
        strides=((g.strides[0]*bin_fac, g.strides[1]*bin_fac)+g.strides))
    return strided.mean(axis=-1).mean(axis=-1)  # order is NOT important! See notes..

rawDescription: Python code to quickly reduce the resolution of an image using numpy


code:
app.config["APPLICATION_ROOT"] = "/abc/123"

@app.route("/")
def index():
    return "The URL for this page is {}".format(url_for("index"))

# Will return "The URL for this page is /abc/123/"

rawDescription: Add a prefix to all Flask routes

description: Add a prefix to all Flask routes


rawDescription: Getting method calls and their arguments from method object


code:
a = range(5) # python list of numpy array
np.diff(a)

rawDescription: Numpy difference between neighboring elements


code:
L = []
for i in range(3,6):
    L.append(np.array(range(1,i)))

rawDescription: how to stack numpy array in a list

description: Stack numpy array in a list


code:
from sympy import *
x = Symbol(x)
x + x

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code:
store.get_storer('df').table.attrs
store.get_storer('df').table.attrs.values_block_0_kind = ['new','b','c']

rawDescription: Is it possible to directly rename pandas dataframe's columns stored in hdf5 file?


code:
class EntryAbstractClass(models.Model):
    """Base Model design for publishing entries"""
    STATUS_CHOICES = ((DRAFT, _('draft')),
                      (HIDDEN, _('hidden')),
                      (PUBLISHED, _('published')))

    title = models.CharField(_('title'), max_length=255)

    image = models.ImageField(_('image'), upload_to=UPLOAD_TO,
                              blank=True, help_text=_('used for illustration'))
    content = models.TextField(_('content'))
    excerpt = models.TextField(_('excerpt'), blank=True,
                                help_text=_('optional element'))

    tags = TagField(_('tags'))
    categories = models.ManyToManyField(Category, verbose_name=_('categories'),
                                        related_name='entries',
                                        blank=True, null=True)
    related = models.ManyToManyField('self', verbose_name=_('related entries'),
                                     blank=True, null=True)

    slug = models.SlugField(help_text=_('used for publication'),
                            unique_for_date='creation_date',
                            max_length=255)

    authors = models.ManyToManyField(User, verbose_name=_('authors'),
                                     related_name='entries',
                                     blank=True, null=False)

rawDescription: Create a entry object in zinnia for the view function -basic python


rawDescription: Get new datetime object according to timezone difference


rawDescription: How do I interate through a paired list when using map and lambda?

description: Interate through a paired list when using map and lambda


code:
status = client.status()
status['state']

rawDescription: How to check if mpd is playing or stopped?

description: Check if mpd is playing or stopped


code:
import numpy as np
# create a DataFrame (this can also be from an RDD)
df = sqlCtx.createDataFrame(map(lambda x:map(float, x), np.random.rand(50, 3)))
df.agg({col: "mean" for col in df.columns}).collect()

rawDescription: Spark reduceByKey on several different values


code:
itemvalues = {'Item1':[0,0,0]
}

rawDescription: python text rpg inventory system

description: Python text rpg inventory system


rawDescription: Black voodoo of NumPy Einsum

description: Black voodoo of NumPy Einsum


code:
hh = mechanize.HTTPHandler()
hsh = mechanize.HTTPSHandler()
hh.set_http_debuglevel(1)
hsh.set_http_debuglevel(1)
opener = mechanize.build_opener(hh, hsh)
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.NOTSET)
mechanize.install_opener(opener)

rawDescription: How do I get Python's Mechanize to POST an ajax request?

description: Get Python's Mechanize to POST an ajax request


code:
dnaPair = dict(A="T", T="A", C="G", G="C")
complement = [dnaPair[base] for base in dnaSeq]
complement

rawDescription: Python .split list is callable but index is out of range?


code: #!/usr/bin/env python

rawDescription: I have python file name MiscTest.py and now I want to run this file in linux with single name MiscTest only


code:
x_with_time = pd.Series(x.values, index=when)
x_with_time

rawDescription: How to add date and time information to time series data using python numpy or pandas

description: Add date and time information to time series data using python numpy or pandas


code:
from itertools import izip, imap
list(imap(lambda x: x[1] if not x[0] else x[0], izip(list1, list2)))

rawDescription: Python: merge lists or data frames and overwrite missing values


code:
class ReadModifyUpdateTest(mox.MoxTestBase):
    def test_modify(self):
        mock_record = self.mox.CreateMockAnthing()
        mock_store = self.mox.CreateMockAnything()
        mock_modifier = self.mox.CreateMockAnything()

        sequence = OrderedCallSequence(self)
        mock_store.read("test_key").WithSideEffects(sequence.assertOrder()).AndReturn(mock_record)
        mock_modifier.modify(mock_record).WithSideEffects(sequence.assertOrder())
        mock_store.update("test_key", mock_record).WithSideEffects(sequence.assertOrder())
        self.mox.ReplayAll()

        updater = ReadModifyUpdate(mock_store, mock_modifier)
        updater.modify("test_key")

rawDescription: Testing call order across mock objects with Mox and Python


code:
#!/usr/bin/env python

import re

infile = 'in.conf'
outfile = 'out.conf'

change_vars_list = (r'%var1%', r'%var2%', r'%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')

with open(infile, 'r') as inconf:
    lines = inconf.read()

    print('\nRaw lines:\n\n%s' % lines)
    print('\nVars to change:')
    print(change_vars_list)

    outdata = lines
    for var, value in zip(change_vars_list, change_values_list):
        outdata = re.sub(var, value, outdata)

    print('\nNew data:\n\n%s\n' % outdata)

with open(outfile, 'w') as outconf:
    outconf.write(outdata)

rawDescription: re.sub - multi value and multi lines substitution

description: Re.sub - multi value and multi lines substitution


code:
translation_table = dict.fromkeys(map(ord, ')(@\n#$'), None)
bucket_list = [x.translate(translation_table) for x in bucket_list ]

rawDescription: Python -unicode- translate table doesn't remove chars


code:
table = pd.pivot_table(apps, index=['app_name', 'date'],
                       columns=['is_match'],
                       values = 'rewards_count',
                       aggfunc=np.sum,
                       margins=True)

rawDescription: Pandas Column Calculations in PivotTable


rawDescription: Waiting for keypress in Tkinter

description: Waiting for keypress in Tkinter


code:
def removearticles(text):
  re.sub('\s+(a|an|and|the)(\s+)', '\2', text)

rawDescription: Remove all articles, connector words, etc., from a string in Python


code:
def swap_items(lst, index1, index2):
    lst[index1], lst[index2] = lst[index2], lst[index1]

rawDescription: Replacing two elements of a list in place with a function [python 3]


code:
s.head()
s['user3']

rawDescription: Create iterable list from very large number of entries


code:
io = bpdb.PDBIO()
io.set_structure(s)
io.save('1y26_cropped.pdb', ResSelect())

rawDescription: remove parts from a pdb file using python

description: Remove parts from a pdb file using python


code: form = Form(initial={'username': costumer.username})

rawDescription: Display a default value in form fields Django


code:
request = None
for key, value in conditions:
  new_request = Q(**{key: value})

  if request: request |= new_request
  else: request = new_request

rawDescription: How to join multiple params dynamically for django Q object

description: Join multiple params dynamically for django Q object


rawDescription: What does it mean to "call" a function in Python?


code:
import paramiko
def run_ls_la():
    client = paramiko.SSHClient()
    client.connect("myssh.server.org", username="foo", password="bar")
    stdin, stdout, stderr = client.exec_command("ls -la")
    print(stdout.read())

rawDescription: How to create 3 instances of command prompt in Windows and pass commands to each prompt in parallel using python

description: Create 3 instances of command prompt in Windows and pass commands to each prompt in parallel using python


code: S2 = A[list(set(range(100)) - set(inx))]

rawDescription: numpy random.choice elements that are not selected

description: Numpy random.choice elements that are not selected


code:
header_list = ['First Name:', 'Last Name:', 'Phone:', 'City:', 'State:', 'Zip:']
client_list = ['Joe', 'Somebody', '911', 'Somewhere', 'AA', '012345']

for head, entry in zip(header_list, client_list):
    print(head, entry)

rawDescription: How to loop through a list inside of a loop

description: Loop through a list inside of a loop


code:
from contextlib import nested

with nested(patch("foo.load",side_effects=["a","b","c"]), patch("bar.check",return_value=True)) as (mock_load, mock_check):
    take_action()
    assert mock_load.called
    assert mock_check.called

rawDescription: patch multiple methods from different modules (using Python mock)

description: Patch multiple methods from different modules (using Python mock)


code:
# Note: This is Python2.x specific. It's identical except for the import on 3.x
import cPickle as pickle
import numpy as np

data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]

with open('mat.pkl', 'wb') as outfile:
    pickle.dump(data, outfile, pickle.HIGHEST_PROTOCOL)

with open('mat.pkl', 'rb') as infile:
    result = pickle.load(infile)

rawDescription: NumPy save some arrays at once

description: NumPy save some arrays at once


code: data = {'code':'this is the code', 'some':'other', 'stuff':'here'}

rawDescription: How to make a specific key the first key in a dictionary?

description: Make a specific key the first key in a dictionary


code: Data = [strip_suffixes(w) for w in wordlist]

rawDescription: Conditional Removal of suffix from words in a python list


code:
from tkinter import *
filedialog

rawDescription: filedialog, tkinter and opening files

description: Filedialog, tkinter and opening files


code:
a_iter = iter(a); next(a_iter)
[k for i,j in zip(a, a_iter) for k in [i] + [(0,n) for n in range(i[1]+1, j[1])]] + a[-1:]

rawDescription: Insert missing elements in a nested list based on a condition - Python


code:
class ShoppingList (models.Model):
    user = models.ForeignKey(User,related_name="user_shoplist")
    list_name = models.CharField(max_length=200)
    # your other fields...

class Item(models.Model):
    from_list = models.ForeignKey(ShoppingList, related_name="list_items")
    item_name = models.CharField(max_length=200)
    # more fields..

#user actions
user = request.user
user_shoplist = user.user_shoplist.create(list_name="Dolls")

#adding items to shopping list
new_item1 = user_shoplist.list_items.create(item_name='barbie')
new_item2 = user_shoplist.list_items.create(item_name='teddy')
#.... etc etc

# all shopping lists of a user
user_shopping_lists = user.user_shoplist.all()

#all items in a shopping list of a user ("user_shoplist" from above)
all_items_in_a_shoppinglist = user_shoplist.list_items.all()

rawDescription: dont get how to make connection

description: Dont get how to make connection


code:
#FinalGrade

results = []

print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Institution = str(input("Please Enter the Name of Your Insitution: "))

while True:
   print ("\n")
   print ("---------------------------------NEW STUDENT---------------------------------")
   print ("\n")
   Year = str(input("Please Enter the Year of the Student (For Example, 'Year 1 / 2 / 3 / 4'): "))
   print ("\n")
   print ("-----------------------------------------------------------------------------")
   print ("\n")
   Student = str(input("Student Full Name: "))
   print ("\n")
   Grade1 = int(input("Enter Student's First Term Grade: "))
   Grade2 = int(input("Enter Student's Second Term Grade: "))
   Grade3 = int(input("Enter Student's Third Term Grade: "))
   Grade4 = int(input("Enter Student's Fourth Term Grade: "))

   average =  (Grade1+Grade2+Grade3+Grade4)/4

   print ("\n")
   print ("-----------------------------------------------------------------------------")
   print ("\n")
   print ("Total Grade Average: %G" % (average))

   passed_or_failed = "PASSED"
   if average < 40:
      passed_or_failed = 'FAILED'
   results.append(passed_or_failed)

   print ("\n")
   print ("%s has: %s" % (Student, passed_or_failed))
   print ("\n")

   cont = input('Do you want to keep entering students? Y/N: ')

   if cont.lower() == "n":
      print ("\n")
      print ("-----------------------------------------------------------------------------")
      print ("\n")
      print ("Thank you for using FinalGrade. Goodbye.")
      break

rawDescription: Python IF Statement not being displayed

description: Python IF Statement not being displayed


code:
def your_view(request):
    next = strip_lang(request.path)
    return render(request,  "form.html", {'next': next})

rawDescription: internalization set language redirect view. how to redirect to the same page?

description: Internalization set language redirect view. how to redirect to the same page


code:
sizer = wx.GridBagSizer()
sizer.Add(wx.Button(self, label="click"), border=10, flag=wx.LEFT)

main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(sizer, 0, wx.BOTTOM, 5)

rawDescription: Rectangular border widths for sizer in wxPython


rawDescription: How to pluralize a name in a template with jinja2?

description: Pluralize a name in a template with jinja2


code: print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))

rawDescription: Two Decimals in Python?

description: Two Decimals in Python


rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code:
[{'content': u'edit this is post text - what i want',
  'date': u'27 February, 2007',
  'author': u'this is the author name, also want, have way to get',
  'title': u'edit'},
 {'content': u'edit post text, what I want.',
  'date': u'26 February, 2007',
  'author': u'edit author name',
  'title': u'edit'}]

rawDescription: Using BeautifulSoup to pull multiple posts from a single blog archive page, without scripts


code:
for xi, yi in zip(x,y):
   assert xi**2 + yi**2 <= 9

rawDescription: Using 'If' to run the loop again?

description: Using 'If' to run the loop again


rawDescription: Pulling valid data from bytestring in Python 3


code:
result = POINT_CLOUD[INDICES.T]
np.allclose(result[0], LIST1)
np.allclose(result[1], LIST2)

rawDescription: Split a large numpy array into separate arrays with a list of grouped indices


code:
from datetime import datetime

max_dates = {}
for entry in list_of_dicts:
    date = datetime.strptime(entry['date'], '%d-%b-%y')
    country = entry['country']
    if country not in max_dates or date > max_dates[country][0]:
        max_dates[country] = (date, entry)

result = [entry for date, entry in max_dates.values()]

rawDescription: Python: get maximum value object for unique key


code:
value = {}
for (pattern, slice, key) in zip([patternA, patternB, patternC],
                                 [slice(45,67), slice(5,7), slice(4,5)],
                                 ['abc', 'xyx', 'txt']):
    m = re.search(pattern, string)
    if m:
        value[key] = m.group(0)[slice]
        break

rawDescription: Smart pythonic way of removing if elif on regular expressions


code:
context={
    'fetch_result': foo.fetch_result(),
}

rawDescription: How to include a function call in a Django template?

description: Include a function call in a Django template


code: multiples = [value for value in range(high, low-1, -1) if not value % num]

rawDescription: Count even and odd numbers and the totals (python)


code: registers['name']='register_1 register_2 register_3 register_4'.split()

rawDescription: Placing a numpy record array inside another record array python


code:
for item in float(item_list[3]):
    total_pop += pop
for item in int(item_list[2]):
    total_area += area

rawDescription: adding population from a website

description: Adding population from a website


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

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='polar')

N = 8
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = np.ones(N)
width = 2 * np.pi / N
bars = ax.bar(theta, radii, width=width, bottom=0.6)

colors = plt.cm.Spectral(np.linspace(0, 1, N))

for color, bar in zip(colors, bars):
    bar.set_facecolor(color)

xlabels = np.array([0,21,18,15,12,9,6,3])
ax.set_thetagrids(np.degrees(theta), xlabels, frac=1.2,
                  rotation=270, fontsize=60)

ax.set_yticklabels([])
ax.grid(False)

fig.tight_layout()

plt.show()

rawDescription: How to add space for xticklabels in python?

description: Add space for xticklabels in python


code:
def update_ABC(request, payload):
    accounts = app.data.driver.db['abc_collection']
    account = accounts.insert(docs)

app = Eve()
app.on_post_POST_ABC += update_ABC
app.run()

rawDescription: submit request (post) internally in python-eve

description: Submit request (post) internally in python-eve


code:
from sympy import *
x = symbols('x')
solve(3.5*x + 90 - 7*x, x) #right hand side is 0 and we solve for x

rawDescription: Using Python to find the intersection of two equations


code:
# Page Setup
PAGE_WIDTH, PAGE_HEIGHT = landscape(letter)

class MyPdf():
    """
    My PDF
    """
    document            = None

    def __init__(self, file_like_handle=None):
        self.document = BaseDocTemplate(file_like_handle, pagesize=landscape(letter))

        self.build_templates()

    def build_templates(self):

        first_page_frames = []

        #First Page Title Frame
        frame_title = Frame(.25*inch, PAGE_HEIGHT-(1.75*inch), PAGE_WIDTH-(inch*.5), inch*.5, id="frame_title", showBoundary=0)
        first_page_frames.append(frame_title)

        # First Page Body Frames
        frame_body = Frame(.5*inch, PAGE_HEIGHT-(8*inch), PAGE_WIDTH-(inch), inch*6.25, id="frame_body", showBoundary=0)
        first_page_frames.append(frame_body)

        # Second Page Body Frame
        frame_body_full = Frame(.5*inch, PAGE_HEIGHT-(8*inch), PAGE_WIDTH-(inch), inch*7, id="frame_body_full", showBoundary=0)

        templates = []
        templates.append(PageTemplate(frames=first_page_frames, id="first_page", onPage=self.first_page))
        templates.append(PageTemplate(frames=[frame_body_full], id="child_pages", onPage=self.child_pages))
        templates.append(PageTemplate(frames=[frame_body_full], id="child_pages", onPage=self.last_page))
        self.document.addPageTemplates(templates)

    def first_page(self, canvas, doc):
        """
        First page has an image header and footer
        """
        canvas.saveState()
        canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-header-landscape.png", inch*.25, PAGE_HEIGHT-(1.25 * inch), PAGE_WIDTH-(.5*inch), ((11/8)*inch))
        canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-footer-landscape.png", inch*.25, inch*.25, PAGE_WIDTH-(.5*inch), (.316*inch))
        canvas.restoreState()

    def child_pages(self, canvas, doc):
        """
        Second page has a smaller header and the same footer
        """
        canvas.saveState()
        canvas.setFillColor(HexColor("#f4f3f1"))
        canvas.rect(inch*.25, PAGE_HEIGHT-(.25 * inch), PAGE_WIDTH-(.5*inch), -(.5*inch), fill=1, stroke=0)
        canvas.setFillColor(HexColor("#e5b53b"))
        canvas.setFont('Gotham-Bold', 16)
        canvas.drawString(inch*.5, PAGE_HEIGHT-((.6)*inch), "PAGE")
        canvas.setFillColor(HexColor("#00355f"))
        canvas.drawString(inch*1.75, PAGE_HEIGHT-((.6)*inch), "OVERVIEW")
        canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-footer-landscape.png", inch*.25, inch*.25, PAGE_WIDTH-(.5*inch), (.316*inch))
        canvas.restoreState()

    def build(self):
        return self.document.build(self.elements)

    def add_first_page(self):

        sample = getSampleStyleSheet()
        style_title = copy.deepcopy(sample['BodyText'])
        style_title.fontSize = 18
        style_title.textColor = HexColor("#00355f")

        style_body  = copy.deepcopy(sample['BodyText'])
        style_body.fontSize = 10
        style_body.alignment = reportlab.lib.enums.TA_LEFT
        style_body.spaceBefore = 25
        style_body.spaceAfter = 15
        style_body.textColor = HexColor("#000000")
        style_body.leading = 14

        self.elements.append(Paragraph("""PAGEOVERVIEW""", style_title))
        self.elements.append(FrameBreak())

        self.elements.append(Paragraph("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean elementum malesuada euismod. Praesent ut ante risus. Aenean eleifend massa elit, non adipiscing ipsum. Integer et arcu tortor, a bibendum metus. Maecenas eget nulla id sem placerat dignissim sit amet et ligula. Donec vitae mi mauris. Praesent lacinia, mauris at malesuada bibendum, metus eros molestie ipsum, sed consequat dolor diam interdum ipsum. Phasellus consectetur auctor laoreet. Suspendisse vel nisl lacus, vitae auctor dui.""", style_body))

        # ADD A CUSTOM REPORTLAB CANVAS OBJECT
        self.elements.append(SomeGraph())

        self.elements.append(Paragraph("""Our strategic allocations for each strategy are determined by our Dynamic Strategic Asset Allocation process - the Science of Dynamic Investing. Our proprietary mathematical model uses updated Price Matters<super>®</super> capital market assumptions (expected return, risk and correlation figures) to determine the optimal allocation to each asset class to achieve the goals of each strategy within the assigned risk tolerance and time horizon. The Art of Dynamic Investing enables us to adapt to changing economic and political realities as we reposition strategies with tactical tilts to the strategic allocations as we see value and momentum of various asset classes being affected during the year. The chart below shows the strategic weightings and the tactical allocations to each asset class as of the close of business on the date cited.""", style_body))

        self.elements.append(NextPageTemplate("child_pages"))
        self.elements.append(PageBreak())

    def add_second_page(self):
        sample = getSampleStyleSheet()
        style_title = copy.deepcopy(sample['BodyText'])
        style_title.fontSize = 18
        style_title.textColor = HexColor("#00355f")

        style_body  = copy.deepcopy(sample['BodyText'])
        style_body.fontSize = 10
        style_body.alignment = reportlab.lib.enums.TA_LEFT
        style_body.spaceBefore = 25
        style_body.spaceAfter = 15
        style_body.textColor = HexColor("#000000")
        style_body.leading = 14

        self.elements.append(Paragraph("""Morbi posuere erat non nunc faucibus rhoncus. Donec at ante at tellus vehicula gravida. Praesent vulputate viverra neque, ut consectetur turpis vestibulum at. Integer interdum diam sed leo vehicula in viverra mauris venenatis. Morbi tristique pretium nunc vel ultrices. Fusce vitae augue lorem, et feugiat lorem. Donec sit amet nulla eget elit feugiat euismod rutrum ut magna. Pellentesque condimentum, tellus at rutrum egestas, dui neque dapibus risus, malesuada mollis risus eros id ligula. Fusce id cursus nulla. Etiam porttitor vulputate tellus eu blandit. Donec elementum erat sed tellus dapibus eleifend. Pellentesque sagittis, libero ac sodales laoreet, erat turpis fringilla est, vel accumsan nunc nisi eget orci. Integer condimentum libero in tellus lacinia ultricies quis ac odio. Vivamus justo urna, faucibus vitae bibendum dapibus, condimentum et ligula. Nullam interdum velit at orci blandit nec suscipit lorem lobortis. Pellentesque purus nunc, pulvinar vitae ullamcorper id, rhoncus sit amet diam.""", style_body))

    def add_disclosures(self):

        sample = getSampleStyleSheet()
        style_d = copy.deepcopy(sample['BodyText'])
        style_d.fontSize        = 8
        style_d.alignment   = reportlab.lib.enums.TA_LEFT
        style_d.textColor   = HexColor("#9D8D85")

        self.elements.append(NextPageTemplate("last_page"))
        self.elements.append(PageBreak())

        self.elements.append(Paragraph("""Important Disclosures""", style_d))

        self.elements.append(Paragraph("""Copyright 2012 Francis Yaconiello All Rights Reserved.""", style_d))

rawDescription: Django and reportlab issue for dynamic report


rawDescription: How to convert numpy datetime64 into datetime

description: Convert numpy datetime64 into datetime


code:
time_tuple = (year, month, day, hour, minute, second, day_of_week, day_in_year, dst)
unix_time = time.mktime(time_tuple)

rawDescription: using cython to generate a unix timestamp

description: Using cython to generate a unix timestamp


code: np.random.uniform(0, cutoffs[-1])

rawDescription: draw random element in numpy

description: Draw random element in numpy


code:
@bottle.route('/static/:filename#.*#')
def static(filename):
    return bottle.static_file(filename, root='./static/')

rawDescription: Browser caching with BottlePy/GAE

description: Browser caching with BottlePy/GAE


code:
def weighted_choice_bisect_compile(items):
    """Returns a function that makes a weighted random choice from items."""
    added_weights = []
    last_sum = 0

    for item, weight in items:
        last_sum += weight
        added_weights.append(last_sum)

    def choice(rnd=random.random, bis=bisect.bisect):
        return items[bis(added_weights, rnd() * last_sum)][0]
    return choice

rawDescription: Probability distribution in Python

description: Probability distribution in Python


code:
import os

R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)

while True:
    if R.f.tell() != n:
        line = R.f.readline()
        print(line)
        print("Not at EOF")
    else:
         print("At EOF")
         break

rawDescription: Find out if file pointer is at EOF in Python


code:
headers = [header.get_text() for header in first.find_all('td')]
results = [[data.get_text() for data in row.find_all(['th', 'td'])] for row in allRows]

df = pd.DataFrame(data=results, columns=headers)
print(df)

rawDescription: The second row and third row should be a single row


code:
# Just one line :)
Z = hac.linkage(timeSeries, 'single', 'correlation')

# Plot the dendogram
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('sample index')
plt.ylabel('distance')
hac.dendrogram(
    Z,
    leaf_rotation=90.,  # rotates the x axis labels
    leaf_font_size=8.,  # font size for the x axis labels
)
plt.show()

rawDescription: Hierarchical clustering of time series in Python scipy/numpy/pandas?


code:
def upload_job_file_path(instance, filename):
    return 'uploads/job_meta/files/%s/%s' % (instance.job_id, filename)

class JobFileSubmit(models.Model):
    job = models.ForeignKey(Jobs)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=upload_job_file_path, blank=False, null=False)
    uploadDate = models.DateTimeField(auto_now=True)

rawDescription: Django: Upload Files and Save to Disk

description: Django: Upload Files and Save to Disk


code:
headers = ["X", "Y", "Z", "XX", "YY"]
data = zip(headers, myarray.all())
return render(request, 'template.html', {'data': data})

rawDescription: Using index from iterated list

description: Using index from iterated list


rawDescription: Converting a String to List in Python

description: Converting a String to List in Python


code:
test = 'Today it is Tuesday'
removeText = 'pqrst'
test.translate(None, removeText+removeText.upper())

rawDescription: Removing certain letters from a string

description: Removing certain letters from a string


code: movielist = '\n'.join([' ' +i for i in movie])

rawDescription: Beginner not sure how to join lists while scraping


rawDescription: Django: How to identifying through which link user done social authentication?


code:
((a,b,c) for a in A for b in B for c in C)
            #SAME AS#
((a,b,c) for (a,b,c) in itertools.product(A,B,C))
            #SAME AS#
for a in A:
    for b in B:
        for c in C:
            yield (a,b,c)

rawDescription: What's wrong with this nested list comprehension?


rawDescription: Creating an overlap array with conditions - Python


code:
from __future__ import with_statement
from fabric.api import hide, run, get

with hide('output'):
    run('mysqldump --no-data test | tee test.create_table')
    get('~/test.create_table', '~/test.create_table')

rawDescription: Easy way to suppress output of fabric run?


code:
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

n, bins, patches = ax1.hist(a)
ax1.set_xlabel('Angle a (degrees)')
ax1.set_ylabel('Frequency')

n, bins, patches = ax2.hist(b)
ax2.set_xlabel('Angle b (degrees)')
ax2.set_ylabel('Frequency')

rawDescription: How to create multiple histograms on separate graphs with matplotlib?

description: Create multiple histograms on separate graphs with matplotlib


code:
from calendar import month_abbr
month_to_index = {month.upper(): i for i, month in enumerate(month_abbr[1:])}
import pprint
pprint.pprint(sorted(mylist, key=lambda d: month_to_index[d['month'][:3]]))

rawDescription: list of dictionary Sorting in python

description: List of dictionary Sorting in python


code: fred@wherever.com, wilma@wherever.com

rawDescription: appending a single string to each element of a list in python

description: Appending a single string to each element of a list in python


code:
s = '"hello world." here are some words. "and more"'
re.findall(r'"[^"]*"|\S+', s)

rawDescription: matching quoted strings and unquoted words

description: Matching quoted strings and unquoted words


code:
with open("f1.txt", "r") as infile1:
    udict = dict(line.strip().split("\t", 1) for line in infile1)
regex = re.compile("|".join(map(re.escape, udict)))
with open("f2.txt", "r") as infile2, open("out.txt", "w") as outfile:
    for line in infile2:
        outfile.write(regex.sub(lambda m: udict[m.group()], line))

rawDescription: python beginner - faster way to find and replace in large file?

description: Python beginner - faster way to find and replace in large file


code:
import pandas as pd
import itertools

df = pd.read_csv("avito_trend.csv",
                      parse_dates=[2])

def f(df):
    dfs = []
    i = 0
    for x in [list(x) for x in itertools.combinations(df['address'].unique(), 2)]:
        i += 1
        c1 = df.loc[df['address'].isin([x[0]]), 'ID']
        c2 = df.loc[df['address'].isin([x[1]]), 'ID']
        c = pd.Series(list(set(c1).intersection(set(c2))))
        #add inverted intersection c2 vs c1
        c_invert = pd.Series(list(set(c2).intersection(set(c1))))
        dfs.append(pd.DataFrame({'common users':len(c), 'pair of websites':' and '.join(x), 'sort': i}, index=[0]))
        #swap values in x
        x[1],x[0] = x[0],x[1]
        dfs.append(pd.DataFrame({'common users':len(c_invert), 'pair of websites':' and '.join(x), 'sort': i}, index=[0]))
    return pd.concat(dfs)

common_users = df.groupby([df['used_at'].dt.year]).apply(f).reset_index(drop=True, level=1).reset_index()

rawDescription: Sort strings in column and print graph

description: Sort strings in column and print graph


code:
import sys

def colprint(totwidth, table):
  numcols = max(len(row) for row in table)
  # ensure all rows have >= numcols columns, maybe empty
  padded = [row+numcols*('',) for row in table]
  # compute col widths, including separating space (except for last one)
  widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)]
  widths[-1] -= 1
  # drop or truncate columns from the right in order to fit
  while sum(widths) > totwidth:
    mustlose = sum(widths) - totwidth
    if widths[-1] <= mustlose:
      del widths[-1]
    else:
      widths[-1] -= mustlose
      break
  # and finally, the output phase!
  for row in padded:
    for w, i in zip(widths, row):
      sys.stdout.write('%*s' % (-w, i[:w]))
    sys.stdout.write('\n')

rawDescription: apt like column output - python library

description: Apt like column output - python library


code:
string="this is a sample input file an input file will always be all lower case with no punctuation"

def words(count):
    return [" ".join(string.split()[a:b]) for a in range(len(string.split())) for b in range(a+count+1) if len(string.split()[a:b]) == count]

rawDescription: Being Pythonic: Collecting arbitrary strings - indexer


code:
for r0 in itertools.product([0, 1], repeat=3):
    r0 = (0,) + r0 # keep r0 a tuple!
    for r1 in itertools.product([0, 1], repeat=3):
        r1 = (1,) + r1 # same here
        # ...

rawDescription: itertools.product - return list instead of tuple

description: Itertools.product - return list instead of tuple


code:
import django
def django_version(request):
    return { 'django_version': django.VERSION }

rawDescription: Django template tag to display Django version


code:
import functools
import weakref

class Memoized(object):
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.

    >>> counter = 0
    >>> @Memoized
    ... def count():
    ...     global counter
    ...     counter += 1
    ...     return counter

    >>> counter = 0
    >>> Memoized.reset()
    >>> count()
    1
    >>> count()
    1
    >>> Memoized.reset()
    >>> count()
    2

    >>> class test(object):
    ...     @Memoized
    ...     def func(self):
    ...         global counter
    ...         counter += 1
    ...         return counter
    >>> testobject = test()
    >>> counter = 0
    >>> testobject.func()
    1
    >>> testobject.func()
    1
    >>> Memoized.reset()
    >>> testobject.func()
    2
    """

    caches = weakref.WeakSet()

    def __init__(self, func):
        self.func = func
        self.cache = {}
        Memoized.caches.add(self)

    def __call__(self, *args):
      try:
          return self.cache[args]
      except KeyError:
          value = self.func(*args)
          self.cache[args] = value
          return value
      except TypeError:
          # uncachable -- for instance, passing a list as an argument.
          # Better to not cache than to blow up entirely.
          return self.func(*args)

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

    @staticmethod
    def reset():
        for memo in Memoized.caches:
            memo.cache = {}

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: What can be done to speed up this memoization decorator?


code:
import re
r = re.compile(r'<[^>]+>')
for it in source:
    r.sub('', it)

rawDescription: Better way to use re.sub

description: Better way to use re.sub


code: CELERY_CREATE_MISSING_QUEUES = True

rawDescription: Create celery multiple queues

description: Create celery multiple queues


code:
from pkg_resources import get_distribution

__version__ = get_distribution('foobar').version

rawDescription: What is the correct way to share package version with setup.py and the package?


code: integer, value = divmod(integer, base)

rawDescription: Divmod alternative method

description: Divmod alternative method


code:
decimal_lowest_in_string = []
decimal_highest_in_string = []
decimal_lowest_in_string.append(min(decimal_values))
decimal_lowest_in_string
decimal_highest_in_string.append(max(decimal_values))
decimal_highest_in_string

rawDescription: CSV string to decimal in python list

description: CSV string to decimal in python list


code:
for i in range(len(data_all)):
    data_string_sample=((data_all[i]['utcdate']['mday']),(data_all[i]['utcdate']['mon']),(data_all[i]['utcdate']['year']),(data_all[i]['utcdate']['hour']),(data_all[i]['utcdate']['min']),(data_all[i]['tempm']),(data_all[i]['hum']),(data_all[i]['pressurem']))

rawDescription: Python - Iterate through, and extract, elements of a dictionary type list


code:
threshold = 2
flow[np.abs(flow) < threshold] = 0

rawDescription: openCV Thresholding negative values

description: OpenCV Thresholding negative values


code:
np.nonzero(A)[0]
ind = A[np.nonzero(A)[0]]

rawDescription: Rearrange row elements using numpy in Python


rawDescription: Pandas - turning a DF column into an Index but without duplication


code:
def writeFilesForEveryGroupsFromDict(aDict):
    for key, value in aDict.values():
        with open(key + '.txt', 'w') as f:
            f.write(value[0])

rawDescription: Python3 create files from dictionary

description: Python3 create files from dictionary


rawDescription: Python taking a certain string from a list


code: df

rawDescription: MultiIndexing in pandas based on column conditions


code:
my_dict = dict.fromkeys(['a', 'b', 'c'], 10)
my_dict.update(dict.fromkeys(['b', 'e'], 20))

rawDescription: Is it possible to assign the same value to multiple keys in a dict object at once?


code:
@sensitive_variables('user', 'pw', 'cc')
def my_view(request):
  pass

rawDescription: Django 1.3 Error report remove sensitive information


code:
reviews = []
for rating in soup.find_all(itemprop='review'):
    data = {}
    for item in rating.find_all(itemprop=True):
        data[item['itemprop']] = item.attrs.get('content') or item.get_text()
    reviews.append(data)

rawDescription: beautifulsoup with internal javascript

description: Beautifulsoup with internal javascript


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> ')
soup.find(itemprop="streetAddress").get_text()
soup.find(itemprop="streetAddress").get("content")

rawDescription: Beautiful soup meta content tag

description: Beautiful soup meta content tag


code:
import math

def rint(x):
  x_int = int(x)
  x_rem = x - x_int
  if (x_int % 2) == 1:
    return round(x)
  else:
    if x_rem - 0.5 < 0.001:
      return math.floor(x)
    else:
      return math.ceil(x)

rawDescription: App Engine: Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore


code:
from collections import defaultdict
dct = defaultdict(list)
for x,y in enumerate(lst, 1):
    dct[y].append(x)
dct

rawDescription: Find indices of elements in a list in Python


code:
decorator = type(self).__dict__['decorator']
self.post = decorator(self.post)

rawDescription: What's the cleanest way to add a decorator from a derived class to its base class?


rawDescription: How can I sort a list by the decimals only?

description: Sort a list by the decimals only


code:
st = set(range(1, len(choices))+ 1)
while True:
    choose = int(input(warning + prompt))
    if choose in st:
        return choose
    print("Invalid response '%s': try again" % choose)
    for number in range(1, len(choices)  + 1):
        msg = "%g: %s" % (number, choices[number])
        print(msg)

rawDescription: Python: Unable to quit menu - user input


code:
winner = max(potentialWinners, key=getCardValue) #get max card value while calculating zero as 10
print("player", tricks.index(winner), "wins with the card", winner)

rawDescription: Sorting Cards played in each trick according to a certain set of rules


code:
import requests
result = requests.get('http://127.0.0.1:1234/1251.html')
result.encoding

rawDescription: Send request to page with windows-1251 encoding from python


rawDescription: Python floating-point precision format specifier


code:
long(gamma(101))
fac(100)

rawDescription: conversion float to long in python

description: Conversion float to long in python


code:
import application.views.foo
import application.views.bar
import application.views.main

rawDescription: Python importing (in Flask)

description: Python importing (in Flask)


code:
from tkinter import *

def hide_me(event, widget):
    widget.pack_forget()

def show_me(event, widget):
    widget.pack()

root = Tk()
lbl = Label(root, text="Victim")

btn = Button(root, text="Hide the victim")
btn.bind('<Button-1>', lambda event: hide_me(event, lbl))
btn.pack()

btn2 = Button(root, text="Show the victim")
btn2.bind('<Button-1>', lambda event: show_me(event, lbl))
btn2.pack()

lbl.pack()

root.mainloop()

rawDescription: Lift and raise a Canvas over a Canvas in tkinter


code: words.update(word.lower() for word in e.split())

rawDescription: Python counter key value

description: Python counter key value


rawDescription: Python: Iterate over string with while loop


code:
import pandas as pd
areas = pd.DataFrame({'Com':[1,2,3], 'Ind':[4,5,6]})
demand = pd.DataFrame({'Water':[4,3],
                       'Elec':[8,9]}, index=['Com', 'Ind'])

def multiply_by_demand(series):
    return demand.ix[series.name].apply(lambda x: x*series).stack()
df = areas.apply(multiply_by_demand).unstack(0)
print(df)

rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code:
def get_overlap_simple(keys):
    prefixes = defaultdict(list)
    for key in keys:
        prefixes[key[:-1]].append(key)
    return [(key, other) for key in keys for other in prefixes[key[1:]]]

rawDescription: Getting all keys in a dict that overlap with other keys in the same dict


rawDescription: Python - append VS extend efficiency

description: Python - append VS extend efficiency


code: property_asel = [property_a[i] for i in good_indices]

rawDescription: Python: Select subset from list based on index set


code:
dg
dh
di
eg
eh
ei
fg
fh
fi

rawDescription: custom permutation python?

description: Custom permutation python


code:
def log_wrap(mydict):
    mystr = '\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()])
    write_to_log(mydict)

log_wrap(mydict)

rawDescription: concatenate items in dictionary in python using list comprehension

description: Concatenate items in dictionary in python using list comprehension


code:
def has_background_attribute(tag):
    return tag.has_key('background')

soup.find_all(has_background_attribute)

rawDescription: Using Python & Beautiful Soup, can I obtain a tag list filtered by whether background attr is set?


code:
from pprint import pprint
mylist = [101, 102, 103, 104, 105, 106]
pprint(list(sublists(mylist)))

rawDescription: Python: breaking a list into all possible sublists


code:
from modX import *

print("I love {}".format(my_string))  # -> I love eggs

rawDescription: unify python script keeping specific parts

description: Unify python script keeping specific parts


code: #!/usr/bin/env python2.6

rawDescription: How programmaticaly run another python script with other python version?


code:
import re

quadratic_equation_matcher = re.compile(r'(-?\d+)x\^2 ([+-]\d+)x ([+-]\d+)')
quadratic_equation = '-3x^2 +7x -44'
matches = quadratic_equation_matcher.match(quadratic_equation)
a = int(matches.group(1))
b = int(matches.group(2))
c = int(matches.group(3))
d = b**2 - 4*a*b
x1 = (-b + d**0.5)/(2*a)
x2 = (-b - d**0.5)/(2*a)
x1 # => -0.75542709911179939
x2 # => 3.0887604324451328

rawDescription: Python: Regular expression for quadratic equations


code:
tornado.web.application([
    (r'/items$', ItemHandler),
    (r'/items/(\d+$)', ItemHandler),
    (r'/items/(\d+)/(edit)$', ItemHandler),
])

rawDescription: Tornado Restful Handler Classes

description: Tornado Restful Handler Classes


code:
from django.views.generic import ListView
from django.views.generic.edit import FormMixin
from django.core.urlresolvers import reverse_lazy
from .profiles.models import Profile
from .forms import ProfileSearchForm

class IndexView(FormMixin, ListView):
    model = Profile
    template_name = 'index.html'
    form_class = ProfileSearchForm
    success_url = reverse_lazy('index')

    def get_queryset(self):
        queryset = super(IndexView, self).get_queryset()
        specialties = self.request.GET.getlist('specialties')
        if specialties:
            queryset = queryset.filter(specialties__in=specialties).distinct('user')
        return queryset

    def get_form_kwargs(self):
        kwargs = super(IndexView, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        form_class = self.get_form_class()
        context['form'] = self.get_form(form_class)
        return context

rawDescription: How to search on a Many to Many field in Django?

description: Search on a Many to Many field in Django


code:
def write_brat(tree, filename_prefix):
    text, standoff = char_standoff(tree)
    with open(filename_prefix + '.txt', 'w') as f:
        print(text, file=f)
    with open(filename_prefix + '.ann', 'w') as f:
        for i, (path, label, start, stop) in enumerate(standoff):
            print('T{}'.format(i), '{} {} {}'.format(label, start, stop), text[start:stop], sep='\t', file=f)

rawDescription: Converting NLTK phrase structure trees to BRAT .ann standoff


code:
global weatherobjectslist
class weathersource():
    def __init__(self, weatherobjectlist):
        weatherobjectlist.append(self)

rawDescription: I want a classes __init__ to add the object to a list, but I want to prevent redundancy and "if self not in objectlist" isn't working


code: columns = line.split()

rawDescription: Reading specific sections of new lines

description: Reading specific sections of new lines


code:
jinja_options = app.jinja_options.copy()

jinja_options.update(dict(
    block_start_string='<%',
    block_end_string='%>',
    variable_start_string='%%',
    variable_end_string='%%',
    comment_start_string='<#',
    comment_end_string='#>'
))
app.jinja_options = jinja_options

rawDescription: Is it possible to use Angular with the Jinja2 template engine?


code:
cur_page = 1
while True:
    try:
        driver.find_element_by_link_text(str(cur_page)).click()
    except NoSuchElementException:
        break

    # logic

    cur_page += 1

rawDescription: how to crawl a javascript page whose content name is defined by a reference?

description: Crawl a javascript page whose content name is defined by a reference


code:
from collections import Counter

summed = Counter()
for d in l:
    summed[d['name']] += d['amount']
result = [{'name': name, 'amount': amount} for name, amount in summed.most_common()]

rawDescription: How to combine values in python list of dictionaries

description: Combine values in python list of dictionaries


code: {{ create_date| date:"N j, Y" }}

rawDescription: Creating a resuable template in Django

description: Creating a resuable template in Django


code:
fmt = '%-8s%-20s%s'

print(fmt % ('', 'Assignment', 'Grade'))
for i, (name, grade) in enumerate(zip(nameList, gradeList)):
    print(fmt % (i, name, grade))

rawDescription: Printing 2 evenly populated lists side by side evenly