rawDescription: Transpose a matrix in Python

description: Transpose a matrix in Python


rawDescription: How to turn a list/tuple into a space separated string in python using a single line?

description: Turn a list/tuple into a space separated string in python using a single line


code:
#!/usr/bin/env python
import os
from collections import deque
from subprocess import Popen, PIPE

DEVNULL = open(os.devnull, 'wb', 0)

time_lines_count = 1 # how many lines /usr/bin/time produces
p = Popen(['/usr/bin/time', '--format=%e seconds'] +
          ['sleep', '1'], stdout=DEVNULL, stderr=PIPE)
with p.stderr:
    q = deque(iter(p.stderr.readline, b''), maxlen=time_lines_count)
rc = p.wait()
print(b''.join(q).decode().strip())

rawDescription: Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?


code: b = [x + (100 if x < 4 else 1) for x in a]

rawDescription: Fastest way to modify list values with condition python


code:
def firstOccur(key, string):
    for i in range(len(string)):
        if key == string[i]:
            return i
    return -1

rawDescription: How to make a function that detects a character in a string and returns it's position in the string? Python 3.2

description: Make a function that detects a character in a string and returns it's position in the string? Python 3.2


code: map(function, list_of_dicts)

rawDescription: What is more effective iterate a list and call a function or pass the list to the function


code:
dis.dis(lambda x: x & (1 << 3))
dis.dis(lambda x: x & 0b1000)

rawDescription: python check if bit in sequence is true or false

description: Python check if bit in sequence is true or false


code:
frame['b'].where(frame['a'], 2 * frame['b'])
frame['c'] = frame['b'].where(frame['a'], 2 * frame['b'])

rawDescription: doing calculations in pandas dataframe based on trailing row

description: Doing calculations in pandas dataframe based on trailing row


code:
from nltk import FreqDist
import csv

fdist = FreqDist("aaa b cccc dd e")

with open("fdist.csv", "wb") as fp:
    writer = csv.writer(fp, quoting=csv.QUOTE_ALL)
    writer.writerows(fdist.items())

rawDescription: How to output NLTK tabulate results into CSV?

description: Output NLTK tabulate results into CSV


rawDescription: Generate system of equations

description: Generate system of equations


code:
drivefiles  = drive.ListFile().GetList()
self.User.GoogleFile = None
while True:
    for f in drivefiles:
        if f['title'] == 'Hello.txt':
            self.User.GoogleFile = f
            break
        if self.User.GoogleFile!=None:
            self.Message=json.loads(self.User.GoogleFile.GetContentString())
    raw_input("Press Enter to continue...")

rawDescription: Access shared file with PyDrive

description: Access shared file with PyDrive


code:
['2-Propanone', 'Acetone', 'Acetone [NF]', 'Dimethyl ketone']
['Acetone']

rawDescription: Can I access the subchild of a parent in XPath?

description: Access the subchild of a parent in XPath


code:
def word2vec(word):
    from collections import Counter
    from math import sqrt

    # count the characters in word
    cw = Counter(word)
    # precomputes a set of the different characters
    sw = set(cw)
    # precomputes the "length" of the word vector
    lw = sqrt(sum(c*c for c in cw.values()))

    # return a tuple
    return cw, sw, lw

def cosdis(v1, v2):
    # which characters are common to the two words?
    common = v1[1].intersection(v2[1])
    # by definition of cosine distance we have
    return sum(v1[0][ch]*v2[0][ch] for ch in common)/v1[2]/v2[2]

rawDescription: cosine similarity between two words in a list

description: Cosine similarity between two words in a list


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors

data = np.random.random((10,10))
data = 10 * (data - 0.8)

num_levels = 20
vmin, vmax = data.min(), data.max()
midpoint = 0
levels = np.linspace(vmin, vmax, num_levels)
midp = np.mean(np.c_[levels[:-1], levels[1:]], axis=1)
vals = np.interp(midp, [vmin, midpoint, vmax], [0, 0.5, 1])
colors = plt.cm.seismic(vals)
cmap, norm = from_levels_and_colors(levels, colors)

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=cmap, norm=norm, interpolation='none')
fig.colorbar(im)
plt.show()

rawDescription: Shifted colorbar matplotlib

description: Shifted colorbar matplotlib


code:
counts = Counter()
for dct in lst:
    counts[dct['medication_name']] += dct['total_prescriptions']
for dct in lst:
    dct['final_count'] = counts[dct['medication_name']]

from pprint import pprint    as pp

rawDescription: Summing values for a particular key in a list of dicts in python


code:
from functools import wraps
def count_check(function, count={}):
    """Returns number of times any function with this decorator is called
    """
    count[function] = 0
    @wraps(function)
    def increase_count(*args, **kwargs):
        count[function] += 1
        return function(*args, **kwargs), count[function], sum(count.values())

    return increase_count

rawDescription: Python - Count number of times function passes through decorator


code:
def ret(l):
   l.append(5)
   return l

def no_ret(l):
   l.append(5)

def test_ret():
    l=[]
    for i in xrange(100000):
        ret(l)

def test_no_ret():
    l=[]
    for i in xrange(100000):
        no_ret(l)

rawDescription: Return statement in method that modifies in-place


rawDescription: Python: how to compute the number of shortest paths passing through one node?


code:
from bigfloat import *
def logit(p):
    with precision(100000):
        return log(p)- log(1 -BigFloat(p))

def inv_logit(p):
    with precision(100000):
        return exp(p) / (1 + exp(p))

int(round(logit(inv_logit(12422.0))))
# gives 12422
int(round(logit(inv_logit(-12422.0))))
# gives -12422

rawDescription: logit and inverse logit functions for extreme values

description: Logit and inverse logit functions for extreme values


code: #!/home/my/virtual/bin/python

rawDescription: Cron and virtualenv

description: Cron and virtualenv


code:
class MySaveMixin(object):
    """My Mixin for providing save functionality to Models"""
    def save(self, *args, **kwargs):
        super(self.__class__, self).save(*args, **kwargs)
        if not self.item_id:
            self.item_id = '%s%s' % (self.__class__.__name__[0], self.pk)
            self.save()

class Series(models.Model, MySaveMixin):
    item_id = models.CharField(max_length=60, unique=True, blank=True)
    name = models.CharField(max_length=600, blank=True)

rawDescription: How to add same save method to all models

description: Add same save method to all models


code:
params = urllib.urlencode({'key': '8TU6AC31T81MV52N', 'field1': 'my value'})
f = urllib.urlopen("https://api.thingspeak.com/update", data=params)

rawDescription: How to POST - API in thingspeak.comusing urllib in Python


rawDescription: python max function with mixed strings and numbers

description: Python max function with mixed strings and numbers


code:
instances = MyModel.objects.filter(a='1').only('id', 'a', 'choicefield')
instances[0].get_choicefield_display()  # will work fine

rawDescription: Get full label name of ChoiceField in QuerySet values list


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


rawDescription: Generate all n digit numbers using itertools, with bounds on range of 1st digit


code:
import imp
my_module = imp.load_source('my_module', 'strange.name-1.py')

rawDescription: Import .py files with punctuation before extension


rawDescription: operation in arrays

description: Operation in arrays


code:
number = input('What number do you want to start with? ')

while len(number) > 1:
    number = str(sum(int(digit) for digit in number))

print('Result is', number)

rawDescription: How to add numbers in an integer

description: Add numbers in an integer


code:
def prettyfloat(number):
    return "%0.2f" % number  # Works the same.

rawDescription: subclassing float to force fixed point printing precision in python

description: Subclassing float to force fixed point printing precision in python


code:
def func_1(a, b, c):
    b += a
    if b >= 100:
        print("\nAdd 1!\n")
        c += 1
        b -= 100
    a = 0
    # Rest of the function

rawDescription: Python: variables not cumulative passing through functions


code: csval = parseline(linecache.getline('variables.txt', 7))

rawDescription: Extracting specific variables of a line with linecache


rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
bi_bins = (struct.pack('>I',  i) for i in ints)
''.join(bi_bins)

rawDescription: Python write string "1001101" as binary stream to file


code: 'text2 foobar baz'

rawDescription: How to grab item outside of tag using python+beautifulsoup

description: Grab item outside of tag using python+beautifulsoup


rawDescription: Python: How do you convert n-bits to base 64?


code:
df['max_a'] = pd.rolling_max(df['a'].tshift(-14),15)
df['min_b'] = pd.rolling_min(df['b'].tshift(-14),15)
df.head(20)

rawDescription: Calculating averages of 15 records ahead of the current record as a new column


code: Django

rawDescription: Configure Django1.6 with python 27 on openshift Step by step


code: abcd

rawDescription: How to extract 4 characters after '-' in a hostname

description: Extract 4 characters after '-' in a hostname


rawDescription: Python integers to strings

description: Python integers to strings


code:
rules = list([None, None])
for a in range(2):
  rules[a] = lambda t: a

rules[0](0)
rules[0](1)
rules[1](0)
rules[1](1)

rawDescription: Python for loop initialization of reference to function


code:
grouped = {}
for elem in L:
    key = elem.partition('_')[0]
    grouped.setdefault(key, []).append(elem)
grouped = grouped.values()

rawDescription: Split list into sublist based on part of value


code: ( MY_DSL_FOO_FUNCTION(params), ANOTHER_DSL_FUNCTION(), expression_in_python, more_expressions_in_python )

rawDescription: When a DSL gets 'lispy'

description: When a DSL gets 'lispy'


code:
d = {'t1': 'm1', 'year': '2003'}
fmt = "select * from records where year = {year} and t1 = {t1}"
fmt.format_map(d) # available only in Python 3.2+
fmt.format(**d)

rawDescription: how to do a complex replace in python using regex?

description: Do a complex replace in python using regex


code: times = [result.group('time') for result in messages]

rawDescription: Navigating Callable-Iterators

description: Navigating Callable-Iterators


code:
def dot(arr1, arr2):
    return sum([x*y for x,y in zip(arr1, arr2)])

dot(row(A,0), col(B,0))

rawDescription: How to multiply each row in a matrix by each column in the second matrix in Python?

description: Multiply each row in a matrix by each column in the second matrix in Python


code:
nh, nw = new_arr.shape
norm_arr[:nh, :nw] = new_arr

rawDescription: Better image normalization with numpy

description: Better image normalization with numpy


code:
# start spin
self.spin(bets)
# payout for bets

rawDescription: Roulette program will not recognize correct guess. Why?


code: interestingelts = (x for x in oldlist if x not in ['a', 'c'])

rawDescription: List Manipulation in Python with pop()

description: List Manipulation in Python with pop()


code:
import os
import sys
import inspect

from pprint import pprint
# Get the current folder, which is the input folder
mod_b_folder = os.path.realpath(
    os.path.abspath(
        os.path.split(
            inspect.getfile(
                inspect.currentframe()
            )
     )[0]
   )
)
folder_parts = mod_b_folder.split(os.sep)
prev_test_pack_path = os.sep.join(folder_parts[0:-2])
test_pack_path = os.sep.join(folder_parts[0:-1])
sys.path.insert(0, test_pack_path)
sys.path.insert(0, prev_test_pack_path)

# Rest of module B

rawDescription: Absolute vs Relative Imports in Python 2


code:
def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

rawDescription: Python - Create a list with initial capacity


code:
lst = [[0]*5 for _ in range(5)]
[id(sublst) for sublst in lst]

rawDescription: How to multiply lists and set a single variable?

description: Multiply lists and set a single variable


code:
#header file3
python
file

rawDescription: concatenate several file remove header lines

description: Concatenate several file remove header lines


code:
import re
sample = "linux = r'^LIN',"
eag = 'linux'
rpat = re.compile("^\s*%s\s*=\s*(r'[^']+')" % re.escape(eag))
rpat.match(sample).group(1)

rawDescription: python regex using re.compile and match

description: Python regex using re.compile and match


code:
import os

def makeascript(where):
  f = open(where, 'w')
  f.write('import os\nprint "Dir in file:", os.getcwd()\n')
  f.close()

def main():
  where = '/tmp/bah.py'
  makeascript(where)
  execfile(where)
  os.chdir('/tmp')
  execfile(where)

if __name__ == '__main__':
  main()

rawDescription: Python: execfile from other file's working directory?


code:
def main(global_conf, **settings):
    parser = ConfigParser({'here': global_conf['__here__']})
    parser.read(global_conf['__file__'])
    for k, v in parser.items('user:sg:qa'):
        settings['user:sg:qa:' + k] = v

    config = Configurator(settings=settings)

rawDescription: How can I access a custom section in a Pyramid .ini file?

description: Access a custom section in a Pyramid .ini file


code:
a = numpy.asarray(a, dtype=float)
b = numpy.asarray(b, dtype=float)

rawDescription: Fitting a straight line to a log-log curve in matplotlib


code: len(set(product(A, repeat=3)))

rawDescription: Possible alignments of two lists using Python


code:
with open(youroutput,'wb') as fout:
    fout.write(struct.pack('<f',300.0))

rawDescription: How to write a REAL32 value to a file in Python?

description: Write a REAL32 value to a file in Python


code:
qList = re.sub("[^\w]", " ",  request.args.get('q') ).split()
return render_template('list_of_found_items.html', items = map(RESULT_BLAH_BLAH_METHOD, qList))

rawDescription: Variable is not shown in Flask template

description: Variable is not shown in Flask template


rawDescription: `struct.unpack_from` doesn't work with `bytearray`?


code: set(generate_neighbors('ab', {'a', 'b', 'c', 'd'}))

rawDescription: Faster alternative to for loop in for loop


code:
image = {
    'pixels': im.tostring(),
    'size': im.size,
    'mode': im.mode,
}

rawDescription: Pickleable Image Object

description: Pickleable Image Object


code:
if get_path_and_weight(data, "Abe", "Dan"):
    print("connected")

rawDescription: Find path from a list of tuples in Python


code:
se=int(raw_input())

if se < len(items):
    item = items[se-1]
    the_path = "/var/mobile/TP/{}".format(item)
else:
    print("Please enter a value between 1 and {}".format(len(items)))

rawDescription: How to assign variable to listed items in python?

description: Assign variable to listed items in python


code:
apple = Topic.objects.filter(tag='Apple')
sub_topics = apple.sub_topics.all() ## Gets all sub_topics.

rawDescription: Django, topic model with subtopics

description: Django, topic model with subtopics


code:
class AnimalModelForm(ModelForm):
    class Meta:
        model = Animal
        fields = ['animal', ]
        widgets = {'configurator': MyWidget, }

rawDescription: Django with Select2 remote data example

description: Django with Select2 remote data example


code:
from bs4 import NavigableString

span = tender_soup.find('div',{"id":"cpv_codes"}).findNext('span')
categories = [c.strip() for c in span.contents if isinstance(c, NavigableString)]

rawDescription: BeautifulSoup beautifying an ugly process


code:
track_keys = ("artist", "title", "image_xl", "image_l", "image_m", "image_s")

zipped = zip(_artist_name, _artist_title, _xl, _l, _m, _s)
track_data['recent_tracks'] = [dict(zip(track_keys, values)) for values in zipped]

rawDescription: Putting a zipped object into a dictionary


code:
import pyMyDB

class Driving(object):

    def __init__(self,db):
        self.db = db

    def GetTachometerReading(self):
        # self here is the Driving instance,
        # but we have access to the db
        print(self.db.db_stuff)

pyMyDB.MyDB.submodule_classes.append(Driving)

rawDescription: Access parent object from submodule

description: Access parent object from submodule


rawDescription: Help on Regular Expression problem

description: Help on Regular Expression problem


code:
or_statement = lambda a, b: "%s or %s = %s" % (a, b, a or b)
or_statement(True, False)
or_statement(True, None)
or_statement(None, None)

rawDescription: Why python designed as str(None) return 'None' instead of an empty string?


code:
M.data
M.indices
M.indptr

rawDescription: How do I get a scipy.csr sparse-matrix as a normal dense matrix without toDense()?

description: Get a scipy.csr sparse-matrix as a normal dense matrix without toDense()


code:
import pandas as pd
import scipy.stats.mstats as mstats
def mode(x):
    return mstats.mode(x, axis=None)[0]

df = pd.DataFrame({'Feature': ['ON', 'OFF', 'ON', 'ON', 'OFF'],
                   'ID': [1, 1, 2, 1, 2],
                   'ITEM1': [2.3, 2.55, 8.32, 1.56, 3.55],
                   'ITEM2': [544, 544, 674, 544, 674],
                   'ITEM3': [32.2, 23.4, 15.5, 43.4, 32.4],})

df.groupby(['Feature','ID']).agg({'ITEM1':'mean','ITEM3':'mean','ITEM2':mode})
print(df)

rawDescription: Pandas mean and mode particular columns in DataFrame


code:
def get_object(self):
    object = super(PersonView, self).get_object()
    object.num_groups = object.group_set.all().count()
    return object

rawDescription: Use get_object() and aggregate() in DetailView in Django


code:
def func(x,keyword='bar'):
    return (x,keyword)

rawDescription: Python functions within lists

description: Python functions within lists


code:
from distutils.core import setup
import py2exe

setup(
    name='Tester',
    console=['Loader.py'],
    packages=['api']
)

rawDescription: Python Plugin Capbility

description: Python Plugin Capbility


code:
def pseudo_rand_point():
    x = random.randint(0, screen_width-1)
    if rect_x <= x < rect_x + rect_width:
        y = random.randint(0, screen_height-rect_height-1)
        if y >= rect_y:
            y += rect_height
    else:
        y = random.randint(0, screen_height-1)
    return (x, y)

rawDescription: Generate random number outside of range in python


code:
y.shape
z=y.reshape(3,4)
z.__array_interface__
z

rawDescription: When will numpy copy the array when using reshape()


code:
class Car(object):
    #Car is a subclass of Python's base objeect. The reasons for this, and the reasons why you
    #see some classes without (object) or any other class between brackets is beyond the scope
    #of this answer.

    def get_number_of_wheels(self):
        return 4

    def get_engine(self):
        return CarEngine(fuel=30)

class RaceCar(Car):
#Racecar is a subclass of Car
    def get_engine(self):
        return RaceCarEngine(fuel=50)

my_car = Car() #create a new Car instance
desired_car = RaceCar() #create a new RaceCar instance.
my_car.get_engine() #returns a CarEngine instance
desired_car.get_engine() #returns a RaceCarEngine instance

my_car.get_number_of_wheels() #returns 4.
desired_car.get_number_of_wheels() # also returns 4! WHAT?!?!?!

rawDescription: What' the meaning of the brackets in the class?


code: [['Host', 'www.perdu.com'], ['Connection', 'keep-alive'], ['Cache-Control', 'max-age=0'], ['Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8'], ['User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36'], ['DNT', '1'], ['Accept-Encoding', 'gzip,deflate,sdch'], ['Accept-Language', 'en-US,en;q=0.8,es;q=0.6,fr;q=0.4'], ['']]

rawDescription: Split list with colon seperated items into list of tuples


rawDescription: Is there an efficient way of generating numbers with repeated digits in Python?


rawDescription: Reusable library to get human readable version of file size?


code:
# settings.py
CACHES = {
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379:1',
    }
}

rawDescription: Django connection to Redis

description: Django connection to Redis


code: norm = colors.Normalize()

rawDescription: Normalizing Colormap Used by Facecolors in Matplotlib


code:
reg = re.escape(reg)
pat = re.compile(reg)

rawDescription: Ignore special characters when creating a regular expression in python


rawDescription: get slice from multi-dimensions in python

description: Get slice from multi-dimensions in python


rawDescription: Simulating a key press event in Python 2.7


rawDescription: Is there any fastest way to execute For loops in python?


code:
class SwitchBoard(object):
    def __init__(self, num_switches):
        # create a dict of {number: state} key-values
        self.switches = {i: False for i in range(num_switches)}

    def flip(self, num):
        # test for the number being one of the dict's keys
        if num in self.switches:
            if self.switches[num]:
                print("Lightswitch %s was on!" % num)
            else:
                print("Lightswitch %s was off!" % num)
            # flip the value
            self.switches[num] = not self.switches[num]
        else:
            print("Lightswitch %s does not exist!" % num)

    def flip_every_nth(self, n):
        for i in range(0, len(self.switches), n):
            self.flip(i)

x = SwitchBoard(8)
x.switches
x.flip(1)
x.flip(3)
x.flip(1)
x.flip(10)
x.switches
x.flip_every_nth(3)

rawDescription: Assigning boolean values to integer

description: Assigning boolean values to integer


code:
from collections import Counter
p1_conns = Counter(('a','a','a','a','a','b','b','b','b','c','c'))
p2_conns = Counter(('b','c','d','e','f','c','a','e','d','e','f'))
p1_conns & p2_conns
sorted(p1_conns & p2_conns)
len(p1_conns & p2_conns)

rawDescription: Find maximum # of connections between 2 people


code: django-admin --version;

rawDescription: Automated Installation of Django Using Shell Script


code:
my_array = np.array([0, 1, 2, 3, 4, 5, 6])
my_dict2 = {'group_a': my_array[0:1], 'group_b': my_array[1:]}
my_dict2
my_array[0] = 200
my_dict2

rawDescription: Numpy - retaining the pointer when referencing a single element


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

driver = webdriver.Chrome()  # CHANGEME
driver.get('http://www.quora.com/Kevin-Rose')
element = WebDriverWait(driver, 2).until(
    EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Followers"))
)
element.click()

rawDescription: Finding element with explicit wait using selenium webdriver in python


rawDescription: How to manipulate digits within an integer/string?

description: Manipulate digits within an integer/string


code:
doc = etree.fromstring(text)
combine_elements(doc, ' / '.join)

rawDescription: Combine value of similar tags to one tag


rawDescription: xpath search attribute with part of string

description: Xpath search attribute with part of string


rawDescription: Trouble pivoting / reshaping a pandas dataframe


code:
if 'test' in COMMAND_LINE_TARGETS:
    runTestsCmd = env.Command('runTests', None, Action(runTests, "Running tests"))
    AlwaysBuild(runTestsCmd)
    Alias('test', runTestsCmd)

rawDescription: Call nosetests as a scons task.

description: Call nosetests as a scons task.


code:
tupleli = [('2011-09-2%s' % i, i) for i in range(5)]
tupleli
dt = dtype=[('start date', '|S11'), ('n', np.int64)]
dt

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code: [d[searchtitle] for d in lst if searchtitle in d]

rawDescription: How to find dict value by Key in list

description: Find dict value by Key in list


code:
import time

time.sleep(50)

rawDescription: Run a python script independently when a method is called


code: good

rawDescription: How to get a word bounded between `word' with regex? python

description: Get a word bounded between `word' with regex? python


code:
@property
def X(self):
    return self.A
@x.setter
def X(self, value):
    self.A = value
@x.deleter
def X(self):
    del self.A

rawDescription: Two classes with a structurally identical method but one differently named variable


code:
def compare(s1, s2):
    if not s2:
        return True
    elif s2[0] in s1:
        return compare(s1, s2[1:])
    else:
        return False

rawDescription: string recursion problems

description: String recursion problems


code: string = repr(uni)

rawDescription: Python 2.7, how to assign the "unicode literal representation" of a unicode instance to an str instance?


code: [f for d in dirs for f in os.listdir(d) if os.path.isfile(os.path.join(d, f))]

rawDescription: Using enumurate value of second for in list comprehension


code:
from itertools import islice
iterator = (x for x in ('a', 'b', 'c', 'd', 'e'))
tuple(islice(iterator, 3))

rawDescription: Assign next n iterations to tuple

description: Assign next n iterations to tuple


rawDescription: Pyinstaller: cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle


rawDescription: python3 How do I identify / handle unwanted unicode from scraped web page?

description: Python3 How do I identify / handle unwanted unicode from scraped web page


code:
for key in set(file1) & set(file2):
    result[file1[key]] = file2[key]

rawDescription: Text processing with two files

description: Text processing with two files


code:
# Fetch all labels and things:
labels = list(Label.objects.all())
things = list(Thing.objects.all())
# Fetch all label-thing pairs:
labels_of = defaultdict(lambda: [])
for pair in Thing.labels.through.objects.filter(label__in=labels):
    labels_of[pair.thing_id].append(pair.label_id)
# Put everything together:
data = {}
data['labels'] = [model_to_dict(label) for label in labels]
data['things'] = []
for thing in things:
    thing_dict = model_to_dict(thing, exclude='labels')
    thing_dict['labels'] = labels_of[thing.id]
    data['things'].append(thing_dict)

rawDescription: django many-to-many field: prefetch primary keys only

description: Django many-to-many field: prefetch primary keys only


code:
import zlib
zlib.compress('foo')[:3]
zlib.compress('bar')[:3]
s = 'serve as the indispensable'
len(s)
len(zlib.compress(s))-3

rawDescription: Writing 3,795,790,711 unique key:value pairs to redis


code:
of = open(sys.argv[1], 'ab')
for arg in sys.argv[2:]:
    val = int(arg)
    for b in (val/100, val%100):
        of.write(chr(int(str(b), base=16)))

rawDescription: binary file editing using python script

description: Binary file editing using python script


code:
import urlib2

response = urllib2.urlopen('http://example.com/some/path/', {'myvar': 'myvalue'})

rawDescription: in need of a simple example that shows serverside python program passing data to webserver

description: In need of a simple example that shows serverside python program passing data to webserver


rawDescription: Pandas: Compress Column Names to Cell Values where True


code:
import random
import string
def generateRandomString(size):
    return(''.join(random.choice(string.ascii_letters) for i in range(size)))

rawDescription: Generating random string of seedable data


code: findall("%s.*" % re.escape(name), info)[0]

rawDescription: python 2.2 find string after linebreak

description: Python 2.2 find string after linebreak


code:
import itertools
import random
import time

a = ["google.com", "yahoo.com", "gmail.com"]
combs = list(itertools.combinations(a, 2))
random.shuffle(combs)
for c in combs:
    print(c)
    time.sleep(3600)

rawDescription: Time based rotation

description: Time based rotation


code:
def __next__(self):
    res = next(self.items)
    self.count += 1
    return res

rawDescription: Establishing the number of values yielded by a generator


code:
iList1
iList2

rawDescription: How should I break a list of tuples so that it forms lists with same keys?


code:
import pandas as pd

def read_multiheader(filepath_or_buffer, num_header_rows=2, encoding=None):
    from pandas.io.common import get_filepath_or_buffer
    filepath_or_buffer, _ = get_filepath_or_buffer(filepath_or_buffer, encoding)
    df = pd.read_table(filepath_or_buffer, sep='\s*[|]\s*', header=None)
    columns = df.iloc[:num_header_rows]
    columns = columns.fillna('')
    columns = pd.MultiIndex.from_arrays(columns.values.tolist())
    df = df.iloc[num_header_rows:]
    df.columns = columns
    return df

df = read_multiheader('data')
df2 = read_multiheader('data2')
newdf = pd.concat([df2, df], axis=1)
print(newdf)

rawDescription: Removing "unnamed: #" when writing to CSV using pandas


code:
arr = np.arange(50).reshape(10, 5); arr
win_size = 5
isize = arr.itemsize; isize

rawDescription: n-dimensional sliding window with Pandas or Numpy

description: N-dimensional sliding window with Pandas or Numpy


code: AUTH_USER_MODEL = 'customauth.MyUser'

rawDescription: Django Abstract BaseUser

description: Django Abstract BaseUser


rawDescription: Lists, conditionals and loops don't give the result expected


code:
def lowest_z(obj):
    return min(p.z for p in obj.point_array)

sorted(list_of_objects, key=lowest_z)

rawDescription: Python, sort a list of objects by lowest sub-object attribute


rawDescription: Python: Deleting Specific value from the list


code: ['subject', 'filer, subject', 'filer', 'activity, subject']

rawDescription: Filter a tuple with another tuple in Python


code:
example1.com
example2.com

rawDescription: How to specify hosts list or roledefs in text file (instead of code)?

description: Specify hosts list or roledefs in text file (instead of code)


rawDescription: Is there a in built method from python csv module to enumerate all possible value for a specific column?


rawDescription: Numpy.unique - getting output with consistent depth


code:
with open(os.path.join(self.dirname, self.filename), 'w') as filehandle:
    filehandle.write(contents)

rawDescription: wxPython New, Save, and SaveAs Methods

description: WxPython New, Save, and SaveAs Methods


code:
class ClientfileSerializer(serializers.ModelSerializer):

  owner_id = serializers.IntegerField()
  owner = ContactSerializer(read_only=True)

  class Meta():
    model = Clientfile
    fields = (
      'id',
      'owner_id',
      'owner',
    )

rawDescription: Django Rest Framework nested resource key "id" unaccessible


code:
from flask import Flask
from extensions import celery, db

def create_app():
    app = Flask()

    #configure/initialize all your extensions
    db.init_app(app)
    celery.init_app(app)

    return app

rawDescription: How to use Flask-SQLAlchemy in a Celery task

description: Use Flask-SQLAlchemy in a Celery task


code:
nmf_model.fit(A);
H = nmf_model.components_.T;

rawDescription: Nonnegative matrix factorization in Sklearn


code:
def prepopulate(self):
    engine = create_engine('sqlite:////' + self.__dbpath)
    if self._train_set:
        trainset.Base.create_all(engine)
    else:
        testset.Base.create_all(engine)
    self.__prepopulated = True

rawDescription: Accessing SQLalchemy from a class

description: Accessing SQLalchemy from a class


rawDescription: Python: numpy/pandas change values on condition


code: data.shape = shape

rawDescription: Read flat list into multidimensional array/matrix in python


code:
import operator
sorted(dictionary.items(), key=operator.itemgetter(1))

rawDescription: How do I iterate over a Python dictionary, ordered by values?

description: Iterate over a Python dictionary, ordered by values


code:
import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()

rawDescription: Calling a function of a module from a string with the function's name in Python


code: qconf -mc

rawDescription: Sun Grid Engine, force one job per node

description: Sun Grid Engine, force one job per node


code: marker = xrange(10, 100, 10)

rawDescription: Getting indices for certain percent of a length of a list


code:
class FontWeight():
    from com.sun.star.awt.FontWeight import (NORMAL, BOLD,)

Text_Bold = FontWeight.BOLD
Text_Normal = FontWeight.NORMAL
cursor.CharWeight=Text_Bold

cursor.CharWeight=Text_Normal

rawDescription: How do I insert text as Italic or Bold etc with a python macro in libreoffice writer

description: Insert text as Italic or Bold etc with a python macro in libreoffice writer


code: ['Theone Normalperson', 'Someone Middlename MacIntyre', 'Jack Really Awesome']

rawDescription: Using Regex to 'Clean Up' a List of Names


code:
df = s.reset_index()
df
del df[1]
df

rawDescription: Pandas reset index on series to remove multiindex


rawDescription: Conditional dataframe calculations based on a columns suffix


code:
import numpy as np
import time
import itertools

def cartesian(arrays, out=None):
    ...

def test_numpy(arrays):
    for res in cartesian(arrays):
        pass

def test_itertools(arrays):
    for res in itertools.product(*arrays):
        pass

def main():
    arrays = [np.fromiter(range(100), dtype=int), np.fromiter(range(100, 200), dtype=int)]
    start = time.clock()
    for _ in range(100):
        test_numpy(arrays)
    print(time.clock() - start)
    start = time.clock()
    for _ in range(100):
        test_itertools(arrays)
    print(time.clock() - start)

if __name__ == '__main__':
    main()

rawDescription: Numpy equivalent of itertools.product

description: Numpy equivalent of itertools.product


code: z = [i for i, thing in enumerate(objects) if thing.bar == '$']

rawDescription: Short way to extract sublist from list in python by given conditions


code:
import  requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get("http://oilprice.com/Latest-Energy-News/World-News").content)
main_div = soup.select_one("div.tableGrid__column.tableGrid__column--articleContent.category")

divs = main_div.select('div.categoryArticle__content')

print([(d.select_one("p.categoryArticle__meta").text, d.a["href"]) for d in divs])

rawDescription: Python and beautifulSoup: scraping two values - url and date and having the return results paired


code:
import regex
regex.findall("[[:alnum:]]+", "hello_there1 A2... bl3h")
#>>> ['hello', 'there1', 'A2', 'bl3h']

rawDescription: Python: finding sequences in string

description: Python: finding sequences in string


code:
t1.start()
t2.start()

rawDescription: How to run 2 different processes at once in Python

description: Run 2 different processes at once in Python


code:
def __str__(self):
    solved, solution = self.solveIt()
    return '{}\n{}'.format(len(self.seq),
                           ','.join(map(str, solution)))

rawDescription: Turning my function into a class

description: Turning my function into a class


code: g_tree.node[obj_id]['name'] = obj_name

rawDescription: Unable to generate network data in tree format while retaining node attributes


code:
from bs4 import BeautifulSoup, SoupStrainer

parse_only = SoupStrainer(id=["first", "third", "loner"])
soup = BeautifulSoup(my_document, "html.parser", parse_only=parse_only)

rawDescription: How to get "subsoups" and concatenate/join them?

description: Get "subsoups" and concatenate/join them


code:
Model1.objects.raw('''SELECT *, @row := @row + 1 AS row
                   FROM myapp_model1
                   JOIN (SELECT @row := 0) rowtable
                   INNER JOIN myapp_model2
                   ON myapp_model1.field = myapp_model2.field
                   AND ...''')

rawDescription: Most efficient way to use the django ORM when comparing elements from two lists


rawDescription: Subtracting 12 when the sum of two variables is greater or equal to 12


code:
x = "moonshot"
y = list(x)
y
z = y.sort()
z
type(z)
sorted(x)

rawDescription: Anagram Function Returning None

description: Anagram Function Returning None


code:
result = []
for i1 in l1:
    for i2 in l2:
        result.append("{}{}".format(i1, i2))
result

rawDescription: Concat each element of list with each element of second list


code: [a] + list(d)

rawDescription: Concatenate a list with a list of lists

description: Concatenate a list with a list of lists


code:
s = "HowAre\nyouDoing"
s
s.replace("\n", "")

rawDescription: operate with python '\' special character in a string

description: Operate with python '\' special character in a string


code:
a = ['spam']
b = a[:]
b
a is b

rawDescription: How to copy boost python list or his reference with "=" operator

description: Copy boost python list or his reference with "=" operator


code:
dates = speed['created_time'].dt.normalize()
speed['reached_date'] = dates + speed['reached_time']
speed['diff'] = speed['created_time'] - speed['reached_date']

rawDescription: pandas date column subtraction

description: Pandas date column subtraction


code:
class StructWithSlots(object):
    __slots__ = []
record = StructWithSlots()
record.number = 3
record.__dict__

rawDescription: Why do Python's empty classes and functions work as arbitrary data containers, but not other objects?


code: [''.join(v) for k, v in itertools.groupby(a)]

rawDescription: Split if two consecutive characters are not same


code: getHashValue(filename, hashlib.md5)

rawDescription: Unable to pass a variable to function

description: Unable to pass a variable to function


code:
from django.utils.text import slugify

class ProductAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # don't overwrite manually set slug
        if form.cleaned_data['slug'] == "":
            obj.slug = slugify(form.cleaned_data['brand']) + "-" + slugify(form.cleaned_data['name'])
        obj.save()

rawDescription: How do I customize a slug field in Django?

description: Customize a slug field in Django


code: val_pivot_df = val_df.pivot(index='lat', columns='lon', values='b_value')

rawDescription: restructuring pandas dataframe into meshgrid for basemap

description: Restructuring pandas dataframe into meshgrid for basemap


code:
import imp
import sys

f, pathname, desc = imp.find_module('logging', sys.path[1:])
logging = imp.load_module('logging', f, pathname, desc)

rawDescription: Importing a file with the same name as the file you're in


code:
fp = open('file.txt', 'rb')

for i in range(1,101):
    fname = 'file'+ str(i) +'.txt'
    fp.seek(0)
    ftp.storbinary('STOR ' + fname, fp)

fp.close()

rawDescription: Python read file into memory for repeated FTP copy


code:
from Tkinter import *
import os
import threading

def CONVERT():
    numlines = len(chatbox.get("1.0",END).splitlines())
    if numlines > 2:
        chatbox.delete("1.0",END)
        chatbox.insert(INSERT,"Console: Limit Reached, Chat Wiped" + "\n")
    chatbox.insert(INSERT,"You: "+USER_ENTRY.get()+ "\n")
    INPUT_BOX.set("")

chat = Tk()
chat.title("Net Send Client [0.4]")
chat.geometry('550x500+200+200')

title = StringVar()
title.set("Net Send Chat\n Type in box to send.")
title_widget = Label(chat,textvariable = title, height = 4)
title_widget.pack()

INPUT_BOX = StringVar()
USER_ENTRY = Entry(chat,textvariable = INPUT_BOX)
USER_ENTRY.pack(side=TOP, padx = 10, pady = 20)

send_button = Button(chat, text="Send",width = 20, command = CONVERT)
send_button.pack(padx = 10, pady = 10)

chatbox = Text(width = 60, height = 15, relief = SUNKEN)
left = Frame(chatbox)
right = Frame(chatbox)
s_start = Scrollbar(right)
s_start.pack(side=RIGHT)

chatbox.grid(row = 0, column = 0, columnspan = 3)
chatbox.pack()

chat.mainloop()

rawDescription: Thread designed to delete Tkinter Text Widget Content does not operate.


code: # \rApples: 1\rBananas: 1\rPineapples: 1\r\r

rawDescription: Appending to a line

description: Appending to a line


code:
import sys
sys.getsizeof(s)

rawDescription: How to get the size of a string in Python?

description: Get the size of a string in Python


code:
def is_float(x):
    try:
        float(x)
        return True
    except ValueError:
        return False
lis = ['fun','3.25','4.222','cool','82.356','go','foo','255.224']
[x for x in lis if not is_float(x)]

rawDescription: How to check float string?

description: Check float string


code:
merged = pd.merge(a, b, on='id')
matching = merged[(merged.left == merged.left_and_right) | (merged.right == merged.left_and_right)]
(matching.groupby(['id', 'left', 'right'])['boolen'].sum()).reset_index()

rawDescription: Conditional multi column matching (reviewed with new example)


code: {{ lines|linebreaksbr }}

rawDescription: How can display the lines from linux log file in browser


code:
def add_sizes(l):
    return map(lambda x:(x,len(x)),l)

rawDescription: Transforming a string in a list

description: Transforming a string in a list


rawDescription: Python Lists input- Integers and Strings


code: X

rawDescription: Creating a X input matrix and y output vector via Python


rawDescription: Python Regex for alpha(alpha|digit)*

description: Python Regex for alpha(alpha|digit)*


code:
x = T.fscalar()
y = T.fvector()
z = T.concatenate([x.reshape((1,)), y.reshape((-1,))])

e = (z ** 2).sum()
g = T.grad(e, wrt=x)

ff = theano.function([x, y], [e, g])

rawDescription: theano (python): elementwise gradient

description: Theano (python): elementwise gradient


code:
db.letter.opening.widget = suggest_widget(db.receiver.opening,
                                          limitby=(0,10), min_length=1, db=db(db.i2l_receiver_profile.user_id==auth.user_id))

rawDescription: web2py Autofilling/autocomplete returns id

description: Web2py Autofilling/autocomplete returns id


code:
import xml.etree.ElementTree as ET

content='''<network_objects>
<network_object>
<Name>Test_Group_A</Name>
<Class_Name>network_object_group</Class_Name>
<members>
  <reference>
    <Name>Host1</Name>

network_objects

  </reference>
  <reference>
    <Name>Host2</Name>

network_objects

  </reference>
  <reference>
    <Name>Host3</Name>

network_objects

  </reference>
  <reference>
    <Name>Host4</Name>

network_objects

  </reference>
  <reference>
    <Name>Host5</Name>

network_objects

  </reference>
  <reference>
    <Name>Host6</Name>

network_objects

  </reference>
</members>
</network_object>
</network_objects>
'''

rawDescription: Python Looping with etree

description: Python Looping with etree


code:
class LongListAsTextField(with_metaclass(models.SubfieldBase, models.TextField)):

    def to_python(self, value):
        if isinstance(value, list):
           return value

        return [
            long(val)
            for val in value.split(',')
            if val.isdigit()
        ]

    def get_prep_value(self, value):
        return ','.join([str(val) for val in value])

rawDescription: I have a list of long integers that I assign to a django model charfield. The list of longs get converted to list of unicodes


rawDescription: Implementing Google's DiffMatchPatch API for Python 2/3


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup('''

..

...

...

...

''', ['lxml','xml'])

for tr in soup.select('table > tr'):
    print(tr)
    print('---')

rawDescription: Python BeautifulSoup Find Siblings

description: Python BeautifulSoup Find Siblings


code:
msg=MIMEText("""The nightly build status was a SUCCESS\n\n
    Build File: %s
    \n\n
    Build Results File: %s
    \n\n
    Sandbox Folder: %s
    \n\n
    Antibrick File: """ % (build_file,build_file,sandbox),
    antibrick,
    "\n\n"
)

rawDescription: String manipulation in Python

description: String manipulation in Python


code:
if suit in ("Diamonds","Hearts","Clubs","Spades"):
    return "Accepted"
else:
    return "Wrong input"

rawDescription: Better way, of writing a Long "if" statements?


code:
while event is not QUIT:
    event = event_queue.get(block=True)
    dispatch(event)

rawDescription: How should I get my Tkinter IRC client to continuously read data from the IRC server?


rawDescription: Finding trigrams for entire corpus with NLTK


rawDescription: How to make my SWIG extension module work with Pickle?

description: Make my SWIG extension module work with Pickle


rawDescription: Beautifulsoup: get class name for each word


code: df1.merge(df2[['member', 'time']])

rawDescription: Python/Pandas filter out unique rows from DataFrames


code:
if event.button == 3:
    if self.shift_is_held:
        do_something()
    else:
        do_something_else()

rawDescription: matplotlib: How to pick up shift click on figure?

description: Matplotlib: How to pick up shift click on figure


code:
import os.path
os.path.exists(str)

rawDescription: how to verify a hash in python?

description: Verify a hash in python


code:
def test(a):
    ''' Always returns a 3-tuple, composed of Flag,data,data. Data may be None '''
    if a > 0:
        return True, None, None
    else:
        return False, 123, 'foo'

flag,data1,data2 = test(a)

rawDescription: Handy return values in Python

description: Handy return values in Python


code:
urlpatterns = patterns('',
   url(r'^blogposts$', resource_here, { 'emitter_format': 'text' }),
)

rawDescription: How do I use Django piston to return a response in text/plain?

description: Use Django piston to return a response in text/plain


code:
def select_for_update(self, **kwargs):
    """
    Returns a new QuerySet instance that will select objects with a
    FOR UPDATE lock.
    """
    # Default to false for nowait
    nowait = kwargs.pop('nowait', False)
    obj = self._clone()
    obj.query.select_for_update = True
    obj.query.select_for_update_nowait = nowait
    return obj

rawDescription: select_for_update kind of functionality in django 1.3 to avoid race condition

description: Select_for_update kind of functionality in django 1.3 to avoid race condition


code:
a = soup.select_one("div.address > a")
" ".join(a.find_all(text=True)).strip()

rawDescription: BS4 How to get text without using .text?

description: BS4 How to get text without using .text


code:
def thread_main():
    while True:
        (quit, data) = work_queue().get()
        if quit: break
        do_work(data)

rawDescription: Difference between thread.join and thread.abort in python multithreading


code:
A=np.random.randint(5,size=(10,3))
A
B=np.random.randint(10,size=2)
B
A[B,:]
A[np.random.randint(10,size=2),:]

rawDescription: Numpy: Get random set of rows from 2D array


code:
from collections import defaultdict #if on Python 3
conv = defaultdict(lambda: str)

rawDescription: force MySQLdb to treat all MySQL data as strings

description: Force MySQLdb to treat all MySQL data as strings


code: valuesNew

rawDescription: Add values in a list of tuples if one element is repeated


code: [__import__('os').fork() for i in xrange(2**64) for x in range(i)]

rawDescription: Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?


code: listofobj = [dict(zip(headers, sublist)) for sublist in listoflist]

rawDescription: How to quickly convert from items in a list of lists to list of dictionaries in python?

description: Quickly convert from items in a list of lists to list of dictionaries in python


code: taste = [b.taste for b in beers if b.name==name][0]

rawDescription: How to access an object in a list by property?

description: Access an object in a list by property


code:
from itertools import product

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', ... ,'z']
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
chars = ["!", "@", "#", "$"]

combinations = product(alphabet, numbers, chars)
generator = ({'letter': l, 'number': n, 'char': c} for l, n, c in combinations)

rawDescription: Better way to execute nested for loops to generate a dict?


code:
def sum_square_difference(n):
    r = range(1, n+1)  # first n natural numbers
    return sum(i**2 for i in r) - sum(r)**2

rawDescription: Function to calculate the difference between sum of squares and square of sums


code:
winner = None
for car in cars:
    if winner is None or car.Odometer > winner.Odometer:
        winner = car

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code: score = float(input("enter the score please"))

rawDescription: This python code calls a function that returns a value but user input is asked twice


code: bubble_up(my_heap, lambda x, y: x < y)

rawDescription: how to Pass an inequality into a function as a variable, then evaluate it?


code: import numpy;

rawDescription: optimizing low pass filter smoothing code for activity recognition

description: Optimizing low pass filter smoothing code for activity recognition


code:
with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = zip(*csv.reader(Spenn, delimiter="\t"))
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

rawDescription: Python: Searching a specific columns of a table for not matching items


code:
import re
subject = "AA BB CC DD EE FF GG HH"
reobj = re.compile(r"(?=((((\b\S+)(?: \S+)?)(?: \S+)?)(?: \S+)?))")
result = reobj.findall(subject)
tokens = set()
for a in result:
    for b in a:
        tokens.add(b)
print(tokens)

rawDescription: Use python regex to match all possible groups of 1, 2, 3, and 4 words


rawDescription: Finding the difference between two numpy structured arrays


code:
from sqlalchemy import event
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import create_session
from sqlalchemy.schema import Column, DDL
from sqlalchemy.types import Integer

Base = declarative_base()
engine = create_engine('sqlite:////tmp/test.db', echo=True)

class TableXYZ(Base):
    __tablename__ = 'tablexyz'
    id = Column(Integer, primary_key=True)

#event.listen(
#   Base.metadata, 'after_create',
#   DDL("""
#   alter table TableXYZ add column name text
#   """)

event.listen(
    TableXYZ.__table__, 'after_create',
    DDL("""
    alter table TableXYZ add column name text
    """)
)
Base.metadata.create_all(engine)

rawDescription: In SQLAlchemy, how do I define an event to fire DDL using declarative syntax?


code:
l4 = ['1']*10 #list of immutable objects
l4

l4[0]='0'
l4

l5 = [{1:'1'}]*10 #list of mutable objects

l5

l5[0][1] = 'ONE'

l5

rawDescription: change value in list Python

description: Change value in list Python


code:
crack_list = map(Crack, z1_values, z2_values, coeff_values)
from pprint import pprint
pprint(crack_list)

rawDescription: python: iterate using a class method

description: Python: iterate using a class method


code:
#!/usr/bin/env python
import urllib
import requests # $ pip install requests

params = {'str1': 'string1', 'str2': 'string2', 'filename': 'filename.txt'}
file = 'file content as a file object or string, etc'
url = 'http://example.com/SomeName/action.php?' + urllib.urlencode(params)
r = requests.post(url, data=file, headers={'Content-Type': 'text/plain'})
print(r.text) # response

rawDescription: send both string and buffer using httplib with python to the server

description: Send both string and buffer using httplib with python to the server


code: transform(math.e, ['cube', 'log', 'square'])

rawDescription: preserving order of function implementation

description: Preserving order of function implementation


rawDescription: Python regex - do not match word when it is in html tag


code:
from functools import reduce
from operator import mul

x = reduce(mul, [1,3,7,1,2])

rawDescription: Pythonic way of multiplying contents of list by one another in Python3


code:
def _worker(args):
    return filter_max_returning_min(*args)

def multi_main(fileglob, prefix, outputfile, processes):
    from multiprocessing import Pool
    pool = Pool(processes=processes)
    workerargs = ((fn, prefix) for fn in glob.iglob(fileglob))
    minlines = pool.imap_unordered(_worker, workerargs, processes)
    write_file(outputfile, minlines)

rawDescription: Finding minimum value of word from a lot of files in python?


code:
def intersect_range(lst, start, stop):
    start_i = bisect.bisect_left(lst, start)
    if start <= lst[start_i] < stop:
        return lst[start_i]
    else:
        return None

rawDescription: Efficiently determine if a number out of a range of subsequent numbers is in an ordered list. (in Python)


code:
for i in list2: total=total+card_value.get(i,0)

for l in list1:
   for i in l:
    total=total+card_value.get(i,0)

rawDescription: How to make a function that calculate elements in list?

description: Make a function that calculate elements in list


code:
def main():
    plt, args = handleCommandLine()   # CHANGED HERE
    fig, ax = plt.subplots(1)
    # ...

def handleCommandLine():
    p = argparse.ArgumentParser()
    p.add_argument('--backend', '-b', default=None, help='Specify plotting backend')
    args = p.parse_args()

    if args.backend != None:
        matplotlib.use(args.backend)  #Must occur before importing pyplot

    import matplotlib.pyplot as plt   #Must occur after setting backend, if desired
    return plt, args   # CHANGED HERE

rawDescription: How can I import a module into main() from a sub function?

description: Import a module into main() from a sub function


rawDescription: Regex for word exclusion in python

description: Regex for word exclusion in python


code: set = '%10f' % val

rawDescription: Pretty printing a list of list of floats?


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

d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                        'Paris', 'New York', 'New York', 'London', 'Paris'],
     'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
     'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}

df = pd.DataFrame(d)
groups = df.groupby(['City'])
for city, grp in groups:                           # 1
    fig, ax = plt.subplots(figsize=(5, 4))
    grp.plot(kind='scatter', x='Age', y='Weight',  # 2
             ax=ax)

    plt.show()

rawDescription: Pandas for loop on a group by

description: Pandas for loop on a group by


rawDescription: is it possible to create a list of lists on a recursive function?

description: Is it possible to create a list of lists on a recursive function


code:
results = []
for value in values:
    results.append(value)

rawDescription: How to create an array with size increasing with the iteration

description: Create an array with size increasing with the iteration


code:
def sum_func(func, pred):
    return sum(takewhile(pred, (func(i) for i in count(1))))

rawDescription: Sum while in Python?

description: Sum while in Python


code:
import csv

def readcountries():
    with open("countries.txt") as fh:
        reader = csv.reader(fh, skipinitialspace=True)
        rows = [[n, float(a), int(p)] for n, a, p in reader]

rawDescription: python binary search and file i/o

description: Python binary search and file i/o


code:
from gmpy2 import xmpz
a=xmpz(7)
bin(a)
a[48]=1
bin(a)

rawDescription: getting 64 bit integer in python

description: Getting 64 bit integer in python


code:
import collections
import json

myfiles = '''
    a/b/c/d/e/file1
    a/b/c/d/e/file2
    a/f/g/h/i/file3
    a/f/g/h/i/file4
'''

# Convert to a list
myfiles = myfiles.split()

def recursive_dict():
    """
    This function returns a defaultdict() object
    that will always return new defaultdict() objects
    as the values for any non-existent dict keys.
    Those new defaultdict() objects will likewise
    return new defaultdict() objects as the values
    for non-existent keys, ad infinitum.
    """
    return collections.defaultdict(recursive_dict)

def insert_file(mydict, fname):
    for part in fname.split('/'):
        mydict = mydict[part]

    # If you want to record that this was a terminal,
    # you can do something like this, too:
    # mydict[None] = True

topdict = recursive_dict()
for fname in myfiles:
    insert_file(topdict, fname)

print(json.dumps(topdict, sort_keys=True,
                indent=4, separators=(',', ': ')))

rawDescription: How to convert a file path into treeview?

description: Convert a file path into treeview


code: permNums([[]])

rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


rawDescription: large filesize difference between `pandas to_json` and `read_json`

description: Large filesize difference between `pandas to_json` and `read_json`


code:
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  LPARAM(PChar('Environment')), SMTO_ABORTIFHUNG, 5000, MsgResult);

rawDescription: How to notify Python from an Inno Setup that the environment path has changed?

description: Notify Python from an Inno Setup that the environment path has changed


code:
from itertools import izip_longest as izip_l, chain, repeat
expanded = [repeat(k, config[k]) for k in config]

rawDescription: distribute a list in python

description: Distribute a list in python


code: sorted(lst, key=lambda s: s.lower())

rawDescription: case-insensitive list sorting, without lowercasing the result?

description: Case-insensitive list sorting, without lowercasing the result


rawDescription: Parsing IMAP Email BODYSTRUCTURE for Attachment Names


code:
tupList = [(2,16), (4, 42), (3, 23)]
sorted(tupList, key = lambda tup: tup[1])
print(tupList)

rawDescription: Sorting tuples by element value in Python


code:
list_obj_array = np.ndarray((1,), dtype=object)
list_obj_array[0] = [1,2,3]
f2(X,list_obj_array)  # using your definition from above

rawDescription: Numpy vectorize, using lists as arguments


rawDescription: Python Sqlalchemy: Filter by datediff of months


code:
p1 = np.einsum('i,ijkl->jkl',B,X_u)#OUT_DIM - (k,N,nS)
sol = np.einsum('ijkl,j->il',X_r*p1[None,:,:,:],k)#OUT_DIM (3,nS)

rawDescription: Fastest way to use Numpy - multi-dimensional sums and products


code: ['aaron', 'charlie']

rawDescription: How do I create a list as a dictionary entry for a specific key in Python?

description: Create a list as a dictionary entry for a specific key in Python


code: ''.join( "%"+i+s[n+1] for n,i in enumerate(s)  if n%2==0 )

rawDescription: Turn a hex string into a percent encoded string in Python


code:
for product in multiplicative_partitions((2, 3), (3, 1)):
    print('*'.join(map(str, product)))

rawDescription: How can I generate all possible divisor products for a number?

description: Generate all possible divisor products for a number


code:
def crossover(self):
    new_population = []

    for x in range(0,20):
        z=random.choice(self.population)
        y=random.sample(z,3)
        x=random.choice(self.population)
        w=random.sample(x,3)
        v=y+w

        new_population.append(v)

    self.population = new_population
    print(self.population)

rawDescription: updating a list in python

description: Updating a list in python


code:
from Tkinter import Tk, Frame, Button

def translate(event):
    if event.widget["text"] in monthdict.keys():
        event.widget.config(bg="Red", text=monthdict[event.widget["text"]])
    else:
        for key, val in monthdict.iteritems():
           if val in event.widget["text"]:
               event.widget.config(bg="Blue", text=key)

root = Tk()
mainframe = Frame(root)
mainframe.pack()
monthdict = {"January": "Enero", "February": "Febrero", "March": "Marzo"}
buttondict = {}

for key in monthdict.keys():
    buttondict[key] = Button(mainframe, text=key, bg="Blue")
    buttondict[key].bind("<Button-1>", translate)
    buttondict[key].pack()

root.mainloop()

rawDescription: How can I optimize my code for my Spanish Translation Program?

description: Optimize my code for my Spanish Translation Program


code:
def _sphere_getattr(self, name):
    if name=='python_data':
         self.__dict__[name]=self.make_python_data()
         return self.__dict__[name]
    else:
        raise AttributeError
Sphere.__getattr__ = _sphere_getattr

rawDescription: Swig and Python - different object instantation


code:
def traverse(directory, callback=process, file_type="txt"):
    for dirpath, dirnames, filenames in os.walk(directory):
        for f in filenames:
            path = os.path.abspath(os.path.join(dirpath, f))
            if path.endswith(file_type):
                callback(path)

rawDescription: How can I make this python script walk through a directory tree?

description: Make this python script walk through a directory tree


rawDescription: Avoid exec in instance variable definition


code:
def parseBirthday():
    type, data = Lexer.next_token()
    if type == Lexer.DATE: # 1, 3 & 4
        date = data
        type, data = Lexer.next_token()
        if type == Lexer.COLON or type == Lexer.COMMA: # 1 & 4
            person = parsePersonInPluralForm()
            type, data = Lexer.next_token()
            if type != Lexer.BIRTHDAY: raise ParseError()
        elif type == Lexer.BIRTHDAY: # 3
            type, data = Lexer.next_token()
            if type != Lexer.OF: raise ParseError()
            person = parsePerson()
    elif type == Lexer.STRING: # 2 & 5
        Lexer.keep(type, data)
        person = parsePersonInPluralForm()
        type, data = Lexer.next_token()
        if type != Lexer.BIRTHDAY: raise ParseError()
        type, data = Lexer.next_token()
        if type == Lexer.COMMA: # 2
            type, data = Lexer.next_token()
        if type != Lexer.DATE: raise ParseError()
        date = data
    else:
        raise ParseError()
    return person, date

rawDescription: lexical analyse or series of regular expressions to parse unstructured text into structured form

description: Lexical analyse or series of regular expressions to parse unstructured text into structured form


code:
creds = pika.PlainCredentials(**creds)
params = pika.ConnectionParameters(credentials=creds,
                                   **conn_params)
try:
    connection = pika.BlockingConnection(params)
    LOG.info("Connection to Rabbit was established")
    return connection
except (ProbableAuthenticationError, AuthenticationError):
    LOG.error("Authentication Failed", exc_info=True)
except ProbableAccessDeniedError:
    LOG.error("The Virtual Host configured wrong!", exc_info=True)
except ChannelClosed:
    LOG.error("ChannelClosed error", exc_info=True)
except AMQPConnectionError:
    LOG.error("RabbitMQ server is down or Host Unreachable")
    LOG.error("Connection attempt timed out!")
    LOG.error("Trying to re-connect to RabbitMQ...")
    time.sleep(reconnection_interval)
    # <here goes your reconnection logic >

rawDescription: RabbitMQ Message/Topic Receiver Crashing when RabbitMQ is not running


code:
output = {}
for key in dict1.keys() & dict2.keys():
    output.setdefault(dict1[key], []).append(dict2[key])

rawDescription: Match two dictionaries by key and return array of values


rawDescription: SA: can I have a 'year' column_property for a Date column?


code:
import re

with open('Output2.txt') as f:
    doc = f.read()

item7 = r"Item 7\.*\s*Management.s Discussion and Analysis of Financial Condition and Results of Operations"
item8 = r"Item 8\.*\s*Financial Statements"

discussion_pattern = re.compile(
    r"(?P<item7>" + item7 + ")"
    r"([\S\s]*)"
    r"(?P<item7heading>" + item7 +")"
    r"(?P<discussion>[\S\s]*)"
    r"(?P<item8heading>" + item8 + ")"
)

match = re.search(discussion_pattern, doc)
discussion = match.group('discussion')

rawDescription: Python: Using regex to find the last pair of occurence


code: filename = u"ad\nbla'{-+\)(ç?"

rawDescription: Create (sane/safe) filename from any (unsafe) string


code:
try:
    float(element) # int may also work depending on your data
except ValueError:
    pass

rawDescription: In pure python (no numpy, etc.) how can I find the mean of certain columns of a two dimensional list?


code:
a
m
N
out

rawDescription: numpy mask array limiting the frequency of masked values

description: Numpy mask array limiting the frequency of masked values


code:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
import scipy.sparse as sparse

a_matrix = sparse.rand(10, 10, format='coo', density=0.8)

G = bipartite.from_biadjacency_matrix(a_matrix, create_using=None,
                                         edge_attribute='weight')
X, Y = bipartite.sets(G)
pos = dict()
pos.update((n, (0, i*10)) for i, n in enumerate(X))
pos.update((n, (0.5, i*10)) for i, n in enumerate(Y))
num_edges = G.number_of_edges()
num_nodes = G.number_of_nodes()
nx.draw(G, pos=pos, with_labels=True,
        edge_color=np.random.random(num_edges),
        edge_cmap=plt.get_cmap('Blues'),
        node_color=np.random.random(num_nodes),
        cmap=plt.get_cmap('Reds'))
plt.show()

rawDescription: How to change colours of nodes and edges of bipartite graph in networkX?

description: Change colours of nodes and edges of bipartite graph in networkX


code:
df = readObs(indir, filename)
df.set_index(['%_GPST', 'satID'])

rawDescription: Reading GPS RINEX data with Pandas

description: Reading GPS RINEX data with Pandas


code: any(d.get('a', None) == 5 for d in array)

rawDescription: How to check whether a (key, value) pair is in a array which includes lots of dictionaries in Python

description: Check whether a (key, value) pair is in a array which includes lots of dictionaries in Python


code:
class Quantity(object):

    def __init__(self, value, unit):
        self.unit = unit
        self.value = value

    def __getitem__(self, key):
        return Quantity(self.value[key], unit=self.unit)

    def __len__(self):
        return len(self.value)

    def __array__(self):
        return self.value

rawDescription: How to prevent Numpy from splitting up an array-like object

description: Prevent Numpy from splitting up an array-like object


code:
import re
s = '
breakeven volume (BEV), 28
'
re.sub(r'page(\d+)">\1', lambda m: 'page{0}">{0}'.format(int(m.group(1)) - 1), s)

rawDescription: Find numbers in a string and decrement them


code: apply(f,args,kwargs)

rawDescription: Python multiprocessing.Pool: when to use apply, apply_async or map?


code:
index = pd.date_range('20/10/2014', '22/10/2014')
multi_index = pd.MultiIndex.from_product([index, ['red', 'yellow']])
df.reindex(multi_index)

rawDescription: Re-index dataframe by new range of dates


code:
def listcomp_throwaway():
    [examplefunc(i) for i in range(100)]

def forloop_throwaway():
    for i in range(100):
        examplefunc(i)

rawDescription: Why list comprehension can be faster than map() in Python?


code:
from cStringIO import StringIO

sheet = book.add_sheet('Sheet1')
buf = StringIO()
buf.write('Put me')
if some_condition:
   buf.write(' in same cell')

sheet.write(1, 1, buf.getvalue())

rawDescription: how to append particular excel cell value using python?

description: Append particular excel cell value using python


rawDescription: Removing length 1 dimensions in arrays

description: Removing length 1 dimensions in arrays


code:
from lxml import etree

xml = """<FOO xmlns="SOME_REALLY_LONG_STRING"
 xmlns:ss="THE_VERY_SAME_REALLY_LONG_STRING_AS_ROOT"
>
    <child_of_foo>
        ....
    </child_of_foo>
    ...
    <SomethingIWant ss:Name="bar">
        ....
    </SomethingIWant>
    ...
</FOO>"""

root = etree.fromstring(xml)
ns = {'ss': 'THE_VERY_SAME_REALLY_LONG_STRING_AS_ROOT'}

# i want just the first one for now
result = root.xpath('//@ss:Name', namespaces=ns)[0]
print(result)

rawDescription: How to get an attribute of an Element that is namespaced

description: Get an attribute of an Element that is namespaced


code:
from django.shortcuts import render
from .forms import ParseForm   # simple form with textarea field called markup
import mistune

class TokenTreeRenderer(mistune.Renderer):
    # options is required
    options = {}

    def placeholder(self):
        return []

    def __getattribute__(self, name):
        """Saves the arguments to each Markdown handling method."""
        found = TokenTreeRenderer.__dict__.get(name)
        if found is not None:
            return object.__getattribute__(self, name)

        def fake_method(*args, **kwargs):
            return [(name, args, kwargs)]
        return fake_method

def parse(request):
    context = {}
    if request.method == 'POST':
        parse_form = ParseForm(request.POST)
        if parse_form.is_valid():
            # parse the data
            markdown = mistune.Markdown(renderer=TokenTreeRenderer())
            tokenized = markdown(parse_form.cleaned_data['markup'])
            context.update({'tokenized': tokenized, })
            # no need for a redirect in this case

    else:
        parse_form = ParseForm(initial={'markup': 'This is a **bold** text sample', })

    context.update({'form': parse_form, })
    return render(request, 'mctests/parse.html', context)

rawDescription: parse a string multiple delimiters returning list of tuples with style and text

description: Parse a string multiple delimiters returning list of tuples with style and text


code:
4
3
True

rawDescription: numpy -- Transform non-contiguous data to contiguous data in place

description: Numpy -- Transform non-contiguous data to contiguous data in place


rawDescription: Multiply ticklabel values in colorbar when plotting matrix with imshow


code:
import numpy
ids = numpy.arange(100000000, dtype='uint32')  # 32 bits is enough for numbers up to about 4 billion
numpy.random.shuffle(ids)

rawDescription: Generate big random sequence of unique numbers


code:
from timeit import timeit
lst = list(range(1000))
timeit('list(reversed(lst))', 'from __main__ import lst')
timeit('lst[::-1]', 'from __main__ import lst')

rawDescription: Reverse a list without reversed command

description: Reverse a list without reversed command


code:
@receiver(pre_save, sender=User)
def update_username_from_email(sender, instance, **kwargs):
    user_email = instance.email
    username = user_email[:30]
    n = 1
    while User.objects.exclude(pk=instance.pk).filter(username=username).exists():
        n += 1
        username = user_email[:(29 - len(str(n)))] + '-' + str(n)
    instance.username = username

rawDescription: django-allauth set username the same as email

description: Django-allauth set username the same as email


code:
import wx

class Settings(wx.Dialog):
    def __init__(self, settings, *args, **kwargs):
        wx.Dialog.__init__(self, *args, **kwargs)
        self.settings = settings

        self.panel = wx.Panel(self)
        self.button_ok = wx.Button(self.panel, label="OK")
        self.button_cancel = wx.Button(self.panel, label="Cancel")
        self.button_ok.Bind(wx.EVT_BUTTON, self.onOk)
        self.button_cancel.Bind(wx.EVT_BUTTON, self.onCancel)

        self.checkboxes = []
        for i in range(3):
            checkbox = wx.CheckBox(self.panel, label=str(i))
            checkbox.SetValue(self.settings[i])
            self.checkboxes.append(checkbox)

        self.sizer = wx.BoxSizer()
        for checkbox in self.checkboxes:
            self.sizer.Add(checkbox)
        self.sizer.Add(self.button_ok)
        self.sizer.Add(self.button_cancel)

        self.panel.SetSizerAndFit(self.sizer)

    def onCancel(self, e):
        self.EndModal(wx.ID_CANCEL)

    def onOk(self, e):
        for i in range(3):
            self.settings[i] = self.checkboxes[i].GetValue()
        self.EndModal(wx.ID_OK)

    def GetSettings(self):
        return self.settings

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Show settings")
        self.button.Bind(wx.EVT_BUTTON, self.onSettings)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

        self.settings = [False, False, False]

    def onSettings(self, e):
        settings_dialog = Settings(self.settings, self)
        res = settings_dialog.ShowModal()
        if res == wx.ID_OK:
            self.settings = settings_dialog.GetSettings()
        settings_dialog.Destroy()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython, efficient way to create a settings dialog

description: WxPython, efficient way to create a settings dialog


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

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

plt.plot(x, y)
plt.axhline(0, color="black")
plt.axvline(0, color="black")

plt.xlim(-5, 3)
plt.ylim(-5, 3)

plt.show()

rawDescription: Show specific range in graphic

description: Show specific range in graphic


code:
import time
import unittest

class TestExampleOne(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.value = 1

    def test_one(self):
        time.sleep(1)
        self.assertEqual(1, self.value)

rawDescription: How to benchmark unit tests in Python without adding any code

description: Benchmark unit tests in Python without adding any code


code:
def isSquare(x):
    if x == 1:
        return True
    low = 0
    high = x // 2
    root = high
    while root * root != x:
       root = (low + high) // 2
       if low + 1 >= high:
          return False
       if root * root > x:
          high = root
       else:
          low = root
    return True

rawDescription: Finding if a number is a perfect square

description: Finding if a number is a perfect square


code:
def helper():
    bar = get_some_value()
    yield bar
    save(bar)

def foo():
  do_something()
  yield from helper()
  do_something_else()
  # more code in between
  yield from helper()
  # finishing up

rawDescription: Code duplication in generator functions in Python


rawDescription: Python Pandas Lookup/Cross Referencing

description: Python Pandas Lookup/Cross Referencing


code:
class ACL(db.Model):
  user = db.UserProperty()
  permissions = db.ListProperty(str) # there are lots of other ways to store the permissions as well

rawDescription: How to keep an app engine entity imported as a module to a user.py and an admin.py file consistent

description: Keep an app engine entity imported as a module to a user.py and an admin.py file consistent


rawDescription: numpy bytes to plain string

description: Numpy bytes to plain string


code:
import re

def zerowidthsplit(pattern, string):
    splits = list(m.start() for m in re.finditer(pattern, string))
    starts = [0] + splits
    ends = splits + [ len(string) ]
    return [string[start:end] for start, end in zip(starts, ends)]

print(zerowidthsplit(r'(?<!foo)(?=bar)', 'foobarbarbazbar'))

rawDescription: Python regex: splitting on pattern match that is an empty string


rawDescription: Using Numpy to Count Numbers in a range

description: Using Numpy to Count Numbers in a range


code:
from random import randint
l = {randint(0, 1023): 1 for _ in xrange(0, 10)}

rawDescription: Populating a sparse list with random 1's


code:
from settings import settings

knob = settings.Knob()

rawDescription: Accessing classes from arbitrary modules inside of package directly


code:
import wx
from orange import oranges

if __name__ =='__main__':
    app = wx.App(False)
    window = oranges(parent=None,id=-1)
    window.Show()
    app.MainLoop()

rawDescription: How to call a wxFrame from a different file in wxPython?

description: Call a wxFrame from a different file in wxPython


code:
# <input name="name" type="text" />
name = self.request.get("name")

# <input name="subscribe" type="checkbox" value="yes" />
subscribe_to_newsletter = self.request.get("subscribe", default_value="no")

# <select name="favorite_foods" multiple="true">...</select>
favorite_foods = self.request.get("favorite_foods", allow_multiple=True)

rawDescription: Get form data using get method in python webapp2


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

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t,s)

ylims = ax.get_ylim()
ax.set_yticks(ylims)

xlims = ax.get_xlim()
ax.set_xticks(xlims)

plt.show()

rawDescription: Placing ticks on specific values

description: Placing ticks on specific values


rawDescription: Python graphics module

description: Python graphics module


code:
require("FinancialInstrument")
stock("GS", currency("USD")) # define the stock
#[1] "GS"
update_instruments.yahoo("GS") #update with yahoo
#[1] "GS"
getInstrument("GS")
#primary_id          :"GS"
#currency            :"USD"
#multiplier          :1
#tick_size           :0.01
#identifiers         : list()
#type                :"stock"
#name                :"Goldman Sachs Gro"
#exchange            :"NYSE"
#market.cap          :"47.870B"
#avg.volume          :5480530
#EPS                 :6.76
#EPS.current.year.est:11.4
#EPS.next.year.est   :12.9
#book.value          :134
#EBITDA              :0
#range.52wk          :"84.27 - 139.25"
#defined.by          :"yahoo"
#updated             : POSIXct, format: "2012-06-21 19:31:11"

rawDescription: Is there a way to automatically get general info of many stocks like P/E ratio, Yield, and so on?


code:
for i in range(bits):
    Array[(byte_offset + ((bit_offset + Bit_Offset + i)/ 8))] |= ((value & 1) << ((bit_offset + Bit_Offset + i) % 8));
    value >>=1

rawDescription: Understanding bit-manipulation function in Python


rawDescription: Are functions evaluated when passed as parameters?


rawDescription: numpy type conversions for arrays vs. scalars

description: Numpy type conversions for arrays vs. scalars


code:
import pip
import sys

if sys.version_info.major >= 3:
    from io import StringIO
else:
    from StringIO import StringIO

def get_version(package):
    f = StringIO()
    sys.stdout = f
    pip.main(["show", package])
    sys.stdout = sys.__stdout__
    return next((line.split(":", 1)[1].strip()
                 for line in f.getvalue().splitlines() if line.startswith("Version")), "No match")

rawDescription: How to check version of python package if no __version__ variable is set

description: Check version of python package if no __version__ variable is set


code:
xpath = "//td[@class='column-datacaption' and normalize-space(text())='Gesamtkostenquote']/following-sibling::td"
dues = driver.find_element_by_xpath(xpath)

rawDescription: Unique content identifier with Selenium: InvalidSelectorError


code:
lst = []

class AwesomeMeta(type):
    def __new__(metacls, cls, bases, classdict):
        if 'name' in classdict:
            lst.append(classdict['name'])
        return super().__new__(metacls, cls, bases, classdict)

class Awesome(metaclass=AwesomeMeta):
    """This is my magical super class."""

class Inherits(Awesome):
    """Awesome does awesome stuff with Inherits."""

    name = 'Stack'

class InheritsAgain(Awesome):
    """More awesomely stuff!"""

    name = 'Overflow'

class AndAgain(Awesome):
    name = "/root/path/<name>/<id>"

    def go():
        pass

print(lst)

rawDescription: Do something automatically after class definition?


code:
def avDates() :

    import urllib.request
    import json

    response = urllib.request.urlopen('http://www.website.com/api.php')
    content = response.read()
    data = json.loads(content.decode('utf-8'))
    dates = []
    for i in data:
        dates.append(str(i['Month'])+": "+str(i['the_days'])) #don't print it yet
    return dates

rawDescription: Having some problems printing out an array in Python3


code:
def build(self):
    '''Build the screen.
    '''
    self.settings_cls = MySettings

rawDescription: Dynamically updated Kivy settings entry

description: Dynamically updated Kivy settings entry


code:
def quickstart(root=None, script_name="", config=None):
    if config:
        _global_conf_alias.update(config)

    tree.mount(root, script_name, config)

    engine.signals.subscribe()
    engine.start()
    engine.block()

rawDescription: cherrypy - 'module' object has no attribute session when run with uWSGI

description: Cherrypy - 'module' object has no attribute session when run with uWSGI


code:
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

@receiver((post_save, post_delete), sender='main.OrderItem')
def update_order_when_items_changed(sender, instance, **kwargs):
    order = instance.order
    order.set_weight()
    order.set_total_price()
    order.save()

rawDescription: How can I create initial values for a model in django?

description: Create initial values for a model in django


code:
maxi = np.zeros(image_shape) # something like (1024, 1024)

for im in files:
    im_array = np.array(Image.open(im))
    inds = im_array > maxi # find where image intensity > max intensity
    maxi[inds] = im_array[inds] # update the maximum value at each pixel

max_im = Image.fromarray(maxi)
max_im.save("max_intensity.tif")

rawDescription: Find the maximum x,y value fromn a series of images


rawDescription: update not working with pymongo

description: Update not working with pymongo


code:
idx = np.random.choice(np.arange(len(x)), num_samples)
plt.scatter(x[idx], y[idx])

rawDescription: Python - Randomly subsamble a range of points to plot


code:
from astropy.io import fits
fits.writeto('filename.fits', img)

rawDescription: Converting ASCII Table to FITS image

description: Converting ASCII Table to FITS image


code:
import somewhere

class TestClass(somewhere.BaseSomewhere):
    def test_function(self):
        pass

rawDescription: What is a better way of handling import *


code:
a = np.random.rand(100)
b = np.random.randn(100)
np.mean(a)
np.mean(b)

rawDescription: The random number generator in numpy

description: The random number generator in numpy


code:
from multiprocessing import Pool

num_threads = 10

with Pool(num_threads) as pool:
    results = pool.map(lst)

rawDescription: Multiprocessing on a set number of cores


code:
import inspect
frames = inspect.stack()
defined_in_class = False
if len(frames) > 2:
    maybe_class_frame = frames[2]
    statement_list = maybe_class_frame[4]
    first_statment = statement_list[0]
    if first_statment.strip().startswith('class '):
        defined_in_class = True

rawDescription: Python: can a decorator determine if a function is being defined inside a class?


code: cursor = cnxn.cursor()

rawDescription: pyodbc - where to insert data?

description: Pyodbc - where to insert data


rawDescription: Remove matched tags in html files?

description: Remove matched tags in html files


code:
def remove_duplicates(seq):
    found = set()
    for item in seq:
        if item in found:
            continue
        found.add(item)
        yield item

rawDescription: What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python?


code:
M_strided = np.lib.stride_tricks.as_strided(
                M,                              # input array
                (700, M.shape[0], M.shape[1]),  # output dimensions
                (0, M.strides[0], M.strides[1]) # stride length in bytes
            )

rawDescription: python - repeating numpy array without replicating data

description: Python - repeating numpy array without replicating data


code:
def flat_list(l):
    for node in l:
        if isinstance(node, list):
            for i in flat_list(node):
                yield i
        else:
            yield node

rawDescription: How can I find the index for a list of nested lists which I am recursing over?

description: Find the index for a list of nested lists which I am recursing over


code: {reduce(lambda x, y : '{0};{1}'.format(x,y), l[j]):{k[i]: l[j][i] for i in range(len(k))} for j in range(1, len(l))}

rawDescription: Translating a 2D Array to nested dictonary


code:
from __future__ import print_function
map(print, row)

rawDescription: Split values from arrays

description: Split values from arrays


code:
import csv
with open('fake_csv.csv', 'r') as f:
    reader = csv.DictReader(f)
    my_rows = [row for row in reader]

my_rows

rawDescription: Aparrent looping issue: Why am I appending the same thing to my list over and over again?


code: cmd = int(data);

rawDescription: How can I send an enum to a python tcp server?

description: Send an enum to a python tcp server


code: by3 = [plus102[i:i+3] for i in range(0,len(plus102),3)]

rawDescription: Getting Python to read a text file in chunks of 3 (codons) and give me an output


rawDescription: find duplicates users and their activity count in list of logs in python

description: Find duplicates users and their activity count in list of logs in python


code:
from operator import mul
reduce(mul, range(1, 5))

rawDescription: Python equivalent of MATLAB command prod


code:
lst2 = [x for x in lst if x != '']
lst2

rawDescription: Remove empty element but keep zeros as values


code:
import re
import yaml as yaml
from yaml.resolver import BaseResolver, Resolver
from yaml.emitter import Emitter
from yaml.serializer import Serializer
from yaml.representer import Representer as Repr

class MyResolver(BaseResolver):
    pass

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:bool',
    re.compile(u'''^(?:true|True|TRUE|false|False|FALSE)$''', re.X),
    list(u'tTfF'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:float',
    re.compile(u'''^(?:
     [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
    |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
    |\\.[0-9_]+(?:[eE][-+][0-9]+)?
    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
    |[-+]?\\.(?:inf|Inf|INF)
    |\\.(?:nan|NaN|NAN))$''', re.X),
    list(u'-+0123456789.'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:int',
    re.compile(u'''^(?:[-+]?0b[0-1_]+
    |[-+]?[0-9]+
    |[-+]?0o?[0-7_]+
    |[-+]?(?:0|[1-9][0-9_]*)
    |[-+]?0x[0-9a-fA-F_]+
    |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
    list(u'-+0123456789'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:merge',
    re.compile(u'^(?:<<)$'),
    [u'<'])

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:null',
    re.compile(u'''^(?: ~
    |null|Null|NULL
    | )$''', re.X),
    [u'~', u'n', u'N', u''])

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:timestamp',
    re.compile(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
    |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
    (?:[Tt]|[ \\t]+)[0-9][0-9]?
    :[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)?
    (?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
    list(u'0123456789'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:value',
    re.compile(u'^(?:=)$'),
    [u'='])

# The following resolver is only for documentation purposes. It cannot work
# because plain scalars cannot start with '!', '&', or '*'.
MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:yaml',
    re.compile(u'^(?:!|&|\\*)$'),
    list(u'!&*'))

class MySafeDumper(Emitter, Serializer, Repr, MyResolver):
    def __init__(self, stream,
                 default_style=None, default_flow_style=None,
                 canonical=None, indent=None, width=None,
                 allow_unicode=None, line_break=None,
                 encoding=None, explicit_start=None, explicit_end=None,
                 version=None, tags=None):
        Emitter.__init__(self, stream, canonical=canonical,
                         indent=indent, width=width,
                         allow_unicode=allow_unicode, line_break=line_break)
        Serializer.__init__(self, encoding=encoding,
                            explicit_start=explicit_start,
                            explicit_end=explicit_end,
                            version=version, tags=tags)
        Repr.__init__(self, default_style=default_style,
                                 default_flow_style=default_flow_style)
        MyResolver.__init__(self)

print(yaml.dump(dict(sampe='Yes'), Dumper=MySafeDumper))

rawDescription: yes or no dumping as 'yes' or 'no' in PyYAML

description: Yes or no dumping as 'yes' or 'no' in PyYAML


code:
import myapplication

a= myapplication.Application()

rawDescription: Organizing a large Python project that must share an internal state?


code:
def addition(self,complex):
    return mycomplex(real+complex.real,imag+complex.imag)

rawDescription: python create a class with complex numbers

description: Python create a class with complex numbers


code:
def four():
    k = np.random.randint(138**4)
    a = k % 138
    b = k // 138 % 138
    c = k // 138**2 % 138
    d = k // 138**3 % 138
    return (a, b, c, d) if a != b and a != c and a != d and b != c and b != d and c != d else four()

rawDescription: Time performance of np.random.permutation, np.random.choice


code: integer = Word(nums).setParseAction(lambda tokens:int(tokens[0]))

rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


code:
rdd1 = sc.parallelize([1, 2, 3])
rdd2 = sc.parallelize([4, 5, 6])
rdd3 = sc.parallelize([7, 8, 9])

rdd = sc.union([rdd1, rdd2, rdd3])
rdd.collect()

## [1, 2, 3, 4, 5, 6, 7, 8, 9]

rawDescription: Spark union of multiple RDDs

description: Spark union of multiple RDDs


code:
#add code here to figure out the number of 0's you need, naming the variable n.
listofzeros = [0] * n

rawDescription: List of zeros in python

description: List of zeros in python


code: (lambda mx=max(map(a.count, set(a))): [x for x in set(a) if a.count(x) == mx])()

rawDescription: Return a list containing the number with most repeats from a list of numbers


code: model = LogisticRegression(C=1000000)

rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


code:
import numpy as np
N = 10**6
list_a = np.random.randint(2*10**6, size=N).tolist()
list_b = np.random.randint(2*10**6, size=N).tolist()

rawDescription: The fastest way in Python to merge and remove duplicate ids


rawDescription: How to get the length of a cell value in pandas dataframe?

description: Get the length of a cell value in pandas dataframe


code: itertools.imap(lambda x: "".join(x), itertools.permutations("0123456789"))

rawDescription: How to turn the result (in python) of itertools.permutations("0123456789") into list of strings

description: Turn the result (in python) of itertools.permutations("0123456789") into list of strings


code:
import numpy as np
a = np.array([0,1,2,3,4,5,6,7,8,9])
num_neighbor=3

for index in range(len(a)):
    left = a[:index][-num_neighbor:]
    right= a[index+1:num_neighbor+index+1]
    print(index,left,right)

rawDescription: how to get the neighboring elements in a numpy array with taking boundaries into account?

description: Get the neighboring elements in a numpy array with taking boundaries into account


code:
import webapp2
from webapp2_extras import i18n

AVAILABLE_LOCALES = ['en_GB', 'es_ES']

class BaseHandler(webapp2.RequestHandler):
    def __init__(self, request, response):
        """ Override the initialiser in order to set the language.
        """
        self.initialize(request, response)

        # first, try and set locale from cookie
        locale = request.cookies.get('locale')
        if locale in AVAILABLE_LOCALES:
            i18n.get_i18n().set_locale(locale)
        else:
            # if that failed, try and set locale from accept language header
            header = request.headers.get('Accept-Language', '')  # e.g. en-gb,en;q=0.8,es-es;q=0.5,eu;q=0.3
            locales = [locale.split(';')[0] for locale in header.split(',')]
            for locale in locales:
                if locale in AVAILABLE_LOCALES:
                    i18n.get_i18n().set_locale(locale)
                    break
            else:
                # if still no locale set, use the first available one
                i18n.get_i18n().set_locale(AVAILABLE_LOCALES[0])

rawDescription: How to decide the language from cookies/headers/session in webapp2?

description: Decide the language from cookies/headers/session in webapp2


code:
import re
a = '\t\t\tHere is the next part of string.  More garbage.'
re.sub(r'^(\t*)', r'\1 Added String here. ', a)
re.sub(r'^(\t*)', r'\1 Added String here. ', 'No leading tabs.')

rawDescription: Add string between tabs and text

description: Add string between tabs and text


code: [word for word in words if any(not char.isdigit() for char in word)]

rawDescription: Python list-comprehension for words that do not consist solely of digits


code:
foo
bofoo
foobar
barfood

rawDescription: Simple Django queryset __icontains search that will find most specific elements first


code: difflib.get_close_matches(word, ['car', 'animal', 'house', 'animation'])

rawDescription: How to find the most similar word in a list in python

description: Find the most similar word in a list in python


code:
filtered_signs=median_filter(signs, 5) #pick window size based on result. second arg and odd number.
pl.plot(filtered_signs)
pl.ylim(-1.2,1.2)

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

description: Extract this obvious event from this image


code:
class new_integer(int):
  __add__ = magic_decorator(int.__add__)
  __sub__ = magic_decorator(int.__sub__)
  ...

rawDescription: Argument parsing with python decorators

description: Argument parsing with python decorators


rawDescription: Get only last part of xpath

description: Get only last part of xpath


code:
view.py
from .models import Speaker
from .serializers import SpeakerSerializer, UserSerializer

from rest_framework import viewsets
from django.contrib.auth.models import User

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'username'

class SpeakerViewSet(viewsets.ModelViewSet):
    queryset = Speaker.objects.all().select_related('user')
    serializer_class = SpeakerSerializer
    lookup_field = 'user__username'

rawDescription: django rest framework lookup_field through OneToOneField

description: Django rest framework lookup_field through OneToOneField


rawDescription: Change string in file in python

description: Change string in file in python


code:
import subprocess
subprocess.Popen([r'path/to/PowerShell/script.exe',
                         '-ExecutionPolicy',
                         'Unrestricted',
                         'path/to/background_image.png'], cwd=os.getcwd())

rawDescription: Python - Change Desktop Background Fast

description: Python - Change Desktop Background Fast


code:
class group_property(property):
    def __get__(self, obj, objtype=None):
        return super(group_property, self).__get__(obj.config, objtype)

    def __set__(self, obj, value):
        super(group_property, self).__set__(obj.config, value)

    def __delete__(self, obj):
        return super(group_property, self).__del__(obj.config)

class Config2(object):
    ...
    class group(object):
        ...
        @group_property
        def e(config):
            return config.group.c * config.a

rawDescription: Python: Idiomatic properties for structured data?


code: obj = __import__("mymod", ...).mymod

rawDescription: Import object from module of same name using __import__


code: totals

rawDescription: grouping table elements according to grouping column values

description: Grouping table elements according to grouping column values


code:
for match in soup.find_all('td', class_='match-details'):
    home_tag = match.find('span', class_='team-home')
    home = home_tag and ''.join(home_tag.stripped_strings)
    score_tag = match.find('span', class_='score')
    score = score_tag and ''.join(score_tag.stripped_strings)
    away_tag = match.find('span', class_='team-away')
    away = away_tag and ''.join(away_tag.stripped_strings)

rawDescription: Python Beautifulsoup4 website parsing

description: Python Beautifulsoup4 website parsing


code:
d1 = dict(zip("kapow", "squee"))
d2 = dict(zip("bar", "foo"))
d3 = dict(zip("xyz", "abc"))
dicts = d1, d2, d3
from pprint import pprint
pprint(dicts)
from itertools import compress
for d_with_key in compress(dicts, ("a" in d for d in dicts)):
    print(d_with_key)

rawDescription: What is the best way to search for a key in multiple dictionaries in Python


code:
denormalized = []
for tup in list_of_tuples:
    for x in tup:
        denormalized.append(x)

rawDescription: Passing variable length parameters to a function in python


code:
import requests

payload = {'v': '1',                # Version.
           'tid': 'UA-XXXXX-1',     # Tracking ID / Property ID.
           'cid': '123456',         # Anonymous Client ID.
           'dh': 'www.example.com', # Document hostname.
           'dp': 'home',            # Page.
           't': 'pageview'          # Hit Type.
          }

requests.post('http://www.google-analytics.com/collect', payload)

rawDescription: How to track a PYPI project using google analytics?

description: Track a PYPI project using google analytics


code:
import pandas as pd
iris = pd.read_csv('iris.csv')
axarr, color_map = factor_scatter_matrix(iris,'Name')
color_map

rawDescription: class labels in Pandas scattermatrix

description: Class labels in Pandas scattermatrix


code: [x for x in ilist if len(x) > 0]

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

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


code:
repo = {}
infile = open('test10.log','r')
lines = infile.readlines()[2:-1]
for i in lines:
    module, time = [a.strip() for a in i.split(',')]
    repo.setdefault(module, []).append(int(time))

rawDescription: read data from file, store in a python dict and search for values in python

description: Read data from file, store in a python dict and search for values in python


code:
import blocktrail, time
class Bit():
    def __init__(self):
        self.nonce_list = []
    def run(self):
        while True:
            client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
            address = client.address('x')
            latest_block = client.block_latest()
            nonce = latest_block['nonce']
            blockhash = latest_block['hash']
            nonce_str = str(nonce)
            self.nonce_list.append(nonce_str)
            print(self.nonce_list)
            time.sleep(60)

Bit().run()

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