code:
class Vector2D:
    def __init__(self, x, y, vx, vy):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy

    def update(self):
        self.x += self.vx
        self.y += self.vy

    def copyto(self, rect):
        rect.x = int(round(self.x,0))
        rect.y = int(round(self.y,0))

speed = Vector2D(100, 100, .5, .5)

rawDescription: Adding a speed vector to a position vector only works with integers


rawDescription: Convert from string to tuple with "\" in python


rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code: [Fraction(x, y) for x in a for y in b]

rawDescription: How to pair every item in a 2 lists as fractions until the end of said lists?

description: Pair every item in a 2 lists as fractions until the end of said lists


code:
def split(txt, seps):
    default_sep = seps[0]

    # we skip seps[0] because that's the default seperator
    for sep in seps[1:]:
        txt = txt.replace(sep, default_sep)
    return [i.strip() for i in txt.split(default_sep)]

rawDescription: Python: Split string by list of separators


code:
class Group(object):
    pass

type(Group)
isinstance(Group, object)

rawDescription: Are class names objects in python?

description: Are class names objects in python


code:
import logging
import random

class Debug(object):
    @property
    def ThreadAwareLogger(self):
        loggers = [logging.getLogger('abc'),logging.getLogger('def')]
        return self.anotherDebugMethod(loggers)
    def anotherDebugMethod(self,loggers):
        return random.choice(loggers)
class SomeOtherClass(object):
    def __init__(self):
        self.debug=Debug()
    @property
    def logger(self):
        return self.debug.ThreadAwareLogger
    def otherMethod(self):
        self.logger.info('Message')

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG)
    x=SomeOtherClass()
    for i in range(5):
        x.otherMethod()

rawDescription: How does asigning of @property works? (Assigning of a getter to another variable.)


code: main(module='test_module', exit=False)

rawDescription: Capture the run time from running a unittest TestCase into a Python variable


code:
s = ['ABC','DEF','GHI','JKL']
lis=[list(x) for x in s]
lis

rawDescription: Store each character of a String in a list


code:
db.test.find({
    'evidence.0': True,
    'evidence.1': True,
    'evidence.2': {'$in': [True, None]}
})

rawDescription: Match all fields of an array using a regex


rawDescription: Best approach to detect subnet overlap in a postgresql db


rawDescription: Reading arabic text encoded in utf-8 in python


code:
date0 = datetime.datetime.strptime(d0, "%m/%d/%Y %I:%M:%S %p")
date1 = datetime.datetime.strptime(d1, "%m/%d/%Y %I:%M %p")
delta = date0 - date1
return delta.days + (delta.seconds / 86400.0) # 60 seconds in 60 minutes in 24 hours

rawDescription: Finding the difference between times in different columns through a CSV file


code:
line = '01/01/2015 7:30:10 a.m. Tag off : 16 Address Ave     $1.00   $26.00'
line.split(' : ')
line.split(' : ')[0]
line.split(' : ')[0].split(' Tag ')
timestr, status = line.split(' : ')[0].split(' Tag ')
print(status)
print(timestr)

rawDescription: Python putting certain texts into a dictionary from a large string


code: opposing_numbers(0.25, 5)

rawDescription: How do I write a custom generator function with python

description: Write a custom generator function with python


code:
import pandas as pn
from datetime import date
df = pn.read_csv('fut.csv', index_col=2, parse_dates=[2])
pn.rolling_mean(df['CLOSE'], window=7)
pn.rolling_mean(df['CLOSE'], window=7)[date(2005,4,26)]

rawDescription: Select 7, 14, 20, 50, 200 day prices from OHLC data in SQL database.


code:
def original(arr, val):
    pos = np.where(arr>=val)[0]
    return arr[pos[0]:pos[-1]+1]

def with_argmax(arr, val):
    pos = (arr>=val)
    return arr[pos.argmax():-pos[::-1].argmax() or None]

rawDescription: Numpy subset array between first and last occurence of logical expression match


code:
k = testDec()
k.x
k.x = 5
k.x

rawDescription: Why does @foo.setter in Python not work for me?


code:
class SquarePython:
    def Square(self, number):
        return number * number

rawDescription: Calling Python script from windows form

description: Calling Python script from windows form


code:
def b(self, p, data):
    current = p
    if current.data == data:
        return True
    elif current.data == 1:
        return False
    else:
        self.b(current.next, data)

rawDescription: Return True, False and None in Python

description: Return True, False and None in Python


rawDescription: Which Python module is suitable for data manipulation in a list?


code:
dv = list()
# arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]

# dictionary counting number of occurances
seqDic = { }

for i in seq:
  if i in seqDic:
    seqDic[i] += 1
  else:
    dv.append(i)
    seqDic[i] = 1

rawDescription: Learning Python and using dictionaries

description: Learning Python and using dictionaries


rawDescription: Python: divide elements of a list based on a condition


code:
def subgen_2(i):
    i * 3

rawDescription: How to make Python recognize a function as a generator function?

description: Make Python recognize a function as a generator function


code:
from celery.utils import uuid
from celery import chord

class ProgressChord(chord):

    def __call__(self, body=None, **kwargs):
        _chord = self.Chord
        body = (body or self.kwargs['body']).clone()
        kwargs = dict(self.kwargs, body=body, **kwargs)
        if _chord.app.conf.CELERY_ALWAYS_EAGER:
            return self.apply((), kwargs)
        callback_id = body.options.setdefault('task_id', uuid())
        r= _chord(**kwargs)
        return _chord.AsyncResult(callback_id), 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:
from A import B
import A.B.C
import A.B.D
del A

rawDescription: "from A import B.C" in Python?

description: "from A import B.C" in Python


code:
while distance[0][0][0] == '*':
    for i in range(0,3):
        for j in range(0,3):
            if distance[i][j][0] != '*':
                k = distance[i][j][0]
                for i in range(0,3):
                    for j in range(0,3):
                        distance[i][j][k] = 0

rawDescription: Python sudoku solver blocks

description: Python sudoku solver blocks


code:
def callsomething(x):
    if x in {3,4,5,6}: pass

dis.dis(callsomething)

rawDescription: Does program really created the inner object each time?


code:
array([[False,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

rawDescription: Opencv: How to detect pixel color change


code:
def _finditem(op_type, obj):
    if isinstance(obj, dict):
        obj['children'] = _finditem(op_type, obj['children'])
    else:
        for x in obj:
            if x['title'] in subjects[op_type]:
                x['children'] = operations[op_type](x['children'])
            else:
                try:
                    x['children'] = _finditem(op_type, x['children'])
                except:
                    continue
    return obj

rawDescription: Recursively remove nested items in dictionary


rawDescription: Python HTML Email : How to insert list items in HTML email


code:
['\n                ',
 'Liat Towers',
 '\n                541 Liat towers #01-01',
 '\n                Orchard Road',
 '\n                Singapore 238888',
 'Opening Hours: ',
 '\n                24 hours (Daily)',
 '\n                Telephone: 6737 8036']

rawDescription: scrapy, how to separate text within a HTML tag element

description: Scrapy, how to separate text within a HTML tag element


code:
ARTICLE_TYPE_CHOICES = (
    (0, 'music'),
    (1, 'weddings'),
    (2, 'outreach'),
    ...
)

class Article(models.Model):
     ...
     type = models.IntegerField(choices=ARTICLE_TYPE_CHOICES)
     ...

rawDescription: Refactoring Django class-based views, clean up 18 repetitive classes.


rawDescription: Python RegEx: How to deal with lines

description: Python RegEx: How to deal with lines


code:
from contextlib import contextmanager

none_context = contextmanager(lambda: iter([None]))()
# <contextlib.GeneratorContextManager at 0x1021a0110>

with (open(f) if f is not None else none_context) as FILE:
    do_something(FILE)

rawDescription: Is it possible to have an optional with/as statement in python?


code:
hash(1)
hash(0)
hash(-1)

rawDescription: hashing different tuples in python give identical result

description: Hashing different tuples in python give identical result


rawDescription: Python regex -- extraneous matchings

description: Python regex -- extraneous matchings


code:
import json

json_dict = {}
for arrival_date, data in df.groupby('ArrivalDate'):
    matching_dates = data[data.DepatureDate==arrival_date]
    not_matching_dates = data[data.DepatureDate!=arrival_date]
    json_dict[arrival_date.strftime('%Y-%m-%d')] = {}
    if not matching_dates.empty:
        for city, flights in matching_dates.groupby('Arrival'):
            json_dict[arrival_date.strftime('%Y-%m-%d')][city] = [str(v) for v in flights.ID.to_dict().values()]
    if not not_matching_dates.empty:
        for city, flights in not_matching_dates.groupby('Departure'):
            json_dict[arrival_date.strftime('%Y-%m-%d')][city] = [str(v) for v in flights.ID.to_dict().values()]

rawDescription: I need help to structure the python csv to json in the following format, pease


rawDescription: Using regex to find a string starting with /team/ and ending with /Euro_2012


rawDescription: How to delete all the odd ordinal items in a list?

description: Delete all the odd ordinal items in a list


rawDescription: Python: Making a read-only property accessible via **vars(some_class)


rawDescription: How do I create a python subprocess using a file for stdin starting at a certain line?

description: Create a python subprocess using a file for stdin starting at a certain line


code:
import os

all_files = os.listdir(os.path.dirname(__file__))
modules = [x for x in all_files if x.endswith(".py") and not x.startswith("_")]
__all__ = [x.rpartition(".")[0] for x in modules]

rawDescription: Why does import * not run the imported code?


code:
def profile():
    global Profile
    import sys
    if "path/to/your/project" not in sys.path:
        sys.path.append("path/to/your/project")
    from userprofile.models import Profile

rawDescription: How can I permanently store commands in the Python REPL/prompt?

description: Permanently store commands in the Python REPL/prompt


code:
from collections import defaultdict
d = defaultdict(int)
for i in dates:
   d[i[0]] += 1
[[k,d[k]] for k in d]

rawDescription: python count number of times the date has appeared

description: Python count number of times the date has appeared


code:
from collections import deque
def stock_sim(price,time,mu,std):
    temp = deque([price + random.lognormvariate(mu,std) for i in range(time)])
    temp.appendleft(price)
    return temp

rawDescription: I am creating a list and need to return the initial value


code:
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'ID1': [1]*4+[2]*2, 'ID2':list('ABCDAB'),
    'Conversion Rate': [0.046562, 0.315975, 0.577998, 0.059465, 0.6, 0.4]})
raw_df = pd.DataFrame({'ID1': [1,2], 'Value':[100, 200]})

def random_id2(x):
    return np.random.choice(x['ID2'], p=x['Conversion Rate'].values)

id2 = df.groupby(['ID1']).apply(random_id2)

final_df = raw_df.copy()
final_df['ID1'] = final_df['ID1'].map(id2)
final_df = final_df.rename(columns={'ID1': 'ID2'})

print(final_df)

rawDescription: Random sampling and Pandas dataframes

description: Random sampling and Pandas dataframes


code:
import ast
import re

order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall

with open(FILENAME) as inf:
    for line in inf:
        order = [ast.literal_eval(op) for op in order_items(line)]
        # ta-da! Now do something with the order

rawDescription: Converting an unknown data structure to a known data structure in Python


rawDescription: Converting a list of Python dictionaries into a SciPy sparse matrix


code:
# row, column indices of the lower triangle of B
r, c = np.tril_indices_from(B)

# flip the column indices by subtracting them from r, which is equal to the number
# of nonzero elements in each row minus one
B[r, c] = B[r, r - c]

print(repr(B))
# array([[ 1.  ,  0.  ,  0.  ,  0.  ],
#        [ 0.75,  0.25,  0.  ,  0.  ],
#        [ 0.7 ,  0.2 ,  0.1 ,  0.  ],
#        [ 0.1 ,  0.4 ,  0.3 ,  0.2 ]])

rawDescription: Flip non-zero values along each row of a lower triangular numpy array


code:
from contextlib import contextmanager

@contextmanager
def redirect_stdout(filename):
    orig_stdout = sys.stdout
    try:
        with open(filename, "w+") as outfile:
            sys.stdout = outfile
            yield
    finally:
        sys.stdout = orig_stdout

rawDescription: How to print to screen after redirect print to file, in python?

description: Print to screen after redirect print to file, in python


code:
transitions = (c for a in drop(5, input)
                 for b in a.split('->')
                 for c in b.split(','))

rawDescription: How to easily transition from Haskell to Python 3

description: Easily transition from Haskell to Python 3


code:
def mapper(f):
    def wrapper(items):
        for x in items:
            yield f(x)
    return rename_code_object(wrapper, f.__name__)

@mapper
def double(x):
    return x * 2

double([1, 2])
list(double([1, 2]))

rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code:
range_10 = range(10)
shifted = RangeShift(range_10, 7)
len(shifted)
shifted.start
shifted.stop
shifted.step
shifted[3]
shifted[8]
list(shifted)
shifted.shift = 3
list(shifted)
range_10_2 = range(0, 10, 2)
shifted_10_2 = RangeShift(range_10_2, 4)
list(shifted_10_2)

rawDescription: Python 3.x Shifting Ranges

description: Python 3.x Shifting Ranges


code:
import operator
try:
    # Python 3 moved reduce to the functools module
    from functools import reduce
except ImportError:
    pass

the_answer = reduce(operator.sub, mynos)

rawDescription: Generating two random numbers and subtracting them


code:
def rotate(strg,n):
    return strg[n:] + strg[:n]

rawDescription: swap letters in a string in python

description: Swap letters in a string in python


code:
owner = serializers.HiddenField(
    default=serializers.CurrentUserDefault()
)

rawDescription: How to add a static User field to django query

description: Add a static User field to django query


code:
haystack = "Foo, bar\nUSER ID bla\n\t\nbla\nbla You can\n cheese"
m = re.findall(r'USER ID.+?You can', haystack, re.DOTALL)
if m:
    print(haystack, "->", m)
else:
    print(haystack, "->", "NO LUCK")

rawDescription: python regular expression get only data between two strings

description: Python regular expression get only data between two strings


code:
X = [ [ Int("x_%s_%s" % (i+1, j+1)) for j in range(9) ]
  for i in range(9) ]

rawDescription: How to define a matrix?

description: Define a matrix


code:
Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))

rawDescription: Checking if sys.argv[x] is defined

description: Checking if sys.argv[x] is defined


code:
type(r.json())
dict

rawDescription: How to pull information from a Json

description: Pull information from a Json


code:
input_file = open('a_file_that_you_prepared.txt', 'r')
subprocess.Popen('sh abc.sh',
                 shell=True,
                 stdout=subprocess.PIPE,
                 stdin=input_file)
input_file.close()

rawDescription: Press enter as command input

description: Press enter as command input


code:
from flask import Flask, render_template_string, request, jsonify
import wikipedia

app = Flask(__name__)

index_html='''

Search Term: <input id="key" name="key"/>
<input id="submit" type="button" value="Go" onclick="submit();" />

'''

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

@app.route('/topics')
def topics():
    key = request.args.get('key')
    topics = wikipedia.search(key) or ['No topic found']
    return jsonify(topics=topics)

app.run(debug=True)

rawDescription: Using Flask, Jinja2, HTML to update page on buttonpress


code:
def accepts_method(decorator):

    @functools.wraps(decorator)
    def decowrapper(func):
        if hasattr(func, "im_func"):
            return type(func)(decorator(func.im_func), func.im_self, func.im_class)
        else:
            return decorator(func)

    return decowrapper

rawDescription: Python: I want to decorate a MethodType attribute without changing the attribute type to FunctionType


rawDescription: How to have negative zero always formatted as positive zero in a python string?

description: Have negative zero always formatted as positive zero in a python string


code:
client_id = found[0]['client_uuid']
all_from_client = rc.db_query({'client_uuid': client_uuid})

rawDescription: IPython parallel : how to recover job IDs from IPcontroller


code:
class C(object):
    def my_regular_method(self, foo, bar):
        pass
    @staticmethod
    def my_static_method(foo, bar):
        pass

c = C()
c.my_regular_method(1, 2)
c.my_static_method(1, 2)

rawDescription: Can python have class or instance methods that do not have "self" as the first argument?


rawDescription: What's the difference between groupby.first() and groupby.head(1)


code:
from scrapy.crawler import Crawler
from scrapy import signals
from scrapy.utils.project import get_project_settings
from twisted.internet import reactor
from billiard import Process

class CrawlerScript(Process):
    def __init__(self, spider):
        Process.__init__(self)
        settings = get_project_settings()
        self.crawler = Crawler(spider.__class__, settings)
        self.crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
        self.spider = spider

    def run(self):
        self.crawler.crawl(self.spider)
        reactor.run()

def crawl_async():
    spider = MySpider()
    crawler = CrawlerScript(spider)
    crawler.start()
    crawler.join()

rawDescription: Easiest way to run scrapy crawler so it doesn't block the script


code: any('cow' in v for v in animals.values())

rawDescription: Python: Testing if a value is present in a defaultdict list


code:
import re
r = re.compile(r'\d(@+)')
a = 'some text 1 a8 777@@@ @ more text here 123 456'
r.search(a).group(1)
b = 'some text @@@ @ more text here 123 456'
r.search(b) #None
c = 'some text @@@ 777@ more text here 123 456'
r.search(c).group(1)

rawDescription: How to extract a specific symbols from string if they follow after the number

description: Extract a specific symbols from string if they follow after the number


code:
def create_something(self):
    self.variable = loader.loadModel('myModel.bam')
    self.variable.setPos(123,1231,5)

rawDescription: Accessing a variable defined inside a function Python


code: forget_torpedoes( [5, 6, 7, 8] )

rawDescription: Dictionary of dictionaries in python!

description: Dictionary of dictionaries in python!


code:
subjects = [
    ["History", "Sociology", "Economics"],
    ["Bengali", "Hindi"],
    ["Sanskrit", "Mathematics"],
    ["Philosophy"],
    ["Political Science"],
    ["English"]
]

rawDescription: Algorithm ,Finding combination from a list with n elements


code:
from operator import methodcaller
results = map(methodcaller('method'), myObjects)

rawDescription: best way to deal with a large number of objects in python

description: Deal with a large number of objects in python


code:
import Tkinter as tk

NUM_BUTTONS = 3
button_list = []
label_list = []

def toggle_text(button_num):
    button = button_list[button_num]
    label = label_list[button_num]
    if button['text'] == 'WL':
        button['text'] = 'WYL'
        label['bg'] = 'green'
    else:
        button['text'] = 'WL'
        label['bg'] = 'red'

root = tk.Tk()
root.title('GUI - TEST')

for i in range(NUM_BUTTONS):  # create widgets
    def _wrapper(button_num=i):  # default argument value is current index
        toggle_text(button_num)

    button = tk.Button(text='WL', width=12, bg='red', command=_wrapper)
    button.grid(row=i, column=1)
    button_list.append(button)

    label = tk.Label(text=i+1, width=6, bg='red')
    label.grid(row=i, column=2)
    label_list.append(label)

root.mainloop()

rawDescription: Basic Python methods & GUI assistance

description: Basic Python methods & GUI assistance


code:
data = pd.DataFrame(np.zeros((15,3)), columns=['RNF', 'WET', 'HMD'])
data

rawDescription: How do I slice a Multindex timeseries dataframe on Pandas?

description: Slice a Multindex timeseries dataframe on Pandas


code:
from itertools import chain

':'.join(chain.from_iterable(data))

rawDescription: Python Iterate an integer as long as elements exist in a list


code:
def encode(input, output, quotetabs, header = 0):
    ...
    def write(s, output=output, lineEnd='\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character encoded.
        if s and s[-1:] in ' \t':
            output.write(s[:-1] + quote(s[-1]) + lineEnd)
        elif s == '.':
            output.write(quote(s) + lineEnd)
        else:
            output.write(s + lineEnd)

    ...  # 35 more lines of code that call write in several places

rawDescription: Real-world examples of nested functions

description: Real-world examples of nested functions


code:
for file in def_scons_exe:
    if file == item[-4:]:
        filelist.append(filepath)

rawDescription: finding specific type of files in mac (python)

description: Finding specific type of files in mac (python)


code:
class VideoAdmin(admin.ModelAdmin):
    ...
    class Media:
        js = ('path/to/this.js',)

rawDescription: Django: change inlines based on select option


code:
city, state = line.split(', ')
state = state[:2]
return (city, state)

rawDescription: Splitting a state name with a city name, return a list containing both?


code:
types = {"A": func_a,
         "B": func_b}

choice = input("A/B: ")

types[choice]()

rawDescription: Run Code based on User Input (Python3,Pandas)


code:
class ipthread(threading.Thread):
  def __init__(self, ip=None, labelobj=None):
    self.ip = ip
    self.labelobj = labelobj

  def newip(self, ip):
    self.ip = ip

  def run(self):
    while True:
        self.response = os.system("ping -c 1 -W 10 " + self.ip + " > /dev/null 2> /dev/null")
        if self.response==0:
            self.labelobj.config(text="connected", bg='green')
        else:
            self.labelobj.config(text="no connection", bg='red')
        time.sleep(1)

rawDescription: Is this a valid way to subclass a python thread to accept a variable update?


code:
import random

def draw_with_delayed_replacement(seq):
    drawn = random.choice(seq)
    rejectables = [drawn]
    yield drawn

    drawn = random.choice(seq)
    while drawn in rejectables:
        drawn = random.choice(seq)
    rejectables.append(drawn)
    yield drawn

    while True:
        drawn = random.choice(seq)
        if drawn in rejectables:
            continue
        else:
            rejectables.pop(0)
            rejectables.append(drawn)
            yield drawn

rawDescription: shuffle list with repetition constraint 2-back python

description: Shuffle list with repetition constraint 2-back python


code:
DCNS = 'http://purl.org/dc/elements/1.1/'
creator = article_node.xpath('.//{{{0}}}creator'.format(DCNS))

rawDescription: python : lxml xpath tag name with colon

description: Python : lxml xpath tag name with colon


code:
with open("classScores.txt", "a") as my_file:  #my_file is automatically closed after execution leaves the body of the with statement
    username = 'Sajjjjid'
    correct_answers = 3

    my_file.write("{}:{}\n".format(username,correct_answers))

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


code:
class Thing(object):
  def __init__(self, id, targets, binaries):
    self.id = id
    self.targets = targets
    self.binaries = binaries

import numpy as np
t = Thing(1, np.arange(3), np.arange(3,9,2))

import dill
with open('electron_data.pkl', 'w') as f:
  dill.dump(t, f)

rawDescription: How does Python pickle save objects?

description: How does Python pickle save objects


code:
list_1 = "if looks kill then i'm murdering".split()
dic_1 = {"kill": -2, "murdering": -3, "monty": 5}
set_1 = set()
set_1 |= dic_1.viewkeys() & list_1
set_1
set_1 |= dic_1.viewkeys() & "monty python's flying circus".split()
set_1

rawDescription: How can I extract list items using dictionary keys?

description: Extract list items using dictionary keys


code:
result = pd.DataFrame()
result['document_id'] = df.groupby(['company', 'year']).apply(lambda x: [d for d in x['document_id'].drop_duplicates()])

rawDescription: Pandas dataframe frequency operation

description: Pandas dataframe frequency operation


code:
secret_string = SecretString("ACME: Top Secret", "antwerp")
print(secret_string.decrypt("antwerp"))
print(secret_string.__plain_text)

rawDescription: How to deny users to create an instance of a parent object in Python

description: Deny users to create an instance of a parent object in Python


code:
test1.func
Test.func

rawDescription: python functions

description: Python functions


rawDescription: numpy.power() and math.pow() don't give the same result

description: Numpy.power() and math.pow() don't give the same result


rawDescription: Modular addition in python

description: Modular addition in python


code:
df['quartile boundaries'] = pctile_object
pandas.merge(df,df2,on='quartile boundaries')

rawDescription: Pandas assign each row the mean of its bin


code:
from matplotlib import pyplot as plt
fig = plt.figure()                      # initialize figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # add axis

rawDescription: How to shrink plot on x-axis in matplotlib?

description: Shrink plot on x-axis in matplotlib


code:
class Agent(object): # Agent is now a new-style class
    def __init__(self):
        self.cmd_queue = Queue()
        self.res_queue = Queue()
        self.worker = Worker(self.cmd_queue, self.res_queue)
        self.worker.start()

    def __getstate__(self):
        """ This is called to pickle the instance """
        self_dict = self.__dict__.copy()
        del self_dict['cmd_queue']
        del self_dict['res_queue']
        del self_dict['worker']
        return self_dict

    def __setstate__(self, self_dict):
        """ This is called to unpickle the instance. """
        self.__dict__ = self_dict

    ... # The rest is the same.

rawDescription: Python multiprocessing in objects

description: Python multiprocessing in objects


rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code:
setup="""
R = 100
C = 100
from copy import deepcopy
import numpy as np
ref = [[i for i in range(C)] for _ in range(R)]
ref_np = np.array(ref)
cp = [[100 for i in range(C)] for _ in range(R)]
cp_np = np.array(cp)
"""

rawDescription: What is the fastest way to copy a 2D array in Python?


code: all_lines = f.readlines()

rawDescription: Python: Why do my loops on a certain text file read empty lines although the file is not empty?


code:
json_obj = {'nomNom': {'fooNom': 2, 'camelFoo': 3}, 'camelCase': {'caseFoo': 4, 'barBar': {'fooFoo': 44}}}
convert_json(json_obj, camel_to_underscore)

rawDescription: Converting identifier naming between camelCase and underscores during JSON serialization/deserialization


code: foo = func

rawDescription: Defining a function multiple times

description: Defining a function multiple times


code:
from datetime import datetime
start = datetime.now()

rawDescription: Python: How to time script from beginning to end?


code:
for sublist in thelist:
  sublist[0:0] = 8, 9

rawDescription: Modifying list contents in Python

description: Modifying list contents in Python


code:
import matplotlib.pyplot as plt

fig = plt.Figure()
ax = fig.add_subplot(111)

colors = ('b','g','r','c','m','y','k','w',)
sessions = (sess1, sess2, sess3)
for sess, color in zip(sessions, colors):
    ax.plot(sess.x, sess.y, color=color)

rawDescription: matplotlib - runtime adding multiple lines without knowing in advance

description: Matplotlib - runtime adding multiple lines without knowing in advance


code:
m = re.sub(r'dog(?=\d)', r'animal_', s)
m

rawDescription: Python regex sub with 1 following paramter


code:
import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

rawDescription: How to set xlim and ylim for a subplot in matplotlib

description: Set xlim and ylim for a subplot in matplotlib


code:
list_of_dicts = [{"this": "hi
", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty
", "good bye": "to all of that"}]
tmp = []

for dic in list_of_dicts:
    for key, val in dic.items():
        tmp.append({key: val.replace("
", " ")})

list_of_dicts = tmp

rawDescription: How to Alter a Dict's Values in a List Comprehension


code:
class User(rom.Model):
    name = rom.String(required=True, unique=True, index=True)
    nickname = rom.String(required=False)
    photo = rom.String(required=False)

user1 = User(name="Ankush", nickname="iamankush", photo="http://graph.facebook.com/iamkhush/picture")
user1.save()
User.query.filter(name="ankush").all()

rawDescription: Unable to use query with Redis Object Mapper (ROM)


code: i+1  # i has no value assign to it. Since i+1 is doing something to i, this will not work.

rawDescription: How do I create variables without declaration in python?

description: Create variables without declaration in python


code: x,y,z = [float(f) for f in p.split()]

rawDescription: Breaking an XML string into three floats


rawDescription: Getting the closest date to a given date


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

import pandas as pd

urls = [
    'http://www.oddsportal.com/hockey/austria/ebel-2014-2015/results/#/page/',
    'http://www.oddsportal.com/hockey/austria/ebel-2013-2014/results/#/page/'
]

data = []

driver = webdriver.PhantomJS()
driver.implicitly_wait(10)
wait = WebDriverWait(driver, 10)

for url in urls:
    for page in range(1, 8):
        driver.get(url + str(page))
        # wait for the page to load
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div#tournamentTable tr.deactivate")))

        for match in driver.find_elements_by_css_selector("div#tournamentTable tr.deactivate"):
            home, away = match.find_element_by_class_name("table-participant").text.split(" - ")
            date = match.find_element_by_xpath(".//preceding::th[contains(@class, 'first2')][1]").text

            if " - " in date:
                date, event = date.split(" - ")
            else:
                event = "Not specified"

            data.append({
                "home": home.strip(),
                "away": away.strip(),
                "date": date.strip(),
                "event": event.strip()
            })

driver.close()

df = pd.DataFrame(data)
print(df)

rawDescription: Selenium scraping with multiple urls

description: Selenium scraping with multiple urls


rawDescription: Is it bad to name a Python module "global" or other keyword?


code:
ranges = {v: [v, v] for v in values}

for v in values:
    if v - 1 in ranges and v in ranges:
        p, q = ranges[v - 1], ranges[v]
        if p[1] == v - 1 and q[0] == v:
            if q[0] != q[1]:
                del ranges[q[0]]
            if p[0] != p[1]:
                del ranges[p[1]]
            p[1] = q[1]
            ranges[p[1]] = p

result = {k: v[1] - v[0] + 1 for k, v in ranges.iteritems() if k == v[0]}

rawDescription: Partitioning a set of values in Python

description: Partitioning a set of values in Python


code:
db.seqs.insert({
    'collection' : 'admin_collection',
    'id' : 0
})

rawDescription: How to autoincrement id at every insert in Pymongo?

description: Autoincrement id at every insert in Pymongo


code:
from pprint import pprint
pprint(dicts)

rawDescription: How to read lines of dictionary and write to a CSV file

description: Read lines of dictionary and write to a CSV file


rawDescription: How do you change a list of integers and strings into a list of integers and floats in python?

description: Change a list of integers and strings into a list of integers and floats in python


code:
class Choice(models.Model):
    question = models.ForeignKey(Question, related_name='choices')

rawDescription: Setting of model attribute which lists all related items


code:
class mybitarray(bitarray):
    def __lshift__(self, count):
        return self[count:] + type(self)('0') * count
    def __rshift__(self, count):
        return type(self)('0') * count + self[:-count]
    def __repr__(self):
        return "{}('{}')".format(type(self).__name__, self.to01())

rawDescription: How to left shift a bitarray in python

description: Left shift a bitarray in python


code:
class aHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        self.write(json.dumps(dict(
            location='/tasks',
            user=self.current_user,
            timestamp='',
            projects='',
            type='',
            taskCount='',
            resName='')))

rawDescription: Tornado redirecting to page with parameters


code:
data = ['\n\nfoo','\n\n\nbar']
sum(item.count('\n') for item in data)

rawDescription: Python .count: Can't find correct syntax to count \n


code:
import re

regex = re.match(r'''(^
    \s*
    (clns|bfd|ip)
    \s+
    (routing|graceful-restart|default-network|default-gateway|subnet-zero|cef)
$)+''', re.MULTILINE | re.VERBOSE)

rawDescription: Match multiple lines in a file using regular expression python


code:
def find_station(lat, long):
    distances = weather.apply(
        lambda row: dist(lat, long, row['Latitude'], row['Longitude']),
        axis=1)
    return weather.loc[distances.idxmin(), 'StationName']

rawDescription: How to find the closest match based on 2 keys from one dataframe to another?

description: Find the closest match based on 2 keys from one dataframe to another


code:
from bs4 import BeautifulSoup

data = """

"""

soup = BeautifulSoup(data)
print(soup.select('tr.deals span.hotel-name a')[0]['href'])

rawDescription: Get value of attribute using CSS Selectors with BeutifulSoup


code:
with open('filename', 'wb') as f:
    var = {1 : 'a' , 2 : 'b'}
    pickle.dump(var, f)

rawDescription: Python serialization - Why pickle?

description: Python serialization - Why pickle


code: list(set(a) ^ set(b))

rawDescription: Get the items not repeated in a list

description: Get the items not repeated in a list


code:
class SomePage(object):

    def GET(self):
        web.header("Content-Type", "text/html")
        return """
        <html><body>
            <form method="POST">
                <input type="input" name="Domain required" />
                <input type="input" name="example_field" />
                <input type="input" name="example_field_2" />
                <input type="submit" name="submit"/>
            </form>
        </body></html>
        """

    def POST(self):
        cgi_fields = web.input()
        return cgi_fields['Domain required'], cgi_fields.example_field, cgi_fields.get('example_field_2')

rawDescription: Parsing responses from web.py

description: Parsing responses from web.py


code: import foo

rawDescription: How to run a module developed in Eclipse in a Python interactive prompt?

description: Run a module developed in Eclipse in a Python interactive prompt


rawDescription: Conditionally combine columns in pandas data frame


code:
import numpy as np
d1 = np.arange(np.datetime64('2014-11-01 12:00'), np.datetime64('2014-11-01 14:00'))
d2 = d1.copy()
np.random.shuffle(d2)
diff = d2 - d1

rawDescription: Plotting the difference between two datetime64[ns]


code: [w for w in words_list if anagram_match(w)]

rawDescription: Find out the words from a python list which contains permutation of another word


code:
Znew = griddata( X,Y,Z, Xnew,Ynew )
    # 1d X Y Z Xnew Ynew -> interpolated 2d Znew on meshgrid(Xnew,Ynew)
assert X.ndim == Y.ndim == Z.ndim == 1  and  len(X) == len(Y) == len(Z)

rawDescription: Problem with 2D interpolation in SciPy, non-rectangular grid


rawDescription: How to generate a string with user specifying the length

description: Generate a string with user specifying the length


code:
two_thirds = multiplier(2, 3)
two_thirds(7)

rawDescription: What is a cell in the context of an interpreter or compiler?


code:
if 'action:3.4' in request.POST:
    action = '3.4'
...

rawDescription: Get ID of one of multiple buttons in HTML form in Django


code: X = X[..., np.newaxis] if type(X) == np.ndarray else X

rawDescription: Numpy Dimensions: Multiplications with scalar/matrix


code:
from collections import defaultdict
d = defaultdict(set)
d.update({"TIM":set([('xx', 'yy'), ('aa', 'bb')]), "SAM":set([('yy', 'cc')])})
d["SAM"].add(('tt','uu'))
d["KIM"].add(('ii','pp'))
d

rawDescription: Python Dictionary Update and Append

description: Python Dictionary Update and Append


rawDescription: Rounding integers in python

description: Rounding integers in python


code:
@staticmethod
def f():
    return 'hello world'

rawDescription: Is every function in the class with `self` an instance variable even if it just does something unrelated to the specific instance?


code:
@celery.task()
def add(x, y):
    logger = add.get_logger()
    logger.info("Adding %s + %s" % (x, y))
    return x + y

rawDescription: Send log messages from all celery tasks to a single file


rawDescription: All the common elements present in the List of Python


code: def graph2(words): return {word: list(neighbours(word)) for word in words}

rawDescription: Efficiently build a graph of words with given Hamming distance


code:
with open('/etc/ssh/sshd_config') as f:
    for line in f:
        if line.startswith('IgnoreRhosts yes'):
            print(line)

rawDescription: Python regex search for string at beginning of line in file


code:
def views(request):
    form = FooForm(request.POST or None, user=request.user)

rawDescription: Set Months and Day Ranges for SelectDateWidget in Django


code:
...
cursor = connection.cursor()
cursor.execute("""
    INSERT INTO Users (name, phone, date)
    VALUES (%s,%s,%s)
    ON DUPLICATE KEY UPDATE phone = %s, date=%s;
    """,(name,phone,date,phone,date))
cursor.close()

rawDescription: Updating a SQL table with Python 2.7?

description: Updating a SQL table with Python 2.7


code:
import matplotlib.pylab as pl
from matplotlib import rc
rc('text', usetex=True)
rc('font', size=14)
rc('legend', fontsize=13)
rc('text.latex', preamble=r'\usepackage{cmbright}')

pl.figure()
pl.plot([0,1], [0,1], label=r'$\theta_{\phi}^3$')
pl.legend(frameon=False, loc=2)
pl.xlabel(r'change of $\widehat{\phi}$')
pl.ylabel(r'change of $\theta_{\phi}^3$')

rawDescription: Consistent fonts between matplotlib and latex


code:
# Extract the values along the line, using nearest-neighbor interpolation
zi = z[row.astype(int), col.astype(int)]

rawDescription: Plot cross section through heat map

description: Plot cross section through heat map


code:
env = {}
env.update(os.environ)
env.update(jj)
subprocess.call('echo ${pp}', shell=True, env=env)

rawDescription: Execute the shell script by passing certain parameters to it using Python?


rawDescription: How can I iterate through the indices of the list?

description: Iterate through the indices of the list


code:
# Store matching indices of 'sentence' in 'vocab' when "left-searched"
out = np.searchsorted(vocab,sentence,'left').astype(float)

# Get matching indices of 'sentence' in 'vocab' when "right-searched".
# Now, the trick is that non-matches won't have any change between left
# and right searches. So, compare these two searches and look for the
# unchanged ones, which are the invalid ones and set them as NaNs.
right_idx = np.searchsorted(vocab,sentence,'right')
out[out == right_idx] = np.nan

rawDescription: match non-unique, un-sorted array to indexes in unique, sorted array

description: Match non-unique, un-sorted array to indexes in unique, sorted array


code:
from django.db import models
from decimal import Decimal
class CurrencyField(models.DecimalField):
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        try:
           return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01"))
        except AttributeError:
           return None

rawDescription: Django: How should I store a money value?


code:
import tkinter as tk

root = tk.Tk()

button = tk.Button(root, text="this is button")
label = tk.Label(root, text="this is label")

button.pack()
label.pack()

slaves = root.pack_slaves()
print (slaves)

root.mainloop()

rawDescription: GUI Tkinter method which returns a list of all the widgets currently packed with .pack()?


code: "RETR " + filename

rawDescription: What is lambda doing in this python code?


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

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)

x = np.linspace(0, np.pi, 100)

line1, = ax1.plot(x, np.cos(3*x), color='red')
line2, = ax2.plot(x, np.sin(4*x), color='green')

# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0.5
# in figure coordinates.
# "center" is basically saying center horizontal alignment and
# center vertical alignment in this case
fig.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5],
           loc='center', ncol=2)

plt.show()

rawDescription: How to position and align a matplotlib figure legend?

description: Position and align a matplotlib figure legend


code:
from __future__ import division
import pylab
import numpy

from matplotlib.patches import Polygon
from mpl_toolkits.basemap import pyproj
from mpl_toolkits.basemap import Basemap

class Basemap(Basemap):
    def ellipse(self, x0, y0, a, b, n, ax=None, **kwargs):
        """
        Draws a polygon centered at ``x0, y0``. The polygon approximates an
        ellipse on the surface of the Earth with semi-major-axis ``a`` and
        semi-minor axis ``b`` degrees longitude and latitude, made up of
        ``n`` vertices.

        For a description of the properties of ellipsis, please refer to [1].

        The polygon is based upon code written do plot Tissot's indicatrix
        found on the matplotlib mailing list at [2].

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \**kwargs passed on to matplotlib.patches.Polygon

        RETURNS
            poly : a maptplotlib.patches.Polygon object.

        REFERENCES
            [1] : http://en.wikipedia.org/wiki/Ellipse

        """
        ax = kwargs.pop('ax', None) or self._check_ax()
        g = pyproj.Geod(a=self.rmajor, b=self.rminor)
        # Gets forward and back azimuths, plus distances between initial
        # points (x0, y0)
        azf, azb, dist = g.inv([x0, x0], [y0, y0], [x0+a, x0], [y0, y0+b])
        tsid = dist[0] * dist[1] # a * b

        # Initializes list of segments, calculates \del azimuth, and goes on
        # for every vertex
        seg = [self(x0+a, y0)]
        AZ = numpy.linspace(azf[0], 360. + azf[0], n)
        for i, az in enumerate(AZ):
            # Skips segments along equator (Geod can't handle equatorial arcs).
            if numpy.allclose(0., y0) and (numpy.allclose(90., az) or
                numpy.allclose(270., az)):
                continue

            # In polar coordinates, with the origin at the center of the
            # ellipse and with the angular coordinate ``az`` measured from the
            # major axis, the ellipse's equation  is [1]:
            #
            #                           a * b
            # r(az) = ------------------------------------------
            #         ((b * cos(az))**2 + (a * sin(az))**2)**0.5
            #
            # Azymuth angle in radial coordinates and corrected for reference
            # angle.
            azr = 2. * numpy.pi / 360. * (az + 90.)
            A = dist[0] * numpy.sin(azr)
            B = dist[1] * numpy.cos(azr)
            r = tsid / (B**2. + A**2.)**0.5
            lon, lat, azb = g.fwd(x0, y0, az, r)
            x, y = self(lon, lat)

            # Add segment if it is in the map projection region.
            if x < 1e20 and y < 1e20:
                seg.append((x, y))

        poly = Polygon(seg, **kwargs)
        ax.add_patch(poly)

        # Set axes limits to fit map region.
        self.set_axes_limits(ax=ax)

        return poly

rawDescription: Drawing ellipses on matplotlib basemap projections


code: answer = random.randint(1,8)

rawDescription: Dictionary and elif

description: Dictionary and elif


code: from uncertainties.math_ops import *  # Work on scalars and scalars with uncertainty

rawDescription: Definition of mathematical operations (sin…) on NumPy arrays containing objects


rawDescription: Zip list of tuples with flat list

description: Zip list of tuples with flat list


code:
import heapq
def gen_weird_sequence(genA, genB):
    heap = []
    a0 = next_a = next(genA)
    saved_a = []
    for b in genB:
        while next_a < b:
            saved_a.append(next_a)
            next_a = next(genA)
        # saved_a now contains all a < b
        for a in saved_a:
            heapq.heappush(heap, (a+b, a, b)) #decorate pair with sorting key a+b
        # (minimum sum in the next round) > b + a0, so yield everything smaller
        while heap and heap[0][0] <= b + a0:
            yield heapq.heappop(heap)[1:] # pop smallest and undecorate

rawDescription: Generate ordered tuples of infinite sequences


code: x1 = sys.argv[1]

rawDescription: how to pass command line string arguments and compare them python

description: Pass command line string arguments and compare them python


code:
import email.utils
email.utils.parseaddr("John Smith <jsmith@gmail.com>")

rawDescription: Parse small string for name and email?

description: Parse small string for name and email


code:
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.contenttypes.models import ContentType

def make_checked(modeladmin, request, queryset):
    queryset.update(checked = 1)

    ct = ContentType.objects.get_for_model(queryset.model)
    for obj in queryset:
        LogEntry.objects.log_action(
            user_id=request.user.id,
            content_type_id=ct.pk,
            object_id=obj.pk,
            object_repr=obj.description,
            action_flag=CHANGE,
            change_message="You have ...")
make_checked.short_description = 'Mark selected products as checked'

rawDescription: Django - Custom Admin Actions Logging

description: Django - Custom Admin Actions Logging


code: python /usr/bin/ipython

rawDescription: Sending python command line arguments in ipython


code:
import gtk
import rsvg
handle = rsvg.Handle()
handle.write(buffer=xml_data)
# xml_data is the XML string for the object you want
image = gtk.Image()
image.set_from_pixbuf(handle.get_pixbuf())

rawDescription: How do I render *parts* of a svg file?

description: Render *parts* of a svg file


code:
import sys
import serial

ser = serial.Serial(port=sys.argv[1],baudrate=int(sys.argv[2]))
while True:  # The program never ends... will be killed when master is over.
    # sys.stdin.readline()

    ser.write('serial command here\n') # send command to serial port
    output = ser.readline() # read output

    sys.stdout.write(output) # write output to stdout
    sys.stdout.flush()

rawDescription: Python Pyserial read data form multiple serial ports at same time


rawDescription: Scipy sparse matrix assignment using only stored elements


code:
class Avg(object):
    def __init__(self, total=0.0, num=0):
        super(Avg,self).__init__()
        self.total = total
        self.num   = num

    def add(self, value):
        self.total += value
        self.num   += 1

    def value(self):
        return self.total / self.num

def avgBy(data, field=0):
    res = defaultdict(Avg)
    for unit,testdict in data.iteritems():
        for test,val in testdict.iteritems():
            res[(unit,test)[field]].add(val)
    return {item:avg.value() for item,avg in res.iteritems()}

dictone = dictify(listone)
avg_by_unit = avgBy(dictone, 0)
print(avg_by_unit)
avg_by_test = avgBy(dictone, 1)
print(avg_by_test)

rawDescription: Python: Substracting between list of dictionaries


code:
from flask.ext.sqlalchemy import Session

@app.route('/example/')
def home():
    session_two = Session(bind=db.engine.connect())
    foos = session_two.query(Foo).all()

    for foo in foos:
        db.session.add(Bar(foo))
    db.session.commit()

    return render_template_string('''
        {% for foo in foos %}
            {{ foo.name }}
        {% endfor %}
    ''', foos=foos)

rawDescription: Proper way to prevent SQLAlchemy from re-running queries on expired objects?


code:
self.button1 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(1))
...
self.button2 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(2))

rawDescription: On python, how do I determine which button was clicked


code: #!/usr/bin/python (Depends on where your python is: check its path with: $ whereis python)

rawDescription: How to run python script only once in a specific day of the week in bash

description: Run python script only once in a specific day of the week in bash


code:
Outputting: 0
Outputting: 1
Outputting: 2
...
Outputting: 9997
Outputting: 9998
Outputting: 9999

rawDescription: Python capture stdout from subprocess line by line


code:
import sys
from PyQt5.QtWidgets import (QWidget, QToolTip,
    QPushButton, QApplication)
from PyQt5.QtGui import QFont

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setToolTip('This is a QWidget widget')

        btn = QPushButton('Button', self)
        btn.setToolTip('This is a QPushButton widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Tooltips')
        self.show()

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

rawDescription: Why Tkinter can be procedural and PyQt can only be used just with the OO paradigm?


code:
def f5(last_N_days):
    with open("data.csv") as i, open("resuls.csv", "wb") as o:
        rdr = csv.reader(i)
        wrt = csv.writer(o)
        data, currdate = defaultdict(lambda:[0, 0,0,0]), None
        cumulativedata = defaultdict(lambda:defaultdict(lambda:[0, 0,0,0]))
        for line in rdr:
            date, name = datetime.datetime.strptime(line[0], '%d/%m/%Y'), line[7]

            if date != currdate or not currdate:
                for k,v in data.iteritems():
                    cumulativedata[currdate][k] = list(v[2:])
                    v[:2]=[v[2] - cumulativedata[clean_before][k][0],
                                 v[3] - cumulativedata[clean_before][k][1]]
                clean_before = date + datetime.timedelta(days=-(last_N_days))
                currdate = date

            wrt.writerow(line + data[name][:2])

            data[name][3] += 1

            if line[6] == "1":
                data[name][2] += 1

f5(1) # Calculate only for last 1 day

rawDescription: Counting number of occurrences up to x days previous to row date


code:
i2d = np.unravel_index(i, a.shape)
i2d

rawDescription: Get max or min n-elements out of numpy array? (preferably not flattened)


code: df['dailyOpen'] = df.groupby('date').open.transform(lambda s: s[0])

rawDescription: FX Data - analyse intraday data

description: FX Data - analyse intraday data


rawDescription: Detecting geographic clusters

description: Detecting geographic clusters


code:
with open("data_points.txt") as f:
    content = f.readlines()
    content = [x.strip("\n")for x in content]
    content = [x.replace("\xa1\xa6", "20") for x in content]
    content = [x.replace("\xa1P", " ") for x in content]

rawDescription: Making columns with data in other column in Pandas


rawDescription: One x axis, one y axis on left, one y axis on right


code:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, -2, 3])
c = a == b
c

rawDescription: How to compare two arrays in python with 1s for hits and 0s for non-hits?

description: Compare two arrays in python with 1s for hits and 0s for non-hits


code:
import numpy as np
from matplotlib import pyplot as pl
from matplotlib import cm

measurements = np.array([[0, "a"], [1, "b"], [2, "c"]])
times = np.arange(3)
values = np.array(measurements[:,0], dtype=float)
parameters = np.array(measurements[:,1], dtype='S1')

pl.scatter(times, values, c = cm.spectral(values/max(values)))
pl.show()

rawDescription: Plot a curve that has different colors depending on a parameter


code:
nop = number_of_particles

# Give pos a 3rd index so we can use np.repeat below
# equivalent to `pos3d = np.array([ position ])
pos3d = position.reshape(1, nop, 2)

# 3D arras with a repeated index so we can form combinations
# diff_i[i][j] = position[i] (for all j)
# diff_j[i][j] = position[j] (for all i)
diff_i = np.repeat(pos3d, nop, axis=1).reshape(nop, nop, 2)
diff_j = np.repeat(pos3d, nop, axis=0)

# diff[i][j] = vector pointing from position[i] to position[j]
diff = diff_j - diff_i

# norm[i][j] = sqrt( diff[i][j]**2 )
norm = np.linalg.norm(diff, axis=2)

# check for collisions and take the region above the diagonal
collided = np.triu(norm < radius, k=1)

for i, j in zip(*np.nonzero(collided)):
    # unit vector from i to j
    unit = diff[i][j] / norm[i][j]

    # flip velocity
    velocity[i] -= 1.9 * np.dot(unit, velocity[i]) * unit
    velocity[j] -= 1.9 * np.dot(unit, velocity[j]) * unit

    # push particle j to be radius units from i
    # This isn't particularly effective when 3+ points are close together
    position[j] += (radius - norm[i][j]) * unit

...

rawDescription: Many particles in box - physics simulation


code: PREFIXES = [sys.prefix, sys.exec_prefix, '/usr/local']

rawDescription: How come when I move a python file into scipy.stats folder in ubuntu it disappears?


code:
'''
Sources:
http://pythonpath.wordpress.com/2012/05/08/pil-to-opencv-image/
http://www.lucaamore.com/?p=638
'''

#Python 2.7.2
#Opencv 2.4.2
#PIL 1.1.7

import cv
import Image

def DetectFace(image, faceCascade):
    #modified from: http://www.lucaamore.com/?p=638

    min_size = (20,20)
    image_scale = 1
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Allocate the temporary images
    smallImage = cv.CreateImage(
            (
                cv.Round(image.width / image_scale),
                cv.Round(image.height / image_scale)
            ), 8 ,1)

    # Scale input image for faster processing
    cv.Resize(image, smallImage, cv.CV_INTER_LINEAR)

    # Equalize the histogram
    cv.EqualizeHist(smallImage, smallImage)

    # Detect the faces
    faces = cv.HaarDetectObjects(
            smallImage, faceCascade, cv.CreateMemStorage(0),
            haar_scale, min_neighbors, haar_flags, min_size
        )

    # If faces are found
    if faces:
        for ((x, y, w, h), n) in faces:
            # the input to cv.HaarDetectObjects was resized, so scale the
            # bounding box of each face and convert it to two CvPoints
            pt1 = (int(x * image_scale), int(y * image_scale))
            pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
            cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)

    return image

def pil2cvGrey(pil_im):
    #from: http://pythonpath.wordpress.com/2012/05/08/pil-to-opencv-image/
    pil_im = pil_im.convert('L')
    cv_im = cv.CreateImageHeader(pil_im.size, cv.IPL_DEPTH_8U, 1)
    cv.SetData(cv_im, pil_im.tostring(), pil_im.size[0]  )
    return cv_im

def cv2pil(cv_im):
    return Image.fromstring("L", cv.GetSize(cv_im), cv_im.tostring())

pil_im=Image.open('testPics/faces.jpg')
cv_im=pil2cv(pil_im)
#the haarcascade files tells opencv what to look for.
faceCascade = cv.Load('C:/Python27/Lib/site-packages/opencv/haarcascade_frontalface_default.xml')
face=DetectFace(cv_im,faceCascade)
img=cv2pil(face)
img.show()

rawDescription: Detect face then autocrop pictures

description: Detect face then autocrop pictures


code:
seen = set()
s1 = [x for x in a if x[0] not in seen and not seen.add(x[0])]
seen = set()
s2 = [x for x in b if x[0] not in seen and not seen.add(x[0])]
s1
s2

rawDescription: Python Operations (Intersection, Union, Duplicate) with nested Lists/Tuples possible?


code:
def f(x, y):
    return x * y

rawDescription: How to use filter() on a string and get multiple word occurences?

description: Use filter() on a string and get multiple word occurences


rawDescription: How to separate data imported as text in Python into datearray and numeric data

description: Separate data imported as text in Python into datearray and numeric data


code: print(yaml.dump({'name': 'wut', 'age': 'wise'}, default_flow_style=False))

rawDescription: PyYAML dumping invalid YAML unless param includes an array


code: getCssValue(property-name)

rawDescription: How do I select an element by its style from css (not inline) using webdriver (python)

description: Select an element by its style from css (not inline) using webdriver (python)


code: areasList = SelectMultipleField(u'Test Areas', choices=TestArea.names())

rawDescription: WTForms - multi-value string to SelectMultipleField


code: extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

rawDescription: How to enlarge image axis in Python?

description: Enlarge image axis in Python


code: tk.Button(..., command=prog.runprog)

rawDescription: Python tkinter button callback unexpected behaviour


code: df['delta'] = df.val_ - df.val

rawDescription: Pandas dataframe - deltas of data with same ids


code:
from ocmg_common.protobuf.rpc_pb2 import Exception as PBException
from importlib import import_module

pb_message = PBException(message='hello world')
pb_message_string = pb_message.SerializeToString()

def deserialize(message, typ):
    module_, class_ = typ.rsplit('.', 1)
    class_ = getattr(import_module(module_), class_)
    rv = class_()
    rv.ParseFromString(message)
    return rv

print(deserialize(pb_message_string, 'ocmg_common.protobuf.rpc_pb2.Exception'))

rawDescription: Deserialize Protobuf in python from class name


code: x.rpartition(' ')[-1]  # Splits on the first actual space found

rawDescription: Split off the contents of a variable after the last space in python?


code:
import urllib.request
url="http://einstein.biz/"
m = urllib.request.urlopen(url)
msg = m.read()
regex = re.compile(r'(?s)<a\s*href=[\'"].*?[\'"][^<>]*>([A-Za-z][^<>]*)</a>')
titles = regex.findall(str(msg))
print(titles)

rawDescription: How to extract all the link name from a html page

description: Extract all the link name from a html page


code:
from numpy.random import rand
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

NUM = 3
ellipse = lambda: Ellipse(rand(2)*10, rand(), rand(), rand()*360)
ells = [ellipse() for i in range(NUM)]

fig, ax = plt.subplots()

for e in ells:
    ax.add_artist(e)
    e.set(clip_box=ax.bbox, alpha=rand(), facecolor=rand(3))

ax.legend(ells, ['Ellipse{}'.format(i+1) for i in range(NUM)])
ax.set(xlim=[0, 10], ylim=[0, 10], aspect='equal')

plt.show()

rawDescription: Label plotted ellipses

description: Label plotted ellipses


code:
with open("list.csv", "U") as file1, open("example.csv", "rb") as file2, open("output.csv", "wb+") as file3:
    reader1 = csv.reader(file1)
    reader2 = csv.reader(file2)
    writer = csv.writer(file3)

    reader1_rows = [row for row in reader1]
    reader2_rows = [row for row in reader2]

    for num, row in enumerate(reader1_rows):
        if ([word for word in row if word in ' '.join(reader2_rows[num])]):
            writer.writerow([row, reader2_rows[num]])

rawDescription: Similarities between two csv files

description: Similarities between two csv files


code:
#!/usr/bin/env python3
import os
#--- set the path to the directory, the new file and the tag below
dr = "/path/to/directory"; out = "/path/to/newfile"; tag = ".txt"
#---

files = os.listdir(dr)
for f in files:
    if f.endswith(tag):
        # read the file as a list of lines
        content = open(dr+"/"+f).readlines()
        # the first item in a list = index 0, so line 23 is index 22
        needed_lines = content[22:25]
        # convert list to string, add a new line
        string_topaste = ("").join(needed_lines)+"\n"
        # add the lines to the new file, create the file if necessary
        open(out, "+a").write(string_topaste)

rawDescription: Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines)


code:
College.__init__.__defaults__
foo = College()
foo.courses
print(foo)

rawDescription: Why does JSONDecoder deserialize json String to Python Objects intuitively?


code:
s = 'The quick brown fox jumps over the lazy dog'
m = re.search('brown', s)
m.span()
start, end = m.span()
s[end:]

rawDescription: Find length of string matched by regex

description: Find length of string matched by regex


code: quote("")

rawDescription: Quote POSIX shell special characters in Python output


code:
selectedCoins = []
for coin in coins:
    if coin <= price:
        selectedCoins.append(mincoinList[price - coin])

return min(selectedCoins) + 1

rawDescription: Returning minimum of array with for loop iteration


rawDescription: What is the best way to do multi-dimensional indexing with numpy?


code:
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise
with open(filename, "w") as f:
    f.write("FOOBAR")

rawDescription: Python, automatically creating directories with file output


code:
import requests

url = 'http://pool.cdn.lagardere.cz/fm-evropa2-128'

def print_url(r, *args, **kwargs):
    print(r.headers)

requests.get(url, hooks=dict(response=print_url))

rawDescription: Python 3 - Urllib3 read internet radio metadata


code: return set(main_list)

rawDescription: all subsets of a set append Nonetype Error

description: All subsets of a set append Nonetype Error


code:
app = Flask(__name__, template_folder='views')
app.register_blueprint(controllers.route1, url_prefix="/route1")
app.register_blueprint(controllers.route2, url_prefix="/route2")

rawDescription: Modular routes in python flask

description: Modular routes in python flask


code: [(i,j) for i,j in combinations(my_list,2) if i+j==30]

rawDescription: How to iterate and sum each element in a list with another to find a number?

description: Iterate and sum each element in a list with another to find a number


code:
import itertools

def parse1(file,stop):
# 1st parsing function
    for line in file:
       # Stop parsing on condition
        if line.strip() == stop:
            return itertools.chain([line],file) # important line
        else:
        # Parse the line (just print for example)
            print('parse1: '+line)

rawDescription: Cancel last line iteration on a file

description: Cancel last line iteration on a file


code: set(['pathA/file2', 'pathA/file9'])

rawDescription: re-implement __eq__ to compare sets with symmetric_difference in python

description: Re-implement __eq__ to compare sets with symmetric_difference in python


code:
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']
['Day', 'Date', 'Week']

rawDescription: Is it possible to display only first list element in for loop?


code:
def cmp_list(x,y):
    return True if x == y else all( abs(a) == abs(b) for a,b in zip(a,b) )

duplicate_idx = [ idx for idx,val in enumerate(your_list_of_lists[1:])
                  if cmp_list(val,your_list_of_lists[idx])  ]

#now remove duplicates:
for idx in reversed(duplicate_idx):
    _ = your_list_of_lists.pop(idx)

rawDescription: Sort list of lists by unique reversed absolute condition


rawDescription: Python - getting all the min elements and its indices from a list


code:
{"date": "2013-06-21 17:48:00", "interpret": "MUMFORD & SONS", "title": "I WILL WAIT"}
{"date": "2013-06-21 17:44:00", "interpret": "TASMIN ARCHER", "title": "SLEEPING SATELLITE"}
{"date": "2013-06-21 17:40:03", "interpret": "ROBIN THICKE", "title": "BLURRED LINES (feat. T.I. & PHARRELL)"}
{"date": "2013-06-21 17:35:02", "interpret": "TINA TURNER", "title": "TWO PEOPLE"}
{"date": "2013-06-21 17:31:02", "interpret": "BON JOVI", "title": "WHAT ABOUT NOW"}
{"date": "2013-06-21 17:28:03", "interpret": "ROXETTE", "title": "SHE'S GOT NOTHING ON (BUT THE RADIO)"}
{"date": "2013-06-21 17:18:01", "interpret": "GNARLS BARKLEY", "title": "CRAZY"}
{"date": "2013-06-21 17:08:01", "interpret": "FLO RIDA", "title": "WHISTLE"}
{"date": "2013-06-21 17:05:03", "interpret": "WHAM", "title": "WAKE ME UP BEFORE YOU GO GO"}
{"date": "2013-06-21 17:00:03", "interpret": "P!NK FEAT. NATE RUESS", "title": "JUST GIVE ME A REASON"}
{"date": "2013-06-21 16:48:01", "interpret": "SHAKIRA", "title": "WHENEVER, WHEREVER"}
{"date": "2013-06-21 16:44:00", "interpret": "ALPHAVILLE", "title": "BIG IN JAPAN"}
{"date": "2013-06-21 16:40:01", "interpret": "XAVIER NAIDOO", "title": "BEI MEINER SEELE"}
{"date": "2013-06-21 16:36:02", "interpret": "SANTANA", "title": "SMOOTH"}
{"date": "2013-06-21 16:32:01", "interpret": "OLLY MURS", "title": "ARMY OF TWO"}

rawDescription: Scrapy start_urls too long / Unsupported URL Scheme


code:
import elementtree.ElementTree as etree
#~ import cElementTree as etree

def CDATA(text=None):
    element = etree.Element(CDATA)
    element.text = text
    return element

class ElementTreeCDATA(etree.ElementTree):
    def _write(self, file, node, encoding, namespaces):
        if node.tag is CDATA:
            text = node.text.encode(encoding)
            file.write("\n<![CDATA[%s]]>\n" % text)
        else:
            etree.ElementTree._write(self, file, node, encoding, namespaces)

if __name__ == "__main__":
    import sys

    text = """
    <?xml version='1.0' encoding='utf-8'?>
    <text>
    This is just some sample text.
    </text>
    """

    e = etree.Element("data")
    cdata = CDATA(text)
    e.append(cdata)
    et = ElementTreeCDATA(e)
    et.write(sys.stdout, "utf-8")

rawDescription: How to output CDATA using ElementTree

description: Output CDATA using ElementTree


code: [('Copper Bracelet - 3mm - Polished', 'http://store.highsnobiety.com/products/highsnobiety-x-simon-me-copper-bracelet-3mm'), ('Copper Bracelet - 5mm - Brushed', 'http://store.highsnobiety.com/products/copy-of-highsnobiety-x-simon-me-copper-bracelet-5mm'), ('Copper Bracelet - 7mm - Polished', 'http://store.highsnobiety.com/products/copy-of-copy-of-highsnobiety-x-simon-me-copper-bracelet-7mm'), ('Highsnobiety x EARLY - Leather Pouch', 'http://store.highsnobiety.com/products/highsnobiety-x-early-leather-pouch'), (u'A Bathing Ape\xae Highsnobiety 10th Anniversary Tee', 'http://store.highsnobiety.com/products/a-bathing-ape-highsnobiety-10th-anniversary-tee'), ('Highsnobiety Magazine Issue 11', 'http://store.highsnobiety.com/products/highsnobiety-magazine-issue-11'), ('A5', 'http://store.highsnobiety.com/products/anniversary-product-04'), ('A6', 'http://store.highsnobiety.com/products/a6'), ('A7', 'http://store.highsnobiety.com/products/a7'), ('A8', 'http://store.highsnobiety.com/products/a8'), ('A9', 'http://store.highsnobiety.com/products/a9'), ('A10', 'http://store.highsnobiety.com/products/a10'), ('Highsnobiety x Stampd Snapback - New York', 'http://store.highsnobiety.com/products/highsnobiety-x-stampd'), ('Highsnobiety x Stampd Snapback - Berlin', 'http://store.highsnobiety.com/products/highsnobiety-x-stampd-snapback-berlin'), ('Carhartt WIP x Highsnobiety - Hooded Sweatshirt', 'http://store.highsnobiety.com/products/carhartt-wip-x-highsnobiety-hoodie'), ('Carhartt WIP x Highsnobiety - Long-Sleeve T-Shirt', 'http://store.highsnobiety.com/products/carhartt-wip-x-highsnobiety-longsleeve'), ('Carhartt WIP x Highsnobiety - Sweat Pants', 'http://store.highsnobiety.com/products/copy-of-carhartt-wip-x-highsnobiety-pants'), ('Carhartt WIP x Highsnobiety - Beanie', 'http://store.highsnobiety.com/products/copy-of-copy-of-carhartt-wip-x-highsnobiety-beanie'), ('adidas Consortium x Highsnobiety UltraBOOST', 'http://store.highsnobiety.com/products/adidas-consortium-x-highsnobiety-ultraboost'), ('adidas Consortium x Highsnobiety Campus 80s', 'http://store.highsnobiety.com/products/adidas-consortium-x-highsnobiety-campus-80s'), ('Highsnobiety Tonal Logo Snapback - Black', 'http://store.highsnobiety.com/products/highsnobiety-logo-snapback-black'), ('Highsnobiety Tonal Logo Snapback - Navy', 'http://store.highsnobiety.com/products/highsnobiety-logo-snapback-navy'), ('Highsnobiety Tonal Logo Snapback - Red', 'http://store.highsnobiety.com/products/highsnobiety-logo-snapback-red'), ('Highsnobiety Tonal Logo Snapback - White', 'http://store.highsnobiety.com/products/highsnobiety-logo-snapback-white'), ('Highsnobiety Magazine Issue 9 - Yohji Yamamoto', 'http://store.highsnobiety.com/products/highsnobiety-magazine-issue-9-yohji-yamamoto'), ('Highsnobiety Magazine Issue 10 - Kobe Bryant', 'http://store.highsnobiety.com/products/copy-of-highsnobiety-magazine-issue-10-kobe-bryant'), ('Highsnobiety Magazine Issue 10 - Gosha Rubchinskiy', 'http://store.highsnobiety.com/products/highsnobiety-magazine-issue-10-gosha-rubchinskiy'), ('Ronnie Fieg x Highsnobiety x Puma RF-Blaze of Glory', 'http://store.highsnobiety.com/products/ronnie-fieg-x-highsnobiety-x-puma-rf-blaze-of-glory'), ('Ronnie Fieg x Highsnobiety x Puma RF698S', 'http://store.highsnobiety.com/products/copy-of-ronnie-fieg-x-highsnobiety-x-puma-rf-blaze-of-glory')]

rawDescription: Using LXML to print out individual strings from file


code:
import openpyxl
wb = openpyxl.Workbook()
sheet = wb['Sheet']
sheet['A1'] = 'Hello world!'
sheet['A1'].value

rawDescription: Writing to row using openpyxl?

description: Writing to row using openpyxl


code: globals()['given'] = step_decorator

rawDescription: How are Behave's decorators created/declared?


code: sum([y for x in vList for y in x])

rawDescription: how to convert list to number and add them up (python 2.7)

description: Convert list to number and add them up (python 2.7)


code:
def create_SubElement(_parent,_tag,attrib={},_text=None,nsmap=None,**_extra):
    result = etree.SubElement(_parent,_tag,attrib,nsmap,**_extra)
    result.text = _text
    return result

rawDescription: Python lxml Subelement with text value?

description: Python lxml Subelement with text value


rawDescription: Adding '0' to binary

description: Adding '0' to binary


code:
"""A
multiline
string
is
easy.
"""

rawDescription: String creation: Differences between two syntaxes ' ' and " "?


code:
class ImmutableDefaultArgumentsObject(ImmutableDefaultArgumentsBase):
    cache = []
    def function_a(self, mutable_default_arg=set()):
        print("function_b", mutable_default_arg, id(mutable_default_arg))
        self.cache.append(mutable_default_arg)

rawDescription: Fix mutable default arguments via metaclass


code:
def __getattr__(self, k):
    """ Defines the names of the methods to be the same as the
    keys of the dictionaries.
    """
    if k in self:
        return self[k]
    raise AttributeError(k)

def __setattr__(self, k, v):
    if k in self:
        self[k] = v
    super(Machine, self).__setattr__(k, v)

rawDescription: Extract methods of a class from the keys of a dictionary


code:
ShoeReview.objects\
          .filter(owner_review__ratings__rating_attribute__attribute='overall')\
          .order_by(owner_review__ratings__rating)

rawDescription: Help on my django models for my shoe review website


code:
class MyClass(namedtuple("MyClass", ["a", "b"])):

    def __new__(cls, a="v1", b="v2"):
        return super(MyClass, cls).__new__(cls, a, b)

rawDescription: Python: how to implement __getattr__()?

description: Python: how to implement __getattr__()


code:
from coke import *
make(data)

rawDescription: Is it possible in python to define functions outside of a programs main namespace and add them for easy access like a .h file in c?


rawDescription: python regex pattern to extract value between two characters

description: Python regex pattern to extract value between two characters


code: sheet.write(i, index, each, style)

rawDescription: convert multiple csv to xls using python with number stored as integer not text

description: Convert multiple csv to xls using python with number stored as integer not text


rawDescription: Put value at centre of bins for histogram


code:
def index():
    if auth.user:
        response.view = 'default/index_logged_in.html'
    ...
    return dict(...)

rawDescription: Load a diferent view when logged in

description: Load a diferent view when logged in


code: nt = lambda a, b: S[a].intersection(S[b])

rawDescription: Pairwise Set Intersection in Python

description: Pairwise Set Intersection in Python


code:
def einsum_code(V, F):
    n, p = V.shape
    F = F.copy()
    F[np.triu_indices(n, 1)] = 0
    return np.einsum('ij,ik,jk->k', F, V, V)

rawDescription: numpy vectorization of double python for loop

description: Numpy vectorization of double python for loop


code:
w=v.stack()
w.sort_values(inplace=True)

rawDescription: Smallest Difference Between 2 object in Dataframe


code:
from bottle import hook, response, route, run, static_file, request
import json
import socket
import sqlite3

#These lines are needed for avoiding the "Access-Control-Allow-Origin" errors
@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

#Note that the text on the route decorator is the name of the resource
# and the name of the function which answers the request could have any name
@route('/examplePage')
def exPage():
    return "
This is an example of web page

Hope you enjoy it!
"

#If you want to return a JSON you can use a common dict of Python,
# the conversion to JSON is automatically done by the framework
@route('/sampleJSON', method='GET')
def mySample():
    return { "first": "This is the first", "second": "the second one here", "third": "and finally the third one!" }

#If you have to send parameters, the right sintax is as calling the resoure
# with a kind of path, with the parameters separed with slash ( / ) and they
# MUST to be written inside the lesser/greater than signs  ( <parameter_name> )
@route('/dataQuery/<name>/<age>')
def myQuery(name,age):
    connection= sqlite3.connect("C:/folder/data.db")
    mycursor = connection.cursor()
    mycursor.execute("select * from client where name = ? and age= ?",(name, age))
    results = mycursor.fetchall()
    theQuery = []
    for tuple in results:
        theQuery.append({"name":tuple[0],"age":tuple[1]})
    return json.dumps(theQuery)

#If you want to send images in jpg format you can use this below
@route('/images/<filename:re:.*\.jpg>')
def send_image(filename):
    return static_file(filename, root="C:/folder/images", mimetype="image/jpg")

#To send a favicon to a webpage use this below
@route('/favicon.ico')
def favicon():
    return static_file('windowIcon.ico', root="C:/folder/images", mimetype="image/ico")

#And the MOST important line to set this program as a web service provider is this
run(host=socket.gethostname(), port=8000)

rawDescription: How to connect Javascript to Python sharing data with JSON format in both ways?

description: Connect Javascript to Python sharing data with JSON format in both ways


code:
disp = 0.15
for k in box1.keys():
    for line1,line2 in zip(box1[k],box2[k]):
        setp(line1,xdata=getp(line1,'xdata') - disp)
        setp(line2,xdata=getp(line2,'xdata') + disp)

rawDescription: Pandas boxplot x-axis setting

description: Pandas boxplot x-axis setting


rawDescription: How can I see the bytecode of a decorated function?

description: See the bytecode of a decorated function


code:
while True:
    print ("Welcome")
    command = input ("Enter command: ")
    if command == "register": #String variable here
        registerMe = input ("What is your name? ")
        print (registerMe) #print or do whatever you want on here
        break

rawDescription: How to link in Python

description: Link in Python


code:
[x.lower() for x in ["A","B","C"]]
[x.upper() for x in ["a","b","c"]]

rawDescription: Convert a Python list with strings all to lowercase or uppercase


code: sorted(yourdict, key=int)

rawDescription: Sorting dictionary for printing

description: Sorting dictionary for printing


code:
import numpy as np
np.dtype('long')

rawDescription: How can I create a numpy dtype from the string 'long'?

description: Create a numpy dtype from the string 'long'


code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2015-12-22 by Culebra v11.0.8
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

import unittest

from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase

TAG = 'CULEBRA'

class CulebraTests(CulebraTestCase):

    @classmethod
    def setUpClass(cls):
        cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
        cls.kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
        cls.options = {'start-activity': 'com.duolingo/.app.LoginActivity', 'concertina': False, 'device-art': None, 'use-jar': False, 'multi-device': False, 'unit-test-class': True, 'save-screenshot': None, 'use-dictionary': False, 'glare': False, 'dictionary-keys-from': 'id', 'scale': 0.5, 'find-views-with-content-description': True, 'window': -1, 'orientation-locked': None, 'save-view-screenshots': None, 'find-views-by-id': True, 'log-actions': False, 'use-regexps': False, 'null-back-end': False, 'auto-regexps': None, 'do-not-verify-screen-dump': True, 'verbose-comments': False, 'gui': True, 'find-views-with-text': True, 'prepend-to-sys-path': False, 'install-apk': None, 'drop-shadow': False, 'output': None, 'unit-test-method': None, 'interactive': False}
        cls.sleep = 5

    def setUp(self):
        super(CulebraTests, self).setUp()

    def tearDown(self):
        super(CulebraTests, self).tearDown()

    def preconditions(self):
        if not super(CulebraTests, self).preconditions():
            return False
        return True

    def testSomething(self):
        if not self.preconditions():
            self.fail('Preconditions failed')

        _s = CulebraTests.sleep
        _v = CulebraTests.verbose

        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'GET STARTED').touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'Spanish', root=self.vc.findViewByIdOrRaise('id/no_id/5')).touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'None', False, False)

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

rawDescription: Error of Script with MonkeyRunner and AndroidViewClient (Touch)


code:
for i in xrange(len(games)):
    globals()[games[i][1].__name__] = route(games[i][0])(games[i][1])

rawDescription: python defining multiple classes with decorators

description: Python defining multiple classes with decorators


code: q = np.empty(2, dtype='object')

rawDescription: Numpy.unique - getting output with consistent depth


rawDescription: Numpy Matrix Multiplication U*B*U.T Results in Non-symmetric Matrix


code: out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate()

rawDescription: Python subprocess readlines()?

description: Python subprocess readlines()


code: '%0*d' % (width, number)

rawDescription: Dynamically calculated zero padding in format string in python


code: print(merge())

rawDescription: Python - Merge Sort Recursive Algorithm

description: Python - Merge Sort Recursive Algorithm


rawDescription: Easy way to collapse trailing dimensions of numpy array?


code:
ax = gca()
ax.hold(True)

rawDescription: Re-initialize the plot in pylab

description: Re-initialize the plot in pylab


code:
from collections import defaultdict
import inspect
inspect.getmodule(defaultdict)

rawDescription: retrieve the Package.Module.Class name from a (Python) class/type

description: Retrieve the Package.Module.Class name from a (Python) class/type


rawDescription: Python - Convert String into Iterable Integer List


code:
rev = [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
min_length = min(len(x) for x in rev)  # find the min length among all items
rotated = []

rotated

rawDescription: How does this code snippet rotating a matrix work?


code:
registered_info_elements = {}
@classmethod
def register_variant(cls):
    cls.registered_info_elements[cls.type.default] = cls
@classmethod
def dispatch_hook(cls, pkt=None, *args, **kargs):
    if pkt:
        t = ord(pkt[0])
        return cls.registered_info_elements.get(t, cls)
    return cls

rawDescription: show2() method won't display sub classes

description: Show2() method won't display sub classes


code:
from collections import defaultdict
a = defaultdict((lambda : 'DNE'))

rawDescription: Python Dictionary return requested key if value does not exist


rawDescription: Creating numpy array with empty columns using genfromtxt


code:
import scipy.interpolate

interp = scipy.interpolate.Rbf(lon, lat, z, function='linear')

# 20x20 grid of points to interpolate on
yy, xx = np.mgrid[lat.min():lat.max():20j, lon.min():lon.max():20j]

zi = interp(xx, yy)

# Plot the results
fig, ax = plt.subplots()
artist = ax.scatter(lon, lat, c=z, s=100, cmap='gist_earth',
                     vmin=zi.min(), vmax=zi.max())
ax.pcolormesh(xx, yy, zi, cmap='gist_earth')
ax.axis('tight')
plt.show()

rawDescription: How do I reshape a numpy array for use with scipy interpolate?

description: Reshape a numpy array for use with scipy interpolate


code:
arr = np.vstack([xvalues, yvalues, zvalues]).T
out = arr.dot(arr.T)

rawDescription: Python, creating a large-dimensional matrix of 3-dimensional dot products


code: plt.imshow(Image2_mask, cmap='jet', alpha=0.5) # interpolation='none'

rawDescription: Overlay an image segmentation with numpy and matplotlib


code:
import dateutil.parser

ops = dict()

def update_ops(opsdict, row):

    # first get the timestamp and op name in a useable format
    timestamp = dateutil.parser.parse(row[1])
    op_name = row[2]

    ## now populate, or update the dictionary
    if op_name not in opsdict:
        # sets a new dict entry with the operation's timestamp.
        # since we don't know what the start time and end time
        # is yet, for the moment set them both.
        opsdict[op_name] = { 'start_time': timestamp,
                            'end_time': timetstamp }
    else:
        # now evaluate the current timestamp against each start_time
        # and end_time value. Update as needed.
        if opsdict[op_name]['start_time'] > timestamp:
            opsdict[op_name]['start_time'] = timestamp
        if opsdict[op_name]['end_time'] < timestamp:
            opsdict[op_name]['end_time'] = timestamp

rawDescription: Parse CSV file and modify columns

description: Parse CSV file and modify columns


code:
max_entries_shown = 10
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-s",
    nargs = '?',
    const = max_entries_shown,
    type=int)
args = parser.parse_args()

rawDescription: python argparse optional positional argument with detectable switch

description: Python argparse optional positional argument with detectable switch


rawDescription: Python List Change

description: Python List Change


code:
def func_1(t):
   x,y=t
   return (x*x) + (y*y)

def func_2(t, a):
   x,y=t
   return ((x-a)*(x-a)) + ((y-a) *(y-a))

rawDescription: Scipy fmin argument passing

description: Scipy fmin argument passing


code:
(data
    .groupby("Region")
    .agg(
        F.avg("Salary"),
        F.count(F.when(F.col("IsUnemployed"), F.col("IsUnemployed")))))

rawDescription: How to count a boolean in grouped Spark data frame

description: Count a boolean in grouped Spark data frame


code:
soFar = []
for char in secretWord:
    soFar.append('_')

rawDescription: use .replace() on only one character of a string with repetitive characters

description: Use .replace() on only one character of a string with repetitive characters


code:
from PIL import Image
im = Image.fromstring('L', (8, 8), byte_seq)
im.show()

rawDescription: string to b&w image

description: String to b&w image


code:
rules = (
    Rule(SgmlLinkExtractor(allow=r'.*'), callback='parse_items', follow=True),
)

def parse_items(self, response, sel=None):
    sel = Selector(response)
    for r in self.parse_item1(response, sel):
        yield r

    for r in self.parse_item2(response, sel):
        yield r

def parse_item1(self, response, sel=None):
    if sel is None:
        sel = Selector(response)
    i = IdeeItem()
    i['website']    =   sel.xpath("""/html/body/table/tr[1]/td[2]/div[4]/div/table/tr[4]/td/h4/text()""").extract()
    i['title']  =   sel.xpath("""/html/body/table/tr[1]/td[2]/div[4]/div/table/tr[2]/td/h4/text()""").extract()
    return i

def parse_item2(self, response, sel=None):
    if sel is None:
        sel = Selector(response)
    i = IdeeItem()
    i['website']    =   sel.xpath("""/html/body/table/tr[1]/td[2]/div[4]/div/table/tr[6]/td/h4/text()""").extract()
    i['email']  =    sel.xpath("""//html/body/table/tr[1]/td[2]/div[4]/div/table/tr[8]/td/a[1]/text()""").extract()
    return i

rawDescription: How to crawl several elements at once?

description: Crawl several elements at once


code:
for row_num in range(4):
    formula = '=IF(E%d>0,(G%d+H%d)/E%d,0)' % tuple([row_num + 1] * 4)

rawDescription: Python xlsxwriter: Adjust excel reference cells in loop when creating formula


code:
sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
[i for i, item in enumerate(sent3) if item == 'the']

rawDescription: NLTK index of a word with mulitiple occurences


code:
dirname = 'C:\\Users\\myUsers\\Videos'
os.path.basename(dirname)

rawDescription: modifying key's name in python dictionary

description: Modifying key's name in python dictionary


code:
func = "go"+x.split()[-1]+"()" #"goWest()"
exec(func)

rawDescription: Turn user input strings into a function call


rawDescription: Can you "stream" images to ffmpeg to construct a video, instead of saving them to disk?


rawDescription: Match string between special characters

description: Match string between special characters


code:
class KeyBasedDefaultDict(dict):
    def __init__(self, default_factories, *args, **kw):
        self._default_factories = default_factories
        super(KeyBasedDefaultDict, self).__init__(*args, **kw)

    def __missing__(self, key):
        factory = self._default_factories.get(key)
        if factory is None:
            raise KeyError(key)
        new_value = factory()
        self[key] = new_value
        return new_value

rawDescription: Python nested defaultdict with mix data types


code:
dfTrials["response 2"] = dfTrials["condition"] + dfTrials["no"]
dfTrials

rawDescription: Edit pandas dataframe row-by-row

description: Edit pandas dataframe row-by-row


code: "Mary has an {1} and a {0} or {1}".format(*my_array.astype('U'))

rawDescription: Numpy String Encoding

description: Numpy String Encoding


code:
df
id = df.ix[:, ['names']]
df.columns = pandas.MultiIndex.from_tuples([tuple(c.split('_')) for c in df.columns])
pandas.merge(df.stack(0).reset_index(1), id, left_index=True, right_index=True)

rawDescription: Reshaping dataframes in pandas based on column labels


code:
class MyProxy(Proxy):
    def __init__(self, obj):
        super(MyProxy, self).__init__(obj)
        self.proxy_foo = 999

    def __getattribute__(self, item):
        #print("__getattribute__({}, {})".format(self, item))
        if item == 'foo':
            return self.proxy_foo
        if item == 'do_something':
            return functools.partial(object.__getattribute__(self, '_obj').__class__.do_something, self)
        return super(MyProxy, self).__getattribute__(item)

a = A()
myproxy = MyProxy(a)

rawDescription: Proxying variables in Python

description: Proxying variables in Python


code:
import urllib2
file_checker = None
print("Please Wait...")
while True:
    try:
        req = urllib2.Request('http://www.voidspace.org.uk')
        response = urllib2.urlopen(req, timeout=20)
        print("Connected")
        with open("outfile.html", 'w+') as out_data:
            for data in response.readlines():
                file_checker = open("outfile.html")
                if data not in file_checker.readlines():
                    out_data.write(str(data))
        break
    except urllib2.URLError:
        print("Connection Error!")
        print("Connecting again...please wait")
file_checker.close()
print("done")

rawDescription: Urllib2 Python - Reconnecting and Splitting Response


code: v = data[row][col]

rawDescription: Python - best way to set a column in a 2d array to a specific value


code: a_objects = {}

rawDescription: How to create objects for a class automatically?

description: Create objects for a class automatically


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

label = ax.xaxis.get_ticklabels()[-1]
label.set_bbox(dict(facecolor='none', edgecolor='red'))

plt.show()

rawDescription: Draw box around tick label in Matplotlib


rawDescription: How to merge and convert list of tuples to Dict

description: Merge and convert list of tuples to Dict


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as cm
import matplotlib.ticker as ct

data = np.exp(np.random.rand(20, 20) * 100)

fig, ax = plt.subplots()
log_norm = cm.LogNorm()

im = ax.imshow(data, interpolation='nearest', cmap='viridis', norm=log_norm)
fig.colorbar(im, format=ct.LogFormatterExponent())

rawDescription: matplotlib LogFormatterExponent -- 'e' in the exponent labels of cbar

description: Matplotlib LogFormatterExponent -- 'e' in the exponent labels of cbar


code:
profile.run("a.count('1')")
profile.run("b = Counter(a); b['1']")

rawDescription: Fastest way to count number of occurrences in a Python list


code:
from sqlalchemy.dialects import mysql
mysql.INTEGER(unsigned=True)

rawDescription: Unsigned int for dataframe to_sql using sqlalchemy types


code:
def factor(n, _memo={1: []}):
    """returns a list of the prime factors of integer n

       n must be > 0 (otherwise, raises ValueError).

       uses a stream of primes in increasing order generated
       by `primes.generator()` (q.v.).

       do **not** pass argument _memo, it's used for memoization
       (holding the list of factors for all ints that have already
        been factorized by this function in this process's past).
    """
    # get error cases out of the way first
    if n <= 0: raise ValueError("Can't factor %r" % n)
    # localmemo records all numbers which are being factorized
    # for the first time in this specific call to `factor`, each
    # with a list of corresponding factors found so far
    localmemo = {}
    # keep a copy of the original n since in the loop below n
    # gets decreased
    orgn = n
    p = primes.generator()  # yields an infinite iterable
    # look at each prime (the .send call below may cause a prime
    # to be looked at more than once since it's assumed to work
    # as a "push back" for this specific generator)
    for x in p:
        if n in _memo:  # we've factorized n already in the past
            # (or n is 1, which is always a key in _memo!)
            # so we're all done, mop up
            # every list of factors in localmemo gets all n's factors
            for k in localmemo:
                localmemo[k].extend(_memo[n])
            # add every localmemo list to _memo for future calls
            _memo.update(localmemo)
            # now orgn is in _memo (as it was in localmemo if it had
            # not already been in _memo it's been added) so we can just
            # index to get the corresponding list of factors
            return _memo[orgn]
        # start with an empty list since we don't know n's factors yet
        localmemo[n] = []
        if n % x == 0:  # x is a factor of n, so of everything we're factoring
            n = n/x
            for k in localmemo:
                localmemo[k].append(x)  # ...so add it to every entry in localmemo
            p.send(x)  # get `x` again next time (it might be a multiple factor!)

rawDescription: Critique my prime_factors() function

description: Critique my prime_factors() function


code: foundInstances.append(['http://' + str(num) + 'endofsite' + ', ' + desc])

rawDescription: Using Python to write a CSV file with delimiter


code:
d = {x: 0 for x in elems}
for x in items:
    d[x] += 1

print(min(d, key=d.get)) # b

rawDescription: Python: Find the list element that is contained least times in another list


code:
import sys
import sip
sip.setapi('QVariant', 2)
from PyQt4.QtGui import *
from PyQt4.QtCore import *

data = {"first":{"status":"closed"},"second":{"status":"expired"},"third":{ "status":"cancelled"}}

class ComboDelegate(QItemDelegate):
    def __init__(self, view):
        QItemDelegate.__init__(self)
        self._view = view

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        li = []
        li.append("closed")
        li.append("expired")
        li.append("cancelled")
        li.append("waiting")
        editor.addItems(li)

        editor.activated.connect(lambda index, editor=editor: self._view.commitData(editor))
        editor.activated.connect(lambda index, editor=editor: self._view.closeEditor(editor,QAbstractItemDelegate.NoHint))
        QTimer.singleShot(10,editor.showPopup)

        return editor

    def setEditorData(self, editor, index):
        value = index.model().data(index, Qt.EditRole)
        editor.setCurrentIndex(editor.findText(value))

class Example(QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.tableview = QTableView()
        self.tableview.setItemDelegateForColumn(1, ComboDelegate(self.tableview))

        self.setCentralWidget(self.tableview)

        self.model = QStandardItemModel()
        self.tableview.setModel(self.model)
        self.fillModel()

        self.show()

    def fillModel(self):
        for i in data:
            name_str = i
            status_str = data[i]["status"]
            name = QStandardItem(name_str)
            status = QStandardItem(status_str)
            items = [name, status]
            self.model.appendRow(items)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

rawDescription: How to restore the index of a QComboBox delegate in a QTableView?

description: Restore the index of a QComboBox delegate in a QTableView


code:
a = getattr(proxy, "is_even")
a(5)

rawDescription: How to invoke an XML RPC method with Python when the method name is only known at runtime?

description: Invoke an XML RPC method with Python when the method name is only known at runtime


code: oldfile, newfile = args.rename

rawDescription: Python argparse: name parameters

description: Python argparse: name parameters


rawDescription: parse query string with urllib in Python 2.4

description: Parse query string with urllib in Python 2.4


code:
from itertools import chain

def calc_check(workers):
    return sum(chain.from_iterable(workers.values())) * 13

rawDescription: Looping and returning all values in a dictionary


rawDescription: Create an instance from serializer without persisting it to db


code:
pcheck = PermissionChecker()
pcheck.permissions

rawDescription: How to use self.method() in class creation time?

description: Use self.method() in class creation time


code:
@gen.coroutine
def get(self):
    """ GET request handler - need for IE8- users. Used ONLY for them
    """
    result = yield self._request_action()
    # do something with result, if you need

@gen.coroutine
def post(self):
    """ POST handling for all users, except IE8-
    """
    result = yield self._request_action()
    # do something with result, if you need

rawDescription: Encapsulating asynchronous actions in functions


code:
ix = np.array([1, 3, 5])
iy = np.array([1, 3, 5])
im[ix[:, np.newaxis], iy[np.newaxis, :]]

rawDescription: NumPy Indexing - all pairwise elements of lists of indices