code:
import pandas as pd
import numpy as np
from datetime import datetime, timedelta, date
import time
import matplotlib.pyplot as plt
import matplotlib.dates as dates

df2 = pd.DataFrame({'A' : np.random.rand(1440).cumsum()}, index = pd.date_range('1/1/2015', periods=1440, freq='1min'))

df2.A.plot()
plt.gca().xaxis.set_major_locator(dates.HourLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()

rawDescription: Drop the date from a matplotlib time series plot


rawDescription: Creating an array of irregular numbers in Numpy


code:
def update_func(model):
    def update(modeladmin, request, queryset):
        ...
        form = module_form(request.POST)
        if form.is_valid():
            one = form.cleaned_data[model]
            ...
        ...
    return update
admin.site.add_action(update_func('module'))
admin.site.add_action(update_func('src'))

rawDescription: How to write two similar django admin actions

description: Write two similar django admin actions


rawDescription: Can I use cStringIO the same as StringIO?

description: Use cStringIO the same as StringIO


code:
import re
def stripComments(code):
    code = str(code)
    return re.sub(r'(?m)^ *#.*\n?', '', code)

print(stripComments("""#foo bar
bar foo
# buz"""))

rawDescription: How to remove '#' comments from a string?

description: Remove '#' comments from a string


code:
for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
    for title in entry.findall('{http://www.w3.org/2005/Atom}title'):
        name = title.text
        contacts_list.append(name)

rawDescription: Parsing Google contacts feed in Python

description: Parsing Google contacts feed in Python


code:
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

x = numpy.linspace(0, 2*numpy.pi, 200)
y = numpy.linspace(0, 2*numpy.pi, 200)

xx, yy = numpy.meshgrid(x, y)

z = numpy.sin(xx) * numpy.cos(yy)

fig = plt.figure()
s = fig.add_subplot(1, 1, 1)
s.imshow(z, vmin=0, vmax=1)
s.contour(z, levels=[0.5])
fig.savefig('t.png')

rawDescription: Transition line in heat map - python

description: Transition line in heat map - python


code:
t = "hoboboobbobbbobobbopbbobbbpbooboboboobbobovob"
l = "bob"
count = 0
for x in range(len(t)-len(l)+1):
    if (l == t[x:x+len(l)]):
        count += 1

print(count)

rawDescription: How can i write a piece of code that would check the amount of times a word has occured from the user input

description: Write a piece of code that would check the amount of times a word has occured from the user input


code:
import re # use this library for splitting off words

all_words = [] # initialize list to store the words

with open('my_file.txt') as f: # best way to open a file
   for line in f:
       line = line.strip() # remove trailing newline
       words = re.split(r'\W+', line) # split the line into words even when you have punctuation
       all_words += words

# looping is done now, and all lines have been read

all_words = set(all_words) # remove duplicates
all_words = sorted(all_words) # sort (capitalized words will come first)

rawDescription: How do I parse text file in python to create a sorted list with duplicates removed

description: Parse text file in python to create a sorted list with duplicates removed


code:
print("Hello, and welcome! What is first and last name?")
name = input()
print("There are", len(name), "letters in your name.")
print("What letter would you like to search for in your name?")
letter = input()
if letter:
    find_letter = name.find(letter)
    print(find_letter+1)

rawDescription: string slicing, Search a character

description: String slicing, Search a character


code: "/ ".join([item for sublist in list1 for item in sublist])

rawDescription: Python - Remove square brackets from list


code:
import shutil
import os

from distutils.core import setup
from distutils.core import Extension

from distutils.command.build_ext import build_ext
from distutils.command.install_lib import install_lib

library = None

def generate_lib():
    """
        Build library and copy it to a temp folder.
        :returns: Location of the generated library is returned.
    """
    raise NotImplementedError

class MyInstall(install_lib):
    def install(self):
        global library
        shutil.move(library, self.install_dir)
        return [os.path.join(self.install_dir, library.split(os.sep)[-1])]

class MyBuildExtension(build_ext):
    def run(self):
        global library
        library = create_lib();

module = Extension('name',
                   sources=[])

setup(
    name='...',
    version='...',
    ext_modules=[module],
    description='...',
    long_description='...',
    author='...',
    author_email='...',
    url='...',
    keywords='...',
    license='...',
    platforms=[],
    classifiers=[],
    cmdclass={
        'build_ext': MyBuildExtension,
        'install_lib': MyInstall
    },
)

rawDescription: Can I use an alternative build system for my Python extension module (written in C++)?

description: Use an alternative build system for my Python extension module (written in C++)


rawDescription: How do I write a regex function in Python that checks if a user has only letters and numbers?

description: Write a regex function in Python that checks if a user has only letters and numbers


code:
import sys
from PyQt4 import QtGui, QtCore

class mymainwindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self, None, QtCore.Qt.WindowStaysOnTopHint)

app = QtGui.QApplication(sys.argv)
mywindow = mymainwindow()
mywindow.show()
app.exec_()

rawDescription: PyQt: Always on top

description: PyQt: Always on top


code:
yield self.publish('com.example.onhello', counter,
   options = autobahn.wamp.types.PublishOptions(excludeMe = False))

rawDescription: Single AppSession can't subscribe to and publish on the same topic


code:
import importlib
importlib.reload

rawDescription: Reload a Module in Python 3.4

description: Reload a Module in Python 3.4


code:
import numpy as np
import cv2

# Input image
image = cv2.imread('oaHUs.jpg')

# Converts to grey for better reulsts
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Converts to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# HSV values
lower_skin = np.array([5,36,53])
upper_skin = np.array([19,120,125])

mask = cv2.inRange(hsv, lower_skin, upper_skin)

mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)

# Finds contours
im2, cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Draws contours
for c in cnts:
    if cv2.contourArea(c) < 3000:
        continue

    (x, y, w, h) = cv2.boundingRect(c)
    cv2.rectangle(image, (x,y), (x+w,y+h), (0, 255, 0), 2)

    ## BEGIN - draw rotated rectangle
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(image,[box],0,(0,191,255),2)
    ## END - draw rotated rectangle

cv2.imwrite('out.png', image)

rawDescription: Drawing angled rectangles in OpenCV

description: Drawing angled rectangles in OpenCV


code:
if monthStr in Mylist1 and dayStr in range(0, 32):
    print("Valid date")
else:
    print("Not a Valid date")

rawDescription: How can I find if user input is inclusive in list of arbitrary integers in Python 3.3.0

description: Find if user input is inclusive in list of arbitrary integers in Python 3.3.0


code:
class Rating(models.Model):
    content = models.OneToOneField(Content, primary_key=True)
    ip =  models.CharField(max_length=200, blank=True)
    rating = models.IntegerField(default=0)

    class Meta:
        unique_together= (('content', 'ip'),)

rawDescription: How to make uniques in Django Models? And also index a column in Django

description: Make uniques in Django Models? And also index a column in Django


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.text = CustomText(self, background="white")
        self.pos = tk.Label(self, text="Position: ", anchor="w", background="gray")
        self.pos.pack(side="top", fill="x")
        self.text.pack(side="right", fill="both", expand=True)

        self.text.bind("<<Change>>", self._on_change)

        self.text.insert("end", "one\ntwo\nthree\n")
        self.text.insert("end", "four\n",("bigfont",))
        self.text.insert("end", "five\n")

    def _on_change(self, event):
        message = "Position: " + self.text.index("insert")
        self.pos.configure(text=message)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lrange $args 0 2] == {mark set insert})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True);
    root.mainloop()

rawDescription: How to I have the call back in Tkinter when I change the current insert position


code:
from lxml import etree
# Create Xml
root = etree.Element("UpdateInventoryRequest")
doc = etree.ElementTree(root)

root.append(etree.Element("StartDate"))
root.append(etree.Element("RoomId"))
root.append(etree.Element("Data"))
data_root = root[2]
data_root.append(etree.Element("Availability"))
data_root.append(etree.Element("Price"))
# Xml in code

def buildXmlUpdate(dfrom, roomId, ldays):

    start_date_sard = dfrom
    roomId = str(roomId)
    room_id_sard = roomId

    for n in ldays:
        print (dfrom, roomId, n)
        ldays[-1]['avail'] = str(ldays[-1]['avail'])
        ldays[-1]['price'] =str(ldays[-1]['price'])
        availability_in_data = ldays[-1]['avail']
        price_in_data = ldays[-1]['price']

    root[0].text = start_date_sard
    root[1].text = room_id_sard
    data_root[0].text = availability_in_data
    data_root[1].text = price_in_data

#here execute the function

buildXmlUpdate('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
doc.write('testoutput.xml', pretty_print=True)

rawDescription: AttributeError: 'NoneType' object has no attribute 'text'


code: matches = re.findall(r'#\w*', line)

rawDescription: How can I grab all terms beginning with '#'?

description: Grab all terms beginning with '#'


code:
from numpy import allclose,zeros_like
from numpy.random import rand
from numpy.linalg import solve

# generate the 5 vectors as random arrays
mat = rand(5,5)
v1,v2,v3,v4,v5 = mat.T
v0 = rand(5)
x= solve(mat,v0)

#first check
assert allclose(dot(mat,x),v0)

#2nd check, which is the equation of the OP
res = zeros_like(v0)
for xj,vj in zip([v1,v2,v3,v4,v5],x):
    res+= xj*vj

assert allclose(res,v0)

rawDescription: Expand vector in terms of others

description: Expand vector in terms of others


rawDescription: Converting decimal to Formatted Binary and Hex - Python


code:
def item(i, v):
  if i != 1: return v
  return strangestuff(v)

for row in rows:
  t = tuple(item(i, c.InnerText)
            for i, c in enumerate(row.Descendants[TableCell]())
           )

rawDescription: Create a new Tuple with one element modified


rawDescription: how to get this string using python

description: Get this string using python


rawDescription: Python Pyplot proper candlestick timestamp epoch change and scale


code:
import numpy as np
from scipy.interpolate import pchip
import matplotlib.pyplot as plt

# Data to be interpolated.
x = np.arange(10.0)
y = np.array([5.0, 10.0, 20.0, 15.0, 13.0, 22.0, 20.0, 15.0, 12.0, 16.0])

# Create the interpolator.
interp = pchip(x, y)

# Dense x for the smooth curve.
xx = np.linspace(0, 9.0, 101)

# Plot it all.
plt.plot(xx, interp(xx))
plt.plot(x, y, 'bo')
plt.ylim(0, 25)
plt.grid(True)
plt.show()

rawDescription: How to plot line (polygonal chain) with numpy/scipy/matplotlib with minimal smoothing

description: Plot line (polygonal chain) with numpy/scipy/matplotlib with minimal smoothing


code:
for i, rec in enumerate(records):
    if rec.call_duration is None:
        records[i] = rec._replace(call_duration=0)

rawDescription: Replacing value of variable in list of named tuples


code:
import pylab as p
p.matshow(p.array([[0,1],[1,1]]),cmap="Greys") ; p.show()

rawDescription: Graphically represent lists

description: Graphically represent lists


code:
import numpy as np
xind = np.floor((x-xmin)/xdelta).astype(int)
yind = np.floor((y-ymin)/ydelta).astype(int)

xind[np.argmax(x)] = -1
yind[np.argmax(y)] = -1

arr = grid[xind,yind]

rawDescription: reduce time for a long for-loop in python

description: Reduce time for a long for-loop in python


code:
from bs4 import BeautifulSoup
html_doc= """

<topic>oil, gas</topic>
body text

<topic>food</topic>
body text

<topic>cars</topic>
body text

"""
soup = BeautifulSoup(html_doc)

bodies = [a.get_text() for a in soup.find_all('body')]
topics = [a.get_text() for a in soup.find_all('topic')]

rawDescription: beautifulsoup findall

description: Beautifulsoup findall


code:
import lxml.etree as ET

content = '''\
<root>
   She
   <opt>went</opt>
   <opt>didn't go</opt>
   to school.
</root>'''

root = ET.fromstring(content)
root.tag = 'sentence'
newroot = ET.Element('root')
newroot.insert(0,root)
print(ET.tostring(newroot))

# <root><sentence>
#    She
#    <opt>went</opt>
#    <opt>didn't go</opt>
#    to school.
# </sentence></root>

rawDescription: How to wrap an element (its text and subelements) in Python 3?

description: Wrap an element (its text and subelements) in Python 3


code:
def directory_exists(self, directory_name):
        new_dir_name = directory_name.strip("/")
        if new_dir_name in ftp.nlst():
            self.change_directory(directory_name)
        else:
            self.make_directory(directory_name)
            self.change_directory(directory_name)

rawDescription: Change directories in Python, not working


code:
from itertools import chain
from operator import attrgetter

images = ImageItem.objects.filter(user=user)
video = VideoItem.objects.filter(user=user)
audio = AudioItem.objects.filter(user=user)
result_list = sorted(chain(images, video, audio),
                     key=attrgetter('upload_date'),
                     reverse=True)

rawDescription: Django: Ordered list of model instances from different models?


code:
targetword = "good"
wordmap = {
    "best": targetword,
    "positive": targetword,
    "awesome": targetword,
    "fantastic": targetword
}

rawDescription: a data structure with key as a cluster of words and value as a single word or string

description: A data structure with key as a cluster of words and value as a single word or string


code:
my_list = ['red', 'blue', 'green', 'yellow', 'purple', 'black']
result = (my_list[i:i+2] for i in range(0, len(my_list), 2))
list(result)

rawDescription: Python add multiple lists to list

description: Python add multiple lists to list


code:
import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import FixedLocator, \
     MaxNLocator, DictFormatter
import numpy as np
import matplotlib.pyplot as plt

# generate 100 random data points
# order the theta coordinates

# theta between 0 and 2*pi
theta = np.random.rand(100)*2.*np.pi
theta = np.sort(theta)

# "radius" between 0 and a max value of 40,000
# as roughly in your example
# normalize the r coordinates and offset by 1 (will be clear later)
MAX_R = 40000.
radius = np.random.rand(100)*MAX_R
radius = radius/np.max(radius) + 1.

# initialize figure:
fig = plt.figure()

# set up polar axis
tr = PolarAxes.PolarTransform()

# define angle ticks around the circumference:
angle_ticks = [(0, r"$0$"),
               (.25*np.pi, r"$\frac{1}{4}\pi$"),
               (.5*np.pi, r"$\frac{1}{2}\pi$"),
               (.75*np.pi, r"$\frac{3}{4}\pi$"),
               (1.*np.pi, r"$\pi$"),
               (1.25*np.pi, r"$\frac{5}{4}\pi$"),
               (1.5*np.pi, r"$\frac{3}{2}\pi$"),
               (1.75*np.pi, r"$\frac{7}{4}\pi$")]

# set up ticks and spacing around the circle
grid_locator1 = FixedLocator([v for v, s in angle_ticks])
tick_formatter1 = DictFormatter(dict(angle_ticks))

# set up grid spacing along the 'radius'
radius_ticks = [(1., '0.0'),
                (1.5, '%i' % (MAX_R/2.)),
                (2.0, '%i' % (MAX_R))]

grid_locator2 = FixedLocator([v for v, s in radius_ticks])
tick_formatter2 = DictFormatter(dict(radius_ticks))

# set up axis:
# tr: the polar axis setup
# extremes: theta max, theta min, r max, r min
# the grid for the theta axis
# the grid for the r axis
# the tick formatting for the theta axis
# the tick formatting for the r axis
grid_helper = floating_axes.GridHelperCurveLinear(tr,
                                                  extremes=(2.*np.pi, 0, 2, 1),
                                                  grid_locator1=grid_locator1,
                                                  grid_locator2=grid_locator2,
                                                  tick_formatter1=tick_formatter1,
                                                  tick_formatter2=tick_formatter2)

ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
fig.add_subplot(ax1)

# create a parasite axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)

aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder=0.9 # but this has a side effect that the patch is
                     # drawn twice, and possibly over some other
                     # artists. So, we decrease the zorder a bit to
                     # prevent this.

# plot your data:
aux_ax.plot(theta, radius)
plt.show()

rawDescription: Matplotlib polar plot radial axis offset


code:
frames = [pd.read_csv('f1.csv'), pd.read_csv('f2.csv')]
result = concat(frames,ignore_index=True)

rawDescription: Merge two files in Python PANDAS?

description: Merge two files in Python PANDAS


code:
import gtk

class ScaleImage:
    def __init__(self):
        self.temp_height = 0
        self.temp_width = 0

        window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        image = gtk.Image()
        image.set_from_file('/home/my_test_image.jpg')
        self.pixbuf = image.get_pixbuf()
        image.connect('expose-event', self.on_image_resize, window)

        box = gtk.ScrolledWindow()
        box.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        box.add(image)

        window.add(box)
        window.set_size_request(300, 300)
        window.show_all()

    def on_image_resize(self, widget, event, window):
        allocation = widget.get_allocation()
        if self.temp_height != allocation.height or self.temp_width != allocation.width:
            self.temp_height = allocation.height
            self.temp_width = allocation.width
            pixbuf = self.pixbuf.scale_simple(allocation.width, allocation.height, gtk.gdk.INTERP_BILINEAR)
            widget.set_from_pixbuf(pixbuf)

    def close_application(self, widget, event, data=None):
        gtk.main_quit()
        return False

if __name__ == "__main__":
    ScaleImage()
    gtk.main()

rawDescription: Automatic image scaling on resize with (Py)GTK


code:
s = 'i am what i am am'
seen = {}
result = []
for index, word in enumerate(s.split(), 1):
    result.append(seen.setdefault(word, index))
result = ' '.join(map(str, result))

print(result) # 1 2 3 1 2 2

rawDescription: How can save the order of a string?(Python 3.)


code:
class FUSE(object):

    """This class is the lower level interface and should not be subclassed

       under normal use. Its methods are called by fuse.

       Assumes API version 2.6 or later."""

    def __init__(self, operations, mountpoint, raw_fi=False, **kwargs):

        """Setting raw_fi to True will cause FUSE to pass the fuse_file_info

           class as is to Operations, instead of just the fh field.

           This gives you access to direct_io, keep_cache, etc."""

rawDescription: What is happening when this code calls FUSE like this?


code: elistable = list(csv.DictReader(open("./elispotable.csv", 'rU')))

rawDescription: Can I edit dictionaries created by dictreader in python

description: Edit dictionaries created by dictreader in python


code:
from xml.dom.minidom import parse
import xml.dom.minidom
import csv
from itertools import count
c = count(1) #starts from 1
def writeToCSV(myLibrary):
    with open('csvout.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter = ',')
        writer.writerow(['key', 'title', 'author', 'author']) #added key
        books = myLibrary.getElementsByTagName("book")
        for book in books:
            titleValue = book.getElementsByTagName("title")[0].childNodes[0].data
            authors =[]
            for author in book.getElementsByTagName("author"):
                authors.append(author.childNodes[0].data)
            writer.writerow([c.next()] + [titleValue] + authors)

doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]

rawDescription: writer.writerow parsing XML to CSV

description: Writer.writerow parsing XML to CSV


code:
def create_dict():
  global my_dict
  if 'my_dict' not in globals():
    my_dict = {}

create_dict()
print (my_dict)

rawDescription: Python: make a dictionary created in a function visible to outside world


code:
class GalleryList(ListView):

    def get_context_data(self, **kwargs):
        ctx = super(GalleryList, self).get_context_data(**kwargs)
        ctx['title'] = 'My Title'
        ctx['description'] = 'My Description'
        return ctx

rawDescription: Django: ListView. Where can I declare variables that I want to have on template?


code:
myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))

rawDescription: How to convert elements(string) to integer in tuple in Python

description: Convert elements(string) to integer in tuple in Python


code:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, cm,landscape
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle, Image
from reportlab.lib.enums import TA_LEFT, TA_CENTER
from reportlab.lib import colors
from reportlab.lib.units import inch

a = Image.open("path/to/temp.jpg")
a.drawHeight = 2*inch
a.drawWidth = 2*inch
data=[['1',a],['3','4']]
c = canvas.Canvas("Reportlabtest.pdf", pagesize=landscape(A4))
table = Table(data, colWidths=200, rowHeights=50)
table.setStyle(TableStyle([
                           ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                           ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                           ('BACKGROUND',(0,0),(-1,2),colors.lightgrey)
                           ]))
table.wrapOn(c, 200, 400)
table.drawOn(c,20,50)
c.save()

rawDescription: Python reportlab inserting image into table


code:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from composite_form.forms import CompositeForm
from example.models import Profile

class BaseProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ("user")

class ProfileForm(CompositeForm):
    form_list = [UserCreationForm, BaseProfileForm]

    def clean_address(self):
        return "blah"

    def save(self, commit=True):
        if not self.is_valid():
            raise ValueError("Invalid form")
        user_form = self.get_form(UserCreationForm)
        user = user_form.save()
        profile_form = self.get_form(BaseProfileForm)
        profile_form.instance.user = user
        return profile_form.save()

rawDescription: Django: Put a Form into a Form (recursive ...)


code:
mylist = [1,2,3,4,5,6]
mylist[::3]
mylist[1::3]
mylist[2::3]
lis = range(1,21)
new1, new2, new3 = [lis[i::3] for i in xrange(3)]
new1
new2
new3

rawDescription: python create several lists from one list

description: Python create several lists from one list


code:
class MockMkdir(object):
    def __init__(self):
        self.received_args = None
    def __call__(*args):
        self.received_args = args

class MyTest(unittest.TestCase):
    def setUp():
        self._orig_mkdir = os.mkdir
        os.mkdir = MockMkdir()
    def tearDown():
        os.mkdir = self._orig_mkdir
    def test_set_path(self):
        site = Site()
        site.set_path('foo/bar')
        self.assertEqual(os.mkdir.received_args[0], 'foo/bar')

rawDescription: How to Unit Test 'mkdir' function without file system access?


rawDescription: Sort a Python date string list

description: Sort a Python date string list


code:
class CustomAuthenticationPolicy(object):
    def effective_principals(self, request):
        principals = [Everyone]

        identity = request.headers.get('x-identity')
        # validate the identity somehow
        if is_valid(identity):
            principals += [Authenticated, identity, 'g:editors']
        return principals

config.set_authentication_policy(CustomAuthenticationPolicy())

rawDescription: Pyramid: Is it possible to use Authorization without Authentication?


code:
import struct
struct.pack('!H', 65000)

rawDescription: Python: Creating 16-bit source and destination ports for a packet header


code:
import wx  # for gui

class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Title', size=(300,200))
        tournLevel = ['$10,000', '$15,000', '$20,000', '$50,000','$75,000','$100,000']
        self.levelBox = wx.ListBox(panel, -1, (40, 50), (90, 90), tournLevel)
        self.levelBox.SetSelection(1)  # default selection
        self.checkButton = wx.Button(panel, label= "Check Now", pos = (150, 50), size = (90, 40))
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.checkButton)

    def OnClick(self, event):
        currLevel = self.levelBox.GetSelection()
        print(currLevel) # to test if GetSelection is working

if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame(parent=None, id=-1)
    frame.Show()
    app.MainLoop()

rawDescription: WxPython using Listbox and other UserInput with a Button


code:
t1, t2 = datetime.time(...), datetime.time(...)

t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond

delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])

rawDescription: What is the simplest way to find the difference between 2 times in python?


code:
'''
Created on 5-mrt.-2012
@author: Max
'''
from Tkinter import *

class main(Tk):
    def __init__(self,parent):
        self.mainWindow()
    def mainWindow(self):
        '''Make the main window '''
        #self.quitAll()
        self.app = Tk()
        self.app.title('NMBS application')
        self.makeAppButtons()
        self.finish(self.app)
    def makeAppButtons(self):
        '''Make all the buttons for the main menu'''
        button_lijn = Button(self.app, text="Voeg lijnritten toe", command = self.lijnritten)
        button_lijn.pack()
    def finish(self,window):
        ''' Make the main window'''
        window.mainloop()
    def endButton(self,window):
        '''Make a quit button'''
        button_back = Button(window,text="Sluiten",command = self.mainWindow)
        button_back.pack()
    def quitAll(self):
        '''Close all the current windows'''
        self.lijn_window.quit()
        self.app.quit()
    def lijnritten(self):
        ''' Make the lijnritten window'''
        self.app.quit()
        self.lijn_window = Tk()
        self.lijn_window.title("lijnritten")
        self.endButton(self.lijn_window)
        self.finish(self.lijn_window)
main(None)

rawDescription: Python GUI with Tkinter

description: Python GUI with Tkinter


code:
import tkinter as tk

root = tk.Tk()

pressed = False

def onClick(event):
    global pressed
    pressed = not pressed # toggle pressed when clicked
    print('Pressed')

def onMove(event):
    if pressed:
        print(event.x, event.y)

root.bind('<Button-2>', onClick)
root.bind('<Motion>', onMove)

root.mainloop()

rawDescription: tkinter: How to automatically scroll using middle mouse button?

description: Tkinter: How to automatically scroll using middle mouse button


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

N = 100
xmax = 1.
v_sigma = 2.5 / 2. # 95% of the samples contained within 0, 5
v_mean  = 2.5      # mean at 2.5

N_sub = 10
v_sub_index = np.random.randint(0, N, N_sub)

particle_position = np.random.rand (N) * xmax
particle_velocity = np.random.randn(N)

particle_position_sub   = np.array(particle_position[v_sub_index])
particle_velocity_sub   = np.array(particle_velocity[v_sub_index])
particle_position_nosub = np.delete(particle_position, v_sub_index)
particle_velocity_nosub = np.delete(particle_velocity, v_sub_index)

pl.scatter(particle_position_nosub, particle_velocity_nosub, color='b', marker='o')
pl.scatter(particle_position_sub  , particle_velocity_sub  , color='r', marker='^')
pl.show()

rawDescription: Python/Matplotlib: Randomly select "sample" scatter points for different marker


rawDescription: Import specific class or function in Python Parallel job


code:
import dbus
session_bus = dbus.SessionBus()
purple_obj = session_bus.get_object("im.pidgin.purple.PurpleService",
                                    "/im/pidgin/purple/PurpleObject")
purple_int = dbus.Interface(purple_obj,
                            "im.pidgin.purple.PurpleInterface")
my_account_id = purple_int.PurpleAccountsGetAllActive()[0] # or some other account from yours
conv = purple_int.PurpleConversationNew(1, my_account_id, "recipient's email")
conv_im = purple_int.PurpleConvIm(conv)
purple_int.PurpleConvImSend(conv_im, "This is your message")

rawDescription: Send Notification to pidgin via python 2.4


code:
with open('file.txt') as f:
    # Remove the \n characters at the end of each line
    all_lines = [x.strip() for x in f.readlines()]
    for line in all_lines:
        # Check for presence of word' or word's
        if line+"'" in all_lines or line+"'s" in all_lines:
            print('****')
        else:
            print(line)

rawDescription: Iterative regex in Python: find and replace


code: foo = foo.replace(' ', '')[:-3].upper()

rawDescription: Python Remove last 3 characters of a string


code:
example = list(range(10))
list(filter(lambda n: n % 2, example))

rawDescription: Does filter preserve list ordering?

description: Does filter preserve list ordering


code: df.groupby("item_id").filter(lambda x: len(x) > 1)

rawDescription: Delete all values matching index with less than N occurrences in a pandas dataframe


code: getattr(alist, 'remove')(val)

rawDescription: Is it possible to map dictionary to object operations in python


code:
for rule in rules:
    negative_rules.append((rule.key.lower() + "__" + "iexact", rule.value))

negative_rules = reduce(operator.or_, [Q(x) for x in negative_rules]) if negative_rules else Q()

Obj.objects.exclude(negative_rules)

rawDescription: Django exclude for same field with different values


rawDescription: Converting IPv4 Address to a Hex IPv6 Address in Python


code:
'foo\u2116'
'foo\N{NUMERO SIGN}'

rawDescription: Operating on character '№'

description: Operating on character '№'


code:
from itertools import permutations
a = [1, 2, 3]
list(permutations(a, 2))

rawDescription: how to collect many tuple from a list in python in one line?

description: Collect many tuple from a list in python in one line


code:
from PyQt4 import QtCore
s = QtCore.QString('foo')
s

rawDescription: How to create QString in PyQt4?

description: Create QString in PyQt4


code: Section = 'Sec_' + Section

rawDescription: Concatenate strings in python 2.4?

description: Concatenate strings in python 2.4


code:
import tempfile
import itertools as IT
import os

def uniquify(path, sep = ''):
    def name_sequence():
        count = IT.count()
        yield ''
        while True:
            yield '{s}{n:d}'.format(s = sep, n = next(count))
    orig = tempfile._name_sequence
    with tempfile._once_lock:
        tempfile._name_sequence = name_sequence()
        path = os.path.normpath(path)
        dirname, basename = os.path.split(path)
        filename, ext = os.path.splitext(basename)
        fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext)
        tempfile._name_sequence = orig
    return filename

print(uniquify('/tmp/file.pdf'))

rawDescription: python: Create file but if name exists add number

description: Python: Create file but if name exists add number


code:
import difflib
d = difflib.Differ()
l = list(d.compare("hello", "heXXo"))
l

rawDescription: In python, produce HTML highlighting the differences of two simple strings


rawDescription: How to get the ip address of the computer which runs a web application in python

description: Get the ip address of the computer which runs a web application in python


code:
lst = "my first program".split()
set(itertools.permutations(lst))

rawDescription: get all combinations words of a string

description: Get all combinations words of a string


code:
from datetime import date
from shutil import copytree

currentDate = str(date.today())
currentDate = currentDate.replace("-", ".")
DESTINATION = "C:\\Users\\D34DLYHAX\\Desktop\\Backup " + currentDate

copytree("C:\\Users\\D34DLYHAX\\Pictures\\", DESTINATION + "\\My Pictures")

rawDescription: Python shutil.copytree function not working


code:
import django_tables2 as tables
import itertools

class CountryTable(tables.Table):
    counter = tables.Column(empty_values=(), orderable=False)

    def render_counter(self):
        self.row_counter = getattr(self, 'row_counter', itertools.count())
        return next(self.row_counter)

rawDescription: How to add counter column in django-tables2?

description: Add counter column in django-tables2


code:
# Create some sample data to play with
# Function to duplicate rows

rawDescription: How to create multiple copies of rows by multiplication in pandas?

description: Create multiple copies of rows by multiplication in pandas


code:
import re
def open_delimited(filename, delimiter, *args, **kwargs):
    """
    http://stackoverflow.com/a/17508761/190597
    """
    with open(filename, *args, **kwargs) as infile:
        chunksize = 10000
        remainder = ''
        for chunk in iter(lambda: infile.read(chunksize), ''):
            pieces = re.split(delimiter, remainder + chunk)
            for piece in pieces[:-1]:
                yield piece
            remainder = pieces[-1]
        if remainder:
            yield remainder

filename = 'post.txt'
for chunk in open_delimited(filename, '##', 'r'):
    print(chunk)
    print('-'*80)

rawDescription: Parsing big text file using regex

description: Parsing big text file using regex


rawDescription: Int in base 2 to binary string python

description: Int in base 2 to binary string python


code:
from model01 import Model01Form
from model02 import Model02Form

rawDescription: Python Submodules an easier reference

description: Python Submodules an easier reference


code:
data = {}
for e in Estate.objects.select_related("sub_region__region__country"):
    sub, region, country = e.sub_region, e.sub_region.region, e.sub_region.region.country
    if country.name not in data:
        data[country.name] = {}
    if region.name not in data[country.name]:
        data[country.name][region.name] = {}
    if sub.name not in data[country.name][region.name]:
       data[country.name][region.name][sub.name] = []
    data[country.name][region.name][sub.name].append(e.name)
json_data = json.dumps(data)

rawDescription: Serializing JSON object effectively

description: Serializing JSON object effectively


code:
substr_start = my_str.find("L") - 2
substr.append(my_str[substr_start:substr_start+5])

rawDescription: creating sub-strings from strings without referring index

description: Creating sub-strings from strings without referring index


code:
import datetime
timestamp = "Tue, 19 Jan 2016 16:12:18 -0800 (PST)"
dt = datetime.datetime.strptime(timestamp, "%a, %d %b %Y %H:%M:%S %z (%Z)")

rawDescription: Converting gmail timestamp to strptime

description: Converting gmail timestamp to strptime


code:
offset = lines.count()
new_indexed_lines = (new_lines
  .zipWithIndex()
  .map(lambda xi: (xi[1] + offset, xi[0])))

rawDescription: generate/insert contiguous numbers to elements in a Spark RDD

description: Generate/insert contiguous numbers to elements in a Spark RDD


code: c.execute(statement, list_of_vars + [0, 100])

rawDescription: Using a list and a normal value

description: Using a list and a normal value


code:
import pydoc

import math # test
print(pydoc.render_doc(math))

rawDescription: How can I print Python's help page straight to stdout?

description: Print Python's help page straight to stdout


code: [i for i in range(100) if i > 10 if i < 50]

rawDescription: python list comprehension with multiple 'if's

description: Python list comprehension with multiple 'if's


code:
import pygame, sys
import time
pygame.init()
screen = pygame.display.set_mode([1500,750])
background = pygame.Surface(screen.get_size())
background.fill([255, 255, 255])

class Attacker(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.x_pos, self.y_pos = location
        self.rect.x, self.rect.y = location
        self.jumping = False
        self.falling = False
        self.direction = 1

    def jump(self):
        if self.y_pos > CEILING:
            self.x_pos += 1*self.direction
            self.y_pos -= 5
        else:
            self.jumping = False
            self.falling = True

        self.update_pos()

    def fall(self):
        if self.y_pos < FLOOR:
            self.x_pos += 1*self.direction
            self.y_pos += 5
        else:
            self.falling = False

        self.update_pos()

    def update_pos(self):
        self.rect.x = self.x_pos
        self.rect.y = self.y_pos

FLOOR = 700
CEILING = 300

my_ball = Attacker('wackyball.bmp',[300, FLOOR])

running = True
while running:
    if my_ball.jumping:
        my_ball.jump()
    if my_ball.falling:
        my_ball.fall()

    screen.blit(my_ball.image, my_ball.rect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                my_ball.y_pos -= 5
            elif event.key == pygame.K_DOWN:
                my_ball.y_pos += 5
            elif event.key == pygame.K_RIGHT:
                my_ball.direction = 1
                my_ball.x_pos += 5
            elif event.key == pygame.K_LEFT:
                my_ball.direction = -1
                my_ball.x_pos -= 5
            elif event.key == pygame.K_SPACE:
                if not my_ball.falling:
                    my_ball.jumping = True
            my_ball.update_pos()
    screen.blit(background, (0, 0))
    screen.blit(my_ball.image, my_ball.rect)
    pygame.display.flip()

pygame.quit()

rawDescription: Making program do two things at the same time and command crashes game


code:
board = []

pcol = 7
prow = 0

for x in range(8):
    board.append([" * "] * 8)

# player position
def player():
    board[pcol][prow] = " P "

def printboard(board):
    for row in board:
        row = " ".join(row)
        print (row)

def playermovement():
    global pcol
    global prow

    # clear position
    board[pcol][prow] = " * "

    # new position
    pcol = int(input("Column: "))
    prow = int(input("Vertical: "))
    pcol=7-pcol
    return board, pcol, prow

player()
printboard(board)

playermovement()

player()
printboard(board)

rawDescription: Python game player movement

description: Python game player movement


code:
values = """Item1 Linen Shirt
Item2 Linen Shirt
ItemB Linen Shirt1
Item Linen Skirt
ItemC Linen Skirt2"""

data = values.split('\n')

print(difflib.get_close_matches(data[0], data))

rawDescription: Django DISTINCT match pattern with tolerance


code:
db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...

rawDescription: looking for a more pythonic way to access the database

description: Looking for a more pythonic way to access the database


rawDescription: Extract items delimited with square brackets using python regular expressions


code:
class Foo(object):
    def f(self): pass

Foo.f
Foo().f
Foo.__dict__['f']
Foo.f.__func__
Foo.f.__func__.__get__(Foo(), Foo)
Foo.f.__func__.__get__(None, Foo)

rawDescription: python - call instance method using __func__

description: Python - call instance method using __func__


code:
import numpy as np
x = [2, 3, 4]
y = [1, 2, 3]
np.repeat(x, y)

rawDescription: Repeat each item in a list a number of times specified in another list


code: vsizer.Add(hsizer2, 1, wx.EXPAND)

rawDescription: Align control to bottom of panel in wxPython


code:
def open_url(url):
    pass #Open the url in a browser

for i,url in enumerate(url_list):
    label=tk.Label(frame,text=url)
    label.grid(row=i)
    label.bind("<Button-1>",lambda e,url=url:open_url(url))

rawDescription: Clickable Tkinter labels

description: Clickable Tkinter labels


code: last_item = soup.find_all("li", {"class":"fn"})[-1]

rawDescription: BeautifulSoup: Find n-th occurence of element


code:
def binary_search(array, x, low=0, high=None):
    if high is None:
        high = len(array)
    while low < high:
        mid = (low+high)//2
        if array[mid] < x:
            low = mid+1
        else:
            high = mid
    return -1 if low >= len(array) or array[low] != x else low

rawDescription: Wrong output binary search program

description: Wrong output binary search program


code:
import subprocess
args=["hello", "bobbity bob", "bye"]
subprocess.list2cmdline(args)

rawDescription: how to format a shell command line from a list of arguments in python

description: Format a shell command line from a list of arguments in python


code: re.sub(r'\b\w', lambda m: m.group(0).upper(), s.lower())

rawDescription: Creating a function identical to str.title() function in Python


code:
import csv

with open("input.txt") as infile, open('output.txt', 'w') as fout:
    outfile = csv.writer(fout, delimiter='\t')
    for name, id, seq in csv.reader(infile, delimiter='\t'):
        locs = [i for i,char in enumerate(seq) if char=='r']
        for loc in locs:
            outfile.writerow([name, id, seq[max(loc-35, 0) : loc+36]])

rawDescription: Retrieving character's flanking region

description: Retrieving character's flanking region


code:
foo_element = soup.find('macro', attrs={"name" : "foo"}) # returns the foo element
foo_element['value'] = "baz" # changes the value attribute

rawDescription: Edit XML value based on Key

description: Edit XML value based on Key


code: zip(*data) + [tuple(voxelGrid[x] for x in data)]

rawDescription: python map data to list of lists/tuples

description: Python map data to list of lists/tuples


code:
class Liquid(object):
    def foo(self):
        pass

    def bar(self):
        pass

class Water(Liquid):
    def __getattribute__(self, name):
        if name == 'bar':
            raise AttributeError("'Water' object has no attribute 'bar'")

l = Liquid()
l.bar()
w = Water()
w.bar()

rawDescription: Is there any way that I can restrict a child class from inheriting some of its parent's methods?


code:
import urllib2
import urlparse
import re

def get_hops(url):
    redirect_re = re.compile('<meta[^>]*?url=(.*?)["\']', re.IGNORECASE)
    hops = []
    while url:
        if url in hops:
            url = None
        else:
            hops.insert(0, url)
            response = urllib2.urlopen(url)
            if response.geturl() != url:
                hops.insert(0, response.geturl())
            # check for redirect meta tag
            match = redirect_re.search(response.read())
            if match:
                url = urlparse.urljoin(url, match.groups()[0].strip())
            else:
                url = None
    return hops

rawDescription: how to follow meta refreshes in Python

description: Follow meta refreshes in Python


code:
import datetime

iterations = 100000000000
subiterations = 10000
chunks, remaining = divmod(iterations, subiterations)

now = datetime.datetime.now()
printcounter = 0
for i in range(chunks):
    for j in range(subiterations):
        #Do operation
        pass

    printcounter += subiterations
    print('{:,d} at {} hours {} minutes'.format(printcounter, now.hour, now.minute))

if remaining:
    for j in range(remaining):
        #Do operation
        pass

    printcounter += remaining
    print('{:,d} at {} hours {} minutes'.format(printcounter, now.hour, now.minute))

rawDescription: Don't check variable every iteration

description: Don't check variable every iteration


code: file = open(r"D:\wamp\www\User_App.rar", "rb")

rawDescription: Downloaded file is damaged in django

description: Downloaded file is damaged in django


code:
fin = open("hi.bmp", "rb")
out = open("values.txt","rw")
value = struct.unpack('i', fin.read(4))[0]
out.write("%d\n" % value) # just loop over the 2 last lines
out.close()
fin.close()

rawDescription: Convert file of bytes to ints Python

description: Convert file of bytes to ints Python


code: find_element_by_xpath('//button[contains(text(), "Add to Cart")]')

rawDescription: Find button using associated text in selenium


code: from PyQt4 import Qt

rawDescription: import PyQt4 does not include PyQt4.QtCore or QtGui

description: Import PyQt4 does not include PyQt4.QtCore or QtGui


code:
from ast import literal_eval

a = literal_eval("[1, 2, 3]")

print(a)

rawDescription: String in to list Python

description: String in to list Python


code:
alldata = impdat.root.data
datastruct = {}
for names in impdat.rood.data.__members___:
    datastruct[names] = eval('alldata.' + names + '[0][:]')

rawDescription: Accessing Data from .mat (version 8.1) structure in Python


code: arr = [[int(i) for i in line.split()] for line in open('input.txt')]

rawDescription: Reading a triangle of numbers into a 2d array of ints in Python


code: pd.concat([DataFrame({'s1': s1}), DataFrame({'s2': s2})]).ffill().bfill()

rawDescription: Adding hetrogenous TimeSeries to a DataFrame


rawDescription: Python Mechanize upload

description: Python Mechanize upload


code:
import networkx as nx
import matplotlib.pyplot as plt

n = 100  # Number of nodes
m = 4  # Number of initial links
seed = 100
G = nx.barabasi_albert_graph(n, m, seed)

ncols = 10
pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}
nx.draw(G, pos, with_labels=True)
plt.show()

rawDescription: Python: how to generate a scale-free network with pre-defined node positions?


code:
#get the key
k = ob.getData().getKey()
#create a new Ipo
ni = Ipo.New('Key','ni')
#if there check if there already a key by that name, otherwise add key
if(k.ipo['Key 1'] == None):   k.ipo.addCurve('Key 1')
#add a point to the 'Key 1' ipo curve
k.ipo['Key 1'].append(BezTriple.New(6.0,0.8,0.1))

rawDescription: how do I set a value for a ShapeKey in Blender Python?

description: Set a value for a ShapeKey in Blender Python


code:
authors = []
directors = []
for persons in movie_json.get('results').get('authors'):
    for person in person:
        if person.get('person'):
            if person.get('key')=='author':
                authors.append(person.get('person'))
            elif person.get('key')=='director':
                directors.append(person.get('person'))
authors = None if authors == [] else ', '.join(authors)
directors = None if directors == [] else ', '.join(directors)

rawDescription: How to extract data with particular key from parsed json?

description: Extract data with particular key from parsed json


code:
import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame(zip(
    [1010, 2020, 3030, 2020, 1515, 3030, 4545],
    [.1, .2, .33, .25, .5, .75, .45],
    [.1, .2, .33, .25, .5, .75, .45],
))

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter objects from the dataframe writer object.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})
format3 = workbook.add_format({'num_format': 'h:mm:ss AM/PM'})

# Set the column width and format.
worksheet.set_column('B:B', 18, format1)

# Set the format but not the column width.
worksheet.set_column('C:C', None, format2)

worksheet.set_column('D:D', 16, format3)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

rawDescription: Writing pandas DataFrame to Excel with different formats for different columns


code:
with open('.myfile', 'r') as myfile:
    header = myfile.readline().split()
    game_number, tourney_number, hand_number = header[1], header[3], header[5]
    for line in myfile:
        player_name, player_action = line.split()[1:]

rawDescription: Best way to extract information from file

description: Extract information from file


code:
def lastF(name):
    """Function that takes a string of the form
    <FirstName LastName> as a parameter and returns
    a string of the form <LastName, F.>.
    """
    # If 'name' is empty (empty strings are False), return it.
    if not name:
        return name
    # Split name by spaces and assign the first item of the split to 'first'.
    first = name.split()[0]
    # Split name by spaces and assign the last item of the split to 'last'.
    last = name.split()[-1]
    # Concatenate 'last', ",", the first letter of 'first' and "." and return it.
    return last + ', ' + first[0] + '.'

rawDescription: Write a function for python

description: Write a function for python


rawDescription: How to delete element from list in Python?

description: Delete element from list in Python


code:
stat = cloudstorage.compose(
    [
        "path/to/part1",
        "path/to/part2",
        "path/to/part3",
        # ...
    ],
    "/my_bucket/path/to/output"
)

rawDescription: Handling big files with Google Cloud Storage API


code:
s = '2014-03-07T17:52:00.000+0000'
print(numpy.datetime64(s).item().replace(tzinfo=pytz.UTC).isoformat('T'))

rawDescription: Write numpy datetime64 in ISO 8601 with timezone


code:
from itertools import izip_longest

for row in izip_longest(*myDict.values(), fillvalue=''):
    ...

rawDescription: Writing all the values of a dictionary in columns


code:
class Migration:

    def forwards(self, orm):
        # Rename 'name' field to 'full_name'
        db.rename_column('app_foo', 'name', 'full_name')

    def backwards(self, orm):
        # Rename 'full_name' field to 'name'
        db.rename_column('app_foo', 'full_name', 'name')

rawDescription: Django - How to rename a model field using South?


code:
import re

expr = re.sub(r'\b' + ip + r'\b', "("+ip+".~"+ip+")", expr)

rawDescription: Issue with modifying string with python

description: Issue with modifying string with python


code: next((key for key, names in mylist.items() if 'Fred' in names), None)

rawDescription: Python 3 - Return dictionary key of searched value


code:
import cPickle as pickle

class Family(object):
    __slots__ = ['father', 'var1']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = father, var1
    def __getstate__(self):
        return self.father, self.var1
    def __setstate__(self, state):
        self.father, self.var1 = state

foo = Family('father',1)
foo.var1 = 2
foo_pickled = pickle.dumps(foo)
foo2 = pickle.loads(foo_pickled)
print(repr(foo2))
# <__main__.Family object at 0xb77037ec>

print(foo2.var1)
# 2

description: Python, override__getstate__() __setstate__()


code: import file1

rawDescription: import directory containing python src files as module

description: Import directory containing python src files as module


code:
GPIO.setmode(GPIO.BCM)
GPIO.Setup (17, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.Setup (18, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.Setup (21, GPIO.IN, Pull_up_down = GPIO.PUD_DOWN)
GPIO.Setup (22, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup (23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.Setup (24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

while True:
    try:
        if GPIO.input(17) == 1: # all `if` should be lowercase and the `try`
            writeTexts(+1,-370,55) # don't need `()` in if statements.
            writeTexts(today + difference1,-100,-200)
        if GPIO.input(18) == 1:
            WriteTexts(-1,-370,55)
        if GPIO.input(21) == 1:
            writeTexts(0,-370,55)
        if GPIO.Input(22) == 1:
            writeTexts(+1,280,55)
        if GPIO.input(23) == 1:
            writeTexts(-1,280,55)
            writeTexts(today + difference1,550,-200)
        if GPIO.input(24) == 1:
            writeTexts(0,280,55)
            sleep(.01)
    except KeyboardInterrupt: # missing `:`
        exit()

GPIO.Cleanup ()

rawDescription: python+raspberry pi gpio invalid syntax

description: Python+raspberry pi gpio invalid syntax


code:
with open('fileids2.txt', 'r') as f:
    genres = [word.strip() for word in f.next().split(',')]

rawDescription: create a list from separated comma items in a file

description: Create a list from separated comma items in a file


code:
import datetime
ts = 1388898695
dt = datetime.datetime.fromtimestamp(ts)
dt.hour,dt.minute,dt.second
next_ts = dt+datetime.timedelta(minutes=1,seconds=-dt.second)
next_ts.hour,next_ts.minute,next_ts.second
prev_ts = dt-datetime.timedelta(minutes=1,seconds=dt.second)
prev_ts.hour,prev_ts.minute,prev_ts.second

rawDescription: Python method to find time stamp difference to compute even time intervals


code:
querysting = "select Year, {} from table where Year={}".format(c,y)
df = pd.read_sql(querystring,db)

rawDescription: Passing a column name as a variable to a select statement in a function in python / pandas


code:
def anagram(a, b):
  # string to list
  str1 = list(a.lower())
  str2 = list(b.lower())

  #sort list
  str1.sort()
  str2.sort()

  #join list back to string
  str1 = ''.join(str1)
  str2 = ''.join(str2)

  return str1 == str2

print(anagram('Orchestra', 'Carthorse'))

rawDescription: Anagram test for two strings in python

description: Anagram test for two strings in python


code:
token = subprocess.Popen(["echo " + token],
                         stdout=subprocess.PIPE, shell=True).communicate()[0].strip()

rawDescription: Get output of Python command using Popen


code:
from time import sleep

class MyClass:
    def _my_func(self, x=sleep(1)):
        pass
    def my_func2(self):
        self._my_func()

class MyClass2:
    def my_func2(self):
        def my_func(x=sleep(1)):
            pass
        my_func()

rawDescription: function definition inside another function definition -slow?

description: Function definition inside another function definition -slow


code: child_orders = my_order.order_set.all()

rawDescription: Reverse self referencing foreign key in Django


code:
import numpy as NP
from matplotlib import pyplot as PLT
from matplotlib import cm as CM

A = NP.random.randint(10, 100, 100).reshape(10, 10)
mask =  NP.tri(A.shape[0], k=-1)
A = NP.ma.array(A, mask=mask) # mask out the lower triangle
fig = PLT.figure()
ax1 = fig.add_subplot(111)
cmap = CM.get_cmap('jet', 10) # jet doesn't have white color
cmap.set_bad('w') # default value is 'k'
ax1.imshow(A, interpolation="nearest", cmap=cmap)
ax1.grid(True)
PLT.show()

rawDescription: Plotting only upper/lower triangle of a heatmap


code: not all(t1)

rawDescription: Python - best way to check if tuple has any empty/None values?


code:
b=int(input("Please enter how many people have collected money: "))
total = [0]*b
for i in range(b):
    a=int(input("Please enter the amount raised: "))
    total[i] = a

rawDescription: For i in range(b) variable

description: For i in range(b) variable


code:
import matplotlib.pyplot as plt

x = [124.46, 8.20, 52.55, 4.33]
y = [124.46, 50.2, 78.3, 778.8]
xerr = [54.2, 0.1, 2.41, 1.78]
yerr = [22.55, 0.37, 3.77, 0.14]

descrip = ['Atom 1', 'Atom 2', 'Atom 3', 'Atom 4']

plt.errorbar(x, y, xerr, yerr, capsize=0, ls='none', color='black',
            elinewidth=2)

for xpos, ypos, name in zip(x, y, descrip):
    plt.annotate(name, (xpos, ypos), xytext=(8, 8), va='bottom',
                textcoords='offset points')

plt.show()

rawDescription: scatterplot with xerr and yerr with matplotlib

description: Scatterplot with xerr and yerr with matplotlib


code:
from itertools import imap, islice
with open('c:/file.sql') as inf, open('c:/file.txt','w') as outf:
    for line in imap(str.strip, islice(inf, 47, None)):
        data = line.split(',')
        if len(data) > 35:
            hash = data[13]
            select = hash[3:-1]
            outf.write(select+'\n')

rawDescription: Code iteration really slow, why?

description: Code iteration really slow, why


code: [i['x'] for i in a]

rawDescription: best way to get right thing using python

description: Get right thing using python


code:
from pybrain.structure import FeedForwardNetwork
n = FeedForwardNetwork()

from pybrain.structure import LinearLayer, SigmoidLayer
inLayer = LinearLayer(8)
hiddenLayer = SigmoidLayer(10)
hiddenLayer2 = SigmoidLayer(10)
outLayer = LinearLayer(2)

n.addInputModule(inLayer)
n.addModule(hiddenLayer)
n.addModule(hiddenLayer2)
n.addOutputModule(outLayer)

from pybrain.structure import FullConnection
in_to_hidden = FullConnection(inLayer, hiddenLayer1)
hidden_to_hidden = FullConnection(hiddenLayer1, hiddenLayer2)
hidden_to_out = FullConnection(hiddenLayer2, outLayer)

n.addConnection(in_to_hidden)
n.addConnection(hidden_to_hidden)
n.addConnection(hidden_to_out)

n.sortModules()

rawDescription: Weights in Multi Layer Neural Network

description: Weights in Multi Layer Neural Network


rawDescription: netifaces: Trying to get ipaddress of all Interfaces in Linux

description: Netifaces: Trying to get ipaddress of all Interfaces in Linux


code:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip_longest(a, b)

rawDescription: Get pairwise iterator with additional item in the end


code:
df = pd.read_csv(fn, parse_dates=[[0, 1]], index_col=0)
df.between_time("09:04:00", "09:25:00")

rawDescription: Geting data in between specific column variables in python


code:
class MSV(ScrollView):
    x_exclusion_lower = NumericProperty(None, allownone=True)
    x_exclusion_upper = NumericProperty(None, allownone=True)
    x_exclusion = ReferenceListProperty(x_exclusion_lower, x_exclusion_upper)

    def on_touch_down(self, touch):
        pos_in_sv = self.to_local(*touch.pos)
        if (self.x_exclusion_lower is not None or self.x_exclusion_upper is not None) and (self.x_exclusion_lower is None or self.x_exclusion_lower <= pos_in_sv[0]) and \
                (self.x_exclusion_upper is None or self.x_exclusion_upper >= pos_in_sv[0]):
            touch.push()
            touch.apply_transform_2d(self.to_local)
            if self.dispatch_children('on_touch_down', touch):
                return True
            touch.pop()
        super(MSV, self).on_touch_down(touch)

rawDescription: Ignore area in ScrollView for scrolling interactions


rawDescription: Convert key from dictionary to int in python


code:
annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')

#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--')
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

rawDescription: Plot a horizontal line using matplotlib

description: Plot a horizontal line using matplotlib


code: str = str[:1].upper() + str[1:]

rawDescription: Capitalize a string

description: Capitalize a string


code:
s='DIV ID=0X78800009 EXT="LOS ANGELES" TY=STANDARD OWN=0X74400002 ABBR=LA'

s.split('"')[1]
'LOS ANGELES'

rawDescription: Pull a specific substring out of a line in python


code:
@tornado.web.authenticated
def get(self):
    ...

rawDescription: What's a nice way to write a login required decorator for certain handlers in Tornado?


code: HTMLParser.HTMLParser().unescape( '😄' )

rawDescription: Convert HTML Entity to Python Emoji

description: Convert HTML Entity to Python Emoji


code:
import re
email = 'google@google.comyahoo@yahoo.com'
re.sub(r'\.com(\w)', '.com, \\1', email)

rawDescription: Replace characters using re.sub - keep one character


code:
def is_negative(word):
    if word in ["not", "no"] or word.endswith("n't"):
        return True
    else:
        return False

def negate_sequence(text):
    text = text.split()
    # remove punctuation
    text = [word.strip("?.,!:;") for word in text]
    # Prepend 'not' to each word if the preceeding word contains a negation.
    text = ['not '+word if is_negative(text[i-1]) else word for i, word in enumerate(text[:])]
    return text

if __name__ =="__main__":
    print(negate_sequence("i am not here right now, because i am not good to see that"))

rawDescription: How to add space in conditions Python

description: Add space in conditions Python


rawDescription: Migrating a PositiveSmallIntegerField to a PositiveIntegerField and using the BIGINT field in Postgres


code:
import numpy as np
import pandas as pd
from collections import defaultdict

# creating a dataframe
idx = ['one','two','two','two','three','three']
df = pd.DataFrame(np.random.randint(1,10,24).reshape((6,4)), index = idx, columns = list('ABCD'))
df = df.reset_index()

# converting the data frame to a dictionary based on the format desired
data_dict = defaultdict(list)
for counter in df.iterrows():
    data_dict[str(counter[1][0])].append(str(list(counter[1][1:]))[1:-1].replace(",",""))

# writing the dictionary to file
df2 = pd.DataFrame.from_dict(data_dict, orient = 'index')
df2.to_csv('temp.csv', header = False)

rawDescription: How to make a dictionary in python and save data in a file

description: Make a dictionary in python and save data in a file


code:
from sqlalchemy.schema import Column
from sqlalchemy.types import Unicode, Integer

from camelot.admin.entity_admin import EntityAdmin
from camelot.core.orm import Entity, ManyToOne, OneToMany
import camelot.types

class AlternativeAdmin(EntityAdmin):
    verbose_name = 'Employee'
    list_display = ['name']

class Company(Entity):
    __tablename__ = 'company'

    name = Column(Unicode())
    city = Column(Unicode())
    employees = OneToMany('Employee')

    def __unicode__(self):
        return self.name or ''

    class Admin(EntityAdmin):
        verbose_name = 'Company'
        verbose_name_plural = 'Companies'
        list_display = ['name', 'city', 'employees']
        field_attributes = {'employees': {'create_inline': True,
                                          'admin': AlternativeAdmin}}

class Employee(Entity):
    __tablename__ = "employee"

    name = Column(Unicode())
    age = Column(Integer())
    company = ManyToOne('Company')

    def __unicode__(self):
        return self.name or ''

    class Admin(EntityAdmin):
        verbose_name = 'Employee'
        list_display = ['name', 'age', 'company']

rawDescription: Camelot (Python framework): Specifying an Alternative EntityAdmin


code:
def get_index(self, particle):
    bounds = particle.aabb

    # right
    if bounds.x > self.v_midpoint:

        # bottom
        if bounds.y > self.h_midpoint:
            return 3

        # top
        elif bounds.y + bounds.height < self.h_midpoint:
            return 0

    # left
    elif bounds.x + bounds.width < self.v_midpoint:

        # bottom
        if bounds.y > self.h_midpoint:
            return 2

        # top
        elif bounds.y + bounds.height < self.h_midpoint:
            return 1

    return -1

rawDescription: Efficient quadtree implementation in python


code:
a = 5
b = 5
a is b
id(a)
id(b)
a = 1234
b = 1234
a is b
id(a)
id(b)

rawDescription: unusual comparision result when using is operator

description: Unusual comparision result when using is operator


code: thefile = urllib2.urlopen(someURL)

rawDescription: How do I use python-magic to get the file type of a file over the Internet?

description: Use python-magic to get the file type of a file over the Internet


code:
import simpy
import random

class Interupted(object):

    def __init__(self, env):
        self.env = env
        self.isInterrupted = False
        self.interruptions = 0
        self.action = env.process(self.run())

    def run(self):
        print('start at time %s' % (self.env.now))
        try:
            yield self.env.timeout(10)
        except simpy.Interrupt as interrupt:
            self.isInterrupted = not self.isInterrupted
            self.interruptions += 1
            print('interrupted at time %s interrupted: %s interrupted by: %s' % (self.env.now, self.isInterrupted, interrupt.cause))
        while (self.interruptions > 0):
            self.interruptions = self.interruptions - 1
            try:
                yield self.env.timeout(5)
            except simpy.Interrupt as interrupt:
                self.interruptions += 1
                print('interrupted at time %s interrupted: %s interrupted by: %s' % (self.env.now, self.isInterrupted, interrupt.cause))
        print('end at time %s' % (self.env.now))

class Interruptor(object):

    def __init__(self, env, interrupted):
        self.env = env
        self.interrupted = interrupted
        self.action = env.process(self.run(interrupted))

    def run(self, interrupted):
        for i in range(16):
            yield self.env.timeout(5)
            if(not interrupted.action.processed):
                interrupted.action.interrupt("interrupt nr: %s" % i)

env = simpy.Environment()
interrupted = Interupted(env)
interruptor = Interruptor(env, interrupted)
env.run(until=100)

rawDescription: Simpy; how to incorporate an unknown amount of interrupts


code:
import hashlib, glob
file_paths = glob.glob("/home/rolf/StackOverflow/*.py")
hash_object = hashlib.sha256(str(file_paths))
file_name= hash_object.hexdigest()
file_name
'f69dd9583eabae55319e9a56dbfc737cc16ab58634d9042f4c530e9a85e7d77c'

file_paths = glob.glob("/home/rolf/Research/*.py")
hash_object = hashlib.sha256(str(file_paths))
file_name= hash_object.hexdigest()
file_name
'dc4beec8e859b190d966068a52674d135f22520514ac1020b3e11a4af090e579'

rawDescription: Python: Constructing a unique file name for a list of files


rawDescription: Iterating over pairs of coordinates in Python


code:
class MyProcess(psutil.Process):
    def get_cpu_percent(self, interval=0.1):
        return 42

rawDescription: Is it possible to change the contents of __init__.py files of a module while runtime using python?


code:
from PyQt4 import QtCore

class Pot(QtCore.QObject):

    temperatureRaisedSignal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        QtCore.QObject.__init__(self)
        self.temperature = 1

    def Boil(self):
        self.temperatureRaisedSignal.emit()
        self.temperature += 1

class Thermometer():
    def __init__(self, pot):
        self.pot = pot
        self.pot.temperatureRaisedSignal.connect(self.temperatureWarning)

    def StartMeasure(self):
        self.pot.Boil()

    def temperatureWarning(self):
        print("Too high temperature!")

if __name__ == '__main__':
    pot = Pot()
    th = Thermometer(pot)
    th.StartMeasure()

rawDescription: How to connect pyqtSignal between classes in PyQT

description: Connect pyqtSignal between classes in PyQT


code:
class ToggleButton(Button):
    def __init__(self, text="ToggleButton", state=True):
        super(ToggleButton, self).__init__(text)
        self.state = state

    def press(self):
        super(ToggleButton, self).press()
        self.state = not self.state
        print('ToggleButton is now', 'ON' if self.state else 'OFF')

rawDescription: beginner Python class

description: Beginner Python class


code:
out_dict = {'123456':{'exam':[97, 98, 45], 'homework': [44,45]}}

# example of a list with grades. maybe read from a file?
homework_grades = [1,2,3,4]

# appends grades one at a time
for a_grade in homework_grades:
   out_dict['123456']['homework'].append(a_grade)

# or append all grades in one go.
out_dict['123456']['homework'] += homework_grades

rawDescription: Assistance with Nested Dictionary

description: Assistance with Nested Dictionary


code: print ('sup').capitalize()

rawDescription: Python 3 execution order quirk with print?


code:
upd = (t_node.update()
        .values(
            parent_id = t_node_node.c.parent_id,
            label = t_node_node.c.label,
            )
        .where(t_node_node.c.child_id == t_node.c.node_id)
        )

rawDescription: SQLAlchemy: update from_select

description: SQLAlchemy: update from_select


code:
self.processing_label.show()
QtGui.qApp.processEvents() # or QtCore.QCoreApplication.processEvents()
self.qry_db()

rawDescription: how to wait to force subroutine to show widget before it continue to next line

description: Wait to force subroutine to show widget before it continue to next line


code:
from pydub import AudioSegment

song = AudioSegment.from_file("/path/to/file.mp3", format="mp3")
song.export("/path/to/new/filename.mp4", format="mp4")

rawDescription: Export (but not save to) an audio file in PyDub?


code:
class X(str):
    def myMethod( self ):
            return int(self)
s=X("Hi Mom")
s.lower()
s.myMethod()
z=X("271828")
z.lower()
z.myMethod()

rawDescription: Extending builtin classes in python

description: Extending builtin classes in python


code:
import re
from collections import Counter

cnt = Counter()
ipre = re.compile(r'^(?P<ip>(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])) - -')
with open(infilename) as infile:
    for line in infile:
        m = ipre.match(line)
        if m is not None:
            ip = m.groupdict()['ip']
            cnt[ip] += 1

rawDescription: How to find how many times a particular ip appears in a log file?

description: Find how many times a particular ip appears in a log file


code:
msg = MIMEMultipart()
msg['From'], msg['To'], msg['Subject'] = ... # specify your sender, receiver, subject attributes
body = 'This is the body of the email.'
body = MIMEText(body) # convert the body to a MIME compatible string
msg.attach(body) # attach it to your main message

rawDescription: how to send a email body part through MIMEMultipart

description: Send a email body part through MIMEMultipart


code:
s = unicode(1)
type(s).__name__

rawDescription: Get name of type as a string

description: Get name of type as a string


code:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

rawDescription: What is the best way to compare floats for almost-equality in Python?


code:
output = subprocess.check_output(['wmic', 'PATH', 'Win32_videocontroller',  'GET', 'description'], universal_newlines=True)
print(output , "\n")

rawDescription: Python subprocess Messy output

description: Python subprocess Messy output


rawDescription: Remove duplicate sets from lists

description: Remove duplicate sets from lists


code:
def normalize(data):
  labels = data.map(lambda lp: lp.label)
  minLabel = labels.min()
  return data.map(
    lambda lp: LabeledPoint(lp.label - minLabel, lp.features))

rawDescription: How to shift labels in Python using Apache Spark

description: Shift labels in Python using Apache Spark


code: [[' '.join(w[0] for w in sent) for sent in p] for p in paras]

rawDescription: Python list comprehension troubles

description: Python list comprehension troubles


code:
import psycopg2
conn = psycopg2.connect("dbname=regress")
curs = conn.cursor()
curs.execute("create table my_table(id serial primary key, field_1 integer, field_2 integer);")
data = [(0, 0), (0, 0)]
curs.executemany(
    "INSERT INTO my_table (field_1, field_2) "
    "VALUES (%s, %s) RETURNING id;",
    data
)

curs.fetchall()

rawDescription: getting ids of multiple rows inserted in psycopg2

description: Getting ids of multiple rows inserted in psycopg2


code:
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
r.hmset('test', {1: 'a', 2: 'b'})
r.hset('test', 2, 'c')
r.hget('test', 2)

rawDescription: redis storing json data with hget command .while fetching forced to fetch all json data in place of single json variable

description: Redis storing json data with hget command .while fetching forced to fetch all json data in place of single json variable


code:
import time

def perform_actions():
    print("Hello.. again")

try:
    while True:
        perform_actions()
        try:
            while True: time.sleep(3600)
        except KeyboardInterrupt:
            time.sleep(0.5)
except KeyboardInterrupt:
    pass

rawDescription: Scanning Keypress in Python

description: Scanning Keypress in Python


code:
my_string = "abcdef"
my_interval = slice(1, 3)
print(my_string[my_interval])

rawDescription: I can save an interval in a variable?

description: I can save an interval in a variable


code:
@register.inclusion_tag('studies/student_block.html', takes_context = True)
def student_block(context):
    request = context['request']
    # you can use request what ever you want

rawDescription: Django Templatetag, request username

description: Django Templatetag, request username


code:
@app.route('/users/change_password/', methods=['PUT'])
@auth.login_required
def changeUserPassword(user):
    return auth.username() + ", You want to change your password"

rawDescription: Webservice - Use username in function after login


code:
a = "I AM A DEVELOPER"
a.lower().split()

rawDescription: Which one to prefer - line.lower() vs. word.lower()


code: a = [random.randrange(-10, 11) / 10 for _ in range(100)]

rawDescription: Use list comprehension without iteration variable


code:
class BlogPost(ndb.Model):
    title = ndb.StringProperty()
    content = ndb.TextProperty()
    timestamp = ndb.DateTimeProperty(auto_add_now=True)

# Then you can specify a parent in the constructor (where user is a User entity)
blog_post = BlogPost(parent=user)
blog_post.title = 'Post title'
blog_post.content = 'Post content'
blog_post.put()

rawDescription: Creating a user in Google App Engine and migrations the easy way


code:
class Person:
    def __init__(self, canvas, pts, i):
        self.canvas = canvas
        self.oval_id = self.canvas.create_oval(...)

    def change_color(self):
        self.canvas.itemconfigure(self.oval_id, ...)

rawDescription: Modifying a tkinter canvas object when creating it with a loop


code:
a = [3,4,1]
df_a = pd.DataFrame({'VAL2' : a})
df_b= pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})
pd.merge(df_a,b,left_on='VAL2',right_on='VAL1',how='outer')

rawDescription: ordering dataframe according to a list, matching one of the columns in pandas

description: Ordering dataframe according to a list, matching one of the columns in pandas


code:
with open("file_in.txt") as f:
   with open("file_out.txt","w") as f2:
        for line in f:
            if "my_test" in line:
                f2.write(line.rstrip("\n")+next(f)) # the next line :P

rawDescription: Search a string and write it in a new text file along with its next line by using Python


code:
import numpy as np
from sklearn.metrics import r2_score, mean_squared_error
secret_mses = []

def r2_secret_mse(estimator, X_test, y_test):
    predictions = estimator.predict(X_test)
    secret_mses.append(mean_squared_error(y_test, predictions))
    return r2_score(y_test, predictions)

X = np.random.randn(20, 10)
y = np.random.randn(20)

from sklearn.cross_validation import cross_val_score
from sklearn.linear_model import Ridge

r2_scores = cross_val_score(Ridge(), X, y, scoring=r2_secret_mse, cv=5)

rawDescription: How to get both MSE and R2 from a sklearn GridSearchCV?

description: Get both MSE and R2 from a sklearn GridSearchCV


code:
def productpage(self, response):
    specs = Selector(response).xpath('//*[@id="Specs"]/fieldset')
    itemdict = {}
    for i in specs:
        test = i.xpath('dl')
        for t in test:
            itemdict[t.xpath('dt/text()').extract()[0]] = t.xpath('dd/text()').extract()[0]
        item = response.meta['item']
    item['make'] = itemdict['Brand']
    yield item

rawDescription: Geting data from table with Scrapy, different row order per page


code:
input_file = open('/path/to/input_file')
output_file = open('/path/to/output_file', 'w')
for line in input_file:
    answer = myFunction(line)
    output_file.write("Case #x: "+str(answer))
input_file.close()
output_file.close()

rawDescription: What is an output file in python

description: What is an output file in python


code:
try:
    for word in query_words:
        with open('takeaway.txt') as f:
            for line in open('takeaway.txt'):
                if word in line:
                    raise StopIteration
except StopIteration:
    print(line)
else:
    print("sorry your request could not be found")

rawDescription: Unable to break from for statement in Python


code:
# Python 2.7
modified_raw_html = unicode(soup)

# Python3
modified_raw_html = str(soup)

rawDescription: HTML Parsing issue with BeautifulSoup Library


code:
import random
for i in range(4):
    some_dict.pop( random.choice(some_dict.keys()) )

rawDescription: Removing items randomly from a dictionary


code:
angularaxis=dict(
    tickcolor='rgb(253,253,253)',
    range=[20,50]
    )

rawDescription: Change axis of plotly polar plot

description: Change axis of plotly polar plot


code:
import multiprocessing as mp
import time

def Counter(i, event):
    i.value=1
    while i.value > 0 and not event.is_set():
        print("i: ",i.value)
        i.value += 1

def ValueTester(i, stopval, event):
    while True:
        if i.value >= stopval:
            event.set()
            break
        else:
            time.sleep(0.1)

if __name__ == '__main__':
    num = mp.Value('d', 0.0)
    event = mp.Event()
    counter = mp.Process(target=Counter, args=(num, event))
    counter.start()
    tester = mp.Process(target=ValueTester, args=(num, 10, event))
    tester.start()
    tester.join()
    counter.join()
    print("Process Complete")

rawDescription: Python Multiprocessing: Ending an infinite counter


code:
L = [[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]
L = [set(e) for e in L]
combined = []
while L:
    group = L.pop()
    for other in L:
        if group.intersection(other):
            group.update(other)
    L = [e for e in L if not group.intersection(e)]
    combined.append(group)

combined

rawDescription: How can I combine arrays in Python?

description: Combine arrays in Python


code:
arr = np.loadtxt('foo.txt', dtype=object)
_, indices = np.unique(arr[:, 0][::-1], return_index=True)
arr[::-1][indices]
arr[len(arr) - indices - 1]

rawDescription: Find occurrences of a value in a numpy array and assign it appropriate weights


code:
import datetime
s = "Mon, 26 Dec 2011 20:42:08 +0200"
t = datetime.datetime.strptime(s, "%a, %d %b %Y %H:%M:%S %z")
t

rawDescription: How to normalize string to datetime format in Python

description: Normalize string to datetime format in Python


code:
idToActor = {a['personid']:a for a in actor_info}

for award in award_list:
    actor = idToActor[award['personid']]
    actor.setdefault('awards',[]).append(award)

rawDescription: Appending a list of dicts as an element of another list (Python)


code:
import gi
gi.require_version('Gtk', '3.0')

from gi.repository import Gio
from gi.repository import Gtk

class AppWindow (Gtk.ApplicationWindow):
    def __init__(self):
        Gtk.ApplicationWindow.__init__(self)
        self.set_default_size(200, 200)

    # Override the default handler for the delete-event signal
    def do_delete_event(self, event):
        # Show our message dialog
        d = Gtk.MessageDialog(transient_for=self,
                              modal=True,
                              buttons=Gtk.ButtonsType.OK_CANCEL)
        d.props.text = 'Are you sure you want to quit?'
        response = d.run()
        d.destroy()

        # We only terminate when the user presses the OK button
        if response == Gtk.ResponseType.OK:
            print('Terminating...')
            return False

        # Otherwise we keep the application open
        return True

def on_activate(app):
    # Show the application window
    win = AppWindow()
    win.props.application = app
    win.show()

if __name__ == '__main__':
    # Create an application instance
    app = Gtk.Application(application_id='com.example.ExampleApp', flags=0)

    # Use ::activate to show our application window
    app.connect('activate', on_activate)
    app.run()

rawDescription: GTK+3: Ask confirmation before application quit


code:
import boto3

# Extract the files from the s3 bucket
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
bucket_files = [x.key for x in bucket.objects.filter(Prefix='a/')]

rawDescription: How to isolate files in S3 bucket by directory?

description: Isolate files in S3 bucket by directory


code:
import datetime
diff = datetime.datetime.fromtimestamp(1418647594) - datetime.datetime.fromtimestamp(1418177737)
diff
diff.days

rawDescription: getting difference of 2 time since epoch in days

description: Getting difference of 2 time since epoch in days


code:
lists = {}
lists['homework'] = [40, 60, 70]
lists['tests'] = [35, 99, 20]
lists

rawDescription: Naming Lists Using User Input

description: Naming Lists Using User Input


code:
# Made-up data
Sframe = pd.DataFrame({'TermName': ['Fall', 'Fall', 'Fall', 'Fall'],
'DistrictName': ['Downtown', 'Downtown', 'Downtown', 'Downtown'],
'SchoolName': ['Seattle Central', 'Ballard', 'Ballard', 'Ballard'],
'StudentLastName': ['Doe', 'Doe', 'Doe', 'Doe'],
'StudentFirstName': ['John', 'Jane', 'Jane', 'Jane'],
'StudentMI': ['X', 'X', 'X', 'X'],
'StudentID': ['1234', '9876', '9876', '9876'],
'StudentDateOfBirth': ['2000-01-01', '2001-01-01', '2001-01-01', '2001-01-01'],
'StudentEthnicGroup': ['Asian American', 'White', 'White', 'White'],
'StudentGender': ['M', 'F', 'F', 'F'],
'Grade': ['10th', '9th', '9th', '9th'],
'TermSchoolStudent': ['Z', 'Z', 'Z', 'Z']})

# Remove duplicates based upon StudentID, in-place (i.e., modify object 'Sframe').
# UPDATE: I read that you want duplicates completely removed from data frame.
# Sframe.drop_duplicates(cols = ['StudentID'], take_last = False, inplace = True)

Sframe['dup_check_1'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = False)
Sframe['dup_check_2'] = Sframe.duplicated(cols = ['TermName', 'SchoolName', 'StudentID'], take_last = True)
Sframe = Sframe[(Sframe['dup_check_1'] == False) & (Sframe['dup_check_2'] == False)]
del Sframe['dup_check_1'], Sframe['dup_check_2']

rawDescription: Replace a whole dataframe with another (overwrite) (Python 3.4 pandas)


code:
y, z = 1, 2
def all_global():
    global x
    x = y + z

print(x,y,z)
all_global()
print(x,y,z)

rawDescription: What is the scope of global variable in this case?


code:
#!/usr/local/bin/python3
# -*- coding: utf8 -*-

import sys
import ctypes
import socket

from ctypes import *
u_short = c_ushort
u_char = c_ubyte
u_int = c_int

class ip_address(Structure):
    _fields_ = [("byte1", u_char),
                ("byte2", u_char),
                ("byte3", u_char),
                ("byte4", u_char)]

class ip_header(BigEndianStructure):
    _fields_ = [("ver_ihl", u_char),
                ("tos", u_char),
                ("tlen", u_short),
                ("identification", u_short),
                ("flags_fo", u_short),
                ("ttl", u_char),
                ("proto", u_char),
                ("crc", u_short),
                ("saddr", ip_address),
                ("daddr", ip_address),
                ("op_pad", u_int)]

class udp_header(BigEndianStructure):
    _fields_ = [("sport", u_short),
                ("dport", u_short),
                ("len", u_short),
                ("crc", u_short)]

def packet_handler(pkt_data):

    # cast pkt_data to void so we can do some pointer arithmetic
    v_pkt_data = ctypes.cast(pkt_data, ctypes.c_void_p)

    # retrieve the position of the ip header
    v_ip_header = ctypes.c_void_p(v_pkt_data.value + 14)
    pih = ctypes.cast(v_ip_header, ctypes.POINTER(ip_header))
    ih = pih.contents

    # retrieve the position of the udp header
    ip_len = (ih.ver_ihl & 0xf) * 4
    uh = ctypes.cast(ctypes.cast(pih, ctypes.c_void_p).value + ip_len,
                     ctypes.POINTER(udp_header)).contents

    # convert from network byte order to host byte order
    sport = socket.ntohs(uh.sport)
    dport = socket.ntohs(uh.dport)

    print("{}.{}.{}.{}:{} -> {}.{}.{}.{}:{}".format(
        ih.saddr.byte1, ih.saddr.byte2, ih.saddr.byte3, ih.saddr.byte4, sport,
        ih.daddr.byte1, ih.daddr.byte2, ih.daddr.byte3, ih.daddr.byte4, dport))

    # Extracting data
    #

    # data offset from ip header start
    data_offset = ip_len + ctypes.sizeof(udp_header)
    # data length
    data_len = ih.tlen - ip_len - ctypes.sizeof(udp_header)
    # get data
    arr_type = (ctypes.c_uint8 * data_len)
    data = arr_type.from_address(v_ip_header.value + data_offset)

    print(data[0:data_len])

    # note: same thing could be achieved from pkt_data
    print(pkt_data[14+data_offset:14+data_offset+data_len])

def main(packet_file):
    with open(packet_file, "rb") as fd:
        data = fd.read()

    # create ctypes.c_char_array
    pkt_data = ctypes.c_buffer(data)
    packet_handler(pkt_data)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        main(sys.argv[1])

rawDescription: C / Python WinPCap Translation

description: C / Python WinPCap Translation


code:
import urllib.request
import gzip

# Function: Convert information within html document to a text file
# Append information to the file
def html_to_text(source_html, target_file):

    opener = urllib.request.build_opener()
    # These headers are necessary to ensure that the website thinks that a browser is retrieving information
    # not a program.
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'),
                         ('Connection', 'keep-alive'),
                         ('Accept-encoding', 'gzip, deflate'),
                         ('Accept-language', 'en-US,en;q=0.5'),
                         ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                         ('Host', 'sg,finance.yahoo.com'), ]
    r = opener.open(source_html)

    # Check from the "Response Headers" in Firebug whether the content is encoded
    # Since the content is encoded in gzip format, decompression is necessary
    response = gzip.decompress(r.read())

    # The response headers would mention the "charset" from there the encoding type can be obtained
    response = response.decode(encoding='utf-8')
    print(response)
    temp_file = open(target_file, 'w+')
    temp_file.write(response)

source_address = "https://sg.finance.yahoo.com/lookup/all?s=*&t=A&m=SG&r=&b=0"
target_location = "C:\\Users\\Admin\\PycharmProjects\\TheLastPuff\\Source\\yahoo_ticker_symbols.txt"

html_to_text(source_address, target_location)

rawDescription: Legitimizing a web request so that the server allows the request through


code:
def lpr(self, message):
    """Print a message to the screen.

    :type message: String
    :param message: The message string.
    """
    self.terminal.nextLine()
    self.terminal.write(_format_message(message))
    self.terminal.nextLine()
    self.drawInputLine()

rawDescription: twisted command line protocol

description: Twisted command line protocol


code:
from matplotlib import pyplot as plt
from scipy.misc import lena

fig, ax = plt.subplots(1, 1)

x = np.linspace(0, 1, 10)
y = np.random.rand(10)
image = ax.imshow(lena(), cmap=plt.cm.gray, extent=[0, 1, 0, 1])
line = ax.plot(x, y, '-r', lw=2)

# invisible clipping polygon
poly = ax.fill_between(x, 0, y, visible=False)
clip = poly.get_paths()[0]

# you will need to do this separately for each of the images in your plot
image.set_clip_path(clip, transform=ax.transData)

plt.show()

rawDescription: Plotting a background image to a matplotlib graph


code:
def __unicode__(self):
    return u"{0} ({1}, {2})".format(self.icon, self.attrib1, self.attrib2)

rawDescription: Define Self as multiple attributes in Django


rawDescription: Reading specific words and values from a file and storing them in a dictionary


rawDescription: Turn a string that is a formatted list into a list


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d

def windline(x,y,deviation,color):
    y1 = y-deviation/2
    y2 = y+deviation/2
    tol = (y2.max()-y1.min())*0.05
    X, Y = np.meshgrid(np.linspace(x.min(), x.max(), 100), np.linspace(y1.min()-tol, y2.max()+tol, 100))
    Z = X.copy()
    for i in range(Z.shape[0]):
        Z[i,:] = c

    #plt.pcolormesh(X, Y, Z)
    plt.contourf(X, Y, Z, cmap='seismic')

    plt.fill_between(x, y2, y2=np.ones(x.shape)*(y2.max()+tol), color='w')
    plt.fill_between(x, np.ones(x.shape) * (y1.min() - tol), y2=y1, color='w')
    plt.xlim(x.min(), x.max())
    plt.ylim(y1.min()-tol, y2.max()+tol)
    plt.show()

x = np.arange(100)
yo = np.random.randint(20, 60, 21)
y = interp1d(np.arange(0, 101, 5), yo, kind='cubic')(x)
dv = np.random.randint(2, 10, 21)
d = interp1d(np.arange(0, 101, 5), dv, kind='cubic')(x)
co = np.random.randint(20, 60, 21)
c = interp1d(np.arange(0, 101, 5), co, kind='cubic')(x)
windline(x, y, d, c)

rawDescription: Changing the linewidth and the color simultaneously in matplotlib


code:
def convert_bool(col):
    if str(col).title() ==  "True": #check for nan
        return "YES"
    elif str(col).title() == "False":
        return "NO"
    else:
        return col
pandas.read_csv(file_in, converters={"C3": lambda x:convert_bool(x)})

rawDescription: Python Pandas Mixed Boolean Yes/True and NaN Columns


code:
def callback(files):
    joined_files = ''.join([open(f).read() for f in files])
    do_something_with(joined_files)

dialog = QtGui.QFileDialog()
dialog.setFileMode(3) #allow selection of multiple files
dialog.filesSelected.connect(callback)
dialog.show()

rawDescription: Python Qt QFileDialog::getopenFileNames - File select order


code:
gen = itertools.combinations_with_replacement(characters,password_length) #1
for password in gen:                                                      #2
    check_password(password)                                              #3

rawDescription: How can I create a simple python brute force function?

description: Create a simple python brute force function


code:
import win32security
import _winreg as winreg

sid = win32security.LookupAccountName(None, user_name)[0]
sidstr = win32security.ConvertSidToStringSid(sid)
key = winreg.OpenKey(winreg.HKEY_USERS, sidstr)
# do something with the key

rawDescription: Reading HKEY CURRENT USER from the registry in Python, specifying the user


code:
my_string = "[{}]".format(
    subprocess.check_output("command1 && echo ',' && command2",
                            shell=True, stderr=STDOUT, env=env))

rawDescription: Converting string into valid json with Python


code:
# Run the SQL Select Statement
result = conn.execute("""SELECT * FROM
        [LifelineChatDB].[dbo].[vw_AllCenterChatOverview]""")

# Get column names
column_names = result.keys()

rawDescription: How to copy entire SQL Server table into CSV including column headers?

description: Copy entire SQL Server table into CSV including column headers


code:
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

emailfrom = "sender@example.com"
emailto = "destination@example.com"
fileToSend = "hi.csv"
username = "user"
password = "password"

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()

rawDescription: How do I send an email with a .csv attachment using Python

description: Send an email with a .csv attachment using Python


code:
email = 'k@example.com'
access_token = 'vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg'
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (email, access_token)

imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
imap_conn.select('INBOX')

rawDescription: Access Gmail Imap with OAuth 2.0 Access token


code:
PATTERN = '''
    power< head=any+
     trailer< '.' method=any >
     parens=trailer< '(' tail=[argument | arglist] ')'>

    >
'''

rawDescription: How to fetch method call using a custom migration fixer in lib2to3?

description: Fetch method call using a custom migration fixer in lib2to3


rawDescription: how to get a sublist of desired length using python?

description: Get a sublist of desired length using python


code:
A1 = ['a','a','a','foo','c','d','a','e','bar','bar','bar','e','d','d']
ref = []
for i in A1:
   if i not in ref:
       ref.append(i)

[ref.index(i)+1 for i in A1]

rawDescription: Giving indices to list entries

description: Giving indices to list entries


code:
from collections import MutableMapping

class TreeDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        super(TreeDict, self).__init__()
        self.update(*args, **kwargs)
    ...

rawDescription: constructor for dict implementation in Python

description: Constructor for dict implementation in Python


rawDescription: Parsing meta tags efficiently with lxml?

description: Parsing meta tags efficiently with lxml


code:
def profile_required(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, LOGIN_URL)
        else:
            try:
                profile = request.user.profile
            except Profile.DoesNotExist:
                return redirect(CREATE_PROFILE_REDIRECT_URL)
            else:
                return view_func(request, *args, **kwargs)
    return wrapped

rawDescription: How can I write a decorator in Django to check two separate conditions and redirect accordingly?

description: Write a decorator in Django to check two separate conditions and redirect accordingly


code: increment(counter[1, ...])

rawDescription: how to extract a zero-dimensional slice from a 1-dimensional array in numpy

description: Extract a zero-dimensional slice from a 1-dimensional array in numpy


code:
def robust_float(s):
    try:
        return float(s)
    except ValueError:
        if 'nan' in s.lower():
            return float('nan')
        else:
            raise

rawDescription: reading floating-point numbers with 1.#QNAN values in python

description: Reading floating-point numbers with 1.#QNAN values in python


code:
my_list = forms.ModelMultipleChoiceField(
    label='List',
    required=False,
    queryset=[],
    widget=SelectMultiple(attrs={'class': 'foobar'}))

rawDescription: django form add css to ModelMultipleChoiceFIeld

description: Django form add css to ModelMultipleChoiceFIeld


rawDescription: Replacing Pandas PivotTable Non-Null Result Cells With A Fixed String


code:
CYGWIN_KEY = "SOFTWARE\\Cygwin\\setup"
hk_user = winreg.HKEY_CURRENT_USER
key = winreg.OpenKey(hk_user, CYGWIN_KEY)
root = winreg.QueryValueEx(key, "rootdir")[0]

rawDescription: Get Cygwin installation path in a Python script


rawDescription: Building histogram from a dict without having to iterate over the keys


code: carlists = user.carlist_set.all()

rawDescription: Django, ManyToMany field, get the right object with extra fields


code: mask = (data['event_type'] & event_type).astype(bool)

rawDescription: Filtering of structured array via bit-wise operation (bitmask) on column data


code:
d = {(1, 2): [(2,), (1,)], (1, 3): [(3,), (1,)], (2, 3): [(2,), (3,)],
     (1,): [1], (2,): [2], (3,): [3], (1, 2, 3): [(1, 2), (3,)]}

def unpack(d,key):
    if len(d[key]) == 1:
        return tuple(d[key])
    ret = tuple()
    for k in d[key]:
        if k in d:
            ret += unpack(d,k)
        else:
            # This happens if the value for the key has
            # one value, in that case we simply add that
            # to the returning tuple
            ret += (k,)
    return ret

for key in d:
    ret = unpack(d,key)
    print('  key, ret: ',key,', ',ret)

rawDescription: How to break the input from dictionary python

description: Break the input from dictionary python