code:
lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]
result = "\n".join("\t".join(map(str,l)) for l in lists)

rawDescription: Convert list of lists to delimited string


code:
def insertRandomRows(engine, table, count):
    rows = []
    for i in range(count):
        rows.append(table(randstr(), randstr(), randstr()))
    session = sessionmaker(bind = engine)()
    session.add_all(rows)
    session.commit()
    session.close()

rawDescription: add row to declarated table sqlalchemy

description: Add row to declarated table sqlalchemy


code:
class MyModel(models.Model):
    name = models.CharField(max_length=140)
    url = models.CharField(max_length=140)

    def save(self, *args, **kwargs):
        self.url = self.name.replace(' ', '_').lower()
        super(MyModel, self).save(*args, **kwargs)

rawDescription: Django: Auto Generate a CharField using data from another CharField


code:
ay, by = zip(*(calc(x) for x in steps))
ay
by

rawDescription: List comprehension and function returning multiple values


code:
for service in accounts:
        for account, creds in accounts[service].iteritems():
            account.setupAccount(creds['username'], creds['password'])

rawDescription: Python: How to deal with non-subscriptable objects?


rawDescription: Python, SqlAlchemy: Many to many relationship, find those without


rawDescription: Acces all off diagonal elements of boolean numpy matrix


code:
def divide(dividends, divisors):
    ret = dict()
    for key, dividend in dividends.iteritems():
        if key in divisor:
            ret[key] = dividend/divisors[key]
        else:
            ret[key] = dividend
    return ret

rawDescription: Dividing values of dictionaries by values of another dictionary python


code:
from sklearn.cross_validation import KFold, StratifiedKFold
## Choose one of the two next lines
cv = KFold(self.cv_folds)   # for regression
cv = StratifiedKFold(y, self.cv_folds)   # for classification

cv_scores = cross_validation.cross_val_score(rfc, X, y, cv=cv)

rawDescription: Cross Validation sklearn - How the splits are performed?


code:
for x, y, z in zip(func1(), func2(), func3()):
    melFile.write("currentTime %f" % x)
    melFile.write('setAttr "blend_shape.lip_round" %f' % y)
    melFile.write('setAttr "blend_shape.jaw_open" %f' % z)

rawDescription: passing contents from multiple lists generated in different functions to a file

description: Passing contents from multiple lists generated in different functions to a file


code:
import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("http://www.example.com/").read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
        print(line.get('href'))

rawDescription: Parsing a website with Python

description: Parsing a website with Python


code:
from skimage.data import lena  # Color image version of lena. If you don't have skimage, use any image
import matplotlib.pyplot as plt

img = lena().astype(float) / 256.
plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(img)

sepia_filter = np.array([[.393, .769, .189],
                         [.349, .686, .168],
                         [.272, .534, .131]])

# here goes the filtering
sepia_img = img.dot(sepia_filter.T)

# Unfortunately your filter lines do not have unit sum, so we need to rescale
sepia_img /= sepia_img.max()

plt.subplot(1, 2, 2)
plt.imshow(sepia_img)
plt.show()

rawDescription: Using numpy to apply a sepia effect to a 3D array


code:
paragraph = Paragraph(header_string, styleH)
paragraph.keepWithNext = True
Story.append(paragraph)
Story.append(table)

rawDescription: how to group objects in reportlab, so that they stay together across new pages

description: Group objects in reportlab, so that they stay together across new pages


code:
class FileList(list):
    def __init__(self, files, mode='r'):
        list.__init__(open(arg, mode) for arg in files)
    def __enter__(self):
        return self
    def __exit__(self, *args):
        for fobj in self:
            fobj.close()

with FileList(["ACCELEROMETER", "GPS", ...], mode='w') as fl:
    for fobj in fl:
        ...

rawDescription: Get file objects inside a scope of "with" block


code:
import win32serviceutil
import win32service
import win32event
import servicemanager

import win32gui
import win32gui_struct
struct = win32gui_struct.struct
pywintypes = win32gui_struct.pywintypes
import win32con

GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEREMOVECOMPLETE = 0x8004

import ctypes

#
# Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be
# used for monkey-patching said module with correct handling
# of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE
#
def _UnpackDEV_BROADCAST (lparam):
  if lparam == 0: return None
  hdr_format = "iii"
  hdr_size = struct.calcsize (hdr_format)
  hdr_buf = win32gui.PyGetMemory (lparam, hdr_size)
  size, devtype, reserved = struct.unpack ("iii", hdr_buf)
  # Due to x64 alignment issues, we need to use the full format string over
  # the entire buffer.  ie, on x64:
  # calcsize('iiiP') != calcsize('iii')+calcsize('P')
  buf = win32gui.PyGetMemory (lparam, size)

  extra = {}
  if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
    fmt = hdr_format + "16s"
    _, _, _, guid_bytes = struct.unpack (fmt, buf[:struct.calcsize(fmt)])
    extra['classguid'] = pywintypes.IID (guid_bytes, True)
    extra['name'] = ctypes.wstring_at (lparam + struct.calcsize(fmt))
  else:
    raise NotImplementedError("unknown device type %d" % (devtype,))
  return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
win32gui_struct.UnpackDEV_BROADCAST = _UnpackDEV_BROADCAST

class DeviceEventService (win32serviceutil.ServiceFramework):

  _svc_name_ = "DevEventHandler"
  _svc_display_name_ = "Device Event Handler"
  _svc_description_ = "Handle device notification events"

  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__ (self, args)
    self.hWaitStop = win32event.CreateEvent (None, 0, 0, None)
    #
    # Specify that we're interested in device interface
    # events for USB devices
    #
    filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE (
      GUID_DEVINTERFACE_USB_DEVICE
    )
    self.hDevNotify = win32gui.RegisterDeviceNotification (
      self.ssh, # copy of the service status handle
      filter,
      win32con.DEVICE_NOTIFY_SERVICE_HANDLE
    )

  #
  # Add to the list of controls already handled by the underlying
  # ServiceFramework class. We're only interested in device events
  #
  def GetAcceptedControls(self):
    rc = win32serviceutil.ServiceFramework.GetAcceptedControls (self)
    rc |= win32service.SERVICE_CONTROL_DEVICEEVENT
    return rc

  #
  # Handle non-standard service events (including our device broadcasts)
  # by logging to the Application event log
  #
  def SvcOtherEx(self, control, event_type, data):
    if control == win32service.SERVICE_CONTROL_DEVICEEVENT:
      info = win32gui_struct.UnpackDEV_BROADCAST(data)
      #
      # This is the key bit here where you'll presumably
      # do something other than log the event. Perhaps pulse
      # a named event or write to a secure pipe etc. etc.
      #
      if event_type == DBT_DEVICEARRIVAL:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s arrived" % info.name, '')
        )
      elif event_type == DBT_DEVICEREMOVECOMPLETE:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s removed" % info.name, '')
        )

  #
  # Standard stuff for stopping and running service; nothing
  # specific to device notifications
  #
  def SvcStop(self):
    self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent (self.hWaitStop)

  def SvcDoRun(self):
    win32event.WaitForSingleObject (self.hWaitStop, win32event.INFINITE)
    servicemanager.LogMsg (
      servicemanager.EVENTLOG_INFORMATION_TYPE,
      servicemanager.PYS_SERVICE_STOPPED,
      (self._svc_name_, '')
    )

if __name__=='__main__':
  win32serviceutil.HandleCommandLine (DeviceEventService)

rawDescription: Detect inserted USB on Windows

description: Detect inserted USB on Windows


code:
velParam_numpy = 2*velArray
velParam_vtk = numpy_to_vtk(velParam_numpy)
velParam_vtk.SetName('VelParam') #rememebr to give an unique name
data.GetPointData().AddArray(velParam_vtk)

rawDescription: Writing and modifying VTK polydata files using Python


code:
fields = ('name', 'school')
match_found = any(all(x[f]==example[f] for f in fields) for x in myList)

rawDescription: In list of dicts, match dict based on one key/value?


rawDescription: PDF and CDF without SciPy

description: PDF and CDF without SciPy


code:
import numpy as np
import time

# NB. Scipy >= 0.14.0 probably required
import scipy
from scipy.sparse.linalg import gmres, spsolve
from scipy.sparse import csgraph
from scipy import sparse

def markov_stationary_components(P, tol=1e-12):
    """
    Split the chain first to connected components, and solve the
    stationary state for the smallest one
    """
    n = P.shape[0]

    # 0. Drop zero edges
    P = P.tocsr()
    P.eliminate_zeros()

    # 1. Separate to connected components
    n_components, labels = csgraph.connected_components(P, directed=True, connection='strong')

    # The labels also contain decaying components that need to be skipped
    index_sets = []
    for j in range(n_components):
        indices = np.flatnonzero(labels == j)
        other_indices = np.flatnonzero(labels != j)

        Px = P[indices,:][:,other_indices]
        if Px.max() == 0:
            index_sets.append(indices)
    n_components = len(index_sets)

    # 2. Pick the smallest one
    sizes = [indices.size for indices in index_sets]
    min_j = np.argmin(sizes)
    indices = index_sets[min_j]

    print("Solving for component {0}/{1} of size {2}".format(min_j, n_components, indices.size))

    # 3. Solve stationary state for it
    p = np.zeros(n)
    if indices.size == 1:
        # Simple case
        p[indices] = 1
    else:
        p[indices] = markov_stationary_one(P[indices,:][:,indices], tol=tol)

    return p

def markov_stationary_one(P, tol=1e-12, direct=False):
    """
    Solve stationary state of Markov chain by replacing the first
    equation by the normalization condition.
    """
    if P.shape == (1, 1):
        return np.array([1.0])

    n = P.shape[0]
    dP = P - sparse.eye(n)
    A = sparse.vstack([np.ones(n), dP.T[1:,:]])
    rhs = np.zeros((n,))
    rhs[0] = 1

    if direct:
        # Requires that the solution is unique
        return spsolve(A, rhs)
    else:
        # GMRES does not care whether the solution is unique or not, it
        # will pick the first one it finds in the Krylov subspace
        p, info = gmres(A, rhs, tol=tol)
        if info != 0:
            raise RuntimeError("gmres didn't converge")
        return p

def main():
    # Random transition matrix (connected)
    n = 100000
    np.random.seed(1234)
    P = sparse.rand(n, n, 1e-3) + sparse.eye(n)
    P = P + sparse.diags([1, 1], [-1, 1], shape=P.shape)

    # Disconnect several components
    P = P.tolil()
    P[:1000,1000:] = 0
    P[1000:,:1000] = 0

    P[10000:11000,:10000] = 0
    P[10000:11000,11000:] = 0
    P[:10000,10000:11000] = 0
    P[11000:,10000:11000] = 0

    # Normalize
    P = P.tocsr()
    P = P.multiply(sparse.csr_matrix(1/P.sum(1).A))

    print("*** Case 1")
    doit(P)

    print("*** Case 2")
    P = sparse.csr_matrix(np.array([[1.0, 0.0, 0.0, 0.0],
                                    [0.5, 0.5, 0.0, 0.0],
                                    [0.0, 0.0, 0.5, 0.5],
                                    [0.0, 0.0, 0.5, 0.5]]))
    doit(P)

def doit(P):
    assert isinstance(P, sparse.csr_matrix)
    assert np.isfinite(P.data).all()

    print("Construction finished!")

    def check_solution(method):
        print("\n\n-- {0}".format(method.__name__))
        start = time.time()
        p = method(P)
        print("time: {0}".format(time.time() - start))
        print("error: {0}".format(np.linalg.norm(P.T.dot(p) - p)))
        print("min(p)/max(p): {0}, {1}".format(p.min(), p.max()))
        print("sum(p): {0}".format(p.sum()))

    check_solution(markov_stationary_components)

if __name__ == "__main__":
    main()

rawDescription: Markov chain stationary distributions with scipy.sparse?


code:
def validCheck(check, valid_list):
    all_keys = []
    for r in range(len(check)):
        key = " ".join(check[r:])
        revkey = " ".join(check[-r:-1])

        valid_key = []
        valid_revkey = []

        if key in valid_list:
            valid_key.append(key)
        if revkey in valid_list:
            valid_revkey.append(revkey)

        all_keys.extend(valid_key + valid_revkey)

    return max(all_keys, key=len) if all_keys else None

rawDescription: Iterating recursively over joined items in a list


code:
def calculate_path(v1, v2):
  return [v1, ..., v2]

from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(('localhost', 9393))
server.register_function(calculate_path)
server.serve_forever()

rawDescription: Calling a Python program from PHP

description: Calling a Python program from PHP


code:
from lxml import etree as ET

calendar = ET.ElementTree()
calendar.parse("calendar-week.xml")

elem_list = calendar.xpath('//div[contains(concat(" ", @class, " "), " day ")]')

rawDescription: find xml element with multiple values

description: Find xml element with multiple values


code:
with open("input.txt") as f1:
   with open("output.txt","w") as f2:
        for _ in range(15):
            f2.write(f1.readline())

rawDescription: Reading specific lines from a file and writing to another file in python


code:
with self.canvas:
    rect = Rectangle(pos=(0, 0), size=(10, 10))

rect.pos = (50, 50)

rawDescription: How to dynamically create texture from set of widgets in Kivy?

description: Dynamically create texture from set of widgets in Kivy


code: sum1, sum2 = sum(x[1] for x in my_list), sum(x[2] for x in my_list)

rawDescription: Operation with values at specific indexes in a list of list


code: part = lambda theta,phi, x=x, y=y, z=z, k=k: (N.cos(theta)**(0.5))*N.sin(theta)*N.exp(-1j*k*(x*N.sin(theta)*N.cos(phi) + y*N.sin(theta)*N.sin(phi) - z*N.cos(theta)))

rawDescription: Python lambda with complex number

description: Python lambda with complex number


code:
from gi.repository import Gtk
from gi.repository import GdkPixbuf

store = Gtk.ListStore(str, GdkPixbuf.Pixbuf)

pb = GdkPixbuf.Pixbuf.new_from_file_at_size("picture.png", 32, 32)
store.append(["Test", pb])

combo = Gtk.ComboBox.new_with_model(store)

renderer = Gtk.CellRendererText()
combo.pack_start(renderer, True)
combo.add_attribute(renderer, "text", 0)

renderer = Gtk.CellRendererPixbuf()
combo.pack_start(renderer, False)
combo.add_attribute(renderer, "pixbuf", 1)

window = Gtk.Window()
window.add(combo)
window.show_all()

window.connect('delete-event', lambda w, e: Gtk.main_quit())

Gtk.main()

rawDescription: How can I create a GTK ComboBox with images in Python?

description: Create a GTK ComboBox with images in Python


code:
for p in self.tree.xpath('//body/p'):
    if p.tail is None:  # some conditions specifically for my doc
        children = p.getchildren()
        if len(children)>1:
            for child in children:
                #if other stuffs present, break
                if child.tag!='strong' or child.tail is not None:
                    break
            else:
                # If not break, we find a p block to fix
                # Get rid of stuffs inside p, and put a SubElement in
                etree.strip_tags(p,'strong')
                tmp_text = p.text_content()
                p.clear()
                subtext = etree.SubElement(p, "strong")
                subtext.text = tmp_text

rawDescription: Combine multiple tags with lxml

description: Combine multiple tags with lxml


code:
import web
from beaker.middleware import SessionMiddleware

urls = (
         '/', 'index',
         '/login', 'Login',
         '/logout', 'Logout'
        )

t_globals = {
             'datestr': web.datestr,
             'str': str,
             'datetime': datetime
             }

# beaker options are optional.... but it's good to see
# where they are called

session_opts = {
    'session.cookie_expires': True,
    'session.timeout' : 600,
    'session.secure' : True,
}

# define webPy app
app = web.application(urls, globals())

# smash it all together and define name for cookie key (sid)
def session_mw(app):
    return SessionMiddleware(app, config = session_opts, key = "sid")

# function to check if we are logged in
def logged(session):
    if 'login' in session:
        if session['login']==1:
            return True
        else:
            return False
    else:
        return False

# create different renders based on log in privilege
def create_render(privilege):
    session = web.ctx.environ['beaker.session']
    if logged(session) == True:
        if privilege == 0:
            render = web.template.render('/templates/user/', base='user_base', globals=t_globals)
        elif privilege == 1:
            render = web.template.render('/templates/user/', base='user_base', globals=t_globals)
        elif privilege == 2:
            render = web.template.render('/templates/admin/', base='base', globals=t_globals)
        else:
            render = web.template.render('/templates/viewer/', base='base', globals=t_globals)
    else:
        render = web.template.render('templates/', globals=t_globals)
    return render

class Login:
    def GET(self):
        session = web.ctx.environ['beaker.session']
        if logged(session) == True:
            render = create_render(session['privilege'])
            return render.index()
        else:
            render = create_render(0)
            return render.login()

   # I get user credentials from a database (called in model.get_users)
        def POST(self):
            session = web.ctx.environ['beaker.session']
            data= web.input()
            name = data['user']
            passwd = data['passwd']
            ident = model.get_users(m, name)
            try:
                if passwd == ident.password.strip():
                    session['login'] = 1
                    session['privilege'] = ident['privilege']
                    session['user'] = name
                    session.save()
                    render = create_render(session['privilege'])
                    return render.index()

                else:
                    session.login = 0
                    session.privilege = 0
                    session.user = 'none'
                    render = create_render(session['privilege'])
                    return render.login()
            except:
                session['login'] = 0
                session['privilege'] = 0
                render = create_render(session['privilege'])
                return render.login()

    class Logout:
        def GET(self):
            session = web.ctx.environ['beaker.session']
            try:
                render = create_render(0)
                session.invalidate()
                session.delete()
                return render.logout()
            except:
                session.invalidate()
                session.delete()
                render = create_render(0)
                return render.logout()

    class index:
        def GET(self):
            session = web.ctx.environ['beaker.session']
            if logged(session) == False:
                raise web.seeother('/login')
            else:
                render = create_render(0)
                return render.index()

    if __name__ == "__main__":
        app.run(session_mw)

rawDescription: webPy Sessions - Concurrent users use same session and session timeout

description: WebPy Sessions - Concurrent users use same session and session timeout


code:
rows = [
    ['Dan Danson', '1', '6', '9'],
    ['John Johnson', '5', '7', '10'],
    ['Mike Mikeson', '10', '7', '6'],
]
rows = [row[:1] + sorted(row[1:], key=int, reverse=True) for row in rows]
sorted(rows, key=lambda row: sum(map(int, row[1:])), reverse=True)

rawDescription: Python - Ordering Number Values in a List Containing Strings and Numbers


code:
import os
os.chdir('../dir')

rawDescription: Take user input to navigate to a directory


code: {{ theInfo if public else 'this info is hidden' | safe }}

rawDescription: Flask html not rendered when using Jinja2 templating tag


code: os.startfile("path/to/file") # may only work on Windows

rawDescription: Display a file to the user with Python

description: Display a file to the user with Python


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

a=np.random.uniform(0,1,1600).reshape((40,40))
fig, ax = plt.subplots(1,1)
ax.matshow(a, vmin = 0, vmax = 1, interpolation = 'none')
tick_list = np.append(np.arange(0,40,5), 39)
label_list=map(lambda x: str(0.05*x), tick_list)
ax.set_xticks(tick_list)
ax.set_xticklabels(label_list)
ax.set_yticks(tick_list)
ax.set_yticklabels(label_list)
plt.show()

rawDescription: matshow in python with extents that make ticks in the middle of squares

description: Matshow in python with extents that make ticks in the middle of squares


code:
class myDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.tableWidget=QTableWidget()
        l=QVBoxLayout()
        l.addSpacing(290)
        l.setContentsMargins(0,0,0,0)
        l.addWidget(self.tableWidget)
        self.setLayout(l)

rawDescription: PyQt5: QTableWidget rezizing with parent window


code:
import threading

class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.is_playing = False
        self.pack()
        self.widgets()

    def widgets(self):
        self.beep = Button(self, text = "Beep", command = self.play_beep)
        self.beep.pack()
        self.stop = Button(self, text = "Stop", command = self.stop_beep)
        self.stop.pack()

    def play_beep(self):
        self.is_running = True
        self.beep_th = threading.Thread(target=self.run)
        self.beep_th.start()

    def run(self):
        count = 10
        while self.is_running == True and count != 0:
            winsound.Beep(randint(100, 2500), 200)
            count -= 1

    def stop_beep(self):
        try:
            self.is_running = False
            self.beep_th.join(0)
            self.beep_th = None
        except (AttributeError, RuntimeError): # beep thread could be None
            pass

    def closeEvent(self, event): # This is a pyside method look for a TKinter equivalent.
        """When you close the App clean up the thread and close the thread properly."""
        self.stop_beep()
        super().closeEvent(event)

rawDescription: How to interrupt a thread/process by making a correct "Stop" button in Tkinter (Python)?

description: Interrupt a thread/process by making a correct "Stop" button in Tkinter (Python)


code: a = a[~np.isnan(a)]

rawDescription: "isnotnan" functionality in numpy, can this be more pythonic?


code:
exitId = wx.NewId()
self.Bind(wx.EVT_MENU, self.onExit, id=exitId )

accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('W'), exitMenuItem.GetId()) ])
self.frame.SetAcceleratorTable(accel_tbl)

rawDescription: Using Command-W or Control-W to close a Frame


rawDescription: Type checking of arguments Python

description: Type checking of arguments Python


code:
import urllib2
from django import http

def some_django_view(request):
    fh = urllib2.urlopen('http://your_php_page/?' + request.GET.urlencode())
    return http.HttpResponse(fh.read())

rawDescription: Converting PHP to django in stages

description: Converting PHP to django in stages


code: [s[i] + s[i+1] for i in range(0, len(s), 2)]

rawDescription: How to merge lists by two together?

description: Merge lists by two together


code:
def is_square(o):
    # If o is empty, it's a square - that takes care of the True
    # Otherwise, ensure that each of the elements inside o
    # contains the same number of elements as o itself.
    # To do that you just need to compare the length of each element with the length of o
    total_length = len(o)
    return all(len(elem) == total_length for elem in o)

# A somewhat more verbose equivalent would be as follows:
def is_square(o):
    total_length = len(o)
    for elem in o:
        # If there's any sublist that has a different length from the total, return False and we're done
        if len(elem) != total_length:
            return False
    # Empty lists and anything that made past that loop must be a square
    return True

o1 = [[True,False,False],[False,False,False],[True,False,False]]
o2 = [[True,False,False],[False,False,False]]
o3 = [[True],[False,False],[True,False,False]]

for o in o1, o2, o3:
    print(is_square(o))

rawDescription: How to define a function that checks if a given list of booleans creates a square

description: Define a function that checks if a given list of booleans creates a square


code:
a = np.arange(1, 4)
b = np.arange(4, 6)
np.insert(np.resize(a, (b.shape[0], a.shape[0])), 2, b, axis=1)

rawDescription: Forming matrix from 2 vectors in Numpy, with repetition of 1 vector


code:
import os, sys
if os.isatty(sys.stdout.fileno()):
    ...

rawDescription: Checking for interactive shell in a Python script


code:
import re
s = """aaaaaaGET(abc)aaaaaa
aaaaaaaaaaaaa
aaaaaMATCH(00)aaaaaaa
aaaaaaaaaaaaa
aaaaGEX(xyz)aaaaaa
aaaaaaGET(notneed)aaaaaa
aaaaaaGEX(no)aaaaaa
aaaaaaGET(nope)aaaaaa
aaaaaaGET(AbC)aaaaaa
aaaaaaaaaaaaa
aaaaaaaaaaaaa
aaaaaMATCH(01)aaaaaaa
aaaaaaaaaaaaa
aaaaGEX(XYz)aaaaaa"""
m = re.findall(r'GET.*?\(([^)]*)\)(?:(?!GET|GEX).)*?\(([^)]*)\)(?:(?!GET|GEX).)*?GEX\(([^)]*)\)', s, re.DOTALL)
m

rawDescription: Python/RegEx/findall: How do I extract a pattern from behind the match?


code:
sock = httplib.HTTPConnection('server.com', 80)
data = "op=a_login_attempt"
headers = { "Host":"server.com",
            "Content-Type":"application/x-www-form-urlencoded; charset=UTF=8",
            "Referer":"server2.com",
            "Cookie":"session=12345678",}
sock.request("POST", '/login.php', data, headers)

rawDescription: Java setRequestHeader in Python

description: Java setRequestHeader in Python


code:
import locale

locale.setlocale(locale.LC_ALL, "")
a=sorted(list(ref_list.items()), key=lambda x: locale.strxfrm(x[1][0]))
sorted_ref_list=sorted(a, key=lambda x: locale.strxfrm(x[1][1]))

rawDescription: Complex subsorts on dictionary of arrays with Unicode


code:
def weightedL2(a,b,w):
    q = a-b
    return np.sqrt((w*q*q).sum())

rawDescription: Euclidean distance with weights

description: Euclidean distance with weights


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

points = [(3.28,0.00),(4.00,0.50),(4.40,1.0),(4.60,1.52),(5.00,2.5),(5.00,3.34),(4.70,3.8)]
points = points + [(4.50,3.96),(4.20,4.0),(3.70,3.90),(3.00,3.5),(2.00,2.9)]
data = np.array(points)

tck,u = interpolate.splprep(data.transpose(), s=0)
unew = np.arange(0, 1.01, 0.01)
out = interpolate.splev(unew, tck)

plt.figure()
plt.plot(out[0], out[1], color='orange')
plt.plot(data[:,0], data[:,1], 'ob')
plt.show()

rawDescription: How to draw cubic spline in matplotlib

description: Draw cubic spline in matplotlib


code:
text = ['Andy Fennimore Cooper\n', 'Peter, Paul, and Mary\n','Andy Gosling\n']
data=' '.join(e.strip('\n,.') for e in ''.join(text).split()).split()
data
[e for e in data if data.count(e)==1]
list({e for e in data if data.count(e)==2})

rawDescription: Keeping a count of words in a list without using any count method in python?


code:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://www.cmohs.org/search-results.php?q=&x=40&y=9&rank=Musician&organization=&division=&company=&conflict=')

# get hrefs
view_links = driver.find_elements_by_class_name('recipientView')
for index, view in enumerate(view_links):
    html = view.get_attribute('innerHTML')
    href = html.split('"')[1]

    view_links[index] = href

# visit each href and get data
for href in view_links:
    driver.get(href)

    detail_data = driver.find_elements_by_class_name('dataBar')
    for detail in detail_data:
        print(detail.text)

rawDescription: Assistance with selenium web scraping

description: Assistance with selenium web scraping


code:
import csv
from collections import Counter
from itertools import imap
from operator import  itemgetter

with open('yourcsv') as f:
    next(f) # skip the header
    cn = Counter(imap(itemgetter(2), csv.reader(f)))

    for t in cn.iteritems():
        print("{} appears {} times".format(*t))

rawDescription: Count the frequency of words from a column in Python using external csv file


code:
l = documents.items()
l.sort(key=lambda x: x[1]['weight'], reverse=True)
result = [d[0] for d in l]

rawDescription: Sorting with a python dictionary

description: Sorting with a python dictionary


code:
s = "{a}|{b}.{c}.{a}"
import string
formatter = string.Formatter()
[item[1] for item in formatter.parse(s)]

rawDescription: List of variable inside a string

description: List of variable inside a string


rawDescription: python - How to remove some tags

description: Python - How to remove some tags


code:
from Tkinter import *

def com1():
    print ('activate')
    b1.config(state = ACTIVE)
    b2.config(state = DISABLED) #toggles the buttons

def com2():
    print('de-activate')
    b1.config(state = DISABLED)
    b2.config(state = ACTIVE) #toggles the buttons

def win():
    global b1
    global b2 #This is to allow passing b1 and b2 to com1 and com2, but may not be the most "efficient" way to do this...
    window = Tk()
    window.geometry ('500x500')
    b1 = Button(text = 'Disabled', pady = '10', padx = '10', state = DISABLED, command = com2) #command com2 added here
    b1.place(x = 100, y = 10)
    b2 = Button(text = 'activate', pady = '10', padx = '10', command = com1) #com changed to com1
    b2.place(x = 10, y = 10)

    window.mainloop()

win()

rawDescription: Wierd material glitch in blender

description: Wierd material glitch in blender


code:
import sys

class NonEmptyClassTest(unittest.TestCase):
    def _makeOne(self, clear=False):
        if clear:
            try:
                del sys.modules['module_name']
            except KeyError:
                pass
        from module_name import NonEmptyClass
        return NonEmptyClass

    def test_makeName(self):
        nec = self._makeOne(clear=True)
        nec.addName("Fred")
        nec.printAllData()
        self.assertEquals(1 , len(nec.dummy_data))

    def test_makeName_1(self):
        nec = self._makeOne(clear=True)
        nec.addName("Fred")
        nec.printAllData()
        self.assertEquals(1 , len(nec.dummy_data))

rawDescription: Remove reference to Python class between unittests


code: {{ value.time.date }}

rawDescription: Remove time in date time function?

description: Remove time in date time function


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

def data_gen():
    t = data_gen.t
    cnt = 0
    while cnt < 1000:
        cnt+=1
        t += 0.05
        y1 = np.sin(2*np.pi*t) * np.exp(-t/10.)
        y2 = np.cos(2*np.pi*t) * np.exp(-t/10.)
        # adapted the data generator to yield both sin and cos
        yield t, y1, y2

data_gen.t = 0

# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(2,1)

# intialize two line objects (one in each axes)
line1, = ax1.plot([], [], lw=2)
line2, = ax2.plot([], [], lw=2, color='r')
line = [line1, line2]

# the same axes initalizations as before (just now we do it for both of them)
for ax in [ax1, ax2]:
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 5)
    ax.grid()

# initialize the data arrays
xdata, y1data, y2data = [], [], []
def run(data):
    # update the data
    t, y1, y2 = data
    xdata.append(t)
    y1data.append(y1)
    y2data.append(y2)

    # axis limits checking. Same as before, just for both axes
    for ax in [ax1, ax2]:
        xmin, xmax = ax.get_xlim()
        if t >= xmax:
            ax.set_xlim(xmin, 2*xmax)
            ax.figure.canvas.draw()

    # update the data of both line objects
    line[0].set_data(xdata, y1data)
    line[1].set_data(xdata, y2data)

    return line

ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
    repeat=False)
plt.show()

rawDescription: animated subplots using matplotlib

description: Animated subplots using matplotlib


code:
class IterRegistry(type):
    def __new__(cls, name, bases, attr):
        attr['_registry'] = {} # now every class has it's own _registry
        return type.__new__(cls, name, bases, attr)

rawDescription: python: defining registry in base class

description: Python: defining registry in base class


code:
paste

df
df.fillna(0)
df2 = df
df2.fillna(0)
df2  # note how this is unchanged.
df.fillna(0, inplace=True)  # this will replace the values.
df

rawDescription: Pandas .fillna() not filling values in DataFrame in Python 3


code:
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyForm,self).__init__(parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.mdiArea.addSubWindow(self.ui.subwindow)
        self.ui.mdiArea.addSubWindow(self.ui.subwindow_2)
        QtCore.QTimer.singleShot(10, lambda: self.ui.mdiArea.setActiveSubWindow(self.ui.mdiArea.subWindowList()[0]))

        self.ui_weights = [getattr(self.ui,'wt%d'%i) for i in range(1,5)]
        self.ui_cas = [
            [getattr(self.ui,'ca%d_%d'%(row,i)) for i in range(1,5)]
            for row in range(1,21)
        ]
        self.ui_cawas = [getattr(self.ui,'ca_wa_%d'%row) for row in range(1,21)]
        for wt in self.ui_weights:
            wt.editingFinished.connect(self.runBoth)
        for row in self.ui_cas:
            for cell in row:
                cell.editingFinished.connect(self.waCalc)

    def runBoth(self):
        self.wtResult()
        self.waCalc()

    def wtResult(self):
        result = sum(float(wt.text() or 0) for wt in self.ui_weights)
        self.ui.wt_total.setText(str(result))

    def waCalc(self):
        for row, wa in zip(self.ui_cas,self.ui_cawas):
            result = sum(
                float(ca.text() or 0) * float(wt.text() or 0)
                for ca,wt in zip(row, self.ui_weights)
            )
            wa.setText(str(result))

rawDescription: Is there a more elegant or simple way to accomplish my goal?


code: module.testVars = [1, 2, 3, "foo"]

rawDescription: How to pass variables using Unittest suite

description: Pass variables using Unittest suite


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

Base= declarative_base()

_usergroup_table = Table('usergroup_table', Base.metadata,
    Column('user_id',  Integer, ForeignKey('user.id')),
    Column('group_id', Integer, ForeignKey('group.id')))

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(60), nullable=False, unique=True)
    group_id = Column(Integer, ForeignKey('group.id'), nullable=False)
    primary_group = relationship("Group")

    @validates('primary_group')
    def _add_pg(self, key, target):
        self.groups.add(target)
        return target

    @validates('groups', include_removes=True)
    def _modify_groups(self, key, target, is_remove):
        if is_remove and target is self.primary_group:
            del self.primary_group
        return target

class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String(60), nullable=False)
    users = relationship('User', secondary=_usergroup_table,
                            backref=backref('groups', collection_class=set))

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

s = Session(e)

g1, g2, g3 = Group(name='g1'), Group(name='g2'), Group(name='g3')
u1 = User(name='u1', primary_group=g1)

u1.groups.update([g2, g3])

s.add_all([
    g1, g2, g3, u1
])
s.commit()

u1.groups.remove(g1)
assert u1.primary_group is None
u1.primary_group = g2
s.commit()

rawDescription: Sqlalchemy: One to Many relationship combined with Many to Many relationship


code:
def table_all():
    for line in range(1,13):
        for table in range(1,13):
            print(line * table, end=" ")
        print("\n")

rawDescription: Printing times tables: How do I add a new line between results?


code:
str = "" # byte stream for encoding data
str += struct.pack("5f i", vert1.x, vert1.y, vert1.z, vert1.u, vert1.v, vert1.color) # 5 floats and an int
# same for other vertices

device. ReadVertices( verts, 3) # send vertices to C library

rawDescription: Pass array of structs from Python to C

description: Pass array of structs from Python to C


code:
worksheet2.conditional_format(color_range2, {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 0, 'format': perc_fmt})
worksheet2.conditional_format(color_range2, {'type': 'cell',
                                     'criteria': '<',
                                     'value': 0, 'format': perc_fmt})

rawDescription: xlswriter formatting a range

description: Xlswriter formatting a range


code:
import os, types
isinstance(os, types.ModuleType)

rawDescription: how to isinstance(x, module)?

description: Isinstance(x, module)


code:
class chest():
    openCount = 0
    openFunctions = [
                        function1,
                        function2,
                        function3,
                        ...
                    ]

    def use(self):
        self.openFunctions[openCount]
        self.openCount += 1

rawDescription: How do I create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python?

description: Create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python


code:
def file_open(self):
    name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
    qp = QtGui.QPixmap(name)
    self.ql = QtGui.QLabel(None)
    self.ql.setPixmap(qp)
    self.ql.move(200,200)
    self.ql.show()

rawDescription: How to load a file in PyQt4?

description: Load a file in PyQt4


code:
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "proxy.server.address")
profile.set_preference("network.proxy.http_port", "port_number")
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)

rawDescription: Running selenium behind a proxy server

description: Running selenium behind a proxy server


code:
from subprocess import Popen, PIPE

sh = Popen("sudo %s" % bf_path, shell=True, stdout=PIPE, stderr=PIPE)

rawDescription: Use python to run shell script with Popen behaves differently in python command line and actual program


code:
from collections import deque
stack = deque()
stack.append(10)
stack.append(20)
stack.append(30)
stack
stack.pop()           # LIFO
stack.pop()

queue = deque()
queue.append(10)
queue.append(20)
queue.append(30)
queue
queue.popleft()       # FIFO
queue.popleft()

rawDescription: Understanding Stacks and Queues in python


code:
import re
...
def playlist_url(self):
    """
    Generates a playlist URL
    """
    new_url = re.sub(r'^(http:\/\/)([\w\W]+)&list=([\w\W]+)(\&index=[\d]+)$', r'//\2?list=\3', self.video_url)
    return new_url
...

rawDescription: django - replace parts of urlfield

description: Django - replace parts of urlfield


code:
sentence = "The quick brown fox jumps over the bridge"
vowels = "aeiouAEIOU"
finalVowel = []

# Return True if arg is in vowels; otherwise, return False
isVowel = lambda arg: arg in vowels

def vowelFilter(sentence):
    for letter in sentence:
        if isVowel(letter):  # Call the lambda to test if letter is a vowel
            finalVowel.append(letter)
    return finalVowel

print (vowelFilter(sentence))

rawDescription: Python vowel filter, appending to string


code:
c=db.cursor()
c.execute("""select * from table""")
output = []
for row in c:
    output.append(float(row[4]))

rawDescription: get raw decimal value from mysqldb query

description: Get raw decimal value from mysqldb query


code:
x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
x_formatter.set_scientific(False)
ax.xaxis.set_major_formatter(x_formatter)

rawDescription: How to change matplotlib axes so that that it does not display in scientific notation?

description: Change matplotlib axes so that that it does not display in scientific notation


code:
word = "because"
print(word[0])  # Prints "b"
print(word[1])  # Prints "e"
print(word[2])  # Prints "c"
print(word[3])  # Prints "a"
print(word[4])  # Prints "u"
print(word[5])  # Prints "s"
print(word[6])  # Prints "e"

rawDescription: Is it possible to change a whole word into multiple letter variables?


code:
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt

im = scipy.misc.imread('all_blobs.png',flatten=1)
im, number_of_objects = ndimage.label(im)
blobs = ndimage.find_objects(im)

plt.imsave('blobs.png', im)
for i,j in enumerate(blobs):
    plt.imsave('blob'+str(i)+'.png',im[j])

rawDescription: how after ndimage.find_object ... color features?

description: How after ndimage.find_object ... color features


code:
from __future__ import  division   # not required in py3.x

func_apply(my_minus, x=[2, 4, 5, 7], y=[1, 4, 3, 9])
func_apply(my_divd,  a=[2, 4, 5, 7], b=[1, 4, 3, 9])

rawDescription: How to collectively send the parameter to a Python function and collect the result in list?

description: Collectively send the parameter to a Python function and collect the result in list


code:
def __iter__(self):
    for elt in self.l:
        yield elt

rawDescription: Iterating through a class python

description: Iterating through a class python


code:
from bs4 import BeautifulSoup
markup = 'this text is red'
soup = BeautifulSoup(markup)
soup.font
new_tag = soup.new_tag('span')
new_tag['style'] = 'color: ' + soup.font['color']
new_tag.string = soup.font.string
soup.font.replace_with(new_tag)
soup

rawDescription: Using python/BeautifulSoup to replace HTML tag pair with a different one


code: B = filter(lambda x: abs(x) != float('inf'), A)

rawDescription: How can I make array B from array A without infinities included in Python 2.7?

description: Make array B from array A without infinities included in Python 2.7


code:
import networkx as nx
def is_tree(G):
    if nx.number_of_nodes(G) != nx.number_of_edges(G) + 1:
        return False
    return nx.is_connected(G)

if __name__ == '__main__':

    print(is_tree(nx.path_graph(5)))
    print(is_tree(nx.star_graph(5)))
    print(is_tree(nx.house_graph()))

rawDescription: Check if an undirected graph is a tree in networkx


code:
import logging
import sys

from ghost import Ghost, TimeoutError

logging.basicConfig(level=logging.INFO)

url = "http://www.six-structured-products.com/en/search-find/new-search#search_type=profi&class_category=svsp"

ghost = Ghost(wait_timeout=20, log_level=logging.CRITICAL)
data = dict()

def extract_value(line, ntd):
    return line.findFirst('td.DataItem:nth-child(%d)' % ntd).toPlainText()

def extract(ghost):
    lines = ghost.main_frame.findAllElements(
        '.derivativeSearchResult > tbody:nth-child(2) tr'
    )

    for line in lines:
        symbol = extract_value(line, 2)
        name = extract_value(line, 5)
        logging.info("Found %s: %s" % (symbol, name))
        # Persist data here

    ghost.sleep(1)

    try:
        ghost.click('.pagination_next a', expect_loading=True)
    except TimeoutError:
        sys.exit(0)

    extract(ghost)

ghost.open(url)
extract(ghost)

rawDescription: Scrape data with Ghost

description: Scrape data with Ghost


code:
verification_email = 'fed@test.free.com'
pattern = r'.*@(test.free.com|free.com.au|free.com.au.org|free.com.org)$'

import re
if re.search( pattern , verification_email):
    print('yes')
    # or on your case, return 'yes'

rawDescription: How to verify a domain with an email contain the domain

description: Verify a domain with an email contain the domain


rawDescription: Unable to find font cache of matplotlib on a mac


code:
N = 10
arr_bool = np.random.random_integers(0,1,(N,N))
arr_val  = np.random.rand(N,N)
imshow(arr_bool*arr_val, cmap = cm.spectral_r, interpolation = 'nearest')

rawDescription: color certain points a different color matrix matplotlib

description: Color certain points a different color matrix matplotlib


code:
# list of tuples
mkp1 = [(1, 2), (3, 4), (5, 6)]
mkp2 = [(10, 20), (30, 40), (50, 60)]

# zip this list
pairs = zip(mkp1, mkp2)

# unzip this list
p1, p2 = [], []
for kpp in pairs:
    p1.append(kpp[0])
    p2.append(kpp[1])

print('p1:', p1)
print('p2:', p2)

rawDescription: Python 3 zip list unpacking

description: Python 3 zip list unpacking


code:
import subprocess
import requests
import shutil
import glob
import json

audio = requests.get('http://somesite.com/some.mp3')
sox = shutil.which('sox') or glob.glob('C:\Program Files*\sox*\sox.exe')[0]
p = subprocess.Popen(sox + ' -t mp3 - -t flac - rate 16k', stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True)
stdout, stderr = p.communicate(audio.content)
url = 'http://www.google.com/speech-api/v2/recognize?client=chromium&lang=en-US&key=AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw'
headers = {'Content-Type': 'audio/x-flac; rate=16000'}
response = requests.post(url, data = stdout, headers = headers).text

result = None
for line in response.split('\n'):
    try:
        result = json.loads(line)['result'][0]['alternative'][0]['transcript']
        break
    except:
        pass

rawDescription: MP3 to FLAC for Google's Speech API

description: MP3 to FLAC for Google's Speech API


code:
from bs4 import BeautifulSoup
import urllib.request
from collections import *
from statistics import mean
import time
import re

list_url=[]

url = 'http://m.zooplus.co.uk/shop/pet_food/royal_canin_food/rc_size_dog'
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html,"html.parser")
rows = soup.find_all('li',{'class':re.compile('list-item.*')})

for row in rows:
    cls=row.attrs.get("class")
    if not ("highlighted" in cls):
        print(row.text)

rawDescription: Beautiful Soup can't make the difference between CSS class


rawDescription: Converting a binary string to a binary number as to perform binary arithmetic


code: next((x for x in testSet if x["ID"] == 230), None)

rawDescription: python - search for an element inside a dictionary inside a list

description: Python - search for an element inside a dictionary inside a list


rawDescription: Python pandas groupby aggregation

description: Python pandas groupby aggregation


code:
'hello'.isspace()
'  \n\t  '.isspace()

rawDescription: Python: regular expressions in control structures


code:
cost = driver.find_element_by_css_selector("input.cost-total")
print(cost.get_attribute("value"))

rawDescription: Python Selenium Web Scrapping - Hidden Text / Javascript?


code:
data = 'word,length\nTr\xe4umen,7\nGr\xfc\xdfe,5'
df = pd.read_csv(StringIO(data), encoding='latin-1')
df
df['word'][1]

rawDescription: Importing text with pandas/python

description: Importing text with pandas/python


code:
re.search('tune[ -]yards', '58 tune yards of music')
re.search('tune[ -]yards', '35 tune-yards of trombone')

rawDescription: Make two characters equivalent in a Python find() call


code:
import arcpy

# Your input feature class
fc = r'C:\path\to\your.gdb\feature_class'

# Start an update cursor and change values from 0 to 100 in a field called "your_field"
with arcpy.da.UpdateCursor(fc, "your_field") as cursor:
    for row in cursor:
        if row[0] == 0:
            row[0] = 100
        cursor.updateRow(row)

rawDescription: How to replace values in an attribute table for one column?

description: Replace values in an attribute table for one column


code:
rounds = 0
rounds2= 0
loop=1
while True:
    if loop==1:
        if rounds == 1:
            print('A')
        elif rounds == 2:
            print('B')
        else:
            rounds = 0
        rounds = rounds + 1
        loop=2
    if loop==2:
        if rounds2 == 1:
            print('a')
        elif rounds2 == 2:
            print('b')
        else:
            rounds2 = 0
        rounds2 = rounds2 + 1
        loop=1

rawDescription: How do I run multiple while loops that switch off after each loop round?

description: Run multiple while loops that switch off after each loop round


code: return x or "default"

rawDescription: Is there shorthand for returning a default value if None in Python?


code:
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Test')

# A1: no style, no wrap, despite newline
sheet.write(0, 0, 'Hello\nWorld')

# B1: with style, there is wrap
style = xlwt.XFStyle()
style.alignment.wrap = 1
sheet.write(0, 1, 'Hello\nWorld', style)
book.save('test.xls')

rawDescription: Writing multi-line strings to cells using xlwt module


code: col2 = i[1].strip()

rawDescription: Python dropping white space

description: Python dropping white space


code:
@api.multi
@api.depends('vote_partner_ids.type')
def compute_type(self):
    for record in self:
        if self.vote_partner_ids.type:
            record.vote_history_ids = [(0, 0, {'fieldA': self.vote_partner_ids.type + 4,
                                                'fieldB': self.vote_partner_ids.type - 2})]

rawDescription: Odoo : Value in one2many doen't change in api.depends


rawDescription: Groupby based on value in previous row

description: Groupby based on value in previous row


code:
class LinkedList(object):
    def __init__(self, head=None):
        self.head = head

    def empty(self):
        return self.head is None

    def insert(self, data):
        new_node = Node(data)    # Want to insert this
        if self.empty():         # Is this list empty?
            self.head = new_node #   Yes? Then add the head
        else:                    # No? There are elements in the list
            current_node = self.head                    # Save a moving reference
            while not current_node.get_next() is None:  # While there are forward nodes
                current_node = current_node.get_next()  # Move the reference forward
            current_node.set_next(new_node)             # Set the last node, thus inserting at the "end"

rawDescription: Trouble with forward linked list

description: Trouble with forward linked list


code:
button = gui.Button("Start", width = 200)

button = gui.Button("Start", height = 100)

button = gui.Button("Start", width = 200, height = 100)

rawDescription: How to make a fixed size button with PGU

description: Make a fixed size button with PGU


code:
numbers = [192829, 88288, 912, 1992, 2828, 38]
for number in numbers:
    print("{0:{1}d}".format(number,len(str(max(numbers)))))

rawDescription: format numbers with variable length

description: Format numbers with variable length


rawDescription: Reversible hash function?

description: Reversible hash function


code:
for line in hapinfile:
    q=line.rstrip('\n').rstrip('\r').split('\t')
    g=q[0:11]
    if g[0] in dictoutfile:
        g.extend( dictoutfile[g[0]] )
        o.write(str('\t'.join(g)+'\n'))

rawDescription: simple python script running very slow (csv file)

description: Simple python script running very slow (csv file)


code: setattr(self.instance, key, self.saving_path + self.slug + '_' + key + '.' + self.image_format)

rawDescription: Using a dictionary (or other structure) key in a variable name


code:
class MyModel(models.Model):
    field1 = models.BlahField()
    field2 = models.FooField()
    field3 = models.BazField()

    class Meta:
        unique_together = ("field1", "field2")

rawDescription: How to specify uniqueness for a tuple of field in a Django model

description: Specify uniqueness for a tuple of field in a Django model


code:
def parsemsg(s):
    """Breaks a message from an IRC server into its prefix, command, and arguments.
    """
    prefix = ''
    trailing = []
    if not s:
       raise IRCBadMessage("Empty line.")
    if s[0] == ':':
        prefix, s = s[1:].split(' ', 1)
    if s.find(' :') != -1:
        s, trailing = s.split(' :', 1)
        args = s.split()
        args.append(trailing)
    else:
        args = s.split()
    command = args.pop(0)
    return prefix, command, args

parsemsg(":test!~test@test.com PRIVMSG #channel :Hi!")
# ('test!~test@test.com', 'PRIVMSG', ['#channel', 'Hi!'])

rawDescription: Python & parsing IRC messages

description: Python & parsing IRC messages


code:
if first_int % 2 == 0 and second_int % 2 == 0:
    print ("Both even")
else:
    print("Not Both Even")

rawDescription: Finding Even Numbers In Python

description: Finding Even Numbers In Python


code:
import json
from getdata.models import record_search

query_data = record_search.objects.filter(**filter_kwargs) \
                          .values("id", "domain", "record", "record_points_to",
                                  "priority_mx", "ttl", "generated_on")
data = json.dumps(list(query_data))

rawDescription: Python Django json serialise

description: Python Django json serialise


rawDescription: how to arrange a list in the order of index od another sorted list in python?

description: Arrange a list in the order of index od another sorted list in python


code:
import os
os.environ['JAVA_HOME']

rawDescription: read from .bash_profile via python

description: Read from .bash_profile via python


code:
n = int(input("Enter a positive integer value: "))
for i in range(n, 0, -1):
    if i == 1 or i == n:
        print("*" * i)
    else:
        print("*" + (" " * (i - 2)) + "*")

rawDescription: How to print this pattern? I cannot get the logic for eliminating the middle part

description: Print this pattern? I cannot get the logic for eliminating the middle part


code:
q = Ticket.objects.extra(select={'is_top': "status = 4"})
q = q.extra(order_by = ['-is_top'])

rawDescription: Can Django ORM do an ORDER BY on a specific value of a column?


rawDescription: PyPlot- Manipulating the y axis without explicitly setting the range (setting the number of ticks and "round" numbers)


code:
def firstline_to_list(fvar):
    """
    Input tab separated file.
    Output first row as list.
    """
    import csv, sys

    with open(fvar, 'r') as tsvfile:
        tabreader = csv.reader(tsvfile, delimiter='\t')
        try:
            if sys.version > '3':
                result = next(tabreader)
            else:
                result = tabreader.next()
        except StopIteration:
            result = None

    return result

rawDescription: Pythonic way to extract first line of a tabular file to a list


code:
import cx_Oracle

dsn = cx_Oracle.makedsn(host, port, sid)
db = cx_Oracle.connect(user, password, dsn)

rawDescription: connect to oracle9i using python2.7 on ubuntu 64bit

description: Connect to oracle9i using python2.7 on ubuntu 64bit


code:
import random
L = range(100)
amount = 10
[random.choice(L) for _ in range(amount)]

rawDescription: How to make a random array in Python?

description: Make a random array in Python


rawDescription: Removing duplicated numbers within tuples


rawDescription: window handling in selenium (python)

description: Window handling in selenium (python)


code:
import os

subprogs = [None] * 4
for i in range(4):
    subprogs[i] = os.popen("app -appnum " + i, "r")

rawDescription: Forking Multiple Apps Under Python Subprocess


code:
import time
time.sleep(5) #wait 5 seconds

rawDescription: Counting time in python?

description: Counting time in python


code: array[array == -9999] = np.nan

rawDescription: Retain numpy mask when inserting arrays

description: Retain numpy mask when inserting arrays


rawDescription: BeautifulSoup doesnt find some elements while they exists


code:
from collections import defaultdict
d = defaultdict(list)
d['key'].append(5)
d
dict(d)

rawDescription: Dictionary with multiple string values for a key


code:
from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

rawDescription: Flask Basic HTTP Auth use login page

description: Flask Basic HTTP Auth use login page


code:
import webbrowser

webbrowser.get("open -a C:\\Program F~\\Mozilla Firefox\\firefox.exe %s")
webbrowser.open('http://google.com')

rawDescription: Python webbrowser - registering browsers on Windows


code:
import re
re.findall(r'foo(?:$|\n)', "foo\nbar\nfood\nfoo")

rawDescription: Can't find the correct regex syntax to match newline or end of string


code:
def what_type(s, possible_types=((int, [0]), (float, ()))):
    for t, xargs in possible_types:
        try: t(s, *xargs)
        except ValueError: pass
        else: return t
    return str

rawDescription: Detect data type from XML string using python


code:
@hosts('host.example.com')
def task():
    if run('echo $SOME_VAR') == 'some value':
        run('some_other_command.sh')

rawDescription: Possible to use conditional execution in Fabric?


code:
#players.py
class Player():
    def __init__(self):
        self.score = 0

#games.py
def checkers(player):
    #blahblahblah dostuff
    player.score += 1
    print(player.score) #if everything goes right, this should print 1

#main.py
from players import player
from games import checkers
player = Player()
checkers(player)
player.score += 1
print(player.score) #if everything goes right, this should print 2

rawDescription: Importing variable not giving the desired value


code:
import os
os.system('clear')

rawDescription: Python clear the screen code?

description: Python clear the screen code


code:
class PickleableStaticMethod(object):
    def __init__(self, fn, cls=None):
        self.cls = cls
        self.fn = fn
    def __call__(self, *args, **kwargs):
        return self.fn(*args, **kwargs)
    def __get__(self, obj, cls):
        return PickleableStaticMethod(self.fn, cls)
    def __getstate__(self):
        return (self.cls, self.fn.__name__)
    def __setstate__(self, state):
        self.cls, name = state
        self.fn = getattr(self.cls, name).fn

rawDescription: Pickling a staticmethod in Python

description: Pickling a staticmethod in Python


code: np.bincount(accmap, weights=a)

rawDescription: Is there a MATLAB accumarray equivalent in numpy?


code:
search = "This is the line I'm looking for.\n"
with open("highscores.txt") as file:
    if any(line == search for line in file):
        print("Found it!")
    else:
        print("Move along.")

rawDescription: How to see if a line exists in a file in python?

description: See if a line exists in a file in python


code:
from time import sleep
from threading import Thread

def some_task():
    while True:
        pass

t = Thread(target=some_task)  # run the some_task function in another
                              # thread
t.daemon = True               # Python will exit when the main thread
                              # exits, even if this thread is still
                              # running
t.start()

snooziness = int(raw_input('Enter the amount of seconds you want to run this: '))
sleep(snooziness)

# Since this is the end of the script, Python will now exit.  If we
# still had any other non-daemon threads running, we wouldn't exit.
# However, since our task is a daemon thread, Python will exit even if
# it's still going.

rawDescription: Running a python script for a user-specified amount of time?


code:
from flask import Flask, url_for

app = Flask(__name__)

def has_no_empty_params(rule):
    defaults = rule.defaults if rule.defaults is not None else ()
    arguments = rule.arguments if rule.arguments is not None else ()
    return len(defaults) >= len(arguments)

@app.route("/site-map")
def site_map():
    links = []
    for rule in app.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters
        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            links.append((url, rule.endpoint))
    # links is now a list of url, endpoint tuples

rawDescription: get a list of all routes defined in the app

description: Get a list of all routes defined in the app


rawDescription: What does this notation do for lists in Python: "someList[:]"?


code:
import os
for i in range(1,10):
    # First clear the screen
    os.system('cls' if os.name == 'nt' else 'clear')
    print('variable 1 value = %s' % i)
    print('variable 2 value = %s' % i+1)
    print('variable 3 value = %s' % i+2)

rawDescription: update printed data debug python

description: Update printed data debug python


code:
import pygame
from pygame.locals import *

grid = [[0, 0, 0, 0, 0],
        [1, 1, 0, 0, 0],
        [0, 1, 0, 1, 1],
        [0, 1, 0, 1, 0],
        [0, 1, 1, 1, 0]]
resolution = (160, 160)
cell_margin = 14
cell_colors = (255, 255, 255), (0, 0, 0)
player_character = "@"
player_color = (255, 0, 0)
player_size = 20
current_position = [0, 1]

def main():
    pygame.init()
    screen = pygame.display.set_mode(resolution)
    screen.fill(cell_colors[1])
    player = pygame.font.Font(None, player_size).render(player_character,
                                                        False, player_color)
    while True:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                key = event.key
                if key == K_UP:
                    move(0, -1)
                elif key == K_RIGHT:
                    move(1, 0)
                elif key == K_DOWN:
                    move(0, 1)
                elif key == K_LEFT:
                    move(-1, 0)
            elif event.type == QUIT:
                return
        draw_maze(screen)
        draw_player(player, screen)
        pygame.display.update()

def draw_maze(screen):
    for row in xrange(len(grid)):
        for column in xrange(len(grid[0])):
            screen.fill(cell_colors[grid[column][row]],
                        get_cell_rect((row, column), screen))

def get_cell_rect(coordinates, screen):
    row, column = coordinates
    cell_width = screen.get_width() / len(grid)
    adjusted_width = cell_width - cell_margin
    return pygame.Rect(row * cell_width + cell_margin / 2,
                       column * cell_width + cell_margin / 2,
                       adjusted_width, adjusted_width)

def draw_player(player, screen):
    rect = player.get_rect()
    rect.center = get_cell_rect(current_position, screen).center
    screen.blit(player, rect)

def move(dx, dy):
    x, y = current_position
    nx, ny = x + dx, y + dy
    if nx >= 0 and nx < len(grid) and ny >= 0 and ny < len(grid[0]) and \
       grid[ny][nx]:
        current_position[0] = nx
        current_position[1] = ny

if __name__ == "__main__":
    main()
    pygame.quit()

rawDescription: Draw Ascii character above rectangle with pygame


code:
import urllib2
request = urllib2.Request('http://diveintomark.org/xml/atom.xml')
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
feeddata = opener.open(request).read()

rawDescription: debugging python web service

description: Debugging python web service


code:
if "Certificate error" in driver.title:
    driver.get("javascript:document.getElementById('invalidcert_continue').click()")

rawDescription: Bypass Security Certificate page on Microsoft Edge for Selenium Webdriver


code:
for form in formset:
    form.instance.user = user
    form.instance.warval = warval

rawDescription: Django:How to instantiate all the forms in the formset?


code:
from pylab import *
xmax = 4.0
xmin = -xmax
D = 20
ymax = 4.0
ymin = -ymax
x = linspace(xmin, xmax, D)
y = linspace(ymin, ymax, D)
X, Y = meshgrid(x, y)
deg = arctan(Y**2 - X)
QP = quiver(X,Y,cos(deg),sin(deg))
show()

rawDescription: Plotting ODEs, Isoclines using Python

description: Plotting ODEs, Isoclines using Python


code:
def choice(options, prompt):
    while True:
        output = input(prompt)    # Use raw_input(prompt) for Python 2.x
        if output in options:
            return output
        else:
            print("Bad option. Options: " + ", ".join(options))

rawDescription: Python equivalent for batch Choice command


rawDescription: What is a good size (in bytes) for a log file?


code:
import subprocess

command = ['pdftk', '-', 'dump_data_fields']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, errorout = p.communicate(input=new_doc_data)

rawDescription: Is it possible to process a file in Django without saving it?


code:
class A(object):
   def __init__(self, attribute1, attribute2):
       self.attribute1 = attribute1
       self.attribute2 = attribute2
a = A(1, 2)
a.attribute1
a.attribute2

rawDescription: Instantiating classes in python - setting attributes


code:
from imagekit.processors import Adjust
Adjust(color=0.5)

rawDescription: Change saturation with Imagekit, PIL or Pillow?


code:
class Model(QtSql.QSqlTableModel):
    def __init__(self, parent=None):
        super(Model, self).__init__(parent)
        self.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)

        self.setTable("test")
        self.select()

    def columnCount(self, parent=QtCore.QModelIndex()):
        # this is probably obvious
        # since we are adding a virtual column, we need one more column
        return super(Model, self).columnCount()+1

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole and index.column()==2:
            # 2nd column is our virtual column.
            # if we are there, we need to calculate and return the value
            # we take the first two columns, get the data, turn it to integer and sum them
            # [0] at the end is necessary because pyqt returns value and a bool
            # http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qvariant.html#toInt
            return sum(self.data(self.index(index.row(), i)).toInt()[0] for i in range(2))
        if index.column() > 2:
            # if we are past 2nd column, we need to shift it to left by one
            # to get the real value
            index = self.index(index.row(), index.column()-1)
        # get the value from base implementation
        return super(Model, self).data(index, role)

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        # this is similar to `data`
        if section==2 and orientation==QtCore.Qt.Horizontal and role==QtCore.Qt.DisplayRole:
            return 'Sum'
        if section > 2 and orientation==QtCore.Qt.Horizontal:
            section -= 1
        return super(Model, self).headerData(section, orientation, role)

    def flags(self, index):
        # since 2nd column is virtual, it doesn't make sense for it to be Editable
        # other columns can be Editable (default for QSqlTableModel)
        if index.column()==2:
            return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable

    def setData(self, index, data, role):
        # similar to data.
        # we need to be careful when setting data (after edit)
        # if column is after 2, it is actually the column before that
        if index.column() > 2:
            index = self.index(index.row(), index.column()-1)
        return super(Model, self).setData(index, data, role)

rawDescription: Virtual column in QTableView?

description: Virtual column in QTableView


code:
s = 'blah\\x2Ddude'

s.encode().decode('unicode-escape')
Out[133]: 'blah-dude'

rawDescription: How do I unescape a unicode escaped string in python?

description: Unescape a unicode escaped string in python


code:
#!/usr/bin/env python
import tarfile
import sys
import hashlib
from contextlib import closing
from functools import partial

try:
    from urllib.request import urlopen
except ImportError: # Python 2
    from urllib2 import urlopen

def md5sum(file, bufsize=1<<15):
    d = hashlib.md5()
    for buf in iter(partial(file.read, bufsize), b''):
        d.update(buf)
    return d.hexdigest()

url = sys.argv[1] # url to download
with closing(urlopen(url)) as r, tarfile.open(fileobj=r, mode='r|*') as archive:
    for member in archive:
        if member.isreg(): # extract only regular files from the archive
            with closing(archive.extractfile(member)) as file:
                print("{name}\t{sum}".format(name=member.name, sum=md5sum(file)))

rawDescription: streaming md5sum of contents of a large remote tarball

description: Streaming md5sum of contents of a large remote tarball


code:
import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup

def changerankscrapper(site):
    """
    Takes a site url, scrapes that site's Alexa page,
    and returns the site's global Alexa rank and the
    change in that rank over the past three months.
    """

    #Create Alexa URL
    url = "http://www.alexa.com/siteinfo/" + site

    #Get HTML
    cj = cookielib.CookieJar()
    mech = mechanize.OpenerFactory().build_opener(mechanize.HTTPCookieProcessor(cj))
    request = mechanize.Request(url)
    response = mech.open(request)
    html = response.read()

    #Parse HTML with BeautifulSoup
    soup = BeautifulSoup(html)

    globalrank = int(soup.find("strong", { "class" : "metricsUrl font-big2 valign" }).text)
    changerank = int(soup.find("span", { "class" : "change-wrapper change-up" }).text)

    return globalrank, changerank

#Example
site = "http://stackoverflow.com/"
globalrank, changerank = changerankscrapper(site)
print(globalrank)
print(changerank)

rawDescription: Possible to get alexa information or google page rankings over time?


code:
car = [
    ["Brand", "Citroen"],
    ["Model", "C4"],
    ["Details", "Lounge"],
    ["shift",
        [
            ["manual","5", "shifts"],
            ["automatic","5", "sequential"],
            ["automatic","5", "paddleshift"]
        ]
    ]
]

print(car)

rawDescription: Include an subarray in array in python

description: Include an subarray in array in python


code:
import cProfile
import cStringIO
import logging
import pstats

def webapp_add_wsgi_middleware(app):

  def profiling_wrapper(environ, start_response):
    profile = cProfile.Profile()
    response = profile.runcall(app, environ, start_response)
    stream = cStringIO.StringIO()
    stats = pstats.Stats(profile, stream=stream)
    stats.sort_stats('cumulative').print_stats()
    logging.info('Profile data:\n%s', stream.getvalue())
    return response

  return profiling_wrapper

rawDescription: How to profile Google App Engine python27 runtime (not python)

description: Profile Google App Engine python27 runtime (not python)


code:
secondLastLine = None
lastLine = None
with open("myfile.txt") as infile:
    secondLastLine, lastLine = infile.readline(), infile.readline()
    for line in infile:
        # do stuff
        secondLastLine = lastLine
        lastLine = line

# do stuff with secondLastLine

rawDescription: Python:Detect if the current line in file read is the last one


code:
from zope.schema import Text, List, Object
from zope.interface import Interface

class IChildInterface(Interface):
    someField = Text()

class IParentInterface(Interface):
    mycollection = List(value_type=Object(title=u'Child',
                                          schema=IChildInterface))

rawDescription: How can a zope.interface.Interface require implementation of a list of objects that implement another interface?


code:
#example
def make_popup(self):
    popupSurf = pygame.Surface(width, height)
    options = ['Attack',
               'Talk']
    for i in range(len(options)):
        textSurf = BASICFONT.render(options[i], 1, BLUE)
        textRect = textSurf.get_rect()
        textRect.top = self.top
        textRect.left = self.left
        self.top += pygame.font.Font.get_linesize(BASICFONT)
        popupSurf.blit(textSurf, textRect)
    popupRect = popupSurf.get_rect()
    popupRect.centerx = SCREENWIDTH/2
    popupRect.centery = SCREENHEIGHT/2
    DISPLAYSURFACE.blit(popupSurf, popupRect)
    pygame.display.update()

rawDescription: How to make a popup radial menu in Pygame?

description: Make a popup radial menu in Pygame


code:
last_state = False
while True:
    x,y = win32api.GetCursorPos()
    state = x < 0
    if state == last_state:
        continue
    last_state = state
    if state:
        print("2")
    else:
        print("1")

rawDescription: Take action when the cursor position crosses a particular x value


code: [(name,type(getattr(math,name))) for name in dir(math)]

rawDescription: Python - dir() - how can I differentiate between functions/method and simple attributes?


code:
def parse_qname(packet):
    components = []
    offset = 0
    while True:
        length, = struct.unpack_from('B', packet, offset)
        offset += 1
        if not length:
            break
        component = struct.unpack_from('{}s'.format(length), packet, offset)
        offset += length
        components.append(component)
    return components, offset

rawDescription: How can I parse a char array with octal values in Python?

description: Parse a char array with octal values in Python


code:
for row in myColl.find():
    row['myvar'] = 123
    myColl.save(row)

rawDescription: Updating each element in collection MongoDB


code:
import re
re.findall(r'""(.*?)""', '"asfdfdfds""O8770""asdsadjieere""tykjkj""ldkflskfd"')

rawDescription: double quote string python

description: Double quote string python


code:
from mock import call, patch

@patch('my_app.views.requests')
def test_response_verify(self, mock_requests):
    # We setup the mock, this may look like magic but it works, return_value is
    # a special attribute on a mock, it is what is returned when it is called
    # So this is saying we want the return value of requests.get to have an
    # status code attribute of 200
    mock_requests.get.return_value.status_code = 200

    # Here we make the call to the view
    response = SubscriptionView().post(request, {'remote_url': 'some_url'})

    self.assertEqual(
        mock_requests.get.call_args_list,
        [call('some_url', params={'verify': 'hello'})]
    )

rawDescription: Python mock, django and requests

description: Python mock, django and requests


code:
wordCheck = raw_input("please enter the word you would like to check the spelling of: ")
with open("words.txt", "r") as f:
    found = False
    for line in f:
        if line.strip() == wordCheck:
            print ('That is the correct spelling for '+ wordCheck)
            found = True
            break
    if not found:
        print ( wordCheck+ " is not in our dictionary")

rawDescription: searching a text file for an inputted word in python

description: Searching a text file for an inputted word in python


code:
def extract(raw_string, start_marker, end_marker):
    start = raw_string.index(start_marker) + len(start_marker)
    end = raw_string.index(end_marker, start)
    return raw_string[start:end]

rawDescription: Python Function To Find String Between Two Markers


code:
import matplotlib.pyplot as plt

x = [0,0,1,0,1,1,0,1,1,0,0,0,1]
plt.bar(range(len(x)), x, align='center')

rawDescription: Histogram in Python

description: Histogram in Python


code:
def decimal_to_base4(num):
    result=""
    while num > 0:
        quotient = num//4
        result+=str(num%4)
        num = quotient
    result = result[::-1]
    print(result, end="")

rawDescription: How to reverse integer values from a while loop?

description: Reverse integer values from a while loop


code:
import os, urlparse
p = urlparse.urlparse('file://C:/test/doc.txt')
finalPath = os.path.abspath(os.path.join(p.netloc, p.path))

rawDescription: Is there a convenient way to map a file uri to os.path?


code:
while aStr.count(',') < Num:
     another = file.readline()
     aStr = aStr + another

rawDescription: How to remove newline within a column in delimited file?

description: Remove newline within a column in delimited file


code:
import pandas as pd

def get_min_max_by_date(df_group):
    if len(df_group['hour'].unique()) < 24:
        new_df = pd.DataFrame()
    else:
        year = df_group['year'].unique()[0]
        j_day = df_group['jday'].unique()[0]
        min_temp = df_group['temp'].min()
        max_temp = df_group['temp'].max()
        new_df = pd.DataFrame({'year': [year],
                               'julian_day': [j_day],
                               'min_temp': [min_temp],
                               'max_temp': [max_temp]}, index=[0])
    return new_df

df = pd.read_table(data,
                   skiprows=1,
                   sep='\t',
                   usecols=(0, 3, 4, 6),
                   names=['year', 'jday', 'hour', 'temp'],
                   na_values=-999.9)

final_df = df.groupby(['year', 'jday'],
                      as_index=False).apply(get_min_max_by_date)
final_df = final_df.reset_index()

rawDescription: If statement in grouped Pandas dataframe


code:
class MyTests(TestCase):

    def setUp(self):
        self.view = BaseView
        with patch.object(self.view, '_get_data', side_effect=view_data_mock):
            self.view_instance = self.view()

    def test_stuff(self):
        self.assertEqual([], self.view_instance.attribute)
        self.assertTrue(self.view_instance.thing)

def view_data_mock(view):
    view.attribute = []
    view.thing = True

rawDescription: how to mock a specific method of a class based View without overriding `self`

description: Mock a specific method of a class based View without overriding `self`


code:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

rawDescription: How to Convert a Text File into a List in Python


code:
import itertools

my_list = ['a', 'b', 'c', 'd']
MAX_LENGTH = 4

for length in range(1,MAX_LENGTH + 1):
  for x in itertools.product(my_list, repeat=length):
    print(''.join(x))

rawDescription: output all possible variants of a string

description: Output all possible variants of a string


code:
class TabularSelectMultiple(SelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'
','
	Label
']
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = u' for="%s"' % final_attrs['id']
            else:
                label_for = u''
            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values).render(name, option_value)
            option_value = force_unicode(option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append(u'
%s	 %s
' % (cb, label_for, option_label))
        output.append(u'
')
        return mark_safe(u'\n'.join(output))

class HouseForm(forms.ModelForm):
    amenities = ModelMultipleChoiceField(
        queryset=Amenity.objects.all(),
        widget=TabularSelectMultiple(),
        required=False
    )

rawDescription: How to display the options' label in ModelMultipleChoiceField?

description: Display the options' label in ModelMultipleChoiceField


code: s_optChoice = input("Enter your choice (Rock, Paper or Scizzors: ")

rawDescription: How do I assign a string to a variable?

description: Assign a string to a variable


code:
import tkinter as tk

root = tk.Tk()
# List of your colours
COLOURS = [['red', 'green', 'dark blue'],
           ['turquoise', 'grey', 'yellow'],
           ['pink', 'orange', 'purple']]

# Nested for-loop for a 3x3 grid
for x in range(3):
    for y in range(3):
        if x == 1 and y == 1: # If statement for the Listbox
            tk.Listbox(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y)
        else:
            tk.Button(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y)

root.mainloop()

rawDescription: Compacting my class for my tkinter window with buttons


code:
#this should be done only once in your code *anywhere* before while loop starts
newtime=pygame.time.get_ticks()

# when you fire, inside while loop
# should be ideally inside update method
oldtime=newtime
newtime=pygame.time.get_ticks()
if newtime-oldtime<500: #in milliseconds
    fire()

rawDescription: pygame: player fire delay

description: Pygame: player fire delay


code:
if isinstance(variable, QuerySet):
    do_this

rawDescription: Best practice method for evaluating if a Django queryset object (or not) before slicing it?


rawDescription: How to sum values of one column and group them by another column

description: Sum values of one column and group them by another column


code:
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

rawDescription: Can I mark an iterator as finished prematurely?

description: Mark an iterator as finished prematurely


code:
import time
import re
import os
import stat
import logging
import logging.handlers as handlers

class SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler):
    """
    Handler for logging to a set of files, which switches from one file
    to the next when the current file reaches a certain size, or at certain
    timed intervals
    """
    def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None,
                 delay=0, when='h', interval=1, utc=False):
        # If rotation/rollover is wanted, it doesn't make sense to use another
        # mode. If for example 'w' were specified, then if there were multiple
        # runs of the calling application, the logs from previous runs would be
        # lost if the 'w' is respected, because the log file would be truncated
        # on each run.
        if maxBytes > 0:
            mode = 'a'
        handlers.TimedRotatingFileHandler.__init__(
            self, filename, when, interval, backupCount, encoding, delay, utc)
        self.maxBytes = maxBytes

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        Basically, see if the supplied record would cause the file to exceed
        the size limit we have.
        """
        if self.stream is None:                 # delay was set...
            self.stream = self._open()
        if self.maxBytes > 0:                   # are we rolling over?
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
            if self.stream.tell() + len(msg) >= self.maxBytes:
                return 1
        t = int(time.time())
        if t >= self.rolloverAt:
            return 1
        return 0

def demo_SizedTimedRotatingFileHandler():
    log_filename='/tmp/log_rotate'
    logger=logging.getLogger('MyLogger')
    logger.setLevel(logging.DEBUG)
    handler=SizedTimedRotatingFileHandler(
        log_filename, maxBytes=100, backupCount=5,
        when='s',interval=10,
        # encoding='bz2',  # uncomment for bz2 compression
        )
    logger.addHandler(handler)
    for i in range(10000):
        time.sleep(0.1)
        logger.debug('i=%d' % i)

demo_SizedTimedRotatingFileHandler()

rawDescription: Python, want logging with log rotation and compression


code:
from os.path import basename, dirname
import openpyxl

def crearlista (*arg, **kw):
    inventario = openpyxl.Workbook(encoding = "Utf-8")
    sheet = inventario.active
    i = 1

    for dirpath, subdirs, files in os.walk("//media//rayeus/Datos/Mis Documentos/Nueva carpeta/", topdown=False):
        file_dir = basename(dirpath) or dirname(basename(dirpath))
        for name in files:
            sheet.cell(row=i, column=1).value = dirpath
            sheet.cell(row=i, column=2).value = file_dir
            sheet.cell(row=i, column=3).value = name
            i += 1

rawDescription: Unexpected behaviour while iterating directories in python


code:
import subprocess
subprocess.call(['bash', '-c', '. ~/.profile && knife-LHR'])

rawDescription: How do I execute a bash function defined in .profile using python subprocess module?

description: Execute a bash function defined in .profile using python subprocess module


code:
m = gateway.jvm.java.util.HashMap()
m["a"] = 0
m.put("b",1)
m
u"b" in m
del(m["a"])
m
m["c"] = 2

rawDescription: py4j: dict to JAVA map

description: Py4j: dict to JAVA map


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

num = 10
data = np.random.random((num, 2))
values = np.random.normal(10, 5, num)

# I'm too lazy to draw irregular polygons, so I'll use circles
circles = [plt.Circle([x, y], 0.1) for (x,y) in data]
col = PatchCollection(circles)

col.set(array=values, cmap='jet')

fig, ax = plt.subplots()

ax.add_collection(col)
ax.autoscale()
ax.axis('equal')

fig.colorbar(col)
plt.show()

rawDescription: Matplotlib colorbar for PatchCollection overrides colors


code:
cropped = pygame.Surface((80, 80))
cropped.blit(buttonStates, (0, 0), (30, 30, 80, 80))

rawDescription: How can I crop an image with Pygame?

description: Crop an image with Pygame


code:
import subprocess
import datetime

t1 = datetime.datetime.now()
h = subprocess.Popen(...) # See subprocess module documentation for the args
h.communicate()
t2 = datetime.datetime.now()
print("Return Code: %d" % h.returncode)
print("Delta: %s" % (t2 - t1))

rawDescription: Can I use Python to time an external C++ .exe and grab its return value too?

description: Use Python to time an external C++ .exe and grab its return value too


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo!' in browser.title

elem = browser.find_element_by_name('p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

rawDescription: Browser automate tasks

description: Browser automate tasks


code:
import lxml.etree as le
data = """<root
             xmlns:one="http://www.first.uri/here/"
             xmlns:two="http://www.second.uri/here/">

          ...all other child elements here...
          </root>"""

tree = le.XML(data)
print(tree.nsmap)
# {'two': 'http://www.second.uri/here/', 'one': 'http://www.first.uri/here/'}

rawDescription: XML and Python: Get the namespaces declared in root element


code:
import re
my_string = 'a hello aaaaa hi aaaaaaa bye bbb'
re.sub(r'a+', 'b', my_string)

rawDescription: Change single/multiple character to another single character


code:
from termcolor import *
cprint('hello', 'red')
import colorama
colorama.init()
cprint('hello', 'red')

rawDescription: Why termcolor doesn't work in python?

description: Why termcolor doesn't work in python


code: max(len(l) for l in dict.values()) # 4

rawDescription: Finding maximal length value in dictionary


code: array1,array2,array3,array4 = [np.ma.zeros(np.shape(array0)) for _ in range(4)]

rawDescription: Preallocate multiple identically shaped numpy arrays


code:
from subprocess import Popen, PIPE, STDOUT
from threading  import Thread
import os
import pexpect.fdpexpect

# tee and teed_call are based on http://stackoverflow.com/a/4985080/2073595

def tee(infile, *files):
    """Print `infile` to `files` in a separate thread."""
    def fanout(infile, *files):
        for line in iter(infile.readline, ''):
            for f in files:
                f.write(line)
        infile.close()
    t = Thread(target=fanout, args=(infile,)+files)
    t.daemon = True
    t.start()
    return t

def teed_call(cmd_args, files, **kwargs):
    p = Popen(cmd_args,
              stdout=PIPE,
              stderr=STDOUT,
              **kwargs)
    threads = []
    threads.append(tee(p.stdout, *files))
    return (threads, p)

with open("log.txt", 'w') as logf:
    # Create pipes for unbuffered reading and writing
    rpipe, wpipe = os.pipe()
    rpipe = os.fdopen(rpipe, 'r', 0)
    wpipe = os.fdopen(wpipe, 'w', 0)

    # Have pexpect read from the readable end of the pipe
    pobj = pexpect.fdpexpect.fdspawn(rpipe)

    # Call some script, and tee output to our log file and
    # the writable end of the pipe.
    threads, p = teed_call(["./myscript.sh"], [wpipe, logf])

    # myscript.sh will print 'hey'
    pobj.expect("hey")

    # orderly shutdown/cleanup
    for t in threads: t.join()
    p.wait()
    rpipe.close()
    wpipe.close()

rawDescription: Can I use fdpexpect on a file that's currently being written to?

description: Use fdpexpect on a file that's currently being written to


code:
import numpy as np

classes = np.array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'])

classnames, indices = np.unique(classes, return_inverse=True)

print(classnames)
# ['a' 'b' 'c' 'd']

print(indices)
# [0 1 2 2 1 0 0 3]

print(classnames[indices])
# ['a' 'b' 'c' 'c' 'b' 'a' 'a' 'd']

rawDescription: Python: how to convert a string array to a factor list


code:
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)

rawDescription: Deploying program to Heroku. Errors

description: Deploying program to Heroku. Errors


code:
if not os.environ.get("DISABLE_UTF8_REDEFINE"):
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

rawDescription: Strange characters in Django shell, arrowkeys not working


rawDescription: Python: Get different time format

description: Python: Get different time format


code:
wikilink_rx = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]')
return wikilink_rx.sub(r'\1', the_string)

rawDescription: Python regular expression with wiki text


code:
for a in arrayA:
    if a in arrayB:
        indexA = arrayA.index(a)
        indexB = arrayB.index(a)
        break

rawDescription: Python: Find indices of the *first* match between two arrays


code:
def _read_loop(self, resp):

    while self.running and not resp.isclosed():

        # Note: keep-alive newlines might be inserted before each length value.
        # read until we get a digit...
        c = '\n'
        while c == '\n' and self.running and not resp.isclosed():
            c = resp.read(1)
        delimited_string = c

        # read rest of delimiter length..
        d = ''
        while d != '\n' and self.running and not resp.isclosed():
            d = resp.read(1)
            delimited_string += d

        try:
            int_to_read = int(delimited_string)
            next_status_obj = resp.read( int_to_read )
            # print 'status_object = %s' % next_status_obj
            self._data(next_status_obj)
        except ValueError:
            pass

    if resp.isclosed():
        self.on_closed(resp)

rawDescription: streaming api with tweepy only returns second last tweet and NOT the immediately last tweet

description: Streaming api with tweepy only returns second last tweet and NOT the immediately last tweet


code:
address = "SOUTH 16TH STREET"
" ".join([word.capitalize() for word in address.split()])

rawDescription: How can I change the case of abbreviated ordinals to lower while keeping the rest of the string in title case?

description: Change the case of abbreviated ordinals to lower while keeping the rest of the string in title case


code:
# A.func = func
A.__dict__['func'] = func # This just sets the attribute
# A.func
#   The __getattribute__ method of a type object calls the __get__ method with
#   None as the first parameter and the type as the second.
A.__dict__['func'].__get__(None, A) # The __get__ method of a function object
                                    # returns an unbound method object if the
                                    # first parameter is None.
a = A()
# a.func()
#   The __getattribute__ method of object finds an attribute on the type object
#   and calls the __get__ method of it with the instance as its first parameter.
a.__class__.__dict__['func'].__get__(a, a.__class__)
#   This returns a bound method object that is actually just a proxy for
#   inserting the object as the first parameter to the function call.

rawDescription: How does assignment of a function as a class attribute become a method in Python?


code:
for root, subdirs, files in os.walk(this_path):
  for my_file in files:
    shutil.move(os.path.join(root, my_file), os.path.join(this_path, filename))

rawDescription: in python how do I figure out the current path of the os.walk()?

description: In python how do I figure out the current path of the os.walk()


code:
def next_page(request,location_id):
    loc = Location.objects.get(id=location_id)

rawDescription: django getting variable from url into view

description: Django getting variable from url into view


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 2, (50, 4)), columns=["id1", "id2", "count1", "count2"])
df["compare"] = ((df.id1==df.id2) & (df.count1==df.count2)).astype(int)

rawDescription: Compare columns pandas

description: Compare columns pandas


code:
def int2str(i):
    _bytes = list()
    while i > 0:
        n = i % 256
        _bytes.insert(0, n)
        i = i >> 8
    return ''.join(struct.pack('B', x) for x in _bytes)

rawDescription: How to pack integers of arbitrary size to byte buffer in Python

description: Pack integers of arbitrary size to byte buffer in Python


code: sys.excepthook = sys.__excepthook__

rawDescription: How to get root of the apport sys.excepthook?

description: Get root of the apport sys.excepthook


code:
import os.path
dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))]

rawDescription: how to get all folder only in a given path in python?

description: Get all folder only in a given path in python


code:
import inspect
from collections import Counter
c = Counter()
inspect.getmodule(c)
inspect.getmodule(Counter)

rawDescription: Getting Module from Type

description: Getting Module from Type


code:
text = "I have a good python book so will become pythonist"
'python' in text.split()

rawDescription: Search a word which exactly match using python


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

cdict = {'red': ((0.0, 0.0, 0.0),
                 (0.5, 1.0, 1.0),
                 (1.0, 1.0, 1.0)),
        'green':((0.0, 0.0, 0.0),
                 (0.5, 1.0, 1.0),
                 (1.0, 0.0, 0.0)),
         'blue':((0.0, 1.0, 1.0),
                 (0.5, 0.0, 0.0),
                 (1.0, 0.0, 0.0))}

custom_cmap = mpl.colors.LinearSegmentedColormap('mymap', cdict, 256)

plt.imshow(np.arange(36).reshape(6,6), cmap=custom_cmap, interpolation='none')

rawDescription: Custom Matplotlib colourmap - like pgfplots


code:
# ...
plot.axes.set_ylim(0,msize-1)
plot.axes.set_xlim(0,msize-1)
#
plot.axes.set_aspect('equal')
# ...

rawDescription: How to keep aspect ratio on matplotlib graphs while adding more objects to the figure?

description: Keep aspect ratio on matplotlib graphs while adding more objects to the figure


code:
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

rawDescription: Create a list of sets of atoms

description: Create a list of sets of atoms


code:
import os, re, shutil

r = re.compile(r'^([0-9]{2})([0-9]{2})([0-9]{2})-(.*)$')

for root, dirs, files in os.walk('/path/to/topdir'):
    for filename in files:
        match = r.match(filename)
        if match:
            newfilename = match.group(3) + match.group(1) + match.group(2) + '-' + match.group(4)
            newfilename = os.path.join(root, newfilename)
            oldfilename = os.path.join(root, filename)

            # Rename oldfilename to newfilename
            shutil.move(oldfilename, newfilename)

rawDescription: Changing Directory Names in Python

description: Changing Directory Names in Python


code:
import Tkinter as tk
import gps

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.gps_label = tk.Label(self, text="", width=40)
        self.gps_label.pack(fill="both", expand=True, padx=20, pady=20)

        # initialize gps
        self.gpsd = gps.gps(mode=WATCH_ENABLE)
        self._update_gps_data()

    def _update_gps_data(self):
        data = self.gpsd.next()
        self.gps_label.configure(text="gps data: " + data)

        # run again in one second (1000 ms)
        self.after(1000, self._update_gps_data)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Refreshing gps data in Tkinter

description: Refreshing gps data in Tkinter


code:
import csv
import collections
import itertools

grids = dict()
groups = dict()

with open("connect.csv", "r") as fp:
    reader = csv.reader(fp)
    for line in reader:
        # extract month/year from the last column
        date = line.pop(-1)
        month,year = date.split('/')
        # clean empty names
        line = [name.strip() for name in line if name.strip()]
        # generate group name
        group = ''.join(sorted(line)).replace('.','')
        #increment group count
        if group in groups:
            groups[group]+=1
        else:
            groups[group]=1
        #if grid exists for month, update else create
        if (month,year) in grids:
            grid = grids[(month,year)]
        else:
            grid = collections.Counter()
            grids[(month,year)] = grid
        # count single works
        if len(line) == 1:
            grid[line[0], line[0]] += 1
        # do pairwise counts
        for pair in itertools.combinations(line, 2):
            grid[pair] += 1
            grid[pair[::-1]] += 1

for date,grid in grids.items():
    actors = sorted(set(pair[0] for pair in grid))
    #Filename from date
    filename = "connection_grid_%s_%s.csv" % date
    with open(filename, "w") as fp:
        writer = csv.writer(fp)
        writer.writerow([''] + actors)
        for actor in actors:
            line = [actor,] + [grid[actor, other] for other in actors]
            writer.writerow(line)

with open('groups.csv','w') as fp:
    writer = csv.writer(fp)
    for item in sorted(groups.items()):
        writer.writerow(item)

rawDescription: Making various groupings

description: Making various groupings