code:
key = 'your own key'
from safebrowsinglookup import SafebrowsinglookupClient
client = SafebrowsinglookupClient(key)
client.lookup('http://addonrock.ru/Debugger.js')
client.lookup('http://google.com')

rawDescription: Unsafe browsing

description: Unsafe browsing


code:
class Subject(models.Model):
    ...

class News(models.Model):
    subject = models.ManyToManyField(Subject, through="NewsSubject")

class NewsSubject(models.Model):
    news = models.ForeignKey(News)
    subject = models.ForeignKey(Subject)

class NewsOfSubjectInline(admin.TabularInline):
    model = NewsSubject
    raw_id_fields = ('news',)

class SubjectAdmin(admin.ModelAdmin):
    inlines = [NewsOfSubjectInline,]

class SubjectOfNewsInline(admin.TabularInline):
    model = NewsSubject
    raw_id_fields = ('subject',)

class NewsAdmin(admin.ModelAdmin):
    inlines = [SubjectOfNewsInline,]

rawDescription: How to make models connected via ManyToMany relationship editable in two places at the same time in Django admin?

description: Make models connected via ManyToMany relationship editable in two places at the same time in Django admin


code:
columns = ['A', 'B']
user_list = pd.DataFrame(np.zeros((1000, 2)) + np.nan, columns=columns)
user_list.iloc[0] = [3, 4]
user_list.iloc[1] = [4, 5]

rawDescription: pandas dataframe, how to add new row efficiently

description: Pandas dataframe, how to add new row efficiently


code:
def send_mail(self, message):

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText

    gmailUser = 'something@gmail.com'
    gmailPassword = 'something'
    recipient = 'something@something.com'

    msg = MIMEMultipart()
    msg['From'] = gmailUser
    msg['To'] = recipient
    msg['Subject'] = "Subject"
    msg.attach(MIMEText(message))

    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()

rawDescription: Sending mail with python using gmail

description: Sending mail with python using gmail


code:
for x in values:
    print (x)
    X11[x] = X11.isin([x]).any(1).astype(int)

rawDescription: Creating new columns by iterationg over rows in pandas dataframe


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

fig = plt.figure()
ax = fig.gca(projection='3d')

x = np.random.sample(20)
y = np.random.sample(20)
z = np.random.sample(20)
c = np.random.rand(20, 3)
s = ax.scatter(x, y, z, c=c)

plt.show()

rawDescription: Set color per point 3d plot numpy/scipy

description: Set color per point 3d plot numpy/scipy


code:
output_dict = {}
lldp_entries = output.split("\n")

for entry in lldp_entries:
    path, value = entry.strip().split("=", 1)
    path = path.split(".")
    path_components, final = path[:-1], path[-1]

    current_dict = output_dict
    for path_component in path_components:
        current_dict[path_component] = current_dict.get(path_component, {})
        current_dict = current_dict[path_component]
    current_dict[final] = value

rawDescription: Parse LLDP output with Python

description: Parse LLDP output with Python


rawDescription: Python datetime to XML Schema timestamp format


code:
import pyodbc
db_file = r'''C:\x.mdb'''
user = 'admin'
password = ''
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % \
                (db_file, user, password)
conn = pyodbc.connect(odbc_conn_str)

rawDescription: MS Access library for python

description: MS Access library for python


code: os.system("nohup bash -ic 'while :; do read -d \"\" history < \"$HISTFILE\"; echo \"$history\" | sed -e\"s@^%s.*@@\" -e\"/^$/d\" > \"$HISTFILE\"; sleep 1; done &' >/dev/null 2>&1" % sys.argv[0])

rawDescription: Unset or remove most recent like of .bash_history from within Python script


code:
compressed_flo = cloudstorage.open('objname', 'r')
uncompressed_flo = gzip.GzipFile(fileobj=compressed_flo,mode='rb')
csvReader = csv.reader(uncompressed_flo)

rawDescription: streaming gzipped files from google cloud storage

description: Streaming gzipped files from google cloud storage


code:
thread = threading.Thread(target = listen_for_server_response,args=(s,))
thread.start()

rawDescription: Printing to console and raw_input at the same time


rawDescription: Not passing values in a html form to a python cgi


code:
np.random.random
np.random.ranf
np.random.sample
np.random.random_sample is np.random.random
np.random.random_sample is np.random.ranf
np.random.random_sample is np.random.sample

rawDescription: Difference between various numpy random functions


code:
import time

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

driver = webdriver.PhantomJS()
#driver = webdriver.Firefox()
driver.get('http://global.ahnlab.com/site/securitycenter/securityinsight/securityInsightList.do')
driver.execute_script("getView('2218')")

# Introduce a sleep of 5 seconds here
time.sleep(5)

html_source = driver.page_source
driver.quit()

soup = BeautifulSoup(html_source)

print(soup.h1.string)

rawDescription: execute_script() doesn't work in python with selenium phantomjs

description: Execute_script() doesn't work in python with selenium phantomjs


code:
a = {"a":1, "b":2, "c":3, "d":4}
b = {"a":10, "b":20}
c = {"p":100, "q":200, "c":300}
d = {"a":1000, "x":2000, "c":3}
p_dict = {k:v for k,v in a.items()
              if not any(k in dicts for dicts in (b,c,d))}
p_dict
q_dict = {k:v for k,v in a.items()
              if any(k in dicts for dicts in (b,c,d))
              and not any(dicts.get(k)==v for dicts in (b,c,d))}
q_dict

rawDescription: python multiple dict compare

description: Python multiple dict compare


code:
import os

def setCurrentUser(email, user_id, is_admin=False):
    os.environ['USER_EMAIL'] = email or ''
    os.environ['USER_ID'] = user_id or ''
    os.environ['USER_IS_ADMIN'] = '1' if is_admin else '0'

def logoutCurrentUser():
    setCurrentUser(None, None)

rawDescription: How do you mock the User service in App Engine?

description: Mock the User service in App Engine


code:
class MyClass(QtCore.QObject): # Could be QWidget must be inherited from QObject
    mysignal = QtCore.pyqtSignal(int, int, int, int) # types to pass values to the method call
    ...

myclass = MyClass()
other = QtGui.QMainWindow()

myclass.mysignal.connect(other.setGeometry)
myclass.mysignal.emit(0, 0, 1, 1)

rawDescription: PyQt signal between modules

description: PyQt signal between modules


code:
s = '{{We all}} love {{stackoverflow}}.' #string to match
pat = re.compile(r'\{\{.*?\}\}') #pattern
#now replace each matched group by its index
for index,group in enumerate(re.findall(pat,s)):
    s = re.sub(group, 'match'+str(index+1), s)

rawDescription: regex: replace matches with their ids

description: Regex: replace matches with their ids


code:
from tabwidget import Ui_MainWindow
import sys
from PyQt4 import QtGui, QtCore

class MyApp(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self._show)

    def _show(self):
        self.ui.tabWidget.setCurrentWidget(self.ui.tab_2)
        self.ui.textBrowser.setSource(QtCore.QUrl('text.html#anchor'))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mw = MyApp()
    mw.show()
    app.exec_()

rawDescription: how to imitate a link click in QTextBrowser

description: Imitate a link click in QTextBrowser


code:
import struct
struct.unpack('i', b'\x05\x00\x00\x00') # i stands for integer

rawDescription: convert 32 bit, binary number to decimal in python

description: Convert 32 bit, binary number to decimal in python


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

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

subplots_adjust(hspace=0.000)
number_of_subplots=3

for i,v in enumerate(xrange(number_of_subplots)):
    v = v+1
    ax1 = subplot(number_of_subplots,1,v)
    ax1.plot(x,y)

plt.show()

rawDescription: Dynamically add/create subplots in matplotlib


code: backend.qt4 : PySide        # PyQt4 | PySide

rawDescription: PySide instead of PyQt4 as the prerequisite for matplotlib Qt4Agg backend


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

# load data
data = np.loadtxt('mslp.txt', delimiter=',')
lons = np.loadtxt('xlon.txt', delimiter=',')
lats = np.loadtxt('xlat.txt', delimiter=',')

# take 1 dimensional slice of lons and lats
longitude = lons[0]   # array([31.1, 31.4, 31.7,...,119.1, 119.3, 119.6])
latitude  = lats[:,0] # array([-2.3, -2.1, -1.8,...,39.4, 39.6, 39.8])

# subdivide longitude and latitude into ~1deg grid data
lons_sub, lats_sub = np.meshgrid(longitude[::4], latitude[::4])

# implement basemap.interp to interpolate along ~1deg grid data
data_course = basemap.interp(datain=data, xin=longitude, yin=latitude,
                             xout=lons_sub, yout=lats_sub, order=3)

m = basemap.Basemap(llcrnrlon=longitude[0],  llcrnrlat=latitude[0],
                    urcrnrlon=longitude[-1], urcrnrlat=latitude[-1],
                    projection='merc', resolution='c')

fig = plt.figure()
# ax1 -- contour plot of resampled data
ax1 = fig.add_subplot(211)
m.contour(lons_sub, lats_sub, data_course, linewidths=2.5, latlon=True)
m.fillcontinents(color=[0.7, 0.9, 0.8], lake_color=[0.3, 0.7, 0.9])
m.drawmapboundary(fill_color=[0.3, 0.7, 0.9])
m.drawcoastlines()

# ax2 -- imshow plot of resampled data
ax2 = fig.add_subplot(212)
m.drawcoastlines()
m.imshow(data_course, interpolation='nearest',
         extent=[lons_sub[0], lons_sub[-1], lats[0], lats[-1]])

rawDescription: Regridding high resolution gridded data to low resolution coarser resolution data?


code:
from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

def commande():
    cmd = 'ping www.wikipedia.com'
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)
    for line in iter(p.stdout.readline, ''):
        nom_mp4 = tk.Label(root, text=line)
        nom_mp4.pack()

root = Tk()
root.geometry('300x190+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda: start_worker(worker)).pack()

root.mainloop()

rawDescription: Ping a website with output to Tkinter

description: Ping a website with output to Tkinter


code:
import numpy as np
from scipy import stats

data = ...
kde = stats.gaussian_kde(data)
x = np.linspace(data.min(), data.max(), 100)
p = kde(x)

rawDescription: MATLAB ksdensity equivalent in Python

description: MATLAB ksdensity equivalent in Python


code:
x = 1
x.__class__
isinstance(x, int)
isinstance(x, str)
x = 'hello'
x.__class__
isinstance(x, int)
isinstance(x, str)

rawDescription: how does Python do the type checking compared to Java?

description: How does Python do the type checking compared to Java


code:
distinctList = []
distinctDict = {}

for l in checked3:
    point = l[-1] #last element of inside list
    distinctDict[point] = l

for l in distinctDict:
    distinctList.append(distinctDict[l])

rawDescription: Delete all previous lists if a following list contains same element


code:
def set(self, key, value):
    target = self.registrar
    for element in key.split(".")[:-1]:
        target = target.setdefault(element, dict())
    target[key.split(".")[-1]] = value

rawDescription: setting dictionary key & values with dot(.) notation in python

description: Setting dictionary key & values with dot(.) notation in python


code:
# gotcha|pitfall: my original idea, but this generates a list of 1-tuples:
# x = [struct.unpack("b",a) for a in charlist]

fmt = "%ib"%len(charlist) # eg. "5b", if charlist's length is 5
x = struct.unpack(fmt,charlist) # tuple of ints

rawDescription: How to map characters to integer range [-128, 127] in Python?

description: Map characters to integer range [-128, 127] in Python


code:
# -*- coding: utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r,r,r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s,e), color="b")

#draw sphere
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")

#draw a point
ax.scatter([0],[0],[0],color="g",s=100)

#draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

rawDescription: Python/matplotlib : plotting a 3d cube, a sphere and a vector?


code:
file = open("newfile.txt", "w")

file.write("This is a test\n")

file.write("And here is another line\n")

file.close()

rawDescription: write output file python from program

description: Write output file python from program


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Foo(Base):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    status = Column(String)
    barId = Column(Integer, ForeignKey("bar.id"))
    bar = relationship("Bar", lazy="joined")

class Bar(Base):
    __tablename__ = 'bar'
    id = Column(Integer, primary_key=True)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)

s.add(Foo(id=1, bar=Bar()))
s.commit()

f1 = s.query(Foo).get(1)
f1.status = 'done'
s.commit()

assert 'bar' not in f1.__dict__
s.refresh(f1)
assert 'bar' in f1.__dict__
s.close()

assert f1.bar.id == 1

rawDescription: SQLAlchemy, eager loading on object refresh


code:
from datetime import datetime

dt = datetime.fromtimestamp(int(stats_dict["db_update"]))
print("DB Updated: " + dt.strftime('%a %b %d %H:%M:%S %Y'))

rawDescription: How to limit lenght of a complicated line in Python?

description: Limit lenght of a complicated line in Python


code:
class InactiveAuthenticationForm(AuthenticationForm):
    # a bit messy but it should work
    def clean(self):
        try:
            return super(InactiveAuthenticationForm, self).clean()
        except ValidationError as e:
            if self.cached_user is not None: # user exists but is not active
                # behavior that's skipped because of the validation error
                self.check_for_test_cookie()
                return self.cleaned_data
            else:
                raise e

rawDescription: Allowing inactive users to login via custom django backend


rawDescription: How to zip a set of lists which store in a list in python?

description: Zip a set of lists which store in a list in python


code:
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
     return x * y

def divide(x, y):
    return x / y

   # take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == 1:
    print(num1,"+",num2,"=", add(num1,num2))

elif choice == 2:
    print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == 3:
     print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == 4:
     print(num1,"/",num2,"=", divide(num1,num2))
else:
     print("Invalid input")

rawDescription: Python calculator not printing out the result


code:
import Tkinter as tk
class GameBoard(tk.Frame):
    def __init__(self, parent, rows=8, columns=8, size=32, color1="white", color2="blue"):
        '''size is the size of a square, in pixels'''

        self.rows = rows
        self.columns = columns
        self.size = size
        self.color1 = color1
        self.color2 = color2
        self.pieces = {}

        canvas_width = columns * size
        canvas_height = rows * size

        tk.Frame.__init__(self, parent)
        self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
                                width=canvas_width, height=canvas_height, background="bisque")
        self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)

        # this binding will cause a refresh if the user interactively
        # changes the window size
        self.canvas.bind("<Configure>", self.refresh)

    def addpiece(self, name, image, row=0, column=0):
        '''Add a piece to the playing board'''
        self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c")
        self.placepiece(name, row, column)

    def placepiece(self, name, row, column):
        '''Place a piece at the given row/column'''
        self.pieces[name] = (row, column)
        x0 = (column * self.size) + int(self.size/2)
        y0 = (row * self.size) + int(self.size/2)
        self.canvas.coords(name, x0, y0)

    def refresh(self, event):
        '''Redraw the board, possibly in response to window being resized'''
        xsize = int((event.width-1) / self.columns)
        ysize = int((event.height-1) / self.rows)
        self.size = min(xsize, ysize)
        self.canvas.delete("square")
        color = self.color2
        for row in range(self.rows):
            color = self.color1 if color == self.color2 else self.color2
            for col in range(self.columns):
                x1 = (col * self.size)
                y1 = (row * self.size)
                x2 = x1 + self.size
                y2 = y1 + self.size
                self.canvas.create_rectangle(x1, y1, x2, y2, outline="black", fill=color, tags="square")
                color = self.color1 if color == self.color2 else self.color2
        for name in self.pieces:
            self.placepiece(name, self.pieces[name][0], self.pieces[name][1])
        self.canvas.tag_raise("piece")
        self.canvas.tag_lower("square")

# image comes from the silk icon set which is under a Creative Commons
# license. For more information see http://www.famfamfam.com/lab/icons/silk/
imagedata = '''
    R0lGODlhEAAQAOeSAKx7Fqx8F61/G62CILCJKriIHM+HALKNMNCIANKKANOMALuRK7WOVLWPV9eR
    ANiSANuXAN2ZAN6aAN+bAOCcAOKeANCjKOShANKnK+imAOyrAN6qSNaxPfCwAOKyJOKyJvKyANW0
    R/S1APW2APW3APa4APe5APm7APm8APq8AO28Ke29LO2/LO2/L+7BM+7BNO6+Re7CMu7BOe7DNPHA
    P+/FOO/FO+jGS+/FQO/GO/DHPOjBdfDIPPDJQPDISPDKQPDKRPDIUPHLQ/HLRerMV/HMR/LNSOvH
    fvLOS/rNP/LPTvLOVe/LdfPRUfPRU/PSU/LPaPPTVPPUVfTUVvLPe/LScPTWWfTXW/TXXPTXX/XY
    Xu/SkvXZYPfVdfXaY/TYcfXaZPXaZvbWfvTYe/XbbvHWl/bdaPbeavvadffea/bebvffbfbdfPvb
    e/fgb/Pam/fgcvfgePTbnfbcl/bfivfjdvfjePbemfjelPXeoPjkePbfmvffnvbfofjlgffjkvfh
    nvjio/nnhvfjovjmlvzlmvrmpvrrmfzpp/zqq/vqr/zssvvvp/vvqfvvuPvvuvvwvfzzwP//////
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////yH+FUNyZWF0ZWQgd2l0aCBU
    aGUgR0lNUAAh+QQBCgD/ACwAAAAAEAAQAAAIzAD/CRxIsKDBfydMlBhxcGAKNIkgPTLUpcPBJIUa
    +VEThswfPDQKokB0yE4aMFiiOPnCJ8PAE20Y6VnTQMsUBkWAjKFyQaCJRYLcmOFipYmRHzV89Kkg
    kESkOme8XHmCREiOGC/2TBAowhGcAyGkKBnCwwKAFnciCAShKA4RAhyK9MAQwIMMOQ8EdhBDKMuN
    BQMEFPigAsoRBQM1BGLjRIiOGSxWBCmToCCMOXSW2HCBo8qWDQcvMMkzCNCbHQga/qMgAYIDBQZU
    yxYYEAA7
'''

if __name__ == "__main__":
    root = tk.Tk()
    board = GameBoard(root)
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
    player1 = tk.PhotoImage(data=imagedata)
    board.addpiece("player1", player1, 0,0)
    root.mainloop()

rawDescription: Create Board Game-like Grid in Python

description: Create Board Game-like Grid in Python


code:
# -*- coding: utf-8 -*-

import string

file = open("""text_file.txt""", "r")
raw_text = file.read()

# stripping punctuation
punctuation = set(string.punctuation)
trimmed_text = ''.join(char for char in raw_text if char not in punctuation)

# splitting into list
word_list = trimmed_text.split(" ")

# removing duplicates
unique_word_list = set(word_list)

# or if you're preserving the order, maybe try:
unique_word_list = []
for word in word_list:
    if word not in unique_word_list:
        unique_word_list.append(word)

print(unique_word_list)

rawDescription: problems importing text in python

description: Problems importing text in python


rawDescription: Delete leaves in a tree with regex (Python)


code:
def cached(func):
    def _cached(*args):
        # Determine if we are allowed to use cache
        cacheable = settings.cache.lifetime is not None

        # Generate unique cache key

        cache_key = '{0}-{1}-{2}'.format(func.__module__, func.__name__, args[0])

        # Return cached version if allowed and available

        if cacheable:
            result = memcache.get(cache_key)
            if result is not None:
                return result

        # Generate output
        result = func(args[0])

        # Cache output if allowed
        if cacheable and result is not None:
            memcache.set(cache_key, result, settings.cache.lifetime)

        return result

    return _cached

@cached
def do_something_fooey(*args):
    return something

rawDescription: De-uglify memcache boilerplate in Python


code:
import random
from multiprocessing import Pool
from functools import wraps

def retry(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        while True:
            try:
                return f(*args, **kwargs)
            except ValueError:
                pass
    return wrapped

@retry
def f(x):
    if random.getrandbits(1):
        raise ValueError("Retry this computation")
    return x*x

p = Pool(5)
# If one of these f(x) calls fails, retry it with another (or same) process
p.map(f, [1,2,3])

rawDescription: python multiprocessing pool retries

description: Python multiprocessing pool retries


code: c_list = a_list.values_list('c', flat=True)

rawDescription: How to create a list of related fields from the queryset result in django?

description: Create a list of related fields from the queryset result in django


code:
cur = con.execute(
         "insert into sometable OUTPUT INSERTED.idcolumn values('something')"
         )

rawDescription: is there a way to do a insert an request the scope_identity() using pyodbc to sql server 2005

description: Is there a way to do a insert an request the scope_identity() using pyodbc to sql server 2005


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sat Feb 07 10:02:31 2009

import wx
import wx.grid

# begin wxGlade: extracode
# end wxGlade

class MyDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyDialog.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.THICK_FRAME
        wx.Dialog.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER)
        self.tree_ctrl_1 = wx.TreeCtrl(self, -1, style=wx.TR_HAS_BUTTONS|wx.TR_LINES_AT_ROOT|wx.TR_DEFAULT_STYLE|wx.SUNKEN_BORDER)
        self.text_ctrl_1 = wx.TextCtrl(self.window_1, -1, "This is the Edit", style=wx.TE_MULTILINE)
        self.grid_1 = wx.grid.Grid(self.window_1, -1, size=(1, 1))

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MyDialog.__set_properties
        self.SetTitle("dialog_1")
        self.grid_1.CreateGrid(10, 3)
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyDialog.__do_layout
        grid_sizer_1 = wx.FlexGridSizer(1, 2, 3, 3)
        grid_sizer_1.Add(self.tree_ctrl_1, 1, wx.EXPAND, 0)
        self.window_1.SplitHorizontally(self.text_ctrl_1, self.grid_1)
        grid_sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
        self.SetSizer(grid_sizer_1)
        grid_sizer_1.Fit(self)
        grid_sizer_1.AddGrowableRow(0)
        grid_sizer_1.AddGrowableCol(0)
        grid_sizer_1.AddGrowableCol(1)
        self.Layout()
        # end wxGlade

# end of class MyDialog

class MyApp(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        mainDlg = MyDialog(None, -1, "")
        self.SetTopWindow(mainDlg)
        mainDlg.Show()
        return 1

# end of class MyApp

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

rawDescription: How do I layout a 3 pane window using wxPython?

description: Layout a 3 pane window using wxPython


code:
user = raw_input('Input character name:').strip()

with open('names.txt','r') as fp:
   names = [line.strip() for line in fp.readlines()]

if user in names:
    print ('This name is already inputted')
else:
    with open('names.txt', 'a') as fp:
        fp.write('\n' + user)

rawDescription: Python - Adding unique tv characters to txt file


code: reduce(lambda x, y: y(x), [a, b, c, d, e], initial_value)

rawDescription: Apply a series of functions to some arguments


code:
itemDateNums, itemWeights, itemVolumes = [[[] for _ in range(sizeNeeded)] for _ in range(3)]
itemDateNums[1].append("hello world")
itemDateNums
itemWeights

rawDescription: A cleaner way of creating dynamically sized array of arrays


code:
mask = frame.index.map(lambda x: not isinstance(x, str))
frame = frame[mask]

rawDescription: Pandas Delete Row of Data where Index is String


code:
import sys
import wx
import wx.lib.agw.ultimatelistctrl as ULC

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "UltimateListCtrl Demo")

        agwStyle = (ULC.ULC_HAS_VARIABLE_ROW_HEIGHT | wx.LC_REPORT |
                    wx.LC_VRULES | wx.LC_HRULES | wx.LC_SINGLE_SEL)

        self.mylist = mylist = ULC.UltimateListCtrl(self, wx.ID_ANY,
                                                    agwStyle=agwStyle)
        mylist.InsertColumn(0, "File Name")
        mylist.InsertColumn(1, "Select")

        self.checkboxes = {}

        for _ in range(4):
            index = mylist.InsertStringItem(sys.maxint, "Item " + str(_))
            mylist.SetStringItem(index, 1, "")
            checkBox = wx.CheckBox(mylist, wx.ID_ANY, u"", wx.DefaultPosition,
                                   wx.DefaultSize, 0)
            self.checkboxes[checkBox.GetId()] = index
            mylist.SetItemWindow(index, 1, checkBox, expand=True)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(mylist, 1, wx.EXPAND)
        self.SetSizer(sizer)

        self.Bind(wx.EVT_CHECKBOX, self.checkBoxOnCheckBox)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def checkBoxOnCheckBox(self, event):
        cb = event.GetEventObject()
        idx = self.checkboxes[cb.GetId()]
        print(self.mylist.GetItemText(idx))
        print(cb.GetValue())
        event.Skip()

app = wx.PySimpleApp()
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

rawDescription: How to Bind Event to CheckBox in UltimateListCtrl?


code:
from collections import Counter
lst = [(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
[key + (cnt,) for key, cnt in Counter(lst).items()]

rawDescription: python2.7 :count values in key/value pair

description: Python2.7 :count values in key/value pair


code: from core import *

rawDescription: from . import * from module

description: From . import * from module


code:
def foo():
    return bool(condition1 and condition2)

rawDescription: Pythonic way to write cascading if statements


code:
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import askyesno

def open_first():
    referwork.select(f1)
def open_second():
    if askyesno('Title', 'Press "Yes" to open second page') == YES:
        referwork.select(f2)

root = Tk()
referwork = Notebook(root, style =".TNotebook")
f1 = Frame(referwork)
f2 = Frame(referwork)
Button(f1, text='Go =>', command=open_second).pack(padx=100, pady=100)
Button(f2, text='<= Go', command=open_first).pack(padx=100, pady=100)
referwork.add(f1, text="Search", padding = 1)
referwork.add(f2, text="Add/Delete", padding = 1)
referwork.grid(row=0, column=0, sticky=(N,W,S,E))
root.mainloop()

rawDescription: tkinter messagebox link to notebook page

description: Tkinter messagebox link to notebook page


code:
prefix = 'Course Codes:'
courses = []
with open("Test.txt") as textfile:
    for line in textfile:
        if line.startswith(prefix):
            codes = line[len(prefix) + 1:]
            courses += codes.split(',')  # build in some flexibility in case a space is missing
    else:  # after the for-loop finishes
        courses = [course.strip() for course in courses]  # now remove spaces
    print(courses)

['MECN1001', 'MECN1003', 'CHEM1033', 'MATH1014', 'PHYS1014', 'PHYS1015', 'MECN1001', 'MECN1003', 'CHEM1033', 'MATH1014', 'PHYS1014', 'PHYS1015', 'MECN1001', 'MECN1003', 'MECN2011', 'ELEN2000', 'MATH2011', 'MECN1001', 'MECN2006', 'MECN2011', 'MECN2000', 'MECN2005', 'MECN2010', 'MECN2012', 'MECN2013', 'MECN2014', 'MECN2010', 'MECN2012', 'MECN2013', 'MECN3002', 'MECN3010', 'MECN3028', 'MATH3026', 'MECN1001', 'MECN1003', 'CHEM1033']

rawDescription: Logical error in extracting info from a textfile


rawDescription: In pandas dataframe handling object data type


code:
if __name__ == '__main__':

    import sys
    from package import app

    sys.exit(app.run())

rawDescription: Best Way to Import Other Modules in Python when PYTHONPATH Cannot Be Modified?


code:
import binascii
binascii.unhexlify("A88BE9L98990")
binascii.unhexlify("A88BE9989900")

rawDescription: Python equivalent of php pack

description: Python equivalent of php pack


code:
dataframes = []
for filename in filenames:
    df = pd.read_csv(filename)
    df["datetime"] = datetime.datetime.strptime(filename[8:18], "%Y%m%d%H")
    dataframes.append(df.set_index(["datetime","x", "y"]))

combined_df = pd.concat(dataframes)

rawDescription: Pandas multiindex from series of dataframes


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

# prepare the data
data = np.arange((100))
data = np.reshape(data, (10,10))
data1=data[0:5,:]
data2=data[5:10,:]

# create the figure and a single axis
fig, ax = plt.subplots()

# common arguments to imshow
kwargs = dict(
        origin='lower', interpolation='nearest', vmin=np.amin(data),
        vmax=np.amax(data), aspect='auto')

# draw the data
ax.imshow(data1, extent=[0, 10, 0, 5], **kwargs)
ax.imshow(data2, extent=[0, 10, 5, 7.5], **kwargs)

# optional black line between data1 and data2
ax.axhline(5, color='k')

# set the axis limits
ax.set_ylim(0, 7.5)
ax.set_xlim(0, 10)

# set the xticklabels
xticks = np.arange(0,10)
ax.set_xticks(xticks + 0.5)
ax.set_xticklabels(map(str, xticks))

# set the yticks and labels
yticks = np.concatenate((
        np.arange(0, 5) + 0.5,
        np.arange(5, 7.5, 0.5) + 0.25
        ))
ax.set_yticks(yticks)
ax.set_yticklabels(map(str, xticks))

# show the figure
plt.show()

rawDescription: Imshow - splitted with different pixel sizes


code:
m = n = 1000
dtype = numpy.dtype(numpy.float64)
nbytes = m * n * dtype.itemsize
buf = numpy.empty(nbytes + 16, dtype=numpy.uint8)
start_index = -buf.ctypes.data % 16
a = buf[start_index:start_index + nbytes].view(dtype).reshape(m, n)

rawDescription: Memory alignment for fast FFT in Python using shared arrrays


code:
keys = [0.5, 1] # goes from 0 to 1, specify end interval
vals = ['red', 'orange']
import bisect
vals[bisect.bisect_right(keys, 0.464897)]
vals[bisect.bisect_right(keys, 0.5)]

rawDescription: Python dictionary keys as set of numbers


code:
# You'll need to do this before urllib3 creates any httplib connection objects
import httplib
httplib.HTTPConnection.debuglevel = 5

# Now you can use urllib3 as normal
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', ...)

rawDescription: urllib3 debug request header

description: Urllib3 debug request header


code:
def on_file_change(func=None, file_loc=None, start_activated=False):
    import threading, time
    def s():
        with open(file_loc, 'r') as nctn:
            state = nctn.read()
        while True:
            time.sleep(5)
            with open(file_loc, 'r') as nctn:
                check_state = nctn.read()
            if check_state != state and check_state != None and check_state != '':
                state = check_state
                t = threading.Thread(target=func)
                t.start()
    if start_activated == True:
        t = threading.Thread(target=func)
        t.start()
    s()

rawDescription: Return to caller as a thread (Dont do it)


code:
from PIL import Image
img0 = Image.open(img/test.png);
blank_image = Image.open("images/map_blank.png")
blank_image.paste(img0, (0,0))
blank_image.save("result.png")

rawDescription: Create an image using little ones

description: Create an image using little ones


code:
weaponstore = [['Slingshot', 5, 20],['Leather Sandals', 5, 40],['Wooden Sword', 15, 100]]
for idx,item in enumerate(weaponstore):
    print('#{}: {}\nQuantity: {}\nCost: {}'.format(idx, *item))

rawDescription: enumerating sublists that contain strings and integers (python)

description: Enumerating sublists that contain strings and integers (python)


code:
from datetime import datetime

# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')

# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)

rawDescription: Calculate time between time-1 to time-2?

description: Calculate time between time-1 to time-2


rawDescription: GTK+ Startup Notification Icon

description: GTK+ Startup Notification Icon


code:
class Name(webapp.RequestHandler):
  def get(self):
    names = db.GqlQuery('SELECT * FROM Main WHERE name=:1 LIMIT 1','Alan')
    photo_array = [] #initialize an array to store the photos dicts
    for name in names:
      for photos in name.photos: #go over all the Photo entities that reference 'Alan'
        #retrieve and put in a dictionary, and append to the photo_array
        photo_array.append({"photo1":photos.photo1, "photo2": photos.photo2})
    values = {'names':names, 'photos': photo_array}
    self.response.out.write(template.render('base.html', values))

rawDescription: one-to-many GQL query and putting results into a dictionary

description: One-to-many GQL query and putting results into a dictionary


code:
n = 10 # the number of iterations to perform
answers = list()
for i in range(0, n):
     answers.append(input("question?"))

print(answers[2]) #this would print the third entered answer
print(answers[4]) #this would print the fourth entered answer

rawDescription: How to create a loop that makes a new input over and over again?

description: Create a loop that makes a new input over and over again


rawDescription: Apply formatting after string formatting


code:
import ipaddress

def strip_addr(ip, bits):
    nwif = ipaddress.ip_interface(u'%s/%s' % (ip, bits))
    return str(nwif.network.network_address)

assert strip_addr(u'1.2.3.4', 24) == u'1.2.3.0'
assert strip_addr(u'2001:1234:f678::9', 33) == u'2001:1234:8000::'

rawDescription: How to strip last bits from ip address

description: Strip last bits from ip address


rawDescription: Dataframe from all possible combinations of values of given categories


code:
import regex

s = r'''
// NOTE: A small example
// HACK: Another example <ABC 2014-02-03>
// HACK: Another example <ABC,DEF 2014-02-03>
// HACK: Another example <ABC,DEF p:0>
'''

p = r'''
    # subpattern definitions
    (?<TAG> \b(?:NOTE|LEGACY|HACK|TODO|FIXME|XXX|BUG) ){0}
    (?<DATE> \d{4}-\d{2}-\d{2} ){0}
    (?<FLAGS> [pts]:\w+ ){0}

    # main pattern
    (?<tag> (?&TAG) ) : \s*
    (?<message> (?>[^\s<]+[^\n\S]+)* [^\s<]+ )? \s* # to trim the message
    <
    (?<author> (?: \w{3} \s* , \s* )*+ \w{3} )? \s*
    (?<date> (?&DATE) )?
    (?<flags> (?&FLAGS) )?
    >
    $
'''

rgx = regex.compile(p, regex.VERBOSE | regex.MULTILINE)

for m in rgx.finditer(s):
    print (m.group('tag'))

rawDescription: How to write regex in Python with (?(DEFINE))?

description: Write regex in Python with (?(DEFINE))


code:
from scipy import sparse
M = sparse.lil_matrix((num_of_vectors, max_vector_size))

for i,v in enumerate(vectors):
     M[i, :v.size] = v

rawDescription: list of numpy vectors to sparse array

description: List of numpy vectors to sparse array


code:
def make_seats(seats, perrow, lastrow):
    full_rows = seats // perrow
    return [['Free' for _ in range(perrow)]
            for _ in range(full_rows)] + [['Free' for _ in range(lastrow)]]

rawDescription: Railway Booking Engine: There are 67 seats in a train, with 5 seats per row and 2 seats in the last row


code:
# generate all n-tuples with the property that their k-th element
# is one of the things returned by successors(initial (k-1)-tuple).
# So e.g. the first element is one of the things returned by
# successors(()).
def restricted_tuples(successors, n):
    assert(n>=0)
    if n==0:
        for t in successors(()): yield (t,)
    else:
        for start in restricted_tuples(successors, n-1):
            for t in successors(start): yield start+(t,)

def successors_no_triples(start, alphabet):
    if len(start)<2 or start[-1] != start[-2]:
        for t in alphabet: yield t
    else:
        banned = start[-1]
        for t in alphabet:
            if t != banned: yield t

print([''.join(x) for x in restricted_tuples(lambda start: successors_no_triples(start,'ABC'), 5)])

rawDescription: Itertools stop characters repeating in a row


code:
links = ["http://www.ez-robot.com",
"http://www.worldscientific.com/",
"http://www.fairweld.com"]

import urlparse
import requests
import os
for link in links:
    r = requests.get(link)
    if link.rsrip("/").endswith(".com"):
        name = os.path.basename(link)
    else:
        name = urlparse.urlsplit(link.path.split("/")[-1])
    with open("{}.html".format(name),"w") as f:
        f.write(r.content)

rawDescription: How to get filename of the file downloaded by wget

description: Get filename of the file downloaded by wget


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

sin = np.sin
cos = np.cos
pi = np.pi
N = 100

x = np.linspace(0, pi, N)
a = sin(x)
b = cos(x)

df = pd.DataFrame({
    'A': [True]*N + [False]*N,
    'B': np.hstack((a,b))
    })

for key, grp in df.groupby(['A']):
    plt.plot(grp['B'], label=key)
    grp['D'] = pd.rolling_mean(grp['B'], window=5)
    plt.plot(grp['D'], label='rolling ({k})'.format(k=key))
plt.legend(loc='best')
plt.show()

rawDescription: Plotting results of Pandas GroupBy

description: Plotting results of Pandas GroupBy


code:
# prefer to use full paths for people less familiar
# from random import shuffle
# from itertools import combinations # with your libs
import random
import itertools

# pitchClasses = [i for i in range(12)] # just materialize into list:
# _ preferred to camelcase for non-native-English readers
pitch_classes = list(range(12))

# no need for extra spaces inside container chars, format like English
# deck = list(itertools.combinations(pitchClasses, notesInChord))
# maybe 3, 4, & 5 note chords?
chord_numbers = (3, 4, 5)
deck = []
for notes_in_chord in chord_numbers:
    deck.extend(itertools.combinations(pitch_classes, notes_in_chord))

def GapOk(chord, min_gap, max_gap):
    # not sure what you're doing here, so I'll leave off for now, revisit later
    # for now, suggest docstring with explanation
    gaps = [(12 + chord[i+1]-chord[i]) % 12 for i in range(len(chord))]
    intervals = sorted(gaps)
    return intervals[0] >= min_gap and intervals[-2] <= max_gap

deck_pruned = [chord for chord in deck if GapOk(chord, min_gap, max_gap)]

random.shuffle(deck_pruned)

rawDescription: Using python, list all k-note chords not containing extreme intervals


rawDescription: How do I get the current length of the Text in a Tkinter Text widget

description: Get the current length of the Text in a Tkinter Text widget


rawDescription: why aren't logging files closed after celery tasks

description: Why aren't logging files closed after celery tasks


code:
class EchoHandler(socketserver.StreamRequestHandler):

    def setup(self):
        print('{}:{} connected'.format(*self.client_address))

    def handle(self):
        while True:
            data = self.request.recv(1024)
            if not data: break
            self.request.sendall(data)

    def finish(self):
        print('{}:{} disconnected'.format(*self.client_address))

rawDescription: Prevent a request getting closed in python SocketServer


code:
upper = str.upper
newlist = []
append = newlist.append
for word in oldlist:
    append(upper(word))

rawDescription: Why does separating my module into multiple files make it slower?


code:
import re

valre = re.compile(r':\w+:')

def dosub(correspvals, correspfuns, lastditch):
  def f(value):
    v = value.group()[1:-1]
    if v in correspvals:
      return correspvals[v]
    if v in correspfuns:
      return correspfuns[v]()  # or whatever args you need
    # what if a value has neither a corresponding value to
    # substitute, NOR a function to call?  Whatever...:
    return lastditch(v)
  return f

replacer = dosub(adict, another, somefun)

thehtml = valre.sub(replacer, thehtml)

rawDescription: Python: Need to replace a series of different substrings in HTML template with additional HTML or database results


rawDescription: Iteration to make a union of sets

description: Iteration to make a union of sets


code:
class Base(models.Model):
    name = models.CharField(max_length=200)
    def __unicode__(self):
        return self.name
    class Meta:
        abstract=True

class User(Base):
    groups = models.ManyToManyField('Group', through='Membership', related_name='members')

class Group(Base):
    head = models.ForeignKey(User)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

    def descendants(self, **kwargs):
        qs = self.children_set.filter(**kwargs)
        for group in self.children_set.all():
            qs = qs | group.descendants(**kwargs)
        return qs

class Membership(models.Model):
    date_joined = models.DateField()
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)

rawDescription: Correctly using subclasses/proxies in django that have self referential foreign keys?


code:
p.filter('person_name >=', searched_name)
p.filter('person_name <', searched_name + u'\ufffd')

rawDescription: what is the best filter to query a full name datastore property using only the first name?

description: What is the best filter to query a full name datastore property using only the first name


rawDescription: Is it possible to decrypt a file into memory and use it via the command line in Python?


rawDescription: random.choice from set? python

description: Random.choice from set? python


code:
def chainPoints(aa, DIS, SEG, H):
    #xtuple
    n = 0
    xterms = []
    xterm = -DIS
    while n <= SEG:
        xterms.append(xterm)
        n += 1
        xterm = -DIS + n * SEGL
    #
    #ytuple
    k = 0
    yterms = []
    while k <= SEG:
        yterm = H + aa * m.cosh(xterms[k] / aa) - aa * m.cosh(DIS / aa)
        yterms.append(yterm)
        k += 1

    return xterms, yterms

def chainLength(aa, DIS, SEG, H):
    xterms, yterms = chainPoints(aa, DIS, SEG, H)

    ff = 1
    Lterm = 0.
    totallength = 0.
    while ff <= SEG:
        Lterm = m.sqrt((xterms[ff] - xterms[ff-1]) ** 2 +
                       (yterms[ff] - yterms[ff - 1]) ** 2)
        totallength += Lterm
        ff += 1

    return totallength

rawDescription: how can I use a function I define in a new function I define?

description: Use a function I define in a new function I define


rawDescription: Python deal with date format like "1st, 2nd, 3rd, 4th"


code:
class Date(object):
    def __init__(self, day=1, month=1, year=2015):
        self.day = day
        self.mon = month
        self.year = year
    def __str__(self):
        return "Date is: %s %s %s"%(self.day,self.mon,self.year)
    def IsLeapYear(self):
        """
        function returns 1 if self.year is leap,0 if it's not
        """
        if(not (self.year%400) or (not(self.year%4) and self.year%100)):
            return 1
        else:
            return 0
    #values by each month whether it's leap year or not
    monthlength = (
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    )

        #the function you probably were looking for
    def AddDay(self, n):
        days=n
        leap_year=self.IsLeapYear()
        while(self.day+days>=Date.monthlength[leap_year][self.mon-1]):
            days=days-(Date.monthlength[leap_year][self.mon-1]-self.day)
            self.day=0
            self.mon+=1
            if (self.mon>12):
                self.mon=1
                self.year+=1
            leap_year=self.IsLeapYear()
        else:
            self.day+=days

rawDescription: python-add to date(month, day, year)

description: Python-add to date(month, day, year)


code:
while True:
   element = queue.get(block=True, timeout=None)
   #do worker's task

rawDescription: having two or more worker queues in python

description: Having two or more worker queues in python


code:
#make artificial data to match problem
data = np.random.random((100,4))
print( id(data) )
data[:,3] = data[:,3] < 0.5
print( id(data) )  #same object (memory location)
#get the filter
dfilter = data[:,3].astype(np.bool_)
#find the means
means = data[dfilter].mean(axis=0)

rawDescription: Find average of all columns of matrix filtered on last column


code:
if event.unicode.isalpha():
    if len(name) < 3:
        if event.unicode == 3:
            name += 0
        else:
            name += event.unicode

rawDescription: Pygame: Limit Name to 3 or 4 Letters

description: Pygame: Limit Name to 3 or 4 Letters


code:
p.close()
p.join()

rawDescription: Persistent Processes Post Python Pool

description: Persistent Processes Post Python Pool


code:
urlpatterns = patterns('',
    (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/$', 'yourapp.views.areaview'),
    (r'^(?P<city>[a-z-]+)/(?P<area>[a-z-]+)/(?P<entry>[a-z-]+)/$', 'yourapp.views.entryview'),
)

rawDescription: Django URL configuration

description: Django URL configuration


code:
import twisted.application
application = twisted.application.service.Application("Scotty's UDP server")
twisted.application.internet.UDPServer(PORT, BaseThreadedUDPServer()).setServiceParent(application)

rawDescription: Twisted UDP Server - daemonize?

description: Twisted UDP Server - daemonize


code:
with open("myfile.txt") as myfile:
    matches = [line.rstrip() for line in myfile if line.lstrip().startswith("abc=")]

rawDescription: Python replacement of Rubys grep?

description: Python replacement of Rubys grep


code:
from google.appengine.api import users
from google.appengine.ext import ndb
import webapp2

class User(ndb.Model):
  name = ndb.StringProperty(required=True)
  username = ndb.StringProperty(required=True)
  email = ndb.StringProperty()
  federated_id = ndb.StringProperty()
  admin = ndb.BooleanProperty()

class BaseHandler(webapp2.RequestHandler):
  def get_user_db(self):
    federated_user = users.get_current_user()
    if not federated_user:
      return None
    user_db_qry = User.query(User.federated_id == federated_user.user_id())
    user_db_list = user_db_qry.fetch(1)
    #If that returns non empty list, then return the first element which is the user_db
    if user_db_list:
      return user_db_list[0]

    #Otherwise create a new user_db entity, with default values and return
    user_db = User(
        name=federated_user.nickname().title(),
        username=federated_user.nickname(),
        email=federated_user.email(),
        federated_id=federated_user.user_id(),
        admin=users.is_current_user_admin(),
      )
    user_db.put()
    return user_db

class MainHandler(BaseHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    if self.get_user_db():
      self.response.out.write('Hello, %s!
' % self.get_user_db().name)
      self.response.out.write('Logout' % (users.create_logout_url(self.request.uri)))
    else:
      self.response.out.write('Hello, stranger!
')
      self.response.out.write('Login' % (users.create_login_url(self.request.uri)))

app = webapp2.WSGIApplication([('/', MainHandler)],
                              debug=True)

rawDescription: give openid users additional information

description: Give openid users additional information


code:
class PhotoAdmin(admin.TabularInline):
    model = Photo

class AlbumAdmin(admin.ModelAdmin):
    search_fields = ["title"]
    list_display = ["title"]
    model = Album
    inlines = [PhotoAdmin]

rawDescription: Viewing photos within an album in admin page


code:
import seaborn as sns

a2 = a.pivot_table( index='animal', columns='country', values='value', fill_value=0 )

sns.heatmap(a2)

rawDescription: How do I plot hexbin with Pandas and discrete axes? (alternatively, any color-based plotting)

description: Plot hexbin with Pandas and discrete axes? (alternatively, any color-based plotting)


code:
import numpy as np
a = np.vstack([np.ones(11), np.arange(11)])
a
np.fft.irfft(np.fft.rfft(a, axis=1), axis=1)
a = np.vstack([np.ones(10), np.arange(10)])
np.fft.irfft(np.fft.rfft(a, axis=1), axis=1)
a = np.vstack([np.ones(10), np.arange(10)]).T
a
np.fft.irfft(np.fft.rfft(a, axis=0), axis=0)

rawDescription: Python NumPy - FFT and Inverse FFT?

description: Python NumPy - FFT and Inverse FFT


code:
from django.db.models import F

Entry.objects.filter(user_has_read).update(views=F('views') + 1)

rawDescription: Django model multiple updates with objects' own data?


code:
dictionary = {}
word_pos_list = []
for word in sentence:
    if word not in dictionary:
        dictionary[word] = len(dictionary) + 1
    word_pos_list.append(dictionary[word])

rawDescription: "for unit, object in enumerate" not working as I think it should


code: p = Process(target=secondProcess)

rawDescription: Running multiple processes in parallel

description: Running multiple processes in parallel


code:
entity.compressed_value = entity.compressed_value
entity.put()

rawDescription: NDB BlobProperty 'compressed' option, can be set afterwards?


code:
from dateutil.relativedelta import relativedelta
import datetime

result = []

today = datetime.date.today()
current = datetime.date(2010, 8, 1)

while current <= today:
    result.append(current)
    current += relativedelta(months=1)

rawDescription: Python: get all months in range?

description: Python: get all months in range


code:
res = []
for sequence in product(*input, *action):
    method = getattr(tasks, sequence[1]['method'])
    ch = chain(method.s(input_document, **(sequence[1])))
    for seq in sequence[2:]:
        method = getattr(tasks, seq['method'])
        ch |= method.s(**seq)
    res.append(ch)
r = group(res).apply_async()
r.save()
return r.id

rawDescription: Fan-out and subsequent synchronization with celery


code:
import array
from pydub import AudioSegment
from pydub.utils import get_array_type

sound = AudioSegment.from_wav(file="./8700hz.wav")

bit_depth = sound.sample_width * 8
array_type = get_array_type(bit_depth)

numeric_array = array.array(array_type, sound._data)

rawDescription: Pydub raw audio data

description: Pydub raw audio data


code:
file = open('file1.csv','rU')

lines = [line.strip().strip('"') for line in file]  # strip white space, too, to be sure

read = csv.reader(lines, delimiter='\t')
# any iterable producing strings will do in the reader constructor

rawDescription: issue in reading n number of values from a csv file header in python

description: Issue in reading n number of values from a csv file header in python


code:
if self.isCellEditControlShown:
    # _active_row and _active_col are set in the event handler...
    cellEditor = self.GetCellEditor(self._active_row, self._active_col)
    textControl = cellEditor.GetControl()
    textControl.Paste()

rawDescription: wxPython: how to implement paste in a grid cell?

description: WxPython: how to implement paste in a grid cell


code:
initial = {
           'update_date': datetime.datetime.now(),
           'creation_date': datetime.datetime.now(),
           'update_author': 1 # not Author.objects.get(id=1)
          }
if kwargs.has_key('initial'):
    kwargs['initial'].update(initial)
else:
    kwargs['initial'] = initial
# Initializing form only after you have set initial dict
super(DataReviewsForm,self).__init__(*args, **kwargs)

self.fields['update_date'].widget = forms.HiddenInput()
self.fields['creation_date'].widget = forms.HiddenInput()
self.fields['update_author'].widget = forms.HiddenInput()

rawDescription: Initialize a django.forms.ModelChoiceField, bound with a foreign key and a default value


code:
class Foo():
  def __init__(self, value):
    self.value = value

  def __bool__(self):
    return self.value != 0

a = Foo(1)
b = Foo(0)

for each in [a,b]:
  if each : print( "The value isn't 0 :)" )
  else : print( "The value is 0..." )

rawDescription: Return False with a class in some defined cases


code:
import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        # this will be the container for a row of buttons
        # a background color has been added just to make
        # it stand out.
        container = tk.Frame(self.root, background="#ffd3d3")

        # these are the buttons. If you want, you can make these
        # children of the container and avoid the use of "in_"
        # in the pack command, but I find it easier to maintain
        # code by keeping my widget hierarchy shallow.
        b1 = tk.Button(text="Button 1")
        b2 = tk.Button(text="Button 2")
        b3 = tk.Button(text="Button 3")

        # pack the buttons in the container. Since the buttons
        # are children of the root we need to use the in_ parameter.
        b1.pack(in_=container, side="left")
        b2.pack(in_=container, side="left")
        b3.pack(in_=container, side="left")

        # finally, pack the container in the root window
        container.pack(side="top", fill="x")

        self.root.mainloop()

if __name__ == "__main__":
    app=App()

rawDescription: How to display a sequence of widgets on the same row?

description: Display a sequence of widgets on the same row


code:
from datetime import datetime

class Test(Base):
    __tablename__ = 'test'
    id = Column('id', String, primary_key=True)
    _time = Column('time', String)

    @property
    def time(self):
        return datetime.strptime(self._time, '%Y-%m-%d %H:%M')

rawDescription: SQLAlchemy: How to convert a value of a colum in ORM-class


code:
import os
import re

# Precompile the regex so it only happens once. This saves a bit of time,
# especially if your file is large.
# I've also modified the regex to include a capture group [1] for the part
# between the > and the <, allowing us to grab the string there later. There
# are other ways to do it (e.g. with lookbehind and lookahead), but this is the
# simplest.
regex = re.compile(r'>([\w\.-]+)	')

with open('folders.txt', 'r', encoding='utf-8') as f:
    # Loop through the lines in f.
    # Alternatively, you can also do
    #     lines = f.readlines()
    #     for line in lines:
    #         ...
    # but it's less memory-efficient because it puts the whole file in memory.
    for line in f:
        match = regex.search(line)
        # re.search returns a match object [2], or None if the string doesn't
        # match the regex.
        if not match:  # Throw away non-matching lines.
            continue
        # Get the value of capture group #1.
        match = match.group(1)
        newpath = r'C:\Desktop\scriptFolders\%s' % match
        if not os.path.exists(newpath):
            os.makedirs(newpath)

rawDescription: using a regex to grab titles of folders from text file (python)

description: Using a regex to grab titles of folders from text file (python)


code:
from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engineString = 'postgresql://wberg:%s@localhost/mydatabase' % urlquote('pass/word')
engine = create_engine(engineString)

rawDescription: SQLAlchemy ValueError for slash in password for create_engine()


code:
class Menu:
    def __init__(self):
        self.active = True

        # start a timer for the menu
        Timer(3, self.reset).start()

    def update(self, scr):
        if self.active:
            surf = pygame.Surface((100, 100))
            surf.fill((255, 255, 255))
            scr.blit(surf, (270, 190))

    def reset(self):
        self.active = False

menu = Menu()

while True:
    pygame.display.update()
    queue = pygame.event.get()
    scr.fill((0, 0, 0))

    for event in queue:
        if event.type == QUIT:
            pygame.quit(); sys.exit()

    menu.update(scr)

rawDescription: Python/Pygame How to make something disappear off of screen after a set amount of time?


code:
pv = df.pivot('Name', 'Field')
pv.columns = [c[1] for c in pv.columns]
pv.reset_index(inplace=True)

rawDescription: how to pivot a dataframe into another dataframe

description: Pivot a dataframe into another dataframe


code:
import serial
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO
from xmodem import XMODEM, CRC
from time import sleep

def readUntil(char = None):
    def serialPortReader():
        while True:
            tmp = port.read(1)
            if not tmp or (char and char == tmp):
                break
            yield tmp
    return ''.join(serialPortReader())

def getc(size, timeout=1):
    return port.read(size)

def putc(data, timeout=1):
    port.write(data)
    sleep(0.001) # give device time to send ACK

port = serial.Serial(port='COM5',parity=serial.PARITY_NONE,bytesize=serial.EIGHTBITS,stopbits=serial.STOPBITS_ONE,timeout=0,xonxoff=0,rtscts=0,dsrdtr=0,baudrate=115200)
port.write("command that loads data via xmodem\r\n")
sleep(0.02) # give device time to handle command
readUntil(CRC)
buffer = StringIO('data to send')
XMODEM(getc, putc).send(buffer, quiet = 1)
buffer.close()
readUntil()

rawDescription: Can I use the xmodem protocol with PySerial?

description: Use the xmodem protocol with PySerial


code:
class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

rawDescription: How can I use the python HTMLParser library to extract data from a specific div tag?

description: Use the python HTMLParser library to extract data from a specific div tag


code:
cur.executemany("UPDATE Writers SET Name = %s WHERE Id = %s ",
        [("new_value" , "3"),("new_value" , "6")])

rawDescription: How to update multiple rows with single MySQL query in python?

description: Update multiple rows with single MySQL query in python


rawDescription: Is it possible to append a whole list of XML nodes without a loop?


code:
import multiprocessing

...

def calc_one(xymm):
  x,y,(a0,p0,a1,p1) = xymm
  w0 = Waves.GetSampleValues(Waves.WaveParams((a0[y, x], 0, p0[y, x], 0)))
  w1 = Waves.GetSampleValues(Waves.WaveParams((a1[y, x], 0, p1[y, x], 0)))

  return x,y,DemoPoint(w0, w1, useOld)

inputs = []
for y in range(0, 288):
  for x in range(0, 352):
    inputs.append((x,y,(a0,p0,a1,p1)))

resultPhase0 = {}
resultPhase1 = {}
resultAmp0 = {}
resultAmp1 = {}

num_of_workers = multiprocessing.cpu_count()
pool = multiprocessing.Pool(num_of_workers)

for data in pool.map(calc_one,inputs):
  x,y,(am0,am1,ph0,ph1) = data
  resultPhase0[y,x],resultPhase1[y,x],resultAmp0[y,x],resultAmp1[y,x] = ph0,ph1,am0,am1

return resultAmp0, resultAmp1, resultPhase0, resultPhase1

rawDescription: more complex parallel for-loop in Python

description: More complex parallel for-loop in Python


code:
class MyFormatter(logging.Formatter):
    def format(self, record):
       return record.msg.replace("test", "")

#...
console.setFormatter(MyFormatter())
#...

rawDescription: Python logging - using filters to remove information


code:
#--- Open the file   + write on it ---

f = open('out.csv','a')
prev_data = open('out.csv', 'r').read()

header = "Datetime,Location,Temperature,current_condition\n"

# Add a header only if the file is empty
if prev_data == '':
    f.write(header)

date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " + str(now.hour)          + ":" + str(now.minute) + ":" + str(now.second)
f.write(','.join([date,locations,str(temp_f),weather]))
f.write('\n')
f.close()
# --- And Close the file ---

rawDescription: Python header print one time for every time I run the script not each time


rawDescription: Swapping Elements Between Lists

description: Swapping Elements Between Lists


code:
with open(filepath, 'r') as file:
    for line in file:
        # the following is done for each line
        if not line.startswith('<p>'):
            # if the line doesn't start with <p> go to next line
            continue
        if line.startswith('<p>'):
            # if line starts with <p> do the following with
            # the rest of the line
            curFace = []
            for face in line: # here your are still on the line with <p>
                if line.startswith('p'): # your still on the first line
                    # before this you need to get the next line from the file
                    coords = line.strip('\np()/ ').split(',')

rawDescription: Encode Mesh from text-file

description: Encode Mesh from text-file


code:
import pygame
from pygame.locals import *

SCR_WID, SCR_HEI = 640, 480
screen = pygame.display.set_mode((SCR_WID, SCR_HEI))
pygame.display.set_caption("Pong")
pygame.font.init()
clock = pygame.time.Clock()
FPS = 60
pygame.init()

BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GOLD = (201,168,168)
Call = pygame.sprite.Group(())
got = pygame.sprite.Group(())
#SCR_WID, SCR_HEI = 640, 480
backg = pygame.Surface((SCR_WID, SCR_HEI)) #pygame.image.load("background.png")

class Player(pygame.sprite.Sprite):
        def __init__(self, name):
                pygame.sprite.Sprite.__init__(self)
                if name == "george":
                        self.x, self.y = 16, SCR_HEI/2
                elif name =="frank":
                        self.x, self.y = SCR_WID-16, SCR_HEI/2
                self.name = name
                self.speed = 3
                self.padWid, self.padHei = 8, 64
                self.score = 0
                self.scoreFont = pygame.font.SysFont("Arial", 32) #imagine_font.ttf", 64)

        def scoring(self):
                scoreBlit = self.scoreFont.render(str(self.score), 1, (255, 255, 255))
                if self.name == "george":
                        screen.blit(scoreBlit, (32, 16))
                        if self.score == 10:
                                print ("player 1 wins!")
                                exit()
                elif self.name == "frank":
                        screen.blit(scoreBlit, (SCR_HEI+92, 16))
                        if self.score == 10:
                                print ("Player 2 wins!")
                                exit()

        def movement(self):

                keys = pygame.key.get_pressed()
                if self.name == "george":
                        if keys[pygame.K_w]:
                                self.y -= self.speed
                        elif keys[pygame.K_s]:
                                self.y += self.speed
                elif self.name == "frank":
                        if keys[pygame.K_UP]:
                                self.y -= self.speed
                        elif keys[pygame.K_DOWN]:
                                self.y += self.speed

                if self.y <= 0:
                        self.y = 0
                elif self.y >= SCR_HEI-64:
                        self.y = SCR_HEI-64

        def draw(self):
                pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.padWid, self.padHei))

class Ball(pygame.sprite.Sprite):
    image = pygame.Surface((8,8)) #pygame.image.load("bong.png")
    image.fill((255,255,255))
    def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.rect = self.image.get_rect()

            self.rect.x, self.rect.y = SCR_WID/2, SCR_HEI/2
            self.speed_x = -3
            self.speed_y = 3
            self.size = 8

    def movement(self):
            self.rect.x += self.speed_x
            self.rect.y += self.speed_y

            if self.rect.y <= 0:
                    self.speed_y *= -1
            elif self.rect.y >= SCR_HEI-self.size:
                    self.speed_y *= -1

            if self.rect.x <= 0:
                    self.__init__()
                    enemy.score += 1
            elif self.rect.x >= SCR_WID-self.size:
                    self.__init__()
                    self.speed_x = 3
                    player.score += 1

            for n in range(-self.size, player.padHei):
                    if self.rect.y == player.y + n:
                            if self.rect.x <= player.x + player.padWid:
                                    self.speed_x *= -1
                                    break
                    n += 1
            for n in range(-self.size, enemy.padHei):
                    if self.rect.y == enemy.y + n:
                            if self.rect.x >= enemy.x - enemy.padWid:
                                    self.speed_x *= -1
                                    break

    def draw(self, screen):
        pygame.draw.rect(screen, (255,255,255), (self.rect.x, self.rect.y, self.size, self.size))

class Block(pygame.sprite.Sprite):
        image = pygame.Surface((20,20)) #image.load("brick.png")

        def __init__(self):
                pygame.sprite.Sprite.__init__(self)
                self.rect = self.image.get_rect()
                self.rect.x = 300
                self.rect.y = 0

def main():
    backgscale = pygame.transform.scale(backg,(SCR_WID, SCR_HEI))

    global player
    player = Player("george")

    global enemy
    enemy = Player("frank")

    block = Block ()
    got.add(block)

    ball = Ball()
    Call.add(ball)

    while True:

            for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                            print("Game exited by user")
                            exit()

            screen.blit(backg,(0,0))
            got.update()
            Call.update()
            backgscale = pygame.transform.scale(backg,(SCR_WID, SCR_HEI))
            got.draw(screen)
            Call.draw(screen)
            player.movement()
            enemy.movement()
            ball.movement()

            player.draw()
            player.scoring()
            enemy.draw()
            enemy.scoring()

            pygame.display.flip()
            clock.tick(FPS)

if __name__ == "__main__":
    main()

rawDescription: The Pong ball is going through the paddle and hitting the wall and reflecting rather hitting the paddle


code:
import xml.etree.ElementTree as ET

data = '''
<nowdisplaying deviceID="000C8" source="AIN">
<ContentItem source="AIN" istable="true"/>
<Status>L_STATE</Status>
</nowdisplaying>
'''

root = ET.fromstring(data)
print("source:", root.get("source"))

rawDescription: Python xml parsing using xml.etree.ElementTree not working


code:
name = u"aaa"
name.encode("utf_16")

rawDescription: Python how to get null padded byte string from unicode string


code:
import numpy as np
import pandas as pd
from datetime import datetime
dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]
index.astype(np.int64)
index.astype(np.int64) // 10**9

rawDescription: Convert pandas DateTimeIndex to Unix Time?


rawDescription: Rebalancing after failover a couchbase node


code:
def calcHash():
        hasher = hashlib.md5()
        localtime   = time.localtime()
        timeString  = time.strftime("%Y-%m-%d-%H-%M-%S", localtime)
        print(timeString)
        hasher.update(timeString.encode('utf-8'))
        print("Calculated: " + hasher.hexdigest())

rawDescription: Hashing a time-string: Why not receive same results?


code: x = [e for i, e in enumerate(x) if i not in [5, 12, 23]]

rawDescription: How to remove multiple elements from a list>

description: Remove multiple elements from a list>


code:
keys = ['a', 'b', 'c' ,'a']
values=[1, 2, 3, 4]
d = {}
for k,v in zip(keys, values):
    d.setdefault(k, []).append(v)

d

rawDescription: Convert two lists to dictionary with values as list


code:
from ast import literal_eval

numbers = literal_eval(your_string)

rawDescription: To strip a certain character out in Python


code:
def update_board(self):
    """Updates the map, however and whenever needed."""

    #Listens for the user to click the 'x' to exit.
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    #Re-draws the map.
    self.blit_board()

    pygame.display.update()

rawDescription: Failing to blit image to screen

description: Failing to blit image to screen


code:
@contextlib.contextmanager
def suppress_exceptions(*exceptions):
    if not exceptions:
        exceptions = Exception
    try:
        yield
    except exceptions:
        # You would log an error here
        # If you have logging in your application
        pass

with suppress_exceptions():
    1/0

print("Ignored the exception!")

with suppress_exceptions(IOError):
    1/0

# The second one will let the exception through

rawDescription: Protected method call in Python?

description: Protected method call in Python


code:
from Spotfire.Dxp.Application import Filters as filters
strTtype= Document.Properties['Ttype']
FilterSelection = Document.Data.Filterings["Main Scheme"]
cbfRefund = Document.FilteringSchemes[FilterSelection][Document.Data.Tables["Transaction Data"]]["Refund Transaction"].As[filters.CheckBoxFilter]()
if strTtype=="Refund":
    for CheckBoxValue in cbfRefund.Values:
        cbfRefund.Uncheck(CheckBoxValue)
        if CheckBoxValue == "Refund":
            cbfRefund.Check(CheckBoxValue)
            cbfRefund.IncludeEmpty=False#This clears the "(Empty)" checkbox

rawDescription: How can checkbox filter be set with IronPython in Spotfire?


code:
import urllib2

def get_unread_msgs(user, passwd):
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm='New mail feed',
        uri='https://mail.google.com',
        user='%s@gmail.com' % user,
        passwd=passwd
    )
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')
    return feed.read()

rawDescription: How to auto log into gmail atom feed with Python?

description: Auto log into gmail atom feed with Python


code:
class NestedDict(collections.OrderedDict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def mergejsons(jsns):
 ##use auto vification Nested Dict
    op=nesteddict.NestedDict()
    for j in jsns:
        jdata=json.load(open(j))
        jname=j.split('.')[0][-2:]
        for commnkey,val in jdata.items():
            for k,v in val.items():
                if k!='commonkey':
                    op[commnkey][k][jname]=v
                if  op[commnkey].has_key('commonkey'):
                    continue
                else:
                    op[commnkey][k][jname]=v

rawDescription: Union Multiple Nested JSONs in Python

description: Union Multiple Nested JSONs in Python


rawDescription: stdout comparison to a hash result (python)

description: Stdout comparison to a hash result (python)


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
element = WebDriverWait(ff, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "rf-st-stop")))

rawDescription: Selenium / Python - target a "loading" gif and perform action upon the .gif disappearing?


code:
self.model = QSqlTableModel(self)
self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)

rawDescription: How do I change the data displayed, not the data itself, with QSqlTableModel?

description: Change the data displayed, not the data itself, with QSqlTableModel


code:
class NewsletterAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.save()
        if not change: # newly created newsletter
            if obj.send_to == '1':
                for student in Student.objects.all():
                    EmailLog.objects.create(student=student, newsletter=obj)
            elif obj.send_to == '2':
                for teacher in Teacher.objects.all():
                    EmailLog.objects.create(teacher=teacher, newsletter=obj)

rawDescription: Do Some work before Saving and After Saving data in django Admin


code:
p_translation = ""
i_translation = ""
interviewer = False
for line in f:
    if line.startsWith("Participant: Participant"):
        #This would be the place to process i_translation
        #because now the translation of the interviewer was
        #fully read
        interviewer = False
        p_translation = ""
    elif line.startsWith("Participant: Interviewer"):
        #This would be the place to process p_translation
        #because now the translation of the participant was
        #fully read
        interviewer = True
        i_translation = ""
    else:
        if interviewer:
            i_translation += line
        else:
            p_translation += line

rawDescription: Reading from textfile without having to use readline()


code:
def repl(m):
  inner_word = list(m.group(2))
  random.shuffle(inner_word)
  return m.group(1) + "".join(inner_word) + m.group(3)
text = "Professor Abdolmalek, please report your absences promptly."
re.sub(r"(\w)(\w+)(\w)", repl, text)
re.sub(r"(\w)(\w+)(\w)", repl, text)

rawDescription: Iterating through regular expressions in Python


code:
data=np.genfromtxt("file.csv", delimiter=',', dtype=None, names=True)
columns = data.dtype.names
for i in range(len(data['id'])):
    p = MyModel()
    for a in range(1, len(columns)): #1
        if hasattr(p, columns[a]):
            setattr(p, columns[a], data[i][columns[a]])
        else:
            raise AttributeError("'MyModel' object has no attribute '{0}'".format(columns[a]))
    p.save()

rawDescription: How to update dynamically a model in Django?

description: Update dynamically a model in Django


code:
def random_person(request):
    # 1282302 is max number of people currently
    get_random = random.randint(1,1282302)
    get_person = Person.objects.get(pk=get_random)
    person_name = get_person.full
    return HttpResponseRedirect(reverse('film_chart_view')+"?q="+get_person.short)

rawDescription: Django calling a view from another view

description: Django calling a view from another view


code:
from tkinter import Tk

root = Tk()

def afterstartup():
    print("hello")

# The number here is how many milliseconds to wait
root.after(1000, afterstartup)

root.mainloop()

rawDescription: Initialization just after tkinter's root.mainloop() has begun (Python)


rawDescription: Why should not use list.sort in python

description: Why should not use list.sort in python


code:
strs1="PARTITION BY HASH(SOME_THING)"
strs2="SUBPARTITION BY HASH(SOME_THING)"
bool(re.match(r"^PARTITION BY HASH",strs1))
bool(re.match(r"^PARTITION BY HASH",strs2))

rawDescription: Python regex match

description: Python regex match


code:
class C(object):
  def __init__(self, val):
    self.val = val

rawDescription: Python: how can I initialize my empty objects?


code:
try:
    # Python 2
    text_type = unicode
except NameError:
    # Python 3
    text_type = str

rawDescription: Writing py2.x and py3.x compatible code without six.text_type


code: np.fft.ifft(x, axis=1)

rawDescription: Inverse discrete Fourier transform of across specified dimension in Python/Numpy


code:
import tarfile

with tarfile.open("test.tbz2",mode='w:bz2') as f:
    t = tarfile.TarInfo('mydir')
    t.type = tarfile.DIRTYPE
    f.addfile(t)

rawDescription: add empty directory to tarfile

description: Add empty directory to tarfile


code:
def func2(X, y):
    num_examples, num_features = np.shape(X)
    weights = np.random.uniform(-1./(2*num_examples), 1./(2*num_examples), num_features)

    K = (np.dot(X, weights) - y)

    return weights - alpha/num_examples*np.einsum('i,ij->j', K, X)

rawDescription: How to perform Numpy optimisation for this code?

description: Perform Numpy optimisation for this code


code:
# map class names to classes
avail = dict((cls.__name__, cls) for cls in (Spam, Eggs, Toast))

@app.route('/hello')
def hello():
    name = request.args['name']
    obj = avail[name]()
    return 'you created a {}'.format(name)

rawDescription: Instantiate class based on request parameter


code:
for row in input:
    splitted = row[0].lower().split()
    for s in splitted :
        for cle, valeur in dict.items() :
            if cle == s :
                print ("{} >> {}".format(cle, valeur))

rawDescription: dissociate firstname/surname by comparing

description: Dissociate firstname/surname by comparing


code: df.xs(df.index.levels[N][K], level=N)

rawDescription: Integer-based (K,N) indexing of Multi-Index DataFrames


code:
import wx, thread, os, time

ID_EXIT = 110

class Dummy:
    pass

gp = Dummy()

class MainPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.buttonRun = wx.Button(self, label="Run")
        self.buttonRun.Bind(wx.EVT_BUTTON, self.OnRun )
        self.buttonExit = wx.Button(self, label="Exit")
        self.buttonExit.Bind(wx.EVT_BUTTON, self.OnExit)

        self.labelChooseRoot = wx.StaticText(self, label ="Root catalog: ")
        self.labelScratchWrk = wx.StaticText(self, label ="Scratch workspace: ")
        self.labelMergeFile = wx.StaticText(self, label ="Merge file: ")

        self.textChooseRoot = wx.TextCtrl(self, size=(210, -1))
        self.textChooseRoot.Bind(wx.EVT_LEFT_UP, self.OnChooseRoot)
        self.textScratchWrk = wx.TextCtrl(self, size=(210, -1))
        self.textMergeFile = wx.TextCtrl(self, size=(210, -1))
        self.textOutput = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)

        self.sizerF = wx.FlexGridSizer(3, 2, 5, 5)
        self.sizerF.Add(self.labelChooseRoot)  #row 1, col 1
        self.sizerF.Add(self.textChooseRoot)   #row 1, col 2
        self.sizerF.Add(self.labelScratchWrk)  #row 2, col 1
        self.sizerF.Add(self.textScratchWrk)   #row 2, col 2
        self.sizerF.Add(self.labelMergeFile)   #row 3, col 1
        self.sizerF.Add(self.textMergeFile)    #row 3, col 2

        self.sizerB = wx.BoxSizer(wx.VERTICAL)
        self.sizerB.Add(self.buttonRun, 1, wx.ALIGN_RIGHT|wx.ALL, 5)
        self.sizerB.Add(self.buttonExit, 0, wx.ALIGN_RIGHT|wx.ALL, 5)

        self.sizer1 = wx.BoxSizer()
        self.sizer1.Add(self.sizerF, 0, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL, 10)
        self.sizer1.Add(self.sizerB, 0, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL)

        self.sizer2 = wx.BoxSizer()
        self.sizer2.Add(self.textOutput, 1, wx.EXPAND | wx.ALL, 5)

        self.sizerFinal = wx.BoxSizer(wx.VERTICAL)
        self.sizerFinal.Add(self.sizer1, 0, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL)
        self.sizerFinal.Add(self.sizer2, 1, wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL)

        self.SetSizerAndFit(self.sizerFinal)

    def OnChooseRoot(self, event):
        dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            root_path = dlg.GetPath()
            self.textChooseRoot.SetValue(root_path)
        dlg.Destroy()

    def CheckValid(self):
        return 0

    def OnRun(self, Event=None):
        #---Check input values, continue if not wrong
        if self.CheckValid() == 0:
            #Get root directory
            root_path = self.textChooseRoot.GetValue()
            #Get scratch workspace
            scratch_workspace =self.textScratchWrk.GetValue()
            #Get merge file
            merge_fil = self.textMergeFile.GetValue()

            thread.start_new_thread(self.OnIndex, (root_path,scratch_workspace,merge_fil))

    def showmsg(self, msg):
        self.textOutput.AppendText(msg + "\n")

    def OnIndex(self,root_path,scratch_workspace,merge_fil):
            #---PUBSUB - publishes a message to the "show.statusbar"
##            msg = "Please wait...Program is running..."
##            Publisher().sendMessage(("show.statusbar"), msg)
            #---START INDEX GENERATOR CODE
            gp.overwriteoutput = 1
            gp.OutputMFlag = "DISABLED"
            gp.OutputZFlag = "DISABLED"
            fc_List = {}

            #Get log file. For now a constant. Needs to be changed.
            #logfil = open("C:\\Python26\\Code\\log.txt", mode = "w")

            fold_nr = 0
            for root_fold, dirs, files in os.walk(root_path):
                root_fold_low = root_fold.lower()
                if not root_fold_low.find(".gdb") > -1:
                    fold_nr += 1
                    tot_t = time.clock()

                    wx.CallAfter(self.textOutput.AppendText, ("Mappe : " + str(fold_nr) + " : " + root_fold + "\n"))

    def OnExit(self, event):
        self.GetParent().Close()

class MainWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="IndexGenerator", size=(430, 330),
                          style=((wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE |
                                  wx.STAY_ON_TOP) ^ wx.RESIZE_BORDER))
        self.CreateStatusBar()

        self.fileMenu = wx.Menu()
        self.fileMenu.Append(ID_EXIT, "E&xit", "Exit the program")
        self.menuBar = wx.MenuBar()
        self.menuBar.Append(self.fileMenu, "&File")
        self.SetMenuBar(self.menuBar)
        wx.EVT_MENU(self, ID_EXIT, self.OnExit)

        self.Panel = MainPanel(self)

        self.CentreOnScreen()
        self.Show()

    def OnExit(self,  event):
        self.Close()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainWindow()
    app.MainLoop()

rawDescription: wxPython: Problems with thread

description: WxPython: Problems with thread


code:
class Author(Model):
    name = CharField(max_length=100)

    class Meta:
        ordering = ('name',)

rawDescription: How to alphabetically order a drop-down list in Django admin?

description: Alphabetically order a drop-down list in Django admin


code:
class ListAction(argparse.Action):
    def __call__(parser, namespace, values, option_string=None):
        setattr(namespace, 'list', values[0])
        do_something_completely_different()

rawDescription: Adding options which both change behaviour and store an argument


code:
import maya.cmds
sel = cmds.ls(sl=1, fl=1)
for i in sel:
    pp = cmds.pointPosition(i, w=1)
    fol = cmds.createNode('follicle')
    cmds.move(pp[0], pp[1], pp[2], fol)

rawDescription: Python & Maya: Creating follicles at selected vertexs


code:
@BlogSerializer.data_handler
def flatten(serializer, data, obj):
    if 'author' in data:
        author = data['author']
        del data['author']
        return dict(author, **data)
    else:
        return data

rawDescription: How to merge a nested object with parent in marshmallow (+ sqlalchemy)?

description: Merge a nested object with parent in marshmallow (+ sqlalchemy)


code:
def f(each_code):
    start = datetime.datetime(2010, 1, 1)
    end = datetime.datetime.today()
    get_prices = web.DataReader(each_code, 'yahoo', start, end)
    get_prices.to_csv(each_code + '.csv')

p = Pool(20)
p.map(f, df['Symbol'])

rawDescription: multiprocessing / multithreading in python to download files

description: Multiprocessing / multithreading in python to download files


code:
from sklearn.datasets import load_iris
from sklearn import tree

# load data and divide it to train and validation
iris = load_iris()

num_train = 100
X_train = iris.data[:num_train,:]
X_valida = iris.data[num_train:,:]

y_train = iris.target[:num_train]
y_valida = iris.target[num_train:]

# convert data to float32
X_train = X_train.astype('float32')

# fit the decision tree using the train data set
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)

# Now I want to know the corresponding leaf node id for each of my training data point
clf.tree_.apply(X_train)

# This gives the leaf node id:
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2])

rawDescription: Finding a corresponding leaf node for each data point in a decision tree (scikit-learn)


code:
import gtk

class MainWindow():
    def __init__(self):
        self.window = gtk.Window()
        self.box = gtk.EventBox ()
        self.window.add (self.box)
        self.box.add (gtk.Label ('some text'))
        self.window.show_all()

        import sys
        self.box.connect ('button-press-event',
                          lambda widget, event:
                              sys.stdout.write ('%s // %s\n' % (widget, event)))

if __name__ == "__main__":
    main = MainWindow()
    gtk.main()

rawDescription: Catching a click anywhere inside a gtk.Window


code:
ll = ['listA_5_val','listB_15_val','listC_25_val']
[int(x[6:-4]) for x in ll]
[int(x.split('_')[1]) for x in ll]

rawDescription: extract from each element of list in python

description: Extract from each element of list in python


code:
from sympy import Symbol, factor
a = Symbol("a")
factor(a**4 - 8*a**3 + 20*a**2 - 16*a + 4)

rawDescription: Calculate symbolic square root of expression (with parameters) in python?


code:
node = [None, None, None, None]
node = [[[None, None, None, None], None, None, None], None, None, None]

rawDescription: Memory efficient variable types in Python


code: result = [list(someListOfElements) for _ in xrange(x)]

rawDescription: How to create a list or tuple of empty lists in Python?

description: Create a list or tuple of empty lists in Python


rawDescription: number approximation in python

description: Number approximation in python


code:
board
board=[[x if x!=0 else " " for x in i] for i in board]
board

rawDescription: replace characters in list of lists

description: Replace characters in list of lists


code:
camera = 'Camera1'
channel = 'translateX'
keyframes = cmds.keyframe('{}.{}'.format(camera, channel), query=True)
first, last = keyframes[0], keyframes[-1]
cmds.playbackOptions(min=first, max=last, ast=first, aet=last)

rawDescription: Maya python and camera animation

description: Maya python and camera animation


code: ' '.join(str(i) for i in your_list)

rawDescription: Printed representation of list

description: Printed representation of list


code:
a = df.pivot_table(index='ID', columns='name1', values='T1_val')
b = df.pivot_table(index='ID', columns='name2', values='C1_val')
pd.concat((a, b), axis=1).reset_index()

rawDescription: pandas data frame reshaping

description: Pandas data frame reshaping


code:
found_pair = False
# MAX_X and MAX_Y would be have to be supplied by you
for x in range(0, MAX_X+1):
    for y in range(0, MAX_Y+1):
        if self.rank == self.cube.Get_cart_rank([x,y,0]):
            found_pair = True
            break

if found_pair:
    ...

rawDescription: Any integer wildcard in python?

description: Any integer wildcard in python


code:
from subprocess import check_output, STDOUT

network_info = check_output('ifconfig', stderr=STDOUT)

rawDescription: Python Subprocess Finishes, but Output File Not Available


code: print ((' ' * spaces) + ((symbol + ' ') * i))

rawDescription: Creating pyramid using symbols in Python


rawDescription: Convert UTF-8 bytes to some other encoding in Python


code:
import h5py
with h5py.File('myfile.hdf5','w') as f:
    dset = f.create_dataset("MyDataset", (100, 100), 'i')
    dset[...] = 42

with h5py.File('myfile.hdf5','r+') as ff:
    dset = ff.create_group("MyGroup")

rawDescription: I can't read data back in using h5py. "unable to create group"


code:
data = { "email" : "my_new_email@example.com", "age" : 20, "city" : "London", "country" : "UK", "language" : "English", "profession" : "developer", "employeer" : "BBC" }
User.query.filter_by(username='admin').update(data)
db.session.commit()

rawDescription: update multiples fields with sql alchemy

description: Update multiples fields with sql alchemy


code:
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, Parameter, report_fit

# create data to be fitted
x = np.linspace(0, 15, 301)
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
np.random.normal(size=len(x), scale=0.2) )

# define objective function: returns the array to be minimized
def fcn2min(params, x, data):

    """ model decaying sine wave, subtract data"""
    amp = params['amp'].value
    shift = params['shift'].value
    omega = params['omega'].value
    decay = params['decay'].value
    model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)

    # tell Python we're modifying the model_data list
    # that was declared outside of this function
    global model_data

    # store the model data produced by this function call
    # add any data you want to display later to this "dictionary"
    model_data += [{
        "amp": amp,
        "shift": shift,
        "omega": omega,
        "decay": decay
    }]

    return model - data

# create a set of Parameters
params = Parameters()
params.add('amp',   value= 10,  min=0)
params.add('decay', value= 0.1)
params.add('shift', value= 0.0, min=-np.pi/2., max=np.pi/2)
params.add('omega', value= 5.0)

# declare an empty list to hold the model data
model_data = []

# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(x, data))

# print each item in the model data list
for datum in model_data:
    for key in datum:

        #the 5 in %.5f controls the precision of the floating point value
        print("%s: %.5f  ") % (key, datum[key]),
    print

# calculate final result
final = data + result.residual

# try to plot results
plt.plot(x,data,'k+')
plt.plot(x,final,'r')
plt.show()

rawDescription: With using lmfit module in python, how to call the parameters in the model?


code:
subprocess.Popen(proxy_cmd,
                 shell=True,
                 stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE)

rawDescription: diverting the stdin when ssh-ing to another machine from python

description: Diverting the stdin when ssh-ing to another machine from python


code:
##### include mydir in distribution #######
def extra_datas(mydir):
    def rec_glob(p, files):
        import os
        import glob
        for d in glob.glob(p):
            if os.path.isfile(d):
                files.append(d)
            rec_glob("%s/*" % d, files)
    files = []
    rec_glob("%s/*" % mydir, files)
    extra_datas = []
    for f in files:
        extra_datas.append((f, f, 'DATA'))

    return extra_datas
###########################################

# append the 'data' dir
a.datas += extra_datas('data')

rawDescription: Including a directory using Pyinstaller

description: Including a directory using Pyinstaller


code:
match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

rawDescription: Extracting date from a string in Python

description: Extracting date from a string in Python


code:
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

class MyView(View):
    @method_decorator(user_passes_test(lambda u: u.is_superuser))
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

rawDescription: django user_passes_test decorator

description: Django user_passes_test decorator


code: os.environ["APPDATA"] # returns "c:\\Users\\<username>\\AppData\\Roaming"

rawDescription: Refer to system dependent / user paths like "AppData" or "MyDocuments"?


code:
class ApiDataset(object):
    def __init__(self, api_addr):
        self.http_api_addr = api_addr
        self.data = None

    def cache_data(self):
        # Access API and cache returned data on object.
        if self.data is None:
            self.data = get_data_from_api()

    def __iter__(self):
        self.cache_results()
        for item in self.data['objects']:
            yield item

    def __len__(self):
        self.cache_results()
        return self.data['total_count']

rawDescription: django-tables2 - How to assign total item count with non-queryset data pagination?

description: Django-tables2 - How to assign total item count with non-queryset data pagination


code:
def proclevel(levels):
    if levels > 0:
        generator = proclevel(levels - 1)
        temp = None
        for firsthash, secondhash in generator:
            if not temp: temp = hashofthem(firsthash, secondhash)
            else: yield temp, hashofthem(firsthash, secondhash); temp = None
        #If odd number of packets
        if temp: yield temp, None
    else:
        temp = None
        for chunk in chunks:
            if not temp: temp = hash(chunk)
            else: yield temp, hash(chunk); temp = None
        if temp: yield temp, None

rawDescription: Reverse tree building (with an odd number of children)


code: mynewlist = [s for s in mylist if s.isdigit()]

rawDescription: Python check if list items are numbers

description: Python check if list items are numbers


code:
s = 'foreign, for fore'
re.findall(r'\bfor\b', s)

rawDescription: Python find a specific word

description: Python find a specific word


code:
temperature = [23, 24, 25, 26, 27]
print("Today's temperature is %.02f" % (temperature[0]))
print("Today's temperature is {:.02f}".format(temperature[0]))

rawDescription: How to apply "%.02f" in Python format function?

description: Apply "%.02f" in Python format function


code:
for i, item in enumerate(test):
    if i and i % 4 == 0:
        f.write("\n")
    f.write("%-9s|   " % item)

rawDescription: Formatting/Displaying list in python

description: Formatting/Displaying list in python


code:
import numpy as np
import matplotlib.pyplot as pl
import scipy.stats as st

data = np.random.multivariate_normal((0, 0), [[0.8, 0.05], [0.05, 0.7]], 100)
x = data[:, 0]
y = data[:, 1]
xmin, xmax = -3, 3
ymin, ymax = -3, 3

# Peform the kernel density estimate
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)

fig = pl.figure()
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# Contourf plot
cfset = ax.contourf(xx, yy, f, cmap='Blues')
## Or kernel density estimate plot instead of the contourf plot
#ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
cset = ax.contour(xx, yy, f, colors='k')
# Label plot
ax.clabel(cset, inline=1, fontsize=10)
ax.set_xlabel('Y1')
ax.set_ylabel('Y0')

pl.show()

rawDescription: Plotting 2D Kernel Density Estimation with Python


code: html = t.render(Context({'matrix': matrix, 'passcount': passcount, 'count': count}))

rawDescription: Django/Python : Need to Pass integer variables from the Django view to a template


code:
def read_mx_cells(file, parse_cell = lambda x:x):
  rows = (line.rstrip().split() for line in file)
  header = next(rows)
  for row in rows:
    row_id = row[0]
    for col_id,cell in zip(header, row[1:]):
      yield ((row_id, col_id), parse_cell(cell))

with open('matrix.txt') as f:
  for x in read_mx_cells(f, int):
    print(x)
# ('A','A'),1
# ('A','B'),2
# ('A','C'),3 ...

with open('matrix.txt') as f:
  print(dict(read_mx_cells(f, int)))
# { ('A','A'): 1, ('A','B'): 2, ('A','C'): 3 ... }
# Note that python dicts dont retain item order

rawDescription: Matrix file to dictionary in python

description: Matrix file to dictionary in python


code:
import sys,os
sys.path.append(os.environ['SPARK_HOME'] + '/python')
sys.path.append(os.environ['SPARK_HOME']+ '/python/build')
sys.path.append(os.environ['SPARK_HOME'] + '/python/pyspark')

#This part was neccesary for me, since I have a weird set up
sys.path.insert('0' + '/usr/bin')

import pyspark
sc = pyspark.SparkContext()

rawDescription: Launch pyspark from regular python

description: Launch pyspark from regular python


code:
from pyswitch import Switch

mySwitch = Switch()

@myswitch.caseRegEx(regex1)
def doSomething(matchObj, *args, **kwargs):
    # Do Something
    return 1

@myswitch.caseRegEx(regex2)
def doSomethingElse(matchObj, *args, **kwargs):
    # Do Something Else
    return 2

rval = myswitch(stringYouWantToSwitchOn)

rawDescription: how can I combine a switch-case and regex in Python

description: Combine a switch-case and regex in Python


rawDescription: Fill between x and baseline x position in Matplotlib


code:
s = sum(L)
A = [x/s for x in L]

rawDescription: Does python interpreter reuse results for efficiency?