code:
import os
import re
r = re.compile(r"|".join([e for e in exc]))
for f in os.listdir("path"):
    if f.endswith((".mp4",".mp3",".avi")):
        f = r.sub("",f)

rawDescription: How to loop through list of options inside if statement in python 2.7?

description: Loop through list of options inside if statement in python 2.7


code:
from django.utils.html import strip_tags
message = strip_tags(form.cleaned_data['message'])

rawDescription: Sanitizing HTML in submitted form data

description: Sanitizing HTML in submitted form data


code: users = User.objects.filter(event__in=list(events.values_list('pk', flat=True)))

rawDescription: Most efficient Django query to return results spanning multiple tables


rawDescription: Unpacking arguments from argparse

description: Unpacking arguments from argparse


code:
def show_hand(hand):
    print('Your cards:')
    for i, (rank, suit) in enumerate(hand, 1):
        rank = ranks.get(rank, rank)
        suit = suits[suit]
        print('%d: %s of %s' % (i, rank, suit))

rawDescription: how to print user friendly poker hand in python?

description: Print user friendly poker hand in python


rawDescription: Decoding hex string gives me garbage

description: Decoding hex string gives me garbage


rawDescription: Dealing with a string and byte in python


code:
@app.route('/')
def homepage():
    title = 'home'

    #First Plot
    from my_plots import first_plot
    p = first_plot()

    #Second Plot
    from my_plots import second_plot
    p2 = second_plot()

    script, div = components(p)
    script2, div2 = components(p)

    return render_template('index.html', title = title, script = script,
    div = div, script2 = script2, div2 = div2)

rawDescription: Embedding multiple bokeh HTML plots into flask


code:
c=np.arange(10).reshape(5,2)
a, b = c[:,0], c[:,1]
a
c.flatten()

rawDescription: Numpy - Stacked memory view of two 1D arrays


code:
from itertools import groupby
from operator import itemgetter
d = {'usage': [0, 1, 1, 2, 1, 4, 7], 'power': [2, 2, 3, 6, 3, 3, 2], 'time': [1, 2, 2, 3, 4, 4, 5]}
groups = groupby(zip(d['time'], d['power'], d['usage']), key=itemgetter(0))
lists = zip(*[[k] + map(sum, zip(*g)[1:]) for k, g in groups])
dict(zip(('time', 'power', 'usage'), lists))

rawDescription: How to sum 3 same sized sorted lists based on the identical elements of the first one in Python?

description: Sum 3 same sized sorted lists based on the identical elements of the first one in Python


code: sumif = lambda x, y: sum(map(Counter, data[x]), Counter())[y]

rawDescription: Is there a SUMIF function to sum across identifiers in a dictionary in Python?


code:
for y in range(1, 9):
    for x in range(4):
        base = 20 if y % 2 == 0 else 10
        canvas.drawRect(base + (x * 20), y * 10, 10, 10)

rawDescription: Graphics window that creates a checkerboard with 64 squares,python


rawDescription: Interleave two numpy arrays based on element distances (python)


code: ['comment', '/* foo bar*/']

rawDescription: Pyparsing: How to insert new elements to a ParseResult


rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


code:
from collections import Counter
from itertools import chain
def sortPairList2(data):
    tally = Counter(chain(*map(set, data)))
    data.sort(key=lambda x: sorted(tally[i] for i in x))

rawDescription: Sorting a list pairs by frequency of the pair elements


code:
class ADT(object):
    def __init__(self, count):
        # Count could be very large. Or maybe you want to perform a function
        # on each value before passing it to adt, e.g.,
        # self.adt = (expensive_func(x) for x in xrange(count))
        self.adt = xrange(count)
        self.adt_as_list = list(self.adt)
        self.adt_as_iter = iter(self.adt)

    @property
    def adt_as_gen(self):
        for x in self.adt:
            y = yield
            yield x + y

rawDescription: access wrapped value, return object, iterator or yield?

description: Access wrapped value, return object, iterator or yield


rawDescription: iPython Pandas: how to convert a cell with multiple values to multiple row?

description: IPython Pandas: how to convert a cell with multiple values to multiple row


code: rdd = sc.binaryFiles(outdir)

rawDescription: Spark reading python3 pickle as input

description: Spark reading python3 pickle as input


code:
def do_paging(pageable_list, start, end):
    return pageable_list[start:end]

pageable_list = do_paging(pageable_list, start, end)

rawDescription: Why can't I change a list in a method?

description: Why can't I change a list in a method


code:
def splitnonalpha(s):
   pos = 1
   while pos < len(s) and s[pos].isalpha():
      pos+=1
   return (s[:pos], s[pos:])

rawDescription: Python - How to split a string by non alpha characters


code:
url_match('', 'test')
url_match('', 'te')
url_match('this is a ', 'test')

rawDescription: how to test for a regex match

description: Test for a regex match


code:
blocks = map(lambda x : np.split(x, a.shape[1]/size, 1), # Split the columns
                        np.split(a, a.shape[0]/size, 0)) # Split the rows

rawDescription: Indexes of fixed size sub-matrices of numpy array


code:
for a in ax.reshape(-1):
    a.plot(...)

rawDescription: Stuffing a pandas DataFrame.plot into a matplotlib subplot


code:
with open("out.txt", "w") as outfile:
    for id, td in get_time_deltas(INFILE):
         outfile.write("Msg %s took %f seconds\n", (id, td))

rawDescription: How do I create a list of timedeltas in python?

description: Create a list of timedeltas in python


code:
rules = [
    Rule(LinkExtractor(allow=r"/news/world-.*"),
         callback='parse_item', follow=True)
]

rawDescription: scrapy rules generating single link

description: Scrapy rules generating single link


rawDescription: Python - Pygame bullet movements

description: Python - Pygame bullet movements


code: fig, ax = plt.subplots(5, sharex=True, squeeze=True)

rawDescription: Remove first and last ticks label of each y-axis subplot


code:
import itertools

results = []
for x in itertools.product(range(3), repeat=12):
    if myfilter(x):
        results.append(x)

rawDescription: Recursive generation + filtering. Better non-recursive?


code:
caps = webdriver.DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 (KHTML, like Gecko) Chrome/15.0.87"

self.driver = webdriver.PhantomJS(desired_capabilities=caps)
self.driver.maximize_window()

rawDescription: Amazon web scraping

description: Amazon web scraping


code:
class Page(webapp.RequestHandler):
    def getLanguage(self):
        try:
            language = self.request.cookies['django_language']
            self.locate = language
            logging.info( "Get Language as %s" % self.locate )
        except:
            from django.conf import settings
            self.locate = settings.LANGUAGE_CODE
            logging.info( "Set Language as %s" % self.locate )
        translation.activate( self.locate )
    def get(self):
        self.getLanguage()
        #...

rawDescription: how to make site show different language(chinese and english) on google-app-engine

description: Make site show different language(chinese and english) on google-app-engine


rawDescription: how to flatten a 2D list to 1D without using numpy?

description: Flatten a 2D list to 1D without using numpy


code:
mylist = [
    value,
    value2,
    value3,
    ]

rawDescription: Is there any way to make code organized if I have a super long list?


code:
type(getattr(x, 'a'))
type(getattr(x, 'b'))
type(getattr(x, 'test'))

rawDescription: Parse Python file to retrieve variables, values, function definitions


code:
try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *
    # Calculator is a class derived from Frame.  Frames, being someone generic,
    # make a nice base class for whatever you what to create.
# Calculator is a class derived from Frame.  Frames, being someone generic,
        # make a nice base class for whatever you what to create.
class Calculator(Frame):

    # Create and return a packed frame.
    def frame(this, side):
        w = Frame(this)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    def keyPressed(self,event):
        #test to see whether enetr is pressed
        if event.keysym == 'Return':
            self.calc()

    # Create and return a button.
    def button(this, root, side, text, command=None):
        w = Button(root, text=text, command=command)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    # Enter a digit.
    need_clr = False
    def digit(self, digit):
        if self.need_clr:
            self.display.set('')
            self.need_clr = False
        self.display.set(self.display.get() + digit)

    # Change sign.
    def sign(self):
        need_clr = False
        cont = self.display.get()
        if len(cont) > 0 and cont[0] == '-':
            self.display.set(cont[1:])
        else:
            self.display.set('-' + cont)

    # Decimal
    def decimal(self):
        self.need_clr = False
        cont = self.display.get()
        lastsp = cont.rfind(' ')
        if lastsp == -1:
            lastsp = 0
        if cont.find('.',lastsp) == -1:
            self.display.set(cont + '.')

    # Push a function button.
    def oper(self, op):
        self.display.set(self.display.get() + ' ' + op + ' ')
        self.need_clr = False

    # Calculate the expressoin and set the result.
    def calc(self):
        try:
            self.display.set(eval(self.display.get()))
            self.need_clr = True
        except:
            showerror('Operation Error', 'Illegal Operation')
            self.display.set('')
            self.need_clr = False

    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'Verdana 12 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple Calculator')

        # The StringVar() object holds the value of the Entry.
        self.display = StringVar()
        e = Entry(self, relief=SUNKEN, textvariable=self.display)
        e.pack(side=TOP, expand=YES, fill=BOTH)

        # This is a nice loop to produce the number buttons.  The Lambda
        # is an anonymous function.
        for key in ("123", "456", "789"):
            keyF = self.frame(TOP)
            for char in key:
                self.button(keyF, LEFT, char,
                            lambda c=char: self.digit(c))

        keyF = self.frame(TOP)
        self.button(keyF, LEFT, '-', self.sign)
        self.button(keyF, LEFT, '0', lambda ch='0': self.digit(ch))
        self.button(keyF, LEFT, '.', self.decimal)

        # The frame is used to hold the operator buttons.
        opsF = self.frame(TOP)
        for char in "+-*/=":
            if char == '=':
                btn = self.button(opsF, LEFT, char, self.calc)
            else:
                btn = self.button(opsF, LEFT, char,
                                  lambda w=self, s=char: w.oper(s))

        # Clear button.
        clearF = self.frame(BOTTOM)
        self.button(clearF, LEFT, 'Clr', lambda w=self.display: w.set(''))
        self.bind_all('<Key>', self.keyPressed)
     # Make a new function for the - sign.  Maybe for . as well.  Add event
     # bindings for digits to call the button functions.

     # This allows the file to be used either as a module or an independent
     # program.
if __name__ == '__main__':
    Calculator().mainloop()

rawDescription: i cant use the equals or the enter key on my keyboard to get an answer for anything

description: I cant use the equals or the enter key on my keyboard to get an answer for anything


rawDescription: Capture screen using Glut and OpenGL with Python


rawDescription: How can I index a line to the next white space available?

description: Index a line to the next white space available


code:
#!/usr/bin/env python

import curses

screen = curses.initscr()

try:
    screen.border(0)

    box1 = curses.newwin(20, 20, 5, 5)
    box1.box()

    screen.refresh()
    box1.refresh()

    screen.getch()

finally:
    curses.endwin()

rawDescription: Why won't my curses box draw?

description: Why won't my curses box draw


code:
with open('input.txt') as f:
    for line in f:
        k, v = map(int, line.split())
        d.setdefault(k, []).append(v)

rawDescription: Simple file to dictionary

description: Simple file to dictionary


code:
def index_2d(myList, v): #Returns tuple containing the position of v in the 2D list
  for i, x in enumerate(myList):
     if v in x:
        return (i, x.index(v))

rawDescription: Swap two numbers in list of tuples (python)


rawDescription: Numpy: Sum clumps of rows

description: Numpy: Sum clumps of rows


code:
y_min, y_max = ax.get_ylim()
ax.set_ylim([y_min,y_max])
x_min, x_max = ax.get_xlim()
ax.set_xlim([x_min,x_max])

plt.plot([x_min,x_max], [y_max,y_max], [-30, -30], 'k-', lw=2)

rawDescription: How to color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure?

description: Color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure


code:
import numpy as np
a=np.zeros((2,5))
a
a.shape

rawDescription: merge sift descriptor matrix, numpyarray

description: Merge sift descriptor matrix, numpyarray


code:
g1 = Game(...)
g1.winner = playerA
g1.loser = playerB

rawDescription: Secondary Join Condition Ignored in Insert SQL Alchemy


rawDescription: pass a list within a list as an argument to subprocess in python

description: Pass a list within a list as an argument to subprocess in python


rawDescription: How to transform a time series pandas dataframe using the index attributes?

description: Transform a time series pandas dataframe using the index attributes


code:
import bisect
import datetime

def generate_last(dts):
    current = dts[0].replace(microsecond=0)
    end = dts[-1]
    pos = 0
    while current < end:
        current += datetime.timedelta(seconds=1)
        pos = bisect.bisect(dts, current, lo=pos)
        yield dts[pos - 1]

rawDescription: Extracting latest datetime from a list "every second"


code:
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

plt.plot([0,2], [2,4])
fig = plt.gcf()
ax = plt.gca()

bb_data = Bbox.from_bounds(0.5, 2.5, 1.0, 0.3)
disp_coords = ax.transData.transform(bb_data)
fig_coords = fig.transFigure.inverted().transform(disp_coords)

fig.add_axes(Bbox(fig_coords))

plt.show()

rawDescription: Convert matplotlib data units to normalized units


code:
count=0
for i in data:
    count+=1

rawDescription: Consuming JSON into django view

description: Consuming JSON into django view


code:
def guess2(text):
    from ast import literal_eval
    tokens = (t.strip() for t in text.split(','))
    for token in tokens:
        try:
            token_value = literal_eval(token)
            token_type = type(token_value)
            yield token_value, token_type
        except ValueError as e:
            yield token, type(token)

rawDescription: python: reading in a table and converting each column to the right data type

description: Python: reading in a table and converting each column to the right data type


rawDescription: python threads - always have x active threads when iterating over n tasks

description: Python threads - always have x active threads when iterating over n tasks


code:
class MyClass(models.Model):
   id = models.BigIntegerField(default = fields.make_id, primary_key=True)

rawDescription: How to replace Django's primary key with a different integer that is unique for that table

description: Replace Django's primary key with a different integer that is unique for that table


code: stop_models = [i for i in tokenized_models if str(i).lower() not in stopset]

rawDescription: Removing stopwords from list using python3


code: aggregateList += recordList

rawDescription: Python Overwriting List Element

description: Python Overwriting List Element


code:
if players[player_turn-1].winner():
    ...

rawDescription: I am having trouble exiting my infinite loop in pygame


rawDescription: regex to extract values within parentheses and the word before parentheses using python

description: Regex to extract values within parentheses and the word before parentheses using python


code:
test = 'the cat sat on the mat'
test.index('cat')  # returns 4

rawDescription: How to find the position of a word inside a string in c# or python?

description: Find the position of a word inside a string in c# or python


code: [format(x,'02d') for x in lis]

rawDescription: Convert range(r) to list of strings of length 2 in python


code: from important import private1 # OK, too

rawDescription: Always include file when importing module in python


rawDescription: Pythonic way to compare two lists and print out the differences


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

fig = plt.figure(figsize=(4, 5))
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.imshow(plt.imread('test.png'), aspect='auto')

# qt specific!
fig.canvas.toolbar.setVisible(False)

plt.show()

rawDescription: How can I display a matplotlib interactive window without any of the controls visible?

description: Display a matplotlib interactive window without any of the controls visible


code:
import unittest
import sys
import os
import glob

__usage__ = '''
%prog      # Searches CWD
%prog DIR
'''

if __name__ == '__main__':
    unit_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
    os.chdir(unit_dir)
    suite = unittest.TestSuite()
    for filename in glob.glob('test_*.py'):
        modname = filename[:-3]
        module = __import__(modname)
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Running unit tests in a test suite (with each test as an individual test script)


rawDescription: Getting 2-d array pattern from user inputs in python


code: Block = numpy.bmat('A11,A12; A21,A22')

rawDescription: Better way to create block matrices out of individual blocks in numpy?


code:
param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
value = urllib.urlencode(param)
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)

rawDescription: Curl request in python

description: Curl request in python


code:
collection = Collection()
collection.profiles = (arg1, arg2, arg3), {'kwarg1':val1, 'kwarg2':val2}

rawDescription: Using a class instance as a class attribute, descriptors, and properties


code:
with open('output.csv', 'wb') as f:
    w = csv.writer(f, delimiter='\t')
    w.writerow([''] + lst)
    for key in keys:
        w.writerow([key] + [dct[item].get(key, '') for item in lst])

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


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

xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()

rawDescription: matplotlib: Set markers for individual points on a line

description: Matplotlib: Set markers for individual points on a line


rawDescription: How to empty a Python list without doing list = []?

description: Empty a Python list without doing list = []


code:
import difflib
a = ["spam", "eggs", "spammy", "eggy"]
b = 'spam'
sorted(a, key=lambda x: difflib.SequenceMatcher(None, x, b).ratio())

rawDescription: How to sort list of strings by best match (difflib ratio)

description: Sort list of strings by best match (difflib ratio)


rawDescription: How do I make one list from multiple columns using Python's Pandas?

description: Make one list from multiple columns using Python's Pandas


code:
import formencode

class HoleSchema(formencode.Schema):
    allow_extra_fields = False
    yardage = formencode.validators.Int(not_empty=True)
    par = formencode.validators.Int(not_empty=True)

class CourseForm(formencode.Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'})
    hole = formencode.ForEach(HoleSchema())

rawDescription: Pylons FormEncode with an array of form elements


rawDescription: Limit sum of entries in numpy array by adjusting negative entries


code:
def button_clicked(self):
    x = 100 # Generate your number here
    self.label.setText("My number: {0}".format(x))

rawDescription: Using simple python script in qt (via QT-designer)


code:
import itertools
def get_range(dictionary, begin, end):
  return dict(itertools.islice(dictionary.iteritems(), begin, end+1))

rawDescription: python: how to get a subset of dict

description: Python: how to get a subset of dict


code:
headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

rawDescription: Skip the headers when editing a csv file using Python


code:
#!/usr/bin/env python

import os
import sys

import distutils.errors
import setuptools

if not hasattr(sys, "hexversion") or sys.hexversion < 0x02040000:
    raise distutils.errors.DistutilsError("Python 2.4 or newer is          required")

if os.name == "posix":
    from setup_posix import get_config
else:  # assume windows
    from setup_windows import get_config

metadata, options = get_config()
metadata['ext_modules'] = [
    setuptools.Extension(sources=['_mysql.c'], **options)]
metadata['long_description'] =    metadata['long_description'].replace(r'\n', '')
setuptools.setup(**metadata)

rawDescription: Does the MySQLdb module in python restarts the MYSQL service on the instalation?


code:
type({}.viewkeys())({})
class MyView(type({}.viewkeys())): pass

rawDescription: Subclassing datatypes that have views in Python2.7 and Python3


code:
a = 1
b = 2
print(a==b)
a = 2
print(a==b)

rawDescription: Why the below command prints nothing

description: Why the below command prints nothing


rawDescription: Mock stdout in Python

description: Mock stdout in Python


code:
def my_func(*args):
    return sum(args)
my_func(1,2,3,4)

rawDescription: How to write a python function that adds all arguments?

description: Write a python function that adds all arguments


code:
if request.method == 'POST':
    for prediction in form.predictions:
        store=db.session.query(Fixture_prediction) \
            .filter(Fixture_prediction.user_id==user_id) \
            .filter(Fixture_prediction.fixture_id==prediction.fixture_id.data)\
            .update({'home_score':prediction.home_score.data\
            ,'away_score':prediction.away_score.data})
    db.session.commit()
    flash('Prediction added')
    return redirect(url_for('predictions'))

rawDescription: How do I correctly submit results from a wtformusing Jinja with a Python /Flask setup

description: Correctly submit results from a wtformusing Jinja with a Python /Flask setup


code:
list1 = ["X", "Y", "Z"]
list2 = [1, 2, 3]
list3 = [list(t) for t in zip(list1, list2)]
list3

rawDescription: How to combine lists? (Python)

description: Combine lists? (Python)


code: df['flag'] = (df.low < df.dailyOpen) & (df.close > df.dailyOpen)

rawDescription: FX Data - analyse intraday data

description: FX Data - analyse intraday data


code: transformed_B = { item[0]: item[1] for item in B}

rawDescription: Replace elements in 2nd column of array with new value from 2nd column of smaller array when 1st column matches


rawDescription: Python - Appending list to list during while loop - Result not as expected


code:
words = [x + " and " + y for x in firstList for y in secondList]
print(*words, sep="\n")

rawDescription: Python Combining strings and printing multiple times


code:
from sqlalchemy.orm import aliased
a_alias = aliased(A)
session.query(
      Association.association_property_1,
      func.abs(A.a_property_special - a_alias.a_property_special)
     ).\
     join(Association.a).\
     join(Association.b).join(a_alias, B.a).\
     filter(a_alias.a_property_special > 3.0)

rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


code:
cursor.execute("SELECT foo_type, SUM(amount) "
               "FROM items, foos "
               "WHERE items.foo_type = foos.type "
               "GROUP BY foo_type")
results = list(cursor)

# results is a list of tuples: [(type1, sum1), (type2, sum2), ...]

rawDescription: python sqlite3 sum each type

description: Python sqlite3 sum each type


code: data_out = p.communicate(input_str)[0]

rawDescription: Dynamic string operations in Python

description: Dynamic string operations in Python


code:
class MetaA(type):
    def __getitem__(cls,val):
        return "It works"

class A(object):
    __metaclass__=MetaA
    pass

print(A[0])
# It works

rawDescription: How to write a static python getitem method?

description: Write a static python getitem method


code:
def callback_maker(waves):
    def callback(in_data, frame_count, time_info, status_flags):
        # do stuff (waves is in scope)
        signal = waves.next()
        return (signal, pyaudio.paContinue)
    return callback

rawDescription: (python) Finding the argument of a parent function from a callback


code:
import numpy as np

def get_difference(x,y):
    return sum(ele_x != ele_y for ele_x, ele_y in zip(x,y))

my_list = ['abcde','abcwe','zbfwe']
n = len(my_list)

my_array = np.zeros((n,n))
#
for i, ele_1 in enumerate(my_list):
    for j, ele_2 in enumerate(my_list):
        if j >= i:
            break # Since the matrix is symmetrical we don't need to
                  # calculate everything
        difference = get_difference(ele_1, ele_2)
        my_array[i, j] = difference
        my_array[j, i] = difference

rawDescription: Calculate matrix of pairwise differences for large number of sequences?


code:
def sparseness2(xs):
    nr = np.sqrt(xs.shape[1])
    a = np.sum(np.abs(xs), axis=1)
    b = np.sqrt(np.sum(np.square(xs), axis=1))
    sparseness = (nr - a/b) / (nr - 1)
    return sparseness

res_arr = sparseness2(express_df.values)
res2 = pd.Series(res_arr, index=express_df.index)

rawDescription: Fast alternative to run a numpy based function over all the rows in Pandas DataFrame


code:
import socket
import subprocess
from select import select

try:
    import winreg
except ImportError:
    import _winreg as winreg

try:
    VLC_PATH = winreg.QueryValueEx(
        winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
            r'SOFTWARE\VideoLAN\VLC'), '')[0]
except WindowsError:
    exit("Error: VLC not found.")

def send_command(sock, cmd, get_result=False):
    try:
        cmd = (cmd + '\n').encode('ascii')
    except AttributeError:
        cmd += b'\n'
    sent = total = sock.send(cmd)
    while total < len(cmd):
        sent = sock.send(cmd[total:])
        if sent == 0:
            raise socket.error('Socket connection broken.')
        total += sent
    if get_result:
        return receive_result(sock)

def receive_result(sock):
    data = bytearray()
    sock.setblocking(0)
    while select([sock], [], [], 1.0)[0]:
        chunk = sock.recv(1024)
        if chunk == b'':
            raise socket.error('Socket connection broken.')
        data.extend(chunk)
    sock.setblocking(1)
    return data.decode('utf-8')

def main(address, port):
    import time
    rc_host = '{0}:{1}'.format(address, port)
    vlc = subprocess.Popen([VLC_PATH, '-I', 'rc', '--rc-host', rc_host,
                            '--rc-quiet'])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((address, port))
        help_msg = send_command(sock, 'help', True)
        print(help_msg)
        send_command(sock, 'quit')
    except socket.error as e:
        exit("Error: " + e.args[0])
    finally:
        sock.close()
        time.sleep(0.5)
        if vlc.poll() is None:
            vlc.terminate()

if __name__ == '__main__':
    main('localhost', 12345)

rawDescription: WIndows: subprocess making new console window, losing stdin/out


rawDescription: Numpy bincount() with floats

description: Numpy bincount() with floats


code:
check([2,3])
check([4, float('inf')])

rawDescription: Check if dictionary key is filled with list of 2 numbers


code:
for v in sorted(lst):
    print("%.4f: %.4f" % (v, mapper.to_rgba(v)[0]) )

rawDescription: Map values to colors in matplotlib

description: Map values to colors in matplotlib


rawDescription: Windows path in python

description: Windows path in python


code:
A = np.random.rand(2,3,4,5,7,8,4)
B = np.random.rand(2,3)
shp = A.shape
direct_out = A*B[:,:,None,None,None,None,None]
np.allclose(out,direct_out) # Verify

rawDescription: Elementwise multiplication of tensors of unknown dimension


code:
# you'll have to set a few other options to get good estimates,
# in particular n_iterations, but this should get you going
lr = SGDClassifier(loss="log")

rawDescription: Batch gradient descent with scikit learn (sklearn)


rawDescription: Inserting strings into lists in Python (v. 3.4.2)


code:
imgFile = open(fileName, "rb")
sys.stdout.write("Content-type: image/jpeg\r\n")
sys.stdout.write("\r\n")
sys.stdout.write(imgFile.read())
imgFile.close()

rawDescription: Problems outputting an image over http using Python


code:
import urllib.request

class NoRedirection(urllib.request.HTTPErrorProcessor):
    def http_response(self, request, response):
        return response
    https_response = http_response

opener = urllib.request.build_opener(NoRedirection)

req = urllib.request.Request("http://www.google.com", method="HEAD")
resp = opener.open(req)

rawDescription: Why am I able to read a HEAD http request in python 3 urllib.request?


rawDescription: Overlapping regex

description: Overlapping regex


rawDescription: Thresholded pixel indices of a NumPy array


code: myDict = {'value': 1}

rawDescription: When to use __getattr__

description: When to use __getattr__


code:
class Engine(object):

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

rawDescription: Learn Python the Hard Way - exercise 43 - Classes: passing one class instance to another class when instantiating


rawDescription: Do requests sessions end when the program is killed?


code:
## ...
## ...
## All the plots are created above...

fig.tight_layout()  # You call fig.tight_layout BEFORE creating the colorbar

import matplotlib
# You input the POSITION AND DIMENSIONS RELATIVE TO THE AXES
x0, y0, width, height = [0.6, 0.9, 0.2, 0.04]

# and transform them after to get the ABSOLUTE POSITION AND DIMENSIONS
Bbox = matplotlib.transforms.Bbox.from_bounds(x0, y0, width, height)
trans = ax18.transAxes + fig.transFigure.inverted()
l, b, w, h = matplotlib.transforms.TransformedBbox(Bbox, trans).bounds

# Now just create the axes and the colorbar
cbaxes = fig.add_axes([l, b, w, h])
cbar = plt.colorbar(sca, cax=cbaxes, ticks=[0, 1], orientation='horizontal')
cbar.ax.tick_params(labelsize=9)

out_png = 'colorbar.png'
plt.savefig(out_png, dpi=150)
plt.close()

rawDescription: Can't fix position of colorbar in image with multiple subplots


code:
from string import punctuation

junk = {ord(ch):"" for ch in punctuation + "\n"}

arr = np.array(list(stg.translate(junk)))

rawDescription: Convert a long string into a matrix, cleaning it


code:
if random in range(0, 16):
    winning = 0

rawDescription: How do I search a range for a single integer?

description: Search a range for a single integer


code:
fname = "feed.txt"
fname = open('feed.txt', 'r')

rawDescription: Counting lines, words, and characters within a text file using Python


code:
for line in f1:
    for i in range(len(KEYWORDS)):
        if line.startswith("#define") and KEYWORDS[i] in line:
            line = "#define " + KEYWORDS[i] + " " + str(VALS[i])+"\n"
    f2.write(line)

rawDescription: Python script to replace #define values in C file


code: storage_ii =  birdofprey.storage_i + storage_ii

rawDescription: Python Global Variable: sharing between function class then function


code:
data['Diff'] = data['Customer ID'].map(diff)
data

rawDescription: Adding first date instances to a new column in pandas dataframe


code: g.groupby(level='c2', as_index=False).apply(lambda x: x.loc['a'] - x.loc['b'])

rawDescription: how to perform calculations across specific rows and columns of a crosstabulation in pandas?

description: Perform calculations across specific rows and columns of a crosstabulation in pandas


code: import Tkinter as tk

rawDescription: Tkinter adding line number to text widget


code:
select_formula()
select_formula()

rawDescription: Python: Raw Input and if statements

description: Python: Raw Input and if statements


code:
import numpy as np
import re

try:
    # Python2
    import string
    table = string.maketrans('()','  ')
except AttributeError:
    # Python3
    table = bytes.maketrans(b'()',b'  ')

with open('data', 'rb') as f:
    lines = (line.translate(table) for line in f)
    arr = np.genfromtxt(lines)
print(arr)

rawDescription: Python numpy.genfromtxt

description: Python numpy.genfromtxt


code:
import sys
from PyQt4.QtGui import *

class Ui(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        graphicsView = QGraphicsView()
        graphicsView.setStyleSheet("border: 0px")

        grid = QGridLayout()
        grid.addWidget(graphicsView)

        self.setLayout(grid)

app = QApplication(sys.argv)
ui = Ui()
ui.show()
sys.exit(app.exec_())

rawDescription: Unable to fully remove border of PyQt QGraphicsView


code:
cp_d1 = dict1.copy()
cp_d2 = dict2.copy()

for k, v in dict1.iteritems():
    if k in dict2:
        if dict2[k][1] > v[1]:
            del cp_d1[k]
        else:
            del cp_d2[k]
cp_d1.update(cp_d2)

print(cp_d1)
{1: ['out', 2], 2: ['out', 1], 3: ['in', 1]}

rawDescription: Python Merge 2 or more Dicts using a value to handle duplicate keys


code:
class Listener(object):
    def __init__(self,
                 rcon_or_url=settings.EVENTS_PUBSUB_URL,
                 channels=None,
                 buffer_key=settings.EVENTS_BUFFER_KEY,
                 last_event_id=None):
        if isinstance(rcon_or_url, redis.StrictRedis):
            self.rcon = rcon_or_url
        elif isinstance(rcon_or_url, basestring):
            self.rcon = redis.StrictRedis(**utils.parse_redis_url(rcon_or_url))
        if channels is None:
            channels = [settings.EVENTS_PUBSUB_CHANNEL]
        self.channels = channels
        self.buffer_key = buffer_key
        self.last_event_id = last_event_id
        self.pubsub = self.rcon.pubsub()
        self.pubsub.subscribe(channels)

        # Send a superfluous message down the pubsub to flush out stale
        # connections.
        for channel in self.channels:
            # Use buffer_key=None since these pings never need to be remembered
            # and replayed.
            sender = Sender(self.rcon, channel, None)
            sender.publish('_flush', tags=['hidden'])

    def __iter__(self):
        # If we've been initted with a buffer key, then get all the events off
        # that and spew them out before blocking on the pubsub.
        if self.buffer_key:
            buffered_events = self.rcon.lrange(self.buffer_key, 0, -1)

            # check whether msg with last_event_id is still in buffer.  If so,
            # trim buffered_events to have only newer messages.
            if self.last_event_id:
                # Note that we're looping through most recent messages first,
                # here
                counter = 0
                for msg in buffered_events:
                    if (json.loads(msg)['id'] == self.last_event_id):
                        break
                    counter += 1
                buffered_events = buffered_events[:counter]

            for msg in reversed(list(buffered_events)):
                # Stream out oldest messages first
                yield to_sse({'data': msg})

        for msg in self.pubsub.listen():
            if msg['type'] == 'message':
                yield to_sse(msg)

    def close(self):
        self.pubsub.close()
        self.rcon.connection_pool.disconnect()

class SSEResponse(HttpResponse):
    def __init__(self, rcon_or_url, channels, buffer_key=None,
                 last_event_id=None, *args, **kwargs):
        self.listener = Listener(rcon_or_url, channels, buffer_key,
                                 last_event_id)
        super(SSEResponse, self).__init__(self.listener,
                                          mimetype='text/event-stream',
                                          *args, **kwargs)

    def close(self):
        """
        This will be called by the WSGI server at the end of the request, even
        if the client disconnects midstream.  Unless you're using Django's
        runserver, in which case you should expect to see Redis connections
        build up until http://bugs.python.org/issue16220 is fixed.
        """
        self.listener.close()

def to_sse(msg):
    """
    Given a Redis pubsub message that was published by a Sender (ie, has a JSON
    body with time, message, title, tags, and id), return a properly-formatted
    SSE string.
    """
    data = json.loads(msg['data'])

    # According to the SSE spec, lines beginning with a colon should be
    # ignored.  We can use that as a way to force zombie listeners to try
    # pushing something down the socket and clean up their redis connections
    # when they get an error.
    # See http://dev.w3.org/html5/eventsource/#event-stream-interpretation
    if data['message'] == '_flush':
        return ":\n"  # Administering colonic!

    if 'id' in data:
        out = "id: " + data['id'] + '\n'
    else:
        out = ''
    if 'name' in data:
        out += 'name: ' + data['name'] + '\n'

    payload = json.dumps({
        'time': data['time'],
        'message': data['message'],
        'tags': data['tags'],
        'title': data['title'],
    })
    out += 'data: ' + payload + '\n\n'
    return out

rawDescription: Django: Cleaning up redis connection after client disconnects from stream


rawDescription: JSON: Concatenate 2 string values in value


code:
OUTPUT
2 , 0

rawDescription: Quiver vector from high value toward low value


code:
all(df == df1.combine_first(df))
True

rawDescription: a way to check if data frame contains a smaller data frame

description: A way to check if data frame contains a smaller data frame


code:
from sklearn.feature_extraction.text import CountVectorizer
def mytokenizer(x):
    return [y for y in x.split() if len(y) > 2]

# Full document-term matrix
cv = CountVectorizer(tokenizer=mytokenizer)
X = cv.fit_transform(preproc)
X
# <1181x3289 sparse matrix of type '<type 'numpy.int64'>'
#   with 8980 stored elements in Compressed Sparse Column format>

# Sparse terms removed
cv2 = CountVectorizer(tokenizer=mytokenizer, min_df=0.005)
X2 = cv2.fit_transform(preproc)
X2
# <1181x309 sparse matrix of type '<type 'numpy.int64'>'
#   with 4669 stored elements in Compressed Sparse Column format>

rawDescription: Exactly replicating R text preprocessing in python


code:
def fn1(pts , condition):
    return [ filter( lambda m: condition(m), pts),  filter( lambda m: not condition(m), pts)  ]

rawDescription: Split data into sub cubes in numpy

description: Split data into sub cubes in numpy


code: np.repeat(a[:,np.newaxis], 5, 1)

rawDescription: Dot product between a matrix and a 1d-array in numpy


code:
import itertools as IT

def count_regular():
     if not hasattr(count_regular,"c"):
         count_regular.c = -1
     count_regular.c +=1
     return count_regular.c

def counter_gen():
    c = 0
    while True:
        yield c
        c += 1

def using_count_regular(N):
    return [count_regular() for i in range(N)]

def using_counter_gen(N):
    counter = counter_gen()
    return [next(counter) for i in range(N)]

def using_itertools(N):
    count = IT.count()
    return [next(count) for i in range(N)]

rawDescription: python performance- function vs generator functions

description: Python performance- function vs generator functions


code:
"some5string".split(5) # wont work it needs a string
"some5string".split("5") # will work

rawDescription: Python expected a character buffer object


rawDescription: How to create a new nested list from a function and an existing nested list in python?

description: Create a new nested list from a function and an existing nested list in python


code:
class SettingsForm(forms.ModelForm):
    receive_newsletter = forms.BooleanField()

    class Meta:
        model = Settings

rawDescription: How to insert a checkbox in a django form

description: Insert a checkbox in a django form


code:
import sys, os
standardlib = os.listdir(sys.path[n])

rawDescription: python how to use imp.find_module or alternative

description: Python how to use imp.find_module or alternative


code: [x == y for (x, y) in zip("TICK", "TOCK")].count(True)

rawDescription: Comparing Strings

description: Comparing Strings


code:
r = range(n)
it = iter(r)
for i in it:
    foo(i)

rawDescription: Can you jump to the nth iteration in a loop?

description: Jump to the nth iteration in a loop


rawDescription: Python: how to print exponential equations in matplotlib?


rawDescription: Call a function defined in another function


rawDescription: Seeing if values in a list are of equal value ~Python


code:
first_names = []
for n in names:
    first_names.append(n.split()[0])

rawDescription: Best way to split strings

description: Split strings


code:
import ctypes

class elements(ctypes.Structure):
    _fields_ = [("elementA", ctypes.c_char * 48),
                ("elementB", ctypes.c_char * 12 * 4)]

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code: super(Palette, self).__init__(*args)

rawDescription: How can a class that inherits from list and uses keyword arguments be made to work in both Python 2 and Python 3?


code:
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: How can I rearange a list items into paired tuple/list in python?

description: Rearange a list items into paired tuple/list in python


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.label import Label

from kivy.lang import Builder

from functools import partial

kv = '''
<CentralWidget>:
    pos_hint: {'center_y': .5}
    size_hint: None, None
    canvas:
        Color:
            rgb: 1, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

<SideWidget>:
    pos_hint: {'center_y': .5}
    size_hint: None, 1
    canvas.before:
        Color:
            rgb: 0, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size
'''

Builder.load_string(kv)

class CentralWidget(Widget):
    pass

class SideWidget(Label):
    pass

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        w1 = SideWidget(text="............................")
        w2 = CentralWidget()
        w3 = SideWidget(text="............................")

        self.add_widget(w1)
        self.add_widget(w2)
        self.add_widget(w3)

    def on_size(self, *args):
        # self.size - size of parent widget
        # self.children - children of widget
        # self.children[0].texture_size - sife of content of selectend children widget
        # self.children[0].size - size of selected children widget to set
        if((self.size[0]-500)/2 > self.children[0].texture_size[0]):
            self.children[0].size = ((self.size[0]-500)/2, 0)
            self.children[1].size = (500, 500)
            self.children[2].size = ((self.size[0]-500)/2, 0)
        else:
            self.children[1].size = (self.size[0]-2*self.children[0].texture_size[0], self.size[0]-2*self.children[0].texture_size[0])

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: How do I set minimum allowable width/height for widget/layout in Kivy?

description: Set minimum allowable width/height for widget/layout in Kivy


rawDescription: Get the items not repeated in a list

description: Get the items not repeated in a list


code:
class spam(object):
    eggs = []

x = spam()
x.eggs.add(...)

rawDescription: Pythonic way to "flatten" object hierarchy to nested dicts?


rawDescription: Switching row header and column header in python


rawDescription: setData is very slow

description: SetData is very slow


code: global_list[0] is global_list[1]

rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code: [setattr(inst, 'some_setting', True) for inst in list_of_instances]

rawDescription: Setting attributes on object instances in Python via map builtin


code:
lcd = pd.DataFrame({'issue_date': pd.date_range('2015-09-01', periods=4, freq='Q')})
lcd.issue_date.apply(lambda x: x.strftime('%m%Y'))

rawDescription: Python Parsing Month, year from datetime64[ns]


code: curr[i]=max(next[n]+e for n in neigh(i,len(next)))

rawDescription: Finding the Maximum Route in a given input


code:
def get_flags_opt(self):
    return ['-xhost -openmp -fp-model strict']

rawDescription: Disabling fp-model strict when using ifort with f2py


code: imat = mat

rawDescription: Python Array Cleanup Issues

description: Python Array Cleanup Issues


code:
space_buttons = [] #list of space buttons

...

for txt,val in space:
    space_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=v, command=ShowChoice,value=val)
    space_button.grid(row=8, column=val-1)
    #add it to the list of space buttons
    space_buttons.append(space_button)

rawDescription: disable buttons in Python and Tk

description: Disable buttons in Python and Tk


code: value = request.GET.get('ugq_no')

rawDescription: How to get request.environ values in python?

description: Get request.environ values in python


code:
def invert(f, x, y, z):
    G = np.vstack([np.ones_like(x), x, y, z]).T
    m, _, _, _ = np.linalg.lstsq(G, f)

    d, e, f, g = m
    a = np.sqrt(d)
    b = np.sqrt(e)
    c = np.arctan2(g, f) # Note that `c` will be in radians, not degrees
    return a, b, c

rawDescription: Solving non-linear equations in python

description: Solving non-linear equations in python


code:
def line_exp(x, a, b, c, d, e):
    return a*x + b + c*np.exp((x-d)/e)

e0 = .1, 20., .01, 1000., 2000.
e, ecov = curve_fit(line_exp, x, y, e0)

rawDescription: Fit a curve for data made up of two distinct regimes


code:
self
test1

rawDescription: Python Introspection: How to get varnames of class methods?


code:
urlpatterns = patterns('',
    url(r'^wiki/Sacramentum_\(oath\)/', my_view),
)

rawDescription: Parenthesis URL dispatcher Django?

description: Parenthesis URL dispatcher Django


code:
path = os.path.dirname(surShaderTex)
f = surShaderTex.split("/")[-1]
tifName = os.path.splitext(f)[0] + ".tif"
texName = os.path.splitext(f)[0] + ".tex"
tifPath = os.path.join(path, tifName)
texPath = os.path.join(path, texName)

rawDescription: Unable to display all the information except for first selection


code:
knownPairs = []

#Get a new list of Ids/Product

response = ''
for i in ListOfIds:
    for p in ListOfProducts:
        pair = (i, p)
        if not pair in knownPairs:
            response += func1(i, p, target, Status)
        else:
            knownPairs += pair

rawDescription: how to call a function only for different combination of id and product

description: Call a function only for different combination of id and product


code:
def main(request):
    users = PUsers.objects.all()
    return render(request, 'main.html', {'users': users})

rawDescription: django-python create Multidimensional Array in views.py

description: Django-python create Multidimensional Array in views.py


code:
class Sparse(dict):
    pass

rawDescription: The most efficient way to store large symmetric sparse matrices in python


code:
Regex
import re
pattern = '(^|-)NS4.+NS1(-|$)'
print(re.search(pattern, strA) is not None)
print(re.search(pattern, strB) is not None)

# False
# True

rawDescription: How to specify the regex string in python

description: Specify the regex string in python


code:
class User(models.Model):
    name = models.CharField(max_length=40)
    videos_watched = models.ManyToManyField('Video', through='WatchedVideo')

class Video(models.Model):
    name = models.CharField(max_length=40)
    time  = models.IntegerField()

class WatchedVideo(models.Model):
    user = models.ForeignKey(User)
    video = models.ForeignKey(Video)
    watched_on = models.DateTimeField(auto_now_add=True)

rawDescription: One to Many relationship of models in Django


code:
new_filename = filename_noext
for key in file_names.keys():
  new_filename = new_filename.replace(key, file_names[key])

rawDescription: How to rename a specific word in a file name using python

description: Rename a specific word in a file name using python


rawDescription: Ignore strings which do not completely match regex?


code: int(age.days / 365.24)

rawDescription: How can I compare dates using Python?

description: Compare dates using Python


rawDescription: django return foreign key object from queryset?

description: Django return foreign key object from queryset


code:
import time

minute = 60
next_time = time.time()
while True:
    doSomeWork()
    next_time += minute
    sleep_time = next_time - time.time()
    if sleep_time > 0:
        time.sleep(sleep_time)

rawDescription: python periodic looping idiom?

description: Python periodic looping idiom


code: something and something

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
def foo(some,arguments):
    pass #do something here

rawDescription: What is the meaning of the phrase "registering a callback" with Python APIs?


code:
class Foo(object):
    from methods import *

rawDescription: How to share behavior b/w classes in python?

description: Share behavior b/w classes in python


rawDescription: Pandas - make a column dtype object or Factor


code: ','.join([str(instance.public_dns_name) for instance in instances])

rawDescription: Joining a list of object values into a string using list comprehensions in python 2.7


code:
x, y = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 10, 3))
x
y

rawDescription: NumPy map calculation depending on the indices


rawDescription: Recursive function that prints the binary representation of the integer


code:
import csv
import re

fields = ('productId', 'userId', 'profileName', 'helpfulness', 'rating', 'time', 'summary', 'text')

with open("largefile.txt", "r") as myfile, open(outnamename,'w', newline='') as fw:
    writer = csv.DictWriter(fw, fields, delimiter='|')

    record = {}
    for line in myfile:
        if not line.strip() and record:
            # empty line is the end of a record
            writer.writerow(record)
            record = {}
            continue

        field, value = line.split(': ', 1)
        record[field.partition('/')[-1].strip()] = value.strip()

    if record:
        # handle last record
        writer.writerow(record)

rawDescription: Parsing large (9GB) file using python

description: Parsing large (9GB) file using python


code:
soup.find_all("td", attrs={'headers':'rp9'})[0].text
soup.find_all("td", attrs={'headers':'rp9'})[1].text

rawDescription: Why does bs4 return tags and then an empty list to this find_all() method?


code:
n0=n+1
for n1 in range(n0+1,p):
    n0 = (n0 * n1)%p
return p-pow(n0,(p-2),p)

rawDescription: multiplication of all numbers (between 2 numbers) python

description: Multiplication of all numbers (between 2 numbers) python


code: MyClass.newer_field = "this is the newest field"

rawDescription: Does django (python) reuse object?

description: Does django (python) reuse object


rawDescription: Select multiple groups from pandas groupby object


code:
my_list = [(1, 2), (4, 7), (6, 0)]
result = [x for t in my_list for x in t]

rawDescription: Expanding a list of tuples

description: Expanding a list of tuples


code:
dict1 = {(k1, k2): v for k1, k2, v in list1}
dict2 = {(k1, k2): v for k1, k2, v in list2}

rawDescription: Best way of adding two lists?

description: Best way of adding two lists


rawDescription: pandas dataframe concat with 'NA'

description: Pandas dataframe concat with 'NA'


code:
for fooddict in list1:
    print(fooddict)

rawDescription: Accesing dictionaries that are in a list


rawDescription: How to "simulate" numpy.delete during processing


rawDescription: Why doesn't the Python 2D array index order matter when used with colon ( : )


code: strs.replace(' Bedroom', '')

rawDescription: Cut of middle word from a string python

description: Cut of middle word from a string python


code:
lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
lst.sort(key=lambda x: x[0])  #Only necessary if your list isn't sorted already.
new_lst = [list(v) for k,v in itertools.groupby(lst,key=lambda x:x[0])]

rawDescription: Python tuple list

description: Python tuple list


code:
print(requests.get("https://httpbin.org/cookies/set?foo=bar").json())
print(requests.get("https://httpbin.org/cookies").json())
s = requests.Session()
print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
print(s.get("https://httpbin.org/cookies").json())
s = requests.Session()
s.cookies.set_policy(BlockAll())
print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
print(requests.get("https://httpbin.org/cookies").json())

rawDescription: How to disable cookie handling with the Python requests library?

description: Disable cookie handling with the Python requests library


code: sample_names_duplicates = set(pd.read_csv(infile, sep="\t", engine="c", usecols=[4], squeeze=True))

rawDescription: Read large csv file with many duplicate values, drop duplicates while reading


code: titles1 = dict([(x["id"], x) for x in list1])

rawDescription: Python compare dictonaries for different values


code:
def kbwrap(event):
    return kbeventhandler(event,flag)
hm.KeyDown = kbwrap

rawDescription: peculiar error on ntpath.py

description: Peculiar error on ntpath.py


code:
import threading

class Foo(object):
    instance_count = 0

def inc_by(n):
    for i in xrange(n):
        Foo.instance_count += 1

threads = [threading.Thread(target=inc_by, args=(100000,)) for thread_nr in xrange(100)]
for thread in threads: thread.start()
for thread in threads: thread.join()

print(Foo.instance_count) # Expected 10M for threadsafe ops, I get around 5M

rawDescription: Is modifying a class variable in python threadsafe?


code:
from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: simple regex trouble

description: Simple regex trouble


rawDescription: Search for a variable in a file and get its value with python


code:
data = bytes.fromhex('01AF23')
s.send(data)

rawDescription: How can I send anything other than strings through Python sock.send()

description: Send anything other than strings through Python sock.send()


rawDescription: loading issue of subpackages in astropy 0.3 in ubuntu 14.04

description: Loading issue of subpackages in astropy 0.3 in ubuntu 14.04


code:
#!/usr/bin/env python3
from string import ascii_lowercase

def abcdearian(s):
    return issorted_recursive([c for c in s.lower() if c in ascii_lowercase])

def issorted_recursive(L):
    return L[0] <= L[1] and issorted_recursive(L[1:]) if len(L) > 1 else True

rawDescription: Python 3.3: Recursive version of a function


rawDescription: Graph with distance and travelling times: find most km's in 24 hours (with constraints)


rawDescription: Pandas: rare data form disrupts normal statistical analysis


code:
def make_cell(val=None):
    x = val
    def closure():
        return x
    return closure.__closure__[0]

rawDescription: How to create new closure cell objects?

description: Create new closure cell objects


code:
# if j is your json string, convert it into a python object
d = json.loads(j)

# then do your modifications as above:
d["request"]["slice"][0]["date"] = "2015-05-23"

# and finally convert back to json:
j = json.dumps(d)

rawDescription: build dynamical JSON/LIST obj in Python

description: Build dynamical JSON/LIST obj in Python


code:
gameOver=Label(root, text='Game over!\nYou scored' + str(number) + ' points!',
                           font=('Arial Black', '26'), bg='red')

rawDescription: Problems with creating label in tkinter

description: Problems with creating label in tkinter


rawDescription: remove dictionaire from list if ALL values are empty string

description: Remove dictionaire from list if ALL values are empty string


code:
import argparse
import sys

class VerifyNoBuild(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print 'No: {n} {v} {o}'.format(n=args, v=values, o=option_string)
        if args.build is not None:
            parser.error(
                '--build should not be used with --from or --interval')
        setattr(args, self.dest, values)

class VerifyOnlyBuild(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print 'Only: {n} {v} {o}'.format(n=args, v=values, o=option_string)
        if getattr(args, 'from') is not None:
            parser.error('--from should not be used with --build')
        if getattr(args, 'interval') is not None:
            parser.error('--interval should not be used with --build')
        setattr(args, self.dest, values)

parser = argparse.ArgumentParser(description='A Tool')
subparsers = parser.add_subparsers(help='sub-command help')

# create the parser for the 'download' command
download_parser = subparsers.add_parser('download', help='download help')

download_parser.add_argument('--interval',
                             type=int, help='interval help',
                             action=VerifyNoBuild)
download_parser.add_argument('--from',
                             type=int, action=VerifyNoBuild)
download_parser.add_argument('--build',
                             type=int, action=VerifyOnlyBuild)

args = parser.parse_args('download --from 1234 --interval 60'.split())
print(args)
# Namespace(build=None, from=1234, interval=60)

args = parser.parse_args('download --build 1432'.split())
print(args)
# Namespace(build=1432, from=None, interval=None)

args = parser.parse_args('download --build 1432 --from 1234'.split())
print(args)
# usage: test.py download [-h] [--interval INTERVAL] [--from FROM] [--build BUILD]
# test.py download: error: --build should not be used with --from or --interval

args = parser.parse_args('download --build 1432 --interval 60'.split())
print(args)
# usage: test.py download [-h] [--interval INTERVAL] [--from FROM] [--build BUILD]
# test.py download: error: --build should not be used with --from or --interval

rawDescription: python argparse subcommand with dependency and conflict

description: Python argparse subcommand with dependency and conflict


code:
import Tkinter as tk
import tkFont

class App:
    def __init__(self):
        root=tk.Tk()
        # create a custom font
        self.customFont = tkFont.Font(family="Helvetica", size=12)

        # create a couple widgets that use that font
        buttonframe = tk.Frame()
        label = tk.Label(root, text="Hello, world", font=self.customFont)
        text = tk.Text(root, width=20, height=2, font=self.customFont)
        buttonframe.pack(side="top", fill="x")
        label.pack()
        text.pack()
        text.insert("end","press +/- buttons to change\nfont size")

        # create buttons to adjust the font
        bigger = tk.Button(root, text="+", command=self.OnBigger)
        smaller = tk.Button(root, text="-", command=self.OnSmaller)
        bigger.pack(in_=buttonframe, side="left")
        smaller.pack(in_=buttonframe, side="left")

        root.mainloop()

    def OnBigger(self):
        '''Make the font 2 points bigger'''
        size = self.customFont['size']
        self.customFont.configure(size=size+2)

    def OnSmaller(self):
        '''Make the font 2 points smaller'''
        size = self.customFont['size']
        self.customFont.configure(size=size-2)

app=App()

rawDescription: How to change a widget's font style without knowing the widget's font family/size?

description: Change a widget's font style without knowing the widget's font family/size


code:
import pandas as pd
df = pd.read_csv("stuff.dat",sep=r"\s+")
df["ranks"] = df.reset_index().groupby("Name")["index"].rank("first")
df2 = df.pivot_table(rows=["Name", "URL", "Email"],
                     cols="ranks",
                     aggfunc=lambda x: x, fill_value='')
df2.columns = [c[0] + str(int(c[1])) for c in df2.columns.get_values()]
df2 = df2.reset_index()

rawDescription: Using Python to Combine CSV Elements From Columns to Rows


code: IPYTHON=1 /path/to/bin/pyspark

rawDescription: How to load IPython shell with PySpark

description: Load IPython shell with PySpark


code:
a = "<div class=\"haha\"><\/div>"
a.replace('\\','')

rawDescription: Clear invalid escape in python?

description: Clear invalid escape in python


code:
mask = ~np.isnan(x)
x = x[mask]
y = y[mask]
mask = ~np.isnan(y)
x = x[mask]
y = y[mask]

rawDescription: Removing nan in array at position from another numpy array


rawDescription: Tkinter Text Tag Config not persisting

description: Tkinter Text Tag Config not persisting


code: df.apply(lambda r: r.Full.lower().replace(r.Partial.lower(), '_' + r.Partial + '_'), axis=1)

rawDescription: Pandas: matching a string in series with string from another series


code: packed_data = chr(len(asciiString) % 8) + packed_data

rawDescription: Huffman encoding: how to write binary data in Python


code:
import ruamel.yaml as yaml

yaml_str = """\
depth:
  - rows: 480
  - cols: 640   # my number of columns
  - dt: f
  - data: x
"""

data3 = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
print(yaml.dump(data3, Dumper=yaml.RoundTripDumper))

rawDescription: sort a YAML block mapping sequence in python

description: Sort a YAML block mapping sequence in python


rawDescription: accessing value of a python @property

description: Accessing value of a python @property


code:
def org_app(x, A, c):
    x = np.atleast_2d(x)
    b = np.zeros(x.shape[0], dtype=np.bool)
    for row in range(x.shape[0]):
        xmc = x[row, :] - c
        b[row] = xmc.dot(A).dot(xmc) <= 1
    return b

def vectorized_app1(x,A,c):
    xc = x-c
    return ((xc.dot(A))*xc).sum(1) <= 1

def vectorized_app2(x,A,c):
    xc = x-c
    return np.einsum('ij,jk,ik->i',xc,A,xc) <= 1

rawDescription: Dot product vectorization - NumPy

description: Dot product vectorization - NumPy


code:
is_foo = np.asarray([ele.type == "foo" for ele in data])
v1 = np.where(~is_foo, 1, 0)
v2 = np.where(~is_foo, 20, 0)

rawDescription: Vector filling array using numpy

description: Vector filling array using numpy


code:
for line in tail('test.log'):
    if line.startswith('error'):
        print('Error:', line)

rawDescription: Get return value from shell command in python


code:
import win32ui
import win32print
import win32con

INCH = 1440

hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (win32print.GetDefaultPrinter ())
hDC.StartDoc ("Test doc")
hDC.StartPage ()
hDC.SetMapMode (win32con.MM_TWIPS)
hDC.DrawText ("TEST", (0, INCH * -1, INCH * 8, INCH * -2), win32con.DT_CENTER)
hDC.EndPage ()
hDC.EndDoc ()

rawDescription: python win32print not printing

description: Python win32print not printing


rawDescription: python addition 2 digit number

description: Python addition 2 digit number


rawDescription: Unpack dictionary that contains a list of dictionaries and insert in columns


code:
class Val(object):
    def __init__(self):
        self.this_val = 123

class ValDesc(object):
    def __init__(self):
        self.cls_lookup = {}

    def __get__(self, obj, objtype=None):
        return self.cls_lookup.setdefault(objtype, Val())

class A(object):
    foo = ValDesc()

class B(A):
    pass
class C(A):
    pass

rawDescription: help with python inheritance

description: Help with python inheritance


code:
dtypes1 = [('point_index',int),('name','S50')]
dtypes
dtypes2=dtypes1 + dtypes[1:]
z=np.zeros(y.shape[0],dtype=dtypes2)

rawDescription: python numpy left join recarray with duplicated key value

description: Python numpy left join recarray with duplicated key value


code:
from scipy import sparse
from bisect import bisect_left

class lil2(sparse.lil_matrix):
    def removecol(self,j):
        if j < 0:
            j += self.shape[1]

        if j < 0 or j >= self.shape[1]:
            raise IndexError('column index out of bounds')

        rows = self.rows
        data = self.data
        for i in xrange(self.shape[0]):
            pos = bisect_left(rows[i], j)
            if pos == len(rows[i]):
                continue
            elif rows[i][pos] == j:
                rows[i].pop(pos)
                data[i].pop(pos)
                if pos == len(rows[i]):
                    continue
            for pos2 in xrange(pos,len(rows[i])):
                rows[i][pos2] -= 1

        self._shape = (self._shape[0],self._shape[1]-1)

rawDescription: How can I remove a column from a sparse matrix efficiently?

description: Remove a column from a sparse matrix efficiently


rawDescription: Listing select option values with Selenium and Python


code:
file = open('D:\\mydirectory\\soggetti.txt','r')
file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pf.close()
file_pg.close()

p_lines = []
g_lines = []
i = 0
with file:
    for line in file:
        i = 0
        c = 0
        while i < len(line):
            carattere = line[i]
            if carattere == "|":
                c = c + 1
                if c == 4:
                    if line[i-1] == "P":
                        p_lines.append(line)
                        break
                    elif line[i-1] == "G":
                        g_lines.append(line)
                        break
            i = i + 1
file.close()

file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pf.writelines(p_lines)
file_pf.close()

file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pg.writelines(g_lines)
file_pg.close()

rawDescription: Python: faster method to read and create file


rawDescription: Construct bipartite graph from columns of python dataframe


code:
"""innerlink.py - print text of e.g. `<div><h3><a>This</a></h3></div>`."""

from html.parser import HTMLParser

class InnerLinkParser(HTMLParser):

    """A parser for HTML with links in h3s in divs."""

    def __init__(self):
        HTMLParser.__init__(self)
        self.stack = []

    def handle_starttag(self, tag, attrs):
        self.stack.append(tag)

    def handle_endtag(self, tag):
        while self.stack:
            item = self.stack.pop()
            if item == tag:
                break
        else:
            raise ValueError("unmatched closing %r tag." % tag)

    def handle_data(self, data):
        if self.stack[-3:] == ["div", "h3", "a"]:
            print(data)

def parse(html):
    """Feed the parser with some HTML."""
    parser = InnerLinkParser()
    parser.feed(html)

rawDescription: How to read inner tags with HTMLParser?

description: Read inner tags with HTMLParser


code:
import csv
with open('some_list_file.txt', 'rb') as list_file:
    reader = csv.reader(some_list_file)
    with open('Testit.txt', 'W+') as output_file:
        for line in reader:
            IDs = [part for part in line if part.startswith('Mon-')]
            if IDs:
                output_file.write(IDs[0] + '\n') # or accept multiple ID values if that's a possibilty

rawDescription: Replacing multiple characters in a string


code: v.set("Internet is online")

rawDescription: Tkinter set new value for labels

description: Tkinter set new value for labels


rawDescription: Multiple Values for a single key in a dictionary


code:
df = pd.melt(df, id_vars="Event", var_name="Which", value_name="Time")
df["Signal"] = df.pop("Which").replace({"Start-Time": 1, "End-Time": -1})
pivoted = df.pivot(columns="Event", index="Time").fillna(0)
pivoted = pivoted.sort_index() # just in case; can't remember if this is guaranteed
df_out = pivoted.cumsum() + (pivoted == -1)

rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
def wrap(to_wrap, wrap_in):
    contents = to_wrap.replace_with(wrap_in)
    wrap_in.append(contents)

rawDescription: Add parent tags with beautiful soup

description: Add parent tags with beautiful soup


code:
class A:
  def __init__(self, l, r):
    self.l = l
    self.r = r
  def __str__(self):
    return "(%s + %s)" %(self.l, self.r)
  def __eq__(self, other):
    th = str(self).replace("(","").replace(")","").replace(" ","")
    ot = str(other).replace("(","").replace(")","").replace(" ","")
    return sorted(th.split('+')) == sorted(ot.split('+'))

rawDescription: Symbolic calculator in Python: how to correctly override __eq__


code:
import gc, pprint
pprint.pprint(gc.get_referrers("string"))

rawDescription: How python object store the reference counter for garbage collection


code:
def EvenlyDistribute(lst, n):
    """Distribute items in lst (tuples of (val, weight)) into n buckets"""
    buckets = [[] for i in range(n)]
    weights = [[0, i] for i in range(n)]
    for item in sorted(lst, key=lambda x: x[1], reverse=True):
        idx = weights[0][1]
        buckets[idx].append(item)
        weights[0][0] += item[1]
        weights = sorted(weights)
    return buckets

rawDescription: How would you evenly distribute a list of sublists that each have a numerical value across three lists?


code:
def find_holes_2d(coords):
    coords = np.asanyarray(coords)

    # determine grid and transform coordinates
    uniq_x, labels_x = np.unique(coords[:,0], return_inverse=True)
    uniq_y, labels_y = np.unique(coords[:,1], return_inverse=True)

    # layout the known grid in an array
    grid = np.zeros([len(uniq_x), len(uniq_y)], bool)
    grid[labels_x, labels_y] = True

    # see which grid points are inside known coordinates
    x_fwd  = np.logical_or.accumulate(grid, axis=0)
    x_bkwd = np.logical_or.accumulate(grid[::-1], axis=0)[::-1]
    y_fwd  = np.logical_or.accumulate(grid, axis=1)
    y_bkwd = np.logical_or.accumulate(grid[:,::-1], axis=1)[:,::-1]

    # select the holes according to the criteria
    holes = ~grid & (x_fwd & x_bkwd | y_fwd & y_bkwd)

    # Transform positions back to original coordinates
    I,J = np.where(holes)
    return np.column_stack([uniq_x[I], uniq_y[J]])

rawDescription: Python: Complete asymmetric grid

description: Python: Complete asymmetric grid


rawDescription: Customizing rolling_apply function in Python pandas


rawDescription: How can you pack an array of 2 chars + 2 null characters with python's struct?

description: Pack an array of 2 chars + 2 null characters with python's struct


code:
db.collection.findOne({"venues.value": { "$lt": 200 } },
    {
        "venues": { "$elemMatch": { "value": { "$lt": 200 } } },
        "_id": 0
    });

rawDescription: python: query mongodb database to find a specific value under a unknown field

description: Python: query mongodb database to find a specific value under a unknown field


code:
class SomeClass(object):
    dct = {}
    nbr = 0
    def method(self, nbr):
        self.dct[nbr]=nbr
        self.dct = self.dct
        self.nbr+=nbr

rawDescription: Modify object via Python multiprocessing.Pool: strange behavior


code:
import random
import wx

########################################################################
class TabPanel(wx.Panel):
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """"""
        wx.Panel.__init__(self, parent=parent)

        colors = ["red", "blue", "gray", "yellow", "green"]
        self.SetBackgroundColour(random.choice(colors))

        btn = wx.Button(self, label="Press Me")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(btn, 0, wx.ALL, 10)
        self.SetSizer(sizer)

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

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Notebook Tutorial",
                          size=(600,400)
                          )
        panel = wx.Panel(self)
        self.tab_num = 3

        self.notebook = wx.Notebook(panel)
        tabOne = TabPanel(self.notebook)
        self.notebook.AddPage(tabOne, "Tab 1")

        tabTwo = TabPanel(self.notebook)
        self.notebook.AddPage(tabTwo, "Tab 2")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5)

        btn = wx.Button(panel, label="Add Page")
        btn.Bind(wx.EVT_BUTTON, self.addPage)
        sizer.Add(btn)

        panel.SetSizer(sizer)
        self.Layout()

        self.Show()

    #----------------------------------------------------------------------
    def addPage(self, event):
        """"""
        new_tab = TabPanel(self.notebook)
        self.notebook.AddPage(new_tab, "Tab %s" % self.tab_num)
        self.tab_num += 1

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

rawDescription: wxPython Notebook Pages

description: WxPython Notebook Pages


code: my_list.sort(key=lambda x: (order.index(x[0]), x[2], x[3]))

rawDescription: Python sort list of lists over multiple levels and with a custom order


code:
def find(*args, **kwargs):
    """Find a book in the collection specified"""

    search_args = [('access_key', api_key),]
    if not is_valid_collection(kwargs['collection']):
        return None
    kwargs.pop('collection')
    for key in kwargs:
        # Only the first keword is honored
        if kwargs[key]:
            search_args.append(('index1', key))
            search_args.append(('value1', kwargs[key]))
            break

    url = urllib.basejoin(api_url, '%s.xml' % 'books')
    data = urllib.urlencode(search_args)
    req = urllib2.urlopen(url, data)
    rdata = []
    chunk = 'xx'
    while chunk:
        chunk = req.read()
        if chunk:
            rdata.append(chunk)
    tree = ElementTree.fromstring(''.join(rdata))
    results = []
    for i, elem in enumerate(tree.getiterator('BookData')):
        results.append(
               {'isbn': elem.get('isbn'),
                'isbn13': elem.get('isbn13'),
                'title': elem.find('Title').text,
                'author': elem.find('AuthorsText').text,
                'publisher': elem.find('PublisherText').text,}
             )
    return results

rawDescription: How to consume XML from RESTful web services using Django / Python?

description: Consume XML from RESTful web services using Django / Python


code:
import bisect
# a helper function to perform binary search
hit_idx = lambda x: bisect.bisect_left( batch.StartTime, x ) - 1

idx = event.DateTime.map( hit_idx )
event[ 'BatchNo' ] = map( batch.BatchNo.get, idx )

rawDescription: Collating timestamped events into date ranges with pandas


code:
def hms_list(amounts):
    return [hms(amount) for amount in amounts]

rawDescription: For loop troubleshooting

description: For loop troubleshooting


code:
LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"
AVAILABLE_COMMANDS = {
    'Left': LEFT,
    'Right': RIGHT,
    'Up': UP,
    'Down': DOWN,
    'Reset': RESET
}

@app.route('/')
def execute():
    return render_template('main.html', commands=AVAILABLE_COMMANDS)

@app.route('/<cmd>')
def command(cmd=None):
    if cmd == RESET:
       camera_command = "X"
       response = "Resetting ..."
    else:
        camera_command = cmd[0].upper()
        response = "Moving {}".format(cmd.capitalize())

    # ser.write(camera_command)
    return response, 200, {'Content-Type': 'text/plain'}

rawDescription: Flask Button run Python without refreshing page?


code:
class class_b(context_mixin):
    def __init__(self):
        self.a = class_a()
    @contextlib.contextmanager
    def context(self):
        with self.a:
            print('class_b enter')
            try:
                yield self
            finally:
                print('class_b exit')

rawDescription: Pythons 'with'-statement: correctly nest/derive classes with __enter__/__exit__


rawDescription: Editing multi-dimensional arrays in Python


code:
import os
os.environ['LSCOLORS'] = 'gxfxcxdxbxegedabagacad'

rawDescription: IPython qtconsole highlighting

description: IPython qtconsole highlighting


code: ' * '.join(['{}^{}'.format(k, v) if v > 1 else k for k, v in counts.most_common()])

rawDescription: Python: Count and rearrange numbers with same value in a list


code:
import argparse
parser = argparse.ArgumentParser(prog='ipush',
        description='Utility to push the last commit and email the color diff')
parser.prog

rawDescription: accessing ArgumentParser variable with environment variable

description: Accessing ArgumentParser variable with environment variable


code:
url(r'^accounts/signup/$',
        userena_views.signup,
        {'signup_form': SignupFormExtra}),

rawDescription: adding extra fields to django-userena forms

description: Adding extra fields to django-userena forms


code:
input = [(0, 'Ok.  I just '), (-1, 'need to write '), (0, 'out a random bunch of text\nand then keep going.  I'), (-1, ' just'), (0, " did an enter to see how that goes and all\nthe rest of it.  I know I need.  Here's a skipped line.\n\nThen there is more and "), (-1, 't'), (0, 'hen there was the thing.')]

top_3 = [filtered_change[1] for filtered_change in sorted(sorted(enumerate(input), key=lambda change: len(change[1][1]), reverse=True)[:3])]

rawDescription: Parsing diff results (list of tuples) with python


code:
from pprint import pprint

from bs4 import BeautifulSoup

data = """

        Class
        Fail
        Error
        Skip
        Success
        Total

            Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2
            1
            9
            0
            219
            229

        Total
        1
        9
        0
        219
        229

"""

soup = BeautifulSoup(data, "html.parser")

headers = [header.get_text(strip=True) for header in soup.find_all("th")]
rows = [dict(zip(headers, [td.get_text(strip=True) for td in row.find_all("td")]))
        for row in soup.find_all("tr")[1:-1]]

pprint(rows)

rawDescription: BeautifulSoup my for loop is printing all the data from the td tag. I would like to exclude the last section of the td tag


code:
template = 'a value: {a}; b value: {b}'
data = {'a': 'Spam', 'b': 'Eggs'}
template.format(**data)

rawDescription: Convert JSON to .ics (Python)

description: Convert JSON to .ics (Python)


code:
for n in itertools.product(l, repeat=i+1):
    ...

rawDescription: Passing arguments in function dynamically in Python 3


rawDescription: Python 2.7 CSV: How to remove duplicate rows based on a value


code:
content = '''

Michael Jordan

Real Madrid

Ping Pong

'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(content)

person = {}

for div in soup.findAll('div', {'class': 'value'}):
    person[div.find('p').attrs['class'][0]] = div.text.strip()

print(person)

rawDescription: BeautifulSoup: Get the class text

description: BeautifulSoup: Get the class text


code:
fmt = ",".join(["%i"] + ["%10.6e"] * my_array.shape[1])
np.savetxt(f, temp, fmt=fmt, delimiter=",")

rawDescription: Formatting a NumPy array

description: Formatting a NumPy array


code: firstG, secondG = f(first), list(f(second))

rawDescription: Different results from yield vs return

description: Different results from yield vs return


code: yield (n,) + tuple(map(next, iterators))

rawDescription: Variable length 'yield'?

description: Variable length 'yield'


code:
# The dict, with the first file
d = { 'id' : counter,
      'file': [ {'name': filename,
                 'uri' : 'http://localhost:8000/uploads/' + filename,
                 'path' : os.path.join(dirname, filename) } ] }

# Then append all files you want to the list found in d['file']
d['file'].append({'name': some_other_filename,
                  'uri': some_other_uri,
                  'path': some_other_path})

rawDescription: Python Dictionary Appending

description: Python Dictionary Appending


code:
y=x[mask]
np.copyto(y,[2,3])

rawDescription: Write to a masked array in numpy

description: Write to a masked array in numpy


code:
cd_x=np.array([k.pt[0] for k in keypoints])
cd_y=np.array([k.pt[1] for k in keypoints])

rawDescription: List of objects to numpy array

description: List of objects to numpy array


code: ','.join(map("'{0}'".format, mylist))

rawDescription: How to convert list into string with quotes in python

description: Convert list into string with quotes in python


code: s = 'it works ' + ''.join(bli)

rawDescription: python concat before

description: Python concat before


code:
{u'b23e5d453643f66b68634d0204884cdf':
     [u'/Volumes/Backup/images_to_test/File_one_copy.png', u'/Volumes/Backup/images_to_test/File_one.png'],
 u'f0b4108172c50f243d9e0132df4703a0':
     [u'/Volumes/Backup/images_to_test/File_with_no_duplicate.png']
}

rawDescription: How to find duplicates in tuples with Python, using sqlite3?

description: Find duplicates in tuples with Python, using sqlite3


code:
def counter():
    r = re.compile('[^0-9]')
    yield from (sum(map(int, r.sub('', x))) for x in self.get_xs())

rawDescription: How to write in more pythonic way?

description: Write in more pythonic way


code:
import numpy as np
from scipy.spatial.distance import cdist

C = B[np.argmin(cdist(A,B),1)]

rawDescription: How to find the closest corresponding vectors between two coordinate matrices?

description: Find the closest corresponding vectors between two coordinate matrices


rawDescription: How to use scikit-learn to predict the rate of change in a site's hit counts

description: Use scikit-learn to predict the rate of change in a site's hit counts


code:
tup = ([1, 2, 3],4,5 ,6)
[id(x) for x in tup]
lis = list(tup)

rawDescription: Time complexity of casting lists to tuples in python and vice versa


code:
def fact (n): # n = 1..whatever
    result = n
    for i in range (2,n):
        result = result * n

def fib(n): # n = 1..whatever
    me = 1
    if n >1:
        grandparent = 1
        parent = 1;
        for i in range(2, n):
            me = parent + grandparent
            grandparent = parent
            parent = me
    return me

rawDescription: The flow of a Recursive Call

description: The flow of a Recursive Call


rawDescription: Django Models - SELECT DISTINCT(foo) FROM table is too slow


code:
import os
import subprocess

line = "perl tilt.pl %s > final-%s.txt" # second `%s`

framespdb = os.listdir("prac_frames")

for frames in framespdb:
    cmd = line % (frames, frames) # second `frames`
    print(cmd)
    subprocess.Popen(cmd, shell=True)

rawDescription: Linux Command for Perl in Python

description: Linux Command for Perl in Python


code: soup.select_one("span > a.link_to_img")

rawDescription: Python BeautifulSoupe4: How to get link from anchor tag without duplicate


code:
import sys

del sys.modules['c']

rawDescription: Is __subclasses__() cached?

description: Is __subclasses__() cached


code:
func = lambda i:spe.jn_zeros(i,mmax)
np.vstack(np.vectorize(func, otypes=[np.ndarray])(np.arange(nmax+1)))

rawDescription: Is there a more pythonic way to write

description: Is there a more pythonic way to write


code:
class Callable(object):
    def __init__(self, name):
        self.name = name
    def __call__(self, greeting):
        return '{}, {}!'.format(greeting, self.name)

Callable('World')('Hello')

rawDescription: Python 'Functions are objects'

description: Python 'Functions are objects'


code: np.std(data, axis=0)

rawDescription: numpy standard deviation stacked arrays

description: Numpy standard deviation stacked arrays


code:
class MusicTag(models.Model):
    tag=models.CharField(max_length=30)

class userItem(models.Model):
    userName=models.CharField(max_length=30)
    tags= models.ManyToManyField(MusicTag)

rawDescription: How to design models.py when I want to store the complex data like this?

description: Design models.py when I want to store the complex data like this


code: large[startrow:startrow + small.shape[0], startcol:startcol + small.shape[1]] = small

rawDescription: Copying a list of lists into part of another one in the most pythonic way


rawDescription: Assign variables to the list elements, without knowing it's length


code:
def _status(invite):
    if invite.is_activated:
        return "Activated"
    if invite.is_alive:
        return "Live"
    return "Expired"

_status.short_description = 'status'
Invite.status = _status # Invite is model class

rawDescription: Django add model methods at runtime

description: Django add model methods at runtime


code:
with open(the_filename, 'w') as f:
    for s in image_links:
        f.write(s + '\n')

rawDescription: Parsing txt file, to web scrape an image from each link on each line, with python


code:
data_list_1 = [(x,y,c) for (x,y,c) in data_list if c=='U1']
data_list_2 = [(x,y,c) for (x,y,c) in data_list if c=='U2']

rawDescription: Python "input data"

description: Python "input data"


code:
from sqlalch import db, Artist, Suggestion
Artist.query.all()
Suggestion.query.all()
Suggestion.query.all()[0].artist

rawDescription: Foreign key model in model's __repr__()

description: Foreign key model in model's __repr__()


code:
def my_decorator(f):
     def wrapper(*args, **kwargs):
         return f(*args, **kwargs)
     wrapper.decorators = [wrapper]
     if hasattr(f, 'decorators'):
         wrapper.decorators.extend[f.decorators]
     return wrapper

rawDescription: Is it possible to use reflection to examine a function's decorators in Python 2.5?


code: foo(*li)

rawDescription: How to transfer all the elements of a list into a function which asks for *args?

description: Transfer all the elements of a list into a function which asks for *args


code: newContent = content[0:loc - 1] # I think the -1 is needed, not sure

rawDescription: Programmatically delete everything before a HTML node?


code:
def reverse(word):
    return "".join(reversed("abc"))

rawDescription: Reverse String Function in Python (Primitive Steps)


code:
words = ['a','la','fresh','shrimp','ban']
sentence = 'They fresh bananas in Mexico, and more these days'
a = [word for word in words if word in sentence.split(' ')]
print(a) #['fresh']

b = any(word in sentence.split(' ') for word in words)
print(b) #True

rawDescription: Best performance method for evaluating presence of substrings within strings in python?


code:
U1 = aliased(User, name="u1")
U2 = aliased(User, name="u2")
q = (session
     .query(
         U1, U2,
         U2.followers.any(User.id == U1.id).label("followed_back"),
     )
     .join(U2, U1.followers)
     # .filter(...)
     # .order_by(...)
     )

for u1, u2, follows in q:
    print(u1, u2, follows)

rawDescription: SQLAlchemy - How do I SELECT x.id IS NOT NULL AS with a join?


code:
first = [['a','b','c'],['d','e','f']]
second = [['a','b','c'],['d','e','f'],[1,2,3],['g','h','i']]
master = set(tuple(i) for i in first)
master.update((tuple(i) for i in second))
list(master)

rawDescription: Python compare list to list of lists to check for duplicates


code:
def replace_empty_dict_with(d, value):
    for k, v in d.iteritems():
        if len(v) == 0:
            d[k] = value
        else:
            replace_empty_dict_with(v, value)

d = {}
w = {}
for node, pid, _ in main_array:
    if pid == -1:
        w[node] = d[node] = {}
    else:
        parent = main_array[pid][0]
        w[node] = w[parent][node] = {}

replace_empty_dict_with(d, -1)
import pprint
pprint.pprint(d)

rawDescription: convert array to json object

description: Convert array to json object


code:
def edit_distance(s1,s2):
    split1 = list(s1)    # Split strings into characters
    split2 = list(s2)
    count = 0            # This variable is local, it is not shared through calls to the function!
    pos = 0              # Same

    if split1[pos] == split2[pos]:   # pos is always 0 here!
        pos += 1                     # pos is incremented anyway, in if but also in else !
    else:
        pos +=1                      # See above
        count += 1                   # count is incremented, now it is 1
        edit_distance(s1, s2)        # recursive call, but with the identical arguments as before! The next function call will do exactly the same as this one, resulting in infinite recursion!

return count    # Wrong indentation here

rawDescription: Finding the edit distance of two strings with recursion


rawDescription: How to normalize percentages in python

description: Normalize percentages in python


rawDescription: clone element with beautifulsoup

description: Clone element with beautifulsoup


code:
def findMiniRow(numlst):
    if not numlst:
        return -1
    x = []
    for lst in numlst:
        x.append(sum(lst))
        m = min(x)
    return [i for i, j in enumerate(x) if j == m]

rawDescription: Returning empty list -1

description: Returning empty list -1


rawDescription: Best way to extract .ico from .exe and paint with PyQt?

description: Extract .ico from .exe and paint with PyQt


rawDescription: ipython: pressing 'esc' key breaks readline

description: Ipython: pressing 'esc' key breaks readline


code:
x is y
id(x)
id(y)

rawDescription: Equal strings auto updating (List object reference)


code:
from menus.base import Modifier
from menus.menu_pool import menu_pool

class MyMode(Modifier):
    """

    """
    def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb):
        if post_cut:
            return nodes

        for node in nodes:
            if node.title == u'Page not clickable':
                node.no_click = True

        return nodes

menu_pool.register_modifier(MyMode)

rawDescription: Make menu item not clickable in Django CMS


code: [instance.ticker for instance in Ticker.query.all()]

rawDescription: How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?

description: A query a set of objects and return a set of object specific attribute in SQLachemy/Elixir


code:
# make adjustment to bottom
top = fig.subplotpars.top
bottom = fig.subplotpars.bottom
newHspace = (fig.subplotpars.hspace
             *(top-bottom)
             /(top-bottom-textHeightFig))
fig.subplots_adjust(bottom=bottom+textHeightFig,
                    hspace=newHspace)

rawDescription: Automatically expand canvas for long lines


code:
self.aliens = []
for i in range(5):
    alien = Alien((i*100)+10, 0)
    self.alien_sprites.add(alien)
    self.aliens.append(alien)

rawDescription: Pygame - Space Invaders Aliens

description: Pygame - Space Invaders Aliens


code:
import pandas as pd
df = pd.DataFrame({'customer_id':range(5), 'A':('a', 'b', 'c', 'd', 'e')})
df
df[df.customer_id.isin((1,3))]

rawDescription: pandas query rows by list

description: Pandas query rows by list


code: outfile.write('ticker: %s current price: %s last trade: %s\n' % (quote['t'], quote['l_cur'], quote['lt']))

rawDescription: Python - Write multiple lists to file

description: Python - Write multiple lists to file


code:
class NestedChatViewSet(
    viewsets.mixins.CreateModelMixin,
    viewsets.mixins.ListModelMixin,
    viewsets.GenericViewSet):

    queryset = Chat.objects.all()
    serializer_class = ChatSerializer
    permission_classes = (IsAuthenticated, IsUserVerified, IsUserSignedPrivacyAgreement, IsUserOfConsent, )

    def get_queryset(self):
        return Chat.objects.filter(consent=self.kwargs['consent_pk']).order_by('-created')

    def get_consent(self, request, pk=None):
        consent = get_object_or_404(Consent, pk=pk)
        self.check_object_permissions(self.request, consent)
        self.consent = consent
        return self.consent

    def create(self, request, *args, **kwargs):
        self.get_consent(request, pk=kwargs['consent_pk'])
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        serializer.save(
            user=self.request.user,
            consent=self.consent
        )

    def list(self, request, *args, **kwargs):
        self.get_consent(request, pk=kwargs['consent_pk'])
        return super().list(request, *args, **kwargs)

rawDescription: Unable to extend Django REST Framework viewset to handle multi-level API


code:
from numpy import array
a = array([True, True, True])
b = array([True, True, False])
a & b
a | b
a ^ b

rawDescription: Python list of booleans comparison gives strange results


rawDescription: python regular expression findall, need to remove inexact matches

description: Python regular expression findall, need to remove inexact matches


code: QApplication.style().drawControl(QStyle.CE_ItemViewItem, option, painter, QTreeView())

rawDescription: PyQt: QStyledItemDelegate in QTableView on Windows Vista/7?


code:
with open(inputfile) as fin, open(outputfile,'w') as fout:
    non_blank_lines = (line for line in fin if line.strip())
    sorted_lines = sorted(non_blank_lines,key=line_to_tuple)
    fout.writelines(sorted_lines)

rawDescription: Sorting data by multiple columns

description: Sorting data by multiple columns


rawDescription: How do I specify which columns to print to a text file using Python?

description: Specify which columns to print to a text file using Python


code:
class Order(BaseModel):
    company = models.ForeignKey(Company)
    products = models.ManyToManyField(Product, through='OrderProduct')

rawDescription: Django, m2m with same model

description: Django, m2m with same model


code:
import asyncio
from contextlib import suppress

async def echo_forever():
    while True:
        print("echo")
        await asyncio.sleep(1)

async def main():
    asyncio.ensure_future(echo_forever())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

    # Let's also cancel all running tasks:
    pending = asyncio.Task.all_tasks()
    for task in pending:
        task.cancel()
        # Now we should await task to execute it's cancellation.
        # Cancelled task raises asyncio.CancelledError that we can suppress:
        with suppress(asyncio.CancelledError):
            loop.run_until_complete(task)

rawDescription: "Fire and forget" python async/await

description: "Fire and forget" python async/await


code:
def ant_coordinates(ant_row, ant_col, orientation):
    color = orig_grid[ant_row][ant_col]
    if color == 'white':
        if orientation == 'East':
            ant_row += 1
        elif orientation == 'South':
            ant_col -= 1
    return ant_row, ant_col, orientation

rawDescription: how to make langton's ant move a step in python

description: Make langton's ant move a step in python


rawDescription: How to add/remove said a curve to/from a plot in Python with Matplotlib

description: Add/remove said a curve to/from a plot in Python with Matplotlib


code:
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    assert(not __debug__)
    return "Hello World"

rawDescription: uWSGI optimize option

description: UWSGI optimize option


rawDescription: Call Outside Function In Python

description: Call Outside Function In Python


code:
new=ET.Element('Data')
new.text='FOUR'
child[1].append(new)
new=ET.Element('Data')
new.text='FIVE'
child[1].append(new)

rawDescription: python elementtree xml append

description: Python elementtree xml append


code:
import csv

w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])

rawDescription: How to escape comma in string Python 2.7 in a .csv file

description: Escape comma in string Python 2.7 in a .csv file


rawDescription: Processing randomly distributed experimental data using ks_2samp in scipy


code:
class Inc(object):
    def __init__(self):
        self.i = 0
        self.t = 0.0
    def __iadd__(self, f):
        self.i += 1
        self.t += f
        return self

rawDescription: defaultdict and tuples

description: Defaultdict and tuples


code:
int_columns = [1, 3, 5]
for row in range(sh.nrows):
    new_row = sh.row_values(row)
    for col in int_columns:
        new_row[col] = int(new_row[col])
    writetab.writerow(new_row)

rawDescription: Convert Float to Integer During xcel to Tab Delimited File Conversion


rawDescription: Calculate conditional means in Pandas

description: Calculate conditional means in Pandas


code:
with open(input[1], 'a') as fileA:
    fileA.write(' '.join(input[2:]))

rawDescription: How do i ignore the space in command line input in python

description: Ignore the space in command line input in python


code: '020 MT VERNON ST NW'

rawDescription: Fastest Way To Round Number Inside List of Strings Python


code: points = [int(p) for p in input().split()]

rawDescription: Accepting an unknown number of variables using input()


code: count = (~np.einsum('ij->i',listScore != [2,0])).sum()

rawDescription: Equivalent of count list function in numpy array


code:
foo, bar = (1, 2)
foo
bar
baz, = (3, )
baz

rawDescription: SQLAlchemy: How is it that a comma determines if a query returns a String or a Tuple?


code:
sql = 'INSERT INTO media_files (%s) VALUES (%%s, %%s, %%s, %%s,   ...)' % ','.join(fieldlist)
cursor.execute(sql, valuelist)

rawDescription: MySQL Dynamic Query Statement in Python

description: MySQL Dynamic Query Statement in Python


code:
@background(schedule=60*5)
def send_html_mail_post(id, template):
    u = User.objects.get(id=id)
    user_email = u.email
    subject = "anything"
    html_content = template.format(arguments)
    from_email, to = from_email, user_email
    text_content = ''
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

rawDescription: how to use django-background-tasks

description: Use django-background-tasks


code:
while True:
    time.sleep(1)

rawDescription: Why is my threading/multiprocessing python script not exiting properly?


rawDescription: django haystack inheritance problems

description: Django haystack inheritance problems