code:
def iter_3d(A,B,C):
    A_2 = np.zeros((A.shape[0], A.shape[1] + 1, A.shape[2]))
    for j in xrange(np.size(C, 0)):
      i = C[j]
      A_2[j, :, :] = np.concatenate((A[j, 0:i + 1, :], [B[j, i, :]], A[j, i + 1:, :]))
    return A_2

fn_4d(A, B, C, iter_3d)

rawDescription: Insertion of non aligned elements in 4-dimensional matrices in numpy


code: rs = numpy.linspace(0, 4, 400)

rawDescription: Code for logistic equation

description: Code for logistic equation


code:
width = 4
grid = '01 02 03 04 04 03 02 01 04 04 104 04 01 02 01 02'
[[int(x) for x in grid.split()][i:i+width] for i in xrange(0, grid.count(" "), width)]

rawDescription: Create multi-dimensional list from list

description: Create multi-dimensional list from list


code:
vowels = set(["a","e","i","o","u"])
def awesome(name):
    vowel_count = 0
    for letter in name:
        if letter in vowels:
            vowel_count += 1
    return vowel_count

rawDescription: Vowel count only for one word?

description: Vowel count only for one word


rawDescription: Regex: How to find attribute in html, that includes another attribute


code:
from PySide import QtGui
from example_ui import Ui_Window

class Window(QtGui.QWidget, Ui_Window):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.button.setStyleSheet("""
            QPushButton {
                background-image: url(:/button/res/login_enter_button.gif);
            }
            """)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: An images does not show in the program, using PySide and QtDesigner


rawDescription: Python Decimals format

description: Python Decimals format


code:
import copy

copy3 = copy.deepcopy(orig)

id(copy3[0]) == id(orig[0])   # inner list have different id
orig[0][3] = 34

orig
copy3

rawDescription: Changing a value in one list changes the values in another list with a different memory ID


rawDescription: How can I recreate a pointer to a global array in python

description: Recreate a pointer to a global array in python


code:
page_number(30, 15)
page_number(31, 15)

rawDescription: Iterate over double values to produce page numbers


code:
def log_interp(zz, xx, yy):
    logz = np.log10(zz)
    logx = np.log10(xx)
    logy = np.log10(yy)
    return np.power(10.0, np.inter(logz, logx, logy))

rawDescription: Logarithmic interpolation in python

description: Logarithmic interpolation in python


code:
delta.name = "delta"
hg = pd.concat((hg, delta), axis=1)
hg

rawDescription: Pandas days between in a single column

description: Pandas days between in a single column


code:
def s_equation(a):
    left, right = a.split('=')
    return eval(left) == eval(right)

rawDescription: How do I write a string equation solver in python?

description: Write a string equation solver in python


code:
pkt = ICMP()/IP()/TCP()
ipHeader = pkt.getlayer(IP)
ipHeader

rawDescription: How to read whole ip layer and tcp layer from a packet when using scapy?

description: Read whole ip layer and tcp layer from a packet when using scapy


rawDescription: A simple button, when clicked increase a number by one


rawDescription: Python/Numpy subarray selection

description: Python/Numpy subarray selection


code:
def word_reader(filename, L):
  L2 = L+2
  # returns an iterator
  return (word.strip() for word in open(filename) \
          if len(word) < L2 and len(word) > 2)

rawDescription: How can this Python Scrabble word finder be made faster?


code:
import concurrent.futures as cf
import logging
import os

errmsg = 'conversion of track {} failed, return code {}'
okmsg = 'finished track {}, "{}"'
num = len(data['tracks'])
with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp:
    fl = [tp.submit(runflac, t, data) for t in range(num)]
    for fut in cf.as_completed(fl):
        idx, rv = fut.result()
        if rv == 0:
            logging.info(okmsg.format(idx+1, data['tracks'][idx]))
        else:
            logging.error(errmsg.format(idx+1, rv))

rawDescription: How to process sub-batches of asynchronous jobs?

description: Process sub-batches of asynchronous jobs


rawDescription: python script does not work but individual shell command does

description: Python script does not work but individual shell command does


code:
A
np.in1d(A[:,3:],B) # Flattened mask
np.in1d(A[:,3:],B).reshape(A.shape[0],-1) # Reshaped mask
A[:,3:][np.in1d(A[:,3:],B).reshape(A.shape[0],-1)] = 0 # Final code
A

rawDescription: Intersection of 2d and 1d Numpy array

description: Intersection of 2d and 1d Numpy array


code: {'abbajare': ', per dimostrar gridando. Inf. VII, 43.', 'abbandonare': ', per lasciare una impresa difficile: Par.\nXVIII, 9.', 'abbagliato': ' (l’), sanese, uomo goloso che consu'}

rawDescription: zConvert an HTML file into a Python dictionary

description: ZConvert an HTML file into a Python dictionary


code:
'a' +rd('sdkkkkkk')
'a'+'s' +rd('dkkkkkk')
'a'+'s'+'d' +rd('kkkkkk')

rawDescription: Contradictory outputs in simple recursive function


rawDescription: Is it expected behavior with os.path.join()


code:
import mock
f = mock.Mock()
f(1)
f(2)
f.assert_has_calls([mock.call(1), mock.call(2)])
f.assert_has_calls([mock.call(2), mock.call(1)])
f.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)
f(3)
f.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)
f.assert_has_calls([mock.call(1), mock.call(2)])
assert len(f.mock_calls)==2
assert len(f.mock_calls)==3
def assert_is_calls(m, calls, any_order=False):
   assert len(m.mock_calls) == len(calls)
   m.assert_has_calls(calls, any_order=any_order)

assert_is_calls(f, [mock.call(1), mock.call(2), mock.call(3)])
assert_is_calls(f, [mock.call(1), mock.call(3), mock.call(2)])
assert_is_calls(f, [mock.call(1), mock.call(3), mock.call(2)], True)
assert_is_calls(f, [mock.call(1), mock.call(3)], True)

rawDescription: Checking whether function has been called multiple times with different parameters


code:
date_list=[datetime.date.today()- dateutil.relativedelta.relativedelta(months = x) for x in range(11,-1,-1)]
month_list=[datetime.date.strftime(x,'%b %Y') for x in date_list]

rawDescription: Make a list of months and years in Pandas


code:
# If there are a lot of area codes, using a set/frozenset will allow much faster lookup
area_codes_set = frozenset(area_codes)
for line in txt:
    is_number = phonenumbers.parse(line,"GB")
    if phonenumbers.is_valid_number(is_number):
        # Assuming lines that match always start with ###
        if line[:3] in area_codes_set:
            print(line, line[:3])

rawDescription: In Python,if startswith values in tuple, I also need to return which value


code:
import socket_patched
socket_patched.original_function('foo', 'bar')
# This call brings us 'Happiness'

rawDescription: How to make a copy of a python module in runtime?

description: Make a copy of a python module in runtime


code:
mapp = one_to_one_dict()
for line in f:
    k, v = line.split(None, 1)
    mapp[k] = v

rawDescription: More efficient way to get unique first occurrence from a Python dict


code: changed = ''.join(newstate[c] for c in prev)

rawDescription: How to implement the concept of cellular automata in python

description: Implement the concept of cellular automata in python


code:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

AWS_ACCESS_KEY_ID = 'access-id'
AWS_SECRET_ACCESS_KEY = 'secret-key'
AWS_STORAGE_BUCKET_NAME = 'bucket-name'
AWS_PRELOAD_METADATA = True # necessary to fix manage.py collectstatic command to only upload changed files instead of all files

rawDescription: Proper way to handle static files and templates for Django on Heroku


code:
C = np.linalg.inv(np.transpose(A).dot(A))
C = C.dot(np.transpose(A)).dot(B)

rawDescription: Loops to minimize function of arrays in python


code:
update
by_id
by_lookup
create
use_for_related_fields

rawDescription: PyCharm doesn't understand custom Manager of model


code:
@asyncio.coroutine
def fetch_page(url):
    response = yield from aiohttp.request('GET', url)
    assert response.status == 200
    return (yield from response.read())

rawDescription: Pros and cons of using return (yield from some_function())


rawDescription: Open URL "silently" in python or similar


code:
def change_color(self, color):
    template_css = """QProgressBar::chunk { background: %s; }"""
    css = template_css % color
    self.setStyleSheet(css)

rawDescription: Python: QtGui.QProgressBar Color

description: Python: QtGui.QProgressBar Color


code:
x = []
for i in range(3):
    kcopy = k[:]
    random.shuffle(kcopy)
    x.append(kcopy)

rawDescription: python random.shuffle() in a while loop

description: Python random.shuffle() in a while loop


code:
from cStringIO import StringIO
from tokenize import generate_tokens, untokenize, NAME, NUMBER, OP, STRING

def is_float_literal(s):
    """Identify floating-point literals amongst all numeric literals."""
    if s.endswith('j'):
        return False  # Exclude imaginary literals.
    elif '.' in s:
        return True  # It's got a '.' in it and it's not imaginary.
    elif s.startswith(('0x', '0X')):
        return False  # Must be a hexadecimal integer.
    else:
        return 'e' in s  # After excluding hex, 'e' must indicate an exponent.

def decistmt(s):
    """Substitute Decimals for floats in a string of statements.

    >>> from decimal import Decimal
    >>> s = 'print +21.3e-5*-.1234/81.7'
    >>> decistmt(s)
    "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"

    >>> exec(s)
    -3.21716034272e-007
    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7

    """
    result = []
    g = generate_tokens(StringIO(s).readline)   # tokenize the string
    for toknum, tokval, _, _, _  in g:
        if toknum == NUMBER and is_float_literal(tokval):
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result)

rawDescription: Convert ast.Num to decimal.Decimal for precision in python


code: json.loads( '{"vld_id": 1, "something_else": true, "vls_error": 2}' )

rawDescription: Passing a Python list using JSON and Django


code:
from collections import OrderedDict

with open('in.csv') as f:
    r = csv.reader(f)
    od = OrderedDict()
    for row in r:
        # get key/ first element in row
        key = row[0]
        # create key/list paring if it does not exist, else just append the value
        od.setdefault(key, []).append(row[1:])
print(od)

rawDescription: Converting CSV data to list in dictionary


code:
import Image

def color_separator(im):
    if im.getpalette():
        im = im.convert('RGB')

    colors = im.getcolors()
    width, height = im.size
    colors_dict = dict((val[1],Image.new('RGB', (width, height), (0,0,0)))
                        for val in colors)
    pix = im.load()
    for i in xrange(width):
        for j in xrange(height):
            colors_dict[pix[i,j]].putpixel((i,j), pix[i,j])
    return colors_dict

im = Image.open("colorwheel.tiff")
colors_dict = color_separator(im)
#show the images:
colors_dict.popitem()[1].show()
colors_dict.popitem()[1].show()

rawDescription: PIL? Extract all pixels of a given RGB value


code:
a = [2,7,9]
b = [[7,9],[1,2],[2,9]]

st = set(a)

print(sum(st.issuperset(sub) for sub in b))
2

rawDescription: Count of pair element in list

description: Count of pair element in list


code:
import lxml.html as LH

doc = LH.fromstring(content)
print([tr.xpath('td[1]/a/@href | td[position()=2 or position()=3]/text()')
       for tr in doc.xpath('//tr')])

rawDescription: Parsing HTML data with lxml

description: Parsing HTML data with lxml


code:
for row in response.css("tr[class^=row]"):
    header_text = row.xpath("preceding-sibling::tr[starts-with(@class, 'header')][1]/text()").extract_first()
    row_text = row.xpath("text()").extract_first()
    print(header_text, row_text)

rawDescription: Scrapy table with tr as header how to import it


code:
class TopMeta(type):
    def __new__(cls, clsname, bases, dct):
        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(TopMeta, cls).__new__(cls, clsname, bases, uppercase_attr)

    def sos(cls):
        return 'sos'

class UpperMeta(type):
    __metaclass__ = TopMeta
    def __new__(cls, clsname, bases, dct):
        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(UpperMeta, cls).__new__(cls, clsname, bases, uppercase_attr)

class B(object):
    __metaclass__ = UpperMeta

assert not hasattr(B, 'sos')

rawDescription: Why does a class have the attributes of its metaclass?


code:
star_list = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
star_list = [i for i, next_i in zip(star_list, star_list[1:] + [None])
             if (i, next_i) != ('**', '**')]

rawDescription: Remove certain consecutive duplicates in list


code:
categories = (
    (category1, dispatch1method),
    (category2, dispatch2method),
    (category3, dispatch3method),
    (category4, dispatch4method),
    (category5, dispatch5method),
)

next(method for cat, method in categories if request_type in cat)(arguments)

rawDescription: Best practices for Python if-elif-elif-elif when dispatching requests


code:
import operator
keyfunc = operator.attrgetter(avggrouper1, avggrouper2)
df_hour_means = df_hour_means.groupby(keyfunc).mean()

rawDescription: Python Pandas groupby function with dynamic parameters for monthly, hourly means


rawDescription: Using df.apply() with a Pandas MuliIndex / carrying out operations on hierarchical index rows?


code:
def get_sentinel_user():
    return User.objects.get_or_create(username='deleted')[0]

class MyModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))

rawDescription: Django not cascading on delete

description: Django not cascading on delete


rawDescription: View pdf image in an iPython Notebook

description: View pdf image in an iPython Notebook


rawDescription: How would I convert words to numbers in python 3 (own keys and values)?


code:
def foo(x): return x
def bar(x): return x*x

rawDescription: IPython: Alias which uses a magic function itself


code:
results = {}
for label, text_edit in zip(self.labels, self.text_edits):
    results[label] = text_edit.text()

rawDescription: How do I size QLayout based on proportionality?

description: Size QLayout based on proportionality


code:
one_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
stat = {'A': 5,
          'B':3,
          'C':9,
          'U': 5,
          'D': 9,
          'a': 99}

total_count = sum(stat.get(letter, 0) for letter in one_letter) # should be 31

rawDescription: calculate percentage of strings instead of statistics

description: Calculate percentage of strings instead of statistics


code:
s
' '.join(hexlify(c.encode('utf8')) for c in s.split())
b' '.join(hexlify(c.encode('utf8')) for c in s.split())    # Python 3

rawDescription: Convert unicode characters to utf-8 in python


code:
img = Image.fromarray(closest, 'L')
img.show()

rawDescription: Face Recognition - How to return the correct image?


rawDescription: pyPdf ignores newlines in PDF file

description: PyPdf ignores newlines in PDF file


code:
class int:
    def __hash__(self):
        value = self
        if value == -1:
            value = -2
        return value

rawDescription: What's the logic behind Python's hash function order?


rawDescription: Parsing plain text with section in Python


rawDescription: creating dynamic nested dictionary

description: Creating dynamic nested dictionary


code:
class Board:
    def f(self):
        return 'Hello'
    def print_board(self):
        return 'Hello'

b = Board()
print(b.f())
print(b.print_board())

rawDescription: Underscores in method names [silly mistake]


code:
from dateutil.parser import parse

def is_date(string):
    try:
        parse(string)
        return True
    except ValueError:
        return False

rawDescription: Check if string has date, any format

description: Check if string has date, any format


rawDescription: Python - Splitting up a string into a list of paired chars


code:
# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()

rawDescription: Python - Start a Function at Given Time

description: Python - Start a Function at Given Time


code:
def animation ( i = 0 ):
    sys.stdout.write( '\r' + ( '.' * i ) + '   ' )
    sys.stdout.flush()
    Timer( 0.5, animation, ( 0 if i == 3 else i + 1, ) ).start()

animation()
print( 'started!' )

while True:
    pass

rawDescription: How can I make an indeterminate progress bar in a Python console app?

description: Make an indeterminate progress bar in a Python console app


code:
import regex
text = 'ذوب 6 خوی 7 بزاق ،آب‌دهان ، یم 10 زهاب، 11 آبرو، حیثیت، شرف'
regex.findall(r'\p{L}+', text.replace('\u200c', ''))

rawDescription: Tokenizing non English Text in Python

description: Tokenizing non English Text in Python


code: phonebook['Steven']['Number']

rawDescription: Python Phonebook

description: Python Phonebook


code:
from flask import Flask, render_template, redirect, request, url_for
import flask.ext.login as flask_login
from flask.ext.login import LoginManager, UserMixin

login_manager = LoginManager()

app = Flask(__name__)
app.secret_key = 'key'

login_manager.init_app(app)

users = {'user1':{'pw':'pass1'},
         'user2':{'pw':'pass2'},
         'user3':{'pw':'pass3'}}

class User(UserMixin):
  pass

@login_manager.user_loader
def user_loader(username):
  if username not in users:
    return

  user = User()
  user.id = username
  return user

@login_manager.request_loader
def request_loader(request):
  username = request.form.get('username')
  if username not in users:
    return

  user = User()
  user.id = username

  user.is_authenticated = request.form['pw'] == users[username]['pw']

  return user

@app.route('/', methods=['GET', 'POST'])
def index():
  if request.method == 'POST':
    username = request.form.get('username')
    if request.form.get('pw') == users[username]['pw']:
      user = User()
      user.id = username
      flask_login.login_user(user)
      return redirect(url_for('protect'))
  return render_template('index.html')

@app.route('/protect')
@flask_login.login_required
def protect():
  return render_template('protected.html')

@app.route('/logout')
def logout():
  flask_login.logout_user()
  return 'Logged out'

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

rawDescription: Anonym password protect pages without username with Flask


code:
def print_table(seq, width=3):
    print('\n'.join([''.join(
        [(str(u[-i]) if len(u) >= i else '').rjust(width) for u in seq])
            for i in range(max(len(u) for u in seq), 0, -1)]))

rawDescription: Print elements of list horizontally

description: Print elements of list horizontally


code:
s = 'Who is awesome? Chad'
s.split(' ')[-1]

rawDescription: Search one text file for values of another and then print that line


rawDescription: Modify only a specific tuple in python (incomprehensible)


code:
len(A)
len(B)
np.all(np.unique(A[['idx1', 'idx2']]) == np.unique(B[['idx1', 'idx2']]))

rawDescription: stratified sampling in numpy

description: Stratified sampling in numpy


code: WebDriverWait(selenium_browser, 10).until(lambda driver: len(driver.find_elements_by_xpath("//div[@id='headlines_transcripts']//li")) != old_count)

rawDescription: Selenium - Python bindings - Detect new AJAX data


code: re.search("[a-zA-Z](\d{2})", "S07E01 - Meet the New Boss.avi").group(1)

rawDescription: Find 1 letter and 2 numbers using RegEx

description: Find 1 letter and 2 numbers using RegEx


code:
CustomAvg = Avg[Height] + Avg[Weight]    # store as a constant
CustomAvg *= Avg[Height] + Avg[Weight]   # store as a callable

rawDescription: Evaluating nested variables with pyparsing for a DSL


code: ('/details/(\d+)', DetailsPage),

rawDescription: How to reformat URLs to be more restful (from .../?id=123 to .../123)?

description: Reformat URLs to be more restful (from .../?id=123 to .../123)


code: import mfxLib02 as mfxLib

rawDescription: How to maintain different version of a python module?

description: Maintain different version of a python module


code:
import itertools

database = [
    {"Name":"Arnold", "Age":"52", "Height":"160"},
    {"Name":"Donald", "Age":"52", "Height":"161"},
    {"Name":"Trevor", "Age":"22", "Height":"150"},
]

def search(s):
    s = s.lower() # it is a nice feature to ignore case
    for item in database:
        if any(s in v.lower() for v in item.values()): # if any value contains s
            yield item # spit out the item — this is a generator function

# iterate over at most 5 first results
for result in itertools.islice(search("52"), 5):
    print(result)

rawDescription: How can I implement a fuzzy search across each value of a dictionary in a multiple dictionary list?

description: Implement a fuzzy search across each value of a dictionary in a multiple dictionary list


code: soup.find('a', text='See full summary')['href']

rawDescription: Match href value with a regular expression


code: func(arg1, arg2, arg3)

rawDescription: How can i have more than 255 arguments in Z3py function?

description: Have more than 255 arguments in Z3py function


code: keyName = myMember.key().name()

rawDescription: How can I get the key_name of the entry in Model() on GAE for Python?

description: Get the key_name of the entry in Model() on GAE for Python


code:
for name in sorted(user_scores):
    print(name, '-', user_scores[name])

rawDescription: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file


code:
import cv2
import numpy as np

# Colors (B, G, R)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

def create_blank(width, height, color=(0, 0, 0)):
    """Create new image(numpy array) filled with certain color in BGR"""
    image = np.zeros((height, width, 3), np.uint8)
    # Fill image with color
    image[:] = color

    return image

def draw_half_circle_no_round(image):
    height, width = image.shape[0:2]
    # Ellipse parameters
    radius = 100
    center = (width / 2, height - 25)
    axes = (radius, radius)
    angle = 0
    startAngle = 180
    endAngle = 360
    # When thickness == -1 -> Fill shape
    thickness = -1

    # Draw black half circle
    cv2.ellipse(image, center, axes, angle, startAngle, endAngle, BLACK, thickness)

    axes = (radius - 10, radius - 10)
    # Draw a bit smaller white half circle
    cv2.ellipse(image, center, axes, angle, startAngle, endAngle, WHITE, thickness)

# Create new blank 300x150 white image
width, height = 300, 150

image = create_blank(width, height, color=WHITE)
draw_half_circle_no_round(image)
cv2.imwrite('half_circle_no_round.jpg', image)

rawDescription: How can I draw half circle in OpenCV?

description: Draw half circle in OpenCV


code:
class Foo(object):
    def __init__(self, parent):
        self.parent = parent
        self._vals = {}

    def __setitem__(self, key, val):
        parent.do_side_effect(key, val)
        self._vals[key] = val

rawDescription: Pythonic alternative to dict-style setter?


code:
import mechanize
import urllib, urllib2
from bs4 import BeautifulSoup

url = 'http://as0.mta.info/mnr/fares/choosestation.cfm'
post_url = 'http://as0.mta.info/mnr/fares/get_fares.cfm'

def get_fares(orig, dest):
    params = urllib.urlencode({'dest_stat':dest, 'orig_stat':orig })
    rq = mechanize.Request(post_url, params)

    fares_page = mechanize.urlopen(rq)
    print(fares_page.read())

pool = BeautifulSoup(urllib2.urlopen(url).read())

#let's keep our stations organised
stations = {}

# dict by station id
for option in pool.find('select', {'name':'orig_stat'}).findChildren():
    stations[option['value']] = {'name':option.string}

#iterate over all routes
for origin in stations:
    destinations = get_list_of_dests(origin) #use your code for this
    stations[origin]['dests'] = destinations

    for destination in destinations:
        print('Processing from %s to %s' % (origin, destination))
        get_fares(origin, destination)

rawDescription: Python mechanize javascript

description: Python mechanize javascript


rawDescription: Merging records in a Numpy structured array


code:
def is_factor(f, N):
    """is f a factor of N?"""
    return (N % f) == 0

rawDescription: How to use IPython.parallel map() with generators as input to function

description: Use IPython.parallel map() with generators as input to function


code:
import ctypes

class ProtocolStructure(type(ctypes.Structure)):
  def __str__(self):
    s='''
typedef struct __attribute__((packed)) {
\t%s
}'''
    return s % '\n\t'.join(('%s %s;' % (ty.__name__[2:], name) for name,ty in self._fields_))

class struct_token_type_delta(ctypes.Structure, metaclass=ProtocolStructure):
  _fields_ = (('token_type', ctypes.c_uint8),
              ('delta', ctypes.c_int16))

if __name__ == '__main__':
  # when this file is run instead of imported print the header file to stdout

  h='''
#ifndef PROTO_H
#define PROTO_H
%s
#endif
'''

  print(h % ';\n'.join('%s %s;\n' % (ty, name)  for name,ty in globals().items() if issubclass(type(ty), ProtocolStructure)))

rawDescription: Casting string/buffer data using swig wrapped typedef structs and enums in python


code:
def get_value(word):
    return lookup.get(word)

rawDescription: Python Binary Search for Dictionary

description: Python Binary Search for Dictionary


code:
import struct
# 24 bits: 01010101 10101010 11110000
byte1 = 0x55
byte2 = 0xaa
byte3 = 0xf0
data = struct.pack("BBB", byte1, byte2, byte3)

rawDescription: python - pack exactly 24 bits into unsigned/signed int

description: Python - pack exactly 24 bits into unsigned/signed int


code: values = [d[tuple(a)] for a in indices]

rawDescription: Conversion: np.array of indices to np.array of corresponding dict entries


code:
NSMAP = { 'exa': 'http://www.example.com/test',
          'axx': 'http://www.example.com/foo' }

root = ET.Element('{http://www.example.com/test}root', nsmap=NSMAP)
sub_element = ET.SubElement(root, '{http://www.example.com/test}sub_element')
foo_element = ET.SubElement(sub_element, '{http://www.example.com/foo}foo')
bar_element = ET.SubElement(sub_element, '{http://www.example.com/foo}bar')

tree = ET.ElementTree(root)

print(ET.tostring(tree,encoding='UTF-8',pretty_print=True,xml_declaration=True))

rawDescription: How to force all namespace declarations to be attached to the root element?

description: Force all namespace declarations to be attached to the root element


code:
numbered = {}
for i in tup:
    numbered.setdefault(i[1], []).append(i)

rawDescription: Splitting a list of tuples by 2nd element - python


rawDescription: Numpy append ones to matrix

description: Numpy append ones to matrix


code:
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
    """
    Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
    None, settings.SECRET_KEY is used instead.
    If compress is True (not the default) checks if compressing using zlib can
    save some space. Prepends a '.' to signify compression. This is included
    in the signature, to protect against zip bombs.
    Salt can be used to namespace the hash, so that a signed string is
    only valid for a given namespace. Leaving this at the default
    value or re-using a salt value across different parts of your
    application without good cause is a security risk.
    The serializer is expected to return a bytestring.
    """

rawDescription: Change Django secret key within script

description: Change Django secret key within script


code:
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

rawDescription: How to remove all the punctuation in a string? (Python)

description: Remove all the punctuation in a string? (Python)


code:
from PyQt4 import QtGui, QtCore
from classfile import ClassCode

class Stack(ClassCode):
    def __init__(self, parent=None):
        ClassCode.__init__(self, parent)

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.stack = Stack(self)
        self.setCentralWidget(self.stack)

rawDescription: PyQt4 - Custom widget class structure?

description: PyQt4 - Custom widget class structure


code:
for i in range(X):
    btn = Tkinter.Button(text=u'%d' % i)
    btn['command'] = lambda button=btn: some_callback(button)

rawDescription: Why does Tkinter hang when I call tkSimpleDialog.askstring from a lambda?


rawDescription: python merge panda dataframes keep dates

description: Python merge panda dataframes keep dates


code:
@register.inclusion_tag('qrcode/qr_tag.html', takes_context=True)
def get_qrcode_image(context, text, size):
    url = reverse('generate_qr')
    return {'url': url, 'text': text, 'size': size}

rawDescription: How to display a PIL image object in Django view?

description: Display a PIL image object in Django view


rawDescription: How to sort tire sizes in python

description: Sort tire sizes in python


code:
{u'HEADER 2': {'data_point_2': [u'DATA32'],
               'data_point_3': [u'DATA33'],
               'data_point_1': [u'DATA31']},
 u'HEADER 1': {'data_point_2': [u'DATA32'],
               'data_point_3': [u'DATA33'],
               'data_point_1': [u'DATA31']}}

rawDescription: Iterating through a table of rows with beautiful soup in python


code:
from mypprint import pprint
pprint.pprint(object_with_np.arrays)

rawDescription: Pretty print and substitute numpy arrays


code:
if wait_time_secs not in acceptable_values:
    teachUsage()

rawDescription: How to check whether script input param is among list of acceptable values?

description: Check whether script input param is among list of acceptable values


rawDescription: Regex for finding variable references in a C file using Python


TestData

ProgramName: AST

rawDescription: Convert python decimal to string in deeply nested and unpredictable list


code:
from hurry.filesize import size, iec
size(11000, system=iec)
size(198283722, system=iec)

rawDescription: Better way to convert file sizes in Python


code:
self.__statusdata = json.dumps(statusdata)
statusdata = json.loads(self.__statusdata)

rawDescription: how to use Json in Python

description: Use Json in Python


code: from ROOTFOL.PACKAGE import *

rawDescription: Pydev tags import as "unresolved import" but code using this import works fine.


rawDescription: Mock: Tracking all Calls. Shell vs. program inconsistency


code:
from array import array
f.write(array('B', bytes))

rawDescription: Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)


code:
with open(outputfile, 'w') as output:
    with open(file, 'r+') as book:
        for line in book:
            output.write(pattern.sub(translate, line))

rawDescription: Using Two Sets of Words for a Find and Replace RE


code:
lst=['3a', '4a', '5a', '6a', 'Ca', 'Da', 'Aa', 'Ba', '4b','5b', '6b', '7b', '7c', '8c']
prev = lst[0][-1]
streak = 1
streaklst = [lst[0]]
matches = []
for x in lst[1:]:
    if x[-1] == prev:
        streak += 1
        streaklst.append(x)
    else:
        if streak >= 4:
            matches.append(streaklst)
        streaklst = [x]
        streak = 1
        prev = x[-1]

print(matches)

rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


code: index = app.route(...)(index)

rawDescription: Python Decorator Self-firing

description: Python Decorator Self-firing


code:
import re

def headerfiller(df):
    df.columns = [re.sub(r' \n', '_', c) for c in df.columns]

rawDescription: Remove space and newlines in pandas columns using idiomatic Python?


code:
comma_indices = []
for index, p in enumerate(prp1):
    if p == ",":
        commas.append(index)

rawDescription: Python - Narrowing down itertools permutations results with "if" statements. How to with repeated element?


code: data = genfromtxt('data.csv', delimiter=',', names=True, dtype=None)

rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


code:
data_nan = np.full(data.shape, np.nan)
data_nan[result] = data[result]
data = data_nan

rawDescription: set the elements not included by np.where as np.nan

description: Set the elements not included by np.where as np.nan


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

rawDescription: Different databases with the same models on Django


code:
# The basic things
import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://www.kcda.org/KCDA_Awarded_Contracts.htm').read())

rawDescription: Using BeautifulSoup to find a tag and evaluate whether it fits some criteria


code:
import modules

# when code from modules.py is required
modules.foo()

rawDescription: Make python module not load/run itself unless it is a an "import"


code:
import re
sample = '.jalsdkjflkajsdf_lajsdlfIFIX_100(IFIX_asdf_200)'
patternI1 = r'\.\w*(IPROC|IFIX|IPTAT)\w*?(\d\d*)\D*.*\(\w*(IPROC|IFIX|IPTAT)\w*?(\d\d*)\D*.*\)'
re.search(patternI1, sample).groups()

rawDescription: Python regex and using s/ in pattern

description: Python regex and using s/ in pattern


code:
import numpy as np
import matplotlib.pyplot as plt
def plot_square(x, y):
    y_squared = np.square(y)
    return plt.plot(x, y_squared)

rawDescription: How can I write unit tests against code that uses matplotlib?

description: Write unit tests against code that uses matplotlib


rawDescription: numpy array multiplication slower than for loop with vector multiplication?

description: Numpy array multiplication slower than for loop with vector multiplication


code:
f = open('test.txt','r')
data = f.read()
x = re.findall(r'alpha(.*?)bravo',data,re.DOTALL)
x
"".join(x).replace('\n',' ')

rawDescription: How to extract information between two unique words in a large text file

description: Extract information between two unique words in a large text file


rawDescription: matplotlib's scatter plot changes the axis of another plot

description: Matplotlib's scatter plot changes the axis of another plot


rawDescription: Is there already package in python which generate strong random sequence which uses only digits?


rawDescription: Assigning values to a NumPy array

description: Assigning values to a NumPy array


code:
def openaudio(self, path):
    # Do not do this here! Connections should usually be made in the init() method of the container!
    # self.connect(self.ui.listWidget,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))

    # Also take a look at the 'new' PyQt signals & slots style:
    # self.ui.listWidget.currentTextChanged.connect(self.ui.label_4.setText)

    self.mediaObject.setCurrentSource(phonon.Phonon.MediaSource(path))
    self.mediaObject.play()

rawDescription: How to get the file name and show it on Qlistwidget?

description: Get the file name and show it on Qlistwidget


code:
a1 = ['Second', 'Third', 'Fourth']
b1 = ['First', 'Second', 'Third']

a2 = ['First', 'Third', 'Fourth']
b2 = ['First', 'Second', 'Third']

a3 = ['First', 'Third', 'Fourth']
b3 = ['First', 'Second', 'Fourth']

def merge(a, b):
    c = []
    b_oldindex = 0
    for a_index in range(len(a)):
        match = False
        for b_index in range(b_oldindex, len(b)):
            if a[a_index] == b[b_index]:
                c.extend(b[b_oldindex:b_index+1])
                b_oldindex = b_index + 1
                match = True
                break
        if not match:
            c.append(a[a_index])
    if b_oldindex < len(b):
        c.extend(b[b_oldindex:])
    return c

print(merge(a1,b1))
print(merge(a2,b2))
print(merge(a3,b3))
print(merge(b1,a1))
print(merge(b2,a2))
print(merge(b3,a3))

rawDescription: Combine two lists of strings

description: Combine two lists of strings


code:
py -2        # launch latest 2.x version installed.
py -3        # latest 3.x
py -3.2      # run exact version
py -3.2-32   # run 32-bit version on 64-bit system.

rawDescription: Do I have to uninstall old python versions to update to a new one in Windows?


code:
def form_valid(self, form):
    self.object = form.save(commit=False)
    project = Project.objects.get(slug=self.kwargs["project_slug"])
    self.object.project = project
    self.object.save()

    return super(ProjectDetailToDoForm, self).form_valid(form)

rawDescription: Django - Query to retrieve pk from other model


code:
n = np.npv(0.01, cashflow)
np.irr(np.r_[-n, cashflow])

rawDescription: Basic Financial Library for Python

description: Basic Financial Library for Python


code:
myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
    current = current.setdefault(key, {})

rawDescription: Creating dictionary using list/tuple elements as key


code:
flowTcp = ("in_port" + LBRACE + in_port("in_port") + RBRACE + COMMA +
            eth("eth") + COMMA +
            Optional("eth_type" + LBRACE + eth_type("eth_type") + RBRACE + COMMA ) +
            Optional(arp("arp") + COMMA) +
            Optional(ipv4("ipv4") + COMMA) +
            Optional(tcp("tcp") + COMMA) +
            "packets" + COLON + packets("packets"))

rawDescription: extract data from ovs dump-flow using pyparsing

description: Extract data from ovs dump-flow using pyparsing


code:
# the foo module object is added as a member attribute of bar on import
# with the name foo in the bar namespace
import foo
# the same foo object is aliased within the bar namespace with the name
# fooy
import foo as fooy
# foo.x and foo.y are referenced from the bar namespace as x and y,
# available as member attributes of the bar module object
from foo import x, y
# z is a member attribute of the bar module object
z = 'z'

rawDescription: Importing "sub" modules to be own "sub" modules


code: df['diff'] = df['value'].diff()

rawDescription: Speeding up group-wise differencing in Pandas


code:
if x == 0:
    somestuff_A

rawDescription: Python Pythonic way to organize/design if statements


code:
org_list = ['aa', 'b2', 'c', 'd']
mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
[mapping[i] for i in org_list]

rawDescription: Python program that generate a list from a given list according to a mapping


code: pieces = map(float, pieces) #assign the floated list to the variable 'pieces'

rawDescription: Map serial port data into integer

description: Map serial port data into integer


code:
print_to_console("Hello TTY!")
# -> Hello TTY!

rawDescription: Python output to Console within Subprocess from the child scricpt


rawDescription: Regex: How to split by "=" and not by "!="


rawDescription: PyQt4 - Using a QItemDelegate to display widget in a QListView


rawDescription: Grabbing specific indices of a list in Python


rawDescription: Sorting list nested in tuples

description: Sorting list nested in tuples


code:
def sigma8(data):
    import collections as col

    particles = [Particle(x) for x in data]
    boxes = col.Counter([x.box_label for x in particles])
    counts = boxes.most_common()

    #some other stuff

rawDescription: Quickly counting particles in grid

description: Quickly counting particles in grid


code:
def customFilter(s):
    foundStart = False
    for i, val in enumerate(s):
        if not foundStart and val == 1:
            foundStart = True
            start = i
        if foundStart and val == 0:
            end = i
            yield (start, end+1)
            foundStart = False
    if foundStart:
        yield (start, len(s))

rawDescription: matplotlib how to fill_between step function

description: Matplotlib how to fill_between step function


code:
import unittest
import itertools

def encode(bits):
    '''Encode n bits to an integer using a leading 1 to mark the length of the bit stream.

    Example: [0,0,0] == 0b1000 == 16
    '''
    # start with an initial 1.
    # iteratively shift current value left and OR in new bit.
    return reduce(lambda n,b: n << 1 | b,bits,1)

def decode(encoded):
    '''Decode a positive integer into a list of 0/1 values.
    The most significant bit marks the length and is removed.

    Example:  137 = 0b10001001 = [0,0,0,1,0,0,1]
    '''
    if encoded < 1:
        raise ValueError('encoded must be > 0')
    return [1 if c=='1' else 0 for c in format(encoded,'b')][1:]

class Cases(unittest.TestCase):
    def testEncodeZeros(self):
        for i in xrange(100):
            bits = [0]*i
            self.assertEqual(encode(bits),2**i)
    def testEncodeOnes(self):
        for i in xrange(100):
            bits = [1]*i
            self.assertEqual(encode(bits),2**(i+1)-1)
    def testDecodeZeros(self):
        for i in xrange(100):
            encoded = 2**i
            self.assertEqual(decode(encoded),[0]*i)
    def testDecodeOnes(self):
        for i in xrange(100):
            encoded = 2**(i+1)-1
            self.assertEqual(decode(encoded),[1]*i)
    def testEncodeDecode(self):
        for n in xrange(10):
            for bits in itertools.product([0,1],repeat=n):
                self.assertEqual(decode(encode(bits)),list(bits))
    def testDecodeZero(self):
        self.assertRaises(ValueError,decode,0)
    def testDecodeNegative(self):
        self.assertRaises(ValueError,decode,-1)

if __name__ == '__main__':
    unittest.main()

rawDescription: How to encode stream of bits (not bytes) in Python - is any simple module for it?

description: Encode stream of bits (not bytes) in Python - is any simple module for it


code:
import numpy as np

np.random.seed(2016)
N = 2
hour = np.tile(np.arange(24), N)
rentals = np.random.randint(10, size=(len(hour),))
# say, weather=1 means good weather, 2 means bad weather
weather = np.random.randint(1, 3, size=(len(hour),))

average_rentals = dict()
for kind, w in zip(['good', 'bad', 'all'], [1, 2, None]):
    if w is None:
        mask = slice(None)
    else:
        mask = (weather == w)
    masked_hour = hour[mask]
    masked_rentals = rentals[mask]
    total_rentals = np.bincount(masked_hour, weights=masked_rentals, minlength=24)
    total_hours = np.bincount(masked_hour, minlength=24)
    average_rentals[kind] = (total_rentals / total_hours)

for kind, result in average_rentals.items():
    print('\n{}: {}'.format(kind, result))

rawDescription: Is there a way to use bincount with a clause in python?


code:
# Internal function used by func2 and func1
def func2_(value):
    list1=[]
    list2=[]
    value=10
    #do some operations based on value
    (list3,list4)=func3(value)
    return list1, list2, list3, list4

# Real func2 with the desired public API
def func2(value):
    list1, list2, _, _ = func2_(value)
    return list1, list2

def func1() :
    value =20
    (list1,list2,list3,list4)= func2_(value)
    #func1 _has_ list3 and list4

rawDescription: Returning function values based on argument?


code:
pika
squi
pokes = {'pikachu': pika, 'squirtle': squi}

rawDescription: Map each element in a Series to a Series and combine the result into a DataFrame


code: df['Score'].apply(lambda score: lookup['Grade'][(lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)].values[0])

rawDescription: Pandas table lookup

description: Pandas table lookup


code:
# -*- coding: utf-8 -*-
from multiprocessing import Pool
import os

users = {
    'a': '1',
    'b': '2',
    'c': '3'
}

def launcher(usr_login, usr_password):
    os.system("python implementation.py %s %s" % (usr_login, usr_password))

if __name__ == '__main__':
    with Pool(3) as p:
        p.starmap(launcher, users.items())

rawDescription: Python Multiprocessing function

description: Python Multiprocessing function


code:
from django import template

register = template.Library()

@register.filter(name="extract_meta")
def extract_meta(request):
    values = request.META.items()
    values.sort
    html = []
    for k, v in values:
        html.append('
%s	%s
' % (k, v))
    return '
%s
' % '/n'.join(html)

rawDescription: Django display in html from views.py

description: Django display in html from views.py


code:
groups = df.groupby(['currency'])
for key, grp in groups:
    print(grp)

rawDescription: Reading chunks of csv file in Python using pandas


rawDescription: Rearranging Matrix Elements with Numpy

description: Rearranging Matrix Elements with Numpy


code:
plist = [c.assistants for c in Course.query.join(
University).filter(University.name == 'MIT')]
[p.name for p in set(itertools.chain(*plist))]

rawDescription: SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list


code:
NUMBERS = {'2': 'A', '22': 'B', '222': 'C', '3': 'D', '33':'E', '333': 'F'}

def normalize_number(number):
    for item in number.split():
        if len(set(item)) == 1:
            yield item
        else:
            last = item[0]
            res = [last]
            for entry in item[1:]:
                if entry == last:
                    res.append(entry)
                else:
                    yield ''.join(res)
                    res = [entry]
                    last = entry
            yield ''.join(res)

def number_to_word(number):
    res = []
    for item in normalize_number(number):
        try:
            res.append(NUMBERS[item])
        except KeyError:
            if len(item) >= 4:
                end = len(item) % 3
                if end == 0:
                    end = 3
                res.append(NUMBERS[item[:end]])
    return ''.join(res)

rawDescription: Writing with numbers

description: Writing with numbers


code:
limit = 10
q1 = User.objects.filter(first__iexact=token).order_by('last')[:limit]
limit -= len(q1)
if limit:
    q2 = User.objects.exclude(pk__in=q1).filter(first__istartswith=token).order_by('last')[:limit]
else:
    q2 = []
users = list(q1) + list(q2)

rawDescription: Return exact matches at top of Django Queryset


rawDescription: Format date like: Monday, 1st March

description: Format date like: Monday, 1st March


rawDescription: Python Timenow Without Milliseconds?

description: Python Timenow Without Milliseconds


code:
def permuteDataFrame(inDf):
    permutedDf = pd.DataFrame({'X' : np.random.permutation(inDf.X),
                               'Y' : np.random.permutation(inDf.Y)})
    # check for dupes
    clash = permutedDf[permutedDf.X == permutedDf.Y]
    if clash.shape[0] > 1: #repermuting can't work if only one row has a match
        clash = permutedDf[permutedDf.X == permutedDf.Y].copy()
        noclash = permutedDf[permutedDf.X != permutedDf.Y].copy()
        # recursion FTW: run the clashes back through this algo
        clash = permuteDataFrame(clash)
        permutedDf = pd.concat([clash, noclash ])
    if clash.shape[0] == 1: # handle the single match problem
        # solving the single match by grabbing the single match plus a random other record and permuting
        # get the vector of bools that indicate matches
        clashIndex = permutedDf.X == permutedDf.Y
        # randomly make another one True
        ilocToSwap = np.random.randint(permutedDf.shape[0]) # random record location to swap
        indexOfClashes.iloc[ilocToSwap] = True
        clash = permutedDf[indexOfClashes]
        # recursion FTW: run the clashes back through this algo
        clash = permuteDataFrame(clash)
        permutedDf = pd.concat([clash, noclash ])
    return permutedDf

rawDescription: Creating a permutation, with restrictions


code:
import textwrap
text = 'בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשּׁמַיִם, וְאֵת הָאָרֶץ'
print(textwrap.fill(text, width=40))  # bad, aggressive wrapping
import uniseg.graphemecluster
def new_len(x):
    if isinstance(x, str):
        return sum(1 for _ in uniseg.graphemecluster.grapheme_clusters(x))
    return len(x)
textwrap.len = new_len
print(textwrap.fill(text, width=40))  # Good wrapping

rawDescription: How do you get the display width of combined Unicode characters in Python 3?

description: Get the display width of combined Unicode characters in Python 3


code:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst[::2]  # Every other item (every item counting by 2's)

rawDescription: Understanding a line of code

description: Understanding a line of code


code:
soapProdAPI.objects.extra(
    select = {
        'rest_id'   : "app_restProdAPI.rest_id",
        'rest_host' : "app_restProdAPI.rest_host",
        'rest_ip'   : "app_restProdAPI.rest_ip",
        'rest_mode' : "app_restProdAPI.rest_mode",
        'rest_state': "app_restProdAPI.rest_state"
    },
    tables = ["app_restProdAPI"],
    where = ["app_restProdAPI.rest_host = app_soapProdAPI.soap_host \
              OR app_restProdAPI.rest_ip = app_soapProdAPI.soap_ip"]
)

rawDescription: Converting LEFT OUTER JOIN query to Django orm queryset/query


code:
@login_manager.user_loader
def load_user(userid):
    return User()

rawDescription: Single-Passcode Authentication on a Flask App


code:
import itertools

class Indexable(object):
    def __init__(self,it):
        self.it = iter(it)
    def __iter__(self):
        return self.it
    def __getitem__(self,index):
        try:
            return next(itertools.islice(self.it,index,index+1))
        except TypeError:
            return list(itertools.islice(self.it,index.start,index.stop,index.step))

rawDescription: Index and Slice a Generator in Python

description: Index and Slice a Generator in Python


code:
# retrieve stdout as a binary file object
output = getattr(sys.stdout, 'buffer', sys.stdout)

rawDescription: Writing bytes to standard output in a way compatible with both, python2 and python3


code:
zs = sorted(z, reverse=True)
zs

rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


code:
from cx_Freeze import main
sys.argv = [sys.argv[0], '--target-dir', '%s'%DISTFOLDER, '--base', 'Win32GUI', entrypoint ]
main()

rawDescription: How to stop a python program executable from opening a cmd shell?

description: Stop a python program executable from opening a cmd shell


code:
SETTINGS = {
    'mode_3': dict(zip(keys, [True, False, False, True])),
}

rawDescription: DRYly represent a list of settings objects


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code:
from functools import wraps

def stateful_memoize(*attrs):
    """Memoization that respects specified instance state."""
    def decorator(method):
        @wraps(method)
        def wrapper(self, *args):
            state = args + tuple(getattr(self, attr)
                                 for attr in attrs)
            if state not in wrapper.cache:
                wrapper.cache[state] = method(self, *args)
            return wrapper.cache[state]
        wrapper.cache = {}
        return wrapper
    return decorator

rawDescription: How to memoize method when one of its memoized parameters should be an instance variable

description: Memoize method when one of its memoized parameters should be an instance variable


code: q = session.query(Task).order_by(sort_logic)  # see the sql at the end of this answer

rawDescription: Specify the sort-order for an Enum field type


code:
for x in tree.iter_preorder():
    do_action(x)

rawDescription: Loop through a bunch of folderish content, which may be itself folderish?


rawDescription: Capturing input between periods in Python


code:
from pebble import process

task = process.concurrent(target=library_function, args=( ... ))
task.cancel()

rawDescription: Terminate asynchronous multiprocessing thread from gunicorn-based web session


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup as bs

source = urlopen(url).read()
soup = bs(source)

rawDescription: Beautifulsoup url loading error

description: Beautifulsoup url loading error


code: print(x), # this will still print a space, but not a newline

rawDescription: Print a row of numbers and then have it make a new line and continue counting


code:
class SurprisingIter(object):
    def __init__(self):
        self.__iter__ = lambda self: iter("abc")

    def __iter__(self):
        return iter([1, 2, 3])

rawDescription: python make class iterable by returning embedded iterable

description: Python make class iterable by returning embedded iterable


code:
tstdata, trndata = alldata.splitWithProportion(0.25)

trndata._convertToOneOfMany()
tstdata._convertToOneOfMany()

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


rawDescription: How do I group by one or more dimensions in a time series with Pandas?

description: Group by one or more dimensions in a time series with Pandas


code:
myregex = re.compile('zone.*?\};', re.DOTALL | re.MULTILINE)
mylist = myregex.findall(myfile.read())

rawDescription: reading a file that follows pattern into array

description: Reading a file that follows pattern into array


code:
import itertools

for ns in itertools.product(*[numbers[g] for g in order]):
    print(*ns) # or 'print ns' for 2.x

rawDescription: Generate combinations (in spefici order) by using one item per list in Python?


code: soup.find_all(class_=["div1", "a1"])

rawDescription: I want to search div and <a> with specified class using beautifulsoup


code: open('t.txt', 'w').write(s)

rawDescription: python pandas dataframe to csv exporting a formatted text file with unique formats for each column

description: Python pandas dataframe to csv exporting a formatted text file with unique formats for each column


code:
foo = OptionParser()
foo.add_option("-f", "--file", dest="filename",help="read data from FILENAME")
foo.add_option("-v", "--verbose",action="store_true", dest="verbose")
bar = ArgumentParser(epilog = foo.format_help(), formatter_class = RawTextHelpFormatter)
bar.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator')
bar.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum the integers (default: find the max)')
bar.print_help()

rawDescription: Can I pass on options from optparse to argparse?

description: Pass on options from optparse to argparse


code: totalImgage = np.hstack((Image,Image2))

rawDescription: Sticking two pictures together in python


code:
for result in soup.find_all("div", {"class": "result"}):  # or soup.select("div.result")
    company = result.find("span", {"class": "company"}).get_text(strip=True)
    location = result.find("span", {"class": "location"}).get_text(strip=True)

    print(company, location)

rawDescription: python BeautifulSoup soup.findAll(), how to make search result match

description: Python BeautifulSoup soup.findAll(), how to make search result match


code:
from functools import total_ordering

@total_ordering
class MyString(str):
    sortmap = {x: i for i, x in enumerate("abdcfe")}

    def __lt__(self, other):
        return self.sortmap[self] < self.sortmap[other]

    # inherit __eq__ from str

    def __getitem__(self, i):
        return type(self)(super(MyString, self).__getitem__(i))

rawDescription: Inheriting from "str" class

description: Inheriting from "str" class


code:
from tkinter import *

class MyApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        fr = Frame(self)
        fr.pack()
        self.canvas  = Canvas(fr, height = 100, width = 100)
        self.canvas.pack()
        self.rect = self.canvas.create_rectangle(25, 25, 75, 75, fill = "white")
        self.do_blink = False
        start_button = Button(self, text="start blinking",
                              command=self.start_blinking)
        stop_button = Button(self, text="stop blinking",
                              command=self.stop_blinking)
        start_button.pack()
        stop_button.pack()

    def start_blinking(self):
        self.do_blink = True
        self.blink()

    def stop_blinking(self):
        self.do_blink = False

    def blink(self):
        if self.do_blink:
            current_color = self.canvas.itemcget(self.rect, "fill")
            new_color = "red" if current_color == "white" else "white"
            self.canvas.itemconfigure(self.rect, fill=new_color)
            self.after(1000, self.blink)

if __name__ == "__main__":
    root = MyApp()
    root.mainloop()

rawDescription: Tkinter, executing functions over time

description: Tkinter, executing functions over time


code:
import pandas as pd

events_list = ['Rain', 'Rain', 'Fog-Rain', 'Rain-Snow', 'Thunderstorm', 'Fog-Thunderstorm']

weather_df = pd.DataFrame(events_list, columns=['Events'])

print(weather_df)

rawDescription: Pandas split column into multiple

description: Pandas split column into multiple


rawDescription: How Accelerate factor function from SAGE


code: [i[1] for i in sorted(d.values())]

rawDescription: Return all the values of a specific index number


code:
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(3)
        self.setCentralWidget(self.table)
        data1 = ['row1','row2','row3','row4']
        data2 = ['1','2.0','3.00000001','3.9999999']

        self.table.setRowCount(4)

        for index in range(4):
            item1 = QtGui.QTableWidgetItem(data1[index])
            self.table.setItem(index,0,item1)
            item2 = QtGui.QTableWidgetItem(data2[index])
            self.table.setItem(index,1,item2)
            self.btn_sell = QtGui.QPushButton('Edit')
            self.btn_sell.clicked.connect(self.handleButtonClicked)
            self.table.setCellWidget(index,2,self.btn_sell)

    def handleButtonClicked(self):
        button = QtGui.qApp.focusWidget()
        # or button = self.sender()
        index = self.table.indexAt(button.pos())
        if index.isValid():
            print(index.row(), index.column())

rawDescription: How to add multiple QPushButtons to a QTableView?

description: Add multiple QPushButtons to a QTableView


code:
b = Bar()
b.write('Hello, World!')

rawDescription: Controlling child class method from parent class


rawDescription: python gather together ascii and utf-8 stuff

description: Python gather together ascii and utf-8 stuff


code:
#assuming that indexed times are in seconds
t.sort(inplace=True)
t.index = pd.to_datetime(t.index * 10e9) #to convert from nanoseconds to seconds
t.resample('s', how='sum').cumsum()

rawDescription: Python (Pandas): count of records between values at a given time (Packets in Flight)


code:
EnumWindows         = ctypes.windll.user32.EnumWindows
EnumWindowsProc     = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
IsWindowVisible     = ctypes.windll.user32.IsWindowVisible
IsZoomed            = ctypes.windll.user32.IsZoomed
GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow
GetShellWindow      = ctypes.windll.user32.GetShellWindow

rawDescription: Python: simple 'if' statement to tell you if the user has no windows maximized


code:
hash = sha256_crypt.encrypt("password", rounds=110000, salt='4QB3mR7z8SVQwVDt')
# '$5$rounds=110000$4QB3mR7z8SVQwVDt$hF/KhMEITeydgv58fXf2brManFYwhhy.dMqGnrkrLb1'

rawDescription: Verifying Python generated SHA256 strings using Ruby


code: axes.set_xticklabels(labels, fontdict=None, minor=False, **kwargs)

rawDescription: Equivalent function for xticks for an AxesSubplot object


rawDescription: How to set an attribute to a vector in rpy2

description: Set an attribute to a vector in rpy2


rawDescription: How to index pandas DataFrames by selecting times in a particular interval?

description: Index pandas DataFrames by selecting times in a particular interval


code:
def takes_iterable(func):
    generic = singledispatch(func)
    @generic.register(Iterable)
    def _(it):
        return [func(*args) for args in it]
    return generic

@takes_iterable
def mult(a, b):
    return a * b

rawDescription: can a python decorator make a function able to operate on single objects and collection objects intelligently?

description: Can a python decorator make a function able to operate on single objects and collection objects intelligently


code:
import requests
url = 'http://www.content.alternative.ac.nz/index.php/alternative/login/signIn'
r = requests.post(url, data={'username': 'username', 'password': 'password', 'remember': '1'})

rawDescription: python urllib2, passworded content and a null response

description: Python urllib2, passworded content and a null response


code:
import pandas as pd

def cumsum_limit(x):
    q = np.sum(x[:-1])
    if q > 0:
        q = q%5
    r = x[-1]
    if q+r <= 5:
        return q+r
    elif (q+r)%5 == 0:
        return 5
    else:
        return (q+r)%5

a = np.array([1,1,1,1,1,1,1,1,1,1]) # your example array

rawDescription: Reset cumsum if over limit (python)

description: Reset cumsum if over limit (python)


rawDescription: Button parameter “command” executes when declared, but not when pressed


code:
del h
del k
del m
del a

# At this point, there is still one active reference to the instance
# that we first created when we assigned it to name "a".

del g

# Now we have removed all references to that instance, so it gets deleted.

rawDescription: Python: pass by reference

description: Python: pass by reference


rawDescription: Python pandas timeseries resample giving unexpected results


code:
l = left.groupby('key')['lval'].apply(list)
l.name = 'lval'
l
r = right.groupby('key')['rval'].apply(list)
r.name = 'rval'

rawDescription: Merging dataframes with duplicate indices


code:
import lxml.html as lh

content='''\

pudding: peaches and cream

cheese: Epoisses and St Marcellin

'''

tree=lh.fromstring(content)
for elt in tree.xpath('//li[not(descendant::a[@class="new"])]/small/text()'):
    print(elt)

# pudding

rawDescription: lxml: how to discard all <li> elements containing a link with particular class?

description: Lxml: how to discard all <li> elements containing a link with particular class


rawDescription: Django view: Count specific value from model


rawDescription: How to check if I'm running in a shell (have a terminal) in Python?

description: Check if I'm running in a shell (have a terminal) in Python


code:
import os, unittest

class Tests():

    def suite(self): #Function stores all the modules to be tested

        modules_to_test = []
        test_dir = os.listdir('.')
        for test in test_dir:
            if test.startswith('test') and test.endswith('.py'):
                modules_to_test.append(test.rstrip('.py'))

        alltests = unittest.TestSuite()
        for module in map(__import__, modules_to_test):
            module.testvars = ["variables you want to pass through"]
            alltests.addTest(unittest.findTestCases(module))
        return alltests

if __name__ == '__main__':
    MyTests = Tests()
    unittest.main(defaultTest='MyTests.suite')

rawDescription: how to add dozen of test cases to a test suite automatically in python

description: Add dozen of test cases to a test suite automatically in python


code:
from mygeonames.models import Country
cc = Country.objects.all()
cc[0].capital

rawDescription: How to add capital to django-cities-light country model?

description: Add capital to django-cities-light country model


code: Weight[i] = Date[i] - Date[0]

rawDescription: Ranking with time weighting

description: Ranking with time weighting


code:
list(map(d.update, extras))
d

rawDescription: Python 3 map dictionary update method to a list of other dictionaries


code:
def SaveTextFile(self):
    save(self.file_path)     # Your code to save file

rawDescription: Return value from button click

description: Return value from button click


code:
# Python3 code:
import pandas as pd
import numpy as np
import treetaggerwrapper
import multiprocessing as mp

input_file = 'new_corpus.csv'
output_file = 'output3.csv'

''' Reading in the file '''
all_lines = []
with open(input_file) as f:
    for line in f:
        all_lines.append(line.strip().split('|', 1))

df = pd.DataFrame(all_lines[1:], columns = all_lines[0])

''' Multiprocessing '''

# Number of processes can be adjusted for better performance:
nproc = mp.cpu_count()

# Function to be run at the start of every subprocess.
# Each subprocess will have its own TreeTagger called pool_tagger.
def init():
    global pool_tagger
    pool_tagger = treetaggerwrapper.TreeTagger(TAGLANG='en')

# The actual job done in subprcesses:
def run(arr):
    out = np.empty_like(arr)
    for i in range(len(arr)):
        out[i] = pool_tagger.tag_text(arr[i])
    return out

# Splitting the input
lst_split = np.array_split(df.values[:,1], nproc)

with mp.Pool(processes = nproc, initializer = init) as p:
    lst_out = p.map(run, lst_split)

# Concatenating the output from subprocesses
df['POS-tagged_content'] =  np.concatenate(lst_out)

# Format fix:
def fix_format(x):
    '''x - a list or an array'''
    out = list(tuple(i.split('\t')) for i in x)
    return out
df['POS-tagged_content'] = df['POS-tagged_content'].apply(fix_format)

df.to_csv(output_file, sep = '|')

rawDescription: Optimizing function computation in a pandas column?


code:
rdb, temp = name.split('_', 1)
master, db = temp.rsplit('_', 1)

rawDescription: Python dictionary optimize this script

description: Python dictionary optimize this script


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

rawDescription: decoding and encoding Hebrew string in Python

description: Decoding and encoding Hebrew string in Python


rawDescription: I cannot seem to find the correct formatting spec for preceding zeroes in python


code:
for country in ["ireland", "england", "scotland"]:
    for num in [1, 2]:
        parse_xml(path.format(country, num))

rawDescription: Reading the same filename from multiple locations


code:
def polarize(im):
    return (im[:,:]>=numpy.mean(im,axis=(0,1)))*255

rawDescription: Polarizing image attempt--what's wrong?

description: Polarizing image attempt--what's wrong


code:
def insert(list1, var, i):
    newlist = []
    for idx in range(i):
        newlist.append(list1[idx])
    newlist.append(var)
    for idx in range(i, len(list1)-1):
        newlist.append(list1[idx])
    return newlist

rawDescription: insert element into list, move pre-existing elements

description: Insert element into list, move pre-existing elements


code:
import itertools

ranges = [range(r[0], r[1] + 1) if len(r) == 2 else r for r in parsed_ranges]
addresses = itertools.product(*ranges)

rawDescription: Python - Generate a list of IP addresses from user input


code:
def _build_delegate(name, attr, cls, type_):
    def f(*args, **kwargs):
        args = tuple(a if not isinstance(a, cls) else a.int_ for a in args)
        ret = attr(*args, **kwargs)
        if not isinstance(ret, type_) or name == '__hash__':
            return ret
        return cls(ret)
    return f

def delegated_special_methods(type_):
    def decorator(cls):
        for name, value in vars(type_).items():
            if (name[:2], name[-2:]) != ('__', '__') or not callable(value):
                continue
            if hasattr(cls, name) and not name in ('__repr__', '__hash__'):
                continue
            setattr(cls, name, _build_delegate(name, value, cls, type_))
        return cls
    return decorator

@delegated_special_methods(int)
class U32(object):
    def __init__(self, num=0, base=None):
        """Creates the U32 object.

        Args:
            num: the integer/string to use as the initial state
            base: the base of the integer use if the num given was a string
        """
        if base is None:
            self.int_ = int(num) % 2**32
        else:
            self.int_ = int(num, base) % 2**32
    def __coerce__(self, ignored):
        return None
    def __str__(self):
        return "<U32 instance at 0x%x, int=%d>" % (id(self), self.int_)

rawDescription: Python 3 __getattr__ behaving differently than in Python 2?


rawDescription: Custom simple Python HTTP server not serving css files


rawDescription: What is pythonic way to do dt[,y:=myfun(x),by=list(a,b,c)] in R?


rawDescription: how do i turn for loop iterator into a neat pythonic one line for loop

description: Turn for loop iterator into a neat pythonic one line for loop


code: fcntl(3, F_SETFL, O_RDWR)

rawDescription: What could I grep for in strace output from a gevent app to test whether it's using blocking network IO?


code:
for i in xrange(1, 4):
    for j in xrange(2, 6):
        setattr(Tests, "test_%r_%r" % (i, j), lambda self: self.check(i, j))

rawDescription: What does the lambda self: do

description: What does the lambda self: do


rawDescription: Building on "How to read and write a table / matrix to file with python?"


code:
import pipes
from subprocess import Popen, PIPE

cmd = ["ssh", self.host, "cat > " + pipes.quote(out_path)] # no '-tt'
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(in_string)

rawDescription: python subprocess communicate freezes

description: Python subprocess communicate freezes


rawDescription: Can I use a variable string to refer to a list?

description: Use a variable string to refer to a list


code:
W = Wrapped()
W.crawl_1()
W.crawl_2()
W.this_is_not_wrapped()

rawDescription: How to get a method called (decorator?) after every object method

description: Get a method called (decorator?) after every object method


rawDescription: Create Dictionary Of Lists from List of Dictionaries in Python


code: jsonify(eqtls=[e.serialize() for e in my_list_of_eqtls])

rawDescription: Flask jsonify a list of objects

description: Flask jsonify a list of objects


rawDescription: Pass variable between python scripts on different computers.


code:
import pandas as pd
import sys

input_string_book = [
"1|The Hunger Games",
"2|To Kill a Mockingbird",
"3|Pride and Prejudice",
"4|Animal Farm"]
input_string_book_df = pd.DataFrame(columns=('BookID','Title'))

input_string_rating = [
"101|1|1",
"102|2|2",
"103|3|3",
"104|4|4",
"105|1|5",
"106|2|1",
"107|3|2",
"108|4|3"]
input_string_rating_df = pd.DataFrame(columns=('ReaderID','BookID','Rating'))

input_string_reader = [
"101|M|1000|email",
"102|F|1001|mobile",
"103|M|1002|email",
"104|F|1003|mobile",
"105|M|1004|email",
"106|F|1005|mobile",
"107|M|1006|email",
"108|F|1007|mobile"]
input_string_reader_df = pd.DataFrame(columns=('ReaderID','Gender','PostCode','PreferComms'))

#for line in sys.stdin:
for line in input_string_book + input_string_rating + input_string_reader:
    try:

        line = line.strip()

        splits = line.split("|")

        if len(splits) == 2:
            input_string_book_df = input_string_book_df.append(pd.DataFrame([[splits[0],splits[1]]],columns=('BookID','Title')))
        elif len(splits) == 3:
            input_string_rating_df = input_string_rating_df.append(pd.DataFrame([[splits[0],splits[1],splits[2]]],columns=('ReaderID','BookID','Rating')))
        else:
            input_string_reader_df = input_string_reader_df.append(pd.DataFrame([[splits[0],splits[1],splits[2],splits[3]]]
            ,columns=('ReaderID','Gender','PostCode','PreferComms')))

    except:
        raise

l_concat_1 = input_string_book_df.merge(input_string_rating_df,on='BookID',how='inner')

l_concat_2 = l_concat_1.merge(input_string_reader_df,on='ReaderID',how='inner')

for each_iter in l_concat_2[['BookID', 'Title', 'ReaderID', 'Rating', 'Gender']].iterrows():
    print('%s\t%s\t%s\t%s\t%s' % (each_iter[1][0], each_iter[1][1], each_iter[1][2], each_iter[1][3], each_iter[1][4]))

rawDescription: Python MapReduce Hadoop Streaming Job that requires 3 input files?


code:
import time
for i in range(5):
    print('test '+str(i))
    for j in range(1,6):
        time.sleep(1)
        print("waiting for "+str(j) +" sec")
print("Have any test funcs been called")

rawDescription: Will a for loop that calls a function finish before any of the functions are called?


rawDescription: How to merge two JSONs

description: Merge two JSONs


code:
members = set()
members.add(1)
1 in members
2 in members

rawDescription: I've been using dictionary keys as membership markers. Is this a good idea?


code:
@app.route("/yourform/getinfo")
def show_sorted_info():
  return render_template("results.html")

rawDescription: How to make jinja 2 display different divs if different options are selected

description: Make jinja 2 display different divs if different options are selected


rawDescription: Read file in unknown directory

description: Read file in unknown directory


code:
import re
words = re.findall(r'\w+', somestring)

rawDescription: Python: finding the two words following a key word


code:
[col for col in df.columns if 'Value' in col]
df[[col for col in df.columns if 'Value' in col]].min(axis=1)

rawDescription: Defining x ticks in pandas

description: Defining x ticks in pandas


rawDescription: Getting each word from long list in python


code:
@app.route('/tip-amount')
def tip_calculator():
    meal = request.args.get('meal', type=int)
    if meal is None:
        # redirect back to form if the parameter is missing or not an integer
        return redirect(url_for('meal_total'))
    tax = 0.2
    tip = 0.15
    meal_total = meal + meal * tax
    tip = meal_total * 0.15
    return render_template('tip_amount.html', tip=tip)

rawDescription: How do I make this function redirect to a given html page?

description: Make this function redirect to a given html page


code:
pos = np.vstack(positions) # turn your Nx2 nested list -> Nx2 np.ndarray
x, y = pos.T # take the transpose so 2xN then unpack into x and y
ln, = plt.plot(x, y, STYLE, color=COLOR, label=LABEL)

rawDescription: How to remove the previous drawing in matplotlib, Python?

description: Remove the previous drawing in matplotlib, Python


code:
import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = "right")
font = tkFont.Font(family="Helvetica", size=20, weight = tkFont.BOLD)

for i in xrange(6):
    f = Tkinter.Frame(right,width=50,height=50)
    b = Tkinter.Button(f, text = str(i), font = font)

    f.rowconfigure(0, weight = 1)
    f.columnconfigure(0, weight = 1)
    f.grid_propagate(0)

    f.grid(row = i/3, column = i%3)
    b.grid(sticky = "NWSE")

top.mainloop()

rawDescription: Displaying square Tkinter.Button's?

description: Displaying square Tkinter.Button's


code:
for i, val in enumerate(lst[2:]):
    print(i, val)

rawDescription: For count from 2

description: For count from 2


code:
import threading
import time
import sublime
import sublime_plugin

def buildsnippetURL():
    return ""

def getsnippets(snippet_url):
    time.sleep(3)
    return ""

class SyncsnippetsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        syncsnippetsThread = SyncsnippetsThread(self, edit)
        syncsnippetsThread.start()

class SyncsnippetsThread(threading.Thread):
    def __init__(self, cmd, edit):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.edit = edit

    def buildLexerDict(self,snippets):
        lexers = snippets[0]['user']['lexers']
        lexer_dict = {}
        for lexer in lexers:
            lexer_dict[lexer] = []
        return lexer_dict

    def buildsnippetsContextDict(self,snippets,lexer_dict):
        snippets_dict = lexer_dict
        for snippet in snippets:
            snippets_dict[snippet['lexer']].append({"id":str(snippet['id']),
                                         "title":snippet['title']})
        return snippets_dict

    def run(self):
        snippet_url = buildsnippetURL()
        snippets_count = 1;
        snippets = getsnippets(snippet_url)

        """
        context_menu = '['
        context_menu += '\n\t{ "caption": "snippets", "id": "file", "children":'
        context_menu += '\n\t\t['
        if snippets == None:
            {"caption":"No snippets available"}
        else:
            snippets = snippets['objects']
            lexers = self.buildLexerDict(snippets)
            snippets_dict = self.buildsnippetsContextDict(snippets, lexers)
            for j,key in reversed(list(enumerate(reversed(snippets_dict.keys())))):
                ... loop through JSON and create menu ...
                if j == 0:
                    context_menu += ''
                else:
                    context_menu += ','
        context_menu += '\n\t\t]'
        context_menu += '\n\t}'
        context_menu += '\n]'
        f = open(sublime.packages_path() + '\snippetSync\\Context.sublime-menu', 'w')
        f.write(context_menu)
        f.close
        """

        sublime.set_timeout(lambda: self.callback(snippets_count), 1)

    def callback(self, snippets_count):
        self.cmd.view.set_status('snippet', 'snippet Sync: Added ' + str(snippets_count)  + ' snippets from your account.')
        sublime.set_timeout(lambda: self.cmd.view.erase_status('snippet'), 3000)

rawDescription: Python threading in for loop

description: Python threading in for loop


rawDescription: pandas dataframe groupby and get nth row

description: Pandas dataframe groupby and get nth row


code:
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))

rawDescription: tkinter python maximize window

description: Tkinter python maximize window


code:
trues, falses = partition(lambda x: x > 10, [1,4,12,7,42])
trues
falses

rawDescription: python equivalent of filter() getting two output lists (i.e. partition of a list)

description: Python equivalent of filter() getting two output lists (i.e. partition of a list)


code:
def my_func(acc, elem):
    return acc and elem > 5

reduce(my_func, my_list, True)

rawDescription: python reduce accum as an argument

description: Python reduce accum as an argument


code:
import sys
import pexpect # $ pip install pexpect

output, exitstatus = pexpect.runu('apt-get download firefox',
                                  logfile=sys.stdout,
                                  withexitstatus=1)

rawDescription: Last unbuffered line can't be read

description: Last unbuffered line can't be read


code:
a_foo = Foo()
a_foo.spam
a_foo.spam = 3
a_foo.spam

rawDescription: which to use: class variables versus classmethod?

description: Which to use: class variables versus classmethod


code:
from colorsys import hsv_to_rgb

import random
def data_to_color(x, y):
    return (
        (x/width)**(0.5+random.random()*2),
        (y/height)**3,
        (x/width*y/height)*0.6 + random.random()*0.4
    )

colors = [[data_to_color(x, y) for x, y in row] for row in data]
colors = numpy.array(colors)
colors.shape
#>>> (500, 300, 3)

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


rawDescription: create timestemps for given data

description: Create timestemps for given data


rawDescription: How to show help for all subparsers in argparse?

description: Show help for all subparsers in argparse


rawDescription: Is there a way to remove all characters except letters in a string in Python?


code:
a = [{1: u'100'}, {2: u'200'}, {3: u'300', 4: "not unicode"}]
[{k:float(v) if isinstance(v, unicode) else v for k,v in d.iteritems()} for d in a]

rawDescription: How to change value for item in a list of dict in python in a simple way?

description: Change value for item in a list of dict in python in a simple way


code:
imgtag  = re.match(r'<img.*?>',line)
if imtag:
    print("yo it's a {}".format(imgtag.group(0)))

rawDescription: how do i return a string from a regex match in python

description: Return a string from a regex match in python


code:
def save_session(self, response):
    if self.session is None or not self.session.modified:
        return

rawDescription: Persisting Webapp2 Sessions on GAE

description: Persisting Webapp2 Sessions on GAE


code:
c2_setup='''
def lpf(num):
    while num % 2 == 0:
        num /= 2
    if num == 1:
        return 2
    else:
        i = 3
        while num > 1:
            if num % i == 0:
                num /= i
            else:
                i += 2
        return i
'''
c2_run='l = lpf(600851475143)'
timeit.timeit(setup=c2_setup, stmt=c2_run, number=10000)

rawDescription: Why is function-less slower?

description: Why is function-less slower


code: get_ipython().run_cell_magic(u'R', u'-o x', u'x <- c(1,2,3)')

rawDescription: Keep cells or magic functions from saving to python script


code:
# forms.py
class TicketForm(forms.ModelForm):
    def __init__(self, current_user, *args, **kwargs):
        super(TicketForm, self).__init__(*args, **kwargs)
        self.fields['event'].queryset = Event.objects.filter(creator =
             current_user)

rawDescription: Django model form with selected rows

description: Django model form with selected rows


code:
def __setattr__(self, name, value):
    raise AttributeError('''Can't set attribute "{0}"'''.format(name))

rawDescription: How to make class immutable in python?

description: Make class immutable in python


code:
result = max_year.join(result)
del result['YEAR']

#                   MONTH  SALARY  SUM(DAYS)
# JOB    NAME YEAR
# Employ Mary 2014      1     200         20
#             2014      2     190         20
# Worker Bob  2014      1     210         29
#             2014      2      80         29

rawDescription: Pandas multiple index with multiple aggregate functions


code:
D
dist

rawDescription: Using ARPACK solving eigenvalueproblem, but getting inconsistent results with Matlab


code:
from random import randint
def num_random():
    counter = 0
    areas = []
    while (counter <= 99):
       counter=counter+1
       base=randint(1,100)
       height=randint(1,100)
       area = base*height/2
       areas.append(area)
    data(max(areas))

def data(area):
    print("area=",area)

num_random()

rawDescription: How can I know what's the largest number from a while loop in python?

description: Know what's the largest number from a while loop in python


code:
def EmptyVar(lst):
    return [type(i)() for i in lst]

rawDescription: Empty a variable without destroying it

description: Empty a variable without destroying it


code:
browser.execute_script("$('body').empty()")
browser.evaluate_script("4+4") == 8

rawDescription: What's the easiest way to download the source of a webpage in python? (After javascript has been applied)


code: all_groups = visitors | older_groups

rawDescription: How to sort a Django queryset by a conditional aggregation of related items?

description: Sort a Django queryset by a conditional aggregation of related items


rawDescription: open bin file and convert ascii to hex

description: Open bin file and convert ascii to hex


code:
import datetime

now = datetime.datetime.now()
yearStart = datetime.datetime(now.year, 1, 1)
diffTime = now - yearStart
yearSeconds = int(diffTime.total_seconds())

rawDescription: Writing NetCDF time variable from start of year


code:
for attr in ("video_codec", "resolution_width", "resolution_height", "video_bitrate",
             "ratio", "profile", "audio_codec", "audio_channels", "audio_bitrate"):
    if attr in profile:
        setattr(self, attr, profile[attr])

rawDescription: How to simplify this mass of similar ifs

description: Simplify this mass of similar ifs


code:
from urlparse import urljoin
import requests

url = "https://news.google.co.uk"

def get_sections(start, sections):
    '''Pulls the links for each sections we pass in, i.e World, Business etc...'''
    cont = requests.get(start).content
    xml = fromstring(cont, HTMLParser())
    # links are all in the  a tag inside the esc-layout-table table
    # where the a tag class is article
    secs = xml.xpath("//span[@class='section-name']")
    for sec in secs:
        _sec = sec.text.rsplit(None, 1)[0].lower().rstrip(".")
        if _sec in sections:
            yield _sec, urljoin(url, sec.xpath(".//parent::a/@href")[0])

def get_section_links(sec_url):
    ''''Get all links from individual sections.'''
    cont = requests.get(sec_url).content
    xml = fromstring(cont, HTMLParser())
    seen = set()
    for url in xml.xpath("//div[@class='section-stream-content']//a/@url"):
        if url not in seen:
            yield url
        seen.add(url)

    # set of sections we want
s = {'business', 'world', "sports", "u.k"}

for sec, link in get_sections(url, s):
    for sec_link in (get_section_links(link)):
        print(sec, sec_link)

rawDescription: Why does my webcrawler not follow into the next link containing keywords


code: results = [train_dict.get(x, sample) for x in test]

rawDescription: Looking for a quick way to speed up my code


code:
a = Decimal(2)
one = Decimal(1)
b = a * (a+one) * (a+one+one)
c = Decimal(4) / b
type(c)
pi = pi + c
pi

rawDescription: Why has my program "stopped" working?

description: Why has my program "stopped" working


code:
import math, time
from concurrent import futures

PRIMES = [112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419, 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def bench(f):
    start = time.time()
    f()
    elapsed = time.time() - start
    print("Completed in {} seconds".format(elapsed))

def concurrent():
    with futures.ProcessPoolExecutor() as executor:
        values = list(executor.map(is_prime, PRIMES))

def listcomp():
    values = [is_prime(x) for x in PRIMES]

rawDescription: Python and performance of list comprehensions


code:
class Agent(Thread):
    mylock = Lock()
    def write_result(self):
        self.mylock.acquire()
        try:
            ...
        finally:
            self.mylock.release()

rawDescription: Multithreaded Resource Access - Where Do I Put My Locks?


code:
for tag in ['blockquote', 'img', ... ]:
    soup.find(tag).decompose()

rawDescription: Extract content with BeautifulSoup and Python


code:
f = open("filename", "r")

buff = ""
array = []
for line in f:
    buff += line
    if "}" in line:
        start = buff.index("{")
        end = buff.index("}")
        array.append([float(val.strip()) for val in buff[start+1:end].split(",")])
        buff = buff[end+1:]

f.close()

print(array)

rawDescription: Matrix converting to a list in python

description: Matrix converting to a list in python


rawDescription: multiple conditioned slicing (pandas dataframe)

description: Multiple conditioned slicing (pandas dataframe)


code:
f1 = make_replacer('foo, bar / moo, car')
f2 = make_replacer('foo, dar / moo, ear')
f1('foo$$moo')
f2('foo$$moo')

rawDescription: Pythonically creating a string-modifying lambda function dynamically based off of input recieved


code: data = np.loadtxt('data.dat', delimiter='\t', unpack=True, comments='#')

rawDescription: How to import uncommented text from a file in Python?

description: Import uncommented text from a file in Python


code:
changed = [d['name'] for d in listB
           if d['name'] in auxdict and d['val'] != auxdict[d['name']]]

rawDescription: List of Dicts comparision to match between lists and detect value changes in Python


code: df.filter(regex=r'\.Length$', axis=1)

rawDescription: Identifying multiple columns by name in Pandas


code:
pattern=re.compile(r'\bdata-id="(\d+)"')
s = 'data-id="48859672"'
pattern.search(s).group(1)

rawDescription: How could I get a part of a match string by RegEx in Python?


code: a_vals = [y for x,y in coords[::2]]

rawDescription: Extracting 2nd element from multiple sub-lists with stepping


code:
# Builds objects on instantiation for a vegetable and color
class Veg:
    def __init__(self, name, color):
        self.name = name
        self.color = color
        print('You have created a new', self.color, self.name, end='.\n')

    def __str__(self):
        return 'One {} {}'.format(self.color, self.name)

# Function to create a new vegetable and store it in a list
def createVeg():
    name = input('What is the name of the Vegetable? ')
    color = input('What color is the vegetable? ')

    vegList.append(Veg(name, color))
    return

# Initialize variables
vegList = []
choice = 'y'

# Main loop
while choice == 'y':
    print('Your basket contains:\n')
    for veg in vegList:
        print(veg)
    choice = input('Would you like to add a new vegetable? (y / n) ')
    if choice == 'y':
        createVeg()
    if choice == 'n':
        break

print('Goodbye!')

rawDescription: Instantiating Python objects, and using lists


code:
from rcdtype import *
Point = recordtype('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt1 = Point(1.0, 5.0)
pt1.x = 2.0
print(pt1[0])

rawDescription: What are "named tuples" in Python?

description: What are "named tuples" in Python


rawDescription: How to add raw input values in Python?

description: Add raw input values in Python


code:
for digit in '1234':
    for i in range(len(letters)):
        s = list(letters)
        s[i] = digit
        print(''.join(s))

rawDescription: Change one character at a time in a string, don't change the string?


code:
def from_parent(cls, parent):
    return cls(revert_change(parent.a), revert_change(parent.b))
    # Or, if you save the original values
    # return cls(parent.orig_a, parent.orig_b)

rawDescription: initialize child class with parent

description: Initialize child class with parent


rawDescription: iterating over list and concatenating alphabetical sequence in Python

description: Iterating over list and concatenating alphabetical sequence in Python


code:
th = np.linspace(0, 2*np.pi, 128)
df = pd.DataFrame({'sin': np.sin(th),
                   'shift +': np.sin(th + np.pi / 3),
                   'shift -': np.sin(th - np.pi / 3)}, index=th)

fig, ax = plt.subplots()
from cycler import cycler
style_cycle = cycler('color',['r', 'black', 'pink']) + cycler('marker', 'sxo')
#style_cycle = [{'color': 'r', 'marker': 's'},
#               {'color': 'black', 'marker': 'x'},
#               {'color': 'pink', 'marker': 'o'}]
arts = pandas_plot(ax, df, style_cycle, markevery=10)
vlns = []
for x in np.arange(1, 7) * np.pi/3:
    vlns.append(plt.axvline(x, color='k', linestyle=':'))
plt.axhline(0, color='k', linestyle=':')

rawDescription: IPython Notebook/Matplotlib: Interactive show/hide graphs on a plot, is it possible?


code: import types

rawDescription: How to distinguish bound method or a function from a class?

description: Distinguish bound method or a function from a class


code:
obj = MyModel.objects.annotate(item_one_count=Count('items_one')) \
             .annotate(item_two_count=Count('items_two')) \
             .annotate(item_three_count=Count('items_three')) \
             .get(...)

rawDescription: Avoiding multiple queries for multiple counts


code:
self.aMessages = {"bMessage1": [False, "This is the message 1", 0],
                  "bMessage2": [False, "This is the message 2", 0],
                  "bMessage3": [False, "This is the message 3", 0],
                  "bMessage4": [False, "This is the message 4", 0],
                  "bMessage5": [False, "This is the message 5", 0]}

rawDescription: Message displaying in QListWidget/View on boolean condition


code:
import datetime

class Clock(object):
    def __init__(self):
        self.reset()
    def reset(self):
        self.accumulator = datetime.timedelta(0)
        self.started = None
    def start_stop(self):
        if self.started:
            self.accumulator += (
                datetime.datetime.utcnow() - self.started
            )
            self.started = None
        else:
            self.started = datetime.datetime.utcnow()
    @property
    def elapsed(self):
        if self.started:
            return self.accumulator + (
                datetime.datetime.utcnow() - self.started
            )
        return self.accumulator
    def __repr__(self):
        return "<Clock {} ({})>".format(
            self.elapsed,
            'started' if self.started else 'stopped'
        )

rawDescription: How should a clock object be made in Python?


code:
class Tab(gtk.HBox):
    def __init__(self, child):
        self.child = child

self.notebook.append_page(Tab(myWidget), gtk.Label("title"))

def pageSelected(self, notebook, page, pagenum):
    box = notebook.get_nth_page(pagenum)
    box.child.reparent(box)

rawDescription: How to get (childless) “tabs” in a pygtk application

description: Get (childless) “tabs” in a pygtk application


code:
import pandas as pd
x = pd.to_datetime(data).time

pd.Series(x)

rawDescription: Convert Time Column to UTC Time, no date


code:
d = defaultdict(lambda: defaultdict(list))
d
d['alex']['blue'].append(3)
d['alex']['blue'].append(4)
d['liza']['green'].append(2)
d
d.keys()
d['alex'].keys()
d['alex']['blue']

rawDescription: using nested loops in order to group data in a csv

description: Using nested loops in order to group data in a csv


rawDescription: Double assignment in python

description: Double assignment in python


code:
subprocess.Popen('start dir', shell=True)

subprocess.Popen('start cmd /C dir', shell=True)

rawDescription: Executing a program from python so that it opens in separate cmd.exe window


code:
from functools import partial
setCallback(partial(myObj.callbackFunction), param="x")

rawDescription: Python callback working with functions but not methods


rawDescription: defaultdict one-step initialization

description: Defaultdict one-step initialization


code:
concat = lambda iterable: list(itertools.chain.from_iterable(iterable))

polys = concat(path.to_polygons() for path in paths)
lc = PolyCollection(polys, edgecolor='black',
                    facecolor='green', closed=False)

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code:
import re
versionstring = 'version_4.11.2-2-1.4'
map(int, re.findall(r'\d+', versionstring))

rawDescription: Cleanest way to obtain a list of the numeric values in a string


code: data_dict = dict(data)

rawDescription: How to load a npz file in a non-lazy way?

description: Load a npz file in a non-lazy way


code:
data = [chr(int(x, base=2)) for x in bytes]
output.write(''.join(data))

rawDescription: What is the most efficient way to write in binary output in python?


code:
import itertools

def behind(it):
    # it = iter(it)  # to handle non-iterator iterable.
    i1, i2 = itertools.tee(it)
    next(i1)
    return (next(i2) for x in i1)

rawDescription: Iterator that excludes the last element

description: Iterator that excludes the last element


rawDescription: Subsetting data in python

description: Subsetting data in python


code:
#-*- coding:utf-8 -*-
#!/usr/bin/env python

import xml.dom.minidom

info = '''
<Head>
<child>this is text for child</child>
</Head>
'''

dom = xml.dom.minidom.parseString(info)
dom.firstChild.tagName = 'parent'
# save it to any file you want
xml_file = 'C:\\temp\\lch.xml'
f = open(xml_file, 'wb')
dom.writexml(f)
f.close()

rawDescription: Set XML root with libxml2 Python bindings


code:
import timeit, re, random
tests = [''.join([chr(random.randrange(256)) for _ in range(2)]) for _ in range(1000)]
def test_str_isalpha(s):
    return len(s) == 2 and s.isalpha()

def test_regex(s, pattern=re.compile('^[a-zA-Z]{2}$')):
    return pattern.match(s) is not None

timeit.timeit('for s in tests: test(s)', 'from __main__ import tests, test_str_isalpha as test', number=10000)
timeit.timeit('for s in tests: test(s)', 'from __main__ import tests, test_regex as test', number=10000)

rawDescription: Validate a two characters code using python


rawDescription: Can I find which parameters are "pre-assigned" in python?

description: Find which parameters are "pre-assigned" in python


code:
def load_words(file1):
    answer = collections.defaultdict(list)
    for line in file1:
        line = line.strip()
        if line not in answer[line[0]]:
            answer[line[0]].append(line)
    return answer

rawDescription: dictionary help for python using a file

description: Dictionary help for python using a file


rawDescription: How to remove parenthesis from elements in a list (Python)

description: Remove parenthesis from elements in a list (Python)


code: data

rawDescription: python add two list and createing a new list

description: Python add two list and createing a new list


rawDescription: Count the multiple occurrences in a set

description: Count the multiple occurrences in a set


code:
def euclidean_dist3(x1, x2):
    assert(len(x1) == len(x2))

    x1 = np.array(x1)
    x2 = np.array(x2)

    diff = x1 - x2

    squared = np.transpose(diff) * diff

    summed = sum(squared)

    norm = np.sqrt(summed)

    return norm

rawDescription: How to vectorize array operations in Python

description: Vectorize array operations in Python


code:
p.wait()
p.returncode

rawDescription: Python subprocess.Popen strange behavior


rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
from itertools import chain

def chunk(s):
    """Split a string on whitespace or hyphens"""
    return chain(*(c.split("-") for c in s.split()))

def process(latin, gloss, trans):
    chunks = zip(chunk(latin), chunk(gloss))

rawDescription: Using Python to count morphemes in a file & list them in columns


rawDescription: Best Way to Convert a Dictionary of Dictionaries into a tab file


code:
import numpy as np
import cv
from PIL import Image

# open the image
img = Image.open('./pic.png', 'r')

r,g,b, alpha_channel = img.split()

mask = np.array(alpha_channel)

# all elements in alpha_channel that have value 0
# are set to 1 in the mask matrix
mask[alpha_channel==0] = 1

# all elements in alpha_channel that have value 100
# are set to 0 in the mask matrix
mask[alpha_channel==100] = 0

rawDescription: How to create Mask matrix variable for OpenCV minMaxLoc function in Python?

description: Create Mask matrix variable for OpenCV minMaxLoc function in Python


rawDescription: convert list of strings to numpy list of lists

description: Convert list of strings to numpy list of lists


rawDescription: Pandas, unexpected behavior of .resample('B')


code:
if clientKey not in data:
    data[clientKey] = [ref]   # single-item list

rawDescription: Cannot append string to dictionary key

description: Cannot append string to dictionary key


rawDescription: How to get n elements of a list not contained in another one?

description: Get n elements of a list not contained in another one