code:
import wx

class MyCheckBox(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, 'Checking Options', size=(470, 400))
        panel = wx.Panel(self, -1)

        self.cb_list = []
        for pos in [(120,75), (200,75), (278,75), (356,75), (120,105), (200,105), (278,105), (356,105)]:
            cb = wx.CheckBox(panel, -1, '', pos)
            cb.SetValue(False)
            self.cb_list.append(cb)

        wx.StaticText(panel, -1, "Send output to File", (70, 255))
        self.cb = wx.CheckBox(panel, -1, '', (50, 255))
        self.cb.SetValue(True)

        wx.EVT_CHECKBOX(self, self.cb.GetId(), self.ShowTitle)

        self.btnSelect = wx.Button(panel, label="Select All", pos=(45, 295))
        self.Bind(wx.EVT_BUTTON, self.OnSelectAll, id = self.btnSelect.GetId())

        self.btnUnSelectAll = wx.Button(panel, label="Unselect All*", pos=(173, 295))
        self.Bind(wx.EVT_BUTTON, self.OnUnSelectAll, id = self.btnUnSelectAll.GetId())

        self.btnApply = wx.Button(panel, label="Apply/Close", pos=(305, 295))
        self.Bind(wx.EVT_BUTTON, self.OnApply, id = self.btnApply.GetId())

        wx.StaticText(panel, -1, "* Note: 'Unselect All' button will not unselect storms that" '\n'
                  "   have already determined", (20, 350))

        self.Show()
        self.Centre()

    def ShowTitle(self, event):
        if self.cb.GetValue():
            self.SetTitle('checkbox.py')
        else: self.SetTitle('')

    def OnSelectAll(self, event):
        for cb in self.cb_list:
            cb.SetValue(True)

    def OnUnSelectAll(self, event):
        for cb in self.cb_list:
            cb.SetValue(False)

    def OnApply(self, event):
        selection = self.cb.GetValue()
        for i, cb in enumerate(self.cb_list):
            if cb.GetValue():
                print('{} selected'.format(i))

app = wx.App(0)
MyCheckBox(None, -1, 'checkbox.py')
app.MainLoop()

rawDescription: How to return selected check boxes using wxPython?

description: Return selected check boxes using wxPython


code:
dirs = '\\users\\username\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\'
cop_dir = '\\users\\Desktop\\'

for r,d,f in os.walk(dirs):
    if 'places.sqlite' in f:
        shutil.copy2(os.path.join(r, 'places.sqlite'), cop_dir)
        break

rawDescription: Python: Copying a file with shutil

description: Python: Copying a file with shutil


rawDescription: Python: How to determine the specific Linux distribution being used?


code:
import re
s = "Some.File.Num10.example.txt"
p = re.compile("Num\d{2}")
match = p.search(s)
s[:match.start()]

rawDescription: String splitting in Python using regex

description: String splitting in Python using regex


code:
import re
line = '4.20    AENC    [#sec4.20 Audio encryption]'
full_match = re.search(r'^\S+\s+(\S+)\s+\[#\S+ (.*?)\]', line)
dict_key = full_match.group(1)   # 'AENC'
id3v2_tag = full_match.group(2)  # 'Audio encryption'

rawDescription: Grab two parts of a single, short string


code:
def getCoord(self):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.imshow(self.img)
    cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)
    plt.show()
    return self.point

rawDescription: Python: how to get coordinates on mouse click using matplotlib.canvas


code:
import os
import glob
import pandas as pd
import matplotlib.pyplot as plt

# file mask
fmask = r'./data/????/AS*.??'

# all RegEx replacements
replacements = {
  r'T': 0
}

# list of data files
flist = glob.glob(fmask)

def read_data(flist, date_col='date', **kwargs):
    dfs = []
    for f in flist:
        # parse year from the file name
        y = os.path.basename(f).replace('.', '')[-4:]
        df = pd.read_table(f, **kwargs)
        # replace day of year with a date
        df[date_col] = pd.to_datetime(y + df[date_col].astype(str).str.zfill(3), format='%Y%j')
        dfs.append(df)
    return pd.concat(dfs, ignore_index=True)

df = read_data(flist,
               date_col='date',
               sep=r'\s+',
               header=None,
               names=['date','prec'],
               engine='python',
               skipfooter=1,
              ) \
     .replace(replacements, regex=True) \
     .set_index('date') \
     .apply(pd.to_numeric, args=('coerce',))

df.plot()

plt.show()

rawDescription: How to read multiple files from different folder in python

description: Read multiple files from different folder in python


code:
for line in open(logfile, 'r'):
  (timestr, gamestr) = line.split(' - ')
  hour = time.strptime(timestr, time_format).tm_hour
  n_games = parse_game_count(gamestr)
  entry_counts[hour] += 1
  game_counts[hour] += n_games
for hour in range(25): # you can in theory get hour=24!
  busyness_by_hour[hour] = game_counts[hour] / entry_counts[hour]

rawDescription: Parsing a log file to find most active times


code:
tokens = ['LastName', 'Color']
dictResult = {}
with open(fileName,'r') as fileHandle:
   for line in fileHandle:
      lineParts = line.split(" ")
      if len(lineParts) == 2 and lineParts[0] in tokens:
           dictResult[lineParts[0]] = lineParts[1]

rawDescription: Python extract values from text using keys


code:
def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
        if array[i] <= array[begin]:
            pivot += 1
            array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    return pivot

def quicksort(array, begin=0, end=None):
    if end is None:
        end = len(array) - 1
    if begin >= end:
        return
    pivot = partition(array, begin, end)
    quicksort(array, begin, pivot-1)
    quicksort(array, pivot+1, end)

array = [6,4,2,1,7,8,5,3]
quicksort(array)
print (array)

rawDescription: Python- Quicksort program in-place

description: Python- Quicksort program in-place


code:
class FancyView(object):
    def __init__(self, array, index):
        self._array = array
        self._index = index.copy()
    def __array__(self):
        return self._array[self._index]
    def __getitem__(self, index):
        return self._array[self._index[index]]

b = FancyView(a, p)

rawDescription: Generating a remapped numpy array as a view.


code:
from tkinter import *
import tkinter.ttk as ttk

root = Tk()                         # Main window
myColor = '#40E0D0'                 # Its a light blue color
root.configure(bg=myColor)          # Setting color of main window to myColor

s = ttk.Style()                     # Creating style element
s.configure('Wild.TRadiobutton',    # First argument is the name of style. Needs to end with: .TRadiobutton
        background=myColor,         # Setting background to our specified color above
        foreground='black')         # You can define colors like this also

rb1 = ttk.Radiobutton(text = "works :)", style = 'Wild.TRadiobutton')       # Linking style with the button

rb1.pack()                          # Placing Radiobutton

root.mainloop()                     # Beginning loop

rawDescription: Changing the background color of a radio button with tkinter in Python 3


code:
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    ...
    zip = models.CharField(max_length=12, blank=True, null=True)
    city_state = models.CharField(max_length=30, blank=True, null=True)
    lat = models.DecimalField(max_digits=12, decimal_places=9, blank=True, null=True)
    lng = models.DecimalField(max_digits=12, decimal_places=9, blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.zip:
            (city_state, lat, lng) = get_lat_lng(self.zip)
            if city_state and lat and lng:
                self.city_state = city_state
                self.lat = lat
                self.lng = lng

        super(UserProfile, self).save(*args, **kwargs)

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('zip',)

rawDescription: Django: Populating data into a model based on an identifier


code:
[ values['daily_process'] for items in parsed_response
                              for values in items.values() ]

rawDescription: Forming List Comprehension For Dictionary Inside a List of Dictionaries


code:
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
G = nx.dodecahedral_graph()
pos = nx.spring_layout(G)
ax = plt.gca()
for u,v in G.edges():
    x = [pos[u][0],pos[v][0]]
    y = [pos[u][1],pos[v][1]]
    l = Line2D(x,y,linewidth=8,solid_capstyle='round')
    ax.add_line(l)
ax.autoscale()
plt.show()

rawDescription: networkx draw_networkx_edges capstyle

description: Networkx draw_networkx_edges capstyle


code:
d = {'temp': x, 'dens': y}
df = pd.DataFrame(data=d)

x1 = pd.DataFrame({'temp': np.linspace(df.temp.min(), df.temp.max(), 200)})

poly_2 = smf.ols(formula='dens ~ 1 + temp + I(temp ** 2.0)', data=df).fit()
plt.plot(x, y, 'o', alpha=0.2)
plt.plot(x1.temp, poly_2.predict(x1), 'r-',
         label='2nd order poly fit, $R^2$=%.2f' % poly_2.rsquared,
         alpha=0.9)
plt.xlim((-10, 50))
plt.ylim((0, 0.25))
plt.xlabel('mean air temp')
plt.ylabel('density')
plt.legend(loc="upper left")

# with quantile regression

# Least Absolute Deviation
# The LAD model is a special case of quantile regression where q=0.5

mod = smf.quantreg('dens ~ temp + I(temp ** 2.0)', df)
res = mod.fit(q=.5)
print(res.summary())

# Quantile regression for 5 quantiles

quantiles = [.05, .25, .50, .75, .95]

# get all result instances in a list
res_all = [mod.fit(q=q) for q in quantiles]

res_ols = smf.ols('dens ~ temp + I(temp ** 2.0)', df).fit()

plt.figure()

# create x for prediction
x_p = np.linspace(df.temp.min(), df.temp.max(), 50)
df_p = pd.DataFrame({'temp': x_p})

for qm, res in zip(quantiles, res_all):
    # get prediction for the model and plot
    # here we use a dict which works the same way as the df in ols
    plt.plot(x_p, res.predict({'temp': x_p}), linestyle='--', lw=1,
             color='k', label='q=%.2F' % qm, zorder=2)

y_ols_predicted = res_ols.predict(df_p)
plt.plot(x_p, y_ols_predicted, color='red', zorder=1)
#plt.scatter(df.temp, df.dens, alpha=.2)
plt.plot(df.temp, df.dens, 'o', alpha=.2, zorder=0)
plt.xlim((-10, 50))
plt.ylim((0, 0.25))
#plt.legend(loc="upper center")
plt.xlabel('mean air temp')
plt.ylabel('density')
plt.title('')
plt.show()

rawDescription: Using StatsModels to plot quantile regression for 2nd order polynomial


code:
if msg.is_multipart():
    for part in msg.get_payload():
          """ Process message, but do not recurse """
          filename = part.get_filename()

rawDescription: How do I skip processing the attachments of an email which is an attachment of a different email

description: Skip processing the attachments of an email which is an attachment of a different email


code:
def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    """
    if not thread.isAlive():
        return

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

rawDescription: How to structure code to be able to launch tasks that can kill/replace each other

description: Structure code to be able to launch tasks that can kill/replace each other


code:
from operator import attrgetter
a, b, c = attrgetter('a', 'b', 'c')(foo())

rawDescription: Assign results of function call in one line in python


code:
import wx
import cv, cv2

class ShowCapture(wx.Panel):
    def __init__(self, parent, capture, fps=15):
        wx.Panel.__init__(self, parent)

        self.capture = capture
        ret, frame = self.capture.read()

        height, width = frame.shape[:2]
        parent.SetSize((width, height))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        self.bmp = wx.BitmapFromBuffer(width, height, frame)

        self.timer = wx.Timer(self)
        self.timer.Start(1000./fps)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_TIMER, self.NextFrame)

    def OnPaint(self, evt):
        dc = wx.BufferedPaintDC(self)
        dc.DrawBitmap(self.bmp, 0, 0)

    def NextFrame(self, event):
        ret, frame = self.capture.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.bmp.CopyFromBuffer(frame)
            self.Refresh()

capture = cv2.VideoCapture(0)
capture.set(cv.CV_CAP_PROP_FRAME_WIDTH, 320)
capture.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 240)

app = wx.App()
frame = wx.Frame(None)
cap = ShowCapture(frame, capture)
frame.Show()
app.MainLoop()

rawDescription: Opencv integration with wxpython

description: Opencv integration with wxpython


code: z = a if switch == 1 else (b if switch == 2 else c)

rawDescription: using else in inline conditional python

description: Using else in inline conditional python


code: (df.src + df.dest).isin(df.dest + df.src)

rawDescription: Compare two columns in pandas DataFrame against the inverse


rawDescription: Replace only one instance of a duplicate in a string. Python


code:
for prev, curr, next in neighborhood(list):
    if (prev == desired_value):
        print(prev+" "+next)
        desired_value = __builtins__.next(value_iterator)

rawDescription: Scope of next() in Python

description: Scope of next() in Python


code: df['salary'] = series.reindex(df.index, level=0)

rawDescription: How to broadcast on a single index in hierarchically indexed DataFrame?

description: Broadcast on a single index in hierarchically indexed DataFrame


code:
a = numpy.arange(10000, dtype=numpy.double)
p = a[100:].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
p.contents
a[100] = 55
p.contents

rawDescription: ctypes pointer into the middle of a numpy array

description: Ctypes pointer into the middle of a numpy array


code:
import numpy as np
import numpy.ma as ma
a = np.arange(24).reshape((6,4))
mask=~(np.abs(a - a.mean(axis=1)[:,np.newaxis]) < a.std(axis=1)[:,np.newaxis])
mask
ma.array(a,mask=mask).mean(axis=1).data

rawDescription: Computing trimmed mean along an axis

description: Computing trimmed mean along an axis


rawDescription: Slicing multiple rows by single index

description: Slicing multiple rows by single index


code:
from lxml import etree

xmlfile = etree.parse('xmlfile.xml')
identifier_nodes = xmlfile.xpath("//*[local-name() = 'identifier']")

rawDescription: Accessing Elements with and without namespaces using lxml


code: follows = models.ManyToManyField('self', related_name='follows', symmetrical=False)

rawDescription: How to implement followers/following in Django

description: Implement followers/following in Django


code:
import numpy as np
N=2
np.zeros((N,)*1)
np.zeros((N,)*2)
np.zeros((N,)*3)

rawDescription: Create Multidimensional Zeros Python

description: Create Multidimensional Zeros Python


code:
p = psutil.Process(os.getpid())
# blocking
p.get_cpu_percent(interval=1)
# non-blocking (percentage since last call)
p.get_cpu_percent(interval=0)

rawDescription: How to use psutil.get_cpu_percent()?

description: Use psutil.get_cpu_percent()


code:
p1 = Popen(["openssl", "verify", "-CApath", capath, "-crl_check_all"],
           stdin = PIPE, stdout = PIPE, stderr = PIPE)

message, error = p1.communicate(certificate)

verified = ("OK" in message and not "error" in message)

rawDescription: How can I verify an X509 certificate in python including a CRL check?

description: Verify an X509 certificate in python including a CRL check


code:
import lxml.etree
root=lxml.etree.fromstring("""<xml>
<node></node>
<text number="2">Text number 2</text>
<text number="3">Text number 3</text>
...
<text number="N">Text number N</text>
...
<node></node>
</xml>""")
elements=root.xpath('//text[@number="2"]')
elements
help(elements[0])

rawDescription: lxml (xml python parser) go to next element

description: Lxml (xml python parser) go to next element


code:
import re
with open('myfile.txt', 'r') as file:
    content = file.read()
with open('myfile.txt', 'w') as file:
    file.write(re.sub(r'\d+[\dO]+|[\dO]+\d+', lambda m: m.group().replace('O', '0'), content))

rawDescription: How to replace a character in some specific word in a text file using python

description: Replace a character in some specific word in a text file using python


code:
from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

rawDescription: Python Matplotlib Y-Axis Labels on Right Side of Plot


rawDescription: Elementwise multiplication ignoring certain rows of a matrix


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

x = 10 ** np.arange(1, 10)
y = 10 ** np.arange(1, 10) * 2

df1 = pd.DataFrame(data=y, index=x)

df1.plot(loglog=True, legend=False)

plt.show()

rawDescription: Log-Log plot of pandas dataframe

description: Log-Log plot of pandas dataframe


code:
import logging

class LoggingHandler(logging.Handler):
    def emit(self, record):
        assert isinstance(record, logging.LogRecord)
        print("LoggingHandler received LogRecord: {}".format(record))

        self.format(record)

        # List of LogRecord attributes expected when reading the
        # documentation of the logging module:

        expected_attributes = \
            "args,asctime,created,exc_info,filename,funcName,levelname," \
            "levelno,lineno,module,msecs,message,msg,name,pathname," \
            "process,processName,relativeCreated,stack_info,thread,threadName"

        for ea in expected_attributes.split(","):
            if not hasattr(record, ea):
                print("UNEXPECTED: LogRecord does not have the '{}' field!".format(ea))

formatter = logging.Formatter("%(asctime)s")
loggingHandler = LoggingHandler()
loggingHandler.setFormatter(formatter)
rootLogger = logging.getLogger()
rootLogger.addHandler(loggingHandler)

# emit an WARNING message
logging.warning("WARNING MESSAGE")

rawDescription: LogRecord does not have expected fields

description: LogRecord does not have expected fields


code: plt.imshow(k, vmin=0, vmax=1)

rawDescription: python imshow grayscale static color values

description: Python imshow grayscale static color values


code:
class MyClass(object):
    def __init__(self):
        ...
        self._data = data12

    def __getitem__(self, obj):
        return self._data.__getitem__(obj)

rawDescription: In Python, how can I append an ndarray to self in a function


code: x = subprocess.check_output(['whoami'])

rawDescription: Return value of x = os.system(..)

description: Return value of x = os.system(..)


code:
import re
pattern = re.compile("(?<=MI\s)(\d+\.\d+)")
for i, line in enumerate(open('the_file.txt')):
    for match in re.finditer(pattern, line):
        var = (i+1, match.groups())
        my_conten = float(var[1][0])

rawDescription: Assign specific content of a .txt file into a python variable


code:
from email.parser import Parser
import sys

message = Parser().parse(sys.stdin)
if message['content-type'].lower().startswith('text/'):
    print(message.get_payload(decode=True))
else:
    raise DieScreamingInAnguish('aaaargh!')  # pseudo-pseudocode

rawDescription: mail body encoding after procmail processing

description: Mail body encoding after procmail processing


code:
#!/usr/bin/env python

"""Simple, text-based RPG."""

import random  # Generate pseudo-random numbers.
import time  # Time access and conversions.

class Character(object):
    """Define the character."""

    def __init__(self, name, health, attack):

        self.name = str(name)  # Expecting a string.

        self.health = int(health)  # Expecting an integer.

        self.attack = int(attack)  # Expecting an integer.

    def properties(self):
        """Returns dictionary containing the character properties."""

        # Because using dictionaries is awesome.
        characteristics = {
            'name': self.name,
            'health': self.health,
            'attack': self.attack
        }

        return characteristics  # Returns a dictionary

def get_player():
    """Acquire the name of the player, and begin the game."""

    # Newline characters should improve readability on the command line.
    print('\nWelcome puny warrior, to my Dungeon of DOOM, and stuff.\n')

    # Variable names should be easy to read and understand.
    player_name = input(
        """
        Welcome puny warrior, to my Dungeon of DOOM... and stuff.

        Tell me your name: """
    )

    # Get and store the player's response.
    player_response = input(
        """
        Do you want to begin puny warrior who calls himself %s? (Y/N): \
        """ % player_name
        )

    if player_response.upper() == "Y":
        pass

    else:
        print('\nYou die now\n', player_name)

    return player_name

def score():
    """Assign a score between 1 and 100."""

    return random.randint(1, 100)

def main():
    """Where the automagic happens."""

    # Assuming you want random integers.
    player = Character(get_player(), score(), score()).properties()
    zombie = Character('Zombie', score(), score()).properties()
    dragon = Character('Dragon', score(), score()).properties()
    skeleton = Character('Skeleton', score(), score()).properties()

    # Since you're working with a dictictionary, you can now do things like:
    print(player['name'])
    print(zombie['name'], zombie['health'])
    print("%s: %s, %s" % (dragon['name'], dragon['health'], dragon['attack']))

# The correct methodology.
if __name__ == "__main__":
    main()

rawDescription: Can I 'import' information to a class object from a previously defined function?


code: random.sample(list(enumerate(a)), 5)

rawDescription: Python: Picking an element without replacement


code: color = '#eeefff'

rawDescription: Matplotlib: assign an ever different colour


code:
with open('data.csv') as f:
    lines = f.readlines()

lines = lines[1:] # skip header
result = dict()
for line in lines:
    sphere, product = line.split(',')
    product = product.strip()
    if not result.has_key(product):
        result[product] = list()
    result[product].append(sphere.strip())

with open('data_out.csv', 'w') as f:
    for product, spheres_list in result.items():
        f.write("%s,%s\n" %(product, ','.join(spheres_list)))

rawDescription: Transpose csv file in python

description: Transpose csv file in python


code:
with open(infile) as f:
    next(f) # skip first line
    with open(infile,"w") as f1:
        for line in f:
            f1.write(line) # write from second line

rawDescription: How do I remove the first line of a file without copying and slicing the whole file?

description: Remove the first line of a file without copying and slicing the whole file


code:
import itertools
with open('output.txt', 'w') as f:
    for n in range(1,5):
        for p in itertools.permutations('ab@F3',n):
            print(''.join(p), file=f)

rawDescription: Combine characters and output to file

description: Combine characters and output to file


code:
class SearchPreferenceForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SearchPreferenceForm, self).__init__(*args, **kwargs)
        self.fields['location'].empty_values.append('all')
        self.fields['school_type'].empty_values.append('all')

rawDescription: Validate POST data with extra argument using Django modelForm


code:
import numpy as np
data = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
required = np.where((data <= 2) | (data >= 4),data,np.nan)
required

rawDescription: element selection in numpy array

description: Element selection in numpy array


code:
import glob

interesting_files = glob.glob("*.csv")

header_saved = False
with open('output.csv','wb') as fout:
    for filename in interesting_files:
        with open(filename) as fin:
            header = next(fin)
            if not header_saved:
                fout.write(header)
                header_saved = True
            for line in fin:
                fout.write(line)

rawDescription: Merging multiple CSV files without headers being repeated (using Python)


rawDescription: Duplicate numpy array rows where the number of duplications varies


code:
def remove_repeated_pairs(l):
    i = 2;
    while i < len(l)-1:
            if l[i] == l[i-2] and l[i+1]==l[i-1]:
                l.pop(i);
                l.pop(i);
            else:
                i+=1;

    return l;

rawDescription: Adjacent multiple elements removing in Python sequences


code:
def cidr(prefix):
    return socket.inet_ntoa(struct.pack(">I", (0xffffffff << (32 - prefix)) & 0xffffffff))

rawDescription: How to convert a CIDR prefix to a dotted-quad netmask in Python?

description: Convert a CIDR prefix to a dotted-quad netmask in Python


code:
class SubWindow:

    def change(self):
        self.s1Var.set("new1")

    def createWidgets(self, root):
        self.s1Var = StringVar(); self.s1Var.set("string1")

        self.s1Label = Label(root,textvariable=self.s1Var)
        self.s1Label.grid(row=0, column=5)

        self.changeButton = Button(root, text="Change", command=self.change)
        self.changeButton.grid(row=9, column=7)

rawDescription: How to apply to new data on tkinter's canvas

description: Apply to new data on tkinter's canvas


code:
import decimal
decimal.Decimal('1') / (decimal.Decimal('5') / decimal.Decimal('1000000'))

rawDescription: Python 2.7 division not showing exact result


code:
def timer(message, x):
  for i in range(1,x):
    sys.stdout.write("\r%s%d" % (message, i))
    sys.stdout.flush()
    sleep(1)
    sys.stdout.write('\r  \r')
...

timer('Now counting..... ', 6)

rawDescription: How to append a "timer" inline with a print statement?

description: Append a "timer" inline with a print statement


code:
import matplotlib.pyplot as plt

xs = range(11)
ys = [0] * 11
colors = [ i * 0.1 for i in range(11) ]

plt.scatter(xs, ys, s=600, c = colors, cmap='YlGnBu')
plt.colorbar()
plt.show()

rawDescription: Matplotlib - color as third variable for already normalized data - not in grayscale


code:
class MainWindow (gtk.Window):
    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file('gladefile.ui')
        self.builder.get_object('button1').set_label("Hello, World!")

rawDescription: Adding widgets from Glade file to a subclass of gtk.Window in Python. How?


code:
d = np.dtype('int8')  # for example

min_value = np.iinfo(d).min
max_value = np.iinfo(d).max
signed = min_value!=0   # can also use "dtype.kind", see Jaime's comment
size = d.itemsize       # see comment

rawDescription: query properties of numpy dtypes

description: Query properties of numpy dtypes


code:
# .  = -Root----Admin
# .. = -Root
# ../JSON = -Root----JSON
my_file = open("../JSON/targetfile", "w")
my_file.write("foo")
my_file.close()

rawDescription: Save to a parallel directory in python

description: Save to a parallel directory in python


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

sns.set_style("white")

fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
ax2 =ax.twinx()
ax2.plot(100*np.random.rand(10))
sns.despine(ax=ax, right=True, left=True)
sns.despine(ax=ax2, left=True, right=False)
ax2.spines['right'].set_color('white')

rawDescription: Seaborn despine with two y-scales (twinx)


code:
from django.http import HttpResponseRedirect

def updatetext(request, fb_id):
    Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])

    fb = get_object_or_404(Account, pk=fb_id)
    return HttpResponseRedirect(reverse('account', kwargs={"fb_id": fb_id}))

rawDescription: Django views and URl's

description: Django views and URl's


code:
def get_list(file, cmp, fout):
    ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp))
    return fout[ind].rstrip('\n').split(' ')

root = r'c:\begpython\wavnk'
header = 6
for lst in lists:
    save = database_index[lst]
    index, base, _, abs2, abs1, *_ = save
    using_data[index] = save

    base = os.path.join(root, base.replace('phone', 'text'))
    fin, fout = base + '.pm', base + '.mcep'
    file = open(fin)
    fout = open(fout).readlines()
    [next(file) for _ in range(header)]
    file = [float(line.partition(' ')[0]) for line in file]
    join_cost_index_end[index] = get_list(file, float(abs1), fout)
    join_cost_index_strt[index] = get_list(file, float(abs2), fout)

rawDescription: Can this code be further optimized?

description: Can this code be further optimized


code:
def ipython(self):
    try:
        from IPython.frontend.terminal.ipapp import TerminalIPythonApp
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[])
        app.start()
    except ImportError:
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        try:
            from IPython.Shell import IPShell
            shell = IPShell(argv=[])
            shell.mainloop()
        except ImportError:
            # IPython not found at all, raise ImportError
            raise

rawDescription: Variables scope in inline django shell, vs python shell


rawDescription: Preventing PyTables (in Pandas) from printing "Closing remaining open files..."


code: df_c = pd.concat([df_a.reset_index(drop=True), df_b], axis=1)

rawDescription: Pandas column bind (cbind) two data frames


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

class MyAnimation(anim.TimedAnimation):
    def __init__(self, ax=None):
        if ax is None:
            fig, ax = plt.subplots()

        self.shape = (10, 10)
        data = np.zeros(self.shape)
        self.im = ax.imshow(data, vmin=0, vmax=1)
        super(self.__class__, self).__init__(ax.figure, interval=50, blit=True)

    def _draw_frame(self, framedata):
        data = np.random.rand(*self.shape)
        self.im.set_data(data)

    def new_frame_seq(self):
        return iter(range(100))

ani = MyAnimation()

rawDescription: matplotlib image animation not displayed if all entries in first frame are identical

description: Matplotlib image animation not displayed if all entries in first frame are identical


code:
unique_count = df.drop_duplicates().groupby('id').cumcount() + 1
unique_count.reindex(df.index).ffill()

rawDescription: cumulative number of unique elements for pandas dataframe

description: Cumulative number of unique elements for pandas dataframe


code:
url_pattern = 'ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis/surface/air.sig995.{}.nc'
for year in range(2006, 2012+1):
    url = url_pattern.format(year)
    print(url)

rawDescription: Downloading a certain file from a website


code:
from collections import defaultdict
dic = defaultdict(list)
for i in data:
    dic[i['Dept']].append(i['Name'])

rawDescription: Python Dict Comprehension to Create and Update Dictionary


code:
import glob
import os

files = glob.glob("D:\\myfolder\\a.b*.c0[589].jpg")
files = [f for f in files if 2001003 <= int(os.path.basename(f)[3:10]) <= 2001050]

rawDescription: create a list of files from a directory with various parameters

description: Create a list of files from a directory with various parameters


code:
import matplotlib.pyplot as plt
plt.subplot(6,1,1)
plt.subplot(6,1,2)
plt.subplot(6,1,3)
plt.subplot(2,1,2)

rawDescription: adjusting heights of individual subplots in matplotlib in Python

description: Adjusting heights of individual subplots in matplotlib in Python


rawDescription: How do I refer to a spcific datatable in IronPython in Spotfire?

description: Refer to a spcific datatable in IronPython in Spotfire


code:
import pandas
dfCurrentReportResults = pandas.DataFrame([['a','b'],['c','d'],['e','f'],['g','h'],['i','j']], columns=['Retention_y', 'Retention_x'])
dfCurrentReportResults['Retention_x'][1] = None
dfCurrentReportResults['Retention_x'][3] = None
dfCurrentReportResults
dfCurrentReportResults['Retention'] =  dfCurrentReportResults.apply(lambda x : x.Retention_y if x.Retention_x == None else x.Retention_x, axis=1)
dfCurrentReportResults

rawDescription: Using an if statement in a dataframe with lambda functions


code:
def listing_av_populate(self,response):
    db = MyDatabase()
    item = response.meta['item']
    item['update_bid_av'] = 3

    yield item

    query1 = "SELECT listing_id FROM listing_availability WHERE availability=1"
    listing_ids = db.query(query1)

    for lid in listing_ids:
        query2 = "SELECT url from listings where listing_id="+str(lid['listing_id'])
        self.start_urls.append( db.query(query2)[0]['url'] )

    for url in self.start_urls:
        yield Request(url, self.parse, priority=1)

def start_requests(self):

    link = "http://alexanderwhite.se/"
    item = PopulateListingAvItem()
    yield Request(link, callback=self.listing_av_populate, meta={'item': item}, priority=300)

rawDescription: Scrapy spider closes prematurely after yield request inside start_requests function


code:
datetime.datetime.strptime('2015 June 1','%Y %B %d')
datetime.datetime.strptime('2015 June 1','%Y %B %d').date()

rawDescription: How to convert 2015 June 1 into date format in python

description: Convert 2015 June 1 into date format in python


code:
import numpy
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas

N = 20
numpy.random.seed(N)

dates = pandas.date_range('1/1/2014', periods=N, freq='m')
df = pandas.DataFrame(
    data=numpy.random.randn(N),
    index=dates,
    columns=['A']
)

fig, ax = plt.subplots(figsize=(10, 6))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df.index, df['A'], width=25, align='center')

rawDescription: Matplotlib DateFormatter for axis label not working


code:
import time
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, asynchronous
from tornado import gen

class MyHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        self.write("sleeping .... ")
        self.flush()
        # Do nothing for 5 sec
        yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)
        self.write("I'm awake!")
        self.finish()

rawDescription: tornado equivalent of delay

description: Tornado equivalent of delay


code:
from collections import OrderedDict

a = {'score':3, 'color':'red'}
b = {'score':1, 'color':'yellow'}
lst = []

for d in [a,b]:
    temp = OrderedDict()
    for k in sorted(d, reverse=True):
        temp.setdefault(k, d[k])
    lst.append(temp)

OUTPUT: [OrderedDict([('score', 3), ('color', 'red')]), OrderedDict([('score', 1), ('color', 'yellow')])]

rawDescription: Flip order of elements in JSON in Python


code:
if button.CanSetTransparent():
    button.SetTransparent(100)

rawDescription: Opacity of individual widgets in WXPython


code:
class Job(object):
    def __init__(self, fpriority, spriority, description, iata , hops, cost):
        self.fpriority = fpriority
        self.spriority = spriority

    def __cmp__(self, other):
        '''Comparisons for Python 2.x - it's done differently in 3.x'''
        if self.fpriority > other.fpriority:
            return 1
        elif self.fpriority < other.fpriority:
            return -1
        else:
            if self.spriority > other.spriority:
                return 1
            elif self.spriority < other.spriority:
                return -1
            else:
                return 0

rawDescription: Priority Queue with two Priorities Python


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

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot(np.arange(10))
ax1.set_aspect("equal")

ax2.plot(np.arange(10), np.arange(0, 1, .1))

# Determining the ranges
x1,x2 = ax2.get_xlim()
y1,y2 = ax2.get_ylim()
xRange = x2-x1
yRange = y2-y1

ax2.set_aspect(xRange/yRange)

plt.show()

rawDescription: Same size of axes if one of them has set_aspectratio to "equal"


code:
def test_find_anagrams():
    stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
    result = []
    for str1 in stringlist:
        result.extend(word for word in get_dictionary_word_list() if anagram(word,str1))
    return result

rawDescription: defining a function which calls another function for a variety of strings python

description: Defining a function which calls another function for a variety of strings python


code:
from django.core import management
management.call_command('runserver')

rawDescription: How to start Django up programatically

description: Start Django up programatically


code:
class FooBar:
    def __init__(self):
        self.whatever = None

rawDescription: Python class variables

description: Python class variables


code:
import functools
f = lambda selflambda, x=x, *y: foo(x, y, selflambda)
f = functools.partial(f, f)

rawDescription: Lambda, calling itself into the lambda definition


code: msglist = [ hextotal[i:i+4096] for i in range(0,len(hextotal),4096) ]

rawDescription: Python: How to add three text files into one variable and then split it into a list


code: [input[i:i+n] for i in range(0, len(input), n)]

rawDescription: Creating lists from elements in a bigger list


code:
s = "10 packets transmitted, 10 packets received, 0.00% packet loss"
trans,recv,loss = s.split(",")

print(trans,recv,loss)
('10 packets transmitted', ' 10 packets received', ' 0.00% packet loss')
print(float(loss.split("%")[0] > 5))
False

rawDescription: Python Regular Expression - match , compare and decide


code: yourList = myList + [40]

rawDescription: Allow Python list append method to return the new list


code:
def assign_ID(dic, id):
    for key in dic:
        if id in dic[key]:
            return key

rawDescription: Python Function Takes too Long as Dictionary Gets too Big


code:
if (prev_input and (not input)):
    door_closed()

rawDescription: reverse event trigger in python script

description: Reverse event trigger in python script


code:
import logging

summary_verbose_handler = logging.config.logging._handlers['summary_verbose']

log_core = logging.getLogger('myapp.some_routine')
log_core.addHandler(summary_verbose_handler)

rawDescription: How can I access handlers defined in config?

description: Access handlers defined in config


code:
import wx

class scarlett(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, size=(400, 350))

    panel = wx.Panel(self, -1)
    sizer = wx.GridBagSizer(4, 4)

    text1 = wx.StaticText(panel, -1, 'Scarlett')
    sizer.Add(text1, (0, 0), flag = wx.TOP | wx.LEFT | wx.BOTTOM, border=5)
    self.tc = wx.TextCtrl(panel, -1)
    sizer.Add(self.tc, (1, 0), (1, 6), wx.EXPAND |wx.LEFT | wx.RIGHT, 5)

    text2 = wx.StaticText(panel, -1, 'You')
    sizer.Add(text2, (2, 0), flag = wx.TOP | wx.LEFT | wx.RIGHT, border = 5 )
    self.listbox = wx.ListBox(panel, -1, style = wx.LB_ALWAYS_SB)
    sizer.Add(self.listbox, (3, 0), (3, 6), wx.EXPAND |wx.LEFT | wx.RIGHT, 5)

    buttonOk = wx.Button(panel, -1, 'Ok', size=(90, 28))
    buttonCancel = wx.Button(panel, -1, 'Cancel', size=(90, 28))
    sizer.Add(buttonOk, (7, 1))
    sizer.Add(buttonCancel, (7, 2), flag = wx.RIGHT | wx.BOTTOM, border = 5)

    self.Bind(wx.EVT_BUTTON, self.OnQuit, buttonCancel)
    self.Bind(wx.EVT_BUTTON, self.OnCopyText, buttonOk)

    sizer.AddGrowableCol(0)
    sizer.AddGrowableRow(5)
    sizer.AddGrowableRow(6)
    sizer.SetEmptyCellSize((1, 1))
    panel.SetSizer(sizer)

    self.Center()
    self.Show(True)

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

  def OnCopyText(self, event):
    self.listbox.Append(self.tc.GetValue())

app = wx.App()
frm = scarlett(None, -1, "scarlett")
app.MainLoop()

rawDescription: Event get value in wxpython

description: Event get value in wxpython


code:
import random
from livewires import games, color

games.init(screen_width = 640, screen_height = 480, fps = 50)

class Ball(games.Sprite):

    quit_label = games.Text(value = "Press Q to Quit", size = 25, color = color.white, top = 5, right = 130,
                              is_collideable = False)
    games.screen.add(quit_label)

    def update(self):
        if self.right > games.screen.width:
            self.dx = -self.dx

        if self.left < 0:
            self.game_over()

        if self.bottom > games.screen.height or self.top < 0:
            self.dy = -self.dy

        #pressing 'q' quits the game
        if games.keyboard.is_pressed(games.K_q):
            self.game_over()

    def bounce(self):
        self.dx = -self.dx

    def game_over(self):
        """ End the game. """
        end_message = games.Message(value = "Game Over",
                                    size = 90,
                                    color = color.red,
                                    x = games.screen.width/2,
                                    y = games.screen.height/2,
                                    lifetime = 3 * games.screen.fps,
                                    after_death = games.screen.quit,
                                    is_collideable = False)
        games.screen.add(end_message)
        self.destroy()

class Paddle(games.Sprite):
    image = games.load_image("paddle.bmp")

    score = games.Text(value = 0, size = 25, color = color.white, top = 15,
        right = games.screen.width - 10, is_collideable = False)
    games.screen.add(score)

    def __init__(self):
        super(Paddle, self).__init__(image = Paddle.image, x = games.mouse.x, bottom = games.screen.height)

    def update(self):
        """ Move to mouse y position. """
        self.y = games.mouse.y

        if self.left > 0:
            self.left = 10

        if self.right > games.screen.height:
            self.right = games.screen.height

        self.check_catch()

    def check_catch(self):
        for ball in self.overlapping_sprites:
            Paddle.score.value += 1
            ball_image2 = games.load_image("ball.bmp")
            ball2 = Ball(image = ball_image2,
                      x = games.screen.width/2,
                      y = games.screen.height/2,
                      dx = 1,
                      dy = 1)
            games.screen.add(ball2)
            ball.bounce()

def main():
    wall_image = games.load_image("background.bmp", transparent = False)
    games.screen.background = wall_image

    ball_image = games.load_image("ball.bmp")
    the_ball = Ball(image = ball_image,
                      x = games.screen.width/2,
                      y = games.screen.height/2,
                      dx = 1,
                      dy = 1)
    games.screen.add(the_ball)

    the_paddle = Paddle()
    games.screen.add(the_paddle)

    games.mouse.is_visible = False

    games.screen.mainloop()

# kick it off!
main()

rawDescription: Unable to fix broken ball movement in pygame pong


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            '/home/html/templates/lawrence.com',
            '/home/html/templates/default',
        ],
    },
]

rawDescription: Djangos TEMPLATE_DIRS not found

description: Djangos TEMPLATE_DIRS not found


code:
import collections
d = collections.defaultdict(list)

with open('lakhlists.txt') as f:
    for line in f:
        aslist = line.split()  # assuming whitespace separators
        d[aslist[1]].append(aslist)

rawDescription: indexing for faster search of lists in a file?

description: Indexing for faster search of lists in a file


code:
with open ("results/results_%s.txt" % bla, "r") as myfile:
  raey = {}
  for line in myfile:
    line = line.translate(None, ''.join(chars_to_remove))
    abc = line.split("_", 2)
    year = abc[1:2]
    year = ''.join(year)
    year = year.translate(None, ''.join(chars_to_remove))
    #increment the value of the "year"-key, if not present set it to 0 to avoid key erros
    raey[year] = raey.get(year, 0) + 1

rawDescription: Add key and value to dictionary

description: Add key and value to dictionary


code:
@event.listens_for(MyBase, 'mapper_configured')
def get_special_columns(mapper, cls):
    for attrname in dir(cls):
        val = getattr(cls, attrname)
        if isinstance(val, SpecialColumn):
             name1, name2 = "_%s_1" % attrname, "_%s_2" % attrname
             setattr(cls, name1, Column(...))
             setattr(cls, name2, Column(...))

             @hybrid_property
             def myhybrid(self):
                 return getattr(self, name1), getattr(self, name2)

             @myhybrid.setter
             def myhybrid(self, value):
                 setattr(self, name1, value[0])
                 setattr(self, name2, value[1])

             setattr(cls, attrname, myhybrid)

rawDescription: Custom metaclass to create hybrid properties in SQLAlchemy


rawDescription: Sort python list by function

description: Sort python list by function


code:
import csv

a=[['Lindsey Jessica <xyz@icloud.com>'],
['Jonathan Bob <a@xyz.edu>'],
['Homer Simpson <b@xyz.edu>']]

mylist=[elem[0].split() for elem in a ]

"""Output[['Lindsey', 'Jessica', '<xyz@icloud.com>'], ['Jonathan', 'Bob', '<a@xyz.edu>'], ['Homer', 'Simpson', '<b@xyz.edu>']]"""

mylist1=[]
#removing '<' and'>' and creating a new list name mylist1
for elem in mylist:
    elem[2] = elem[2][1:len(elem[2])-1]
    mylist1.append(elem)
#writing to a csv file
with open('out.csv', 'wb') as fp:
    myf = csv.writer(fp, delimiter=',')
    myf.writerows(mylist1)

rawDescription: Split 1 Column of CSV Into 3 Lists/Columns


code:
class scraper():
    def somefunc(self):
        self.host = "intranet.ku.dk"
        self.url = "https://intranet.ku.dk/Selvbetjening/Sider/default.aspx"
        self.data = urllib.urlencode(postDataDict)
        self.headers = {   #You can fill these values by looking into what the browser sends.
            'Accept': 'text/html; */*',
            'Accept-Language': '',
            'Accept-Encoding': 'identity',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded'}
        response = makeRequest(host,url,data)
        if (response.status == 302):
            url = '/'+response.getheader("Location").split('/')[3]
            response = makeRequest(host,url,{})

    def makeRequest(self,host,url,data):
        cookies = ''
        for key in self.cookies:
            cookies = cookies + key + '=' + self.cookies[key] + '; '
        self.headers['Cookie'] = cookies
        conn = httplib.HTTPSConnection(host)
        conn.request("POST", url, data, self.headers)
        response = conn.getresponse()
        self.saveCookies(response.getheader("Set-Cookie"))
        responseVal = response.read()
        conn.close()
        self.headers['Referer'] = fullUrl #setting header for next request
        return response

    def saveCookies(self,cookies):
        if cookies is not None:
            values = cookies.split()
            for value in values:
                parts = value.split('=')
                if(len(parts) > 1):
                    if((parts[0] != 'expires') and (parts[0] != 'Max-Age') and (parts[0] != 'Path') and (parts[0] != 'path') and (parts[0] != 'Domain')):
                        self.cookies[parts[0]] = parts[1].rstrip(';')

rawDescription: How to retrieve data from a iframe on a HTTPS secured site with a login

description: Retrieve data from a iframe on a HTTPS secured site with a login


code:
class MyTable(DeferredReflection, Base):
    __tablename__ = 'my_table'
    __table_args__ = {'schema': 'schema2'}

rawDescription: SQLAlchemy: reflect table into explicitly created class


code:
import tkinter
import time

root = tkinter.Tk()
can = tkinter.Canvas(root, width = 10, height = 10)
can.rowconfigure(0, weight=1)
can.columnconfigure(0, weight=1)
can.grid()

root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

for i in range(10):
    can.configure(width = i * 50, height = i * 50)
    root.update()
    print(i)
    time.sleep(0.5)

rawDescription: How can I make a window fit its contents in tkinter?

description: Make a window fit its contents in tkinter


code: maxvalues = heapq.nlargest(20, lst)

rawDescription: Filter max 20 values from a list of integers


code:
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar

window = Tk()

name_array = [('a1','a2','a3'), ('b1','b2','b3'), ('c1','c2','c3'),('d1','d2','d3')]
position_track = IntVar()

first_name = StringVar()
last_name = StringVar()
email = StringVar()

def return_value(pos):
    first_name.set(name_array[pos][0])
    last_name.set(name_array[pos][1])
    email.set(name_array[pos][2])

def update_value(pos):
    name_array[pos] = (first_name.get(), last_name.get(), email.get())

def first_value():
    global position_track
    return_value(0)
    position_track.set(0)

def last_value():
    global position_track
    return_value(-1)
    position_track.set(-1)

def next_value():
    global position_track
    if position_track.get() == len(name_array):
        position_track.set(1)
    temp = position_track.get()
    return_value(temp + 1)
    position_track.set(temp + 1)

def prev_value():
    global position_track
    if position_track.get() == -1:
        position_track.set(len(name_array) - 1)
    temp = position_track.get()
    return_value(temp - 1)
    position_track.set(temp - 1)

label_first_name = Label(window, text = 'First Name:', justify = 'right', padx = 5)
entry_first_name = Entry(window, textvariable = first_name)
label_last_name = Label(window, text = 'Last Name:', justify = 'right', padx = 5)
entry_last_name = Entry(window, textvariable = last_name)
label_email = Label(window, text = 'Email Address:', justify = 'right', padx = 5)
entry_email = Entry(window, textvariable = email)

button_first = Button(window, text = 'First', command = first_value)
button_last = Button(window, text = 'Last', command = last_value)
button_prev = Button(window, text = 'Prev', command = prev_value)
button_next = Button(window, text = 'Next', command = next_value)
button_quit = Button(window, text = 'Quit')
button_quit.configure(command=window.destroy)

labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
buttons = [button_first, button_last, button_prev, button_next, button_last, button_quit]

for i in range(3):
    labels[i].grid(row = i, column = 0, sticky = 'W')
    entries[i].grid(row = i, column = 1, columnspan = 6)

for j in range(6):
    buttons[j].grid(row = 3, column = j, sticky = 'E')

window.mainloop()

rawDescription: global variable issues with tkinter python

description: Global variable issues with tkinter python


code:
import pandas as pd
df = pd.read_excel(FILENAME)

rawDescription: Shortest code to load an excel sheet with header?


code:
my_text = re.sub(r"<[^>]*>", "", my_text)

#
# some    STUFF   here
# Obary   SEES    Obary
#
#
# ...

rawDescription: Negation using regular expressions

description: Negation using regular expressions


code:
def function(var, key):
    def change_variable():
        nonlocal var
        var += 1
        print(var)  # just to prove it's incrementing
    turtle.listen()
    turtle.onkey(change_variable, key)

rawDescription: Easier Way to Accept Key Presses in Turtle?


code:
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

# Required so that GET requests workr
@toolkit.side_effect_free
def get_news(context,data_dict=None):
  # The actual custom API method
  return {"hello":"world"}

class CustomAPIPlugin(plugins.SingletonPlugin):
  plugins.implements(plugins.interfaces.IActions)

  def get_actions(self):
    # Registers the custom API method defined above
    return {'get_news': get_news}

rawDescription: How can I extend CKAN API?

description: Extend CKAN API


rawDescription: Given a list of lists, find the index of the list which contains a particular item in Python


code:
b = intern('testing123')
getrefcount(b)
a = 'test'
a = intern(a+'ing123')
getrefcount(b)
a is b

rawDescription: why doesn't python rereference this existing object?

description: Why doesn't python rereference this existing object


code: like = 'Hello, i found {} in your list'.format(', '.join(notFinishedModules))

rawDescription: How to put String names out of list to new String in pythonic way

description: Put String names out of list to new String in pythonic way


rawDescription: Get coords of an oval in Tkinter

description: Get coords of an oval in Tkinter


rawDescription: How to make browser to download the Django CSV file response

description: Make browser to download the Django CSV file response


code:
min(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"])
'echidna'
max(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"])
'ostrich'

rawDescription: Pythonic way to find key of weighted minimum and maximum from a dictionary


code:
_opener = None
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
    global _opener
    if _opener is None:
        _opener = build_opener()
    return _opener.open(url, data, timeout)

def install_opener(opener):
    global _opener
    _opener = opener

rawDescription: Are urllib2 and httplib thread safe?

description: Are urllib2 and httplib thread safe


code:
def convert(arr):
    return [int(float(x))*8 for x in arr]

f1 = convert(f1)
f2 = convert(f2)
f3 = convert(f3)

rawDescription: python function which edits different arrays

description: Python function which edits different arrays


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

    def save():
        if not self.pk: # It's a creation, not an update
            self.cards = self.stock * 2
            super(card, self).save(*args, **kwargs)

rawDescription: Multiply content of Integerfield

description: Multiply content of Integerfield


code:
def userouput(toprint):
    print(toprint)

def userinput():
    userin = raw_input("Enter: ")
    userouput(userin)

if __name__ == '__main__':
    userinput()

rawDescription: pass input from one function to another in python

description: Pass input from one function to another in python


code:
def current_docs(docs):
  tmp = {}
  output = []
  for d in docs:
    if d['name'] in tmp:
      continue
    tmp[d['name']] = 1
    output.append(d)
  return output

rawDescription: Filtering a List of Objects by multiple Object Attributes


code:
@simplegeneric
def float(*args, **kwds):
    return __builtin__.float(*args, **kwds)

@float.register(timedelta)
def timedelta_as_float(td):
    seconds = td.seconds
    hours = seconds // 3600
    seconds = (seconds - hours * 3600) * (1.0 / 3600)
    return td.days * 24 + hours + seconds

@float.register(Time)
def Time_as_float(t):
    return t.tofloat()

rawDescription: Python: Calling a function based on a argument value


code: sorted(enumerate(a), key=lambda x: x[1])

rawDescription: Sorting while preserving order in python


code:
# encoding: utf-8
import os, os.path, sys
import tornado.web
import tornado.testing
import mox

class BaseHandler(tornado.web.RequestHandler):
    def get_login_url(self):
        return u"/login"

    def get_current_user(self):
        user_json = self.get_secure_cookie("user")
        if user_json:
            return tornado.escape.json_decode(user_json)
        else:
            return None

class HelloHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.render("protected.html")

class Protected(tornado.web.RequestHandler):
    def get_current_user(self):
        # get an user from somewhere
        return "andy"

    @tornado.web.authenticated
    def get(self):
        self.render("protected.html")

class TestAuthenticatedHandlers(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        self.mox = mox.Mox()
        app = tornado.web.Application([
            (r'/protected', Protected),
            (r'/hello', HelloHandler)
        ])
        return app

    def tearDown(self):
        self.mox.UnsetStubs()
        self.mox.ResetAll()

    def test_new_admin(self):
        self.mox.StubOutWithMock(Protected, 'get_current_user', use_mock_anything=True)
        Protected.get_current_user().AndReturn("test_user")
        self.mox.ReplayAll()
        resp = self.fetch('/protected')
        self.assertEqual(resp.code, 200)
        self.mox.VerifyAll()

    def test_hello_page(self):
        self.mox.StubOutWithMock(HelloHandler, 'get_current_user', use_mock_anything=True)
        HelloHandler.get_current_user().AndReturn("test_user")
        self.mox.ReplayAll()
        resp = self.fetch('/hello')
        self.assertEqual(resp.code, 200)
        self.assertIn( "Hello", resp.body )
        self.mox.VerifyAll()

description: Tornado testing @tornado.web.authenticated


code:
from PIL import Image
trial_image = Image.open(file)
trial_image.verify()

rawDescription: How does Django determine if an uploaded image is valid?


code: x = zip(*args)

rawDescription: Can you dynamically create the arguments for the zip() function in python 2?

description: Dynamically create the arguments for the zip() function in python 2


code:
class foo(object):
    def __init__(self, a):
            self.a = a
    def __index__(self):
            return self.a

data = [1, 2, 3, 4, 5]
data[foo(1)]

rawDescription: Python: Using a class as a list index

description: Python: Using a class as a list index


code:
class Middleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):

        def custom_start_response(status, headers, exc_info=None):
            headers.append(('Set-Cookie', "name=value"))
            return start_response(status, headers, exc_info)

        return self.app(environ, custom_start_response)

rawDescription: How to add http headers in WSGI middleware?

description: Add http headers in WSGI middleware


code:
friendship_union = select([
    FacebookFriendship.dater_id,
    cast(FacebookFriendship.fb_uid_friend, Integer()).label(
        'fb_uid_friend')
]).union(
    select([
        cast(FacebookFriendship.fb_uid_friend, Integer()),
        FacebookFriendship.dater_id]
    )
).alias()

cls.all_fb_friendships = relationship(
    UserSocialAuth,
    secondary=friendship_union,
    primaryjoin=UserSocialAuth.user_id == friendship_union.c.dater_id,
    secondaryjoin=and_(
        UserSocialAuth.provider == 'facebook',
        cast(UserSocialAuth.uid, Integer() ) == friendship_union.c.fb_uid_friend,
    ),
    viewonly=True
)

rawDescription: SQLAlchemy: How can I define a relationship as the union of two other relationships?


code:
ax.set_xticks(np.arange(5) + 1.)
ax.set_xticklabels(a['f1'])

rawDescription: matplotlib - Shunt x-axis labels

description: Matplotlib - Shunt x-axis labels


code:
def user_ok(self):
    key_name = 'info@example.com'
    new_user = Profile(key_name=key_name)
    new_user.put()

    os.environ['USER_EMAIL'] = key_name
    os.environ['USER_ID'] = key_name
    os.environ['USER_IS_ADMIN'] = ''
    response = self.get( '/appindex' )
    self.assertOK(response)

    # Now let's reset it to check that the user will be redirected.
    new_user.delete()
    response = self.get( '/appindex' )
    self.assertEqual(response.headers['Location'], 'http://localhost/newuser')

rawDescription: WebTest: Testing with decorators + datastore calls


code:
import wx
from PIL import Image

SIZE = (640, 480)

def get_image():
    # Put your code here to return a PIL image from the camera.
    return Image.new('L', SIZE)

def pil_to_wx(image):
    width, height = image.size
    buffer = image.convert('RGB').tostring()
    bitmap = wx.BitmapFromBuffer(width, height, buffer)
    return bitmap

class Panel(wx.Panel):
    def __init__(self, parent):
        super(Panel, self).__init__(parent, -1)
        self.SetSize(SIZE)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        self.update()
    def update(self):
        self.Refresh()
        self.Update()
        wx.CallLater(15, self.update)
    def create_bitmap(self):
        image = get_image()
        bitmap = pil_to_wx(image)
        return bitmap
    def on_paint(self, event):
        bitmap = self.create_bitmap()
        dc = wx.AutoBufferedPaintDC(self)
        dc.DrawBitmap(bitmap, 0, 0)

class Frame(wx.Frame):
    def __init__(self):
        style = wx.DEFAULT_FRAME_STYLE & ~wx.RESIZE_BORDER & ~wx.MAXIMIZE_BOX
        super(Frame, self).__init__(None, -1, 'Camera Viewer', style=style)
        panel = Panel(self)
        self.Fit()

def main():
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Center()
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: Any quick Python GUI to display live images from Camera


code:
def randstat(level):
    points = randint(10,max(20,5*level))

    # set all our minimums to zero
    stats = [0, 0, 0, 0, 0]

    for i in range(points):
        stat = randint(0, len(stats)-1); # pick a random stat to increment
        stats[stat] = stats[stat] + 1

    # extract the stats back out of our array
    agility = stats[0]
    stamina = stats[1]
    strength = stats[2]
    vitality = stats[3]
    intelligence = stats[4]

rawDescription: Doing tasks in a random order

description: Doing tasks in a random order


code:
Popen(' '.join(args+['>', 'logFile', '2>&1']), # shell specific cmdline
      shell=True) # on Windows see _cmdline2list to understand what is going on

rawDescription: jython killing parent process that spawns subprocess breaks subprocess stdout to file?

description: Jython killing parent process that spawns subprocess breaks subprocess stdout to file


code:
import subprocess

def svnversion():
    p = subprocess.Popen("svnversion", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate()
    return stdout

rawDescription: How to programmatically get SVN revision number?

description: Programmatically get SVN revision number


code:
#!/usr/bin/python
filename='thefile.txt'
search="class Parking(models.Model):"
add="\n    layer_id= models.ForeignKey('sdr_layer.id')"
content=open(filename,'r').read()
content=content.replace(search,search+add)
fp=open(filename,'w')
fp.write(content)
fp.close()

rawDescription: How to insert a string of characters into a text file using python?

description: Insert a string of characters into a text file using python


code:
def search(request):

    from sets import Set

    var=""

    # create set object
    set = Set()

    if request.method=='POST':

        s1=request.POST.get("input1")
        s1=s1.split(",")

        for i in s1:

            if i :
                # |= is the set union operator
                set |= Set(form2.objects.filter(keyskills=i))

        # convert set back to list
        var=list(set)

    return render(request,"searchresult.html",{'var1':var})

rawDescription: how to avoid repeated values retrieved from database?

description: Avoid repeated values retrieved from database


code:
## Callback function invoked when header data is ready
def header(buf):
    import sys
    sys.stdout.write(buf)
    # Returning None implies that all bytes were written

c = pycurl.Curl()
c.setopt(pycurl.URL, "http://www.siteA.com/")
c.setopt(pycurl.HEADERFUNCTION, header)
c.perform()

rawDescription: Python: Get the redirect urls using cURL


code:
import zipfile
import requests
import StringIO

u = requests.get("http://www.pythonchallenge.com/pc/def/channel.zip")
f = StringIO.StringIO()
f.write(u.content)

def extract_zip(input_zip):
    input_zip = zipfile.ZipFile(input_zip)
    return {i: input_zip.read(i) for i in input_zip.namelist()}
extracted = extract_zip(f)

rawDescription: Python - Download File Using Requests, Directly to Memory


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

fname = 'total_watt.csv'

# Read in the data, but I skipped setting the index and made sure no data
# is lost to a nonexistent header
df = pd.read_csv(fname, parse_dates=[0], header=None, names=['datetime', 'watt'])

# We want to separate the date from the time, so create two new columns
df['date'] = [x.date() for x in df['datetime']]
df['time'] = [x.time() for x in df['datetime']]

# Now we want to reshape the data so we have dates and times making the result 2D
pv = df.pivot(index='time', columns='date', values='watt')

# Not every date has every time, so fill in the subsequent NaNs or there will be holes
# in the surface
pv = pv.fillna(0.0)

# Now, we need to construct some arrays that matplotlib will like for X and Y values
xx, yy = np.mgrid[0:len(pv),0:len(pv.columns)]

# We can now plot the values directly in matplotlib using mplot3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(xx, yy, pv.values, cmap='jet', rstride=1, cstride=1)
ax.grid(False)

# Now we have to adjust the ticks and ticklabels - so turn the values into strings
dates = [x.strftime('%Y-%m-%d') for x in pv.columns]
times = [str(x) for x in pv.index]

# Setting a tick every fifth element seemed about right
ax.set_xticks(xx[::5,0])
ax.set_xticklabels(times[::5])
ax.set_yticks(yy[0,::5])
ax.set_yticklabels(dates[::5])

plt.show()

rawDescription: Using pandas/matplotlib/python, I cannot visualize my csv file as clusters


code:
@gen.coroutine
def update_all( self ):

    futures = []
    for service in self.port_list:
        futures.append(self.update_service(str(service.get('port'))))

    self.response_list = yield futures
    self.response = json.dumps( self.response_list )

    return self.response

rawDescription: How start multiple tasks at once in tornado


code:
mypanel = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],
                  major_axis=pd.date_range('1/1/2000', periods=5),
                  minor_axis=['A', 'B', 'C', 'D'])

def func1(k, x):
    print(k)
    return x.apply(np.log)

mypanel.apply(lambda x: func1('the wrong name', x))  # 1000 loops, best of 3: 1.01 ms per loop
pd.Panel({k: func1(k, v) for k, v in mypanel.iteritems()})  # 1000 loops, best of 3: 800 µs per loop

rawDescription: How to get item name in pandas panel.apply function

description: Get item name in pandas panel.apply function


code:
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

fig = plt.figure(figsize=(8, 10))
gs1 = plt.GridSpec(2, 1, hspace=0.2)
gs2 = plt.GridSpec(8, 1, hspace=0)

ax1 = fig.add_subplot(gs1[0], projection='3d')
ax1.plot(range(10), range(10), range(10))

ax = fig.add_subplot(gs2[4])
lower_axes = [ax]
for i in range(4, 8):
    if i > 4:
        ax = fig.add_subplot(gs2[i], sharex=lower_axes[0])
    ax.plot(range(10))
    ax.locator_params(axis='y', nbins=5, prune='both')
    lower_axes.append(ax)

for ax in lower_axes:
    ax.label_outer()

plt.show()

rawDescription: Python Numpy add hspace between 3D plot and 2D plot with shared axes


code:
import ctypes

def deref(addr, typ):
    return ctypes.cast(addr, ctypes.POINTER(typ))

deref(id(4), ctypes.c_int)[6] = 5

2 + 2
#>>> 5

2 + 2 == 5
#>>> True

rawDescription: Python force a condition

description: Python force a condition


code:
class MYREALM_securepage(webapp.RequestHandler):
  def get(self):
      if not 'Authorization' in self.request.headers:
          self.response.headers['WWW-Authenticate'] = 'Basic realm="MYREALM"'
          self.response.set_status(401)
          self.response.out.write("Authorization required")
      else:
          auth = self.request.headers['Authorization']
          (username, password) = base64.b64decode(auth.split(' ')[1]).split(':')
          # Check the username and password, and proceed ...

rawDescription: Python/WebApp Google App Engine - testing for user/pass in the headers


code:
import sys
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout = open('/dev/null', 'w')
sys.stderr = open('/dev/null', 'w')

rawDescription: Can I redirect all output to /dev/null from within python?

description: Redirect all output to /dev/null from within python


code:
import pexpect as px

cmds = ['cmd1', 'cmd2', 'cmd3']
retcode = -1
while (retcode<10):
    if (retcode<2):
        child = px.spawn('telnet %s %s' % (ip_addr,port))
    lregex = '(sername:)'            # Insert regex for login prompt here
    pregex = '(prompt1>)|(prompt2$)' # Insert your prompt regex here
    # retcode = 0 for px.TIMEOUT, 1 for px.EOF, 2 for lregex match...
    retcode = child.expect([px.TIMEOUT, px.EOF, lregex, pregex],timeout = 10)
    if (retcode==2):
        do_login(child)  # Build a do_login() method to send user / passwd
    elif (2<retcode<10) and (len(cmds)>0):
        cmd = cmds.pop(0)
        child.sendline(cmd)
    else:
        retcode = 10

rawDescription: Catching a dying process in pexpect

description: Catching a dying process in pexpect


code:
for l in read_file:
    l.replace("5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22",
              "5EFF837F-EFC2-4c32-A3D4-RHUI5345JO")
    # Write to file..

rawDescription: Search for a String and replace it with a variable


code:
h,s,v = cv2.split(img)
mask = (v == 0) + (v == 100) + (s == 0)
mask = numpy.logical_not(mask)

rawDescription: OpenCV- ignoring pixels when generating a hue histogram


code:
variables = subprocess.Popen(
    ["bash", "-c", "trap 'env' exit; source \"$1\" > /dev/null 2>&1",
       "_", "yourscript"],
    shell=False, stdout=subprocess.PIPE).communicate()[0]

rawDescription: Can I run a bash script in Python and keep any env variables it exports?

description: Run a bash script in Python and keep any env variables it exports


code:
import urllib
from bs4 import BeautifulSoup

url = "http://aqicn.org/city/shenyang/usconsulate/json"
soup = BeautifulSoup(urllib.urlopen(url), "html.parser")
soup.find("div", class_="aqivalue").get_text()

rawDescription: How to read the content of an website?

description: Read the content of an website


code:
import Tkinter as tkinter

def on_frame_click(e):
    print("frame clicked")

def retag(tag, *args):
    '''Add the given tag as the first bindtag for every widget passed in'''
    for widget in args:
        widget.bindtags((tag,) + widget.bindtags())

tk = tkinter.Tk()
a_frame = tkinter.Frame(tk, bg="red", padx=20, pady=20)
a_label = tkinter.Label(a_frame, text="A Label")
a_button = tkinter.Button(a_frame, text="click me!")
a_frame.pack()
a_label.pack()
a_button.pack()
tk.protocol("WM_DELETE_WINDOW", tk.destroy)
retag("special", a_frame, a_label, a_button)
tk.bind_class("special", "<Button>", on_frame_click)
tk.mainloop()

rawDescription: How to capture events on tkinter child widgets?

description: Capture events on tkinter child widgets


code:
button = gtk.Button("text on button")
button.set_size_request(width=30, height=20)

rawDescription: Keep PyGTK Button from Resizing on Label Change


code:
import csv
now = 'Tue Apr 15 10:23:05 2014'
inorout = 'out'

with open('timeclock.csv', 'a', newline='') as timeclocklog:
    timeclockwriter = csv.writer(timeclocklog)
    timeclockwriter.writerow([now, inorout])

rawDescription: Writing a CSV on Windows

description: Writing a CSV on Windows


code:
import matplotlib.pyplot as plt
import numpy as np
from bubblegum.backend.mpl.cross_section_2d import CrossSection
fig= plt.figure()
cs= CrossSection(fig)
img= np.random.rand(100,100)
cs.update_image(img)
plt.show()

rawDescription: matplotlib interactive plot with slices of image

description: Matplotlib interactive plot with slices of image


code:
inds = {'EUR': [whatever],
        'AFR': [foo],
        'ASN': [other]}

foos = inds['EUR']

rawDescription: Set string as variable name

description: Set string as variable name


code:
def weighted_choice(choices):
   total = sum(w for c, w in choices)
   r = random.uniform(0, total)
   upto = 0
   for c, w in choices:
      if upto + w >= r:
         return c
      upto += w
   assert False, "Shouldn't get here"

rawDescription: A weighted version of random.choice

description: A weighted version of random.choice


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcol
import matplotlib.cm as cm

start_time = 100
end_time = 120

# Generate some dummy data.
tim = range(start_time,end_time+1)
xdat = np.arange(0,90.1)
ydat = [np.sin(0.2*(xdat-t)/np.pi) for t in tim]

# Make a user-defined colormap.
cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName",["r","b"])

# Make a normalizer that will map the time values from
# [start_time,end_time+1] -> [0,1].
cnorm = mcol.Normalize(vmin=min(tim),vmax=max(tim))

# Turn these into an object that can be used to map time values to colors and
# can be passed to plt.colorbar().
cpick = cm.ScalarMappable(norm=cnorm,cmap=cm1)
cpick.set_array([])

F = plt.figure()
A = F.add_subplot(111)
for y, t in zip(ydat,tim):
    A.plot(xdat,y,color=cpick.to_rgba(t))

plt.colorbar(cpick,label="Time (seconds)")

rawDescription: Python: making color bar that runs from red to blue


code:
def toggle(fshow,fhide):
    fhide.pack_forget()
    fshow.pack()

btn1 = Button(btnframe,text="screen1", command=lambda:toggle(myframe1,myframe2),width=9)
btn1.pack(side=LEFT)

btn2 = Button(btnframe,text="screen2",command=lambda:toggle(myframe2,myframe1),width=9)
btn2.pack(side=LEFT)

rawDescription: Is it possible in tkinter to pull up different screens in the same location


code:
new_dict = {}
for ik in masterSensor:
    new_dict[str(ik['ItemK'])] = {'MasterKey' : ik['MasterKey'], 'SensorId' : None}

for sk in sensor:
    new_dict[str(sk['SensorK'])]['SensorId'] = sk['SensorId']

rawDescription: Finding matching dictionary elements within two different lists


code:
def StudentID(self, obj):
  return '%s' % obj.pk
StudentID.short_description = 'StudentID'
def Student_Name(self, obj):
    return '%s' % obj.name

rawDescription: Getting attributes from queryset in django-admin


code:
SOUTH_MIGRATION_MODULES = {
    'books': 'myproject.app_name.migrations',
}

rawDescription: Changing South Migration Directory

description: Changing South Migration Directory


code:
from scipy.interpolate import interp1d
x = np.linspace(0, 10, 10)
y = np.array([np.exp(-x/3.0), 2*x])
f = interp1d(x, y)
f(2)
np.array([np.exp(-2/3.0), 2*2])

rawDescription: Vector-valued function interpolation using NumPy/SciPy


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

# Make example data
x = np.linspace(0,2.0,50)
y1 = x**0.5
y2 = x**1.5
y3 = x**0.2

# Plot data
fig, ax = plt.subplots(1,1,facecolor='white')
fig.subplots_adjust(right=0.8) # Make room for annotations
p1, = ax.plot(x, y1)
p2, = ax.plot(x, y2, '--')
p3, = ax.plot(x, y3, '-.')
pp = [p1, p2, p3]

# Get sort indices from last ydata
yp = np.array([y1[-1], y2[-1], y3[-1]])
s = np.argsort(yp)

# Create annotation locations (I've used axes fraction coordinates)
# and am assuming they are evenly spaced
a_posx = np.tile([1.1], 3)
a_posy = np.linspace(0,1,3)

# Map plot linestyles to terminology expected by an annotation FancyArrowPatch
ls = [p.get_linestyle() for p in pp]
lsmap = {'-':'solid', '--':'dashed', ':':'dotted', '-.':'dashdot'}
als = map(lsmap.get, ls)

# Annotate
for i in s:
    ax.annotate('Plot Y%d' % s[i], [x[-1], yp[s[i]]], [a_posx[i], a_posy[i]],
                textcoords='axes fraction',
                arrowprops=dict(arrowstyle='-', edgecolor=pp[s[i]].get_color(),
                                linestyle=als[s[i]]))

plt.show()

rawDescription: matplotlib legend that is ordered by the last Y values, and have lines from the last plot point to the legend

description: Matplotlib legend that is ordered by the last Y values, and have lines from the last plot point to the legend


code:
with open("file1.txt", 'r') as in_file, open("file2.txt", 'a') as out_file:
    for lines in in_file:
        line = lines.strip()
        # Perform some operation
        out_file.write(line)
        out_file.write('\r\n')

rawDescription: Better approach for reading/writing files in python?


code:
def replace_in_file(filename, key, new_value):
    f = open(filename, "r")
    lines = f.readlines()
    f.close()
    for i, line in enumerate(lines):
        if line.split('=')[0].strip(' \n') == key:
            lines[i] = key + ' = ' + new_value + '\n'
    f = open(filename, "w")
    f.write("".join(lines))
    f.close()

replace_in_file("file.txt", 'db_host', "7777")

rawDescription: write and Replace particular line in file

description: Write and Replace particular line in file


rawDescription: Second for loop is ignored when I iterate through a file


code: u'string' == 'string'

rawDescription: How to compare u'string' and 'string'?

description: Compare u'string' and 'string'


code:
from project.apps.tracks.models import Track
# import for slugify

def process_slug():
    """ Populate slug field, if they are empty.
    """
    for track in Track.objects.all():
        if not track.slug:
            slug = slugify("%s - %s" % (track.name, track.artist))
            track.slug = slug
            track.save()

rawDescription: Django script add field to database

description: Django script add field to database


code:
def main():
    while True:
        try:
            interest_rate = int(input("Please enter an interest rate: "))
            if interest_rate > 10:
                confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
                if confirm =="y":
                    break
            elif 0 <= interest_rate < 10:
                break
        except ValueError:
            print("Entered value is not a number! ")
    return interest_rate

main()

rawDescription: Python Nested Loop Enter Value and Confirm Answer


code:
def mk_int(s):
    s = s.strip()
    return int(s) if s else 0

rawDescription: How to make "int" parse blank strings?

description: Make "int" parse blank strings


rawDescription: MongoDB: How to determine is specific value does not exist


code:
import xml.etree.ElementTree as ET
import re

def extractTextFromElement(elementName, stringofxml):
    tree = ET.fromstring(stringofxml)
    for child in tree.getiterator():
        if child.tag == elementName:
            len = ET.tostring(child)
            return re.sub(r'<.*?>', '', len)

usage: extractTextFromElement('tag2', XML_data)

rawDescription: Python minidom XML parser - ignore child tags


rawDescription: Convert dictionary to bytes and back again python?


code:
import signal
signal.signal(signal.SIGCHLD, lambda _x,_y: os.wait())

rawDescription: python/django spawn background process and avoid zombie process

description: Python/django spawn background process and avoid zombie process


code:
import subprocess
result = subprocess.Popen("./compile_cmd.sh")
text = result.communicate()[0]
returncode = result.returncode

rawDescription: How to get the exit status set in a shell script in python

description: Get the exit status set in a shell script in python


code:
class HackerNewsLinks(Model):
    """
    A test model that uses a global secondary index
    """
    class Meta:
        region = 'us-west-1'
        table_name = 'HackerNews'
    link = UnicodeAttribute(hash_key=True)
    title = UnicodeAttribute()
    days_index = DaysIndex()
    days_old = NumberAttribute(default=0)

rawDescription: Pynamodb - how to set the region?

description: Pynamodb - how to set the region


code:
from xml.dom.minidom import Document
import copy
import re
from collections import OrderedDict

class d2x:
    ''' Converts Dictionary to XML '''
    def __init__(self, structure):
        self.doc = Document()
        if len(structure) == 1:
            rootName = str(structure.keys()[0])
            self.root = self.doc.createElement(rootName)
            self.doc.appendChild(self.root)
            self.build(self.root, structure[rootName])

    def build(self, father, structure):
        if type(structure) == dict:
            for k in structure:
                tag = self.doc.createElement(k)
                father.appendChild(tag)
                self.build(tag, structure[k])
        elif type(structure) == OrderedDict:
            for k in structure:
                tag = self.doc.createElement(k)
                father.appendChild(tag)
                self.build(tag, structure[k])

        elif type(structure) == list:
            grandFather = father.parentNode
            tagName = father.tagName
            grandFather.removeChild(father)
            for l in structure:
                tag = self.doc.createElement(tagName)
                self.build(tag, l)
                grandFather.appendChild(tag)

        else:
            data = str(structure)
            tag = self.doc.createTextNode(data)
            father.appendChild(tag)

    def display(self):
        # I render from the root instead of doc to get rid of the XML header
        #return self.root.toprettyxml(indent="  ")
        return self.root.toxml()

class SolaceNode:
    ''' a sub dictionary builder '''
    def __init__(self):
        self.__dict__ = OrderedDict()
    def __getattr__(self, name):
        name = re.sub("_", "-", name)
        try:
            return self.__dict__[name]
        except:
            self.__dict__[name] = SolaceNode()
            return self.__dict__[name]
    def __str__(self):
        return str(self.__dict__)
    def __repr__(self):
        return str(self.__dict__)
    def __call__(self, *args, **kwargs):
        return self.__dict__
    def __setattr__(self, name, value):
        name = re.sub("_", "-", name)
        self.__dict__[name] = value

class SolaceXMLBuilder(object):
    ''' main dictionary builder

    Any dot-name-space like calling of a instance of SolaceXMLBuilder will create
    nested dictionary keys. These are converted to XML whenever the instance
    representation is called ( __repr__ )

    Example

    a=SolaceXMLBuilder()
    a.foo.bar.baz=2
    str(a)
    '<rpc semp-version="soltr/5_5">\n<foo><bar><baz>2</baz></bar></foo></rpc>'

    '''
    def __init__(self):
        self.__dict__ = OrderedDict()
        self.__setattr__ = None
    def __getattr__(self, name):
        name = re.sub("_", "-", name)
        try:
            return self.__dict__[name]
        except:
            self.__dict__[name] = SolaceNode()
            return self.__dict__[name]
    def __repr__(self):
        # Show XML
        myxml = d2x(eval(str(self.__dict__)))
        # I had to conjur up my own header cause solace doesnt like </rpc> to have attribs
        #return str('<rpc semp-version="soltr/5_5">\n%s</rpc>' % myxml.display())
        return str('<rpc semp-version="soltr/5_5">\n%s</rpc>' % myxml.display())
    def __call__(self, *args, **kwargs):
        return self.__dict__
    # def __setattr__(self, name, value):
    #   raise Exception('no you cant create assignments here, only on sub-elements')

if __name__ == '__main__':
    x = SolaceXMLBuilder()
    x.create.message_vpn.vpn_name='NEWVPN'
    print(x)

    # <?xml version="1.0" ?>
    # <rpc semp-version="soltr/5_5">
    #   <create>
    #     <message-vpn>
    #       <vpn-name>
    #         NEWVPN
    #       </vpn-name>
    #     </message-vpn>
    #   </create>
    # </rpc semp-version="soltr/5_5">

    x=SolaceXMLBuilder()
    x.message_vpn.vpn_name='NEWVPN'
    x.message_vpn.no.feature_X
    print(x)

    # <?xml version="1.0" ?>
    # <rpc semp-version="soltr/5_5">
    #   <message-vpn>
    #     <vpn-name>
    #       NEWVPN
    #     </vpn-name>
    #     <no>
    #       <feature-X/>
    #     </no>
    #   </message-vpn>
    # </rpc semp-version="soltr/5_5">

    # >>> client = SolaceAPI('pt1')
    # >>> xml = SolaceXMLBuilder()
    # >>> xml.create.message_vpn.vpn_name='NEWVPN'
    # >>> client.rpc(str(xml))
    # {u'rpc-reply': {u'execute-result': {u'@code': u'ok'}, u'@semp-version': u'soltr/5_5'}}

rawDescription: Python XML dot name constructor

description: Python XML dot name constructor


code:
with open('testreview.txt', 'w') as fid:
    for review in resultsoup:
        review_list = review.get_text()
        fid.write(unidecode(review_list))

rawDescription: Scraping and saving tripadvisor reviews - using beautifulsoup, get_text() on python 3


code:
import os

BASEDIR = "f:\\dir"

#build list of inputs
Inraster = []
for year in range (1983, 2014):
    for month in range(1, 13):
        fname = "ref{:04d}_{:02d}.tif".format(year, month)
        # is there actually a file by this name?
        if os.path.isfile(os.path.join(BASEDIR, fname)):
            Inraster.append(fname)

rawDescription: Creating an 'or' statement in a list Python


code:
while True:
  sys.stdout.write('\rfoo.  ')
  sys.stdout.flush()
  delay(100)
  sys.stdout.write('\rfoo.. ')
  sys.stdout.flush()
  delay(100)
  sys.stdout.write('\rfoo...')
  sys.stdout.flush()
  delay(100)

rawDescription: How can I show never ending dots ("...") in a while loop

description: Show never ending dots ("...") in a while loop


code:
# turn strings into datetimes
date_format = "%Y-%m-%d %H:%M:%S"
for row in data:
    row[1] = datetime.datetime.strptime(row[1], date_format)

split_dt = datetime.timedelta(minutes=5)
dts = (d1[1]-d0[1] for d0, d1 in zip(data, data[1:]))
split_at = [i for i, dt in enumerate(dts, 1) if dt >= split_dt]
groups = [data[i:j] for i, j in zip([0]+split_at, split_at+[None])]

rawDescription: Clustering / Grouping a list based on time (python)


code:
wanted = set(['123', '789'])

with open("inputfile.txt",'r') as infile, open("outfile.txt",'w') as outfile:
    for line in infile:
        if line.startswith('NUM,'):
            UNIT = line.strip().split(',')[1]
            if UNIT not in wanted:
                for _ in xrange(4):
                    infile.next()
                continue

        outfile.write(line)

rawDescription: Deleting certain line of text file in python


code: canvas.create_text(x, y, width=80)

rawDescription: Python/Tkinter: Version of Canvas create_text() that supports word wrap


code: thecookie.output(None, '')

rawDescription: Cookies and HTTP with Python

description: Cookies and HTTP with Python


code:
class SamplemodAdmin(admin.ModelAdmin):
   pass
admin.site.register(Samplemod, SamplemodAdmin)

rawDescription: Registering a model in Admin page

description: Registering a model in Admin page


code:
import os
import fileinput

path = r'C:\Users\Data'
files = [os.path.join(path,data_file) for data_file in sorted(os.listdir(path))]

times = []
yvals = []

f = fileinput.input(files=files)
for line in f:
    if 11 <= f.filelineno() <= 21:
        columns = line.split('\t')
        times.append(column[0])
        yvals.append(column[1])
f.close()

rawDescription: Python: To read files from a folder according to the date as specified on the filename and sort


code:
from PIL import Image
from PIL import ImageDraw
import random as rnd
import numpy as np
import matplotlib.pyplot as plt

N = 60000
s = (500, 500)

im = Image.new('RGBA', s, (255,255,255,255))
draw = ImageDraw.Draw(im)

for i in range(N):
    x1 = rnd.random() * s[0]
    y1 = rnd.random() * s[1]
    x2 = rnd.random() * s[0]
    y2 = rnd.random() * s[1]
    alpha = rnd.random()
    color  = (int(rnd.random() * 256), int(rnd.random() * 256), int(rnd.random() * 256), int(alpha * 256))
    draw.line(((x1,y1),(x2,y2)), fill=color, width=1)

plt.imshow(np.asarray(im),
           origin='lower')
plt.show()

rawDescription: Matplotlib: Plotting numerous disconnected line segments with different colors


code:
import numpy as np
a = np.eye(1000)
a[::200, ::200]

rawDescription: subsampling a numpy array?

description: Subsampling a numpy array


code:
class Customer(models.Model):
    name = models.CharField(max_length=64)
    myid = models.CharField(primary_key=True, max_length=64)

rawDescription: Django return specific field from model as foreign key


code:
def kron(a, b):
    if hasattr(a, '__kron__'):
        return a.__kron__(b)
    if hasattr(b, '__rkron__'):
        return b.__rkron__(a)
    # Default kron implementation here
    return complex_operation_on_a_and_b(a, b)

rawDescription: Defining "overloaded" functions in python


rawDescription: Randomly picking numbers from a list according to a uniform distribution


code: from django.template.loader import render_to_string

rawDescription: Django Html email adds extra characters to the email body


code:
def invert_int(n):
    number_bit_len = n.bit_length()
    max_val = (2 ** number_bit_len) - 1
    return ~n & max_val

rawDescription: Python invert a number

description: Python invert a number


code: x[np.arange(x.shape[0]), :, y]

rawDescription: How to select values in a n-dimensional array

description: Select values in a n-dimensional array


code:
from collections import Mapping, Sequence
isinstance('ac', Sequence)
isinstance('ac', Mapping)
isinstance({3:42}, Mapping)
isinstance({3:42}, Sequence)

rawDescription: How to distinguish between a sequence and a mapping

description: Distinguish between a sequence and a mapping


code:
import itertools
for line in itertools.islice(file, None, None, n):
    do_whatever_with(line)

rawDescription: Slicing in python, advancing n lines after a line is copied and used


code:
@fproject.route('/save', methods=['POST'])
def save():
    global table

    text.append(request.form['name'])
    text.append(request.form['dimensions'])
    text.append(request.form['weight'])
    text.append(request.form['status'])
    add_package.add_package_values(text)
    add_package.add_package_to_db(new_package)
    table = populate_table(table)

    return redirect(url_for('index'))

rawDescription: Flask: How to update HTML table with data from SQLite on homepage after data are saved into db from subpage?


code: set (A,B) == set (B, A)

rawDescription: "Undirected" tuple comparison

description: "Undirected" tuple comparison


code:
import dis
TheString = "k=abs(x)+y"
Binary = compile( TheString , "<string>" , "exec" )
dis.dis(Binary)

rawDescription: python: how to get the source from a code object?

description: Python: how to get the source from a code object


code:
controllerIpAddr = "127.0.0.1"
controllerPort = "6633"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((controllerIpAddr, controllerPort))

rawDescription: How to bind Pox with my program

description: Bind Pox with my program


code:
x = lambda: magic
x.foo = 1
x.bar = 2

rawDescription: Easiest way to create a object that can take custom atttributes in python


code:
import glob

list_of_files = glob.glob('./*.txt')

with open("stripD.xls", "w") as fout:
    for fileName in list_of_files:
        data_list = open( fileName, "r" ).readlines()
        fout.write(data_list[17])
        fout.writelines(data_list[44:])

rawDescription: reading from multiple txt files - strip data and save to xls

description: Reading from multiple txt files - strip data and save to xls


code:
start = time.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S')
start = datetime.datetime(*start[:6])

rawDescription: Subtract SQL DATETIME from datetime.now() in Python


rawDescription: Django ManyToMany Query intersection

description: Django ManyToMany Query intersection


code:
from poster.encode import MultipartParam

files["image"]= MultipartParam("image", filename=memfile.name, filetype=memfile.content_type, fileobj=memfile.file)

rawDescription: Post an InMemoryUploadedFile from a file input field to another external server


code:
import numpy

randoms = numpy.random.random((1043, 261))

covs = [numpy.cov(randoms) for _ in range(10)]
all((c==covs[0]).all() for c in covs)
#>>> True

rawDescription: Covariance Matrix calculated by Python Numpy change every time


code:
def bar(x):
    def f(y):
        f.x=f.x+1
        return (f.x, y)
    f.x=x
    return f

rawDescription: Create a functor as a callable class or as a nested function


code:
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtNetwork
from PyQt4 import QtWebKit

class PDFViewer(QtWebKit.QWebView):
    pdf_viewer_page = 'res/pdf-viewer.html'

    def __init__(self, parent=None):
        super().__init__(parent)
        self.settings = QtWebKit.QWebSettings.globalSettings()
        self.settings.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessFileUrls, True )
        self.settings.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, True )
        self.settings.setAttribute(QtWebKit.QWebSettings.DeveloperExtrasEnabled, True )
        nam = QtNetwork.QNetworkAccessManager()
        page = QtWebKit.QWebPage(self)
        page.setNetworkAccessManager(nam)
        self.setPage(page)
        self.loadFinished.connect(self.onLoadFinish)
        self.setUrl(QtCore.QUrl(self.pdf_viewer_page))

    def onLoadFinish(self, success):
        if success:
            self.page().mainFrame().evaluateJavaScript("init();")

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    viewer = PDFViewer(parent=None)
    viewer.show()
    sys.exit(app.exec_())

rawDescription: How to Rendering PDF using pdf.js viewer in pyqt webkit


code:
json.loads('[1, 2, "dog"]')
json.loads('{"animals": ["cat", "dog"], "4": 4}')
json.loads('"dog"')

rawDescription: simplejson documentation?

description: Simplejson documentation


code:
def generate_timeline(file):
    for line in file:
         time1 = extract_time_from_line(line)
         yield time1, line

for (time1, line) in heapq.merge(generate_timeline(file1), generate_timeline(file2)):
    process(line)

rawDescription: Using generators to read two files in time priority


code:
import wx

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

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

        lbl = wx.StaticText(self, label="Enter text to copy to clipboard:")
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        copyBtn = wx.Button(self, label="Copy")
        copyBtn.Bind(wx.EVT_BUTTON, self.onCopy)
        copyFlushBtn = wx.Button(self, label="Copy and Flush")
        copyFlushBtn.Bind(wx.EVT_BUTTON, self.onCopyAndFlush)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(lbl, 0, wx.ALL, 5)
        sizer.Add(self.text, 1, wx.EXPAND)
        sizer.Add(copyBtn, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(copyFlushBtn, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def onCopy(self, event):
        """"""
        self.dataObj = wx.TextDataObject()
        self.dataObj.SetText(self.text.GetValue())
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.dataObj)
            wx.TheClipboard.Close()
        else:
            wx.MessageBox("Unable to open the clipboard", "Error")

    #----------------------------------------------------------------------
    def onCopyAndFlush(self, event):
        """"""
        self.dataObj = wx.TextDataObject()
        self.dataObj.SetText(self.text.GetValue())
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.dataObj)
            wx.TheClipboard.Flush()
        else:
            wx.MessageBox("Unable to open the clipboard", "Error")

        self.GetParent().Close()

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

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Clipboard Tutorial")
        panel = ClipboardPanel(self)
        self.Show()

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

rawDescription: Clipboard.Flush() always fails in wxpython app


code:
l = [1, 3, 2, 5, 4, None, 7]
sorted(l, key=lambda x: (x is None, x))

rawDescription: Python sort list with None at the end

description: Python sort list with None at the end


code: lnew = lold[:]

rawDescription: List and append elements

description: List and append elements


code:
a = 1
def test(b):
    return b*10
c = a or test(2)
c
a = 0
c = a or test(2)
c

rawDescription: Python conditional variable assignment

description: Python conditional variable assignment


code:
child.logfile_read = sys.stdout
child.sendline(command)
child.expect(COMMAND_PROMPT)

rawDescription: Writing and reading stdout unbuffered to a file over SSH


code:
import json
from django.core.serializers.json import DjangoJSONEncoder

...

def graph(request):
    queryset = MeterReading.objects.filter(user=request.user).values()
    data = json.dumps(list(queryset), cls=DjangoJSONEncoder)
    ...

rawDescription: Pull only a JSON serializable part of a DateTimeField into a queryset?


code: slice = myarray[...,i]

rawDescription: Numpy slice of arbitrary dimensions

description: Numpy slice of arbitrary dimensions


code:
myprod1 = itertools.product(param1, zip(param2, param2_description)) # remark: replaced the dataframes simply by letters
list(myprod1)

rawDescription: Python: associating a description to each combination of itertools.product


code: cursor.execute('SELECT * FROM songs WHERE filename LIKE ?', ('{}%'.format(key_string),))

rawDescription: python sqlite3: How to use LIKE and ? to do partial matching?

description: Python sqlite3: How to use LIKE and ? to do partial matching


code: c = repeat(b, a)

rawDescription: Create new array with array elements/amounts set by two other arrays in Python


code:
if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore('sessions'), {'count': 0})
    web.config._session = session
else:
    session = web.config._session

rawDescription: `web.py` sessions with Apache2

description: `web.py` sessions with Apache2


code:
import random

# random.choice is a convenient method
possible_choices = ["Scissors", "Paper", "Rock"]
random_choice = random.choice(possible_choices)

# set notation, valid since Python 2.7+ and 3.1+ (thanks Nick T)
winning = {("Scissors", "Paper"), ("Paper", "Rock"), ("Rock", "Scissors")}

player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in possible_choices:
      print("Not valid choice.")
      raw_input()

if player_input == random_choice:
      print("You both choose %s" % random_choice)
elif (player_input, random_choice) in winning:
      print("You picked %s and the bot picked %s, you win!" % (player_input, random_choice))
else:
      print("You picked %s and the bot picked %s, you lose!" % (player_input, random_choice))

raw_input()

rawDescription: Python - Scissors, paper and rock game

description: Python - Scissors, paper and rock game


code:
db.foo.month.requires = IS_IN_DB(db, 'month.id', db.month._format,
                                 orderby=db.month.id)

rawDescription: How to set default orderby in a web2py table?

description: Set default orderby in a web2py table