code:
def get(self, block=True, timeout=None):
    # ... lots of comments
    self.not_empty.acquire()
    try:
        if not block:
            if not self._qsize():
                raise Empty
        elif timeout is None:
            while not self._qsize():
                self.not_empty.wait()
        elif timeout < 0:
            raise ValueError("'timeout' must be a non-negative number")
        else:
            endtime = _time() + timeout
            while not self._qsize():
                remaining = endtime - _time()
                if remaining <= 0.0:
                    raise Empty
                self.not_empty.wait(remaining)
        item = self._get()
        self.not_full.notify()
        return item
    finally:
        self.not_empty.release()

def _get(self):
    return self.queue.popleft()

rawDescription: How to wait until a multithread queue is not empty without wasting too much cpu cycles

description: Wait until a multithread queue is not empty without wasting too much cpu cycles


rawDescription: multiple layouts/layout transitions in a python plasmoid

description: Multiple layouts/layout transitions in a python plasmoid


rawDescription: How to convert Numpy Array to Python Dictionary with Sequential Keys?

description: Convert Numpy Array to Python Dictionary with Sequential Keys


code:
df1.join(df2, how='outer')
#or
df1.join(df2) # this works also

rawDescription: Is it possible to add several columns at once to a pandas DataFrame?


code:
import sys
import tornado
import tornado.iostream
from tornado.ioloop import IOLoop
from functools import partial

def read(stdin, data):
    print(data)
    # below lines are unnecessary they are only for testing purposes
    stdin.close()
    IOLoop.instance().stop()

if __name__ == "__main__":
    stdin = tornado.iostream.PipeIOStream(sys.stdin.fileno())
    stdin.read_until_close(callback=partial(read, stdin))
    IOLoop.instance().start()

rawDescription: How to listen for event of closed stdin in a tornado loop?

description: Listen for event of closed stdin in a tornado loop


rawDescription: Joining Subsequent List Elements - Python


rawDescription: How do I Pythonically print a list with formatting?


code: list.insert(0, 'foo')

rawDescription: Inserting a string into a list without getting split into characters


rawDescription: How to store and search list in SQLAlchemy?

description: Store and search list in SQLAlchemy


code:
import eventlet
eventlet.monkey_patch()
import module

rawDescription: Eventlets and SMTP

description: Eventlets and SMTP


code:
import re
myre = re.compile(r"\w{4,}")
myre.findall('Lorem, ipsum! dolor sit? amet...')

rawDescription: List of all words matching regular expression


code:
ed_col = ['a','a','b','c','c','a']
job_col = ['aa','bb','aa','aa','bb','cc']
pdata = pd.DataFrame({'ed':ed_col, 'job':job_col})
my_counts= pdata.groupby(['ed','job']).size().unstack().fillna(0)

rawDescription: Dividing two columns of an unstacked dataframe


code:
def __init__(self):
    self.__dict__.update(locals())

rawDescription: Python __init__ setattr on arguments?

description: Python __init__ setattr on arguments


code:
regex = re.compile(r'(.)\1+')

def replacer(match):
    return match.group(1) + str(len(match.group(0)))

regex.sub(replacer, 'aaabbkka')
#=> 'a3b2k2a'

rawDescription: Python - packing/unpacking by letters

description: Python - packing/unpacking by letters


code:
def SetHP(self, hpPercentage, curHP, maxHP):
    if not self.hpGauge.IsShow():
        self.SetSize(200 + 7*self.nameLength, 70)
        self.hpGauge.Show()
        self.UpdatePosition()
    self.hpGauge.SetPercentage(hpPercentage, 100)

    strCurHP = str(curHP)
    strMaxHP = str(maxHP)
    self.broadCastHP.SetText(HPformat(strCurHP) + " / " + HPformat(strMaxHP))

rawDescription: Python comma and divide an integer

description: Python comma and divide an integer


code:
df['duration'] = df['duration'].astype('timedelta64[s]').fillna(0)
df

rawDescription: Time series analysis in pandas

description: Time series analysis in pandas


code:
with open('data.txt') as f:
    for line in f: # can iterate over f, no need for readlines
       values = line.split(None, 1) # splits on first whitespace only
       cur.execute(query,values)

rawDescription: Python : saving variables from a text file created


rawDescription: How to get a reference of the list inside the list comprehension in Python

description: Get a reference of the list inside the list comprehension in Python


code: from itertools import chain, cycle

rawDescription: How to cycle a variable in a given range in python

description: Cycle a variable in a given range in python


code:
def svd_whiten(X):

    U, s, Vt = np.linalg.svd(X)

    # U and Vt are the singular matrices, and s contains the singular values.
    # Since the rows of both U and Vt are orthonormal vectors, then U * Vt
    # will be white
    X_white = np.dot(U, Vt)

    return X_white

rawDescription: How to whiten matrix in PCA

description: Whiten matrix in PCA


rawDescription: Extract two dates, result in seconds (pandas)


rawDescription: Selecting Subset of Pandas DataFrame

description: Selecting Subset of Pandas DataFrame


code:
from functools import update_wrapper
class class_or_instance(object):
    def __init__(self, fn):
        self.fn = fn

    def __get__(self, obj, cls):
        if obj is not None:
            f = lambda *args, **kwds: self.fn(obj, *args, **kwds)
        else:
            f = lambda *args, **kwds: self.fn(cls, *args, **kwds)
        # update the function to have the correct metadata
        update_wrapper(f, self.fn)
        return f

class A(object):
    @class_or_instance
    def func1(self,*args):
        """some docstring"""
        pass

rawDescription: Python - using decorator.py to preserve a method docstring


rawDescription: How to disable input to a Text widget but allow programatic input?

description: Disable input to a Text widget but allow programatic input


rawDescription: Average tuple of tuples

description: Average tuple of tuples


code:
import test
test.cvar.g_float = 4.5
test.getMe()

rawDescription: Wrapping C code with SWIG that uses static global variables


code: app.listen(7000, 'xxx.xxx.xxx.xxx')

rawDescription: Run tornado web app in my own computer as server


code:
import requests
from bs4 import BeautifulSoup
import re

url = "http://www.rockefeller.edu/research/areas/summary.php?id=1"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

for x in (soup.find_all(True,text=re.compile(r'comment', re.I))):
    print(x)

rawDescription: Python 3 - Can't print using the re library


code:
import collections

with open("cpu_text", "r") as f:
    lines = f.readlines()

lines = [line.strip() for line in lines]

group_id = 0
group_member_id = 0
output_dict = collections.OrderedDict()

for line in lines:
    if line.find("SYS") > -1:
        group_id += 1
    elif line.find("Tot") > -1:
        group_member_id = 0
    else:
        group_member_id += 1
        key = "{0}-{1}".format(group_id, group_member_id)
        memory = line.split()[7]
        output_dict[key] = memory

print(output_dict)

rawDescription: Parsing members of a variable length python string


rawDescription: How to save and retrive Pandas dataframes with hierarchichal indexing?

description: Save and retrive Pandas dataframes with hierarchichal indexing


code:
import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hmset('post:1', {'title':'Redis is cool!', 'author':'haye321'})

rawDescription: Complex objects with redis-py

description: Complex objects with redis-py


rawDescription: SqlAlchemy - Filtering by field defined as a ForeignKey


code:
import re

pattern1 = '\(\d{3}\)\d{3}-\d{4}'
re.findall(pattern1, "My number is (234)456-3678 and your number is (567)789-4567.")

rawDescription: pulling from file in a certain format python

description: Pulling from file in a certain format python


rawDescription: I can't decipher my list

description: I can't decipher my list


code:
from itertools import count, izip
from collections import OrderedDict, Set

class IndexOrderedSet(Set):
    """An OrderedFrozenSet-like object
       Allows constant time 'index'ing
       But doesn't allow you to remove elements"""
    def __init__(self, iterable = ()):
        self.num = count()
        self.dict = OrderedDict(izip(iterable, self.num))
    def add(self, elem):
        if elem not in self:
            self.dict[elem] = next(self.num)
    def index(self, elem):
        return self.dict[elem]
    def __contains__(self, elem):
        return elem in self.dict
    def __len__(self):
        return len(self.dict)
    def __iter__(self):
        return iter(self.dict)
    def __repr__(self):
        return 'IndexOrderedSet({})'.format(self.dict.keys())

rawDescription: Python OrderedSet with .index() method

description: Python OrderedSet with .index() method


code: column_generator = (worksheet.row_values(i)[0] for i in range(worksheet.nrows))

rawDescription: Using xlrd to get list of excel values in python


code:
from datetime import datetime
import pytz
dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
dt = pytz.timezone('Etc/GMT+8').localize(dt)
dt.isoformat()

rawDescription: Get tz offset from sting

description: Get tz offset from sting


code:
kwargs = {'fk_field__somefield':F('actual_value')}
Model.objects.filter(**kwargs)

rawDescription: How to compare 2 columns of a table through dynamic querying

description: Compare 2 columns of a table through dynamic querying


code:
class Product(models.Model):
    currencies = models.ManyToManyField('Currency', through='Pricing', blank=True, null=True)

class Currency(models.Model):
    name = models.CharField()
    sign = models.CharField()

class Pricing(models.Model):
    product = models.ForeignKey(Product)
    currency = models.ForeignKey(Currency)
    price = models.FloatField()

rawDescription: How to associate some value in model with ForeignKey?

description: Associate some value in model with ForeignKey


code:
convert('CamelCase')
convert('CamelCamelCase')
convert('Camel2Camel2Case')
convert('getHTTPResponseCode')
convert('get2HTTPResponseCode')
convert('HTTPResponseCode')
convert('HTTPResponseCodeXYZ')

rawDescription: Elegant Python function to convert CamelCase to snake_case?


code:
import csv
lst
[{k:float(d[k]) for k in d} for d in lst] #convert values to floats

rawDescription: csv row import into python array

description: Csv row import into python array


code:
numbertoletter(0)
numbertoletter(1)

rawDescription: How to search nested list grid and give lettered coordinates in Python?

description: Search nested list grid and give lettered coordinates in Python


code: l = [sum(v != 0 for v in i) for i in a]

rawDescription: Sum and length of lists of list

description: Sum and length of lists of list


code: df.loc[(cond1) & (cond2), ['column_name1', 'column_name2']]

rawDescription: extract the subset of a pandas multi index data frame

description: Extract the subset of a pandas multi index data frame


code:
environ = os.environ.copy()
environ['JAVA_HOME'] = '/usr/java/jdk1.5.0_07'
environ['PATH'] += ':/usr/java/jdk1.5.0_07/bin'
subprocess.Popen(args, env=environ)

rawDescription: Running Java Application using Popen

description: Running Java Application using Popen


code:
dfMerged['x_y_test'] = dfMerged.val_y == dfMerged.val_x
# gives you a column with a comparison of val_x, val_y.

rawDescription: Pandas difference between dataframes on column values


code:
from itertools import count
from collections import defaultdict
counters = defaultdict(lambda: count(1))
inputlist = [1, 2, 4, 3, 2, 1]
[(n, next(counters[n])) for n in inputlist]

rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


code:
nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
nums.search("0.123").group(0)
nums.search("+0.123").group(0)
nums.search("123").group(0)
nums.search("-123").group(0)
nums.search("1").group(0)

rawDescription: Regular expression to find any number in a string


code:
from pprint import pprint
dates = ['2006-03-28', '2006-04-05', '2006-04-06']
flags = ['buy', 'buy', 'sell']
tickers = ['IBM', 'MSFT', 'IBM']
amount = [1000, 1000, 500]
price = [45.00, 72.00, 53.00]
rows = zip(dates, flags, tickers, amount, price)
pprint(rows)
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('''
CREATE TABLE stocks (
    date datetime,
    action string,
    symbol string,
    quantity integer,
    price real)
''')
cursor = conn.cursor()
cursor.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', rows)
conn.commit()
for row in cursor.execute('SELECT * FROM stocks'):
    print(row)

rawDescription: How to put lists together into list holding them as 'tuples'

description: Put lists together into list holding them as 'tuples'


code:
YahooQuote = collections.namedtuple(
    'YahooQuote', 'date, open, high, low, close, volume, adj_close, ticker')

def prices(ticker):
    # make url given ticker
    ticker_list = [ticker]
    csvfile = urllib2.urlopen(url)
    return [YahooQuote._make(x + ticker_list) for x in csv.reader(csvfile)]

rawDescription: How do I add an ID attribute to each named tuple create from a CSV file?

description: Add an ID attribute to each named tuple create from a CSV file


code:
class MyClass(base):
    value = Column(JsonType())

rawDescription: one field with different data types [SQLAlchemy]

description: One field with different data types [SQLAlchemy]


code:
reparsed_dict = json.loads(json_string)
# reparsed_dict == search_doc

rawDescription: How to make a valid format JSON in python?

description: Make a valid format JSON in python


code:
import numpy as np
N = 5
x = np.arange(N**2).reshape(N, N)
upper = x[np.triu_indices(N, 0)]

rawDescription: Generating indices using np.triu_indices


code:
if not rootdir.endswith('output'):
    return # do not visit it at all
for dirpath, dirs, files in os.walk(rootdir):
    assert dirpath.endswith('output')
    dirs[:] = [d for d in dirs if d.endswith('output')] # edit inplace
    # search files
    for file in files: ...

rawDescription: Entering folder based on name in python

description: Entering folder based on name in python


code:
#build the list
outstanding_amount = []

# read file second time to display its contents with the headers
with open(FILE_NAME) as f:
    reader = csv.reader(f, delimiter=',')
    # display justified column headers
    print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
                            for i, col_header in enumerate(COL_HEADERS)))
    # display justified column data
    for columns in reader:
        if "A" in columns and int(columns[5]) < int(columns[3]):
            print(columns)
            print ("Amount_Outstanding:")
            print (int(columns[3]) - int(columns[5]))

            ###### NEW PART ######
            outstanding_amount.append(int(columns[3]) - int(columns[5]))

# Show the sum of all collected outstanding amount
print (sum(outstanding_amount))

rawDescription: Is there a way to add up integers which i have retrieved from a .txt file


code:
from collections import OrderedDict

return ''.join(OrderedDict.fromkeys(st))

rawDescription: Removing duplicates from a string in Python without using adittional buffer


code:
variable = ...
other_line = Regexp(r'^.*$')
parser = (variable | block | other_line)[:]

rawDescription: How to use Python Lepl to parse a subset of a domain specific language?

description: Use Python Lepl to parse a subset of a domain specific language


code:
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

nsample = 100
np.random.seed(7654321)

fig = plt.figure()
ax = fig.add_subplot(111)
x = stats.t.rvs(3, size=nsample)
res = stats.probplot(x, plot=plt)

ax.get_lines()[0].set_marker('p')
ax.get_lines()[0].set_markerfacecolor('r')
ax.get_lines()[0].set_markersize(12.0)

ax.get_lines()[1].set_linewidth(12.0)

plt.show()

rawDescription: Change Marker Style/Color in Python Probplot


code:
class My_List:
    """My List Implementation"""
    def __init__(self, *args):
        self.data = list(args)
        self.Length = len(args)

    def GetMean(self):
        return 1.0*sum(self.data)/len(self.data)

    def Add(self, *args):
        self.data.extend(list(args))
        self.Length += len(args)

whole_num = My_List(0,1,2,3,4,5)
# Made an **instance** of class **My_List**

rawDescription: Creating instances in python

description: Creating instances in python


code:
import dis
dis.dis(Tester.__init__)

rawDescription: Python "private" name mangling and instance vs class attributes


code: unique = model_dict.keys() ^ server_dict # viewkeys() python2

rawDescription: Python: Compare two identical dictionaries by key, value


code:
# compare all columns except first one and join result DF with the first column
cols = df1.columns
cmp = df1[['ID_NUMBER']].join(df1[cols[1:]] == df2[cols[1:]])

rawDescription: How can I compare results from two CSV files in Python with DictReader or Pandas? (Open to any other methods as well!)

description: Compare results from two CSV files in Python with DictReader or Pandas? (Open to any other methods as well!)


code:
slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"])
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split() # split once
    if any(word in slangNames for word in spl) and any(word  in riskNames for word in spl):
        print(k,v)

rawDescription: How to match words in 2 list against another string of words without sub-string matching in Python?

description: Match words in 2 list against another string of words without sub-string matching in Python


code:
#!/usr/bin/env python3

import time
import datetime as dt

start_time = dt.datetime.today().timestamp()
i = 0
while(True):
    time.sleep(0.1)
    time_diff = dt.datetime.today().timestamp() - start_time
    i += 1
    print(i / time_diff)

rawDescription: How to print iterations per second?

description: Print iterations per second


code:
from itertools import islice
import collections

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

rawDescription: Read from file: read two lines, skip two lines


code:
def baslik_handle(request, title):
   baslik, created = Baslik.objects.get_or_create(title=title)

rawDescription: Django create an object when enter its link


code:
import re
with open('stuff.txt') as f:
    s = f.read()

rawDescription: Extract section names and starting pages from a text file


rawDescription: How to change the range of the x-axis and y-axis in matlibplot?

description: Change the range of the x-axis and y-axis in matlibplot


rawDescription: Combine multiple heatmaps in matplotlib

description: Combine multiple heatmaps in matplotlib


code: map(max, izip_longest(*value_gen(d)))

rawDescription: mapping to the max a variable number of lists

description: Mapping to the max a variable number of lists


rawDescription: Finding combinations that meet a threshold relation


code: sorted_list[pos - 1][0] > sorted_list[pos][0]

rawDescription: Sort a list using selection sort

description: Sort a list using selection sort


code:
func(**{
    API.arg1: 'foo',
    API.arg2: 'bar',
    DATA.arg1: 'foo1',
})

rawDescription: Magic assign for custom parameters

description: Magic assign for custom parameters


rawDescription: How to detect object on images?

description: Detect object on images


code:
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    window1 = MyMainWindow1()
    window1.show()

    window2 = MyMainWindow2()
    window2.show()

    # connect signals to communicate between windows
    window1.someSignal.connect(window2.someSlot)
    window2.anotherSignal.connect(window1.anotherSlot)

    app.exec()

rawDescription: Communicate between two MainWindow() in Qt


code: {'the': 'decrease'}

rawDescription: How to convert text into a dictionary in Python

description: Convert text into a dictionary in Python


code:
from wand.image import Image

with Image(filename="pic.png") as img:
  # Remove alpha
  img.alpha_channel = False
  img.save(filename="pic2.png")

rawDescription: How to convert this command to a python code using Wand & ImageMagick

description: Convert this command to a python code using Wand & ImageMagick


code:
import pandas as pd
from StringIO import StringIO
from pandas.tseries.offsets import DateOffset

str = '''patient_id   visit_date
01           2014-08-10
01           2014-08-12
01           2014-08-13
02           2014-08-12
02           2014-08-15
03           2014-08-13
03           2014-08-15
03           2014-08-16
'''
df = pd.read_csv(StringIO(str), delim_whitespace=True)

df['visit_date'] = pd.to_datetime(df['visit_date'], format='%Y-%m-%d')
df = df.set_index('visit_date', drop=True)

# function to fill in the gaps for each patient
def fill_gaps(group):
    return group.asfreq(DateOffset(days=1))

filled_df = df.groupby('patient_id').apply(fill_gaps)

rawDescription: Counting the number of concurrent entities in a panel data set in pandas


code:
from collections import defaultdict
D = defaultdict(list)
data = [('item', 'category1'), ('item2', 'category1'), ('item3', 'category2')]

for item,category in data:
    D[category].append(item)
print(D)

rawDescription: queryset to dict with common fields as keys

description: Queryset to dict with common fields as keys


code:
res.sort(key=lambda x: x["datetime"])
res

rawDescription: Order a list of dictionaries in python

description: Order a list of dictionaries in python


rawDescription: Remove Outliers from dataset

description: Remove Outliers from dataset


rawDescription: Click event through another widget?

description: Click event through another widget


code:
def has_access(obj, req):
    if req.user == obj.owner:
        return True
    return False

rawDescription: Object level permissions in Django admin


code: a_string = "".join(list_of_strings)

rawDescription: Looking for a strategy for parsing a file


code:
jeb = astronaut.objects.get(name='Jebediah Kerman')
crewed_missions = jeb.missions_set.all()

rawDescription: Reference multiple foreign keys in Django Model


code:
words & keepers
# => ["words", "wormhole"]

rawDescription: Merge/Discard overlapping words

description: Merge/Discard overlapping words


rawDescription: Readable try except handling with calculations


code:
from django import forms
from django.contrib.auth import authenticate

class KeyAuthenticationForm(forms.Form):
    key = forms.CharField('Key', help_text='Enter your invite/authorization security key')
    user = None

    def clean_key(self):
        key = self.cleaned_data['key']
        self.user = authenticate(key=key)
        if not self.user:
            raise forms.ValidationError('Please, enter valid security key!')
        return key

rawDescription: Security issues with a middleware screener page


code:
def f():
   locals()['a'] = 3
   print(a)

rawDescription: Setting function variables with execfile()


code:
def gt_fast(D_get=D.get): return D_get('a', 1)

def ef_fast(D=D): return D['a'] if 'a' in D else 1

timeit.timeit(gt_fast)
timeit.timeit(ef_fast)

rawDescription: Why is an inline if/else faster than a .get() in Python?


code: unique, inverse = np.unique(a, return_inverse=True)

rawDescription: List of indices of every value

description: List of indices of every value


code:
import numpy as np

def permgrid(m, n):
    inds = np.indices((m,) * n)
    return inds.reshape(n, -1).T

rawDescription: Permutation of values on numpy array/matrix


code: all(n % i for i in xrange(3, int(math.sqrt(n)), 2))

rawDescription: What is Python's equivalent of Java's standard for-loop?


code:
class Interval(object):
    """ Representation of a closed interval from 'a' to 'b'. """
    def __init__(self, a, b):
        self.a, self.b = (a, b) if a < b else (b, a)  # make a min & b max

    def intersects(self, other):
        return self.b >= other.a and self.a <= other.b

    def __str__(self):
        return '[{0.a:>{w}}, {0.b:>{w}}]'.format(self, w=2)

testcases = ((Interval(1,  5), Interval(11, 14)),  #  xxxxx
                                                   #            xxxxx
             (Interval(1,  9), Interval( 7, 15)),  #  xxxxxxxxx
                                                   #        xxxxxxxxx
             (Interval(5,  9), Interval( 1, 15)),  #      xxxxx
                                                   #  xxxxxxxxxxxxxxx
             (Interval(0, 15), Interval( 5,  9)))  #  xxxxxxxxxxxxxxx
                                                   #      xxxxx

for I1, I2 in testcases:
    print('{} {:^7} intersect with {}'.format(
                            I1, "does" if I1.intersects(I2) else "doesn't", I2))

rawDescription: Intersect of two lines by begin and end points in python


code:
for lst in my_list:
    if 1 in lst:
       count_element_has_1 += 1
    elif lst.count(0) == len(lst):
       count_all_0 += 1

rawDescription: Add +1 to Count=0 if element in list has at least one 1 value. Python


code: functools.reduce(operator.and_, [60, 13, 12, 21])

rawDescription: Python bitwise AND on multiple numbers, faster way than iterative bitwise operator?


code:
class Link(models.Model):
    blog_post = models.ForeignKey(BlogPost)

rawDescription: How to Model a Foreign Key in a Reusable Django App?


code:
for word, drow in pairup(line.strip().lower()
                         for line in io.open(filepath, 'r')):
  print('{} {}'.format(word, drow))

rawDescription: Efficiently printing matching pairs of semordnilaps from a sorted list of words


rawDescription: pandas: apply function to DataFrame that can return multiple rows

description: Pandas: apply function to DataFrame that can return multiple rows


code:
def primesum(xs, ys):
    if len(xs) > len(ys):
        xs, ys = ys, xs
    # Now xs is the shorter list.
    xs = sorted(xs)  # don't mutate the input list
    sum_limit = xs[-1] + max(ys)  # largest possible sum
    ys = set(ys)     # make lookups fast
    count = 0
    for p in gen_primes_through(sum_limit):
        for x in xs:
            diff = p - x
            if diff < 0:
                # Since xs is sorted, all diffs at and
                # beyond this point are negative too.
                # Since ys contains no negative integers,
                # no point continuing with this p.
                break
            if diff in ys:
                #print("%s + %s = prime %s" % (x, diff, p))
                count += 1
    return count

rawDescription: Python 2 lists of positive integers finding prime number


code:
from __future__ import print_function

suits = {'C': 'Clubs', 'D': 'Diamonds', 'H': 'Hearts', 'S': 'Spades'}
ranks = {'J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}

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

def is_flush(hand):
    #Get suits
    suit_list = zip(*hand)[1]
    #Test if all the cards match the suit of the first card
    suit = suit_list[0]
    return suit if all(s == suit for s in suit_list) else None

#Test
userCards = ['AC', 'KD', '4C', '4S', '7H']
flushCards = '3D 5D AD QD 7D'.split()
hands = (userCards, flushCards)

for hand in hands:
    show_hand(hand)
    suit = is_flush(hand)
    if suit is None:
        print('Not a flush')
    else:
        print('Flush in %s' % suits[suit])
    print()

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

description: Print user friendly poker hand in python


code: ['red', 'orange', 'yellow']

rawDescription: dict of internal keys

description: Dict of internal keys


code: return tuple(None if i else value for i in xrange(tuple_length))

rawDescription: Is there a more lightweight way to get a tuple of variable length?


rawDescription: In PyQt, image won't show after override mousePressEvent of QGraphicsView


code:
from mayavi import mlab
from numpy import array, cos, sin, cos

x_coord = array([0.0, 1.0, 0.0, -1.0])
y_coord = array([1.0, 0.0, -1.0, 0.0])
z_coord = array([0.2, -0.2, 0.2, -0.2])

plt = mlab.points3d(x_coord, y_coord, z_coord)

msplt = plt.mlab_source
@mlab.animate(delay=100)
def anim():
    angle = 0.0
    while True:
        x_coord = array([sin(angle), cos(angle), -sin(angle), -cos(angle)])
        y_coord = array([cos(angle), -sin(angle), -cos(angle), sin(angle)])
        msplt.set(x=x_coord, y=y_coord)
        yield
        angle += 0.1

anim()
mlab.show()

rawDescription: mayavi points3d plot animation won't update the next frame

description: Mayavi points3d plot animation won't update the next frame


code:
class SetAttrMeta(type):
    def __setattr__(cls, name, value):
        print("Hey, you can't set {0} to {1}!".format(name, value))

class C(metaclass=SetAttrMeta):
    pass

rawDescription: Is it possible to override __setattr__ for a class?


code:
import timeit

def sumPair(theList, n):
    for index, e in enumerate(theList):
        if n - e in theList[index+1:]:
            return e, n - e

def sumPair2(theList, n):
    for ind, e in enumerate(theList):
        try:
            theList.index(n - e, ind + 1)
            return e, n - e
        except ValueError:
            pass

def sumPair_gnibbler(theList, n):
    # If n is even, check whether n/2 occurs twice or more in theList
    if n%2 == 0 and theList.count(n/2) > 1:
        return n/2, n/2

    theSet = set(theList)
    for e in theSet:
        if n - e in theSet:
            return e, n - e

rawDescription: One loop? python

description: One loop? python


code:
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
gca().yaxis.set_major_formatter(y_formatter)

rawDescription: Force pyplot to show actual axis values

description: Force pyplot to show actual axis values


rawDescription: Is there a scala/java equivalent of Python 3's collections.Counter


rawDescription: Combine array along axis

description: Combine array along axis


rawDescription: Python Conditional XML Writing

description: Python Conditional XML Writing


code:
links = browser.find_elements_by_class_name('searchTitle')
for i in range(len(links)):
    links = browser.find_elements_by_class_name('searchTitle')
    link = links[i]  # specify the i'th link on the page
    link.click()
    print("clicked!")
    browser.back()

rawDescription: Selenium + Python: StaleElementReferenceException (selecting by class)


code:
def get_changes_between_objects(object1, object2, excludes=[]):
    """
    Finds the changes between the common fields on two objects

    :param object1: The first object
    :param object2: The second object
    :param excludes: A list of field names to exclude
    """
    changes = {}

    # For every field in the model
    for field in object1._meta.fields:
        # Don't process excluded fields or automatically updating fields
        if not field.name in excludes and not isinstance(field, fields.AutoField):
            # If the field isn't a related field (i.e. a foreign key)..
            if not isinstance(field, fields.related.RelatedField):
                old_val = field.value_from_object(object1)
                new_val = field.value_from_object(object2)
                # If the old value doesn't equal the new value, and they're
                # not both equivalent to null (i.e. None and "")
                if old_val != new_val and not(not old_val and not new_val):
                    changes[field.verbose_name] = (old_val, new_val)

            # If the field is a related field..
            elif isinstance(field, fields.related.RelatedField):
                if field.value_from_object(object1) != field.value_from_object(object2):
                    old_pk = field.value_from_object(object1)
                    try:
                        old_val = field.related.parent_model.objects.get(pk=old_pk)
                    except field.related.parent_model.DoesNotExist:
                        old_val = None

                    new_pk = field.value_from_object(object2)
                    try:
                        new_val = field.related.parent_model.objects.get(pk=new_pk)
                    except field.related.parent_model.DoesNotExist:
                        new_val = None

                    changes[field.verbose_name] = (old_val, new_val)

    return changes

rawDescription: Compare old and updated fields in Django model


code:
variable.attribute
tcp_found.ACK

rawDescription: Identify ACK packets from wget in Mininet


rawDescription: List to Dictionary

description: List to Dictionary


rawDescription: Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset


code: location = max(map(line.find, ("FC", "FL")))

rawDescription: How to find the index of multiple sub string in a string by python?

description: Find the index of multiple sub string in a string by python


code:
names = list()
for line in data2[0:]:
    a = line.split("|")
    names.append(a)
print(names)

rawDescription: How to create a list of sublists where the sublists are split strings?

description: Create a list of sublists where the sublists are split strings


code:
df = data[data.columns[data.columns.str.startwith('durations') | data.columns.str.startwith('so')]]
df.fillna(0)

rawDescription: How to select all columns that start with "durations" or "shape"?

description: Select all columns that start with "durations" or "shape"


rawDescription: How can I add two functions together in Python 3?

description: Add two functions together in Python 3


code: {{purchase.customer.ppid | default_xml_tag:"PayPalID" }}

rawDescription: Is there an elegant way to apply {% if .. %} to a whole load of tags in Django?


code:
from __future__ import division, print_function

import numpy

# points in time series
n= 101
# final time (initial time is 0)
tfin= 10

# *end of changeable parameters*

# stepsize
dt= tfin/(n-1)
# sample count
s= numpy.arange(n)
# signal; somewhat arbitrary
y= numpy.sinc(dt*s)
# DFT
fy= numpy.fft.fft(y)
# frequency spectrum in rad/sample
wps= numpy.linspace(0,2*numpy.pi,n+1)[:-1]

# basis for DFT
# see, e.g., http://en.wikipedia.org/wiki/Discrete_Fourier_transform#equation_Eq.2
# and section "Properties -> Orthogonality"; the columns of 'basis' are the u_k vectors
# described there
basis= 1.0/n*numpy.exp(1.0j * wps * s[:,numpy.newaxis])

# reconstruct signal from DFT coeffs and basis
recon_y= numpy.dot(basis,fy)

# expect yerr to be "small"
yerr= numpy.max(numpy.abs(y-recon_y))
print('yerr:',yerr)

# find coefficients by fitting to basis
lin_fy= numpy.linalg.solve(basis,y)

# fyerr should also be "small"
fyerr= numpy.max(numpy.abs(fy-lin_fy))
print('fyerr',fyerr)

rawDescription: FFT vs least squares fitting of fourier components?


code:
# main.py

if __name__ == '__main__':
    from package1.module1 import SomeClass
    SomeClass().start()

rawDescription: Import paths - the right way?

description: Import paths - the right way


rawDescription: How to parse code (in Python)?

description: Parse code (in Python)


code: int(text_widget.index('end-1c').split('.')[0])  # returns line count

rawDescription: Getting the total number of lines in a Tkinter Text widget?


code:
main_thread_id = win32api.GetCurrentThreadId()
event_handling = True

def disable_event_handling():   # Puts a stop to the loop that checks for events
    global event_handling
    event_handling = False
    win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0)  # Sends a QUIT message to win32gui.PumpMessages(), without this it wouldn't stop checking for messages to pump
    return event_handling

rawDescription: Python - Constantly running an event handler without wxPython?


code:
blocks = np.array(blocks)
blocks.shape

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


rawDescription: Executing code on startup in Django 1.7

description: Executing code on startup in Django 1.7


rawDescription: get previous value of pandas datetime index

description: Get previous value of pandas datetime index


code: s._set_facecolors, s._set_edgecolors = s.set_facecolors, s.set_edgecolors

rawDescription: Controlling alpha value on 3D scatter plot using Python and matplotlib


code:
from collections import  OrderedDict

print(list(OrderedDict((sub[0], sub) for sub in sorted(zip(a, b, c))).values()))
[(1, 4, 3), (3, 7, 3), (7, 4, 1)]

rawDescription: How to turn 3 lists into an ordered dictionary

description: Turn 3 lists into an ordered dictionary


code: df['dataDiv'] = df['data'] / df.groupby((df['T'] == 0).cumsum())['data'].transform('first')

rawDescription: How to normalize values in a dataframe column in different ranges

description: Normalize values in a dataframe column in different ranges


rawDescription: Creating numpy array with different steps


code:
def connect_callbacks(obj):
    for _, f in inspect.getmembers(obj, inspect.ismethod):
        try:
            marks = f.__func__._marks
        except AttributeError:
            continue
        for widget, signal in marks:
            widget.connect(signal, f)

rawDescription: How to get a reference to an instance method from a decorator

description: Get a reference to an instance method from a decorator


rawDescription: Reduce Two Pandas Series to a Single One


code:
x.a
x.b

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


code:
import numexpr as ne

x1 = x0 + np.rint(ne.evaluate("cos(dirrad) * length")).astype(np.int32)
y1 = y0 + np.rint(ne.evaluate("sin(dirrad) * length")).astype(np.int32)

rawDescription: Time-efficient way for creation of many random stick coordinates with numpy


code:
__getitem__
__reversed__
index
count

rawDescription: Is any Python type whose objects contain elements that are numbered called a sequence type?


rawDescription: NumPy dtype issues in genfromtxt(), reads string in as bytestring


code:
dictionary = {}
for list in list_of_lists:
    dictionary[list[0]] = list[1:]

rawDescription: pulling min and max values from list of list

description: Pulling min and max values from list of list


code: func = lambda x: reversed(x.split())

rawDescription: Reverse an input using tuples Python

description: Reverse an input using tuples Python


code: np.concatenate([np.linspace(0, 2, 60), np.linspace(2, 10, 40)])

rawDescription: Stretched sections in plotting

description: Stretched sections in plotting


rawDescription: What does this piece of python indexing code do


code:
import pandas as pd
import numpy as np

N = 10000
df = pd.DataFrame(np.random.randint(0, 5, size=(N, 4)), columns=["c1", "c2", "c3", "c4"])
df["c5"] = np.random.randn(N)

def replace(group):
    mean, std = group.mean(), group.std()
    inliers = (group - mean).abs() <= 2*std
    return group.where(inliers, mean)

def drop(group):
    mean, std = group.mean(), group.std()
    inliers = (group - mean).abs() <= 2*std
    return inliers

g = df.groupby(['c1','c2','c3','c4'])

s1 = g.c5.transform(replace)
res1 = s1.groupby(g.grouper).agg([np.mean, np.std, len])

mask = g.c5.apply(drop)
res2 = df[mask].groupby(['c1','c2','c3','c4']).c5.agg([np.mean, np.std, len])

rawDescription: Remove outliers before aggregate in Python Pandas


rawDescription: Brackets in the statement. How does it work?


code:
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X

rawDescription: numpy 2D array assignment with 2D value and indices arrays

description: Numpy 2D array assignment with 2D value and indices arrays


rawDescription: How to split a line of code into multiple lines?

description: Split a line of code into multiple lines


code:
for element in selector.xpath('//element'):
    attributes = []
    # loop over all attribute nodes of the element
    for index, attribute in enumerate(element.xpath('@*'), start=1):
        # use XPath's name() string function on each attribute,
        # using their position
        attribute_name = element.xpath('name(@*[%d])' % index).extract_first()
        # Scrapy's extract() on an attribute returns its value
        attributes.append((attribute_name, attribute.extract()))

attributes # list of (attribute name, attribute value) tuples
dict(attributes)

rawDescription: Getting name of attributes with Scrapy XPATH


code:
def compose1(*funcs):
    @wraps(funcs[0])
    def composed(arg):
        for func in reversed(funcs):
            arg = func(arg)
        return arg
    return composed

get_page_list = compose1(make_list, cleanup, get_text, get_page)

rawDescription: cleaning up nested function calls

description: Cleaning up nested function calls


rawDescription: Python round up integer to next hundred

description: Python round up integer to next hundred


rawDescription: Automatically call all functions matching a certain pattern in python


code: para = ['1','2',str(error_list)]

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

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


code:
with open("C:/Users/JawshBawx/Documents/LiClipse Workspace/RPScLSp/RPScLSp_Src/Stats.txt", "r") as f:
    lines = f.readlines()
    wins = int(lines[0].strip())
    draws = int(lines[1].strip())
    losses = int(lines[2].strip())

if result == 0:
    print("Draw!")
    draws += 1

elif result in [1, 2]:
    print(ai_var+" Wins!")
    losses += 1

else:
    print(user_var+" Wins!")
    wins += 1

with open("C:/Users/JawshBawx/Documents/LiClipse Workspace/RPScLSp/RPScLSp_Src/Stats.txt","w") as f:
    f.write(str(wins)+'\n')
    f.write(str(draws)+'\n')
    f.write(str(losses)+'\n')

rawDescription: Convert integer within a list into a string to be written to a text file and later retrieved


code:
import csv

with open('123.csv', 'r') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    header = next(csv_input)
    first_row = next(csv_input)

    csv_output.writerow(header)
    csv_output.writerow(first_row)

    for row in csv_input:
        if row[0] == first_row[0]:
            if row[1] == first_row[1] or row[7] == '0':
                csv_output.writerow(row)

rawDescription: How to search for the common records of one csv file to another csv file without using for loop

description: Search for the common records of one csv file to another csv file without using for loop


code:
def addNode(a,k,newNode):
    if k in a:
        a[k][newNode]
    else:
        for x in a:
            addNode(a[x],k,newNode)

rawDescription: Python recursive tree issues (adding elements or arbitrary nodes)


code:
idx = df.groupby('id').cumcount()
idx

rawDescription: How to generate the unique id from a list of ids containing duplicates

description: Generate the unique id from a list of ids containing duplicates


code:
def enum(*sequential, **named):
    """ Contruct an enum """
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.items())
    key_names = enums.keys()
    enums['reverse_mapping'] = reverse
    @classmethod
    def keys(klass):
       return key_names
    enums['keys'] = keys
    return type('Enum', (), enums)

rawDescription: python built-in function type, how to define a member function for the new type?

description: Python built-in function type, how to define a member function for the new type


code:
def bin(x):
    if x==0:
        return '0'
    else:
        return (bin(x/2)+str(x%2)).lstrip('0') or '0'

rawDescription: Python 2.5 convert string to binary

description: Python 2.5 convert string to binary


code: point = np.argwhere(vor.point_region == region)

rawDescription: voronoi and lloyd relaxation using python/scipy

description: Voronoi and lloyd relaxation using python/scipy


code: h.map(lambda x: 7 if x > 3046 else 10)

rawDescription: How do I get each answer for each row with this conditional

description: Get each answer for each row with this conditional


code:
import time

def password():
    pw = input("Enter Password: ")
    if pw == initial_pw:
        print("Initializing....")
        time.sleep(0.5)
    else:
        print("Access Denied! Wrong Password!")
        password()

def Setting():
     pw = input("Enter Old Password: ")
     if pw == initial_pw:
         new_pw = input("Enter New Password: ")
         print (new_pw)
         print ("Password has been changed.")
     else:
         print ("Sorry, you have just entered an invalid password.")
         Setting()
     try:
         return new_pw
     except UnboundLocalError:
         return pw

initial_pw = input("Create New Password: ")
print("Create Successful.")
while True:
    password()

    print("Press 1 to change password")
    choice = int(input("Please choose an option: "))
    if choice == 1:
        initial_pw = Setting()

rawDescription: How to change or overwrite input password

description: Change or overwrite input password


code:
def __before__(self, action, pageid=None):
    page_q = meta.Session.query(model.Page)
    c.page = pageid and page_q.filter_by(id=int(pageid)).first() or None
    if c.page is None:
        abort(404)

rawDescription: Pylons paginator question

description: Pylons paginator question


code:
for table, values in zip(TableNameList, my_arr):
    c.execute("INSERT INTO %s VALUES (?, ?, ?)"%table, values)

rawDescription: python sqlite3 executemany using multiple lists

description: Python sqlite3 executemany using multiple lists


code:
files_to_show = {os.path.basename(name):name
                      for name in FULL_PATHS_SOURCE}

rawDescription: Attach data element to tkinter Listbox element


code:
def mean_mod(a, b, md=40):
    return md * ( ((a+b)//2) // md )

print(mean_mod(0, 600))
print(mean_mod(0, 300))

rawDescription: How can obtain middle number with grid/step in Python


code:
import random

def random_derangement(n):
    while True:
        v = range(n)
        for j in range(n - 1, -1, -1):
            p = random.randint(0, j)
            if v[p] == j:
                break
            else:
                v[j], v[p] = v[p], v[j]
        else:
            if v[0] != 0:
                return tuple(v)

rawDescription: Generate a random derangement of a list

description: Generate a random derangement of a list


code: for i in range(len(p)): b[i] = m[i,:n,:n].dot(p[i]-m[i,n,:])

rawDescription: Interpolation with Delaunay Triangulation (n-dim)


code:
result = []
for values in my_dict.values():
    for v in values:
        last_num = v[2]
        result.append(last_num)

rawDescription: Getting a list of values from dictionary when values are tuples within lists?


code:
def findbetween(pattern, input):
    out = []
    start = 0
    for m in re.finditer(pattern, input):
        out.append(input[start:m.start()])
        start = m.end()
    return out

rawDescription: Python-Getting contents between current and next occurrence of pattern in a string


rawDescription: Django .id usage in url function

description: Django .id usage in url function


rawDescription: Sorting a list of tuples with 3 elements in python


rawDescription: How to call IronPython function from C#/F#?

description: Call IronPython function from C#/F#


rawDescription: How to plot two columns of a pandas data frame using points?

description: Plot two columns of a pandas data frame using points


code: plt.rcParams["figure.figsize"] = (8, 10)

rawDescription: How to adjust the distance between y-axis label in python

description: Adjust the distance between y-axis label in python


rawDescription: A more optimized code in recursion exercise


code: versions_for_model = d['A'].keys()

rawDescription: Dictionary with named values?

description: Dictionary with named values


code: arr=[[0 for x in xrange(n)] for x in xrange(n)]

rawDescription: filling a n*n matrix with n elements

description: Filling a n*n matrix with n elements


rawDescription: Append items from Y list to one specific list from X list Python


rawDescription: Conditional maths operation on 2D numpy array checking on one dimension and doing different operations on diff dimensions


rawDescription: How to draw vertical lines on a given plot in matplotlib?

description: Draw vertical lines on a given plot in matplotlib


code:
import a

print (a.var1)
print (a.var2)

rawDescription: Referencing a variable inside another module/.py file


code:
# define a generator for converting string and cutting off it
def alph_to_num(phone):
    for index in range(len(phone)):
        if index >= 7:
            return

        if index == 4:
            yield '-'

        p = phone[index]

        if p in alph_num_dict:
            yield alph_num_dict[p]
        else:
            yield p

rawDescription: Python 2.7 Convert Letters to Phone Numbers


code:
class MyAdminSite(AdminSite):
    # Text to put at the end of each page's <title>.
    site_title = ugettext_lazy('Test panel title')
    # My custom variable
    import datetime
    srv_time = "%s" % datetime.datetime.now()

    def __init__(self, *args, **kwargs):
        super(MyAdminSite, self).__init__(*args, **kwargs)
        self.srv_time = "%s" % datetime.datetime.now()

    def each_context(self):
        """
        Overriden dictionary of variables returned for
        *every* page in the admin site.
        """
        return {
            'site_title': self.site_title,
            'site_header': self.site_header,
            'srv_time': self.srv_time,
        }

rawDescription: Django: Admin template shows old values after page refresh


code:
img_bgr = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
print(img_bgr.shape)

rawDescription: Convert a 2D numpy array into a 3d numpy array representing a grayscaled image


code:
x = arr.__getitem__((slice(4, 6), slice(9, 10), slice(None, None, -1)))
x.__setitem__(0, 100)

rawDescription: Use Numpy Multidimensional Array Slicing Without Using the [slice,slice] Syntax?


code:
from itertools import chain
list(chain(*[[[y[0],z] for z in y[1].split('. ')] for y in x]))

rawDescription: Convert list into sub-list while maintaining "key"


code:
import csv

set1 = set()
for record in csv.reader(open('foo.csv', 'rb')):
    user, machine_id, ip_address, mac_address = record
    set1.add(mac_address)
    # or simply "set1.add(record[3])", if you don't need the other fields.

rawDescription: Script to compare a string in two different files


rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


code:
def filterRow(row):
    while row[-1] == "":
        row.pop()

rawDescription: How to remove leftmost/rightmost elements in list that satisfy a certain criterion in python?

description: Remove leftmost/rightmost elements in list that satisfy a certain criterion in python


code:
from django.db import models
from django_extensions.db.fields import AutoSlugField
from categories.models import CategoryBase

class MusicCategory(CategoryBase):
    # add extra fields, like images, "featured" and such here
    pass

class Artist(CategoryBase):
    name       = CharField(max_length=255,)
    categories = models.ManyToManyField(MusicCategory, related_name="artists")

    def __unicode__(self):
        return self.name

class Song(models.Model):
    slug        = AutoSlugField(populate_from='title', unique=True)
    title       = models.CharField(max_length=255,)
    artist      = models.ForeignKey(Artist, related_name="songs", on_delete=models.PROTECT)
    categories  = models.ManyToManyField(MusicCategory, related_name="songs")
    description = models.TextField()

    def __unicode__(self):
        return self.title

rawDescription: django categories: How to get children of a category using django-categories?

description: Django categories: How to get children of a category using django-categories


code:
remove_from_start = ["http://", "https://", "ftp://"]
for s in remove_from_start:
    if site.startswith(s):
        site = site[len(s):]
        break

rawDescription: Using replace() function to replace multiple texts(strings) at once in Python


rawDescription: How to append columns based on other column values to pandas dataframe

description: Append columns based on other column values to pandas dataframe


code:
import lxml.etree
data='''\
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
'''
doc = lxml.etree.XML(data)
e=doc.find('node2/[@a1="x2"]')
doc.remove(e)
print(lxml.etree.tostring(doc))

# <node1>
#   <node2 a1="x1"> ... </node2>
#   <node2 a1="x1"> ... </node2>
# </node1>

rawDescription: xml filtering with python

description: Xml filtering with python


rawDescription: Turn NumPy Array of characters into a string


code:
def sort_day_week_key(day_week_str):
    return int(day_week_str.split()[-1])

rawDescription: Sorting Numericly and by Month name

description: Sorting Numericly and by Month name


code:
import os
for curfile in files:
    with open(curfile) as infile:
        with open("temp_file", 'w') as outfile:
            content = infile.read()
            processed_content = processContent(content)
            outfile.write(processed_content)
    os.remove(curfile) # For windows only
    os.rename("temp_file", curfile)

rawDescription: Reading and writing to files in the same iteration


code:
class class_c (object):
 def __init__(self, parent=None):
   self.parent=parent

 def close_call (self):
      from main import MainWindow
      self.parent.close_ok()# NOTICE THIS CHANGE, parent is now the original MainWindow

rawDescription: The Code does not work successfully when the function is called


code:
import textwrap

print("\n".join(textwrap.wrap("This is my sooo long title", 10)))

rawDescription: Split a string at a natural break

description: Split a string at a natural break


code:
from django import forms
from django.forms import widgets,Form, CharField, MultiValueField, ChoiceField, DecimalField

imperial = "imp"
imperial_display = "Miles"
metric = "met"
metric_display  = "Kilometers"
unit_types = ((imperial, imperial_display), (metric, metric_display))

#You would use that library instead of this, and maybe not floats
def to_imperial(val):
    return float(val) * 1.60934

def to_metric(val):
    return float(val) / 0.62137

class NumberUnitWidget(widgets.MultiWidget):
    def __init__(self, default_unit=None, attrs=None):
        #I feel like this default_unit thing I'm doing is ugly
        #but I couldn't think of another way to get the decompress
        #to know which unit to convert to
        self.default_unit = default_unit

        _widgets = [
            widgets.NumberInput(attrs=attrs),
            widgets.Select(attrs=attrs, choices=unit_types),
        ]
        super(NumberUnitWidget, self).__init__(_widgets, attrs)

    #convert a single value to list for the form
    def decompress(self, value):
        if value:
            if self.default_unit == imperial:
                return [to_imperial(value), self.default_unit]

            #value is the correct format
            return [value, self.default_unit]
        return [0, self.default_unit]

class NumberUnitField(MultiValueField):

    def __init__(self, *args, **kwargs):
        _widget = NumberUnitWidget(default_unit=kwargs['initial'][0])
        fields = [
            DecimalField(label="Number!"),
            ChoiceField(choices=unit_types)
        ]
        super(NumberUnitField, self).__init__(fields=fields, widget = _widget, *args, **kwargs)

    def compress(self, values):
        if values[1] == imperial:
            #They inputed using imperial, convert to kilo
            return  to_metric(values[0])
        return values[0] #You dont need to convert because its in the format you want

class TestForm(Form):
    name = CharField()
    num = NumberUnitField(initial=[None, metric])

rawDescription: Concept of different systems of measurement in Django project


code:
grades = '50 20 1 55 90'
grades.split()
[int(i) for i in grades.split()]

rawDescription: How do I convert strings of digits into lists of digits with proper spacing?

description: Convert strings of digits into lists of digits with proper spacing


code:
import numpy as np
import cv2
sobel5x = cv2.getDerivKernels(1, 0, 5)
np.outer(sobel5x[0], sobel5x[1])
sobel5y = cv2.getDerivKernels(0, 1, 5)
np.outer(sobel5y[0], sobel5y[1])
sobel7x = cv2.getDerivKernels(1, 0, 7)
np.outer(sobel7x[0], sobel7x[1])
sobel7y = cv2.getDerivKernels(0, 1, 7)
np.outer(sobel7y[0], sobel7y[1])

rawDescription: What are the kernel coefficients for OpenCV's Sobel filter for sizes larger than 3 x 3?


code: jsonCallback({"date": "2014-02-20 10:49:47", "reaction": "None", "name": "Dilantin"})

rawDescription: AJAX JSONP Failure returns statustext "success", correct callback


code:
view = webkit.WebView()
settings = view.get_settings()
settings.set_property('enable-file-access-from-file-uris', 1)
view.open('file://./foo.html')

rawDescription: python webkitgtk xmlhttprequest file protocol

description: Python webkitgtk xmlhttprequest file protocol


rawDescription: Dictionary __gt__ and __lt__ implementation


code:
binMin = floor(low_cut / 22050.0 * 128)
binMax = ceil(high_cut / 22050.0 * 128)
which = fftData[binMin:binMax].argmax() + 1

rawDescription: FFT Filter on Complex Numbers in Python

description: FFT Filter on Complex Numbers in Python


code:
x= [[1,2],[4,5]]
y=x[:]   #it makes a shallow copy,i.e if the objects inside it are mutable then it just copies their reference to the y
y is x
y[0].append(99)
x
y
y[0] is x[0]

rawDescription: Copying arrays in python and manipulating one


code:
from collections import Counter
from html.parser import HTMLParser

ru_abc = set('абвгдеёжзийклмнопрстуфхцчшщъыьэюя')
parser = HTMLParser()
stat_data = {'other': Counter(), 'russian': Counter()}

with open(filename) as fileobj:
    for line in fileobj:
        line = parser.unescape(line)
        stat_data['russian'].update(c for c in line if c in ru_abc)
        stat_data['other'].update(c for c in line if c not in ru_abc)

rawDescription: How to decode 'xmlcharrefreplace' ascii to UTF-8 in python3?

description: Decode 'xmlcharrefreplace' ascii to UTF-8 in python3


rawDescription: Different result with vectorized code to standard loop in numpy


code:
for i in range(3):
    sys.stdout.write('')

rawDescription: Output from sys.stdout in interactive mode


code: from string import ascii_lowercase as al

rawDescription: How to create a dict with letters as keys in a concise way?

description: Create a dict with letters as keys in a concise way


code:
import StringIO
datastream = StringIO.StringIO()
datastream.write(data)
datastream.seek(0)
#create dropbox client
client.put_file('/test', datastream)

rawDescription: python: download file and send it to online storage in realtime

description: Python: download file and send it to online storage in realtime


code:
items = []
for list in lists:
    if list.select('.[h1[text()] and h2[text()] and h3[text()]]'):
        item = TypeItem()
        item['thing1'] = list.select('h1/text()').extract()
        item['thing2'] = list.select('h2/text()').extract()
        item['thing3'] = list.select('h3/text()').extract()
        items.append(item)
return(items)

rawDescription: Scrapy - how to prevent output lines with blank element?


code: {'Peripheral Temp': 30.0, 'System Temp': 23.0, 'CPU Temp': 26.0, 'PCH Temp': 42.0}

rawDescription: How do I parse a multiline string into a python dict?

description: Parse a multiline string into a python dict


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import resources

pixmap = QPixamp(":/newPrefix/download.jpeg")

rawDescription: Importing resource file to PyQt code?

description: Importing resource file to PyQt code


code:
def solve(x, y, mazeList=None):
    if mazeList is None:
        mazeList = loadMaze("sample.maze")

rawDescription: Runtime Error in python: "Maximum recursion depth exceeded"


code:
import psycopg2
import pandas as pd
from pandas.io.sql import frame_query

conn_string = "host='localhost' dbname='mydb' user='postgres' password='password'"
conn = psycopg2.connect(conn_string)
df = frame_query('select * from cities', con=conn)

rawDescription: Make pivot tables in sql like in spss

description: Make pivot tables in sql like in spss


code:
z = np.arange(-6.28, 6.28, 0.1)
plt.plot(z, np.sin(z))
plt.show()

rawDescription: Python maplotlib sine curve with random.randn


code:
import numpy as np
from scipy import sparse

X = sparse.lil_matrix((100,100)) # some sparse matrix
X[1,17] = 1
X[17,17] = 1
indices = np.nonzero(X) # a tuple of two arrays: 0th is row indices, 1st is cols
X.tocsc()[indices] # this just gives you the array of all non-zero entries

rawDescription: How to efficiently remove columns from a sparse matrix that only contain zeros?

description: Efficiently remove columns from a sparse matrix that only contain zeros


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


code:
class ProcessWrapper(object):
    def __init__(self, process):
        self._process_pid = process.pid()

    def processPid(self):
        return self._process_pid

rawDescription: Common practice of __new__ constructor?

description: Common practice of __new__ constructor


code:
def _match( v1, v2 ):
    """
        The number of identical elements in v1 and v2 where v1 and v2 are lists.
    """

    res = len(list((Counter(v1) & Counter(v2)).elements()))
    return res

def _mind( vectors, vi, i ):
    "Calculate value of position i for vector vi in vectors."
    def pos(i):
        return 0 <= i < len( vectors )

    if isinstance(vi, int):
        if pos(vi):
            v = vectors[vi][ 1 ]
        else:
            return 0
    else:
        v = vi

    if pos(i):
        return _match( vectors[ i ][ 1 ], v )
    else:
        return 0

def _near_vectors2(vectors):
    i = 0
    for v in vectors:
        max_val = 0
        new_pos = None
        for k in range(len(vectors)):
            if k != i:
                v = vectors[ i ][ 1 ] # current vector

                # Calc. sum of links, move if links are improved
                next_k = k + 1 if i < k else k - 1
                cur_mind = _mind(vectors, v, k) + _mind(vectors, v, next_k) - _mind(vectors, k, next_k) - _mind(vectors, v, i + 1 ) - _mind(vectors, v, i - 1 ) + _mind(vectors, i - 1, i + 1)

                if cur_mind > max_val:
                    max_val = cur_mind
                    new_pos = k

        # move element
        if new_pos is not None:
            vectors.insert( new_pos, vectors.pop( i ) )

        i += 1

    return vectors

rawDescription: How to pull together vectors with common components in a list?

description: Pull together vectors with common components in a list


code:
for line in someRangeOfLines:
    for col in someRangeOfCols:
        try:
            cell= FooVal.objects().get( col = col, line = line )
        except FooVal.DoesNotExist:
            cell= None

rawDescription: outer join modelisation in django

description: Outer join modelisation in django


code:
if self.index <= other.index:
    return True
return False

rawDescription: Simpler way to do python operator overloading?


code:
class A(object):

    def __init__(self):
        self.__prop = None

    @property
    def prop(self):
        return self.__prop

    @prop.setter
    def prop(self, value):
        self.__prop = value

class B(A):

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

    @property
    def prop(self):
        return A.prop.fget(self)

    @prop.setter
    def prop(self, value):
        value['extra'] = 'stuff'
        A.prop.fset(self, value)

rawDescription: Python - extending properties like you'd extend a function


rawDescription: remove white space using strip()

description: Remove white space using strip()


code:
@staticmethod
def union(*sets):
    union = OrderedSet()
    union.union(*sets)
    return union

def union(self, *sets):
    for set in sets:
        self |= set

rawDescription: Does Python have an ordered set?

description: Does Python have an ordered set


rawDescription: how to get all item with specific value from dict?

description: Get all item with specific value from dict


code:
class DictModel(db.Model):
    def to_dict(self):
       return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

class Match(DictModel):
    date_time = db.DateTimeProperty()
    team1 = db.StringProperty()
    team2 = db.StringProperty()
    venue = db.StringProperty()
    result = db.IntegerProperty()

rawDescription: send tidy json data of a database model from server(python) to client

description: Send tidy json data of a database model from server(python) to client


code:
for listing in listings_data:
    listings['Address: %s' % soup.find("li", "address").string]

rawDescription: Iterating through an object returned by Beautiful Soup


code:
def method2(x):
    while x < 0.1:
        x *= 10
    return x

rawDescription: Faster way to shift a decimal in Python to remove zeros?


code:
stdin, stdout, stderr = ssh.exec_command('uname -a')

ssh.exec_command('ls -la')

rawDescription: python dealing with SSH [many clients ]

description: Python dealing with SSH [many clients ]


rawDescription: Tabbing in Python?

description: Tabbing in Python


rawDescription: intersection of multiple sets in a list

description: Intersection of multiple sets in a list


code:
lines = open("myfile.txt", "r").read().splitlines()
if sorted(lines) == lines:
    print("File is in the correct order.")

rawDescription: Find if a String is in Ascending order (Lexicographically)


code:
avg=sum(map(int,zip(*l)[1]))/len(l)
avg

rawDescription: Returning .txt file contents

description: Returning .txt file contents


code:
{'keyword2': 'bar', 'keyword1': 'foo'}
{'keyword2': 'bar', 'keyword1': 'foo'}

rawDescription: Passing a list of kwargs?

description: Passing a list of kwargs


code:
[sel.xpath('''.//div/node()[count(preceding-sibling::br)=%d]
                           [not(self::br)]''' % i).extract()
 for i in range(0, len(sel.xpath('.//div/br'))+1)]

rawDescription: Scrapy selector for nodes between <br /> tags


rawDescription: Finding closest pair of coordinates from a list


rawDescription: How to write tweet IDs to a CSV file as strings

description: Write tweet IDs to a CSV file as strings


rawDescription: How to check if a word appears in ID(location in element list) of another word(key)

description: Check if a word appears in ID(location in element list) of another word(key)


code:
import xml.etree.cElementTree as ET
# import lxml.etree as ET   # also works

content = '''\
<abc>
    <cd>text1</cd>
    <cd>text2</cd>
    <ef>text3</ef>
    <ef>text4</ef>
</abc>'''

doc = ET.fromstring(content)
texts = (x.text for x in doc)
print(zip(*zip(*[texts]*2)))

rawDescription: how to convert xml into list

description: Convert xml into list


code:
import re

matching_link = grab_toc.find('a', text=re.compile('one', re.IGNORECASE))

rawDescription: Beautiful Soup and searching in results

description: Beautiful Soup and searching in results


rawDescription: How can I write to my CSV file in my booking system [STUCK]

description: Write to my CSV file in my booking system [STUCK]


rawDescription: Setting the order of output for a table

description: Setting the order of output for a table


code: owner.walk(onedog, anotherdog)

rawDescription: Writing methods that accept either a single item or an iterable in Python


code:
def random_samples(k):
    random.shuffle(id_list)
    while id_list:
        res, id_list = id_list[-k:], id_list[:-k]
        yield res

rawDescription: Python very slow random sampling over big list


code:
from __future__ import print_function

from pyparsing import CharsNotIn, Group, LineEnd, OneOrMore, Word, ZeroOrMore
from pyparsing import delimitedList, nums

SPACE_CHARS = ' \t'
word = CharsNotIn(SPACE_CHARS)
space = Word(SPACE_CHARS, exact=1)
label = delimitedList(word, delim=space, combine=True)
# an alternative contruction for 'label' could be:
# label = Combine(word + ZeroOrMore(space + word))
value = Word(nums)
line = label('label') + Group(OneOrMore(value))('values') + LineEnd().suppress()

text = """
string                     0            1           10
string with white space    0            10          30
string9 with number 9      10           20          50
string_ with underline     10           50          1
(string with parentese)    50           20          100
""".strip()

print('input text:\n', text, '\nparsed text:\n', sep='\n')
for line_tokens, start_location, end_location in line.scanString(text):
    print(line_tokens.dump())

rawDescription: Accept everything until "more than 1 white space", using pyparsing


code:
import threading
condition = threading.Condition()
queue = []
class Client():
    def write_message(self,msg):
        print(msg)

clients=[Client()]

jobdone=object()

def Consumer():
    while True:
        condition.acquire()
        try:
            if not queue:
                condition.wait()
            json = queue.pop()
            if json is jobdone:
                break;
            clients[0].write_message(json)
        finally:
            condition.release()

t = threading.Thread(target=Consumer);
t.start()
import time
time.sleep(2)
condition.acquire()
queue.append(jobdone)
condition.notify()
condition.release()

rawDescription: In Producer/Consumer pattern, how could I kill the consumer thread?


client_id: [[INSERT CLIENT ID HERE]]

client_secret: [[INSERT CLIENT SECRET HERE]]

rawDescription: I have got the "Authorization code" for my app. But how can I use it to post in the blogger using gdata-python-client?


rawDescription: Python, assign the last three elements of a list to individual variables


code:
while 1:
    try:
        url = queue.get_nowait()
        # StopIteration mark that no url will be added to the queue anymore.
        if url is StopIteration:
             break
    except Empty:
        continue
    ...
pool.join()

rawDescription: Python Thread Communication Solution

description: Python Thread Communication Solution


code:
class Struct():
    pass

rawDescription: mustache/pystache: Rendering complex objects

description: Mustache/pystache: Rendering complex objects


code:
class Palette(list):
    def __init__(self, *args, **kwargs):
        super(Palette, self).__init__(args)
        self.name = kwargs.pop('name', None)
        self.description = kwargs.pop('description', None)
        self.extend(kwargs.pop('colors', []))
        if kwargs:
            raise TypeError('{} does not take {} as argument(s)'.format(
                type(self).__name__, ', '.join(kwargs)))

palette1 = Palette(
    name   = "palette 1",
    colors = [
        "#F1E1BD",
        "#EEBA85",
        "#E18D76",
        "#9C837E",
        "#5B7887"
    ]
)
palette2 = Palette("#F1E1BD", "#EEBA85", "#E18D76", "#9C837E", "#5B7887",
                   name="palette 2")
palette1
palette2
palette1.name
palette2.name
palette1.description = 'This is palette 1.'
palette2.description = 'This is palette 2.'
Palette(foo='bar', spam='eggs')

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


code: [a if a else 2 for a in [0,1,0,3]]

rawDescription: Is it possible to use 'else' in a python list comprehension?


code:
from collections import defaultdict
groups = defaultdict(list)
dct = { 'a' : [0, 5, 7], 'b' : [1, 2, 5], 'c' : [3, 2], 'd' : [3], 'e' : [0, 5]}
for key, values in dct.items():
    for value in values:
        groups[value].append(key)

for key in groups.keys():
    if len(groups[key]) > 1:    # i.e. the value is common to more than 1 group
        print(key, groups[key])

(0, ['a', 'e'])
(2, ['c', 'b'])
(3, ['c', 'd'])
(5, ['a', 'b', 'e'])

rawDescription: Finding all the overlapping groups of dictionary keys


code:
from requests.packages.urllib3 import Retry
import requests

# Create a session
s = requests.Session()

# Define your retries for http and https urls
http_retries = Retry(...)
https_retries = Retry(...)

# Create adapters with the retry logic for each
http = requests.adapters.HTTPAdapter(max_retries=http_retries)
https = requests.adapters.HTTPAdapter(max_retries=https_retries)

# Replace the session's original adapters
s.mount('http://', http)
s.mount('https://', https)

# Start using the session
s.get(url)

rawDescription: Cleanly setting max_retries on Python requests get or post method


code:
# someapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    # other fields

    def get_full_name(self):
        if not self.user.first_name:
            return
        return ' '.join([self.user.first_name, self.user.last_name])

# template
{{ user.get_profile.get_full_name }}

rawDescription: What is the equivalent of "none" in django templates?


code:
import os
import sys
import requests  # pip install requests

class upload_in_chunks(object):
    def __init__(self, filename, chunksize=1 << 13):
        self.filename = filename
        self.chunksize = chunksize
        self.totalsize = os.path.getsize(filename)
        self.readsofar = 0

    def __iter__(self):
        with open(self.filename, 'rb') as file:
            while True:
                data = file.read(self.chunksize)
                if not data:
                    sys.stderr.write("\n")
                    break
                self.readsofar += len(data)
                percent = self.readsofar * 1e2 / self.totalsize
                sys.stderr.write("\r{percent:3.0f}%".format(percent=percent))
                yield data

    def __len__(self):
        return self.totalsize

# XXX fails
r = requests.post("http://httpbin.org/post",
                  data=upload_in_chunks(__file__, chunksize=10))

rawDescription: Progress of Python requests post

description: Progress of Python requests post


code:
from celery import current_app
# `after_task_publish` is available in celery 3.1+
# for older versions use the deprecated `task_sent` signal
from celery.signals import after_task_publish

@after_task_publish.connect
def update_sent_state(sender=None, body=None, **kwargs):
    # the task may not exist if sent using `send_task` which
    # sends tasks by name, so fall back to the default result backend
    # if that is the case.
    task = current_app.tasks.get(sender)
    backend = task.backend if task else current_app.backend

    backend.store_result(body['id'], None, "SENT")

rawDescription: Find out whether celery task exists

description: Find out whether celery task exists


code:
class SampleUsage(Generic):

    def process_data(self):
        # In any of your methods you can call these generic functions
        self.get_query()

rawDescription: How do I design this procedural code as class based (object oriented)?

description: Design this procedural code as class based (object oriented)


code:
Numeric = []
x1 = []
soup =BeautifulSoup(urllib.request.urlopen("file:///C:/Users/Home/Downloads/SuperLoto_Results__539-796.htm").read(),'lxml')
for row in soup.find_all('tr'):
    try:
        col = row.find_all('td')
        x1.extend(col[3])
        Numeric.extend(col[0])
    except:
        print("error")
print(x1.__len__())
print(Numeric.__len__())

rawDescription: Loop stoped on half of data

description: Loop stoped on half of data


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

data = np.random.rand(10,10)

plt.subplot(1,2,1)
con = plt.contourf(data, cmap=cm.jet)
plt.title('Jet')
plt.colorbar()

hax = plt.subplot(1,2,2)
con = plt.contourf(data, cmap=cm.gray)
plt.title('Gray')
plt.colorbar()

rawDescription: Meaning of cmap in contourf

description: Meaning of cmap in contourf


rawDescription: Python json.loads not able to parse json string


code:
import numpy
from numpy.lib._datasource import DataSource
#def open(path, mode='r', destpath=os.curdir):
def openm(path, mode='r', destpath=None):
  ds = DataSource(destpath)
  return ds.open(path, mode)
numpy.lib._datasource.open=openm

rawDescription: genfromtxt: how to disable caching

description: Genfromtxt: how to disable caching


code:
def nodups(s):
    last = None
    for w in s:
        if w == last:
            continue
        yield w
        last = w

rawDescription: Stripping duplicate words from generated text in python script


code:
class Parent:
    def f(self, *v_args):
        arg = self.helper_f(*v_args)
        print("Received {}.".format(arg))
        return arg ** 3

    def helper_f(self,*args):
        "really should be an abstract method, must be implemented in a subclass"
        raise NotImplementedError("Must override in a subclass!")

class Child(Parent):
    def helper_f(self, c, b, a):
        print(a, b, c)
        return a

# Prints "Received 2.". Sets value to 8.
value = Child().f(0, 1, 2)

rawDescription: How can I return a value to a superclass without overriding the parent function?

description: Return a value to a superclass without overriding the parent function


code:
class Group(models.Model):
    group_name = models.CharField(max_length=50, unique=False, blank=False)

class Group_Cover(models.Model):
    group = models.OneToOneField(Group)
    group_cover = models.ImageField(upload_to="/image/group/")

class Group_Member(models.Model):
    user = models.ForeignKey(User2)
    group = models.ForeignKey(Group)

rawDescription: Django OneToOneField and ForeignKeyField add "_id" suffix to the field


rawDescription: Vectorized element assignment involving comparisons between matrices in Numpy


code:
from datetime import datetime, time, timedelta
def value_to_time(val):
    if val == 'now':
        return datetime.now().time()
    if val.endswith('min'):
        return (datetime.now() + timedelta(minutes=int(val[:-3]))).time()
    hours, minutes = map(int, val.split(':'))
    return time(hours, minutes)

lst = ['3min', '9min', '16:21', '16:36', '16:51', 'now']
sorted(lst, key=value_to_time)

rawDescription: Python - sorting a tuple, characters over numbers


code:
operator.setitem(a, b, c)
operator.__setitem__(a, b, c)

rawDescription: Check for [] operator

description: Check for [] operator


code: l.sort(key=lambda item: item[1])

rawDescription: Most pythonic way to reorder repeating list


code:
seen = OrderedDict()
for first, second in l:
    if second not in seen or first > seen[second]:
        seen[second] = first

[(x, y) for y, x in seen.items()]

rawDescription: Deleting all tuples except ones with the smallest gap between integers, in the list of tuples


code:
...
import seaborn as sns
...

@devices_blueprint.route('/devices/test/')
def test():

    img = StringIO.StringIO()
    sns.set_style("dark") #E.G.

    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)

rawDescription: How to render and return plot to view in flask?

description: Render and return plot to view in flask


rawDescription: More efficient way to iterate groupby Pandas dataframe?


code:
#admin.py inside your graph app
class WatchedVideoInline(admin.TabularInline):
    model = WatchedVideo

class UserAdmin(admin.ModelAdmin):
    inlines = [WatchedVideoInline]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

rawDescription: One to Many relationship of models in Django


code:
week_ago = (DateNow - timedelta(weeks=1))
day_ago = (DateNow - timedelta(days=1))
data_Week = {}
data_24 = {}
#data_before = {}

for row in f_reader:
    stringRowDate = row[0]
    Date = datetime.datetime.strptime(stringRowDate,"%Y-%m-%d %H:%M")
    if Date >= day_ago:
        data_24[row[0]] = row[1:]
    elif Date >= week_ago:
        data_Week[row[0]] = row[1:]
    else:
        continue
        #data_before[row[0]] = row[1:]

rawDescription: Iterate over . csv file --> write into two dictionaries


code:
from nltk.util import ngrams
from nltk import word_tokenize
string = "I see a tall tree outside. A man is under the tall tree"
len([i for i in ngrams(word_tokenize(string),n=2) if i==('tall', 'tree')])
string = "I would like to install treehouses at my yard"
len([i for i in ngrams(word_tokenize(string),n=2) if i==('tall', 'tree')])

rawDescription: NLTK count frequency of sub phrase

description: NLTK count frequency of sub phrase


rawDescription: Django Query including a table where no relation can be followed


code:
def __init__(self):
    print(self.__class__.b) # Python 2.x and old-style class

rawDescription: Python: Reference to a class generically in an instance method?


rawDescription: Python: Bytes to string with accented characters


code:
foo(args.arg1)
foo(args.arg1, args.arg2)
foo(args.arg1, arg2=args.arg2)

rawDescription: Using argparse with function that takes **kwargs argument


code: df.columns = df.columns.droplevel(0)

rawDescription: Convert column elements to column name in panda (part II)


code: latestVersion = max(int(fname.rsplit('.',1)[0].rsplit("_",1)[1].strip('v')) for fname in myFiles)

rawDescription: Determining the latest version of a file (python)


code: os.system("start C:")

rawDescription: wxPython. How to open a folder with wxWidget (python) hyperlink?

description: WxPython. How to open a folder with wxWidget (python) hyperlink


code: index = random.randrange(len(names) - 1)

rawDescription: how to find unknown variable in list?

description: Find unknown variable in list


rawDescription: How to use distinct with pipeline in mongodb using python

description: Use distinct with pipeline in mongodb using python


rawDescription: Python Unicode Conversions

description: Python Unicode Conversions


code:
import os, datetime
def cmonth(filename):
    ts = os.stat(filename).st_ctime
    return datetime.date.fromtimestamp(ts).month

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
from xml.etree.ElementTree import ElementTree

tree = ElementTree()
tree.parse(xmlFile)
actions = tree.findall('action')

parsed = [{field.tag: field.text for field in action} for action in actions]

rawDescription: Multidimensional dictionary in Python

description: Multidimensional dictionary in Python


code:
from timeit import Timer
Timer(stmt="sorted(xs,key=itemgetter(1))",setup="from operator import itemgetter;xs=range(100);xs=zip(xs,xs);").timeit(300000)
Timer(stmt="sorted(xs,key=lambda x:x[1])",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)
Timer(stmt="sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)

rawDescription: What arguments does Python sort function have?


code:
strs='a;b;c;d'
count=strs.count(";")-1
strs = strs.replace(';',', ',count).replace(';',' & ',)
strs

rawDescription: Python: replace terms in a string except for the last


rawDescription: Get original filename google app engine

description: Get original filename google app engine


code:
record_types = {SEN_RECORD: sen_record,
                DSP_RECORD: dsp_record,
                USO_RECORD: uso_record,
                SDM_RECORD: sdm_record,
                DOC_RECORD: doc_record,
                DAT_RECORD: dat_record,
                LAT_RECORD: lat_record,
                SWI_RECORD: swi_record,
                FTL_RECORD: ftl_record}

rawDescription: Can a constructor for a super class return instances of a sub class instead?


code:
from django.shortcuts import get_object_or_404

def comment(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    # usual form boilerplate below here

rawDescription: set the value of a django HiddenInput widget to another object's id rendered in the template

description: Set the value of a django HiddenInput widget to another object's id rendered in the template


code:
class BMeta(AMeta):
    def __new__(meta, name, bases, dct):
        cls = super(BMeta, meta).__new__(meta, name, bases, dct)
        cls._specializations = {}
        return cls

    def _get_specialization(cls, selector):
        if selector not in cls._specializations:
            name = "{}_{}".format(cls.__name__, selector)
            bases = (cls.__bases__[0]._get_specialization(selector),)
            dct = cls.__dict__.copy()
            specialization = type(name, bases, dct) # not a BMeta!
            cls._specializations[selector] = specialization
        return cls._specializations[selector]

    def __call__(cls, selector, *args, **kwargs):
        cls = cls._get_specialization(selector)
        return type.__call__(cls, *args, **kwargs) # selector could be passed on here

class B(A, metaclass=BMeta):
    pass

rawDescription: Changing the bases of an object based on arguments to __init__


code:
def __repr__(self):
    return "Dir('{}')".format(self.path.resolve())

rawDescription: How can I get the proper capitalization for a path?

description: Get the proper capitalization for a path


code:
from re import sub
with open("/path/to/file") as myfile:
    lines = []
    for line in myfile:
        line = sub('punctacros="Tasla"(_.*)', r'TROGA\1', line)
        lines.append(line)
with open("/path/to/file", "w") as myfile:
    myfile.writelines(lines)

rawDescription: Replace part of a matched string in python


code:
import lxml.html as LH

html = '''

Granular computing based
data
mining
in the views of rough set and fuzzy set

'''

root = LH.fromstring(html)
for elt in root.xpath('//a'):
    print(elt.text_content())

rawDescription: Get data between two tags in Python

description: Get data between two tags in Python


code:
class MyClass(object):
  pass
dir(MyClass)

rawDescription: Attribute assignment to built-in object

description: Attribute assignment to built-in object


code:
class C(Base1, Base2):
    def create(self):
        Base1.create(self)
        Base2.create(self)

rawDescription: Class Inheritence Naming in Python

description: Class Inheritence Naming in Python


code: vals = np.array([mapping[key] for key in keys])

rawDescription: Numpy: Convert values in a 1-D array based upon dictionary


code: dave = next(person for person in a.pList if person.num == 123)

rawDescription: how to select an object from a list of objects by its attribute in python

description: Select an object from a list of objects by its attribute in python


code:
def pearsonr_flex(a,b, axis=1):
    # stats.pearsonr adapted for
    # x and y are (N,2) arrays
    n = x.shape[axis]
    mx = x.mean(axis, keepdims=True)
    my = y.mean(axis, keepdims=True)
    xm, ym = x-mx, y-my
    r_num = np.add.reduce(xm * ym, axis)
    r_den = np.sqrt(stats.ss(xm, axis) * stats.ss(ym, axis))
    r = r_num / r_den
    r = np.clip(r, -1.0, 1.0)
    return r

pearsonr_flex(xx, yy, 1)
preasonr_flex(x, y, 0)

rawDescription: Any faster way to get the same results?

description: Any faster way to get the same results


code:
#it will determine whether there is a same a in row or not
def search_row(sudoku_map_search, a, row):
    for i in range(9):
        if sudoku_map_search[row][i] == a:
            return 0;
    return 1;

rawDescription: Sudoku with python

description: Sudoku with python


code:
a.setflags(write=False)  # sets the WRITEABLE flag to False
a[2] = 10                # the modification will fail

rawDescription: How can I verify when a copy is made in Python?

description: Verify when a copy is made in Python


code:
nextx(lst,5,7,11)
nextx(lst,5,7,11) == [lst[j%len(lst)] for j in range(5,5+11)] == list(islice(cycle(lst),5,5+11))

rawDescription: Iterate through a List Multiple times Cyclically starting from the Matching Index


code: archivo = models.FileField(upload_to = 'path/%Y/%M/%D/')

rawDescription: Change filename before save file in Django


code:
word = ''
for character in element:
    word = word + character
print(word)

rawDescription: List conversion/transformation

description: List conversion/transformation


code:
l=[[1],[3,4],[5],[6,7,8],[4,0],[2],[5,6,7]]
from itertools import groupby
[list(g) for _,g in groupby(sorted(l,key=len),key=len)]

rawDescription: Making Sub Lists Based on Lengths of Items


code: add = primes_matrix[n2][1] + primes_matrix[n3][2]

rawDescription: Very slow python running time when trying to solve project Euler. Unsure if python or slow algorithm


code:
vl_list = [] # create a list for values
for line in values.split("\n"):
    vl_list.extend(line.split(","))

rawDescription: Split values and store into a list

description: Split values and store into a list


code: ['ConfigurationItem', 'UNICODE_OUTPUT', '__builtins__', '__cached__', '__doc__', '__file__', '__githash__', '__loader__', '__minimum_numpy_version__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_check_numpy', '_get_test_runner', '_init_log', '_initialize_astropy', '_teardown_log', 'config', 'constants', 'coordinates', 'cosmology', 'cython_version', 'extern', 'find_api_page', 'io', 'log', 'logger', 'logging', 'online_docs_root', 'table', 'test', 'time', 'units', 'utils', 'version', 'version_helpers', 'wcs']

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

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


rawDescription: Initializing numpy masked array from Python int list with None values


code:
nl = [['Prashant', 32], ['Pallavi', 36], ['Dheeraj', 39], ['Shivam', 40]]
from operator import itemgetter
mn = min(nl, key=itemgetter(1))[1]
filtered = [x for x in nl if x[1] != mn]
mn_fil = min(filtered,key=itemgetter(1))[1]
out = [x for x in filtered if x[1] == mn_fil]
out

rawDescription: How to find the second lowest lists into a nested list by their second value?

description: Find the second lowest lists into a nested list by their second value


code:
def process_request(self, request, spider):
    request.meta['proxy'] = self.proxy_pool[random.randint(0, len(self.proxy_pool) - 1)]

rawDescription: Scrapy how to use a proxy pool

description: Scrapy how to use a proxy pool


code:
def bytes(integer):
    return divmod(integer, 0x100)

rawDescription: Best way to split a hexadecimal in python?

description: Split a hexadecimal in python


code:
unique_id = '%32x' % random.getrandbits(16*8)
unique_id

rawDescription: Django package to generate random alphanumeric string


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

rawDescription: Problems with creating label in tkinter

description: Problems with creating label in tkinter


code: [d for d in inputlist if any(v != '' for v in d.itervalues())]

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

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


rawDescription: Python: Find in list

description: Python: Find in list


code:
from sqlalchemy.orm.attributes import manager_of_class
a_table = manager_of_class(TableA).mapper.mapped_table
b_table = manager_of_class(TableB).mapper.mapped_table

rawDescription: Mapping a 'fake' object in SQLAlchemy

description: Mapping a 'fake' object in SQLAlchemy


rawDescription: How to call or refer to an instance attribute from another's class method

description: Call or refer to an instance attribute from another's class method


code:
from rauth.session import OAuth1Session

session = OAuth1Session(consumer_key=VIMEO_CLIENTID,
                        consumer_secret=VIMEO_CLIENTSECRET,
                        access_token=VIMEO_ACCESSTOKEN,
                        access_token_secret=VIMEO_ACCESSTOKENSECRET)

response = session.get('http://vimeo.com/api/rest/v2', params={'method': 'vimeo.oauth.checkAccessToken'})

rawDescription: OAuth Signature not valid error using Rauth, Python against the Vimeo API


code:
def filter_func(dic, filterdic):
    for k,v in filterdic.items():
        if k == 'items':
            if any(elemv in dic[k] for elemv in v):
                return True
        elif v == dic[k]:
            return True
    return False

def filter_cards(deck, filterdic):
    return list(filter(lambda dic, filterdic=filterdic: filter_func(dic, filterdic) , deck))

rawDescription: filter items by value in dict

description: Filter items by value in dict


code:
import numpy as np
pos = np.array([[200,0], [210,210], [215,215], [192,186]], dtype=float)
lastpos = np.array([[200,2000], [ 210,210], [195, 195], [160,160]], dtype=float)
velocity = np.array([[ 5,5], [8,2], [5,3], [10,-4]], dtype=float)
mass = np.array([ 10, 20, 5, 30 ], dtype=float)
size = np.array([ 15, 25, 15, 30 ], dtype=float)

def moveParticles(pos, lastpos, velocity, dt):
    lastpos[:] = pos[:]
    pos[:] += velocity * dt

rawDescription: Writing calculation results back into its array?


code: res = np.mean(data, axis=(2,3,4))

rawDescription: How to get a mean array with numpy

description: Get a mean array with numpy


code: [list(pro) for pro in product({1,-1},repeat=3)]

rawDescription: How do I fill a list in python with elements from a specific set?

description: Fill a list in python with elements from a specific set


code: scroll_area.view_y = 30 # start 30 pixels down

rawDescription: Render and scroll through multiline paragraphs using pyglet and ScrollableTextLayout


code:
def false_recursive():
    false_recursive

def true_recursive():
    true_recursive()

assert is_recursive(true_recursive), 'Must not fail'
assert not is_recursive(false_recursive), 'See? It fails' # AssertionError: See? It fails

rawDescription: Search for recursive functions in a Python project


code:
file = open("test.txt", "r")
reader = csv.DictReader(file, delimiter="\t")

ids = [] #open 3 new lists to hold your data
start = []
end = []
for data in reader:
    ids.append(float(data["id"]))
    start.append(float(data["start"]))
    end.append(float(data["end"])-float(data["start"])) #remember: it's "width" not "right edge coordinate"

rawDescription: Plot large data in the specified format using python


code: feature3 = [d.get('Feature3') for d in df.dic]

rawDescription: Extract dictionary value from column in data frame


rawDescription: Plotting rotated pole projection in cartopy


code:
num = X.prod()

(num * y).sum()

rawDescription: Multiplying each element of a numpy array and summing it up


code:
' '.join(filter(None, pattern.split(test_str)))
len(_.split())

rawDescription: Insert a space between a non-alphanumeric and alphanumeric char except specific char (Python)


code:
def foo(): return foo()  # infinite recursion
def foo(): return foo()  # infinite recursion

foo
bar = foo
del foo
foo
bar
bar()

rawDescription: Scope of function inside the function (understanding recursion)


code: data = [list(DictReader(x, delimiter='\t')) for x in stringios]

rawDescription: Splitting Rows in csv on several header rows


code:
from string import ascii_lowercase, digits
from itertools import product, combinations_with_replacement as cr, chain

for p in product(cr(ascii_lowercase,3), digits,ascii_lowercase):
    print("".join(chain.from_iterable(p)))

rawDescription: Simple code to generate a wordlist of specific type


code:
from flask import Blueprint

bp = Blueprint('routes', __name__)

from project.routes import views

rawDescription: Flask: are blueprints necessary for app factories?


code:
B.add_edges_from(
    [(row['domain'], row['subdomain']) for idx, row in df.iterrows()])

rawDescription: Construct bipartite graph from columns of python dataframe


code: three = models.TextField(widget=form.Textarea(attrs={"class": "mceNoEditor"}))

rawDescription: django: disable tinymce for one certain field

description: Django: disable tinymce for one certain field


code:
from framework import logutils
logutils.set_up_only_once()

rawDescription: Logging in a Framework

description: Logging in a Framework


code:
from collections import defaultdict, Counter
d = defaultdict(Counter)
d['red']['blue'] += 1
d['green']['brown'] += 1
d['red']['blue'] += 1
pprint.pprint(d)

rawDescription: skip excel lines with python

description: Skip excel lines with python


rawDescription: To use BeautifulSoup to extract parts of texts in webpage title


code:
class MediaItemManager(models.Manager):
    def get_queryset(self):
        return super(MediaItemManager, self).get_queryset().filter(...)

rawDescription: In Django, how do I gracefully add a queryset filter to a large group or all members of an object?


code: df1.merge(df2, on='Name')

rawDescription: How to merge two DataFrames of unequal size based on row value

description: Merge two DataFrames of unequal size based on row value


code:
# num = 1
# words = ['foo', 'bar', 'baz']

rawDescription: Capture all repetitions of a group using Python regular expression


rawDescription: Write list of lists to csv row

description: Write list of lists to csv row


code:
def register_lib(self, p):
    libpath = os.path.join(LIBPATH, p)
    zippath = libpath + '.zip'
    zf = zipfile.PyZipFile(zippath, mode='w')
    try:
        zf.debug = 3
        zf.writepy(libpath)
        self.sc.addPyFile(zippath)
    finally:
        zf.close()

rawDescription: Modify SparkContext from outside __main__ file sent to spark-submit


code:
def between(a, b):
    def between_percentage(series):
        return float(len(series[(a <= series) & (series < b)])) / float(len(series))
    return between_percentage

rawDescription: Customizing rolling_apply function in Python pandas