code:
import zlib

decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
data = decompressor.decompress(response_body)

rawDescription: HTTP response body is obfuscated

description: HTTP response body is obfuscated


code:
def two_tier_dict_init(tier1, tier2, value_factory):
    return {t1: {t2: value_factory() for t2 in tier2} for t1 in tier1}

rawDescription: Why are values of a two-level dictionary all pointing to the same object in Python 2.7?


rawDescription: Selenium not working to switch tabs and extracting url


code:
answers_string = soup.findAll("input", {"id":"hdnAjaxImageCacheKey"})[0]["value"]
answers = answers_string[::-1][17:22].upper()

rawDescription: Python BeautifulSoup: Text from the html (web) page not shown while soup.find_all(..)


rawDescription: read_csv with missing/incomplete header or irregular number of columns

description: Read_csv with missing/incomplete header or irregular number of columns


code:
import urlparse
url = 'http://redirect.tinyurl.com/api/click?key=a7e37b5f6ff1de9cb410158b1013e54a&out=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fprofile%2FA3B4EO22KUPKYW&loc=&cuid=0072ce987ebb47328d22e465a051ce7&opt=false&format=txt'
try:
    out = urlparse.parse_qs(urlparse.urlparse(url).query)['out'][0]
    print(out) #http://www.amazon.com/gp/profile/A3B4EO22KUPKYW
except Exception as e: # dont catch all
    print('not found')

rawDescription: Find tiny url final redirected url

description: Find tiny url final redirected url


rawDescription: In line.split('+')[-1] what does the -1 in the square brackets indicate in Python


code:
import os, os.path, shutil

src="G:\\TestCopy"
dst="D:\\TestCopy"

def copy_tree(srcpath, dstpath):
    print(srcpath)
    if not os.path.exists(dstpath):
        os.makedirs(dstpath)
    for candidate in os.listdir(srcpath):
        srccan = os.path.join(srcpath, candidate)
        dstcan = os.path.join(dstpath, candidate)
        if os.path.isdir(srccan):
            copy_tree(srccan, dstcan)
        else:
            shutil.copyfile(srccan, dstcan)

copy_tree(src, dst)

rawDescription: Python: recursively copy batch of directories


code:
def _get_server(self, key):
    if isinstance(key, tuple):
        serverhash, key = key
    else:
        serverhash = serverHashFunction(key)

    for i in range(Client._SERVER_RETRIES):
        server = self.buckets[serverhash % len(self.buckets)]
        if server.connect():
            #print "(using server %s)" % server,
            return server, key
        serverhash = serverHashFunction(str(serverhash) + str(i))
    return None, None

rawDescription: How does django handle multiple memcached servers?


code: ['Jane', 'Rachel', 'Beatrix']

rawDescription: Pythonic way to return interval from a list


code:
if middle == 'Missing':
    middle = ""

rawDescription: Using a for loop to concatenate columns in Pandas


rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


code:
# in project/app/context_processors.py
from app.models import Product

def top_products(request):
    return {'top_products': Products.objects.all()} # of course some filter here

rawDescription: How can I send data to a base template in Django?

description: Send data to a base template in Django


rawDescription: Efficient product of 1D array and 3D array along one dimension - NumPy


code:
conv = np.convolve([-1.,1],weighted_sum, mode='same')
pl.plot(conv)

rawDescription: How can I extract this obvious event from this image?

description: Extract this obvious event from this image


code:
import hdf5storage # get code on https://pypi.python.org/pypi/hdf5storage/0.1.3

matcontent = {}
matcontent[u'some_numbers'] = [10, 50, 20] # each key must be a unicode string
hdf5storage.write(matcontent, '.', 'test.mat', store_python_metadata=False, matlab_compatible=True)

rawDescription: Create .mat v7.3 files from Python using hdf5storage


code:
{'department': u'AFRCST - AFRICAN STUDIES', 'course': u'201A', 'section': u'1 - LYDON'}
{'department': u'AFRKLA - AFRICAN LANGUAGES', 'course': u'1A', 'section': u'1 - TA'}
{'department': u'AFRKLA - AFRICAN LANGUAGES', 'course': u'150A', 'section': u'1 - FANTA, A.A.'}
{'department': u'AFROAM - AFRO-AMERICAN STUDIES', 'course': u'6', 'section': u'1 - STREETER, C.A.'}
{'department': u'AFROAM - AFRO-AMERICAN STUDIES', 'course': u'M10A', 'section': u'1 - LYDON, G.E.'}
{'department': u'AFROAM - AFRO-AMERICAN STUDIES', 'course': u'M102', 'section': u'1 - LEWIS, L.I.'}
{'department': u'AFROAM - AFRO-AMERICAN STUDIES', 'course': u'M103A', 'section': u'1 - PRICE, Z.F.'}
{'department': u'AFROAM - AFRO-AMERICAN STUDIES', 'course': u'M104A', 'section': u'1 - YARBOROUGH'}
...

rawDescription: Can Selenium WebDriver click on all combinations from drop down menu


code:
import psycopg2
import pandas.io.sql as pdsql

conn = psycopg2.connect(...)

the_frame = pdsql.read_frame("SELECT * FROM %s;" % name_of_table, conn)

rawDescription: Getting data from table in database

description: Getting data from table in database


code:
lower = Vertex()
higher = Vertex()

rawDescription: A way to pass milions of items in python to C program many times in rapid succesion


code:
['Registration Number: ', ' CS 2047103']
['Name of the Candidate: ', 'PATIL SANTOSH KUMARRAO        ']
['Examination Paper: ', 'CS - Computer Science and Information Technology']
['Marks Obtained: ', '75.67 Out of 100']
['GATE Score: ', '911']
['All India Rank: ', '34']
['No of Candidates Appeared in CS: ', '156780']
['Qualifying Marks for CS: ', '\r\n\t\t\t\t\t']
['General', 'OBC ', '(Non-Creamy)', 'SC / ST / PD ']
['31.54', '28.39', '21.03 ']

rawDescription: HTML Parsing using Python

description: HTML Parsing using Python


rawDescription: How to get pyparser to work in a particular form

description: Get pyparser to work in a particular form


code: self.myFoo = types.MethodType(myFoo, self)

rawDescription: python pass self to referenced function

description: Python pass self to referenced function


code:
import httplib, urllib2

class HTTPSClientAuthHandler(urllib2.HTTPSHandler):

    def __init__(self, key, cert):
        urllib2.HTTPSHandler.__init__(self)
        self.key = key
        self.cert = cert
    def https_open(self, req):
        #Rather than pass in a reference to a connection class, we pass in
        # a reference to a function which, for all intents and purposes,
        # will behave as a constructor
        return self.do_open(self.getConnection, req)
    def getConnection(self, host, timeout=300):
        return  httplib.HTTPSConnection(host,
                                             key_file=self.key,
                                             cert_file=self.cert,
                                             timeout=timeout)

rawDescription: Use python to access a site with PKI security


code: list2 = [[dict([tup]) for tup in zip(*sublist)] for sublist in zip(list1[0::2], list1[1::2])]

rawDescription: how to convert two-dimensional list to another list with dict as elements

description: Convert two-dimensional list to another list with dict as elements


code:
self.stDate = datetime.datetime.now()
self.endDate = datetime.datetime.now() - datetime.timedelta(days=1000)

rawDescription: Retrieve data from mongodb based on date condition in pymongo


code: print("walrus", end=" ", flush=True)

rawDescription: Python waits to print incomplete lines?

description: Python waits to print incomplete lines


code:
class MyView(View):
    def get_template_names(self):
        if self.request.user.get_profile().type == 'foo':
            return ['path/to/foo_profile.html']
        elif self.request.user.get_profile().type == 'bar':
            return ['path/to/bar_profile.html']
        else:
            return ['path/to/generic_profile.html']

rawDescription: Show different profile based on user type


code:
Output
{
  "anotherName": [
    {
      "anArray": [
        {
          "anotherKey": "value",
          "key": "value"
        },
        {
          "anotherKey": "value",
          "key": "value"
        }
      ]
    }
  ],
  "name": [
    {
      "someKey": "some Value"
    },
    {
      "someKey": "another value"
    }
  ]
}

rawDescription: Remove whitespaces and newlines from JSON file


code: filter(None, ilist)

rawDescription: filter lists of lists by taking out items less than a certain length - more pythonic way?

description: Filter lists of lists by taking out items less than a certain length - more pythonic way


code:
from django.http import HttpResponse
import datetime
from pprint import pformat

def current_datetime(request):
    now = datetime.datetime.now()
    return HttpResponse(pformat(now), mimetype="text/plain")

rawDescription: django generic templates

description: Django generic templates


code:
b = input('Enter word: ')
for letter in b:
 with open('d:\word_list.txt', 'r') as inF:
  for item in inF:
   if item.startswith(letter):
    print(item)

rawDescription: searching in text file word list and check all the words that start with each letter I input

description: Searching in text file word list and check all the words that start with each letter I input


code:
import blocktrail, time

class Bit():
    def __init__(self, key, secret, net, retry_fail=1, update=60,max_fail=10):
        self.nonce_list = []
        self.seen = set()
        self.key = key
        self.secret = secret
        self.net = net
        self.key = key
        self.retry_fail = retry_fail
        self.update = update
        self.max_fails = max_fail

    def connect(self):
          return blocktrail.APIClient(api_key=self.key, api_secret=self.secret, network=self.net, testnet=False)

    def run(self):
        while True:
            if not self.max_fails:
                break
            try:
                client = self.connect()
                latest_block = client.block_latest()
            except blocktrail.exceptions.MissingEndpoint as e:
                self.max_fails -= 1
                print("Error: {}\n sleeping for {} second(s) before retrying".format(e.msg, self.retry_fail))
                time.sleep(self.retry_fail)
                continue
            nonce = latest_block['nonce']
            if nonce not in self.seen:
                self.nonce_list.append(nonce)
                self.seen.add(nonce)
            print(self.nonce_list)
            time.sleep(self.update)

rawDescription: Creating a list in python using the same string but with different values attached to it


code:
@asyncio.coroutine
def make_clients(nb_clients, delay):
    futures = []
    for client_id in range(nb_clients):
        url = WS_CHANNEL_URL.format(client_id=client_id)
        coro = WebSocketClient(client_id, url).run()
        futures.append(asyncio.ensure_future(coro))
        yield from asyncio.sleep(delay)
    yield from asyncio.wait(futures)

rawDescription: Gradually create async tasks and wait for all of them to complete


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

def bland_altman_plot(data1, data2, *args, **kwargs):
    data1     = np.asarray(data1)
    data2     = np.asarray(data2)
    mean      = np.mean([data1, data2], axis=0)
    diff      = data1 - data2                   # Difference between data1 and data2
    md        = np.mean(diff)                   # Mean of the difference
    sd        = np.std(diff, axis=0)            # Standard deviation of the difference

    plt.scatter(mean, diff, *args, **kwargs)
    plt.axhline(md,           color='gray', linestyle='--')
    plt.axhline(md + 1.96*sd, color='gray', linestyle='--')
    plt.axhline(md - 1.96*sd, color='gray', linestyle='--')

rawDescription: Bland-Altman plot in Python

description: Bland-Altman plot in Python


code:
file = open('/path/to/file')
for line in file:
    process_line(line)

    # No way of telling if this is the last line!

rawDescription: What is the pythonic way to detect the last element in a python 'for' loop?


code:
for col in df.columns:
    if len(df[col].unique()) == 1:
        df.drop(col,inplace=True,axis=1)

rawDescription: quickly drop dataframe columns with only one distinct value

description: Quickly drop dataframe columns with only one distinct value


code:
a, b, c = np.random.rand(3, 4, 5)
a, b  = np.arange(12).reshape(2,-1)

rawDescription: assigning an object to multiple variables - python

description: Assigning an object to multiple variables - python


rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


rawDescription: Newbie ?: is this a variable, function, or what?


code: foo(some, params)

rawDescription: How to toggle the action of a decorator in Python3

description: Toggle the action of a decorator in Python3


code:
class StringInside(object):

    def __init__(self, data=''):
        self._data = []
        self._data.extend(data)

    def write(self, data):
        self._data.extend(data)

    def read(self, start=None, stop=None):
        return ''.join(self._data[start:stop])

    def __getitem__(self, key):
        return ''.join(self._data[key])

rawDescription: subclass str, and make new method with same effect as +=

description: Subclass str, and make new method with same effect as +=


rawDescription: hasAttribute in lxml?

description: HasAttribute in lxml


code: map(function,iterable)

rawDescription: Python FTP Upload Multiple Files at Once


code:
#plot it
ax = plt.subplot(111)
ax.bar(bin, data, width, color='r')
plt.xlim([0,bin.size])
plt.show()

rawDescription: Annoying white space in bar chart (matplotlib, Python)


code:
seen = set()
[ [y for y in x if y not in seen and not seen.add(y)] for x in a]

rawDescription: Delete duplicate tuples from list of list in Python


rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
from nanomsg import Socket, PAIR
sock = Socket(PAIR)
sock.bind('inproc://bob')
sock.send(dir)
sock.send(dirS)
sock.send(fileS)

rawDescription: Python sending mutliple strings using socket.send() / socket.recv()


code:
for n in nums:
        if n > least_max:
            max_nums[least_max_key] = n
            least_max_key = min(max_nums, key=max_nums.get) # this is O(k)
            least_max = max_nums[least_max_key]

rawDescription: What is the Time Complexity of finding the max k integers?


rawDescription: Instantiate two 2D numpy arrays from a list of strings


code:
def foo3(annot, simi_matrix_word):
    N = annot.shape[0]
    A = annot.astype(bool)
    simi_matrix_img = np.eye(N,dtype=float)
    for i,j in zip(*np.tril_indices(N,-1)):
        score = simi_matrix_word[A[i],:][:,A[j]]
        simi_matrix_img[i, j] = score.mean()
    return simi_matrix_img

rawDescription: How can I accelerate the array assignment in python?

description: Accelerate the array assignment in python


code:
fast = TestSuite()
fast.addTests( TestFastThis )
fast.addTests( TestFastThat )

rawDescription: Python unittest: how to run only part of a test file?


code:
import math
a % 10 ** int(math.log10(a)/2)
int(str(a)[-int(math.log10(a)/2):])

rawDescription: how to divide integer and take some part

description: Divide integer and take some part


rawDescription: how to format list and assign them seperately?

description: Format list and assign them seperately


code: df[['date', 'time', ... ]].to_csv('df.csv')

rawDescription: How to specify date format when using pandas.to_csv?

description: Specify date format when using pandas.to_csv


code:
from collections import Counter

res = Counter()
for k, v in data:
    res.update({k: v})

print(res)

rawDescription: Getting totals from list of lists and apply it to a dictionary


code:
Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension))

rawDescription: How do I split models.py into different files for different models in Pyramid?

description: Split models.py into different files for different models in Pyramid


code: PySpam_System("an example");

rawDescription: Python Function Capsules

description: Python Function Capsules


code:
def convert_to_decimal(degrees, arcminutes, arcseconds):
    '''
       Convert degrees, minutes, seconds into the
       same latitude (or longitude) as a single in
       decimal degrees (a single value of type float)
    '''
    return 42.0

rawDescription: python code for "minute of arc" calculation, completing a latitude and longitude conversion function

description: Python code for "minute of arc" calculation, completing a latitude and longitude conversion function


code:
def set_status_text(text):
    self.statusbar.SetStatusText(text, 0)

rawDescription: How can I align the text in a StatusBar to the right in wxPython?

description: Align the text in a StatusBar to the right in wxPython


code:
class Foo(object):
    @property
    def bar(self): return 'spam'

foo = Foo()
foo.bar
foo.bar = 'ham'

rawDescription: Using descriptor to access variable instead of binding this variable with the target in the instance


code:
dict = {
        ('cat', 10) : [value1, value2, value3, ..., value10],
        ('dog', 15) : [value1, value2, value3, ..., value15],
        ('zen', 15) : [value1, value2, value3, ..., value15]
       }

rawDescription: Constructing a dictionary with multi part keys


code:
from collections import defaultdict
import json

data = defaultdict(lambda: defaultdict(dict))

i=0
for k1 in ['Name{}'.format(j) for j in range(1,6)]:
    for k2 in ('Item1', 'Item2', 'Item33'):
        data[k1]['ItemList'][k2]=i
        i+=1

print(json.dumps(data))

rawDescription: python list tree indexing

description: Python list tree indexing


code:
from rest_framework import serializers

class JSONSerializerField(serializers.Field):
    """ Serializer for JSONField -- required to make field writable"""
    def to_internal_value(self, data):
        return data
    def to_representation(self, value):
        return value

rawDescription: Django Rest Framework and JSONField

description: Django Rest Framework and JSONField


code: price_str = price_str.lstrip('$') # 17.95

rawDescription: Parsing text in BS4

description: Parsing text in BS4


rawDescription: Format string by binary list

description: Format string by binary list


code: cos_amp * np.cos( 2 * np.pi * freq * time) + sin_amp * np.sin( 2 * np.pi * freq * time)

rawDescription: Drawing FFT discrete signal using continuous sine-waves ?!


code: ['word', 'word', 'word']

rawDescription: Match a word in a string using regex - python


code:
import time
time.strftime(start_time_format, time.localtime(mt))

rawDescription: Python : INPUT a microtime float, RESULT a formatted datetime


rawDescription: Python Pandas Pivot Table - Adding calculated column to multi-index column


code:
s = set()
sl = [s.add(elem) or elem for elem in ls if elem == 4 or elem not in s]

rawDescription: How to remove all duplicates from list except one element in Python?

description: Remove all duplicates from list except one element in Python


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--arg", nargs="?", type=str, dest="arg", const="")
print(parser.parse_args([]))
print(parser.parse_args(['--arg']))
print(parser.parse_args(['--arg=lol']))

rawDescription: python argparse strore_true and store optional option in one argument

description: Python argparse strore_true and store optional option in one argument


rawDescription: selecting rows in numpy ndarray based on the value of two columns

description: Selecting rows in numpy ndarray based on the value of two columns


code:
mapping = dict(zip(alpha, alphaShift))
encrypted = ''.join(mapping.get(char, char) for char in unencrypted)

rawDescription: Better way to test for a value in a list than to stack try's and except's


code: pd.concat([df1, df2], axis=1)

rawDescription: Zip pandas dataframes into a new dataframe


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

a = np.array([3, 5, 10, np.inf, 5, 8])
imdata = np.atleast_2d(a)
cmap = plt.cm.hot
cmap.set_over('b')
cmap.set_under('g')
fig, ax = plt.subplots()

b = a[np.isfinite(a)]
im = ax.pcolormesh(imdata, cmap=cmap, vmin=b.min(), vmax=b.max())

plt.colorbar(im, extend='both')
plt.show()

rawDescription: pcolormesh with masked invalid values

description: Pcolormesh with masked invalid values


code:
import inspect
spec = inspect.getargspec(f)
spec

rawDescription: Where is the default parameter in Python function


code:
triplets = []
for a,b in combinations(range(1,1000),2):
  if 1000000-2000*a-2000*b+2*a*b==0:
    triplets.append([a, b, sqrt(a**2 + b**2)])

rawDescription: Why isn't my solution to Project Euler 9 working?


rawDescription: Difference between methods and functions


rawDescription: Compare string of bits with elements of a table python


code:
mags     = filter(lambda x: x.endswith('MAG'), a)
mag_errs = filter(lambda x: x.endswith('MAG_ERR'), a)

rawDescription: Finding a pattern in a list of strings

description: Finding a pattern in a list of strings


code:
    #gdocs.auth_token = gdata.gauth.OAuthHmacToken(SETTINGS['CONSUMER_KEY'],
    #                                               SETTINGS['CONSUMER_SECRET'],
    #                                               access_token,
    #                                               access_token_key,
    #                                               gdata.gauth.ACCESS_TOKEN)

rawDescription: Use Access Token once accepted?

description: Use Access Token once accepted


code:
dpid_string = '0000000000000201'
':'.join([dpid_string[i:i + 2] for i in range(0, len(dpid_string), 2)])

rawDescription: String formating by inserting ':'

description: String formating by inserting ':'


code: file1list = [ np.array(entry) for entry in file1list ]

rawDescription: efficient string comparison in python including numerical evaluation

description: Efficient string comparison in python including numerical evaluation


code:
from scipy.spatial import cKDTree

tree = cKDTree(points)
pairs = tree.query_pairs(coorRadius)

rawDescription: Efficient double iteration over array

description: Efficient double iteration over array


rawDescription: regexp, python: index of last occurrence. Has negative look-behind

description: Regexp, python: index of last occurrence. Has negative look-behind


code:
from scipy import sparse
i=[0,0,0,1,1,1]
j=[0,1,2,0,3,4]
A=sparse.csr_matrix((np.ones_like(j),(i,j)))
print(A)

rawDescription: Read sparse matrix in python

description: Read sparse matrix in python


code:
df["label"] = df["change"] > 1.03
df

rawDescription: pandas dataframe: new column depending on other

description: Pandas dataframe: new column depending on other


code:
def MaxValue(maxValue):
    def wrapFunction(function):
        def replacedMaxValueFunction(self, value):
            assert value <= maxValue
            return function(self, value)
        replacedMaxValueFunction.__name__ = function.__name__
        return replacedMaxValueFunction
    return wrapFunction

rawDescription: Python 3.x - Data Annotation Validation Equivalent


code:
import json
def metrics(request):
    data = json.loads(request.POST.get('data'))
    program = data.get('program','')
    marketplace = data.get('marketplace','')
    metrics = data.get('metrics','')

rawDescription: Convert Javascript dictionary to python dictionary


code: int(a & ~Qt.ActionMask)

rawDescription: Qt DropActions: What is ActionMask for?

description: Qt DropActions: What is ActionMask for


code:
move = ChessBoard().make_move
move("e4")
move("e5")

rawDescription: Currying using python with-statement?

description: Currying using python with-statement


code:
def show_categories(request):
    ctx = {
        'categories': Category.objects.all(),
    }

    return render(request, 'my_template.html', ctx)

rawDescription: Get all categories and items in category


rawDescription: How to get the first digit of the fractional part of a decimal number?

description: Get the first digit of the fractional part of a decimal number


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

rawDescription: When walking through files and folders, how do I compare the current filename with the next, in python?


code: _names = sys.builtin_module_names

rawDescription: Where is os.stat() defined in CPython?

description: Where is os.stat() defined in CPython


rawDescription: Python writing a csv to dictionary with headers as keys and rows as values


code:
c.values = np.array([0,1])
store.select('df', where=c)

rawDescription: Selecting rows from an HDFStore by index using where


code:
a = "\\n"
a
b = a.replace("\\n", "\n")
b
len(a)
len(b)
ord(b)

rawDescription: Newline literal read from file is being escaped automatically


code: args_str = ','.join(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row) for row in cur_msql)

rawDescription: Python - Concat the output of join() method


code:
def get_user(x):
    name1 = input('Give me name ' + x + '\n').lower()
    while name1 == "" or not name1.replace(' ','').isalpha():
        name1 = input('Give me name ' + x + '\n').lower()
    return name1

users = []

for i in range(3):
    users.append(get_user(str(i+1)))

print(users)

rawDescription: Turning this code into a python function


code:
y=np.arange(12).reshape(3,4)
y

rawDescription: Python/numpy issue with array/vector with empty second dimension


rawDescription: igraph select function for generic attributes

description: Igraph select function for generic attributes


code:
class MyClass(object):
    def __init__(self, member):
        self.member = member

rawDescription: Python class members confusion

description: Python class members confusion


rawDescription: TypeError list object is not callable when trying to convert an object to a string


code:
from appscript import *
app('Numbers').documents.first.sheets.first.tables.first.selection_range.cells.first.value.set(to=42)

rawDescription: How to set value of current Numbers cell using Py-Appscript

description: Set value of current Numbers cell using Py-Appscript


code:
from PIL import Image

im = Image.open("g.bmp")       # The input image. Should be greyscale
out = open("out.txt", "wb")    # The output.

data = im.getdata()            # This will create a generator that yields
                               # the value of the rbg values consecutively. If
                               # g.bmp is a 2x2 image of four rgb(12, 12, 12) pixels,
                               # list(data) should be
                               # [(12,12,12), (12,12,12), (12,12,12), (12,12,12)]

for i in data:                   # Here we iterate through the pixels.
    if i[0] < 10:                # If r==b==g, we only really
                                 # need one pixel (i[0] or "r")

        out.write(str(i[0])+" ") # if the pixel is valid, we'll write the value. So for
                                 # rgb(4, 4, 4), we'll output the string "4"
    else:
        out.write("X ")          # Otherwise, it does not meet the requirements, so
                                 # we'll output "X"

rawDescription: Print pixels in image which are < 10,10,10


rawDescription: Limit of digit-by-digit calculation of square roots


code:
文本
文
本

rawDescription: Iterating through a unicode string in Python


code:
from urllib import urlopen
try:
    urlopen(path)
except IOError:
    pass # does not exist
else:
    pass # does exist

rawDescription: How to check if a network path exist?

description: Check if a network path exist


code: dd[next(reversed(dd))]

rawDescription: Get last value of an OrderedDict in Python3


code:
for name, score in sorted(scores.items(), key=itemgetter(1), reverse=True):
    print(name, score)

rawDescription: Efficiently processing data in text file


code:
def do_all(self):
    for c in reversed(self.__class__.__mro__[:-1]):
        if 'do_it' in c.__dict__:
            c.do_it(self)

rawDescription: How can I ensure that a method is called (once, if present) for every class in a hierarchy?

description: Ensure that a method is called (once, if present) for every class in a hierarchy


code: [int(t) for t in tokens]

rawDescription: convert a list of strings to a list of numbers?

description: Convert a list of strings to a list of numbers


code: sys.stdout.write(",".join(["{:}:{:}".format(key, value) for key, value in countlist .items()]))

rawDescription: Print frequency of words, in a sentence, in a single line


code:
list1, list2, list3 = [0, 1], ['a', 'b'], [2, 3]
from itertools import chain
for item in chain(list1, list2, list3):
    print(item)

rawDescription: Iterate two lists in the same loop

description: Iterate two lists in the same loop


code:
class MyDataFrameView(object):

    def __init__(self, df):
        self.data = df

    def x(self):
        return self.data.ix['foo', 'x']

    def y(self):
        return self.data.ix['bar', 'y']

rawDescription: Dynamically Generating Pandas Views

description: Dynamically Generating Pandas Views


code:
def resizeEvent(self, event):
    super(myQLabel, self).resizeEvent(event)

    if not self.text():
        return

    #--- fetch current parameters ----

    f = self.font()
    cr = self.contentsRect()

    #--- iterate to find the font size that fits the contentsRect ---

    dw = event.size().width() - event.oldSize().width()   # width change
    dh = event.size().height() - event.oldSize().height() # height change

    fs = max(f.pixelSize(), 1)
    while True:

        f.setPixelSize(fs)
        br =  QtGui.QFontMetrics(f).boundingRect(self.text())

        if dw >= 0 and dh >= 0: # label is expanding

            if br.height() <= cr.height() and br.width() <= cr.width():
                fs += 1
            else:
                f.setPixelSize(max(fs - 1, 1)) # backtrack
                break

        else: # label is shrinking

            if br.height() > cr.height() or br.width() > cr.width():
                fs -= 1
            else:
                break

        if fs < 1: break

    #--- update font size ---

    self.setFont(f)

rawDescription: Syncing Label fontsize with layout in PyQt


code:
# all .pyx files in a folder
from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'MyProject',
  ext_modules = cythonize(["*.pyx"]),
)

rawDescription: Cython setup.py for several .pyx

description: Cython setup.py for several .pyx


code:
arg = verify_state('TAG1') == 100
some_func(arg)

rawDescription: How to get atributes and operator from function

description: Get atributes and operator from function


code:
rslt = {
    inp[i][0]+", "+inp[i][1]: inp[i:i+3]
    for i in range(0, len(inp), 3)
}

rawDescription: Creating a dictionary from a list

description: Creating a dictionary from a list


code:
import sys
import test2
from PyQt4 import QtGui

class Example(QtGui.QWidget):
    def __init__(self, app):
        self.app = app
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.btn = QtGui.QPushButton('Dialog', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)

        self.le = QtGui.QLineEdit(self)
        self.le.move(130, 22)

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('test')
        self.show()

    def showDialog(self):
        self.le.setText(test2.main("10",self.le, self.app))

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example(app)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: pyqt4 QLineEdit realtime output using other py module

description: Pyqt4 QLineEdit realtime output using other py module


code:
from turtle import fd, right, left  # etc

right(90)
fd(100)
backwards(300) # throws an error!
forwards(300)  # throws an error!

rawDescription: Importing Turtle graphics modules

description: Importing Turtle graphics modules


code:
def fun1():

    allresults = []

    # do you loop and generate objects like
    results = {
        "A": {"B":1,"C":0,"D":3},
        "B": {"A":1,"C":0,"D":3},
        "C": {"B":1,"A":0,"D":3},
        "D": {"B":1,"C":0,"A":3},
        "min": 0,
        "x": "A",
        "y": "C",
        "new": "AC"
    }

    # and add them to your list
    allresults.append(results)

    return allresults

rawDescription: How to use python output generated by several print statements?

description: Use python output generated by several print statements


code: names = names.split(', ')

rawDescription: Python: extract unique id from file name


code: sorted(ngrams, key=lambda s: s.count(" "), reverse=True)

rawDescription: How to sort list of string by n-grams in python

description: Sort list of string by n-grams in python


code:
answer= ""
while answer != "E":
    menu()
    answer= input("what is your menu choice?")
    if answer=="C":
        customer= input("who are you?")
        index= customerind(customer)
        if index == -1:
          print('Customer not found. Exiting...')
          break #Break out of the while loop above so the program exits.
    if answer== "W":
        withdrawAmt = float(input("how much did you want to withdraw today?"))
        withdraw(index, withdrawAmt)
        printbalance(index)
    if answer=="B":
        printbalance(index)
    if answer=="D":
        depositAmt = float(input("how much did you want to deposit today?"))
        deposit(index, depositAmt)
        printbalance(index)

rawDescription: how do you break code in a if loop?

description: Break code in a if loop


code:
with open('spam.bmp', 'rb') as f:
    data = bytearray(f.read())

rawDescription: working with .bmp files in python 3

description: Working with .bmp files in python 3


code: df.index.get_loc_level((1, "A"))

rawDescription: Pandas multi-index best way to slice for ranges of subordinate levels


code:
end_pos = source.find(char, start)
output.append(source[start_pos:end_pos])

rawDescription: Iteration issue in python

description: Iteration issue in python


code:
from .test_basic import *
from .test_detail import *

rawDescription: Execute Unittest in Django

description: Execute Unittest in Django


code: M = list(set(L))

rawDescription: Algorithm - How to delete duplicate elements in a list efficiently?


code:
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
multituples = [tuple(l) for l in multilist]
from collections import Counter
tc = Counter(multituples)
tc

rawDescription: Count the same list's occur frequency in a multi-dimensional list?


rawDescription: comparing a list item within certain interval in python

description: Comparing a list item within certain interval in python


rawDescription: Python Numpy 2D Array Number of Rows For Empty Matrix is Still 1


code:
elevation_change = np.zeros_like(sediment_transport)
nrows, ncols = flow_direction.shape
lookup = {32: (-1, -1),
          16:  (0, -1),
          8:   (1, -1),
          4:   (1,  0),
          64: (-1,  0),
          128:(-1,  1),
          1:   (0,  1),
          2:   (1,  1)}

for value, (row, col) in lookup.iteritems():
    mask = flow_direction == value
    shifted = np.roll(mask, row, 0)
    shifted = np.roll(shifted, col, 1)
    elevation_change[mask] = sediment_transport[shifted]

return elevation_change

rawDescription: Iterating through a numpy array and then indexing a value in another array


rawDescription: Merging lists in a row wise manner to generate a 2D array


rawDescription: Using array indexing to apply 2D array function on 3D array


code:
import ctypes
from ctypes.util import find_library

# enforces priority of hand-compiled OpenBLAS library over version in /usr/lib
# that comes from Ubuntu repos
try_paths = ['/opt/OpenBLAS/lib/libopenblas.so',
             '/lib/libopenblas.so',
             '/usr/lib/libopenblas.so.0',
             find_library('openblas')]
openblas_lib = None
for libpath in try_paths:
    try:
        openblas_lib = ctypes.cdll.LoadLibrary(libpath)
        break
    except OSError:
        continue
if openblas_lib is None:
    raise EnvironmentError('Could not locate an OpenBLAS shared library', 2)

def set_num_threads(n):
    """
    Set the current number of threads used by the OpenBLAS server
    """
    openblas_lib.openblas_set_num_threads(int(n))

def num_threads(n):
    """
    Set the OpenBLAS thread context:

        print "Before ", get_num_threads()

        with num_threads(n):
            print "In thread context: ", get_num_threads()

        print "After ", get_num_threads()

    """
    return ThreadContext(n)

class ThreadContext(object):

    def __init__(self, num_threads):
        self._old_num_threads = get_num_threads()
        self.num_threads = num_threads

    def __enter__(self):
        set_num_threads(self.num_threads)

    def __exit__(self, *args):
        set_num_threads(self._old_num_threads)

# these features were added very recently:
# <https://github.com/xianyi/OpenBLAS/commit/65a847cd361d33b4a65c10d13eefb11eb02f04d7>
try:
    openblas_lib.openblas_get_num_threads()
    def get_num_threads():
        """Get the current number of threads used by the OpenBLAS server
        """
        return openblas_lib.openblas_get_num_threads()
except AttributeError:
    def get_num_threads():
        """Dummy function (symbol not present in %s), returns -1.
        """ % openblas_lib._name
        return -1
    pass

try:
    openblas_lib.openblas_get_num_procs()
    def get_num_procs():
        """Get the total number of physical processors
        """
        return openblas_lib.openblas_get_num_procs()
except AttributeError:
    def get_num_procs():
        """Dummy function (symbol not present in %s), returns -1.
        """ % openblas_lib._name
        return -1
    pass

rawDescription: Set max number of threads at runtime on numpy/openblas


code:
import urllib2

class HTTPBasic403AuthHandler(urllib2.HTTPBasicAuthHandler):
    # retry with basic auth when facing a 403 forbidden
    def http_error_403(self, req, fp, code, msg, headers):
        host = req.get_host()
        realm = None
        return self.retry_http_basic_auth(host, req, realm)

rawDescription: Fetching a URL from a basic-auth protected Jenkins server with urllib2


code:
if not args.funcs:
    args.funcs = [func1, func2, func3]

rawDescription: python argparse set behaviour when no arguments provided

description: Python argparse set behaviour when no arguments provided


code:
from robot.errors import RemoteError
class A(object):
    def fun(self,var):
        if int(var)>5:
            raise RemoteError('test','test',fatal=True,continuable=True)

rawDescription: Getting ROBOT_CONTINUE_ON_FAILURE = true to work


rawDescription: pandas.read_html returns only one table

description: Pandas.read_html returns only one table


code: p = Symbol('p', positive=True)

rawDescription: SymPy -- define domain of variable

description: SymPy -- define domain of variable


code:
cursor.execute("DELETE from ...")
result = cursor.rowcount

rawDescription: Python: retrieve number of rows affected with SQL DELETE query


code:
d = {}
for line in infile:
    if "=" in line:
        key, val = map(str.strip, line.split("="))
        d[key] = val
    else:
        d[key] += line.strip()

rawDescription: Parsing txt file into dictionary in Python


code: linklist = [tag.get('href') for tag in links if tag.get('href') is not None]

rawDescription: Saving results to list from a for loop?

description: Saving results to list from a for loop


code:
import csv

with open('output.txt','wb') as fou:
    csv_writer = csv.writer(fou)
    for tag in tags:
        split_on_whitespace = t.text.split()
        csv_writer.writerow(split_on_whitespace)

rawDescription: Extracting a specific string out an HTML document


rawDescription: What is the best Pythonic way to parse this data?


code:
keylist = dct.keys()
keylist.sort()

rawDescription: python JSON only get keys in first level

description: Python JSON only get keys in first level


code:
from collections import Counter
x = Counter([1, 2, 3, 4])
y = Counter([1, 1, 2, 5, 6])
x - y
y - x

rawDescription: Looking for more pythonic list comparison solution


code:
lxml.html.document_fromstring('
a
')[0]

rawDescription: parse html body fragment in lxml

description: Parse html body fragment in lxml


code:
class my_large_num(object):

    def __init__(self):
        self.num_iterations = 0

    def __iter__(self):
        return self

    def next(self):
        if self.num_iterations < 1:
            self.num_iterations += 1
            return 10**200
        else:
            raise StopIteration()

rawDescription: Can I store an iterator in a file which I can read from later? Will this reduce space consumption?

description: Store an iterator in a file which I can read from later? Will this reduce space consumption


code:
from itertools import izip, ifilter # on Py3 instead use normal zip and filter
f1 = ifilter(predicate, f1)
f2 = ifilter(predicate, f2)

all(x == y for x, y in izip(f1, f2))

rawDescription: Ignoring lines while comparing files using Python


code:
x = ['a','a','b','c','c','d']
from collections import Counter
count = Counter(x)
count
count.most_common()

rawDescription: Python: value that occurs the most in a list


code:
import time
from nltk import word_tokenize

import urllib.request
url = 'https://raw.githubusercontent.com/Simdiva/DSL-Task/master/data/DSLCC-v2.0/test/test.txt'
response = urllib.request.urlopen(url)
data = response.read().decode('utf8')

for _ in range(10):
    start = time.time()
    for line in data.split('\n'):
        line.split()
    print ('str.split():\t', time.time() - start)

for _ in range(10):
    start = time.time()
    for line in data.split('\n'):
        word_tokenize(line)
    print ('word_tokenize():\t', time.time() - start)

rawDescription: Python re.split() vs nltk word_tokenize and sent_tokenize


rawDescription: Scrapy - Follow RSS links

description: Scrapy - Follow RSS links


rawDescription: Not able to sort the unicode numbers in python


code: print(video[i][boxes[j]] / video[i+1][boxes[j]], end='\t')

rawDescription: Within a nested for loop, how can I print tab and carriage return delimited groups of data?


code:
s = (
    r"foo\tbar\n"
    r"baz\tqux\n")
s
s = ''.join(r"""
foo\tbar\n
baz\tqux\n
""".splitlines())
s
from textwrap import dedent
s = ''.join(dedent(r"""
    foo\tbar\n
    baz\tqux\n
""").splitlines())
s

rawDescription: How can I create a single raw string from multiple literals in Python?

description: Create a single raw string from multiple literals in Python


code: [['i', 'love', 'skiing'], ['he', 'hates', 'bathing'], ['he', 'hates', 'disco']]

rawDescription: mixed string breaking down in order and per keyword from groups

description: Mixed string breaking down in order and per keyword from groups


code:
import sys
import inspect

_line_number = None
_frame = None
def jump_to(line_number, frame):
    global _line_number, _frame
    print("Set jump to line", line_number, "in", inspect.getfile(frame))

    _frame = frame
    _line_number = line_number

def _trace(frame, event, arg):
    global _line_number, _frame

    try:
        if _line_number is not None:
            if inspect.getfile(_frame) == inspect.getfile(frame):
                print("Jumping to line", _line_number, "in", inspect.getfile(frame))
                frame.f_lineno = _line_number
                _line_number = None

    except ValueError as e:
        print(e)

    return _trace

def install():
    sys.settrace(_trace)
    frame = sys._getframe().f_back
    while frame:
        frame.f_trace = _trace
        frame = frame.f_back

rawDescription: Python: resuming program at line number in the context before an exception using a custom sys.excepthook


code:
for column in df.columns:
    df[column] = df[column].apply(lambda L, rep={c:i for i,c in enumerate('abcdefh', 1)}: rep[L[0]])

rawDescription: Dataframe Replace Regex

description: Dataframe Replace Regex


rawDescription: Fine-Uploader in depth information on the use of Azure Blob Storage through python flask


code:
class Name(object):
    def __init__(self,s):
        self.firstname = s.get('firstname','')
        self.lastname = s.get('lastname')

rawDescription: Overriding decorated subclass methods

description: Overriding decorated subclass methods


code: email = db.EmailField(max_length=255, unique=True, regex=r'.*?boston\.edu$')

rawDescription: StringField in mongodb requirements

description: StringField in mongodb requirements


code: lf, rf = abs(np.fft.rfft(left)), abs(np.fft.rfft(right))

rawDescription: Python amplitude spectrum plot

description: Python amplitude spectrum plot


code:
extra_install_requires = []
try:
    from collections import OrderedDict
except ImportError:
    extra_install_requires.append('ordereddict>=1.1')

rawDescription: What is the best way to handle dependencies based on the Python version?


rawDescription: How to parse HTML using the lxml.html library

description: Parse HTML using the lxml.html library


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

data = [1, 5, 1, 1, 6, 3, 3, 4, 5, 5, 5, 2, 5]
correlation = [(i, data.count(i)) for i in set(data)]
correlation.sort(key=lambda x: x[1])

labels, values = zip(*correlation)

indexes = np.arange(len(correlation))
width = 1

plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()

rawDescription: Plot a histogram with the x axis values based on the height of the column


code:
from bs4 import BeautifulSoup
from mechanize import Browser

br = Browser()
br.addheaders = [('User-agent', 'Firefox')]
response = br.open("http://www.hanyc.org/members/hotels/")

web_data = response.read()

soup = BeautifulSoup(web_data, "html.parser")
tags = soup.find_all('span', attrs={"class": "hanyccompany"})

for tag in tags:
    print(tag.parent.text)
    print("------------------------------")

rawDescription: How to find all next siblings from a particular class using css selectors

description: Find all next siblings from a particular class using css selectors


rawDescription: Python Assign Value to New Column If Contains() Is True


code:
frame = Frame(master,width = 100,height = 100)
frame.focus_set()

rawDescription: Problems with Tkinter Binding to enter/return


rawDescription: simple/efficient way to expand a pandas dataframe

description: Simple/efficient way to expand a pandas dataframe


code:
for word in word_list:
    word_dict.setdefault(word[0], set()).add(word)

rawDescription: Assigning lower case alphabet as keys in a dictionary?


code:
if a == '' or b == '':
    print('Either a or b is empty')

rawDescription: How do I compare two variables against one string in python?

description: Compare two variables against one string in python


rawDescription: Spark: Manipulation of Multiple RDDs

description: Spark: Manipulation of Multiple RDDs


code:
PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

rawDescription: How to use Bcrypt to encrypt passwords in Django

description: Use Bcrypt to encrypt passwords in Django


code:
if __name__ == '__main__':
    start()

rawDescription: What is Wrong with this Code?(Python test Project)


code:
def qwer(num):
    d = {}
    for i in range(num+1):
        d[str(i)] = i
    return d

rawDescription: What is the name of this dictionary?

description: What is the name of this dictionary


rawDescription: python pandas: get fiscal quarter from fiscal year and month (for UK)

description: Python pandas: get fiscal quarter from fiscal year and month (for UK)


rawDescription: How to Find the Neighbors of a Cell in an ndarray?


code:
test_str = "/*\n test.cpp\n *\n *\n *\n\t2013.02.30\n *\n */\n"
test_str.encode('unicode_escape')

rawDescription: Python handling newline and tab characters when writing to file


code:
from functools import partial
def a(*args):
    return sum(args)

b = partial(a, 2, 3)
b(6, 7, 8)

rawDescription: Map list by partial function vs lambda

description: Map list by partial function vs lambda


code:
test_str = "# <init> (Lorg/cyanogenmod/audiofx/ActivityMusic;)V\n         , 0 iput-object v1, v0, Lorg/cyanogenmod/audiofx/ActivityMusic$11;->this$0 Lorg/cyanogenmod/audiofx/ActivityMusic;\n         , 4 invoke-direct v0, Ljava/lang/Object;-><init>()V\n         , a return-void "
print(test_str.split('\n')[0])

rawDescription: Python Regex starting with hashtag

description: Python Regex starting with hashtag


code:
a.length       # Instead of the getter
a.length = 2   # Instead of the setter
a.length

rawDescription: Creating a Rectangle class

description: Creating a Rectangle class


code:
from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5

BLOCK_SIZE = 16

def pad(data):
    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
    return data + (chr(length)*length).encode()

def unpad(data):
    return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]

def bytes_to_key(data, salt, output=48):
    # extended from https://gist.github.com/gsakkis/4546068
    assert len(salt) == 8, len(salt)
    data += salt
    key = md5(data).digest()
    final_key = key
    while len(final_key) < output:
        key = md5(key + data).digest()
        final_key += key
    return final_key[:output]

def encrypt(message, passphrase):
    salt = Random.new().read(8)
    key_iv = bytes_to_key(passphrase, salt, 32+16)
    key = key_iv[:32]
    iv = key_iv[32:]
    aes = AES.new(key, AES.MODE_CBC, iv)
    return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))

def decrypt(encrypted, passphrase):
    encrypted = base64.b64decode(encrypted)
    assert encrypted[0:8] == b"Salted__"
    salt = encrypted[8:16]
    key_iv = bytes_to_key(passphrase, salt, 32+16)
    key = key_iv[:32]
    iv = key_iv[32:]
    aes = AES.new(key, AES.MODE_CBC, iv)
    return unpad(aes.decrypt(encrypted[16:]))

password = "some password".encode()
ct_b64 = "U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"

pt = decrypt(ct_b64, password)
print("pt", pt)

print("pt", decrypt(encrypt(pt, password), password))

rawDescription: How to decrypt password from JavaScript CryptoJS.AES.encrypt(password, passphrase) in Python

description: Decrypt password from JavaScript CryptoJS.AES.encrypt(password, passphrase) in Python


rawDescription: Pandas: How to plot a barchar with dataframes with labels?


code:
it = client.factory.create('ns0:GatewayReq')
it

rawDescription: SUDS: Pass Array Parameter in Client.service Method : GAE Python


code: decimal = sum(16**i * hexmap(s) for i, s in enumerate(reversed(hexstring)))

rawDescription: Hex addition with some limitations

description: Hex addition with some limitations


code:
# conftest.py
import pytest

browsers = {"ff": 'FIREFOX', 'ie': 'INTERNETEXPLORER'}

def pytest_addoption(parser):
    parser.addoption("--browser", default='',
        type='choice', choices=sorted(browsers),
        help="runs tests only for given browser")

@pytest.yield_fixture(params=browsers.keys())
def browser(request):
    selected = request.config.getoption('browser')
    if selected and selected != request.param:
        pytest.skip('browser {} selected in the command line'.format(selected))
    driver = browsers[request.param]
    yield driver

rawDescription: py.test conftest - Modify Fixture Parameter Based on sys.argv

description: Py.test conftest - Modify Fixture Parameter Based on sys.argv


code:
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)

rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
a1 = Article(headline='...')
a1.publications.add(p1)
a1.save()
a1.publications.add(p1)

rawDescription: Prevent m2m_changed from firing when creating an object


rawDescription: Depth First Search in Python (including cycles)


code:
str1 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag"
str2 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag br_tag"
re.search(r'.*\w(\..*)$', str2).group(1)
re.search(r'.*\w(\..*)$', str1).group(1)
str3 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag .br_tag"
re.search(r'.*\w(\..*)$', str3).group(1)

rawDescription: Regular expression to find last group in python


code:
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=2).fit(X)
centers2D = pca.transform(kmeans.cluster_centers_)

plt.hold(True)
plt.scatter(centers2D[:,0], centers2D[:,1],
            marker='x', s=200, linewidths=3, c='r')
plt.show()              #not required if using ipython notebook

rawDescription: plot a document tfidf 2D graph

description: Plot a document tfidf 2D graph


code:
from collections import Iterator
from threading import Lock
import time

class RateLimiter(Iterator):
    """Iterator that yields a value at most once every 'interval' seconds."""
    def __init__(self, interval):
        self.lock = Lock()
        self.interval = interval
        self.next_yield = 0

    def __next__(self):
        with self.lock:
            t = time.time()
            if t < self.next_yield:
                time.sleep(self.next_yield - t)
                t = time.time()
            self.next_yield = t + self.interval

api_rate_limiter = RateLimiter(1)

def work_function(work):
    next(api_rate_limiter)
    call_api(...)

rawDescription: Using Python threads to make thousands of calls to a slow API with a rate limit


code:
import array
import sys

def readline(n, f, findex):
  f.seek(findex[n] + 1)
  bytes = f.read(findex[n+1] - findex[n])
  return bytes.decode('utf8')

def main():
  fn = sys.argv[1]
  with open(fn + '.indx', 'rb') as f:
    findex = array.array('l')
    findex.fromfile(f, 1)
    findex.fromfile(f, findex[0])
    findex[0] = -1
  with open(fn, 'rb') as f:
    for n in sys.argv[2:]:
      print(n, repr(readline(int(n), f, findex)))

main()

rawDescription: Moving to an arbitrary position in a file in Python


code:
import unittest
class TestCaseA(unittest.TestCase):
    def setUp(self):
        self.thing = A()

    def test_does_x():
        self.assertTrue(self.thing.does_x())

rawDescription: Test subclass behaviour?

description: Test subclass behaviour


rawDescription: Python multiprocessing.Pool.map dying silently


code:
import wx

class DrawPanel(wx.Frame):

    """Draw a line to a panel."""

    def __init__(self):
        wx.Frame.__init__(self, title="Draw on Panel")
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, event=None):
        dc = wx.PaintDC(self)
        dc.Clear()
        dc.SetPen(wx.Pen(wx.BLACK, 4))
        dc.DrawLine(0, 0, 50, 50)

app = wx.App(False)
frame = DrawPanel()
frame.Show()
app.MainLoop()

rawDescription: How to clear drawing on screen in wxpython?

description: Clear drawing on screen in wxpython


rawDescription: Python: split string by a multi-character delimiter unless inside quotes


code:
from bs4 import BeautifulSoup

html = """
 some title
 aaa
 bbb
 ccc
"""

soup = BeautifulSoup(html)

for td in soup.find_all('td'):
    print(td.get_text())

rawDescription: How to convert html data using python

description: Convert html data using python


code:
if (x == 'X'):
    new_disorder.append( "{} {}".format(i, seq[i]) )

rawDescription: How to align and compare two elements (sequence) in a list using python

description: Align and compare two elements (sequence) in a list using python


code: print('TmpClass inherits from : %s' % TmpClass.__bases__)

rawDescription: printing a variable in python

description: Printing a variable in python


code:
def UsernameStartsWithAaccount(context=''):
    field = 'username__startswith'
    if context:
        field = context + '__' + field
    return Q(**{field: 'a'})

rawDescription: Building Django Q() objects from other Q() objects, but with relation crossing context


rawDescription: Median sort a list in unordered fashion

description: Median sort a list in unordered fashion


code:
form = {
    'first_name': 'Per',
    'last_name': 'Thulin',
}
from urllib import urlencode
urlencode(form)

rawDescription: How to simulate POST arguments in python

description: Simulate POST arguments in python


code:
def key_hash(data):
    # hash should be a 32-bit unsigned integer
    hashed = 0
    for char in data:
        # hashed += ((hashed << 19) + ord(char)) & 0xFFFFFFFF
        # the above is wrong; it's not masking the final addition.
        hashed = (hashed + (hashed << 19) + ord(char)) & 0xFFFFFFFF
    return hashed

rawDescription: CARP hash in Python

description: CARP hash in Python


code: a = hasher1.update(buf1)

rawDescription: Compare md5 hashes of two files in python


code: fname = "finviz.csv";

rawDescription: How to download and rewrite a file in Python?

description: Download and rewrite a file in Python


code:
import random

def slicer(longitude):
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = random.sample(alphabet,longitude)
    return result

print(''.join(slicer(10)))  # Produces a list, use .join() to print a string

rawDescription: slicing dynamically in python

description: Slicing dynamically in python


code: x.groupby('B').apply(filtermax, 'A', ['A0', 'A1', 'A4'], 'C')

rawDescription: How to filter results of a groupby in pandas

description: Filter results of a groupby in pandas


code:
def escape_html(s):
    s = s.replace('&', "&")
    s = s.replace(">", ">")
    s = s.replace("<", "<")
    s = s.replace('"', """)
    return s

rawDescription: Escape characters and raw string

description: Escape characters and raw string


code:
# test.py
from random import randint
from collections import defaultdict
from collections import Counter

list1 = [randint(1, 10000) for i in range(1000000)]
list2 = [randint(1, 5000) for i in range(10000)]

def list_sub_ddl(list1, list2):
    dd = defaultdict(list)
    for i in list1:
        dd[i].append(i)

    for i in list2:
        if dd[i]:
            dd[i].pop()

    return (x for v in dd.itervalues() for x in v)

def list_sub_ddi(list1, list2):
    dd = defaultdict(int)
    for i in list1:
        dd[i] += 1

    for i in list2:
        dd[i] -= 1

    return (x for l in ([k]*n for k,n in dd.iteritems() if n>0) for x in l)

def list_sub_counter(list1, list2):
    c = Counter(list1) - Counter(list2)
    return (x for l in ([k]*n for k,n in c.iteritems() if n>0) for x in l)

rawDescription: Can I perform minus or join operations on lists in python including duplicate entries

description: Perform minus or join operations on lists in python including duplicate entries


code:
parser = email.parser.Parser()
message = parser.parse(open('/home/vinko/jlm.txt','r'))
message.is_multipart()
parts = message.get_payload()
len(parts)
parts[0].get_content_type()
parts[1].get_content_type()
parts[0].get_payload()

rawDescription: email body from a parsed email object in jython

description: Email body from a parsed email object in jython


code:
tupled_dict = {k: v for k, v in tupled_dict.iteritems() if 'a' not in k}
tupled_dict

rawDescription: Return and delete all key-value pairs whose tuple keys contain a given element


code: 'aaa bbb ccc ddd eee fff'.partition('ddd')

rawDescription: Python regex search AND split

description: Python regex search AND split


code: indices_empty_fields = [i for i, f in enumerate(values) if f == ""]

rawDescription: constructing regexp expression to check for particular text-database format

description: Constructing regexp expression to check for particular text-database format


code:
word = "countries"
myStemmer = nltk.stem.porter.PorterStemmer()
myStemmer.b = word
myStemmer.k = len(word) - 1
myStemmer.k0 = 0
myStemmer.step1ab()
myStemmer.b[myStemmer.k0:myStemmer.k+1]

rawDescription: How to use NLTK stem

description: Use NLTK stem


code:
import ctypes
import numpy as np
a = (ctypes.c_int * 10)(1,2,3,4,5,6,7,8,9,0)
b = (ctypes.c_int * 10)(5,0,5,0,5,0,5,0,5,0)

x = np.array(a)
y = np.array(b)

x - y

rawDescription: How to add/substract with c_double_Array?

description: Add/substract with c_double_Array


code:
a = [1, 345, 23, 345, 90, 1]
unq, unq_idx, unq_cnt = np.unique(a, return_inverse=True, return_counts=True)

rawDescription: Checking for and indexing non-unique/duplicate values in a numpy array


code:
from xml.dom.minidom import Document

# Get all lineEdit values
elements = dict(
    mac = self.lineEdit_mac.text,
    broadcast = self.lineEdit_broadcast.text,
    destination = self.lineEdit_destination.text,
    port = self.lineEdit_port.text,
    destinationCheckBox = self.checkBox_destination.checkState,
    portCheckBox = self.checkBox_port.checkState
)

doc = Document()
wol = doc.createElement("wol")
doc.appendChild(wol)

for name, fn in elements.iteritems():
    node = doc.createElement(name)
    wol.appendChild(node)

    text = str(fn())
    nodeText = doc.createTextNode(text)
    node.appendChild(nodeText)

with open(fileName, 'w') as f:
    doc.writexml(f, indent='', addindent='  ', newl='\n')

rawDescription: How to save qlineedit fields into an XML file using Python for loops?

description: Save qlineedit fields into an XML file using Python for loops


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

rawDescription: Not getting proper character encoding with Facebook posts data


rawDescription: Parsing xml in python - don't understand the DOM


rawDescription: Generating a list of evenly distributed numbers from range


code: from Math import Calculate

rawDescription: How to include external Python code to use in other files?

description: Include external Python code to use in other files


code:
mylist= {'name':'james', 'age': '23', 'time': 'next'}
"select * from players where {}".format(
    ' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))

rawDescription: Looping Through Python Dictionary

description: Looping Through Python Dictionary


code:
import gevent
from gevent.queue import Queue

class BroadcastQueue(object):
    def __init__(self):
        self._queues = []

    def register(self):
        q = Queue()
        self._queues.append(q)
        return q

    def broadcast(self, val):
        for q in self._queues:
            q.put(val)

def setter(bqueue):
    '''After 3 seconds, wake all threads waiting on the value of evt'''
    while True:
        gevent.sleep(3)
        bqueue.broadcast("hi")

def waiter(arg, bqueue):
    queue = bqueue.register()
    while True:
        val = queue.get()
        print("waiter {} {}".format(arg, val))

def main():
    bqueue = BroadcastQueue()
    gevent.joinall([
        gevent.spawn(setter, bqueue),
        gevent.spawn(waiter, 1, bqueue),
        gevent.spawn(waiter, 2, bqueue),
        gevent.spawn(waiter, 3, bqueue),
    ])

if __name__ == '__main__':
    main()

rawDescription: gevent - Pass a value to many greenlets in parallel

description: Gevent - Pass a value to many greenlets in parallel


code:
from itertools import takewhile

#needlessly pedantic way of doing this
num_zeroes = len(list(takewhile(lambda p: p == 0, max(x))))

rawDescription: Remove occuring elements from multiple lists (shorten multiple lists) by value


code: sizes = [len(rec) for rec in SeqIO.parse("test_fasta.fasta", "fasta")]

rawDescription: Parsing fasta file with biopython to count number sequence reads belonging to each ID


code:
from functools import partial
NullColumn = partial(Column,nullable=True)

rawDescription: SQLAlchemy set default nullable=False

description: SQLAlchemy set default nullable=False


code:
import os
import re

parensnumber = re.compile(r'\s*\((\d+)\)')

with open('C:\\Dropbox\\test.txt','r') as input:
    for line in input:
        count = int(parensnumber.search(line).group(1))
        for i in range(count):
            print(parensnumber.sub('-{0}'.format(i + 1), line))

rawDescription: How to parse a number from line

description: Parse a number from line


code:
import pandas as pd
import numpy as np

outer_1 =['open','close','vol',]
outer_2 =['high','low']
inner = ['sd','mean']
tickers=['AAPL','MSFT','NTES','GOOG']

rawDescription: Creating a multindex'd column DataFrame (expanded explanation)


code:
def missingint(i,j,k):
    return 40-i-j-k

rawDescription: Given two of three items, return the missing item


code:
from robobrowser import RoboBrowser

browser = RoboBrowser(history=True,
    user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36')
browser.open('http://selleraccounts.snapdeal.com/')

form = browser.get_form(id='fm1')
form['username'].value = myusername
form['password'].value = mypassword
browser.submit_form(form)

rawDescription: get restricted page after login using requests,urllib2 python

description: Get restricted page after login using requests,urllib2 python


rawDescription: Python Regular expression for splitting mentions of two years appearing altogether


code:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
import logging

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

def send_message(to):
    log.error('starting send email')
    subject, from_email = 'Message Confirmation', 'youraddress@gmail.com'
    html_content = render_to_string('emails/message.html', {'email': str(to)})
    # this strips the html, so people will have the text as well.
    text_content = strip_tags(html_content)
    # create the email, and attach the HTML version as well.
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

rawDescription: Django/Python: How can i monitor mysql database and trigger email when timestamp = NOW()?


code: df['x'] + sdf['y'].to_dense()

rawDescription: sparse versions of Pandas DataFrame

description: Sparse versions of Pandas DataFrame


code:
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
start = datetime.strptime(start_time, '%I:%M%p').time()
end = datetime.strptime(end_time, '%I:%M%p').time()
start, end = datetime.combine(BoW, start), datetime.combine(BoW, end)

rawDescription: Strings with start and end time to datetime


code:
for i in range(0, len(some_list), line_length):
    print( some_list[i:i+line_length] )

rawDescription: Idiomatic way to print arbitrary number of items from a list on each line


code: df = df.set_index(['used_at', 'ID', 'address']).unstack().loc[:, 'active_seconds'].reset_index('ID')

rawDescription: Report with Pivot Tables like in Excel using Python


code:
myobject = type("Foo", (object,), {})()
myobject.foo = 'bar'

rawDescription: Python simple naked objects

description: Python simple naked objects


code:
a = list()
a.extend((1,2,3,4))
a.append(5)

rawDescription: Overriding list method

description: Overriding list method


rawDescription: Python How to get Scrapy Xpath data from Basic Table?


code: r'^glossary/', include('glossary.urls')

rawDescription: Django mixes my templates

description: Django mixes my templates


rawDescription: Turning an existing array into a multidimensional


code:
home_team = models.ForeignKey('<app_name>. StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
away_team = models.ForeignKey('<app_name>. StraightredTeam', db_column='awayteamid', related_name='away_fixtures')

rawDescription: Django - How to link tables

description: Django - How to link tables


rawDescription: How can I take a list and add elements in columns in intervals?

description: Take a list and add elements in columns in intervals


code:
from collections import Counter

counts = Counter(routes)

multi_routes = [i for i in counts if counts[i] > 1]

rawDescription: Filtering a list python repeated items

description: Filtering a list python repeated items


rawDescription: Python append lists into lists

description: Python append lists into lists


code:
import string
import scipy.io as sio
import numpy as np

letters = string.ascii_lowercase
datafiles = ['/tmp/data{i:d}.mat'.format(i = i) for i in range(3)]

def loadrun(runs, varnames = None):
    for fle in runs:
        _varnames = None if varnames is None else varnames[:]
        yield sio.loadmat(fle, variable_names = _varnames)

def create_datafiles():
    for filename in datafiles:
        arr = np.arange(9).reshape((3, 3))
        mdict = {letter : arr for letter in letters}
        sio.savemat(filename, mdict = mdict)

create_datafiles()
vnames = ['a', 'c', 'd']
trials = loadrun(datafiles, vnames)
for t in trials:
    print(t.keys())

rawDescription: Why is scipy.io.loadmat failing to filter out variables on all but the first iteration of this generator function?


code: sorted_ranges = sorted(ranges,cmp=lambda x,y: (x[0]-y[0]) if ((x[0]-y[0]) != 0 ) else (y[-1]-x[-1]))

rawDescription: Filtering a list of integer in range, to exclude the subsets in python


code: list(pairwise(pleio))

rawDescription: Pair combinations of elements in dictionary without repetition


code:
def makelists(list_count):
    return [[] for _ in range(list_count)]

rawDescription: Create lists python

description: Create lists python


code:
lol = [["A1", "A2", "A3"], ["A1", "A2", "A3"], ["A1", "A2", "A3"]]
set([tuple(sorted(x)) for x in itertools.product(*lol) if len(set(x)) == len(lol)])
lol = [["A1", "A2"], ["A2", "A3", "A4"], ["A3", "A5"]]
set([tuple(sorted(x)) for x in itertools.product(*lol) if len(set(x)) == len(lol)])

rawDescription: Creating resources combination

description: Creating resources combination


rawDescription: How can i split a single tuple into multiple using python?

description: Split a single tuple into multiple using python


code:
regex = re.compile('#(.*?)#')
re.sub(regex, '<b>\\1</b>', str)

rawDescription: How can I replace a character with different patterns (HTML tags) in Python?

description: Replace a character with different patterns (HTML tags) in Python


code:
from functools import partial
def func_1(a, b=1, c=None):
    return a, b, c
func_2 = partial(func_1, b=2, c='asdf')
func_2(42)
func_2(42, b=5, c='spam')

rawDescription: Changing keyword defaults of a function in Python


code:
from collections import Counter
d =Counter()
d.update({'key1':10,'key2':14,'key3':47})
d['key1'] += 20
d['key4'] += 50  # Also works for keys that are not present
d

rawDescription: Sum values in a Python dict?

description: Sum values in a Python dict


code:
class MyFirefox(webdriver.Firefox):
    def quit(self):
        webdriver.Firefox.quit(self)
        self.session_id = None

rawDescription: Python Selenium: How to check whether the WebDriver did quit()?


code:
import datetime as dt

dates = [
    dt.datetime(1970, 1, 1, 0, 2),
    dt.datetime(1970, 1, 1, 0, 3),
    dt.datetime(1970, 1, 1, 0, 12),
    dt.datetime(1970, 1, 1, 0, 7),
    dt.datetime(1970, 1, 1, 0, 8),
    dt.datetime(1970, 1, 1, 0, 9),
    dt.datetime(1970, 1, 1, 0, 13)
]

def group_dates(dates, delta):
    it = iter(dates)
    prev = next(it)
    grouped, total =  [[prev]], delta.total_seconds()
    for dte in it:
        if (dte - prev).total_seconds() <= total:
            grouped[-1].append(dte)
        else:
            grouped.append([dte])
        prev = dte
    return grouped
def td(l):
    seconds = sum((d - dt.datetime(1970, 1, 1)).total_seconds() for d in l) / len(l)
    return dt.datetime.utcfromtimestamp(seconds)

from pprint import pprint as pp
pp([td(sub) for sub in group_dates(dates,dt.timedelta(minutes=2))])

rawDescription: reduce datetime list by timedelta

description: Reduce datetime list by timedelta


code:
import re
s = 'GigabitEthernet0/0/0/0 '
s[:2]+''.join(re.findall(r'\d', s))

rawDescription: Complex regex in Python

description: Complex regex in Python


rawDescription: Getting an object by name

description: Getting an object by name


rawDescription: Invalid syntax in path when changing directory


code: a = D['a'] if 'a' in D else print('hah')

rawDescription: why does D.get(k,v) seem to always execute v if v is returned from a function?

description: Why does D.get(k,v) seem to always execute v if v is returned from a function


rawDescription: intersection of two lists of dictionaries by key/value pair

description: Intersection of two lists of dictionaries by key/value pair


code:
#!/usr/bin/env python3

from __future__ import print_function

try:
    import readline  # noqa
except ImportError:
    print("Warning: No readline support available!")

try:
    input = raw_input
except NameError:
    pass

import sys
from os import path
from operator import eq, ge, gt, le, lt, ne

from tinydb import TinyDB, where

ops = {
    "==": eq,
    "!=": ne,
    "<=": le,
    ">=": ge,
    "<": lt,
    ">": gt,
}

def isint(s):
    return all(map(str.isdigit, s))

def isfloat(s):
    return "." in s and isint(s.replace(".", ""))

def createdb(filename):
    db = TinyDB(filename)
    db.insert({"id": 1, "name": "Tom",   "age": 10, "grade": 4})
    db.insert({"id": 2, "name": "Alice", "age":  9, "grade": 3})
    db.insert({"id": 3, "name": "John",  "age": 11, "grade": 5})
    db.close()

def opendb(filename):
    return TinyDB(filename)

def parse_query(s):
    qs = []

    tokens = s.split("&")
    tokens = map(str.strip, tokens)

    for token in tokens:
        try:
            k, op, v = token.split(" ", 3)
        except Exception as e:
            print("Syntax Error with {0:s}: {1:s}".format(repr(s), e))
            return where(None)

        opf = ops.get(op, None)
        if opf is None:
            print("Unknown operator: {0:s}".format(op))
            return where(None)

        if isfloat(v):
            v = float(v)
        elif isint(v):
            v = int(v)

        qs.append(opf(where(k), v))

    return reduce(lambda a, b: a & b, qs)

def main():
    if not path.exists(sys.argv[1]):
        createdb(sys.argv[1])

    db = opendb(sys.argv[1])

    while True:
        try:
            s = input("Query: ")
            q = parse_query(s)
            print(repr(db.search(q)))
        except (EOFError, KeyboardInterrupt):
            break

    db.close()

if __name__ == "__main__":
    main()

rawDescription: Dynamically parse and build TinyDB queries


code:
engine = db.create_engine('sqlite:///:memory:')
session = orm.sessionmaker(bind=engine)()
Base.metadata.create_all(engine)

lt = User('Ludovic Tiako')
the_wire = Series('The Wire')
friends = Series('Friends')
session.add_all([lt, the_wire, friends])
session.commit() # need to commit here to generate the id fields

tw_s01e01 = Episode(1,1,the_wire.id)
tw_s01e02 = Episode(1,2,the_wire.id)
f_s01e01 = Episode(1,1,friends.id)
f_s01e02 = Episode(1,2,friends.id)
f_s01e03 = Episode(1,3,friends.id)

session.add_all([tw_s01e01, tw_s01e02,
                f_s01e01, f_s01e02, f_s01e03])
session.commit()

the_wire.episodes # > [The Wire S1E1, The Wire S1E2]
friends.episodes # > [Friends S1E1, Friends S1E2, Friends S1E3]

rawDescription: SQLAlchemy: retrieve all episodes from favorite_series of specific user


code:
@register.filter
def lookup(d, key):
    if key not in d:
        return None
    return d[key]

rawDescription: How to use django template dot notation inside a for loop

description: Use django template dot notation inside a for loop


code:
from collections import OrderedDict
a, b = ([1, 2, 2, 1, 1, 3], [0.1, 0.2, 0.3, 0.4, 0.5, 1.0])
d = OrderedDict()
for k, v in zip(a, b):
    d[k] = d.get(k, 0) + v

d.keys(), d.values()

rawDescription: Sum and aggregate over a list with equal values


rawDescription: How to start a file that has a period in front of it?

description: Start a file that has a period in front of it


code:
tree.SetDropTarget(MyDropTarget())
tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.on_drag)
tree.GetMainWindow().Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda x: None)

rawDescription: wx.TreeCtrl drag and drop, copy and move

description: Wx.TreeCtrl drag and drop, copy and move


code: value.key in dict.keys()

rawDescription: python key in dict.keys() performance for large dictionaries

description: Python key in dict.keys() performance for large dictionaries


code: fig, (ax1, ax2) = plt.subplots(1, 2)

rawDescription: Creating two completely independent plots in matplotlib and going back and forth between them


code: df2["Date"] = pd.to_datetime(df2.Year.astype(str) + "-" + df2.Month, format="%Y-%b")

rawDescription: Bokeh line plot is merging data on graph


rawDescription: Plot timeseries of histograms in Python

description: Plot timeseries of histograms in Python


code:
def fib(n):
    cur = 1
    old = 1
    i = 1
    while (i < n):
        cur, old, i = cur+old, cur, i+1
    return cur

for i in range(10):
    print(fib(i))

rawDescription: How do I print a fibonacci sequence to the nth number in Python?

description: Print a fibonacci sequence to the nth number in Python


code:
import inspect

class MyClass():
    def __init__(self):
        pass
    def method1(self):
        pass
    def method2(self):
        pass

# exclude __...__ methods
actual_methods = [member for member in inspect.getmembers(MyClass)
                  if not member[0].startswith('__')]
print(len(actual_methods))

rawDescription: Method count per class in PyDev

description: Method count per class in PyDev


rawDescription: Why is 'x' in ('x',) faster than 'x' == 'x'?


code:
server.py
@asyncio.coroutine
def got_connection(reader, writer):
    msg = yield from reader.read()
    message = 'another Test Message'.encode('ascii')
    print('Sending message to {}:{} - {}'.format('localhost', 5000, message))
    writer.write(message)
    writer.write_eof()

rawDescription: Why is this Python 3 asyncio client sending the bytes only after the Python process is interrupted?


code:
json_func = globals(json_data["name"])
json_func(*json_data["args"])

rawDescription: Can JSON for Python Encode/decode functions from text files?


rawDescription: remove non-numeric rows in one column with pandas

description: Remove non-numeric rows in one column with pandas


code:
class Node(object):
    def __init__(self, data=None, weight=None,
                       left=None, right=None,
                       code=None):
        self.data = data
        self.weight = weight
        self.left = left
        self.right = right
        self.code = code

    def is_symbol(self):
        return self.left is self.right is None

    def __repr__(self):
        return "[%s,%s,(%s),(%s)]" % (self.data,
                                      self.code,
                                      self.left,
                                      self.right)

    def __cmp__(self, a):
        return cmp(self.weight, a.weight)

def encode(syms, weights):
    from heapq import heapify, heappush, heappop

    tree = [Node(data=s, weight=w)
            for s, w in zip(syms, weights)]
    sym2node = {s.data: s for s in tree}
    heapify(tree)
    while len(tree) > 1:
        a, b = heappop(tree), heappop(tree)
        heappush(tree, Node(weight=a.weight + b.weight,
                            left=a, right=b))

    # Compute code lengths for the canonical coding.
    sym2len = {}
    def assign_codelen(node, codelen):
        if node is not None:
            if node.is_symbol():
                sym2len[node.data] = codelen
            else:
                assign_codelen(node.left, codelen + 1)
                assign_codelen(node.right, codelen + 1)
    assign_codelen(tree[0], 0)

    # Create canonical codes, but with a twist:  instead
    # of ordering symbols alphabetically, order them by
    # their position in the `syms` list.
    # Construct a list of (codelen, index, symbol) triples.
    # `index` breaks ties so that symbols with the same
    # code length retain their original ordering.
    triples = [(sym2len[name], i, name)
                for i, name in enumerate(syms)]
    code = oldcodelen = 0
    for codelen, _, name in sorted(triples):
        if codelen > oldcodelen:
            code <<= (codelen - oldcodelen)
        sym2node[name].code = format(code, "0%db" % codelen)
        code += 1
        oldcodelen = codelen

    # Create a tree corresponding to the new codes.
    tree = Node(code="")
    dir2attr = {"0": "left", "1": "right"}
    for snode in sym2node.values():
        scode = snode.code
        codesofar = ""
        parent = tree
        # Walk the tree creating any needed interior nodes.
        for d in scode:
            assert parent is not None
            codesofar += d
            attr = dir2attr[d]
            child = getattr(parent, attr)
            if codesofar == scode:
                # We're at the leaf position.
                assert child is None
                setattr(parent, attr, snode)
            elif child is not None:
                assert child.code == codesofar
            else:
                child = Node(code=codesofar)
                setattr(parent, attr, child)
            parent = child

    # Finally, paste the `data` attributes together up
    # the tree.  Why?  Don't know ;-)
    def paste(node):
        if node is None:
            return ""
        elif node.is_symbol():
            return node.data
        else:
            result = paste(node.left) + paste(node.right)
            node.data = result
            return result
    paste(tree)

    return tree

rawDescription: Mapping a list to a Huffman Tree whilst preserving relative order


code:
import numpy
numpy.nextafter(1, 0)

rawDescription: How do I clip a floating-point number to just below a limit?

description: Clip a floating-point number to just below a limit


code:
import numpy as np
a = [1,2,3,4,5]
a_arr = np.array(a)
b = a_arr * np.arange(1,a_arr.shape[0]+1)
b

rawDescription: calculations using both a value from a list and the index of that value?

description: Calculations using both a value from a list and the index of that value


rawDescription: Rendering vectors in a sphere, with better perception


code:
from operater import itemgetter

i = min((x for x in aList if x[2] == 1), key=itemgetter(1))

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
print(foo.bar._decorators)
# (<function many at 0xb76d9d14>, <function decos at 0xb76d9d4c>, <function here at 0xb76d9d84>)

rawDescription: Introspection to get decorator names on a method?


code:
def rcount(a):
    without_reset = (a == 1).cumsum()
    reset_at = (a == 0)
    overcount = np.maximum.accumulate(without_reset * reset_at)
    result = without_reset - overcount
    return result

rawDescription: Cumulative counts in NumPy without iteration


rawDescription: Dictionaries containing the biggest values


rawDescription: Query regarding the "width" option for format specifiers in python?


code:
writer = csv.writer(open('/tmp/output.csv', 'w'))
writer.writerows(lines)

rawDescription: Change specific value in CSV file via Python


code:
with open("/dev/null", "w") as devnull:
    subprocess.Popen(["echo", "foobar"], stdout=devnull)

rawDescription: How do I change that which is inherited by stdout=None in subrocess.Popen(stdout=None)?

description: Change that which is inherited by stdout=None in subrocess.Popen(stdout=None)


code:
import ipaddress
addr = str(ipaddress.ip_address(167772160))
assert addr == '10.0.0.0'

rawDescription: using inet_ntoa function in Python

description: Using inet_ntoa function in Python


code:
encoded = unicodevalue.encode('utf8')
sliced = encoded[:1000]

while True:
    try:
        sliced.decode('utf8')
    except UnicodeDecodeError:
        sliced = sliced[:-1]  # remove one invalid byte
    else:
        break

rawDescription: python : read first 1000 bytes from a unicode string

description: Python : read first 1000 bytes from a unicode string


code:
my_file.write(a)
# ...
my_file.write(b)
# ...
my_file.write(c)

rawDescription: Three ways to print in Python -- when to use each?


code: aapl = aapl.asfreq('B', method='ffill')

rawDescription: How can I approximate the periodicity of a panda time Series

description: Approximate the periodicity of a panda time Series


code: my_ordered_fields = ['example','simple'] #or ['example','simple','next','more next','..etc..']

rawDescription: Inserting complex dictionaries into a sqlite database?


rawDescription: Convert Python strings into floats explicitly using the comma or the point as separators


code:
def search(x, seq):
    for i, v in enumerate(seq):
        if x < v:
            return i
    return len(seq)

rawDescription: how to define sort_tuple that returns a tuple in ascending order

description: Define sort_tuple that returns a tuple in ascending order


code:
class Test():
    def __init__(self):
        self.some_number = 0
        self.other_number = 0

    def update_values(self):
        self.some_number = 2
        self.other_number = 3

    @property
    def lst(self):
        return [self.some_number, self.other_number]

    @property
    def dic(self):
        return {'some_number': self.some_number,
                'other_number': self.other_number}

rawDescription: python update class's list or dictionary when variables change elsewhere

description: Python update class's list or dictionary when variables change elsewhere


code:
x = "nurses run"
b=[str(letter) for letter in x if letter.isalpha()]

b
c = b[::-1]
b == c

rawDescription: checking if the given inputted word is a palindrome or not

description: Checking if the given inputted word is a palindrome or not


code:
import subprocess
from win32process import CREATE_NO_WINDOW

p = subprocess.Popen(
            cmdstring,
            stdin=subprocess.PIPE,
            bufsize=-1,
            shell=False,
            creationflags = CREATE_NO_WINDOW
            )

rawDescription: How to hide PhantomJS console when running a GUI app in Py2Exe?

description: Hide PhantomJS console when running a GUI app in Py2Exe


rawDescription: Test if value exists in several lists

description: Test if value exists in several lists


code:
# make some z vlues
z = numpy.sin(xy[:,1]-0.2*xy[:,1])

rawDescription: Using scipy's kmeans2 function in python


code:
rarr = np.random.random((100, 20))
frarr = f(rarr)

rawDescription: translating matlab code to python: optmizing numerical functions

description: Translating matlab code to python: optmizing numerical functions


code:
import pyparsing as pyp
ident = pyp.Combine(pyp.Literal('foobar')+pyp.Word(pyp.alphas))('foo')
for match in ident.searchString('bar foobarfoo bar foobarbafoo'):
    print(match.foo)

rawDescription: Is there a "startswith" method in pyparsing


rawDescription: Speed up array query in Numpy/Python

description: Speed up array query in Numpy/Python


code:
with open('infilename', 'r') as infile:
    reader = csv.reader(infile)
    for row in reader:
        stripped_value = re.sub(r'^0{3}', '', row[5])

rawDescription: stripping the zeros in csv with python

description: Stripping the zeros in csv with python


code:
import xlrd

def _isEmpty(_):
        return ''

def _isString(element):
        return element.value.encode('ascii', 'ignore')

def _isFloat(element):
    return float(element.value)

def _isDate(element):
    import datetime
    rawDate = float(element.value)
    return (datetime.datetime(1899, 12, 30) +
            datetime.timedelta(days=rawDate))

def _isBool(element):
    return element.value == 1

def _isExcelGarbage(element):
    return int(element.value)

_options = {0: _isEmpty,
            1: _isString,
            2: _isFloat,
            3: _isDate,
            4: _isBool,
            5: _isExcelGarbage,
            6: _isEmpty}

def WorkbookToDict(filename):
    '''
        Reads .xlsx file into dictionary.

        The keys of the dictionary correspond to sheet names in the Excel workbook.
        The first row of the Excel workbook is taken to be column names, and each row
        of the worksheet is read into a separate dictionary, whose keys correspond to
        column names. The collection of dictionaries (as a list) forms the value in the
        dictionary. The output maps sheet names (keys) to a collection of dictionaries
        (value).
    '''
    book = xlrd.open_workbook(filename)
    allSheets = {}
    for s in book.sheets():
        thisSheet = []
        headings = [_options[x.ctype](x) for x in s.row(0)]

        for i in range(s.nrows):
            if i == 0:
                continue

            thisRow = s.row(i)
            if len(thisRow) != len(headings):
                raise Exception("Mismatch between headings and row length in ExcelReader")

            rowDict = {}
            for h, r in zip(headings, thisRow):
                rowDict[h] = _options[r.ctype](r)
            thisSheet.append(rowDict)
        allSheets[str(s.name)] = thisSheet
    return allSheets

rawDescription: Python script to manipulate excel sheets by auto-filling spaces in columns


code:
import re

integers = re.compile(r'(?<!\S)\d+(?!\S)')
integers.findall(stringy)

rawDescription: Python 2.7: Faster/better way to extract all integer values from a string?


code:
import datetime
now = datetime.datetime.now
now().strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Shorter version of now()

description: Shorter version of now()


code:
T
TT
TTT
TT
T

rawDescription: Triangle of "T" in Python

description: Triangle of "T" in Python


code:
from collections import OrderedDict

od = OrderedDict()
import csv
import re
with open("in.csv") as f,open("new.csv", "w") as out:
    header = next(f)
    for line in f:
        loc, rest = re.split("\s{2,}",line.rstrip(),1)
        od.setdefault(loc, []).extend(rest)
    out.write(header)
    for loc, vals in od.items():
        out.write("{} ".format(loc))
        out.write(" ".join(vals))

rawDescription: Python: Reading thru CSV file, finding columns with same value and appending their other column values


code: df

rawDescription: Conditional Cell Substitution in Pandas, Python 2.7


code:
d = {"foo": 42, "bar": 23}
items = list(d.items())
dict(items)

rawDescription: deconstructing and reconstructing python dictionary

description: Deconstructing and reconstructing python dictionary


code:
a = [row['x']+a*row['y']+b*row['z'] for row in
     tab.read_sorted('z', checkCSI=True)]

rawDescription: What is the most memory efficient way to combine read_sorted and Expr in pytables?


code:
import os

rootDir = '.'
files = {}
for dirName, subdirList, fileList in os.walk(rootDir):
    files[dirName] = fileList

rawDescription: How to read folder structure and assign it to datastructure?

description: Read folder structure and assign it to datastructure


code:
def my_processor(request, id):
    context = {'edit':InfoPredioGeneral.objects.filter(pk=id),
               'p':InfoPredioGeneral.objects.filter(user_id=request.user).latest('id')}
    return context

rawDescription: Accessing to PK in Function Based View in a Template Context Processor


rawDescription: Python code has the following import

description: Python code has the following import


code:
import lxml.html
from lxml.cssselect import CSSSelector
content = result.read()
page_html = lxml.html.fromstring(content)

elements = page_html.xpath('//*[self::div or self::span]')

rawDescription: lxml findall div and span tags

description: Lxml findall div and span tags


code:
playcount = tree.find('Playcount')
playcount.text = "2"

rawDescription: Python ElementTree XML Modifying Elements with Multiple Values


code:
import openpyxl
import csv

wb = openpyxl.load_workbook('test.xlsx')
sh = wb.get_active_sheet()
with open('test.csv', 'wb') as f:
    c = csv.writer(f)
    for r in sh.rows:
        c.writerow([cell.value for cell in r])

rawDescription: How to save an Excel worksheet as CSV from Python (Unix)?

description: Save an Excel worksheet as CSV from Python (Unix)


code:
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
    if seq_record.id == name:
        return seq_record.seq

rawDescription: Search Fasta file in python, return read efficiently


code:
def f(z):
    globs = {'Y': z}
    exec('def closure():\n return Y*2', globs)
    return globs['closure']

rawDescription: How to dynamically construct a closure's namespace "pythonically"

description: Dynamically construct a closure's namespace "pythonically"


code:
# equal-width bins
df['inc_index'] = pd.cut(df.A, bins=4, labels=[1, 2, 3, 4])

# custom bin edges
df['inc_index'] = pd.cut(df.A, bins=[0, 20000, 30000, 40000, 50000],
                         labels=[1, 2, 3, 4])

rawDescription: Python/Pandas - Best way to group by criteria?


rawDescription: How to find most frequent values in numpy ndarray?

description: Find most frequent values in numpy ndarray


rawDescription: Remove NaN and convert to float32 in Python Pandas


code:
import numpy as np
import pandas as pd
import gc

A = pd.DataFrame({'score':np.random.random(32346018), 'coordinate':np.arange(1, 32346019)})
peak_centers = []
peak_scores = []
exclusion = 147
count = 0
while A.shape[0] > 0:
    gc.collect()  # Force garbage collection.
    count += 1    # Increment the iteration count.
    print('iteration %d, shape %s' % (count, A.shape))
    raw_input()   # Wait for the user to press Enter.
    idx = A.score.values.argmax()
    one_center = A.coordinate.iloc[idx]
    # peak_centers and peak_scores are python lists
    peak_centers.append(one_center)
    peak_scores.append(A.score.iloc[idx])
    print(len(peak_centers), len(peak_scores))
    # exclude the coordinates around the selected peak
    A = A.loc[(A.coordinate <= one_center - exclusion) | (A.coordinate >= one_center + exclusion)]

rawDescription: Memory usage accumulated in while loop

description: Memory usage accumulated in while loop


code:
import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""
    result = []
    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)
    return unicode(delim.join(result))

rawDescription: Normalizing unicode text to filenames, etc. in Python


code: [chr((ord(i)+ord(j))%26+97) for i,j in zip(uinput,uinput2)]

rawDescription: Adding list/string ord() values in Python


code:
def addQuestion(self):
    question = ' '.join(self.stack)
    answer = input(question)

rawDescription: Adding a string with spaces to a stack

description: Adding a string with spaces to a stack


rawDescription: is there a way to get the index for multiple lists python?

description: Is there a way to get the index for multiple lists python


code:
def get_Change_selection(self,value):
    global my_change
    my_change = value
    if value == 'Yes':
        self.textChanges.config(state=stateOpts[0])
    else:
        self.textChanges.config(state=stateOpts[1])
    self.dropVarChanges.set(value)

    return

rawDescription: python tkinter: use a drop-down menu to enable a text field

description: Python tkinter: use a drop-down menu to enable a text field


rawDescription: Python: Sort a list into multiple lists or dictionary


code:
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

rawDescription: Does Python all(list) use short circuit evaluation?


rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


rawDescription: How to quickly count number of 0(s) in a binary list?

description: Quickly count number of 0(s) in a binary list


code:
class ResultSet(list):
    """A ResultSet is just a list that keeps track of the SoupStrainer
    that created it."""
    def __init__(self, source, result=()):
        super(ResultSet, self).__init__(result)
        self.source = source

rawDescription: Extract single href from a web page

description: Extract single href from a web page


rawDescription: How to escape special characters of a string with single backslashes

description: Escape special characters of a string with single backslashes


code:
class Foo(Base1, Base2):
    bar = 'baz'

    def spam(self):
         return 'ham'

rawDescription: Python - type(name,bases,dict)

description: Python - type(name,bases,dict)


code:
import numpy as np
filter = [np.nan, 'Like', 'Liked']

df.apply(lambda column: column[~column.isin(filter)].reset_index(drop=True))

rawDescription: Getting Dataframe from existing Dataframe after some filter


code:
def is_abecedarian(word):
    return word == ''.join(sorted(word))

rawDescription: Calling Python Function with string argument


code: df['group'] = df['mask'].cumsum()

rawDescription: Generate a multi-indexed dataframe from a dictionary with different length of values


code: trt = ['4' if word == '5' else word for word in trt]

rawDescription: Python - how to replace string in a list?


code:
sam1_identifiers = set()
for line in reader1:
    sam1_identifiers.add(line[0])

rawDescription: Python: Fastest way of parsing first column of large table in array


code:
sum = result.sum(level=0, axis=1)

print(result.div(sum, axis=1, level=0))

rawDescription: How to normalize MultiIndex DataFrame with its sum values

description: Normalize MultiIndex DataFrame with its sum values


code:
listData = []
for A in range(1, 3):
    for B in range(4, 6):
        for C in range(7, 10):
            listData.append([A,B,C, A+B+C]) #I just used A+B+C instead of the func f

df = pandas.DataFrame(columns = ["A", "B", "C", "Output"], data = listData)
print(df)

rawDescription: how to output the result of a nested loop using Python

description: Output the result of a nested loop using Python


code: ofset = range(len(objlist)+1)

rawDescription: Splitting Python Integer(blender3d)

description: Splitting Python Integer(blender3d)


rawDescription: Find values in mongodb with array

description: Find values in mongodb with array