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

MONTH_COUNT = 3

driver = webdriver.Firefox()
driver.maximize_window()
driver.get("https://www.airbnb.pt/rooms/265820")

# wait for the check in input to load
wait = WebDriverWait(driver, 10)
elem = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.book-it-panel input[name=checkin]")))
elem.click()

# iterate over the month count
for month in range(MONTH_COUNT):
    # wait for datepicker to load
    wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, '.ui-datepicker:not(.loading)'))
    )

    # getting current month for displaying purposes
    current_month = driver.find_element_by_css_selector(".ui-datepicker-month").text
    print(current_month)

    # iterate over days
    days = driver.find_elements_by_css_selector(".ui-datepicker table.ui-datepicker-calendar tr td")
    for cell in days:
        day = cell.text.strip()
        if not day:
            continue

        if "ui-datepicker-unselectable" in cell.get_attribute("class"):
            status = "Unavailable"
        else:
            status = "Available"

        price = "n/a"
        if status == "Available":
            # hover the cell and wait for the tooltip
            ActionChains(driver).move_to_element(cell).perform()
            price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.datepicker-tooltip'))).text

        print(day, status, price)

    print("-----")
    # click next month
    driver.find_element_by_css_selector("a.ui-datepicker-next").click()

driver.close()

rawDescription: Getting availability from datepicker for x months for a site


code:
import numpy as np
pvt = pd.pivot_table(df, values=['duration'],index=['resource','activity'], columns=['project_id'], aggfunc=np.sum,margins=True, fill_value=0)

rawDescription: List of dictionary in python as HTML Table format


code:
from collections import deque
from itertools import product
from string import ascii_lowercase, digits

def generate_words(start, length, _chars=ascii_lowercase + digits):
    remainder = length - len(start)
    if remainder < 1:
        yield start
        return
    for letters in product(_chars, repeat=remainder):
        combo = deque(letters + (start,))
        for _ in range(remainder + 1):
            yield ''.join(combo)
            combo.rotate()

rawDescription: Make a list of words from given characters


code:
soup = BeautifulSoup(html_doc, "lxml")
soup.head

rawDescription: Can we convert all XML tags to lowercase in Beautifulsoup


rawDescription: Python / PyMongo - How to convert a MongoDB find() query to a PyMongo dictionary


code:
import collections
def probability(n, s, t):
    prev = {0:1} #previous roll is 0 for first time
    for _ in range(n):
        cur = collections.defaultdict(int) #current probability
        for r,times in prev.items():
            for i in range(1,s+1):
                #if r occured `times` times in the last iteration then
                #r+i have `times` more possibilities for the current iteration.
                cur[r+i]+=times
        prev = cur #use this for the next iteration

    return cur[t] / s**n
    #return round(cur[t] / s**n , 4)

rawDescription: probability of T total eyes when throwing N dice with S sides

description: Probability of T total eyes when throwing N dice with S sides


code:
import copy
for i in copy.copy(test):
    if i not in ["C","D"]:
        test.remove(i)

rawDescription: How can I loop through a list of strings?

description: Loop through a list of strings


code:
number = 0
for digit in numbers:
    number = number * 10 + digit
number

rawDescription: Convert an int list into an int number

description: Convert an int list into an int number


code:
func_dict = {}

def collected_func(key):
    def decorator(func):
        func_dict[key] = func
        return func
    return decorator

@collected_func(12)
def foo():
    pass

rawDescription: python function that returns a function from list of functions

description: Python function that returns a function from list of functions


code: list_rho.extend(val.split(", "))

rawDescription: Python3 input() floats list

description: Python3 input() floats list


code: animate /path/to/animated.gif

rawDescription: How to display an animated gif with Linux?

description: Display an animated gif with Linux


code:
import ctypes as C
import numpy as np
from numpy.ctypeslib import as_ctypes
lib = C.CDLL("libmytest.so")

def set_N_threads(nthreads):
    self.lib.omp_set_num_threads(nthreads)

def do_some_task(input_array):
    input_array = input_array.astype("float32")
    output_array = np.empty_like(input_array)
    lib.do_some_omp_task(as_ctypes(input_array),
                         as_ctypes(output_array),
                         C.c_size_t(input_array.size))
    return output_array

rawDescription: Extending Python with parallelized C programs (under OMP)


code:
{'Alphabet overtakes Apple in market value - for now': 'https://in.finance.yahoo.com/news/alphabet-overtakes-apple-market-value-140918508.html',
 'Alphabet passes Apple to become most valuable traded U.S. company': 'https://in.finance.yahoo.com/news/alphabet-passes-apple-become-most-012844730.html',
 'Apple bets new 4-inch iPhone to draw big-screen converts in China, India': 'https://in.finance.yahoo.com/news/apple-bets-4-inch-iphone-112024627.html',
 'Apple iPhone sales weaker than expected': 'https://in.finance.yahoo.com/news/apple-iphone-sales-weaker-expected-221908381.html',
 'Apple likely to invoke free-speech rights in encryption fight': 'https://in.finance.yahoo.com/news/apple-likely-invoke-free-speech-030713050.html',
 'Apple sees first sales dip in more than a decade as super-growth era falters': 'https://in.finance.yahoo.com/news/apple-sells-fewer-iphones-expected-213516373.html',
 'Apple shares fall most in two years in wake of earnings report': 'https://in.finance.yahoo.com/news/apple-shares-seen-staying-muted-132628994.html',
 "Apple's new iPhone faces challenge measuring up in China, India": 'https://in.finance.yahoo.com/news/apples-iphone-faces-challenge-measuring-002248597.html',
 "Bad run continues for 'Freedom 251', website down again on second day": 'https://in.finance.yahoo.com/news/bad-run-continues-freedom-251-092804374.html',
 "EXCLUSIVE - Common mobile software could have opened San Bernardino shooter's iPhone": 'https://in.finance.yahoo.com/news/common-mobile-software-could-opened-030713243.html',
 'Foxconn says in talks with Sharp over deal hitch; hopes for agreement': 'https://in.finance.yahoo.com/news/sharp-shares-plunge-foxconn-puts-031032213.html',
 'Older Headlines': '/q/h?s=AAPL&t=2016-01-27T03:49:08+05:30',
 'Samsung Elec warns of difficult 2016 as smartphone troubles spread': 'https://in.finance.yahoo.com/news/samsung-electronics-warns-difficult-2016-003517395.html',
 'Samsung wins appeal in patent dispute with Apple': 'https://in.finance.yahoo.com/news/samsung-wins-appeal-patent-dispute-022120916.html',
 "Signs of life for Apple's stock as Wall St eyes new iPhone": 'https://in.finance.yahoo.com/news/signs-life-apples-stock-wall-165820189.html',
 'Solid support for Apple in iPhone encryption fight - Reuters/Ipsos': 'https://in.finance.yahoo.com/news/solid-support-apple-iphone-encryption-121255578.html',
 'U.S. appeals court upholds Apple e-book settlement': 'https://in.finance.yahoo.com/news/u-appeals-court-upholds-apple-164738354.html',
 'U.S., Apple ratchet up rhetoric in fight over encryption': 'https://in.finance.yahoo.com/news/u-apple-ratchet-rhetoric-fight-030713673.html',
 'With China weakening, Apple turns to India': 'https://in.finance.yahoo.com/news/china-weakening-apple-turns-india-032020575.html'}

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code: [a['pos'][name]>b['pos'][name] for name in ['x','y']]

rawDescription: comparing numpy structured arrays

description: Comparing numpy structured arrays


rawDescription: Python: transform a list of lists of tuples


code: r

rawDescription: How to track the progress of individual tasks inside a group which forms the header to a chord in celery?

description: Track the progress of individual tasks inside a group which forms the header to a chord in celery


code:
myArr = bytearray()
with open(r"C:\Users\User\MyFileName.bin", "rb") as f:
    byte = f.read(1)
    while byte:
        myArr.append(ord(byte))
        byte = f.read(1)

rawDescription: "unicode argument without an encoding" when adding a byte to bytearray using extend


code: sum(1 for v in l if v == 2)

rawDescription: Count by > DATE

description: Count by > DATE


code:
import itertools

x = [3, 5, 6, 1, 2]
y = [6, 7, 8, 9, 10]

lists = sorted(itertools.izip(*[x, y]))
new_x, new_y = list(itertools.izip(*lists))

# import operator
# new_x = map(operator.itemgetter(0), lists)        # [1, 2, 3, 5, 6]
# new_y = map(operator.itemgetter(1), lists)        # [9, 10, 6, 7, 8]

# Plot
import matplotlib.pylab as plt
plt.plot(new_x, new_y)
plt.show()

rawDescription: Python's Matplotlib plotting in wrong order


code:
final = []
for key, vals in processed.items():
    for start, end in vals:
        final.append("%s:%s:%s" % (key, str(start), str(end)))

rawDescription: Python - Overlapping Ranges - Determine unique positions


code:
@pytest.fixture(scope='session', autouse=True)
def someobj(request):
    return SomeObj()

rawDescription: How to share object from fixture to all tests using pytest?

description: Share object from fixture to all tests using pytest


code:
t = show(x)
t[0] # result
t[1] # a
t[2] # b

rawDescription: Python return true - false and value

description: Python return true - false and value


code:
for fname in walkPDFfiles('.'):
    print(fname, 'is PDF file.')

rawDescription: How to distinguish a PDF file from other files?

description: Distinguish a PDF file from other files


code:
while True:
    a = random_function()
    b = random_function()
    if a == b:
        break

rawDescription: (PYTHON) Until a == b

description: (PYTHON) Until a == b


code:
x = [(None, None, None), (None, None, None), (None, None, None)]
not any(any(inner) for inner in x)
x = [(None, None, None), (None, None, None), (None, None, 1)]
not any(any(inner) for inner in x)

rawDescription: Check if all elements in nested iterables evaluate to False


code:
import itertools

def generate_arrangements(iterable):
    iterator = iter(iterable)
    while True:
        number =  next(iterator)
        arrangement = list(list(row) for row in itertools.islice(iterator, 4))
        yield number, arrangement

(first_num, first_arr), (second_num, second_arr) = generate_arrangements(data)

rawDescription: Unpack a given number of items in Python?


rawDescription: When oracle virtualbox are set, How to get local ip address in python


code:
raw_packed = self.get_argument('packed_arg', None)
packed = {}
if raw_packed:
    packed = tornado.escape.json_decode(raw_packed)
arg1 = packed.get('arg1')
arg2 = packed.get('arg2')

rawDescription: Sending non-string argument in a POST request to a Tornado server


code:
def add( self, node, port=None, intfName=None, mode=None, return_mobilityhelper=False ):
    ...
    if return_mobilityhelper:
        return tb, mobilityhelper
    else:
        return tb

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


rawDescription: How to recursively add 1 to number 1000000 times without recursion limit change?

description: Recursively add 1 to number 1000000 times without recursion limit change


code:
import itertools

example = {((0, 0), (0, 2), (0, 3)): (-2, 0),
           ((1, 3), (0, 2), (0, 3)): (-5, 8),
           ((4, 7), (0, 2), (0, 1)): (3, -2)}
keyfunc = lambda x: x[0][1:] # [0] -> key; [1:] -> all-but-first tuple

items = sorted(example.items(), key=keyfunc)

for key, subiterator in itertools.groupby(items, keyfunc):
    # grouped by this
    print(key)
    for subkey, subvalue in subiterator:
        # but these are the actual things that were grouped
        print(subkey, ':', subvalue)

rawDescription: Group dictionary by a partial key

description: Group dictionary by a partial key


rawDescription: Using DataFrame to get matrix of identifiers


code:
import re

numbers = {}
with open('1.txt') as f:
    for line in f:
        row = re.split(r'(\d+)', line.strip())
        words = tuple(row[::2])  # Extract non-number parts to use it as key
        if words not in numbers:
            numbers[words] = [int(n) for n in row[1::2]]  # extract number parts.
        numbers[words] = [n+1 for n in numbers[words]]  # Increase numbers.
        row[1::2] = map(str, numbers[words])  # Assign back numbers
        print(''.join(row))

rawDescription: python managing redundant data by incrementing no. in a text file

description: Python managing redundant data by incrementing no. in a text file


code:
def union(a, b):
    return a + b

rawDescription: Python: Why "return" won´t print out all list elements in a simple for loop and "print" will do it?


rawDescription: How to create a new df.column based on 2+ conditions in Pandas without iteration?

description: Create a new df.column based on 2+ conditions in Pandas without iteration


rawDescription: Splitting a list in python

description: Splitting a list in python


code:
def processLine(line):
    userName = firstFour(string)
    names = nameArrangement(string)
    character = passwordGen()
    return userName + ", " + names + ", " + password

rawDescription: How can I split a file into seperate lines in python?

description: Split a file into seperate lines in python


code:
import numpy as np
np.in1d(A,B).any()

rawDescription: Check if 2 arrays have at least one element in common?


rawDescription: Pandas DataFrame.unstack() Changes Order of Row and Column Headers


code:
import re
from itertools import chain
lines = ["hello world", "second line", "third line"]
words = chain(*[re.split(r'\s+', line) for line in lines])

rawDescription: Return list of words from a list of lines with regexp


code: [x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]

rawDescription: element that appear more that once in the list in Python

description: Element that appear more that once in the list in Python


code:
for i in range(0, len(tables)):
    df = tables[i]
    df.replace(regex=True,inplace=True,to_replace='½',value='.5')
    df.iloc[:, 0] = pd.to_numeric(df.iloc[:, 0], errors='coerce')
    df1 = df[(df.iloc[:, 0] >= 900) & (df['0'] <= 999) & (df['0'].notnull())]
    print (df1)

rawDescription: Select all the rows based on a column value pandas


code: [t[:-1] for t in listoftuples]

rawDescription: removing something from a list of tuples

description: Removing something from a list of tuples


rawDescription: python 3 read array (list?) into new values

description: Python 3 read array (list?) into new values


code:
import requests
from os.path  import basename

r = requests.get("xxxxxxxxx")
soup = BeautifulSoup(r.content)

for link in links:
    if "http" in link.get('src'):
        lnk = link.get('src')
        with open(basename(lnk), "wb") as f:
            f.write(requests.get(lnk).content)

rawDescription: How to download images from BeautifulSoup?

description: Download images from BeautifulSoup


code:
def count_num(filename):
    myfile = open(filename)
    text = myfile.read() # Note: added parentheses
    words = text.split()
    sum_ = 0
    for word in words:
        # Check if can convert to int type safely
        sum_ += int(word) if word.isdigit() else 0

    return sum_

print(count_num(some_file))

rawDescription: How to open a text file that contains numbers, and print the sum. Must use a for/while loop?

description: Open a text file that contains numbers, and print the sum. Must use a for/while loop


code: help(sum)

rawDescription: How to print your function's documentation python

description: Print your function's documentation python


code: suit_sels = [random.randint(0,3) for i in range(13)]

rawDescription: Card generator game printing in a column, not a row


code: Foo: Hi

rawDescription: Overwrite built-in function

description: Overwrite built-in function


rawDescription: How to coarse grain xy coordinates

description: Coarse grain xy coordinates


code:
import B
B.IMC = IMC

rawDescription: Python namespaces: How to make unique objects accessible in other modules?


code:
rows = [['user1@a.com','user4@b.com','user3@c.com'],
        ['user2@a.com'],
        ['user3@c.com', 'user1@a.com'],
        ['user4@b.com','user1@a.com','user3@b.com']]

rawDescription: Sorting rows into groups based on shared values


code:
from cffi import FFI
from numpy import uint32

__all__ = ['integer_sort']

ffi = FFI()
ffi.cdef('void u4_sort(unsigned* a, const long sz);')
C = ffi.dlopen('u4_sort.so')

def integer_sort(arr):
    assert arr.dtype == uint32, 'Expected uint32, got {}'.format(arr.dtype)
    begin = ffi.cast('unsigned*', arr.ctypes.data)
    C.u4_sort(begin, arr.size)

rawDescription: How to sort an array of integers faster than quicksort?

description: Sort an array of integers faster than quicksort


code:
form_list = ['blah', 12, [], {}, 'yeah!']
print(list(map(type, form_list)))

rawDescription: Best way to find out the object type of each item in a list

description: Find out the object type of each item in a list


code:
...

y_fmt = tick.FormatStrFormatter('%2.2e')
ax.yaxis.set_major_formatter(y_fmt)

...

rawDescription: Matplotlib pyplot axes formatter

description: Matplotlib pyplot axes formatter


code:
from string import ascii_letters
stripped_str = whatever_str.rstrip(ascii_letters)

rawDescription: Is there an elegant way to strip all alphabetic characters from the end of a string?


code: {blocked.keys()[0]:str({k: v for k, v in all_odds.values()[0].iteritems() if k not in blocked.values()[0]})}

rawDescription: Removing nested dict items with dict comprehension


code:
[
   {
      'isMapped':'',
      'haveRev':'10',
      'headAction':'edit',
      'headModTime':'1465312503',
      'clientFile':'/users/jen/dvcs/usage/home/depot_create.rb',
      'headRev':'10',
      'headChange':'7666',
      'headTime':'1465312526',
      'depotFile':'//depot/scripts/depot_create.rb',
      'headType':'text'
   }
]

rawDescription: P4python: get changelist number of latest revision of file checked in in perforce by python code


code:
elements[3] is elements[3]
elements[3] == elements[3]

rawDescription: Why is my object properly removed from a list when __eq__ isn't being called?


code:
from yourapp.models import Person

dad = Person.objects.create(name="Dad")
john = Person.objects.create(name='John', parent=dad)
jim = Person.objects.create(name='Jim', parent=john)

rawDescription: In Django how can I search for related models based on the order they were added to a ManyToMany Field?


code:
s1="""l0 = ["A","B", "A","B","B", "A","B","B","B","B", "A", "A", "A","B"]

def gen_group(L):
    out = ["A"]
    while L:
        for ind, elem in enumerate(L[1:]):
            if elem == "A":
                break
            else:
                out.append(elem)

        for i in range(ind + 1):
            L.pop(0)

        yield out
        out = ["A"]

out =gen_group(l0)"""

s2 = """A, B = 'A', 'B'
x = [A,B, A,B,B, A,B,B,B,B, A, A, A,B]
map(lambda arr: [i for i in arr[0]], map(lambda e: ['A'+e], ''.join(x).split('A')[1:]))"""

s3 = """def subListGenerator(f,items):
    i = 0
    n = len(items)
    while i < n:
        sublist = [items[i]]
        i += 1
        while i < n and not f(items[i]):
            sublist.append(items[i])
            i += 1
        yield sublist

items = ['A', 'B', 'A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'B']
g = subListGenerator(lambda x: x == 'A',items)"""

rawDescription: How can I group a list of objects by continuity?

description: Group a list of objects by continuity


code: testspec = imp.load_source("testspec", args.test)

rawDescription: Is there a Python test framework suitable to run simulations


code:
calls = ['admob.api.oauthcert', 'admob.api.newsession', 'admob.endusercampaign']
from collections import Counter
Counter(reduce(lambda x,y: x+y,map (lambda x : x.split("."),calls))).most_common(2)

rawDescription: Python finding most common pattern in list of strings


code:
l = range(25)
np.matrix(np.reshape(l, (5,5)))

rawDescription: Create a matrix out of an array

description: Create a matrix out of an array


code:
f = SpellFactory()
f.setQuery('some query')
...

rawDescription: Python Twisted Client

description: Python Twisted Client


code: '\tdef test(self, arr1, arr2):\n'

rawDescription: Function arguments in creating function file dynamically


code: np.char.rstrip(rawData, b'"')

rawDescription: Not understood behavior of Numpy genfromtxt


rawDescription: dynamically create and search a dictionary of IPs with their seen timestamps

description: Dynamically create and search a dictionary of IPs with their seen timestamps


code:
from itertools import product
for orientation in product(*zip(rectangles, map(Rectangle.flipped, rectangles))):
    print(orientation)

rawDescription: Python list of objects, get all 'orientations' of attributes


rawDescription: Splitting or pulling only integers in an array - python


code:
for n, df in dictDF.iteritems():
    df['period'] = n

rawDescription: Pandas: Dict of data frames to unbalanced Panel


rawDescription: matplotlib problems plotting logged data and setting its x/y bounds

description: Matplotlib problems plotting logged data and setting its x/y bounds


code:
values = food_to_food_type.values()
dict( zip( values, [NUM_FOOD_TYPES]*len(values) ) )

rawDescription: How can I "map" a dict to change only the values in Python


code:
def three_consec (string, character):
    found = 0
    for c in string:
        if c == character:
            found += 1
        else:
            found = 0

        if found > 2:
            return True

    return False

rawDescription: trying to find if a character appears successively in a string

description: Trying to find if a character appears successively in a string


code: axes.axes.fly_mode = 'none'

rawDescription: Preventing axis from updating on camera move - mayavi python


code:
import operator
from itertools import product

unary_op = operator.pos, operator.neg

for ops in product(unary_op, repeat=3):
    result = sum(op(var) for op, var in zip(ops, (var1, var2, var3)))

rawDescription: Pythonic way to iterate and/or enumerate with a binary 'switch'


code:
import inspect

def square_param(param):
    def func_decorator(func):
        def func_caller(*args,**kwargs):
            funparams = inspect.getargspec(func).args
            if param in funparams:
                i = funparams.index(param)
                if len(args) > i:
                    args = list(args)   # Make mutable
                    args[i] = args[i] * args[i]
            if param in kwargs:
                kwargs[param] = kwargs[param] * kwargs[param]
            return func(*args,**kwargs)
        return func_caller
    return func_decorator

rawDescription: How can I treat positional arguments as keyword arguments in Python 2

description: Treat positional arguments as keyword arguments in Python 2


code:
normalized_totals = daily_totals.groupby(lambda d: d.month).transform(lambda x: float(x)/x.sum())
normalized_totals

rawDescription: Reshaping tables in pandas

description: Reshaping tables in pandas


rawDescription: draw random element in numpy

description: Draw random element in numpy


code:
list_display('get_related_field')
...
def get_related_field(self, obj):
    return obj.related_object.some_field
get_related_field.short_description = 'Some Field' # Column header
get_related_field.admin_order_field = 'related_object__some_field'

rawDescription: Access data from a related class in Django


code:
def myfunction(list_a, list_b):
   return dict(zip(list_a, list_b))

my_dict = myfunction(some_list_a, some_list_b)

rawDescription: Is it possible to create a dictionary inside a function using python?


code:
import operator
def differ(w1, w2):
    return len(w1) == len(w2) and sum(map(operator.ne, w1, w2)) == 1

rawDescription: Comparing characters in a string

description: Comparing characters in a string


rawDescription: Number divided by 4 by python regex

description: Number divided by 4 by python regex


code:
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

rawDescription: Interleaving Lists in Python

description: Interleaving Lists in Python


code:
import tokenize, io

code_string = """
# Comment 1
x = "#Notacomment"
##### Comment 2 #####
"""

buf = io.StringIO(code_string)

for line in tokenize.generate_tokens(buf.readline):
    if line.type == tokenize.COMMENT:
        print(line)

rawDescription: Is there a tool to extract all comments from python source, preserving source line/col info?


code:
import requests
import math
from bs4 import BeautifulSoup

url = "http://www.agoda.com/ambassador-hotel-taipei/hotel/taipei-tw.html?asq=8m91A1C3D%252bTr%252bvRSmuClW5dm5vJXWO5dlQmHx%252fdU9qxilNob5hJg0b218wml6rCgncYsXBK0nWktmYtQJCEMu0P07Y3BjaTYhdrZvavpUnmfy3moWn%252bv8f2Lfx7HovrV95j6mrlCfGou99kE%252bA0aX0aof09AStNs69qUxvAVo53D4ZTrmAxm3bVkqZJr62cU&tyra=1%257c2&searchrequestid=2e2b0e8c-cadb-465b-8dea-2222e24a1678&pingnumber=1&checkin=2015-10-01&los=1"
res = requests.get(url)
soup = BeautifulSoup(res.text)

rooms = soup.select('.room-type')[1:] # the first instance of the class isn't a room

room_list = []

for room in rooms:
    room_info = {}

    room_info['en_room'] = room.select('.room-name')[0].text.strip()
    room_info['currency'] = room.select('.currency')[0].text.strip()
    room_info['price'] = room.select('.sellprice')[0].text.strip()

    sp_info = room.select('.left-room-info')[0].text.strip().split('\r')
    if len(sp_info) > 1:
        sp_info = ", ".join([ info.strip() for info in sp_info ])
    elif not sp_info[0]: # check for empty string
        sp_info = "N/A"
    room_info['sp_info'] = sp_info

    pay_later = room.select('.book-now-paylater')
    room_info['pay_later'] = pay_later[0].text.strip() if pay_later else "N/A"

    room_list.append(room_info)

rawDescription: Python - Crawl Multiple Classes within a Page Using BeautifulSoup


rawDescription: stacking 2D matrix using Python

description: Stacking 2D matrix using Python


code:
import csv

with open("test.csv", "wb") as f:
    csv.writer(f).writerows((k, v) for k, v in coordDict.iteritems())

rawDescription: creating a csv file from svg paths and ids

description: Creating a csv file from svg paths and ids


code:
badCharSet = set(badChars)
any((c in badChars) for c in yourString)

rawDescription: Find which lines in a file contain certain characters


code:
import networkx as nx
G = nx.MultiGraph()
G.add_edge(1,2,color='red')
G.edges(data=True)
G.add_edge(1,2,color='blue')
G.edges(data=True)
G.edges(data=True,keys=True)
G.add_edge(1,2,key=0,color='blue')
G.edges(data=True,keys=True)
G[1][2]
G[1][2][0]['color']='green'
G.edges(data=True,keys=True)

rawDescription: Add new attribute to an edge in networkx


rawDescription: create column names by joining two labels of different levels with pandas

description: Create column names by joining two labels of different levels with pandas


code:
#!/usr/bin/env python3
from datetime import datetime, timedelta

assert year > 100
utc_time = datetime(year, month, day, hours, minutes, seconds, ms*1000)
millis = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1)

rawDescription: Equivalent of date.utc in python

description: Equivalent of date.utc in python


code:
def apply_(f,*args,**kwargs):
  return f(*args,**kwargs)

multiprocessing.map(apply_,[(f,1) for f in functions])

rawDescription: Multiprocessing pool 'apply_async' only seems to call function once


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

# Generate some data...
x, y = np.mgrid[:141, :101]
z = np.cos(np.hypot(x, y))

# Plot the figure...
plt.pcolormesh(x, y, z, cmap=mpl.cm.Reds)

plt.show()

rawDescription: Customize x-axis in matplotlib

description: Customize x-axis in matplotlib


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

rawDescription: Implementing .all() for a list of booleans?


code: re.findall(r'taxid:(\d+)', s)

rawDescription: python regular expression substitute

description: Python regular expression substitute


rawDescription: BeautifulSoup/Python/HTML - Return the div class right after a specific div class


rawDescription: PyQt - forcing one tab to appear first?

description: PyQt - forcing one tab to appear first


code:
a = dict()
a['trees'] = dict()
a['trees']['oak'] = 453
a['trees']['pine'] = 12
a['trees']['chestnut'] = 65
b = a['trees']
for key,value in b.iteritems():
    b[key] = value + 100

a

rawDescription: Using FOR IN and dictionaries in PYTHON 2.7


code:
def isleaf(x):
    return not isinstance(x[1], tuple)

rawDescription: Inserting an element in list, at exact location, without array sizing in Python?


code:
def isAscii(s):
    return all(ord(c) < 128 for c in s)

rawDescription: Trouble converting certain special characters from Ascii in Python


code:
import project.foobar
project.foobar

rawDescription: Override namespace in Python

description: Override namespace in Python


code:
alist = [np.array([item, item+1]) for item in range(5)]
alist
np.array(alist)

rawDescription: collapse a list of ndarray to a matrix

description: Collapse a list of ndarray to a matrix


code:
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class MyModel(models.Model):
    field1 = models.TextField()
    field2 = models.IntegerField()

@receiver(pre_save, sender=MyModel)
def mymodel_save_handler(sender, instance, *args, **kwargs):
     if instance.field1 is None or instance.field1 == "":
         instance.field1 = default_value

rawDescription: How to change input fields while overriding a django save() method

description: Change input fields while overriding a django save() method


code:
def nub(it):
    seen = set()
    for x in it:
        if x not in seen:
            yield x
            seen.add(x)

rawDescription: python generators duplicates

description: Python generators duplicates


code:
for path_flag in path_flags:
  if flag == path_flag:
    make_next_absolute = True
    break

if flag.startswith( path_flag ):
    path = flag[ len( path_flag ): ]
    new_flag = path_flag + os.path.join( working_directory, path )
    break

rawDescription: YCM does not find my headers?

description: YCM does not find my headers


code: set_tids = set(tids)

rawDescription: How to do an efficient loop with comparisons and insertions in other lists

description: Do an efficient loop with comparisons and insertions in other lists


code:
fruits = ['Apple', 'Mango', 'Pineapple', 'Banana', 'Oranges']
sizes = ['small', 'medium', 'big']
list(itertools.product(fruits, sizes))

rawDescription: How to avoid hard coding in if condition of python script

description: Avoid hard coding in if condition of python script


code:
# Initialize one tagger
tagger = treetaggerwrapper.TreeTagger(TAGLANG='en')
# Loop over the files
all_tags = []
for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))):
    with codecs.open(filename, encoding='utf-8') as f:
        # Read the file
        content = f.read()
        # Tag it
        tags = tagger.tag_text(content)
        # add those tags to the master tag list
        all_tags.append(tags)

print(all_tags)

rawDescription: How to create a nested list from an object?

description: Create a nested list from an object


code:
np.any(np.isclose(c, a), axis=0)
#array([ True,  True, False, False], dtype=bool)

rawDescription: Pythonic and efficient way to do an elementwise "in" using numpy


code:
def rem(iterable):
    c = collections.Counter(iterable)
    for k in c:
        c[k] -= 1
    return sorted(c.elements())

rawDescription: Returning a copy of the list in which one instance of every value is removed


code: [int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))]

rawDescription: How do I turn a string of digits into a list of one-digit integers?

description: Turn a string of digits into a list of one-digit integers


code:
def _abc(cls, *args, **kwargs):
    pass

class Foo:
    abc = classmethod(_abc)

    @classmethod
    def abcd(cls, fn=_abc):
        pass

rawDescription: How to surely refer to global objects in a class during definition?

description: Surely refer to global objects in a class during definition


code:
dest = dict(orig)  # or orig.copy()
dest.update(extra)

rawDescription: Python append dictionary to dictionary

description: Python append dictionary to dictionary


rawDescription: Parsing Cisco Output in Python

description: Parsing Cisco Output in Python


rawDescription: How to re.sub() a optional matching group using regex in Python?

description: Re.sub() a optional matching group using regex in Python


code:
d = {}
d[8] = []
for i in range(3):
    d[i] = 9
    d[8].append(i)

rawDescription: Creating an alternating dictionary with a loop in Python


code:
from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://sa:saPassword@localhost:52865/myDb')
conn = engine.connect()
rows = conn.execute("select name FROM sys.databases;")
for row in rows:
    print(row["name"])

rawDescription: List names of all available MS SQL databases on server using python


code:
import tabulate

with open('path/to/output.csv') as inf:
    print(tabulate(inf, headers="firstrow"))

rawDescription: Print csv input file into a table of columns/rows


code: sorted((i,k) for i,j in mydict.items() for k in ([j] if isinstance(j, str) or isinstance(j, int) else j))

rawDescription: Python dictionary to sorted tuples, can this be done better?


code:
while not entry:
 entry = self.upload_chunk(start_byte, self.file_handle.read(self.chunk_size))
 start_byte += self.chunk_size

rawDescription: Using Google App Engine how to upload document in google docs (python)


code:
for part, level in matches(line):
    print(part)

rawDescription: Python 3 - Different way of writing a print statement


code:
def majority_element(seq, default=None):
    """Find which element in *seq* sequence is in the majority.

    Return *default* if no such element exists.

    Use Moore's linear time constant space majority vote algorithm
    """
    candidate = default
    count = 0
    for e in seq:
        if count != 0:
            count += 1 if candidate == e else -1
        else: # count == 0
            candidate = e
            count = 1

    # check the majority
    return candidate if seq.count(candidate) > len(seq) // 2 else default

rawDescription: Python Find Majority Number in O(n) time and O(1) memory


code:
def replace_letters(x,y):
   return x.replace(y,'')

rawDescription: Remove letters from sting

description: Remove letters from sting


code:
def my_function():
    self.display_views_by_country(doc, entry_doc_id.get())

command=my_function

rawDescription: Entry.get() returns nothing tkinter - python 3.4


code:
import networkx as nx
G=nx.Graph()
for person in persons:
  if person.father_id != -1:
    G.add_edge(person, persons_by_id[person.father_id])

rawDescription: How to directly access class instances through class dictionary in Python

description: Directly access class instances through class dictionary in Python


code:
@no_event
def callback2():
    ...

rawDescription: How can I prevent Tkinter from passing the event object in a binding? Is there any workaround to do this?

description: Prevent Tkinter from passing the event object in a binding? Is there any workaround to do this


code:
def inside_doctest(original_stdout=sys.stdout):
    return original_stdout != sys.stdout

rawDescription: How to determine whether code is running in a doctest?

description: Determine whether code is running in a doctest


rawDescription: not able to output specific row from xpath response

description: Not able to output specific row from xpath response


code:
for line in input_file:
    data = [float(x) for x in line.split(',')]

rawDescription: On significant figures of numbers in python


code:
import tempfile

path = tempfile.mktemp()
with open(path, "w") as fw:
    fw.write('''{"stuff": [{"a": 1, "b": 2, "c": 3}]}''')
df = sqlContext.read.json(path)
df.registerTempTable("df")

df.printSchema()
## root
##  |-- stuff: array (nullable = true)
##  |    |-- element: struct (containsNull = true)
##  |    |    |-- a: long (nullable = true)
##  |    |    |-- b: long (nullable = true)
##  |    |    |-- c: long (nullable = true)

sqlContext.sql("SELECT stuff[0].a FROM df").show()

## +---+
## |_c0|
## +---+
## |  1|
## +---+

rawDescription: SparkSQL sql syntax for nth item in array


code:
import random
data = [[random.randrange(10) for _ in range(3)], [random.randrange(10) for _ in range(3)]]

rawDescription: Plotting random points with Python in Linux


code:
def hashablize(obj):
    """Convert a container hierarchy into one that can be hashed.

    Don't use this with recursive structures!
    Also, this won't be useful if you pass dictionaries with
    keys that don't have a total order.
    Actually, maybe you're best off not using this function at all."""
    try:
        hash(obj)
    except TypeError:
        if isinstance(obj, dict):
            return tuple((k, hashablize(v)) for (k, v) in sorted(obj.iteritems()))
        elif hasattr(obj, '__iter__'):
            return tuple(hashablize(o) for o in obj)
        else:
            raise TypeError("Can't hashablize object of type %r" % type(obj))
    else:
        return obj

rawDescription: Is the pickling process deterministic?

description: Is the pickling process deterministic


code:
[{u'id': 7489651, u'position': {u'title': u'Director of Sales, New York '}},
 {u'id': 7489610,
  u'position': {u'title': u'Senior Software Development Engineer'}},
 {u'id': 7489572,
  u'position': {u'title': u'Senior Analyst, Marketing Analytics'}},
 {u'id': 7489559,
  u'position': {u'title': u'Director,  Quantitative Analytics'}},
 {u'id': 7489542, u'position': {u'title': u'Senior Quantitative Analyst'}},
 {u'id': 7489520,
  u'position': {u'title': u'Director - Progam Lead and Project Manager - Collateral Management'}},
 {u'id': 7489519, u'position': {u'title': u'Accounting and Finance Manager'}},
 {u'id': 7489508,
  u'position': {u'title': u'Software Development Engineer - Test'}},
 {u'id': 7489462,
  u'position': {u'title': u'Sr. Sales Executive - Technology'}},
 {u'id': 7489264, u'position': {u'title': u'Recruitment Manager'}}]

rawDescription: Parsing object in python

description: Parsing object in python


code:
l = lambda a, b: None
l.func_code.co_argcount

rawDescription: how do I find out how many arguments a lambda function needs

description: Find out how many arguments a lambda function needs


code:
for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Game = False
            break

rawDescription: Pygame - why my game repeats instead of closing?


rawDescription: Python Speeding Up Retrieving data from extremely large string


code:
from selenium.webdriver.common.action_chains import ActionChains

def get_properties(element):
    return {
        prop: element.value_of_css_property(prop)
        for prop in ['background-color', 'color', 'text-decoration']
    }

def is_hovered(driver, element):
    properties_before = get_properties(element)

    ActionChains(driver).move_to_element(element).perform()

    properties_after = get_properties(element)
    return properties_before != properties_after

rawDescription: xpath for capturing hover css property from selenium webelement in python

description: Xpath for capturing hover css property from selenium webelement in python


rawDescription: Storing a dict with np.savez gives unexpected result?


rawDescription: Slicing python matrix into quadrants

description: Slicing python matrix into quadrants


code: string_val = "x" * 10  # gives you "xxxxxxxxxx"

rawDescription: In Python, how do I create a string of n characters in one line of code?


rawDescription: how do I export my lists into an excel compatible file?

description: Export my lists into an excel compatible file


code:
RotMatrix = zero(3,3)
RotMatrix[0][0]=cos(Theta)
RotMatrix[0][1]=-1*sin(Theta)
RotMatrix[1][0]=sin(Theta)
RotMatrix[1][1]=cos(Theta)
RotMatrix[2][2]=1

rotated=mult(RotMatrix, original)

rawDescription: Rotation, scale and translate function for python


rawDescription: How to add a set of alphanumeric contents into a list using python?

description: Add a set of alphanumeric contents into a list using python


code:
df = df.groupby('index').first()
df

rawDescription: Find Unique Dates in Numpy Datetime Array


code:
# Create a simple Point class to represent the affine points.
from collections import namedtuple
Point = namedtuple("Point", "x y")

# The point at infinity (origin for the group law).
O = 'Origin'

rawDescription: Elliptic curve point addition over a finite field in Python


code:
from  collections import defaultdict

sequences = ['GATCCG', 'GTACGC']
d = defaultdict(lambda: defaultdict(int))  # d[char][position] = count
for seq in sequences:
    for i, char in enumerate(seq):  # enum('abc'): [(0,'a'),(1,'b'),(2,'c')]
        d[char][i] += 1

d['C'][3]  # 2
d['C'][4]  # 1
d['C'][5]  # 1

rawDescription: Counting the number of times a letter occurs at a certain position using python


code: [map(lambda x:x+1 ,group) for group in x]

rawDescription: Python: List comprehension list of lists


code:
class P(models.Model):
    pass

class T(models.Model):
    # on_delete=models.CASCADE is the default, including it here to be explicit
    p = models.ForeignKey(P, on_delete=models.CASCADE)

rawDescription: Django admin delete != Model.delete()

description: Django admin delete != Model.delete()


code:
generate_draw()
generate_draw()

rawDescription: How can I loop a lottery number generator?

description: Loop a lottery number generator


code:
g = sns.FacetGrid(df, col="variable", size=4, aspect=.7)
g.map(sns.boxplot, "genotype", "value", "environment").add_legend(title="environment")

rawDescription: Boxplots by group for multivariate two-factorial designs using matplotlib + pandas


rawDescription: Algorithm to offset a list of data

description: Algorithm to offset a list of data


code:
d = {}
for (i,st) in enumerate(start):
    d[st] = (shape[i],length[i],end[i])

rawDescription: Using a dictionary to index parallel arrays?


code:
# one side
gifts = Gift.query.filter(Gift.category == category).all()
# other side
gifts = Category.query.get(category_id).gifts

rawDescription: How to access child of child from parent in sqlalchemy?

description: Access child of child from parent in sqlalchemy


code: df.pivot('Symbol', 'TimeStamp').stack()

rawDescription: Pandas DataFrame - desired index has duplicate values


code:
def eliminate_shorter(list_of_lists):
    inputlist = sorted(list_of_lists, key=len)
    outputlist = [inputlist.pop()]
    numbers = set(outputlist[0])
    for sublist in reversed(inputlist):
        if not numbers.intersection(sublist):
            numbers.update(sublist)
            outputlist.append(sublist)
    return outputlist

rawDescription: How to remove list with in a list if an element in one list is present in the other

description: Remove list with in a list if an element in one list is present in the other


code: [x if x[0] == 'A' else "A" + x for x in y]

rawDescription: How to minimize string-appending to one line in Python?

description: Minimize string-appending to one line in Python


code:
from collections import Iterable

def product_of(items):
    if isinstance(items, Iterable):
        # list of items - reduce it
        total = 1
        for item in items:
            total *= product_of(item)   # <= recursive call on each item
        return total                    #    (could be a sub-list)
    else:
        # single value - return it
        return items

rawDescription: How do I multiply integers within a nested list?

description: Multiply integers within a nested list


code:
from tkinter import *
root = Tk()

root.grid_columnconfigure(0, weight=1)
#uncomment this line if you want the Label widget to stretch vertically.
#or leave it as is if you only want the Text widget to stretch.
#root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)

root.resizable(width = True, height = True)
label = Label(root, text = "Text")
label.grid(sticky="NEWS")

text = Text(root)
text.grid(sticky="NEWS")
root.mainloop()

rawDescription: Fill space with widgets on resize

description: Fill space with widgets on resize


code:
import pygraphviz as pgv
G=pgv.AGraph()
G.add_edge('1','2')
G.layout()
G.draw('file.png')

rawDescription: open .dot formatted graph from python

description: Open .dot formatted graph from python


code: curr_angle += angle_step

rawDescription: Python - Pygame - Handling angles and speeds of animations


rawDescription: Generating repetitive data in numpy / pandas in a fast vectorized way


code:
from _jpeg import jpeg
from _png import png

rawDescription: Avoid double typing class names in python


code:
import ctypes

c_short = ctypes.c_cshort

class Flags_bits(ctypes.LittleEndianStructure):
    _fields_ = [("bitField1", c_short, 1),
                ("bitField2", c_short, 4),
                ("bitField3", c_short, 6),
                ("bitField4", c_short, 1),
                ("bitField5", c_short, 2),
                ("bitField6", c_short, 2),
                ("bitField7", c_short, 6),
                ("bitField8", c_short, 4),
                ("bitField9", c_short, 4),
                ("bitField10", c_short, 1),
                ("bitField11", c_short, 1)]

for field_descr in Flags_bits._fields_:
    name = field_descr[0]
    field = getattr(Flags_bits, name)
    bfield_bits = field.size >> 16
    if bfield_bits:
        start = 8 * field.offset + field.size & 0xFFFF
        stop = start + bfield_bits
    else:
        start = 8 * field.offset
        stop = start + 8 * field.size
    print("{:>10s}: bits {:>2d}:{:>2d}".format(
          name, start, stop))

rawDescription: Python ctype-bitfields: get bitfield location


code:
class Monad(object):
    def __init__(self, *args, **kwargs):
        # init from each arg.  Try three things:
        # 0) if it has a ".__dict__" attribute, update from that.
        # 1) if it looks like a key/value tuple, insert value for key.
        # 2) else, just see if the whole thing is a dict or similar.
        # Other instances of class Monad() will be handled by (0)
        for x in args:
            if hasattr("__dict__", x):
                self.__dict__.update(x.__dict__)
            else:
                try:
                    key, value = x
                    self.__dict__[key] = value
                except TypeError:
                    self.__dict__.update(x)
        self.__dict__.update(kwargs)

def __identity(x):
    return x

def __callt(v, f):
    return f(v)

def __callt_maybe(v, f):
    if v:
        return f(v)
    else:
        return None

m_identity = Monad(bind=__callt, unit=__identity)
m_maybe = Monad(bind=__callt_maybe, unit=__identity)

def m_chain(*fns, **kwargs):
    """what this function does is not relevant to the question"""
    m = kwargs.get("m", m_identity)
    def m_chain_link(chain_expr, step):
        return lambda v: m.bind(chain_expr(v), step)
    return reduce(m_chain_link, fns, m.unit)

print(m_chain(lambda x: 2*x, lambda x:2*x, m=m_identity)(2)) # prints 8
print(m_chain(lambda x: None, lambda x:2*x, m=m_maybe)(2)) # prints None

rawDescription: python late binding - dynamically put locals in scope

description: Python late binding - dynamically put locals in scope


code:
a=['1','2']
b=['1','2','3']

c = [x for x in a]
c.extend(b)

diff = [x for x in c if a.count(x)+b.count(x) == 1]

rawDescription: restoring list from unified_diff output

description: Restoring list from unified_diff output


code: df.replace('X', 0)

rawDescription: python pandas to drop lines and substitute values in specific columns of a csv file

description: Python pandas to drop lines and substitute values in specific columns of a csv file


code:
class a(object): pass
a.__dict__['wut'] = 4
setattr(a, 'wut', 7)
a.wut

rawDescription: How can I assign a new class attribute via __dict__ in python?

description: Assign a new class attribute via __dict__ in python


code:
def csv_reader(it):
    for line in it:
        yield line.strip().split(',')

rawDescription: Don't understand Python's csv.reader object


code:
for sublist in data:
    if search in sublist:
        print("there", sublist)
        break
else:
    print("not there")

rawDescription: Python Search within Lists within Lists

description: Python Search within Lists within Lists


rawDescription: Python - Multiply matrices with different numbers of columns


code: ab = [a[:0:-1] + sub if a[0] in sub else sub for sub in b]

rawDescription: python list reverse and merge

description: Python list reverse and merge


code:
def property_functions(**properties):
    def construct_method(prop):
        def f_n(self):
            return foo(getattr(self, prop))
        return f_n

    def class_decorator(cls):
        for name, prop in properties.iteritems():
            setattr(cls, name, construct_method(prop))

        return cls

    return class_decorator

rawDescription: How to define similar class-functions related to different class-properties inside __init__

description: Define similar class-functions related to different class-properties inside __init__


code:
values = [4, 0, 0, 0, 0, 0, 0, 0, 103, 196, 124, 0, 0, 0, 0, 0]
as_characters = ''.join(chr(c) for c in values)
as_characters
len(as_characters)

rawDescription: Scapy padding.load what is the meaning of 'g' and '|' symbols


rawDescription: Python timedate match

description: Python timedate match


code:
class User(models.Model):
    name = models.Charfield()
    lat = models.FloatField()
    lng = models.FloatField()

rawDescription: Using GeopositionField to find closest database entries


code:
for testy in collection.find().distinct('stores'):
    print(testy)

rawDescription: How to get distinct values from PyMongo

description: Get distinct values from PyMongo


code:
by_index = ([sub_index, list_index] for list_index, list_item in
             enumerate(items) for sub_index in list_item[0])
list(by_index)
[[[0, 1], 0], [[2, 20], 0], [[1, 3], 1], [[5, 29], 1], [[50, 500], 1]]

rawDescription: Python argmin/argmax: Finding the index of the value which is the min or max


code: TimeStamp = TimeStamp.replace('\r', '')

rawDescription: String appending is acting really odd Python


rawDescription: how to build a Python dict value from another one during dict creation?

description: Build a Python dict value from another one during dict creation


code:
mylist = list(obj.names(section))
mytuple = tuple(obj.names(section))

rawDescription: Python: Return tuple or list?

description: Python: Return tuple or list


code:
import numpy as np
xi = np.arange(len(x))
yi = np.arange(len(y))
Xi, Yi = np.meshgrid(xi, yi)

rawDescription: python matplotlib : ploting 3d surface from string indexed arrays

description: Python matplotlib : ploting 3d surface from string indexed arrays


code:
class SmartBool(QObject):

    valueChanged = pyqtSignal(bool)         # Signal to be emitted when value changes.

    def __init__(self):
        super(SmartBool, self).__init__()   # Call QObject contructor.
        self.__value = False                # False initialized by default.

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self, value):
        if self.__value != value:
            self.valueChanged.emit(value)   # If value change emit signal.
            self.__value = value

rawDescription: Python2 PyQt4 Connect a bool Variable to a QCheckBox item


code:
info = ['apple: 1', 'orange: 2', 'grape: 3']
info = dict(line.split(': ') for line in info)
info

rawDescription: Python: creating dictionary from a bunch of "key: value" strings?


code:
from collections import OrderedDict
OrderedDict(zip(list[::2], list[1::2]))

rawDescription: dictionary and list in python

description: Dictionary and list in python


code:
doc = open('task.txt', 'rt')
parse = doc.read()
listing = parse.split(",")
PID = listing[1]
PID = int(PID.replace('"','').replace("'",""))
os.kill(PID, signal.SIGTERM)

rawDescription: Kill the Popen child process

description: Kill the Popen child process


code:
def parse_funky_numstring(s):
    neg = s.count('-') % 2
    s = s.replace('-', '0')
    num = float(s)
    return -num if neg else num

rawDescription: python string formatting function

description: Python string formatting function


rawDescription: Python: Why is list comprehension slower than for loop


code:
def foo(a, b):
    """
    Take your arguments back, I don't want them!

    a -- int
    b -- str
    """

    return a, b

rawDescription: Is there a python IDE that will tell you the type of a variable when you hover over it?


code:
def invert(fn):
    return lambda x: not fn(x)

rawDescription: Concise way to call ifilter with multiple predicates in python


code: '\x00r\x00e\x00s'.decode('utf-16-be') # produces u'res'

rawDescription: Unable to grep output of python program, possible utf-16


rawDescription: How to convert hyphenated weights to pounds in csv

description: Convert hyphenated weights to pounds in csv


code: [x.split('/') for x in stringin.split(' ')]

rawDescription: separate line in words by slash and use /W but avoid :

description: Separate line in words by slash and use /W but avoid :


code:
from glob import glob
import fileinput
with open('output.csv', 'w') as out:
    for line in fileinput.input(glob('*.log')):
        if 'KEYWORD' in line:
            out.write(line)

rawDescription: Copy select lines from many text files and paste to new file


code:
from collections import defaultdict
import csv

with open("infile") as f:
    d = defaultdict(int)
    for k,v in csv.reader(f,delimiter=" "):
        d[k] += int(v)

print(d)

rawDescription: From list getting keys and values

description: From list getting keys and values


code:
import matplotlib.pyplot as plt

# initial values
x = [0,1,2]
y = [[3,5,7],[4,6,8],[5,7,9]]

# create the line instances and store them in a list
line_objects = list()
for yi in y:
    line_objects.extend(plt.plot(x, yi))

# new values with which we want to update the plot
x = [1,2,3]
y = [[4,6,8],[5,7,9],[6,8,0]]

# update the y values dynamically (without recreating the plot)
for yi, line_object in zip(y, line_objects):
    line_object.set_xdata(x)
    line_object.set_ydata(yi)

rawDescription: Drawing dynamically n plots

description: Drawing dynamically n plots


code:
class Employee(models.Model):
    office = models.ForeignKey(Office)
    name = models.CharField(max_length=50)
    mail = models.EmailField(null=True, blank=True)
    def __unicode__(self):
            return self.name

rawDescription: Django model relation

description: Django model relation


code:
class MyClass:
    def __init__(self):
        self.values = []

    def __setitem__(self, item, value):
        self.value.append(value)

    def previousvalue(self):
        return self.values[-2]

    def __str__(self):
        return str(self.values[-1])

x = MyClass()
x[:] = 5
x[:] = 6
print(x.previousvalue())

rawDescription: How to design a python class which will behave like root classes

description: Design a python class which will behave like root classes


code:
import pprint

pp = pprint.PrettyPrinter(indent=4)

dict1 = { 'Person' : { 'Male' : {'Boys' : {'Roger' : {'age' : 20},
                                           'Rafa' : {'age' : 25}
                                          }
                                },
                       'Female' : { 'Girls' : {'Serena' : {'age' : 23},
                                               'Maria' : {'age' : 15}
                                              }
                                  }

                     },
          'Animal' : { 'Huge' : {'Elephant' : {'color' : 'black' }
                                }
                     }
        }
'''
dict2 = { 'Person' : { 'Male' : {'Boys' : {'Roger' : {'age' : 20}
                                          }
                                },
                       'Female' : { 'Girls' : {'Serena' : {'age' : 23},
                                               'Maria' : {'age' : 1}
                                              }
                                  }
                     }
        }

dict2 = { 'Person' : { 'Male' : {'Boys' : {'Roger' : {'age' : 20},
                                           'Rafa' : {'age' : 2}
                                          }
                                }
                     }
        }
'''

dict2 = { 'Person' : { 'Male' : {'Boys' : {'Roger' : {'age' : 2}}},
                       'Female' : 'Serena'}
        }

key_list = []
err_list = {}
def comp(exp,act):
    for key in exp:
        key_list.append(key)
        exp_val = exp[key]
        try:
            act_val = act[key]
            is_dict_exp = isinstance(exp_val,__builtins__.dict)
            is_dict_act = isinstance(act_val,__builtins__.dict)

            if is_dict_exp == is_dict_act == True:
                comp(exp_val,act_val)
            elif is_dict_exp == is_dict_act == False:
                if not exp_val == act_val:
                    temp = {"Exp" : exp_val,"Act" : act_val}
                    err_key = "-->".join(key_list)
                    if err_list.has_key(key):
                        err_list[err_key].update(temp)
                    else:
                        err_list.update({err_key : temp})
            else:
                temp = {"Exp" : exp_val, "Act" : act_val}
                err_key = "-->".join(key_list)
                if err_list.has_key(key):
                    err_list[err_key].update(temp)
                else:
                    err_list.update({err_key : temp})

        except KeyError:
            temp = {"Exp" : exp_val,"Act" : "NOT_FOUND"}
            err_key = "-->".join(key_list)
            if err_list.has_key(key):
                err_list[err_key].update(temp)
            else:
                err_list.update({err_key : temp})
        key_list.pop()

comp(dict1,dict2)

pp.pprint(err_list)

rawDescription: Is there a good way python to compare complex dictionaries with unkonwn depth & level


code: book.author = 'Joyce, James'

rawDescription: Python XML Serialisation using attributes


code:
# define output-format
numdtype = num.dtype('2f')

# write data
myarray.tofile('filename', numdtype)

rawDescription: How to write variables as binary data with Python?

description: Write variables as binary data with Python


code:
from flask_wtf import Form
from wtforms import SelectField

class Test(Form):
    name = SelectField('Name')

rawDescription: Access to session in flask_wtf

description: Access to session in flask_wtf


code:
from subprocess import call
call(["ls", "-l"])

rawDescription: Using python to issue command prompts

description: Using python to issue command prompts


rawDescription: numpy add dtype array

description: Numpy add dtype array


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

# Create a figure and axis
fig, ax = plt.subplots()

# Plot 100 random points that are very small
x = np.random.rand(100)/100000.0
y = np.random.rand(100)/100000.0
ax.scatter(x, y)

# Set the x and y limits
x_min, x_max = get_min_max(x)
ax.set_xlim(x_min, x_max)
y_min, y_max = get_min_max(y)
ax.set_ylim(y_min, y_max)

# Format the exponents nicely
ax = format_exponent(ax, axis='x')
ax = format_exponent(ax, axis='y')

# And show the figure
plt.show()

rawDescription: Adjust exponent text after setting scientific limits on matplotlib axis


code:
import json
from pprint import pprint

def new_keys(d1, d2, result={}):
    for key, d1_val in d1.iteritems():
        if key not in d2:
            result[key] = d1_val
        else:
            if isinstance(d1_val, dict) and isinstance(d2[key], dict):
                # Don't pass result.
                new_result = {}
                new_keys(d1[key], d2[key], new_result)
                # If new_result is not empty
                if new_result:
                   result[key] = new_result
            else:
                if d1_val != d2[key]:
                   result[key] = d1_val

    return result

with open("before.json") as data_file:
    before = json.loads(data_file.read())

with open("after.json") as data_file:
    after = json.loads(data_file.read())
pprint(new_keys(before,after))

rawDescription: Looping through a dictionary and tracking key depth


code: [value for _, value in frozenset((type(x), x) for x in l)]

rawDescription: Python removing duplicates in list and 1==1.0 True


rawDescription: Numpy.loadtxt imports data as array of arrays rather than a multidimension array


rawDescription: Couple of matplotlib newbie doubts

description: Couple of matplotlib newbie doubts


code:
import scrapy
from goose import Goose

class Article(scrapy.Item):
    title = scrapy.Field()
    text = scrapy.Field()

class MyGooseSpider(scrapy.Spider):
    name = 'goose'
    start_urls = [
        'http://blog.scrapinghub.com/2014/06/18/extracting-schema-org-microdata-using-scrapy-selectors-and-xpath/',
        'http://blog.scrapinghub.com/2014/07/17/xpath-tips-from-the-web-scraping-trenches/',
    ]

    def parse(self, response):
        article = Goose().extract(raw_html=response.body)
        yield Article(title=article.title, text=article.cleaned_text)

rawDescription: Can I use scrapy with goose?

description: Use scrapy with goose


code:
s = np.array(s)
l = np.array(l)

rawDescription: python: how to find a subset of one set that is closest to another

description: Python: how to find a subset of one set that is closest to another


rawDescription: Groupby - taking last element - how do I keep nan's?


code: df['id'].apply(lambda x: re.sub('\s*[a-z]+$', '', x))

rawDescription: Pandas replace full word string

description: Pandas replace full word string


code:
time1 = list(itertools.chain(*timeList))[0].split(":")
seconds_total = (time1[0] * 60) + time1[1]

rawDescription: A better way to extract data in Python

description: A better way to extract data in Python


code:
fReplace = lambda k: d[k]
new_series = map(fReplace, my_series) # or my_series.map if you're in pandas

# alternatively (and there's probably a nicer way, I don't have pandas to play with)
new_series = pd.Series(map(fReplace, my_series))

rawDescription: Mapping list of lists to pandas Series

description: Mapping list of lists to pandas Series


code:
dx = np.diff(np.append(x, x[-1]))
dy = np.diff(np.append(y, y[-1]))
max_gap = np.abs(np.hypot(dx, dy)).argmax() + 1

x = np.append(x[max_gap:], x[:max_gap])
y = np.append(y[max_gap:], y[:max_gap])

rawDescription: Numpy way to sort out a messy array for plotting


code:
from itertools import groupby
from operator import itemgetter

[max(g) for _,g in groupby(sorted(l),key=itemgetter(0))]

rawDescription: Given a list of lists in Python, return the maximum length uniquely-valued sublists


code: newtext = '_'

rawDescription: Remove special characters from csv file using python


code:
from ctypes import *
from ctypes.wintypes import *

def GetRate(hDev, pDate):
    # Your implementation
    return 0

# you'll need GETRATE to pass it in the argtypes to the target function
GETRATE = WINFUNCTYPE(c_int, HANDLE, POINTER(c_int))
pGetRate = GETRATE(GetRate)

# now you can pass pGetRate as a callback to another function

rawDescription: Python ctypes integer pointer

description: Python ctypes integer pointer


rawDescription: Python Regex on comma, space

description: Python Regex on comma, space


code:
def prepost(f):
    def prepost_wrapper(self, *args, **kwargs):
        pre_name  = 'pre_'  + f.__name__
        post_name = 'post_' + f.__name__
        if hasattr(self, pre_name):  getattr(self, pre_name) (*args, **kwargs)
        ret = f(self, *args, **kwargs)
        if hasattr(self, post_name): getattr(self, post_name)(*args, **kwargs)
        return ret
    return prepost_wrapper

class Base:
    @prepost
    def f(self, a, b=99):
        print("f()", a, b)
    @prepost
    def missing(self):
        print("nothing special here")

class Derived(Base):
    def pre_f(self, a, b=0): # the arguments must match!
        print("pre_f()", a, b)
    def post_f(self, a, b=1):
        print("post_f()", a, b)

foo = Derived()
foo.f("abc")
foo.missing()
foo.f("xyz", 12)

rawDescription: Make a decorator call method-specific pre and post methods in a class


code:
from StringIO import StringIO

class StdoutFilter(StringIO):

    def __init__(self, stdout):
        StringIO.__init__(self, stdout)
        self.stdout = stdout

rawDescription: Prevent string being printed python

description: Prevent string being printed python


code:
spacer = "N" * 64

with open ("join_fasta_test.fasta", 'r') as fh_in, \
        open("join_fasta_test_out.fasta", 'w') as fh_out:
     prev = next(fh_in)  # first line
     for line in fh_in:
         if line.startswith('>'):
            prev = prev.rstrip('\n') + spacer + '\n'
         fh_out.write(prev)
         prev = line
     fh_out.write(prev.rstrip('\n') + spacer + '\n')

rawDescription: How to add bunch of "N's" at the end of file in python?

description: Add bunch of "N's" at the end of file in python


code:
from threading import Thread

import gtk, gobject

class Belt(gtk.Window):

    def __init__(self):
        super(Belt, self).__init__()
        self.connect("destroy", self.destroy)

        self.show_all()

        self.isLogged = True
        self.iniError = False

    def destroy(self, widget, data=None):
        if self.isLogged:
            md = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, 0, gtk.BUTTONS_NONE, "Text")
            md.show_all()
            Thread(target=self._this_takes_very_long).start()

    def main(self):
        if self.iniError is False:
            gtk.gdk.threads_init()
            gtk.gdk.threads_enter()
            gtk.main()
            gtk.gdk.threads_leave()

    def _this_takes_very_long(self):
        self.send('users/logout.json', {}, False, False)
        gobject.idle_add(gtk.main_quit)

if __name__ == "__main__":
    app = Belt()
    app.main()

rawDescription: python GTK: Dialog with information that app is closing

description: Python GTK: Dialog with information that app is closing


code:
# before loop
all_buttons = dict()

# inside loop
all_buttons[ alpha[i] ] = Button(...)
all_buttons[ alpha[i] ].grid(...)

# in function
def letterGuess(letter):
    all_buttons[ letter ].config(state=DISABLED)

rawDescription: Sneaky way of disabling a button once it's been pressed?


code:
value = [data[i] for i in index if data[i] > 1000]
findex = [i for i in index if data[i] > 1000]

rawDescription: Removing elements from list based on index from another list


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

# Generate some interesting random data
np.random.seed(1)
series1 = np.random.normal(0, 1, 1000).cumsum() + 20
series2 = np.random.normal(0, 1, 1000).cumsum()
# Our x-coordinates
index = np.arange(series1.size)

# Boundaries of the gray "easing region"
i0, i1 = 300, 700

# In this case, I've chosen a sinusoidal easing function...
x = np.pi * (index - i0) / (i1 - i0)
easing = 0.5 * np.cos(x) + 0.5

# To the left of the gray region, easing should be 1 (all series2)
easing[index < i0] = 1

# To the right, it should be 0 (all series1)
easing[index >= i1] = 0

# Now let's calculate the new series that will slowly approach the first
# We'll operate on the difference and then add series1 back in
diff = series2 - series1
series3 = easing * diff + series1

rawDescription: numpy / scipy: Making one series converge towards another after a period of time

description: Numpy / scipy: Making one series converge towards another after a period of time


code:
x = np.arange(10)
middle = lambda x: x[len(x)/4:len(x)*3/4]

rawDescription: Index the middle of a numpy array?

description: Index the middle of a numpy array


code:
import psutil

psutil.get_users()

rawDescription: Find out who is logged in on linux using python


code:
passwd = getpass('Password: ')
salt = passwd_encrypt[:4]
h = hashlib.md5()
h.update(salt)
h.update(passwd.encode())
if passwd_encrypt != salt + h.hexdigest():
    raise LoginFailed()

rawDescription: Generating passwords in Python 3.1.1

description: Generating passwords in Python 3.1.1


rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


rawDescription: Python, lxml - get a sibling tag's (grand)child's text


code:
import mechanize
br=mechanize.Browser()
br.open('https://mog.com/hp/sign_in')
br.select_form(nr=0)
br['user[login]']= your_login
br['user[password]']= your_password
br.submit()
br.retrieve('http://mog.com/my_mog/playlists','playlist.html')

rawDescription: How can I log into a website using python?

description: Log into a website using python


code: Dict1 = {c[0]:0 for c in PriceList}

rawDescription: 'int' object has no attribute 'update' - dictionary within dictionary - python2.7


code:
from Tkinter import *
import ttk

class MainWindow(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title("ProgressBar example")
        #self.master.minsize(400, 100)
        self.grid(sticky=E+W+N+S)

        #-----

        self.var_ind = IntVar(self)

        self.pbar_ind = ttk.Progressbar(self, orient="horizontal", length=400, mode="indeterminate", variable=self.var_ind, maximum=100)
        self.pbar_ind.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S, columnspan=3)

        Label(self, text="indeterminate").grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.lab_ind_var = Label(self, text="VAR:")
        self.lab_ind_var.grid(row=1, column=1, pady=2, padx=2, sticky=E+W+N+S)

        self.lab_ind_max = Label(self, text="MAX:")
        self.lab_ind_max.grid(row=1, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        self.var_det = IntVar(self)

        self.pbar_det = ttk.Progressbar(self, orient="horizontal", length=400, mode="determinate", variable=self.var_det, maximum=100)
        self.pbar_det.grid(row=2, column=0, pady=2, padx=2, sticky=E+W+N+S, columnspan=3)

        Label(self, text="determinate").grid(row=3, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.lab_det_var = Label(self, text="VAR:")
        self.lab_det_var.grid(row=3, column=1, pady=2, padx=2, sticky=E+W+N+S)

        self.lab_det_max = Label(self, text="MAX:")
        self.lab_det_max.grid(row=3, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="ANIMATION:").grid(row=4, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='START', command=self.animation_start).grid(row=4, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='STOP', command=self.animation_stop).grid(row=4, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="SET:").grid(row=5, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='BEGIN', command=self.set_begin).grid(row=5, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='END', command=self.set_end).grid(row=5, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="SET:").grid(row=6, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='23', command=lambda:self.set(23)).grid(row=6, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='77', command=lambda:self.set(77)).grid(row=6, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="SET:").grid(row=7, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='+23', command=lambda:self.set_plus(23)).grid(row=7, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='-77', command=lambda:self.set_plus(-77)).grid(row=7, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="STEP:").grid(row=8, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='+1', command=lambda:self.step(1)).grid(row=8, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='-10', command=lambda:self.step(-10)).grid(row=8, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        Label(self, text="MAX:").grid(row=9, column=0, pady=2, padx=2, sticky=E+W+N+S)

        Button(self, text='100', command=lambda:self.max(100)).grid(row=9, column=1, pady=2, padx=2, sticky=E+W+N+S)
        Button(self, text='200', command=lambda:self.max(200)).grid(row=9, column=2, pady=2, padx=2, sticky=E+W+N+S)

        #-----

        self.update_labels_after = False
        self.update_labels()

    #-----

    def animation_start(self):
        self.update_labels_after = True

        self.pbar_ind.start() # .start(1)
        self.pbar_det.start() # .start(1)

        self.update_labels()

    def animation_stop(self):
        self.update_labels_after = False

        self.pbar_ind.stop()
        self.pbar_det.stop()

        self.update_labels()

    #-----

    def set_begin(self):
        self.var_ind.set( 0 )
        self.var_det.set( 0 )

        self.update_labels()

    def set_end(self):
        self.var_ind.set( self.pbar_ind.cget('maximum') )
        self.var_det.set( self.pbar_det.cget('maximum') )

        self.update_labels()

    #-----

    def set(self, val):
        self.var_ind.set( val )
        self.var_det.set( val )

        self.update_labels()

    #-----

    def set_plus(self, val):
        self.var_ind.set( self.var_ind.get() + val )
        self.var_det.set( self.var_det.get() + val )

        self.update_labels()

    #-----

    def step(self, val=1):
        self.pbar_ind.step(val) # .step()
        self.pbar_det.step(val) # .step()

        self.update_labels()

    #-----

    def max(self, val=1):
        self.pbar_ind.config(maximum=val)
        self.pbar_det.config(maximum=val)

        self.update_labels()

    #-----

    def update_labels(self):

        self.lab_ind_var.config(text='VAR: %d' % (self.var_ind.get()))
        self.lab_ind_max.config(text='MAX: %d' % (self.pbar_ind.cget('maximum')))

        self.lab_det_var.config(text='VAR: %d' % (self.var_det.get()))
        self.lab_det_max.config(text='MAX: %d' % (self.pbar_det.cget('maximum')))

        if self.update_labels_after:
            self.after(50, self.update_labels)

if __name__=="__main__":
   MainWindow().mainloop()

rawDescription: tkinter progressbar - linked to function?

description: Tkinter progressbar - linked to function


code:
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', True)""" % ([0, 0]))
conn.commit()
# Inserted the (0,0) case
for i, x in enumerate(data):
    for s in range(target_sum + 1):
        for c in range(s / x + 1):
            cursor.execute(""" SELECT value, state FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
            if cursor.rowcount == 0:
                cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', False)""" % ([s - c * x, i]))
            elif cursor.rowcount == 1:
                (value, state) = cursor.fetchone() # Gets the state
                if state: # equivalent to your if in the first example
                    insertOrUpdate(conn, [s, i+1])
    conn.commit()

rawDescription: Results are different between python and mysql for similar command


code:
# firstly, we use imap to call GetMyPoints a bunch of times
objects = itertools.imap(GetMyPoints, xrange(100))
# next, we use itertools.chain to flatten it into all of the polygons
polygons = itertools.chain.from_iterable(objects)
# tee gives us two iterators over the polygons
polygons_a, polygons_b = itertools.tee(polygons)
# the lengths will be the length of each polygon
polygon_lengths = itertools.imap(len, polygons_a)
# for the actual points, we'll flatten the polygons into points
points = itertools.chain.from_iterable(polygons_b)
# then we'll flatten the points into values
values = itertools.chain.from_iterable(points)

# package all of that into a numpy array
all_points = numpy.fromiter(values, float)
# reshape the numpy array so we have two values for each coordinate
all_points = all_points.reshape(all_points.size // 2, 2)

# produce an iterator of lengths, but put a zero in front
polygon_positions = itertools.chain([0], polygon_lengths)
# produce another numpy array from this
# however, we take the cumulative sum
# so that each index will be the starting index of a polygon
polygon_positions = numpy.cumsum( numpy.fromiter(polygon_positions, int) )

# now for the transformation
# multiply the first coordinate of every point by *.5
all_points[:,0] *= .5

# now to get it out

# polygon_positions is all of the starting positions
# polygon_postions[1:] is the same, but shifted on forward,
# thus it gives us the end of each slice
# slice makes these all slice objects
slices = itertools.starmap(slice, itertools.izip(polygon_positions, polygon_positions[1:]))
# polygons produces an iterator which uses the slices to fetch
# each polygon
polygons = itertools.imap(all_points.__getitem__, slices)

# just iterate over the polygon normally
# each one will be a slice of the numpy array
for polygon in polygons:
    draw_polygon(polygon)

rawDescription: numpy arrays: filling and extracting data quickly

description: Numpy arrays: filling and extracting data quickly


code:
from re import split
lista = ['janu', 'manu', 'tanu', 'banu']
[split("(^[^aeiou]+)(?=[aeiouy])", x)[1]+"doc" for x in lista]

rawDescription: Applying regex on each item of a list in Python


code:
def main():
    parser = argparse.ArgumentParser(description='Python Grep.')
    parser.add_argument('--debug', action='store_true', help='Print debug messages')
    parser.add_argument('pattern', type=str, nargs='+', help='Pattern(s) for pgrepping')
    args = parser.parse_args()

    pattern = '|'.join(['(?:{})'.format(p) for p in args.pattern])
    Grepper(pattern, args.debug).matchline()

rawDescription: Take multiple patterns from cli. argparse Python3


code:
x1 = np.array([1, 10, 100, 1000, 10000])
x2 = np.array([5, 50, 500, 5000, 50000])

y1 = np.array([-1, -10, -100, -1000, -10000])
y2 = np.array([5, 50, 500, 5000, 50000])

x = np.concatenate((x1,x2))
y = np.concatenate((y1,y2))

sorted = np.argsort(y)

ax.plot(x[sorted],abs(y[sorted]),'+-b',label='all data')
ax.plot(abs(x[y<= 0]),abs(y[y<= 0]),'o',markerfacecolor='none',
                                        markeredgecolor='r',
                                        label='we are negative')

rawDescription: Connect different data series with the same line


code:
def last_day(dt):
     rest, month = divmod(dt.month, 12)
     return date(dt.year + rest, month + 1, 1) - timedelta(days=1)

rawDescription: Python: Date manipulation code

description: Python: Date manipulation code


code:
class1 = { 'Ethan':'9','Ian':'3','Helen':'8','Holly':'6' }
print(sorted(class1.items()))

rawDescription: How do I print a sorted Dictionary in Python 3.4.3

description: Print a sorted Dictionary in Python 3.4.3


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
import numpy as np

result = np.array([x for x in datarelmax_0 if x in datarelmax_1])

rawDescription: How to create a numpy array from two lists of tuples, but only when the tuples are the same

description: Create a numpy array from two lists of tuples, but only when the tuples are the same


rawDescription: Extract sub-lists recursively from main list


code: consume(bytesIter, height/2)

rawDescription: Incrementing itertools.imap without reading to object in Python for performance


code:
from django.contrib.auth.models import User

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)
    answer = models.CharField(choices=ANSWER_CHOICES, max_length=1)

rawDescription: django weighted questionnaire?

description: Django weighted questionnaire


code: df['hour'] = df.index.hour

rawDescription: Average hourly week profile for a year excluding weekend days and holidays


code:
class MySuper():
    def __init__(*args, **kwargs):
        pass

rawDescription: How to dynamically create new python class files?

description: Dynamically create new python class files


code: b = Button(app_name, text="..." , command = any_function(7))

rawDescription: tkinter , python , buttons

description: Tkinter , python , buttons


code:
movie_lists = [movies, rest_movies, ...]
for movie_list in movie_lists:
    for item in movie_list:
        if item['name'] == movie_to_find:
            print(item['year'])
            break

rawDescription: Efficient way to find unique value in one of few lists


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([1, 10000, 1, 100000])
ax.loglog()

plt.show()

rawDescription: Matplotlib log scale tick label number formatting


code:
import os
import os.path

new_list = []

for each in texture_filename_list:
    file_name = os.path.basename(each)
    stripped_file_name = os.path.splitext(file_name)[0]
    new_list.append(stripped_file_name)

rawDescription: extracting only texture filenames being used in maya file from the list of filename paths

description: Extracting only texture filenames being used in maya file from the list of filename paths


code:
from math import sqrt
sqrt.__module__

rawDescription: How do you check in which module a function is defined? Python

description: Check in which module a function is defined? Python


code:
regPay = float(wage) * min(int(hours),40)
# min(hours,40) will return hours, unless hours > 40 then it will return 40
OTpay = float(wage) * OVERTIMERATE * max(int(hours)-40,0)
# max(hours-40,0) will return hours-40, unless hours <= 40 then it will return 0

rawDescription: How to select a range of numbers to multiply an hourly wage by

description: Select a range of numbers to multiply an hourly wage by


code:
possible_adj = []
for ss in wn.synsets('terribly'):
  for lemmas in ss.lemmas: # all possible lemmas.
    for lemma in lemmas:
      for ps in lemma.pertainyms(): # all possible pertainyms.
        for p in ps:
          for ln in p.name: # all possible lemma names.
            possible_adj.append(ln)

rawDescription: Getting adjective from an adverb in nltk or other NLP library


code:
def some_operation(value):
  ...

collection.each(some_operation)

rawDescription: Learning Python from Ruby; Differences and Similarities


rawDescription: counting unique value pairs in pandas

description: Counting unique value pairs in pandas


code:
for d in lst:
    d['score'] -= 1

rawDescription: List of dictionaries - subtract a constant from each dictionary value


code:
def nearby_spots_new(request, lat, lng, radius=5000, limit=50):
    """
    WITH USE OF GEODJANGO and POSTGIS
    https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#distance-queries
    """
    user_location = fromstr("POINT(%s %s)" % (lng, lat))
    desired_radius = {'m': radius}
    nearby_spots = Spot.objects.filter(
        mpoint__distance_lte=(user_location, D(**desired_radius))).distance(
        user_location).order_by('distance')[:limit]
    serializer = SpotWithDistanceSerializer(nearby_spots, many=True)

    return JSONResponse(serializer.data)

rawDescription: Returning nearby locations in Django

description: Returning nearby locations in Django


code: log4j.rootCategory=WARN, console

rawDescription: How to turn off INFO logging in PySpark?

description: Turn off INFO logging in PySpark


code:
from pyparsing import ParserElement, LineEnd, Literal, restOfLine, ZeroOrMore, Group, StringEnd

test = """
section header 1:
 some words can be anything
 more words could be anything at all
 etc etc lala

some other header:
 as before could be anything
 hey isnt this fun
"""
ParserElement.defaultWhitespaceChars=(" \t")
NL = LineEnd().suppress()
END = StringEnd()

header_1=Literal('section header 1:')
header_2=Literal('some other header:')
any_header = (header_1 | header_2)
# text isn't just anything! don't accept header line, and stop at the end of the input string
text=Group(~any_header + ~END + restOfLine)

overall_structure = ZeroOrMore(Group(any_header +
                                     Group(ZeroOrMore(text))))
overall_structure.ignore(NL)

from pprint import pprint
print(overall_structure.parseString(test).asList())

rawDescription: pyparsing capturing groups of arbitrary text with given headers as nested lists

description: Pyparsing capturing groups of arbitrary text with given headers as nested lists


code:
from PIL import ImageFile

self.assertIsInstance(SimpleExample.img, ImageFile.ImageFile)

rawDescription: assertIsInstance() against multiple class names

description: AssertIsInstance() against multiple class names


code:
import sys

if __name__ == '__main__':
    if sys.argv[1] == '-l':
        list_my_repos()

rawDescription: python - beginner - integrating optparse in a program

description: Python - beginner - integrating optparse in a program


code:
def merge_lists(l1, l2, key):
    merged = {}
    for item in l1+l2:
        if item[key] in merged:
            merged[item[key]].update(item)
        else:
            merged[item[key]] = item
    return [val for (_, val) in merged.items()]

courses = merge_lists(user_course_score, courses, 'course_id')

rawDescription: How to merge lists of dictionaries

description: Merge lists of dictionaries


code:
from bs4 import BeautifulSoup
table_data = [[cell.text for cell in row("td")]
                         for row in BeautifulSoup(html_data)("tr")]

rawDescription: Convert a HTML Table to JSON

description: Convert a HTML Table to JSON


rawDescription: converting python source code to utf-8

description: Converting python source code to utf-8


code: temp = copy.deepcopy(z)

rawDescription: How can I assign by value in python

description: Assign by value in python


code:
result = defaultdict(dict)

for bigkey, d in yourdict.values():
    # bigkey="K", d={"k": 2, "x": 1.0}, ...
    total = sum(d.values())
    # d.values() == [2, 1.0]
    for k,v in d.items():
        # k="k", v=2, ...
        result[bigkey][k] = v / total
        # result["K"]["k"] = 3 / 2

rawDescription: Accessing dictionary within dictionary

description: Accessing dictionary within dictionary


code:
if str3:
    outfilename3 = 'data3-{}.csv'.format(now_str)
    out_file3 = open(outfilename3, 'w')
    out_file3.write(str3)

rawDescription: How Do I Output Multiple Scraped Datasets to Their Own .CSV Files in Python?


rawDescription: sort on multiple parameters in list of dictionaries/lists

description: Sort on multiple parameters in list of dictionaries/lists


code:
import logging
import logging.config

lFooBefore = logging.getLogger('foo')
lScriptBefore = logging.getLogger('script')
logging.config.fileConfig('logger.ini')

lFooBefore.debug('Does not log')
lScriptBefore.debug('Does log')
logging.getLogger('foo').debug('Does also not log')
logging.getLogger('bar').debug('Does log')

rawDescription: Python root logger messages not being logged via handler configured with fileConfig


code:
t1 = df1[["start", "end"]]
t2 = df2[["start", "end"]]
f = t2.apply(lambda x2: t1.apply(lambda x1: x1.isin(x2).all(), axis=1).any(), axis=1)
df2[~f]

rawDescription: picking out elements based on complement of records in Python pandas

description: Picking out elements based on complement of records in Python pandas


rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
def error(msg, *args, **kwargs):
    if len(root.handlers) == 0:
        basicConfig()
    root.error(msg, *args, **kwargs)

rawDescription: Python StringIO is not correctly capturing data from stderr


rawDescription: Finding corners in a 2d map with walls

description: Finding corners in a 2d map with walls


code:
imgs = tree.xpath('.//img')
thm = "new-value"
for img in imgs:
    img.set('src', thm)
    a = etree.Element('a', href="#")
    img.addprevious(a)
    a.insert(0, img)

rawDescription: lxml python load html string without header and body and add element around targeted elements

description: Lxml python load html string without header and body and add element around targeted elements


code: #!/usr/bin/python

rawDescription: Running a python script from PHP with Apache


code:
def common_substr(a, b, k):
  for substr in (a[i:i+k] for i in range(len(a)-k+1)):
    if substr in b:
      return substr

rawDescription: Common substring of length k

description: Common substring of length k


code:
import re
pattern = re.compile(r"^Name=(.*)$", flags=re.MULTILINE)
re.sub(pattern, "Name=%s" % replace_name, s)

rawDescription: Replacing variable text in between two known elements


code:
@decorator
def function():
    pass

rawDescription: Is a Python Decorator the same as Java annotation, or Java with Aspects?


code:
def random(x, show):
    variable_x = x
    result = f(x)
    show(result)

def show(result):
    plt.plot(result, x)
    plt.show()

result = random(x, show)

rawDescription: Is there a way to create a subplot that contains plots created inside functions?


rawDescription: Python List splitting, sorting by date, then joining


code:
#Python3
def make_acronym(sentence):
    excluded_words = ['by', 'the', 'of']
    acronym = ''.join(word[0] for word in sentence.split(' ') if word not in excluded_words)
    return acronym.upper()

rawDescription: How to sort specific string, in the following situation (PYTHON)

description: Sort specific string, in the following situation (PYTHON)


code:
word = input()
word

rawDescription: Take user input and put it in a list of characters (Python 3)


rawDescription: How does np.multiply work?

description: How does np.multiply work


code:
@route('/hello')
def hello():
    return template('index.tpl', {'text': "hello"})

rawDescription: What's the best way to disable Jinja2 template caching in bottle.py?


rawDescription: How to add the sum of cubes using a function in python?

description: Add the sum of cubes using a function in python


rawDescription: pandas - get a fraction of each multi-index level label rows

description: Pandas - get a fraction of each multi-index level label rows


code:
t=threading.Thread(target=self.workerFuncSpinner,
    args=(taskOnDeckQueue, taskCompletionQueue, taskErrorQueue, i))

rawDescription: Python threading issue: threads blocking each other


rawDescription: Numpy Routine for Computing Matrix Minors?


code: import_list = f.readlines()

rawDescription: How to read a randomly imported text file and store it in a list

description: Read a randomly imported text file and store it in a list


code: k.reshape(k.shape + (1,))

rawDescription: Is this the best way to add an extra dimension to a numpy array in one line of code?


code:
def get_py_type(access_type):
    if access_type == "integer":
        return "int"
    elif access_type.startswith("varchar"):
        return "str"
    elif access_type == "double":
        return "float"
    elif access_type == "date":
        return "datetime"
    else:
        return "unknown"

rawDescription: Python: Changing Types while writing in a MS-Access DB


code:
import example
my_object = example.MyObject()
status, t, x = my_object.compute(example.Container([1, 2, 3]), 4)
assert(status == 42)
assert(t == 21)
assert(isinstance(x, example.Container))

rawDescription: boost python returning tuple containing custom types

description: Boost python returning tuple containing custom types


code: len(set(list1).intersection(list2)) > 0

rawDescription: Python - Comparing two lists

description: Python - Comparing two lists


code:
import ast

#...
funcname,args = t.split('(',1)
args = ast_literal_eval('('+args)
if hasattr(args,'__iter__'):
    getattr(turtle,funcname)(*args)
else:
    getattr(turtle,funcname)(args)

rawDescription: How can I execute a command inputted by the user as a turtle command?

description: Execute a command inputted by the user as a turtle command


code:
br.open(URL)
res = mechanize._form.ParseString(FORM_HTML, BASE_URL)
br.form = res[1]
#continue as if the form was on the page and selected with .select_form()
br['username'] = 'foo'
br['password'] = 'bar'
br.submit()

rawDescription: python mechanize: create and submit a form

description: Python mechanize: create and submit a form


rawDescription: Creating distinct objects in a function

description: Creating distinct objects in a function


code:
from collections import defaultdict
from PIL import Image, ImageDraw

def connected_components(edges):
    """
    Given a graph represented by edges (i.e. pairs of nodes), generate its
    connected components as sets of nodes.

    Time complexity is linear with respect to the number of edges.
    """
    neighbors = defaultdict(set)
    for a, b in edges:
        neighbors[a].add(b)
        neighbors[b].add(a)
    seen = set()
    def component(node, neighbors=neighbors, seen=seen, see=seen.add):
        unseen = set([node])
        next_unseen = unseen.pop
        while unseen:
            node = next_unseen()
            see(node)
            unseen |= neighbors[node] - seen
            yield node
    return (set(component(node)) for node in neighbors if node not in seen)

def matching_pixels(image, test):
    """
    Generate all pixel coordinates where pixel satisfies test.
    """
    width, height = image.size
    pixels = image.load()
    for x in xrange(width):
        for y in xrange(height):
            if test(pixels[x, y]):
                yield x, y

def make_edges(coordinates):
    """
    Generate all pairs of neighboring pixel coordinates.
    """
    coordinates = set(coordinates)
    for x, y in coordinates:
        if (x - 1, y - 1) in coordinates:
            yield (x, y), (x - 1, y - 1)
        if (x, y - 1) in coordinates:
            yield (x, y), (x, y - 1)
        if (x + 1, y - 1) in coordinates:
            yield (x, y), (x + 1, y - 1)
        if (x - 1, y) in coordinates:
            yield (x, y), (x - 1, y)
        yield (x, y), (x, y)

def boundingbox(coordinates):
    """
    Return the bounding box of all coordinates.
    """
    xs, ys = zip(*coordinates)
    return min(xs), min(ys), max(xs), max(ys)

def disjoint_areas(image, test):
    """
    Return the bounding boxes of all non-consecutive areas
    who's pixels satisfy test.
    """
    for each in connected_components(make_edges(matching_pixels(image, test))):
        yield boundingbox(each)

def is_black_enough(pixel):
    r, g, b = pixel
    return r < 10 and g < 10 and b < 10

if __name__ == '__main__':

    image = Image.open('some_image.jpg')
    draw = ImageDraw.Draw(image)
    for rect in disjoint_areas(image, is_black_enough):
        draw.rectangle(rect, outline=(255, 0, 0))
    image.show()

rawDescription: How to determine regions of pixels with a shared value using PIL

description: Determine regions of pixels with a shared value using PIL


code:
xy = ['X', 'Y']
distance_array = numpy.sum((df1[xy].values - df2[xy].values)**2, axis=1)
distance_array.argmin()

rawDescription: Calculating the minimum distance between two DataFrames


code:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegressionCV
from sklearn.pipeline import make_pipeline

clf = make_pipeline(CountVectorizer(), LogisticRegressionCV(cv=2))

rawDescription: How to store predicted classes matching the pre-vectorized X in Python Scikit-learn?

description: Store predicted classes matching the pre-vectorized X in Python Scikit-learn


code:
df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['A', 'B'])
df
pd.Index(np.arange(0, len(df))).equals(df.index)

rawDescription: checking if pandas dataframe is indexed?

description: Checking if pandas dataframe is indexed


code:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

rawDescription: How to remove leading and trailing zeros in a string? Python

description: Remove leading and trailing zeros in a string? Python


code: event = cal.add('vevent')

rawDescription: Create "downloadable" vCalendar object for Outlook with vObject (Python)


rawDescription: How to transform a pair of values into a sorted unique array?

description: Transform a pair of values into a sorted unique array


code:
import matplotlib
import matplotlib.pyplot as plt

class My_Axes(matplotlib.axes.Axes):
    name = "My_Axes"
    def drag_pan(self, button, key, x, y):
        matplotlib.axes.Axes.drag_pan(self, button, 'x', x, y) # pretend key=='x'

matplotlib.projections.register_projection(My_Axes)

figure = plt.figure()
ax = figure.add_subplot(111, projection="My_Axes")
ax.plot([0, 1, 2], [0, 1, 0])
plt.show()

rawDescription: matplotlib forcing pan/zoom to constrain to x-axes

description: Matplotlib forcing pan/zoom to constrain to x-axes


rawDescription: How python suds or sf-suds work with "wsdl:import"?


code: unfollowThese = [ person for person in iFollow if person not in followsMe ]

rawDescription: Create new list containing list x but not elements in list y that are the same as in list x - python


code: print("Your number is ", a, ".")

rawDescription: Need assistance on Print function

description: Need assistance on Print function