code:
first_window_handler = driver.current_window_handle
driver.find_element_by_css_selector("body").send_keys(Keys.CONTROL + 't')
second_window_handler = driver.window_handles[1]

# from second page
driver.switch_to.window(second_window_handler)
element_from_second = driver.find_element_by_css_selector('something')

# from first page
driver.switch_to.window(first_window_handler)
element_from_first = driver.find_element_by_css_selector('something else')

rawDescription: Python back to previous page with remembering the elements


code:
a = [1]
b = [2]
lst = [a, b]
lst
lst[1][0] = 4  # changes contents of second mutable container in lst
lst
a
b

rawDescription: Store reference to primitive type in Python?


code:
def isfloat(string):
    try:
        float(string)
        return True
    except:
        return False

[float(item) for s in mylist for item in s.split() if isfloat(item)]
#[10000.0, 5398.38770002321]

rawDescription: List comprehension replacing items that are not float or int


code:
def post(self, request):
     serializer = self.get_serializer(data=request.DATA)

     if serializer.is_valid():
         user = serializer.object.get('user') or request.user
         # check if settings swith is on / then check validity
         if settings.ACCOUNT_EMAIL_VERIFICATION == settings.ACCOUNT_EMAIL_VERIFICATION_MANDATORY:
             email_address = user.emailaddress_set.get(email=user.email)
             if not email_address.verified:
                  return Response(status=403, data='E-mail is not verified.')

         token = serializer.object.get('token')
         response_data = jwt_response_payload_handler(token, user, request)

         return Response(response_data)

     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

rawDescription: django jwt generate token if email confirmed

description: Django jwt generate token if email confirmed


code:
import Tkinter as tk
root = tk.Tk()
count = 0
def add_line():
    global count
    count += 1
    tk.Label(text='Label %d' % count).pack()
tk.Button(root, text="Hello World", command=add_line).pack()
root.mainloop()

rawDescription: Button to add widgets , in Tkinter

description: Button to add widgets , in Tkinter


code:
import requests

url = 'https://fcq.colorado.edu/scripts/broker.exe'

payload = {
    "_PROGRAM": "fcqlib.fcqdata.sas",
    "_SERVICE": "fcq",
    "camp": "BD",
    "fileFrmt": "HTM",
    "ftrm": "1",
    "fyr": "2007",
    "grp1": "ALL",
    "jjj": "mytst",
    "ltrm": "7",
    "lyr": "2013",
    "sort": "descending YEARTERM SUBJECT COURSE SECTION",
}

payload.update({
    'subj': 'CSCI',
    'crse': '1300',
})

def main():
    r = requests.post(url, payload)
    with open("requests_results.html", "w") as f:
        f.write(r.content)
    return 0

if __name__ == '__main__':
    main()

rawDescription: Using python to submit a web form with liburl or requests


code:
while True:
    screen_image.fill(Color('white'))
    screen_image.blit(image_on_in_game, (0,0))
    screen.blit(pygame.transform.scale(screen_image, chosen_resolution), (0,0))
    pygame.display.flip()

rawDescription: Pygame image used as screen then final transformed to screen


code:
with open('dna.txt', 'w+') as output:
    for _ in range(15):
        dna = random_dna_sequence(30)
        output.write(dna)

rawDescription: Write multiple prints in a text file

description: Write multiple prints in a text file


rawDescription: how to format a line in python?

description: Format a line in python


code:
from sklearn import preprocessing
trdata = preprocessing.scale(trdata)

rawDescription: faster data fitting ( or learn) function in python scikit

description: Faster data fitting ( or learn) function in python scikit


code:
#!/usr/bin/python

import cgi;
import codecs;

form = cgi.FieldStorage()
my_a = form.getvalue("a","")

wFile = codecs.open("test.txt", "w", "utf8")
wFile.write(my_a);
wFile.close()

print("Content-Type: text/plain")
print("Location: ../plain.html")
print()

rawDescription: Passing a string from a form in html-file to a python-script respecting utf-8 encoding


code:
class my_class(object):
  def my_func(self,var_name):
    setattr(self,var_name,5)
a = my_class()
a.my_func('yes')
a.yes

rawDescription: Setting name of variable in a class with a function?


code:
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty
from kivy.uix.label import Label

Builder.load_string('''
<BackgroundWidget>:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            size: root.size
            pos: root.pos
''')

class BackgroundWidget(Widget):
    '''BackgroundWidget class
    '''

    background_color_r = BoundedNumericProperty(0., min=0., max=1.)
    background_color_g = BoundedNumericProperty(0., min=0., max=1.)
    background_color_b = BoundedNumericProperty(0., min=0., max=1.)
    background_color_a = BoundedNumericProperty(0., min=0., max=1.)

    background_color = ReferenceListProperty(background_color_r, background_color_g, background_color_b, background_color_a)

class BackgroundLabel(BackgroundWidget, Label): pass

rawDescription: Label with Background Color with Container as Screen dosent show background color


code:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

rawDescription: Not need CSRF feature in django 1.2.3

description: Not need CSRF feature in django 1.2.3


code: ''.join(str(x) for x in strlist)

rawDescription: Converting a list of "stuff" to a single string


code:
class FooTable(DeclBase):
    financial_day_of_month = Column('financial_day_of_month', Integer,
                                        nullable=False, default=1)
    __table_args__ = (
        CheckConstraint('financial_day_of_month between 1 and 31', name='check1'),
        {})

rawDescription: sqlalchemy: How do I enforce date range on column?

description: Sqlalchemy: How do I enforce date range on column


code:
from tkinter import Tk, PhotoImage, Button, FLAT
root = Tk()
mineImagesList = [PhotoImage(file="Resources/Mine/saperx_mine_%s.png" % (frame)) for frame in range(1, 11)]
button = Button(root, bd=0, relief=FLAT, command= lambda: func(button))

def func (object, frame=0):
    object.configure(image=mineImagesList[frame])
    object.image = mineImagesList[frame]
    print("Object image:", object.image)
    if frame+1 < len(mineImagesList):
        frame += 1
        root.after(34, lambda frame=frame, object=object: func(object=object, frame=frame))

button.pack()
root.mainloop()

rawDescription: Python tkinter widget image animation function with after in a loop misbehaving


code:
import json
f = json.loads('["Title_1","Item1","Item2","Item3","Title_2","Item1","Item2","Item3","Title_3","Item1","Item2","Item3"]')
dict((item.lower()+'key', item) for item in f if not item.startswith('Title_'))

rawDescription: How can I improve my LogConverter?

description: Improve my LogConverter


code: {x:random_ints.count(x) for random_ints in [[random.randint(0,4) for _ in range(6)]] for x in set(random_ints)}

rawDescription: how to access a nested comprehensioned-list

description: Access a nested comprehensioned-list


rawDescription: Using CSS Selector to click a button

description: Using CSS Selector to click a button


code:
import serial

com=serial.Serial('COM2')
elements=[65,67,69,71]      #Create an array of your choice
a_var=bytearray(elements)   #Create byte array of it
com.write(a_var[0:3])       #Write desired elements at serial port

a_var[0]=a_var[0]+1         #Do your mathematical manipulation

com.write(a_var[0:1])       #Write again as desired
com.close()

rawDescription: Sending hexadecimal or ASCII value stored in a variable using pyserial


code:
item = QtGui.QListWidgetItem()
item.setText(QtGui.QApplication.translate("Dialog", x, None,    QtGui.QApplication.UnicodeUTF8))
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(item)

rawDescription: Qt Designer Qlistwidget checkbox

description: Qt Designer Qlistwidget checkbox


code:
import subprocess
process = subprocess.Popen(
    ['ccextractorwin.exe', '-stdout', '-quiet', 'myvideo.mpg'],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
all_output = []
while True:
    out_line = process.stdout.readline()
    all_output.append(out_line)  # Add this line to the list of lines to keep
    if out_line == u'\n':  # We've hit an empty line, or whatever else you deem like a good stopping point
        break  # the while loop

# Now, kill the process dead in its tracks.
# This probably isn't great for open file handles, but whatever
process.kill()

rawDescription: How do I get only the first closed caption from a video file?

description: Get only the first closed caption from a video file


code:
import ast
dic = {u'key-a':u'val-a', "key-b":"val-b"}
strs = repr(dic)
strs
ast.literal_eval(strs)

rawDescription: how to deserialize a python printed dictionary?

description: Deserialize a python printed dictionary


code:
import itertools
[x  for x in itertools.combinations("ABC", 2)]

rawDescription: How long does it takes to check all possibilities?


code:
import requests

payload = "s2345"

response = requests.post('http://hastebin.com/documents', data=payload)
if response.status_code == 200:
    print(response.json()['key'])

rawDescription: requests.post to hastebin.com not working

description: Requests.post to hastebin.com not working


rawDescription: search for "does-not-contain" on a dataframe in pandas

description: Search for "does-not-contain" on a dataframe in pandas


code:
import sqlalchemy.types as types

class CoinFlipDataType(types.TypeDecorator):
    impl = types.String

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        assert value in (True, False)
        return 'heads' if value else 'tails'

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        assert value in ('heads', 'tails'), value
        return value == 'heads'

    def copy(self):
        return CoinFlipDataType(self.impl.length)

def data_map():
    mapper(Foo, db_foo, properties={'is_heads': db_foo.c.side})

db_foo = Table(
    'foo', metadata,
    Column('id', Integer, primary_key=True),
    Column('side', CoinFlipDataType(5), nullable=False))

rawDescription: Mapping db varchar to domain object bool


rawDescription: Groupwise downsampling and plotting of pd.DataFrame


code:
from __future__ import absolute_import, unicode_literals

from celery import current_app
from celery.bin import worker

if __name__ == '__main__':
    app = current_app._get_current_object()

    worker = worker.worker(app=app)

    options = {
        'broker': 'amqp://guest:guest@localhost:5672//',
        'loglevel': 'INFO',
        'traceback': True,
    }

    worker.run(**options)

rawDescription: How to start a Celery worker from a script/module __main__?

description: Start a Celery worker from a script/module __main__


code:
import datetime

def previous_week_range(date):
    start_date = date + datetime.timedelta(-date.weekday(), weeks=-1)
    end_date = date + datetime.timedelta(-date.weekday() - 1)
    return start_date, end_date

previous_week_range(datetime.date(2015, 2, 9))  # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 13))  # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 16))  # 2015-02-09, 2015-02-15

rawDescription: how get the last week as start date and end date based on date in current week in scrapy

description: How get the last week as start date and end date based on date in current week in scrapy


rawDescription: How to extract the specific tuples from lists in python?

description: Extract the specific tuples from lists in python


code:
def unpack(seq, count):
  return seq[:count] + [seq[count:]]
a, b = unpack([1, 2, 3], 1)
a
b
a, b = unpack([1, 2], 1)
a
b
a, b = unpack([1], 1)
a
b
a, b = unpack([], 1)
a, b, c, d = unpack(range(10), 3)
a
b
c
d

rawDescription: return variable outputs in Python function?

description: Return variable outputs in Python function


code:
import lxml.html

root = lxml.html.fromstring('
Test Link to be removed. link')
for a in root.xpath('a[not(@href)]'):
    a.drop_tag()

assert lxml.html.tostring(root) == '
Test Link to be removed. link
'

rawDescription: Python regex to strip html a tags without href attribute


code:
# This should be in RegContextFacory
__acl__ = [
    (Allow, 'group:viewers', 'view'),
    (Allow, 'group:creators', 'create'),
    (Allow, 'group:editors', 'edit'),
    (Allow, 'group:deleters', 'delete'),
    (Allow, Authenticated, ALL_PERMISSIONS),
    (Deny, Everyone, ALL_PERMISSIONS),
]

def user_callback(user_name, request):

    if user_name == 'admin':
        return 'Authenticated'

    base = request.matchdict.get('base')
    resource = request.matchdict.get('id')
    auth_provider = AuthProvider(user_name, base, resource)
    return auth_provider.get_permission() #Should return somtehing like ['group:viewers']

rawDescription: Set view permission depending on request matchdict in Pyramid


code:
import networkx as nx

def test(G):
    for e in G.edges_iter():
        print(e)

if __name__=='__main__':
    from timeit import Timer
    G = nx.DiGraph()
    G.add_edges_from([(1,2),(4,5)])
    t = Timer("test(G)","from __main__ import test,G")
    print( t.timeit(1))

rawDescription: TypeError when iterate over DiGraph()

description: TypeError when iterate over DiGraph()


code:
from celery import task
from datetime import datetime, timedelta

@task()
def add(x, y):
    return x + y

tomorrow = datetime.now() + timedelta(days=1)
add.apply_async(args=[10, 10], eta=tomorrow)

rawDescription: Django Schedule and queue Non periodic Tasks


code:
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)

rawDescription: nosetest deprecation warnings

description: Nosetest deprecation warnings


code: medname = [med.get_attribute('value') for med in medicationsTextBoxLocatorTextBox if med.get_attribute('value') != ""]

rawDescription: appending another variable besides what was iterated inside list comprehension (python)

description: Appending another variable besides what was iterated inside list comprehension (python)


code:
import matplotlib.pyplot as plt

plt.figure()
plt.plot([1,2], [1,2])

# Option 1
# QT backend
manager = plt.get_current_fig_manager()
manager.window.showMaximized()

# Option 2
# TkAgg backend
manager = plt.get_current_fig_manager()
manager.resize(*manager.window.maxsize())

# Option 3
# WX backend
manager = plt.get_current_fig_manager()
manager.frame.Maximize(True)

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

rawDescription: Saving Matplotlib graphs to image as full screen


code:
from itertools import product

for x, y, z in product(xrange(xs), xrange(zs), xrange(ys)):
    vp = [x * vs, y * vs, z * vs]
    v = Cube(vp)

rawDescription: Python For Loop Slowing With Time

description: Python For Loop Slowing With Time


code:
from itertools import product
[(x, y, 0) for x, y in product(range(5), repeat=2)]

rawDescription: Python populating x and y values incrementally


rawDescription: Algorithm to choose number of random numbers from list in python?


code:
from scipy import stats
data = stats.beta.rvs(a=1, b=2, size=100, random_state=101)
xxx = stats.beta.fit(data)
stats.beta.pdf(0.1, *xxx)
stats.beta.mean(*xxx)

rawDescription: How do I find out what the .fit function of a scipy stat distribution returns?

description: Find out what the .fit function of a scipy stat distribution returns


rawDescription: python sort list of lists based on inner element AND ignore case

description: Python sort list of lists based on inner element AND ignore case


rawDescription: How can I print a Python file's docstring when executing it?

description: Print a Python file's docstring when executing it


code: [[j*((i==index)*(scale-1)+1) for i,j in enumerate(l)] for l in mtx]

rawDescription: Scale a column of a list-of-lists in Python


code:
import numpy as np
np.issubdtype(np.int32, np.integer)
np.issubdtype(np.float32, np.integer)
np.issubdtype(np.complex64, np.integer)
np.issubdtype(np.uint8, np.integer)
np.issubdtype(np.bool, np.integer)
np.issubdtype(np.void, np.integer)

rawDescription: How do I check if a numpy dtype is integral?

description: Check if a numpy dtype is integral


code:
if h is None:
    if isinstance(file, basestring):
        f = open(file, 'rb')
        h = f.read(32)
    else:
        location = file.tell()
        h = file.read(32)
        file.seek(location)

rawDescription: why do python imghdr test functions take the file as an argument?

description: Why do python imghdr test functions take the file as an argument


code:
class ReadOnlyList(list):
    def __init__(self, other):
        self._list = other

    def __getitem__(self, index):
        return self._list[index]

    def __iter__(self):
        return iter(self._list)

    def __slice__(self, *args, **kw):
        return self._list.__slice__(*args, **kw)

    def __repr__(self):
        return repr(self._list)

    def __len__(self):
        return len(self._list)

    def NotImplemented(self, *args, **kw):
        raise ValueError("Read Only list proxy")

    append = pop = __setitem__ = __setslice__ = __delitem__ = NotImplemented

rawDescription: Immutable list in Python

description: Immutable list in Python


rawDescription: Why is numpy.polyfit is off by a large margin?


code:
import inspect
n2 = len(inspect.getargspec(sum2)[0])
n3 = len(inspect.getargspec(sum3)[0])
sum2(*varList[0:n2])
sum3(*varList[0:n3])

rawDescription: python - enter the correct number of variables based on function handle

description: Python - enter the correct number of variables based on function handle


rawDescription: Producing polygon offsets using Clipper lib in python


code:
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
# Make sure the height is such that there is something to scroll.
layout.bind(minimum_height=layout.setter('height'))
for i in range(30):
    btn = Button(text=str(i), size_hint_y=None, height=40)
    layout.add_widget(btn)
root = ScrollView(size_hint=(None, None), size=(400, 400),
                scroll_type=['bars'], bar_width='10dp') #you can use both ['bars','content']
root.add_widget(layout)

rawDescription: How can I control my Kivy scrollview by dragging the sliders?

description: Control my Kivy scrollview by dragging the sliders


rawDescription: How do I retrieve a modules path when I have a class from that module

description: Retrieve a modules path when I have a class from that module


code:
class ScheduledPayment(Base):
    id = Column(Integer, primary_key=True)
    invoice_id = Column(Integer)
    is_canceled = Column(Boolean, default=False)

    __table_args__ = (
        Index('only_one_active_invoice', invoice_id, is_canceled,
              unique=True,
              postgresql_where=(~is_canceled)),
    )

rawDescription: Creating partial unique index with sqlalchemy on Postgres


code:
#
# pygame (simple) template - by furas
#

# ---------------------------------------------------------------------

import pygame
import pygame.gfxdraw
import random

# === CONSTANS === (UPPER_CASE names)

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

CYAN    = (  0, 255, 255)
MAGENTA = (255,   0, 255)
YELLOW  = (255, 255,   0)

SCREEN_WIDTH  = 800
SCREEN_HEIGHT = 600

# === CLASSES === (CamelCase names)

class Button():

    def __init__(self, text, x, y, width, height, on_click=None, fg_color=RED, bg_color=WHITE, font_size=35):
        self.text = text

        font = pygame.font.SysFont(None, font_size)

        # rectangle - without position, to put text in correct place
        self.rect = pygame.Rect(0, 0, width, height)

        # normal button - fill background
        self.normal_image = pygame.surface.Surface( self.rect.size )
        self.normal_image.fill(bg_color)

        # normal button - add text
        text_image = font.render(text, True, fg_color)
        text_rect = text_image.get_rect(center=self.rect.center)
        self.normal_image.blit(text_image, text_rect)

        # hover button - fill background
        self.hover_image = pygame.surface.Surface( self.rect.size )
        self.hover_image.fill(fg_color)

        # hover button - add text
        text_image = font.render(text, True, bg_color)
        text_rect = text_image.get_rect(center=self.rect.center)
        self.hover_image.blit(text_image, text_rect)

        # set position
        self.rect.x = x
        self.rect.y = y

        # other
        self.on_click = on_click
        self.hover = False

    def draw(self, surface):
        # draw normal or hover image
        if self.hover:
            surface.blit(self.hover_image, self.rect)
        else:
            surface.blit(self.normal_image, self.rect)

    def event_handler(self, event):
        # is mouse over button ?
        if event.type == pygame.MOUSEMOTION:
            self.hover = self.rect.collidepoint(event.pos)

        # is mouse clicked ? run function.
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.hover and self.on_click:
                self.on_click()

# === FUNCTIONS === (lower_case names)

def do_it():
    global background_color

    if background_color == BLACK:
        background_color = RED
    elif background_color == RED:
        background_color = GREEN
    else:
        background_color = BLACK

    print("Button pressed")

# === MAIN ===

# --- init ---

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

# --- objects ---

# create button
button = Button('CHANGE COLOR', 0, 0, 300, 50, on_click=do_it)

# add function later
#button_quit.on_click = do_it

# center button
button.rect.center = screen_rect.center

# default bacground color - changed in do_it()
background_color = BLACK

# --- mainloop ---

clock = pygame.time.Clock()
is_running = True

while is_running:

    # --- events ---

    for event in pygame.event.get():

        # --- global events ---

        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False

        # --- objects events ---

        button.event_handler(event)

    # --- updates ---

        # empty

    # --- draws ---

    # clear buffer
    screen.fill(background_color)

    # draw all objects - widgets (buttons, labels)

    button.draw(screen)

    clock.tick(25)

    # send buffer to video card
    pygame.display.update()

# --- the end ---

pygame.quit()

rawDescription: Pygame buttons not creating working buttons


code:
idx = np.random.permutation(np.arange(len(df)))
df.iloc[idx].drop_duplicates()

rawDescription: dropping duplicates randomly

description: Dropping duplicates randomly


code:
import Image

MAX_SIZE = 1280
image = Image.open(image_path)
original_size = max(image.size[0], image.size[1])

if original_size >= MAX_SIZE:
    resized_file = open(image_path.split('.')[0] + '_resized.jpg', "w")
    if (image.size[0] > image.size[1]):
        resized_width = MAX_SIZE
        resized_height = int(round((MAX_SIZE/float(image.size[0]))*image.size[1]))
    else:
        resized_height = MAX_SIZE
        resized_width = int(round((MAX_SIZE/float(image.size[1]))*image.size[0]))

    image = image.resize((resized_width, resized_height), Image.ANTIALIAS)
    image.save(resized_file, 'JPEG')

rawDescription: Using Python to Resize Images when Greater than 1280 on either side


code:
lst = ['120 abc','123 abc','256 abc','125 bcd','326 bcd','426 bcd']
list2 = {}
for listItem in lst:
    if listItem.index('2') == 1:
        t = listItem.split()
        if t[1] in list2:
            list2[t[1]] = list2[t[1]] + 1
        else:
            list2[t[1]] = 1

print(list2)

rawDescription: Keeping tracks of the first digit of similar items in a list Python


rawDescription: Nested Django query

description: Nested Django query


code:
isinstance(3, numbers.Integral)
isinstance(3.0, numbers.Integral)
isinstance(3+0j, numbers.Integral)

rawDescription: What's the relationship between numbers.Integral and int in builtins module in Python 3


code:
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute('select y1 from table where pagenr=? and x1=?',
(pagenr_value, x1_value))
output = c.fetchall()

rawDescription: Python/sqlite: get column values as a list/tuple from rows where other columns have certain values


code: import sys

rawDescription: Quit function in python program

description: Quit function in python program


code:
def _dont_doctest_inherited_docstrings(docstring):
    docstring_disabled = ""
    for line in docstring.splitlines():
        docstring_disabled += line + "#doctest: +DISABLE"
    return docstring_disabled

class _frommethod:
    """
    Adapted from numpy.ma._frommethod
    """

    def __init__(self, func_name):
        self.__name__ = func_name
        docstring = getattr(MaskedArray, func_name).__doc__
        self.__doc__ = _dont_doctest_inherited_docstrings(docstring)
        self.obj = None

rawDescription: prevent sphinx from executing inherited doctests

description: Prevent sphinx from executing inherited doctests


code:
autoforms = []
part_formsets = []
autos = Auto.objects.all()
PartFormSet = inlineformset_factory(Auto, Part, fields=('field1', 'field2'))
for auto in autos:
    autoform = AutoForm(instance=auto)
    autoforms.append(autoform)
    part_formset = PartFormSet(instance=auto)
    part_formsets.append(part_formset)
c = {'autoforms': autoforms, 'part_formsets': part_formsets}
return render(request, 'some.html', c)

rawDescription: Django multiple included forms with foreign key


rawDescription: force unpacking of certain egg directories

description: Force unpacking of certain egg directories


code:
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.view = QWebView(self)
        self.view.installEventFilter(self)
        # create other components here

    def eventFilter(self, obj, event):
        if obj == self.view:
            if (event.type() == QEvent.MouseButtonRelease):
                htc = self.view.page().mainFrame().hitTestContent(event.pos())
                e = htc.element()
                if e:
                    #do somesing with e
                    return True
        return  QMainWindow.eventFilter(obj, event)

rawDescription: How do I get DOM element by mouse click on PyQT5 QWebView

description: Get DOM element by mouse click on PyQT5 QWebView


code:
# Prepare the QGraphicsView widget
scene = QtGui.QGraphicsScene(graphicsView)
graphicsView.setScene(scene)
graphicsView.setRenderHint(QtGui.QPainter.Antialiasing)

# Draw a line
path = QtGui.QPainterPath()
path.moveTo(0, 0)
path.cubicTo(100, -20, 40, 90, 20, 20)
scene.addPath(path)

rawDescription: How to use QPainterPath?

description: Use QPainterPath


code:
coll = Elasticsearch()
coll.update(index='stories-test',doc_type='news',id=hit.meta.id,
                body={"doc": {"stanford": 1, "parsed_sents": parsed }})

rawDescription: How to update a document using elasticsearch-py?

description: Update a document using elasticsearch-py


code:
def getSpeciesGlobal(some_object):  # a normal function
    return some_object.species

polly = Pet("Polly", "Parrot")
polly.species   # "Parrot"
getSpeciesGlobal(polly)   # "Parrot"
# if we assign this function to the class.
Pet.getSpeciesGlobal = getSpeciesGlobal
Pet.getSpeciesGlobal(polly)  # "Parrot"

# the original way in your question
polly.getSpecies()  # "Parrot"
Pet.getSpecies(polly)   # "Parrot"

rawDescription: Python simple class understanding

description: Python simple class understanding


code:
import numpy as np
d = {10:0.5, 9: 0.4, 8:0.1}
x,p = zip(*d.items())
np.random.choice(x, p=p)

rawDescription: Is there a built-in function to get a number when i have numbers and their probabilities? (Python)


code:
import pandas as pd
import numpy as np

dlist = pd.date_range('2015-01-01',periods=5)
df = pd.DataFrame(dlist, columns=['DATE'])
df['EC'] = range(7033,7033+len(df))
df['HS'] = np.random.randint(0,9,5)
df['AH'] = np.random.randint(0,9,5)
df['DAY'] = df.DATE.dt.strftime('%a')
pv = pd.pivot_table(df, columns=[df.DATE.dt.date, df.DAY, 'EC'], values=['HS','AH'])
pv = pv.unstack(level=[1,2]).unstack(level=0)
pv.to_excel('solution.xlsx')

rawDescription: Grouping levels - multiindex in python pandas


code:
import csv
import collections

artists = collections.Counter()
album = collections.Counter()
song = collections.Counter()
with open('lastfm.csv') as input_file:
    for row in csv.reader(input_file, delimiter=';'):
        artists[row[0]] += 1
        album[row[1]] += 1
        song[row[2]] += 1

with open('output.csv', 'w') as output_file:
    writer = csv.writer(output_file, delimiter=';')
    with open('lastfm.csv', 'r') as input_file:
        for row in csv.reader(input_file, delimiter=';'):
            writer.writerow(row + [song[row[2]], artists[row[0]], album[row[1]]])

rawDescription: Python: appending a counter to a csv file


rawDescription: Python: count occurances of a given char in a string


code:
import genericpath
genericpath.__file__

rawDescription: Find Python module filename

description: Find Python module filename


code:
n = int(input("Enter a number: "))
for i in range(2, n):
    if n % i == 0:
        print(False)
        break
else:
    print(True)

rawDescription: prime number python for loops

description: Prime number python for loops


rawDescription: Python - Issues with selenium button click using XPath


code:
# 1. allocating space for the output array:
output_arr = np.zeros(shape = (len(df), 5000), dtype = int)
# 2. converting DF to np.array (arr_df will be of shape (len(df),1)):
arr_df = np.array(df)
# 3. iterating:
for i in range(len(arr_df)):
    # arr_df[i] is a np.array containing a list so we have to use arr_df[i][0] to get to the tuples:
    idx, values = zip(*arr_df[i][0])
    output_arr[i,idx] = val

rawDescription: How to convert a data frame to a big matrix fast with python-pandas?

description: Convert a data frame to a big matrix fast with python-pandas


code:
prevToken = None
def depthFirstTraverseTokenLinking(tree):
    depthFirstTraverseTokenLinkingPhase1(tree)
    depthFirstTraverseTokenLinkingPhase2(tree)

def depthFirstTraverseTokenLinkingPhase1(tree):
    global prevToken
    if len(tree.children) == 0:
        tree.prevToken = prevToken
        if prevToken != None :
            prevToken.nextToken = tree # Is something wrong with this line?
        prevToken = tree
        return

    for c in tree.children:
        depthFirstTraverseTokenLinkingPhase1(c)

def depthFirstTraverseTokenLinkingPhase2(tree):
    if len(tree.children) == 0:
        return

    for c in tree.children:
        depthFirstTraverseTokenLinkingPhase2(c)

    if tree.children[0].prevToken is not None:
        tree.prevToken = tree.children[0].prevToken
    else:
        tree.prevToken = tree.children[0]

    if tree.children[-1].nextToken is not None:
        tree.nextToken = tree.children[-1].nextToken
    else:
        tree.nextToken = tree.children[-1]

rawDescription: Strange behavior in Python code

description: Strange behavior in Python code


code:
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000] }
clf = GridSearchCV(LogisticRegression(penalty='l2'), param_grid)
GridSearchCV(cv=None,
       estimator=LogisticRegression(C=1.0, intercept_scaling=1, dual=False, fit_intercept=True,
          penalty='l2', tol=0.0001),
       param_grid={'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]})

rawDescription: Fine-tuning parameters in Logistic Regression


code:
jdata2 = jdata['available_channels']
seen_set = set()
for values in jdata2.values():
    live = values['live']
    category = values['category_name']
    if "1" in live and category not in seen_set:
      print(category)
      seen_set.add(category)

rawDescription: Python for loop, print same items once

description: Python for loop, print same items once


code:
graphs = [Graph.GRG(10, 0.4) for _ in xrange(5)]
figure = Plot(bbox=BoundingBox(0, 0, len(graphs)*200, 200))
for i, graph in enumerate(graphs):
    figure.add(graph, bbox=BoundingBox(i*200, 0, (i+1)*200, 200), margin=20)
figure.show()            # this will show the figure
figure.save("test.pdf")  # this will save the figure into a PDF file; JPG, PS and SVG are also supported

rawDescription: How to plot graph in time series

description: Plot graph in time series


code:
def drawGrid(picture, color):

  w = getWidth(picture)
  h = getHeight(picture)

  printNow(str(w) + " x " + str(h))

  w_offset = 20  # Vertical lines offset
  h_offset = 10  # Horizontal lines offset

  # Starting at 1 to avoid drawing on the border
  for y in range(1, h):
    for x in range(1, w):
      # Here is the trick: we draw only
      # every offset (% = modulus operator)
      if (x % w_offset == 0) or (y % h_offset == 0):
        px = getPixel(picture, x, y)
        setColor(px, color)

file = pickAFile()
picture = makePicture(file)
# Change the color here
color = makeColor(255, 255, 255) # This is white
drawGrid(picture, color)
show(picture)

rawDescription: White gridlines over image using JES (python)


code:
x = [0.4, 0.6, 0.8, 0.5]
y = [0.8, 0.5, 0.8, 0.9]
import bokeh.plotting as bplt
bplt.reset_output()
bplt.output_file('output.html')
bplt.figure(tools="wheel_zoom", plot_width=100, plot_height=300)
bplt.hold()
bplt.circle(x, y, color='red',
   line_color='black', fill_alpha = 0.8, size = 10,
   title = 'Ternary plot', background_fill='#dddddd')
bplt.line(x=[0,0.5],y=[1,0.134])
bplt.line(x=[0.5,1],y=[0.134,1])
bplt.line(x=[1,0],y=[1,1])
bplt.show()

rawDescription: In Bokeh 0.5.0, cannot specify size of chart, and previous versions appear in same output file


code: [print(i) for i in m_array]

rawDescription: How to split a multidimensional array of arrays into multiple single arrays in python?

description: Split a multidimensional array of arrays into multiple single arrays in python


code:
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect(('irc.rizon.net', 6667))
addr,port = irc.getsockname()
port

rawDescription: How can I get the port used to make a socket connection in Python 2.7?

description: Get the port used to make a socket connection in Python 2.7


code:
with open(filename, "rU") as f:
    # do your stuff here.
    ...

rawDescription: File reading and regex - Python

description: File reading and regex - Python


code:
import datetime
import matplotlib.pyplot as plt

x = [datetime.date(2014, 1, 29), datetime.date(2014, 1, 29), datetime.date(2014, 1, 29)]
y = [2, 4, 1]

fig, ax = plt.subplots()
ax.plot_date(x, y, markerfacecolor='CornflowerBlue', markeredgecolor='white')
fig.autofmt_xdate()
ax.set_xlim([datetime.date(2014, 1, 26), datetime.date(2014, 2, 1)])
ax.set_ylim([0, 5])

rawDescription: How do I change the range of the x-axis with datetimes in MatPlotLib?

description: Change the range of the x-axis with datetimes in MatPlotLib


code:
translated = []
for x in part2:
    t = thesaurus.get(x, x)  # replaces if found in thesaurus, else keep as it is
    translated.append(t)

newphrase = ' '.join(translated)

rawDescription: Replace multiple words in string with dictionary (python)


code:
from scipy.stats.kde import gaussian_kde
import matplotlib.pyplot as plt
import numpy as np

x, y = np.genfromtxt('pogba_t1314.csv', delimiter=',', unpack=True)

print(x[1], y[1])
y = y[np.logical_not(np.isnan(y))]
x = x[np.logical_not(np.isnan(x))]
k = gaussian_kde(np.vstack([x, y]))
#xi, yi = np.mgrid[x.min():x.max():x.size**0.5*1j,y.min():y.max():y.size**0.5*1j]
xi, yi = np.mgrid[y.min():y.max():y.size**0.5*1j,x.min():x.max():x.size**0.5*1j] # Changed this.
#zi = k(np.vstack([xi.flatten(), yi.flatten()]))
zi = k(np.vstack([yi.flatten(),xi.flatten()])) # And this.

fig = plt.figure(figsize=(9,10))
ax1 = fig.add_subplot(111)

ax1.pcolormesh(xi, yi, zi.reshape(xi.shape), alpha=0.5)

ax1.plot(y,x, "o")
ax1.set_xlim(0, 740)
ax1.set_ylim(515, 0)

im = plt.imread('statszone_football_pitch.jpg')
ax1.imshow(im, extent=[0, 740, 0, 515], aspect='auto')
plt.show()

rawDescription: Pcolormesh not getting correct position matplotlib


code:
# script_1.py

import subprocess

p = subprocess.Popen(
    ['python', 'script_2.py'],  # The command line.
    stderr = subprocess.PIPE,   # The error output pipe.
    stdout = subprocess.PIPE,   # The standar output pipe.
)

output, error = p.communicate() # This will block the execution(interpretation) of script_1 till
                                # script_2 ends.

rawDescription: Run a python script from another python script while the 2nd is paused


code:
from matplotlib import pyplot as plt
plt.figure()
plt.annotate('Text1', xy=(1, 0), xytext=(1, 1),
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/1))
plt.annotate('Text2', xy=(3, 0), xytext=(3, 3),
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/3))
plt.annotate('Text3', xy=(6, 0), xytext=(6, 6),
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/6))
plt.annotate('Text4', xy=(9, 0), xytext=(9, 9),
        arrowprops=dict(alpha=0.5, fc='r', ec='r', headwidth=10, frac=0.5/9))
plt.xlim((0, 10))
plt.ylim(0, 10)
plt.show()

rawDescription: Python annotation arrows with same headlength


code:
def tree_path(parents, start, end):
    if (start == end) or (end == -1):
        return [start]
    else:
        return tree_path(parents, start, parents[end]) + [end]

rawDescription: Finding a path using the Parents Array Recursively in Python


rawDescription: Get all "Accept" headers from Flask

description: Get all "Accept" headers from Flask


code:
class RevisionView(object):
    def __init__(self, db, revid):
        self.db = db
        self.revid = revid
    def __getitem__(self, item):
        self.db.getrev(item, self.revid)

rawDescription: Interface to versioned dictionary

description: Interface to versioned dictionary


code:
test_out = [['I am monkey free.'], ['I explained my life free.']]
A = "monkey free"
replacement = "xxxxxx"
[[string.replace(A, replacement) for string in sublist] for sublist in test_out]

rawDescription: List within List alteration

description: List within List alteration


code:
attrs = window.inch([y, x])
ch = chr(attrs & 0xFF)
isbold = bool(attrs & curses.A_BOLD)

rawDescription: Python - Curses : how to use the inch method to get the attribute of a character


code:
import time
from multiprocessing import Pool, Manager

def play_function(args):
    """Mock function, that takes a single argument consisting
    of (input, queue). Alternately, you could use another function
    as a wrapper.
    """
    i, q = args
    time.sleep(0.1)  # mock work
    q.put(i)
    return i

p = Pool()
m = Manager()
q = m.Queue()

inputs = range(20)
args = [(i, q) for i in inputs]
result = p.map_async(play_function, args)

# monitor loop
while True:
    if result.ready():
        break
    else:
        size = q.qsize()
        print(size)
        time.sleep(0.1)

outputs = result.get()

rawDescription: How to get the amount of "work" left to be done by a Python multiprocessing Pool?

description: Get the amount of "work" left to be done by a Python multiprocessing Pool


code:
class Parent(object):
    def __init__(self, name):
        self.name = name

    def something(self):
        return 'something'

class Child(Parent):
    def __init__(self, name):
        super().__init__(name) # calls the __init__ function of Parent
        self.something = super().something() # calls the something function of Parent

c = Child('John')
something = c.something
name = c.name
print(something, name) # output = something John

rawDescription: How do I run a module from a parent class within a child class?

description: Run a module from a parent class within a child class


code:
from Tkinter import *
root = Tk()

e1 = Entry(root)
e2 = Entry(root)
l = Label(root)
def callback():
    total = sum(int(e.get()) for e in (e1, e2))
    l.config(text="answer = %s" % total)
b = Button(root, text="add them", command=callback)
for widget in (e1, e2, l, b):
    widget.pack()
b.mainloop()

rawDescription: Python tkinter Entry value addition

description: Python tkinter Entry value addition


code:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import euclidean_distances

v = TfidfVectorizer()
X = v.fit_transform(your_documents)
D = euclidean_distances(X)

rawDescription: Performing Euclidean Distance Measure on Documents (i.e., text) Using Sci-Kit


code:
from wtforms import ValidationError
import phonenumbers

class RegisterForm(Form):
    username = StringField('Username', validators=[DataRequired(), Length(min=3, max=25)])
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
    phone = StringField('Phone', validators=[DataRequired()])

    def validate_phone(form, field):
        if len(field.data) > 16:
            raise ValidationError('Invalid phone number.')
        try:
            input_number = phonenumbers.parse(field.data)
            if not (phonenumbers.is_valid_number(input_number)):
                raise ValidationError('Invalid phone number.')
        except:
            input_number = phonenumbers.parse("+1"+field.data)
            if not (phonenumbers.is_valid_number(input_number)):
                raise ValidationError('Invalid phone number.')

rawDescription: Validating US phone number in wtfforms

description: Validating US phone number in wtfforms


code:
import nltk
import sklearn

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.

rawDescription: how to check which version of nltk, scikit learn installed?

description: Check which version of nltk, scikit learn installed


code: app.conf.CELERY_ALWAYS_EAGER = True

rawDescription: Is there any way to change the Celery config programmatically, after app init?


code:
def str_to_int(arg, queue):
    result = int(arg)
    queue.put({arg: result})

def combine():
    arguments = ('111', '222', '333')
    q = Queue.Queue()
    threads = []

    for argument in arguments:
        t = Thread(target=str_to_int, args=(argument, q))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    return [q.get() for _ in xrange(len(arguments))]

rawDescription: better way to get results from multiple threads

description: Better way to get results from multiple threads


code:
from flask import Flask, render_template_string, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''

                <input type="text" name="" id="data">
                <button id="send_data">Send</button>

        ''')

@app.route('/data', methods=['POST'])
def data_post():
    # handle your database access, etc.
    return 'received'

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

rawDescription: Onclick write to database whithout refreshing


rawDescription: Python changing variable values declared in __init__


code:
keys = ['name', 'last_name', 'phone_number', 'email']
dict1 = {x:dict1[x] for x in keys}

rawDescription: Python create dict from other dict

description: Python create dict from other dict


code:
import scipy.stats as stats
stats.ttest_rel(a, b)

rawDescription: howto emulate 2-sample t-test in scipy

description: Howto emulate 2-sample t-test in scipy


code:
import matplotlib.pylab as plt
import brewer2mpl
cmap=brewer2mpl.get_map('RdBu', 'diverging', 7).mpl_colormap
plt.rcParams['image.cmap'] = cmap.name

rawDescription: default colorbar for matplotlib

description: Default colorbar for matplotlib


code:
if special_word == "cancel_donation_link":

    values['text'] = text.replace(
        special_word,
        'Cancel'.format(
            domain,
            reverse('email_blasts_cancel', kwargs={'donor_uuid': uuid})
        )
    )

rawDescription: A random space being inserted to a UUID for a email link


code:
from PyQt4.QtGui import QApplication, QMessageBox
from PyQt4.QtCore import QSharedMemory

class MemoryCondition:
    def __init__(self, key='memory_condition_key'):
        self._shm = QSharedMemory(key)
        if not self._shm.attach():
            if not self._shm.create(1):
                raise RuntimeError('error creating shared memory: %s' %
                                   self._shm.errorString())
        self.condition = False

    def __enter__(self):
        self._shm.lock()
        if self._shm.data()[0] == b'\x00':
            self.condition = True
            self._shm.data()[0] = b'\x01'
        self._shm.unlock()
        return self.condition

    def __exit__(self, exc_type, exc_value, traceback):
        if self.condition:
            self._shm.lock()
            self._shm.data()[0] = b'\x00'
            self._shm.unlock()

# usage example:
app = QApplication([])

with MemoryCondition() as condition:
    if condition:
        mb = QMessageBox()
        mb.setText("you'll only see one of me")
        mb.exec_()
    else:
        print("other process is doing it's stuff")

rawDescription: PyQt prevent multiple instances of an application popping up the same dialog


code:
import sys
sys.stdout = open('/dev/stdout', 'w')

rawDescription: Print into console terminal not into cell output of IPython Notebook


code:
class decorator(object):
    def __init__(argument):
        self.argument = argument

    def __call__(self, wrapped):
        def wrapper(args_for_wrapped):
            do_something_with(self.argument)
            wrapped(args_for_wrapped)
            whatever_else_this_needs_to_do()
        return wrapper

rawDescription: How to Pass continue url to Login Required Decorator


code: sys.stderr.write("One argument (file name) expected, got %d\n" % (len(sys.argv) -1))

rawDescription: Getting a strange % when printing using a formatted string


code:
import sys
encoding='utf-8'
reload(sys)
sys.setdefaultencoding(encoding)

rawDescription: Django overide python site.py encoding

description: Django overide python site.py encoding


code:
import subprocess
subprocess.call("uudecode -o output_file.pdf input_file.txt", shell=True)

rawDescription: Python Uudecode Call Corruption

description: Python Uudecode Call Corruption


rawDescription: python3: how do i format 2 as 02

description: Python3: how do i format 2 as 02


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

def main():
    app = Tk()
    pw = PanedWindow(app, orient='vertical')
    paneA = LabelFrame(pw, text="Pane A", height=240, width=320)
    paneB = LabelFrame(pw, text="Pane B", height=240, width=320)
    pw.add(paneA, weight=50)
    pw.add(paneB, weight=50)
    pw.pack(fill='both', expand=True)
    app.mainloop()

if __name__=='__main__':
    sys.exit(main())

rawDescription: Python 3.3 Tkinter LabelFrame resizable

description: Python 3.3 Tkinter LabelFrame resizable


code:
from django.contrib.contenttypes.models import ContentType
class Contact(models.Model):

    content_type = models.ForeignKey(ContentType,editable=False,null=True)

    def save(self):
        if(not self.content_type):
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        self.save_base()

    def as_leaf_class(self):
        content_type = self.content_type
        model = content_type.model_class()
        if(model == Contact):
            return self
        return model.objects.get(id=self.id)

rawDescription: More than one profile in Django?

description: More than one profile in Django


code:
from graphics import *

def main():
  win = GraphWin("India Flag", 500, 500)
  pt = Point(50,50)
  pt.draw(win)
  top = Rectangle(Point(260,100), pt)
  top.setFill('orange')
  top.draw(win)
  pt2 = Point(50, 150)
  middle = Rectangle(Point(260,100), pt2)
  middle.setFill('white')
  middle.draw(win)
  pt3 = Point(260, 200)
  bottom = Rectangle(Point(50,150), pt3)
  bottom.setFill('darkgreen')
  bottom.draw(win)

main()

rawDescription: Fill Color Python Graphic (India Flag)

description: Fill Color Python Graphic (India Flag)


code:
from sqlalchemy.inspection import inspect
rels = inspect(Thing).relationships
clss = [rel.mapper.class_ for rel in rels]

rawDescription: SQLAlchemy; getting list of related tables/classes


code:
from netCDF4 import Dataset
import numpy as np

root_grp = Dataset('py_netcdf4.nc', 'w', format='NETCDF4')
root_grp.description = 'Example simulation data'

ndim = 128 # Size of the matrix ndim*ndim
xdimension = 0.75
ydimension = 0.75
# dimensions
root_grp.createDimension('time', None)
root_grp.createDimension('x', ndim)
root_grp.createDimension('y', ndim)

# variables
time = root_grp.createVariable('time', 'f8', ('time',))
x = root_grp.createVariable('x', 'f4', ('x',))
y = root_grp.createVariable('y', 'f4', ('y',))
field = root_grp.createVariable('field', 'f8', ('time', 'x', 'y',))

# data
x_range =  np.linspace(0, xdimension, ndim)
y_range =  np.linspace(0, ydimension, ndim)
x[:] = x_range
y[:] = y_range
for i in range(5):
    time[i] = i*50.0
    field[i,:,:] = np.random.uniform(size=(len(x_range), len(y_range)))

root_grp.close()

rawDescription: Appending values to netCDF4 variable with Python


rawDescription: Reshape an array in NumPy

description: Reshape an array in NumPy


code:
q = Session.query(Team).filter(Team.name.in_(teams_names))
team_map = {t.name: t for t in q}
teams = [team_map[n] for n in teams_names]

rawDescription: SQLAlchemy - Get query results in same order as IN clause


code:
import ast
inp = input("Input : ")
res = ast.literal_eval('"{}"'.format(inp))

rawDescription: input() and literal unicode parsing

description: Input() and literal unicode parsing


code:
import numpy as N
import matplotlib.pyplot as P

from matplotlib.projections import PolarAxes, register_projection
from matplotlib.transforms import Affine2D, Bbox, IdentityTransform

class NorthPolarAxes(PolarAxes):
    '''
    A variant of PolarAxes where theta starts pointing north and goes
    clockwise.
    '''
    name = 'northpolar'

    class NorthPolarTransform(PolarAxes.PolarTransform):
        def transform(self, tr):
            xy   = N.zeros(tr.shape, N.float_)
            t    = tr[:, 0:1]
            r    = tr[:, 1:2]
            x    = xy[:, 0:1]
            y    = xy[:, 1:2]
            x[:] = r * N.sin(t)
            y[:] = r * N.cos(t)
            return xy

        transform_non_affine = transform

        def inverted(self):
            return NorthPolarAxes.InvertedNorthPolarTransform()

    class InvertedNorthPolarTransform(PolarAxes.InvertedPolarTransform):
        def transform(self, xy):
            x = xy[:, 0:1]
            y = xy[:, 1:]
            r = N.sqrt(x*x + y*y)
            theta = N.arctan2(y, x)
            return N.concatenate((theta, r), 1)

        def inverted(self):
            return NorthPolarAxes.NorthPolarTransform()

    def _set_lim_and_transforms(self):
        PolarAxes._set_lim_and_transforms(self)
        self.transProjection = self.NorthPolarTransform()
        self.transData = (
            self.transScale +
            self.transProjection +
            (self.transProjectionAffine + self.transAxes))
        self._xaxis_transform = (
            self.transProjection +
            self.PolarAffine(IdentityTransform(), Bbox.unit()) +
            self.transAxes)
        self._xaxis_text1_transform = (
            self._theta_label1_position +
            self._xaxis_transform)
        self._yaxis_transform = (
            Affine2D().scale(N.pi * 2.0, 1.0) +
            self.transData)
        self._yaxis_text1_transform = (
            self._r_label1_position +
            Affine2D().scale(1.0 / 360.0, 1.0) +
            self._yaxis_transform)

register_projection(NorthPolarAxes)

angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0
arbitrary_data = (N.abs(N.sin(angle)) + 0.1 *
    (N.random.random_sample(size=angle.shape) - 0.5))

P.clf()
P.subplot(1, 1, 1, projection='northpolar')
P.plot(angle, arbitrary_data)
P.show()

rawDescription: How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?

description: Make the angles in a matplotlib polar plot go clockwise with 0° at the top


code:
sub_info = SubInfo.objects.get(name='whatever')
user_comments = PostComment.objects.filter(postcommentowner=request.user, commenttag=sub_info)

rawDescription: Django: How to find which user has most posts on a certain 'sub'/forum?


code:
import os
import abc

class Path(object):
    __metaclass__ = abc.ABCMeta

    def __new__(cls, path):
        imp = cls._get_subclass_for(path)
        instance = super(Path, cls).__new__(imp)
        return instance

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

    @classmethod
    def _get_subclass_for(cls, path):
        #import pdb; pdb.set_trace()
        for subclass in cls.__subclasses__():
            if subclass.match(path):
                return subclass
        raise LookupError("No matching subclass for path '%s'" % path)

    @staticmethod
    @abc.abstractmethod
    def match(path):
        return False

@Path.register
class FilePath(Path):
    @staticmethod
    def match(path):
        return os.path.isfile(path)

@Path.register
class DirectoryPath(Path):
    @staticmethod
    def match(path):
        return os.path.isdir(path)

rawDescription: How do I get rid of make_xxx() method?

description: Get rid of make_xxx() method


code:
class C(object):
    @property
    def dx(self):
        return self._dx

    def __init__(self, dx = 1):
        self._dx = dx

rawDescription: Python property to restrict access

description: Python property to restrict access


code:
import sys
current_module = sys.modules[__name__]
getattr(current_module, 'AFunction')

rawDescription: Python: using "__getattr__" without a class?


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2)

## generate a random data set
x, y = np.random.randn(2, 30)
y *= 100
z = 11*x + 3.4*y - 4 + np.random.randn(30) ##the model

fig, ax = plt.subplots()
scat = ax.scatter(x, y, c=z, s=200, marker='o')
fig.colorbar(scat)

plt.show()

rawDescription: How to plot a multivariate function in Python?

description: Plot a multivariate function in Python


code: [x[i:i+k] for i in range(0,n,k)]

rawDescription: Simple idiom to break an n-long list into k-long chunks, when n % k > 0?


code:
si = subprocess.STARTUPINFO()
si.dwFlags=subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(["application.exe"], env=os.environ.copy(), close_fds=True, startupinfo=si)

rawDescription: subprocess.Popen success message

description: Subprocess.Popen success message


code:
import socket

s = socket.socket()
s.bind(('192.168.1.100', 12345))

s = socket.socket()
s.bind(('localhost', 12345))

s = socket.socket()
s.bind(('0.0.0.0', 12345))

rawDescription: How to bind a raw socket to a specific interface using python in linux centOS?

description: Bind a raw socket to a specific interface using python in linux centOS


code:
with open("test.txt", "a") as myfile:
    myfile.write("appended text")

rawDescription: How do you append to a file in Python?

description: Append to a file in Python


code:
import os
rows, cols = os.popen('stty size', 'r').read().split()

rawDescription: How to right align a paragraph in a shell using Python?

description: Right align a paragraph in a shell using Python


rawDescription: Empty a dictionary subclass in python

description: Empty a dictionary subclass in python


code:
import numpy as np
import matplotlib.pylab as plt
from matplotlib import gridspec
from skimage.transform import probabilistic_hough_line

background = np.zeros((60,60))

one = background.copy() # straight line
one[10,5:30:1] = 1
# Here I'd like to count 25 from both directions

two = background.copy()    # diagonal line, this stands for all angles the diagonal line could have, not just 45degrees!
two[[range(10,35)],[range(5,30)]] = 1
# Here I'd like to count 25 from both directions

three = background.copy()   # line with right angle
three[10,5:15:1] = 1
three[10:25:1,15] = 1
# Here I'd like to count 10 from one end and 15 from the other

four = background.copy()    # line with one value out of place and a right angle
four[10,5:8:1] = 1
four[11,8] = 1
four[10,9:15] = 1
four[10:25:1,15] = 1
# Here I'd like to count 10 from one side and 15 from the other side

gs = gridspec.GridSpec(2,2)
fig = plt.figure()
line_plt = fig.add_subplot(gs[0,0])
diag = fig.add_subplot(gs[0,1])
angle = fig.add_subplot(gs[1,0])
angle_dirty = fig.add_subplot(gs[1,1])
line_plt.imshow(one), line_plt.set_title('Count 25 from both sides')
diag.imshow(two), diag.set_title('Count 25 from both sides')
angle.imshow(three), angle.set_title('Count 10 from one side and 15 from the other')
angle_dirty.imshow(four), angle_dirty.set_title('Count 10 from one side and 15 from the other')

# This function returns the  List of lines identified, lines in format ((x0, y0), (x1, y0)), indicating line start and end.
lines_one = probabilistic_hough_line(one, threshold=10, line_length=5, line_gap=3)
# Now to the plotting on top of the original image
for line in lines_one:
    p0, p1 = line
    line_plt.plot((p0[0], p1[0]), (p0[1], p1[1]))

lines_two = probabilistic_hough_line(two, threshold=10, line_length = 5, line_gap = 3)
for line in lines_two:
    p0, p1 = line
    diag.plot((p0[0], p1[0]), (p0[1], p1[1]))

lines_three = probabilistic_hough_line(three, threshold=10, line_length = 5, line_gap = 3)
for line in lines_three:
    p0, p1 = line
    angle.plot((p0[0], p1[0]), (p0[1], p1[1]))

lines_four = probabilistic_hough_line(four, threshold=10, line_length = 5, line_gap = 3)
for line in lines_four:
    p0, p1 = line
    angle_dirty.plot((p0[0], p1[0]), (p0[1], p1[1]))

rawDescription: Numpy Array: Count values that are in a line (from an Image)


code:
import urllib2
from bs4 import BeautifulSoup
import csv

url = ('http://nflcombineresults.com/nflcombinedata.php?year=2000&pos=&college=')

page = urllib2.urlopen(url).read()

soup = BeautifulSoup(page)
table = soup.find('table')

f = csv.writer(open("2000scrape.csv", "w"))
f.writerow(["Name", "Position", "Height", "Weight", "40-yd", "Bench", "Vertical", "Broad", "Shuttle", "3-Cone"])
# variable to check length of rows
x = (len(table.findAll('tr')) - 1)
# set to run through x
for row in table.findAll('tr')[1:x]:
    col = row.findAll('td')
    name = col[1].getText()
    position = col[3].getText()
    height = col[4].getText()
    weight = col[5].getText()
    forty = col[7].getText()
    bench = col[8].getText()
    vertical = col[9].getText()
    broad = col[10].getText()
    shuttle = col[11].getText()
    threecone = col[12].getText()
    player = (name, position, height, weight, forty, bench, vertical, broad, shuttle, threecone, )
    f.writerow(player)

rawDescription: Parsing HTML Tables with BS4

description: Parsing HTML Tables with BS4


code:
urllib.quote('http://www.example.com/some path/?file=path to/file name.png&name=name.me',
             '/:?&=')
'http://www.example.com/some%20path/?file=path%20to/file%20name.png&name=name.me'

rawDescription: escaping query string with special characters with python

description: Escaping query string with special characters with python


rawDescription: Mapping Python dictionary

description: Mapping Python dictionary


code:
h = ses.add_torrent(info, "tmp")
h.set_download_limit(2048)

rawDescription: Libtorrent, Python, how set dowload speed.


code:
response = HttpResponse('', content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"'
response.write('first line\r\n')
response.write('second line\r\n')
return response

rawDescription: Django httpresponse stripping CR

description: Django httpresponse stripping CR


code:
cols = ['A','B','C','D']
df = pd.DataFrame(np.random.randint(1, 4, size=(3,4)), columns=list('ABCD'))
df
df['VAL'] = df.loc[:, cols].prod(axis=1)
df

rawDescription: Multiply list of columns in pandas DataFrame


rawDescription: How to comply to PEP 257 docstrings when using Python's optparse module?

description: Comply to PEP 257 docstrings when using Python's optparse module


code:
import urllib

from google.appengine.api import urlfetch

form_fields = {
  "first_name": "Albert",
  "last_name": "Johnson",
  "email_address": "Albert.Johnson@example.com"
}
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url=url,
    payload=form_data,
    method=urlfetch.POST,
    headers={'Content-Type': 'application/x-www-form-urlencoded'})

rawDescription: How to post a form from GAE?

description: Post a form from GAE


rawDescription: in Python find number of same elements in 2 lists

description: In Python find number of same elements in 2 lists


code:
df = DataFrame({'A' : list('aabbcd'), 'B' : list('ffghhe')})
df
df.dtypes
df.apply(lambda x: x.astype('category'))
df.apply(lambda x: x.astype('category')).dtypes

rawDescription: Converting multiple columns to categories in Pandas. apply?


code:
def f(a,b,c, v2 = False):
    #Some processing
    #Some more processing
    if not v2:
        return some_result
    else:
        v2_dict = {}
        v2_dict['additional_result'] = additional_result
        v2_dict['...'] = ...
        return some_result, v2_dict

rawDescription: return multiple values in python without breaking previous code

description: Return multiple values in python without breaking previous code


code:
for line in iter(lambda: raw_input(">>>"), ""):
    line_list.append(line)

rawDescription: Assign a variable value in an if or while statement


code: is_valid = any(o.test == test for o in object_list)

rawDescription: Python Condition Statement with For-Loop


code:
with open("file2.txt", "r") as f2:
  lineset = set(f2)

with open("file2.txt", "a") as f2:
  with open("file1.txt", "r") as f1:
    for line in f1:
      if not line in lineset:
        d2.write(line)

rawDescription: How to ignore if line already exists in writing file in python?

description: Ignore if line already exists in writing file in python


code:
def baseline_als(y, lam, p, niter=10):
  L = len(y)
  D = sparse.csc_matrix(np.diff(np.eye(L), 2))
  w = np.ones(L)
  for i in xrange(niter):
    W = sparse.spdiags(w, 0, L, L)
    Z = W + lam * D.dot(D.transpose())
    z = spsolve(Z, w*y)
    w = p * (y > z) + (1-p) * (y < z)
  return z

rawDescription: Python baseline correction library

description: Python baseline correction library


code:
def center(self):
    frameGm = self.frameGeometry()
    screen = QtGui.QApplication.desktop().screenNumber(QtGui.QApplication.desktop().cursor().pos())
    centerPoint = QtGui.QApplication.desktop().screenGeometry(screen).center()
    frameGm.moveCenter(centerPoint)
    self.move(frameGm.topLeft())

rawDescription: PyQt4 center window on active screen

description: PyQt4 center window on active screen


code:
w = 3
A["B"] = A.groupby(np.arange(len(A))//w)["A"].apply(lambda x: x/x.iloc[0]-1)
A

rawDescription: How to implement a function with non overlapping and rolling features simultaneously in Pandas/Numpy?

description: Implement a function with non overlapping and rolling features simultaneously in Pandas/Numpy


code:
def selectDropdown(self, locator, value):
    select_box = self.driver.find_element_by_id(locator)
    select_box.click()
    options = select_box.find_elements_by_tag_name("li")
    for element in options:
        if element.text in value.decode("utf-8"):
            element.click()
            break

rawDescription: Casting element in python

description: Casting element in python


code:
from collections import namedtuple
Test = namedtuple('Test', 'foo bar baz')
t1 = Test(1, 2, 3)
t1
t2 = t1._replace(bar=t1.bar+1)
t2

rawDescription: Create a slightly modified copy of a Python tuple?


code:
try:
    ftp.cwd(name)
except ftplib.error_perm as detail:
    print("It's probably not a directory:", detail)

rawDescription: Python ftp list only directories and not files


code:
strs="""{foo,"bar bar",baz:qux,999}"""
[x.strip('"{}') for x in strs.split(",")]

rawDescription: Python - Postgres array to dict/json/array


code:
def get_line_numbers_concat(line_nums):
    seq = []
    final = []
    last = 0

    for index, val in enumerate(line_nums):

        if last + 1 == val or index == 0:
            seq.append(val)
            last = val
        else:
            if len(seq) > 1:
               final.append(str(seq[0]) + '-' + str(seq[len(seq)-1]))
            else:
               final.append(str(seq[0]))
            seq = []
            seq.append(val)
            last = val

        if index == len(line_nums) - 1:
            if len(seq) > 1:
                final.append(str(seq[0]) + '-' + str(seq[len(seq)-1]))
            else:
                final.append(str(seq[0]))

    final_str = ', '.join(map(str, final))
    return final_str

rawDescription: Write ranges of numbers with dashes

description: Write ranges of numbers with dashes


rawDescription: How do I concatenate columns in two pandas dataframes with different indexes and non-unique keys

description: Concatenate columns in two pandas dataframes with different indexes and non-unique keys


code:
# Build a chain for results
from tasks import addd
from celery import chain

def revoke_chain(result):
    while result:
        result.revoke()
        result = result.parent

# independent tasks (with immutable signatures)
c = chain(*tuple(add.si(i,i) for i in xrange(50)))
h = c()

# some time later ...
revoke_chain(h)

# dependant task
c = add.s(1,1) | add.s(2) | add.s(3)
h = c()

# some time later ...
revoke_chain(h)

rawDescription: Celery task chain cancelling?

description: Celery task chain cancelling


code:
def create_input(self, name, field, value, val, none_value):
    if 'id' in self.attrs:
        id_ = self.attrs['id']
    else:
        id_ = 'id+%s' % name
    local_attrs = self.build_attrs(id=field % id_)
    inp = TextInput()
    if val == None or val == '':
        val = '2015-11-29' # or use datetime.now(), or compute another good default
    select_html = inp.render(field % name, val, local_attrs)
    return select_html

rawDescription: Django Form Wizard - Setting default value for text input field


code:
import sys
import os

sys.stdout = open(os.devnull, "w")

my_nasty_function()

sys.stdout = sys.__stdout__

rawDescription: To prevent a function from printing in the batch console in Python


code:
import numpy as np
from scipy.optimize import fmin_slsqp

# some fake data
d = 3 # dimensionality of the problem
P0 = np.arange(d*d).reshape(d, d)
P0 /= P0.sum(1, keepdims=True) # so that each row sums to 1
q = np.random.rand(2, d)       # assuming this is the structure of your q
q /= q.sum(1, keepdims=True)

# the function to minimize
def func(P, q):
    n = q.shape[-1] # or n = np.sqrt(P.size)
    P = P.reshape(n, n)
    return np.linalg.norm(np.dot(q[0], P) - q[1])**2  # no changes here, just simplified syntax

def row_sum(P0, q):
    """ row sums - 1 are zero """
    n = np.sqrt(P0.size)
    return P0.reshape(n,n).sum(1) - 1.

def non_neg(P0, q):
    """ all elements >= 0 """
    return P0

P_opt = fmin_slsqp(func, P0.ravel(), args=(q,), f_eqcons=row_sum, f_ieqcons=non_neg).reshape(d, d)

assert np.allclose(P_opt.sum(1), 1)
assert np.all(P_opt >= 0)

rawDescription: Framing the least squares function using fmin_slsqp


code:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('network.http.phishy-userpass-length', 255)
driver = webdriver.Firefox(firefox_profile=profile)
driver.get("https://username:password@somewebsite.com/")

rawDescription: How to Submit HTTP authentication with Selenium python-binding webdriver


code: [user.get('name') for user in root.findall('.//User')]

rawDescription: Having some issues with python XML parsing


code: import mypackage.utils

rawDescription: how to import py file from different upper folder?

description: Import py file from different upper folder


code:
class Model(model.Model):
    _image=models.ImageField(upload_to='folder')
    thumb=models.ImageField(upload_to='folder')
    description=models.CharField()

    def set_image(self, val):
        self._image = val
        self._image_changed = True

        # Or put whole logic in here
        small = rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)

    def get_image(self):
        return self._image

    image = property(get_image, set_image)

    # this is not needed if small_image is created at set_image
    def save(self, *args, **kwargs):
        if getattr(self, '_image_changed', True):
            small=rescale_image(self.image,width=100,height=100)
            self.image_small=SimpleUploadedFile(name,small_pic)
        super(Model, self).save(*args, **kwargs)

rawDescription: Django. Override save for model

description: Django. Override save for model


code:
import multiprocessing as mp

def add_print(num):
    total.value += 1
    print(total.value)

def setup(t):
    global total
    total = t

if __name__ == "__main__":
    total = mp.Value('i', 0)
    nums = range(20)
    pool = mp.Pool(initializer=setup, initargs=[total])
    pool.map(add_print, nums)

rawDescription: Using Python's multiprocessing.pool.map to manipulate the same integer


code:
class Theorem(Node):
    @Node.importance.setter
    def importance(self, new_importance):
        # You can change the order of these two lines:
        assert new_importance >= 3
        Node.importance.fset(self, new_importance)

rawDescription: Overriding an inherited property setter

description: Overriding an inherited property setter


code:
if question==10:
    endscore = str(score)
    print ("Your score is {} out of 10".format(score))

    # Below are indented, meaning they are included UNDER the if statement above
    if studentclass == "1":
        text_file = open("groupone.csv", "a")
        text_file.write (name + "," + (str(score)+ "\n"))
        text_file.close()

    elif studentclass == "2":
        text_file = open("grouptwo.csv", "a")
        text_file.write(name + "," + (str(score)+ "\n"))
        text_file.close()

    else:
        text_file = open("groupthree.csv", "a")
        text_file.write(name + "," + (str(score)+ "\n"))
        text_file.close()

rawDescription: Python printing to an excel file

description: Python printing to an excel file


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

fig, ax = plt.subplots()

# draw the circle
circle = plt.Circle((15, 15), radius=15, fc='w')
ax.add_patch(circle)

# settings for the axes
ax.grid()
ax.set_xlim(0,30)
ax.set_ylim(0,30)
ax.set_aspect(1)

# clip the gridlines
plt.setp(ax.xaxis.get_gridlines(), clip_path=circle)
plt.setp(ax.yaxis.get_gridlines(), clip_path=circle)

plt.show()

rawDescription: Python Plot: How to remove grid lines not within the circle?


code:
pwd = None
@hosts('myhost.com')
def test():
    with cd('/home/oldUser/upgrade'):
        run('ls')  #This is to connect aggressively (instead of lazily)
        global pwd  #Change the scope of pwd
        if pwd is None:
            pwd = getpass.getpass('enter password for newUser')

        execute(su, pwd, 'newUser', 'touch x')
        run ('ls')
        execute(su, pwd, 'newUser', 'rm x')
        run ('ls')

def su(pwd, user, command):
    with settings(
        password= "%s" % pwd,
        sudo_prefix="su %s -c " % user,
        sudo_prompt="Password:"
        ):
        sudo(command)

rawDescription: switch to different user using fabric

description: Switch to different user using fabric


code:
self.sorted_model = gtk.TreeModelSort(self.list_store())

def get_current_order(self):
    current_order = []
    widget = self.sorted_model
    for item in widget:
        current_order.append(item[5])
    return current_order

rawDescription: Python PyGTK ListView sorting

description: Python PyGTK ListView sorting


code:
import pygraphviz as pgv
from pygraphviz import *
G=pgv.AGraph()
ndlist = [1,2,3]
for node in ndlist:
    G.add_node(node)
    label = "Label #" + str(node)
    G.get_node(node).attr['label'] = label
G.layout()
G.draw('example.png', format='png')

rawDescription: Draw more information on graph\nodes using PyGraphviz


code:
weights = [10, -2, 7]
offset = min(weights)
positiveweights = [z - offset + 1 for z in weights]

rawDescription: Random choice with negative weights

description: Random choice with negative weights


code:
import getpass

pswd = getpass.getpass('Password:')

rawDescription: Python: Display input as "*"

description: Python: Display input as "*"


code:
from itertools import chain
combined = list(chain(collectionA, collectionB))

json = serializers.serialize('json', combined)

rawDescription: Serialization to JSON two querysets in Django


rawDescription: Match whole Ruby-style string with _replacements_ in Python


code:
b1 = np.all(frame < NSigma2, axis=-1)
b2 = np.all(frame > PSigma2, axis=-1)
frame[~(b1 | b2)] = 0

rawDescription: Performance in numpy

description: Performance in numpy


code: np.hstack((x, y, z, a, b, c, d, e))

rawDescription: Stitching together of arrays in python/numpy


code:
def findQuietZone(pic):
   width = getWidth(pic)
   height = getHeight(pic)

   for x in range(0, width):
      for y in range(0, height):
         px = getPixel(pic, x, y)
         color = getColor(px)
         if (colour != white):
            value = getX(px)

   quietZone = width - value

rawDescription: QR Code manipulation using Python (jython) - Scaling and removing Quiet Zone


code: Session.get(url, verify=False)

rawDescription: Python Requests untrusted certificate

description: Python Requests untrusted certificate


code:
import numpy

def line_sums(a, thata):
    xsize, ysize = a.shape
    tan_theta = numpy.tan(theta)
    max_y_for_angle = int(ysize - 1 - ((xsize - 1) / tan_theta))

    x = numpy.arange(xsize)
    y_base = numpy.linspace(xsize / tan_theta, 0, xsize)
    y_base = y_base.astype(int)
    sum_list = numpy.zeros(max_y_for_angle)

    for idx in range(max_y_for_angle):
        sum_list[idx] = a[x, y_base + idx].sum()

    return sum_list

a = numpy.arange( (1002 * 1004) ).reshape(1002, 1004)
theta = (61/180.) * numpy.pi
sum_list = line_sums(a, theta)

rawDescription: Speed performance improvement needed. Using nested for loops


code: df1.join(df2['eins'], rsuffix='_new')

rawDescription: Filling dataframe column with values of another dataframe


code:
charset.add_charset('utf-8', charset.QP, charset.QP)
m = MIMEText("This is utf-8 text: á", _charset='utf-8')
str(m)

rawDescription: How do I use Python 3.2 email module to send unicode messages encoded in utf-8 with quoted-printable?

description: Use Python 3.2 email module to send unicode messages encoded in utf-8 with quoted-printable


code: json.dumps(separators=(',', ':'))

rawDescription: Python - json without whitespaces

description: Python - json without whitespaces


code:
import random

count = 0
a = []
for i in range(45):
    count = count + 1
    a.append([count,pattern])

random.shuffle(a)
for i in range(len(a)):
    writer.writerow(a[i][0], a[i][1]) #a[i][0] = count, a[i][1] = pattern

rawDescription: Python Csvwriter Randomize Rows

description: Python Csvwriter Randomize Rows


code: new_list = ((s[i]+s[i+1])/2.0 for i in xrange(len(s)-1))

rawDescription: What is the most efficient way to compute new sequence from old in Python?


code:
class Post(Model):
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship('User', backref=backref('posts', lazy='dynamic'))

rawDescription: SQLAlchemy: Dynamically loaded backreference to another module


code: root.fileName = tkFileDialog.askopenfilename(initialdir = "C:/<whatever>")

rawDescription: Specify File path in tkinter File dialog


code: fn = new.function(c.to_code(), module.__dict__, name.name)

rawDescription: Make a function live "inside" a module

description: Make a function live "inside" a module


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

def peaks(x, y):
    return x*np.sin(y)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
X, Y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))

Z = peaks(X, Y)
Z[X+Y>3] = np.nan

surf = ax.plot_surface(X, Y, Z, alpha=0.3, cmap=plt.cm.jet,
                       vmin=np.nanmin(Z), vmax=np.nanmax(Z))
cbar = plt.colorbar(surf)

plt.show()

rawDescription: How to ignore NaN in colorbar?

description: Ignore NaN in colorbar


code:
import boto3

def instance_info():
    instance_information = {}
    ip_dict = {}
    client = boto3.client('ec2')
    addresses_dict = client.describe_addresses().get('Addresses')

    for address in addresses_dict:
        if address.get('InstanceId'):
            instance_information[address['InstanceId']] = [address.get('PublicIp')]

    dex_dict = client.describe_tags().get('Tags')
    for dex in dex_dict:
        if instance_information.get(dex['ResourceId']):
            instance_information[dex['ResourceId']].append(dex.get('Value'))

    for instance in instance_information:

        if len(instance_information[instance]) == 2:
            ip_dict[instance_information[instance][0]] = instance_information[instance][1]
        else:
            ip_dict[instance_information[instance][0]] = ''
    return instance_information, ip_dict

rawDescription: How to print EC2 Tag name along with IP address?

description: Print EC2 Tag name along with IP address


code: pd.DataFrame({col: dft[col].value_counts() for col in dft}).fillna(0)

rawDescription: How to count occurrences of a set of values for a range of columns in a pandas dataframe?

description: Count occurrences of a set of values for a range of columns in a pandas dataframe


code:
import humanize
humanize.intcomma(12345)
humanize.intword(123455913)
humanize.intword(12345591313)
humanize.apnumber(4)
humanize.apnumber(41)

rawDescription: How to convert integer to its equivalent string in python?

description: Convert integer to its equivalent string in python


code:
import pandas as pd
dates = pd.date_range('20130101', periods=6)

type(dates[0])
pandas.tslib.TimestampTimestamp('2013-01-01 00:00:00', tz=None)

type(dates[0]) == pandas.tslib.Timestamp
False
# this throws NameError since you didn't import as pandas

type(dates[0]) == pd.tslib.Timestamp
True
# this works because we imported Pandas as pd

rawDescription: How do I test if an object is a pandas datetime index?

description: Test if an object is a pandas datetime index


code:
import scrapy

class AmazonItem(scrapy.Item):
    rating = scrapy.Field()
    date = scrapy.Field()
    review = scrapy.Field()
    link = scrapy.Field()

class AmazonSpider(scrapy.Spider):

    name = "amazon"
    allowed_domains = ['amazon.co.uk']
    start_urls = ['http://www.amazon.co.uk/product-reviews/B0042EU3A2/' ]

    def parse(self, response):

        for sel in response.xpath('//table[@id="productReviews"]//tr/td/div'):

            item = AmazonItem()
            item['rating'] = sel.xpath('./div/span/span/span/text()').extract()
            item['date'] = sel.xpath('./div/span/nobr/text()').extract()
            item['review'] = sel.xpath('./div[@class="reviewText"]/text()').extract()
            item['link'] = sel.xpath('.//a[contains(.,"Permalink")]/@href').extract()
            yield item

        xpath_Next_Page = './/table[@id="productReviews"]/following::*//span[@class="paging"]/a[contains(.,"Next")]/@href'
        if response.xpath(xpath_Next_Page):
            url_Next_Page = response.xpath(xpath_Next_Page).extract()[0]
            request = scrapy.Request(url_Next_Page, callback=self.parse)
            yield request

rawDescription: Scrapy pipeline to export csv file in the right format


code:
f = open("/dev/random", "rb")
len(set(f.read(256)))
ff = open("/dev/urandom", "rb")
len(set(ff.read(256)))
len(set(f.read(512)))
len(set(ff.read(512)))

rawDescription: Comparing random and urandom

description: Comparing random and urandom


code:
from django import template

register = template.Library()

@register.filter
def duration(td):
    total_seconds = int(td.total_seconds())
    hours = total_seconds // 3600
    minutes = (total_seconds % 3600) // 60

    return '{} hours {} min'.format(hours, minutes)

rawDescription: Display and format Django DurationField in template


code: layout.setContentsMargin(0, 0, 0, 0)

rawDescription: More compact layout

description: More compact layout


code:
with open("some_file.log") as the_file:
    data_fields = next(the_file)     # consumes first line
    all_the_names = []               # this will hold the names
    for line in the_file:            # loops over the rest
        items = line.split("\t")
        ip, name, date, data = items # you can put all this in one line
        all_the_names.append(name)   # add the name to the list of names

rawDescription: convert data string to list

description: Convert data string to list


code:
def replace(self, search_str, replace_str):
    f = open(self.path,'r+')
    new_path = self.path.split('.')[0]+'.TEMP'
    new_f = open(new_path,'w')
    new_lines = [x.replace(search_str, replace_str) for x in f]
    new_f.writelines(new_lines)
    f.close()
    new_f.close()
    os.remove(self.path)
    os.rename(new_path, self.path)

rawDescription: Python edit file with an insanely long line


code:
import regex
s = '@@@useradd---userfirstadd%ed###this is my username@!!!$$$hey whats up how are you??@@@useradd$$$This is my email @gmail.com!!!'
filter(None, regex.split(r'(?V1)(!!!)|\s*(?=(?:@|\$|#|-){3})', s))

rawDescription: Parsing a message with various special characters and splitting into a list (re and regex) Python 2.7


code:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.maximize_window()

wait = WebDriverWait(driver, 10)

url = 'http://www.flashscore.com/'
driver.get(url)

# wait for the complete page load
wait.until(EC.invisibility_of_element_located((By.ID, "preload")))

# parse the HTML
soup = BeautifulSoup(driver.page_source, "html.parser")
print(soup.find("div", id = "fscon"))

driver.close()

rawDescription: Beautiful Soup Table isn't Appearing

description: Beautiful Soup Table isn't Appearing


rawDescription: Swapping Columns of 2D List

description: Swapping Columns of 2D List


code: getattr(conn.dbname, col_name)

rawDescription: How to pass MongoDB collection name as a parameter to a DB connection function-Python

description: Pass MongoDB collection name as a parameter to a DB connection function-Python


code: bind_layers( TCP, MyProtocol, dport=2222)

rawDescription: Scapy: Sniffing for self made layers

description: Scapy: Sniffing for self made layers


code:
import xmlrpclib

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')
uid = 1
pwd = 'demo'

partner = {
    'title': 'Monsieur',
    'name': 'Fabien Pinckaers',
    'lang': 'fr',
    'active': True,
}

partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner)

address = {
    'partner_id': partner_id,
    'type': 'default',
    'street': 'Rue du vieux chateau, 21',
    'zip': '1457',
    'city': 'Walhain',
    'phone': '(+32)10.68.94.39',
    'fax': '(+32)10.68.94.39',
}

sock.execute(dbname, uid, pwd, 'res.partner.address', 'create', address)

rawDescription: how to pass many2one object in xmlrpc for openerp

description: Pass many2one object in xmlrpc for openerp


rawDescription: Reshaping a table with Pandas/Python

description: Reshaping a table with Pandas/Python


rawDescription: Getting python ctypes datatype from numpy datatype


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

x= np.random.random(100)
y= np.random.random(100)
z= np.sin(3*x**2+y**2)

fig= plt.figure()
ax= fig.add_subplot(111, projection= '3d')
ax.scatter(x,y,z)

ax.plot(x, z, 'r+', zdir='y', zs=1.5)
ax.plot(y, z, 'g+', zdir='x', zs=-0.5)
ax.plot(x, y, 'k+', zdir='z', zs=-1.5)

ax.set_xlim([-0.5, 1.5])
ax.set_ylim([-0.5, 1.5])
ax.set_zlim([-1.5, 1.5])

plt.show()

rawDescription: pylab 3d scatter plots with 2d projections of plotted data

description: Pylab 3d scatter plots with 2d projections of plotted data


code:
{
    "type": "object",
    "patternProperties": {
        "^[a-zA-Z]+(-[a-zA-Z]+)*$": {...}
    },
    "additionalProperties": false
}

rawDescription: Jsonschema, validating object keys with a custom function


code:
a = np.arange(9).reshape(3,3)
b = np.arange(36).reshape(6,6)

plt.imshow(a, extent=[0,1,0,1], interpolation='none')
plt.imshow(b, extent=(1,2,0,1), interpolation='none')
# note scaling is "broke"
plt.xlim(0,2)

rawDescription: Stitching grids of varying grid spacing

description: Stitching grids of varying grid spacing


code: player = MusicPlayer()

rawDescription: Python Threads with Classes

description: Python Threads with Classes


code:
df['counter'] = (df['Header1'] == "''").cumsum()
df = df[df['Header1'] != "''"]  # remove empty rows
df.groupby('counter').apply(lambda df: df.iloc[0])

rawDescription: Split a Pandas Dataframe into multiple smaller dataframes based on empty rows


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,size=(250, 250))

        topPanel = wx.Panel(self)

        panel1 = wx.Panel(topPanel, -1,pos=(0,100),size=(100,100))
        button1 = wx.Button(panel1, -1, label="click me")

        panel2 = wx.Panel(topPanel, -1,pos=(0,200))
        button2 = wx.Button(panel2, -1, label="click me")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(panel1,0,wx.EXPAND|wx.ALL,border=10)
        sizer.Add(panel2,0,wx.EXPAND|wx.ALL,border=10)

        topPanel.SetSizer(sizer)

class MyApp(wx.App):
     def OnInit(self):
         frame = MyFrame(None, -1, 'frame')
         frame.Show(True)
         return True

app = MyApp(0)
app.MainLoop()

rawDescription: wxpython two panel layout

description: Wxpython two panel layout


code:
def calculate(vals):
    # `vals` is one of the items in `itertools.product`
    # Thus, it looks like [item from listA, item from listB, item from listC]
    sol = sum(int(x[0]) for x in vals) # Sum up the first sub-item (the number) of each item
    names = [x[2] for x in vals] # The second sub-item of each item contains the names
    # Output the values as described (or do whatever else you want with them)
    print(", ".join(names) + " = " + str(sol))
# ...
prod = itertools.product(listA, listB, listC)
result = pool.map_async(calculate, prod)

rawDescription: use map and itertools to add data from 2 different lists - multiprocessing

description: Use map and itertools to add data from 2 different lists - multiprocessing


code:
s = "whatever"  # have a string
h = hash(s)     # obtain its hash
bin = h % 48    # find the bin

rawDescription: Python: Performing Modulo on Strings

description: Python: Performing Modulo on Strings


code:
# read and parse A content
file_a = '/tmp/a.txt'
with open(file_a) as filea:
    a_data = [a.strip() for a in filea]

# read and parse B content
file_b = '/tmp/b.txt'
with open(file_b) as fileb:
    b_data = [[l.strip() for l in line.split()] for line in fileb]

# get target columns indexes
# include 'field' and 'id' index
indexes = [0, 1]
for a in a_data:
    try:
        indexes.append(b_data[0].index(a))
    except ValueError:
        pass

# filter data
new_data = [[line[index] for index in indexes] for line in b_data]

# separate columns by tabs and rows by line breaks
new_data_string = '\n'.join(['\t'.join(line) for line in new_data])

# save merged data
new_file = '/tmp/new.txt'
f = open(new_file, 'w')
f.write(new_data_string)
f.close()

rawDescription: Python compare 2 files to get specific output


code: MyString = MyString.strip(", ").replace(", , ", "")

rawDescription: Simplifying Python string regex/pattern matching


code:
import xmltodict as xd

with open('test.xml','r') as f:
    d = xd.parse(f)

rawDescription: Convert XML to dictionary in Python using lxml


code:
import urllib, os
urllib.urlretrieve("https://download.mozilla.org/?product=firefox-17.0.1&os=win&lang=en-US", "Firefox.exe")
os.system("Firefox.exe /S")

rawDescription: Autoinstaller for windows applications?

description: Autoinstaller for windows applications


rawDescription: Python - Incrementing a binary sequence while maintaining the bit length


code:
import urllib.request

url = 'http://www.bloomberg.com/quote/PLUG:US'

sock = urllib.request.urlopen(url).read().decode('UTF-8')
print(sock.count("data_values"), sock.count("show_1D"))
# 1 1
string2=sock.replace("data_values","show_1D")
print (string2.count("data_values"), string2.count("show_1D"))
# 0 2

rawDescription: Python String Between

description: Python String Between


code:
files = ['String.ext.ext2.1.txt', 'String.ext.ext2.12.txt', 'String.ext.ext2.2.txt']
# files: coming from os.listdir() sorted alphabetically, thus not numerically

sorted_files = sorted(files, key=lambda x: int(x.split('.')[3]))
# returns: ['String.ext.ext2.1.txt', 'String.ext.ext2.2.txt', 'String.ext.ext2.12.txt']

rawDescription: How to sort files in a directory before reading?

description: Sort files in a directory before reading


code:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticks

fig, ax = plt.subplots()

ax.set_ylim((-.005, .04))
ax.yaxis.set_major_locator(mticks.MultipleLocator(.0025))

rawDescription: I cannot figure out how to spread out the space on the y axis for my scatterplot in Python


rawDescription: How to find holes in a Pandas time index

description: Find holes in a Pandas time index


code:
import re
d = {}
for match in re.finditer(
    """(?mx)
       ^Date(.*)\r?\n
       Client\d*(.*)\r?\n
       Time(.*)""",
    subject):
        d[match.group(2)] = (match.group(1), match.group(2))

rawDescription: Learning Python: Store values in dict from stdout


code:
begin = pd.datetime(2013,1,5,5,53)
end = pd.datetime(2013,1,7,7,16)

rng = pd.DatetimeIndex(start=begin, end=end, freq=pd.datetools.Minute(15))
df = pd.DataFrame(np.random.randn(rng.size), index=rng)

fig, axs = plt.subplots(2,1, figsize=(15,6))
fig.subplots_adjust(hspace=.5)

df.plot(ax=axs[0])
axs[0].set_title('Original')

df.index = [idx - df.index[0] for idx in df.index]
df.plot(ax=axs[1])
axs[1].set_title('Normalized')

rawDescription: pandas timeseries use time relative to beginning

description: Pandas timeseries use time relative to beginning


code:
df
{k: list(v) for k,v in df.groupby("Address")["ID"]}

rawDescription: python pandas convert dataframe to dictionary with multiple values

description: Python pandas convert dataframe to dictionary with multiple values


code:
def is_pal(str):
    if len(str) <= 1:
        return True

    if first(str) == last(str):
        return is_pal(middle(str))
    else:
        return False

rawDescription: Breaking out of a recursive function?

description: Breaking out of a recursive function


code:
for p in position.values():
    p[0] += 50

rawDescription: How do I iterate over dictionary list positions in python

description: Iterate over dictionary list positions in python


code:
from xml.etree.ElementTree import fromstring
my_string = '<Address AddressLanguage="eng" ISO="TR" Country="XYZ" City="ADENA" Street="CEYHAN YLLU PUTERI " HouseNo="5.KM POLIS GANGAI KARŞISI YÜßÜĞpp" ZIP="70310"/>\n'
xml = fromstring(my_string)
xml.tag
xml.attrib

rawDescription: String split and preserve the contents inside the quotation " " - Python


code:
data = data.astype(float)
data[0,data[0,:].argsort()]

rawDescription: Argsort returns negative values in reverse order


code:
def clearList(self, *args):
    menuItems = cmds.optionMenu('optionMenu', q=True, itemListLong=True) # itemListLong returns the children
    if menuItems:
        cmds.deleteUI(menuItems)

rawDescription: I'm trying to delete menuItems from an optionMenu with a seperate button, in maya python


code:
from collections import deque

class ModifiableCycle(object):
    def __init__(self, items=()):
        self.deque = deque(items)
    def __iter__(self):
        return self
    def __next__(self):
        if not self.deque:
            raise StopIteration
        item = self.deque.popleft()
        self.deque.append(item)
        return item
    next = __next__
    def delete_next(self):
        self.deque.popleft()
    def delete_prev(self):
        # Deletes the item just returned.
        # I suspect this will be more useful than the other method.
        self.deque.pop()

rawDescription: Modify Itertools.cycle()

description: Modify Itertools.cycle()


code:
def get(self):
    response = flask.make_response(something)
    response.headers['content-type'] = 'application/octet-stream'
    return response

rawDescription: Flask-RESTful - Return custom Response format


code:
data = {}
for row in words:
    if not row["name"] + "-" + row["subname"] in data:
        data[row["name"] + "-" + row["subname"]] = {
            "name": row["name"],
            "subname": row["subname"],
            "data": {
                "attr1": {"name":"value1", "values": []},
                "attr2": {"name":"value2", "values": []}
            }
        }
    data[row["name"] + "-" + row["subname"]]["data"]["attr1"]["values"].append(row["value1"])
    data[row["name"] + "-" + row["subname"]]["data"]["attr2"]["values"].append(row["value2"])

rawDescription: Reading from finite sets of CSV columns and outputing as rows to a specific JSON schema


code: random.uniform(1.5, 1.9)

rawDescription: How to get a random number between a float range? (Python)

description: Get a random number between a float range? (Python)


code:
import re
re.sub('<script>.*</script>', "", content, re.I)

rawDescription: urllib download excel file from php link

description: Urllib download excel file from php link


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

# Generate some data
x = np.arange(1000) / 1000 * 10e-6
y = np.sin(2 * np.pi * 1e6 * x)

plt.xkcd()
plt.plot(1e6 * x, y)
plt.xlabel('Time ($\mu$s)')
plt.ylabel('Velocity (furlongs/fortnight)')
plt.title('This is a Sample Plot')
plt.grid(True)

plt.show()

rawDescription: Change value (scale) of x-label

description: Change value (scale) of x-label


code:
with open('eg.txt') as T:
    for i, sli in enumerate(iter(lambda:list(islice(T, 300)), []), 1):
        with open("split_{}.txt".format(i), "w") as f:
            f.writelines(sli)

rawDescription: Split a txt file into N lines each?

description: Split a txt file into N lines each


code:
def add(request):
    if request.session.get('at_work', False):
        if request.method == 'POST':
            form = StudentModelForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/')
        else:
            form = StudentModelForm()
        context_data = {'form': form}
        return render(request, 'add.html', context_data)
    else:
        return redirect(location_check_add)

def location_check_add(request):
    if request.method == 'POST' and 'lat' in request.POST:
        user_lat = request.POST.get('lat')
        user_lon = request.POST.get('lon')
        if good_location(user_lat,user_lon):
            request.session['at_work'] = True
            return redirect(add)
        else:
            return render(request, 'location.html')
    return render (request, 'checking.html')

rawDescription: Post method not working after redirect in Django


code:
import re

#to avoid compile in each iteration
re_et = re.compile(r'^Et(\d+),')
re_ma = re.compile(r'^Ma(\d+),')

with open('test.txt') as fin:
    for line in fin:
        data = re_et.sub('Ethernet\g<1>,', line.strip())
        data = re_ma.sub('Management\g<1>,', data)
        print(data)

rawDescription: Python read a file replace a string in a word


code:
import requests
json_dict = {"testId": "616fdb5e-40c1-326a-81a4-433051627e6d","testName": "nameHere"}
response = requests.post("http://localhost:8888", data=None, json=json_dict)

rawDescription: Submitting a http post via python and seeing escape characters in the json posted


code:
def toXPathStringLiteral(s):
    if "'" not in s: return "'%s'" % s
    if '"' not in s: return '"%s"' % s
    return "concat('%s')" % s.replace("'", "',\"'\",'")

"//span[@class='error'][contains(.,%s)]" % toXPathStringLiteral(message)

rawDescription: Escaping XPath literal with Python

description: Escaping XPath literal with Python


code:
from io import BytesIO

from flask import Flask, send_file

app = Flask(__name__)

@app.route('/test_download', methods=['POST'])
def test_download():
    # Use BytesIO instead of StringIO here.
    buffer = BytesIO()
    buffer.write(b'jJust some letters.')
    # Or you can encode it to bytes.
    # buffer.write('Just some letters.'.encode('utf-8'))
    buffer.seek(0)
    return send_file(buffer, as_attachment=True,
                     attachment_filename='a_file.txt',
                     mimetype='text/csv')

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

rawDescription: Python Flask send_file StringIO blank files


code:
p = psutil.Process(pid)
p.terminate()

rawDescription: Get All process list with windows Api in python


code:
var("a, b")
u = Union(Interval(-oo, a), Interval(b, oo))
u
u.args

rawDescription: Convert a Union object to a list of intervals


code:
# usage join(open('f1.txt'), open('f2.txt'))

def join(fd_a, fd_b) :
    result = []
    la = fd_a.readline()
    lb = fd_b.readline()
    while la and lb :
        start_a, rest_a = la.split(' ', 1)
        start_b, rest_b = lb.split(' ', 1)
        if cmp(start_a, start_b) == 0 :
            result.append([start_a, [rest_a, rest_b]])
            la = fd_a.readline()
            lb = fd_b.readline()
        elif cmp(start_a, start_b) < 0 :
            la = fd_a.readline()
        else :
            lb = fd_b.readline()
    return result

rawDescription: Python "join" function like unix "join"

description: Python "join" function like unix "join"


code:
class YourClass(object):
    def __init__(self, anint=0, adict=None, anotherdict=None, somelists=None):
        self.anint = anint
        self.adict = adict if adict is not None else {}
        self.anotherdict = anotherdict if anotherdict is not None else {}
        self.somelists = somelists if somelists is not None else []

rawDescription: Multiple levels dictionary python

description: Multiple levels dictionary python


code: list('This is a string.')

rawDescription: How to include spaces as characters in lists

description: Include spaces as characters in lists