code:
from collections import defaultdict
d = defaultdict(list)
for i,j in enumerate(x):
    d[j].append(i)

rawDescription: Python: build dictionary from list

description: Python: build dictionary from list


code:
form = SQLFORM.factory(db.table1, db.table2)
if form.process().accepted:
    invoice_id = db.table.insert(**db.table1._filter_fields(form.vars))
    form.vars.invoice_id = invoice_id
    db.table2.insert(**db.table2._filter_fields(form.vars))

rawDescription: web2py multiple form

description: Web2py multiple form


code:
entries = []
with open('data') as input:
    for line in input:
        entries.append(line.strip().split('\t'))

tableWidget.setRowCount(len(entries))
tableWidget.setColumnCount(len(entries[0]))

for i, row in enumerate(entries):
    for j, col in enumerate(row):
        item = QTableWidgetItem(col)
        tableWidget.setItem(i, j, item)

rawDescription: Python - PyQt - QTable Widget - adding rows


code:
wrapped_list = np.empty((3,),dtype=object)
wrapped_list[:] = my_list2

rawDescription: How to create a numpy _object_ array of other numpy arrays of same and different length?

description: Create a numpy _object_ array of other numpy arrays of same and different length


code:
import os, sys

path_python_exec = sys.executable
path_exec_file = ''

command = '%s %s'%(path_python_exec, path_exec_file)
os.system(command)

rawDescription: How to add .py script to run on another py (python)

description: Add .py script to run on another py (python)


code:
def load_data_folder(self):
    folder = QtWidgets.QFileDialog.getExistingDirectory(self)
    self.df = pvi.import_folder(folder)

rawDescription: pyqt - loading user data, how to avoid using global variable?

description: Pyqt - loading user data, how to avoid using global variable


code:
c=input("Size: ")
while int(c)>100 or int(c)<1:
    #Will repeat until the number is between 1 and 100, inclusively.
    #It will skip the loop if the value is between 1 and 100.

    print ("Size: "+c)
    print ("Invalid input. Try again.")
    c=input("Size: ")

#once the loop is completed, the code following the loop will run
print ("Size: "+c)

rawDescription: While loop user input in range

description: While loop user input in range


code:
from collections import Counter
x=[1,1,2,1,5,2,1,3]
c = Counter(x)
number_of_ones = c[1]  # returns 4
number_of_twos = c[2]  # returns 2

rawDescription: How can you use the values you get from the Counter class in python?

description: Use the values you get from the Counter class in python


rawDescription: Cannot pass arguments from the tkinter widget.after function


code:
class Hangmanner:
    correct_word = ''
    current_guess = ''

    def play_hangman(self, word):
        self.correct_word = word

        self.current_guess = '_' * len(self.correct_word)

        while self.current_guess != self.correct_word:
            self.guess_letter(input("Please guess a letter: "))

    def guess_letter(self, guessed_letter):
        for i in range(len(self.correct_word)):
            if self.correct_word[i] == guessed_letter:
                if i == 0:
                    self.current_guess = self.correct_word[i] + self.current_guess[1:]
                else:
                    self.current_guess = self.current_guess[:i] + self.correct_word[i] + self.current_guess[i + 1:]
        print(self.current_guess)

if __name__ == "__main__":
    hangmanner = Hangmanner()
    hangmanner.play_hangman("test")

rawDescription: Implementing a hangman function in Python


code:
from sympy import *
init_printing()
x = symbols('x')
singularities(1/(x**2 - 1), x)

rawDescription: Is there a simple way to get all discontinuities of a function in a certain domain with sympy?


code:
for x in os.listdir(dir):
    if x.endswith(fext):
        filename = os.path.join(dir, x)
        # do your stuff here

rawDescription: how to search for file's has a known file extension like .py?

description: Search for file's has a known file extension like .py


rawDescription: in python how do I decompose a rotation matrix to a quaternion? (preferrably using the euclid library)

description: In python how do I decompose a rotation matrix to a quaternion? (preferrably using the euclid library)


code:
mylist=[1,2,3,4]
print("Orginal list L=", mylist)
n=len(mylist)
l1=[]
l2=[]

for i in range(1, n+1):
    l1.append(mylist[0:i])
    l2.append(mylist[-i:])
print("L1=", l1)
print("L2=", l2)

rawDescription: list within a list

description: List within a list


code:
df = df.reset_index()
df['b'] = df['b'].fillna('dummy')
df['dummy'] = np.nan
df
df.pivot_table(rows=['a', 'b'], values=['c', 'd', 'e'], aggfunc=sum)
df.pivot_table(rows=['a', 'b'], values=['c', 'd', 'e'], aggfunc=sum).reset_index().replace('dummy',np.nan).set_index(['a','b'])

rawDescription: python pandas: pivot_table silently drops indices with nans

description: Python pandas: pivot_table silently drops indices with nans


code:
len_xaxis,len_yaxis = 5.,5. #fix here your numbers

xspace, yspace = .9, .9 # change the size of the void border here.

x_fig,y_fig = len_xaxis / xspace, len_yaxis / yspace
figure(figsize=(x_fig,y_fig))
plt.subplots_adjust(left=1-xspace, right = xspace, top=yspace, bottom = 1-yspace)
plot([1,2,3],[-1,3,5])

rawDescription: make axes the same length in matplotlib pyplot

description: Make axes the same length in matplotlib pyplot


code:
import os

webString = "http://www.google.com/"
os.system("open "+webString)

rawDescription: Use Python script to output string?

description: Use Python script to output string


code:
import struct
for i in range(0xffffffffffffffff + 1):
     with open('out{:d}'.format(i), 'wb') as f:
         f.write(struct.pack('Q', i))

rawDescription: How to create sequence of binary file in python3?

description: Create sequence of binary file in python3


code:
import sys
import os
try:
    import test_data
except ImportError:
    sys.path.append(os.path.dirname(__file__))
    try:
        import test_data
    finally:
        sys.path.remove(os.path.dirname(__file__))

rawDescription: ImportError: No module named test_data, but test_data.py in same directory as test.py under PyCharm using virtualenv


rawDescription: Split list of tuples where second elment is greater than threshold


code:
font = ImageFont.truetype("arial.ttf", 50)

def criacao(nome):
    base = Image.open("generico/Certificado.png")     # move this line from above
    draw = ImageDraw.Draw(base)                       # this one too

    nome_arquivo = str(datetime.date.today()) + " " + nome[0].upper() + nome[1:len(nome)].lower() + " " + curso
    draw.text((750,1065), nome.upper(), font=font, fill=(0,0,0,0))
    draw.text((750,1414), curso.upper(), font=font, fill=(0,0,0,0))
    draw.text((1220,1625), inicio, font=font, fill=(0,0,0,0))
    draw.text((1500,1625), fim, font=font, fill=(0,0,0,0))
    draw.text((1540,1750), horas + ".", font=font, fill=(0,0,0,0))
    draw.text((1740,2130), str(datetime.date.today()), font=font, fill=(0,0,0,0))
    draw.text((1550,2680), professor, font=font, fill=(0,0,0,0))
    base.save("Criado/" + nome_arquivo + ".png")

rawDescription: Itinerating picture editting in Python

description: Itinerating picture editting in Python


code:
from matplotlib import pyplot as plt, gridspec, lines

import numpy as np

grid = gridspec.GridSpec(1,1)
ax = plt.subplot(grid[0,0])

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

ax.plot(x, y, '-', color = 'black', linewidth = 5)
ax.plot(x, y, '--', color = 'lawngreen', linewidth = 5)

dotted_line1 = lines.Line2D([], [], linewidth=5, linestyle="--", dashes=(10, 1), color='lawngreen')
dotted_line2 = lines.Line2D([], [], linewidth=5, linestyle="-", dashes=(5, 4), color='black')

plt.legend([(dotted_line1, dotted_line2)], ["My Line"])
plt.show()

rawDescription: How to get alternating colours in dashed line using matplotlib?

description: Get alternating colours in dashed line using matplotlib


code: re.compile("Sent from my (iPhone|iPod)")

rawDescription: Python regular expressions OR

description: Python regular expressions OR


code: from __future__ import absolute_import

rawDescription: Importing system modules in python

description: Importing system modules in python


rawDescription: How does one alter a FileField of an object in Django?

description: Alter a FileField of an object in Django


code:
import urllib.request
import urllib.parse

data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
data = data.encode('utf-8')
request = urllib.request.Request("http://requestb.in/xrbl82xr")

# adding charset parameter to the Content-Type header.
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")

f = urllib.request.urlopen(request, data)
print(f.read().decode('utf-8'))

rawDescription: Can't get Python 3 to transfer POST data to PHP


rawDescription: How to lock contents in wxTextCtrl?

description: Lock contents in wxTextCtrl


rawDescription: Convert rows into comma separated string in pandas


code:
from osv import fields, osv

class product_product(osv.osv):
    _name = "product.product"
    _inherit = "product.product"

    def _pvp(self, cr, uid, ids, field_name, arg, context=None):
        """Return calculated PVP with taxes
        """
        res = {}
        tax_obj = self.pool.get('account.tax')
        for product in self.browse(cr, uid, ids, context):
            t = tax_obj.compute_all(cr, uid, product.taxes_id, product.list_price, 1)['total_included']
            res[product.id] = "{0:.2f}".format(t)
        return res

    _columns = {
        'pvp': fields.function(_pvp, type="string", method=True, string="PVP"),  # calculates PVP with taxes
    }

product_product()

rawDescription: Retrieve products price with taxes in openerp report


code:
position_set = set()

while len(position_set) != 6:
    position = (random.randint(0,5), random.randint(0,5))
    position_set.add(position)

position_set

rawDescription: Is this loop method correct? Python 3.4.3


code:
from SortedCollection import SortedCollection
from operator import itemgetter
s = SortedCollection(key=itemgetter(0))
s.insert((1,2,'a'))
s.insert((10,20,'b'))
s.insert((20,30,'c'))
s.find_le(10)

rawDescription: 'Querying' a data structure in Python based on a datetime


code:
# ASSUMPTIONS: All IDs are valid and IDs are unique
# More defenses are necessary if either of these assumptions
# are not true.
failure_count = Thingy.objects.raw("""
    UPDATE Thingy
    SET failure_count = failure_count + 1
    WHERE id = %s
    RETURNING failure_count;
""", [thingy_id])[0].failure_count

if failure_count == THRESHOLD:
    issue_warning_for(thingy_id)

rawDescription: Increment a counter and trigger an action when a threshold is exceeded


rawDescription: Python sum trouble

description: Python sum trouble


rawDescription: Auto-escape special characters in vimscript


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

NANGLES = 200

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
nvals = [0, 2, 4, 10, 20, 40, 100]
for iy in range(len(nvals)):
    n = nvals[iy]
    x = np.arange(NANGLES) / float(NANGLES)
    y = np.ones(NANGLES)*iy # set y position to same value, with regular step
    z = np.sin(n*x*np.pi)
    ax.plot(x, y, z)
ax.set_ylabel('n')
ax.set_yticklabels(nvals) # update y ticks (set at regular step) to your vals

plt.savefig('stackedplot.png')
plt.show()

rawDescription: Stack of 2D plot

description: Stack of 2D plot


code:
from collections import defaultdict

users = defaultdict(dict)
users['John']['phone number'] = 123456

rawDescription: In Python, assign entries of dictionaries dynamically


code:
if any(x in s for x in range(1, 10)):
    print('yes')

rawDescription: How to check if a range of numbers supplied exist in a list? - Python

description: Check if a range of numbers supplied exist in a list? - Python


code:
num_list = ['A', 3452, 3487, 6534, 4521]
percents = [0.18, 0.22, 0.24, 0.36]
[num_list[0]] + [item * percent for item in num_list[1:] for percent in percents]

rawDescription: How to divide a number into multiple unequal parts in python?

description: Divide a number into multiple unequal parts in python


code:
images_schema: {
  "game_id": {
    "type": "string",
    "required": True,
  },
  "title": {
    "type": "string",
    "required": True,
  },
}

games = {
  "schema": {
    "title": {
      "type": "string",
      "required": True
    },
    "name": {
      "type": "string",
      "required": True
    },
  }
}

images = {
  "schema": images_schema,
  "url": "images"  # not really needed
}

games_images = {
  "schema": images_schema,
  "url": "games/<regex('[a-f0-9]{24}'):game_id>/images",
  "datasource": {"source": "images"}
}

rawDescription: In Eve, how can you make a sub-resource of a collection and keep the parent collections endpoint?


code:
import Tkinter as tk

firstclick = True

def on_entry_click(event):
    """function that gets called whenever entry1 is clicked"""
    global firstclick

    if firstclick: # if this is the first time they clicked it
        firstclick = False
        entry.delete(0, "end") # delete all the text in the entry

root = tk.Tk()

label = tk.Label(root, text="User: ")
label.pack(side="left")

entry = tk.Entry(root, bd=1)
entry.insert(0, 'Enter your user name...')
entry.bind('<FocusIn>', on_entry_click)
entry.pack(side="left")

root.mainloop()

rawDescription: How to insert a temporary text in a tkinter Entry widget?

description: Insert a temporary text in a tkinter Entry widget


code:
import wx

class Smiley(wx.PyControl):
    def __init__(self, parent, size=(50,50)):
        super(Smiley, self).__init__(parent,
                                     size=size,
                                     style=wx.NO_BORDER)

        self.InitBuffer()                   # new
        self.Bind(wx.EVT_SIZE, self.OnSize) # new
        self.Bind(wx.EVT_IDLE, self.OnIdle) # new

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

# new block
    def InitBuffer(self):
        self.client_size = self.GetClientSize()
        self.buffer = wx.EmptyBitmap(self.client_size.width, self.client_size.height)
        dc = wx.BufferedDC(None, self.buffer)
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        self.DrawImage(dc)
        self.reInitBuffer = False

    def OnSize(self, event):
        self.reInitBuffer = True

    def OnIdle(self, event):
        if self.reInitBuffer:
            self.InitBuffer()
            self.Refresh(False)

    def DrawImage(self, dc):

        # Get the working rectangle we can draw in
        rect = self.client_size

        # Find a square inside a rectangle (size of the client)
        min_side = min(rect.x, rect.y)
        rect.SetHeight(min_side)
        rect.SetWidth(min_side)

        # Setup the DC
        dc.SetPen(wx.BLACK_PEN) # for drawing lines / borders
        yellowbrush = wx.Brush(wx.Colour(255, 255, 0))
        dc.SetBrush(yellowbrush) # Yellow fill

        # Find the center and draw the circle
        cx = rect.width / 2
        cy = rect.width / 2
        radius = min(rect.width, rect.height) / 2
        dc.DrawCircle(cx, cy, radius)

        # Give it some square blue eyes
        # Calc the size of the eyes 1/8th total
        eyesz = (rect.width / 8, rect.height / 8)
        eyepos = (cx / 2, cy / 2)
        dc.SetBrush(wx.BLUE_BRUSH)
        dc.DrawRectangle(eyepos[0], eyepos[1],
                         eyesz[0], eyesz[1])
        eyepos = (eyepos[0] + (cx - eyesz[0]), eyepos[1])
        dc.DrawRectangle(eyepos[0], eyepos[1],
                         eyesz[0], eyesz[1])

        # Draw the smile
        dc.SetBrush(yellowbrush)
        startpos = (cx / 2, (cy / 2) + cy)
        endpos = (cx + startpos[0], startpos[1])
        dc.DrawArc(startpos[0], startpos[1],
                   endpos[0], endpos[1], cx, cy)

        # Draw a yellow rectangle to cover up the
        # unwanted black lines from the wedge part of
        # our arc
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(startpos[0], cy,
                         endpos[0] - startpos[0],
                         startpos[1] - cy)
# end of a new block

    def OnPaint(self, event):
        wx.BufferedPaintDC(self, self.buffer)

class SmileyApp(wx.App):
    def OnInit(self):
        self.frame = SmileyFrame(None,
                                 title="Drawing Shapes",
                                 size=(300,400))
        self.frame.Show()
        return True

class SmileyFrame(wx.Frame):
    def __init__(self, parent, *args, **kwargs):
        wx.Frame.__init__(self, parent, *args, **kwargs)

        # Attributes
        self.panel = SmileyPanel(self)

        # Layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.panel, 1, wx.EXPAND)
        self.SetSizer(sizer)

class SmileyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        # Layout
        self.__DoLayout()

    def __DoLayout(self):
        # Layout a grid of 4 smileys
        msizer = wx.GridSizer(2, 2, 0, 0)

        for x in range(4):
            smile = Smiley(self)
            msizer.Add(smile, 0, wx.EXPAND)

        self.SetSizer(msizer)

if __name__ == '__main__':
    app = SmileyApp(False)
    app.MainLoop()

rawDescription: wxPython: Dynamically drawn picture becomes broken

description: WxPython: Dynamically drawn picture becomes broken


code:
def nexmo_sendsms(api_key, api_secret, sender, receiver, body):
    """
    Sends a message using Nexmo.

    :param api_key: Nexmo provided api key
    :param api_secret: Nexmo provided secrety key
    :param sender: The number used to send the message
    :param receiver: The number the message is addressed to
    :param body: The message body
    :return: Returns the msgid received back from Nexmo after message has been sent.
    """

    msg = {
        'api_key': api_key,
        'api_secret': api_secret,
        'from': sender,
        'to': receiver,
        'text': body
    }
    nexmo_url = 'https://rest.nexmo.com/sms/json'
    data = urllib.parse.urlencode(msg)
    binary_data = data.encode('utf8')
    req = urllib.request.Request(nexmo_url, binary_data)
    response = urllib.request.urlopen(req)
    result = json.loads(response.readall().decode('utf-8'))
    return result['messages'][0]['message-id']

rawDescription: HTTPResponse object -- JSON object must be str, not 'bytes'


code: result = [os.path.join(root, file) for root, dir, files in os.walk(mydir) for file in files]

rawDescription: Iterating through individual files in os.walk in Python in an idiomatic fashion


code:
from math import log
pad = int(log(lim, 10)) # lim can't be 0

for i in range(lim, -1, -1):
    print('{num:<{pad}}|'.format(pad=pad, num=i))

rawDescription: How to dynamically pad output?

description: Dynamically pad output


code:
class AppointmentUpdateForm(wtf.Form):
    start_time = wtforms.DateField('Start at', [wtforms.validators.required()], widget=DatePickerWidget())
    end_time = wtforms.DateField('End at', [wtforms.validators.required()], widget=DatePickerWidget())

rawDescription: How to display a date_time field in jinja2 template? (flask)

description: Display a date_time field in jinja2 template? (flask)


code:
for key in dict1.keys():
  if key in dict2.keys():
    dict1[key].append(dict2[key])

rawDescription: Matching Python Dict

description: Matching Python Dict


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'ATOMIC_REQUESTS': True,
    }
}

rawDescription: How Django atomic requests works?

description: How Django atomic requests works


code:
from itertools import groupby
[len(list(g)) for k, g in groupby(s) if k == '1']

rawDescription: Replacing a string with counts of streaks


code:
def only_once(a):
  d = {}
  for i in a:
    d.setdefault(i,0)
    d[i] += 1
  return [i for i in a if d[i] == 1]

rawDescription: How to assign key from list for dictionary?

description: Assign key from list for dictionary


code:
from datetime import datetime
timeSlot.sort(key=lambda d: datetime.strptime(d['timeSlot'], '%I:%M %p'))
timeSlot

rawDescription: How do I sort a Python list of strftime('%I:%M %p') in django templates?

description: Sort a Python list of strftime('%I:%M %p') in django templates


code:
def lists_to_dyn(lst):
    return '|'.join(';'.join(','.join(lst3) for lst3 in lst2) for lst2 in lst)

rawDescription: Converting from nested lists to a delimited string


code:
import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    @cherrypy.tools.json_in()
    def observe(self, urlParam1=None):
        print(cherrypy.request.json)
        return ""

    @cherrypy.expose
    def asdf(self):
        return """<!DOCTYPE HTML>
                  <html>
                  <head>
                  <script>function Sendjson(){
                  // code for IE7+, Firefox, Chrome, Opera, Safari
                  if(window.XMLHttpRequest)
                      xmlhttp=new XMLHttpRequest();
                  else// code for IE5
                      xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');

                  xmlhttp.open("POST","/observe", true);
                  xmlhttp.setRequestHeader('Content-Type', 'application/json');
                  xmlhttp.send(JSON.stringify(({name:"Bob"})));
                  }
                  </script>
                  </head>
                  <body onload="Sendjson();">
                  </body>
                  </html>"""

cherrypy.quickstart(HelloWorld())

rawDescription: 'Request' object has no attribute 'json'


code:
def read_file(filename):
    with open(filename, 'r') as f:
        return f.read()

def word_count(filename):
    d = {}
    words = read_file(filename).split()
    for word in words:
        if word in d:
            d[word] +=1
        else:
            d[word] = 1
    for keys,values in d.items():
        print(keys)
        print(values)

    return len(words)

rawDescription: How to add word frequency to my word count

description: Add word frequency to my word count


rawDescription: Regex to retrieve a substring with limited digits and unlimited special characters


code:
from mechanize import Browser

br = Browser()
br.open("http://www.coeweb.istat.it/predefinite/tutto_paese_merce.asp?livello=ATE07_AT2&riga=MERCE&territorio=S&AG=S")

br.select_form(nr=0)
br.find_control("XLS").items[0].selected = True
br.find_control("CODTERRITORIO").value = ["309048"]
response = br.submit()

with open("dataset.xls", "w") as xls_file:
    xls_file.write(response.read())

rawDescription: Compile web form and retrive a file with mechanize


code:
while list[0] == 0:
   list.pop(0)
while list[-1] == 0:
   list.pop()

rawDescription: Shortening a list

description: Shortening a list


code:
class Console(Frame):
    def __init__(self, master, **kwargs):
        Frame.__init__(self, master)
        self.text = Text(self, wrap='word', **kwargs)
        self.text.pack()
        self.text.config(state='disabled')
        self.sequence = ['-', '\\', '|', '/']
        self.load = False
        self.queue = Queue.Queue()
        self.update_me()
    def write(self, line, link=None):
        self.queue.put((line,link))
    def clear(self):
        self.queue.put((None, None))
    def update_me(self):
        try:
            while 1:
                line, link = self.queue.get_nowait()

                self.text.config(state='normal')
                if line is None:
                    self.text.delete(1.0, END)
                elif link and link == 'loader':
                    self.load = True
                    self.text.delete(self.text.index("end-2c"))
                    self.text.insert(self.text.index("end-1c"), str(line))
                else:
                    if self.load:
                        self.text.delete(self.text.index("end-2c"))
                        self.text.insert(self.text.index("end-1c"), str(line))
                    else:
                        self.text.insert(END, str(line))
                    self.load = False
                self.text.see(END)
                self.update_idletasks()
                self.text.config(state='disabled')
        except Queue.Empty:
            pass
        self.after(100, self.update_me)
        if self.load:
            self.queue.put((self.sequence[0], 'loader'))
            self.sequence.append(self.sequence.pop(0))

if __name__ == '__main__':
    # testing application
    import time
    root = Tk()
    console = Console(root)
    console.pack()

    def load_it():
        console.write('Loading World...', 'loader')
        time.sleep(3)
        console.write('Done')

    import threading
    t = threading.Thread(target=load_it)
    t.daemon = True
    t.start()

    root.mainloop()
    exit()

rawDescription: How to create a "loading wheel" in a Tkinter Text widget?

description: Create a "loading wheel" in a Tkinter Text widget


code: samples = [math.sin(2.0 * math.pi * frequency * t / sample_rate) for t in xrange(0, duration_in_samples)]

rawDescription: Simple Pygame Audio at a Frequency

description: Simple Pygame Audio at a Frequency


code:
myStringIO.seek(0)
first = myStringIO.read(65536)
second = myStringIO.read(65536)

rawDescription: Iterate over IOString buffer in python

description: Iterate over IOString buffer in python


code:
class Rectangle:
    def __init__ (self, H=0, W=0):
        self.width = W
        self.height = H

    @property
    def area (self):
            return self.width * self.height

if __name__ == "__main__":
    a = Rectangle (5, 7)
    print ("Rectangle a.w: %s a.h: %s" % (a.width, a.height))
    b = Rectangle()
    b.width = 10
    b.height = 20
    print ("Rectangle b.w: %s b.h: %s" % (b.width, b.height))

rawDescription: Python help: OOP Rectangles

description: Python help: OOP Rectangles


rawDescription: Using map on every other list item Python


code:
class SomeModel(...):
  someconst = somevalue

rawDescription: Define class attribute for django model

description: Define class attribute for django model


code:
def find_pass(fname,target_title):
    with open(fname) as f:
        for ln in f:
            # some test to see if this is the line you want
            if ln.startswith(target_title):
                return ln[len(target_title):].strip()

rawDescription: Get a string from a file

description: Get a string from a file


code:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

#Random data
data = numpy.random.random((10, 10))

fig = plt.figure()

ax1 = fig.add_subplot(1,2,1, aspect = "equal")
ax2 = fig.add_subplot(1,2,2, aspect = "equal", sharey = ax1)  #Share y-axes with subplot 1

#Set y-ticks of subplot 2 invisible
plt.setp(ax2.get_yticklabels(), visible=False)

#Plot data
im1 = ax1.pcolormesh(data)
im2 = ax2.pcolormesh(data)

#Define locations of colorbars for both subplot 1 and 2
divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes("right", size="5%", pad=0.05)

divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("right", size="5%", pad=0.05)

#Create and remove the colorbar for the first subplot
cbar1 = fig.colorbar(im1, cax = cax1)
fig.delaxes(fig.axes[2])

#Create second colorbar
cbar2 = fig.colorbar(im2, cax = cax2)

#Adjust the widths between the subplots
plt.subplots_adjust(wspace = -.059)

plt.show()

rawDescription: 2 subplots sharing y-axis (no space between) with single color bar?


code:
def rgb(minimum, maximum, value):
    minimum, maximum = float(minimum), float(maximum)
    ratio = 2 * (value-minimum) / (maximum - minimum)
    b = int(max(0, 255*(1 - ratio)))
    r = int(max(0, 255*(ratio - 1)))
    g = 255 - b - r
    return r, g, b

rawDescription: Calculate RGB value for a range of values to create heat map


code:
def copyfileobj(fsrc, fdst, callback, length=16*1024):
    copied = 0
    while True:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)
        copied += len(buf)
        callback(copied)

rawDescription: Get progress back from shutil file copy thread


code:
import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)

rawDescription: Python: use mysqldb to import a MySQL table as a dictionary?


rawDescription: Work with tuples

description: Work with tuples


code:
class SuccessfulFeedbackForm(FeedbackFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(SuccessfulFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['was_satisifed'].initial = True

class UnsuccessfulFeedbackForm(FeedbackFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(UnsuccessfulFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['was_satisifed'].initial = False

rawDescription: Set value of field for Django ModelForm in CreateView


code:
def print_rect(l, w, c):
    for a in range(w):
        print(a*" ", l*c)

rawDescription: How to make a parallelogram on python

description: Make a parallelogram on python


rawDescription: Trying to find non-overlapping substrings that contain a specific subsequence


code:
def loop():
    db = sqlite3.connect('schedule.db')
    cur = db.cursor() # create a cursor
    cur.execute('DROP TABLE IF EXISTS schedule')
    cur.execute('CREATE TABLE schedule (hour int, minute int, second int, status text)')
    cur.execute('INSERT INTO schedule (hour,minute,second,status) VALUES (?,?,?,?)',(sche.get('hour'),sche.get('minute'),sche.get('second'),"yes"))
    db.commit()

    cur.close() # close cursor
    db.close() # close connection to sqlite3

    f = open('workfile', 'w')
    f.write('This is a test\n')
    f.close() # close file to write data

    loop1=1
    while ((now.minute >= minute_ON) and (now.minute < minute_OFF) and (loop1<stepping)):
        step()
        loop1=loop1+1

rawDescription: Webiopi (Raspberry pi) with sql or sqlite


code:
from itertools import chain
[x[1] for x in sorted(chain.from_iterable(sample_lists), key=lambda x:int(x[0]))]

rawDescription: Sorting strings with integer values in python


code:
args1 = [u's3://us-east-1.elasticmapreduce/libs/hive/hive-script',
         u'--base-path',
         u's3://us-east-1.elasticmapreduce/libs/hive/',
         u'--install-hive',
         u'--hive-versions',
         u'0.7']
args2 = [u's3://us-east-1.elasticmapreduce/libs/hive/hive-script',
         u'--base-path',
         u's3://us-east-1.elasticmapreduce/libs/hive/',
         u'--hive-versions',
         u'0.7',
         u'--run-hive-script',
         u'--args',
         u'-f',
         s3_query_file_uri]
steps = []
for name, args in zip(('Setup Hive','Run Hive Script'),(args1,args2)):
    step = JarStep(name,
                   's3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar',
                   step_args=args,
                   #action_on_failure="CANCEL_AND_WAIT"
                   )
    #should be inside loop
    steps.append(step)
# Kick off the job
jobid = EmrConnection().run_jobflow(name, s3_log_uri,
                                   steps=steps,
                                   master_instance_type=master_instance_type,
                                   slave_instance_type=slave_instance_type,
                                   num_instances=num_instances,
                                   hadoop_version="0.20")

rawDescription: Python client support for running Hive on top of Amazon EMR


code:
sql = "INSERT INTO reading (series_no, time, api) VALUES ('test1', %s, %s)"
data = (current_time, api)
cur.execute(sql, data)
db.commit()

rawDescription: Why ser.readline data not appear in mysql?


rawDescription: What is the type of os.environ? and Why does it not support viewkeys method


code:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MinuteLocator

x = [16.7,16.8,17.1,17.4]
y = [15,17,14,16]
e = [0.8,1.2,1.1,0.9]
xtn = []
for t in x:
  h = int(t)
  m = int((t-int(t))*60)
  xtn.append(dt.datetime.combine(dt.date(2012,1,1), dt.time(h,m)))

def larger_alim( alim ):
  ''' simple utility function to expand axis limits a bit '''
  amin,amax = alim
  arng = amax-amin
  nmin = amin - 0.1 * arng
  nmax = amax + 0.1 * arng
  return nmin,nmax

plt.errorbar(xtn,y,yerr=e,fmt='+',elinewidth=2,capsize=0,color='k',ecolor='k')
plt.gca().xaxis.set_major_locator( MinuteLocator(byminute=range(0,60,10)) )
plt.gca().xaxis.set_major_formatter( DateFormatter('%H:%M:%S') )
plt.gca().set_xlim( larger_alim( plt.gca().get_xlim() ) )
plt.show()

rawDescription: Manually setting xticks with xaxis_date() in Python/matplotlib


code:
import re

string = """736.199070736:  LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0,
 0x0075007f,
 0x005500dd,
 0x000a00f5)"""

result = re.search(r'\(.*\)', string) # matches anything between parenthesis

result.group()

'(0, 0x0075007f, 0x005500dd,  0x000a00f5)'

rawDescription: How to print specific strings in python?

description: Print specific strings in python


code:
def pil_to_image(self, pil, alpha=True):
    """ Method will convert PIL Image to wx.Image """
    if alpha:
        image = apply( wx.EmptyImage, pil.size )
        image.SetData( pil.convert( "RGB").tostring() )
        image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
    else:
        image = wx.EmptyImage(pil.size[0], pil.size[1])
        new_image = pil.convert('RGB')
        data = new_image.tostring()
        image.SetData(data)
    return image

def image_to_pil(self, image):
    """ Method will convert wx.Image to PIL Image """
    pil = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
    pil.fromstring(image.GetData())
    return pil

rawDescription: Speed up image display

description: Speed up image display


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

x = np.arange(5)
y = np.exp(x)
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x, y)

z = np.sin(x)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x, z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis

rawDescription: How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

description: Tell Matplotlib to create a second (new) plot, then later plot on the old one


code:
import datetime

today = datetime.date.today()
Event.objects.filter(start__lt=today, end__gt=today)

rawDescription: Django: Filter objects by date range

description: Django: Filter objects by date range


code:
#!/usr/bin/env python

import cgi

form = cgi.FieldStorage()

lat = form.getvalue('lat')
lon = form.getvalue('lon')

with open('location.txt','wt') as f:
    if lat:
        f.write(lat)
    f.write("\n")
    if lon:
        f.write(lon)

f.close()

print( "Content-type: text/html\n\n")
print( """\

Test:

""")

rawDescription: Pass information out of html to python

description: Pass information out of html to python


code: np.triu_indices(4, 1)[1]

rawDescription: Generating 1d array of shrinking ranges in numpy


code:
[logger_qpid]
level=NOTSET
handlers=nullHandler
qualname=qpid
propagate=0

rawDescription: Disable logging for a particular package


rawDescription: Calculate from list of strings - Python

description: Calculate from list of strings - Python


rawDescription: Python: How do I format a number with a variable number of digits?


code:
import os
import glob

# Get full path for .root files
root_files = glob.glob('/your_path/*.root')

# Only get root file names
root_file_names = [os.path.basename(f) for f in glob.iglob('/your_path/*.root')]

rawDescription: How can I find files and then loop over them in Python?

description: Find files and then loop over them in Python


code:
from scilab import Scilab
sci = Scilab()
x = sci.rand(20, 20)
y = x*x.transpose()
y_inv = sci.inv(y)

rawDescription: Plot dictionary produced by Python program using Scilab


code:
from datetime import datetime
datetime.now()
A = ['ABC', 'PQR', 'XYZ']
f = open("test.dat", 'w')
f.writelines(list(u'\u27B3 '.encode('utf-8') + str(datetime.now().strftime("%H:%M:%S")) + ' - %s\n' % i for i in A))
f.close()

rawDescription: How to add timestamp to Python writelines()?

description: Add timestamp to Python writelines()


code:
print("Hello World!")
raw_input("Press Enter to Continue. . .: ")
print("\033[FX X X X X X X X X X X X X X X ");
#      ^^^^^^
#    move up
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#            overwrite by whatever you want

rawDescription: Press Enter to Continue. . . Then Delete Statement (Python)


rawDescription: Python: Get random value from a array dimension


code:
df
df.pivot(index="date1", columns="date2", values="A")

rawDescription: How to convert pandas dataframe to matrix and export to csv

description: Convert pandas dataframe to matrix and export to csv


code:
import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

rawDescription: Dynamically updating plot in matplotlib

description: Dynamically updating plot in matplotlib


code:
open("file.txt", 'w').write("one two three")
len(open("file.txt").read())

rawDescription: How does len function actually work for files?


rawDescription: How do I find common items from Python dictionary values?

description: Find common items from Python dictionary values


code:
import os

def get_files_by_file_size(dirname, reverse=False):
    """ Return list of file paths in directory sorted by file size """

    # Get list of files
    filepaths = []
    for basename in os.listdir(dirname):
        filename = os.path.join(dirname, basename)
        if os.path.isfile(filename):
            filepaths.append(filename)

    # Re-populate list with filename, size tuples
    for i in xrange(len(filepaths)):
        filepaths[i] = (filepaths[i], os.path.getsize(filepaths[i]))

    # Sort list by file size
    # If reverse=True sort from largest to smallest
    # If reverse=False sort from smallest to largest
    filepaths.sort(key=lambda filename: filename[1], reverse=reverse)

    # Re-populate list with just filenames
    for i in xrange(len(filepaths)):
        filepaths[i] = filepaths[i][0]

    return filepaths

rawDescription: Get files from Directory Argument, Sorting by Size


code:
import re
text = '(5a)'
match = re.search(r'\(?([0-9A-Za-z]+)\)?', text)
match.group(1)
text = '*(ab2**)'
match = re.search(r'\(?([0-9A-Za-z]+)\)?', text)
match.group(1)

rawDescription: Extracting alphanumeric substring from a string in python


code:
#Fibonacci number calculator function
def fib(n):
    if n==0:
        return 1
    elif n==1:
        return 1
    else:
        return fib(n-1)+fib(n-2)

rawDescription: "n." Fibonacci Number

description: "n." Fibonacci Number


code:
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, report_fit

def gauss(x, amp, cen, sigma):
    "basic gaussian"
    return amp*np.exp(-(x-cen)**2/(2.*sigma**2))

def gauss_dataset(params, i, x):
    """calc gaussian from params for data set i
    using simple, hardwired naming convention"""
    amp = params['amp_%i' % (i+1)].value
    cen = params['cen_%i' % (i+1)].value
    sig = params['sig_%i' % (i+1)].value
    return gauss(x, amp, cen, sig)

def objective(params, x, data):
    """ calculate total residual for fits to several data sets held
    in a 2-D array, and modeled by Gaussian functions"""
    ndata, nx = data.shape
    resid = 0.0*data[:]
    # make residual per data set
    for i in range(ndata):
        resid[i, :] = data[i, :] - gauss_dataset(params, i, x)
    # now flatten this to a 1D array, as minimize() needs
    return resid.flatten()

# create 5 datasets
x  = np.linspace( -1, 2, 151)
data = []
for i in np.arange(5):
    params = Parameters()
    amp   =  0.60 + 9.50*np.random.rand()
    cen   = -0.20 + 1.20*np.random.rand()
    sig   =  0.25 + 0.03*np.random.rand()
    dat   = gauss(x, amp, cen, sig) + np.random.normal(size=len(x), scale=0.1)
    data.append(dat)

# data has shape (5, 151)
data = np.array(data)
assert(data.shape) == (5, 151)

# create 5 sets of parameters, one per data set
fit_params = Parameters()
for iy, y in enumerate(data):
    fit_params.add( 'amp_%i' % (iy+1), value=0.5, min=0.0,  max=200)
    fit_params.add( 'cen_%i' % (iy+1), value=0.4, min=-2.0,  max=2.0)
    fit_params.add( 'sig_%i' % (iy+1), value=0.3, min=0.01, max=3.0)

# but now constrain all values of sigma to have the same value
# by assigning sig_2, sig_3, .. sig_5 to be equal to sig_1
for iy in (2, 3, 4, 5):
    fit_params['sig_%i' % iy].expr='sig_1'

# run the global fit to all the data sets
minimize(objective, fit_params, args=(x, data))
report_fit(fit_params)

# plot the data sets and fits
plt.figure()
for i in range(5):
    y_fit = gauss_dataset(fit_params, i, x)
    plt.plot(x, data[i, :], 'o', x, y_fit, '-')

plt.show()

rawDescription: Python and lmfit: How to fit multiple datasets with shared parameters?


code: dataset = pandas.io.parsers.read_table(my_file, sep='\t', index_col=0, dtype={'ChrA':'str'})

rawDescription: How to force pandas.io.parsers to set column-specific types

description: Force pandas.io.parsers to set column-specific types


code:
def makeArray():
    a = []
    for x in xrange(10):
        a.append(input("Please input the %d number: " % x))
    return a

def main():
    my_array = makeArray()
    print(my_array[2])
main()

rawDescription: How do I get this simple array to work? (Beginner level Python)

description: Get this simple array to work? (Beginner level Python)


code: {{ group.key.urlsafe }}

rawDescription: Google App Engine - updating an entity

description: Google App Engine - updating an entity


code:
names = ((x['name'][:6], x['name'][6:]) for x in json_content)
max(int(b) for a, b in names if a == 'Thomas' and b.isdigit())

rawDescription: Applying regexp and finding the highest number in a list


code:
Worklist[0]=('Read','Float','GagArray',200)
Worklist[1]=('Write','Int','Oiler',1)
Worklist[2]=('Wrtie','BOOL','Buckets',250)

GagArray = gobals()[Worklist[0][2]]

rawDescription: Putting the refence to an instance along with the instance in a list


code:
TEEG_EVENT_TAB1 = 1
TEEG_EVENT_TAB2 = 2

rawDescription: Implementing C's enum and union in python


code:
import json
a = {'foo': 'bar', 'hello': 'jello'}
json.dumps(a)
'{"foo": "bar", "hello": "jello"}'

rawDescription: Modifying a .py file within Python

description: Modifying a .py file within Python


rawDescription: How can I make the following text appear in my python program?

description: Make the following text appear in my python program


code:
# contents of config.py
THIS_URL = os.getenv('TEMP_URL', 'https://www.thisisatest.com')

# contents of test_*.py
...
def setUp(self):
    self.URL = config.THIS_URL

rawDescription: pytest: using fixtures in unittest setUp method

description: Pytest: using fixtures in unittest setUp method


code:
terms = [
    'The resource you are looking for has expired',
    'The resource is not available'
]

has_terms = any(term in content for term in terms)

rawDescription: python web scraping with scrapy spider

description: Python web scraping with scrapy spider


code:
if gzipped:
    source = Popen(["gunzip", "-c", "remotestorage/file.gz"], stdout=PIPE)
else:
    source = Popen(["cat", "remotestorage/file"], stdout=PIPE)
firstchar = source.stdout.read(1)
# "unread" the char we've just read
source = Popen([r"(printf '\x%02x' && cat)" % ord(firstchar)],
               shell=True, stdin=source.stdout, stdout=PIPE)

# Now feed the output to a filter or to a local file.
flocal = None
try:
    if firstchar == "@":
        filter = Popen(["filter", "localstorage/outputfile.fastq"],
                       stdin=source.stdout)
    else:
        flocal = open('localstorage/outputfile.stream', 'w')
        filter = Popen(["cat"], stdin=source.stdout, stdout=flocal)
    filter.communicate()
finally:
    if flocal is not None:
        flocal.close()

rawDescription: Peek into stream of Popen pipeline in Python


code:
def gradient(img, dx, dy, ksize):
    deriv_filter = cv2.getDerivKernels(dx=dx, dy=dy, ksize=ksize, normalize=True)
    return cv2.sepFilter2D(img, -1, deriv_filter[0], deriv_filter[1])

rawDescription: How to normalize OpenCV Sobel filter given kernel size

description: Normalize OpenCV Sobel filter given kernel size


code:
results = []
res = { "next_page": "magic_token_to_get_first_page" }
while "next_page" in res:
    fp = urllib2.urlopen("http://search.twitter.com/search.json" + res["next_page"])
    res = simplejson.load(fp)
    fp.close()
    results.extend(res["results"])

rawDescription: appending successfully to a python list

description: Appending successfully to a python list


code:
import tempfile
import shutil

home = tempfile.mkdtemp()
try:
    gpg = gnupg.GPG(gnupghome=home, keyring='/path/to/keyring/file',
        options=['--no-default-keyring'])
finally:
    shutil.rmtree(home)

rawDescription: Change python-gnupg lock file location?

description: Change python-gnupg lock file location


code: self.newList, self.timeStamp = zip(*((x.rstrip(), '0') for i, x in enumerate(rawFile) if i%2==0))

rawDescription: Efficient way to do these python list comprehensions


code:
import random
def getAnswer(answerNumber):
     if answerNumber == 1:
           return 'It is certain'
     elif answerNumber == 2:
           return 'It is decidedly so'
     elif answerNumber == 3:
           return 'Yes'
     elif answerNumber == 4:
           return 'Reply hazy try again'
     elif answerNumber == 5:
           return 'Ask again later'
     elif answerNumber == 6:
           return 'Concentrate and ask again'
     elif answerNumber == 7:
           return 'My reply is no'
     elif answerNumber == 8:
           return 'Outlook not so good'
     elif answerNumber == 9:
           return 'Very doubtful'

r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)

rawDescription: IndentationError: unindent does not match


code:
def post(self):
    var_dump({ k: self.get_argument(k) for k in self.request.arguments })

rawDescription: get large number of Post values

description: Get large number of Post values


code:
import tkinter as tk

class Mainwindows:
    def __init__(self, master):
        self.master = master
        self.mainframe = tk.Frame(self.master)
        self.mainframe.pack()

        # Create the variable in the main class
        self.inputVar = tk.DoubleVar()

        self.sinputbutton = tk.Button(self.mainframe, text="INPUT", command=self.openinput)
        self.sinputbutton.pack()

        # Temp button to display value
        self.displaybutton = tk.Button(self.mainframe, text="Display", command=self.display)
        self.displaybutton.pack()

    def openinput(self):
        self.inputwindow = tk.Toplevel(self.master)

        # Pass an instance of the DoubleVar into Sinput class
        self.app = Sinput(self.inputwindow, self.inputVar)

    # Temp function to show value
    def display(self):
        print(self.inputVar.get())

class Sinput:
    def __init__(self, master, var):
        self.master = master
        self.var = var

        self.inputframe = tk.Frame(self.master)
        self.inputframe.pack()

        self.stuffinput = tk.Entry(self.inputframe, textvariable=self.var)
        self.stuffinput.pack()

        self.okbutton = tk.Button(self.inputframe, text="Ok", command=self.inputok)
        self.okbutton.pack(side="right", padx=5, pady=10)

    def inputok(self):
        self.master.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    app = Mainwindows(root)
    root.mainloop()

rawDescription: How to keep values in Entry Widget after I wrote them for furthers lookback

description: Keep values in Entry Widget after I wrote them for furthers lookback


code:
s = "And God saw every thing that he had made, and, behold, it was very good. And the evening and the morning were the sixth day."
' '.join([i[0].upper() for i in s.split()])

rawDescription: First Letter separated and capitalized

description: First Letter separated and capitalized


code:
option = 'Yes'

while True:
    demand = input('What do you want to do: ')
    print('Enter your two numbers...')
    a = int(input('First Number= '))
    b = int(input('Second Number= '))
    c = 0
    if demand == 'add':
        c = a + b
    elif demand == 'subtract':
        c = a - b
    elif demand == 'multiply':
        c = a * b
    elif demand == 'divide':
        c = a / b

    print('Answer= %s' %c)
    option = input('Do you want to run agian?: ')
    if option != 'Yes':
        break

rawDescription: While Loops? Need Help Running New Program- Python


code: x = np.meshgrid(*[np.arange(1, x) for x in shape])

rawDescription: numpy meshgrid of dynamic shape

description: Numpy meshgrid of dynamic shape


code:
from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'tmpEmployeeDatabase.csv'
tempfile = NamedTemporaryFile(delete=False)

with open(filename, 'rb') as csvFile, tempfile:
    reader = csv.reader(csvFile, delimiter=',', quotechar='"')
    writer = csv.writer(tempfile, delimiter=',', quotechar='"')

    for row in reader:
        row[1] = row[1].title()
        writer.writerow(row)

shutil.move(tempfile.name, filename)

rawDescription: Inline CSV File Editing with Python

description: Inline CSV File Editing with Python


code:
with open(r'G:\number.csv', 'r') as f:  # read
    content = f.read()
    with open(r'G:\number-post.csv', 'wb') as fh: # write
        fh.write(content.replace('-1','O,O').replace('0','A,A').replace('1','A,B').replace('2','B,B').replace('O','0'))

rawDescription: How could I transfer each cell to different form then separate them to 2 cells ? CSV python


code: solr = Solr(base_url='http://localhost:8080/solr/products', version=4)

rawDescription: Python/mysolr : Select only one core

description: Python/mysolr : Select only one core


code:
num = 12345678
first_four = int(str(num)[:4])
last_four = int(str(num)[4:])
middle_two = int(str(num)[3:5])

rawDescription: How do I get the last numbers of a number variable?

description: Get the last numbers of a number variable


rawDescription: How to convert columns into one datetime column in pandas?

description: Convert columns into one datetime column in pandas


code:
g = df1.groupby(level='Group')
g.apply(lambda x: x <= df2.loc[x.name])

rawDescription: Filter Pandas DataFrame using another DataFrame


rawDescription: django query question

description: Django query question


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

xarray = np.array([[   0],    #curve 1
                   [ 100],    #curve 1
                   [ 200],    #curve 1
                   [   0],    #curve 2
                   [ 100],    #curve 2
                   [ 200]])   #curve 2

yarray = np.array([[ 11],     #curve 1
                   [ 22],     #curve 1
                   [ 22],     #curve 1
                   [ 19],     #curve 2
                   [ 12],     #curve 2
                   [  0]])    #curve 2

# can the value "0" can be used separate xy pairs?
indices = np.argwhere(xarray[:,0] == 0)
for i in range(len(indices)):
    try:
        i0 = indices[i]
        i1 = indices[i+1]
    except:
        i0 = indices[i]
        i1 = len(xarray[:,0])
    plt.fill(xarray[i0:i1,0], yarray[i0:i1,0])
plt.show()

rawDescription: Plot multiple curves with matplotlib.pyplot.fill


code:
f = urlopen ('http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=4&e=29&f=2014&g=d&a=8&b=22&c=1981&ignore=.csv')
with open('output.csv', 'w') as out:
    # print header first
    out.write(f.readline())

    # then print reversed lines
    for line in reversed(f.readlines()):
        out.write(line)

f.close()  # !!!

rawDescription: Print in Reverse Order Python

description: Print in Reverse Order Python


code:
from PySide import QtCore, QtGui
from PySide.QtCore import Slot

try:
  _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
  _fromUtf8 = lambda s: s

class Ui_NewWindow(object):
  def setupUi(self, NewWindow):
    NewWindow.setObjectName(_fromUtf8("NewWindow"))
    NewWindow.resize(439, 225)
    self.centralwidget = QtGui.QWidget(NewWindow)
    self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
    self.pushButton_2.setGeometry(QtCore.QRect(170, 140, 99, 27))
    self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
    self.widget = QtGui.QWidget(self.centralwidget)
    self.widget.setGeometry(QtCore.QRect(40, 30, 365, 89))
    self.widget.setObjectName(_fromUtf8("widget"))
    self.verticalLayout = QtGui.QVBoxLayout(self.widget)
    #self.verticalLayout.setMargin(0)
    self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
    self.horizontalLayout_2 = QtGui.QHBoxLayout()
    self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
    self.label_3 = QtGui.QLabel(self.widget)
    self.label_3.setObjectName(_fromUtf8("label_3"))
    self.horizontalLayout_2.addWidget(self.label_3)
    self.lineEdit = QtGui.QLineEdit(self.widget)
    self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
    self.horizontalLayout_2.addWidget(self.lineEdit)
    self.label_4 = QtGui.QLabel(self.widget)
    self.label_4.setObjectName(_fromUtf8("label_4"))
    self.horizontalLayout_2.addWidget(self.label_4)
    self.lineEdit_2 = QtGui.QLineEdit(self.widget)
    self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
    self.horizontalLayout_2.addWidget(self.lineEdit_2)
    self.verticalLayout.addLayout(self.horizontalLayout_2)
    self.pushButton = QtGui.QPushButton(self.widget)
    self.pushButton.setObjectName(_fromUtf8("pushButton"))
    self.verticalLayout.addWidget(self.pushButton)
    self.horizontalLayout = QtGui.QHBoxLayout()
    self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
    self.label = QtGui.QLabel(self.widget)
    self.label.setObjectName(_fromUtf8("label"))
    self.horizontalLayout.addWidget(self.label)
    self.label_2 = QtGui.QLabel(self.widget)
    self.label_2.setObjectName(_fromUtf8("label_2"))
    self.horizontalLayout.addWidget(self.label_2)
    self.verticalLayout.addLayout(self.horizontalLayout)
    NewWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtGui.QMenuBar(NewWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 439, 25))
    self.menubar.setObjectName(_fromUtf8("menubar"))
    NewWindow.setMenuBar(self.menubar)
    self.statusbar = QtGui.QStatusBar(NewWindow)
    self.statusbar.setObjectName(_fromUtf8("statusbar"))
    NewWindow.setStatusBar(self.statusbar)

    self.retranslateUi(NewWindow)
    QtCore.QMetaObject.connectSlotsByName(NewWindow)

    self.pushButton.clicked.connect(self.add_values)

  def retranslateUi(self, NewWindow):
    NewWindow.setWindowTitle(QtGui.QApplication.translate("NewWindow", "MainWindow",    None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton_2.setText(QtGui.QApplication.translate("NewWindow", "Exit", None, QtGui.QApplication.UnicodeUTF8))
    self.label_3.setText(QtGui.QApplication.translate("NewWindow", "A = ", None, QtGui.QApplication.UnicodeUTF8))
    self.lineEdit.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))
    self.label_4.setText(QtGui.QApplication.translate("NewWindow", "B = ", None, QtGui.QApplication.UnicodeUTF8))
    self.lineEdit_2.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton.setText(QtGui.QApplication.translate("NewWindow", "Add", None, QtGui.QApplication.UnicodeUTF8))
    self.label.setText(QtGui.QApplication.translate("NewWindow", "Answer  : ", None, QtGui.QApplication.UnicodeUTF8))
    self.label_2.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))

  @Slot()
  def add_values(self):
      # you should convert the values to integers for a less error-prone code
      summed = float(self.lineEdit.text()) + float(self.lineEdit_2.text())
      self.label_2.setText(str(summed))

if __name__ == "__main__":
  import sys
  app = QtGui.QApplication(sys.argv)
  NewWindow = QtGui.QMainWindow()
  ui = Ui_NewWindow()
  ui.setupUi(NewWindow)
  NewWindow.show()
  sys.exit(app.exec_())

rawDescription: Assigning value to the variable in Qt

description: Assigning value to the variable in Qt


code: transformed = sig(x)

rawDescription: applying a function to each element in vector in numpy

description: Applying a function to each element in vector in numpy


code:
import struct

def getData():
    data = []
    for i in range( 0, 1024 ):
        data.append( 0.25 * math.sin( math.radians( i ) ) )
    return struct.pack('f'*len(data), *data)

rawDescription: Convert list of floats into buffer in Python?


code:
import fileinput
import sys
import re

newline = '''\
{l}
    public static final String CO_ID = "XXXXX"
'''

filename = '/path/to/file.java'
for line in fileinput.input([filename], inplace=True, backup='.bak'):
    if re.match(r'public class', line):
        sys.stdout.write(newline.format(l=line))
    else:
        sys.stdout.write(line)

rawDescription: Inserting text in a file using Python

description: Inserting text in a file using Python


code:
child = pexpect.spawn('mysql')
child.expect('mysql>')
child.sendline('use test; show tables;')
child.expect('(\d+) row.* in set \(.*\)')
count_tables = child.match.groups()[0]

rawDescription: How to extract output from a running command in a python script?

description: Extract output from a running command in a python script


code:
colors = {}
colors["red"] = [1,2,3] #you can dynamically add to list while reading files.
colors["yellow"] = [0,2,4]
colors

rawDescription: Handle table data in python

description: Handle table data in python


code:
deriv = np.polyder(ridge.coef_[::-1])
yd_plot = np.polyval(deriv,x_plot)

rawDescription: How to extract derivative from a polynomial fit?

description: Extract derivative from a polynomial fit


code:
df.stack()
df.stack().nlargest(6)

rawDescription: Get N largest values from pandas array, with index and column headings intact


code:
import csv
import time

column_count = 2 # Assume we have 2 columns, which is the minimum

with open('somefile.txt') as f:
    reader = csv.reader(f, delimiter=',')
    # fetch the first row, grab the column length
    column_count = len(next(reader))

# Next, create the table:

table_name = 'sometable_{0}'.format(int(time.time()))

q = 'CREATE TEMPORARY TABLE {0} ('.format(table_name)
q += ', '.join('col_{0} VARCHAR(255)'.format(i) for i in range(column_count))
q += ');'

cur.execute(q)
cur.commit()

q = "INSERT INTO {0} VALUES (".format(table_name)
q += ', '.join(('%s ' * column_count).split())
q += ');'

# Now, populate it

with open('somefile.txt') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        cur.execute(q, tuple(row))
        cur.commit()

rawDescription: Import CSV and create Temp Table to store results


code:
new_df = pd.merge(df1, df2, on=key)
new_df.new_col = newdf.apply(lambda row: myfunc(row['A_x'], row['A_y']), axis=1)

rawDescription: pandas two dataframe cross join

description: Pandas two dataframe cross join


code:
import contextlib
import selenium.webdriver as webdriver
import lxml.html as LH
import lxml.html.clean as clean

url="http://www.yahoo.com"
ignore_tags=('script','noscript','style')
with contextlib.closing(webdriver.Firefox()) as browser:
    browser.get(url) # Load page
    content=browser.page_source
    cleaner=clean.Cleaner()
    content=cleaner.clean_html(content)
    with open('/tmp/source.html','w') as f:
       f.write(content.encode('utf-8'))
    doc=LH.fromstring(content)
    with open('/tmp/result.txt','w') as f:
        for elt in doc.iterdescendants():
            if elt.tag in ignore_tags: continue
            text=elt.text or ''
            tail=elt.tail or ''
            words=' '.join((text,tail)).strip()
            if words:
                words=words.encode('utf-8')
                f.write(words+'\n')

rawDescription: Getting all visible text from a webpage using Selenium


code:
time_shifted = df['Time'].groupby(level=0).apply(lambda x: x.shift())
df['Product'] = ((df.Time - time_shifted)*df.Value).fillna(0)
df

rawDescription: Python pandas, multindex, slicing

description: Python pandas, multindex, slicing


code:
class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, instance, form, change):
        user = request.user
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.modified_by = user
        instance.save()
        form.save_m2m()
        return instance

rawDescription: make the user in a model default to the current user

description: Make the user in a model default to the current user


code:
import win32con
import win32gui

def inText(haystack, needle, n):
    parts= haystack.split(needle, n+1)
    if len(parts)<=n+1:
        return False
    if len(haystack)-len(parts[-1])-len(needle):
        return True

def isRealWindow(hWnd):
    '''Return True if given window is a real Windows application window.'''
    if not win32gui.IsWindowVisible(hWnd):
        return False
    if win32gui.GetParent(hWnd) != 0:
        return False
    hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
    lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
    if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
      or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
        if win32gui.GetWindowText(hWnd):
            return True
    return False

def getWindowSizes(text):
    '''Return a list of tuples (handler, (width, height)) for each real window.'''
    def callback(hWnd, extra):
        if not isRealWindow(hWnd):
            return
        title   = win32gui.GetWindowText(hWnd)
        rect    = win32gui.GetWindowRect(hWnd)
        isFrame = inText(title, text, 0)
        if(isFrame):
            windows.append((title, rect[2] - rect[0], rect[3] - rect[1], rect[0],rect[1]))
    windows = []
    win32gui.EnumWindows(callback, windows)
    return windows

def findWindow(text):
    window = getWindowSizes(text)
    name = window[0][0]
    w = window[0][1]
    h = window[0][2]
    x = window[0][3]
    y = window[0][4]

    return name,w,h,x,y

rawDescription: Find a application width and height - Crossplatform


rawDescription: Convert numbers to date

description: Convert numbers to date


code:
db = SQLAlchemy(app)

tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), index=True, unique=True)
    body = db.Column(db.String(500), index=True)
    tags = db.relationship('Tag', secondary=tags,
        backref=db.backref('posts', lazy='dynamic'))

    def __repr__(self):
        return '<Post %r %r>' % (self.title, self.tags)

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), index=True, unique=True)

    def __repr__(self):
        return '<Tag %r>' % (self.name)

rawDescription: Deciding schema for site with articles with editable tags?


code:
from mrjob.job import MRJob
from mrjob.emr import EMRJobRunner

class MRS3KeyProcessor(MRJob):
    # Do some MRJob stuff.
    ...

def s3_name_generator(bucket):
    """Generator that returns boto.s3.Key names.
    """
    # Could also use raw boto here.
    emr = EMRJobRunner()
    key_stream = emr.fs.get_s3_keys(bucket)
    for key in key_stream:
        yield key.name

def main():
    # The '-' argument signifies that we use stdin.
    mr_job = MRCountS3Objects(['--runner', 'inline', '-'])
    stdin = s3_name_generator('my-bucket')
    mr_job.stdin = stdin
    results = []
    with mr_job.make_runner() as runner:
        runner.run()
        for line in runner.stream_output():
            key, value = mr_job.parse_output_line(line)
            results.append((key, value))
    print(results)

if __name__ == '__main__':
    main()

rawDescription: How can I use s3 object names as inputs to an MRJob mapper, but not the s3 objects themselves?

description: Use s3 object names as inputs to an MRJob mapper, but not the s3 objects themselves


code:
# Get the current environment end filter out the old
# PYTHONPATH variable if exists in the environment
env = [env for env in QtCore.QProcess.systemEnvironment()
       if not env.startswith('PYTHONPATH=')]
# Add your PYTHONPATH
env.append('PYTHONPATH=path_to_where_you_want')
# Create a process, set the environment and run the script
p = QtCore.QProcess()
p.setEnvironment(env)
p.start('perl abc.pl')

rawDescription: Start a QProcess with PYTHONPATH set to different python version


code:
import os, os.path, zipfile, arcpy

in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip'

outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1"

z = zipfile.ZipFile(in_Zip,'r')

z.extractall(outDir)

zipContents = z.namelist()
z.close()

for item in zipContents:
    if item.endswith('.zip'):
        fullpath = os.path.join(outDir, item)
        x = zipfile.ZipFile(fullpath,'r')
        dest_path = os.path.dirname(fullpath)
        x.extractall(dest_path)
        x.close()

rawDescription: Trying to unzip a zipfile, then within the folders that result, find and unzip any/all zipfiles


code:
import re
tests = ["Milt Jackson, vibraphone, piano, guitar, 1923 (d. October 9, 1999)", "Howard Johnson, alto sax, 1908 (d. December 28, 1991)","Sonny Greenwich, guitar, 1936", "Eiichi Hayashi, alto sax, 1960", "Yoshio Ikeda, bass, 1942", "Urs Leimgruber, saxophones, bass clarinet. 1952"]
for test in tests:
    m = re.search ("\(d\.(.*)\)", test)
    if m:
        print(m.groups())

rawDescription: Finding the contents of parenthesis

description: Finding the contents of parenthesis


code:
import md5
data = open("filename", "rb").read() # The file
m = md5.new()
m.update(data)
print(m.digest())

rawDescription: Compare and delete duplicate photos

description: Compare and delete duplicate photos


code:
def get_periode(hour):
    if 4 <= hour <= 7:
        return 'morning'
    elif 8 <= hour <= 11:
        return 'before midday'

basket_times['periode'] = basket_times['hour'].map(get_periode)

rawDescription: Iterate through Pandas DataFrame, use condition and add column


code:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

...

return HttpResponseRedirect( reverse('login', kwargs={'foo': 'bar'}) )

rawDescription: Redirect to relative django path

description: Redirect to relative django path


code:
with open('input.txt') as fhi, open('output.txt', 'w') as fho:
  for line in fhi:
    if not pattern.search(line):
      # if there is no match write the line to the output file and proceed.
      fho.write(line)
      continue

    # if we get this far we found a match.  Scan up to seven lines.
    for i in range(7):
      toCheck = next(fhi)

      if not pattern2.search(toCheck):
        # if we don't find the 2nd keyword write the line, continue the sub-loop.
        fho.write(toCheck)
        continue

      # if we get this far we found the second pattern.  Add our newline.
      fho.write(toCheck)
      fho.write('\r\n')

rawDescription: Python to insert a line at a random location of a large text file with condition


code: df.iat[0, df.columns.get_loc('foo')] = df['foo'][0].resample('D').sum().dropna()

rawDescription: Setting values with pandas.DataFrame

description: Setting values with pandas.DataFrame


code:
from scrapy.contrib.linkextractors.lxmlhtml import LxmlParserLinkExtractor

tags = ['img', 'embed', 'link', 'script']
attrs = ['src', 'href']
extractor = LxmlParserLinkExtractor(lambda x: x in tags, lambda x: x in attrs)
resource_urls = [l.url for l in extractor.extract_links(response)]

rawDescription: How to retrieve all the images, js, css urls

description: Retrieve all the images, js, css urls


code: sum(1 for _ in iter(lambda: randint(0, 9), 5))

rawDescription: Counting random numbers

description: Counting random numbers


code:
import re
textstr = ""
with open("mytext.txt", "rb") as fh:
    for line in fh:
        textstr += re.sub(r'\r$', '', line)
print(repr(textstr))

rawDescription: lxml adds urlencoding in xml?

description: Lxml adds urlencoding in xml


code:
def primenumbers():
    j = 2
    chk = 1
    f = open("primes.txt", "w")
    primes = []
    notprimes = []
    ask = input("how many primes? ")
    while len(primes) < int(ask):
        k = 2
        while not(k==j) and not(j%k==0):
            k = k + 1
        if k == j:
            primes.append(j)
            f.write(str(j)+"\n")
        else:
            notprimes.append(j)
        if len(primes) >= 1000*chk:
            chk = chk + 1
            print("There have been " + str(len(primes)) + " primes counted so far")
        j = j + 1
    print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
    f.close
    return(" ")

rawDescription: Basic Prime Number generator

description: Basic Prime Number generator


code:
class AutoWrapper(object):
    wrapped = ()
    def __getattr__(self, attrname):
        for obj in self.wrapped:
            try:
                return getattr(obj, attrname)
            except AttributeError:
                pass
        raise AttributeError(attrname)

class Thing(AutoWrapper):
    def __init__(self, *args):
        self.wrapped = args

class TheValue(object):
    is_square = True

class OtherValue(object):
    is_round = True

def do_something(obj):
    print('do_something to {}'.format(obj))

def process(value):
    if value.is_square:
        do_something(value)

thing1 = Thing(TheValue(), OtherValue())

process(thing1)

rawDescription: How can I 'lift' certain attributes from a wrapped value to the wrapper?


code: dirName = 'seq%03d0' % 1

rawDescription: Sequential directories creation in Python


code:
def OR_Gate():
  a = raw_input("Input A:")
  b = raw_input("Input B:")
  return "True" in [a,b]

rawDescription: Python: Printing the return of a function


code:
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

rawDescription: How do I pick 2 random items from a Python set?

description: Pick 2 random items from a Python set


code:
from selenium.webdriver.common.by import By
import selenic.util

util = selenic.util.Util(driver)

# This goes through util and uses the explicit wait set by util.
foo = util.find_element((By.CSS_SELECTOR, "..."))

# For special cases that take longer to give results.
with util.local_timeout(10):
    # The timeout is set to 10 for calls in this with block.
    bar = util.find_element(...)
# The timeout is restored to what it was just before the with.

rawDescription: Mixing implicit and explicit waits

description: Mixing implicit and explicit waits


code: uvw = db.ListProperty(int, default=[])

rawDescription: Empty list in appengine datastore: java vs python


rawDescription: Pandas concatenate all elements of dataframe into single series


code:
for index, row in dframe.iterrows():
    plt.scatter(row['x'], row['y'], color=row['color'], label=row['name'])
plt.title('Title')
plt.xlabel('X label')
plt.ylabel('Y label')
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.legend(scatterpoints=1, loc='lower left', fontsize=10)
plt.show()

rawDescription: Pandas: Creating a matplotlib legend from a dataframe


rawDescription: How do I keep str(numpy.array) from automatically inserting a newline

description: Keep str(numpy.array) from automatically inserting a newline


code:
# using self made module system.current_users()
users = system.current_users()

printers_with_users = {}

for username in users:

    try:
        printer_yaml = config_data.retrieve_for(username).get(u"printers", [])
    except:
        print("Aborting: Can't find userconfig.yaml!\n")
        exit(1)

    for device, dev_list in printer_yaml.iteritems():
        # parsing datas...
        config_classes = dev_list.get("config_classes", None)
        descr = get_unicode(dev_list, u"descr")
        printer_id = get_unicode(dev_list, u"id")
        is_local = dev_list.get("is_local", None)
        listen_network = dev_list.get("listen_network", None)
        location = get_unicode(dev_list, u"location")
        ppd_file = get_unicode(dev_list, u"ppd_file")
        ppd_uri = get_unicode(dev_list, u"ppd_uri")
        printer_uri = get_unicode(dev_list, u"printer_uri")

        # here is the cool part ;)
        printers_with_users.setdefault(printer_id, []).append(username)

        #configuring printers...

# configure access rules in printers.conf
for printers, accepted_users in printers_with_users.iteritems():
    users_string = ",".join(accepted_users)
    try:
        subproc.call('lpadmin', ['-p', printers, '-u', 'allow:%s' % users_string])
    except:
        print ( "     - unable to set user access rules\n" )
        print (config_error) % printers
        continue

rawDescription: How to bind CUPS printer to user?

description: Bind CUPS printer to user


code:
# Python variable: `p` stores an addition object:
p = (u**2 + a**2*cos(v))

# SymPy symbol, it's just a symbol, no expressions:
p = Symbol('p')

# express symbol-expression relation in some way, like:
{p: (u**2 + a**2*cos(v))}

rawDescription: Substituting an expression with sympy

description: Substituting an expression with sympy


code:
selected = np.where((data < 4) & (data > 1), data, np.nan)
selected

rawDescription: select required data from numpy array

description: Select required data from numpy array


code:
for x in ['a', 'b', 'c', 'd', 'e']:
    setattr(i, x, f(getattr(i, x)))

rawDescription: Elegant way to modify a list of variables by reference in Python?


code: df[df != 0] = value

rawDescription: Pandas replace non-zero values

description: Pandas replace non-zero values


code:
class MySignupView(SignupView):

    def get_context_data(self, **kwargs):
        ret = super(MySignupView, self).get_context_data(**kwargs)
        ret['all_tags'] = Tags.get_tags()

        return ret

rawDescription: Override signup view django-allauth

description: Override signup view django-allauth


code:
import pylab as plt
from matplotlib_venn import venn3, venn3_circles

v = venn3(subsets=(1,1,0,1,0,0,0))
v.get_label_by_id('100').set_text('First')
v.get_label_by_id('010').set_text('Second')
v.get_label_by_id('001').set_text('Third')
plt.title("Not a Venn diagram")
plt.show()

rawDescription: Python Matplotlib Venn diagram

description: Python Matplotlib Venn diagram


code:
import os
import json
from azure import *
from azure.storage import *
from azure.storage.table import TableService, Entity

table_service = TableService(account_name='[account-name]', sas_token='[sas-token]')
list = table_service.query_entities('[table-name]', top=100)

rawDescription: Python: How to connect to Azure cloud storage using shared access key?


code:
for line in open(PATH_TO_FILE):
    cursor.execute(line)

rawDescription: execute *.sql file with python MySQLdb

description: Execute *.sql file with python MySQLdb


code:
def my_view(request):

    if request['x'] == 'a':
        return function_a()
    elif request['x'] == 'b':
        return function_b()

    return some_other_response()

rawDescription: django - render to response from function - not working

description: Django - render to response from function - not working


code:
win32api.LoadKeyboardLayout('00000409',1) # to switch to english
win32api.LoadKeyboardLayout('00000401',1) # to switch to arabic

rawDescription: Automatically change keyboard layout in WinXP


code:
def compress(uncompressed):
    """Compress a string to a list of output symbols."""

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    w = ""
    result = []
    for c in uncompressed:
        wc = w + c
        if wc in dictionary:
            w = wc
        else:
            result.append(dictionary[w])
            # Add wc to the dictionary.
            dictionary[wc] = dict_size
            dict_size += 1
            w = c

    # Output the code for w.
    if w:
        result.append(dictionary[w])
    return result

def decompress(compressed):
    """Decompress a list of output ks to a string."""
    from cStringIO import StringIO

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    # use StringIO, otherwise this becomes O(N^2)
    # due to string concatenation in a loop
    result = StringIO()
    w = compressed.pop(0)
    result.write(w)
    for k in compressed:
        if k in dictionary:
            entry = dictionary[k]
        elif k == dict_size:
            entry = w + w[0]
        else:
            raise ValueError('Bad compressed k: %s' % k)
        result.write(entry)

        # Add w+entry[0] to the dictionary.
        dictionary[dict_size] = w + entry[0]
        dict_size += 1

        w = entry
    return result.getvalue()

# How to use:
compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)

rawDescription: Implementing the LZ78 compression algorithm in python


code:
QByteArray
QChar
QColor
QDate
QDateTime
QKeySequence
QLatin1Char
QLatin1String
QLine
QLineF
QMatrix
QPoint
QPointF
QPolygon
QRect
QRectF
QSize
QSizeF
QString
QTime

rawDescription: Python: Pickle and Qt (PyQT)

description: Python: Pickle and Qt (PyQT)


code:
from formencode import FancyValidator, Invalid
from formencode.validators import Email

class EmailList(FancyValidator):
    """ Takes a delimited (default is comma) string and returns a list of validated e-mails
        Set the delimiter by passing delimiter="A_DELIMITER" to the constructor.
        Also takes all arguments a FancyValidator does.
        The e-mails will always be stripped of whitespace.
    """
    def _to_python(self, value, state):
        try:
            values = str(value).split(self.delimiter)
        except AttributeError:
            values = str(value).split(',')
        validator = formencode.ForEach(validators.Email())
        validator.to_python(values, state)
        return [value.strip() for value in values]

rawDescription: Chain FormEncode Validators

description: Chain FormEncode Validators


code:
def boolean():
    print("You have a boolean" )

def integer():
    print("You have an integer")

def floatType():
    print("You have a float")

def string():
    print("You have a string")

switchDict = {bool: boolean, int: integer, float: floatType, str: string}
switchDict[type(varX)]()

rawDescription: Use a python dictionary for "switch" on datatype


code:
rates = [10000,10000,10000,10000,0,0,0,10000,10000]
from itertools import groupby
[e for e, g in groupby(rates)]

rawDescription: Remove duplicates from subsequences of the list


rawDescription: Gmail email parsing with python when there are unicode characters in body


code:
def foo(the_list, value):
    index = bisect.bisect_left(the_list, value)
    return the_list[index] if the_list[index] == value or index == 0 else the_list[index-1]

rawDescription: Find Item lower or equal to value in list


code:
import os
import signal
import subprocess

process = subprocess.Popen('script.sh', stdout=subprocess.PIPE,
                   shell=False, preexec_fn=os.setsid)

os.killpg(process.pid, signal.SIGTERM)

rawDescription: Execute shell scripts based on value of key pressed


rawDescription: pysnmp: send hex string in trap

description: Pysnmp: send hex string in trap


code:
map = Basemap()
figure = plot.figure()
axes = Axes3D(figure)
for polygon in map.landpolygons:
    polygons.append(polygon.get_cords())
    #alpha = 0-1 in the below 1 highest 0 lowest
    collection = PolyCollection(polygons, closed = False)
axes.add_collection3d(collection)

rawDescription: Plotting 3D bars in Matplotlib

description: Plotting 3D bars in Matplotlib


code:
import copy
new_list = copy.deepcopy(old_list)

rawDescription: How to make a copy of the list?

description: Make a copy of the list


code:
cur.executemany("""
    INSERT INTO
        cord
        (x, y, z)
    VALUES
        (%s, %s, %s)
""", asd)
db.commit()

rawDescription: Python: insert 2D array into MySQL table


code:
my_list = ['a','b','c']
my_values = [1,2,3]
for k, v in zip(my_list, my_values):
    globals()[k] = v

a
b
c

rawDescription: is there a way to instantiate variables from iterated output in python?

description: Is there a way to instantiate variables from iterated output in python


code:
def reverse3(nums):
    return list(reversed(nums))

reverse3([4,5,6])

rawDescription: returning the list reversed

description: Returning the list reversed


code: size: self.minimum_size

rawDescription: Dynamically sizing widgets depending on size of children


code:
vals[ind] = new_vals
vals

rawDescription: Assign a list of values to a list of indices


code:
import random
print('hello')
question1 = [' cbca', ' cbbca']

question = random.choice(question1) # Remember the choice of random

print("What's equal to" + question + "?")
r = input()
if r in ('7,8', '7.8', '78') and question == ' cbca' :

    print("That's correct!")

elif r in ('1', '1,0') and question == ' cbbca' :
    print("That's correct!")

else :
    print('r')

rawDescription: if/elif/else-statement doesn't work with random.choice

description: If/elif/else-statement doesn't work with random.choice


code:
buffer = ''
while True:
    line = raw_input()
    if not line: break

    buffer += line

# process input

rawDescription: Python command Line - multiple Line Input


code:
f2 = open('accessionids.txt','r')
f1 = open('fasta.txt','r')
f3 = open('fasta_parsed.txt','w')

AI_DICT = {}
for line in f2:
    AI_DICT[line[:-1]] = 1

skip = 0
for line in f1:
    if line[0] == '>':
        _splitline = line.split('|')
        accessorIDWithArrow = _splitline[0]
        accessorID = accessorIDWithArrow[1:-1]
        # print accessorID
        if accessorID in AI_DICT:
            f3.write(line)
            skip = 0
        else:
            skip = 1
    else:
        if not skip:
            f3.write(line)

f1.close()
f2.close()
f3.close()

rawDescription: Extract sequences from a FASTA file based on entries in a separate file


code:
for order in root.xpath('//order'):
    modlist = []
    for element in order.iterchildren('carType'):
        modlist.append ("%s" % (element.get('value')))

    for element in order.iter('upgrade'):
        modlist.append ("%s" % str.upper((element.get('type'))))
    # report grand total for order

rawDescription: Performing Function Operations on One .xml Item (and Its Children) at a Time with lxml


code:
import datetime
import time

@app.after_request
def log():
    with open("app.log", "a") as log:
        date = datetime.datetime.now()
        log.write(time.mktime(dt.timetuple()))

rawDescription: Logging application use in python?

description: Logging application use in python


code:
import os, re

samples = {}
for f in os.listdir("."):
    m = re.match(r"MySample (\d+) (\d+).wav", f)
    if m:
        samples[tuple(int(x) for x in m.groups())] = f

rawDescription: Indexed list of files in a folder that match a criteria


code:
import bs4

html_doc = """
<title>The Dormouse's story</title>

The Dormouse's story

Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.

...

"""

soup = bs4.BeautifulSoup(html_doc, 'html.parser')
comments = soup.findAll(text=lambda text:isinstance(text, bs4.Comment))

# Step 1: find the beginning and ending markers
node_start = [ cmt for cmt in comments if cmt.string == " START" ][0]
node_end = [ cmt for cmt in comments if cmt.string == " END " ][0]

# Step 2, subtract the 2nd list of strings from the first
all_text = node_start.find_all_next(text=True)
all_after_text = node_end.find_all_next(text=True)

subset = all_text[:-(len(all_after_text) + 1)]
print(subset)

# ['Lacie', ' and\n', 'Tillie', ';\nand they lived at the bottom of a well.']

rawDescription: How does one get the text from html while ignoring formatting tags using BeautifulSoup?

description: Get the text from html while ignoring formatting tags using BeautifulSoup


rawDescription: how to write a function for numpy matrix in Python

description: Write a function for numpy matrix in Python


code:
import re
str = "my color=red and my color=green"
p = r'color=([a-z]+)'
x = re.findall(p, str)

rawDescription: python parse and get more input from line

description: Python parse and get more input from line


code:
name_title = (("John D",("CEO","COO","CTO")),
              ("Mary J",("COO","MD")),
              ("Tim C",("Dev Ops","Director")))
title_cat = {"CEO": set(["Executive"]),
             "COO": set(["Executive"]),
             "CTO": set(["Executive"]),
             "MD": set(["Executive"]),
             "Dev Ops": set(["IT"]),
             "Director": set(["Other"])}

name_cat = [(name, reduce(lambda x,y:x|y, [title_cat[title]for title in titles])) for name,titles in name_title]

rawDescription: How to match and assign data the pythonic way?

description: Match and assign data the pythonic way


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

df = pd.DataFrame((np.random.random((2,30)).T),columns=['A','B'])
fig, axs = plt.subplots(1,2)
axs[0].scatter(df.A, df.B)
axs[0].set_title('Default y-locator')
from matplotlib.ticker import LinearLocator
axs[1].get_yaxis().set_major_locator(LinearLocator(numticks=12))
axs[1].set_title('12 evenly spaced y-ticks')
axs[1].scatter(df.A, df.B)

rawDescription: Setting an automatic tick interval in PyPlot


code: DictOne, DictTwo, *_ = pickle.load( open ("all.p", "rb") )

rawDescription: unpickle list of dictionaries

description: Unpickle list of dictionaries


code:
session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name],
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

rawDescription: Sqlalchemy in clause

description: Sqlalchemy in clause


code:
last = self.commandMenu.index("end")
for i in range(last+1):
    self.commandMenu.entryconfigure(i, state="normal")

rawDescription: Python Tkinter Menu total index counts

description: Python Tkinter Menu total index counts


code:
import numpy as np
import tensorflow as tf

# First define the variable.
n = 10 # size of x
x1 = tf.Variable(tf.zeros([n], dtype=tf.float64))
x2 = tf.stop_gradient(x1)

# Now define the cost function
f_tensor = tf.mul(tf.mul(tf.reshape(x1, [n]),
                         tf.reshape(x2, [n,1])),
                  tf.reshape(x2, [n,1,1]))
f = tf.reduce_sum(f_tensor)

session = tf.Session()
init = tf.initialize_all_variables()
session.run(init)

# Run on test array
xtest = np.ones(n)
res = session.run([f, tf.gradients(f, x1)[0]],
                  feed_dict={x1 : xtest})

assert res[0] == 1000
for g in res[1]:
    assert g == 100

rawDescription: Tensorflow: share value for two different variables within same operation


rawDescription: show fields containing html tag in django templates like ordinary html tag

description: Show fields containing html tag in django templates like ordinary html tag


code:
while True:
    item = q_out.get() # this will block until another item is available
    # do stuff with that single item here

rawDescription: Python multiprocessing process doesn't run


code:
class SimpleForm(Form):
    acheckbox = MultiCheckboxField('Label')
    bcheckbox = MultiCheckboxField('Label')
    categories = SelectField('Label')

    def __init__(self, filename, *args, **kwargs):
        super(SimpleForm, self).__init__(*args, **kwargs)

        list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
        # create a list of value/description tuples
        files = [(x, x) for x in list_of_files]
        test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
        second_list = list(test.columns)
        second_files = [(x, x) for x in second_list]

        self.acheckbox.choices = files
        self.bcheckbox.choices = second_files
        self.categories.choices = files

rawDescription: dynamically populate dropdown; passing "filename" to SimpleForm() Class

description: Dynamically populate dropdown; passing "filename" to SimpleForm() Class


code:
val = object()
d = {}
d[123] = val
d['name'] = val
d

rawDescription: Is it possible to use multiple keys for a single element in a dict?


code: List2 = [i for i in List1 if len(i.split())>2]

rawDescription: Ignoring items that have fewer than three words


code:
import lxml.html

# lxml can download pages directly
root = lxml.html.parse('http://test.xyz').getroot()

# use a CSS selector for class="main",
# or use root.xpath('//table[@class="main"]')
tables = root.cssselect('table.main')

# extract HTML content from all tables
# use lxml.html.tostring(t, method="text", encoding=unicode)
# to get text content without tags
"\n".join([lxml.html.tostring(t) for t in tables])

# removing only specific empty tags, here  and
for empty in root.xpath('//*[self::b or self::i][not(node())]'):
    empty.getparent().remove(empty)

# removing all empty tags (tags that do not have children nodes)
for empty in root.xpath('//*[not(node())]'):
    empty.getparent().remove(empty)
# root does not contain those empty tags anymore

rawDescription: Parsing HTML with lxml (python)

description: Parsing HTML with lxml (python)


code:
from django.core.mail import EmailMultiAlternatives
body = render_to_string(template_name, locals(),
                      context_instance=RequestContext(request))
email = EmailMultiAlternatives(subject, body, mail_sender, [contact_request.email], headers={'Reply-To': 'do_not_reply@whatever.com'})
email.content_subtype='html'
email.send(fail_silently=False)

rawDescription: Rendered HTML in email body

description: Rendered HTML in email body


code:
ax = df2.plot(kind='bar', stacked=True)
ax.set_ylabel('Y Axis Label')
ax.set_xticklabels(df2.index, rotation='horizontal')

rawDescription: Pandas Plot: Index

description: Pandas Plot: Index


rawDescription: How to get a value from a cell of a data frame?

description: Get a value from a cell of a data frame


code:
def supergraph(g1, keyfunc, allow_selfloops=True):
    g2 = nx.DiGraph()
    for (a,b,d) in g1.edges_iter(data=True):
        result = keyfunc(g1,a,b,d)
        if result is not None:
            a2,b2,w = result
            if a2 != b2 or allow_selfloops:
                g2.add_edge(a2,b2)
                try:
                    g2[a2][b2]['weight'] += w
                except:
                    g2[a2][b2]['weight'] = w

            for u2,u in [(a2,a),(b2,b)]:
                if not u2 in g2:
                    g2.add_node(u2, original_nodes=set([u]))
                else:
                    try:
                        g2.node[u2]['original_nodes'].add(u)
                    except:
                        g2.node[u2]['original_nodes'] = set([u])
    return g2

rawDescription: grouping nodes in networkx

description: Grouping nodes in networkx


code:
from datetime import datetime, timedelta

dt = datetime(2012, 2, 27)
print(dt + timedelta(3))  # March 1st

rawDescription: Does timedelta added to date consider leap year?


rawDescription: Find equidistant points between two coordinates


code: text = text.replace(word, mylist2[mylist1.index(word)])

rawDescription: Python: Searching text for Strings from one List and replacing them with Strings from another


code:
row_idx = np.searchsorted(lookup_array[:,0],key_set)[key_set.argsort()]
values = lookup_array[row_idx,1]

rawDescription: Looking up large sets of keys: dictionary vs. NumPy array


code:
close = driver.find_element_by_xpath('//div[@data-module="frame"]/\
        div[@class="frame__content"]/div[@class="frame__controls"]/\
        div[contains(@class, "frame__controlsButton")\
        and contains(@class,"_close")]')

rawDescription: How to script behavior like clicking on SVG using python

description: Script behavior like clicking on SVG using python


code:
def filter_dictionary(filter_data):
    dictionary_to_filter = {'car 1': 100, 'car 2': 200, 'car 3': 300, 'bus 1': 1000, 'bus 2': 2000, 'bus 3': 3000}
    spl = filter_data.split()
    dictionary_filtered = {k: v for (k, v) in dictionary_to_filter.items() if all(a in k for a in spl)}
    return dictionary_filtered

print(filter_dictionary('ca 1') )
{'car 1': 100}

rawDescription: filtering the keys of a python dictionary for all the items of a list

description: Filtering the keys of a python dictionary for all the items of a list


code:
d = {'name1':name1, 'name2':name2}

for myvar in listname:
    myvar = d.get(myvar)
    do_stuff(myvar)

rawDescription: python: how to evaluate items in a list

description: Python: how to evaluate items in a list


code:
def close(self):
    debug('closing pool')
    if self._state == RUN:
        self._state = CLOSE
        self._worker_handler._state = CLOSE

rawDescription: Python multiprocessing - Why does pool.close() take so long to return?


code:
ast.literal_eval(text)
host, port = ast.literal_eval(text)
host
port

rawDescription: Need help separating the contents of a variable into 2 varaibles in python


code:
def inside(x, y):
    """Check if point (x, y) is inside a unit circle
    with center in the origin (0, 0)"""
    return x*x + y*y < 1

points = ...

# Scala / Python code is equivalent to this
sum([1 if inside(x, y) else 0 for (x, y) in points])

# While Java code is equivalent to this
len([(x, y) for (x, y) in points if inside(x, y)])

rawDescription: Scala/Python vs. Java: SparkContext.map vs. .filter in PI example?


rawDescription: PyQt4: Select multiple items in QTableWidget simultaneously


code:
from numpy import *
data = loadtxt("myfile.txt")                       # myfile.txt contains 4 columns of numbers
t,z = data[:,0], data[:,3]                         # data is 2D numpy array
t,x,y,z = loadtxt("myfile.txt", unpack=True)                  # to unpack all columns
t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True)     # to select just a few columns
data = loadtxt("myfile.txt", skiprows = 7)                    # to skip 7 rows from top of file
data = loadtxt("myfile.txt", comments = '!')                  # use '!' as comment char instead of '#'
data = loadtxt("myfile.txt", delimiter=';')                   # use ';' as column separator instead of whitespace
data = loadtxt("myfile.txt", dtype = int)                     # file contains integers instead of floats

rawDescription: import an array in python

description: Import an array in python


code:
rdd = sc.parallelize([
    ("key1", ("val1_key1", "val2_key1")),
    ("key2", ("val1_key2", "val2_key2"))])

rdd.aggregateByKey([], lambda acc, x: acc + [x], lambda acc1, acc2: acc1 + acc2)

rawDescription: How can I use reduceByKey instead of GroupByKey to construct a list?

description: Use reduceByKey instead of GroupByKey to construct a list


code:
from random import choice
x = [choice(xySet) for _ in range(nObser)]
p = [choice(xP) if v == 'x' else choice(yP) for v in x]
x
p

rawDescription: More Efficient Way to Create array

description: More Efficient Way to Create array


code:
import urllib2

r = urllib2.urlopen('https://openapi.etsy.com/v2/users/redluck2013/profile?fields=transaction_sold_count&api_key=1pmmjgt3j4nz5ollhzz2hvib')

print(r.read())

rawDescription: HTTPS request in python 2.7

description: HTTPS request in python 2.7


code:
if larger == 3:
    if smaller == 3:
        return "C"
    else:
        return minkey
elif smaller == 3:
    return maxkey
else:
    return "C"

rawDescription: ACM programming competition - Python solution


rawDescription: Reading large excel tables (guessing size)


code:
for i in xrange(10):
    frame.bind(str(i), my_handler)

rawDescription: How to bind to all the number keys in Tkinter?

description: Bind to all the number keys in Tkinter


code:
class ProductForm(forms.ModelForm):
    # Meta as above
    def __init__(self, *args, **kwargs):
        if 'instance' in kwargs:
            kwargs['instance'].price_retail = kwargs['instance'].price_retail.quantize(Decimal('0.01'))
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['price_retail'].widget.attrs['class'] = 'input-price'
        self.fields['price_retail'].decimal_places = 2

rawDescription: Shorten Decimal Places of ModelForm field Django


code:
df['dummy'] = df.groupby('group')['dummy'].transform(np.cumsum)
df.ix[df['dummy']!=0, 'dummy'] = 1
df

rawDescription: Pythjon/pandas: how to forward fill from specific value within a group


code:
df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
df
df.groupby("A").filter(lambda x: len(x) > 1)

rawDescription: How do I filter a pandas DataFrame based on value counts?

description: Filter a pandas DataFrame based on value counts


code:
# READ ALL DAT FILE IN PATHIMPORT AND COMBINE INTO ONE TEXT FILE
strToday =  dateToday()
read_files = glob.glob(pathImport + "\\" + "*.Dat")
with open("C:/swipeimport/" + "M_" + strToday + ".txt", "wb") as outfile:
    for x in read_files:
        with open(x, "rb") as infile:
            outfile.write(infile.read())

rawDescription: How to get the contents of multiple dynamic text files and store it in one text file and in mysql - Python 2.7?

description: Get the contents of multiple dynamic text files and store it in one text file and in mysql - Python 2.7


code:
import webbrowser
import pandas as pd
from tempfile import NamedTemporaryFile

def df_window(df):
    with NamedTemporaryFile(delete=False, suffix='.html') as f:
        df.to_html(f)
    webbrowser.open(f.name)

df = pd.DataFrame({'a': [10, 10, 10, 11], 'b': [8, 8 ,8, 9]})
df_window(df)

rawDescription: Possible for pandas dataframe to be rendered in a new window?


code:
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

import wx

class CanvasPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

    def draw(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    fr = wx.Frame(None, title='test')
    panel = CanvasPanel(fr)
    panel.draw()
    fr.Show()
    app.MainLoop()

rawDescription: Embedding a matplotlib figure inside a WxPython panel