code:
import random

class ListDict(object):
    def __init__(self):
        self.item_to_position = {}
        self.items = []

    def add_item(self, item):
        if item in self.item_to_position:
            return
        self.items.append(item)
        self.item_to_position[item] = len(self.items)-1

    def remove_item(self, item):
        position = self.item_to_position.pop(item)
        last_item = self.items.pop()
        if position != len(self.items):
            self.items[position] = last_item
            self.item_to_position[last_item] = position

    def choose_random_item(self):
        return random.choice(self.items)

rawDescription: Python data structure for efficient add, remove, and random.choice


code:
values = [0.1, 2.9, 1.4, 5.7, 9.2, 3.8]

from itertools import takewhile

print(sum(1 for _ in takewhile(lambda x: x< 5,values)))

rawDescription: What is the most pythonic way to iterate over a list until a condition is met?


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self)

        self.textedit = QTextEdit()
        self.clip = QApplication.clipboard()
        self.button = QPushButton("Bold")
        self.connect(self.button, SIGNAL("clicked()"), self.addBold)

        layout = QVBoxLayout()
        layout.addWidget(self.textedit)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def addBold(self):
        self.clip.clear()
        self.textedit.copy()
        currentText = self.clip.text()
        self.textedit.insertPlainText("'''%s'''" % currentText)

app = QApplication([])
widget = Widget()
widget.show()
app.exec_()

rawDescription: Is there a way to add marked text into a variable in pyqt?


code:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np
x, y, z = np.loadtxt('data.txt', unpack=True)
N = int(len(z)**.5)
z = z.reshape(N, N)
plt.imshow(z+10, extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)),
        cmap=cm.hot, norm=LogNorm())
plt.colorbar()
plt.show()

rawDescription: How to plot a density map in python?

description: Plot a density map in python


rawDescription: Matrix Transpose in Python

description: Matrix Transpose in Python


rawDescription: Python equivalent of `copy link location` in a browser


code:
grid = []
for i in range(height):
    if i % 2 == 0:
        grid.append(line[:])
    else:
        board.append(linerev[:])

rawDescription: Changing values in nested lists with python


code:
def post(self):
    second_method()
    my_txn(key)

@db.transactional
def my_txn(key):
    myobj = db.get(key)
    myobj.property = x + 1
    db.put(obj)

rawDescription: Is it a valid transaction where my transactional method just completes the db.put() operation?


code:
def gensort(list):
    sorted_list = []
    for item in list:
        sorted_list = insert_sorted(item, sorted_list)
    return sorted_list

rawDescription: How to Sort List Items from Low to High Without Built-In Tools


code:
#!/usr/bin/env python
import types
from pprint import pformat
from threading import RLock

class SynchronizeMethodWrapper:
    """
    Wrapper object for a method to be called.
    """
    def __init__( self, obj, func, name, rlock ):
        self.obj, self.func, self.name = obj, func, name
        self.rlock = rlock
        assert obj is not None
        assert func is not None
        assert name is not None

    def __call__( self, *args, **kwds ):
        """
        This method gets called before a method is called to sync access to the core object.
        """
        with self.rlock:
            rval = self.func(*args, **kwds)
            return rval

class SynchronizeProxy(object):
    """
    Proxy object that synchronizes access to a core object methods and attributes that don't start with _.
    """
    def __init__( self, core ):
        self._obj = core
        self.rlock = RLock()

    def __getattribute__( self, name ):
        """
        Return a proxy wrapper object if this is a method call.
        """
        if name.startswith('_'):
            return object.__getattribute__(self, name)
        else:
            att = getattr(self._obj, name)
            if type(att) is types.MethodType:
                return SynchronizeMethodWrapper(self, att, name, object.__getattribute__(self, "rlock"))
            else:
                return att

    def __setitem__( self, key, value ):
        """
        Delegate [] syntax.
        """
        name = '__setitem__'
        with self.rlock:
            att = getattr(self._obj, name)
            pmeth = SynchronizeMethodWrapper(self, att, name, self.rlock)
            pmeth(key, value)

rawDescription: synchronize access to python object

description: Synchronize access to python object


code:
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    execfile(filename)

rawDescription: How can I run Python commands every time I start Python

description: Run Python commands every time I start Python


code:
def gen_int():
    n = 0
    while True:
        yield n
        n += 1

rawDescription: How to stop a loop and restart it when a button is clicked?

description: Stop a loop and restart it when a button is clicked


code:
import numpy as NP
from matplotlib import pyplot as PLT

# just create some random data
fnx = lambda : NP.random.randint(3, 10, 10)
y = NP.row_stack((fnx(), fnx(), fnx()))
# this call to 'cumsum' (cumulative sum), passing in your y data,
# is necessary to avoid having to manually order the datasets
x = NP.arange(10)
y_stack = NP.cumsum(y, axis=0)   # a 3x10 array

fig = PLT.figure()
ax1 = fig.add_subplot(111)

ax1.fill_between(x, 0, y_stack[0,:], facecolor="#CC6666", alpha=.7)
ax1.fill_between(x, y_stack[0,:], y_stack[1,:], facecolor="#1DACD6", alpha=.7)
ax1.fill_between(x, y_stack[1,:], y_stack[2,:], facecolor="#6E5160")

PLT.show()

rawDescription: How can I create stacked line graph with matplotlib?

description: Create stacked line graph with matplotlib


code:
import numpy as np
DictVectorizer(dtype=np.float32, sparse=False)

rawDescription: Scikit learn - initialize DictVectorizer with numpy.float32


code:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

cmap = ListedColormap(['red', 'green', 'blue', 'black'], 'indexed')

fig, ax = plt.subplots()
im = ax.imshow([range(4)], interpolation='none', cmap=cmap)
fig.colorbar(im)
plt.show()

rawDescription: matplotlib color map - predefine mappings to values?

description: Matplotlib color map - predefine mappings to values


code:
import sys
from PyQt4 import QtCore, QtGui

class StartTest(QtGui.QMainWindow):
    def __init__(self, questions, parent=None):
        super(StartTest, self).__init__(parent)
        self.stack = QtGui.QStackedWidget(self)
        self.setCentralWidget(self.stack)
        for index, question in enumerate(questions):
            page = Question(question, self)
            page.submit.clicked[()].connect(
                lambda index=index: self.handleSubmit(index))
            self.stack.addWidget(page)
        self.answers = []

    def handleSubmit(self, index):
        page = self.stack.widget(index)
        answer = page.answer.text()
        # validate submitted answer...
        self.answers.append(answer)
        if index < self.stack.count() - 1:
            self.stack.setCurrentIndex(index + 1)

class Question(QtGui.QWidget):
    def __init__(self, question, parent=None):
        super(Question, self).__init__(parent)
        self.question = QtGui.QLabel(question, self)
        self.answer = QtGui.QLineEdit(self)
        self.submit = QtGui.QPushButton('Submit', self)
        form = QtGui.QFormLayout()
        form.addRow(self.question, self.answer)
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(form)
        layout.addWidget(self.submit)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    questions = [
        'What is 5+5?',
        'What is 45+10?',
        'What is 28+47?',
        'What is 22+13?',
        ]
    window = StartTest(questions)
    window.showFullScreen()
    app.exec_()

rawDescription: How do I present 1 string per page?? (PyQt/Python)

description: Present 1 string per page?? (PyQt/Python)


code:
if message.startswith(command):
    your_function(message.split(' ')[1])

rawDescription: How do I use a Python Twitch IRC Bot to take chat message parameters?

description: Use a Python Twitch IRC Bot to take chat message parameters


code:
for elem in soup.find_all('li'):
    for para in elem.find_all('p'):
        para.unwrap()

rawDescription: Remove parent tag (without removing children) with ElementTree


code:
def change_str(s):
    # operation has been split into 2 steps for clarity
    t = s.__iadd__("qwe") # creates a new string object
    s = t # as you know, without the `global` keyword, this `s` is local.

def change_arr(a):
    a.__setitem__(1, "qwe")

rawDescription: inconsistent variable scope in python

description: Inconsistent variable scope in python


code:
for i in range(10):
    for j in range(10):
        print(i,end=' ') #Now i is 0 for the first line, 1 for the next, and so on
    print('\n')

rawDescription: Python - editing my range to print certain strings


code:
class DefaultsAndTypesHelpFormatter(argparse.HelpFormatter):
    def _get_help_string(self, action):
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
                if action.type:
                    help += ' (type: %(type)s)'
        return help

rawDescription: argparse: Include default value and type in '--help'

description: Argparse: Include default value and type in '--help'


code:
applications = {
  'product.example.com': webapp.WSGIApplication([
    ('/', IndexHandler),
    ('/(.*)', ProductHandler)]),
  'user.example.com': webapp.WSGIApplication([
    ('/', IndexHandler),
    ('/(.*)', UserHandler)]),
}

def main():
  run_wsgi_app(applications[os.environ['HTTP_HOST']])

if __name__ == '__main__':
  main()

rawDescription: Working with subdomain in google app engine


code:
# urls.py
urlpatterns += patterns('',
   (r'^(?P<page_alias>.+?)/$', 'views.static_page'),
)

# views.py
def static_page(request, page_alias):    # page_alias holds the part of the url
    try:
        active = Page.objects.get(page_alias=page_alias)
    except Page.DoesNotExist:
        raise Http404("Page does not exist")

rawDescription: Django dynamic urls

description: Django dynamic urls


code: lastItems = [int(i[-1]) for i in yourList[2:]]

rawDescription: Python - get last item in a list, using a file


code:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np

# Generate random data
mu, sigma = 200, 25
x = mu + sigma*np.random.randn(10000)

# Create the histogram and normalize the counts to 1
hist, bins = np.histogram(x, bins = 50)
max_val = max(hist)
hist = [ float(n)/max_val for n in hist]

# Plot the resulting histogram
center = (bins[:-1]+bins[1:])/2
width = 0.7*(bins[1]-bins[0])
plt.bar(center, hist, align = 'center', width = width)
plt.show()

rawDescription: change the count in a Python histogram bin

description: Change the count in a Python histogram bin


code: indices = [i for i, x in enumerate(my_list) if x == "whatever"]

rawDescription: How to find all occurrences of an element in a list?

description: Find all occurrences of an element in a list


code:
#Click Sign In Button
driver.find_element_by_xpath(".//*[@id='bs-example-navbar-collapse-1']/ul/li[3]/a").click()
#Type Username
driver.find_element_by_xpath("(//*[@id='Username'])[3]").send_keys("Username")
#Type Password
driver.find_element_by_xpath("(//*[@id='Password'])[2]").send_keys("Password")
#Click Submit button
driver.find_element_by_xpath("(//div[@class='login_section']//a[@class='dk-btn dk-btn-success'])[2]").click()

rawDescription: Selenium send keys to log in box not working


code:
if __name__ == '__main__':

    indir = r'C:\basil\rs_Rock_and_Sediment\DVD_Data\testdir'
    mdblist = createDeepMdbList(indir)

    processes = 6  # set num procs to use here
    pool = multiprocessing.Pool(processes)

    pool.map(processMdb, mdblist)

rawDescription: Multithreading in ArcGIS with Python

description: Multithreading in ArcGIS with Python


code:
sum(1 for x in "thisissilly")
sum(map(lambda i:1, "anotheronefortheroad"))
sum(1 for x in [3,78,76,34,78])
sum(map(lambda i:1, ['betty','bop','doing','the','do']))

rawDescription: get length of string or list without using len?

description: Get length of string or list without using len


code:
def session_from_token(token):
    key = "session:%s" %(token, )
    session_json = redis.get(key)
    if not session_json:
        return None
    session = json.loads(session_json)
    if not session.get("is_valid"):
        return None
    redis.expire(key, 15 * 60)
    return session

rawDescription: Idle Timeout of Authentication Tokens

description: Idle Timeout of Authentication Tokens


code:
import numpy
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors

# Create fake data
x = numpy.linspace(0,4)
y = numpy.exp(x)

# Now plot one by one
bar_width = x[1] - x[0]  # assuming x is linealy spaced
max_y = y.max()
min_y = y.min()

for pointx, pointy in zip(x,y):
    point = 40
    current_color = cm.jet((pointy - min_y)/(max_y - min_y))
    plt.bar(pointx, point, bar_width, color = current_color)

plt.show()

rawDescription: Matplotlib: using colormap to show regime (axvspan or bar?)


code:
import bs4

html = "
\n                <s>Rs.330</s> Rs.297\n
"
soup = bs4.BeautifulSoup(html, features="xml")
s = soup.div.s.text # u'Rs.330'
b = soup.div.b.text # u'Rs.297'

rawDescription: How to extract content from HTML strings

description: Extract content from HTML strings


code:
import urllib2
from bs4 import BeautifulSoup
baseurl='http://wordpandit.com/learning-bin/visual-vocabulary/page/'

for count in range(1,2):
    url = baseurl + str(count) + "/"
    html_page = urllib2.urlopen(url)
    soup = BeautifulSoup(html_page)
    atag = soup.findAll(rel="prettyPhoto[gallery]", href = True)
    for tag in atag:
        if tag['href'].endswith(".jpg"):
            imgurl = tag['href']
            img = urllib2.urlopen("http://wordpandit.com" + imgurl)
            with open(imgurl.split("/")[-1], "wb") as local_file:
                local_file.write(img.read())

rawDescription: regex or way to get urls for images only

description: Regex or way to get urls for images only


code:
def f():
    a = 1
    b = 2
    list_ = ['a', 'b']
    locals_ = locals()
    dict_ = dict((x, locals_[x]) for x in list_)

rawDescription: using locals() inside dictionary comprehension

description: Using locals() inside dictionary comprehension


code:
x = input()
NUM_LETTERS = 26 #Can't import modules I'm using a web based grader/compiler
def SpyCoder(S, N):
   y = ""
   for i in S:
      if(i.isupper()):
         x = ord(i)
         x += N
         if x > ord('Z'):
            x -= NUM_LETTERS
         elif x < ord('A'):
            x += NUM_LETTERS
         y += chr(x)
      else:
         y += " "
   return y

def GoodnessFinder(S):
   y = 0
   for i in S:
      if i.isupper():
         x = ord(i)
         x -= ord('A')
         y += letterGoodness[x]
      else:
         y += 1
   return y

def GoodnessComparer(S):
   goodnesstocompare = GoodnessFinder(S)
   goodness = 0
   v = ''
   best_v = S
   for i in range(0, 26):
     v = SpyCoder(S, i)
     goodness = GoodnessFinder(v)
     if goodness > goodnesstocompare:
         best_v = v
         goodnesstocompare = goodness
   return best_v

print(GoodnessComparer(x))

rawDescription: Python Caesar Cipher Decoder

description: Python Caesar Cipher Decoder


code:
try:
    # iterator zip from Python 3
    from future_builtins import zip
except ImportError:
    # this *is* Python 3
    pass

z = [xval for xval, yval in zip(x, y) if yval == 0]

rawDescription: Accessing a list given a condition on another list in Python


code:
import tkinter

root = tkinter.Tk()
root.title("root")

top = tkinter.Toplevel(root)
top.title("top")
top.lift(root)
root.mainloop()

rawDescription: How to make Toplevel() widget appear above main root window?

description: Make Toplevel() widget appear above main root window


code:
import subprocess
process = subprocess.Popen(["Mycommand", "with", "arguments"], stdin=subprocess.PIPE)
process.communicate("My text")

rawDescription: python: string as stdin to subcommand

description: Python: string as stdin to subcommand


code:
import pandas as pd
ts = df.Week
for week in range(len(ts) - 1):
    ts = ts.drop(ts.idxmin())
    ts.index = pd.Index(range(len(ts)))
    ts.name = '%s_Week' % week
    df = df.merge(pd.DataFrame(ts), left_index=True,right_index=True, how='outer')

rawDescription: Pandas Dataframe Add a value to a new Column based on the previous row limited to the maximum value in that column


code:
x0 = ... # something
bounds = [(0,np.pi) for _ in range(len(x0))]
result = minimize(Svet, x0, bounds=bounds)

rawDescription: Optimizing a Nested loop that contains 8 for loops to minimize a function


code:
soup = bs4.BeautifulSoup(test, "lxml")
[[x for x in row.findAll('td')] for row in soup.findAll('tr')]
soup = bs4.BeautifulSoup(test, "html5lib")
[[x for x in row.findAll('td')] for row in soup.findAll('tr')]

rawDescription: Using Beautiful Soup for HTML tables that lack </td> tags


code:
from pygame import *
import random

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

FPS = 60

class Ball(sprite.Sprite):
    def __init__(self, xy = (0,0), xm = 0, ym = 0):
        sprite.Sprite.__init__(self)
        self.img_load('evil_balloon_32x32.png')
        self.rect.centerx, self.rect.centery = xy

        self.xmove = xm
        self.ymove = ym

    def update(self):
        self.move()
        self.ballBarrier()

    def move(self):
        self.rect.x += self.xmove
        self.rect.y += self.ymove

    def img_load(self, filename):
        self.image = image.load(filename)
        self.rect = self.image.get_rect()

    def ballBarrier(self):
        """
        Checks to make sure ball is within bounds, adjusts movement speed if it's not
        """
        if self.rect.right > SCREEN_WIDTH:
            self.xmove = random.randint(-2, 0)
        if self.rect.left < 0:
            self.xmove = random.randint(0, 2)
        if self.rect.bottom > SCREEN_HEIGHT:
            self.ymove = random.randint(-2, 0)
        if self.rect.top < 0:
            self.ymove = random.randint(0, 2)

class ball_manager():
    def __init__(self, numballs = 5, balls = []):
        self.blist = balls

        if numballs > 0:
            self.multipleBalls(numballs) # moved this here so balls get init'd only once

    def update(self):
        """
        Update position of all balls
        """
        for ball in self.blist:
            self.ballMove(ball)

    def add_ball(self, xy = (0,0), xm = 0, ym = 0):
        self.blist.append(Ball(xy, xm, ym)) # appends a random ball

    def multipleBalls(self, numballs):
        for i in range(numballs):
            self.add_ball((random.randint(0, SCREEN_WIDTH),
                          random.randint(0, SCREEN_HEIGHT)),
                          random.randint(-2,2),
                          random.randint(-2,2))

class Character(sprite.Sprite):
    def __init__(self, xy):
        sprite.Sprite.__init__(self)
        self.img_load()

        self.rect.centerx, self.rect.centery = xy

        self.movementspeed = 1
        self.velocity = 0

    def down(self):
        self.velocity += self.movementspeed

    def up(self):
        self.velocity -= self.movementspeed

    def characterMove(self, dy):
        if self.rect.bottom + dy > SCREEN_HEIGHT:
            self.rect.bottom = SCREEN_HEIGHT
            self.velocity = 0
        elif self.rect.top + dy < 0:
            self.rect.top = 0
            self.velocity = 0
        else:
            self.rect.y += dy

    def update(self):
        self.characterMove(self.velocity)

    def img_load(self):
        self.image = image.load("scary_clown_32x32.png")
        self.rect = self.image.get_rect()

class Game(object):
    def __init__(self):
        init()
        key.set_repeat(1, 30)
        self.screen = display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.clock = time.Clock()
        display.set_caption('Game')

        event.set_allowed([QUIT, KEYDOWN, KEYUP])
        self.background = Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.background.fill((0,0,0))
        self.screen.blit(self.background, (0,0))
        display.flip()

        self.sprites = sprite.RenderUpdates()

        self.character = Character((SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))

        self.sprites.add(self.character)

        self.balls = ball_manager(5)

        for ball in self.balls.blist:
            self.sprites.add(ball)

    def run(self):
        running = True
        while running == True:
            self.clock.tick(FPS)
            running = self.handleEvents()
            display.set_caption('game %d fps' % self.clock.get_fps())

            self.sprites.clear(self.screen, self.background)

            for sprite in self.sprites:
                sprite.update()

            dirty = self.sprites.draw(self.screen)
            display.update(dirty)

    def handleEvents(self):
        for e in event.get():
            if e.type == QUIT:
                return False

            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    return False
                if e.key == K_UP:
                    self.character.up()
                if e.key == K_DOWN:
                    self.character.down()
                if e.key == K_r:
                   self.sprites.add(Ball((random.randint(0, SCREEN_WIDTH),
                          random.randint(0, SCREEN_HEIGHT)),
                          random.randint(-2,2),
                          random.randint(-2,2)))

        return True

def main():
    game = Game()
    game.run()
    quit()

main()
sys.exit()

rawDescription: Making multiple balls move in pygame

description: Making multiple balls move in pygame


code: np.mean(x, axis=0)

rawDescription: python for loop to calculate mean value for each array segment

description: Python for loop to calculate mean value for each array segment


code:
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vect= TfidfVectorizer(  use_idf=True, smooth_idf=True, sublinear_tf=False)
from sklearn.cross_validation import train_test_split

df= pd.DataFrame({'text':['cat on the','angel eyes has','blue red angel','one two blue','blue whales eat','hot tin roof','angel eyes has','have a cat']\
              ,'class': [0,0,0,1,1,1,0,3]})

X = tfidf_vect.fit_transform(df['text'].values)
y = df['class'].values

from sklearn.decomposition.truncated_svd import TruncatedSVD
pca = TruncatedSVD(n_components=2)
X_reduced_train = pca.fit_transform(X)

a_train, a_test, b_train, b_test = train_test_split(X, y, test_size=0.33, random_state=42)

from sklearn.ensemble import RandomForestClassifier

classifier=RandomForestClassifier(n_estimators=10)
classifier.fit(a_train.toarray(), b_train)
prediction = classifier.predict(a_test.toarray())

rawDescription: TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] while using RF classifier?


rawDescription: How can I move the focus on a Treeview.item with pywinauto?

description: Move the focus on a Treeview.item with pywinauto


code: p = subprocess.Popen("diff "+infile+" "+outfile,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

rawDescription: How to pass a variablename to unix command in subprocess in python3

description: Pass a variablename to unix command in subprocess in python3


code:
connection = engine.raw_connection()
cursor = connection.cursor()
cursor.execute("EXEC sp_doLoaderStuff")
connection.commit()
connection.close()

rawDescription: stored proc not committing with sqlalchemy/pydodbc

description: Stored proc not committing with sqlalchemy/pydodbc


code:
from org.python.core.util import StringUtil
from java.nio import ByteBuffer

tmp, filename = tempfile.mkstemp(suffix = "." + extension, text=True)
bytes = StringUtil().toBytes(attachment)
bb = ByteBuffer.wrap(bytes)
tmp.write(bb)
tmp.close()

rawDescription: How to save email image attachment using Jython

description: Save email image attachment using Jython


code:
try:
    from tkinter import *
except ImportError:
    from Tkinter import *

class NewRoot(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.attributes('-alpha', 0.0)

class MyMain(Toplevel):
    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.overrideredirect(1)
        self.attributes('-topmost', 1)
        self.geometry('+100+100')
        self.bind('<ButtonRelease-3>', self.on_close)  #right-click to get out

    def on_close(self, event):
        self.master.destroy()

if __name__ == '__main__':

    root = NewRoot()
    root.lower()
    root.iconify()
    root.title('Spam 2.0')

    app = MyMain(root)
    app.mainloop()

rawDescription: Making Tkinter windows show up in the taskbar


code: bytes[0:2] == b'\xbe\xef'

rawDescription: Confused about bytes in Python

description: Confused about bytes in Python


code:
def validate(namespace, parser):
    if not any(arg in {"state", "key"} for arg in vars(namespace).keys()):
        parser.print_help()
        parser.exit(2)

namespace = parser.parse_args()
validate(namespace, parser)

rawDescription: How to make at least one argument required and have the possibility to take all arguments with argparse in Python?

description: Make at least one argument required and have the possibility to take all arguments with argparse in Python


code:
import urllib
stats_text = urllib.urlopen('http://ip.of.projector').read()

rawDescription: Fetching information from network projectors using python script


code:
import multiprocessing
from multiprocessing.dummy import Pool as ThreadPool
from functools import partial

def worker(x, y, z):
    pass # Do whatever here

def collectMyResult(result):
    print("Got result {}".format(result))

def abortable_worker(func, *args, **kwargs):
    timeout = kwargs.get('timeout', None)
    p = ThreadPool(1)
    res = p.apply_async(func, args=args)
    try:
        out = res.get(timeout)  # Wait timeout seconds for func to complete.
        return out
    except multiprocessing.TimeoutError:
        print("Aborting due to timeout")
        p.terminate()
        raise

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    featureClass = [[1000,k,1] for k in drange(start,end,step)] #list of arguments
    for f in featureClass:
      abortable_func = partial(abortable_worker, worker, timeout=3)
      pool.apply_async(abortable_func, args=f,callback=collectMyResult)
    pool.close()
    pool.join()

rawDescription: How can I abort a task in a multiprocessing.Pool after a timeout?

description: Abort a task in a multiprocessing.Pool after a timeout


code: new_dict = {'datetime': date_dict.keys(), 'observations': date_dict.values()}

rawDescription: A better way to reorganize dictionary key, value pairs?


rawDescription: Python Tkinter - resize widgets evenly in a window


code:
import ctypes

sectorsPerCluster = ctypes.c_ulonglong(0)
bytesPerSector = ctypes.c_ulonglong(0)
rootPathName = ctypes.c_wchar_p(u"C:\\")

ctypes.windll.kernel32.GetDiskFreeSpaceW(rootPathName,
    ctypes.pointer(sectorsPerCluster),
    ctypes.pointer(bytesPerSector),
    None,
    None,
)

print(sectorsPerCluster.value, bytesPerSector.value)

rawDescription: Determine cluster size of file system in Python


code:
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg') # Need to use in order to run on mac
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation

#=============================================================================================

t_start = 1917 # start frame
t_end = 2130 # end frame

data = pd.read_csv('Smart-first_phase_NaN-zeros.csv') # only coordinate data
df = data.loc[t_start:t_end,'Shoulder_left_x':'Ankle_right_z']

# Find max and min values for animation ranges
df_minmax = pd.DataFrame(index=list('xyz'),columns=range(2))
for i in list('xyz'):
    c_max = df.filter(regex='_{}'.format(i)).max().max()
    c_min = df.filter(regex='_{}'.format(i)).min().min()
    df_minmax.ix[i] = np.array([c_min,c_max])

df_minmax = 1.3*df_minmax # increase by 30% to make animation look better

df.columns  = np.repeat(range(12),3) # store cols like this for simplicity
N_tag = df.shape[1]/3 # nr of tags used (all)

N_trajectories = N_tag

t = np.linspace(0,data.Time[t_end],df.shape[0]) # pseudo time-vector for first walking activity
x_t = np.zeros(shape=(N_tag,df.shape[0],3)) # empty animation array (3D)

for tag in range(12):
    # store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
    x_t[tag,:,:] = df[tag]

x_t = x_t[:, :, [0, 2, 1]]

# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')

# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
# set up lines which create the stick figures

stick_defines = [
    (0, 1),
    (1, 2),
    (3, 4),
    (4, 5),
    (6, 7),
    (7, 8),
    (9, 10),
    (10, 11)
]

stick_lines = [ax.plot([], [], [], 'k-')[0] for _ in stick_defines]

# prepare the axes limits
ax.set_xlim(df_minmax.ix['x'].values)
ax.set_ylim(df_minmax.ix['z'].values) # note usage of z coordinate
ax.set_zlim(df_minmax.ix['y'].values) # note usage of y coordinate

# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)

# initialization function: plot the background of each frame
def init():
    for line, pt in zip(lines, pts):
        # trajectory lines
        line.set_data([], [])
        line.set_3d_properties([])
        # points
        pt.set_data([], [])
        pt.set_3d_properties([])
    return lines + pts + stick_lines

# animation function.  This will be called sequentially with the frame number
def animate(i):
    # we'll step two time-steps per frame.  This leads to nice results.
    i = (5 * i) % x_t.shape[1]

    for line, pt, xi in zip(lines, pts, x_t):
        x, y, z = xi[:i].T # note ordering of points to line up with true exogenous registration (x,z,y)
        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])

    for stick_line, (sp, ep) in zip(stick_lines, stick_defines):
        stick_line._verts3d = x_t[[sp,ep], i, :].T.tolist()

    ax.view_init(30, 0.3 * i)
    fig.canvas.draw()
    return lines + pts + stick_lines

# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=30, blit=True)

plt.show()

rawDescription: 3D animation with matplotlib, connect points to create moving stick figure


code:
df1.xs("Compress", level="op")
df1.xs("BuildIndex", level="op")
df1.xs("BuildIndex", level="op") - df1.xs("Compress", level="op")

rawDescription: update pandas.DataFrame within a group after .groupby()

description: Update pandas.DataFrame within a group after .groupby()


code: imglabel = self.ui.findChild(QtGui.QLabel, "imglabel")

rawDescription: Access widgets added in Qt Designer

description: Access widgets added in Qt Designer


code: compile("cubic_fit(1, 2, get_data())", '<string>', 'eval').co_names

rawDescription: Get functions called in a Python expression


code:
with open('special_words.txt', 'r') as handle:
    special_words = {line.strip() for line in handle}

def filter(word_list):
    return [word for word in word_list if word not in special_words]

rawDescription: Open file in module and keep it in memory


code:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout

class Query(AnchorLayout):
    def __init__(self, **kwargs):
        super(Query, self).__init__(**kwargs)
        self.anchor_x = 'left'
        self.anchor_y='top'

        box = BoxLayout()

        upc_l = Label(text='UPC:', font_size=40, size_hint_y=None,
                      size_hint_x=None, height=50, width=100,)
        entry = TextInput(font_size=40, size_hint_y=None, size_hint_x=None,
                          height=50, width=350)
        search_b = Button(text='Search', font_size=40, size_hint_y=None,
                          size_hint_x=None, height=50, width=200)

        box.add_widget(upc_l)
        box.add_widget(entry)
        box.add_widget(search_b)
        self.add_widget(box)

class MyApp(App):

    def build(self):
        return Query()

if __name__ == '__main__':
    MyApp().run()

rawDescription: Kivy Refractoring

description: Kivy Refractoring


rawDescription: Selecting Element followed by text with Selenium WebDriver


code:
def wait_for_it(proc):
    proc.poll()
    if proc.returncode is None:                      # subprocess hasn't finished yet
        root.after(100, lambda: wait_for_it(proc))   # register a callback for 100ms
    else:
        display(proc.communicate()[0])

def display(x):
    lhs, rhs = x.split("Average = ")
    # the rest of your code goes here...

# instead of root.after(0, display)
wait_for_it(subprocess.Popen(['ping', 'google.com']))

rawDescription: How to execute a subprocess with multithreading

description: Execute a subprocess with multithreading


code:
if filedata.file: # field really is an upload
    with file("Beautiful.mp3", 'w') as outfile:
        outfile.write(filedata.file.read())

rawDescription: Creation of a simple HTML file upload page


code:
d = collections.OrderedDict.fromkeys(zip(alist, blist))
[k[0] for k in d]
[k[1] for k in d]

rawDescription: remove duplicates using set on zip lists

description: Remove duplicates using set on zip lists


code:
A = [1,2,3]
def my_work(A):
    A[:] = [1]*len(A)

A
my_work(A)
A

rawDescription: Python short cut to fill list

description: Python short cut to fill list


rawDescription: use python regex to find key=value pairs separated by comma but keep quoted portion together

description: Use python regex to find key=value pairs separated by comma but keep quoted portion together


code: #TODO: Something

rawDescription: Add a todo list item in SPE (Stani's Python Editor)


code:
clf = Pipeline([('scale', Scaler()),
                ('svm', SVC())])

rawDescription: scikit support to scale features between [0,1] or [-1,1]

description: Scikit support to scale features between [0,1] or [-1,1]


code:
def quickSort(aList, l, r):
    if l < r:
        swap = l
        run = l
        pivot = aList[r]
        while run < r:
            if pivot >= aList[run]:
                aList[swap],aList[run]=aList[run],aList[swap]
                swap += 1
            run += 1

        aList[swap], aList[r] = aList[r], aList[swap]
        quickSort(aList, l, swap-1)
        quickSort(aList, swap+1, r)

rawDescription: quick sort, first sort works, parameters for recursive calls don't

description: Quick sort, first sort works, parameters for recursive calls don't


code:
from django.core.cache import cache

def simulation(a=1):
     value = 0
     while a != None:
          value += a
          cache.set('value', value, 3600)
          time.sleep(5)
          a = cache.get('a', None)

rawDescription: Getting information from long running background process in Django


code:
f = "www.mydomain.com/feed/rss/news_article_602262"
f.split('/')[-1]

rawDescription: feedparser removing <guid> and making long url as id - Python

description: Feedparser removing <guid> and making long url as id - Python


code:
def render(self):
    self.screen.delete("all")
    if GameKeys.isPressed(GameKeys.SPACE):
        print("SPACE")
    self.screen.update()
    self.after(100, self.render)

rawDescription: key only call once while down in python

description: Key only call once while down in python


rawDescription: Flask/SQLAlchemy - How to globally use latin-1 instead of UTF-8?


rawDescription: Python failing to compile on Linux with custom module built in


code:
def main(): pass

foo = main
def main(): pass

foo is main
foo
main

rawDescription: In Python, what does '<function at ...>' mean?


code:
labelR2s=[]
def getRead():
    #update printList
    readComm()
    #update display in GUI

    for i in range(0, len(printList)):               # Change the text for existing labels
        if (len(printList)>len(labelR2s)):           # this is the first time, so append
            labelR2s.append(Tk.Label(frameRead, text=str(printList[i])))
            labelR2s[i].pack(padx=10, pady=3)
        else:
            labelR2s[i].config(text=printList[i])    # in case of update, modify text

    window.update_idletasks()

rawDescription: How do I show updated values in the 'label' widget in Python Tkinter GUI?

description: Show updated values in the 'label' widget in Python Tkinter GUI


code:
import matplotlib.pyplot as plt
import numpy as np
pi = np.pi
sin = np.sin
t = np.linspace(0.0, 2 * pi, 50)
markers = ['+', '*', ',', ] + [r'$\lambda$']
phases = [0, 0.5]
fig, ax = plt.subplots(len(phases))
for axnum, phase in enumerate(phases):
    for i, marker in enumerate(markers, 1):
        ax[axnum].plot(t, i*sin(2*t + phase*pi), marker=marker,
                   label='$i,\phi = {i},{p}$'.format(i=i, p=phase))
    ax[axnum].legend(loc='best', numpoints=1)
plt.show()

rawDescription: Dynamically place legend in plot

description: Dynamically place legend in plot


code:
import itertools
import random

with open('fx-01.txt') as f:
    while True:
        n = random.randint(5, 15)
        elements = [line.strip() for line in itertools.islice(f, n)]
        # itertools.islice(f, n): to fetch `n` lines from file.
        if not elements:
        # if len(elements) < 5: # Use this if you want drop trailing <5 lines.
            break
        print(','.join(elements))

rawDescription: pull out element data random range from list

description: Pull out element data random range from list


code:
cmap = dict(zip(df.prime.unique(), colors))
cmap
df["color"] = df["prime"].replace(cmap)
df

rawDescription: Adding new values to a filtered pandas DataFrame


code:
coupon_types = (self.months, self.dollars, self.lifetime,)

true_count =  sum([1 for ct in coupon_types if ct])
if true_count > 1:
    raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars")

rawDescription: Python: if more than one of three things is true, return false


code:
import json
string_for_printing = json.dumps(original_string).strip('"')

rawDescription: How to escape string for generated C++?

description: Escape string for generated C++


code:
def dfs_limit(g, start, goal, limit=-1):
    '''
    Perform depth first search of graph g.
    if limit >= 0, that is the maximum depth of the search.
    '''
    SENTINEL = object()
    visitedStack = [start]
    path = []

    while visitedStack:
        currentVertex = visitedStack.pop()

        if currentVertex == goal:
            path.append(currentVertex)
            return ' -> '.join(path)

        elif currentVertex == SENTINEL:
            #finished this level; go back up one level
            limit += 1
            path.pop()

        elif limit != 0:
            # go one level deeper, push sentinel
            limit -= 1
            path.append(currentVertex)
            visitedStack.append(SENTINEL)
            visitedStack.extend(g.getVertex(currentVertex).getConnections())

rawDescription: Implementing Depth Limited Path Finding with Stack


code:
def _pad(self, s):
    amount_of_padding = self.bs - len(s) % self.bs   # between 1 and self.bs, inclusive
    padding_char = chr(amount_of_padding)            # encode amount_of_padding in ASCII!
    return s + amount_of_padding * padding_char      # do string repetition with *

def _unpad(self, s):
    padding_char = s[-1]                     # last char is always part of the padding
    amount_of_padding = ord(padding_char)    # decode amount from ASCII value of char
    return s[:-amount_of_padding]            # slice to skip padding chars

rawDescription: How does this Padding Function work

description: How does this Padding Function work


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

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

u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
#ax.plot_wireframe(x, y, z, color="r")

#ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')
ax.scatter(x,y,z,"o")

plt.show()

rawDescription: How to get Coordinates of a Sphere?

description: Get Coordinates of a Sphere


rawDescription: Query to fetch objects surrounding an object


code:
from ast import literal_eval

# sum all columns and replace resulting "][" between columns with ", "
# change str to list with literal_eval
allQuestions = literal_eval(dfQuestion.sum().replace("][", " ,"))
allAnswers = literal_eval(dfAnswers.sum().replace("][", " ,"))
allPosts = allQuestions + allAnswers

rawDescription: Pandas: Merge a dataframe column to a list


code:
from threading import Thread

yourSchemas = [schema1, schema2, schema3]
t = []
def test(region_by_schema):
    for base_schema in region_by_schema.keys():
        do_one_user(base_schema, opt_password)

    for schema in yourSchemas:
        t.append(Thread(target=test, args=[schema]))

    for i in range(len(yourSchemas)):
        t.start()
        t.join()

rawDescription: multithreading in python for loop

description: Multithreading in python for loop


code:
class FlushFile(object):
    """Write-only flushing wrapper for file-type objects."""
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

# Replace stdout with an automatically flushing version
sys.stdout = FlushFile(sys.__stdout__)

rawDescription: Intercepting stdout of a subprocess while it is running


rawDescription: How to use map function on nested lists and converting strings to integers?

description: Use map function on nested lists and converting strings to integers


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

@receiver(post_delete, sender=Book)
def auto_delete_publish_info_with_book(sender, instance, **kwargs):
    instance.info.delete()

@receiver(post_delete, sender=Newspaper)
def auto_delete_publish_info_with_newpaper(sender, instance, **kwargs):
    instance.info.delete()

rawDescription: How to delete one-to-one relating models cascading in django?

description: Delete one-to-one relating models cascading in django


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

# here are the three lists
# for example, you could do random values to demo
x = np.random.randn(8873)
y = np.random.randn(8873)
weights = np.random.rand(8873)

heatmap, _, _ = np.histogram2d(x, y, weights=weights)

plt.clf()
plt.imshow(heatmap)
plt.show()

rawDescription: python matplotlib making heat map out of tuples (x,y,value)

description: Python matplotlib making heat map out of tuples (x,y,value)


code:
import wx
import wx.aui, wx.lib.scrolledpanel

class AppFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)

        # The notebook
        self.nb = wx.aui.AuiNotebook(self)

        # Create a scrolled panel
        panel = wx.lib.scrolledpanel.ScrolledPanel(self, -1)
        panel.SetupScrolling()
        self.add_panel(panel, 'Scrolled Panel')

        # Create a normal panel
        panel = wx.Panel(self, -1)
        self.add_panel(panel, 'Simple Panel')

        # Set the notebook on the frame
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.nb, 1, wx.EXPAND)
        self.SetSizer(self.sizer)

        # Status bar to display the key code of what was typed
        self.sb = self.CreateStatusBar()

    def add_panel(self, panel, name):
        panel.Bind(wx.EVT_KEY_DOWN, self.on_key)
        self.nb.AddPage(panel, name)

    def on_key(self, event):
        self.sb.SetStatusText("key: %d [%d]" % (event.GetKeyCode(), event.GetTimestamp()))
        event.Skip()

class TestApp(wx.App):
    def OnInit(self):
        frame = AppFrame(None, -1, 'Click on a panel and hit a key')
        frame.Show()
        self.SetTopWindow(frame)
        return 1

if __name__ == "__main__":
    app = TestApp(0)
    app.MainLoop()

rawDescription: wxPython: Handling events in a widget that is inside a notebook

description: WxPython: Handling events in a widget that is inside a notebook


code:
from collections import deque

startPosition = 1
data = [1,10,20]

d = deque(data)
d.rotate(-startPosition)

rawDescription: Circular Iterator in Python

description: Circular Iterator in Python


code:
from bs4 import BeautifulSoup
sample = r'''

       }"

'''
soup = BeautifulSoup(sample)
soup.find_all('div', class_=r'\"message-container\"')

rawDescription: BeautifulSoup find on class doesn't work


code:
names_list = ["alice","bob"] #from your file
people = {"Pers"+str(i):Person(name) for i,name in enumerate(names_list)}

rawDescription: How do I procedurally assign more variables while the program is running?

description: Procedurally assign more variables while the program is running


code:
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        attr = dict(attrs)
        if attrs["class"] == "pagelink":
            add_to_result(attrs["onclick"])

rawDescription: How to retrieve onclick text?

description: Retrieve onclick text


code: is_64bits = sys.maxsize > 2**32

rawDescription: Python - check if a system is 32 or 64 bit to determine whether to run the function or not?


code:
class Directions:
    up = 0
    down = 1
    left = 2
    right =3

rawDescription: Enumerations in python

description: Enumerations in python


code:
import zipfile

archive = zipfile.ZipFile('archive.zip')

for file in archive.namelist():
    if file.startswith('foo/'):
        archive.extract(file, 'destination_path')

rawDescription: How to unzip specific folder from a .zip with Python

description: Unzip specific folder from a .zip with Python


code: df_sequence[['RUN_START_DATE', 'PUSHUP_START_DATE', 'SITUP_START_DATE', 'PULLUP_START_DATE']].apply(numpy.argsort, axis=1)

rawDescription: Return sorted indexes skipping nan values in pandas?


code:
def example():
  try:
    return pickle.loads("")
  except EOFError:
    return None

rawDescription: How to pickle a empty file?

description: Pickle a empty file


code:
import itertools
import Tkinter as tk

root = tk.Tk()
forgetButtons = [0,1,3,5,6,7,13,14,16,18,21,30,32,41,42,43,45,46,47,48]
myButtons = []

for x, y in itertools.product(range(7), repeat=2):
    if not x*7 + y in forgetButtons:
        btn = tk.Button(root, width=7, height=4, text="Room%d\none\ntwo\nfour\nfive" % x)
        btn.grid(column=x, row=y, padx=3, pady=3)
        myButtons.append(btn)

root.mainloop()

rawDescription: How to use grid_forget to eliminate a specific ordering of buttons after they have been instantiated

description: Use grid_forget to eliminate a specific ordering of buttons after they have been instantiated


code:
def runTest(self):
    Thread(target=buttonTest, args=(self,)).start()

rawDescription: Getting data from a long function to update a GUI


code: pairs = zip(*[iter(a)]*2)

rawDescription: Is any elegant way to make a list contains some integers to become a list contains some tuples?


code:
thingys = []
for y in l:
    for x in y:
        thingys.append(x)

rawDescription: Idiom for flattening a shallow nested list: how does it work?


rawDescription: String Comparison : Python

description: String Comparison : Python


code:
# some more code
EMPTY = ''
other_links = set()
processed_links = set()
my_page = '//div[@class="product_info"]//table//tr[7]//td[2]//a/@href'

for part in dom1.xpath(my_page):
    if part[:4] == 'http':
        if part not in processed_links:
            processed_links.add(part)
            FINAL_URL = urlparse.urljoin(url, part)
    else:
        other_links.add(part)

rawDescription: Verify if link starts with http when using lxml and xpath in Python


code:
b.submit()  # The second of the two forms
c = csv.DictReader(b.response(), dialect='excel-tab')

rawDescription: Download files from ASP forms with Python


rawDescription: Addressing part of a string via the array syntax in Python


code:
for k in range(1, L):
    mat=1-((signal[k+1:N-k]>signal[1:N-2*k]) & (signal[k+1:N-k]>signal[2*k+1:N]))
    LSM[k,k+2:N-k+1]*=mat

rawDescription: Vectorizing numpy Multiple Condition Nested Loops


code:
#!/usr/bin/env python

# Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com>
# License: MIT (see COPYING file)

# Import pygraphviz
import pygraphviz as pgv

# Graph creation and setting of attributes
gr = pgv.AGraph(rotate='90',bgcolor='lightgray')

# Add nodes and edges
gr.add_edge(("Portugal", "Spain"))
gr.add_edge(("Spain","France"))
gr.add_edge(("France","Belgium"))
gr.add_edge(("France","Germany"))
gr.add_edge(("France","Italy"))
gr.add_edge(("Belgium","Netherlands"))
gr.add_edge(("Germany","Belgium"))
gr.add_edge(("Germany","Netherlands"))
gr.add_edge(("England","Wales"))
gr.add_edge(("England","Scotland"))
gr.add_edge(("Scotland","Wales"))
gr.add_edge(("Switzerland","Austria"))
gr.add_edge(("Switzerland","Germany"))
gr.add_edge(("Switzerland","France"))
gr.add_edge(("Switzerland","Italy"))
gr.add_edge(("Austria","Germany"))
gr.add_edge(("Austria","Italy"))
gr.add_edge(("Austria","Czech Republic"))
gr.add_edge(("Austria","Slovakia"))
gr.add_edge(("Austria","Hungary"))
gr.add_edge(("Denmark","Germany"))
gr.add_edge(("Poland","Czech Republic"))
gr.add_edge(("Poland","Slovakia"))
gr.add_edge(("Poland","Germany"))
gr.add_edge(("Czech Republic","Slovakia"))
gr.add_edge(("Czech Republic","Germany"))
gr.add_edge(("Slovakia","Hungary"))

# Draw as PNG
gr.layout(prog='dot')
gr.draw('europe.png')

rawDescription: Setting graph attributes in pygraph

description: Setting graph attributes in pygraph


code:
text = 'According to James, "we do not know" the source of the problem, "we are clueless".'
re.sub('".+?"', '', text)

rawDescription: Python Reg expression to delete all text inside quotation marks


code:
suitcounter = [0, 0, 0, 0]
suits = {'C': 0, 'D': 1, 'S': 2, 'H': 3}

for card in hand:
    suitcounter[suits[card[1]]] += 1

rawDescription: Python - shortening a redundant loop

description: Python - shortening a redundant loop


rawDescription: Parsing evernote xml with element tree on python: how to find/delete elements with specific tag name


code:
number_of_consonants = sum(word.count(c) for c in consonants)

number_of_vowels = sum(word.count(c) for c in vowels)

rawDescription: python: Counting the amount of vowels or consonants in a user input word

description: Python: Counting the amount of vowels or consonants in a user input word


code:
from itertools import izip_longest
new_cols = DataFrame(list(izip_longest(*df[9].apply(lambda x:x.split(",")), fillvalue=""))).T

rawDescription: Turn column into multiple columns based on number of commas within string python pandas


rawDescription: Reference values in the previous row with map or apply


code:
import csv
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
keys = sorted(maxDict.keys())
csvw = csv.writer(open('output.csv', 'wb'))
csvw.writerow(keys)
data = [maxDict[k] for k in keys]
for row in zip(*data):
  csvw.writerow(row)

rawDescription: Python: Writing a csv output file of a tuple-valued dictionary


code:
def myprint(d, groups):
    new_d = {}
    for k, v in d.items():
        if isinstance(v, dict):
            new_d[k] = myprint(v, groups)
        elif isinstance(v, str):
            new_d[k] = groups[v[1:]] if v.startswith('*') else v
        else:
            new_d[k] = v
    return new_d

rawDescription: Loop through all nested dictionary values and modify value meeting criteria


code:
for index, row in df.iterrows():
    df.loc[index, "A"] = "I am working! {}".format(row["B"])

df

rawDescription: Replace values in Pandas data frame within a loop


code:
from time import *
ctime(time())
ctime(time()+altzone)

rawDescription: Python Convert UTC to PST / PDT format

description: Python Convert UTC to PST / PDT format


code:
ticks = ax.get_xticks()
ticks = np.union1d(ticks, [0.7])
ax.set_xticks(ticks)
ax.set_xticklabels(newlabels)

rawDescription: Tick label modification; How to add an arbitrary tick on the label:


code:
import urllib2

class RedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
        result.status = code
        return result
    http_error_301 = http_error_303 = http_error_307 = http_error_302

opener = urllib2.build_opener(RedirectHandler())
webpage = opener.open('http://www.example.com/product1/456')
...

rawDescription: Preventing a "hidden" redirect with urlopen() in Python


code:
tn.write("<binary_name>")
time.sleep(10)
junk=tn.read_very_eager()
tn.write("cat <path_of_output_file>")
rd_buf=tn.read_very_eager()
print(rd_buf)

rawDescription: Restrict or limit read_very_eager() in python


code:
import re

text = re.sub('<[^<]+>', "", open("/path/to/file").read())
with open("/path/to/file", "w") as f:
    f.write(text)

rawDescription: Python strip XML tags from document

description: Python strip XML tags from document


code:
L = [0, 0, 1, 1, 2, 2, 0]
list(itertools.dropwhile(lambda x: x == 0, L))

rawDescription: lstrip(), rstrip() for lists

description: Lstrip(), rstrip() for lists


code:
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.cross_validation import train_test_split

#create x data
data2['xraw'] = data2.index
x  = data2['xraw'].astype(np.int64) // 10**9

y  = data2['kwh']
y = y.reshape((y.shape[0],1))

#train-test split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(x_train, y_train)

# The coefficients
print('Coefficients: \n', regr.coef_)

# The mean square error
print("Residual sum of squares: %.2f" % np.mean((regr.predict(x_test) - y_test) ** 2))

# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % regr.score(x_test, y_test))

# Plot outputs
plt.scatter(x_test, y_test,  color='black')
plt.plot(x_test, regr.predict(x_test), color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()

rawDescription: prediction using linear regression with sklearn

description: Prediction using linear regression with sklearn


code:
class test(QtGui.QDialog):

    def __init__(self):
        self.directory = None

    def selectFile(self):
        self.listWidget.clear() # In case there are any existing elements in the list
        directory = QtGui.QFileDialog.getExistingDirectory(self, "Pick a folder")
        self.directory = directory

    def convertfile(self):
        directoryPath = self.directory

rawDescription: Python PYQT converting a file

description: Python PYQT converting a file


code:
# Created a simple class for a row in your table
class Row(object):
    def __init__(self, i, t, x, y):
        self.i, self.t, self.x, self.y = int(i), int(t), int(x), int(y)

# Used your example rows...
example_rows = """10  1   34  23
11  1   34  54
12  1   42  4
13  1   76  3
14  1   35  56
15  1   23  4
16  2   56  5
17  2   46  6
18  2   35  77
19  3   75  6
20  3   54  7
21  3   43  6"""

# Build a list with rows from the example 'table'
l = [Row(*i) for i in (line.split() for line in example_rows.split("\n"))]

# Create a types_x dictionary
types_x = {}
for r in l:
    types_x[r.t] = types_x.get(r.t, 0) + r.x

# Print the result
print(types_x) # {1: 244, 2: 137, 3: 172}

rawDescription: Python 2.7 - Extracting information from a table and assigning it to a variable


code:
import csv
import pyodbc

connStr = (
    r"Driver={SQL Server};"
    r"Server=(local)\SQLEXPRESS;"
    r"Database=myDb;"
    r"Trusted_connection=yes;"
    )
cnxn = pyodbc.connect(connStr)
crsr = cnxn.cursor()

sql = """\
SELECT 101 AS numthing, 'foo' AS txtthing
UNION ALL
SELECT 102 AS numthing, 'bar' AS txtthing
UNION ALL
SELECT 103 AS numthing, 'baz' AS txtthing
"""
crsr.execute(sql)
i = 1
for row in crsr:
    with open('C:/__tmp/Projects/record{0}.csv'.format(i), 'w') as f:
        csv.writer(f).writerow(row)
        i += 1
crsr.close()
cnxn.close()

rawDescription: Python Write to Record to New Text File

description: Python Write to Record to New Text File


code: a[[list(a[:, 0]).index(i) for i in a[0]]]

rawDescription: python numpy, sort a matrix by row and column

description: Python numpy, sort a matrix by row and column


code:
from threading import Thread

class MyClass(Thread):
    def __init__(self, other, arguments, here):
        super(MyClass, self).__init__()
        self.daemon = True
        self.cancelled = False
        # do other initialization here

    def run(self):
        """Overloaded Thread.run, runs the update
        method once per every 10 milliseconds."""

        while not self.cancelled:
            self.update()
            sleep(0.01)

    def cancel(self):
        """End this timer thread"""
        self.cancelled = True

    def update(self):
        """Update the counters"""
        pass

my_class_instance = MyClass()

# explicit start is better than implicit start in constructor
my_class_instance.start()

# you can kill the thread with
my_class_instance.cancel()

rawDescription: Python class instance starts method in new thread


code:
hid = plt.pcolormesh(X,Y, data, antialiased=True)

#here we cover up the region that we just plotted in
r3 = [1 for i in range(360)]
theta3 = np.arange(360)*np.pi/180.
plt.fill(theta3, r3, 'w')

#now we can go through and fill in all the regions
for j in range(len(r)):
    rbox = np.array([r[j], r[j], r[j]+ rstep, r[j] + rstep])
    for i in range(len(theta)):
        thetabox = np.array([theta[i], theta[i] + tstep, theta[i] + tstep, theta[i]])
        x = rbox*np.cos(thetabox)
        y = rbox*np.sin(thetabox)
        colorv = np.sin(r[j]/10.*np.pi)
        plt.fill(thetabox,rbox, facecolor = my_cmap(colorv))
#And now we can plot the color bar that fits the data Tada :)
plt.colorbar()
plt.show()

rawDescription: Creating a colour bar for a plot made with plt.fill


code:
import httplib
import urllib

conn = httplib.HTTPSConnection("api.mercadolibre.com")
conn.request("POST", "/oauth/token", urllib.urlencode({
    "grant_type": "client_credentials",
    "client_id": "CLIENT_ID",
    "client_secret": "CLIENT_SECRET",
  }), {"accept": "application/json", "content-type": "application/x-www-form-urlencoded"})
conn.getresponse()

rawDescription: CURL in Python or Django

description: CURL in Python or Django


code:
quadrants = [(685, 227, green),
             (310, 203, red),
             (684, 518, yellow),
             (311, 518, blue)]
x, y = 310, 200
ekraan.blit(background, (x, y))

while True:
    for i in pygame.event.get():
        pygame.display.flip()
        if i.type == pygame.QUIT:
            sys.exit()
        elif i.type == pygame.MOUSEBUTTONDOWN:
            mx, my = i.pos
            for x, y, color in quadrants:
                if abs(mx-x) < 379 and abs(my-y) < 319:
                    ekraan.blit(color, (x, y))
                    klickedButton = color
                    break

rawDescription: How to make interactive area around boxes?

description: Make interactive area around boxes


code:
from django.core.urlresolvers import reverse

def create_photoset_from_photos(modeladmin, request, queryset):
    ids = ','.join([str(photo_id) for photo_id in queryset.values_list('id', flat=True)])
    add_photoset_url = '{url}?photos={ids}'.format(url=reverse('admin:photography_photoset_add'), ids=ids)
    return HttpResponseRedirect(add_photoset_url)

rawDescription: Django: Initialize model add view with data through admin action


code: c.execute('INSERT INTO tablename VALUES ({}?)'.format('?,'*(len(t) - 1)), t)

rawDescription: Brief syntax for inserting row into sqlite database using python sqlite3


code:
import threading
import time

class MiThread(threading.Thread):
    def __init__(self):
        self.my_check = " CHECK "
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(5)
        print("I'm the SECOND thread")
        self.my_check = " CHECK DONE!!!"

print ("I'm the principal thread.")

t = MiThread()
t.start()

while True:
    time.sleep(0.5)
    print("I'm the principal thread, too." + t.my_check)

rawDescription: returning variables from a thread process function in Python 3

description: Returning variables from a thread process function in Python 3


code:
from functools import update_wrapper

def owns_hotdog(hotdog):
    def decorator(fn):
        def wrapped_function(*args, **kwargs):
            # First check if user is authenticated.
            if not logged_in():
                return redirect(url_for('login'))
            # For authorization error it is better to return status code 403
            # and handle it in errorhandler separately, because the user could
            # be already authenticated, but lack the privileges.
            if not authorizeowner(hotdog):
                abort(403)
            return fn(*args, **kwargs)
        return update_wrapper(wrapped_function, fn)
    return decorator

@app.errorhandler(403)
def forbidden_403(exception):
    return 'No hotdogs for you!', 403

rawDescription: How to make a python decorator function in Flask with arguments (for authorization)

description: Make a python decorator function in Flask with arguments (for authorization)


code:
import matplotlib

def empty_get_cachedir(*args, **kwargs):
    return None

matplotlib.get_cachedir = empty_get_cachedir

rawDescription: avoiding the local cache when fetching yahoo finance data from matplotlib.finance in python

description: Avoiding the local cache when fetching yahoo finance data from matplotlib.finance in python


code: np.square(b[:,None] - a).sum(axis=2).T

rawDescription: Sum the squared difference between 2 Numpy arrays


code:
function_table = { u'pmcTRIANG': np.random.triangular }

result = { input[1]: function_table[input[0]](*map(float, input[2:])) }

rawDescription: Turn list into function call

description: Turn list into function call


code:
report.summary=render_template_string(r'
This is a report for {{ user.first_name }}.
', user)

rawDescription: Jinja2 - Process variable from Flask view


code:
class BaseModelSerializer(serializers.ModelSerializer):
    object_type = serializers.SerializerMethodField()

    def get_object_type(obj):
        return obj.__class__.__name__.lower()

class ArticleSerializer(BaseModelSerializer):
    class Meta:
        model = Article
        fields = ('object_type',)

rawDescription: Django rest framework - how to serialise the model class name base serialiser?


code:
MyModel1.foreign_key_id == 5  # this is stored on the model
                              # and does not require a lookup.
MyModel1.foreign_key.id == 5  # this is stored on the target table
                              # and requires a DB hit.

rawDescription: Django query single underscore behaving like double underscore?


rawDescription: What would be a good way to deal with backslash escaped characters?


code:
framerate = 23.976

def _seconds(value):
    if isinstance(value, str):  # value seems to be a timestamp
        _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
        return sum(f * float(t) for f,t in _zip_ft)
    elif isinstance(value, (int, float)):  # frames
        return value / framerate
    else:
        return 0

def _timecode(seconds):
    return '{h:02d}:{m:02d}:{s:02d}:{f:02d}' \
            .format(h=int(seconds/3600),
                    m=int(seconds/60%60),
                    s=int(seconds%60),
                    f=round((seconds-int(seconds))*framerate))

def _frames(seconds):
    return seconds * framerate

def timecode_to_frames(timecode, start=None):
    return _frames(_seconds(timecode) - _seconds(start))

def frames_to_timecode(frames, start=None):
    return _timecode(_seconds(frames) + _seconds(start))

print(timecode_to_frames('00:00:18:10', start='00:00:05:15'))  # ~ 307
print(frames_to_timecode(307, start='00:00:05:15'))  # '00:00:18:10'

rawDescription: Convert Timecode to Frames with set start timecode


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes()

points_with_annotation = []
for i in range(10):
    point, = plt.plot(i, i, 'o', markersize=10)

    annotation = ax.annotate("Mouseover point %s" % i,
        xy=(i, i), xycoords='data',
        xytext=(i + 1, i), textcoords='data',
        horizontalalignment="left",
        arrowprops=dict(arrowstyle="simple",
                        connectionstyle="arc3,rad=-0.2"),
        bbox=dict(boxstyle="round", facecolor="w",
                  edgecolor="0.5", alpha=0.9)
        )
    # by default, disable the annotation visibility
    annotation.set_visible(False)

    points_with_annotation.append([point, annotation])

def on_move(event):
    visibility_changed = False
    for point, annotation in points_with_annotation:
        should_be_visible = (point.contains(event)[0] == True)

        if should_be_visible != annotation.get_visible():
            visibility_changed = True
            annotation.set_visible(should_be_visible)

    if visibility_changed:
        plt.draw()

on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)

plt.show()

rawDescription: Matplotlib basemap: Popup box

description: Matplotlib basemap: Popup box


code:
import os

outfile = open('bla.txt.2', 'w')

search = "#test search 123"
flag = 0

with open('bla.txt', 'r') as f:

    for line in f:
        if flag == 1:
            mod_line = "#" + line
            outfile.write(mod_line)
            flag = 0
            continue

        outfile.write(line)
        if (search in line):
            flag = 1

outfile.close()

os.remove('bla.txt')
os.rename('bla.txt.2', 'bla.txt')

rawDescription: Python search string and replace character in next line


code:
@view_config(route_name='home', renderer='json')
# It's better to keep non-pretty JSON renderer as a default one
def home(request):
   if request.params.get('pretty'):
       request.override_renderer = 'prettyprintjson'
   return {'name':'Fred'}

rawDescription: How do I change from json to a prettyprintjson renderer depending on params passed in?

description: Change from json to a prettyprintjson renderer depending on params passed in


code:
htmlstr = """    <input type="hidden" autocomplete="off" id="post_form_id" name="post_form_id" value="d619a1eb3becdc05a3ebea530396782f" />
    <input type="hidden" name="fb_dtsg" value="AQCYsohu" autocomplete="off" />"""
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmlstr)
[(n['name'], n['value']) for n in soup.findAll('input')]

rawDescription: Find value of input field in html doc using python


code:
# plot a function like y = sin(x) with Tkinter canvas and line

from Tkinter import *
import math

root = Tk()
root.title("Simple plot using canvas and line")

width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor = 0.04
# height stretch
y_amplitude = 80

c = Canvas(width=width, height=height, bg='white')
c.pack()

str1 = "sin(x)=blue"
c.create_text(10, 20, anchor=SW, text=str1)

center_line = c.create_line(0, center, width, center, fill='green')

# create the coordinate list for the sin() curve, have to be integers
xy1 = []
for x in range(400):
    # x coordinates
    xy1.append(x * x_increment)
    # y coordinates
    xy1.append(int(math.sin(x * x_factor) * y_amplitude) + center)

sin_line = c.create_line(xy1, fill='blue')
root.mainloop()

rawDescription: How to draw sinus wave with Tkinter?

description: Draw sinus wave with Tkinter


code:
s = "ASP.NET_SessionId=dqxmhmiDDsraoy4znfohxuk5; ASP.NET_SessionComm=ohitdbrqaaoy4znfohitdS9; SIDPCookie=yDsraavwmhmioi55a2litd55;"
a, b, c = s.split()
a
b
c

rawDescription: Cookie Regular Expression in python

description: Cookie Regular Expression in python


code:
from sys import stdout
from time import sleep

def log():
    while True:
        print('Test log message')
        # flush your buffer
        stdout.flush()
        sleep(1)

rawDescription: How to print out Python message to linux stdout immediately

description: Print out Python message to linux stdout immediately


code:
pattern = r'((?:January|February|March|April|May|June|July|August|September|October|November|December) \d\d?)'
re.findall(pattern, text)[-1]

rawDescription: Python Regex: Pulling the latest date from a string


rawDescription: Python: Splitting by certain pattern

description: Python: Splitting by certain pattern


code:
object_number = [] # list of Object Number
mass_of_object = [] # list of Mass of Object
with open('data.txt') as f:
    for line in f:
        if line.startswith('Object Number'):
            object_number.append(int(line.split('=')[1]))
        elif line.startswith('Mass of Object'):
            mass_of_object.append(int(line.split('=')[1]))

rawDescription: Reading data from large text file with strings and floats in Python


code:
import wx

class myFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None)

        panel1 = wx.Panel(self)
        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        panel1.SetSizer(self.mainSizer)
        self.button1 = wx.Button(panel1, label='xxx')
        self.list1 = wx.ListCtrl(panel1, size=(300, -1),
                                 style=wx.LC_REPORT | wx.LC_VRULES)
        self.mainSizer.Add(self.button1, 0, wx.CENTER)
        self.mainSizer.Add(self.list1, 1, wx.ALL | wx.CENTER, 20)
        self.button1.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self, pliki):
        self.list1.InsertColumn(0, 'col1')
        self.list1.InsertColumn(1, 'col2')
        self.list1.InsertColumn(2, 'col3')
        self.sizeColumns()

    def sizeColumns(self):
        self.list1.SetColumnWidth(0, 150)
        self.list1.SetColumnWidth(1, 150)
        size = (sum([self.list1.GetColumnWidth(i) for i in (0, 1, 2)]), -1)
        self.list1.SetSize(size)
        self.list1.SetMinSize(size)
        self.list1.PostSizeEventToParent()

x = wx.App()
y = myFrame().Show()
x.MainLoop()

rawDescription: resize wx.ListCtrl after creation

description: Resize wx.ListCtrl after creation


code:
class Client(...):
    ...
Client._meta.get_field('mobile')._unique = False

rawDescription: How to remove unique constraint for a model attribute of an abstract model after inheritance?

description: Remove unique constraint for a model attribute of an abstract model after inheritance


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

# sampledata
x = np.arange(199)
r = np.random.rand(100)
y = np.convolve(r, r)

# plot sampledata
plt.plot(x, y, color='grey')

# smoothen sampledata using a 50 degree polynomial
p = sp.polyfit(x, y, deg=50)
y_ = sp.polyval(p, x)

# plot smoothened data
plt.plot(x, y_, color='r', linewidth=2)

plt.show()

rawDescription: How to smooth date based data in matplotlib?

description: Smooth date based data in matplotlib


code:
# Ignore first two lines
t,a,b = np.genfromtxt(path,skiprows=2,delimiter='\t',unpack=True)

rawDescription: ploting graphe with time format from txt file in python

description: Ploting graphe with time format from txt file in python


code:
new_vals = np.array([99, 77])
new_vals[ind]

rawDescription: Using an index array to assign values to an array in numpy


rawDescription: In Python, how to sort a dict inside a dict by a key within the inner dict


code:
from skimage import color
color.colorconv.lab_ref_white = np.array([0.96422, 1.0, 0.82521])
lab = color.rgb2lab(image)

rawDescription: Fast way to convert rgb to lab in python


code:
listcopy = list[:]

import copy
listcopy = copy.copy(list)

# Also make a copy of the objects in the list
import copy
listcopy = copy.deepcopy(list)

rawDescription: Freeze list copy

description: Freeze list copy


code: FigureCanvas.__init__(self, fig)

rawDescription: use a matplotlib Figure in PyQt

description: Use a matplotlib Figure in PyQt


code:
# extract
this_friend = shelf[full_name]
# mutate
this_friend.add_timestamp(now)
# re-add
shelf[full_name] = this_friend
shelf.close()

rawDescription: Python: Append to list owned by an instance stored in shelved dictionary


code:
text = "Yes: No Maybe: So"
words = [w.rstrip(':') for w in text.split()]
new_dict = dict(zip(words[::2], words[1::2]))

rawDescription: Adding 2 dictionary entries from one string


rawDescription: using python to convert integer to 8bit binarey

description: Using python to convert integer to 8bit binarey


code:
import xml.etree.ElementTree as etree
data = """<response>
    <data>
        <vin>1FT7X2B69CEC76666</vin>
    </data>
    <data>
        <vin>1GNDT13S452225555</vin>
    </data>
</response>"""
tree = etree.fromstring(data)
[el.text for el in tree.findall('.//data/vin')]

rawDescription: Store XML values as Python list

description: Store XML values as Python list


code:
def guid2hexstring(val):
    s = ['\\%02X' % ord(x) for x in val]
    return ''.join(s)

guid = ldapobject.get('objectGUID', [''])[0] # 'Igr\xafb\x19ME\xb2P9c\xfb\xa0\xe2w'
guid2string(guid).replace("\\", "") # '496772AF62194D45B2503963FBA0E277'

#and back to a value you can use in an ldap search filter

guid = ''.join(['\\%s' % guid[i:i+2] for i in range(0, len(guid), 2)]) # '\\49\\67\\72\\AF\\62\\19\\4D\\45\\B2\\50\\39\\63\\FB\\A0\\E2\\77'

searchfilter = ('(objectGUID=%s)' % guid)

rawDescription: Python LDAP converting objectGUID to hex string and back


code: str(form['name'])

rawDescription: How does {{ field }} display a field widget in a django template?


code:
a = ['stste', 'setset', 'serthjsetj']
b = json.dumps(a)
b
json.loads(b)

rawDescription: Python List not getting in rendered in javascript


rawDescription: getting spider instance from scrapyd

description: Getting spider instance from scrapyd


code:
def parse(self, source, parser=None):
    if not hasattr(source, "read"):
        source = open(source, "rb")
    if not parser:
        parser = XMLParser(target=TreeBuilder())
    while 1:
        data = source.read(65536)
        if not data:
            break
        parser.feed(data)
    self._root = parser.close()
    return self._root

rawDescription: Python: How to preserve Ä,Ö,Ü when writing to file


code:
import csv
fp = open('samples.csv')
rdr = csv.DictReader(filter(lambda row: row[0]!='#', fp))
for row in rdr:
    print(row)
fp.close()

rawDescription: Python: skip comment lines marked with # in csv.DictReader


code:
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField()

class Mobile(models.Model):
    phone_number = models.CharField(min_length = 7, max_length = 20)
    description = models.CharField(min_length = 7, max_length = 20)
    user_profile = models.ForeignKey(UserProfile)

rawDescription: Create OneToMany models in django

description: Create OneToMany models in django


code:
class A(object):
  pass
class B(object):
  pass
a = A()
type(a)
a.__class__ = B
type(a)
a.__class__ = int

rawDescription: Replace instance with a float from within instance method?


code:
for i, value in enumerate(sections):
    if i not in [17, 24]:
        if ' tax ' in sections[i] or ' Tax ' in sections[i]:
            pat = re.compile("|".join([r"\b{}\b".format(m) for m in months]), re.M)
            month = pat.search("\n".join(sections[i].splitlines()[0:6]))
            print(month)

rawDescription: loop within a loop Python

description: Loop within a loop Python


code:
b = BeautifulSoup.BeautifulStoneSoup("
This is a paragraph with some extra formatting scattered throughout.
")
b.find('p')
b.find('p').next
b.find('p').next.next

rawDescription: Parse XML in order using Python

description: Parse XML in order using Python


rawDescription: Finding rows which aren't in two dataframes


code:
for key in dict1.keys():
    if 'red' in dict1[key]:
        theList = dict1[key]
        # remove 'red' from theList
        # append 'red' to another list in dict1

rawDescription: A dictionary of keys and lists as their values. How to identify item in the list, and move to another list? (python)


code:
use_colours = {"L": "red", "A": "green", "B": "blue"}
ax.scatter(a,b,c,c=[use_colours[x[0]] for x in d],s=50)

rawDescription: Python matplotlib scatter plot : changing colour of data points based on given conditions


code:
class ASGGroup(Model):
    name = CharField(max_length=63, null=True)

    def __unicode__(self):
        return self.name

rawDescription: Django: name of many to many items in the admin interface


code:
class customer_classes:
    # create the base class
    base = declarative_base(metadata=metadata)

    def __init__(self, metadata, customer_id):

        class analytics(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        class embeds(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        class downloads(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        # now lets assign all these classes to attributes
        import inspect
        defined_classes = [cls for cls in locals().values()
                           if inspect.isclass(cls) and issubclass(cls, base)]
        self.__dict__.update({cls.__name__: cls for cls in defined_classes})

# now we can create a set of classes for customer 123
customer_model = customer_classes(123)
session.query(customer_model. analytics).all()

# you can just as easily work with another customer at the same time in the same session
another_model = customer_classes(456)
session.query(another_model.analytics).all()

rawDescription: Using SQLAlchemy mappings with variant tables


code:
from glob import glob

import numpy as np

def read(fname, skip_header=1):
    with open(fname) as f:
        for i in range(skip_header):
            f.next()
        return f.next()

a = np.genfromtxt((read(fname) for fname in glob('test*.txt')))

rawDescription: Python: way to read data from multiple files into 2D numpy array or list


code:
if Gtk.events_pending():
    Gtk.main_iteration()

rawDescription: PyGObject (Glade) Window Never Showing (Multithreaded)


code: ''.join(map(unichr, [65,66,67])) # outputs ABC

rawDescription: Is there a python version of javascript's String.fromCharCode?


code:
from Tkinter import *

myGui=Tk()
myGui.geometry("200x100")
myGui.title("basicGUI")
myGui.configure(bg="gray")

def toggle():
    if buttonText.get() == "LBS":
        buttonText.set("KGS")
    else:
        buttonText.set("LBS")

buttonText = StringVar()
buttonText.set("LBS")      # you can't do StringVar("LBS")
tglBtn = Button(textvariable=buttonText,
                command=toggle)
tglBtn.pack()

mainloop()

rawDescription: if else, button not working

description: If else, button not working


code:
dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']

rawDescription: Extract values in Pandas value_counts()

description: Extract values in Pandas value_counts()


code:
rd = {}
for rowx in xrange(1, sheet.nrows):
    cell = sheet.cell(rowx, 0)
    if cell.ctype != xlrd.XL_CELL_TEXT: continue
    cv = cell.value.strip()
    if not cv: continue
    if cv in rd:
        complain_about_duplicate_row_names()
    rd[cv] = sheet.row_values(rowx)

rawDescription: How to slice excel values based on row values

description: Slice excel values based on row values


code:
try:
  from cStringIO import StringIO
except:
  from StringIO import StringIO
import zipfile

fp = StringIO('PK\x03\x04\x14')
zfp = zipfile.ZipFile(fp, "r")

rawDescription: If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?


code:
LETTERS = "abcdefghijklmnopqrstuvwxyzabc"

def translate_char(ch):
    i = LETTERS.find(ch.lower())
    if i == -1:
        return ch
    else:
        return LETTERS[i:i + 4]

def translate_string(s):
    return "".join(translate_char(ch) for ch in s)

print(translate_string("Hello!"))   # =>  hijkefghlmnolmnoopqr!

rawDescription: Pyhton String Converter; how do I convert a string in python


code: subprocess.Popen(['python3', '-m', 'path.to.python.file', '--option1=OPTION_VALUE'])

rawDescription: How to run Python Library Module as a script from another python file? (Python 3.5.1)

description: Run Python Library Module as a script from another python file? (Python 3.5.1)


code:
def commonprefix(l):
    # this unlike the os.path.commonprefix version
    # always returns path prefixes as it compares
    # path component wise
    cp = []
    ls = [p.split('/') for p in l]
    ml = min( len(p) for p in ls )

    for i in range(ml):

        s = set( p[i] for p in ls )
        if len(s) != 1:
            break

        cp.append(s.pop())

    return '/'.join(cp)

rawDescription: How to circumvent the fallacy of Python's os.path.commonprefix?

description: Circumvent the fallacy of Python's os.path.commonprefix


code:
import sys
getattr(sys.modules[__name__], "Foo")

# or

globals()['Foo']

rawDescription: Get python class object from class name string in the same module


code:
def key_check(self, key):  # "x" is a meaningless name; use something meaningful
    lookup = {
        'grade': self.grade
    }
    func = lookup[key]  # Look up the correct method
    return func()  # Call that method and return its result

rawDescription: Using dict like C switch

description: Using dict like C switch


code:
for h,i in enumerate(self.labels):
    i.bind('<Button-1>', lambda event, i=i: toggle(i.cget('text')))  # <--
    i.grid(row=h%200, column=int(floor(h/200))+1)

rawDescription: Attribute is assigned only to last object in list


rawDescription: How to test memory usage for different parts of the project in Python?

description: Test memory usage for different parts of the project in Python


code:
class LanguagePair(models.Model):
   from_language = models.CharField(max_length=220)
   to_language = models.CharField(max_length=220)

class Translator(models.Model):
   languages = models.ManyToManyField('LanguagePair')
   ...

rawDescription: How to store list of tuples in Django model?

description: Store list of tuples in Django model


code:
from google.appengine.ext import ndb

class PhoneUser(ndb.Model):
  number = ndb.StringProperty()
  user = ndb.KeyProperty()

class User(ndb.Model):
  pass

u = User()
u.put()

p = PhoneUser(id='123-456-7890', number='123-456-7890', user=u.key)
p.put()

u2 = User()
u2.put()

p2 = PhoneUser(id='555-555-5555', number='555-555-5555', user=u2.key)

result =  ndb.get_multi([ndb.Key(PhoneUser, '123-456-7890'), ndb.Key(PhoneUser, '555-555-5555')])

rawDescription: Efficient way to do large IN query in Google App Engine?


code:
date_list = avDates()
date_list_string = ' '.join(date_list) # edit this to match the desired output

html = """

These are the available dates:

""" + date_list_string + """"

"""

rawDescription: How to print Python array within HTML email body?

description: Print Python array within HTML email body


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'testdb',
        'USER': 'testdb_user',
        'PASSWORD': 'testdbpassw',
        'HOST': '',
        'PORT': '',
    },
    'fb': {
        'ENGINE': 'firebird',
        'NAME': '/home/idle/mydb.gdb',
        'USER': 'SYSDBA',
        'PASSWORD': 'passw',
        'HOST': '127.0.0.1',
        'PORT': '3050',
        'OPTIONS': {'charset':'WIN1251', 'dialect':1} ,
    }
}

rawDescription: Django-firebird can not work

description: Django-firebird can not work


rawDescription: How do I get the class of a ManyToMany field in django models?

description: Get the class of a ManyToMany field in django models


code:
import sympy
sympy.__version__
from sympy import S, Eq, solve

vf, d, a, vi, t = S('vf d a vi t'.split())
equations = [
    Eq(vf, vi+a*t),
    Eq(d, vi*t + a*t**2/2),
    Eq(a, 10),
    Eq(d, 60),
    Eq(vi, 5)]

solve(equations)
solve(equations, [a, t, vi, vf, d])

rawDescription: Solving Systems of Equations with SymPy

description: Solving Systems of Equations with SymPy


code:
result = {}
for x in original_list: result.setdefault(x[0], []).append(x[1])
result

rawDescription: effective way of creating dict from a nested list

description: Effective way of creating dict from a nested list


code:
def get_username(request):
    if hasattr(request, 'resolver_match'):
        slug = request.resolver_match.kwargs.get('slug')
        return {'slug': slug}
    return {}

rawDescription: Can I access url kwargs in django template context processor?

description: Access url kwargs in django template context processor


code:
def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

rawDescription: Mapping a range of values to another

description: Mapping a range of values to another


code:
str1 = "This is    a  foo bar   sentence with  crazy spaces that  irritates   my program "
' '.join(str1.split())

rawDescription: Replace multi-spacing in strings with single whitespace - Python


code:
import csv
inputs = ["in1.csv", "in2.csv"]  # etc

# First determine the field names from the top line of each input file
# Comment 1 below
fieldnames = []
for filename in inputs:
  with open(filename, "r", newline="") as f_in:
    reader = csv.reader(f_in)
    headers = next(reader)
    for h in headers:
      if h not in fieldnames:
        fieldnames.append(h)

# Then copy the data
with open("out.csv", "w", newline="") as f_out:   # Comment 2 below
  writer = csv.DictWriter(f_out, fieldnames=fieldnames)
  for filename in inputs:
    with open(filename, "r", newline="") as f_in:
      reader = csv.DictReader(f_in)  # Uses the field names in this file
      for line in reader:
        # Comment 3 below
        writer.writerow(line)

rawDescription: Merge CSVs in python with different columns


code:
import matplotlib.pyplot as plt
from cycler import cycler
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +
                           cycler('linestyle', ['-', '--', ':', '-.'])))

rawDescription: Set default line style cycler in matplotlib


code:
def open_remote_recording():
    recording_doc_id, recording_id = tuple(request.args)
    url = get_doc_url(server = RECORDINGS_SERVER, database = RECORDINGS_DATABASE, doc_id = recording_doc_id, attachment = recording_id)
    content_type = 'audio/mp3'
    f = urllib.urlopen(url)
    return f

@auth.requires_login()
def recordings():
    f = open_remote_recording()
    return response.stream(f, chunk_size=4096)

rawDescription: Stream a couchdb attachment with web2py

description: Stream a couchdb attachment with web2py


code:
for proc_id in pidlist:
   os.kill(int(proc_id), signal.SIGTERM)

rawDescription: Kill all processes using a list of pid's in python?


code:
import re
s = re.compile('\d+')
s2 = 'a123'
s.match(s2)
s.search(s2)

rawDescription: Python simple regex

description: Python simple regex


code:
driver.get('https://www.domcop.com/domains/great-expired-domains/')
aElements = driver.find_elements_by_css_selector('.next > a')
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
aElements[1].click()

rawDescription: Can't click a "next" button using xpath, .select nor Selenium using Python


code:
n = 1000 # The number of terms to compute
halfpi = 1.0

for i in range(1, n):
  numer = i * 2
  denom = i * 2 - 1
  halfpi = halfpi * (numer * numer) / (denom * (denom + 2))
print(2 * halfpi)

rawDescription: Python code for Wallis equation

description: Python code for Wallis equation


code:
import heapq

def huffman_depths(frequencies):
    depths = [0] * len(frequencies)

    heap = [(f, [i]) for i, f in enumerate(frequencies)]
    heapq.heapify(heap)

    while len(heap) > 1:
        f1, indexes1 = heapq.heappop(heap)         # pop two least frequent nodes
        f2, indexes2 = heapq.heappop(heap)

        frequency = f1 + f2                        # combine them
        indexes = indexes1 + indexes2

        for i in indexes:
            depths[i] += 1                         # increment depth count of each index

        heapq.heappush(heap, (frequency, indexes)) # push the combined result back on

    return depths

rawDescription: Python depth of elements in heap using heapq


rawDescription: How can I get the path of my python script?

description: Get the path of my python script


code:
example_array = numpy.array([[0.,0.,0.],[1.,2.,3.],[0.,0.,0.]])
row_mask = (example_array!=0).all(axis=1)
masked_array = example_array[row_mask]

rawDescription: Use of Numpy to mask cells filled with a given value


code:
x = 4
def func():
    x = 6
print(x)
func()
print(x)
def globalfunc():
    global x
    x = 6
print(x)
globalfunc()
print(x)

rawDescription: Python tkinter root.after_cancel() issue


code:
def test_testing(self):
  url = self.base + str(gameid)  #the base ends with '/v2/game/'
  headers = {'content-type': 'application/json'}
  r = requests.post(url,headers=headers)

rawDescription: Python Requests to access flask route with url variable


code:
newlist = [x + 1 if n % step == 0 else x
           for (n, x) in enumerate(oldlist)]

rawDescription: how to grab internal index of current loop in python when iter a list?

description: Grab internal index of current loop in python when iter a list


code:
from pylons import config

def my_cache(*args, **kwargs):
    if config["debug"]:
        decorate = lambda f: f
    else:
        decorate = beaker_cache(*args, **kwargs)

    return decorate

rawDescription: Disable cache in Pylons app under development mode


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

data = [
    [11, 11, 12, 13],
    [9, 0, 0, 12],
    [8, 0, 0, 11],
    [8, 9, 10, 11]
]

#Here's what you have:
data_array = np.array(data)

#Mask every position where there is a 0:
masked_data = np.ma.masked_equal(data_array, 0)

#Plot the matrix:
fig = plt.figure()
ax = fig.gca()
ax.matshow(masked_data, cmap=plt.cm.autumn_r) #_r => reverse the standard color map
plt.show()
#plt.savefig('heatmap.png')

rawDescription: How to plot specific parts of a matrix in matplotlib?

description: Plot specific parts of a matrix in matplotlib


code:
while True:

    VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")

    statement = input("Please enter a word: ")
    statementL = statement.lower()

    if statementL == "quit":
        print ("Exiting program")
        break

    def find_vowel(word):
       for i in range(len(word)):
         if word[i] in VOWELS:
            return i
       return -1

    words =  statement.split()
    count = 0

    for word in words:
       vowel = find_vowel(word)
       # No vowels found
       if(vowel == -1):
          print (word)
       # A vowel is the first letter
       elif(vowel == 0):
          print (word + "way")
       else:
          # A consonant is first
          print (word[vowel:] + word[:vowel] + "ay")

rawDescription: Fixing a While loop in a pig latin translator


code:
# a/b.y
from __future__ import absolute_import
from b.c import X

rawDescription: python submodule shadowing other package

description: Python submodule shadowing other package


code:
def do_configure(self, line):
    config = ConfigMode(...)
    config.cmdloop()

rawDescription: Multiple modes for line-oriented command interpreters with Python Cmd class


code:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

rawDescription: Selenium - Python - drop-down menu option value


code:
teststring = 'AAA XXX 132\nAAA YYY 465\nBBB ZZZ 798'

outputDict = {}

for line in teststring.splitlines():
    val1 = line[0:3]
    val2 = line[4:7]
    val3 = line[8:11]

    if val1 not in outputDict:
        outputDict[val1] = [val2,val3]

rawDescription: Check if there is a dictionary with specific value in a list


code:
def __hash__(self):
    return hash((self.attr1, self.attr2, self.attr3))

rawDescription: Which is a more efficient __hash__ implementation in Python objects? Hashing self.__str__, a tuple of attributes, or a real hash routine?


code:
def f():
  global x
  x += 1

x = 1
f()

rawDescription: about python scopes

description: About python scopes


rawDescription: identifying the format of files

description: Identifying the format of files


code:
import matplotlib.pyplot as plt

f, axes = plt.subplots(4, 1, figsize=(10, 4))
f.subplots_adjust(hspace=0)

rawDescription: Python/Matplotlib: controlling the aspect ratio in gridspec


rawDescription: Find random state of sklearn decision tree classifier


code:
from flask import Flask, render_template
from flask import url_for

app = Flask(__name__, static_url_path='/static')

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

@app.route('/send')
def send():
    return "file" % url_for('static', filename='demo_data.json')

if __name__ == '__main__':
    app.run()

rawDescription: Serving static json data to flask

description: Serving static json data to flask


code:
import numpy as np
# df.shape returns the dimensions in a tuple, the first dimension is the number of rows
np.array_slice(df, df.shape[0]/100)

rawDescription: Is there a Pandas equivalent to each_slice to operate on dataframes


code:
answer = "b"
question = "1) Who made the game Grand Theft Auto 5??\nPlease choose from  the following and write a letter: \n◘ A)Viral\n◘ B)Rockstar Games\n◘  C)Madfinger\n◘ D)Gameloft\n"
print(question)
guess=input("Please enter your answer: ").lower()
if guess ==answer:
    print("Correct")
    score = score + 1
    print("Score:")
    print(score)

else:
    print("Wrong")

rawDescription: Quiz isn't working as intended

description: Quiz isn't working as intended


code:
import random
from itertools import chain
x = [e for e in ([n for n in xrange(random.randrange(1, 5))]
     for x in xrange(10))]
list(chain.from_iterable(x))

rawDescription: How to get flat list in list comprehension from lists of arbitrary number of elements?

description: Get flat list in list comprehension from lists of arbitrary number of elements


code:
class my_class:
   _data_fd = None

   def __init__(self,create,filename):
       if(create):
           self._data_fd = open(filename,'w')

   def __del__(self):
       if(self._data_fd != None):
           self._data_fd.close()

   def measureSample(self):
       ##do something here
       outFile = self._data_fd
       outFile.write('{0} || Concentration: {1}'.format(timeStr, Conc3SD))

if __name__ == '__main__':
    timeStr = time.strftime('%m-%d-%Y_%H_%M_%S_%Z') #use unerscore instead of spaces
    filename = "{0}.{1}".format("Data.txt",timeStr)
    imy_class = my_class(1,filename)
    imy_class.measureSample()
    imy_class.measureSample() ##call multiple times the fd remains open for the lifetime of the object
    del imy_class   ### the file closes now and you will have multiple lines of data

rawDescription: Need to generate a new text file and save it every time I run a script in python


rawDescription: How to convert values in specific column into integer type under numpy matrix

description: Convert values in specific column into integer type under numpy matrix


code:
writer = csv.writer(open('sortedcounts.csv', 'wb'))
header = ['Top Calling Customers'] + list(list(sorted_counts.values())[0].keys())
writer.writerow(header)
for key, value in sorted_counts.items():
    writer.writerow([key] + list(value.values()))

rawDescription: Reformatting Dictionary output in python


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig = plt.figure()

#Build the basemap
antmap = Basemap(projection='spstere', boundinglat=30, lon_0=-60, resolution='f')
antmap.drawcoastlines(color='black', linewidth=0.15)
antmap.bluemarble()

eq_data = open('eq_data')
lats, lons = [], []
mag = []
x,y = antmap(0,0)
point = antmap.plot(x,y,'ro', markersize=5)[0]

# Read the data and build the lists of coordinates here
for i, line in enumerate(eq_data.readlines()):
    lats.append(float(line.split(',')[0]))
    lons.append(float(line.split(',')[1]))
    mag.append(float(line.split(',')[2]))
eq_data.close()

def init():
    point.set_data([],[])
    return point,

# Begin Animation
def animate(i):
    x,y = antmap(lons[i], lats[i])
    point.set_data(x, y)
    return point,

ani = animation.FuncAnimation(fig, animate, init_func=init, interval=500, blit=False)
plt.show()

rawDescription: Matplotlib Basemap Plotting Lat/Lons

description: Matplotlib Basemap Plotting Lat/Lons


code: max(Centroids, key=lambda x: Functions.Correlation_fast(tmp, Centroids[x]))

rawDescription: Pythonic way of getting max of dictionary after applying custom function


code:
x = np.linspace(0,1000)
y = x ** -2

figure()
ax = gca()
ax.loglog(x,y)
ax.grid(True)
ax.grid(True, which='minor')

ax.annotate('a1', (x[15], y[15]),
            backgroundcolor='w',
            color='b',
            va='center',
            ha='center',
            bbox=dict(boxstyle="round", color='b'),)

rawDescription: how to make plot where curves may overlap?

description: Make plot where curves may overlap