code:
import time
from random import randint

Player_win_count = 0
PC_win_count = 0
Game_count = 0

while True:
    original = input("Enter 'Rock', 'Paper' or 'Scisors: ")
    word = original.lower()
    no = randint(1,3)

    if word == "rock":
        if no == 1:
            print ("The Computer chose Rock. It's a tie\n")
            Game_count += 1
        if no == 2:
            print ("The Computer chose Paper. You Lose!\n")
            Game_count += 1
            PC_win_count += 1
        if no == 3:
            print ("The Computer chose Scisors. You win!\n")
            Game_count += 1
            Player_win_count += 1
        print ("The games played are: " + str(Game_count) + "\n      The scores are:\n                 You: " + str(Player_win_count) + "\n            Computer: " + str(PC_win_count))

    elif word == "paper":
        if no == 1:
            print ("The Computer chose Rock. You Win\n")
            Player_win_count += 1
            Game_count += 1
        if no == 2:
            print ("The Computer chose Paper. It's a tie!\n")
            Game_count += 1
        if no == 3:
            print ("The Computer chose Scisors. You lose!\n")
            PC_win_count += 1
            Game_count += 1
        print ("The games played are: " + str(Game_count) + "\n      The scores are:\n                 You: " + str(Player_win_count) + "\n            Computer: " + str(PC_win_count))

    elif word == "scisors":
        if no == 1:
            print ("\nThe Computer chose Rock. You Lose!\n")
            PC_win_count += 1
            Game_count += 1
        if no == 2:
            print ("\nThe Computer chose Paper. You Win!\n")
            PC_win_count += 1
            Game_count += 1
        if no == 3:
            print ("\nThe Computer chose Scisors. It's a tie!\n")
            Game_count += 1
        print ("The games played are: " + str(Game_count) + "\n      The scores are:\n                 You: " + str(Player_win_count) + "\n            Computer: " + str(PC_win_count))

    else:
        print ("That is not a valid entry. Please try again")

rawDescription: Python: MyVariable = MyVariable + 1 not stacking?


code:
import cv2
import numpy as np

capture = cv2.VideoCapture(0)
capture1 = cv2.VideoCapture(1)

while True:
    _, frame1 = capture.read()
    _, frame2 = capture1.read()
    frame1 = cv2.cvtColor(frame1,cv2.COLOR_BGR2RGB)
    frame2 = cv2.cvtColor(frame2,cv2.COLOR_BGR2RGB)
    cv2.imshow("frame1",frame1)
    cv2.imshow("frame2",frame2)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
capture1.release()
capture2.release()
cv2.destroyAllWindows()

rawDescription: How do I display multiple webcam feeds side by side using OpenCV Beta 3.0.0 and Python?

description: Display multiple webcam feeds side by side using OpenCV Beta 3.0.0 and Python


code:
from Queue import Queue

class IterableQueue(Queue):

    _sentinel = object()

    def __iter__(self):
        return iter(self.get, self._sentinel)

    def close(self):
        self.put(self._sentinel)

rawDescription: Python iterable Queue

description: Python iterable Queue


rawDescription: truncate and pad using format specification mini language

description: Truncate and pad using format specification mini language


code:
from tkinter import *

root = Tk()

root.wm_title("Your program")

mylist = []

def get_data(l):
    l.append(box1.get())
    print(l)

var1 = StringVar()
var1.set("ID:")
label1 = Label(root,textvariable=var1,height = 2)
label1.grid(row=0,column=0)

ID=StringVar()
box1=Entry(root,bd=4,textvariable=ID)
box1.grid(row=0,column=1)

botonA= Button(root, text = "accept",command=lambda: get_data(mylist), width=5)
botonA.grid(row=0,column=2)

root.mainloop()

rawDescription: storing data from input box in tkinter

description: Storing data from input box in tkinter


code:
s = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'

l = s.split()
l

d = dict((s, l.index(s)+1) for s in set(l))
d
list(map(lambda s: d[s], l))

rawDescription: Individual words in a list then printing the positions of those words


code:
while True:
    try:
        return requests.head(...)
    except requets.exceptions.ConnectionError:
        time.sleep(0.5)

rawDescription: Python - best way to wait until a remote system is booted


code:
for line in handle.readlines():
    line = line.strip()
    os.system("grep \"%s\" %s > %s.%s" % (line, Infile, Infile, line))

rawDescription: Exporting multiple output files using grep in Python


code:
from dateutil.rrule import DAILY, rrule, MO, TU, WE, TH, FR

def daterange(start_date, end_date):
  return rrule(DAILY, dtstart=start_date, until=end_date, byweekday=(MO,TU,WE,TH,FR))

rawDescription: Python date range generator over business days


rawDescription: Matrix (Jagged Array) for in loop initialization


code:
l = [(1, 3), (6, 7)]
s = 'AABBCCDD'
''.join(s[start-1:end] for (start,end) in l)

rawDescription: Iterate through tuple values python

description: Iterate through tuple values python


code:
class Product(models.Model):
    brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.SET_NULL)

rawDescription: Code in signal not being executed

description: Code in signal not being executed


code: "Harry Potter".lower() == "harry potter".lower()

rawDescription: similar function for strcmpi in python

description: Similar function for strcmpi in python


code:
x = 2
y = 3
[i*y + x for i in range(10)]

rawDescription: Array initialization in Python

description: Array initialization in Python


code:
import sys
if sys.version_info.major < 3:
    print("I'm only for 3, please upgrade")
    sys.exit(1)

rawDescription: Distribute/distutils specify Python version


code:
file.name = slugify(myfile.filename)
name, ext = os.path.splitext(file.name)
while os.path.exists(os.path.join(permanent_store, file.name)):
    name += '_'
    file.name = name + ext

raw_file = os.path.join(permanent_store, file.name)

rawDescription: File Uploads with Turbogears 2

description: File Uploads with Turbogears 2


rawDescription: Diagonalize symbolic matrices python

description: Diagonalize symbolic matrices python


code:
opened_llist = open(locallist, "wt")
connection.retrlines("RETR %s" % "list.txt", opened_llist.write)
opened_llist.write(link + " ")
opened_llist.close()
opened_llist_r = open(locallist, "rb")
connection.storbinary("STOR %s" % "list.txt", opened_llist_r, 8192, print)
opened_llist_r.close()

rawDescription: Uploading a text file by either binary or ASCII both leave it blank?


code:
import numpy as np

nbLamps = 200000
nbDays = 365

arr = np.array([nbLamps, nbDays], dtype=np.bool)

rawDescription: Algorithm in Python to store and search daily occurrance for thousands of numbered events?


code:
def main_menu():
    print ("\nMain Menu        ")
    print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
    return input ("\nEnter your Option:  ")

option = main_menu()

rawDescription: Python Variable is not Defined

description: Python Variable is not Defined


code:
regex = re.compile(r'\b\S*\.example\.com')
regex.findall(string)

rawDescription: Python regex to pull FQDN from syslog server


code:
try:
    import urlparse
    from urllib import urlencode
except: # For Python 3
    import urllib.parse as urlparse
    from urllib.parse import urlencode

url = "http://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}

url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
query.update(params)

url_parts[4] = urlencode(query)

print(urlparse.urlunparse(url_parts))

rawDescription: Add params to given URL in Python

description: Add params to given URL in Python


code:
class House:
    def __init__(self):
        self.ID = ""
        self.window_list = []

class Window:
    def __init__(self):
        self.ID = ""

rawDescription: Python: iterating through a list of objects within a list of objects


code:
import time
tm = time.strptime('January 10, 2012', '%B %d, %Y')
time.strftime('%d %B %Y', tm)

rawDescription: python regex match and replace dates

description: Python regex match and replace dates


code:
brian = {'Queen': 8, 'Ace': 3, 'Jack': 5}
chris = {'Queen': 4, 'Ace': 2, 'Jack': 6}

rawDescription: Advice on picking a data structure in Python


code:
from apache.httpd import request_rec
r = request_rec(environ['apache.request_rec'])
r.user = user

rawDescription: WSGI/Django: pass username back to Apache for access log


code:
while True:
    f = open(server ,"a")  #changed so data will be appended rather than wrote to the file
    initchat = str(input("Chat: "))
    chat = str((user + " - " + initchat))
    f.write(chat + "\n")
    f.close

rawDescription: Python: Write to new file line

description: Python: Write to new file line


code: pandas.read_csv('myfile.csv', usecols=["foo", "bar", "baz"])

rawDescription: Select specific column in read_csv by its name


code:
from Tkinter import (
    Button,
    Canvas,
    DISABLED,
    END,
    Entry,
    Frame,
    LEFT,
    NORMAL,
    RIDGE,
    Text,
    Tk,
)

rawDescription: Is there a recommended format for multi-line imports?


code:
from bs4 import BeautifulSoup
data = '宜家同款 世纪宝贝儿童餐椅婴儿餐椅宝宝餐椅婴儿吃饭椅'
soup = BeautifulSoup(data)
soup.text

rawDescription: How to replace html elements in a string by python?

description: Replace html elements in a string by python


code:
import numpy as np
import pandas as pd

# from here: http://stackoverflow.com/a/32921444/3025981, CC BY-SA by Afshin @ SE
def weighted_median(values, weights):
    ''' compute the weighted median of values list. The
weighted median is computed as follows:
    1- sort both lists (values and weights) based on values.
    2- select the 0.5 point from the weights and return the corresponding values as results
    e.g. values = [1, 3, 0] and weights=[0.1, 0.3, 0.6] assuming weights are probabilities.
    sorted values = [0, 1, 3] and corresponding sorted weights = [0.6,     0.1, 0.3] the 0.5 point on
    weight corresponds to the first item which is 0. so the weighted     median is 0.'''

    #convert the weights into probabilities
    sum_weights = sum(weights)
    weights = np.array([(w*1.0)/sum_weights for w in weights])
    #sort values and weights based on values
    values = np.array(values)
    sorted_indices = np.argsort(values)
    values_sorted  = values[sorted_indices]
    weights_sorted = weights[sorted_indices]
    #select the median point
    it = np.nditer(weights_sorted, flags=['f_index'])
    accumulative_probability = 0
    median_index = -1
    while not it.finished:
        accumulative_probability += it[0]
        if accumulative_probability > 0.5:
            median_index = it.index
            return values_sorted[median_index]
        elif accumulative_probability == 0.5:
            median_index = it.index
            it.iternext()
            next_median_index = it.index
            return np.mean(values_sorted[[median_index, next_median_index]])
        it.iternext()

    return values_sorted[median_index]

# end from

def wmed(group):
    return weighted_median(group['score'], group['times'])

import pandas as pd
df = pd.DataFrame([
        ['user1', 1, 4],
        ['user1', 7, 2],
        ['user2', 3, 1],
        ['user2', 10, 2]
        ], columns = ['user', 'score', 'times'])
groups = df.groupby('user')
groups.apply(wmed)

# user
# user1     1
# user2    10
# dtype: int64

rawDescription: Pandas median over grouped by binned data


rawDescription: Best Way to add group totals to a dataframe in Pandas


code:
import matplotlib
matplotlib.rc('text',usetex=True)
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np

text = '\\begin{tabular}{|c|c|}\\hline1&2\\\\\\hline3&4\\\\\\hline\\end{tabular}'

fig, ax = plt.subplots(1)

img = ax.imshow(np.zeros((10,10)), cmap=plt.cm.gray)
txt = ax.text( 4.5,
          4.5,
          text,
          fontsize=24,
          ha='center',
          va='center',
          bbox=dict(alpha=0))

fig.canvas.draw()
bbox = txt.get_bbox_patch()
xmin = bbox.get_window_extent().xmin
xmax = bbox.get_window_extent().xmax
ymin = bbox.get_window_extent().ymin
ymax = bbox.get_window_extent().ymax

xmin, ymin = fig.transFigure.inverted().transform((xmin, ymin))
xmax, ymax = fig.transFigure.inverted().transform((xmax, ymax))

dx = xmax-xmin
dy = ymax-ymin

# The bounding box vals can be tweaked manually here.
rect = Rectangle((xmin-0.02,ymin-0.01), dx+0.04, dy+0.05, fc='w', transform=fig.transFigure)

ax.add_patch(rect)
fig.canvas.draw()
ax.axis('off')
plt.savefig('ok.png',bbox_inches='tight')

rawDescription: Side-specific padding for matplotlib text bbox


code:
search_ext = (
     config.get("Miscellaneous", "media").strip() + '|' +
     config.get("Miscellaneous", "meta").strip() + '|' +
     config.get("Miscellaneous", "other").strip()
).split('|')

rawDescription: .endswith missing file extention in a loop


code:
from bs4 import BeautifulSoup
import requests

response = requests.get('http://vpnbook.com/freevpn')
soup = BeautifulSoup(response.text, 'html.parser')
pricing = soup.find(id = 'pricing')
first_column = pricing.find('div', {'class': 'one-third'})
for li in first_column.find('ul', {'class': 'disc'}):
    if 'password' in str(li).lower():
        password = li.find('strong').text
print(password)

rawDescription: Extract a word that follows a particular word from a webpage with python


code:
from PyQt4 import QtGui, QtCore

class CustomWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(QtGui.QWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)

        self.lineEdit1 = QtGui.QLineEdit(self)
        layout.addWidget(self.lineEdit1)
        self.pushButton = QtGui.QPushButton("line1 -> line2", self)
        self.pushButton.clicked.connect(self.onClick)
        layout.addWidget(self.pushButton)
        self.lineEdit2 = QtGui.QLineEdit(self)
        layout.addWidget(self.lineEdit2)

    def onClick(self):
        self.lineEdit2.setText(self.lineEdit1.text())

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    widget = CustomWidget()
    widget.show()
    sys.exit(app.exec_())

rawDescription: Accessing QT text in lineEdit

description: Accessing QT text in lineEdit


code: [names[0]] + [n for n in names[1:] if n != names[0]]

rawDescription: parsing list in python

description: Parsing list in python


code: NumberRange = np.logspace(np.log10(0.674), np.log10(100.0), num=1000)

rawDescription: Numbers logarithmically spaced between two floats in numpy


code: ssh.exec_command('. .profile ; cd /home/test/;$run ./test.sh')

rawDescription: Python - using env variables of remote host with / SSH


code:
#admin.py

class ModelAdmin(admin.ModelAdmin):
  list_display = ['brand', 'model_name']
  fields = ['model_name', 'brand']

class ModelInline(admin.TabularInline):
    model = Model

class BrandAdmin(admin.ModelAdmin):
    model = Brand
    inlines = [
        ModelInline,
    ]

admin.site.register(Brand, BrandAdmin)
admin.site.register(Model, ModelAdmin)

rawDescription: Django displaying one to many relationship in the admin page


rawDescription: python append to array in json object

description: Python append to array in json object


code:
current_balance = initialOutstandingBalance
for month in range(1,13):
    print("Month: "+ str(month))
    minimumMonthlyPayment = minimumMonthlyPaymentRate * current_balance
    # this calculation is almost certainly wrong, but is preserved from your starting code
    interestPaid = annualInterestRate / (12*current_balance)
    principalPaid = minimumMonthlyPayment - interestPaid
    current_balance = current_balance - principalPaid
    print("Minimum monthly payment: $"+str(minimumMonthlyPayment))
    print("Principle paid: $"+str(principalPaid))
    print("Remaining Balance: $"+str(current_balance))

rawDescription: How do I change a variable in a for loop in python?

description: Change a variable in a for loop in python


code:
f = open(fname,'r+b')
A = str(mmap.mmap(f.fileno(),0)[:]).split()
for i, value in enumerate(A):
    if value == "********":
       A[i] = "0.0"

rawDescription: Faster replacing in list with a lot of matches


code:
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

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

rawDescription: Is it possible to run a Python script as a service in Windows? If possible, how?


code:
x = 2.4
np.sin(x)/x
x_over_pi = x / np.pi
np.sinc(x_over_pi)
np.sinc(0)

rawDescription: Best way to implement numpy.sin(x) / x where x might contain 0

description: Implement numpy.sin(x) / x where x might contain 0


code:
random.shuffle(l)
random_selection = l[ :l.index(10) ]

rawDescription: How to do a random sample without k, up until a certain integer is produced? (Python)

description: Do a random sample without k, up until a certain integer is produced? (Python)


rawDescription: python list concatenation

description: Python list concatenation


code:
import os

parent_folder = 'Order_forms'
for root, dirs, files in os.walk(parent_folder):
    for f in files:
        with open(os.path.join(root, f), 'r') as f1:
            data = f1.readlines()
            mystr = ",".join([line.strip() for line in data])
            with open(os.path.join(root, '{}_CSV.csv'.format(f)), 'w') as f2:
                f2.write(mystr)

rawDescription: Executing the script one time in each folder


code:
a = 'xyz-abc'
a.find('-')  # return the index of the first instance of '-'
a[a.find('-'):]   # return the string of everything past that index

rawDescription: removing part of a string (up to but not including) in python

description: Removing part of a string (up to but not including) in python


code:
a = 1

import uncompyle2
from StringIO import StringIO
f = StringIO()
uncompyle2.uncompyle_file('path/program.pyc', f)
f.seek(0)
exec(f.read(), globals(), locals())

rawDescription: How to execute compiled python code

description: Execute compiled python code


code:
from math import acos
from math import sqrt
from math import pi

def length(v):
    return sqrt(v[0]**2+v[1]**2)
def dot_product(v,w):
   return v[0]*w[0]+v[1]*w[1]
def determinant(v,w):
   return v[0]*w[1]-v[1]*w[0]
def inner_angle(v,w):
   cosx=dot_product(v,w)/(length(v)*length(w))
   rad=acos(cosx) # in radians
   return rad*180/pi # returns degrees
def angle_clockwise(A, B):
    inner=inner_angle(A,B)
    det = determinant(A,B)
    if det<0: #this is a property of the det. If the det < 0 then B is clockwise of A
        return inner
    else: # if the det > 0 then A is immediately clockwise of B
        return 360-inner

rawDescription: Calculate angle (clockwise) between two points


code:
def immutable_meta(name, bases, dct):
    class Meta(type):
        def __init__(cls, name, bases, dct):
            type.__setattr__(cls,"attr",set(dct.keys()))
            type.__init__(cls, name, bases, dct)

        def __setattr__(cls, attr, value):
            if attr not in cls.attr:
                raise AttributeError ("Cannot assign attributes to this class")
            return type.__setattr__(cls, attr, value)
    return Meta(name, bases, dct)

class A:
    __metaclass__ = immutable_meta
    b = "test"

a = A()
a.c = 10 # this works
A.c = 20 # raises valueError

rawDescription: Ways to make a class immutable in Python


code:
import matplotlib.pyplot as plt
import sympy

x = sympy.symbols('x')
y = 1 + sympy.sin(sympy.sqrt(x**2 + 2))
lat = sympy.latex(y)

fig = plt.figure()
renderer = fig.canvas.get_renderer()
t = plt.text(0.001, 0.001, r"$%s$" % lat, fontsize = 50)
wext = t.get_window_extent(renderer=renderer)

fig.set_size_inches(wext.width / 65, wext.height / 40, forward=True)
fig.patch.set_facecolor('white')
plt.axis('off')
plt.tight_layout()
plt.savefig('out.png', bbox_inches='tight', pad_inches=0)
plt.show()

rawDescription: Matplotlib save only text without whitespace


rawDescription: Import custom python script on pycharm

description: Import custom python script on pycharm


code:
import pandas as pd
csvfile = pd.read_csv('path_to_file')
print(csvfile)

rawDescription: How to save CSV file to Python

description: Save CSV file to Python


code:
import MySQLdb
db = mdb.connect(ip, login, pword)
query = "insert into tbname (entity, attribute) VALUES('foo', 'bar')"
cursor = db.cursor()
cursor.execute(query)
db.commit()

rawDescription: Unable to insert data on Google Cloud SQL but UID field is still AUTO incrementing


code:
import subprocess
p = subprocess.Popen(["blender object.blend --background --python blenderObj.py --box.obj object.obj"], stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
out, err = p.communicate()

rawDescription: What tokens to use with Popen for running a blender script?


code:
class Task(models.Model):
    user = models.ForeignKey('auth.User')
    name = models.CharField(max_length=100)
    added_at = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)

class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        exclude = ['user', ]

def task_create(request):
    form = TaskForm(data=request.POST or None)
    if request.method == 'POST' and form.is_valid():
        task = form.save(commit=False)
        task.user = request.user
        task.save()
        return reverse("todo_list")
    return render(request,
        'task_create.html',
        {'form': form}
    )

rawDescription: Django user authentication and rendering content created by that specific user?


code:
from os.path import expanduser
import os.path.join

SaveDirectory = expanduser(os.path.join('Desktop', 'office_docs'))

rawDescription: screen-shots in ubuntu versus windows through python

description: Screen-shots in ubuntu versus windows through python


code:
class Sessioning(Thread):
    def __init__(self, p_number):
         Thread.__init__(self)
         self._pn = p_number

    def run(self):
        print(self._pn)

p_number = 50885
for i in xrange(30):
    Sessioning(p_number).start()
    p_number += 1

rawDescription: Pass variable contents to class function in Python


code:
import json
from pprint import pprint

with open('json_data.json') as json_data:
    data = json.load(json_data)

pprint(data)
# now you can traverse your data dict....
print(data['1']['server'])

rawDescription: Python : Getting values of key from JSON


code:
try:
    ...
except OperationalError:
    connection.close()
    cursor = connection.cursor()

rawDescription: Recover from dead database connection in Django


code:
bin(7)
bin(9)

rawDescription: Convert Bit-field to list in python

description: Convert Bit-field to list in python


code:
class PersonChangeListForm(forms.ModelForm):
    class Meta:
        model = Person
    name = forms.CharField()

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        if instance:
            initial = kwargs.get('initial', {})
            initial['name'] = '%s %s' % (instance.first_name, instance.last_name)
            kwargs['initial'] = initial
        super(PersonChangeListForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        # use whatever parsing you like here
        first_name, last_name = self.cleaned_data['name'].split(None, 1)
        self.cleaned_data['first_name'] = first_name
        self.cleaned_data['last_name'] = last_name
        super(PersonChangeListForm, self).save(*args, **kwargs)

class PersonAdmin(admin.ModelAdmin):
    def get_changelist_form(self, request, **kwargs):
        return PersonChangeListForm

rawDescription: Custom list_editable field in django admin change list, which doesn't correspond directly to a model field


code:
def load_tests(loader, tests, pattern):
    return suite()

rawDescription: PyCharm run select unittests

description: PyCharm run select unittests


code:
from itertools import product
s = "ABCD"
d = {"B": ["X", "Z"], "D": ["E"]}
poss = [[c]+d.get(c,[]) for c in s]
poss
[''.join(p) for p in product(*poss)]

rawDescription: Combinations of a string with specific variable characters


code:
from django.contrib.admin import AdminSite

class MyAdminSite(AdminSite):
    def get_urls():
        ...

...
my_admin_site = MyAdminSite()
...
my_admin_site.register(MyModel, MyModelAdmin)

rawDescription: New URL on django admin independent of the apps


code:
def increment(self, name):
    """Increments a counter specified by the 'name' argument."""
    self.__dict__[name] += 1

rawDescription: How do I increment an attribute at runtime using getattr/setattr?

description: Increment an attribute at runtime using getattr/setattr


code:
tf = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))
df = pd.DataFrame([[1, 2, 3], [1, 2, 4], [3, 4, 5]], columns=list('abc'))
grouped_sum = df.groupby(['a', 'b'], as_index=False).sum()
grouped_sum
tf.merge(grouped_sum)  # this won't always be the same as grouped_sum!

rawDescription: Selecting from multi-level groupby in pandas


code:
import urllib
f = open('list.txt')
for l in f:
    try:
        #for python3.x use: x= urllib.request.urlopen('http://'+l)
        x= urllib.urlopen('http://'+l)
    except:
        print ('not found')
    else:
        print (x.readlines())

rawDescription: Python - How to get http response of site


code:
def Karten():
    from random import choice
    Karten_Zwischenstand = choice(['a','b','c', ... , 'y','z'])
    return Karten_Zwischenstand

foo = Karten()
print(foo)

rawDescription: I guess this is easy for you => defining


code:
with open('numbers.txt') as f:
    f.read(8)  # read up to 8 chars from first line
    f.readline()  # skip to next line

rawDescription: How To Only Read One Part Of A Line In Python


code:
for item in result:
    partial_data = json.loads(item['result'])
    outer_list = []
    for rec in partial_data['results']:
        inner_list = []
        for key, value in rec:
            inner_list.append(...) # values from the dictionary
        outer_list.append(inner_list)

with open("data.csv", "w", newline='') as file:
    csv_file = csv.writer(file, delimiter=',')
    csv_file.writerow(['published_date', 'linkedin_shares', ... , 'display_title']) # Column label names
    csv_file.writerows(outer_list)

rawDescription: json to csv writing nested dict content

description: Json to csv writing nested dict content


code:
user = User.objects.get(name='bob')

worker = Worker(user_ptr=user, role='chief')
worker.__dict__.update(user.__dict__)
worker.save()

rawDescription: Models inheritance in Django

description: Models inheritance in Django


code:
pixels_hls = np.zeros_like(pixels)

for i in range(1000):
    for j in range(1000):
        pixels_hls[i,j,:] = np.array(colorsys.rgb_to_hls(*pixels[i,j,:]))

rawDescription: How to transform all pixels of an RGB image to HLS image in linear time by using colorsys.rgb_to_hls in python?

description: Transform all pixels of an RGB image to HLS image in linear time by using colorsys.rgb_to_hls in python


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

length = np.random.random(10)
length.sort()
time = np.random.random(10)
time.sort()
slope, intercept = np.polyfit(np.log(length), np.log(time), 1)
print(slope)
plt.loglog(length, time, '--')
plt.show()

rawDescription: Python: How to find the slope of a graph drawn using matplotlib?


rawDescription: How to retrieve the values for only one table field in Django

description: Retrieve the values for only one table field in Django


code:
def all_subsets(b):
    if len(b)==1:
        return [[], b]  # if set has 1 element then it has only 2 substets
    else:
       s = all_subsets(b[:-1])  # calculate subsets of set without last element
       # and compose remaining subsets
       return sorted(s + [e + [b[-1]] for e in s], key=len)  # you can omit sorting if you want

rawDescription: How to write all_subsets function using recursion?

description: Write all_subsets function using recursion


code:
import pandas as pd
from bokeh.plotting import figure, output_notebook, show
output_notebook()

years = [2012,2013,2014,2015]
val   = [230,120,200,340]

# Convert your data into a panda DataFrame format
data=pd.DataFrame({'year':years, 'value':val})

# Create a new column (yearDate) equal to the year Column but with a datetime format
data['yearDate']=pd.to_datetime(data['year'],format='%Y')

# Create a line graph with datetime x axis and use datetime column(yearDate) for this axis
p = figure(width=800, height=250, x_axis_type="datetime")
p.line(x=data['yearDate'],y=data['value'])
show(p)

rawDescription: Parse Years in Python 3.4 Pandas and Bokeh from counter dictionary


code:
matrix=[]
for i in xrange(max):
    matrix.append([None]*max)
for x,y,v in inputs:
    matrix[x][y]=v

rawDescription: 3-column to matrix using python scripting


code:
fig = plt.figure(figsize=(11., 8.5))
ax = fig.add_axes([0.05,0.05,0.6,0.6])
bar=lines.Line2D([],[], color="0.1", linewidth=2,ls=":", marker="1")
leg = ax.legend([bar],["foo"],bbox_to_anchor=[1.,1.], loc="upper left")
s=r"$\alpha$"
s+=r"$\alpha_i \beta_j \gamma^k$"

# You need to draw the artists before you can get its coordinates:
plt.draw()

# Now get coordinates of the legend
p = leg.get_window_extent().inverse_transformed(ax.transAxes)

# Set offset of the text in 'axes fraction' units
# (if it is 0 text will be placed within the legend box, set 'zorder=9' as parameter to ax.annotate to see it)
offset = 0.03

# Now place the text on the plot
ax.annotate('Annotation', (p.p0[0], p.p0[1] - offset), xycoords='axes fraction')

plt.show()

rawDescription: How to anchor a text artist to a legend artist?

description: Anchor a text artist to a legend artist


rawDescription: Python2.7/ NLTK remove part of string before certain character


code:
import sys
from PyQt4 import QtGui, QtCore

class BorderItemDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent, borderRole):
        super(BorderItemDelegate, self).__init__(parent)
        self.borderRole = borderRole

    def sizeHint(self, option, index):
        size = super(BorderItemDelegate, self).sizeHint(option, index)
        pen = index.data(self.borderRole).toPyObject()
        if pen is not None:
            # Make some room for the border
            # When width is 0, it is a cosmetic pen which
            # will be 1 pixel anyways, so set it to 1
            width = max(pen.width(), 1)
            size = size + QtCore.QSize(2 * width, 2 * width)
        return size

    def paint(self, painter, option, index):
        pen = index.data(self.borderRole).toPyObject()
        # copy the rect for later...
        rect = QtCore.QRect(option.rect)
        if pen is not None:
            width = max(pen.width(), 1)
            # ...and remove the extra room we added in sizeHint...
            option.rect.adjust(width, width, -width, -width)

        # ...before painting with the base class method...
        super(BorderItemDelegate, self).paint(painter, option, index)

        # ...then paint the borders
        if pen is not None:
            painter.save()
            # The pen is drawn centered on the rectangle lines
            # with pen.width()/2 width on each side of these lines.
            # So, rather than shifting the drawing of pen.width()/2
            # we double the pen width and clip the part that would
            # go outside the rect.
            painter.setClipRect(rect, QtCore.Qt.ReplaceClip);
            pen.setWidth(2 * width)
            painter.setPen(pen)
            painter.drawRect(rect)
            painter.restore()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mainWindow = QtGui.QMainWindow()
    mainWindow.resize(300,300);

    # Define the Qt.ItemDataRole we will be using
    MyBorderRole = QtCore.Qt.UserRole + 1

    # Create and populate the view
    treeWidget = QtGui.QTreeWidget(mainWindow)
    for i in range(3):
        item = QtGui.QTreeWidgetItem(["Item %d"%(i)])
        treeWidget.addTopLevelItem(item)
        treeWidget.expandItem(item);
        for j in range(10):
            subItem = QtGui.QTreeWidgetItem(["SubItem %d %d"%(i,j)])
            pen = QtGui.QPen(QtGui.QColor.fromHsv(j*25, 255, 255))
            pen.setWidth(j)
            # Store the border pen in the item as the role we defined
            subItem.setData(0, MyBorderRole, pen)
            item.addChild(subItem)

    # Pass the role where we stored the border pen to the delegate constructor
    delegate = BorderItemDelegate(treeWidget, MyBorderRole)
    treeWidget.setItemDelegate(delegate)

    mainWindow.setCentralWidget(treeWidget)
    mainWindow.show()

    sys.exit(app.exec_())

rawDescription: Achieving a border for a QTreeWidgetItem in PyQT


code:
np.repeat(s2.index.values, s2.values)
pd.DataFrame(np.repeat(s2.index.values, s2.values), columns=['value'])

rawDescription: pandas - Going from aggregated format to long format

description: Pandas - Going from aggregated format to long format


code:
# orginal data
tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

# empty dictonary for sorting the data
newTable = {0:[], 1:[], 2:[], 3:[]}

# iterate through each list in tableData
for li in tableData:
    for i in range(len(li)):
        # put each item of tableData into newTable by index
        newTable[i].append(li[i])

# determine the longest list by number of total characters
# for instance ['apples', 'Alice', 'dogs'] would be 15 characters
# we will start with longest being zero at the start
longest = 0
# iterate through newTable
# for example the first key:value will be 0:['apples', 'Alice', 'dogs']
# we only really care about the value (the list) in this case
for key, value in newTable.items():
    # determine the total characters in each list
    # so effectively len('applesAlicedogs') for the first list
    length = len(''.join(value))
    # if the length is the longest length so far,
    # make that equal longest
    if length > longest:
        longest = length

# we will loop through the newTable one last time
# printing spaces infront of each list equal to the difference
# between the length of the longest list and length of the current list
# this way it's all nice and tidy to the right
for key, value in newTable.items():
    print(' ' * (longest - len(''.join(value))) + ' '.join(value))

rawDescription: Automate the Boring Stuff Chapter 6 Table Printer Almost Done


rawDescription: How to get result of numpy.logspace() as a column in single line of code?

description: Get result of numpy.logspace() as a column in single line of code


code: from bugland import bug

rawDescription: Can't install new python module [Ubuntu 15.10]


code:
categories = driver.find_elements_by_css_selector("#categories #category_list li[id^=category] a")

result = [{"link": category.get_attribute("href"), "text": category.text}
          for category in categories]
print(result)

rawDescription: Python Selenium save list items as array


code:
import numpy as np

img = np.random.rand(140,100) # my sample image

img_n,img_m = img.shape  # dimensions of image
p_n, p_m = int(np.ceil(np.linalg.norm(img.shape))), 360*2 # dimensions for out array
cc = [img_n/2, img_m/2] # origin for polar coordinates

# Generate sets of indexes of the polar array (do this only once):
X,Y = np.meshgrid(np.arange(img_m), np.arange(img_n))
Z = (X - cc[0]) + 1j*(Y-cc[1]) # create complex array of image coordinates
r,phi = np.abs(Z), np.angle(Z) + np.pi
rc = np.array(np.rint(r), dtype=int) # radial indexes
phic = np.array(np.rint(phi*(p_m-1)/(2*np.pi)), dtype=int) # angular indexes

# Do the the conversion:
out = np.zeros((p_n, p_m))
out[rc, phic] = img  # utilize numpy's index magic

rawDescription: Vectorize an iterative process

description: Vectorize an iterative process


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

plus5 = make_adder(5)
print(plus5(12))  # prints 17

rawDescription: Nested Function in Python

description: Nested Function in Python


code:
# get active source.
sphere1 = GetActiveSource()

# get animation track
sphere1StartThetaTrack = GetAnimationTrack('StartTheta', index=0, proxy=sphere1)

# create keyframes for this animation track

# create a key frame
keyFrame1 = CompositeKeyFrame()

# create a key frame
keyFrame2 = CompositeKeyFrame()
keyFrame2.KeyTime = 1.0
keyFrame2.KeyValues = [360.0]

# initialize the animation track
sphere1StartThetaTrack.KeyFrames = [keyFrame1, keyFrame2]

# get animation scene
animationScene = GetAnimationScene()
animationScene.Play()

rawDescription: How to embed animation into ParaView scene from script?

description: Embed animation into ParaView scene from script


code:
import os
import sys

PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))

rawDescription: How to keep all my django applications in specific folder

description: Keep all my django applications in specific folder


code:
import datetime

figure()
plot((datetime.datetime(1970,1,1), datetime.datetime(2000,1,1)), (0,1))
xlim(datetime.datetime(1980,1,1), datetime.datetime(1990,6,5))

rawDescription: How do I plot with my axis label as time (in hrs, mins etc.)

description: Plot with my axis label as time (in hrs, mins etc.)


code:
import sys, os
# prepend parent directory to path
sys.path = [os.path.join(os.path.dirname(__file__), os.pardir)] + sys.path
import credentials

rawDescription: Handling common files in Python

description: Handling common files in Python


rawDescription: Update 2D numpy array values

description: Update 2D numpy array values


code:
import sys
del sys.argv
sys.path.append("anki")
import anki.Collection

rawDescription: RubyPython imports

description: RubyPython imports


code:
bisect.bisect_right(li, 0.3) - 1
bisect.bisect_right(li, 0.05) - 1
bisect.bisect_right(li, 0.9) - 1

rawDescription: Find index of list entries where value is in between


rawDescription: Efficient Python array with 100 million zeros?


rawDescription: Detect when a keyframe is set on an attribute in Maya?


code:
from collections import defaultdict
import re

# card_list = card_area.splitlines()
card_list = [
    "2 Cardname", "3 Cardname Two", "1 Cardname Three",
    "Cardname", "Cardname Two", "Cardname Three",
    "1x Cardname", "4X Cardname Two", "2 X Cardname Three",
]

card_dict = defaultdict(int)

pat = re.compile(r'(\d*)\s*(?:[xX]\s+)?(\S.*)')

for card in card_list:
    m = re.search(pat, card)
    if not m:
        continue
    if m.group(1):
        qty = int(m.group(1))
    else:
        qty = 1

    name = m.group(2)
    card_dict[name] += qty

if not card_dict:
    print("empty card_dict!")
else:
    for name in sorted(card_dict):
        print("%20s|%4d" % (name, card_dict[name]))

rawDescription: Use groupdict to parse string to dict

description: Use groupdict to parse string to dict


code:
class SDLThread:
    def __init__(self,screen):
        self.m_bKeepGoing = self.m_bRunning = False
        self.screen = screen
        self.color = (255,0,0)
        self.rect = (10,10,100,100)
    def Start(self):
        self.m_bKeepGoing = self.m_bRunning = True
        thread.start_new_thread(self.Run, ())
    def Stop(self):
        self.m_bKeepGoing = False
    def IsRunning(self):
        return self.m_bRunning
    def Run(self):
        while self.m_bKeepGoing:
            pass
##            GetInput()
##            Draw()
        self.m_bRunning = False;
class SDLPanel(wx.Panel):
    def __init__(self,parent,ID,tplSize):
        global pygame
        wx.Panel.__init__(self, parent, ID, size=tplSize)
        self.Fit()
        os.environ['SDL_WINDOWID'] = str(self.GetHandle())
        os.environ['SDL_VIDEODRIVER'] = 'windib'
        import pygame
        pygame.init()
        icon = pygame.Surface((1,1));icon.set_alpha(0);pygame.display.set_icon(icon)
        global Surface
        Surface = pygame.display.set_mode(tplSize)
        self.thread = SDLThread(Surface)
        self.thread.Start()
    def __del__(self):
        self.thread.Stop()

rawDescription: Adding wxpython in pygame

description: Adding wxpython in pygame


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

data = np.array(data)
length = data.shape[0]
width = data.shape[1]
x, y = np.meshgrid(np.arange(length), np.arange(width))

fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(x, y, data)
plt.show()

rawDescription: Plot a 3d surface from a 'list of lists' using matplotlib


code:
if mytuple in set_of_tuples:
    break  # already added

set_of_tuples.add(mytuple)

rawDescription: Python - set vs. list in a special case

description: Python - set vs. list in a special case


code:
import re

text = "your text here. i.e. something."
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)

rawDescription: Python, Accurately splitting sentences

description: Python, Accurately splitting sentences


rawDescription: Elasticsearch bulk index in chunks using PyEs


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')

sheet_names = ['Data1', 'Chart1', 'Data2', 'Chart2', 'Data3', 'Chart3']
for sheet_name in sheet_names:
    workbook.add_worksheet(sheet_name)

# sort sheets based on name
workbook.worksheets_objs.sort(key=lambda x: x.name)
workbook.close()

rawDescription: Possible to alter worksheet order in xlsxwriter?


code:
import pandas as pd

def crawl(url_stack):
    url_stack = list(url_stack)
    result = []
    while url_stack:
        url = url_stack.pop()
        driver.get(url)
        scraped_urls = ...
        url_stack.extend(scraped_urls)

        something_else = "foobar"
        result.append([url, something_else])
    return pd.DataFrame(result, columns=["URL", "Something else"])

df = pd.read_csv(spreadsheet.csv, delimiter=",")
df = crawl(df['URL'][::-1])
df.to_csv("result.csv", delimiter=",")

rawDescription: Pandas: Append rows to DataFrame already running through pandas.DataFrame.apply


code:
def test_memo__function_should_be_called_once_for_same_arg(self):
    @memo
    def f(arg):
        f.call_count += 1
        return arg
    f.call_count = 0

    self.assertEqual(f(1), 1)
    self.assertEqual(f(1), 1)
    self.assertEqual(f.call_count, 1)

    self.assertEqual(f(2), 2)
    self.assertEqual(f(2), 2)
    self.assertEqual(f(2), 2)
    self.assertEqual(f.call_count, 2)

rawDescription: Testing python memo decorator

description: Testing python memo decorator


code:
import shlex
import subprocess

def filter_history(old, new, name, repoPath):
    """Change author info
    """
    # http://help.github.com/change-author-info/
    # http://stackoverflow.com/a/3880493/190597
    command = """git filter-branch -f --env-filter '
        an="$GIT_AUTHOR_NAME"
        am="$GIT_AUTHOR_EMAIL"
        cn="$GIT_COMMITTER_NAME"
        cm="$GIT_COMMITTER_EMAIL"

        if [[ "$GIT_COMMITTER_NAME" = "{old}" ]]
        then
            cn="{name}"
            cm="{new}"
        fi

        if [[ "$GIT_AUTHOR_NAME" = "{old}" ]]
        then
            an="{name}"
            am="{new}"
        fi

        export GIT_AUTHOR_NAME="$an"
        export GIT_AUTHOR_EMAIL="$am"
        export GIT_COMMITTER_NAME="$cn"
        export GIT_COMMITTER_EMAIL="$cm"
      '
      """.format(old = old, new = new, name = name)

    process = subprocess.Popen(
        shlex.split(command),
        cwd = os.path.dirname(repoPath))
    process.communicate()

rawDescription: Print executed command for Python subprocess.Popen


code:
my_cmap = matplotlib.cm.get_cmap('rainbow')
my_cmap.set_under('w')
imshow(np.arange(25).reshape(5, 5),
       interpolation='none',
       cmap=my_cmap,
       vmin=.001)

rawDescription: How to manually change a colormap in python/matplotlib

description: Manually change a colormap in python/matplotlib


code:
from flask import render_template_string

source_html = u'''

{% for x in the_best %}

        {{x.service}}
        {{x.ip}}
        {{x.router}}
        {{x.detail}}
        {{x.time}}

{% endfor %}

'''

filename = "/var/www/flask-intro/templates/Test.html"

# provide a fake request context for the template
with app.test_request_context('/'), open(filename, "w") as outfh:
    full_html = render_template_string(
        source_html, the_best=the_best, the_time=the_time)
    outfh.write(full_html)

rawDescription: Flask Webpage Via Cron Job - url_for call broken


code:
word
word[0].upper() + word[1:]

rawDescription: Capitalize the first letter in a string?

description: Capitalize the first letter in a string


rawDescription: How to change __builtins__ module variable?

description: Change __builtins__ module variable


code:
import collections
result = collections.OrderedDict()
for d in my_list:
    result.setdefault(d["id"], []).extend(d["val"])
lst = []
for k, v in result.items():
    lst.append({"id": k, "val": v})

rawDescription: merge list of dictionaries which have list init

description: Merge list of dictionaries which have list init


code:
def print_map():
    print('\n\n ___' + '___' * 18 + '__ ')
    for row in range(10):
        print('|     ' * 10 + '|')
        for column in range(10):
            print('|  {}  '.format(tile_contents(row, column)), end='')
        print('|')
        print('|_____' * 10 + '|')
    print('\n\n')

def tile_contents(row,column):
    # Put here all conditionals based on row, column positions of player, monsters
    # Return the character to be displayed in the middle of the cell

    return "X"

print_map()

rawDescription: Printing a Visual Map of RPG Game

description: Printing a Visual Map of RPG Game


code: open('a_mod.py','w').write(''.join(l for l in open("a.py") if l.rstrip()))

rawDescription: Removing Empty Line in a file without Removing Indentation Python


code:
from collections import defaultdict
colours = defaultdict(int)
for item in mylist:
   colours[item["colour"]] +=1

rawDescription: Counting the number of dictionaries of a certain type


code:
valid_utf8 = True
try:
    filename.decode('utf-8')
except UnicodeDecodeError:
    valid_utf8 = False

rawDescription: Check for valid utf8 string in Python

description: Check for valid utf8 string in Python


rawDescription: Interleave rows of two numpy arrays in Python


code:
from your_models import Employee, Manatee

from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

class EmployeeAdminView(ModelView):

  # this is called when a model is created
  def create_model(self, form):
    person = Employee() # create new Employee
    form.populate_obj(person)  # use WTForms to populate the model

    # create a new manatee for this new employee
    # everybody needs a manatee for business purposes
    # this assumes there's a sqlalchemy relationship() between the two models

    manatee = Manatee()
    manatee.name = "Janet"

    person.manatee = manatee

    self.session.add(person)
    self.session.commit()

    # at this point person.id should be available, so you can use that here
    # to make any other queries you need to

    return True

admin = Admin(app)
admin.add_view(EmployeeAdminView(Employee, db.session))

rawDescription: Flask-Admin: Inserting data in two tables at once


code: y.append(opt.fmin(f, y[i], args=(R,)))

rawDescription: How can i use a function with "variable" constants in scipy.optimize?

description: Use a function with "variable" constants in scipy.optimize


code:
x
numpy.transpose(x)

rawDescription: Changing shape of numpy array read from a text file


code:
import csv

file1=open('Source.csv','r')
readfile=csv.reader(file1,delimiter=';')
file2=open('Output.csv','w',newline='')
writefile=csv.writer(file2,delimiter=';')
result=()
for row in readfile:
  if (row[2]>condition1 and 'string' in row[6]):
    result=[str(row[2])+'- '+str(row[6])]
    print(result)#line just to see to info from the output file
    writefile.writerow(result)

file1.close()
file2.close()

rawDescription: Concatenate two column in python

description: Concatenate two column in python


code:
def do_something(*args, **kwargs):
    if args:
        customer_id = args[0]
    elif 'customer' in kwargs:
        customer_id = kwargs['customer']
    elif 'customer_id' in kwargs:
        customer_id = kwargs['customer_id']
    else:
        raise TypeError('Expected customer_id')

rawDescription: switch argument name through deprecation cycle?

description: Switch argument name through deprecation cycle


code: start_date = end_date - datetime.timedelta(days=14)

rawDescription: How to filter an object based on a datetime range in python (Django)

description: Filter an object based on a datetime range in python (Django)


code:
# Take a lowercase copy for comparisons
s = sections[i].lower()
if (('economic' in s or 'economy' in s) and
    ('uncertainty' in s or 'uncertain' in s) and
    ('tax' in s or 'policy' in s)):
    do_stuff()

rawDescription: Boolean search text file in Python

description: Boolean search text file in Python


code:
class PlotWidget(FigureCanvas):

    def __init__(self):
        self.__resizing_needed = True

    def draw(self):
        if self.__resizing_needed:
            self.__resizing_needed = False
            try:
                self.figure.tight_layout()
            except ValueError:
                # Set the minimumSize of this widget to prevent this
                print('Plot too small.')

        super(PlotWidget, self).draw()

    def resizeEvent(self, event):
        self.__resizing_needed = True
        super(PlotWidget, self).resizeEvent(event)

rawDescription: Issue with "dynamic" padding in matplotlib


code:
class RPCThreading(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer):
    pass

rawDescription: Python XMLRPC with concurrent requests

description: Python XMLRPC with concurrent requests


code: logger= logging.getLogger( __name__ )

rawDescription: How can I access the current executing module or class name in Python?

description: Access the current executing module or class name in Python


code:
data = {}
index = 123
data[index] = {}
data[index]["color"] = ["red", "green", "blue"]
data[index]["mass"]  = [100, 98, 90]
data[index]["speed"] = [10, 11, 9]
data[index]["metadata"] = {"event_type": "2015-12-11T1442Z"}

rawDescription: What would be a good Python data structure that can store lists of data that all have a common index and some minor metadata?


rawDescription: Group by hour in SQLAlchemy?

description: Group by hour in SQLAlchemy


code:
data = ["Apple", "Gooseberry", "Orange", "Grape"]
data[0]
data[1]
data[2]
data[3]
data.remove("Gooseberry")
data
data[0]
data[1]
data[2]

rawDescription: A better way to rename keys of a dictionary after deletion of an item?


code:
myFakeFile = StringIO.StringIO()
wtr = csv.DictWriter( myFakeFile, headings )
...
myFakeFile.getvalue()

rawDescription: Convert array to CSV/TSV-formated string in Python


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

def main():
    data = [[u'Simeon Miller ✪', 42], [u'Roger Rabbit', 4711]]
    with open('test.csv', 'wb') as csv_file:
        writer = csv.writer(csv_file)
        for name, number in data:
            writer.writerow([name.encode('utf-8'), str(number)])

if __name__ == '__main__':
    main()

rawDescription: How to write symbol in csv file?

description: Write symbol in csv file


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

#Provide other axis
def get_othercoords(x,y,current,other):

    display_coord = current.transData.transform((x,y))
    inv = other.transData.inverted()
    ax_coord = inv.transform(display_coord)
    return ax_coord

#Plot the data
fig, ax1 = plt.subplots()
t = np.linspace(0,2*np.pi,100)
ax1.plot(t, np.sin(t),'b-')
ax1.set_xlabel('(time)')
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
ax2.plot(t,3.*np.cos(t),'r-')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')

#Get user input
out = plt.ginput(2)

#2nd axis from input
x2b, x2t = out[0][0], out[1][0]
y2b, y2t = out[0][1], out[1][1]

#Draw line
ax2.plot([x2b, x2t],[y2b, y2t],'k-',lw=3)

#1st axis from transform
x1b, y1b = get_othercoords(x2b,y2b,ax2,ax1)
x1t, y1t = get_othercoords(x2t,y2t,ax2,ax1)
plt.title("Distance x1 = " + str(x1t-x1b) + " y1 = " + str(y1t-y1b) + "\n"
          "Distance x2 = " + str(x2t-x2b) + " y2 = " + str(y2t-y2b))
plt.draw()
plt.show()

rawDescription: Python Matplotlib Twinx() cursor values

description: Python Matplotlib Twinx() cursor values


code:
from shapely.geometry import Polygon, Point
from rtree import index

# List of non-overlapping polygons
polygons = [
    Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]),
    Polygon([(0, 0), (1, 0), (1, 1), (0, 0)]),
]

# Populate R-tree index with bounds of polygons
idx = index.Index()
for pos, poly in enumerate(polygons):
    idx.insert(pos, poly.bounds)

# Query a point to see which polygon it is in
# using first Rtree index, then Shapely geometry's within
point = Point(0.5, 0.2)
poly_idx = [i for i in idx.intersection((point.coords[0]))
            if point.within(polygons[i])]
for num, idx in enumerate(poly_idx, 1):
    print("%d:%d:%s" % (num, idx, polygons[idx]))

rawDescription: Optimal way of aggregating geographic points with Python/Shapely


code:
from SimpleCV import *
crops = ((0,0,320,240),(320,0,320,240),(0,240,320,240),(320,240,320,240))
cam=VirtualCamera('vd.mpg','video')
while True:
    imgs=[]
    img=cam.getImage()
    for crop in crops:
        imgs.append(img.crop(crop[0],crop[1],crop[2],crop[3]))
    row1=imgs[0].sideBySide(imgs[1])
    row2=imgs[2].sideBySide(imgs[3])
    outputimg=row1.sideBySide(row2, 'top')
    outputimg.show()

rawDescription: How to show multiple windows simultaneously in simpleCV after cropping image in four segments

description: Show multiple windows simultaneously in simpleCV after cropping image in four segments


code:
class Obj1(Base):
    __tablename__ = 'obj1'
    id = Column(Integer, primary_key=True)
    key = Column(String(20))

    _value_rel = relationship("Obj2", uselist=False, backref="obj1")

    @property
    def value(self):
        return self._value_rel and self._value_rel.value

    @value.setter
    def value(self, value):
        if value is None:
            self._value_rel = None
        elif self._value_rel is None:
            self._value_rel = Obj2(value=value)
        else:
            self._value_rel.value = value

rawDescription: SQLAlchemy Linear One-to-One Relationship


code: open("logfile.txt", "a")

rawDescription: Python - writing in a file from an infinity loop


code:
import wx
import wx.aui

########################################################################
class TabPanel(wx.Panel):
    """
    This will be the first notebook tab
    """
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """"""

        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        sizer = wx.BoxSizer(wx.VERTICAL)
        txtOne = wx.TextCtrl(self, wx.ID_ANY, "")
        txtTwo = wx.TextCtrl(self, wx.ID_ANY, "")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(txtOne, 0, wx.ALL, 5)
        sizer.Add(txtTwo, 0, wx.ALL, 5)

        self.SetSizer(sizer)

class DemoPanel(wx.Panel):
    """
    This will be the first notebook tab
    """
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """"""
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        # create the AuiNotebook instance
        nb = wx.aui.AuiNotebook(self)

        # add some pages to the notebook
        pages = [(TabPanel(nb), "Tab 1"),
                 (TabPanel(nb), "Tab 2"),
                 (TabPanel(nb), "Tab 3")]
        for page, label in pages:
            nb.AddPage(page, label)

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

########################################################################
class DemoFrame(wx.Frame):
    """
    Frame that holds all other widgets
    """

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "AUI-Notebook Tutorial",
                          size=(600,400))
        panel = DemoPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = DemoFrame()
    app.MainLoop()

rawDescription: Is it possible to dock wx.auiManager panes onto tops/bottoms of another panes?


code:
for i in Rental.objects.filter(inventory__film_id=2).order_by("inventory_id"):
    amnt=Payment.objects.filter(rental_id= int(i.rental_id))
    print ("Rental of %s is %s") %(i, amnt[0].amount)

rawDescription: Remove model name in loop | Django ORM

description: Remove model name in loop | Django ORM


rawDescription: Counting categorical data pandas group by dataframe


code:
# Start all the processes.
processes = []
for i in range(100):
    p = subprocess.Popen(['convert', '-background', 'black', '-fill', 'white', '-font', 'arial', '-size', '50x50', '-encoding', 'utf8', '-gravity', 'center', 'caption:"just stole your focus"', 'C:/testFile.png'])
    processes.append(p)

# Wait for all the processes to finish.
for p in processes:
    p.wait()

rawDescription: How to run imagemagick in the background from python

description: Run imagemagick in the background from python


code:
import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://hosted.where2getit.com/raymondjames/ajax?&xml_request=%3Crequest%3E%3Cappkey%3E7BD67064-FC36-11E0-B80D-3AEEDDB2B31E%3C%2Fappkey%3E%3Cformdata+id%3D%22locatorsearch%22%3E%3Cdataview%3Estore_default%3C%2Fdataview%3E%3Climit%3E30%3C%2Flimit%3E%3Cgeolocs%3E%3Cgeoloc%3E%3Caddressline%3E90210%3C%2Faddressline%3E%3Clongitude%3E%3C%2Flongitude%3E%3Clatitude%3E%3C%2Flatitude%3E%3Ccountry%3E%3C%2Fcountry%3E%3C%2Fgeoloc%3E%3C%2Fgeolocs%3E%3Csearchradius%3E25%7C50%7C100%3C%2Fsearchradius%3E%3C%2Fformdata%3E%3C%2Frequest%3E'), 'lxml')
# parse the points of interest into a list
pois = soup.find_all('poi')
# now have your way with them!

rawDescription: How do I scrape information from a frame using Python and Beautiful Soup

description: Scrape information from a frame using Python and Beautiful Soup


code:
def add_method_call(func, method_name):
    def replacement(self, *args, **kw):
        getattr(self, method_name)()
        return func(self, *args, **kw)
    return replacement

def change_all_attrs(cls, added_method):
    for method_name in dir(cls):
        attr = getattr(cls, method_name)
        if callable(attr):
            setattr(cls, method_name, add_method_call(attr, added_method))

class animals(object):
    ...

change_all_attrs(animals, '_internalMethod')

rawDescription: How to make every Class Method call a specified method before execution?

description: Make every Class Method call a specified method before execution


code: foo_parser = subparsers.add_parser('foo', aliases=['f'])

rawDescription: Make Python's argparse accept single-character abbreviations for subparsers?


code:
from Tkinter import *
from PIL import Image, ImageTk

root=Tk()

root.title("My Image")

w = Canvas(root, width=50, height=250)
image = Image.open("blog0.bmp")
w.create_image((25, 125), image=ImageTk.PhotoImage(image))

w.pack()

root.mainloop()

rawDescription: How to load .bmp file into BitmapImage class Tkinter python

description: Load .bmp file into BitmapImage class Tkinter python


code:
VK_CODE = {
    'backspace':0x08
}

def press(*args):
    '''
    press, release
    eg press('x', 'y', 'z')
    '''
    for i in args:
        win32api.keybd_event(VK_CODE[i], 0, 0, 0)
        time.sleep(0.2)
        win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)

press('backspace')

rawDescription: Python 3.3 Send Keys to Visual Boy Advance


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

bins = np.arange(-512, 512)
x = 2000.*bins/1024
plt.plot(x, fft_data)

rawDescription: Shifting x-values of a list plotted in Matplotlib


code:
from Tkinter import *
from os import system as cmd

root = Tk()
termf = Frame(root, height=700, width=1000)
termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()

f=Frame(root)
Label(f,text="/dev/pts/").pack(side=LEFT)
tty_index = Entry(f, width=3)
tty_index.insert(0, "1")
tty_index.pack(side=LEFT)
Label(f,text="Command:").pack(side=LEFT)
e = Entry(f)
e.insert(0, "ls -l")
e.pack(side=LEFT,fill=X,expand=1)

def send_entry_to_terminal(*args):
    """*args needed since callback may be called from no arg (button)
   or one arg (entry)
   """
    command=e.get()
    tty="/dev/pts/%s" % tty_index.get()
    cmd("%s <%s >%s 2> %s" % (command,tty,tty,tty))

e.bind("<Return>",send_entry_to_terminal)
b = Button(f,text="Send", command=send_entry_to_terminal)
b.pack(side=LEFT)
f.pack(fill=X, expand=1)

cmd('xterm -into %d -geometry 160x50 -sb -e "tty; sh" &' % wid)

root.mainloop()

rawDescription: Giving a command in a embedded terminal

description: Giving a command in a embedded terminal


rawDescription: Add ticks for days on Pandas plot

description: Add ticks for days on Pandas plot


code: api.update_status('My status update @whoIReplyTo',tweetId)

rawDescription: Reply to Tweet with Tweepy - Python

description: Reply to Tweet with Tweepy - Python


rawDescription: Using python logging with WatchedFileHandler


code:
def get_line(x1, y1, x2, y2):
    points = []
    issteep = abs(y2-y1) > abs(x2-x1)
    if issteep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2
    rev = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        rev = True
    deltax = x2 - x1
    deltay = abs(y2-y1)
    error = int(deltax / 2)
    y = y1
    ystep = None
    if y1 < y2:
        ystep = 1
    else:
        ystep = -1
    for x in range(x1, x2 + 1):
        if issteep:
            points.append((y, x))
        else:
            points.append((x, y))
        error -= deltay
        if error < 0:
            y += ystep
            error += deltax
    # Reverse the list if the coordinates were reversed
    if rev:
        points.reverse()
    return points

rawDescription: Get all points of a straight line in python


code: difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()

rawDescription: Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines?


code:
import StringIO

pa.read_csv(StringIO.StringIO(lines.join('\n')))

rawDescription: Load data from a list of lines using pandas


code:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
import datetime

#set up sqlalchemy
engine = create_engine('postgresql://<username>:<password>@localhost/flask_database')
Base = declarative_base()
metadata = Base.metadata
metadata.bind = engine
Session = sessionmaker(bind=engine, autoflush=True)
session = Session()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    api_owner_id = Column(Integer, ForeignKey('api.id'))
    email = Column(String(120), unique=True)
    username = Column(String(120), unique=True)
    first_name = Column(String(120))
    last_name = Column(String(120))
    business_name = Column(String(120))
    account_type = Column(String(60))
    mobile_phone = Column(String(120))
    street = Column(String(120))
    street2 = Column(String(120))
    city = Column(String(120))
    state = Column(String(120))
    zip_code = Column(String(120))
    country = Column(String(120))
    creation_date = Column(DateTime, default=datetime.datetime.now())
    password = Column(String(120))
    #github stuffs
    github_link = Column(Boolean, default=False)
    github_usn = Column(String(120))
    github_oauth_token = Column(String(160))
    #balanced stuffs
    balanced_account_uri = Column(String(120))
    ach_verified = Column(Boolean, default=False)
    active = Column(Boolean, default=True)
    profile_updated = Column(Boolean, default=False)
    account_balance = Column(Numeric(precision=10, scale=2), default=0.00)
    admin = Column(Boolean, default=False)
    devapp = relationship('DevApp', backref="user", lazy="dynamic")
    projects = relationship('Project', backref="user", lazy="dynamic")
    proposals = relationship('Proposal', backref="user", lazy="dynamic")
    transactions = relationship('Monies', backref="user", lazy="dynamic")

    def __repr__(self):
        return self.email

rawDescription: using flask-sqlalchemy without the subclassed declarative base

description: Using flask-sqlalchemy without the subclassed declarative base


code:
def zcalc(equ):
        equ = filter(equ)
        pos = equ.find('|')
        while pos != -1:
                parallel_seq = []
                temp_pos = pos
                while True:     #gather all scopes to the left into list
                        lpos = leftscope(equ, temp_pos)
                        parallel_seq.insert(0, equ[lpos:temp_pos])
                        if (lpos == 0): break
                        elif (equ[lpos-1] != "|"): break
                        temp_pos = lpos-1
                temp_pos = pos
                while True:     #gather all scope to the right into list
                        rpos = rightscope(equ, temp_pos)
                        parallel_seq.append(equ[temp_pos+1:rpos+1])
                        if (rpos == len(equ)-1) or (equ[rpos+1] != "|"): break
                        temp_pos = rpos+1
                new_equ = "parallel(["
                for i in parallel_seq:      #create string for paralleled function
                        new_equ = new_equ + i + ","
                equ = equ[0:lpos] + new_equ[:len(new_equ)-1] + "])" + equ[rpos+1:]      #replace parallelized part of string with parallel string
                pos = equ.find("|")
        #return equ
        return eval(equ)

rawDescription: Eval Inside Of Funtion Results In Error, While Outside It Does Not


code:
from random import sample
A = csr_matrix(...)
n = A.shape[0]
indices = sample(range(n), 4*n/5)
A[indices].todense()

rawDescription: How to get a row from coo_matrix as a dense vector in Python?

description: Get a row from coo_matrix as a dense vector in Python


code:
def cancelbutton(self, message):

    pub.unsubscribe(self.savebutton, "mainpanel.SaveButton")
    pub.unsubscribe(self.cancelbutton, "mainpanel.CancelButton")
    self.Close()

def savebutton(self, message):

    results = []

    for lbl in self.databoxes:
        results.append(self.box.GetValue())

    pub.sendMessage(self.pubsubmessage, results)
    pub.unsubscribe(self.savebutton, "mainpanel.SaveButton")
    pub.unsubscribe(self.cancelbutton, "mainpanel.CancelButton")
    self.Close()

rawDescription: Why do my Dialog Box Classes write to each other?


rawDescription: Select an array from a multidimensional array


code:
lst = pots[0]

# solution using a for loop
for i, member in enumerate(lst):
    # i is the position in the list
    # member is the data item from the list
    assert lst[i] == member  # cannot ever fail
    if member == the_one_we_want:
        break  # exit loop, variables i and member are set
else:
    # the_one_we_want was never found
    i = -1  # signal that we never found it

# solution using .index() method function on a list
try:
    i = lst.index(the_one_we_want)
except ValueError:
    # the_one_we_want was not found in lst
    i = -1  # signal that we never found it

rawDescription: Get Value from list using foreach

description: Get Value from list using foreach


code:
x2=linspace(x[0],x[-1],1000)[0:X]
my_curve2=np.interp(x2,x,my_curve)
plt.plot(x2, my_curve2)

rawDescription: Multiple plots on python

description: Multiple plots on python


code:
flags = 0

if multiline:
  flags = re.M

if dotall:
  flags |= re.S

if verbose:
  flags |= re.X

if ignorecase:
  flags |= re.I

if uni_code:
  flags |= re.U

regex = re.compile(r'Test Pattern', flags)

rawDescription: Passing in flags as an argument to re.compile


code:
def call_coro_from_thread(f, *args, **kwargs):
    q = queue.Queue()
    def wrapper():
        fut = f(*args, **kwargs)
        fut.add_done_callback(q.put)
    IOLoop.instance().add_callback(wrapper)
    fut = q.get()
    return fut.result()

rawDescription: In a no-coroutine function, how do you get a return value from coroutine function of Tornado TCP?


code:
def __init__(self,nodeData, left = None, right = None, parent = None):
 self.nodeData = nodeData
 self.left = left
 self.right = right
 self.parent = self

rawDescription: Binary Search Tree - storing reference to parent node


code:
def newSplitter(s, n=16):
    for i in xrange(0, len(s), n):
        yield l[i:i+n]

rawDescription: Efficiency : String Slice Vs Custom Function


code: axvspan(xmin, xmax, hatch='/')

rawDescription: Striped highlighted region using matplitlib/python


code:
for crime in no:
    if  int(crime.getAttribute("id")) == x:
        crimeid = crime.getAttribute("id")
        crimetype = crime.getAttribute("type")
        ...

rawDescription: DOM XML Python, Retrieve specific data

description: DOM XML Python, Retrieve specific data


code:
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the
# categories: [60-70], [71-80], [81,90], [91-]
import os.path

def main():

    endofprogram = False
    try:
        InputFileName = input('Enter name of input file: ')
        infile = open(InputFileName,'r')
        OutputFileName = input('Enter name of output file: ')
        # determine wether name exists
        while True:
            if os.path.isfile(OutputFileName):
                OutputFileName = input('File Exists. Enter name again: ')
            else:
                outfile = open(OutputFileName,'w')
                break
    except IOError:
        print("Error opening file - End of program")
        endofprogram = True

        #If there is not exception, start reading the input file
        #Write the same data in formated form in new file.
    if endofprogram == False:
        cat_60 = []
        cat_71 = []
        cat_81 = []
        cat_91 = []
        for line in infile:
            city, rain = line.split(' ')
            rain = float(rain)

            if 60 <= rain < 70:
                cat_60.append((city, rain)) # Storing a tuple in the list
            elif 70 <= rain < 80:
                cat_71.append((city, rain))
            elif 80 <= rain < 90:
                cat_81.append((city, rain))
            elif 90 <= rain :
                cat_91.append((city, rain))

        outfile.write("[60-70]"+'\n')
        for i in range(len(cat_60)):
            city = cat_60[i][0]
            rain = cat_60[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[70-80]"+'\n')
        for i in range(len(cat_71)):
            city = cat_71[i][0]
            rain = cat_71[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[80-90]"+'\n')
        for i in range(len(cat_81)):
            city = cat_81[i][0]
            rain = cat_81[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[91-]"+'\n')
        for i in range(len(cat_91)):
            city = cat_91[i][0]
            rain = cat_91[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
main()

rawDescription: How format my data in category in python


code:
csv.DictReader
import csv

groups = dict(a=headers_for_list_a, b=headers_for_list_b)
lists = dict((name, []) for name in groups)

for row in csv.DictReader(csvfile, fieldnames=headers):
    for name, grp_headers in groups.items():
        lists[name].append(dict((header, row[header]) for header in grp_headers))

rawDescription: Most elegant way to break CSV columns into separate data structures using Python?


code:
class UserAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = User
        fields = ('name', 'answers')

rawDescription: Django Rest Framework - Get full related objects in list


code:
class YourRequestHandler(webapp2.RequestHandler):
    def post(self):
        body = self.request.body

rawDescription: What is python equivalent of php file_get_contents("php://input")


code:
import numpy as np

# get numpy.arrays in case t and A are not yet numpy.arrays
t = np.array(t)
A = np.array(A)

# find the indices of the timestamps you look for
idx = (t>0) & (t <= 240)

# get the standard deviation and the mean
# A[idx] consists of all those elements in A for which idx is true
np.std(A[idx])
np.mean(A[idx])

rawDescription: Mean and St Dev of indexed elements from a separate array


code:
class EmailSerializer(serializers.ModelSerializer):
    user_info = serializers.RelatedField(source='usermodel', read_only=True)

    class Meta:
        model = EmailAddress
        fields = ('id', 'email', 'user_info')

rawDescription: django-allauth - RESTful API return all email address belonging to a user

description: Django-allauth - RESTful API return all email address belonging to a user


code:
domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']

masterList = zip([domesticated, pets, wildlife],  ['off', 'on', 'on'])

def currentLists():
    activeList = []
    for e in masterList:
        if e[1] == 'on':
            activeList += e[0]

    return activeList

rawDescription: Any way to extract a variable name from a string value?


rawDescription: Does Python for .NET event handler execute in a worker thread


code:
import paramiko
import socket

with open('<filename>', 'rU') as f:

    for node in f.readlines():
        try:
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            print('Connecting to %s.' % node)
            ssh.connect(node.strip(), username=user,password=passw)
            print('Connected to %s.' % node)
            stdin, stdout, stderr = ssh.exec_command(cmd)
            ssh.close()

        except socket.gaierror:
            print('Unable to connect to %s.' % node)
            pass

rawDescription: Unable to connect using hostname read from a file in paramiko


code:
class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

rawDescription: Python style question: Support class as inner class?


code:
import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

rawDescription: How to start a background process in Python?

description: Start a background process in Python


code:
byte = 'a'
'{0:08b}'.format(ord(byte))

rawDescription: How to read a file byte by byte in Python and how to print a bytelist as a binary?

description: Read a file byte by byte in Python and how to print a bytelist as a binary


code:
while True:
    try:
        entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
    except ValueError:
        print("Sorry, an acceptable input was not entered. Try again.")
        continue
    else: # no exception
        if entered > 100:
            print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
            continue
        elif entered <= 0:
            print("Sorry, a percent cannot be negative. Try again.")
            continue
        else:
            #the percent entered is valid, break out of while loop
            break

rawDescription: While loop runs continuously in Python, good input or bad?


code:
class UserView(ModelView):

    column_list = ('first_name', 'last_name', 'username', 'email')
    searchable_columns = ('username', 'email')
# this is to exclude the password field from list_view:
    excluded_list_columns = ['password']
    can_create = True
    can_delete = False
# If you want to make them not editable in form view: use this piece:
    form_widget_args = {
        'name': {
            'readonly': True
        },
    }

rawDescription: How to make a field non-editable in Flask Admin view of a model class

description: Make a field non-editable in Flask Admin view of a model class


code:
m = __import__ (S)
try:
    attrlist = m.__all__
except AttributeError:
    attrlist = dir (m)
for attr in attrlist:
    globals()[attr] = getattr (m, attr)

rawDescription: How does one do the equivalent of "import * from module" with Python's __import__ function?

description: Do the equivalent of "import * from module" with Python's __import__ function


code:
def Problem4():
    y = 909
    a = []
    b = []
    x1 = []
    y1 = []
    while y < 1000:
        x = 100
        while x < 1000:
            z = x*y
            if str(z) == str(z)[::-1]:
                a.append(z)
                x1.append(x)
                y1.append(y)
            else:
                b.append(z)
            x = x + 1
        y = y + 1
    print(a)
    print(x1)
    print(y1)
Problem4()

rawDescription: How to find the largest palindrome made of two three digit numbers in python?

description: Find the largest palindrome made of two three digit numbers in python


code:
def process_list(mylist):
    return [(-3 if x % 15 == 0 else (-2 if x % 5 == 0 else ( -1 if x % 3 == 0 else x))) for x in mylist if isinstance(x, int)]

rawDescription: Algorithm similar to 'Fizzbuzz'

description: Algorithm similar to 'Fizzbuzz'


rawDescription: How to add a string to list inside other list on python 2.7

description: Add a string to list inside other list on python 2.7


code: items[:] = [x for (y, x) in sorted(zip(test_rank, items), key=lambda s: s[0])]

rawDescription: Sorting a list in python in place

description: Sorting a list in python in place


code:
def detectit(response):
   # try headers &c, then, worst case...:
   content = response.read()
   response.read = lambda: content
   # now detect based on content

rawDescription: Is it possible to peek at the data in a urllib2 response?


code:
ListA = [2,1,0]
ListB = [4,5,6]

# make a copy -- I'm assuming you don't want to modify ListA in the process.
new_list = ListA[:]
# insert ListB at a particular location.  I've arbitrarily chosen `1`
# basically this says to take the empty section of the list
# starting just before index 1 and ending just before index 1 and replace it
# with the contents of ListB
new_list[1:1] = ListB
# Check the output to make sure it worked.
print(new_list)  # [2, 4, 5, 6, 1, 0]

rawDescription: Merging List after particular element

description: Merging List after particular element


code:
from pprint import pprint
dct_a = {(x[0].lower(), x[2]): x for x in a}
dct_b = {(x[0].lower(), x[2]): x for x in b}
out = [(dct_a.get(k), dct_b.get(k)) for k in set(dct_a).union(dct_b)]
pprint(out)

rawDescription: Python - Merging 2 lists of tuples by checking their values


code:
import json

v = [1, 2, 4]
s = json.dumps(v)

rawDescription: Serizalize an array in Python

description: Serizalize an array in Python


code:
def dict_replace(dictionary, text, strip_chars=None, replace_func=None):
    """
        Replace word or word phrase in text with keyword in dictionary.

        Arguments:
            dictionary: dict with key:value, key should be in lower case
            text: string to replace
            strip_chars: string contain character to be strip out of each word
            replace_func: function if exist will transform final replacement.
                          Must have 2 params as key and value

        Return:
            string

        Example:
            my_dict = {
                "hello": "hallo",
                "hallo": "hello",    # Only one pass, don't worry
                "smart tv": "http://google.com?q=smart+tv"
            }
            dict_replace(my_dict, "hello google smart tv",
                         replace_func=lambda k,v: '[%s](%s)'%(k,v))
    """

    # First break word phrase in dictionary into single word
    dictionary = dictionary.copy()
    for key in dictionary.keys():
        if ' ' in key:
            key_parts = key.split()
            for part in key_parts:
                # Mark single word with False
                if part not in dictionary:
                    dictionary[part] = False

    # Break text into words and compare one by one
    result = []
    words = text.split()
    words.append('')
    last_match = ''     # Last keyword (lower) match
    original = ''       # Last match in original
    for word in words:
        key_word = word.lower().strip(strip_chars) if \
                   strip_chars is not None else word.lower()
        if key_word in dictionary:
            last_match = last_match + ' ' + key_word if \
                         last_match != '' else key_word
            original = original + ' ' + word if \
                       original != '' else word
        else:
            if last_match != '':
                # If match whole word
                if last_match in dictionary and dictionary[last_match] != False:
                    if replace_func is not None:
                        result.append(replace_func(original, dictionary[last_match]))
                    else:
                        result.append(dictionary[last_match])
                else:
                    # Only match partial of keyword
                    match_parts = last_match.split(' ')
                    match_original = original.split(' ')
                    for i in xrange(0, len(match_parts)):
                        if match_parts[i] in dictionary and \
                           dictionary[match_parts[i]] != False:
                            if replace_func is not None:
                                result.append(replace_func(match_original[i], dictionary[match_parts[i]]))
                            else:
                                result.append(dictionary[match_parts[i]])
            result.append(word)
            last_match = ''
            original = ''

    return ' '.join(result)

rawDescription: Python dictionary replacement with space in key


code:
"""
Usage: calcstats (--analyses <STAT>,...) ... <file> ...

Options:
    <file>                    One or more input filenames
    -a,--analyses <STAT> ...  One or more stat names to compute

"""

import docopt
import time

_Sequence = 0
_Results = {}

def compute_stat(name):
    global _Sequence, _Results

    print("Performing analysis: {}".format(name))
    time.sleep(1)
    _Sequence += 1
    _Results[name] = _Sequence

def display_results(groups):
    global _Results

    groupnum = 1
    for grp in groups:
        print("*** Group {}:".format(groupnum))
        for stat in grp:
            print("\t{}: {}".format(stat, _Results[stat]))
        print("\n")

def parse_args():
    args = docopt.docopt(__doc__)
    args['--analyses'] = [stat.split(',') for stat in args['--analyses']]

    stat_set = set()
    stat_set.update(*args['--analyses'])
    args['STATS.unique'] = stat_set

    return args

def perform_analyses(stat_set):
    for stat in stat_set:
        compute_stat(stat)

if __name__ == '__main__':
    args = parse_args()
    perform_analyses(args['STATS.unique'])
    display_results(args['--analyses'])

rawDescription: Self-inlining python code. (Now with MCVE!)


code: matched = [x for x in dict.keys if len(set(x[:6])) == 1]

rawDescription: Comparing tuples using regex? Python

description: Comparing tuples using regex? Python


rawDescription: Python p value from t-statistic giving nan


code:
stackOfImages = np.array((image1, image2)) #iterate over these if many more
redData = stackOfImages[:, N-1, M-1]

rawDescription: How to extract vector from 3d numpy array?

description: Extract vector from 3d numpy array


rawDescription: Vertical line not respecting min,max limits (matplotlib)


code:
def default(obj):
    if isinstance(obj, np.array):
        return obj.tolist()
    raise TypeError('Not serializable')

with open('data.txt','w') as fl:
    json.dump(data, fl, default=default)

rawDescription: Convert numpy arrays in a nested dictionary into list whilst preserving dictionary structure


code:
from lxml.html import html5parser
from html5lib import HTMLParser

root = html5parser.parse('http://example.com',
                         parser=HTMLParser(namespaceHTMLElements=False))
print(root.tag)  # prints "html"

rawDescription: How to remove namespace value from inside lxml.html.html5paser element tag

description: Remove namespace value from inside lxml.html.html5paser element tag


code:
from dateutil.parser import *
parse("Thu Sep 25 10:36:28 2003")

rawDescription: Convert date formats to another with Python


rawDescription: How to build a neural network with pybrain?

description: Build a neural network with pybrain


code:
import csv
import itertools

with open('errors','w') as err: pass
with open('data','r') as f:
    for key, group in itertools.groupby(
            csv.reader(f),
            lambda row: row[0].startswith('1234567890')):
        if key: continue  # key is True means we've reach the end of an array
        group=list(group) # group is an iterator; we turn it into a list
        array=group[1:]   # everything but the first row is data
        arr_length=int(group[0][0]) # first row contains the length
        if arr_length != len(array): # sanity check
            with open('errors','a') as err:
                err.write('''\
Data file claims arr_length = {l}
{a}
{h}
'''.format(l=arr_length,a=str(list(array)),h='-'*80))
        print(array)

rawDescription: Using CSV arrays as an input to Python

description: Using CSV arrays as an input to Python


code:
class Video(models.Model):
    environment = models.ForeignKey(Environment)

rawDescription: One-To-Many and Many-To-One relatioships in Django


code:
r = range(*sorted((4, -1)))
q = range(*sorted((-1, 4)))

rawDescription: Return if a number is between two values [Python]


rawDescription: Determining largest variable in python

description: Determining largest variable in python


code:
def fn(*args):
    fn2(['foo', 'bar'] + list(args))

rawDescription: Append a tuple to a list

description: Append a tuple to a list


code:
class ActivitySerializer(serializers.ModelSerializer):

    # Create a custom method field
    current_user = serializers.SerializerMethodField('_user')

    # Use this method for the custom field
    def _user(self, obj):
        user = self.context['request'].user
        return user

    class Meta:
        model = Activity
        # Add our custom method to the fields of the serializer
        fields = ('id','current_user')

rawDescription: Get current user in Model Serializer

description: Get current user in Model Serializer


code:
def read_file(name):
    rows = open(name, 'r').readlines()
    data = []
    for r in rows:
        data.append(r.split())
    return data

def invert(data):
    new_data = []
    max_col = 0
    for r in data:
        if len(r) > max_col:
            max_col = len(r)
    col_no = max_col
    for i in range(col_no):
        cal = []
        for j in range(len(data)):
            if i in range(len(data[j])):
                cal.append(data[j][i])
            else:
                cal.append('   ')
        new_data.append(cal)
    return new_data

def merge(data_list):
    big_data = []
    for d in data_list:
        for c in d:
            big_data.append(c)
    return big_data

def write_result(result):
    result_file = open('result', 'w')
    for r in result:
        for e in r:
            result_file.write(e + ' ')
        result_file.write('\n')

data1 = read_file('file1')
data2 = read_file('file2')
data3 = read_file('file3')
new_data1 = invert(data1)
new_data2 = invert(data2)
new_data3 = invert(data3)
big_data = merge([new_data1, new_data2, new_data3])
result = invert(big_data)
write_result(result)

rawDescription: how to merge data present in text files without changing the format using python?

description: Merge data present in text files without changing the format using python


code:
i = w.create_line(xy, fill="red")

w.coords(i, new_xy) # change coordinates
w.itemconfig(i, fill="blue") # change color

rawDescription: Can you change the attributes of a Python Canvas object after creation?

description: Change the attributes of a Python Canvas object after creation


code:
class Attribute(object):
    @declared_attr # the actual syntax on SQLAlchemy for doing mixins
    def a(cls):
       return Column(Integer)

class BaseThing(Base):
    pass

class Thing(BaseThing, Attribute):
    b = Column(Integer)

class Subthing(BaseThing):
    c = Column(Integer)

rawDescription: Mixin being added to every child class table when using joined table inheritance


code:
#to load the xml
from lxml import etree
doc=etree.parse("the path to your xml file")

#to find the Characters tab
doc.find("Characters").text

rawDescription: Can't parse tag from XML using Python

description: Can't parse tag from XML using Python


code:
import numpy as np
arr = np.zeros(size)
arr[indexes] = values
arr

rawDescription: Generate sparse vector

description: Generate sparse vector


code:
class str:
    def __init__(self, characters):
        self.chars = characters

    def join(self, iterable):
        newString = str()

        for item in iterable:
            newString += item #item is assumed to be a string, and += is defined elsewhere
            newString += self.chars

        newString = newString[-len(self.chars):] #remove the last instance of self.chars

        return newString

rawDescription: How are these two functions the same?

description: How are these two functions the same


code:
def Paranoid():
    _secret_dict = {'_secret': 0}
    class ParanoidClass(object):
            def set(self, val):
                    _secret_dict['_secret'] = val * 10
            def get(self):
                    return _secret_dict['_secret'] / 10
    return ParanoidClass()

p = Paranoid()
p.set(123)
p.get()

rawDescription: Preventing access to "private" attribute in Python


code:
import wx

########################################################################
class LoginDialog(wx.Dialog):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Dialog.__init__(self, None, title="Login")

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        userLbl = wx.StaticText(self, label="Username:")
        userTxt = wx.TextCtrl(self)
        self.addWidgets(userLbl, userTxt)

        passLbl = wx.StaticText(self, label="Password:")
        passTxt = wx.TextCtrl(self, style=wx.TE_PASSWORD)
        self.addWidgets(passLbl, passTxt)

        okBtn = wx.Button(self, wx.ID_OK)
        btnSizer.Add(okBtn, 0, wx.CENTER|wx.ALL, 5)
        cancelBtn = wx.Button(self, wx.ID_CANCEL)
        btnSizer.Add(cancelBtn, 0, wx.CENTER|wx.ALL, 5)

        self.mainSizer.Add(btnSizer, 0, wx.CENTER)
        self.SetSizer(self.mainSizer)

    #----------------------------------------------------------------------
    def addWidgets(self, lbl, txt):
        """
        """
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(txt, 1, wx.EXPAND|wx.ALL, 5)
        self.mainSizer.Add(sizer, 0, wx.EXPAND)

if __name__ == "__main__":
    app = wx.App(False)
    dlg = LoginDialog()
    dlg.ShowModal()
    dlg.Destroy()
    app.MainLoop()

rawDescription: wxPython Password, TextCtrol(TE_PASSWORD) isn't allowing ID_OK

description: WxPython Password, TextCtrol(TE_PASSWORD) isn't allowing ID_OK


code:
s = set(big_list)
sum(1 for x in re.finditer(r'\b\w+\b',sentence) if x.group() in s)

rawDescription: Sets vs. Regex for string lookup, which is more scalable?


code:
abcd = "{{complaint}} abcd efc'k , star {{ovservation}} agagag"
[i.strip() for i in re.split(r'\{\{.*?\}\}', abcd) if i]
[i.strip() for i in re.split(r'(\{\{.*?\}\})', abcd) if i]

rawDescription: How to split HTML text node consisting AngularJS tag in Python

description: Split HTML text node consisting AngularJS tag in Python


code:
df2 = df.set_index(['StudentID', 'QuestionID', 'DateRecorded'])
df2
df2.unstack('QuestionID')

rawDescription: ReshapeError while trying to pivot pandas dataframe


code:
class Request:
    def __init__ (self, method):
        self.method = method

def another_decorator (f):
    print ("another")
    return f

def decorator_for_post (f):
    def g (request, *args, **kwargs):
        if request.method == "POST":
            return another_decorator (f) (request, *args, **kwargs)
        return f (request, *args, **kwargs)
    return g

@decorator_for_post
def x (request):
    print ("doing x")

print ("GET")
x (Request ("GET") )
print ("POST")
x (Request ("POST") )

rawDescription: use a decorator for a POST request only in python

description: Use a decorator for a POST request only in python


code:
def randomize(text):
    start= text.find('{')
    if start==-1: #if there are no curly braces, there's nothing to randomize
        return text

    # parse the choices we have
    end= start
    word_start= start+1
    nesting_level= 0
    choices= [] # list of |-separated values
    while True:
        end+= 1
        try:
            char= text[end]
        except IndexError:
            break # if there's no matching closing brace, we'll pretend there is.
        if char=='{':
            nesting_level+= 1
        elif char=='}':
            if nesting_level==0: # matching closing brace found - stop parsing.
                break
            nesting_level-= 1
        elif char=='|' and nesting_level==0:
            # put all text up to this pipe into the list
            choices.append(text[word_start:end])
            word_start= end+1
    # there's no pipe character after the last choice, so we have to add it to the list now
    choices.append(text[word_start:end])
    # recursively call this function on each choice
    choices= [randomize(t) for t in choices]
    # return the text up to the opening brace, a randomly chosen string, and
    # don't forget to randomize the text after the closing brace
    return text[:start] + random.choice(choices) + randomize(text[end+1:])

rawDescription: python randomizer - get random text between curly braces with double nesting level

description: Python randomizer - get random text between curly braces with double nesting level


code:
while True:
    original = input(...)
    PygLatin = True
    while PygLatin:
        if len(original) > 0 and original.isalpha():
            ...
        else:
            print('Error: Not a string!')
    ui = input("Try again? (y/n): ").lower()
    if ui not in ("y", "yes"):
        break

rawDescription: Loops - Will not start over, just spams out a string


code:
td = datetime.timedelta(minutes=5, microseconds=100)
pd.offsets.Micro(td.total_seconds() * 10 ** 6)

rawDescription: Define a pandas.tseries.index.DatetimeIndex using 2 datetimes (dt_start and dt_stop) and a timedelta


code:
import wx

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.frame = parent

        test_btn = wx.Button(self, label='Test Button')
        test_btn.Bind(wx.EVT_MOTION, self.updateStatusBar)

        test_btn_2 = wx.Button(self, label='Test Button')
        test_btn_2.Bind(wx.EVT_MOTION, self.updateStatusBar)

        self.buttons = {test_btn: 'Test help string',
                        test_btn_2: 'Another string'}

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(test_btn, 0, wx.ALL, 5)
        main_sizer.Add(test_btn_2, 0, wx.ALL, 5)
        self.SetSizer(main_sizer)

    #----------------------------------------------------------------------
    def updateStatusBar(self, event):
        """"""
        btn = event.GetEventObject()
        if btn in self.buttons:
            status = self.buttons[btn]
            self.frame.sb.SetStatusText(status)

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Test Help Strings')
        panel = MyPanel(self)
        self.sb = self.CreateStatusBar()
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: wxPython - Setting a help string for a button in toolbar

description: WxPython - Setting a help string for a button in toolbar


code:
def someview(request):
    # ... etc ...
    out = HttpResponse(outputstring,
        mimetype="text/html",
        status_code="302",
        )
    out['Content-Disposition'] = "attachment; filename=download.html"
    # fill in all your favorite HTTP headers here
    return out

rawDescription: Python replacement for PHP's header

description: Python replacement for PHP's header


code:
from Tkinter import *
import ttk

import time
import threading

def foo():
    time.sleep(5) # simulate some work

def start_foo_thread(event):
    global foo_thread
    foo_thread = threading.Thread(target=foo)
    foo_thread.daemon = True
    progressbar.start()
    foo_thread.start()
    root.after(20, check_foo_thread)

def check_foo_thread():
    if foo_thread.is_alive():
        root.after(20, check_foo_thread)
    else:
        progressbar.stop()

root = Tk()
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
progressbar = ttk.Progressbar(mainframe, mode='indeterminate')
progressbar.grid(column=1, row=100, sticky=W)

ttk.Button(mainframe, text="Check",
           command=lambda:start_foo_thread(None)).grid(column=1, row=200,
                                                       sticky=E)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)
root.bind('<Return>', start_foo_thread)

root.mainloop()

rawDescription: Why ttk Progressbar appears after process in Tkinter