code:
file = open('P:\test.csv', 'w')

fields = ('ItemID', 'Factor', 'FixedAmount')
wr = csv.DictWriter(file, fieldnames=fields, lineterminator = '\n')

wr.writeheader()
wr.writerow({'ItemID':1, 'Factor': 2, 'FixedAmount':3})
file.close()

rawDescription: csv.write skipping lines when writing to csv

description: Csv.write skipping lines when writing to csv


code: commands.getoutput('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt')

rawDescription: Bash in Python: Delete single quote

description: Bash in Python: Delete single quote


code:
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')

rawDescription: Why do I always get HTTP 407: Proxy Authentication Required?


rawDescription: How to add differently shaped numpy arrays?

description: Add differently shaped numpy arrays


code:
from scapy.all import *
for pkt in sniff(iface='eth1'):
    if IP in pkt and pkt[IP].src.endswith('5'):
        pkt[IP].dst = '1.1.1.1'
        sendp(pkt, iface='eth2')

rawDescription: is there a way to inspect packets in live traffic scapy?

description: Is there a way to inspect packets in live traffic scapy


code:
from django.conf import settings

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

# models
class Article(models.Model):
    author = models.ForeignKey(AUTH_USER_MODEL)

rawDescription: Best way to reference the User model in Django >= 1.5

description: Reference the User model in Django >= 1.5


code: filename2 = filename.replace( '_', '' ).replace( 'Sounding', 'Sounding2' )

rawDescription: paste special value to another multiple excel files with python

description: Paste special value to another multiple excel files with python


rawDescription: Python save txt file in a different folder


code:
import os
import tarfile
import dateutil.zoneinfo

zi_path = os.path.abspath(os.path.dirname(dateutil.zoneinfo.__file__))
zonesfile = tarfile.TarFile.open(os.path.join(zi_path, 'zoneinfo--latest.tar.gz'))
zonenames = zonesfile.getnames()

rawDescription: Get all available timezones

description: Get all available timezones


code:
import numpy as np
from scipy import interpolate

N = 64
data = np.random.random((21, 10, N))
X = np.linspace(10., 15., 21)
Y = np.linspace(0.05, 1.85, 10)
Xnew = np.linspace(10., 15., 41)
Ynew = np.linspace(0.05, 1.85, 20)
datanew = np.empty((N, 41, 20))
for i0 in np.arange(N):
    f = interpolate.interp2d(X, Y, data[:,:,i0].T, kind='linear')
    datanew[i0] = f(Ynew,Xnew)
datanew = np.rollaxis(datanew, 0, 3)

rawDescription: Interpolation of 3D data in Python

description: Interpolation of 3D data in Python


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

data = np.random.rand(10,10) * 2 - 1

# sample the colormaps that you want to use. Use 128 from each so we get 256
# colors in total
colors1 = plt.cm.binary(np.linspace(0., 1, 128))
colors2 = plt.cm.gist_heat_r(np.linspace(0, 1, 128))

# combine them and build a new colormap
colors = np.vstack((colors1, colors2))
mymap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

plt.pcolor(data, cmap=mymap)
plt.colorbar()
plt.show()

rawDescription: Combining two matplotlib colormaps

description: Combining two matplotlib colormaps


code:
def fileDownload(self, some_Id, range=None):
    # [...] something happens here
    # get the Amazon URL
    fileUrl = we_get_the_amazon_url_here
    req = urllib2.urlopen(fileUrl)
    if len(range):
        req.headers['Range']='bytes=%s-%s' % (range[0], range[1])

    return req.read()

rawDescription: return stream of url file with python urllib2

description: Return stream of url file with python urllib2


code:
import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
for i in xrange(20):
    bar.update(i+1)
    sleep(0.1)
bar.finish()

rawDescription: Python to print out status bar and percentage


code:
from django.utils import simplejson as json

class Get_data(webapp2.RequestHandler):
    def get(self):
        response = urllib2.urlopen('https://api.twitter.com/1/favorites.json?count=5&screen_name=episod')
        data = response.read()
        json_data = json.loads(data)

        template_values = {
            'param1': json_data["..."],
            'param2': json_data["..."],
        }

        template = jinja_environment.get_template(TEMPLATE)
        self.response.out.write(template.render(template_values))

rawDescription: Cannot get URL contents using Python when calling Twitter API


code:
import __main__
__main__.some_variable = module.module_variable

rawDescription: loading module variables in interactive mode

description: Loading module variables in interactive mode


code:
import matplotlib.transforms as transforms

fig = plt.figure()
ax = fig.add_subplot(111)

trans = transforms.blended_transform_factory(
    ax.transData, ax.transAxes)

ax.plot(range(50))
ax.axvline(20)

ax.text(20, 0.05, 'test', transform=trans, rotation='vertical', ha='right')

rawDescription: Matplotlib - Add labels aligned to bottom of axis


code:
from StringIO import StringIO # py3k: from io import StringIO
import csv
with open('./file') as fh:
    io = StringIO(fh.read().replace('\t', ','))

reader = csv.reader(io)

for row in reader:
    print(row)

rawDescription: Pass regex to delimiter field in python's csv module or numpy's genfromtxt / loadtxt?


code:
def wait_for_user(secs):
    import msvcrt
    import time
    start = time.time()
    while True:
        if msvcrt.kbhit():
            msvcrt.getch()
            break
        if time.time() - start > secs:
            break

rawDescription: How to wait for 20 secs for user to press any key?

description: Wait for 20 secs for user to press any key


code:
from ctypes import *
c = cdll.LoadLibrary("libc.so.6")
c.sigqueue
c.sigqueue(100, 10, 0)

rawDescription: How do I send and receive real-time signals `sigqueue()` in Python?

description: Send and receive real-time signals `sigqueue()` in Python


code:
from datetime import datetime
date_input = input('Enter a date(mm/dd/yyyy): ')
date_object = datetime.strptime(date_input, '%m/%d/%Y')
print(date_object.strftime('%B %d, %Y'))

rawDescription: Convert date from mm/dd/yyyy to another format in Python


code: list_dicts = sorted(list_dicts, key=lambda x:int(x['key3'])-int(x['key2'])-int(x['key1']))

rawDescription: Ordering dict objects based on multiple key values and comparison rules


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

fig, ax = plt.subplots()

g = 9.8                                                        #value of gravity
v = 10.0                                                       #initial velocity
theta = 40.0 * np.pi / 180.0                                   #initial angle of launch in radians
t = 2 * v * np.sin(theta) / g
t = np.arange(0, 0.1, 0.01)                                    #time of flight into an array
x = np.arange(0, 0.1, 0.01)
line, = ax.plot(x, v * np.sin(theta) * x - (0.5) * g * x**2)   # plot of x and y in time

def animate(i):
    """change the divisor of i to get a faster (but less precise) animation """
    line.set_xdata(v * np.cos(theta) * (t + i /100.0))
    line.set_ydata(v * np.sin(theta) * (x + i /100.0) - (0.5) * g * (x + i / 100.0)**2)
    return line,

plt.axis([0.0, 10.0, 0.0, 5.0])
ax.set_autoscale_on(False)

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200))
plt.show()

rawDescription: Animating the path of a projectile in python


code:
def makeList(tree):
    paths = []
    if not (tree.left or tree.right):
        return [[tree.data]]
    if tree.left:
        paths.extend([[tree.data] + child for child in makeList(tree.left)])
    if tree.right:
        paths.extend([[tree.data] + child for child in makeList(tree.right)])
    return paths

rawDescription: How to return all possible paths of random binary tree in Python

description: Return all possible paths of random binary tree in Python


code:
def zeros_pattern(s):
    return [c == "0" for c in s]

list_of_strings.sort(key=zeros_pattern)

rawDescription: Python: Sorting a list of strings by string template?


code:
writer = csv.writer(f)
...
writer.writerow([int(x) for x in row])  # Note difference in parameter format

rawDescription: Writing output to csv file [in correct format]


code:
import binascii
genesis = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
given_hash = '6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000'
binascii.unhexlify(given_hash) == binascii.unhexlify(genesis)[::-1]

rawDescription: Double hash SHA256 in Python

description: Double hash SHA256 in Python


code:
import numpy as np

np.savetxt('fname.csv', variable, delimiter=',')
variable = np.loadtxt('fname.csv', delimiter=',')

rawDescription: How to write and read a single Numpy 2D array to and from a CSV file as a single command in Python?

description: Write and read a single Numpy 2D array to and from a CSV file as a single command in Python


code:
from collections import deque
from twisted.internet.defer import Deferred
from twisted.words.protocols.irc import IRCClient

class NoAccount(Exception):
    "No account found."

class MyClient(IRCClient, object):

    def __init__(self):
        self._whoisQueue = deque()

    def deferredWhois(self, nick):
        result = Deferred()
        self._whoisQueue.append((result, nick))
        self.whois(nick)
        return result

    def irc_330(self, prefix, params):
        self._currentActiveNick = params[2]

    def irc_RPL_ENDOFWHOIS(self, prefix, params):
        deferredToFire, who = self._whoisQueue.popleft()
        currentActiveNick = self._currentActiveNick
        self._currentActiveNick = None

        if currentActiveNick is None:
            deferredToFire.errback(NoAccount(who))
        else:
            deferredToFire.callback(currentActiveNick)

rawDescription: Twisted deferred variable from another source


code: df.loc[~ (df.select_dtypes(include=['number']) == 0).all(axis='columns'), :]

rawDescription: How to remove rows where all numerical columns contain zero in Pandas Dataframe with mixed type of columns?

description: Remove rows where all numerical columns contain zero in Pandas Dataframe with mixed type of columns


code:
results = index.search(search.Query(
            #query and options here, including ids_only=True
            ))
doc_ids = [tmp_result.doc_id for tmp_result in results]

rawDescription: How to parse a list of SearchResults?

description: Parse a list of SearchResults


code:
with open("file.csv","r") as f:
    t=[line.strip().split(";")[:2] for line in f]

rawDescription: python Postgresql: Ignoring the last column from csv file

description: Python Postgresql: Ignoring the last column from csv file


code:
inputList = [[1, "Data x"], [2, "Data z"], [3, "Data x"]]

from operator import itemgetter
from collections import defaultdict

dd = defaultdict(list)
for i, v in enumerate(inputList):
    dd[v[1]].append(i)

dupes = [itemgetter(*v)(inputList) for v in dd.itervalues() if len(v) > 1]
# [([1, 'Data x'], [3, 'Data x'])]

rawDescription: Python - identify items from list where sublist items are duplicated


code:
names = []
grades = []
for i in n:
    sn = str(input("What is the student's name? "))
    names.append(sn)
    sg = eval(input("What is the student's grade? "))
    grades.append(sg)

rawDescription: How can you save multiple inputs from a user if you are using a for loop?

description: Save multiple inputs from a user if you are using a for loop


code:
def main():
    GPIO.add_event_detect(Button1, GPIO.RISING, callback=buttonPressed, bouncetime=200)
    GPIO.add_event_detect(Button2, GPIO.RISING, callback=buttonPressed, bouncetime=200)

    # This function just creates an endless loop which does
    # nothing, in order for the button detection to work
    try:
        flag = 0
        while flag == 0:
            device = checkForUSBDevice("MUSIC") # MUSIC is the name of my thumb drive
            if flag == 1:
                flag = 0
            else:
                flag = 0

            if device != "":
            # USB thumb drive has been inserted, new music will be copied
                print('USB erkannt, Musik wird kopiert.', device)

# Stop the callback before loading the files from the USB:
                GPIO.remove_event_detect(Button1)
                GPIO.remove_event_detect(Button2)

                loadMusic(client, CON_ID, device)
                print('Musik wurde kopiert, USB kann entfernt werden!', device)
                while checkForUSBDevice("MUSIC") == device:
                    sleep(1.0)
                print('USB wurde entfernt.')
                loadAlbum(1)

# Recall the main function
                main()

    except KeyboardInterrupt:
        GPIO.cleanup()

rawDescription: Python callback issue with GPIO on raspberry


code:
recipient = namespace.createRecipient("User Name")
resolved = recipient.Resolve()
sharedCalendar = namespace.GetSharedDefaultFolder(recipient, 9)

rawDescription: accessing Exchange calendar items in shared or public folders with Python

description: Accessing Exchange calendar items in shared or public folders with Python


rawDescription: Finding pattern in tuples Python

description: Finding pattern in tuples Python


code:
# your_app.config.develop
DEBUG = True

# your_app.config.production
DEBUG = False

# your_app.app
from flask import Flask
from os import environ

mode = environ.get("YOURAPP_MODE")
mode = "production" if mode is None else "develop"

config = __import__("your_app.config." + mode)

app = Flask("your_app")
app.config.from_object(config)

rawDescription: What Unix tool to quickly add/remove some text to a Python script?


code:
def parse_page1(self, response):
    item = MyItem()
    item['main_url'] = response.url
    request = Request("http://www.example.com/some_page.html",
                      callback=self.parse_page2)
    request.meta['item'] = item
    return request

def parse_page2(self, response):
    item = response.meta['item']
    item['other_url'] = response.url
    return item

rawDescription: Scrapy CrawlSpider: how to access item across different levels of parsing


code:
from flask import Flask, redirect, url_for, session, request
from flask_oauthlib.client import OAuth, OAuthException

SPOTIFY_APP_ID = 'REGULAR_CODE'
SPOTIFY_APP_SECRET = 'SECRET_CODE'

app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

spotify = oauth.remote_app(
    'spotify',
    consumer_key=SPOTIFY_APP_ID,
    consumer_secret=SPOTIFY_APP_SECRET,
    # Change the scope to match whatever it us you need
    # list of scopes can be found in the url below
    # https://developer.spotify.com/web-api/using-scopes/
    request_token_params={'scope': 'user-read-email'},
    base_url='https://accounts.spotify.com',
    request_token_url=None,
    access_token_url='/api/token',
    authorize_url='https://accounts.spotify.com/authorize'
)

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    callback = url_for(
        'spotify_authorized',
        next=request.args.get('next') or request.referrer or None,
        _external=True
    )
    return spotify.authorize(callback=callback)

@app.route('/login/authorized')
def spotify_authorized():
    resp = spotify.authorized_response()
    if resp is None:
        return 'Access denied: reason={0} error={1}'.format(
            request.args['error_reason'],
            request.args['error_description']
        )
    if isinstance(resp, OAuthException):
        return 'Access denied: {0}'.format(resp.message)

    session['oauth_token'] = (resp['access_token'], '')
    me = spotify.get('/me')
    return 'Logged in as id={0} name={1} redirect={2}'.format(
        me.data['id'],
        me.data['name'],
        request.args.get('next')
    )

@spotify.tokengetter
def get_spotify_oauth_token():
    return session.get('oauth_token')

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

rawDescription: Python Spotify OAuth Flow

description: Python Spotify OAuth Flow


code:
import imghdr

try:
    imghdr.test_webp
except AttributeError:
    # add in webp test, see http://bugs.python.org/issue20197
    def test_webp(h, f):
        if h.startswith(b'RIFF') and h[8:12] == b'WEBP':
            return 'webp'

    imghdr.tests.append(test_webp)

rawDescription: how to identify webp image type with python

description: Identify webp image type with python


code:
import requests
from bs4 import BeautifulSoup
from requests import Request, Session
from lxml import html

def Get_data(zipcode, radius):
    All_links = []
    url = 'https://www.aae.org/patients/find.aspx'
    s = requests.Session()
    r = s.get(url)
    #print (r.text.encode('utf-8'))
    soup = BeautifulSoup(r.content,'lxml')
    viewstate = soup.select("#__VIEWSTATE")[0]['value']
    eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value']
    EktronClientManager = soup.select("#EktronClientManager")[0]['value']
    params = {'EktronClientManager':EktronClientManager,
              '__VIEWSTATE':viewstate,
              '__EVENTVALIDATION':eventvalidation,
              'ctl00$ctl00$aaeUtilitySiteSearchWidget$tbxSiteSearch':'Search',
              'ctl00$ctl00$cphContentTypes$cphPageContent$aaeFindEndo$ddlRadius':radius,
              'ctl00$ctl00$cphContentTypes$cphPageContent$aaeFindEndo$txtZipCode':zipcode,
              'ctl00$ctl00$cphContentTypes$cphPageContent$aaeFindEndo$btnFind':'SEARCH'}
    r2 = s.post(url,data=params)
    source = html.fromstring(r2.content)
    links = source.xpath("//table[@class='Results']//tr//a//@href")
    for each in links:
        if "MemberID" and "AddressID" in each:
            print (each)
            All_links.append("https://www.aae.org/patients/"+str(each))
    #print (r2.content)
    soup1 = BeautifulSoup(r2.content,'lxml')
    viewstate = soup1.select("#__VIEWSTATE")[0]['value']
    eventvalidation = soup1.select("#__EVENTVALIDATION")[0]['value']
    EktronClientManager = soup1.select("#EktronClientManager")[0]['value']
    j = 2
    while j < 7:
        page = 'Page$'+str(j)
        print (page)
        params1 = {'__EVENTTARGET':'ctl00$ctl00$cphContentTypes$cphPageContent$aaeFindEndo$grdResults',
                   '__EVENTARGUMENT':page,
                   'EktronClientManager':EktronClientManager,
                   '__VIEWSTATE':viewstate,
                   '__EVENTVALIDATION':eventvalidation,
                   'ctl00$ctl00$aaeUtilitySiteSearchWidget$tbxSiteSearch':'Search'}
        r3 = s.post(url,data=params1)
        source1 = html.fromstring(r3.content)
        links1 = source1.xpath("//table[@class='Results']//tr//a//@href")
        for each1 in links1:
            if "MemberID" and "AddressID" in each1:
                print (each1)
                All_links.append("https://www.aae.org/patients/"+str(each1))
        soup2 = BeautifulSoup(r3.content,'lxml')
        viewstate = soup2.select("#__VIEWSTATE")[0]['value']
        eventvalidation = soup2.select("#__EVENTVALIDATION")[0]['value']
        EktronClientManager = soup2.select("#EktronClientManager")[0]['value']
        j+=1

Get_data(33133, 100)

rawDescription: I am trying to scrape a aspx website but unable to go beyond page2


code:
def twofunc(one, two):
    for a, b in itertools.product(main[one], main[two]):
        return [a, b]

mydata.append(twofunc(2,0))

rawDescription: Appending strings to a list

description: Appending strings to a list


code:
def A(m, n):
    if m == 0:
        return n + 1
    elif m > 0 and n == 1:
        return A(m - 1, 1)
    elif m > 0 and n > 0:
        return A(m - 1, A(m, n - 1))

rawDescription: Why does this code print None?

description: Why does this code print None


code: foo, bar, baz == (list(a) + [None]*3)[:3]

rawDescription: How to unpack optional items from a tuple?

description: Unpack optional items from a tuple


code:
class TestAdmin(TestCase):

    def setUp(self):
        self.client = Client()
        self.my_admin = User(username='user', is_staff=True)
        my_admin.set_password('passphrase') # can't set above because of hashing
        my_admin.save() # needed to save to temporary test db
        response = self.client.get('/admin/', follow=True)
        loginresponse = self.client.login(username='user',password='passphrase')
        self.assertTrue(loginresponse) # should now return "true"

rawDescription: Test Login with credentials as superuser Django 1.9, Python 3.5


rawDescription: How can I ignore zeros when I take the median on columns of an array?

description: Ignore zeros when I take the median on columns of an array


code:
@mock.patch('%s.ftp2email.shutil.move' % __name__)
def test_mark_message(self, move_mock):

    self.ch.mark_message('/path/to/message.xml')
    move_mock.assert_called_with('/path/to/message.xml',
                                 '/path/to/archived/message.xml')

rawDescription: How to patch shutil.move to test some method

description: Patch shutil.move to test some method


code:
import random

with open("mycsv.csv") as fr:
    with open("1.csv", "w") as f1, open("2.csv", "w") as f2, open("3.csv", "w") as f3:
        for line in fr.readlines():
            rd = random.randint(1, 3)
            f = f1 if rd == 1 else (f2 if rd == 2 else f3)
            f.write(line)

rawDescription: Split a huge CSV in three random files in Python


code:
with open('large_file.txt') as f:
   for number,line in enumerate(f):
       if line.startswith('.text'):
           bits = line.split()
           try:
              print('Found at line # {} - {}'.format(number, bits[2]))
           except IndexError:
              print('Malformed line: {}'.format(line))

rawDescription: Find a String with Python?

description: Find a String with Python


code:
df
after = {r + (k,): v for r, kv in df.iterrows() for k,v in kv.to_dict().items()}
import pprint
pprint.pprint(after)

rawDescription: Pandas: Convert DataFrame with MultiIndex to dict


code:
ip="172.168.99.99"
try:
    response = requests.get('https://' + ip + '/views', auth=HTTPDigestAuth('username', 'password'), verify=False)
except urllib3.exceptions.SSLError as e:
    sys.exit('test')

rawDescription: python post with auth

description: Python post with auth


code:
excel.AddIns.Add("C:\Program Files (x86)\PIPC\Excel\PITrendXL.xla").Installed = True
excel.AddIns.Add("C:\Program Files (x86)\PIPC\Excel\pipc32.xll").Installed = True

rawDescription: Opening an excel file manually allows formulas to run, opening an excel file with VBScript or PowerShell or Python's win32com doesn't


code: posts.update({'_id':213}, {'$set':{"jobs.1.title":1}}, upsert=False, multi=True)

rawDescription: mongodb array updates in python script

description: Mongodb array updates in python script


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
import threading

class XMLRPCServerThread(threading.Thread):
    def __init__(self, remoteObject, host='localhost', port=8000):
        self.remoteObject = remoteObject
        self.host = host
        self.port = port
        threading.Thread.__init__(self)

    def stop(self):
        self.server.shutdown()

    def run(self):
        self.server = SimpleXMLRPCServer( (self.host, self.port), logRequests=False )
        self.server.register_instance( self.remoteObject )
        self.server.serve_forever()

class MyRemoteCalls(object):

    def __init__(self, obj):
        self.obj = obj

    def exampleCall(self, arg):
        wx.CallAfter(self.obj.method, arg)
        return 0

def getRPCThread(obj, host='localhost', port=8000):
    remoteObj = MyRemoteCalls(obj)
    rpcThread = XMLRPCServerThread(remoteObj, host, port)
    rpcThread.start()
    return rpcThread

rawDescription: Threading wxPython and XMLRPC

description: Threading wxPython and XMLRPC


code:
while True:
    for event in key_presses():
        handle_event(event)  # stuff that happens as a result of input
    update_state()  # stuff that happens regardless of input
    update_display()  # everything that changes the display (backlight, text, anything)

rawDescription: Python- run a while loop in background of script


code:
import re
from itertools import count

text = '''How many roads must a man walk down Before you call him a man? How many seas must a white dove sail Before she sleeps in the sand? Yes, and how many times must the cannon balls fly Before they're forever banned?'''
result = re.sub(r'(?i)\bhow\b', lambda m, c=count(1): '[{}]'.format(next(c)), text)
# [1] many roads must a man walk down Before you call him a man? [2] many seas must a white dove sail Before she sleeps in the sand? Yes, and [3] many times must the cannon balls fly Before they're forever banned?

rawDescription: sub-string text with a running number

description: Sub-string text with a running number


code:
import colorsys
N = 5
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)

rawDescription: Generating color ranges in Python

description: Generating color ranges in Python


code:
from sympy import *

x = Symbol('x', real=True) # parameter
f = -2 * x**2 + 4*x        # function
derivative = f.diff(x)     # -4*x + 4
solve(derivative, x)       # -4*x + 4 = 0

rawDescription: How to compute argmax with sympy?

description: Compute argmax with sympy


rawDescription: Adding an element to a rdd depending on a calculation on the same rdd


code:
input = ['123', '456', '7 8']
sampleList = []
for digit_str in input:
    for digit in digit_str:
        sampleList.append(digit)

sampleList

rawDescription: How to separate numbers into digits and store them in a list?

description: Separate numbers into digits and store them in a list


rawDescription: Is there a short-hand for nth root of x in Python


code:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.functions import FunctionElement

class CustomNow(FunctionElement):
    name = "custom_now"

@compiles(CustomNow)
def visit_custom_now(element, compiler, **kwargs):
    return "(NOW())"

@compiles(CustomNow, "sqlite")
def visit_custom_now_for_sqlite(element, compiler, **kwargs):
    return "(DATETIME('now', 'localtime'))"

rawDescription: Can a column's server_defaults be different for different dialects in SQLAlchemy?


code:
A = np.zeros((5, 7),dtype=bool)
B = np.array([0,1,3,0,2])
(np.arange(len(A[0])) < B[:,None])

rawDescription: Populate numpy matrix dynamically from array values?


code: a, b, *_ = thing()

rawDescription: Matching Iterators With Discard In Python


code:
import wx

class TestFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, -1)

        self.tree = wx.TreeCtrl(self, style = wx.TR_HIDE_ROOT)
        self.root = self.tree.AddRoot("")

        gr = self.tree.AppendItem(self.root, "Grooveshark")
        pop_r = self.tree.AppendItem(gr, "Popular")
        sr = self.tree.AppendItem(gr, "Search")

        dr = self.tree.AppendItem(self.root, "Download")

        pr = self.tree.AppendItem(self.root, "Pandora")
        stat_r = self.tree.AppendItem(pr, "Stations")

        image_list = wx.ImageList(16, 16)
        grooveshark = image_list.Add(wx.Image("images/grooveshark (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())
        popular     = image_list.Add(wx.Image("images/popular (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())
        search      = image_list.Add(wx.Image("images/search (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())
        download    = image_list.Add(wx.Image("images/download (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())
        pandora     = image_list.Add(wx.Image("images/playlist_icon (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())
        stations    = image_list.Add(wx.Image("images/stations (Custom).png", wx.BITMAP_TYPE_PNG).Scale(16,16).ConvertToBitmap())

        self.tree.AssignImageList(image_list)

        self.tree.SetPyData(gr, None)
        self.tree.SetItemImage(gr, grooveshark, wx.TreeItemIcon_Normal)
        self.tree.SetPyData(pop_r, None)
        self.tree.SetItemImage(pop_r, popular, wx.TreeItemIcon_Normal)
        self.tree.SetPyData(sr, None)
        self.tree.SetItemImage(sr, search, wx.TreeItemIcon_Normal)
        self.tree.SetPyData(dr, None)
        self.tree.SetItemImage(dr, download, wx.TreeItemIcon_Normal)
        self.tree.SetPyData(pr, None)
        self.tree.SetItemImage(pr, pandora, wx.TreeItemIcon_Normal)
        self.tree.SetPyData(stat_r, None)
        self.tree.SetItemImage(stat_r, stations, wx.TreeItemIcon_Normal)

if __name__ == "__main__":
    a = wx.App(False)

    f = TestFrame()
    f.Show()
    a.MainLoop()

rawDescription: wxpython tree ctrl images

description: Wxpython tree ctrl images


code:
#!/usr/bin/python
import sys
#import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *

if __name__ == '__main__':
    #time.sleep(2)
    app = QApplication(sys.argv)
    w = QDialog()
    w.setWindowFlags(Qt.Popup)
    w.setAttribute(Qt.WA_QuitOnClose)
    w.show()
    w.raise_()
    sys.exit(app.exec_())

rawDescription: PyQt: Qt.Popup widget sometimes loses focus without closing, becomes unclosable


code: from file1 import *

rawDescription: Importing variables from another file (python)


code:
redirect_url = '/images/45/'
return HttpResponseRedirect(redirect_url)

rawDescription: Django ModelForm get next item in list after submit


code: table = soup.findAll("tr", {'class' : ['table-tempo-row', 'table-tempo-row-alt'] })

rawDescription: merge queries in beautifulsoup

description: Merge queries in beautifulsoup


code:
bool([])
bool(['monty'])

rawDescription: Print the result of evaluation of an expression in Python


code:
import bottle

app = bottle.app()

@app.route('/')
def index():
    return """<HTML>
    <FORM method="POST">
    <INPUT name="input1">Please provide Input</INPUT>

    </FORM>
    </HTML>"""

@app.post('/')
def index_post():
    print(bottle.request.forms.keys())
    input1 = bottle.request.forms.get("input1")
    print("got", input1)
    return ("I got %s" % input1)

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

rawDescription: Easiest possibility to send request from web to python


code:
def find_all(L, v):
    if not L:
            return []

    result = []
    if L[-1] == v:
            result = [len(L)-1]

    return find_all(L[:-1], v) + result

rawDescription: find all index with recursion

description: Find all index with recursion


code:
@register.render_tag
def page_menu_special(context, token):
    page = None
    template_name = None
    menu_templates = []

    parts = token.split_contents()[1:]
    for part in parts:
        part = Variable(part).resolve(context)
        if isinstance(part, str):
            template_name = part
        elif isinstance(part, Page) or isinstance(part, CustomPage):
            page = part

    if page and page.slug:
        page_template = str(page.slug) if page.slug != home_slug() else "index"
        method_template = page.get_content_model().get_template_name()

        menu_templates.extend([
            u'pages/menus/dropdown_%s.html' % (page_template),
            u'pages/menus/dropdown/%s.html' % (page_template),
        ])

        if method_template:
            menu_templates.append(method_template)

    if template_name:
        menu_templates.insert(0, template_name)

    try:
        t = select_template(menu_templates)
        return t.render(Context(context))
    except TemplateDoesNotExist:
        return u''

rawDescription: Template tag for conditionally rendering or including another template if the path or paths exist


code:
arr = np.array([5.5, -7.2])
out = np.empty_like(arr, dtype=np.int64)
np.ceil(arr, out)
out

rawDescription: Numpy Ceil and Floor "out" Argument

description: Numpy Ceil and Floor "out" Argument


code:
import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('

...

')
soup.findAll(attrs={'class':'myTable'})

rawDescription: Finding Top Level Tags With BeautifulSoup


code:
templist=[]
for key, value in docs.items():
    tf_idf = list(value['tf_idf'].items())
    idf = list(value['idf'].items())
    templist.append(tf_idf + idf)

rawDescription: Append dict items to a list in Python

description: Append dict items to a list in Python


rawDescription: How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)?

description: Get the (x,y) values of the line that is ploted by a contour plot (matplotlib)


code:
from collections import OrderedDict
import json
text =""" { "Version": "2.0", "Description": "A description...", "A": { "B.a": { "B.a.a": { "Value1": "It's value", "Value2": "This value" }, "B.a.1": { "Value1": "Value x.a.1", "Value2": "Value y.a.1" }, "B.a.2": { "Value1": "Value x.a.2", "Value2": "Value y.a.2" }, "B.a.3": { "Value1": "Value x.a.3", "Value2": "Value y.a.3" }, "B.a.4": { "Value1": "Value x.a.4", "Value2": "Value y.a.4" } } }, "B": { "B.a": { "B.a.a": { "Value1": "It's value", "Value2": "This value" }, "B.a.1": { "Value1": "Value x.a.1", "Value2": "Value y.a.1" }, "B.a.2": { "Value1": "Value x.a.2", "Value2": "Value y.a.2" }, "B.a.3": { "Value1": "Value x.a.3", "Value2": "Value y.a.3" }, "B.a.4": { "Value1": "Value x.a.4", "Value2": "Value y.a.4" } } }, "C": { "B.a": { "B.a.a": { "Value1": "It's value", "Value2": "This value" }, "B.a.1": { "Value1": "Value x.a.1", "Value2": "Value y.a.1" }, "B.a.2": { "Value1": "Value x.a.2", "Value2": "Value y.a.2" }, "B.a.3": { "Value1": "Value x.a.3", "Value2": "Value y.a.3" }, "B.a.4": { "Value1": "Value x.a.4", "Value2": "Value y.a.4" } } }}"""
json_object = json.loads(text, object_pairs_hook=OrderedDict)
# Change values
json.dumps(json_object, indent=4)

rawDescription: Reading JSON file and modifying some values to be in the exact same position in Python


code:
logFile = open("C:/folder/logfile.txt", "w")
unittest.TextTestRunner(stream=logFile, verbosity=2).run(customFunction())
logFile.close()

rawDescription: Reading a Unit Test to a file in python with a custom function


code:
class B(A):
    def __init__(self, *a, **k):
      if 'W' in k:
        w = k.pop('W')
      else:
        w = a.pop()
      A.__init__(self, *a, **k)
      self._W = w

rawDescription: Avoid specifying all arguments in a subclass


code:
class A(models.Model):
    title = models.TextField()
    # other fields ...

    class Meta:
        manage = False

    @property
    def b(self):
        if not hasattr(self, "__bcache"):
            self.__bcache, created = B.objects.get_or_create(model_a = self)
        return self.__bcache

rawDescription: Django sync one-to-one models

description: Django sync one-to-one models


code:
multiples = []  # <----------
for number in range(1001):
    if (number % 3 == 0) or (number % 5 == 0):
        multiples.append(number)

rawDescription: Why is the total sum of the list incorrect?


code:
def flip_stack(s):
    return flip_stack_helper(s, Stack()) # Stack is your stack class

def flip_stack_helper(s, t):
    if s.is_empty():
        return t
    t.push(s.pop())
    return flip_stack_helper(s, t)

rawDescription: Reversing a Stack in Python using recursion


code:
import os
import shlex
from subprocess import check_output

DIRECTORY = '/tmp'
OUTPUT_FILE = '/tmp/output.log'

with open(OUTPUT_FILE, 'w') as output:
    for parent, _, _ in os.walk(DIRECTORY):
        os.chdir(parent)
        output.write(check_output(shlex.split('ls -al')))

rawDescription: How to make the subprocess statment to execute under the os.walk(path)

description: Make the subprocess statment to execute under the os.walk(path)


code:
import re

# this regular expression matches lines like "  abcd = feg ; "
CONFIG_LINE = re.compile("^\s*(\w+)\s*=\s*(\w+)\s*;")

# this takes { "variable_1":"a", "variable_2":"b", "variable_3":"c" }
#   and turns it into "folder_a_b_c"
DIR_FMT = "folder_{variable_1}_{variable_2}_{variable_3}".format

def read_config_file(fname):
    with open(fname) as inf:
        matches = (CONFIG_LINE.match(line) for line in inf)
        return {match.group(1):match.group(2) for match in matches if match}

def make_data_file(variables, contents):
    dir = DIR_FMT(**variables)
    fname = os.path.join(dir, "data.txt")
    with open(fname, "w") as outf:
        outf.write(contents)

def main():
    variables = read_config_file("template.cfg")
    make_data_file(variables, "this is my new file")

if __name__=="__main__":
    main()

rawDescription: Generate multiple files python

description: Generate multiple files python


rawDescription: Raising Image with Tkinter and Python

description: Raising Image with Tkinter and Python


code:
def convert_all(all, convert=to_unicode_or_bust):
    if isinstance(all, tuple):
        return tuple(convert_all(piece, convert) for piece in all)
    elif isinstance(all, list):
        return [convert_all(piece, convert) for piece in all]
    return convert(all)

rawDescription: Decoding a list of encoded strings

description: Decoding a list of encoded strings


code:
date_realization_for_articles = Article.objects.values_list('date_realization',
                                                            flat=True).distinct()

rawDescription: Django views select from db list of datefield


code:
G = [{} for i in range(len(points))]
for i,e in enumerate(edges):
  G[e[0]][e[1]] = weights[i]
return G

rawDescription: Faster graph structure generation

description: Faster graph structure generation


code:
from ctypes import Structure, POINTER, c_int

class mifare_tag(Structure):

    _fields_ = [
        ("device", POINTER(nfc_device)),
        ("info", nfc_iso14443a_info),
        ("tag_info", POINTER(supported_tag)),
        ("active", c_int),
        ]

MifareTag = POINTER(mifare_tag)

rawDescription: How to make python binding to typedef pointer alias

description: Make python binding to typedef pointer alias


code:
with open(filename,'wb') as fp:
    pickle.dump(dict1,fp)
    pickle.dump(dict2,fp)
    pickle.dump(dict3,fp)

with open(filename,'rb') as fp:
    d1=pickle.load(fp)
    d2=pickle.load(fp)
    d3=pickle.load(fp)

rawDescription: How to cPickle dump and load separate dictionaries to the same file?

description: CPickle dump and load separate dictionaries to the same file


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

x = np.linspace(-1.0, 1.0, 100)
y = np.linspace(-1.0, 1.0, 100)
X, Y = np.meshgrid(x,y)
F = X**2 + Y**2 - 0.6
plt.contour(X,Y,F,[0])
plt.show()

rawDescription: Plot equation showing a circle

description: Plot equation showing a circle


rawDescription: Best / most pythonic way to get an ordered list of unique items


code:
import yaml

class SomeClass(object):
    def __init__(self, var_a=10, var_b=20, var_c=30):
        self.var_a = var_a
        self.var_b = var_b
        self.var_c = var_c

if __name__ == 'main':
    with open('config.yaml','r') as stream:
        cfg = yaml.load(stream)
    sc = SomeClass(**cfg)

rawDescription: Gracefully loading YAML config with default methods


code:
import clr
files = [ 'file1.py', 'file2.py' ]    # Look into os.walk() if you have more than a few files
clr.CompileModules('Foo.dll', *files)

rawDescription: How to create Library project

description: Create Library project


code:
if __name__ == "__main__" and __package__ == None:
    import importlib
    import os.path
    import sys
    def _gen_path():
        head, tail = os.path.split(os.path.realpath(__file__))
        while head:
            if not os.path.isfile(os.path.join(head, '__init__.py')):
                yield head
                return
            head, tail = os.path.split(head)
            yield tail
    def _load_package():
        path = list(_gen_path())
        syspath = sys.path[:]
        sys.path[:0] = [path.pop()]
        package = '.'.join(reversed(path))
        importlib.import_module(package)
        sys.path = syspath
        return package
    __package__ = _load_package()

rawDescription: Import structure that works both in packages and out, in both Python 2 and 3?


code:
def split_csv_file(f, dst_dir, keyfunc):
    csv_reader = csv.reader(f)
    header = next(csv_reader)
    header_written = set()
    for row in csv_reader:
        k = keyfunc(row)
        with open(os.path.join(dst_dir, k), mode='a', newline='') as output:
            writer = csv.writer(output)
            if k not in header_written:
                writer.writerow(header)
                header_written.add(k)
        writer.writerow(row[0:1])

rawDescription: Python not writing headers

description: Python not writing headers


code:
with open("list.txt") as fp:
    data = [ast.literal_eval(line) for line in fp if line.strip()]

data

rawDescription: Python, need help parsing items from text file into list


code:
import string
import random
length = 30
chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for i in range(length))

rawDescription: How do i generate secure session_id on python?

description: Generate secure session_id on python


code:
import sys
import csv

from BeautifulSoup import BeautifulSoup as Soup

doc = Soup(xml_string)
data = []
cols = set()
for item in doc.findAll('item'):
    d = {}
    for sub in item:
        if hasattr(sub, 'name'):
            d[sub.name] = sub.text
    data.append(d)
    cols = cols.union(d.keys())

cw = csv.writer(sys.stdout)
cw.writerow(cols)
for row in data:
    cw.writerow([row.get(k, 'N/A') for k in cols])

rawDescription: parse many xml objects and write them into a text file (csv, tab-del, ...) using python

description: Parse many xml objects and write them into a text file (csv, tab-del, ...) using python


code:
import requests
import concurrent.futures

t = concurrent.futures.ThreadPoolExecutor(3) # 3 is the number of threads

get_json_from_url = lambda url: requests.get(url, data).json()

r1, r2, r3 = t.map(get_json_from_url, [url_of_api1, url_of_api2, url_of_api3])

rawDescription: Running API's in parallel on same server


code:
def graph(p, ax=None):
    if ax is None:
        ax = plt.gca()
    x = np.linspace(0, np.pi * 2, 1024)
    y = np.sin(x) + p

    ax.set_title("title")
    ax.set_ylabel("ylabel")
    ax.set_xlabel("xlabel")
    ax.plot(x, y, 'ro', label = "some label")
    ax.legend(loc='upper left')

# Number of subplots. This creates a grid of nx * ny windows
nx = 3
ny = 2

fig = plt.gcf()
# Iterate over the axes
for j in xrange(nx * ny):
    t_ax = fig.add_subplot(nx, ny, j + 1)  # Add one for 1-indexing
    graph(j, t_ax)

plt.show()
fig.tight_layout()
plt.draw()

rawDescription: Python: Graphing many graphs at the same time (matplotlib)


code:
import operator
...

def __init__(self, students):
    self.sortedStudents = sorted(students, key=operator.attrgetter('id'))

rawDescription: how to avoid staticmethod in my Python sample

description: Avoid staticmethod in my Python sample


code:
def f(a, b, c):
    '''
    >>> f(1,2,3)
    42
    '''

if __name__ == '__main__':
    import doctest
#    doctest.testmod()
    doctest.run_docstring_examples(f, globals())

rawDescription: Python: Is it possible to only test specific functions with doctest in a module?


code:
def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return self.default
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

rawDescription: Django CharField blank vs default empty

description: Django CharField blank vs default empty


rawDescription: Python: Caesar shift - inputting string that contains multiple "#'{]$ values


code: usrdata['columnB'], usrdata['columnC'] = zip(*usrdata.apply(functionB, axis=1))

rawDescription: How to edit/add two columns to a dataframe in pandas at once - df.apply()

description: Edit/add two columns to a dataframe in pandas at once - df.apply()


rawDescription: python regex split string to each char but keep anything in brackets

description: Python regex split string to each char but keep anything in brackets


code:
import re
text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
re.findall(r'{[^{}]*}', text)

rawDescription: python regex: match to the first "}"

description: Python regex: match to the first "}"


code:
from xml.dom import Node
from collections import OrderedDict

if not hasattr(Node, 'get_all_node_types'):

    @classmethod
    def get_all_node_types(cls, refresh=False):

        if not hasattr(cls, '_type_dict') or refresh:
            unsorted_types = {getattr(cls, name) : name for name in dir(cls) if name.endswith('_NODE')}
            cls._type_dict = OrderedDict(sorted(unsorted_types.items(), key = lambda t : t[0]))
        return cls._type_dict

    setattr(Node, 'get_all_node_types', get_all_node_types)

rawDescription: Get Node nodeType list programatically (xml.dom.minidom.Node)


code: desired_vel = Vector2D( (target_pos.x + target_vel.x * t) - shooter.pos.x, (target_pos.y + target_vel.y*t) - shooter.pos.y ) * self.max_speed

rawDescription: AI projectile targeting, firing a rocket/bullet/etc. so that it intercepts a target


code: xrange(1, n)

rawDescription: Strange loop behavior in Python

description: Strange loop behavior in Python


rawDescription: Turn 2-D list into 1-D with an index from the 2nd dimension


code:
with open(input('Enter file name: '),'r') as f:
    w = [len(word) for line in f for word in line.rstrip().split(" ")]
    w_avg = sum(w)/len(w)

rawDescription: Computes the average word length for all the words in a file?


code:
from collections import defaultdict

d1 = defaultdict(int)
d2 = defaultdict(int)

data = [["09/2011","09/2011"],["09/2011","10/2011"],["10/2011","12/2011"]]

for d in data:
    d1[d[0]] += 1
    d2[d[1]] += 1

out = []
for key in set(d1.keys()) | set(d2.keys()):
    out.append([key, d1.get(key, 0), d2.get(key, 0)])

rawDescription: Count unique dates from a multidimensional list


rawDescription: Cannot append to a returned list?

description: Cannot append to a returned list


code:
ftplib.cwd() # change working directory
ftplib.rmd() # remove directory

rawDescription: Networking: SNMP in the ADV Environment in C#


code:
len(open('cities5000.txt').read().splitlines())
len(list(csv.reader(open('cities5000.txt'), delimiter='\t')))
len(list(csv.reader(open('cities5000.txt'), delimiter='\t', quotechar=None)))

rawDescription: Strange python csv module behavior - don't splitting records


code:
from django.shortcuts import render_to_response

def category(request, slug):
    slug = slug.lower()
    product_type = local_settings.CATEGORY_NAME_TO_ID.get(slug, False)
    if not product_type:
        raise Http404
    products = models.Product.objects.active().filter(product_type = product_type)
    context = {
        'slug': slug,
        'products': products,
        'key': 'wholesale ipad, ipad with retina display, ipad mini, ipad 3, ipad 2',
    }
    return render_to_response('appletrade/category.html', context, context_instance=RequestContext(request))

rawDescription: How to add meta keyword with django

description: Add meta keyword with django


code:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete

rawDescription: OS X: Determine Trash location for a given path


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

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 4
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <body>
        <form action="/gimmefile" method="get">
          <input type="hidden" name="key" value="8TZbmRZ54IL7"/>
          <button type="submit">Export CSV</button>
        </form>
      </body>
      </html>
    '''

  @cherrypy.expose
  def gimmefile(self, key):
    cherrypy.response.headers['Content-Type']        = 'application/octet-stream'
    cherrypy.response.headers['Content-Disposition'] = 'attachment; filename=yourfile.csv'
    return 'Your;file;content;and;{0}'.format(key)

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: My csv export download button is broken

description: My csv export download button is broken


code:
import requests
from django.core.files.uploadedfile import SimpleUploadedFile
response = requests.get("https://www.example.getfile.com/file_id=234")
excel_file = SimpleUploadedFile("excel.xls", response.content, content_type="application/vnd.ms-excel")
file_data = FileData(excel_file=excel_file)
file_data.save()

rawDescription: Save binary data get from url into Django FileField


code:
from django.db import transaction

with  transaction.atomic():
    stories = Story.objects.filter(introtext='')
    for story in stories:
        introtext = story.content[0:(story.content.find('.'))] + ".</p>"
        Story.objects.filter(pk=story.pk).update(introtext=introtext)

rawDescription: What is the most efficient way to iterate django objects updating them?


code: s.str.cat(sep=', ')

rawDescription: How to combine multiple rows of strings into one using pandas?

description: Combine multiple rows of strings into one using pandas


code:
import numpy as np
import pandas as pd
anarray=np.array([[0, 31], [1, 26], [0, 35], [1, 22], [0, 41]])
df = pd.DataFrame(anarray, columns=['is_female', 'age'])
by_gender=df[['is_female','age']].groupby(['is_female'])
by_gender.groups # returns indexes of records
by_gender.get_group(0)['age'] # age of males

rawDescription: Getting count of rows using groupby in Pandas


code:
def find_next(cur_dt):
    import datetime as dt
    t = [dt.time(5,30), dt.time(8,30), dt.time(13,0), dt.time(17,30)]

    cur_t = cur_dt.time()
    cur_d = cur_dt.date()

    for i in range(len(t)):
        if t[i] > cur_t:
            rt = [t[(j+i)%len(t)] for j in range(len(t))]
            rd = [cur_d] * (len(t)-i) + [cur_d + dt.timedelta(days=1)]*i
            return [dt.datetime.combine(rd[j],rt[j]) for j in range(len(rt))]

    # everything happens tomorrow
    return [dt.datetime.combine(cur_d + dt.timedelta(days=1), i) for i in t]

rawDescription: How to generate a sequence of future datetimes in Python and determine nearest datetime from set

description: Generate a sequence of future datetimes in Python and determine nearest datetime from set


code: #!/usr/bin/python

rawDescription: correct way of Setting pythonpath

description: Correct way of Setting pythonpath


code:
c.execute('select * from stocks where price > ?', (50,))

c.execute('select * from stocks where price between ? and ?', (40, 70))

c.execute('select * from stocks where price > ? and symbol = ?', (50, 'IBM'))

rawDescription: Extracting values from SQLite database in Python


code:
def ATM():
    global mode
    pinNum = input('Please enter your 4 digit secret code: ')
    userBalance = float(dict2[pinNum])
    actions = {
        '1': balance,
        '2': withdraw,
        '3': deposit
    }
    while mode == 0:
        if pinNum in dict1:
            greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum]))
        if greet == '4':
            break
        else:
            userBalance = actions.get(greet)(userBalance) or userBalance

def balance(userBalance):
    print('Your current balance is {}.'.format(userBalance))

def deposit(userBalance):
    amount = input('Please enter the amount you wish to be deposited: ')
    userBalance += float(amount)
    return userBalance

def withdraw(userBalance):
    amount = input('Please enter the amount you wish to withdraw" ')
    if userBalance - float(amount) < 0:
             print('You do not have sufficient funds.')
    else:
        userBalance -= float(amount)
    return userBalance

rawDescription: Modifying a variable from one function to another in Python


code:
from django.db import models
from django.db.models.query import QuerySet

class SoftDeletionQuerySet(QuerySet):
    def delete(self):
        # Bulk delete bypasses individual objects' delete methods.
        return super(SoftDeletionQuerySet, self).update(alive=False)

    def hard_delete(self):
        return super(SoftDeletionQuerySet, self).delete()

    def alive(self):
        return self.filter(alive=True)

    def dead(self):
        return self.exclude(alive=True)

class SoftDeletionManager(models.Manager):
    def __init__(self, *args, **kwargs):
        self.alive_only = kwargs.pop('alive_only', True)
        super(SoftDeletionManager, self).__init__(*args, **kwargs)

    def get_queryset(self):
        if self.alive_only:
            return SoftDeletionQuerySet(self.model).filter(alive=True)
        return SoftDeletionQuerySet(self.model)

    def hard_delete(self):
        return self.get_queryset().hard_delete()

class SoftDeletionModel(models.Model):
    alive = models.BooleanField(default=True)

    objects = SoftDeletionManager()
    all_objects = SoftDeletionManager(alive_only=False)

    class Meta:
        abstract = True

    def delete(self):
        self.alive = False
        self.save()

    def hard_delete(self):
        super(SoftDeletionModel, self).delete()

rawDescription: Django remove bulk-delete

description: Django remove bulk-delete


code:
vctestNames = dict((vctest['name'], vctest) for vctest in vcdict['tests'])
dbtestNames = dict((dbtest.name, dbtest) for dbtest in alldbTests)

obsoleteTests = [vctestNames[key]
                 for key in set(vctestNames.keys()) - set(dbtestNames.keys())]

newTests = [dbtestNames[key]
            for key in set(dbtestNames.keys()) - set(vctestNames.keys())]

rawDescription: Pythonic way to parse list of dictionaries for a specific attribute?


code:
from BeautifulSoup import BeautifulSoup

html = \
"""

  Foo1

    Home

    Extract

    Sitemap

"""

soup = BeautifulSoup(html)
soup.findAll("div",id="hotlink")[2].a

# Sitemap

rawDescription: Python -- Regex -- How to find a string between two sets of strings


code:
def process_spider_output(self, response, result, spider):
    items = []
    for x in result:
        if isinstance(x, Request):
            if x.dont_filter or self.should_follow(x, spider):
                yield x
            else:
                domain = urlparse_cached(x).hostname
                if domain and domain not in self.domains_seen[spider]:
                    self.domains_seen[spider].add(domain)
                    # create an item here and yield it
        else:
            yield x

rawDescription: How return items from a custom spider middleware


code:
import sys
from tkinter import *

def forget_page1():
    widgets = [mLabel1, button]
    for widget in widgets:
        widget.place_forget ()
    loadNextPage()

def loadNextPage():
    mLabel2 = Label (text="Welcome to the next page.")
    mLabel2.place (x= 222,y = 200)
    button1 = Button (text = "Hello" )
    button1.place(x = 333,y = 230)

################################
mGui = Tk ()

mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")

mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
                 fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)

button = Button (text = "Next", command = forget_page1)
button.place(x = 275,y = 230)

mGui.mainloop()

rawDescription: first page forgotten where to put the code?

description: First page forgotten where to put the code


code:
from xml.etree.ElementTree import ElementTree

tree = ElementTree()

# Test input
tree.parse("sample.xml")

# List containing names you want to keep
inputID = ['name1', 'name2', 'name3']

for node in tree.findall('.//data'):
    # Remove node if the name attribute value is not in inputID
    if not node.attrib.get('name') in inputID:
        tree.getroot().remove(node)

# Do what you want with the modified xml
tree.write('sample_out.xml')

rawDescription: Filter xml data in Python

description: Filter xml data in Python


code:
from BeautifulSoup import BeautifulSoup
import requests
import re

url = "https://data.medicare.gov/data/hospital-compare"

r = requests.get(url)

data = r.text

soup = BeautifulSoup(data)

for link in soup.findAll('a'):
   if link.has_key('href'):
      if(link['href'].endswith("=Hospital_Revised_Flatfiles.zip")):
         print(link['href'])

rawDescription: BeautifulSoup with dynamic href

description: BeautifulSoup with dynamic href


code:
from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        valuex=int(x.get())
        valuey=int(y.get())
        valuez=int(z.get())
        cappf.set(int(str(valuex)+str(valuey))*10**valuez)
        capnf.set(int(str(valuex)+str(valuey))*10**valuez*10**-3)
        capuf.set(int(str(valuex)+str(valuey))*10**valuez*10**-6)
    except ValueError:
        pass

root=Tk()
root.title('Capacitor Calculator')
mainframe=ttk.Frame(root, padding='10 10 10 10')
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

x=StringVar()
x_entry=ttk.Entry(mainframe, width=3, textvariable=x)
x_entry.grid(column=1, row=2, sticky=(W,E))
y=StringVar()
y_entry=ttk.Entry(mainframe, width=3, textvariable=y)
y_entry.grid(column=1, row=3, sticky=(W,E))
z=StringVar()
z_entry=ttk.Entry(mainframe, width=3, textvariable=z)
z_entry.grid(column=1, row=4, sticky=(W,E))
cappf=StringVar()
capnf=StringVar()
capuf=StringVar()

ttk.Button(mainframe, width=7, text='Calculate', command=calculate).grid(column=2, row=5, sticky=(N, E, W, S))
ttk.Label(mainframe, textvariable=cappf).grid(column=2, row=2, sticky=N)
ttk.Label(mainframe, textvariable=capnf).grid(column=2, row=3, sticky=N)
ttk.Label(mainframe, textvariable=capuf).grid(column=2, row=4, sticky=N)
ttk.Label(mainframe, text='Input:').grid(column=1, row=1, sticky=N)
ttk.Label(mainframe, text='Amount:').grid(column=2, row=1, sticky=N)
ttk.Label(mainframe, text='Units:').grid(column=3, row=1, sticky=N)
ttk.Label(mainframe, text='pf').grid(column=3, row=2, sticky=N)
ttk.Label(mainframe, text='nf').grid(column=3, row=3, sticky=N)
ttk.Label(mainframe, text='uf').grid(column=3, row=4, sticky=N)
##########################################################################################################################
ttk.Button(mainframe, text='Quit', style='red.TButton', command=root.destroy).grid(column=2, row=6, sticky=(N, E, S, W))

ttk.Style().configure('red.TButton', foreground='red', padding=6, font='Corbel 16')
##########################################################################################################################
ttk.Style().configure('TLabel', padding=6, font='Corbel 16', foreground='#0077AF')
ttk.Style().configure("TButton", padding=6, relief="flat", font='Corbel 18', foreground='#00AA11')

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=3)
x_entry.focus()
y_entry.focus()
z_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()

rawDescription: Configuring independent widgets (Tkinter ttk, Python)


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

import odf
from odf.opendocument import OpenDocumentText
from odf.element import Element
from odf.text import P
from odf.math import Math
from namespaces import MATHNS

def main():
    doc = OpenDocumentText()
    p = P(text=u'text')
    df = odf.draw.Frame( zindex=0, anchortype='as-char')
    p.addElement(df)
    doc.text.addElement(p)

    formula =u'c=sqrt(a^2+b^2)'
    math = Math()
    annot = Element(qname = (MATHNS,u'annotation'))
    annot.addText(formula, check_grammar=False)
    annot.setAttribute((MATHNS,'encoding'), 'StarMath 5.0', check_grammar=False)
    math.addElement(annot)
    do = odf.draw.Object()
    do.addElement(math)
    df.addElement(do)

    outputfile = u'result'
    doc.save(outputfile, True)

if __name__ == '__main__':
    main()

rawDescription: How to add math formulas in odt document using odfpy?

description: Add math formulas in odt document using odfpy


code:
tree[1]['blah'] = 'Hello'
print(tree)

rawDescription: Can you explain this behavior with Python defaultdict and autovivification

description: Explain this behavior with Python defaultdict and autovivification


code:
def SailorsResults():
    tony = []
    tony = [3 ,3, 1, 1, 2, 6]
    tony.remove(max(tony))
    print(tony)

SailorsResults()

rawDescription: Remove the highest number in a list and print


code:
import pipes
from subprocess import check_call

check_call("""source /path/to/virtualenvwrapper.sh &&
    mkvirtualenv --no-site-packages """ + pipes.quote(envname),
    executable='bash', shell=True)

rawDescription: subprocess.Popen: mkvirtualenv not found

description: Subprocess.Popen: mkvirtualenv not found


code:
class Account(models.Model):
    username = models.OneToOneField(User, primary_key=True, unique=True)
    receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True)
    balance = models.DecimalField(max_digits=16, decimal_places=8, default=0)

    def __str__(self):
        return str(self.username)

class Deposit(models.Model):
    amount = models.DecimalField(max_digits=16, decimal_places=8, default=0)
    user = models.ForeignKey(User, related_name="deposits")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    confirmed = models.BooleanField(default=False)
    accounted = models.BooleanField(default=False)

    def __str__(self):
        return str(self.user.account.receiveaddress)

rawDescription: Django: Reference between models

description: Django: Reference between models


code:
DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.CustomDownloaderMiddleware': 543,
    'scrapy.contrib.downloadermiddleware.cookies.CookiesMiddleware': 700 # <-
}

rawDescription: How to enable cookiemiddleware in scrapy in python

description: Enable cookiemiddleware in scrapy in python


code:
if ' 645w' in src:
    index = src.find(' 645w')
    end_of_url = src[:index]
    print(end_of_url[end_of_url.rfind('//'):])

rawDescription: How do I reverse search in String to get the index?

description: Reverse search in String to get the index


code: df.apply( lambda x: len(x[-x.isnull()].unique()) == 1 , axis = 1).all()

rawDescription: Use Python pandas to check if coloumns contain identical values or NaN


code:
# for python 3.x
from unittest.mock import patch

# for python 2.x
# from mock import patch
import pandas as pd

class test(unittest.TestCase):
    @patch('foo.pd.read_csv')
    def test(self, mock_read_csv):
        mock_read_csv.return_value = pd.DataFrame({'column1': Series([1., 2., 3.]),'column2': Series([4., 5., 6.])})
        assert foo().getData()

rawDescription: How to change return value of mocked obj?

description: Change return value of mocked obj


code: model = listWidget.model()

rawDescription: Signal when an item is added or removed to a QListWidget


code:
from tkinter import *

class Calc(Frame):
    def __init__(self, master):
        self.modefunction = 1
        """ Initialize the frame. """
        super(Calc,self).__init__(master)
        self.grid()

        self.calculations_frm = Frame(self, width=100, height=30)#bg = "red"
        self.calculations_frm.grid(row = 0, column = 0, columnspan=2)

        self.buttons_frm = Frame(self, width= 50, height=30,)#bg = "green")
        self.buttons_frm.grid(row = 1, column = 1)

        self.buttons_2_functions_1_frm = Frame(self, width=50, height=30)#bg = "blue")
        self.buttons_2_functions_1_frm.grid(row = 1, column = 0)
        self.create_GUI()

    def create_show_calculations(self):
        self.calculation_lbl = Label(self.calculations_frm, text = "will show caluclations here").pack()

    def create_buttons(self):
        #mc stands for mode change
        self.mode_change_btn = Button(self.buttons_frm, text = "mc", command = self.mode_change, height = 1, width = 5)
        self.mode_change_btn.grid(row = 0,column = 0)

        self.plus_btn = Button(self.buttons_frm, text = "plus", height = 1, width = 5)
        self.plus_btn.grid(row = 1,column = 0)

    def create_GUI(self):
        self.create_show_calculations()
        self.create_buttons()
        self.create_1_function_gui()

    def create_1_function_gui(self):
        self.tan_btn = Button(self.buttons_2_functions_1_frm, text = "tan", height = 1, width = 5)
        self.tan_btn.grid(row = 0,column = 0)

        self.san_btn = Button(self.buttons_2_functions_1_frm, text = "san", height = 1, width = 5)
        self.san_btn.grid(row = 0,column = 1)

        self.coz_btn = Button(self.buttons_2_functions_1_frm, text = "coz", height = 1, width = 5)
        self.coz_btn.grid(row = 1,column = 0)

    def create_2_function_gui(self):
        self.buttons_2_functions_2_frm = Frame(self, width=50, height=30)#bg = "blue")
        self.buttons_2_functions_2_frm.grid(row = 1, column = 0)

        self.inverse_tan_btn = Button(self.buttons_2_functions_2_frm, text = "tan-1", height = 1, width = 5)
        self.inverse_tan_btn.grid(row = 0,column = 0)

        self.inverse_san_btn = Button(self.buttons_2_functions_2_frm, text = "san-1", height = 1, width = 5)
        self.inverse_san_btn.grid(row = 0,column = 1)

        self.inverse_coz_btn = Button(self.buttons_2_functions_2_frm, text = "coz-1", height = 1, width = 5)
        self.inverse_coz_btn.grid(row = 1,column = 0)

    def mode_change(self):
        if self.modefunction == 1:
            self.buttons_2_functions_1_frm.destroy()
            self.modefunction = 2
            self.buttons_2_functions_2_frm = Frame(self, width=50, height=30)#bg = "blue")
            self.buttons_2_functions_2_frm.grid(row = 1, column = 0)
            self.create_2_function_gui()
        else:
            self.buttons_2_functions_2_frm.destroy()
            self.modefunction =  1
            self.buttons_2_functions_1_frm = Frame(self, width=50, height=30)#bg = "blue")
            self.buttons_2_functions_1_frm.grid(row = 1, column = 0)
            self.create_1_function_gui()

root = Tk()
root.title("booking system")
root.geometry("500x500")
root.configure(bg="white")
app = Calc(root)

root.mainloop()

rawDescription: Python Tkinter replacing the label and command of a button by clicking another button


rawDescription: What is the best way to get the following data into long format using column labels?


code:
if 'EVN' not in segmentList[x][0:3] :
    create_EVN()

rawDescription: Check if string doesn't exist in List

description: Check if string doesn't exist in List


rawDescription: Return the file extension from filename using string index in python


code:
def foo(some_list):
    result = {}
    for k, v in some_list:
        result.setdefault(k, []).append(v)

    return result

rawDescription: convert a list of tuples to a dictionary and preserve duplicates

description: Convert a list of tuples to a dictionary and preserve duplicates


code:
if x == 1:
    pass
elif x == 5:
    pass
elif x == 10:
    pass

rawDescription: Python: Does python have an equivalent to 'switch'?


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

data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
cmap = cm.get_cmap('jet', 4)
bounds = np.arange(5)
vals = bounds[:-1]
norm = colors.BoundaryNorm(bounds, cmap.N)
ax.imshow(data[None], aspect='auto', interpolation='nearest', cmap=cmap, norm=norm)

cax = fig.add_subplot(122)
cbar = fig.colorbar(ax.images[0], cax=cax, boundaries=bounds, values=vals)
cbar.set_ticks(vals + .5)
cbar.set_ticklabels(['one', 'two', 'three', 'four'])

rawDescription: getting a matplotlib colorbar tick outside data limits for use with boundaries keyword

description: Getting a matplotlib colorbar tick outside data limits for use with boundaries keyword


code:
from itertools import groupby, accumulate
from collections import defaultdict

def sub_seq(li, n):
    d = defaultdict(list)
    rle = [(k, len(list(g))) for k, g in groupby(li)]
    endpoints = accumulate(size for k, size in rle)
    for end_index, (value, count) in zip(endpoints, rle):
        for index in range(end_index - count, end_index - n + 1):
            d[value].append(index)
    return dict(d)

rawDescription: Sequence of elements in a list satisfying a condition


code: obj, created = MyModel.objects.get_or_create(keywordArguments)

rawDescription: A create_or_get method in Django

description: A create_or_get method in Django


code:
from itertools import izip_longest
# http://docs.python.org/library/itertools.html#itertools.izip_longest

# get a list of open readers using a list comprehension
readers = [csv.reader(open(fname, "r")) for fname in list_of_filenames]

# open writer
output_csv = csv.writer(...)

for bunch_of_lines in izip_longest(*readers, fillvalue=['', '', '', '']):
  # Here bunch_of_lines is a tuple of lines read from each reader,
  # e.g. all first lines, all second lines, etc
  # When one file is past EOF but others aren't, you get fillvalue for its line.
  merged_row = []
  for line in bunch_of_lines:
      # if it's a real line, you have 4 items of data.
      # if the file is past EOF, the line is fillvalue from above
      #   which again is guaranteed to have 4 items of data, all empty strings.
      merged_row.extend([line[1], line[3]]) # put columns 1 and 3
  output_csv.writerow(merged_row)

rawDescription: Combining columns of CSV files of unknown lengths but same width in Python


code:
article = Article(...)
revision = Revision(article, ...)
article.current_revision = revision
session.add(article)
session.commit()

rawDescription: Am I abusing the flush() call?

description: Am I abusing the flush() call


code:
with open("myfile.txt", "w") as f:
    for row in n:
        s = ', '.join(str(x) for x in row)
        f.write(s)
        f.write("\n")

rawDescription: How do I write a numpy array into a file in a string form?

description: Write a numpy array into a file in a string form


code:
while True:
    # do some stuff

    if (want_to_go_to_start_early):
        continue # Go back to the start of the loop

    if (want_to_exit_loop):
        break    # Exit the loop

    # do other stuff in the loop

    # at the end of the loop it goes back to the top

# stuff outside the loop (only gets reached after the 'break')

rawDescription: Python 3.x - If quitting program, at the y/n conditional how do I make the no answer go back to the start of program?


rawDescription: Regex: Python First Occurrence After Return or Newline


code: OrderedDict(sorted(your_dict.items(), key=lambda item: float(item[0])))

rawDescription: Sorting DefaultDict() using key values in Python3.x


code:
class Model(object):
    db = None # This var is a class attribute

    @classmethod
    def init_db(cls):
        cls.db = your_code_to_create_db()

class Entry(Model):
    def __init__(self, entry_id, entry_value):
        self.entry_id = entry_id
        self.entry_value = entry_value
        super(Entry, self).__init__()

    def save(self):
        # Use db here
        self.db

# To use
Model.init_db() # Inits the one db var for the class
entry = Entry(...)
entry.save()

rawDescription: Python, DB and models

description: Python, DB and models


code:
for i in range(0,11):
    if i % 3 == 0 and i != 0:
        continue
    print(i)

1
2
4
5
7
8
10

rawDescription: skip every nth value when looping over a range - python

description: Skip every nth value when looping over a range - python


code:
import pandas.io.data as web
web.DataReader(["AAPL", "GOOG"], "yahoo", start='2014-03-26').to_frame()

rawDescription: Random Dataframes

description: Random Dataframes


code:
import os, sys
filename = os.path.splitext(os.path.basename(sys.argv[0]))[0]
if not os.path.exists(filename):
    # filename does not exists, we will emulate cmd behaviour
    sys.stderr.write("'%s' is not recognized as an internal or external command,\noperable program or batch file." % filename)
    sys.exit(9009)
ret = os.system("python %s %s" % (
        filename,
        " ".join(sys.argv[1:])
        ))
exit(ret)

rawDescription: How to run a python script without specifying the file extension (cross platform solution)?

description: Run a python script without specifying the file extension (cross platform solution)


code:
my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
del my_list[0]
my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
if 'hey' in my_list:     # you're looking for this one I think
    del my_list[my_list.index('hey')]

my_list

rawDescription: Python: Remove a single entry in a list based on the position of the entry


code:
def get_images(base_url):
   url = base_url

   while url:
       with contextlib.closing(urllib2.urlopen(url)) as url_file:
           json_data = url_file.read()
       # get_image_urls() extracts the images from JSON and returns an iterable.
       # python 3.3 and up have "yield from"
       # (see https://www.python.org/dev/peps/pep-0380/)
       for img_url in get_image_urls(json_data):
           yield img_url
       # dict.get() conveniently returns None or
       # the provided default argument when the
       # element is missing.
       url = json_data.get('pagination', {}).get('next_url')

images = list(get_images(base_url));

rawDescription: How to call the function it's in?

description: Call the function it's in


code:
from PIL import Image, ImageDraw

img = Image.new('RGBA',(100, 100))

draw = ImageDraw.Draw(img)
draw.ellipse((25, 25, 75, 75), fill=(255, 0, 0))

img.save('test.gif', 'GIF', transparency=0)

rawDescription: How to CREATE a transparent gif (or png) with PIL (python-imaging)


code:
while 1:
    read, _, _ = select.select([inSoc],[],[], 0)
    #if insoc has something for you to read
    for soc in read:
        data = soc.recv(65536)
    #do something else

rawDescription: How to listen on a port and broadcast from another at the same time? Python

description: Listen on a port and broadcast from another at the same time? Python


code:
for name, obj in self.__dict__.iteritems():
    if isinstance(obj, QtCore.QObject) and not obj.objectName(): # QObject without a name
        obj.setObjectName(name)

rawDescription: Python: How to obtain an instance's name at runtime?


code:
import cv2
import numpy as np

def onTrackbarChange(trackbarValue):
    pass

cv2.namedWindow('ctrl')
cv2.createTrackbar( 'thresh', 'ctrl', 128, 255, onTrackbarChange )
c = cv2.VideoCapture(0)
while(1):
    im = c.read()[1]
    thresh=cv2.threshold(cv2.cvtColor(im,cv2.COLOR_BGR2GRAY),
        cv2.getTrackbarPos('thresh','ctrl'),
        255,cv2.THRESH_BINARY)[1]
    cv2.imshow('thresh',thresh)
    if cv2.waitKey(1)==27:
        exit(0)

rawDescription: Python: Input text boxes capturing userinput in parallel to OpenCV Live Webcam image


code:
import numpy as np
import pylab as plt

x = np.linspace(0, 10)
y = x**2
z = 50*np.sin(x)
plt.plot(x, y)
plt.fill_between(x, z, facecolor='r', zorder=3)
plt.show()

rawDescription: matplotlib: how can I make an opaque filled region that covers what's underneath?

description: Matplotlib: how can I make an opaque filled region that covers what's underneath


code:
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
ax=fig.add_subplot(111)

palette = itertools.cycle(sns.color_palette())

for f in files:
    ax.scatter(args, color=next(palette))

rawDescription: seaborn cycle through colours with matplotlib scatter

description: Seaborn cycle through colours with matplotlib scatter


rawDescription: Single quotes as a part of an element of a Python list


code: anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=1, blit=False, repeat=False)

rawDescription: FuncAnimation goes past the frames argument


code:
import matplotlib.pyplot as plt
from pylab import axes

fig = plt.figure()
coords = fig.transFigure.transform((.1, .5))
ax = axes([.2, .1, .7, .8])
ax.plot([1, 2], [1, 2])
axcoords = ax.transAxes.inverted().transform(coords)
ax.set_ylabel('BlaBla')
ax.yaxis.set_label_coords(*axcoords)
plt.draw()

plt.figure().show()
coords = fig.transFigure.transform((.1, .5))
ax = axes([.2, .1, .4, .8])
ax.plot([1, 2], [1, 2])
ax.set_ylabel('BlaBla')
axcoords = ax.transAxes.inverted().transform(coords)
ax.yaxis.set_label_coords(*axcoords)

plt.draw()
plt.show()

rawDescription: Set axes label in coordinate system of figure rather than axes


code: from __future__ import division

rawDescription: calculating angle between two lines in python

description: Calculating angle between two lines in python


code:
def emit(self, record):
    """
    Emit a record.

    If a formatter is specified, it is used to format the record.
    The record is then written to the stream with a trailing newline.  If
    exception information is present, it is formatted using
    traceback.print_exception and appended to the stream.  If the stream
    has an 'encoding' attribute, it is used to determine how to do the
    output to the stream.
    """
    try:
        msg = self.format(record)
        stream = self.stream
        stream.write(msg)
        stream.write(self.terminator)
        self.flush()   # <---
    except (KeyboardInterrupt, SystemExit): #pragma: no cover
        raise
    except:
        self.handleError(record)

rawDescription: Does python logging flush every log?

description: Does python logging flush every log


code:
a,b = zip(*[i.split('.') for i in d])
a
b

rawDescription: More pythonic way to do this (string splitting)?


code:
import tkinter as tk
window = tk.Tk()
window.title("6 Questions")
window.geometry("500x150")
score = 0
def inst():
    t = tk.Label(window, text="All you need to do is just answer each question with either a '1, 2, 3' or the actual word.")
    t.pack()

def start():
    def submit():
        print (ans.get())
        #or do whatever you like with this

    root = tk.Tk()
    root.title("question 1")
    q = tk.Label(root, text="what type of input holds whole numbers")
    q.pack()
    a = tk.Label(root, text="1.) int")
    a.pack()
    b = tk.Label(root, text="2.) string")
    b.pack()
    c = tk.Label(root, text="3.) float")
    c.pack()
    ans = tk.Entry(root, width=40)
    ans.pack()
    #here is the button I want to verify the answer
    sub = tk.Button(root, text="Submit", command=submit)
    sub.pack()

greet = tk.Label(window, text="Welcome to the 6 Question Quiz.")
greet.pack()
startButton = tk.Button(window, command=start, text="Start")
startButton.pack()
instr = tk.Button(window, text="Instructions", command=inst)
instr.pack()
end = tk.Button(window, text="Exit", command=window.destroy)
end.pack()

window.mainloop()

rawDescription: Python tkinter quiz

description: Python tkinter quiz


code:
import matplotlib.pyplot as plt

def chartmak(dic):
    entries = list(dic.items())

    if len(entries) < 10:
        entries.extend([('', 0)] * (10 - len(entries)))

    values = [v for l, v in entries]

    fig, ax = plt.subplots()
    n = len(entries)
    ax.barh(range(n), values, align='center', fc='#80d0f1', ec='w')
    ax.set_yticks(range(n))

    #this need more work to put the GB or the TB
    ax.set_yticklabels(['' if e == 0 else '{:3d} GB'.format(e) for e in values], color='gray')
    ax.tick_params(pad=10)

    for i, (label, val) in enumerate(entries):
        ax.annotate(label.title(), xy=(10, i), fontsize=12, va='center')

    for spine in ('top', 'right', 'bottom', 'left'):
        ax.spines[spine].set_visible(False)

    ax.xaxis.set_ticks([])
    ax.yaxis.set_tick_params(length=0)

    plt.gca().invert_yaxis()
    plt.show()

chartmak({'1': 10, '2':20, '3':30})
chartmak({'1': 10, '2':20, '3':30, '4':40, '5':80, '6':120, '7':100, '8':50, '9':30, '10':40})

rawDescription: python matplotlib how make fixed width Bar chart

description: Python matplotlib how make fixed width Bar chart


code:
names = ['z_' + '_'.join([str(n) for n in name_nums]) for name_nums in list_to_generate_expression_names]
exprs = ['+'.join(expr_items) for expr_items in list_to_generate_expressions]

for name, expr in zip(names,exprs):
    exec('{0} = {1}'.format(name,expr))

rawDescription: Generate many SymPy expressions using the same symbols


code:
def home(request):
    if not  logged_in:
        return HttpResponseRedirect("/login?next=%s"%reverse("home"))

    return HttpResponse(...)

rawDescription: Is it OK to do 302s for architecture in my web applciation?


code:
def get_foo(_id):
    get_foo.foos = dict()
    def real_get_foo(_id):
        # get foo from the API
        get_foo.foos[_id] = foo
        return foo
    if _id in get_foo.foos:
        return get_foo.foos[_id]
    return real_get_foo(_id)

rawDescription: How to handle python objects built from a web API that have references to each other?

description: Handle python objects built from a web API that have references to each other


code:
import enchant
d = enchant.Dict("en_US")
d.check("Hello")
d.check("Helo")
d.suggest("Helo")

rawDescription: How to check if a word is an English word with Python?

description: Check if a word is an English word with Python


code:
class Oracle(object):
  ...

class SQLite(object):
  ...

dbkind = dict(sqlite=SQLite, oracle=Oracle)

def Database(url):
  db_type, rest = string.split(self.url, "://", 1)
  return dbkind[db_type](rest)

rawDescription: Python - how to implement Bridge (or Adapter) design pattern?


code:
import re
r = re.compile(r'(\d+\.\d+)')
r.match('50.2000\xc2\xb0 E').group(1)

rawDescription: How do I split the following string?

description: Split the following string


code:
import time
with open('/Users/alexandrelara/Library/Logs/Unity/Player.log') as f:
    while True:
        line = f.readline()
        if line:
            if line.startswith('[Zone]') and "tag=PLAYSTATE value=LOSING" in line:
                print(line)
        else:
            time.sleep(1)

rawDescription: Reducing CPU usage while parsing logs in real time


code:
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('bar')
parser.parse_args('X --foo Y'.split())
parser.print_help()

rawDescription: what does metavar and action mean in argparse in python?

description: What does metavar and action mean in argparse in python


code:
from string import ascii_uppercase

one_hot = {}
for i, l in enumerate(ascii_uppercase):
    bits = ['0']*26; bits[i] = '1'
    one_hot[l] = ' '.join(bits)

rawDescription: Generate a string representation of a one-hot encoding


code:
tk = Tk()
tk.withdraw()

#do file dialog stuff
(...)

tk.destroy()

rawDescription: Python script to stop Tkinter

description: Python script to stop Tkinter


code:
import theano
import theano.tensor as T

import numpy as np
rng = np.random.RandomState(42)

n, m1, m2  = 10, 20, 30
A = T.fmatrix()
B = T.fmatrix()

C = A.reshape((n, m1, 1)) * B.reshape((n, 1, m2))

func_C = theano.function([A, B], C)

a = rng.randn(n, m1).astype(np.float32)
b = rng.randn(n, m2).astype(np.float32)

r1 = func_C(a, b)
r2 = np.einsum("ij, ik -> ijk", a, b)
assert np.sqrt(((r1 - r2) ** 2).sum()) < 1e-5

rawDescription: Defining expression in theano

description: Defining expression in theano


code:
low = 1
high = 100
guess = random.randint(low, high)
guesses = 1
while guess != answer:
    if guess > answer:
        high = guess - 1
        print(guess)
    elif guess < answer:
        low = guess + 1
        print(guess)
    guess = random.randint(low, high)
    guesses += 1
print("\nWhoopy, I guessed correct.\n")
print("It took me %s guesses to guess %s." % (guesses, answer))

rawDescription: Updating the range during while loop so no dupe guess


code: X.d = Descriptor()

rawDescription: Python Metaprogramming of Descriptors: How to add descriptor after class definition?


code:
import django, datetime
django.utils.timezone.now()
datetime.datetime.now()
datetime.datetime.now() > django.utils.timezone.now()

rawDescription: Django cant do datetime comparision

description: Django cant do datetime comparision


code:
sentinel = object()
def myfunc(arg1, arg2=sentinel):
    if arg2 is sentinel:
        arg2 = arg1
    print (arg1, arg2)

myfunc("foo")           # Prints 'foo foo'
myfunc("foo", None)     # Prints 'foo None'

rawDescription: In Python, can I specify a function argument's default in terms of other arguments?


code:
def layer_activation(input_tensor, weight_tensor):
    return tf.matmul(input_tensor, weight_tensor)

# ...
x = tf.placeholder(...)
W_to_hidden = tf.Variable(...)
test = layer_activation(input_tensor, weight_tensor)
# ...

rawDescription: Tensorflow, py_func, or custom function

description: Tensorflow, py_func, or custom function


code:
# l = [x0y0z0, ...]
def bucketsofun(l, sp=16):
  r = [[] for x in range(sp)]
  for b, e in itertools.izip(itertools.cycle(r), l):
    b.append(e)
  return r

rawDescription: Split Python list into several lists based on index


code:
vectors = np.vstack((vv1, v2, v3))
products = np.dot(A, v)

rawDescription: Python: Multiplying a 3x3 matrix to 3nx1 array without using loops


code:
class ServiceForm(forms.ModelForm):
    regular_service = forms.ChoiceField(required = True, choices = CHOICES, widget=forms.RadioSelect(attrs={'class' : 'Radio'}), initial=1)

rawDescription: How do I 'check' a radio button value using django RadioSelect widget


code:
app = gyroidUI_module.AppWindow()
app.show()

result = app.exec_()
if result == 1:
    fill_ratio = app.ui.fill_ratio_box.value()
    contour_value = app.ui.contour_value_box.value()
    contours = int(app.ui.contours_box.value())

    if app.ui.check_contour_value.checkState() != 0:
        use_contour_value = True
    else:
        use_contour_value = False

    if app.ui.check_closed_surface.checkState() != 0:
        closed_surface = True
    else:
        closed_surface = False

rawDescription: Importing a PyQt-GUI that can save values into another script


code:
from tkinter import *

class mainwindow():
    def __init__(self, master):

        self.master = master
        menubalk = Menu(self.master)

        menubalk.add_command(label="New window", command=self.openNewwindow)
        self.master.config(menu=menubalk)

    def openNewwindow(self):

        def showValues(var, entry):
            print('Value checkbutton:', var.get(), ';', 'Value entryfield: ', entry.get())

        window = Toplevel(self.master)
        var = BooleanVar()
        checkbutton = Checkbutton(window, text="Check", variable=var)
        checkbutton.grid(column=0, row=0)

        var2 = StringVar()
        entry = Entry(window, textvariable=var2)
        entry.grid(column=2,row=0)

        button2 = Button(window,text=u"Show", command=lambda: showValues(var, entry))
        button2.grid(column=1, row=0)

def main():
    root = Tk()
    window = mainwindow(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python tkinter checkbutton value not accesible


code:
np.all(df['series1'] == df['series5'])
np.all(df['series1'] == df['series3'])
np.all(df['series2'] == df['series4'])

rawDescription: Plotting more than 2 series on a figure (matplotlib plot_date() )


code:
def search(start_state, neighbors, goal):
    path = [start_state]

    class PathFound(RuntimeError):
        pass

    def rsearch(x):
        if goal(x):
            raise PathFound
        for y in neighbors(x):
            path.append(y)
            rsearch(y)
            path.pop()

    try:
        rsearch(start_state)
    except PathFound:
        return path

    return None # No path exists

rawDescription: Depth first search algorithm in python

description: Depth first search algorithm in python


code:
import os

def free_space_up_to(free_bytes_required=161061273600, rootfolder="/data/", filesize=104857600, basename="filename-"):
    '''Deletes rootfolder/basename*, oldest first, until there are free_bytes_required available on the partition.
    Assumes that all files have file_size, and are all named basename{0,1,2,3,...}
    Returns number of deleted files.
    '''
    statv = os.statvfs(rootfolder)
    required_space = free_bytes_required - statv.f_bfree*statv.f_bsize
    basepath = os.path.join(rootfolder, basename)
    baselen = len(basepath)
    if required_space <= 0:
        return 0

    # "1 +" here for quickly rounding
    files_to_delete = 1 + required_space/filesize

    # List all matching files. If needed, replace with os.walk for recursively
    # searching into subdirectories of rootfolder
    file_list = [os.path.join(rootfolder, f) for f in os.listdir(rootfolder)
                 if f.startswith(basename)]

    file_list.sort(key=lambda i: int(i[baselen:]), reverse=True)
    # Alternatively, if the filenames can't be trusted, sort based on modification time
    #file_list.sort(key=lambda i: os.stat(i).st_mtime)

    for f in file_list[:files_to_delete]:
        os.remove(f)
    return files_to_delete

rawDescription: Delete oldest files at full disk

description: Delete oldest files at full disk


code:
with open("afterschoolclub.txt","w")     as f:

    f.write(firstname)
    f.write(lastname)
    f.write(gender)
    f.write(form)

with open("afterschoolclub.txt","r")     as f:
    lines = f.readlines()
    print( lines[0])

rawDescription: Basic file handling in python

description: Basic file handling in python


code:
import re

html_file_content = u"asdf 1234 this should contain the source code of a html page that you downloaded"
pattern = u"http://the-url-from-which-you-downloaded-the-html-file.com"
path = u"d:/whatever/path/where/you/downloaded/the/html/file"
new_file_content = re.sub(pattern, path, a)

rawDescription: how to change links of html file to local links

description: Change links of html file to local links


code:
from markupsafe import Markup

@app.template_filter()
def snippet(value):
    for sep in ('<readmore/>', '
', '
', '
'):
        if sep in value:
            break
    else:
        sep = '\n'

    return Markup(value.split(sep, 1)[0])

rawDescription: Create content snippet with Jinja filter


code:
def zrc(n):
    count = 0
    while n%10 == 0 and n != 0:
        n //= 10
        count += 1
    return count

rawDescription: Why does my code return 1 when the given number has more zeroes?


code:
r'Z:\IRF\Data\Primary Care Hospitals\PI\_'\
r'Z:\IRF\Data\Primary Care Hospitals\PI\_'\

rawDescription: python 2.7 line break - directory line to the file

description: Python 2.7 line break - directory line to the file


code:
def todict(obj, classkey=None):
    if isinstance(obj, dict):
        data = {}
        for (k, v) in obj.items():
            data[k] = todict(v, classkey)
        return data
    elif hasattr(obj, "_ast"):
        return todict(obj._ast())
    elif hasattr(obj, "__iter__"):
        return [todict(v, classkey) for v in obj]
    elif hasattr(obj, "__dict__"):
        data = dict([(key, todict(value, classkey))
            for key, value in obj.__dict__.iteritems()
            if not callable(value) and not key.startswith('_')])
        if classkey is not None and hasattr(obj, "__class__"):
            data[classkey] = obj.__class__.__name__
        return data
    else:
        return obj

rawDescription: Recursively convert python object graph to dictionary


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

x = np.random.randn(10)
y = np.random.randn(10)
Cluster = np.array([0, 1, 1, 1, 3, 2, 2, 3, 0, 2])    # Labels of cluster 0 to 3
centers = np.random.randn(4, 2)

fig = plt.figure()
ax = fig.add_subplot(111)
scatter = ax.scatter(x,y,c=Cluster,s=50)
for i,j in centers:
    ax.scatter(i,j,s=50,c='red',marker='+')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.colorbar(scatter)

fig.show()

rawDescription: How to make a scatter plot for clustering in Python

description: Make a scatter plot for clustering in Python


code:
from collections import defaultdict

images = defaultdict(list)

for image, label in randomData:
    images[label].append(image)

for k,v in images.iteritems():
   print('Label {} has {} images'.format(k, len(v)))

rawDescription: How to divide a list of images in Python, based on their labels

description: Divide a list of images in Python, based on their labels


code:
def login(request, username, password):
    # not the actual code, but you get the gist
    logged_in_user = authenticate(username, password)
    request['cur_user'] = logged_in_user.username

description: Django request.session.save() authentication


code:
def subthread1(stop):
    while not stop:
        time.sleep(1)
        print(' 1...')

def main_thread(q):
    stop = [] # list rather than boolean because we need it "by reference"

    t1 = Thread(target=subthread1, args=(stop,))
    t1.daemon = True
    t1.start()

    while True:
        msg = q.get()
        if msg == 0:
            print("EXITING THREAD")
            stop.append(True)
            break

rawDescription: Python: Kill Thread

description: Python: Kill Thread


rawDescription: Python read files in directory and concatenate


rawDescription: DreamPie doesn't load nltk library through import command


code:
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\

Hi!

       How are you?

       Here is the link you wanted.

"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
#...

rawDescription: How to send a EML file as email using python script to list of emails one at a time?

description: Send a EML file as email using python script to list of emails one at a time


code:
# Type:       Cell
# String Form:number:42.0
# File:       c:\python27\lib\site-packages\xlrd\sheet.py
# Source:
class Cell(BaseObject):

    __slots__ = ['ctype', 'value', 'xf_index']

    def __init__(self, ctype, value, xf_index=None):
        self.ctype = ctype
        self.value = value
        self.xf_index = xf_index

    def __repr__(self):
        if self.xf_index is None:
            return "%s:%r" % (ctype_text[self.ctype], self.value)
        else:
            return "%s:%r (XF:%r)" % (ctype_text[self.ctype], self.value, self.xf_index)

rawDescription: xlrd API: get the owner of a lower level object (e.g. get the Sheet object from the Cell object)

description: Xlrd API: get the owner of a lower level object (e.g. get the Sheet object from the Cell object)


code:
from datetime import datetime

tick = datetime.now()

# run the tests here

tock = datetime.now()
diff = tock - tick    # the result is a datetime.timedelta object
print(diff.total_seconds())

rawDescription: Get python unit test duration in seconds


rawDescription: Regular expression to match everything to the end of a string, excluding the last character if it's a slash (/)


code:
TEMPLATE = """
<input id="count" maxlength="100" name="count" type="text"/>
"""
class AnimalTable(tables.Table):
    count = tables.TemplateColumn(TEMPLATE)
    class Meta:
        model = Animal

rawDescription: django-tables2: create a input text box

description: Django-tables2: create a input text box


code:
r=urllib.urlopen("http://google.com")
a=r.read()
type(a)
help(a.decode)
b = a.decode('utf8')
type(b)

rawDescription: Python Response Decoding

description: Python Response Decoding


code:
import whoosh.index as index
ix = index.open_dir("dir/to/index")

rawDescription: Python whoosh to run add_document

description: Python whoosh to run add_document


code:
class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

rawDescription: How does python property class instance work?


code:
sys.stdout.close()
sys.stdout = open("out.txt", "w")

rawDescription: display current process stdout in PySide QTextEdit box

description: Display current process stdout in PySide QTextEdit box


code:
from PyQt4 import Qt,QtGui,QtCore
import base64

# "b64_data" is a variable containing your base64 encoded jpeg

app = QtGui.QApplication([])
w = QtGui.QWidget()
pic = QtGui.QLabel(w)
pm = QtGui.QPixmap()
pm.loadFromData(base64.b64decode(b64_data))
pic.setPixmap(pm)

w.show()
app.exec_()

rawDescription: Displaying an embedded image on PyQt?

description: Displaying an embedded image on PyQt


code: max(list, key=lambda p: smallest_circle.centre.sub(p).norm())

rawDescription: Respected argument for max() function in Python