code:
import re
str_typedef = """typedef enum x
{
    ...
} z;"""
pattern = 'typedef\s+enum\s+([a-zA-Z0-9_]+)\s*{[^{}]*}\s*([a-zA-Z0-9_]+)\s*;'
rs = re.findall(pattern, str_typedef)
for r in rs:
    enum_type_name = r.group(1)
    enum_name = r.group(2)
    # do operations with results here, or store to an array
    # of dictionaries for use later.

rawDescription: Python regex matching c++ typedef'd enums


code:
import csv
rows = csv.reader(open('yourfile.csv', 'rb'), delimiter=' ', quotechar='|')
arows = [row for row in rows if 'a' in row]

rawDescription: Define row of CSV file if row contains specific string


code:
from tkinter import *
import random, time
tk = Tk()
tk.wm_attributes('-topmost', 1)
canvas = Canvas(tk, width=1000, height=1000, bd=0)
canvas.pack()

def rocket(): #draws rocket
        rocketbase=canvas.create_rectangle(x2+50, y2-50, x3-50, y3-90, fill ='blue')
        rrocketfin=canvas.create_rectangle(x2+60, y2-50, x3-40, y3-20, fill ='#e69100')
        lrocketfin=canvas.create_rectangle(x2+40, y2-50, x3-60, y3-20, fill ='#e69100')
        mrocketfin=canvas.create_rectangle(x2+54, y2-50, x3-53, y3-20, fill ='#e69100')
        lrockethead=canvas.create_rectangle(x2+45, y2-125, x3-60, y3-70, fill ='#e69100')
        rrockethead=canvas.create_rectangle(x2+60, y2-125, x3-45, y3-70, fill ='#e69100')

def handle_key_press(e):
    if e.keysym == 'space':
        move_r()

def move_r():
    global y2
    global y3
    y2 -= 50
    y3 -= 50
    rocket()
    tk.update()
    canvas.after(100, move_r)

x2=460
y2=940
x3=570
y3=900
r1=None
tk.bind('<KeyPress-space>', handle_key_press)

background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'red')
base = canvas.create_rectangle(0, 1000, 1000, 900, fill='#86592d')
rocket()
tk.update()

tk.mainloop()

rawDescription: Why does this after statement not work?

description: Why does this after statement not work


code:
a = 10

def some_function(a,b):
  do_something

rawDescription: What top level code is executed on import


code:
import os
import csv
import glob

file_path = '/home/foo/bar/some/where/'
file_pattrn = '*.*'
file_names = {}

with open('somefile.csv') as f:
    reader = csv.reader(f)
    for row in reader:
       file_names[row[0]] = row[1]

for file in glob.iglob(file_path+file_pattrn):
    path, filename = os.path.split(file)
    filename_noext, ext = os.path.splitext(filename)
    new_filename = file_names.get(filename_noext, filename_noext)
    os.rename(os.path.join(path, filename),
              os.path.join(path, '{}{}'.format(new_filename, ext)))

rawDescription: How to rename a file name without changing the extension

description: Rename a file name without changing the extension


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

import wx

class MyFrame(wx.Frame):
  def __init__(self, title):
    super(MyFrame, self).__init__(None, title=title)

    panel = wx.Panel(self)
    self.check = wx.CheckBox(panel, label='confiurm?', pos =(10,70), size=(90,-1))
    self.text  = wx.TextCtrl(panel, pos=(100,70), size=(180,-1))
    # disable the button until the user enters something
    self.check.Disable()

    self.Bind(wx.EVT_CHECKBOX, self.OnCheck, self.check)
    self.Bind(wx.EVT_TEXT, self.OnTypeText, self.text)

    self.Centre()

  def OnTypeText(self, event):
    '''
    OnTypeText is called when the user types some string and
    activate the check box if there is a string.
    '''
    if( len(self.text.GetValue()) > 0 ):
      self.check.Enable()
    else:
      self.check.Disable()

  def OnCheck(self, event):
    '''
    Print the user input if he clicks the checkbox.
    '''
    if( self.check.IsChecked() ):
      print(self.text.GetValue())

class MyApp(wx.App):
  def OnInit(self):
    self.frame = MyFrame('Example')
    self.frame.Show()
    return True

MyApp(False).MainLoop()

rawDescription: .GetValue() is not working for TextCtrl in this particular case


code:
for idx in xrange(1, len(lst), 2):
    if lst[idx] == 'p':
        ...
    if lst[idx] == 'm':
        ...

rawDescription: how to iterate through a list and get values based on the value of the previous index in python?

description: Iterate through a list and get values based on the value of the previous index in python


code:
words = ['hello','my','name','is','david']
sentence = ' '.join(words)

rawDescription: Converting a list of strings to just appear as they are


code:
def closest_common_ancestor(ds1, ds2):

        while ds1 != None:
                dd = ds2
                while dd != None:
                        if ds1 == dd:
                                return dd
                        dd = dd.parent
                ds1 = ds1.parent
        return None

rawDescription: Tree traversal in a customised way in Python?


code: os.system('taskkill /f /im explorer.exe')

rawDescription: Python disabling startmenu and taskbar

description: Python disabling startmenu and taskbar


rawDescription: Why One Liner Result Is Different

description: Why One Liner Result Is Different


code:
import sys
import select
import time

# files monitored for input
read_list = [sys.stdin]
# select() should wait for this many seconds for input.
# A smaller number means more cpu usage, but a greater one
# means a more noticeable delay between input becoming
# available and the program starting to work on it.
timeout = 0.1 # seconds
last_work_time = time.time()

def treat_input(linein):
  global last_work_time
  print("Workin' it!", linein, end="")
  time.sleep(1) # working takes time
  print('Done')
  last_work_time = time.time()

def idle_work():
  global last_work_time
  now = time.time()
  # do some other stuff every 2 seconds of idleness
  if now - last_work_time > 2:
    print('Idle for too long; doing some other stuff.')
    last_work_time = now

def main_loop():
  global read_list
  # while still waiting for input on at least one file
  while read_list:
    ready = select.select(read_list, [], [], timeout)[0]
    if not ready:
      idle_work()
    else:
      for file in ready:
        line = file.readline()
        if not line: # EOF, remove file from input list
          read_list.remove(file)
        elif line.rstrip(): # optional: skipping empty lines
          treat_input(line)

try:
    main_loop()
except KeyboardInterrupt:
  pass

rawDescription: Python check input from console and serial at the same time?


code:
reversedmapping = {v:k for k,v in mapping.items()}
for k,v in revenue.items():
    if (k not in reversedmapping) or (reversedmapping[k] not in spend):
        print(k)

rawDescription: How to check for presence of the key of a value (as defined in one dict) in another dict, in Python?

description: Check for presence of the key of a value (as defined in one dict) in another dict, in Python


code:
from django.db.models.signals import pre_save, post_save

@receiver(pre_save)
def pre_save_handler(sender, instance, *args, **kwargs):
    # some case
    if case_error:
        raise Exception('OMG')

rawDescription: Cancel saving model when using pre_save in django


code:
d = {'a':20, 'b': 20, '?': 10}
sum(value for key, value in d.items() if key != "?")

rawDescription: reduce python dictionary values if key meets condition

description: Reduce python dictionary values if key meets condition


code:
import Tkinter, random

class BubbleFrame:

    def __init__(self, root):
        root.title("Math Bubbles")
        Tkinter.Button(root, text="Add Bubbles", width=8, command=self.bubble).pack()
        Tkinter.Button(root, text="Quit", width=8, command=quit).pack()
        self.canvas = Tkinter.Canvas(root, width=800, height=650, bg = '#afeeee')
        self.canvas.pack()
        self.bubbles = {} # this will hold bubbles ids, positions and velocities

    def bubble(self):
        # add bubbles for numbers from 1 to 20
        for number in range(1, 20+1):
            xval = random.randint(5,765)
            yval = random.randint(5,615)
            s1 = self.canvas.create_oval(xval,yval,xval+30,yval+30, fill="#00ffff",outline="#00bfff",width=5)
            s2 = self.canvas.create_text(xval+15,yval+15, text=number)
            self.bubbles[(s1, s2)] = (xval, yval, 0, 0) # add bubbles to dictionary

    def loop(self, root):
        for (s1, s2), (x, y, dx, dy) in self.bubbles.items():
            # update velocities and positions
            dx += random.randint(-1, 1)
            dy += random.randint(-1, 1)
            # dx and dy should not be too large
            dx, dy = max(-5, min(dx, 5)), max(-5, min(dy, 5))
            # bounce off walls
            if not 0 < x < 770: dx = -dx
            if not 0 < y < 620: dy = -dy
            # apply new velocities
            self.canvas.move(s1, dx, dy)
            self.canvas.move(s2, dx, dy)
            self.bubbles[(s1, s2)] = (x + dx, y + dy, dx, dy)
        # have mainloop repeat this after 100 ms
        root.after(100, self.loop, root)

if __name__ == "__main__":
    root = Tkinter.Tk()
    frame = BubbleFrame(root)
    frame.loop(root)
    root.mainloop()

rawDescription: How to get multiple ovals moving around the canvas?

description: Get multiple ovals moving around the canvas


code:
import numpy as np
import scipy.odr.odrpack as odrpack
np.random.seed(1)

N = 100
x = np.linspace(0,10,N)
y = 3*x - 1 + np.random.random(N)
sx = np.random.random(N)
sy = np.random.random(N)

def f(B, x):
    return B[0]*x + B[1]
linear = odrpack.Model(f)
# mydata = odrpack.Data(x, y, wd=1./np.power(sx,2), we=1./np.power(sy,2))
mydata = odrpack.RealData(x, y, sx=sx, sy=sy)

myodr = odrpack.ODR(mydata, linear, beta0=[1., 2.])
myoutput = myodr.run()
myoutput.pprint()
# Beta: [ 3.02012862 -0.63168734]
# Beta Std Error: [ 0.01188347  0.05616458]
# Beta Covariance: [[ 0.00067276 -0.00267082]
#  [-0.00267082  0.01502792]]
# Residual Variance: 0.209906660703
# Inverse Condition #: 0.105981202542
# Reason(s) for Halting:
#   Sum of squares convergence

rawDescription: python scipy.odrpack.odr example (with sample input / output)?

description: Python scipy.odrpack.odr example (with sample input / output)


code:
href_list = []
for link in soup.find_all("a", href=re.compile('anDetails.asp')):

    href = link.get('href')
    if href not in href_list:
        print(href)
        href_list.append(href)

rawDescription: Remove a href if the same one has been already scrapped


code:
import glob
import serial

def find_ports():
    ports = glob.glob('/dev/ttyACM[0-9]*')

    res = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            res.append(port)
        except:
            pass
    return res

rawDescription: Detect which /dev/ttyACM is open

description: Detect which /dev/ttyACM is open


code:
from django.db import connections, transaction
from django.core.cache import cache # This is the memcache cache.

def flush():
    # This works as advertised on the memcached cache:
    cache.clear()
    # This manually purges the SQLite cache:
    cursor = connections['cache_database'].cursor()
    cursor.execute('DELETE FROM cache_table')
    transaction.commit_unless_managed(using='cache_database')

rawDescription: How to clear the whole cache when using django's page_cache decorator

description: Clear the whole cache when using django's page_cache decorator


code:
def _lookup(self, name, cls, type, timeout = None):
    """Return a list of results.
    name: Queried host name.
    cls: An enum of the query class. See dns.py:

        IN, CS, CH, HS = range(1, 5)

        QUERY_CLASSES = {
            IN: 'IN',
            CS: 'CS',
            CH: 'CH',
            HS: 'HS',
            ANY: 'ANY'
        }

    type: The type of record to search for (or ANY/255 for any and all).
          See dns.py:

        (A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
         RP, AFSDB) = range(1, 19)
        AAAA = 28
        SRV = 33
        NAPTR = 35
        A6 = 38
        DNAME = 39
        SPF = 99

        QUERY_TYPES = {
            A: 'A',
            NS: 'NS',
            MD: 'MD',
            MF: 'MF',
            CNAME: 'CNAME',
            SOA: 'SOA',
            MB: 'MB',
            MG: 'MG',
            MR: 'MR',
            NULL: 'NULL',
            WKS: 'WKS',
            PTR: 'PTR',
            HINFO: 'HINFO',
            MINFO: 'MINFO',
            MX: 'MX',
            TXT: 'TXT',
            RP: 'RP',
            AFSDB: 'AFSDB',

            # 19 through 27?  Eh, I'll get to 'em.

            AAAA: 'AAAA',
            SRV: 'SRV',
            NAPTR: 'NAPTR',
            A6: 'A6',
            DNAME: 'DNAME',
            SPF: 'SPF'
        }

    timeout: The retention time for this record, in seconds.
    """
    cnames = []
    results = []
    authority = []
    additional = []
    default_ttl = max(self.soa[1].minimum, self.soa[1].expire)

    # Do records search. Get a list of classes like Record_A and Record_MX
    # back. These are defined in dns.py .
    domain_records = self.records.get(name.lower())

    # Structure the results so as to present them the way that DNS records
    # usually come back.

    if domain_records:
        # Loop through all of the results.
        for record in domain_records:
            if record.ttl is not None:
                ttl = record.ttl
            else:
                ttl = default_ttl

            # If we're looking at a [subdomain?] NS record, note it.
            if record.TYPE == dns.NS and name.lower() != self.soa[0].lower():
                # NS record belong to a child zone: this is a referral.  As
                # NS records are authoritative in the child zone, ours here
                # are not.  RFC 2181, section 6.1.
                authority.append(
                    dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=False)
                )

            # Was the record what was requested, or did we want everything?
            elif record.TYPE == type or type == dns.ALL_RECORDS:
                results.append(
                    dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
                )

            # If we're looking at a CNAME record, note it.
            if record.TYPE == dns.CNAME:
                cnames.append(
                    dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
                )

        # If no requested records were found, use the CNAME records (if any).
        if not results:
            results = cnames

        # Go through any NS, CNAME, or MX records found, and find the IPs
        # for those hosts.
        #
        # NOTE: The "additional" list doesn't appear to be populated.
        for record in results + authority:
            section = {dns.NS: additional, dns.CNAME: results, dns.MX: additional}.get(record.type)
            if section is not None:
                n = str(record.payload.name)
                for rec in self.records.get(n.lower(), ()):
                    if rec.TYPE == dns.A:
                        section.append(
                            dns.RRHeader(n, dns.A, dns.IN, rec.ttl or default_ttl, rec, auth=True)
                        )

        # Not found. Return an SOA record with the name that was requested
        # (the normal response that you'll see at the console).
        if not results and not authority:
            # Empty response. Include SOA record to allow clients to cache
            # this response.  RFC 1034, sections 3.7 and 4.3.4, and RFC 2181
            # section 7.1.
            authority.append(
                dns.RRHeader(self.soa[0], dns.SOA, dns.IN, ttl, self.soa[1], auth=True)
                )

        # We return a tuple of individual result lists. Each of the records
        # is an instance of RRHeader, which wraps the Record_* classes in
        # dns.py for returning as a result (Resource Record).
        #
        # The first item in the tuple refers to the "ANSWER SECTION" in the
        # DiG output, and the third item refers to the "ADDITIONAL
        # SECTION". As "authority" was an empty list in the example, no
        # output relates to it. It will have NS records if any are present,
        # or contain an SOA record for what was requested if nothing was
        # found.
        #
        #;; QUESTION SECTION:
        #;example-domain.com.            IN      ANY
        #
        #;; ANSWER SECTION:
        #example-domain.com.     3600    IN      SOA     ns1.example-domain.com. root.example-domain.com. 2003010601 3600 3600 3600 3600
        #example-domain.com.     3600    IN      A       127.9.9.9
        #example-domain.com.     3600    IN      NS      ns1.example-domain.com.
        #example-domain.com.     3600    IN      MX      0 mail.example-domain.com.
        #
        #;; ADDITIONAL SECTION:
        #mail.example-domain.com. 3600   IN      A       123.0.16.43

        return defer.succeed((results, authority, additional))
    else:
        if name.lower().endswith(self.soa[0].lower()):
            # We are the authority and we didn't find it.  Goodbye.
            return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
        return defer.fail(failure.Failure(dns.DomainError(name)))

rawDescription: How does Twisted Names build search results for query?


code:
import csv

summary = {}
with open('test.csv', 'rb') as data_file:
    reader = csv.reader(data_file)
    for itemid, value, action in reader:
        if itemid not in summary:
            summary[itemid] = dict(id=itemid, label=[value], meta={'action': action})
        else:
            summary[itemid]['label'].append(value)

data = {"topics": list(summary.values())}

rawDescription: Creating a specifically formatted JSON file from a CSV


code:
def unique_chars(words):
    taken = set()
    uniques = []

    for word in words:
        for char in word:
            if char not in taken:
                taken.add(char)
                uniques.append(char)
                break
        else:
            raise ValueError("There are no unique letters left!")

    return uniques

rawDescription: Is there a way in python to compare strings for unique character


code:
def __init__(self):
    wx.Frame.__init__(self, None, 0, 'wxPython pull-down choice', size = (400, 300))
    panel_select_model= wx.Panel(self, -1)
    model_list = ['Test_A', 'Test_B']
    self._model_type = None

    self._stat_tex = wx.StaticText(panel_select_model, 1, "Select Model Type:", (15, 20))
    self._droplist = wx.Choice(panel_select_model, 2, (150, 18), choices = model_list)

    """ Bind A Panel """
    self._droplist.SetSelection(0)
    self._droplist.Bind(wx.EVT_CHOICE, self.choice_click)

    """ Bind B Panel """
    self._droplist.SetSelection(1)
    self._droplist.Bind(wx.EVT_CHOICE, self.choice_click)

def choice_click(self, event):
    if self._droplist.GetStringSelection() == "Test_A":
        self.Test_A__click()
    elif self._droplist.GetStringSelection() == "Test_B":
        self.Test_B_click()

rawDescription: How to bind items in a wx.Choice component to functions?

description: Bind items in a wx.Choice component to functions


code:
import glob, os
def solution():
    for fn in glob.glob("*_text.exe"):
        os.startfile(fn)

rawDescription: Python : get all exe files in current directory and run them?


code:
@register.filter
def asrepr(value):
    return repr(value)

rawDescription: How to use __repr__ method within django template?

description: Use __repr__ method within django template


code:
def get_slice(my_list, start, stop):
        return my_list[start:stop][:]

def to_string(my_list):
        return 'List is: %s' % ''.join(my_list[:])

str_list = ['s', 'h', 'r', 'u', 'g', 'g', 'e', 'd']

print("\nget_slice Test")
my_slice = get_slice(str_list, 2, 100)
print(to_string(str_list))
print(to_string(my_slice))

my_slice = get_slice(str_list, 6, 1)
print(to_string(my_slice))

my_slice = get_slice(str_list, 2, 5)
print(to_string(str_list))
print(to_string(my_slice))

rawDescription: Python - Writing slice function

description: Python - Writing slice function


code:
resp = self.client.post(reverse('check_answer'), data=data)
card = Card.objects.get(id=card.id)
self.assertEqual(card.score, 1)

rawDescription: Django field doesn't remain incremented even after calling save()


code:
src = """<name> James Gold
</name> said to meet with <name> Mable Helen  </name> tomorrow night"""
[s.strip() for s in re.findall(r'<name>(.*?)</name>', src, re.DOTALL)]

rawDescription: parse annotated file

description: Parse annotated file


code:
self.lab = Tkinter.Label(self,bg='white', relief='groove',
                         textvariable=self.labvar, wraplength=250)

rawDescription: Preventing tkinter labels being stretched by a long string


code:
import os
import webapp2
import logging
import json
from google.appengine.api import mail

class MainPage(webapp2.RequestHandler):

    def get(self):

        #If request comes from the App

        if self.request.referer == 'Your request.referer' :

            message = self.request.get('message')

            #If there is no message or message is empty

            if not message and len(message) == 0:

                self.response.headers.add_header('content-type', 'text/plain', charset='utf-8')

                self.response.out.write('An empty message cannot be submitted')

                return

            #Print message

            logging.info('Message : ' + message)

            #Set email properties

            user_address = 'user_address'
            sender_address = 'sender_address'
            subject = 'Subject'
            body = message

            #Send Email

            mail.send_mail(sender_address, user_address, subject, body)

        #If request comes from unknow sources

        else :

            self.response.headers.add_header('content-type', 'text/plain', charset='utf-8')

            self.response.out.write('This operation is not allowed')

            return

app = webapp2.WSGIApplication([('/', MainPage)])

rawDescription: How to send an email from Backbone app with Google Python AppEngine

description: Send an email from Backbone app with Google Python AppEngine


code:
import csv
import requests

r_temp1 = requests.get('http://www.ndbc.noaa.gov/data/realtime2/BZBM3.txt')
rows_temp1 = r_temp1.text.split('\n')

#writing to a csv file
csvfile_temp1 = open("temp1.csv","wb")
output_temp1 = csv.writer(csvfile_temp1, delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL)
for row in rows_temp1:
    if not row:  continue
    cells = row.split()
    Year = cells[0].strip()
    Month = cells[1].strip()
    Day = cells[2].strip()
    W_temp = cells[14].strip()
    output_temp1.writerow([Year,Month,Day,W_temp])
csvfile_temp1.close()

rawDescription: Python--Web scraping a table and writing only specific columns into a CSV file


rawDescription: Strange... What does [::5,0] mean

description: Strange... What does [::5,0] mean


rawDescription: Django/Postgres: displaying distinct ManyToMany items


code:
import modules.js as js
import modules.rivescript as rivescript

import plugins.weather as weather
import plugins.synd as synd

weather.get("3088")  # Usage example

rawDescription: Importing modules from a folder in python27


code:
coords = poly.exterior.coords[:]
coords[1] = (2.0, 6.0) # coordinate to change

new_poly = Polygon(coords)

rawDescription: Shapely: add new points to existing Polygon


rawDescription: Unicode character creation in Python 3.4


code:
from sqlalchemy import create_engine
import pandas as pd

# create an engine with the following syntax
# mssql (MicroSoft SQL)
# pyodbc (the python database api to your sql)
# username, password, database_name
ms_sql_engine = create_engine('mssql+pyodbc://my_username:my_password@my_database_name')

# I don't have MS sql installed in my PC, so just use sqlite in memory here
my_engine = create_engine('sqlite:///:memory:')

# your data in pandas dataframe
df = pd.DataFrame(np.random.randn(100, 5), columns='A B C D E'.split())

# write to sql
# replace engine with your own MS sql engine
df.to_sql('my_frame', my_engine)

rawDescription: how do i insert without inputting all column names with pyodbc execute many?

description: Insert without inputting all column names with pyodbc execute many


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib.colors import colorConverter
import matplotlib.pyplot as plt
import numpy as np

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

zs = [0.0, 1.0, 2.0]
t  = np.arange(1024)*1e-6
ones = np.ones(1024)
y1 = np.sin(t*2e3*np.pi)
y2 = 0.5*y1
y3 = 0.25*y1

verts=[list(zip(t, y1)), list(zip(t, y2)), list(zip(t, y3))]

poly = PolyCollection(verts, facecolors = ['r','g','b'])
poly.set_alpha(0.7)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlabel('X')
ax.set_xlim3d(0, 1024e-6)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 3)
ax.set_zlabel('Z')
ax.set_zlim3d(-1, 1)

plt.show()

rawDescription: Python 2D plots as 3D (Matplotlib)

description: Python 2D plots as 3D (Matplotlib)


code:
class Calculation(object):
    def some_calculation(self, some_variable, calculate=math.multiplication):
        """some_calculation(some_variable, calculate=math.multiplication)

           More text...
        """
        ...

rawDescription: Sphinx can't cope with function assignment inside class definition


code:
class PlayList(models.Model):
    playlist = models.CharField(max_length=2000)

class UserProfile(models.Model):
    # do you want each `User` to only have one `UserProfile`? If so then OneToOne
    # primary keys are automatically formed by django
    # how django handles profiles: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.User

class UserPlayList(models.Model):
    # don't capitalise attributes, if you haven't seen PEP8 before, do now: http://www.python.org/dev/peps/pep-0008/
    profile = models.ForeignKey(User)
    playlist = models.ForeignKey(PlayList)

class Video(models.Model):
    video_url = models.URLField(max_length=200, null=True, blank=True, help_text="Link to video")

    def __unicode__(self):
        return self.video_url

class VideoPlayList(models.Model):
    video = models.ForeignKey(Video)
    play_list = models.ForeignKey(UserPlayList)

rawDescription: What is the proper way to structure models.py?


code: re.search(u'[\u30a0-\u30ff]', u'カタカナ')

rawDescription: Python and Unicode Blocks for regex

description: Python and Unicode Blocks for regex


code:
import time
from selenium import webdriver

driver = webdriver.Firefox()
start = time.time()
driver.get('http://stackoverflow.com')
end = time.time()
print(end - start)
driver.quit()

rawDescription: Measure the time a browser needs to open a url completely


code:
from operator import itemgetter
from difflib import SequenceMatcher

class Corrector(object):

    def __init__(self, possibilities):
        self.possibilities = possibilities
        self.sums = sum(self.possibilities.values())

    def correct(self, word):
        corrections = {}
        sm = SequenceMatcher(None, word, '')
        for w, t in self.possibilities.iteritems():
            sm.b = w
            corrections[w] = sm.ratio() * t/self.sums
        return max(corrections.iteritems(),key=itemgetter(1))[0]

rawDescription: Spell checker speed up

description: Spell checker speed up


code:
@gen.coroutine
def post(self):
    input_dict = ...
    result = yield executor.submit(expensive_function, input_dict)

rawDescription: Queue and ProcessPoolExecutor in Tornado


code:
docfile = instance.decoder(segments)
response = HttpResponse()
response.write(docfile)
response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name)
return response

rawDescription: django: Is there anyway to serve a file directly from memory

description: Django: Is there anyway to serve a file directly from memory


code:
def get_info(self,node):
    self.values_list.append([node.get(i) for i in list_of_attributes])

rawDescription: Python xml.etree.ElementTree - how to reference the current node that I am parsing


rawDescription: Hide window title bar in pygtk

description: Hide window title bar in pygtk


code:
plt.figure()
CS = plt.contour(X, Y, Z)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')

rawDescription: matplotlib contourf: get Z value under cursor

description: Matplotlib contourf: get Z value under cursor


code:
import pymel.core as pc

mesh = "foo_mesh"
xml = "foo_mesh_cache.xml"
data = "foo_mesh_data.mc"

pc.mel.doImportCacheFile(xml, "", [mesh], list())

rawDescription: importing multiple cache files in Maya using Python

description: Importing multiple cache files in Maya using Python


code:
# load the pipe-delimited replacements into a list
with open ("c:\\pipes.txt", "r") as myfile:
    pipes=myfile.read().split('|')

# keep track of which replacement we are up to
ix = 0

def processmatch(line, match):
    # we want to use these variables which were declared outside the function
    global ix
    global pipes
    # if we still have replacement text to use..
    if ix < len(pipes):
        # replace this match text with the current replacement
        editor.setTargetStart(editor.positionFromLine(line) + match.start())
        editor.setTargetEnd(editor.positionFromLine(line) + match.end())
        editor.replaceTarget(pipes[ix])
        # use the next replacement next time
        ix += 1

# everything the script does will be undone with a single ctrl+Z
editor.beginUndoAction()

# call processmatch for every instance of the target text
editor.pysearch('zyzyzy', processmatch)

editor.endUndoAction()

rawDescription: Replace some string with delimited text

description: Replace some string with delimited text


code: [x for x in range(2,100) if x in mylist and x not in theirList if not name or x%2 ]

rawDescription: How to remove code duplicity in python list comprehension?

description: Remove code duplicity in python list comprehension


code:
ListBox1 = Listbox(TopFrame)
ListBox1.grid(row=2,column=2, rowspan=7)

rawDescription: Python Tkinter - Listbox absolute positioning


code:
for line in fileh:
    line = line.replace("enabled", "disabled")
    ouf.write(line)

rawDescription: Find a replace string in xml file with python


code:
keepMoving = True
mylist = []
while keepMoving:
    x = input("enter a number:")
    if x.isnumeric():
         mylist.append(int(x))
    else:
         keepMoving = False
print(max(mylist))

rawDescription: How do I make my script take only numeric inputs without screwing it up

description: Make my script take only numeric inputs without screwing it up


code:
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_file, show

data = pd.DataFrame({'Symbol' : ['AMBA','FB','WWD','AMBA','FB','WWD','AMBA','FB','WWD','AMBA','FB','WWD','AMBA','FB','WWD','AMBA','FB','WWD',],
                     'Previous_Close' : [10,20,30,10,20,30,10,20,30,10,20,30,10,20,30,10,20,30,],
                     'Date' : pd.to_datetime(['01/01/16', '01/01/16', '01/01/16', '01/02/16', '01/02/16', '01/02/16', '01/03/16', '01/03/16', '01/03/16', '01/04/16', '01/04/16', '01/04/16', '01/05/16', '01/05/16', '01/05/16', '01/06/16', '01/06/16', '01/06/16'], format = '%m/%d/%y')})

symbols = [sym for sym in data.Symbol.unique()]
dates = [date for date in data.Date.unique()]
dates.sort()
lastDate = dates[-1]
colors = ['Darkred', 'Orange', 'Navy']

output_notebook()

TOOLS = ['hover','pan','box_zoom','resize', 'save', 'reset']
# CREATE FIGURE
p = figure(width = 800, height = 600, tools = TOOLS, x_axis_type="datetime")

# PLOT
for cnum, sym in enumerate(symbols):
    # plot stock closing price
    p.line(data[data.Symbol==sym].Date.values, data[data.Symbol==sym].Previous_Close.values, color = colors[cnum])

p.text(data[data.Date==lastDate].Date.values, data[data.Date==lastDate].Previous_Close.values, data[data.Date==lastDate].Symbol.values, text_color = colors, text_font_size = '10pt')

show(p)

rawDescription: Python Bokeh Tick Labels

description: Python Bokeh Tick Labels


code:
import Queue
# maxsize of 0 means that we can put an unlimited number of events
# on the queue
q = Queue.Queue(maxsize=0)

def network_thread():
    while True:
        e = get_network_event()
        q.put(e)

def logic_thread():
    while True:
        # This will wait until there are events to process
        e = q.get()
        process_event(e)

rawDescription: Are there any built-in cross-thread events in python?


code:
A = {'one':1, 'two':2}
B = {'one':1, 'two':999, 'three':3}

for k,v in B.items():
    A.setdefault(k, v)

print(A)

rawDescription: dictionary difference opration

description: Dictionary difference opration


code:
application.search_job(selectors=[{'jobs': ['id',
                                            'customer-job-code',
                                            'posting-date']}],
                       params={'title': 'python', 'count': 2})
# Output
{u'jobs': {u'_count': 2,
  u'_start': 0,
  u'_total': 206747,
  u'values': [{u'customerJobCode': u'0006YT23WQ',
    u'id': 5174636,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}},
   {u'customerJobCode': u'00023CCVC2',
    u'id': 5174634,
    u'postingDate': {u'day': 21, u'month': 3, u'year': 2013}}]}}

rawDescription: Linkedin Company Search API : Get All Counts


code:
Ig_txts = []
i=340
while i <= 1020:
    Ig_txts.append( 'Ig='+str(i) )
    i += 40

for Ig_txt in Ig_txts:
    path = 'C:/test/'+Ig_txt+'/340_TXT'
    out_file = 'C:/test/'+Ig_txt+'/Grey_Zone.csv'

    os.chdir(path)
    ...
    ...

rawDescription: Looping through a directory, importing and processing text files in a chronology order using Python


code:
x = [12, 101, 4, 56]
y = range(len(x))
sorted(y, key=x.__getitem__)

rawDescription: python sort without lambda expressions

description: Python sort without lambda expressions


code:
grid = [['-']*8 for n in range(8)]
insertPoint = random.randrange(1,8)
for i in range(8):
    for j in range(8):
        if i==insertPoint:
            grid[i][j] = 'Q';

rawDescription: What can I do to make this code work?

description: What can I do to make this code work


code:
import random
N = 10
idx = set(random.sample(range(N), N//2))
idx
''.join(['[' if i in idx else ']' for i in range(N)])

rawDescription: Python, Generating random string of brackets


rawDescription: numpy.correlate: Relation between full and valid

description: Numpy.correlate: Relation between full and valid


code:
df = pd.read_csv("trans.csv", skipinitialspace=True)
w = df.groupby(["person", "product"])["val"].sum().reset_index()
w
w.pivot("person", "product").fillna(0)
w.pivot("person", "product").fillna(0).values

rawDescription: Efficient way to load file into 2d numpy array


code:
# List files in directory and upload them to bucket
for filename in all_files:
    #skip all directory entries which are not a file
    if not os.path.isfile(filename):
          continue
    k = Key(bucket)
    k.key = os.path.basename(filename)
    k.set_contents_from_filename(filename, cb=percent_cb, num_cb=10)

rawDescription: Strip path from filename

description: Strip path from filename


code:
import smtplib

msg = """From: hello@hello.com
To: hi@hi.com\n
Subject: <Subject goes here>\n
Here's my message!\nIt is lovely!
"""

server = smtplib.SMTP_SSL('smtp.example.com', port=465)
server.set_debuglevel(1)
server.ehlo
server.login('examplelogin', 'examplepassword')
server.sendmail('me@me.com', ['anyone@anyone.com '], msg)
server.quit()

rawDescription: Add Subject header to server.sendmail() in Python


code:
@list_route(
    methods=['post'], permission_classes=[AllowAny],
    authentication_classes=[NoAuthentication]
)
def recover_password(self, request):
    if request.DATA.get('email'):
        # Lets be smart and reuse django-allauth password recovery system
        form = ResetPasswordForm({'email': request.DATA.get('email')})
        if form.is_valid():
            form.save()
            return Response(status=200)
    return Response(status=400)

rawDescription: Django Rest Framework + Django-Allauth Password Reset/Recovery


rawDescription: Finding the Last Time a Particular Numpy Array has a Value


code:
cross = df.pivot_table(index="col1", columns="col2", aggfunc='size') == 1
cross
cross.all()
cross.columns[cross.all()]

rawDescription: Finding intersection of values in a column associated with unique values in another column Pandas


code:
import yaml
yaml.load('time: "10:01"')

rawDescription: PyYAML interprets string as timestamp

description: PyYAML interprets string as timestamp


code:
def sendLine(self, line):
    return self.transport.write(line + self.delimiter)

rawDescription: self.sendLine or self.transport.write?

description: Self.sendLine or self.transport.write


code:
def dfs(G,a,b,u):
    global i
    G.node[u]['visited'] = 'yes'
    i += 1
    G.node[u]['label'] = i
    print(u)
    print("i", i)
    for v in G.neighbors(u):
        if v == b:
            G.node[v]['visited'] = 'yes'
            i += 1
            G.node[v]['label'] = i
            print("b is ", v)
            print("distance from a to b is ", G.node[v]['label'])
            return True
        elif v != b:
            if G.node[v]['visited'] == 'no':
                found = dfs(G,a,b,v)
                if found:
                    return True
    return False

rawDescription: How to break out a function without return or break in Python

description: Break out a function without return or break in Python


code:
x = [b'\xe1\xa5', b'\x8c*']
[[bin(n) for n in char] for char in x]

rawDescription: Reading a string from a file in binary mode (using Python 3)


code:
data_file = sc.parallelize([
   (u'u1', u's1', 20), (u'u1', u's2', 5),
   (u'u2', u's3', 5), (u'u2', u's2', 10)])

max_by_group = (data_file
  .map(lambda x: (x[0], x))  # Convert to PairwiseRD
  # Take maximum of the passed arguments by the last element (key)
  # equivalent to:
  # lambda x, y: x if x[-1] > y[-1] else y
  .reduceByKey(lambda x1, x2: max(x1, x2, key=lambda x: x[-1]))
  .values()) # Drop keys

max_by_group.collect()
## [('u2', 's2', 10), ('u1', 's1', 20)]

rawDescription: pyspark: grouby and then get max value of each group

description: Pyspark: grouby and then get max value of each group


code:
class User(object):
    def __init__():
        self.first_name = 'Mr'
        self.last_name = 'Anderson'

    @property
    def name():
        return self.first_name + ' ' + self.last_name

rawDescription: How to call method as a property in Python?

description: Call method as a property in Python


code:
import cairo
import pygame

width = 300
height = 200

pygame.init()
pygame.fastevent.init()
clock = pygame.time.Clock()
sdl_surface = pygame.display.set_mode((width, height))

c_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(c_surface)

while True:
    pygame.fastevent.get()
    clock.tick(30)
    ctx.rectangle(10, 10, 50, 50)
    ctx.set_source_rgba(1.0, 0.0, 0.0, 1.0)
    ctx.fill_preserve()

    dest = pygame.surfarray.pixels2d(sdl_surface)
    dest.data[:] = c_surface.get_data()[::-1]
    tmp = pygame.transform.flip(sdl_surface, True, True)
    sdl_surface.fill((0,0,0))    #workaround to clear the display
    del dest     #this is needed to unlock the display surface
    sdl_surface.blit(tmp, (0,0))
    pygame.display.flip()

rawDescription: Byte order when using Cairo in PyGame (SDL)


code:
import csv, codecs, cStringIO

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

rawDescription: In python writing from XML to CSV, encoding error


code:
from unittest import signals
signals.__file__

rawDescription: Which package is Python using?

description: Which package is Python using


rawDescription: How to query an association table in SQLAlchemy?

description: Query an association table in SQLAlchemy


code:
import re

t = 'a b c 100 200'

f = lambda x: str(int(x.group(0)) / 10)
re.sub('\d+', f, t)

# returns 'a b c 10 20'

rawDescription: python re.sub with an integer operation

description: Python re.sub with an integer operation


code:
import sys
from PyQt4 import QtCore, QtGui

class AppWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(AppWidget, self).__init__(parent)
        horizontalLayout = QtGui.QHBoxLayout()
        self.styleLabel = QtGui.QLabel("Set Style:")
        self.styleComboBox = QtGui.QComboBox()
        # add styles from QStyleFactory
        self.styleComboBox.addItems(QtGui.QStyleFactory.keys())
        # find current style
        index = self.styleComboBox.findText(
                    QtGui.qApp.style().objectName(),
                    QtCore.Qt.MatchFixedString)
        # set current style
        self.styleComboBox.setCurrentIndex(index)
        # set style change handler
        self.styleComboBox.activated[str].connect(self.handleStyleChanged)
        horizontalLayout.addWidget(self.styleLabel)
        horizontalLayout.addWidget(self.styleComboBox)
        self.setLayout(horizontalLayout)

    # handler for changing style
    def handleStyleChanged(self, style):
        QtGui.qApp.setStyle(style)

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    widgetApp = AppWidget()
    widgetApp.show()
    sys.exit(app.exec_())

rawDescription: Setting style in using QStyleFactory from a list of styles in a QComboBox


code:
result = [k for k in my_dict if my_dict[k] > min_value and
                                (allow_all_keys or k in allowed_keys)]

rawDescription: What's a pythonic way to check membership in a list that could be None?


code:
class SomeClass(models.Model):
    @property
    def is_complete(self):
        if not hasattr(self, '_is_complete'):
            related_objects = self.do_complicated_database_lookup()
            self._is_complete = len(related_objects) == 0
        return self._is_complete

rawDescription: Idiomatic python - property or method?

description: Idiomatic python - property or method


code:
import klepto
from klepto import lru_cache as memoize
from klepto.keymaps import hashmap
hasher = hashmap(algorithm='md5')
@memoize(keymap=hasher)
def squared(x):
  print("called")
  return x**2

squared(1)
squared(2)
squared(3)
squared(2)

cache = squared.__cache__()
# delete the 'key' for x=2
cache.pop(squared.key(2))
squared(2)

rawDescription: Decorators for selective caching / memoization


code: p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout, stdout=subprocess.PIPE)

rawDescription: Python - how to execute shell commands with pipe?


code:
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from tutorial.items import MangaItem
from urlparse import urlparse

class MangaHere(BaseSpider):
    name = "mangah2"
    start_urls = ["http://www.mangahere.com/seinen/"]
    allowed_domains = ["mangahere.com"]

    def parse(self, response):
        # get index depth ie the total number of pages for the category
        hxs = HtmlXPathSelector(response)
        next_link = hxs.select('//a[@class="next"]')
        index_depth = int(next_link.select('preceding-sibling::a[1]/text()').extract()[0])

        # create a request for the first page
        url = urlparse("http://www.mangahere.com/seinen/")
        yield Request(url.geturl(), callback=self.parse_item)

        # create a request for each subsequent page in the form "./seinen/x.htm"
        for x in xrange(2, index_depth):
            pageURL = "http://www.mangahere.com/seinen/%s.htm" % x
            url = urlparse(pageURL)
            yield Request(url.geturl(), callback=self.parse_item)

    def parse_item(self,response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//ul/li/div')
        items = []
        for site in sites:
            rating = site.select("p/span/text()").extract()
            for r in rating:
                if float(r) > 4.5:
                    item = MangaItem()
                    item["title"] = site.select("div/a/text()").extract()
                    item["desc"] = site.select("p[2]/text()").extract()
                    item["link"] = site.select("div/a/@href").extract()
                    item["rate"] = site.select("p/span/text()").extract()
                    items.append(item)
        return items

rawDescription: How do i create rules for a crawlspider using scrapy

description: Create rules for a crawlspider using scrapy


code:
fo =open("headerValue.txt", "r")
data = [l.split() for l in fo.readlines()]
headers = data[0]
headers.extend(('Eligibility', 'Adult'))
ageind = headers.index('Age')
for line in data[1:]:
    if int(line[ageind]) > 18:
        line.extend(('True', 'yes'))
    else:
        line.extend(('False', 'no'))

rawDescription: Python updating a text file adding headers and their corresponding values


code:
params = {'sites[]': [951, 1007, ...], 'action': 'set', 'extype': 'exclude'}
requests.post('url', data=params)

rawDescription: python requests - posting multiple values with same key, combined with regular keys

description: Python requests - posting multiple values with same key, combined with regular keys


code: a - a.min(axis=0)

rawDescription: Numpy python find minimum value of each column and subtract this value from each column


code:
g=load("test.ncol", directed=False)
g.multilevel_community().q
g.multilevel_community(weights=g.es["weight"]).q

rawDescription: Different result of community detection function in igraph R and Python


code:
class Class2(object):
    def __init__(self):
        self.c1 = Class1()
        self.c1.function1()

rawDescription: How to use functions between classes in python

description: Use functions between classes in python


rawDescription: Tkinter binding mouse double click

description: Tkinter binding mouse double click


code:
import win32com.client
h = win32com.client.Dispatch('matlab.application')
h.Execute ("plot([0 18], [7 23])")
h.Execute ("1+1")

rawDescription: Calling MATLAB functions from python

description: Calling MATLAB functions from python


code:
headers = {'Content-Length': content_length, 'Host': 'Server-1:8080',
           'User-Agent': None, 'Connection': None, 'Accept-Encoding': None}

rawDescription: Python requests module - send only specified headers


code:
from pytagcloud import (create_tag_image, create_html_data,
    make_tags, LAYOUT_MIX)
from pytagcloud.lang.counter import get_tag_counts
from pytagcloud.colors import COLOR_SCHEMES
import webbrowser

# ...the rest of your code...

def wordcloud(self):
    words = nltk.word_tokenize(self._contents)
    doc = " ".join(d for d in words[:70])

    tags = make_tags(get_tag_counts(doc), maxsize=100)
    data = create_html_data(tags, (1600,1200), layout=LAYOUT_MIX, fontname='Philosopher', rectangular=True)

rawDescription: How to hover over the word in word cloud

description: Hover over the word in word cloud


rawDescription: Ensure two Pandas DatetimeIndexes are the same?


code:
xpath = '''//*[self::x or self::y or self::z]
              [descendant::w[@attrib and @attrib2='{0}']]
        '''.format(variable)

rawDescription: How to select specific elements with certain attributes using AND in XPath?

description: Select specific elements with certain attributes using AND in XPath


code:
if sourceRef:
    ds = open(sourceRef, 'rb')
else:
    ds = self._validate(source)

with ds:
    dstreams['master'] = self._generateMasterFile(ds)

rawDescription: Using a conditional 'with' statement in Python


code:
import Tkinter as tk
import tkFileDialog

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.button = tk.Button(text="Pick a file!", command=self.pick_file)
        self.button.pack()
        self.entry_frame = tk.Frame(self)
        self.entry_frame.pack(side="top", fill="both", expand=True)
        self.entry_frame.grid_columnconfigure(0, weight=1)

    def pick_file(self):
        file = tkFileDialog.askopenfile(title="pick a file!")
        if file is not None:
            entry = tk.Entry(self)
            entry.insert(0, file.name)
            entry.grid(in_=self.entry_frame, sticky="ew")
            self.button.configure(text="Pick another file!")

app = SampleApp()
app.mainloop()

rawDescription: Dynamically resizing and adding widgets to Tkinter window


rawDescription: Maximum sum of sublist with a specific length


code:
q = """select a.gvkey,
    a.tic,                      -- COMMENTS
    a.datadate as fyearend,     -- COMMENTS
    year(a.datadate) as year,   /* Another very long
    and multi-lines comment... */
    month(a.datadate) as fyrc, b.datadate,
    month(b.datadate) as month,
    b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate)
    where a.TIC = "IBM"
        and a.datafmt = "STD"
        and a.consol="C"
        and a.indfmt = "INDL"
        and year(a.datadate)>1980
"""

result = p.read_sql_query(q, conn)

rawDescription: Is there a way to write a pandas SQL query across multiple lines with comments?


code:
a = np.arange(100).reshape(10, 10)
a
lilm = scipy.sparse.lil_matrix(a)
lilm[[1, 2, 3], :].toarray() # extract the rows first...
lilm[[1, 2, 3], :][:, [4, 5, 6]].toarray() # ...then the columns

rawDescription: Slicing a scipy.sparse.lil_matrix in rows and columns


code:
def read_labeled_image_list(image_list_file):
    """Reads a .txt file containing pathes and labeles
    Args:
       image_list_file: a .txt file with one /path/to/image per line
       label: optionally, if set label will be pasted after each line
    Returns:
       List with all filenames in file image_list_file
    """
    f = open(image_list_file, 'r')
    filenames = []
    labels = []
    for line in f:
        filename, label = line[:-1].split(' ')
        filenames.append(filename)
        labels.append(int(label))
    return filenames, labels

def read_images_from_disk(input_queue):
    """Consumes a single filename and label as a ' '-delimited string.
    Args:
      filename_and_label_tensor: A scalar string tensor.
    Returns:
      Two tensors: the decoded image, and the string label.
    """
    label = input_queue[1]
    file_contents = tf.read_file(input_queue[0])
    example = tf.image.decode_png(file_contents, channels=3)
    return example, label

# Reads pfathes of images together with their labels
image_list, label_list = read_labeled_image_list(filename)

images = ops.convert_to_tensor(image_list, dtype=dtypes.string)
labels = ops.convert_to_tensor(label_list, dtype=dtypes.int32)

# Makes an input queue
input_queue = tf.train.slice_input_producer([images, labels],
                                            num_epochs=num_epochs,
                                            shuffle=True)

image, label = read_images_from_disk(input_queue)

# Optional Preprocessing or Data Augmentation
# tf.image implements most of the standard image augmentation
image = preprocess_image(image)
label = preprocess_label(label)

# Optional Image and Label Batching
image_batch, label_batch = tf.train.batch([image, label],
                                          batch_size=batch_size)

rawDescription: Tensorflow read images with labels

description: Tensorflow read images with labels


code:
def time_after_time(time_a, time_b):
    time_a_min = time_a.hour * 60 + time_a.minute
    time_b_min = time_b.hour * 60 + time_b.minute
    out_min = time_b_min - time_a_min
    if out_min < 0:
        out_min += 24 * 60
    return datetime.time(out_min / 60, out_min % 60)

rawDescription: counting forward work out how long time a is after time b

description: Counting forward work out how long time a is after time b


code: tp = mystruct.type

rawDescription: How to access the keys or values of Python GDB Value

description: Access the keys or values of Python GDB Value


code:
import os
filename = 'tempfile'
def write(filename,data,offset):
    try:
        f = open(filename,'r+b')
    except IOError:
        f = open(filename,'wb')
    f.seek(offset)
    f.write(data)
    f.close()
write(filename,'1' * (1024*32),1024*1024)
write(filename,'1' * (1024*32),0)
os.path.getsize(filename)

rawDescription: Writing binary data to middle of a sparse file


code:
from dateutil import parser
parser.parse('April 29, 2013, 7:52 p.m.')
parser.parse('April 30, 2013, 4 p.m.')

rawDescription: Python strptime or alternative for complex date string parsing


code:
import active_directory

homeMDB = "CN=UBER MAILBOX,CN=InformationStore,CN=UBERMAILSERVER,"\
        "CN=Servers,CN=Administrative Groups,CN=UBERORG,"\
        "CN=Microsoft Exchange,CN=Services,CN=Configuration,"\
        "DC=uber,DC=org,DC=uk"

user=active_directory.find_user("captain.awesomeface")
user.CreateMailbox(homeMDB)

user.Properties["mail"].Value = "captain.awesomeface@uberorg.com";

user.SetInfo()

rawDescription: Create exchange Mailbox from python

description: Create exchange Mailbox from python


code:
from random import randrange
def roll():
    rolled = randrange(1,7)
    if rolled == 1:
        return "1"
    if rolled == 2:
        return "2"
    if rolled == 3:
        return "3"
    if rolled == 4:
        return "4"
    if rolled == 5:
        return "5"
    if rolled == 6:
        return "6"

def rollManyCountFour(n):
    fourCount = 0
    for i in range (n):
        if roll() == "6":
            fourCount += 1
    print ("In", n,"rolls of a due, there were",fourCount,"fours.")

rollManyCountFour(6000)

rawDescription: Python - rolling a dice fairly and counting how many 4's I get


code:
import random
L = []
for x in range(5):
  l = range(5)
  random.shuffle(l)
  L.append(l)

rawDescription: Applying a method with no return value to each element of a list


code:
dta = 26
limit = 130

dist_to_agree = np.zeros_like(x)
dist_min = []

ym = y-limit
yp = y+limit
for i, xi in enumerate(x):
    irange = (i-np.arange(i+10-dta, i+10+dta))**2
    if not irange.size:
        continue

    ymi = ym[i+10-dta:i+10+dta, :]
    ypi = yp[i+10-dta:i+10+dta, :]

    for j, xij in enumerate(xi):
        jrange = (j-np.arange(j+10-dta, j+10+dta))**2
        if not jrange.size:
            continue

        ymij = ymi[:, j+10-dta:j+10+dta]
        ypij = ypi[:, j+10-dta:j+10+dta]

        imesh, jmesh = np.meshgrid(irange, jrange, indexing='ij')
        dist = np.sqrt(imesh+jmesh)
        dist[ymij > xij  or xij < ypij]  = 10

        mindist = dist.min()
        dist_min.append(mindist)
        dist_to_agree[i,j] = mindist

print(dist_to_agree)

rawDescription: Speeding up array iteration time in python


code: sum(int(n) for n in str(2**1000))

rawDescription: Python code simplification? One line, add all in list


code:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog

interface = Tk()

def openfile():
    return filedialog.askopenfilename()

button = ttk.Button(interface, text="Open", command=openfile)  # <------
button.grid(column=1, row=1)

interface.mainloop()

rawDescription: Simplest way to open a file in tkinter

description: Simplest way to open a file in tkinter


rawDescription: Remove Words From A DF that appear in another DF (Pandas,Python3)


rawDescription: Selenium select with class

description: Selenium select with class


code:
from lxml import html

tree = html.parse('http://www.datamystic.com/timezone/time_zones.html')
table = tree.findall('//table')[1]
data = [
           [td.text_content().strip() for td in row.findall('td')]
           for row in table.findall('tr')
       ]

rawDescription: Fastest, easiest, and best way to parse an HTML table?


code:
X = np.reshape(x, (4,4))
Y = np.reshape(y, (4,4))
nb2 = np.reshape(nb_means, (4,4))
...
ax.plot_wireframe(X, Y, nb2)

rawDescription: Matplotlib 3d Wire Frame plot not plotting as expected


code: response = self.c.get('/emails/html/upload', SERVER_NAME="mydomain.com")

rawDescription: Change the default domain of Client() in unittest of Django


code:
iris = datasets.load_iris()
df=pd.DataFrame(iris.data)
colMap={0:"red",1:"blue",2:"yellow"}
cols=list(map(lambda x:colMap.get(x),iris.target))
scatter_matrix(df,  diagonal='hist',c=cols)

rawDescription: How to paint pandas scatter matrix?

description: Paint pandas scatter matrix


code:
def maketype(cls):
    cls.type = TextField(default=cls.__name__)
    return cls

rawDescription: Python grab class in class definition

description: Python grab class in class definition


code:
ast.fit(x)
p = ast.fit(x, f0=100)
print(stats.kstest(x, ast.cdf, args=p))
p = ast.fit(x, f0=5)
print(stats.kstest(x, ast.cdf, args=p))

rawDescription: Is it possible to use a distribution from statsmodels with scipy.stats?


code:
class MyMessageHandler(object):
    def __init__(self):
        self.sockets = [...]

    def wait(self):
        debug('waiting...')
        i, o, e = select(...)

rawDescription: Casting sockets to subtypes

description: Casting sockets to subtypes


code:
from argparse import ArgumentParser
p = ArgumentParser()
_ = p.add_argument('-f', '--foo', action='store_true')
args = p.parse_args()
args.foo
args = p.parse_args(['-f'])
args.foo

rawDescription: argparse module How to add option without any argument?

description: Argparse module How to add option without any argument


code:
from collections import defaultdict

dolol=defaultdict(list)
for data in lol:
    dolol[data[0],data[1]].append(data[2:])

rawDescription: Python - dividing a list-of-lists to groups


code:
from functools import wraps

class ClassDecorator:
    """ClassDecorator docstring
    """
    def __init__(self, enableCache=True):
        self.enableCache = enableCache

    def __call__(self, wrapper):
        @wraps(wrapper)                              # <-----------
        def numericalmathfunction(*args, **kwargs):
            func = wrapper(*args, **kwargs)
            return func
        return numericalmathfunction

@ClassDecorator(enableCache=True)
class Wrapper(object):
    """Wrapper docstring
    Instructions on how to use the Wrapper
    """
    def __init__(self, p):
        self.p = p

rawDescription: Why does a decorated class looses its docstrings?


code:
from django.db.models import Case, F, Sum, When

Stats.objects.values('product').annotate(
    tot_impressions=Sum('impressions'),
    tot_clicks=Sum('clicks')
).annotate(
    ctr=Case(When(tot_impressions=0, then=None),  # or other value, e.g. then=0
             # 1.0*... is to get float in SQL
             default=1.0*F('tot_clicks')/F('tot_impressions'),
             output_field=models.FloatField())
).order_by('ctr')

rawDescription: Django query expression for calculated fields that require conditions and casting


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

np.random.seed(101)
x = np.random.random(100)
y = np.random.random(100)

fig = plt.figure()
ax = fig.add_subplot(111)
imForEngland = ax.scatter(x,y)
fig.savefig('beforeclip.png')
imForWales = ax.scatter(x,y)
england = patches.Circle((.75,.75),radius=.25,fc='none')
wales = patches.Circle((.25,.25),radius=.25,fc='none')
ax.add_patch(england)
ax.add_patch(wales)
imForEngland.set_clip_path(england)
imForWales.set_clip_path(wales)

fig.savefig('afterclip.png')

rawDescription: Clip an image using several patches in matplotlib


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

lines=[]
for i in range(10):
    for j in range(10):
        lines.append([(0, i), (1, j)])

fig, ax = plt.subplots()
colors = np.random.random(len(lines))
col = LineCollection(lines, array=colors, cmap=plt.cm.gray)
ax.add_collection(col)
ax.autoscale()

def update(i):
    colors = np.random.random(len(lines))
    col.set_array(colors)
    return col,

# Setting this to a very short update interval to show rapid drawing.
# 25ms would be more reasonable than 1ms.
ani = animation.FuncAnimation(fig, update, interval=1, blit=True,
                              init_func=lambda: [col])
# Some matplotlib versions explictly need an `init_func` to display properly...
# Ideally we'd fully initialize the plot inside it. For simplicitly, we'll just
# return the artist so that `FuncAnimation` knows what to draw.
plt.show()

rawDescription: Animation based on only updating colours in a plot


code:
# download some files from the login directory
host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret')
names = host.listdir(host.curdir)
for name in names:
    if host.path.isfile(name):
        host.download(name, name, 'b')        # remote, local, binary mode

rawDescription: Traversing an ftp folder with python

description: Traversing an ftp folder with python


rawDescription: Breaking a Python URL generated w/ several variables back into components


code:
while 1:
    buf = fsrc.read(length)
    if not buf:
        break
    fdst.write(buf)

rawDescription: shutil.move() method in shutil module in Python

description: Shutil.move() method in shutil module in Python


code: t.left(90) # then call tree after with tree()

rawDescription: Making a Tree using Turtle (That is right side up)


code:
D = {'x': [15, 20],
     'y': [11, 12, 14, 16, 19],
     'z': [7, 9, 17, 18]}

order = ['x', 'y', 'z']
pairs = zip(order[:-1], order[1:])

counts = dict()
for pair in pairs:
    counts[pair[0]] = dict()
    for num in D[pair[0]]:
        counts[pair[0]][num] = len([el for el in D[pair[1]] if el >= num])

rawDescription: Sorted tuples from cartesian product of lists


code:
from ctypes import *

a = pointer(c_int(123))
b = pointer(c_int(456))

tmp = pointer(a)[0]
tmp.contents = b.contents

rawDescription: Update ctypes pointer in place

description: Update ctypes pointer in place


code:
import random
format(random.randint(1, 12), '02')

rawDescription: python, generate random string in range 01-12

description: Python, generate random string in range 01-12


code:
from kafka.client import KafkaClient
from kafka.producer import SimpleProducer,KeyedProducer
import logging,sys

class KafkaLoggingHandler(logging.Handler):

    def __init__(self, host, port, topic, key=None):
        logging.Handler.__init__(self)
        self.kafka_client = KafkaClient(host, port)
        self.key = key
        if key is None:
            self.producer = SimpleProducer(self.kafka_client, topic)
        else:
            self.producer = KeyedProducer(self.kafka_client, topic)

    def emit(self, record):
        #drop kafka logging to avoid infinite recursion
        if record.name == 'kafka':
            return
        try:
            #use default formatting
            msg = self.format(record)
            #produce message
            if self.key is None:
                self.producer.send_messages(msg)
            else:
                self.producer.send(self.key, msg)
        except:
            import traceback
            ei = sys.exc_info()
            traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
            del ei

    def close(self):
        self.producer.stop()
        logging.Handler.close(self)

kh = KafkaLoggingHandler("localhost", 9092, "test_log")
#OR
#kh = KafkaLoggingHandler("localhost", 9092, "test_log", "key1")

logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
logger.addHandler(kh)
logger.info("The %s boxing wizards jump %s", 5, "quickly")
logger.debug("The quick brown %s jumps over the lazy %s", "fox",  "dog")
try:
    import math
    math.exp(1000)
except:
    logger.exception("Problem with %s", "math.exp")

rawDescription: How to write to Kafka from Python logging module?

description: Write to Kafka from Python logging module


code:
import numpy as np
from scipy.stats import norm, gaussian_kde
import matplotlib.pyplot as plt
from math import ceil

class cl():
    def __init__(self,x):
        self.x = np.array(x)
        self.mean = np.nanmean(x)
        self.std = np.nanstd(x)
    def pit(self):
         y = norm.cdf((self.x-self.mean)/self.std)
         kernel = gaussian_kde(y)
         title= r'$\mathrm{Histogram\ of\ pit:}$'
         self.plot(kernel.resample(10000).T, title)

    def plotx(self):
        title=r'$\mathrm{Histogram\ of\ x:}$'
        self.plot(self.x, title)

    def plot(self, x, title):

        nbins = ceil(2*len(x)**(1.0/3.0))
        n, bins, patches = plt.hist(x, nbins, normed=1, facecolor='green', alpha=0.75)
        plt.xlabel('X')
        plt.ylabel('Probability')
        plt.title(title)
        plt.grid(True)
        plt.draw()

test=cl(np.random.randn(100000))
plt.figure(1)
plt.subplot(211)
test.plotx()
plt.subplot(212)
test.pit()

plt.show()

rawDescription: Python - How to to use subplot for with different member functions of a class


code:
class PE(object):
    def __init__(self, name):
        self.name = name
        self.interfaces = []
        print('creating device',self.name)

rawDescription: Python - modifying objects in a dictionary with internal methods


rawDescription: How can I store a .CHM Help File as text with Python?

description: Store a .CHM Help File as text with Python


code:
for elm in driver.find_elements_by_css_selector('input.there.are.several.classes.input-sm'):
    elm.clear()
    elm.send_keys("2")

rawDescription: Python Selenium HTML class with multiple types and multiple data-binds


code:
from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID
import uuid

class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql's UUID type, otherwise uses
    CHAR(32), storing as stringified hex values.

    """
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value)
            else:
                # hexstring
                return "%.32x" % value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)

rawDescription: How to use UUIDs instead of integers in MySQL DB

description: Use UUIDs instead of integers in MySQL DB


code:
import json
measurement = 2
listcolorlist = [[234, 431, 134],
                 [214, 451, 114]]
listspeclist = [[0.34, 0.42, 0.45, 0.34, 0.78],
                [0.44, 0.32, 0.45, 0.37, 0.53]]
python_data = {"measurement" : 15000,
               "imi" : 0.5,
               "times" : 30,
               "recalibrate" : False,
               "data" : [{"colorlist" : listcolorlist[i],
                          "speclist" : listspeclist[i]}
                         for i in range(measurement)]}
print(json.dumps(python_data))

rawDescription: How to write a large number of nested records in JSON with Python

description: Write a large number of nested records in JSON with Python


code:
import tkinter as tk

def window1():
    window = tk.Toplevel(root)
    window.title("Welcome")

    # etc etc ...

    tk.Button(window,text="Enter...",command=lambda: window2(window)).pack()

def window2(old_window):
    old_window.destroy()
    # window2 stuff

root = tk.Tk()
root.iconify() # to minimize it, since we're just using Toplevels on top of it
window1()
root.mainloop()

rawDescription: New windows in tkinter

description: New windows in tkinter


code:
def extract_data_one():
    for item in sites:
        os.chdir(r"\\svr-dc\ftp site\%s\Daily" % item)
        subprocess.call(['7z', 'e', 'data1.zip', '*.*'])

rawDescription: 7z will not find archive using subprocess


code:
##
# This class is used to eliminate a standard Dock class' ability to detach and
# move (i.e. dragging this Dock will have no effect)
#
class MyDock(Dock):
    def __init__(self, name, area=None, size=(10, 10), widget=None, hideTitle=False, autoOrientation=True):

        # Initialize the baseclass
        #
        Dock.__init__(self, name, area, size, widget, hideTitle, autoOrientation)

        # Override the label's double click event.  Normally double clicking
        # the dock's label will cause it to detach into it's own window.
        #
        self.label.mouseDoubleClickEvent=self.noopEvent

    def dragEventEnter(self, ev):
        pass

    def dragMoveEvent(self, ev):
        pass

    def dragLeaveEvent(self, ev):
        pass

    def dragDropEvent(self, ev):
        pass

    def noopEvent(self,ev):
        pass

class MyDockArea(DockArea):
    def dragEventEnter(self, ev):
        pass

    def dragMoveEvent(self, ev):
        pass

    def dragLeaveEvent(self, ev):
        pass

    def dragDropEvent(self, ev):
        pas

rawDescription: pyqtgraph Lock dock layout

description: Pyqtgraph Lock dock layout


code:
import unittest
from mock import Mock, patch, DEFAULT, PropertyMock
from specific import SpecificClass

class A():
    def initialize(self):
        raise Exception("Too slow for tests!!!!")

    def fetch(self):
        return "INVALID"

class MyTestCase(unittest.TestCase):
    def test_specific_method(self):
        a = A()
        with patch.multiple(a, initialize=DEFAULT, fetch=DEFAULT) as mocks:
            mock_initialize, mock_fetch = mocks["initialize"], mocks["fetch"]
            mock_fetch.return_value = "a"
            sc = SpecificClass(a, "b", "c")
            self.assertEqual("dcbappenda", sc.specific_method("d"))
            mock_initialize.assert_called_with()

    def test_sanity_check(self):
        a = A()
        sc = SpecificClass(a, "b", "c")
        self.assertRaises(Exception, sc.specific_method, "d")

    #You can patch it in your module if it is imported by from .. as ..
    @patch("specific.GenericClass.__init__", autospec=True, return_value=None)
    def test_super_class(self, mock_init):
        sc = SpecificClass("a", "b", "c")
        mock_init.assert_called_with(sc, "a", "b")
        #Inject a and b
        sc.a = Mock()
        sc.b = "b"
        #configure a
        sc.a.fetch.return_value = "a"
        self.assertEqual("dcba", sc.specific_method("d"))
        sc.a.initialize.assert_called_with()

rawDescription: Mock superclass __init__ method or superclass as a whole for testing


rawDescription: How to find first instance of HTML comment starting with <!-- ? (Python)

description: Find first instance of HTML comment starting with <!-- ? (Python)


code:
df["B"] = df.groupby("A")["B"].diff().fillna(0)
df

rawDescription: Pandas groupby data and do calculation

description: Pandas groupby data and do calculation


code:
def splitRows(x):

    # Extract the actual list of time-stamps.
    theList = x.TimeStamps.iloc[0]

    # Each row will be a dictionary in this list.
    listOfNewRows = list()

    # Iterate over items in list of timestamps,
    # putting each one in a dictionary to later convert to a row,
    # then adding the dictionary to a list.

    for i in theList:
        newRow = dict()
        newRow['CreateDate'] = x.CreateDate.iloc[0]
        newRow['TimeStamps'] = i
        listOfNewRows.append(newRow)

    # Now convert these dictionaries into rows in a new dataframe and return it.
    return pd.DataFrame(listOfNewRows)

df.groupby('CreateDate', as_index = False, group_keys = False).apply(splitRows)

rawDescription: Splitting a List inside a Pandas DataFrame


code:
string1 or string2 or string3 # is the same as
(string1 or string2) or string3
# string1 or string2 is '' or 'Trondheim', and as
# '' is logically False, this results in 'Trondheim'
# 'Trondheim' or string3 is short-circuited and never evaluated,
# because a non-empty string is logically True

rawDescription: What is this code doing?

description: What is this code doing


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

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((2, 4), (0, 0), colspan=4)
ax0.plot(x, y)
ax1 = plt.subplot2grid((2, 4), (1, 0))
ax1.hist(y)
ax2 = plt.subplot2grid((2, 4), (1, 1))
ax2.hist(y)
ax2.set_yticklabels([])
ax2.set_yticks([])
ax3 = plt.subplot2grid((2, 4), (1, 2))
ax3.hist(y)
ax3.set_yticklabels([])
ax3.set_yticks([])
ax4 = plt.subplot2grid((2, 4), (1, 3))
ax4.hist(y)
ax4.set_yticklabels([])
ax4.set_yticks([])

plt.subplots_adjust(wspace=0) # no space left between hists in 2nd row

rawDescription: bunch of histograms next to each other

description: Bunch of histograms next to each other


code:
import tarfile
archive = tarfile.TarFile('/path/to/my/tarfile.tar')
max_size = 0
max_name = None
for file in archive.getmembers():
    if file.size > max_size:
        max_size = file.size
        max_name = file.name

print(max_size)
print(max_name)

rawDescription: Find largest file inside of tarball

description: Find largest file inside of tarball


code:
for a in [1, 2, 3]:
    print(a)

rawDescription: CSV Parsing, trying to understand some code


code: N.all(my_array > 0) if my_array[0] > 0 else N.all(my_array < 0)

rawDescription: Numpy: quickest way to check if all elements in an array have the same sign?


code:
c = reportlab.pdfgen.canvas.Canvas("test.pdf")
# draw some stuff on c
c.showPage()
c.setPageSize((700, 500)) #some page size, given as a tuple in points
# draw some more stuff on c
c.showPage()
c.save()

rawDescription: How to create a PDF document with differing page sizes in reportlab, python

description: Create a PDF document with differing page sizes in reportlab, python


code: flattend = [f for sublist in ((c.real, c.imag) for c in complex_list) for f in sublist]

rawDescription: Write a list of Complex Numbers as Binary Data


rawDescription: how to create a string which can be used as an array in python?

description: Create a string which can be used as an array in python


code:
import sys
import threading
import time
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

# Added new
class Communicate(QObject):
    signal = pyqtSignal(str)

class Some(QWidget):
    e = threading.Event()

    def btnfunc(self):
        self.e.set()

    def __init__(self):
        super().__init__()

        #communicate object
        self.comm = Communicate()
        self.comm.signal.connect(self.append_data)

        self.myButton = QPushButton('do next')
        self.logs = QTextEdit()

        self.mylay = QVBoxLayout()
        self.mylay.addWidget(self.myButton)
        self.mylay.addWidget(self.logs)

        self.setLayout(self.mylay)
        self.setGeometry(300, 300, 300, 550)
        self.setWindowTitle('mytest')
        self.show()
        t = threading.Thread(target=self.myfunc, args=( ))
        t.start()
        self.myButton.clicked.connect(self.btnfunc)

    def myfunc(self):
        for i in range(300):
            # time.sleep(0.4)
            #self.logs.append(str(i))
            self.comm.signal.emit(str(i))
            if i == 20:
                self.e.wait()

    def append_data(self, data):
        self.logs.append(data)

app = QApplication(sys.argv)
ex = Some()
sys.exit(app.exec_())

rawDescription: How to pause/play a thread in PyQT5?

description: Pause/play a thread in PyQT5


code:
import fileinput
import sys

for line in fileinput.input([filename], inplace=True):
    if condition:
        sys.stdout.write(newline)
    else:
        sys.stdout.write(line)

rawDescription: what is the way to replace a line in a file using python

description: What is the way to replace a line in a file using python


code:
import scipy.stats
a = np.array([ 0.,  1.,  1.,  1.,  0.])
b = np.array([ 0.,  1.,  0.,  1.,  1.])
c = np.array([ 1.,  0.,  1.,  1.,  1.])
m = np.vstack([a,b,c])
modes, counts = scipy.stats.mode(m)

modes

rawDescription: How do you make an array of lists from seperate arrays then find most frequent value per lists with python?

description: Make an array of lists from seperate arrays then find most frequent value per lists with python


code: next(s for s in reversed(list_of_string) if s)

rawDescription: How do I get the last non-empty item in a list in Python?

description: Get the last non-empty item in a list in Python


code:
x
ends = numpy.cumsum(x)
ranges = numpy.arange(ends[-1])
ranges = ranges - numpy.repeat(ends-x, x)
ranges

rawDescription: Array of ranges with numpy

description: Array of ranges with numpy


code:
from bs4 import BeautifulSoup

doc = """
    .. balaba ..
   keep me here
    .. baz..
"""

soup = BeautifulSoup(doc)
for i in soup('nav'):
    i.decompose()
soup

#
#
#   keep me here
#
#

rawDescription: Remove data within html tags - Python

description: Remove data within html tags - Python


rawDescription: How to execute a JavaScript function when returning HttpResponse?

description: Execute a JavaScript function when returning HttpResponse


code:
class Setting(models.Model):
    name = models.CharField(max_length=50)
    value = models.TextField()

# ...

# Get the current slot setting
current_slot = Setting.objects.get(name='current_slot').value

# ...

# Or wrap it in a helper method
def get_setting(name, default_value):
    try:
        return Setting.objects.get(name=name).value
    except:
        return default_value

current_slot = get_setting('current_slot', 0)

rawDescription: What is the best way to store database settings with Django?


code:
import os
if not os.path.exists('abc.db'):
    conn = sqlite3.connect('abc.db')

rawDescription: Don't want to create a new database if it doesn't already exists


code:
def _splicegen(maxchars, stringlist):
    """
    Return a list of slices to print based on maxchars string-length boundary.
    """
    runningcount = 0  # start at 0
    tmpslice = []  # tmp list where we append slice numbers.
    for i, item in enumerate(stringlist):
        runningcount += len(item)
        if runningcount <= int(maxchars):
            tmpslice.append(i)
        else:
            yield tmpslice
            tmpslice = [i]
            runningcount = len(item)
    yield(tmpslice)

rawDescription: Splitting up a python list in chunks based on length of items


code:
def value(poly, x):
  """Evaluates a polynomial POLY for a given x.

  The polynomial is expressed as a list of coefficients, with
  the coefficient for x ** N at poly[N].

  This means that x ** 2 + 2*x + 3 is expressed as [3, 2, 1].
  """
  v = 0

  # Bit messy, but we're basically generating the indexes of
  # our polynomial coefficients from highest to lowest
  for coeff in reverse(poly):
    v = v * x + coeff

  return v

rawDescription: Evaluating polynomials in modulo arithmetic


rawDescription: Django: Exclude all rows of a table that have links in another Table


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def main():
    sheros = [['Groot',23,34,35],['Rocket',45,56,67]]

    print(sheros)
    newname = input('what is your name? ' )
    newstat = int(input('what is the new stat? ' ))

    found = False  # Use a flag to track whether name was found
    for entry in sheros:  # Don't use counter. Just loop over elements.
        if entry[0] == newname:
            entry[2:4] = entry[1:3]  # Use list slicing
            entry[1] = newstat
            found = True
            break  # Exit early assuming names are unique.

    if found:
        print("Already here")
    else:
        sheros.append([newname, newstat, 0, 0])

    print(sheros)

if __name__ == "__main__":
    main()

rawDescription: I want to check if something is in/not in a nested list


code:
library(NLP)
library(tm)

library(RColorBrewer)
library(wordcloud)

rawDescription: PypeR fails if R using library(tm)

description: PypeR fails if R using library(tm)


code:
import pygame
speed = 0

screen = pygame.display.set_mode((400,400),0,32)
pygame.display.update()
clock = pygame.time.Clock()

pygame.time.set_timer(pygame.USEREVENT+1, 20)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
        if event.type == pygame.USEREVENT+1:
            if pygame.key.get_pressed()[pygame.K_UP]:
                if speed < 8 :
                    speed+=0.1
            else:
                if speed > 0.1:
                    speed+= -0.1
                else:
                    speed = 0.0

    pygame.display.update()
    print(speed)
    clock.tick(60)

pygame.quit()
quit()

rawDescription: Need Help in Python Variable updation (Pygame module)


code:
list1 = ["vbhg12vbdf42vbsdh24", "dbsh13vdsj24lvk48"]
import re
[re.findall(r'\d+',i) for i in list1]

rawDescription: Process a list and output as list

description: Process a list and output as list


code:
df["Replicate"] = df.groupby(["Block", "Con", "Name"]).cumcount() + 1
df

rawDescription: adding values to a column by order pandas python

description: Adding values to a column by order pandas python


rawDescription: Numpy 1-hot array

description: Numpy 1-hot array


code:
import pylab
import numpy as np
import matplotlib as mpl
import random
import matplotlib.cm as cm

my_cmap = cm.bone

def my_square_scatter(axes, x_array, y_array, size_array, color_array):
    for x, y, size, color in zip(x_array, y_array, size_array, color_array):
        square = pylab.Rectangle((x-size/2,y-size/2), size, size, facecolor = my_cmap(color))
        axes.add_patch(square)
    return True

x = np.arange(100)
y = np.arange(100)
random.shuffle(y)
h = np.arange(100)/10.0
d = np.arange(100)/100.0
random.shuffle(d)

fig = pylab.figure(1)
fig.clf()
axes = pylab.axes()
my_square_scatter(axes, x, y, h, d)
pylab.axis('scaled')

#Create your own colorbar based on the parent axes.
ax, _ = mpl.colorbar.make_axes(axes)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=my_cmap, norm=mpl.colors.Normalize(vmin=0.0, vmax=1.0))
#cbar.set_clim(0.0,1.0) #Scale the colorbar; default is 0--1

pylab.show()

rawDescription: Data plotting in boxes with python

description: Data plotting in boxes with python


code:
from functools import reduce #only necessary in 3.X
d = {}
d['a'] = {} #I'm assuming this is what you meant to type
d['a']['b'] = 3
keys = ("a", "b")
reduce(dict.get, keys, d)

rawDescription: Python - Access hierarchical dict element from list of keys


code:
@django_ajax
def paginated_cache(request):
    more_results = [cache.get('your_results').pop() for result in range(50)]
    # turn this to json, wrap in dictionary and return

rawDescription: Django Lazy Loading Pagination

description: Django Lazy Loading Pagination


code: data = str(values)

rawDescription: Python POST encoding and formatting

description: Python POST encoding and formatting


code:
import sys

from PIL import Image

imin = Image.open(sys.argv[1])
imout = Image.new("RGB", imin.size)

imout.putdata(map(
                  lambda pixel: (0,0,0) if pixel == (0,0,0) else (255,255,255),
                  imin.getdata()
                 )
             )

imout.save(sys.argv[2])

rawDescription: How can I convert every pixel that is not black to a certain color?

description: Convert every pixel that is not black to a certain color


code:
def open_file(file_name):
    """
    opens file in samples, and return base64 encoded streams.
        feel free to use this code if it is helpful.
    """
    from backend import backend
    sample_dir = backend.config["samples_dir"]
    file = open(os.path.join(sample_dir, file_name), 'r')
    stream = file.read()
    encoded_stream = base64.b64encode(stream)
    return encoded_stream

rawDescription: How do I convert a base64 encoded string to a Stream that I can use with FileStorage from werkzeug.datastructures?

description: Convert a base64 encoded string to a Stream that I can use with FileStorage from werkzeug.datastructures


code:
class TestProgress():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('ttk.Progressbar')

        self.val=tk.IntVar()
        self.val.set(0)
        self.pbar = ttk.Progressbar(self.root, length=300,
                    maximum=10, variable=self.val)
        self.pbar.pack(padx=5, pady=5)

        tk.Label(self.root, textvariable=self.val,
                 bg="lightblue").pack()

        ## wait 2 seconds & update
        self.root.after(2000, self.advance)
        self.root.mainloop()

    def advance(self):
        self.val.set(8)

TP=TestProgress()

rawDescription: linking tkinter progress bar to function

description: Linking tkinter progress bar to function


rawDescription: How do I select part of a filename (leave out the extension) in Python?

description: Select part of a filename (leave out the extension) in Python


code:
from PIL import Image, ImageChops, ImageDraw
point_table = ([0] + ([255] * 255))

def new_gray(size, color):
    img = Image.new('L',size)
    dr = ImageDraw.Draw(img)
    dr.rectangle((0,0) + size, color)
    return img

def black_or_b(a, b, opacity=0.85):
    diff = ImageChops.difference(a, b)
    diff = diff.convert('L')
    # Hack: there is no threshold in PILL,
    # so we add the difference with itself to do
    # a poor man's thresholding of the mask:
    #(the values for equal pixels-  0 - don't add up)
    thresholded_diff = diff
    for repeat in range(3):
        thresholded_diff  = ImageChops.add(thresholded_diff, thresholded_diff)
    h,w = size = diff.size
    mask = new_gray(size, int(255 * (opacity)))
    shade = new_gray(size, 0)
    new = a.copy()
    new.paste(shade, mask=mask)
    # To have the original image show partially
    # on the final result, simply put "diff" instead of thresholded_diff bellow
    new.paste(b, mask=thresholded_diff)
    return new

a = Image.open('a.png')
b = Image.open('b.png')
c = black_or_b(a, b)
c.save('c.png')

rawDescription: Compare two images and highlight differences along on the second image


code:
s = " ,this ?is a string! with punctuation. "
import re
pattern = re.compile('\w+')
result = pattern.findall(s)
print(result)

rawDescription: Strip Punctuation From String in Python

description: Strip Punctuation From String in Python


code:
outer_dict = {"sineaster":{"easter":0.75, "sinister":0.60}}
inner_dict = outer_dict["sineaster"]
for key, value in inner_dict.items():
    print('{}: {}'.format(key, value))

rawDescription: how do i traverse nested dictionaries (python)?

description: Traverse nested dictionaries (python)


code: text = wx.TextCtrl(self, style=wx.TE_MULTILINE)

rawDescription: editable Text window with wx in Python

description: Editable Text window with wx in Python


rawDescription: python- How to update a column using value in another column as key to a defined dictionary in Pandas?

description: Python- How to update a column using value in another column as key to a defined dictionary in Pandas


code: [k for k, v in D.items() if 1 <= v <= 100]

rawDescription: Printing dictionary keys based on value

description: Printing dictionary keys based on value


code:
def is_proper_vagrant_template(string):
    """ Is it a proper Vagrant template? """
    return ".vmtx" in string and "vagrant" in string and "sde" not in string

def clean_template(string):
    """ Return the second half of the string, assuming whitespace as a separator """
    return string.split()[1]

temp1 = filter(is_proper_vagrant_template, VMLIST)
clean = map(clean_template, temp1)

rawDescription: Strip characters from list in Python

description: Strip characters from list in Python


code:
def partitions(s, k):
    if not k:
        yield [s]
        return
    for i in range(len(s) + 1):
        for tail in partitions(s[i:], k - 1):
            yield [s[:i]] + tail

rawDescription: Return all possible combinations of a string when splitted into n strings


code:
import numpy as np
# df.shape returns the dimensions in a tuple, the first dimension is the number of rows
df_list = np.array_split(df, df.shape[0]/10)
for d in df_list:
    d.to_csv(csv_path, mode='a')

rawDescription: Pandas Python: Writing output to specific cells in the CSV


code: df.insert(4, "new_col_name", tmp)

rawDescription: Python: how to add a column to a pandas dataframe between two columns?


code:
def describe_builtin(obj):
   """ Describe a builtin function """

   wi('+Built-in Function: %s' % obj.__name__)
   # Built-in functions cannot be inspected by
   # inspect.getargspec. We have to try and parse
   # the __doc__ attribute of the function.
   docstr = obj.__doc__
   args = ''

   if docstr:
      items = docstr.split('\n')
      if items:
         func_descr = items[0]
         s = func_descr.replace(obj.__name__,'')
         idx1 = s.find('(')
         idx2 = s.find(')',idx1)
         if idx1 != -1 and idx2 != -1 and (idx2>idx1+1):
            args = s[idx1+1:idx2]
            wi('\t-Method Arguments:', args)

   if args=='':
      wi('\t-Method Arguments: None')

   print

rawDescription: How to get the number of args of a built-in function in Python?

description: Get the number of args of a built-in function in Python


code: [listName.index(i.split('_')[0]) for i in listNameAge]

rawDescription: Sort and filter a list based on elements from a second list


code:
def onPressToMove(self, event): #get initial location of object to be moved
    winX = event.x - self.canvas.canvasx(0)
    winY = event.y - self.canvas.canvasy(0)
    self.dragInfo["Widget"] = self.canvas.find_closest(event.x, event.y, halo = 5)[0]

    # reset the starting point for the next move
    self.dragInfo["xCoord"] = winX
    self.dragInfo["yCoord"] = winY

rawDescription: Tkinter drag and drop

description: Tkinter drag and drop


code:
def special(**kw):
    def mark(function):
        function.is_special = True
        function.keywords = kw
        return function
    return mark

class Channel:
    def __init__(self, queue):
        self.queue = queue

    def start(self):
        while True:
            if not self.check():
                break

class ChannelA(Channel):
    def start(self):
        # omitted
        pass

    @special(icon="users.png")
    def get_users(self):
        # omitted
        return [i for i in self.queue if i.type == 1]

    @special(hint="don't feed the trolls")
    def get_groups(self):
        # omitted
        return [i for i in self.queue if i.type == 2]

ch = ChannelA(q)

for methodname in dir(type(ch)):
    method = getattr(ch, methodname)
    if getattr(method, 'is_special', False):
        print("Callable name:", method.__name__)
        print("Keywords:", method.keywords)
        print("Result:", method())

rawDescription: Provide a list of methods in a class for use outside of it


code:
s
s.resample('W', fill_method='ffill')

rawDescription: Upsampling to weekly data in pandas

description: Upsampling to weekly data in pandas


code:
import OpenSSL.crypto
from Crypto.Util import asn1

c=OpenSSL.crypto

# The certificate - an X509 object
cert=...

# The private key - a PKey object
priv=...

pub=cert.get_pubkey()

# Only works for RSA (I think)
if pub.type()!=c.TYPE_RSA or priv.type()!=c.TYPE_RSA:
    raise Exception('Can only handle RSA keys')

# This seems to work with public as well
pub_asn1=c.dump_privatekey(c.FILETYPE_ASN1, pub)
priv_asn1=c.dump_privatekey(c.FILETYPE_ASN1, priv)

# Decode DER
pub_der=asn1.DerSequence()
pub_der.decode(pub_asn1)
priv_der=asn1.DerSequence()
priv_der.decode(priv_asn1)

# Get the modulus
pub_modulus=pub_der[1]
priv_modulus=priv_der[1]

if pub_modulus==priv_modulus:
    print('Match')
else:
    print('Oops')

rawDescription: How to check for Python, the key associated with the certificate or not

description: Check for Python, the key associated with the certificate or not


rawDescription: How to get the index of the sorted list for the original list in Python?

description: Get the index of the sorted list for the original list in Python


code:
import numpy as np
new_x_values = [0,1,2]
np.interp(new_x_values, lowess[:,0], lowess[:,1])

rawDescription: Interpolation as prediction in Python

description: Interpolation as prediction in Python


code:
import csv
from collections import Counter

with open('words.csv') as f:
    next(f)  # skip header
    occurrence = Counter(tuple(row[1:3]) for row in csv.reader(f))

with open('occurrence.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['Destination', 'Source', 'Counts'])
    for (dest, src), cnt in occurrence.items():
        writer.writerow([dest, src, cnt])

rawDescription: Count the occurrence of same words in a csv file which occurs in the same row in python


code:
import posixpath
import os.path

_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]
                    if sep not in (None, '/'))

def safe_join(directory, filename):
    # docstring omitted for brevity
    filename = posixpath.normpath(filename)
    for sep in _os_alt_seps:
        if sep in filename:
            raise NotFound()
    if os.path.isabs(filename) or \
       filename == '..' or \
       filename.startswith('../'):
        raise NotFound()
    return os.path.join(directory, filename)

rawDescription: How to join with relative paths only?

description: Join with relative paths only


code:
import urllib

urllib.urlretrieve("http://8020.photos.jpgmag.com/3670771_314453_2ee7120da5_m.jpg",   "my.jpg")

rawDescription: Display or save a List of URL images

description: Display or save a List of URL images


code:
with open(file1,'r') as f:
    for line in f:
        data = parse_line(line) # function according to your data format, either return a dict or a tuple what ever works best for you
        if date['id'] not in idlist_file2:
             do_something_with_this_info(data)

rawDescription: Comparing two text files to remove duplication of the longer one


code:
driver.find_element_by_xpath(
    "//*[contains(text(), 'folder name')]/../../..//tr[2]/td[2]/div"
)

rawDescription: How to select parent of parent component by xpath

description: Select parent of parent component by xpath


rawDescription: Keep selection on Tkinter Entry widget despite not having focus


code:
def download_file(request, ref):
    filepath = "/home/jedema/code_"+ref+".txt"
    filename = os.path.basename(filepath)
    final_filename = "code.txt"
    with open(filepath) as f:
        response = HttpResponse(f.read(), content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
    return response

rawDescription: Django define name of file to serve

description: Django define name of file to serve


code:
import os.path
os.path.sep

rawDescription: is python glob.glob '\' robust across different OS win/unix/mac?

description: Is python glob.glob '\' robust across different OS win/unix/mac


code:
r = tvtk.RectilinearGrid()
r.point_data.scalars = data.ravel()
r.point_data.scalars.name = 'Temperature'

from mayavi.sources.vtk_data_source import VTKDataSource
src = VTKDataSource(data=r)

e.add_source(d)

description: RectilinearGridSource from tvtk.RectilinearGrid()


code:
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'r')

oldF1Value = None
v = None

for l1 in f1:
    [c1, c2] = l1.split()
    if (oldF1Value != c1):
        oldF1Value = c1
        v = f2.readline().splitlines()[0]

    print(c1, v)

f1.close()
f2.close()

rawDescription: Replacing one column in a file with other values


code:
class MainHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.render('intro.html')

rawDescription: How to handle both GET and POST requests in TornadoWeb framework?

description: Handle both GET and POST requests in TornadoWeb framework


code:
# polar plot
ri, ti = np.mgrid[0:2:100j, 0:2*np.pi:100j]
zi = rbf(ri*np.cos(ti), ri*np.sin(ti))

fig = plt.figure()
ax = plt.subplot(121, polar=True)
cax = ax.contour(ti, ri, zi, 10, linewidths=0.5, colors='k')
cax = ax.contourf(ti, ri, zi, 10, cmap=plt.cm.Spectral)
ax.set_rmax(2)

# rect plot
xi, yi = np.mgrid[-2:2:100j, -2:2:100j]
zi = rbf(xi, yi)

ax = plt.subplot(122, aspect='equal')
cax = ax.contour(xi, yi, zi, 10, linewidths=0.5, colors='k')
cax = ax.contourf(xi, yi, zi, 10, cmap=plt.cm.Spectral)
plt.show()

rawDescription: Contour line artifacts in matplotlib after interpolating data on a polar plot


code:
new_img = Image.new("L", (NEW_X_SIZE, NEW_Y_SIZE), "white")
new_img.putdata(new_img_list)
new_img.save('out.tif')

rawDescription: Python - How to save a list as an image?

description: Python - How to save a list as an image


code:
with open(file_path) as f:
    f.next() # skip 1 line
    f.next() # skip another one.
    for line in f:
        pass # now you can keep reading as if there was no first or second line.

rawDescription: How to skip 2 lines in a file with Python?

description: Skip 2 lines in a file with Python


code: ax1.plot(s1.index, s1)

rawDescription: Can pandas plot a time-series without trying to convert the index to Periods?


rawDescription: Rounding a list of floats into integers in Python


rawDescription: python compare each 2bytes in some portion of data

description: Python compare each 2bytes in some portion of data


code:
import mock

def function_under_test(f):
    f.tell()  # => 0
    f.read()
    f.tell()  # => 0
    return f.name

with mock.patch('__main__.open', mock.mock_open(read_data=''), create=True) as m:
    with open('/tmp/1') as f:
        f.name = '/tmp/1'
        f.tell.return_value = 0
        assert function_under_test(f) == '/tmp/1'

rawDescription: Mocking file handles

description: Mocking file handles


code:
N = 12 #number of my plots

upperBoxPoints= []
for d in data:
    upperBoxPoints.append(np.percentile(d, 75))

w = 0.5 # i had to tune the width by hand
ind = range(0,N)  #compute the correct placement from number and width
ind = [x + 0.5+(w/2) for x in ind]

for i in range(N):
    rect = ax.bar(ind[i], menMeans[i], w,  color=color[i], edgecolor='gray', linewidth=2, zorder=10)
# ind[i] position
# menMeans[i] hight of box
# w width
# color=color[i] as you can see i have a complex color scheme, use '#AAAAAAA' for colors, html names won't work
# edgecolor='gray' just like the other one
# linewidth=2 dito
# zorder=2 IMPORTANT you have to use at least 2 to draw it over the other stuff (but not to high or it is over your horizontal orientation lines

rawDescription: Boxplot on distance Data - set Box manually to values