code:
def download(source_url):
    try:
        socket.setdefaulttimeout(10)
        agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)']
        ree = urllib2.Request(source_url)
        ree.add_header('User-Agent',random.choice(agents))
        ree.add_header('Accept-encoding', 'gzip')
        opener = urllib2.build_opener()
        response = opener.open(ree)
        content = response.read()
        compressedstream = StringIO.StringIO(content)
        gzipper = gzip.GzipFile(fileobj=compressedstream)
        try:
            data = gzipper.read()
        except IOError:
            data = content
        return data
    except urllib2.URLError as e:
        return ""

rawDescription: How do I modify this download function in Python?

description: Modify this download function in Python


code:
def f(x, M):
    return M.dot(x)

rawDescription: I'm having difficulty understanding the syntax of scipy.optimize


code: A = U + 1j*V

rawDescription: Constraining the least squares fitting in python


code:
Expected:  set(['mike', 'ape'])
Got:  set(['orange', 'tom'])

rawDescription: Diffing two files while ignoring any missed lines


code:
#!/usr/bin/env python3
import urllib.request
from PIL import Image # $ pip install pillow

im = Image.open(urllib.request.urlopen(url))
print(im.format, im.mode, im.size)

rawDescription: temporarily retrieve an image using the requests library

description: Temporarily retrieve an image using the requests library


code:
from django.db.models import Q

qs = MyModel.objects.filter(~Q(icon__contains='any string'))

rawDescription: Django contains None (or reversed contain)


code:
#!/usr/bin/python
# file: version2.py

from distutils import version
import re
import functools

@functools.total_ordering
class NumberedVersion(version.Version):
    """
    A more flexible implementation of distutils.version.StrictVersion

    This implementation allows to specify:
    - an arbitrary number of version numbers:
        not only '1.2.3' , but also '1.2.3.4.5'
    - the separator between version numbers:
        '1-2-3' is allowed when '-' is specified as separator
    - an arbitrary ordering of pre-release tags:
        1.1alpha3 < 1.1beta2 < 1.1rc1 < 1.1
        when ["alpha", "beta", "rc"] is specified as pre-release tag list
    """

    def __init__(self, vstring=None, sep='.', prerel_tags=('a', 'b')):
        version.Version.__init__(self)
            # super() is better here, but Version is an old-style class

        self.sep = sep
        self.prerel_tags = dict(zip(prerel_tags, xrange(len(prerel_tags))))
        self.version_re = self._compile_pattern(sep, self.prerel_tags.keys())
        self.sep_re = re.compile(re.escape(sep))

        if vstring:
            self.parse(vstring)

    _re_prerel_tag = 'rel_tag'
    _re_prerel_num = 'tag_num'

    def _compile_pattern(self, sep, prerel_tags):
        sep = re.escape(sep)
        tags = '|'.join(re.escape(tag) for tag in prerel_tags)

        if tags:
            release_re = '(?:(?P<{tn}>{tags})(?P<{nn}>\d+))?'\
                .format(tags=tags, tn=self._re_prerel_tag, nn=self._re_prerel_num)
        else:
            release_re = ''

        return re.compile(r'^(\d+)(?:{sep}(\d+))*{rel}$'\
            .format(sep=sep, rel=release_re))

    def parse(self, vstring):
        m = self.version_re.match(vstring)
        if not m:
            raise ValueError("invalid version number '{}'".format(vstring))

        tag = m.group(self._re_prerel_tag)
        tag_num = m.group(self._re_prerel_num)

        if tag is not None and tag_num is not None:
            self.prerelease = (tag, int(tag_num))
            vnum_string = vstring[:-(len(tag) + len(tag_num))]
        else:
            self.prerelease = None
            vnum_string = vstring

        self.version = tuple(map(int, self.sep_re.split(vnum_string)))

    def __repr__(self):
        return "{cls} ('{vstring}', '{sep}', {prerel_tags})"\
            .format(cls=self.__class__.__name__, vstring=str(self),
                sep=self.sep, prerel_tags = list(self.prerel_tags.keys()))

    def __str__(self):
        s = self.sep.join(map(str,self.version))
        if self.prerelease:
            return s + "{}{}".format(*self.prerelease)
        else:
            return s

    def __lt__(self, other):
        """
        Fails when  the separator is not the same or when the pre-release tags
        are not the same or do not respect the same order.
        """
        # TODO deal with trailing zeroes: e.g. "1.2.0" == "1.2"
        if self.prerel_tags != other.prerel_tags or self.sep != other.sep:
            raise ValueError("Unable to compare: instances have different"
                " structures")

        if self.version == other.version and self.prerelease is not None and\
                other.prerelease is not None:

            tag_index = self.prerel_tags[self.prerelease[0]]
            other_index = self.prerel_tags[other.prerelease[0]]
            if tag_index == other_index:
                return self.prerelease[1] < other.prerelease[1]

            return tag_index < other_index

        elif self.version == other.version:
            return self.prerelease is not None and other.prerelease is None

        return self.version < other.version

    def __eq__(self, other):
        tag_index = self.prerel_tags[self.prerelease[0]]
        other_index = other.prerel_tags[other.prerelease[0]]
        return self.prerel_tags == other.prerel_tags and self.sep == other.sep\
            and self.version == other.version and tag_index == other_index and\
                self.prerelease[1] == other.prerelease[1]

import unittest

class TestNumberedVersion(unittest.TestCase):

    def setUp(self):
        self.v = NumberedVersion()

    def test_compile_pattern(self):
        p = self.v._compile_pattern('.', ['a', 'b'])
        tests = {'1.2.3': True, '1a0': True, '1': True, '1.2.3.4a5': True,
            'b': False, '1c0': False, ' 1': False, '': False}
        for test, result in tests.iteritems():
            self.assertEqual(result, p.match(test) is not None, \
                "test: {} result: {}".format(test, result))

    def test_parse(self):
        tests = {"1.2.3.4a5": ((1, 2, 3, 4), ('a', 5))}
        for test, result in tests.iteritems():
            self.v.parse(test)
            self.assertEqual(result, (self.v.version, self.v.prerelease))

    def test_str(self):
        tests = (('1.2.3',), ('10-2-42rc12', '-', ['rc']))
        for t in tests:
            self.assertEqual(t[0], str(NumberedVersion(*t)))

    def test_repr(self):
        v = NumberedVersion('1,2,3rc4', ',', ['lol', 'rc'])
        expected = "NumberedVersion ('1,2,3rc4', ',', ['lol', 'rc'])"
        self.assertEqual(expected, repr(v))

    def test_order(self):
        test = ["1.7.0", "1.7.0rc0", "1.11.0"]
        expected = ['1.7.0rc0', '1.7.0', '1.11.0']
        versions = [NumberedVersion(v, '.', ['rc']) for v in test]
        self.assertEqual(expected, list(map(str,sorted(versions))))

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

rawDescription: Sort Versions in Python

description: Sort Versions in Python


code:
l = [1,2,3]
list(range(1, len(l)))
list(range(1, len(l) + 1))

rawDescription: Python: Unable to quit menu - user input


code:
mod = __import__('animal')
spot = mod.Dog(5)

rawDescription: Dynamically load module with Inheritance


code:
from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import tkFileDialog

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):

        self.parent.title("File dialog")
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        menubar.add_cascade(label="File", menu=fileMenu)

        self.txt = Text(self)
        self.txt.pack(fill=BOTH, expand=1)

    def onOpen(self):

        ftypes = [('Python files', '*.py'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        fl = dlg.show()

        if fl != '':
            text = self.readFile(fl)
            self.txt.insert(END, text)

    def readFile(self, filename):

        f = open(filename, "r")
        text = f.read()
        return text

def main():

    root = Tk()
    ex = Example(root)
    root.geometry("300x250+300+300")
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Opening File (Tkinter)

description: Opening File (Tkinter)


rawDescription: Converting date to string in Python

description: Converting date to string in Python


code:
from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.pack()
label_2.pack()
label_3.pack()
label_4.pack(side=BOTTOM)

root.mainloop()

rawDescription: How to use the grid() python

description: Use the grid() python


code:
xup=np.linspace(0,1,50)
xdn=np.linspace(1,0,50)
x=np.hstack([xup,xdn])
saw2 = np.hstack([x for _ in range(4)])

rawDescription: How to rewrite the code which appends to lists with numpy arrays

description: Rewrite the code which appends to lists with numpy arrays


code:
p = data[0]
p.name

rawDescription: Data type to save a table

description: Data type to save a table


code:
class Baz(object):
    _foo = 'spam'
    @property
    def foo(self):
        return self._foo
    echo = partialmethod_with_descriptorargs(mk_foobar, foo)

baz = Baz()
baz.foo
baz.echo()
baz_echo = baz.echo  # just the method
baz._foo = 'ham'
baz.foo
baz_echo()
baz.echo()

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
final_result = 0
a = '3 4  4 5 6'
i = 0
while i < len(a):
    print('iteration')
    print('i is = ')
    print(i)
    if a[i] is ' ' and a[i + 1] is not ' ':
        if i - 1 is 0:
            final_result = int(a[i - 1]) + int(a[i + 1])
            i += 2  # here goes the increment
            print('1a- m here')
            print(final_result)
            print('i is = ')
            print(i)
        else:
            final_result = final_result + int(a[i + 1])
            i += 2  # here goes the increment
            print('1b- m here')
            print(final_result)
    elif a[i] is ' ' and a[i + 1] is ' ':
        if i - 1 is 0:
            final_result = int(a[i - 1]) - int(a[i + 1])
            i += 3  # here goes the increment
            print('2a- m here')
            print(final_result)
        else:
            final_result = final_result - int(a[i + 2])
            i += 3  # here goes the increment
            print('2b- m here')
            print(final_result)
            print('i is = ')
            print(i)
    else:
        i += 1
print(final_result)

rawDescription: how to decrement and increment loop range 'i' variable in the execution of loop in python

description: Decrement and increment loop range 'i' variable in the execution of loop in python


code: df.pivot_table(rows='Animal', cols='FeedType', values='Amount(kg)', aggfunc='sum')

rawDescription: Equivalent of R's tapply() in Python Pandas


rawDescription: How can I register a single view (not a viewset) on my router?

description: Register a single view (not a viewset) on my router


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib.colors as cols
from numpy.random import randn

def cmap_double_discretize(cmap_bottom, cmap_top, N, split=.5):
    """
    Generates a descritized color map using two existing color maps

    Parameters
    ----------
    cmap_bottom : cmap
        The bottom cmap

    cmap_top : cmap
        The top cmap

    N : int
       The number of bins in each color map

    split : float, optional
       Where to join the maps, must be in [0, 1]
    """
    # sanity check
    assert split < 1 and split > 0
    # set up the data structure
    cdict = {lab: [] for lab in ('red','green','blue')}
    # do this in a fancy loop to a) save typing, b) make it easy to
    # retrofit to do arbitrary splits
    for cmap, ends in zip((cmap_bottom, cmap_top), ((0, split), (split, 1))):

        # run over the _whole_ range for each color map
        colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
        # map the color
        colors_rgba = cmap(colors_i)
        # get the values
        indices = np.linspace(ends[0], ends[1], N+1, endpoint=True)

        for ki,key in enumerate(('red','green','blue')):
            cdict[key].extend((indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1))
            #    print cdict
    # Return colormap object.
    return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

red_cdict = {'red': [(0, 0, 1),
                     (1, 1, 0)],
            'blue': [(0, 0, 0),
                     (1, 1, 0)],
            'green': [(0, 0, 0),
                     (1, 1, 0)]}

blue_cdict = {'blue': [(0, 0, 1),
                       (1, 1, 0),],
            'red': [(0, 0, 1),
                    (1, 0, 0)],
            'green': [(0, 0, 1),
                     (1, 0, 0)]}
red_cmap = cols.LinearSegmentedColormap('red', red_cdict, 1024)
blue_cmap = cols.LinearSegmentedColormap('blue', blue_cdict, 1024)

test_cmap = cmap_double_discretize(red_cmap, blue_cmap, 6)
# these don't actually go to white!
# test_cmap = cmap_double_discretize(cm.get_cmap('Reds_r'), cm.get_cmap('Blues'), 6)

fig, ax = plt.subplots()
data = np.clip(randn(250, 250), -1, 1)

cax = ax.pcolor(data, cmap=test_cmap)
plt.colorbar(cax)

plt.show()

rawDescription: modify discrete LinearSegmentedColormap

description: Modify discrete LinearSegmentedColormap


code: data = data[indices]

rawDescription: Filter numpy structured array based based on unique elements in one dimension


code:
import requests

data = "x"*100000000 # 100MB beefy chunk
requests.post("http://localhost:12346", data=data, timeout=4)

rawDescription: How to prevent blocking forever on urlopen

description: Prevent blocking forever on urlopen


rawDescription: Is there a non-copying constructor for a pandas DataFrame


code:
import datetime
s = datetime.datetime.now()
#codes here
print (datetime.datetime.now() - s)

rawDescription: Python - Catch run time of the file in specific Format


code:
@app.route('/get-file/<name>')
@app.route('/get-file')
def get_file(name=None):
    fs = gridfs.GridFS(MongoClient().CINEfs_example)

    if name is not None:
        f = fs.get_last_version(name)
        r = app.response_class(f, direct_passthrough=True, mimetype='application/octet-stream')
        r.headers.set('Content-Disposition', 'attachment', filename=name)
        return r

    return render_template('get_file.html', names=fs.list())

rawDescription: List and serve files from GridFS with Flask


code:
volume = 193019.2896
decimals = 2
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
decimals = 3
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

rawDescription: Two Decimals in Python?

description: Two Decimals in Python


code:
import random
def rand_range(a, b):
   return a + random.uniform() * (b - a)

x = [rand_range(-3, 3) for i in range(3)]
y = [rand_range(-3, 3) for i in range(3)]

rawDescription: Using 'If' to run the loop again?

description: Using 'If' to run the loop again


code:
with open(newDailyFile) as file:
    lines = file.readlines() #Gets each one line by line, then I can load them
    for i in lines:
        result = loads(i)

rawDescription: python, loading multiple instances of something

description: Python, loading multiple instances of something


code: [v for k, v in globals().items() if 'possible_seq' in k]

rawDescription: How can I access unknown objects at runtime - not their names

description: Access unknown objects at runtime - not their names


code:
lis = ['a', 'b', 'c', 'd']
dic = {x: 0 for x in lis}
dic

rawDescription: Most Pythonic Way to Build Dictionary From Single List


code:
import re
p = re.compile('([+-])(\w, ]+)')
p.findall('+foo,   bar -baz')
p.findall('+foo,bar -baz')

rawDescription: Difficulty getting python regular expression to work


code: pivotarray(df)

rawDescription: How to aggregate the values of a DataFrame (and output a numpy array quickly)?

description: Aggregate the values of a DataFrame (and output a numpy array quickly)


code:
def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t # <-- this is new!
    return run

rawDescription: Threads with decorators

description: Threads with decorators


rawDescription: Replace values of a numpy array by values from another numpy array


rawDescription: pandas to_csv and then read_csv results to numpy.datetime64 messed up due to utc

description: Pandas to_csv and then read_csv results to numpy.datetime64 messed up due to utc


code:
for x in everywhere(list(range(2)), 3):
    print(x)

rawDescription: How to bin all subsets of a python list into n bins

description: Bin all subsets of a python list into n bins


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

# Beginning in one dimension:
mean = 0; Var = 1; N = 100
scatter = np.random.normal(mean,np.sqrt(Var),N)
scatter = np.sort(scatter)
mu1,sigma1 = norm.fit(scatter) # classical fit

scat_sum = np.cumsum(np.ones(scatter.shape))/N # cumulative samples
[mu2,sigma2],Cx = curve_fit(norm.cdf, scatter, scat_sum, p0=[0,1]) # curve fit
print(u"norm.fit():  µ1= {:+.4f}, σ1={:.4f}".format(mu1, sigma1))
print(u"curve_fit(): µ2= {:+.4f}, σ2={:.4f}".format(mu2, sigma2))

fg = plt.figure(1); fg.clf()
ax = fg.add_subplot(1, 1, 1)
t = np.linspace(-4,4, 1000)
ax.plot(t, norm.cdf(t, mu1, sigma1), alpha=.5, label="norm.fit()")
ax.plot(t, norm.cdf(t, mu1, sigma1), alpha=.5, label="curve_fit()")
ax.step(scatter, scat_sum, 'x-', where='post', alpha=.5, label="Samples")
ax.legend(loc="best")
ax.grid(True)
ax.set_xlabel("$x$")
ax.set_ylabel("Cumulative Probability Density")
ax.set_title("Fit to Normal Distribution")

fg.canvas.draw()
plt.show()

rawDescription: How can I find the right gaussian curve given some data?

description: Find the right gaussian curve given some data


code: bs = (d['b'] for d in lst)

rawDescription: Breaking a list in to parts by subject

description: Breaking a list in to parts by subject


code: reversed(x)  # returns an iterator

rawDescription: How to reverse tuples in Python?

description: Reverse tuples in Python


code:
import os
import threading

class ListComparator(threading.Thread):

    def __init__(self, file):

        threading.Thread.__init__(self)
        self.file = file
        self._stopevent = threading.Event()

    def run(self):
        name, extension = os.path.splitext(self.file)

        if (extension == '.txt'):

            print('comparing strings in file ' + name)

            try :
                f = open(file, 'r')

                l = [s.strip('\n') for s in f]

                f.close()

            except:
                print('unable to open file' + file)
                l = None

            if (l != None):

                try :

                    target = open(name + '_compared.txt', 'w')

                except Exception as e:
                    print(e)
                    target = None

                if (target != None):
                    for i in range(0, len(l) - 1):
                        for j in range(i + 1, len(l)):
                            result = 0
                            counter = 0

                            for k in range(len(l[i])):
                                if (int(l[i][k]) == int(l[j][k]) == 1):
                                    counter += 1

                            result = counter / len(l[i])
                            s = l[i] + ', ' + l[j] + ', ' + str(result) + '\n'

                            target.write(s)

                    target.close()

                    print(name + ' compared')
                else:
                    print(name + ' not compared')

        def stop(self):
            self._stopevent.set()

current_dir = os.getcwd()

for subdir, dirs, files in os.walk(current_dir):

    for file in files:

        try :
            comp = ListComparator(file)
            comp.start()

        except Exception as e:
            print(e)

rawDescription: compare lists in python

description: Compare lists in python


rawDescription: In a list of lists, is there a way to get the elements in an element's row and column simultaneously?


code:
new_crit = input("Enter a name for your new critter: ")
for i in noc:
    if i.name == new_crit:  # name is a parameter used in the class Critter
        print("That critter already exists")
        break
else:
    # we can only get here if no such name was found, otherwise the for
    # loop would have ended at the `break`
    Critter.noc.append(Critter(new_crit))
    print("New critter has been created. the critter is named: ", new_crit)

rawDescription: using if...then...else in to check if an object already exists

description: Using if...then...else in to check if an object already exists


code:
import os
os.path.isdir(path)

rawDescription: How to check if a network path exist?

description: Check if a network path exist


code: query['PartNo'] = 85731

rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
import images_qr

# ... Some code here and there ...

self.setWindowIcon(QtGui.QIcon(':/img/image1.png')) # The colon is important, it must be there

rawDescription: PyInstaller won't load the PyQt's images to the GUI


code:
class HashableBytearray(bytearray):
    def __hash__(self):
        return hash(str(self))

h = HashableBytearray('abcd')
hash(h)
h[2] = 'z'
hash(h)

rawDescription: Python quickly hash mutable object

description: Python quickly hash mutable object


code: fullpath = os.path.join(os.path.dirname(sys.argv[0]), 'filename.jpg')

rawDescription: Open (read, write) a file in same directory as main app - python/kivy


code:
from django.core.cache import cache

CACHE_KEY = 'events'
events = cache.get(CACHE_KEY, None)
if events is None:
    events = get_events()
    cache.set(CACHE_KEY, events, 3600) # expires in 1 hour
return events

rawDescription: Can I create a sort of cache in DB using django?

description: Create a sort of cache in DB using django


code:
#  mPlotDATEs.date2num.__doc__
#
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.

rawDescription: Reading a time list and make a plot using matplotlib


code:
for i in range(nrow-1,-1,-1):
    if(i == nrow-1):
        center_y[i,:] = 0.5*deltay[nrow-1]
    else:
        center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

rawDescription: Python: Help in optimizing code

description: Python: Help in optimizing code


code:
import dis
def f():
    def g():
        return 1
dis.dis(f)

rawDescription: python what happens when a function is called?

description: Python what happens when a function is called


code:
def myView(request, *args, **kwargs):
    #Code here.
    distinct = kwargs.pop('distinct') #the distinct parameter(s) {'distinct': 'rate'}
    #verification and validation of distict
    Location.objects.filter(locations_rate__rate=search_rate).distinct(distinct)
    #I assumed only 1 distinct argument

    ...

rawDescription: kwargs in django - how to put distinct() into kwargs

description: Kwargs in django - how to put distinct() into kwargs


rawDescription: How to use python to generate a magazine cover?

description: Use python to generate a magazine cover


code:
from collections import OrderedDict
d = OrderedDict()
for item in items:
    d.setdefault(item['a'], []).append(item)

dict(d.items())

rawDescription: Pythonic way to group items in a list

description: Pythonic way to group items in a list


code:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.core.management import call_command # Add this import

class Migration(DataMigration):
    def forwards(self, orm):
        call_command('createcachetable', 'cache')

    def backwards(self, orm):
        db.delete_table('cache')

    ...

rawDescription: Creating Django Cache table using South?

description: Creating Django Cache table using South


code:
['avito.ru' 'e1.ru' 'drom.ru' 'auto.ru' 'avtomarket.ru' 'am.ru'
 'irr.ru/cars' 'cars.mail.ru/sale']
['avito.ru' 'e1.ru' 'drom.ru' 'auto.ru' 'avtomarket.ru' 'am.ru'
 'irr.ru/cars' 'cars.mail.ru/sale']
['avito.ru' 'e1.ru' 'auto.ru' 'drom.ru' 'irr.ru/cars' 'avtomarket.ru'
 'cars.mail.ru/sale' 'am.ru']

rawDescription: Sort strings in column and print graph

description: Sort strings in column and print graph


code:
code = '''#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
#include <Box2D/Dynamics/Joints/xyz.h> #include <Box2D/Dynamics/Joints/xyz.h>
#include <pqr.h>'''

code = re.sub("(?:(?<=^)|(?<=[\n\r]))#include\s+<[^>]*/", "#include <", code)

rawDescription: python re remove text between < (exclusive) and last / (inclusive) in a line

description: Python re remove text between < (exclusive) and last / (inclusive) in a line


code: (angles + 2 * np.pi) % (2 * np.pi)

rawDescription: Numpy converting range of angles from (-Pi, Pi) to (0, 2*Pi)


code:
import math as m

def JD(dt):
    """ Same calculation as JD but accepts a date object argument

    :param dt: the date object
    :return: the JD result
    """
    yr, mon, day, hr, min, sec = dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
    jd = 367.0 * yr - m.floor(
        (7 * (yr + m.floor((mon + 9) / 12.0))) * 0.25) + m.floor(
        275 * mon / 9.0) + day + 1721013.5 + (
                                                 (sec / 60.0 + min) / 60.0 + hr) / 24.0
    return jd

rawDescription: Formatting python datetime object as argument


code:
from pyparsing import (Suppress, QuotedString, Forward, Group, Dict,
    ZeroOrMore, Word, alphanums, Optional, dblSlashComment)

LBRACE,RBRACE = map(Suppress, "{}")

key_qs = QuotedString('"').setName("key_qs")
value_qs = QuotedString('"', escChar='\\', multiline=True).setName("value_qs")

# use this code to convert integer values to ints at parse time
def convert_integers(tokens):
    if tokens[0].isdigit():
        tokens[0] = int(tokens[0])
value_qs.setParseAction(convert_integers)

LBRACK,RBRACK = map(Suppress, "[]")
qualExpr = Word(alphanums+'$!&|')
qualExprCondition = LBRACK + qualExpr + RBRACK

value = Forward()
key_value = Group(key_qs + value + Optional(qualExprCondition("qual")))
def addQualifierToKey(tokens):
    tt = tokens[0]
    if 'qual' in tt:
        tt[0] += '/' + tt.pop(-1)
key_value.setParseAction(addQualifierToKey)

struct = (LBRACE + Dict(ZeroOrMore(key_value)) + RBRACE).setName("struct")
value <<= (value_qs | struct)
parser = Dict(key_value)
parser.ignore(dblSlashComment)

sample = open('cs_go_sample2.txt').read()
config = parser.parseString(sample)

print (config.keys())
for k in config.lang.keys():
    print ('- ' + k)

#~ config.lang.pprint()
print (config.lang.Tokens.StickerKit_comm01_burn_them_all)
print (config.lang.Tokens['SFUI_SteamOverlay_Text/$WIN32'])

rawDescription: Parsing a CS:GO language file with encoding in Python


code: elapsed_time += my_clock.tick(60) # 60 fps, time is in milliseconds

rawDescription: Flash an image in pygame

description: Flash an image in pygame


rawDescription: Using an item from a list as a new dictionary key


code:
@loggify
class loggedWorker(Working): pass

rawDescription: How to cast object in Python

description: Cast object in Python


code:
df = pd.DataFrame({ 'col_1':[True,True,True,True,False,False,False,False,
                             False,True,False,False,False,False,True,True,
                             True,True,True,True,False] })

df['col_2'] = ((df!=df.shift(1)) & (df!=df.shift(2)) & (df!=df.shift(3)) &
               (df!=df.shift(4)) & (df!=df.shift(5)))

rawDescription: python pandas trying to reduce reliance on loops

description: Python pandas trying to reduce reliance on loops


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(10, size=(20, 2)), columns=list('AB'))
result = df.groupby('A')['B'].describe().unstack()

rawDescription: Getting statistics from different groups of rows


code:
import re
url = '/s/GETTHISDATA/canBeIgnored/canBeIgnored'
re.findall('(?<=/).*?(?=/)', url)
re.findall('(?<=/).*?(?=/)', url)[1]

rawDescription: Get data between two '/' using re module


code:
import os
import tornado.ioloop
import tornado.web

class MyFileHandler(tornado.web.StaticFileHandler):
    def initialize(self, path):
        self.dirname, self.filename = os.path.split(path)
        super(MyFileHandler, self).initialize(self.dirname)

    def get(self, path=None, include_body=True):
        # Ignore 'path'.
        super(MyFileHandler, self).get(self.filename, include_body)

app = tornado.web.Application([
    (r'/foo\.json', MyFileHandler, {'path': '/path/to/foo.json'})
])

app.listen(8888)
tornado.ioloop.IOLoop.current().start()

rawDescription: How can Tornado serve a single static file at an arbitrary location?


rawDescription: Read a file, and print a specific line of it in Python


code:
polys = []
for i in range(5):
    poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
    polys.append(poly)
gc = GeometryCollection(polys)

rawDescription: Building a GeoJSON with Python

description: Building a GeoJSON with Python


code:
b'the wreck of the hesperus'
b'\xe8\xd0\xca@\xee\xe4\xca\xc6\xd6@\xde\xcc@\xe8\xd0\xca@\xd0\xca\xe6\xe0\xca\xe4\xea\xe6'
b'the wreck of the hesperus'
b'the wreck of the hesperus'

rawDescription: Python3 Unicode Decode Error

description: Python3 Unicode Decode Error


code:
import datetime
dtobject = datetime.datetime(2999, 12, 31, 0, 0)
dtobject.strftime('%d-%b-%Y')

rawDescription: getting date fields from oracle in correct format using Python and cx-oracle

description: Getting date fields from oracle in correct format using Python and cx-oracle


code:
def decrypt(message):
    for key in range(1, 101):
        result = ""
        for char in message:
            if (ord(char) - key < 32):
                result += chr(ord(char) - key + 127 - 32)
            else:
                result += chr(ord(char) - key)
        print('key: {} -'.format(key), result)

if __name__ == '__main__':
    print('1 - Encrypt')
    print('2 - Decrypt')
    inp = input('select 1 or 2: ')
    if inp == '1':
        msg = input('Enter message: ')
        key = int(input('Enter key (1-100): '))
        print('Encrypted message:')
        print(encrypt(msg, key))
    else:
        msg = input('Enter message: ')
        decrypt(msg)

rawDescription: How can I tackle this cryptography?

description: Tackle this cryptography


code:
def parse_markup_string(string):
    '''
    Parses the string and returns a MarkupProps instance
    '''
    #The 'value' of an attribute...for some reason the same attribute is called several different things...
    attr_values = ('value', 'ink_rect', 'logical_rect', 'desc', 'color')

    #Get the AttributeList and text
    attr_list, text, accel = pango.parse_markup( string )
    attr_iter = attr_list.get_iterator()

    #Create the converter
    props = MarkupProps()
    props.text = text

    val = True
    while val:
            attrs = attr_iter.get_attrs()

            for attr in attrs:
                    name = attr.type
                    start = attr.start_index
                    end = attr.end_index
                    name = pango.AttrType(name).value_nick

                    value = None
                    #Figure out which 'value' attribute to use...there's only one per pango.Attribute
                    for attr_value in attr_values:
                            if hasattr( attr, attr_value ):
                                    value = getattr( attr, attr_value )
                                    break

                    #There are some irregularities...'font_desc' of the pango.Attribute
                    #should be mapped to the 'font' property of a GtkTextTag
                    if name == 'font_desc':
                            name = 'font'
                    props.add( name, value, start, end )

            val = attr_iter.next()

    return props

rawDescription: Convert pango markup string to GtkTextTag properties


code:
#!/usr/bin/env python

from setuptools import setup, find_packages

setup(name='proj',
      packages=find_packages(),
      package_data={'': ['*.png']})

rawDescription: Managing resources in a Python project

description: Managing resources in a Python project


code:
from __future__ import print_function
import click

@click.command()
@click.option('--name', help='Enter Name')
@click.pass_context
def gatherarguments(ctx, name):
    return ctx

def usectx(ctx):
    print("Name is %s" % ctx.params['name'])

if __name__ == '__main__':
    ctx = gatherarguments(standalone_mode=False)
    print(ctx)
    usectx(ctx)

rawDescription: python click usage of standalone_mode

description: Python click usage of standalone_mode


code:
if s.find('safe') != -1:
    print('This message is safe.')

rawDescription: How to programmatically detect and respond to a key word(s) in chat messages

description: Programmatically detect and respond to a key word(s) in chat messages


code:
import win32api, win32con

#test for a certain type of attribute
attribute = win32api.GetFileAttributes(filepath)
#The file attributes are bitflags, so you want to see if a given flag is 1.
# (AKA if it can fit inside the binary number or not)
# 38 in binary is  100110 which means that 2, 4 and 32 are 'enabled', so we're checking for that
## Thanks to Nneoneo
if attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM):
  raise Exception("hidden file") #or whatever

#or alter them
win32api.SetFileAttributes(filepath, win32con.FILE_ATTRIBUTE_NORMAL) #or FILE_ATTRIBUTE_HIDDEN

rawDescription: python os.listdir() shows protected files

description: Python os.listdir() shows protected files


code:
myString = "a\\tb\\tc\\td"
print(myString)
print(repr(myString))

rawDescription: Python strip a string from config file

description: Python strip a string from config file


code:
from collections import defaultdict
from functools import partial
from itertools import count

unique_count = defaultdict(partial(next, count(1)))
listFruit[:] = [unique_count[el] for el in listFruit]

rawDescription: Any quick way to labelize a list in Python?


code: parser_start = subparsers.add_parser('stop', formatter_class=argparse.RawTextHelpFormatter)

rawDescription: Python argparse: How to insert newline the help text in subparser?


code:
class Derived(Base):
    @staticmethod
    def decorator(func):
        whatever(fund)

rawDescription: What's the cleanest way to add a decorator from a derived class to its base class?


code:
def repl(match):
    if match.group(1) == 'Seq1:':
        return match.group(0)
    return match.group(1) + str(int(match.group(2)) + 10)

result = re.sub(r'(\w+\d+:)(\d+)', repl, s)

rawDescription: Substitution of certain occurences of a string with another string in python


code:
ord('\x80')
import struct
struct.unpack('B', '\x80')

rawDescription: How can I read hexadecimal data with python?

description: Read hexadecimal data with python


code:
l = range(10)
any(x > 10 for x in l)
l = range(20)
any(x > 10 for x in l)

rawDescription: How to achieve python's any() with a custom predicate?

description: Achieve python's any() with a custom predicate


rawDescription: Python exits CSV File before the end of File


code:
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

rawDescription: Remove unnecessary whitespace from Jinja rendered template


code:
file = open("myfile.txt")
data = file.read()
file.close()
Results = Label(window, text = data)
Results.grid(row = 1, column = 1)

rawDescription: How to print results from text file to window using Python

description: Print results from text file to window using Python


code: gb.div(gb.sum(axis=1).values, axis=0)

rawDescription: Getting Row percentages in python to plot


rawDescription: Python Greedy Algorithm

description: Python Greedy Algorithm


code:
#ifdef HAVE_GETC_UNLOCKED
#define GETC(f) getc_unlocked(f)
#define FLOCKFILE(f) flockfile(f)
#define FUNLOCKFILE(f) funlockfile(f)
#else
#define GETC(f) getc(f)
#define FLOCKFILE(f)
#define FUNLOCKFILE(f)
#endif

rawDescription: Python readline on a pipe that has been opened as non-blocking


code: grid_x, grid_y = np.mgrid[0:1:nx*1j, 0:1:ny*1j]

rawDescription: python - Extend 2-d array and interpolate the missing values

description: Python - Extend 2-d array and interpolate the missing values


code:
from shutil import copy
copy("foo.txt", "out.txt")

rawDescription: Reading/Writing to a file in Python

description: Reading/Writing to a file in Python


code: from PyQt5 import QtCore

rawDescription: Animating a rectangle in PyQT5: Why is QtCore not defined?


code:
@tools.cache()
def _get_id(self, cr, uid, module, xml_id):
    ids = self.search(cr, uid, [('module','=',module),('name','=', xml_id)])
    if not ids:
        raise ValueError('No references to %s.%s' % (module, xml_id))
    # the sql constraints ensure us we have only one result
    return ids[0]

rawDescription: OpenERP cache features

description: OpenERP cache features


code:
#!/usr/bin/env python2.7

trainFile = open("danish.train")
numberOfLines = 0

for line in trainFile:
    numberOfLines += 1

lengthTest = numberOfLines / 10

# rewind file to beginning
trainFile.seek(0)

numberOfLines = 0
file_number = 0
for line in trainFile:
    if numberOfLines % lengthTest == 0:
        file_number += 1
        output = open('danish.train.part-%02d' % file_number, 'w')

    numberOfLines += 1
    output.write(line)

rawDescription: how to extract specific lines from a data file

description: Extract specific lines from a data file


rawDescription: Dynamically assigning variable with locals() isn't working in recursive function


code:
def gen_subsets_special(full_set, M, seed=123456):
    # generate randomish M-subsets of full_set, "far apart".
    import random
    from random import sample
    random.seed(seed)
    elements = list(full_set)
    N = len(elements)
    hi = set(range(N))
    lo = set()
    while True:
        assert not (hi & lo)
        assert len(lo | hi) == N
        # First take indices from hi, then (if needed) from lo.
        if len(hi) > M:
            # We can take all of them from hi, with some left over.
            ixhi = set(sample(hi, M))
            ixlo = set()
            # The ixhi counts go down by 1, so move 'em to lo
            hi -= ixhi
            lo |= ixhi
            assert hi
        else:
            # We need to take everything in hi.
            ixhi = hi.copy()
            ixlo = set(sample(lo, M - len(ixhi)))
            hi |= lo - ixlo
            lo = ixlo
        assert not (ixlo & ixhi)
        ix = ixlo | ixhi
        assert len(ix) == M
        yield set(elements[i] for i in ix)

rawDescription: Deterministic python generator for K disparate M-sized subsets of a set


code:
from io import StringIO
timeit(lambda: truncate(StringIO()))
timeit(lambda: new(StringIO()))

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
import re
inputtext = "{% url 'a' b c e %}"
[r[:1] + tuple(r[1].split())
 for r in re.findall(r"{% url '(\w+)'((?:\s+\w+)*) %}", inputtext)]

rawDescription: python 3.3 RE How to grab possible groups?

description: Python 3.3 RE How to grab possible groups


rawDescription: counting up and then down a range in python

description: Counting up and then down a range in python


code:
sentinel = object()
def func(arg=sentinel):
    if arg is sentinel:
       arg = "default"
    do_code()

rawDescription: How to implement optional first argument in Python (reproduce slice() behavior)

description: Implement optional first argument in Python (reproduce slice() behavior)


rawDescription: Python: Way to speed up a repeatedly executed eval statement?


code: cond = cond1 & cond2 & cond3

rawDescription: extracting specific rows of Nx3 array whereby each column satisfies condition

description: Extracting specific rows of Nx3 array whereby each column satisfies condition


code: webbrowser.get('windows-default').open('{ url path for static html page }')

rawDescription: python html pop open

description: Python html pop open


code:
from urllib import urlopen, urlencode
data = {'sgE-1416699-3-2':'10002', 'more_param':'param_value'}
encodeddata = urlencode(data)
url = 'http://surveygizmo.com'

rawDescription: Sending javascript form data in python (post request)?


code:
def func(a_dict):
    """Some function to do something to a dictionary.

    Args:
      a_dict (dict of str: int): Some mapping, I guess?

    """
    ...

rawDescription: How to add python docstring for dict

description: Add python docstring for dict


code:
def check_spider_pipeline(process_item_method):
    """
        This wrapper makes it so pipelines can be turned on and off at a spider level.
    """
    @functools.wraps(process_item_method)
    def wrapper(self, item, spider):
        msg = '%%s %s pipeline step' % (self.__class__.__name__,)
        if self.__class__ in spider.pipeline:
            spider.log(msg % 'executing', level=log.DEBUG)
            return process_item_method(self, item, spider)
        else:
            spider.log(msg % 'skipping', level=log.DEBUG)
            return item

    return wrapper

rawDescription: How to use a decorator to enable a spider to distinguish between scrapy pipelines

description: Use a decorator to enable a spider to distinguish between scrapy pipelines


code:
def findQuakeAge(entry):
    start = entry.find('<category label="Age" term="') + 28
    end = entry.find('"/>', start)
    age = entry[start:end]
    return age

rawDescription: How to find information from the last 24 hours

description: Find information from the last 24 hours


code:
class c:
  pass

rawDescription: What's a standard way to do a no-op in python?


code:
class Base(object):
    flagAtt = None

    def __init__(self) :
       pass

    @classmethod
    def flag(self):
        return self.flagAtt

class Derived(Base):
    flagAtt = True

rawDescription: Python - Redefining class attribute in a derived class


code:
it = iter([0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0])
s = 'stackoverflow'

output = [''.join(('-' for i in b) if not a else b)
          for a,b in
          itertools.groupby(s, key=lambda x: next(it))]

rawDescription: Format string by binary list

description: Format string by binary list


code:
person, john, smith
person, anne, frank
person, bob, macdonald
fruit, orange, banana
fruit, strawberry, fields
fruit, ringring, banana

rawDescription: Compare entries in columns from CSV files and extract matched - python


rawDescription: seg fault when called from python, but runs normally from the command line

description: Seg fault when called from python, but runs normally from the command line


code: df.groupby('Date').agg({'Name': lambda x: '{}/{}'.format(x.isnull().sum(), len(x))})

rawDescription: Python count Null and not Null values in Dataframe


code:
f = dictify(g)
f2 = listify(f)
f3 = intify(f2)
f3()
f3.__list is f2.__list
f3.__dictionary is f2.__dictionary
f3.__int is f2.__int

rawDescription: Why do list/dict attributes retain values outside decorators, but integer attribues do not?


rawDescription: Parsing custom string

description: Parsing custom string


code:
n_test = 200
test_idx2 = gen.choice(test_idx, size=n_test)

rawDescription: Cross-validation: finding row indices for a test set that aren't part of a training set


code:
import re
data = re.findall('<body>([^\<]*)</body>', result)[0]

rawDescription: Parsing fixed-format data embedded in HTML in python


code: users = set(users)

rawDescription: python filtering list for duplicate objects

description: Python filtering list for duplicate objects


code:
import collections
sortedWords = collections.defaultdict(list)

rawDescription: Print different results in Python a dictionary


code:
e = Empty(initial='optional-value')
e.initial
# 'optional-value'
e.val = 'foo'
e.val
# 'foo'
e.bad
# AttributeError: 'Empty' object has no attribute 'bad'
setattr(e, 'user', 'jdi')
e.user
# 'jdi'
e['user']
# 'jdi'

# note that you dont even see anything when you dir()
dir(e)
# []

# and trying to access _obj is protected
e._obj
#AttributeError: 'Empty' object has no attribute '_obj'

# But you could even set your own _obj attribute
e._obj = 1
e._obj
# 1

rawDescription: Creating Truly Empty Types in Python

description: Creating Truly Empty Types in Python


code: sorted(alpha_items, key=lambda x: x[1], reverse=True)

rawDescription: how to sort a list of tuples with list[i][1] as key from biggest to smallest

description: Sort a list of tuples with list[i][1] as key from biggest to smallest


code:
def semi_heap_sort(items, top_k=L):
    lst = []
    heap_store = items[:top_k]

rawDescription: Python performance: heaps

description: Python performance: heaps


code:
class dform(forms.Form):
    location = forms.ChoiceField(choices = get_location_choices())

# elsewhere
from django.db import connection
def get_location_choices():
    cursor = connection.cursor()
    cursor.execute("select location_id, name from location_table")
    return cursor.fetchall()

rawDescription: update django choice field with database results

description: Update django choice field with database results


code: print(all(x >= b[ind] for ind,x in enumerate(a)))

rawDescription: Python: pairwise comparison between two lists: list a >= list b?


code:
import sys
sys.path = [dir for dir in sys.path if dir != '']

rawDescription: changing namespace of current python script (class with module name)

description: Changing namespace of current python script (class with module name)


code:
def _quicksort(count, other_context, A, left=None, right=None):
    ...
    count1, other_context1 = _quicksort(count, other_context, A, left, right)
    ...
    return count + count1, other_context

rawDescription: Counting comparisons quicksort without global Python


code:
class Card(object):

    FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}

    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        value = self.FACES.get(self.rank, self.rank)
        return "{0} of {1}".format(value, self.suit)

    def __lt__(self, other):
        return self.rank < other.rank

rawDescription: Python Simple Card Game to Learn Classes


code:
def create():
    return object()

rawDescription: How do I write a no-op or dummy class in Python?

description: Write a no-op or dummy class in Python


code:
'x' in b
'foo' in b

rawDescription: Is there a Python dict without values?

description: Is there a Python dict without values


code:
import socket

try:
    _GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT
except AttributeError:
    _GLOBAL_DEFAULT_TIMEOUT = object()

rawDescription: how do i set a timeout value for python's mechanize?

description: Set a timeout value for python's mechanize


code:
a = numpy.array(['a', 'b', 'c', 'd', 'e'])
b = numpy.arange(5)
records = numpy.rec.fromarrays((a, b), names=('keys', 'data'))
records
records['keys']
records['data']

rawDescription: Store different datatypes in one NumPy array?


code:
names = ['Tomato', 'Snoskommer', 'Pepper'] # a list containing 3 names
vegetables = {} # an empty dictionary

for name in names: # just textual: for each name in the names list ...
    new_veg = Veg(name) # create a new vegetable with the name stored in the variable 'name'
    vegetables[name] = new_veg # add the new vegetable to the vegetable dictionary

# at this point, the vegetables dictionary will contain a number of vegetables, which you can find by
# 'indexing' the dictionary with their name:
print(vegetables['Tomato'].name) # will print 'Tomato'

rawDescription: Variable creation within a program

description: Variable creation within a program


code:
with open('file') as f:
    my_list = [x.strip() for x in f]

rawDescription: converting a text list (string)to a python list

description: Converting a text list (string)to a python list


code: dctResult = [{'id': item, 'Value': avg(values)} for item, values in items.items()]

rawDescription: Link two dictionaries lists and calculate average values


code: np.newaxis is None

rawDescription: Remove mean from numpy matrix

description: Remove mean from numpy matrix


code:
def is_morse(message):
    allowed = {".", "-", " "}
    return allowed.issuperset(message)

rawDescription: If String ONLY contains "-" or "."

description: If String ONLY contains "-" or "."


rawDescription: Search range of int values using djapian


rawDescription: Python match raw HTTP POST data

description: Python match raw HTTP POST data


rawDescription: Remove element from list without side-effect


code:
df_copy['A'] = df['B']
df_copy.loc[df['D']=='Other', 'A'] = df['C']

rawDescription: Copy value from one column based on the value of another column


code:
import yaml

from collections import OrderedDict

def represent_ordereddict(dumper, data):
    value = []

    for item_key, item_value in data.items():
        node_key = dumper.represent_data(item_key)
        node_value = dumper.represent_data(item_value)

        value.append((node_key, node_value))

    return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value)

yaml.add_representer(OrderedDict, represent_ordereddict)

rawDescription: Can PyYAML dump dict items in non-alphabetical order?


code:
import uuid
uuid.uuid1().bytes.encode('base64').rstrip('=\n').replace('/', '_')

rawDescription: Convert UUID 32-character hex string into a "YouTube-style" short id and back


code:
returnList = [r120item for r120item in r120Final
                 if (r120item[2].strip(), r120item[10]) not in
                     set((str(spectraItem[0]), str(spectraItem[25]))
                         for spectraItem in spectraFinal)]

rawDescription: Nested for loop to search 2 lists

description: Nested for loop to search 2 lists


rawDescription: get the max of R,G,B of one image by using programming

description: Get the max of R,G,B of one image by using programming


code:
x
y

rawDescription: Working with multiple columns from a data file


code:
...
kernel=mod.get_function("foo")
meminfo(kernel)
...
def meminfo(kernel):
    shared=kernel.shared_size_bytes
    regs=kernel.num_regs
    local=kernel.local_size_bytes
    const=kernel.const_size_bytes
    mbpt=kernel.max_threads_per_block
    print("""=MEM=\nLocal:%d,\nShared:%d,\nRegisters:%d,\nConst:%d,\nMax Threads/B:%d"""%(local,shared,regs,const,mbpt))

rawDescription: PyCUDA: Querying Device Status (Memory specifically)


code: for state in states: score += penalty if state == bad else bonus

rawDescription: Python Ternary Style: Is this good or bad style?


rawDescription: How to prepend an element to a list in Mongoengine

description: Prepend an element to a list in Mongoengine


code:
for x in my_list:
   pass # do something

rawDescription: How do I remove an element from a list without using .remove

description: Remove an element from a list without using .remove


code: ['blue', 'white', 'red']

rawDescription: Remove all but certain words from a list (like a white list)


code:
grouped = df.groupby('ID')['Number'].max().to_dict()
df['Total'] = df.apply((lambda row:5 if grouped[row['ID']] else 0), axis=1)

rawDescription: Apply a value to all instances of a number based on conditions


code:
from decimal import Decimal
map(Decimal,s)

rawDescription: converting strings to numeric

description: Converting strings to numeric


rawDescription: how to retrieve field value (values are itself string)in given line using regular expression in python

description: Retrieve field value (values are itself string)in given line using regular expression in python


code: fruits = {Fruit('apple', 'red'), Fruit('banana', 'yellow')}

rawDescription: Accessing list of Python objects by object attribute


rawDescription: I need to know how to sort my dictionary on python by aveage scores with students with multi-ple scores?


code:
class Location(models.Model):
    locationname = models.CharField(max_length=100)

    def __unicode__(self):
        return self.locationname

    def latest(self):
        return Rating.objects.values('rating').filter(von_location=self).order_by('-id')[0]

class Rating(models.Model):
   von_location = models.ForeignKey(Location,related_name="locations_rate")
   rating = models.IntegerField()

   def __unicode__(self):
        return "{0}".format(self.rating)

rawDescription: last record in django models database

description: Last record in django models database


code:
#!/usr/bin/python3

import threading
from queue import Queue

class IRCBetBot(threading.Thread):
    def __init__(self, q, playerName, channelName, currencyName):
        super().__init__()
        self.channel = channelName
        self.playerName = playerName
        self.currencyName = currencyName
        self.queue = q

    def run(self):
        readbuffer = ""
        while 1:
            readbuffer = self.queue.get()  # This will block until a message is sent to the queue.
            print("{} got msg {}".format(self.channel, readbuffer))

if __name__ == "__main__":

    authorisedChannels = [["user1","#channel1","coin1"],
                          ["user2","#channel2","coin2"],
                          ["user3","#channel3","coin3"]]

threads = {}
for item in authorisedChannels:
    try:
        userName = item[0]
        channelName = item[1]
        currencyPrefix = item [2]
        myTuple = (userName,channelName,currencyPrefix)
        q = Queue()
        thread = IRCBetBot(q, *myTuple )
        thread.start()
        threads[channelName] = (q, thread)
    except Exception as e:
        print("An error occurred while creating threads.")
        print(str(e))

while 1:
    a = input("Input your message (channel: msg): ")
    channel, msg = a.split(":")
    threads[channel][0].put(msg)  # Sends a message using the queue object

rawDescription: Send a string message to multiple threads


code:
@synchronized # lock bound to function1
def function1():
    pass

@synchronized # lock bound to function2
def function2():
    pass

@synchronized # lock bound to Class
class Class(object):

    @synchronized # lock bound to instance of Class
    def function_im(self):
        pass

    @synchronized # lock bound to Class
    @classmethod
    def function_cm(cls):
        pass

    @synchronized # lock bound to function_sm
    @staticmethod
    def function_sm():
        pass

rawDescription: Possible to create a @synchronized decorator that's aware of a method's object?


code:
def add_steps(routes, finished_routes):
    new_routes = []
    for r in routes:
        end = r[-1]
        r_finished = True
        for s in steps:
            if s[0] == end:
                new_routes.append(r + [s[1]])
                r_finished = False
        if r_finished:
            finished_routes.append(r)
    return new_routes, finished_routes

rawDescription: Python compare list and store in new variable


rawDescription: Problems Parsing NBA Boxscore Data with BeautifulSoup


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '<your_username>$<your_database_name>',
        'USER': '<your_username>',
        'PASSWORD': '<your_mysql_password>',
        'HOST': 'mysql.server',
    }
}

rawDescription: Pythonanywhere MySQL connection

description: Pythonanywhere MySQL connection


code:
with open('/tmp/test_list.json') as f:
    test_list = json.load(f)

rawDescription: Import dictionary containings lists from csv


code: list(d)

rawDescription: Python Dictionary Methods behaving diff for 2.7.6 and 3.3 version


rawDescription: How can I properly join these strings together (by column then row)?

description: Properly join these strings together (by column then row)


rawDescription: 2d list to 3d list in python

description: 2d list to 3d list in python


code: "abcde"

rawDescription: Python: Read binary file into buffer as integer then Slice


code:
import re
re.findall("\d+\.\d+", "Current Level: 13.4 db.")

rawDescription: How to extract a floating number from a string in Python

description: Extract a floating number from a string in Python


code:
import pexpect
child = pexpect.spawn('vlc -I rc --novideo --noaudio --rc-fake-tty -q  udp://@1.2.3.4:1234')
child.expect('>')
child.sendline('info')
response = child.before

rawDescription: run command in interactive opend bash with python

description: Run command in interactive opend bash with python


rawDescription: How to count similar domains in emails and print every domain only once[python]?

description: Count similar domains in emails and print every domain only once[python]


code: self.root = binary_insert(list_in,0,len(list_in) - 1)

rawDescription: Confusion with recursion and property setters in Python


code:
import itertools

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

import cartopy.feature
from cartopy.mpl.patch import geos_to_path
import cartopy.crs as ccrs

fig = plt.figure()
ax = Axes3D(fig, xlim=[-180, 180], ylim=[-90, 90])
ax.set_zlim(bottom=0)

target_projection = ccrs.PlateCarree()

feature = cartopy.feature.NaturalEarthFeature('physical', 'coastline', '110m')
geoms = feature.geometries()

geoms = [target_projection.project_geometry(geom, feature.crs)
         for geom in geoms]

paths = list(itertools.chain.from_iterable(geos_to_path(geom) for geom in geoms))

# At this point, we start working around mpl3d's slightly broken interfaces.
# So we produce a LineCollection rather than a PathCollection.
segments = []
for path in paths:
    vertices = [vertex for vertex, _ in path.iter_segments()]
    vertices = np.asarray(vertices)
    segments.append(vertices)

lc = LineCollection(segments, color='black')

ax.add_collection3d(lc)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Height')

plt.show()

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


rawDescription: how connect to vertica using pyodbc

description: How connect to vertica using pyodbc


rawDescription: How does Python implement random.choice() from a set?


rawDescription: matplotlib: remove horizontal gap between axes?

description: Matplotlib: remove horizontal gap between axes


code:
if __name__ == '__main__':
    import os
    import sys
    import subprocess
    import textwrap

    class SECURITY_ATTRIBUTES(ctypes.Structure):
        _fields_ = (('nLength',              wintypes.DWORD),
                    ('lpSecurityDescriptor', wintypes.LPVOID),
                    ('bInheritHandle',       wintypes.BOOL))
        def __init__(self, *args, **kwds):
            super(SECURITY_ATTRIBUTES, self).__init__(*args, **kwds)
            self.nLength = ctypes.sizeof(self)

    def test_remote(use_pid=True, show_modules=False):
        sa = SECURITY_ATTRIBUTES(bInheritHandle=True)
        hEvent = kernel32.CreateEventW(ctypes.byref(sa), 0, 0, None)
        try:
            script = textwrap.dedent(r"""
            import sys
            import ctypes
            kernel32 = ctypes.WinDLL('kernel32')
            kernel32.SetEvent(%d)
            sys.stdin.read()""").strip() % hEvent
            cmd = '"%s" -c "%s"' % (sys.executable, script)
            proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                                    close_fds=False)
            try:
                kernel32.WaitForSingleObject(hEvent, 5000)
                if use_pid:
                    pi = ProcessInformation(proc.pid)
                else:
                    pi = ProcessInformation(handle=int(proc._handle))
                assert pi.process_id == proc.pid
                assert pi.image_path == sys.executable
                assert pi.command_line == cmd
                assert pi.module_names[0] == sys.executable
                if show_modules:
                    print('\n'.join(pi.module_names))
            finally:
                proc.terminate()
        finally:
            kernel32.CloseHandle(hEvent)

    print('Test 1: current process')
    pi = ProcessInformation()
    assert os.getpid() == pi.process_id
    assert pi.image_path == pi.module_names[0]
    print('Test 2: remote process (Handle)')
    test_remote(use_pid=False)
    print('Test 3: remote process (PID)')
    test_remote(show_modules=True)

rawDescription: How to access the PEB of another process with python ctypes

description: Access the PEB of another process with python ctypes


code:
category = Counter({'a': 8508, 'c': 345, 'w': 60})
category.keys()
for key, value in category.items():
    print(key, value)

rawDescription: Formatting output of Counter

description: Formatting output of Counter


code:
import math
class Foo:
    def __init__(self):
        self.foo = 4
    def bar(self):
        print("hello world")

    def foo(self):
        return self.bar()

def bar():
    return 123

f = Foo()

rawDescription: Comment Python function calls in a string with source code


code:
from bs4.element import NavigableString, Tag

def extractNavigableStrings(context):
    strings = []
    for e in context.children:
        if isinstance(e, NavigableString):
            strings.append(e)
        if isinstance(e, Tag):
            strings.extend(extractNavigableStrings(e))
    return strings

rawDescription: How to scrape between span tags using beautifulsoup

description: Scrape between span tags using beautifulsoup


rawDescription: Python List Question

description: Python List Question


code:
def makeSomeNicelyDecoratedSubclass(someclass):
  return type('MyNiceName', (someclass,), {'new_attribute':'something'})

rawDescription: Python decorate a class to change parent object type


rawDescription: Find indexes of equal numpy 2D rows

description: Find indexes of equal numpy 2D rows


code:
class FileSystemLoaderWithBase(jinja2.FileSystemLoader):
    def __init__(self, *args, **kwargs):
        self.base_template = kwargs.pop("base_template", None)
        super(FileSystemLoaderWithBase, self).__init__(*args, **kwargs)

    def get_source(self, environment, template):
        (source, path, creation) = super(
            FileSystemLoaderWithBase, self).get_source(environment, template)
        if self.base_template and template != self.base_template:
            source = '{% extends "' + self.base_template + '" %}\n' + source
        return (source, path, creation)

rawDescription: How to set a base template for jinja2 in python?

description: Set a base template for jinja2 in python


code:
import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')

rawDescription: Import python module NOT on path

description: Import python module NOT on path


code: self.label = Label().pack(side=LEFT) # pack return nothing -> None

rawDescription: How to control if a component exists in a Tk object/window?

description: Control if a component exists in a Tk object/window


code:
WS = type("WS", (Warning, StopIteration), {})
warnings.simplefilter("error", WS)
list(type("R", (object,), dict(__init__=lambda self, stop: (setattr(self, 'stop', stop), setattr(self, 'i', 0), None)[-1], __iter__=lambda self: self, next=lambda self: (self.i, setattr(self, 'i', self.i + 1))[0] if self.i < self.stop else warnings.warn("Stop", WS)))(5))

rawDescription: Raising and catching exceptions in an expression in Python 3


rawDescription: Accessing Pyramid database outside of WSGI instance


code:
import byteplay
import cjson

def _other():
    from os import path
    from sys import modules

def do_something():
    import hashlib
    import lxml
    _other()

rawDescription: Python dependencies?

description: Python dependencies


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

x = np.linspace(1, 20, 100)
y = np.sin(x)/x

plt.plot(x, y, '-ob', lw=2, markersize=12)

i = np.where( (x>11) & (x<20) & (y>-0.1))
y[i]*=2

plt.plot(x, y, 'g', lw=2)
plt.show()

rawDescription: how to magnify a peak in matplotlib?

description: Magnify a peak in matplotlib


rawDescription: Round to the nearest 500, Python

description: Round to the nearest 500, Python


code: input_list = ['  \n  ','  data1\n ','   data2\n','  \n','data3\n']

rawDescription: Python - list comprehension in this case is efficient?


code: df.loc[df['column_name'] == some_value]

rawDescription: Select rows from a DataFrame based on values in a column in pandas


rawDescription: Python Decimals format

description: Python Decimals format


code:
import subprocess
def view_file(filepath):
    subprocess.Popen(filepath, shell=True).wait()

rawDescription: How to extract a file within a folder within a zip in python?

description: Extract a file within a folder within a zip in python


code:
data = file2.read()
data = data.lower() #make it all lowercase
data = re.sub("[,-]","",data) #replace unwanted punctuation
list2= data.splitlines()

rawDescription: Return matching strings from different txt files containing lists. Each item on new line


code:
def func(word, lst):
  return min((dist(word, w), w) for w in lst)[1]

rawDescription: How to return the most similar word from a list of words?

description: Return the most similar word from a list of words


code:
import os, glob
for f in glob.glob('~*~*~*.csv'):
    os.rename(f,f.split('~')[-1])

rawDescription: extract values/renaming filename in python

description: Extract values/renaming filename in python


rawDescription: Splitting a string with multiple delimiters and conditions


rawDescription: Filtering a dictionary by multiple values


code:
['beef', 'rob', 'easy', 'test', 'guys']
['bar', 'name', 'Dave', 'hello', 'hello']

rawDescription: Get added and removed words between two strings


code:
from itertools import permutations

encompassed_ranges = []
for a, b in permutations(my_ranges, 2):
    if a not in encompassed_ranges: # to cut short if it is already there
        if is_encompassed_by(a, b):
            encompassed_ranges.append(a)

not_encompassed_ranges = [r for r in my_ranges if r not in encompassed_ranges]

rawDescription: How to approach list of range of values

description: Approach list of range of values


code:
df3 = df2.unstack()
df3.columns = df3.columns.droplevel(0)
df3.reset_index()

rawDescription: Pivoting pandas DataFrame -- AssertionError: Index length did not match values


code:
import re
import socket

import pytest

def __get_pod():
    hostname = socket.gethostname()
    hostname = hostname.split('.', 1)[0]
    if '-' not in hostname:
        return 'Unknown'
    hostname = re.sub(r'\d+', '', hostname)
    return hostname.rsplit('-', 1)[0]

@pytest.mark.parametrize(['hostname', 'expected'], [
    ["web01-east.domain.com", 'web'],
    ["redis01-master-east.domain.com", 'redis-master'],
    ["web01.domain.com", 'Unknown'],
])
def test__get_pod(monkeypatch, hostname, expected):
    monkeypatch.setattr(socket, 'gethostname', lambda: hostname)
    assert __get_pod() == expected

rawDescription: py.test multiple tests for different results

description: Py.test multiple tests for different results


rawDescription: replace or remove one null (python)

description: Replace or remove one null (python)


code:
valid = (quarters <= months.max()) & (quarters >= months.min())
loc = loc[valid]

rawDescription: Equivalent of Matlab 'ismember' in numpy (Python)?


code:
no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '',
# which puts all of the characters together.
result = ''.join(no_digits)

rawDescription: Removing numbers from string

description: Removing numbers from string


code: math.sqrt(sum((a.get(k, 0) - b.get(k, 0))**2 for k in set(a.keys()).union(set(b.keys()))))

rawDescription: Calculate euclidean distance between two vector (bag of words) in python


code:
def lists_to_sets(d):
    for k, v in d.items():
        if isinstance(v, list):
            d[k] = set(v)
        elif isinstance(v, dict):
            lists_to_sets(v)

description: Python dictionary(dictionary(dictionary(list))) comparison


code:
d_max = {k:max(d[k]) for k in d}
d_max

rawDescription: Sorting a dictionary by highest value of nested list


code:
if obj is not None:
    return self.method(obj, *args, **kwargs)
else:
    return self.method(objtype, *args, **kwargs)

rawDescription: Using same function as instance and classmethod in python


code:
#!python3
import codecs
import sys
byte_string = '\u5000\u5001\u5002'.encode('utf8')

# Get the UTF-8 incremental decoder.
decoder_factory = codecs.getincrementaldecoder('utf8')
decoder_instance = decoder_factory()

# Simple example, read two bytes at a time from the byte string.
result = ''
for i in range(0,len(byte_string),2):
    chunk = byte_string[i:i+2]
    result += decoder_instance.decode(chunk)
    print('chunk={} state={} result={}'.format(chunk,decoder_instance.getstate(),ascii(result)))
result += decoder_instance.decode(b'',final=True)
print(ascii(result))

rawDescription: Python 3- check if buffered out bytes form a valid char


code: self.myList = (self.myList + [0] * 4)[:4]

rawDescription: Padding a list in python with particular value


code:
import pandas as pd

def convert(s):
    ls = s.split()
    d = {'day': 1, 'week': 7, 'month': 30, 'year': 360}
    for k, v in d.items():
        if ls[1].startswith(k):
            return int(ls[0]) * v

df = pd.DataFrame({'Col': ['3 days', '5 weeks', '1 year']})

df['Col'] = df['Col'].apply(convert)

print(df)

rawDescription: pandas map string column with a function

description: Pandas map string column with a function


rawDescription: Navigating to second string text using BeautifulSoup


code: sorted(var, key=lambda v: (v.upper(), v[0].islower()))

rawDescription: python sort upper case and lower case

description: Python sort upper case and lower case


code:
import struct
import itertools as IT

def unpack_formats(fmts, data):
    data = iter(data)
    return [struct.unpack(fmt, ''.join(IT.islice(data, struct.calcsize(fmt))))
            for fmt in fmts]

data = struct.pack('<?3h3h', True, 1,2,3,4,5,6)
fmts = ('<?', '<3h', '<3h')
(is_enabled,), cmd_speed, tach_speed = unpack_formats(fmts, data)
print(is_enabled, cmd_speed, tach_speed)

rawDescription: Python - unpack struct into multiple tuples


code: [v for k,v in a.items() if k[2] == 'l1p']

rawDescription: Get elements of a tuple-indexed dictionary specifying only one field of the tuple


code:
class Interface(tk.Frame):
    def __init__(self, master, canvas):
        ...
        self._canvas = canvas
        ...
    def clearall(self):
        self._canvas.delete(tk.ALL)

class App(object):
    def __init__(self, master):
        ...
        self._canvas = tk.Canvas(master, bg='white')
        self._interface = Interface(master, self._canvas)
        ...

rawDescription: Conveying a tkinter button's execution across different classes?


code:
from string import maketrans
from string import ascii_lowercase
cipher_map = maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[:1])
text = 'the quick brown fox jumped over the lazy dog'
text.translate(cipher_map)

rawDescription: How to replace characters in string by the next one?

description: Replace characters in string by the next one


code:
with open('131014-data-xy-conv-1.txt', 'r') as f:
    x = np.array(f.readline().split(',')[1:], int)
    y_and_data = np.genfromtxt(f, delimiter=',')
y = y_and_data[:,0]
data = y_and_data[:,1:]

rawDescription: How to manipulate the data after numpy.loadtxt?

description: Manipulate the data after numpy.loadtxt


code:
class MyClass(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return self.x + other

rawDescription: Add to custom class in Python

description: Add to custom class in Python


code:
from scipy.sparse import csc_matrix
from pyspark.mllib.regression import LabeledPoint

m1 = csc_matrix((
   v1.values,
   (v1.indices, [0] * v1.numNonzeros())),
   shape=(v1.size, 1))

m2 = csc_matrix((
   v2.values,
   (v2.indices, [0] * v2.numNonzeros())),
   shape=(v2.size, 1))

LabeledPoint(0, m1 + m2)

rawDescription: How to add two Sparse Vectors in Spark using Python

description: Add two Sparse Vectors in Spark using Python


code: area = [height*width]

rawDescription: How to write a program in python 3.3.4 that works out the area of a rectangle?

description: Write a program in python 3.3.4 that works out the area of a rectangle


code:
corrected_rows = []
for row in cursor.execute('SELECT id, name FROM company'):
    corrected_rows.append((row[0], row[1].replace(',', '')))

rawDescription: (Python) How to edit existing rows in a SQL DB?


code: multiplications[(i, j)] = i * j

rawDescription: Is my thought process right?

description: Is my thought process right


code:
with open(sys.argv[1]) as ifile, open(sys.argv[2], mode = 'w') as ofile:
    for row in ifile:

    #...
    #You've defined some_condition to be met (you will have to replace this for yourself)
    #E.g.: the number of entries in each row is greater than 5:
        if len([term for term in row.split('#') if term.strip() != '']) > 5:
            ofile.write(row)

rawDescription: write csv row (from within for loop) out to csv file without using python csv module

description: Write csv row (from within for loop) out to csv file without using python csv module


rawDescription: how to access index in a pandas HDStore (pyTables)

description: Access index in a pandas HDStore (pyTables)


code:
import yql
y = yql.Public()
query = 'SELECT * FROM yahoo.finance.option_contracts WHERE symbol="SPY"'
y.execute(query, env="store://datatables.org/alltableswithkeys")

rawDescription: YQL - No definition found for Table

description: YQL - No definition found for Table


code:
for col in cols['count']:
    print(col)

rawDescription: How to count numbers in a list from a csv file filtering out words and commas

description: Count numbers in a list from a csv file filtering out words and commas


code:
import csv

with open('test.csv') as csvfile:
    rows = csv.reader(csvfile)
    res = list(zip(*rows))
    print(res)
    # [('6', '5', '7'), ('2', '2', '3'), ('4', '3', '6')]

rawDescription: How can I turn a csv file into a list of list in python

description: Turn a csv file into a list of list in python


rawDescription: Ordered Dictionary is not sorting

description: Ordered Dictionary is not sorting


code:
plt.axis('equal')
plt.tight_layout()

rawDescription: matplotlib: Don't compress plot in the horizontal direction

description: Matplotlib: Don't compress plot in the horizontal direction


code: sorted(((k1, k2) for k1 in d for k2 in d[k1]), key=lambda t: d[t[0]][t[1]], reverse=True)

rawDescription: Sort nested dictionary python 2.7, by deepest value, return key tuples


code:
def foo(a, b):
    if a == 0 or b == 0:
       return a or b

rawDescription: If else condition with or, return variable that evalutes to FALSE


rawDescription: How to convert a column or row matrix to a diagonal matrix in Python?

description: Convert a column or row matrix to a diagonal matrix in Python


rawDescription: Get a text file specific field issue

description: Get a text file specific field issue


code:
from ipwhois import IPWhois
obj = IPWhois('74.125.225.229')
res=obj.lookup()
res["nets"][0]['country']
res["nets"][0]['abuse_emails']
from pprint import pprint
pprint(res)

rawDescription: How to get WhoIs info by IP in Python 3?

description: Get WhoIs info by IP in Python 3


code:
def thingy(theirnumber):
    if theirnumber > 10:
        return ClassB.ClassB(theirnumber)
    else:
        return ClassA.ClassA(theirnumber)

rawDescription: How to replace an instance in __init__() with a different object?

description: Replace an instance in __init__() with a different object


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

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
    new_cmap = colors.LinearSegmentedColormap.from_list(
        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
        cmap(np.linspace(minval, maxval, n)))
    return new_cmap

arr = np.linspace(0, 50, 100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2)

cmap = plt.get_cmap('jet')
new_cmap = truncate_colormap(cmap, 0.2, 0.8)
ax[0].imshow(arr, interpolation='nearest', cmap=cmap)
ax[1].imshow(arr, interpolation='nearest', cmap=new_cmap)
plt.show()

rawDescription: how to extract a subset of a colormap as a new colormap in matplotlib?

description: Extract a subset of a colormap as a new colormap in matplotlib


rawDescription: Modifying diagonals in multidimensional numpy arrays


code:
import lxml.etree as ET
parser = ET.XMLParser(remove_comments=False)
tree = etree.parse('data', parser=parser)

rawDescription: updating XML attribute value in python

description: Updating XML attribute value in python


rawDescription: PyQt4: Reorder Ok and Cancel buttons in the QDialogButtonBox


code:
f('abcde')
f(*'abcde')

rawDescription: How do I convert tuple of tuples to list in one line (pythonic)?

description: Convert tuple of tuples to list in one line (pythonic)


code:
import os

os.system("start " + pdf_path)

rawDescription: Path information for a python application installed in a different folder per users


rawDescription: Getting unique items from a two dimensional array python


code:
SOCIAL_AUTH_PIPELINE = (
    'social_auth.backends.pipeline.social.social_auth_user',
    'social_auth.backends.pipeline.user.get_username',
    'social_auth.backends.pipeline.user.create_user',
    'social_auth.backends.pipeline.social.associate_user',
    'social_auth.backends.pipeline.social.load_extra_data',
    'social_auth.backends.pipeline.user.update_user_details',
    'myapp.pipeline.create_profile'
)

rawDescription: django social-auth multiple account association

description: Django social-auth multiple account association


code:
import re

MatchObject = type(re.search('', ''))

rawDescription: Python : using isinstance on C based type MatchObject


code:
import networkx as nx
import multiprocessing as mp
import random
import sys
import itertools as IT
import logging
logger = mp.log_to_stderr(logging.DEBUG)

def worker(inqueue, output):
    result = []
    count = 0
    for pair in iter(inqueue.get, sentinel):
        source, target = pair
        for path in nx.all_simple_paths(G, source = source, target = target,
                                        cutoff = None):
            result.append(path)
            count += 1
            if count % 10 == 0:
                logger.info('{c}'.format(c = count))
    output.put(result)

def test_workers():
    result = []
    inqueue = mp.Queue()
    for source, target in IT.product(sources, targets):
        inqueue.put((source, target))
    procs = [mp.Process(target = worker, args = (inqueue, output))
             for i in range(mp.cpu_count())]
    for proc in procs:
        proc.daemon = True
        proc.start()
    for proc in procs:
        inqueue.put(sentinel)
    for proc in procs:
        result.extend(output.get())
    for proc in procs:
        proc.join()
    return result

def test_single_worker():
    result = []
    count = 0
    for source, target in IT.product(sources, targets):
        for path in nx.all_simple_paths(G, source = source, target = target,
                                        cutoff = None):
            result.append(path)
            count += 1
            if count % 10 == 0:
                logger.info('{c}'.format(c = count))

    return result

sentinel = None

seed = 1
m = 1
N = 1340//m
G = nx.gnm_random_graph(N, int(1.7*N), seed)
random.seed(seed)
sources = [random.randrange(N) for i in range(340//m)]
targets = [random.randrange(N) for i in range(1000//m)]
output = mp.Queue()

if __name__ == '__main__':
    test_workers()
    # test_single_worker()
    # assert set(map(tuple, test_workers())) == set(map(tuple, test_single_worker()))

rawDescription: Using multiprocessing for finding network paths


code:
L = ['a', 'b', 'c']
def addtxt():
    print(L)
    L = [s + '.txt' for s in L]
addtxt()

rawDescription: How to modify list entry in python 2.x, using loop

description: Modify list entry in python 2.x, using loop


code:
desired_names = ['name1', 'name2', 'name3']
objs = [foo(name,100, True) for name in desired_names]

rawDescription: Generating objects in python 3.4.3

description: Generating objects in python 3.4.3


code:
self.save_name = tkFileDialog.askopenfilename(title='Select a file')
with open(self.save_name, 'rb') as f:
    self.the_data = f.read() # insert processing here

rawDescription: Open file and save it in another function with tkinter


rawDescription: Python 3 pyQt4 updating GUI with variables from multiple modules/classes


code:
con = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
df.to_sql('db_table', con, index=False)
df_new = pd.read_sql_query("SELECT * FROM db_table",con)
df_new.dtypes

rawDescription: python pandas parse_dates column wildcard for sqlalchemy in pandas 0.14.1?

description: Python pandas parse_dates column wildcard for sqlalchemy in pandas 0.14.1


rawDescription: keys with multiple values in a dictionary (Python)

description: Keys with multiple values in a dictionary (Python)


rawDescription: python pandas extract unique dates from time series

description: Python pandas extract unique dates from time series


code:
chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ'
for i in itertools.product(chars, repeat=5):
    print(i)

rawDescription: Python: itertools.product consuming too much resources


code:
{'IP of Device': 'XXX.XX.XXX.XX', 'Device Type': 'iPhone OS', 'Map ID': '26',
 'Tutorial viewed': 'false', 'Last 5 errors': '(142,752,142,752,752)'}

rawDescription: Parsing txt file into dictionary in Python


rawDescription: Displaying 6.5235375356299998e-07 without exponential notation


code:
def read_paragraph(fp):
    """
    Read lines from the file until the end of the paragraph
    """
    while True:
        line = fp.readline()
        if not line.strip():
            break
        yield line

def skip_paragraph(fp):
    while fp.readline().strip():
        pass

def find_definition(fp, word):
    word = word.upper()
    while True:
        line = fp.readline()
        if not line:
            break  # end of file, consider raising an exception here

        if line.strip() == word:
            yield line          # found the word
            skip_paragraph(fp)  # move to the definition
            for defline in read_paragraph(fp):
                yield defline
            break
        else:
            # we're not interested in the current word, just skipping it
            skip_paragraph(fp)
            skip_paragraph(fp)

rawDescription: Read out definitions of a text file based dictionary


code:
rand = random.WichmannHill(1)
uuid += rand.choice(hexdigits)

rawDescription: Jython random module produces different results to cpython


code:
starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' ']
starring = filter(lambda name: name.strip(), starring)
starring

rawDescription: Remove strings containing only white spaces from list


code:
ZMQ_TCP_KEEPALIVE
ZMQ_TCP_KEEPALIVE_IDLE
ZMQ_TCP_KEEPALIVE_CNT
ZMQ_TCP_KEEPALIVE_INTVL

rawDescription: Auto-reconnect in zmq subscriber

description: Auto-reconnect in zmq subscriber


rawDescription: Randomize elements of a list in jinja 2

description: Randomize elements of a list in jinja 2


code:
class Counter:
    def __init__(self, start=0):
        self.count = start - 1
    def __call__(self):
        self.count += 1
        return self.count

rawDescription: state retention for classes and closures

description: State retention for classes and closures


code: filter(None, mylist())

rawDescription: What is a better pythonic version of this conditional deleting?


code:
p = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
import fcntl, os
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
p.stdout.read()         # raises an exception instead of blocking

rawDescription: Persistent python subprocess

description: Persistent python subprocess


code:
a = a.reshape(3, 3, 3)
max(a)
np.max(a)

rawDescription: What does numpy.max function do?

description: What does numpy.max function do


rawDescription: Set matplotlib plot axis to be the dataframe column name


code:
class PostForm(Form):
    post = StringField('post', validators=[DataRequired()])
    parentID = HiddenField('', validators=[DataRequired()])

rawDescription: How to pass information from html(jinja) to python(flask) through a form

description: Pass information from html(jinja) to python(flask) through a form


code:
f = csv.writer(open("file.csv", "w"))
for row in data:
    f.writerow([str(row)])

rawDescription: Write query rows in csv python

description: Write query rows in csv python


rawDescription: Regex Python findall. Making things nonredundant


code:
import sys
sys.getsizeof(a)

rawDescription: How many elements may python dictionary hold?


code: lcsubstring_length(a, b)

rawDescription: Python: Length of longest common subsequence of lists


rawDescription: How to cascade delete from a child to a parent

description: Cascade delete from a child to a parent


code: [char == '.' for char in l]

rawDescription: List comprehension with two conditions

description: List comprehension with two conditions


code:
import clr
clr.CompileModules("path_to.dll", "path_to.py");

rawDescription: Call .dll function from C# Ironpython

description: Call .dll function from C# Ironpython


code:
data = bytearray('\x01')
ndata = np.frombuffer(data, np.int8)
ndata
ndata[0] = 2
data

rawDescription: How to pipe binary data into numpy arrays without tmp storage?

description: Pipe binary data into numpy arrays without tmp storage


code:
import sys
import termios
import tty

old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())

rawDescription: Python Read Character by Character without printing


code:
#ajax method to retreive well data for dynamic well values, x_pos, y_pos, substance concentration
@app.route('/getWellData', methods=['GET', 'POST'])
def getWellData():
    #get all samples with that date
    date_collected = request.args.get('date_collected')
    site_id = request.args.get('site_id')
    site_map_id = request.args.get('site_map_id')
    substance_id = request.args.get('substance_id')

    well_results = wellSubstanceDataBySite(
        site_id=site_id,
        site_map_id=site_map_id,
        date_collected=date_collected,
        substance_id=substance_id)

    #return json to updateMarks ajax javascript function
    return json.dumps(well_results)

rawDescription: referring to specific parts of a python dictionary in javascript

description: Referring to specific parts of a python dictionary in javascript


code: ', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)])

rawDescription: Python dict to string

description: Python dict to string


rawDescription: generic command line generator in python

description: Generic command line generator in python


code:
storage = StorageByKeyName(CredentialsModel, KEY_NAME, CREDENTIALS_PROPERTY_NAME)
credentials = storage.get()

rawDescription: How can I log in to an arbitrary user in appengine for use with the Drive SDK?

description: Log in to an arbitrary user in appengine for use with the Drive SDK


rawDescription: Group rows in a CSV by blocks of 25

description: Group rows in a CSV by blocks of 25


code:
import json
from django.template.loader import render_to_string

def done(request):
    params = json.loads(request.body)
    report_array = params['report_array']
    html_data = render_to_string('maps/done.html', {'reports_link': report_array})

    return HttpResponse(html_data)

rawDescription: how to pass jquery variable to django view

description: Pass jquery variable to django view


rawDescription: How do I convert a string into a decimal number for arithmetic manipulation in Python?

description: Convert a string into a decimal number for arithmetic manipulation in Python


code:
def make(percentmissing):
  global d
  d = dict.fromkeys(range(100-percentmissing), 1)

def addit(d, k):
  d[k] = k

def with_in():
  dc = d.copy()
  for k in range(100):
    if k not in dc:
      addit(dc, k)
    lc = dc[k]

def with_ex():
  dc = d.copy()
  for k in range(100):
    try: lc = dc[k]
    except KeyError:
      addit(dc, k)
      lc = dc[k]

def with_ge():
  dc = d.copy()
  for k in range(100):
    lc = dc.get(k)
    if lc is None:
      addit(dc, k)
      lc = dc[k]

rawDescription: Python performance: Try-except or not in?


code:
import fileinput
import sys
for line in fileinput.input("in.txt",inplace=True):
    if line.strip():
        w,i = line.split(",")
        sys.stdout.write("{}\n\n".format(w)*int(i))

rawDescription: How do I take a number associated with a word and have the word printed that number of times?

description: Take a number associated with a word and have the word printed that number of times


code:
import sip
sip.isdeleted(self.w)

rawDescription: how to clear child window reference stored in parent application when child window is closed?

description: Clear child window reference stored in parent application when child window is closed


code:
def up_down(a, b):
    mn, mx = min(a), max(b)
    step = -1 if mn > mx else 1
    return range(mn, mx, step)

rawDescription: Construct a list of integers from bigger to smaller in python


rawDescription: Append a NumPy array to a NumPy array

description: Append a NumPy array to a NumPy array


code:
setup(
    # other arguments here...
    entry_points = {
        'console_scripts': ['foo = my_package.some_module:main_func']
    }
)

rawDescription: How to have python program listen on an environment variable?

description: Have python program listen on an environment variable


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

rawDescription: Find and list duplicates in Python list

description: Find and list duplicates in Python list


code:
list1 = [(i.CRC, basename(i.filename)) for i in old.infolist()]
list2 = [(i.CRC, basename(i.filename)) for i in new.infolist()]

rawDescription: Pythonic Way to compare two unordered lists by attributes


code: key = lambda action: action["phase"]

rawDescription: python deque/list filtering

description: Python deque/list filtering


code:
if ('admin', 'unknown') in worker:
    print("toto")

rawDescription: check if item is part of dict keys

description: Check if item is part of dict keys


code:
from rest_framework import serializers, viewsets

class MyModelSerializer(serializers.ModelSerializer):
    def save_object(self, obj, **kwargs):
        """
        Save the deserialized object.
        """
        if getattr(obj, '_nested_forward_relations', None):
            # Nested relationships need to be saved before we can save the
            # parent instance.
            for field_name, sub_object in obj._nested_forward_relations.items():
                if sub_object:
                    self.save_object(sub_object)
                setattr(obj, field_name, sub_object)

        #####  EDITED CODE #####
        if obj.pk:
            obj.save(**kwargs)
        else:
            # Creating a new object. This is silly.
            obj = MyModel.objects.create(obj.to_user, obj.from_user, obj.wedding)
        ##### /EDITED CODE #####

        if getattr(obj, '_m2m_data', None):
            for accessor_name, object_list in obj._m2m_data.items():
                setattr(obj, accessor_name, object_list)
            del(obj._m2m_data)

        if getattr(obj, '_related_data', None):
            related_fields = dict([
                (field.get_accessor_name(), field)
                for field, model
                in obj._meta.get_all_related_objects_with_model()
            ])
            for accessor_name, related in obj._related_data.items():
                if isinstance(related, RelationsList):
                    # Nested reverse fk relationship
                    for related_item in related:
                        fk_field = related_fields[accessor_name].field.name
                        setattr(related_item, fk_field, obj)
                        self.save_object(related_item)

                    # Delete any removed objects
                    if related._deleted:
                        [self.delete_object(item) for item in related._deleted]

                elif isinstance(related, models.Model):
                    # Nested reverse one-one relationship
                    fk_field = obj._meta.get_field_by_name(accessor_name)[0].field.name
                    setattr(related, fk_field, obj)
                    self.save_object(related)
                else:
                    # Reverse FK or reverse one-one
                    setattr(obj, accessor_name, related)
            del(obj._related_data)

class MyModelViewSet(viewsets.ModelViewSet):
    serializer_class = MyModelSerializer
    queryset = MyModel.objects.all()

rawDescription: How to override default create method in django-rest-framework

description: Override default create method in django-rest-framework


rawDescription: How do I order fields of my Row objects in Spark (Python)

description: Order fields of my Row objects in Spark (Python)


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

t = np.linspace(0, np.pi*3, 301)
x = np.sin(t)

rawDescription: Efficiently drawing lines using python

description: Efficiently drawing lines using python


code:
if last_key != key:
    if last_key != None:
        k = last_key.split('|')
        v_id = k[0]

        if v_id == 'a':
            if tot_cnt > 1:
                sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))
        else:
            sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))

rawDescription: How to get the Reducer to emit according to key type

description: Get the Reducer to emit according to key type


code:
func1 = lambda P, Q: (not P) or (not Q)
func2 = lambda P, Q: not(P and Q)
logical_equiv(func1, func2, True, False)

rawDescription: Getting the return value of functions passed in as variables


code:
dict((x,list(a[1:] for a in y)) for x,y in
    itertools.groupby(zip(amr_list, pssr_list, inservice_list), lambda z: z[0]))

rawDescription: Mapping data from excel with Python

description: Mapping data from excel with Python


rawDescription: Variable assignment and manipulation in Python


rawDescription: Get values from multiple entries after entry duplication


rawDescription: Searching items in two lists

description: Searching items in two lists


code:
if w is None:
    w = ones(m, float)
    if s is None:
        s = 0.0

else:
    w = atleast_1d(w)
    if s is None:
        s = m - sqrt(2*m)

rawDescription: scipy splrep() with weights not fitting the given curve

description: Scipy splrep() with weights not fitting the given curve


rawDescription: Deleting consonants from a string in Python


code: caesar_cipher('This is my 3rd test!', 2)     # => 'Vjku ku oa 3tf vguv!'

rawDescription: How do I make python encrypt both uppercase and lowercase?

description: Make python encrypt both uppercase and lowercase


code:
from __future__ import print_function
def print_list(l,size):
    for x in l:
        print(x[2], end='')

rawDescription: Print list as array Python

description: Print list as array Python


rawDescription: Toggling button state on matplotlib NavigationToolbar programmatically


rawDescription: How to multiply a scalar throughout a specific column within a NumPy array?

description: Multiply a scalar throughout a specific column within a NumPy array


code:
with io.open(myFile.json, 'a', encoding='utf-8') as f:
    f.write(unicode(json.dumps(item, ensure_ascii=False)))
    f.write(u'\n')

rawDescription: Export dicts to a json file

description: Export dicts to a json file


rawDescription: Python, using Selenium how to clean page_source from char like /a0:


code:
Name1
Name2
Name3
Name4
Name5

rawDescription: Iterating two lists, comparing the first column and appending the second column


code:
from textwrap import dedent

s = ''.join(dedent(r"""
    foo\tbar\n
    baz\tqux\n
""").splitlines())

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

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


rawDescription: How to access a KEGG entry without specifying the organism using bioservices?

description: Access a KEGG entry without specifying the organism using bioservices


code:
for i,tup in enumerate(tups):
    arr[tup]=np.where(arr[tup]==0,i+1,arr[tup])

rawDescription: how to replace only zeros of a numpy array using a mask

description: Replace only zeros of a numpy array using a mask


code: r.append({k: a[k] for k in ("content", "phrase", "name")})

rawDescription: How to look through a phrase in a dictionary?

description: Look through a phrase in a dictionary


code:
class RecipeIngredients(models.Model):
    recipe = models.ForeignKey(Recipe, related_name='ingredient_quantities')

rawDescription: Django ManyToMany with through model implementation


code:
def check_origin(self, origin):
    return True

rawDescription: tornado 403 GET warning when opening websocket

description: Tornado 403 GET warning when opening websocket


rawDescription: How to perform an operation on this tuple and convert to another tuple in Python?

description: Perform an operation on this tuple and convert to another tuple in Python