code:
import pyglet
from pyglet.gl import *
from collections import OrderedDict
from time import time
from os.path import abspath

class GUI(pyglet.window.Window):
    def __init__(self):
        super(GUI, self).__init__(640,340, caption='Test')

        pyglet.gl.glClearColor(1, 1, 1, 1)
        self.alive = True
        self.batches = OrderedDict()
        self.batches['apples'] = pyglet.graphics.Batch()

        self.framerate = 0, time()
        self.count = 0

    def render(self, *args):
        self.clear()

        #glColor4f(1,0,0,1)
        #drawSquare(x,y)

        if time() - self.framerate[1] > 1:
            print('fps:',self.framerate[0])
            self.framerate = 0, time()
        else:
            # Not an optimal way to do it, but it will work.
            self.framerate = self.framerate[0]+1, self.framerate[1]

        self.flip()

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = False

    def on_key_press(self, symbol, modkey):
        pass

    def on_key_release(self, symbol, modkey):
        pass

    def on_mouse_release(self, x, y, button, modifiers):
        pass

    def on_mouse_press(self, x, y, button, modifiers):
        self.count += 1
        with open('debug.log', 'w') as fh:
            fh.write(str(count))

    def on_mouse_motion(self, x, y, dx, dy):
        pass

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        pass

    def run(self):
        while self.alive:
            event = self.dispatch_events()
            if event:
                print(event)
            self.render()

if __name__ == '__main__':
    x = GUI()
    pyglet.clock.set_fps_limit(60)
    x.run()

rawDescription: Pyglet unstable frame rate

description: Pyglet unstable frame rate


rawDescription: How to convert an array of 27 bytes where each 3 bytes is a 2's complement number into its numeric equivalent?

description: Convert an array of 27 bytes where each 3 bytes is a 2's complement number into its numeric equivalent


rawDescription: Pandas sorting by group aggregate

description: Pandas sorting by group aggregate


code:
import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands')

parser_foo = subparsers.add_parser('foo')
parser_foo.set_defaults(target='foo')

parser_bar = subparsers.add_parser('bar')
parser_bar.add_argument('more')
parser_bar.set_defaults(target='bar')

rawDescription: Nested options with argparse

description: Nested options with argparse


code:
import operator
map(operator.itemgetter(0), a)
list(map(operator.itemgetter(0), a))

rawDescription: Creating a Python list from a list of tuples


rawDescription: efficient way to make pandas.DatetimeIndex in Python

description: Efficient way to make pandas.DatetimeIndex in Python


code:
c = get_config()

c.LocalControllerLauncher.controller_cmd = ['/usr/bin/python2', '-m', 'ipyparallel.controller']
c.LocalEngineLauncher.engine_cmd = ['/usr/bin/python2', '-m', 'ipyparallel.engine']
c.LocalEngineSetLauncher.engine_cmd = ['/usr/bin/python2', '-m', 'ipyparallel.engine']

rawDescription: Change IPython 3 for Python 3 kernel to python2 for the cluster too


rawDescription: how to optimally count elements in a python list

description: Optimally count elements in a python list


code:
def linetotalprice(self):
    return self.orderline_product_price * self.orderline_quantity

rawDescription: Django calculate field based on two other fields in formset


code:
df
df = pd.concat([df[:1], df[1:].sample(frac=1)]).reset_index(drop=True)
df

rawDescription: Shuffle DataFrame rows except the first row


code:
em = EM(5)
np.allclose(em.expectation(),
            em.expectation_fast())
# True

rawDescription: Speeding up guassian EM algorithm

description: Speeding up guassian EM algorithm


rawDescription: Finding the index of the element contains string in a list


code:
import pandas as pd

data = """\
State   type    freq
AZ  low 1101
CT  low 932
DE  low 832
FL  low 4481
GA  low 1619
IA  low 1819
IL  low 4498
IN  low 797
KS  low 162
AZ  mid 412
CT  mid 2149
DE  mid 1152
FL  mid 3304
GA  mid 167
IA  mid 247
IL  mid 3852
IN  mid 1849
KS  mid 379
AZ  high    674
CT  high    418
DE  high    1862
FL  high    948
GA  high    1063
IA  high    1203
IL  high    942
IN  high    1534
KS  high    471"""

data = pd.DataFrame([line.split() for line in data.splitlines()[1:]],
                    columns=data.splitlines()[0].split())

bystate = data.pivot('State', 'type')

rawDescription: Best way to convert Pandas dataframe to json in python

description: Convert Pandas dataframe to json in python


code:
from PyQt4 import QtCore, QtGui
from Renewals import run_renewals
import pandas as pd
import sys

self.Go = QtGui.QPushButton(Form)
self.Go.clicked.connect(self.on_Go_clicked)

self.As_of_Date = QtGui.QDateEdit(Form)

def on_Go_clicked(self):
    # this converts a QDate to a datetime object
    end_date = self.As_of_Date.date().toPyDate()
    run_renewals(end_date)

rawDescription: Import variable from qdateedit into back end script


code:
# Decorator Function
def login_required(something):
    @wraps(something)
    def wrap(*args, **kwargs):
        if "some_admin_name" in session:
            return something(*args, **kwargs)
        else:
            flash("\"You shall not pass!\" - Gandalf")
            return redirect(url_for("login"))
    return wrap

# Function Being Decorated
@app.route("/some/restricted/stuff")
@login_required
def main():
    return render_template("overview.html",
                       stuff = getstuff() )

rawDescription: What is a self-written decorator (like @login_required) actually doing?


code:
class Media:
    js = (
        'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',
        '/media/js/calculate.js',
    )

rawDescription: Django: Update Field Value Based on Other Fields


code: shellreturn = str(shellreturn, 'utf-8')

rawDescription: Python split string by \n character

description: Python split string by \n character


code: {{ listing.uppercase_listing }}

rawDescription: How to write Python Code in Django

description: Write Python Code in Django


rawDescription: Get record from master table if alteast one record exists in slave/child tables using django api


rawDescription: Multiply (a x a) square matrix by (a x c x d) matrix


rawDescription: Trouble comparing 2 excel sheets in Python using nested for loop


code:
data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

rawDescription: python BeautifulSoup parsing table

description: Python BeautifulSoup parsing table


code:
class Foo(models.Model):
     name = models.CharField()

class Bar(models.Model):
     title = models.CharField()
     foo = models.ForeignKey(Foo, related_name='bars')

...

some_foo.bars.all()

rawDescription: How can I write a method within a Django model to retrieve related objects?

description: Write a method within a Django model to retrieve related objects


code:
# Here X, y - your dataset
one_vs_rest = model_tunning.best_estimator_
yT = one_vs_rest.label_binarizer_.transform(y).toarray().T
# Iterate through all L classifiers
for classifier, is_ith_class in zip(one_vs_rest.estimators_, yT):
    print(classifier.score(X, is_ith_class))

rawDescription: Sklearn: Evaluate performance of each classifier of OneVsRestClassifier inside GridSearchCV


rawDescription: Sort data to present barchart highest to lowest in python


code:
import pydraw.shapes
pydraw.shapes.__path__
from pydraw.shapes import circle, square

rawDescription: What are prevalent techniques for enabling user code extensions in Python?


code:
import subprocess
r = subprocess.Popen(['ls', '-l']) #List files on a linux system. Equivalent of dir on windows.
output, errs = r.communicate()
print(output)

rawDescription: Python --- How to execute command prompt and get the output from it?


rawDescription: Python list: exchange every n-th value with the (n+1)th


code:
from django.contrib.auth.models import Group
g = Group.objects.get(name='company')
g.user_set.add(your_user)

rawDescription: How to add a Group to every Instance of a Model

description: Add a Group to every Instance of a Model


rawDescription: How to perform a $and search with Python and MongoDB

description: Perform a $and search with Python and MongoDB


rawDescription: filtered and non-filtered elements in a single pass

description: Filtered and non-filtered elements in a single pass


code:
def __str__(self):
    return ''.join([getattr(self, attr) for attr in (
        'dst_addr', 'src_addr', 'type', 'payload', 'arptype', 'src_mac_addr',
        'src_ip_addr', 'dst_mac_addr', 'dst_ip_addr')])

rawDescription: Cannot return string from python class

description: Cannot return string from python class


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

# DPI, here, has _nothing_ to do with your screen's DPI.
dpi = 80.0
xpixels, ypixels = 800, 800

fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
fig.figimage(np.random.random((xpixels, ypixels)))
plt.show()

rawDescription: Display image with a zoom = 1 with Matplotlib imshow() (how to?)


code: data = [{"name": key, "age": value} for key, value in my_dict.items()]

rawDescription: Move data from key to value in Python dictionary


code:
for index, row in enumerate(data):
    RowSum = my_sum(row)
    print('Row %d: %f' % (index + 1, rowSum))

rawDescription: return index for rows in csv module python

description: Return index for rows in csv module python


code:
def primecheck_longway(x):
    for n in x:
        if not prime(n):
            return False
    return True

rawDescription: Iterate Function through List

description: Iterate Function through List


rawDescription: Method for generating row-column arrays with other arrays


code:
import pywinauto

app = pywinauto.Application().start(r'uTorrent.exe')
time.sleep(5) # because method connect() has no timeout param yet (planned for 0.6.0)
app.connect(title_re=u'^\u03bcTorrent.*(build \d+).*')

main_window = app.window_(title_re=u'^\u03bcTorrent.*(build \d+).*')
main_window.MenuSelect(u'&File->Add Torrent from &URL...\tCtrl+U')

app.AddTorrentFromURL.Edit.SetText('some URL')
app.AddTorrentFromURL.OK.Click()

rawDescription: uTorrent Automation using pywinauto

description: UTorrent Automation using pywinauto


code: -frame

rawDescription: Make every numeric value in a pandas DataFrame negative


code:
from collections import Counter
from itertools import chain

counts = Counter(chain.from_iterable(e.keys() for e in d))

rawDescription: python dictionary count of unique values

description: Python dictionary count of unique values


code:
totals = (df * weights).sum(axis=1)
totals

rawDescription: What is the fastest way to do greedy set cover with Pandas?


code:
text = """I saw a little hermit crab
His coloring was oh so drab

It’s hard to see the butterfly
Because he flies across the sky

etc etc...

Once upon a time
She made a little rhyme
Of course, of course

Before we say again
The pain the pain
A horse, a horse

Lightening, thunder, all around
Soon the rain falls on the ground

I tire of writing poems and rhyme
""".replace('\n', '\r\n')
len([block for block in text.split('\r\n\r\n') if block.count('\r\n') == 1])

rawDescription: count couplets from a list with \r\n line breaks

description: Count couplets from a list with \r\n line breaks


code:
class Puzzle(object):
    def __init__(self, matrix):
        self.matrix = [list(row) for row in matrix]
        self.dim = len(matrix)

    def copy(self):
        return Puzzle(self.matrix)

rawDescription: Avoid a deepcopy when doing a BFS

description: Avoid a deepcopy when doing a BFS


code:
sys.path.append('/path/to/directory/that/my/module/is/in/')
import mymod #.py

rawDescription: Python meta-debugging

description: Python meta-debugging


code:
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
import itertools
k.sort()
list(k for k,_ in itertools.groupby(k))

rawDescription: Python: removing duplicates from a list of lists


code: w = np.array([0 if i not in orig else orig[i] for i in range(100)])

rawDescription: Python Tuple & List Manipulation (As an input to the SVM model in scikit-learn)


code:
def gen_strings(max_length, state="A", str=""):
    result = set()
    gen_strings_r(max_length, state, str, result)
    return result

rawDescription: Return a set from a recursive function

description: Return a set from a recursive function


code:
import numpy as np

#Read and label file 1
f1 = np.genfromtxt('./file1.csv',delimiter=',',dtype="string")
label = np.array(["F1"]*f1.shape[0])
f1 = np.insert(f1, 0, label, axis=1)

#Read and label file 2
f2 = np.genfromtxt('./file2.csv',delimiter=',',dtype="string")
label = np.array(["F2"]*f2.shape[0])
f2 = np.insert(f2, 0, label, axis=1)

#Combine and write
fout = np.vstack((f1,f2))
np.savetxt("fout.csv", fout, delimiter=",", fmt="%s")

rawDescription: add column to csv when exporting numpy ndarray

description: Add column to csv when exporting numpy ndarray


rawDescription: Parsing HTML within Javascript button elements with BeautifulSoup


code: price_match = {k:v for (k,v) in inventory.iteritems() if v[1] == 19}

rawDescription: modifying list element in Python dictionary

description: Modifying list element in Python dictionary


code:
@do_after
def my_view(request):
    ...

rawDescription: Is there a way in python to trigger an action upon exiting a function


rawDescription: String splitting in Python

description: String splitting in Python


code:
df_merged = pd.concat([df1, df2], axis=0)
df_total['Rate_first'] = df_total['Sample1_Count']/df_total['Union_Count']

rawDescription: The comparison sets after grouping dataframe (Python 3, pandas)


code: cat_dict = {(university, sport): url_name for (university, sport, url_name) in cat_list}

rawDescription: python for loop logic to check variables against

description: Python for loop logic to check variables against


rawDescription: python multiplication {how to do it with a dic ?}

description: Python multiplication {how to do it with a dic ?}


code:
import requests
conditions_image1 = "http://openweathermap.org/img/w/{}.png".format(result['list'][1]['weather'][0]['icon'])
#or whatever be the name of your image
response1 = requests.get(conditions_image1)
if response1.status_code == 200:
    f = open("./icons/wc1.png", 'wb')
    f.write(response1.content)
    f.close()

rawDescription: Save app data in Weather App

description: Save app data in Weather App


rawDescription: NaN value when using Lambert Function in Python - in Enthought Canopy


rawDescription: How to extend one sublist by another sublist if they share a common id at the same index in both sublists?

description: Extend one sublist by another sublist if they share a common id at the same index in both sublists


code:
if not request.user.is_staff:
    return Http404

rawDescription: django- run a script from admin

description: Django- run a script from admin


code:
langs = [getattr(lang, 'iso639_1_code', None) or
         getattr(lang, 'iso639_2T_code', None) or
         getattr(lang, 'iso639_3_code')
         for lang in pycountry.languages]

rawDescription: List of language codes (ISO639-1) in Python?


code:
df1a,df2a = df1.align(df2,fill_value=0)
df1a+df2a

rawDescription: Pandas adding two Multiindex Dataframes

description: Pandas adding two Multiindex Dataframes


code: foo = request.form.get('name')

rawDescription: Flask Odd Behavior w/ Folder Creation/File Uploading


code:
line == '/Household/LastName.FirstName.Account.Doctype.Date.extension'
household == 'Household'
lastn     == 'LastName'
firstn    == 'FirstName'
acct      == 'Account'
doctype   == 'Doctype'
date      == 'Date'

line == '- /Volumes/HD/Organized Files/Cosby, Bill/Cosby.Bill..Profile.2006.doc'
household == 'Cosby, Bill'
lastn     == 'Cosby'
firstn    == 'Bill'
acct      == ''
doctype   == 'Profile'
date      == '2006'

rawDescription: Python parse filenames by custom field pattern


rawDescription: Change object's variable from different file


code: cartesian_tuples = [[perm for perm in prod] for prod in product(perms, repeat=3)]

rawDescription: How to generate all possible combinations from all permutations?

description: Generate all possible combinations from all permutations


code:
#!/bin/python

import winerror
import win32event
import win32service
import win32serviceutil
from sys import modules
from os.path import splitext, abspath

SVC_RUN = 1
SVC_REMOVE = 2

class TMP_Service(win32serviceutil.ServiceFramework):

    _svc_name_ = "tmp_svc_name"
    _svc_display_name_ =  "tmp svc disp name"
    _svc_reg_class = "tmp.reg_class"
    _svc_description_ = "tmp description"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.Stop = True
        # I will call reactor.callFromThread(reactor.stop) here to stop the
        # FTP and SCP listeners
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.Stop = False
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        # This infinite loop simulates future behavior of my service. It will
        # run a Twisted reactor to handle FTP and TCP network connections.
        while self.Stop == False:
            pass

        win32event.WaitforSingleObject(self.hWaitStop, win32event.INFINITE)

def install_svc():

    try:
        module_path = modules[TMP_Service.__module__].__file__
    except AttributeError:
        # maybe py2exe went by
        from sys import executable
        module_path = executable

    module_file = splitext(abspath(module_path))[0]
    TMP_Service._svc_reg_class = '%s.%s' % (module_file, TMP_Service.__name__)

    try:
        win32serviceutil.InstallService(
                TMP_Service._svc_reg_class,
                TMP_Service._svc_name_,
                TMP_Service._svc_display_name_,
                startType=win32service.SERVICE_AUTO_START)

    except win32service.error as e:

        if e[0] == winerror.ERROR_SERVICE_EXISTS:
            pass # ignore install error if service is already installed

        else:
            raise

def handle_service(svc):

    if svc == SVC_RUN:

        try:
            win32serviceutil.StartService(TMP_Service._svc_name_)

        except win32service.error as e:

            if ((e[0] == winerror.ERROR_SERVICE_ALREADY_RUNNING) or
                    (e[0] == winerror.ERROR_ALREADY_RUNNING_LKG)):
                pass # ignore failed start if the service is already running

            elif e[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:

                # if the service is not installed, install it and try again
                install_svc()
                win32serviceutil.StartService(TMP_Service._svc_name_)

            else:
                # reraise any other start expection
                raise

        status = win32serviceutil.QueryServiceStatus(TMP_Service._svc_name_)
        print("Service status: {}".format(status[1]))

    else:

        try:
            win32serviceutil.RemoveService(TMP_Service._svc_name_)

        except win32service.error as e:

            if e[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
                pass # ignore failed removal if service is not installed
            else:
                # reraise any other remove exception
                raise

if __name__ == "__main__":
    handle_service(SVC_RUN)

rawDescription: pywin32 service start error: no module named 'tmp'

description: Pywin32 service start error: no module named 'tmp'


code:
with open("in.txt") as input:
    intable = False
    for line in input:
        if line.strip() == "Summary":
            intable = True
        if line.strip() == "Asca":
            intable = False
        if intable and line.strip().startswith("*"):
            print(line.strip())

rawDescription: finding a table in a text file and printing it

description: Finding a table in a text file and printing it


code:
url(r'^v1/statistics/stats_bar$', views.stats_bar, name='stats_bar_statistics')
url(r'^v1/analytics/stats_bar$', views.stats_bar, name='stats_bar_analytics')

reverse('status_bar_statistics') # usage

rawDescription: Django NoReverseMatch Exception for regular expression matching 2 routes


code:
def createMatcher( self, regex ):
    def matchCheck( argument ):
        self.assertTrue( regex.match( argument ) )
    return matchCheck

rawDescription: Equivalent of assertRegexMatches in python 2.4


code:
ratio_sl = [sum(ib, 0.0) / sum(v != 0 for v in ia)  for ia, ib in zip(a, b)]
ratio_sl
[[0 if not v else v + r for v in i] for i, r in zip(a, ratio_sl)]

rawDescription: Sum and length of lists of list

description: Sum and length of lists of list


rawDescription: Using same function as instance and classmethod in python


code:
s = pd.Series(list('abc'))
s
1 in s
'a' in s

rawDescription: How to determine whether a Pandas Column contains a particular value

description: Determine whether a Pandas Column contains a particular value


code:
s = "1231,fdkgjdkfj45,294d"
[''.join(i for i in chunk if i.isdigit()) for chunk in s.split(',')]

rawDescription: Merging certain parts of a list together, depending on an item in the list - Python


code: ['Amato, Andrea', 'Banerjee, Trambak', 'Basu, Pallavi', 'Chang, Wayne', 'Chung, Sung Hun', 'Comings, Alison', 'Cui, Hailong', 'DeGroot, Tyler', 'Dutton, Chaumanix', 'Fu, Luella', 'Golrezaei, Negin', 'Grandy, Jake', 'Han, Rong Qing', 'Han, Ju Rie (Alyssa)', 'Harmon, Derek', 'Hong, Jihoon', 'Jia, He', 'Joshi, Priyanka', 'Kays, Allison', 'Kfir, Alon', 'Kim, Jeunghyun', 'Kim, Pureum', 'Kim, Yookyoung', 'Kim , Jennifer', 'Krikorian, Mariam', 'Lang, Tina', 'Lee, Jennifer', 'Lee, Suk won', 'Lee, Yoonju', 'Li, Guang', 'Li, Yuan', 'Ling, Yun', 'Magkotsios, Georgios', 'Min, Bora', 'Newman, David', 'Oh, Seung Hwan', 'Ozkan, Erhun', 'Paulson, Courtney', 'Pei, Lei', 'Pyun, Sung June', 'Raj, Medha', 'Raveendhran, Roshni', 'Rich, Beverly', 'Ritter, Stacey', 'Sahoo, Satish', 'Skripnik, Roman', 'Smallets, Stephanie', 'Song, Shiwon', 'Stamenov, Ventsislav', 'Subler, Megan', 'Talijan, Vuk', 'Uhalde, Arianna', 'Valsesia, Francesca', 'Wan, Yuan', 'Wang, Jue', 'Wang, Weinan', 'Wang, Xuan', 'Wang, Yongzhi (Alex)', 'Wang, Yingfei (Fiona)', 'Wong, Vivian', 'Xia, Jingjing', 'Xing, Zhe (Adele)', 'Xu, Zibin', 'Yang, Louis', 'Yao, Yao', 'Yi, Irene', 'Yordanov, Kristian', 'Yu, Xiaoqian', 'Zhang, Heng', 'Zhang, Yanwei (Wayne)', 'Zhang, Yingguang', 'Zhang, Mengxia']

rawDescription: Trying to parse the names (and phD degrees) from a faculty university site. Having trouble getting only that


rawDescription: getting rid of some elements that contain just white space in a list

description: Getting rid of some elements that contain just white space in a list


code:
def tofunnystructure(classDict):
    finalStructure = {}
    keys = set(classDict.keys())

    for key, vals in classDict.iteritems():
        newval = {}

        value = [val for val in vals if val not in keys]
        if value:
            newval['value'] = value[0] if len(value) == 1 else value

        groups = [val for val in vals if val in keys]
        if groups:
            newval['group'] = groups[0] if len(groups) == 1 else groups

        finalStructure[key] = newval

    return finalStructure

rawDescription: check if element in values also in key in dict

description: Check if element in values also in key in dict


rawDescription: Find maximum of each row in a numpy array and the corresponding element in another array of the same size


code:
print("The top scoring students from highest to lowest are:")
for k,v in sorted(d.items(),key=lambda x:sum(x[1]),reverse=True):
    print("{} : {}".format(k,sum(v)))

rawDescription: How to sort integers in a variable?

description: Sort integers in a variable


code:
import pickle
from io import BytesIO

dfs = rdd.values().map(lambda p: pickle.load(BytesIO(p)))
dfs.first()[:3]

##         foo       bar
## 0 -0.162584 -2.179106
## 1  0.269399 -0.433037
## 2 -0.295244  0.119195

rawDescription: Spark reading python3 pickle as input

description: Spark reading python3 pickle as input


code:
from collections import Counter
cnt = Counter("abracadabra")

rawDescription: python histogram one-liner

description: Python histogram one-liner


code: pd.cut(s, cuts).value_counts()

rawDescription: Converting float into range in Python

description: Converting float into range in Python


code:
for t in range(10):
    if t == 0:
        points, = ax.plot(x, y, marker='o', linestyle='None')
        text = plt.text(1, 5, "Loops passed: 0")
    else:
        new_x = ... # x updated
        new_y = ... # y updated
        points.set_data(new_x, new_y)
        text.set_text("Loops passed: {0}".format(t))
    plt.pause(0.5)

rawDescription: Change matplotlib.pyplot text() object properties


code:
writer_process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
reader_thread = threading.Thread(target=reader, args=(writer_process.stdout,))
reader_thread.start()
reader_thread.join()

rawDescription: Flushing a pipe (os.pipe) before closing


code:
class C():
    def __init__(self):
        self.__tweet_r = []

    def add_tweet_r(self, recent_tweet):
        self.__tweet_r.append(recent_tweet)

    # Add this:
    def search_tweets(self, author=None, string=''):
        """Return a list of all tweets by author (if provided) and containing string."""
        return [ tweet for tweet in self.__tweet_r
                 if (not author or author == tweet[0])
                    and string in tweet[1] ]

rawDescription: How do I search a list that is located in a class?

description: Search a list that is located in a class


code:
def publishTraverse(self, request, name):
    if name in self.context:
        return MyMessageView(self.context[name], request)

    # fall back to views such as index.html
    view = queryMultiAdapter((self.context, request), name=name)
    if view is not None:
        return view

    # give up and return a 404 Not Found error page
    raise NotFound(self.context, name, request)

rawDescription: Custom traversal and page templates

description: Custom traversal and page templates


code:
from toolz.curried import map, mapcat, concat, pipe
from itertools import repeat
pipe(range(4), mapcat(lambda i: repeat(i, i + 1)), list)

rawDescription: Extracting a dictionary from an RDD in Pyspark


code:
#Pivot to produce No's Bin table
Nos = pivot_table(RRData, values = 'NOs', index = ['SKILL', 'LOGIN'], columns = 'BINS', aggfunc = np.sum)
#Pivot to produce Responses Bin table
Responses = pivot_table(RRData, values = 'RESPONSES', index = ['SKILL', 'LOGIN'], columns = 'BINS', aggfunc = np.sum)

rawDescription: How to bin groupeby counts in pandas?

description: Bin groupeby counts in pandas


code:
class ProductVariation(Priced):
    ...
    def __unicode__(self):
        """
        Display the option names and values for the variation.
        """
        options = []
        for field in self.option_fields():
            if getattr(self, field.name) is not None:
                options.append("%s: %s" % (unicode(field.verbose_name),
                                           getattr(self, field.name)))
        return ("%s %s" % (unicode(self.product), ", ".join(options))).strip()

rawDescription: How to break the item name and size in Django Cartridge cart page?

description: Break the item name and size in Django Cartridge cart page


code:
digits = [12, 5, 39, 1, 40, 8, 17]
total = 0
for digit in digits:
    total = total * 40 + (digit-1)

rawDescription: How to convert a random number to another base format?

description: Convert a random number to another base format


code:
photos = [
    {
        _id: ObjectId(...),
        title: "...",
        date_uploaded: Date(...),
        albums: [
            {name: "family-vacation-2011", title: "My family vacation in 2010"},
            ...
        ]
    },
    ...
]

rawDescription: Proper NoSQL data schema for web photo gallery


rawDescription: Removing rows in a pandas DataFrame where the row contains a string present in a list?


code: circulant(r)

rawDescription: Create a "wrapped" ndarray from a given array


rawDescription: How to extract date from the filename using Python?

description: Extract date from the filename using Python


rawDescription: Average positive numbers in a row

description: Average positive numbers in a row


code:
class C(object):
    pass

def circular():
    for x in range(10**4):
        for y in range(10**4):
            a = C()
            b = C()
            a.x = b
            b.x = a

circular()

rawDescription: Python Delegate Pattern - How to avoid circular reference?


code:
names = ["Power", "Temperature", "Sunlight"]
callbacks = [SomeOtherClass.foo, SomeOtherClass.bar, SomeOtherClass.baz]
pack_options = [{}, {"padx": 5, "ipadx":12}, {}]
for name, callback, pack_options in zip(names, callbacks, pack_options):
    button = Checkbutton(frame, text=name, onvalue = 1, offvalue = 0, height=1, width = 10, command=callback)
    button.pack(side=LEFT, **pack_options)

rawDescription: Can I use a loop to quicky produce x amount of checkbuttons?

description: Use a loop to quicky produce x amount of checkbuttons


code:
counter = dict()
for item in org:
    if item not in counter:
        counter[item] = 1
    else:
        counter[item] += 1
    # Alternatively, just: counter[item] = counter.get(item, 0) + 1

rawDescription: Count equal tuple-elements of a list in Python3


code:
list1 = [("hello", 2), ("world", 3)]
validate_type(list1, [(str, int)])
Out[2]: True

rawDescription: Python: type checking of complex returned values


code: result * result

rawDescription: How to mpf an array?

description: Mpf an array


code:
def find_postag(word, postag):
    start = index[word[0].lower()]
    for line in data[start:]:
        # your code here
        if all(i in line for i in (word,postag)):
            if line.split(" ")[0].startswith(word) and line.split(" ")[1] == word+postag:
                selectedword = line.split(" ")[0]
                break
    return selectedword

rawDescription: reading strings from large file faster

description: Reading strings from large file faster


code:
df['Date'] = combined
del df['hour']
df = df.sort("Date")
df

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


code:
fig, axes = plt.subplots(ncols=2)
df[df.Categories=='A'].Values.plot(ax=axes[0])
df[df.Categories=='B'].Values.plot(ax=axes[1])

rawDescription: Plot a pandas dataframe grouped by column


code:
cmd = ['cvs',
       '-d:pserver:anonymous@bayonne.cvs.sourceforge.net:/cvsroot/bayonne',
       'login']
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

rawDescription: Spawn subprocess that expects console input without blocking?


code:
def convex_hull_volume(pts):
    ch = ConvexHull(pts)
    dt = Delaunay(pts[ch.vertices])
    tets = dt.points[dt.simplices]
    return np.sum(tetrahedron_volume(tets[:, 0], tets[:, 1],
                                     tets[:, 2], tets[:, 3]))

def convex_hull_volume_bis(pts):
    ch = ConvexHull(pts)

    simplices = np.column_stack((np.repeat(ch.vertices[0], ch.nsimplex),
                                 ch.simplices))
    tets = ch.points[simplices]
    return np.sum(tetrahedron_volume(tets[:, 0], tets[:, 1],
                                     tets[:, 2], tets[:, 3]))

rawDescription: Volume of convex hull with QHull from SciPy


code:
X.X.X.X
computername.domainname.com
X
X
X

rawDescription: How do you walk an Element tree parsed using Python's elmenttree module?

description: Walk an Element tree parsed using Python's elmenttree module


code:
from project.routes import bp

@bp.route('/')
def index():
  return render_template('routes/index.html')

rawDescription: Flask: are blueprints necessary for app factories?


code: Session.query(...).filter(..., schema.Term.id < term_alias.id)

rawDescription: SQLAlchemy - Get all Rows which have matching set of Columns


rawDescription: Pandas groupby two columns then get dict for values


code:
LOREM_IPSUM = """\
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""

rawDescription: Python string notation

description: Python string notation


code:
def run_race(self):
    self.thread.stop()
    self.thread.wait()
    self.thread = None
    self.r_window = L79Race.RaceWindow(self)
    self.r_window.show()
    self.hide()

rawDescription: PyQt5 opening and closing windows

description: PyQt5 opening and closing windows


code: collections.deque([], 42)

rawDescription: Creating an empty deque in Python with a max length?


code: cmd_connect = "CONNECT {}:{} HTTP/1.1\r\nProxy-Authorization: Basic <credentials>\r\n\r\n".format(*target)

rawDescription: Python Connect over HTTP proxy with pysftp


code:
from myproject import settings
settings.DATABASE_URL

rawDescription: "real" global variables in Python for programwide settings


rawDescription: Getting the first item item in a many-to-many relation in Django


code:
print(repr(ipa))
print(ascii(ipa))
print(repr(result))
print(ascii(result))

rawDescription: Python: print unicode string stored as a variable


rawDescription: Scipy sparse matrices element wise multiplication


code:
@decorator_factory(...)
def hello():
    ...

rawDescription: Understanding the difference between these two decorators


code: data = redis_connection.hdel(key, *list1)

rawDescription: delete multiple fields for a key in Redis

description: Delete multiple fields for a key in Redis


rawDescription: How to generate regular points on cylindrical surface

description: Generate regular points on cylindrical surface


code: rows = root.clipboard_get().replace(' ', '').split('\n')

rawDescription: Create variables no matter the nr of rows of the data in clipboard


code:
import fractions
fractions.Fraction('2/3')
Frac=fractions.Fraction
Frac('2/3') + Frac('1/3') + Frac('1/10')
Frac('2/3') + Frac('1/6') + Frac('1/10')

rawDescription: Can I keep decimal precision while using integer division in Python?

description: Keep decimal precision while using integer division in Python


code:
class DemographForm(BoxLayout):
    data = DictProperty({})

rawDescription: Creating a form to populate a database in Kivy


code:
def do_thing(LS, SS):
    if LS.lower().startswith(SS.lower()):
        action_on_match(LS[len(SS):])
    else:
        action_on_no_match()

rawDescription: How should I remove one string from the start of another given that I know the longer string matches case-insensitively?


code:
result = modules.stack()
result.index = result.index.get_level_values(0)
result

rawDescription: Transpose Multidimensional Table

description: Transpose Multidimensional Table


code:
def key(branch):
    id, flows = branch
    try:
        return ordered_branches.index(id)
    except ValueError:
        parts = id.split('-')
        id = '-'.join((parts[1], parts[0], parts[2]))
        return ordered_branches.index(id)

rawDescription: Sorting the contents of one list via the contents of another (Python)


code: po_grouped_df = poagg_df.groupby(['EID','PCODE'], as_index=False)

rawDescription: Pandas - GroupBy and then Merge on original table


code:
order = 3
coefficient_matrix = np.arange(1, order*order+1).reshape(order,order)
using_poly(coefficient_matrix)
using_P2(coefficient_matrix)
using_loop(coefficient_matrix)

rawDescription: Faster way to attach 2d polynomial coefficients to terms in Python?


code: these_args = [template.Variable(arg_name).resolve(context) for arg_name in self.arg_names]

rawDescription: django: resolve variables in custom template

description: Django: resolve variables in custom template


code:
class state:
    a = 0
    b = 0
    variable_list = [a,b]

rawDescription: Python list of variables inside a class

description: Python list of variables inside a class


code:
@main.route('/search/results?<dict:data>')
def view_results(data):
    for i in data:
        print(i, data[i])
    return "placeholder"

rawDescription: redirect data to the next view in Flask

description: Redirect data to the next view in Flask


code:
for y in range(0 , height):
    for x in range(0 , width):
        val1 = img1.item(y,x)
        val2 = img2.item(y,x)
        diff_abs = math.fabs(int(val1)-int(val2))
        if diff_abs > threshold:
            cnt += 1
        if x == height and y == width:
            break
        if x == height:
            x=0
        if y == width:
            y=0

rawDescription: Python Opencv img.item() performance too slow


code:
self.bullets = []
self.bullets.append(bullet())
self.bullets.append(bullet())

rawDescription: Create many classes and be able to reference to them


code:
class Movie(models.Model):
    link = models.URLField()
    title = models.CharField(max_length=100, null=True)
    releaseday = models.CharField(max_length=100, null=True)
    def __unicode__(self):
        return '%s' % (self.title)

class Theater(models.Model):
    movies = models.ManyToManyField(Movie, null=True, blank=True, through="ShowTime")
    theater = models.CharField(max_length=255, null=True)
    def __unicode__(self):
        return '%s' % (self.movie_theater)

class ShowTime(models.Model):
    theater = models.ForeignKey(Theater, null=True, blank=True)
    movie = models.ForeignKey(Movie, null=True, blank=True)
    time = models.CharField(max_length=100, null=True)
    def __unicode__(self):
        return '%s' % (self.time)

rawDescription: Django foreignkey query

description: Django foreignkey query


code:
range(13)
[ '%02d' % i for i in range(13) ]

rawDescription: Various Python datetime issues

description: Various Python datetime issues


code:
def y(u):
    return u**(-2) + 8

rawDescription: Adding lambda functions with the same operator in python


code:
# Create a file for test bench:
d = {'Cameron':'UK', 'Merkel':'Germany', 'Obama':'USA', 'Putin':'Russia'}
with open("G8_Leaders.txt", "w") as f:
    f.write(str(d) +'\n')

#Read and print from the file:
with open("G8_Leaders.txt", "r") as f:
    data = f.readlines()
for line in data:
    d = eval(line)
    for y, z in d.items():
        print(y, z)

rawDescription: Need help iterating through a dictionary - Python


rawDescription: Using Django settings in templates

description: Using Django settings in templates


code:
from pyspark.mllib.linalg import SparseVector, VectorUDT

temp_rdd = sc.parallelize([
    (0.0, SparseVector(4, {1: 1.0, 3: 5.5})),
    (1.0, SparseVector(4, {0: -1.0, 2: 0.5}))])

schema = StructType([
    StructField("label", DoubleType(), True),
    StructField("features", VectorUDT(), True)
])

temp_rdd.toDF(schema).printSchema()

## root
##  |-- label: double (nullable = true)
##  |-- features: vector (nullable = true)

rawDescription: How do I convert an RDD with a SparseVector Column to a DataFrame with a column as Vector

description: Convert an RDD with a SparseVector Column to a DataFrame with a column as Vector


code:
x = intern('google.com')
y = intern('google.com')
id(x), id(y)

rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


code:
links = []
domains = []
for name in usernames:
    public_tweets = api.user_timeline(name, count=10)
    for tweet in public_tweets:
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text)
        for url in urls:
            link = requests.head(url, allow_redirects=True).url  # follow redirects to the end
            links.append(link)
            domain = get_tld(link)
            domains.append(domain)
counts = Counter(domains)

rawDescription: Collections Counter not working

description: Collections Counter not working


rawDescription: Numpy: vector of indices and value

description: Numpy: vector of indices and value


code: Old_Values[index] = []

rawDescription: Creating vertical dictionary from text file


code:
p = ax.plot(X,Y,Z, 'or', markersize=3)[0]

for i in range(0,360,5):
    p.set_xdata(radius*np.cos(np.deg2rad(i)))
    p.set_ydata(radius*np.sin(np.deg2rad(i)))
    p.set_3d_properties(zs=i/140.)

rawDescription: Dynamic Point Manipulation in 3D Matplotlib


rawDescription: Python values out of list

description: Python values out of list


code:
align = {"seq1":"ATGCATGC",
         "seq2":"AT----GC",
         "seq3":"A--CA--C"}

annos = {"seq1":{"gene1":[0,3], "gene2":[4,7]},
         "seq2":{"gene1":[0,3], "gene2":[4,7]},
         "seq3":{"gene1":[0,3], "gene2":[4,7]}}

annos3 = {"seq1":{"gene1":[0,2], "gene2":[3,4], "gene3":[5,7]},
          "seq2":{"gene1":[0,2], "gene2":[3,4], "gene3":[5,7]},
          "seq3":{"gene1":[0,2], "gene2":[3,4], "gene3":[5,7]}}

import re
for name,anno in annos.items():
    # indices of gaps removed usinig re
    removed = [(m.start(0)) for m in re.finditer(r'-', align[name])]

    # removes gaps from align dictionary
    align[name] = re.sub(r'-', '', align[name])

    build_dna = ''
    for gene,inds in anno.items():

        start_ind = len(build_dna)+1

        #generator to sum the num '-' removed from gene
        num_gaps = sum(1 for i in removed if i >= inds[0] and i <= inds[1])

        # build the de-gapped string
        build_dna+= align[name][inds[0]:inds[1]+1].replace("-", "")

        end_ind = len(build_dna)

        if num_gaps == len(align[name][inds[0]:inds[1]+1]): #gene is all gaps
            del annos[name][gene] #remove the gene entry
            continue
        #update the values in the annos dictionary
        annos[name][gene][0] = start_ind-1
        annos[name][gene][1] = end_ind-1

rawDescription: Improving code design of DNA alignment degapping


code:
def Prop(fcn):
    g, s = fcn()
    return property(g, s)

rawDescription: C# style properties in python

description: C# style properties in python


rawDescription: Python Program to convert complicated json into csv for a complete beginner


code:
import csv
import xlrd

workbook = xlrd.open_workbook('test.xlsx')
for sheet in workbook.sheets():
    with open('{}.csv'.format(sheet.name), 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))

rawDescription: How to extract sheet from *.xlsm and save it as *.csv in Python?

description: Extract sheet from *.xlsm and save it as *.csv in Python


rawDescription: JSON to Stacked DataFrame

description: JSON to Stacked DataFrame


code:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()

rawDescription: Random word generator- Python

description: Random word generator- Python


code:
def gcd(a,b):
    while b:
        a, b = b, a % b
    return a

def fib_mod(n, m):
    if n < 0:
        raise ValueError

    def fib_rec(n):
        if n == 0:
            return 0, 1
        else:
            a, b = fib_rec(n >> 1)
            c = a * ((b << 1) - a)
            d = b * b + a * a
            if n & 1:
                return d % m, (c + d) % m
            else:
                return c % m, d % m

    return fib_rec(n)[0]

def is_fib_prp(n):
    if n % 5 == 0:
        return not fib_mod(n, n)
    elif n % 5 == 1 or n % 5 == 4:
        return not fib_mod(n-1, n)
    else:
        return not fib_mod(n+1, n)

rawDescription: Prime number generation using Fibonacci possible?


code:
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
for a in pairwise2.align.localms("ACCGTN97CT", "ACCG8DXCT", 2, -1, -.5, -.1):
    print(format_alignment(*a))

rawDescription: Nucleotides separator in the pairwise sequence alignment bio python


code:
import numpy as np
data = np.random.randint(0,10,size=(320,240)) # create a random array of 320x240
data = np.split(data, data.shape[0]/8)  # first split into 8x240, 8x240,... sub-arrays, i.e., split by rows of 8 first.
res = []
for arr in data:
    res.extend(np.split(arr,arr.shape[1]/8, axis=1)) # now for each 8x240 sub-array split it column-wise into 8x8, 8x8,... arrays

res[0]
res[1199]

rawDescription: Slicing an image array into sub array

description: Slicing an image array into sub array


code:
device.label = xxx
device.name = xxx_subdirectory

rawDescription: scripting tool to modify configuration files

description: Scripting tool to modify configuration files


code:
def get_line_counts(total_lines, number_of_files):
    base_size = total_lines // number_of_files
    line_count_list = [base_size for i in range(number_of_files)]
    files_with_an_extra_line = total_lines % number_of_files
    for i in range(files_with_an_extra_line):
        line_count_list[len(line_count_list) - (i + 1)] += 1
    return line_count_list

for i, n in enumerate(get_line_counts(13, 3)):
    print("file {0} will contain {1} line(s)".format(i, n))

rawDescription: How to split file into number of output files in Python 3?

description: Split file into number of output files in Python 3


code:
import csv

listo = [(A,1), (B,2), (C,3)]
headers, vals = zip(*listo)

with open('output.txt', 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow(headers)
    writer.writerow(vals)

rawDescription: Python - Write list of tuples horizontally to a text file


code:
X[(X[:, 0] == 'rainy').ravel() & (X[:, 1] == 'cool').ravel(), :]
matrix([['rainy', 'cool', 'normal', 'FALSE'],
        ['rainy', 'cool', 'normal', 'TRUE']],
       dtype='|S8')

rawDescription: How to get a subset of rows from a NumPy Matrix based on a condition?

description: Get a subset of rows from a NumPy Matrix based on a condition


code: master_matrix = pd.concat(list_of_dfs, axis=1).values

rawDescription: Building a numpy array (matrix) from several dataframes


code:
import re

txt='''\
nothing(blah)

options{ kA: vA, kB : vB, ...etc.... }
   options{ kA: vA, kB : vB, ...etc.... }

blah blah
    options{ kA: vA, kB : vB, ...etc.... }  # tab'''

print(re.findall(r'^\s*(options{[^}]*})',txt, re.S | re.M))
# ['options{ kA: vA, kB : vB, ...etc.... }', 'options{ kA: vA, kB : vB, ...etc.... }', 'options{ kA: vA, kB : vB, ...etc.... }']

rawDescription: find a function with regex in python

description: Find a function with regex in python


rawDescription: Delete numbers not dates in Python (regex)


code:
str='word1 word2 name: phil age : 23 range: 33, 45'
list(map(lambda x:x.strip() if ':' in x else list(map(lambda s:s.strip(), x.split())), re.findall(r'\w+\s*:?\s*(?:"[^"]*"|.*?(?=\w+\s*:\s*|$))?' , str)))

rawDescription: Split on space but not if there is a colon followed by space or if there is a space in quotes


code:
while x < 6:
    mybutton.configure(command=show)

rawDescription: Trying to get a Button to change a Text widget


code: mrdq_job = MRDataQuality(args=['-r', 'hadoop', '--conf-path', 'mrjob.conf', '--jobconf', 'mapred.reduce.tasks=42', '--jobconf', 'my.job.settings.startdate=2013-06-10', '--jobconf', 'my.job.settings.enddate=2013-06-11', meterFile])

rawDescription: Passing parameters to reducer in MRjob

description: Passing parameters to reducer in MRjob


code:
mylist
for idx in xrange(len(mylist)):
    mylist[idx] = mylist[idx] + " moo"

mylist

rawDescription: Add a word at the end of elements of a list


rawDescription: python pyfits, reading header information and using in caculation

description: Python pyfits, reading header information and using in caculation


code: director_list = Actor.director_list()

rawDescription: Access many-to-many related to the same model


code:
class NumbersTest(unittest.TestCase):

    def test_even(self):
        """
        Test that numbers between 0 and 5 are all even.
        """
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

rawDescription: Adding test methods dynamically using decorator


code: text = first_td.renderContents()

rawDescription: Beautiful Soup [Python] and the extracting of text in a table


code:
# Find the Protocol Compiler.
if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  protoc = os.environ['PROTOC']
else:
  protoc = find_executable("protoc")

rawDescription: Python project using protocol buffers, Deployment issues


code:
import locale
def date_format_encoding():
    return locale.getlocale(locale.LC_TIME)[1] or locale.getpreferredencoding()

rawDescription: How determine encoding of datetime.strftime(...) in Python?


code:
tx = graph.cypher.begin()
statement = "MATCH (city:City {Name: {City_Name}}), MATCH (n:Neighborhood {Name: {Neighborhood_Name}}) CREATE (n)-[:IN]->(city)"
for city_name, neighborhood_names in city_neighborhood_map.iteritems():
    for neighborhood_name in neighborhood_names:
        tx.append(statement, {"City_Name": city_name, "Neighborhood_Name": neighborhood_name})

tx.commit()

rawDescription: Optimizing py2neo's cypher insertion

description: Optimizing py2neo's cypher insertion


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ('id', 'name', 'tenure')

class ClassroomSerializer(serializers.ModelSerializer):
    teachers = TeacherSerializer(source='teacher_set')

    class Meta:
        model = Classroom

rawDescription: How do I include related model fields using Django Rest Framework?

description: Include related model fields using Django Rest Framework


rawDescription: Iterating over dict values

description: Iterating over dict values


code:
with open('/tmp/d.txt', 'rt') as infile:
    reader = csv.reader(infile, delimiter='-')
    scores = dict((key.strip(), int(value)) for (key, value) in reader)
    print(scores)

rawDescription: Python: reading txt file containing (alphabet and number) and updating the number


rawDescription: Simple way to append a pandas series with same index


code:
source_file = open('out.csv', 'rb')
reader = csv.DictReader(source_file, delimiter = '\t')
line = reader.next()
len(line)
line.keys()
line['........Time']
line['.Northing']

rawDescription: KeyError when using DictReader()

description: KeyError when using DictReader()


rawDescription: Include labels for each data point in pandas plotting


code:
['TOKYO-BLING.1 H02-AVAILABLE', 'TOKYO-BLING.1 H02-MIDDLING', 'TOKYO-BLING.1 H02-TOP']
['TOKYO-BLING.2 H04-AVAILABLE', 'TOKYO-BLING.2 H04-CANCELLED', 'TOKYO-BLING.2 H04-USED']
['WAY-VERING.1 H03-CANCELLED', 'WAY-VERING.1 H03-TOP']
['WAY-VERING.2 H03-AVAILABLE', 'WAY-VERING.2 H03-USED']

rawDescription: longest common sequence group

description: Longest common sequence group


code:
def foo(**kwargs):
    return dict(((k,v) for k, v in kwargs.items() if v))

rawDescription: Basic Python metaprogramming: populating dictionaries?


code:
def to_int(iterable):
    return [int(x) for x in iterable]

{z[0]:to_int(z[1:]) for z in zip(*list_of_lists)}

rawDescription: How to map multiple lists to one dictionary?

description: Map multiple lists to one dictionary


code:
class UserSite(models.Model):
    user = models.ForeignKey(User)
    site = models.ForeignKey(Site)

class Lead(models.Model):
    user_site = models.OneToOneField(UserSite)
    ...

class UserDemographic(models.Model):
    user_site = models.OneToOneField(UserSite)
    ...

rawDescription: In Django, how do I join a table with a composite primary key to another table?


code:
class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "home.html"
    paginate_by = 3

    def get_context_data(self, **kwargs):
        context = super(BlogIndex, self).get_context_data(**kwargs)
        context['news_list'] = Entry.objects.filter(category='news') # pass 'news_list' in the context
        return context

rawDescription: List doesn't load in django templates

description: List doesn't load in django templates


code:
def iterate_children(parent):
    child = parent.firstChild
    while child != None:
        yield child
        child = child.nextSibling

rawDescription: Iterate over Element childrens in python


code: m = s.apply(lambda x: x.strftime('%b %Y'))

rawDescription: How to generate a bar chart of occurrences per month from a pandas Series?

description: Generate a bar chart of occurrences per month from a pandas Series


code:
from __future__ import print_function

class transposer(object):
    def _do_loop(self):
        line_number = 0
        for line in self.fin:
            line_number += 1
            line = line.strip();
            if line.strip().startswith('"No."'):
                self.keys = line.strip().split(',')[2:]
            elif line.startswith('"'):
                elts = line.strip().split(',')
                if len(elts) == (len(self.keys) + 2):
                    dat = elts[1]
                    ix = 0
                    for val in elts[2:]:
                        print(dat, self.keys[ix], val, sep=',', file = self.out)
                        ix += 1
                else:
                    raise Exception("Syntax error line %d expected %d values found %d"
                                    % (line_number, len(self.keys), len(elts) - 2))

    def transpose(self, ficin, ficout):
        with open(ficin) as fin:
            with open(ficout, 'w') as fout:
                self.do_transpose(fin, fout)
    def do_transpose(self, fin, fout):
        self.fin = fin
        self.out = fout
        self.keys = []
        self._do_loop()

rawDescription: Python - CSV time oriented Transposing large number of columns to rows


code:
class Window(QtGui.QWidget):
    def __init__(self, address):
        QtGui.QWidget.__init__(self)
        ...
        self._uploaders = {}
        self._statustabs = {}

rawDescription: Progress bar will not work correctly if add more than one window(pyside)


code:
List1  = [['a'],['B']]
List2 = ['A','b','C']

print(list(itertools.zip_longest((b for a in List1 for b in a),List2,fillvalue="foo")))
[('a', 'A'), ('B', 'b'), ('foo', 'C')]

rawDescription: How to get the value in a nested list using itertools.zip_longest

description: Get the value in a nested list using itertools.zip_longest


code:
from ipywidgets import widgets
from traitlets import Unicode

class HelloWorldWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/helloworld/helloworld_view", sync=True)
    _view_name = Unicode('HelloWorldView', sync=True)

rawDescription: Import a iPython Custom Widget Function (File Structure?)


code:
e1 = 'extract1.csv'
compare_extract(e1)
# Extract has the following missing columns: amount

e2 = 'extract2.csv'
compare_extract(e2)
# Extract has the same column as standard. Checking for abberant rows...
# The following rows are not in the extract:
#    id     description  amount        date
# 0   4  My description  $11.35  01/01/2015

rawDescription: Comparing gold standard csv file and extracted values csv files in Python


code:
import csv

my_dict = {}

with open('myfile.csv', 'r') as f:
  for line in csv.reader(f):
    my_dict[line[0]] = line[1]

rawDescription: How do I dump text file contents into dictionary

description: Dump text file contents into dictionary


code:
a = [{'sales': 2100, 'department_id': 66, 'department_name': 'dog', 'month': 11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'cat', 'month': 12},
     {'sales': 2100, 'department_id': 66, 'department_name': 'cat', 'month': 11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'dog', 'month': 12}]

from collections import defaultdict

dct = defaultdict(lambda: {"result": [], "meta": "", "department_id": ""})

for d in a:
    _id = d['department_id']
    dct[_id]["result"].append({"sales": d["sales"], "month": d["month"]})
    dct[_id]["meta"] = d['department_name']
    dct[_id]["department_id"] = _id

from pprint import pprint as pp
pp(dct.values())

rawDescription: How do I format a list of dictionaries with itertools.groupby?

description: Format a list of dictionaries with itertools.groupby


code:
def state_from_request_wrapper(wrapped_func):
    wrapped_func = wrapped_func.__func__
    def _w(cls, request):
        state = wrapped_func(cls, request)
        invite_key = extract_invite_key(request)
        if invite_key:
            state['invite_key'] = invite_key
        return state
    return classmethod(_w)

def extract_invitation_key(request):
    referer = request.META.get('HTTP_REFERER')
    if not referer:
        return None
    p = re.compile('iv/(?P<invite_key>[\w\d]+)/$')
    match = p.search(referer)
    if not match:
        return None
    return match.group(1)

SocialLogin.state_from_request = state_from_request_wrapper(SocialLogin.state_from_request)

rawDescription: How to implement an invite flow using django allauth for signup/signin?

description: Implement an invite flow using django allauth for signup/signin


code: subprocess.Popen(['myCppprogram.exe', 'foo', 'bar'], ...)

rawDescription: Call a C++ project main() in Python in Visual Studio?


code: newkey, newvalue = d.keys(), [' '.join(v) for v in d.values()]

rawDescription: Concatenate strings by groups python

description: Concatenate strings by groups python


code:
for k in li:
    d.setdefault(k,0)
    d[k] += 2

rawDescription: python dict add and modify operation

description: Python dict add and modify operation


rawDescription: Unique zero-based id for values in pandas


code: mystr = mystr[:mystr.find('"') + 1]

rawDescription: Python Remove Parts of string by index

description: Python Remove Parts of string by index


code:
[elem
 for line in body
 for elem in (line.split()[1:] if line.startswith('Participant:') else (line,))]

rawDescription: Split, edit, and replace values in list

description: Split, edit, and replace values in list


code: keys = [key for key, value in d.items() if value == 15]

rawDescription: Python 2 Selecting a key with a value

description: Python 2 Selecting a key with a value


code:
y = np.zeros_like(x)
ind = [np.random.choice(np.where(row)[0]) for row in x]
y[range(x.shape[0]), ind] = 1

rawDescription: Choosing random one from each row of a binary numpy matrix?


code:
for i in soup.select("h2.hello-word > a"):
    print(i.text)

rawDescription: How do I get the value of a soup.select?

description: Get the value of a soup.select


code:
def main():
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s %(process)d %(message)s")

    q = JoinableQueue()
    it = count(1)
    producers = [Thread(target=producer, args=(i, q)) for i in islice(it, 2)]
    workers = [Thread(target=worker, args=(i, q)) for i in islice(it, 4)]
    for t in producers+workers:
        t.daemon = True
        t.start()

    for t in producers: t.join() # put items in the queue
    q.join() # wait while it is empty
    # exit main thread (daemon workers die at this point)

if __name__=="__main__":
   main()

rawDescription: Throughput differences when using coroutines vs threading


rawDescription: How to move a Tkinter button?

description: Move a Tkinter button


code: l=map(set,[[]]*passwordLen)

rawDescription: Create a list of n distinct sets

description: Create a list of n distinct sets


code: Series([s[x]+" my index is:  "+x for x in s.keys()], index=s.keys())

rawDescription: pandas row specific apply

description: Pandas row specific apply


code:
for dct in data:
    print(dct["NO_USERS"])

rawDescription: How to read a file block-wise in python

description: Read a file block-wise in python


code:
varOne = set(s1.split(','))
varTwo = set(s2.split(','))
varOne == varTwo

rawDescription: python return equal where the string is not actually equal?

description: Python return equal where the string is not actually equal


rawDescription: Change embedded image type in APIC ID3 tag via Mutagen


code:
# The for-loop will run from 1-8
for port in range(1, 9):
    G.add_edge('Switch0', 'Switch1', key="{}-{}".format(port, port), headport = port, tailport = port)

rawDescription: pygraphviz: How to get same edges connected on different ports without iterating?

description: Pygraphviz: How to get same edges connected on different ports without iterating


code:
numlist, alist, blist = [], [], []
d = {"a": alist, "b": blist}
for item in mixlist:
    d.get(item, numlist).append(item)

rawDescription: Split a list in sublists by a logic criterion


code:
from django.db.models import Q
Blog.objects.filter(Q(key__startswith='a') | Q(key__startswith='b'))

rawDescription: Django - filtering by a portion of the key within a list


code: new_wordlist = [word for word in wordlist if word != variable]

rawDescription: how to assign a word from a text file to a variable in python

description: Assign a word from a text file to a variable in python


code: repr(lambda x:x)

rawDescription: Python: Intersection of two lists of lists


code:
opener = urllib2.build_opener(
    urllib2.HTTPSHandler())
opener.open('https://google.com')

rawDescription: Python - check if file/webpage exists

description: Python - check if file/webpage exists


code:
A
unq_count

rawDescription: Efficiently count the number of occurrences of unique subarrays in NumPy?


code:
is_all_dates
is_boolean
is_categorical
is_floating
is_integer
is_mixed
is_numeric
is_object

rawDescription: pandas object indexes can be either string or int, how can I tell them apart?

description: Pandas object indexes can be either string or int, how can I tell them apart


rawDescription: Splitting a GPS Point into Latitude and Longitude Regular


code:
import mymath
print(mymath.foo(y))

rawDescription: Of Healthy Programming Practices

description: Of Healthy Programming Practices


code: [list(item) + [1] for item in s]

rawDescription: How to count elements in a list of lists of strings

description: Count elements in a list of lists of strings


code: files_in_db = Screenshot.objects.values_list('filename', flat=True).distinct()

rawDescription: Check if an element exists

description: Check if an element exists


code:
test_variable = 1
setEqual(test_variable, [1, 2, 3, 4])
# Passes, because the identifier test_variable
# CAN'T be rebound within this scope from setEqual.
assert test_variable == 1

rawDescription: How do I copy only the values and not the references from a Python list?

description: Copy only the values and not the references from a Python list


rawDescription: How do I get Python2.x `map` functionality in Python3.x?

description: Get Python2.x `map` functionality in Python3.x


code: item = namedtuple('item', 'company google_name place_id formatted_address')

rawDescription: Python: adding named tuples to MySQL in a for loop


code:
input_one = "1 3 2"
input_two = "2 3 0"

rawDescription: Append input to list as integers

description: Append input to list as integers


code:
i = iter(list_of_strings)
for line in i:
    if line[0] == '$':
        try:
            while line[-1] == '#':
                line = i.next()
        except StopIteration:
            break
        # do work on 'line' which begins with $ and doesn't end with #

rawDescription: for loops in python

description: For loops in python


code:
lst = [(key, value['std']) for key, value in sd_dict.items()]
lst.sort(key=lambda x: x[1])
lst

rawDescription: Sorting nested python dictionary by label


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

def main():
    fig, ax = plt.subplots()
    dual_half_circle((0.5, 0.5), radius=0.3, angle=90, ax=ax)
    ax.axis('equal')
    plt.show()

def dual_half_circle(center, radius, angle=0, ax=None, colors=('w','k'),
                     **kwargs):
    """
    Add two half circles to the axes *ax* (or the current axes) with the
    specified facecolors *colors* rotated at *angle* (in degrees).
    """
    if ax is None:
        ax = plt.gca()
    theta1, theta2 = angle, angle + 180
    w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], **kwargs)
    w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], **kwargs)
    for wedge in [w1, w2]:
        ax.add_artist(wedge)
    return [w1, w2]

main()

rawDescription: Matplotlib half black and half white circle


code: list({'number':x,'letter':y,'fruit':z} for x,y,z in zip(numbers,letters,fruits))

rawDescription: How to combine lists into one with sub list in python

description: Combine lists into one with sub list in python


code: DEFABC

rawDescription: Recursion on strings - back to beginning of string?


code:
from abc import ABCMeta, abstractmethod

class YourAbstractFactory(object):
    __metaclass__ = ABCMeta

    @classmethod
    def get_factory(cls, condition):
        cond_map = {
            'impl1': Impl1,
            'impl2': Impl2
        }

        impl = cond_map.get(condition)

        return impl() if impl else None

    @abstractmethod
    def f1(self):
        pass

    @abstractmethod
    def f2(self):
        pass

rawDescription: Advantages to two modules with same interface or two classes with the same interface?


code:
def OnMenuItem(self, evt): #don't forget the evt
    sp = SubPanel(self, wx.ID_ANY, 'TEST')
    #I assume you will add it to a sizer
    #if you aren't... you should
    test_sizer.Add(sp, 1, wx.EXPAND)
    #force the frame to refresh the sizers:
    self.Layout()

rawDescription: How do I Create an instance of a class in another class in Python


rawDescription: How to get node name without namespace if it exists?

description: Get node name without namespace if it exists


code:
def CheckIfFilesMatch(self):
    if(len(self.subdirArray1) != len(self.subdirArray2)):
        self.__FileMatchError("please enter same amount of files")
        return False

    tmp = set(self.subdirArray2)
    for f in self.subdirArray1:
        frev = f.replace(self.rootDir1,self.rootDir2);
        if frev not in tmp:
            self.__FileMatchError("This file: " + f + " does not correspond to any file in parallel.")
            return False
        tmp.discard(frev)
    if tmp:
        self.__FileMatchError("This file: " + tmp.pop() + " does not correspond to any file in parallel.")
        return False
    return True

def __FileMatchError(self, txt):
    self.statusText.SetValue(txt)
    self.blocker = True
    self.statusText.SetForegroundColour(wx.RED)

rawDescription: Image Saving I/O Using Python Efficiency & Speed


code:
from collections import namedtuple

Point_ = namedtuple("Point", ["x", "y"])

class Point(Point_):
    """ A point in 2d space """
    __slots__ = ()

rawDescription: Adding docstrings to namedtuples?

description: Adding docstrings to namedtuples


code: sql = """last_check_timestamp is NULL or DATE_ADD(last_check_timestamp, INTERVAL schedule.interval_seconds SECOND) < DATE(NOW())"""

rawDescription: Query Expired Time Difference in Django ORM


code:
with open("test.txt",'r+') as w_file:
    w_file.write(str(0.8) + "\n" + str(0.2))

subprocess.call(["cat","test.txt"]) #Here I want to call my routine

rawDescription: Write file input for subprocess

description: Write file input for subprocess


code:
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

c = canvas.Canvas("test.pdf")
# move the origin up and to the left
c.translate(inch,inch)
c.setFillColorRGB(1,0,1)
c.drawImage("image1.jpg", 10, 10, 50, 50)
c.drawImage("image2.jpg", 60, 60, 50, 50)

c.showPage()
c.save()

rawDescription: Insert multiple images in a single PDF according to image.coordinates - Python


code:
yourNumber= input('Enter a number: ')
isPrime = 0
if yourNumber == 1:
    isPrime = 1
    print(yourNumber,'is not a prime number')
else :
    for primeCheck in range (int(2), int(yourNumber)):
        if int(yourNumber)%int(primeCheck) == 0:
            isPrime = 1
            break
        else:
            isPrime = 0
    if isPrime == 0:
        print(yourNumber,'is a prime number')
    else:
        print(yourNumber,'is not a prime number')

rawDescription: Python and Prime Numbers

description: Python and Prime Numbers


code:
demo.py
import string
from ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLL

class Row(Structure):
    _fields_ = [('cols_count', c_int),
                ('cols', POINTER(c_char_p))]
    def __init__(self,cols):
        self.cols_count = cols
        # Allocate an array of character pointers
        pc = (c_char_p * cols)()
        self.cols = cast(pc,POINTER(c_char_p))

class Unit(Structure):
    _fields_ = [('rows_count', c_int),
                ('rows',POINTER(Row))]
    def __init__(self,rows,cols):
        self.rows_count = rows
        # Allocate an array of Row structures.
        # This does NOT call __init__.
        pr = (Row * rows)()
        # Call init manually with the column size.
        for r in pr:
            r.__init__(cols)
        self.rows = cast(pr,POINTER(Row))

unit = Unit(2,3)

# Stuff some strings ('aaaaa','bbbbb',etc.)
for i in xrange(unit.rows_count):
    for j in xrange(unit.rows[i].cols_count):
        unit.rows[i].cols[j] = string.ascii_lowercase[i*5+j]*5

dll = CDLL('test.dll')
dll.my_func(byref(unit))

rawDescription: Dynamic arrays and structures in structures in python


code:
with open(json_file_path, "a") as json_file:
    json_file.write("{}\n".format(json.dumps(new_data)))

rawDescription: Update json file

description: Update json file


code:
def does_module_exist_at_given_path(module_name, path):
    '''
    imp.find_module() does not find zipped eggs.
    Needed for check: check if a package is installed twice.
    '''
    for path_item in path:
        result=None
        try:
            result=imp.find_module(module_name, [path_item])
        except ImportError:
            pass

        if result:
            return bool(result)
        if not os.path.isfile(path_item):
            continue
        # could be a zipped egg
        module=zipimport.zipimporter(path_item).find_module(module_name)
        if module:
            return bool(module)
    raise ImportError(module_name)

rawDescription: pip installs package twice

description: Pip installs package twice


code:
import sys
sys.stdout.write('text')

rawDescription: Micropython updating board V 1.0

description: Micropython updating board V 1.0


code:
for item in raw:
  if not cardinals.has_key(item[1]):#wdir e.g. 'W'
    cardinals[item[1]] = bands
for item in cardinals.keys():
  if not cardinal_count.has_key(item):
    cardinal_count[item] = counts #

rawDescription: Strange counting behaviour when sorting list of tuples into dictionary


code:
def __getattr__(self, attr):
    if attr == "foo":
        #function "foo" returns an (whatever object)
        result = foo()
        res_type = type(result)
        wrapper_dict = res_type.__dict__.copy()
        wrapper_dict["__doc__"] = foo.__doc__ #(or "<desired documentation for this attribute>")
        new_type = type(res_type.__name__, (res_type,), wrapper_dict)
        # I will leave it as an "exercise for the reader" if the
        # constructor of the returned object can't take an object
        # of the same instance (python native data types, like int, float, list, can)
        new_result = new_type(result)
    elif ...:
        ...
    return new_result

rawDescription: doc for __getattr__ defined attributes

description: Doc for __getattr__ defined attributes


rawDescription: Python: How to convert a rgb or hex value to single color values


code:
def identity(x):
  return x
min(L, key=identity)

rawDescription: Is this control structure a code smell?

description: Is this control structure a code smell


rawDescription: Get only first duplicates in list of dicts with python


code:
pattern = 'Z:/RunLog/*{0}/*{0}/*{0}_infosite.rst'.format(user_input)
filenames = glob.glob(pattern)

rawDescription: directory path as user input, but for multiple folders at once

description: Directory path as user input, but for multiple folders at once


code: getattr(cwrapper.c, "enum1")

rawDescription: Fetching a C variable value in an enum using its name (a Python string) in Python


code:
def trav(dir_1, dir_2):
    data_0 = []
    data_1 = []
    for dir in [dir_1, dir_2]:
        if dir == dir_1:
            data = data_0
        else:
            data = data_1
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                     data.append(line)

rawDescription: Python, appending to different lists while looping


code:
import email.utils

def split_combined_addresses(addresses):
    parts = email.utils.getaddresses(addresses)
    return [email.utils.formataddr(name_addr) for name_addr in parts]

print(split_combined_addresses(email_to))

rawDescription: Python Retrieve Email Addresses

description: Python Retrieve Email Addresses


code:
my_form = MyForm()
my_form.category.query = Category.filter(user=some_user)

rawDescription: Is it possible to limit choices in SelectModelField in wtf-peewee


code:
['Network', 'Technology', 'GSM / HSPA / LTE']
['Network', '2G bands', 'GSM 850 / 900 / 1800 / 1900 - SIM 1 & SIM 2']
['Network', '\xa0', 'GSM 850 / 900 / 1800 / 1900 - SIM 1 & SIM 2 - India']
['Network', '3G bands', 'HSDPA 850 / 900 / 1900 / 2100 ']
['Network', '\xa0', 'HSDPA 2100 - India']
['Network', '4G bands', 'LTE band 1(2100), 3(1800), 7(2600), 38(2600), 39(1900), 40(2300), 41(2500)']
['Network', 'Speed', 'HSPA, TD-SCDMA, LTE, TD-LTE']
['Network', 'GPRS', 'Yes']
['Network', 'EDGE', 'Yes']
['Launch', 'Announced', '2015, March']
['Launch', 'Status', 'Available. Released 2015, March']
['Body', 'Dimensions', '152.6 x 76.2 x 8 mm (6.01 x 3.00 x 0.31 in)']
['Body', 'Weight', '150 g (5.29 oz)']
['Body', 'SIM', 'Dual SIM (Micro-SIM, dual stand-by)']
['Display', 'Type', 'IPS capacitive touchscreen, 16M colors']
['Display', 'Size', '5.5 inches (~71.7% screen-to-body ratio)']
['Display', 'Resolution', '1080 x 1920 pixels (~401 ppi pixel density)']
['Display', 'Multitouch', 'Yes, up to 5 fingers']
['Display', '\xa0', '- Lenovo Vibe 2.0']
['Platform', 'OS', 'Android OS, v5.0.2 (Lollipop), upgradable to v6.0 (Marshmallow)']
['Platform', 'Chipset', 'Mediatek MT6752']
['Platform', 'CPU', 'Octa-core 1.7 GHz Cortex-A53']
['Platform', 'GPU', 'Mali-T760MP2']
['Memory', 'Card slot', 'microSD, up to 32 GB (dedicated slot)']
['Memory', 'Internal', '16 GB, 2 GB RAM']
['Camera', 'Primary', '13 MP, f/2.0, autofocus, dual-LED flash, check quality']
['Camera', 'Features', 'Geo-tagging, touch focus, face detection, HDR, panorama']
['Camera', 'Video', '1080p@30fps, check quality']
['Camera', 'Secondary', '5 MP, f/2.4']
['Sound', 'Alert types', 'Vibration; MP3, WAV ringtones']
['Sound', 'Loudspeaker ', 'Yes']
['Sound', '3.5mm jack ', 'Yes']
['Sound', '\xa0', '- Dolby Atmos']
['Comms', 'WLAN', 'Wi-Fi 802.11 b/g/n, hotspot']
['Comms', 'Bluetooth', 'v4.1, A2DP, LE']
['Comms', 'GPS', 'Yes, with A-GPS, GLONASS']
['Comms', 'Radio', 'FM radio']
['Comms', 'USB', 'microUSB v2.0, USB Host']
['Features', 'Sensors', 'Accelerometer, gyro, proximity, compass']
['Features', 'Messaging', 'SMS(threaded view), MMS, Email, Push Mail, IM']
['Features', 'Browser', 'HTML5']
['Features', 'Java', 'No']
['Features', '\xa0', '- Active noise cancellation with dedicated mic\r\n- MP4/H.264 player\r\n- MP3/WAV/eAAC+/FLAC player\r\n- Photo/video editor\r\n- Document viewer']
['Battery', '\xa0', 'Removable Li-Ion 3000 mAh battery']
['Battery', 'Stand-by', 'Up to 750 h (3G)']
['Battery', 'Talk time', 'Up to 36 h (3G)']
['Misc', 'Colors', 'Onyx Black, Pearl White, Laser Yellow']
['Misc', 'Price group', '3/10 (About 150 EUR)']
['Tests', 'Performance', '\nBasemark OS II: 1053 / Basemark OS II 2.0: 984Basemark X: 5656']
['Tests', 'Display', '\nContrast ratio: 1793:1 (nominal)']
['Tests', 'Camera', '\nPhoto / Video']
['Tests', 'Loudspeaker', '\nVoice 65dB / Noise 66dB / Ring 76dB\n']
['Tests', 'Battery life', '\n\nEndurance rating 53h\n\n']
['Tests']

rawDescription: Scrap all tables from div using BeautifulSoup


code:
from decimal import Decimal

print(access.getinfo()["balance"])

rawDescription: Python json-rpc help, how to extract data


code: from __future__ import division

rawDescription: How do you get a decimal in python?

description: Get a decimal in python


code: #PolandNeedsWWATour #DownloadElyarFox #DünMürteciBugünHaşhaşi #GalatasaraylılıkNedir #KnowTheTruth Tameni Video Anisa Rahma Mikaeel Manado JDT

rawDescription: Python: Get Twitter Trends in tweepy, and parse JSON


code:
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class TestClassDemo(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def build_abc(self, oneTimeSetUp): # <-- note the oneTimeSetup reference here
        self.abc = ABC(self.driver)

    def test_methodA(self):
        self.driver.get("https://google.com")
        self.abc.enterName("test")
        print("Running method A")

    def test_methodB(self):
        self.abc.enterName("test")
        print("Running method B")

rawDescription: pytest -> How to use fixture return value in test method under a class

description: Pytest -> How to use fixture return value in test method under a class


code:
import re
def sort_nicely(l):
    """
    Sort the given list in the way that humans expect. Modifies the original list.
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    l.sort(key=alphanum_key)
mylist = ['LOG-rank-0-die-10-delay-500.txt',
'LOG-rank-0-die-10-delay-4000.txt',
'LOG-rank-0-die-10-delay-7000.txt',
'LOG-rank-1-die-10-delay-500.txt',
'LOG-rank-1-die-10-delay-4000.txt',
'LOG-rank-1-die-10-delay-7000.txt',
'LOG-rank-2-die-10-delay-500.txt',
'LOG-rank-2-die-10-delay-4000.txt',
'LOG-rank-2-die-10-delay-7000.txt']
sort_nicely(mylist)
print(*mylist, sep='\n')

rawDescription: How to sort files in linux by number?

description: Sort files in linux by number


code: np.array([[x1**2+y1**2 for y1 in y] for x1 in x])

rawDescription: Reshaping numpy array without using two for loops


code:
my_dict = {'fruits':['orange', 'pear']}
type(my_dict['fruits'])

rawDescription: What's the equivalent of PHP's "$my_array[]" in Python?


code:
# test_mpi.py
import os
import socket
from mpi4py import MPI

MPI = MPI.COMM_WORLD

print("{host}[{pid}]: {rank}/{size}".format(
    host=socket.gethostname(),
    pid=os.getpid(),
    rank=MPI.rank,
    size=MPI.size,
))

rawDescription: Setting up a distributed ipython/ipyparallel MPI cluster


code:
from io import StringIO

ss = '''<input type="hidden" name="__FOO" id="__FOO" value="garble" />

<script type="text/javascript">
//<![CDATA[
$(function () {
    // convert to
    var True = true, False = false;

    manatee.start({
        pageIDs: ["16798", "16799", "16800", "16801", "16802"],
        userNames: ["Alice", "Bob", "Carol", "Dave", "Eve"],
        wordCounts: [77,23,64,89,93],
        linkCounts: [2,0,3,1,4],
        pageUrls: ["","/blog/35318264c9a98faf79965c270ac80c5606774df1/data.pdf","/blog/da6645f6e22bf5f75974dc7eed5fcd6160d6b51e/data.pdf","/blog/6f90f101115140727c43cadee0b9e17881403a63/data.pdf","/blog/333584fc2850d1a1f97a0a7bf8c5a12e684856bf/data.pdf","/blog/9a018ecc48a37a9247a6404fd83e085384b445aa/data.pdf"],

        toolbar: {
            id: "ManateeToolbar",
            buttons: [
                {
                    id: "ManateeBrowser",
                    text: "Enter Fullscreen",
                    toggleText: "Escape Fullscreen"
                }
            ]
        }

    });
});
//]]>
</script>

<script type="text/javascript">var blah</script>'''

simili_file = StringIO(ss)

for line in simili_file:
    if line[0:13] == '\t\tpageUrls: [':
        urls = tuple(el[1:-1] for el in line[13:line.find(']')].split(',') if el[1:-1])
    print( urls )

rawDescription: Read contents of <script> with BeautifulSoup


code:
logb = np.log(b.astype('complex'))
real, imag = logb.real, logb.imag
print(np.real_if_close(
    np.exp(
        sum(j * ndimage.convolve(x, s, mode = 'constant')
            for x,j in zip((real, imag),(1,1j))))))
# [[-2. -2. -2.  1.]
#  [-2. -0. -0.  0.]
#  [ 2.  0.  0.  0.]
#  [ 1.  0.  0.  0.]]

rawDescription: Iterate with binary structure over numpy array to get cell sums


code:
matching = []
for c in combinations:
  if reduce(lambda x, y: x * y, c, 1) == 60:
    matching.append(c)

rawDescription: Finding all possible combination on python


code:
stats_div = soup.find('div', class_="tabbertab", title="Stats")
len(stats_div.find_all('table', class_="stat"))

rawDescription: Python beautiful soup how to get deep nested elements


code:
say = lambda x: lambda y: x + " " + y
say('Hello')('World')

rawDescription: Interesting "Hello World" Interview

description: Interesting "Hello World" Interview


code:
async def hello_world(loop):
    print('Hello')
    await asyncio.sleep(5, loop=loop)
    print('World')

rawDescription: Execute coroutine from `call_soon` callback function


code: vocabulary1.count(u'succour')  # vocabulary1 does **not** contain the string u'succour'

rawDescription: FreqDist in NLTK not sorting output

description: FreqDist in NLTK not sorting output


code:
from collections import Counter
from itertools import takewhile

c = Counter(tuple(x) for x in t1)
[list(k) for k, v in takewhile(lambda x: x[1] >= 3, c.most_common())]

rawDescription: list(set) for nested lists?

description: List(set) for nested lists


rawDescription: Rscript Subprocess Python

description: Rscript Subprocess Python


rawDescription: Function which is similar to numpy's diff


code: pages_with_no_items = Page.all().filter("has_items =", False)

rawDescription: Google app engine python problem

description: Google app engine python problem


rawDescription: common elements in two lists where elements are the same

description: Common elements in two lists where elements are the same


rawDescription: User Defined Slice function in python script


code:
a = numpy.arange(9).reshape(3, 3)
a.ravel()

rawDescription: Concatenate all rows of a numpy matrix in python


code:
"a" * 3
output: 'aaa'

rawDescription: How to break "/home/username/ok/ok.txt" in a tree hierarchy in Python?

description: Break "/home/username/ok/ok.txt" in a tree hierarchy in Python


code:
#!/usr/bin/env python

import sys

from circuits import Component
from circuits.io import stdout, Process, write

class Ping(Component):

    stdout = stdout

    def init(self, host):
        self.p = Process(["/bin/ping", host]).register(self)
        self.p.start()

    def read(self, data):
        self.fire(write(data), stdout)

app = Ping(sys.argv[1])
app.run()

rawDescription: Monitoring output of parallel subprocess in python 2.7 - pocketsphinx


code:
def commmanHandler(botuser, botmsg):         # botmsg = '!ban user1'
    command = botmsg.split(' ')[0]           # command = '!ban'
    command = command[1:]                    # command = 'ban'
    argu = message.split(' ')[1]             # argu = 'user1'

    if command not in commmandList:
        raise Exception("command not support")

    if command == 'ban':                     # ban command, or using switch
        # check if admin
        if botuser not in adminList:
            raise Exception("I'm sorry, " + botuser + ", This command is restricted to admins only.")
        # admin, able to ban
        irc.send('PRIVMSG' + channel + ' :' + '.ban ' + argu)

rawDescription: Identify sending user, Python IRC

description: Identify sending user, Python IRC


code:
tdict=dict(request.form)
fdict={}
idict={}
for item in tdict.keys():
    (name,id)=item.split("~",1)
    fdict[name]=tdict[item]
    idict[name]=id

rawDescription: How can I get form input metadata using request.form

description: Get form input metadata using request.form


code:
import os
import sys
import vlc

if __name__ == '__main__':
    #filepath = <either-some-url-or-local-path>
    movie = os.path.expanduser(filepath)
    if 'http://' not in filepath:
        if not os.access(movie, os.R_OK):
            print ( 'Error: %s file is not readable' % movie )
            sys.exit(1)
    instance = vlc.Instance("--sout=#duplicate{dst=file{dst=example.mpg},dst=display}")
    try:
        media = instance.media_new(movie)
    except NameError:
        print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
                       vlc.__version__, vlc.libvlc_get_version()))
        sys.exit(1)
    player = instance.media_player_new()
    player.set_media(media)
    player.play()

    #dont exit!
    while(1):
        continue

rawDescription: Saving a stream while playing it using LibVLC


code:
import boto
conn = boto.connect_ec2()

my_eni_groups = conn.get_all_network_interfaces(['eni-1582af5d'])[0].groups
my_eni_sg_ids = [ x.id for x in my_eni_groups ]

add_sg = 'sg-xxxx1234'

if add_sg not in my_eni_sg_ids:
    my_eni_sg_ids.append(add_sg)

    #only need to call this if we modified the list
    conn.modify_network_interface_attribute(interface_id=eni_id,
                                            attr='groupSet',
                                            value=my_eni_sg_ids)

rawDescription: How do I add or remove security groups from ENIs using Boto?

description: Add or remove security groups from ENIs using Boto


rawDescription: Python Pandas Use if-else to populate new column


code: "hello world sample text".split(" ")

rawDescription: Python regex separate space-delimited words into a list


code: if len(workDays) >= 5: break

rawDescription: When Does a While Loop Break

description: When Does a While Loop Break


code: # ... do other things ...

rawDescription: Asynchronous fetch request with Google App Engine


rawDescription: convert str(time) to date format with other data included

description: Convert str(time) to date format with other data included


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

def make_format(current, other):
    # current and other are axes
    def format_coord(x, y):
        # x, y are data coordinates
        # convert to display coords
        display_coord = current.transData.transform((x,y))
        inv = other.transData.inverted()
        # convert back to data coords with respect to ax
        ax_coord = inv.transform(display_coord)
        coords = [ax_coord, (x, y)]
        return ('Left: {:<40}    Right: {:<}'
                .format(*['({:.3f}, {:.3f})'.format(x, y) for x,y in coords]))
    return format_coord

np.random.seed(6)
numdata = 100
t = np.linspace(0.05, 0.11, numdata)
y1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
y2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax2.format_coord = make_format(ax2, ax1)

ax1.plot(t, y1, 'r-', label='y1')
ax2.plot(t, y2, 'g-', label='y2')

plt.show()

rawDescription: Matplotlib cursor value with two axes

description: Matplotlib cursor value with two axes


code:
Sample
sample
sample
sample
Specimen
Sample
...

rawDescription: Enter data in textarea using mechanize Python


code:
for something in query:
    blah

rawDescription: GAE Datastore ndb models accessed in 5 different ways


code:
from collections import MutableMapping

def set_value(d, keys, newkey, newvalue, default_factory=dict):
    """
    Equivalent to `reduce(dict.get, keys, d)[newkey] = newvalue`
    if all `keys` exists and corresponding values are of correct type
    """
    for key in keys:
        try:
            val = d[key]
        except KeyError:
            val = d[key] = default_factory()
        else:
            if not isinstance(val, MutableMapping):
                val = d[key] = default_factory()
        d = val
    d[newkey] = newvalue

rawDescription: Python: Change values in dict of nested dicts using items in a list


code:
import P4
p4 = P4.P4()
p4.connect()
p4.run_opened()[0]['action']
p4.disconnect()

rawDescription: How to get the type of change in P4Python

description: Get the type of change in P4Python


rawDescription: Initializing object variables - a Java approach, a Python approach?


rawDescription: Is there a one-liner to list a directory two levels deep where the second level is an only-child, but not known?


rawDescription: What are the upper and lower bound for Chinese char in UTF-8?


code:
import re
s = "KAAAKBBBBR"
re.findall(r'[^KR]*[KR]', s)
re.findall(r'[^KR]+[KR]', s)

rawDescription: Translate perl split to python split

description: Translate perl split to python split


rawDescription: Collecting data from .txt url in Python with strange encoding


code:
[('conocías', 'conozcas', 'conociéremos', 'conocerán', 'conocían'),
 (),
 (),
 ('planeareis', 'planeáramos', 'planeasteis', 'planearás')]

rawDescription: Combining Keys in Dictionary into tuples in a list


code:
from datetime import datetime,timedelta
base = datetime.today()
date_list = [(base - timedelta(days=x)).strftime(" %A, %B %d, %Y") for x in range(0, 7)]
print(date_list)

rawDescription: Problems with turning a timedelta calculation into " %A, %B %d, %Y"


code:
import numpy as np

a = np.array(your_list_of_lists)

np.setdiff1d(np.arange(21000), a.flatten())

rawDescription: Python: Find indices which are *not* contained in a list of lists


code:
df['cnt'] = df.groupby('col3')['col3'].transform(len)
df

rawDescription: Counting occurrence of a word in a column of a tsv file using python


code: nums, words = map(list, zip(*nums_and_words))

rawDescription: Python Tuple Unpacking

description: Python Tuple Unpacking


code:
# slower
df.groupby("Letters").sum()["Bool"] # sum everything, select Bool

rawDescription: Summing values in a group of a groupby object?


code:
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from bar')

rawDescription: Is there a way to get a list of column names in sqlite?


code:
d2 = df.unstack().reset_index()
d2 = d2.rename(columns={0: "Sales"})
parts = d2.pop("level_0").str.split(":")
d2["State"] = [p[1].strip() for p in parts]
d2["Sector"] = [p[2].strip() for p in parts]

rawDescription: Pandas Dataframes- Adding Fields Based on Column Titles


rawDescription: python regular expression $[a-zA-Z ][0-9a-zA-Z ]* with forbidding

description: Python regular expression $[a-zA-Z ][0-9a-zA-Z ]* with forbidding


code:
product_one = Product(name="product_one")
product_one.save()

rawDescription: How do you implement multiple data types for an object in Django?

description: Implement multiple data types for an object in Django


code: return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': kwargs['unreadcount']})

rawDescription: Appending render with decorator in Django


code:
while True:
    sentence = input("What is your sentence? ")
    List1 = sentence.split(' ')
    List1 = [item.lower() for item in List1]

    # Here is the check. It creates a new list with only the strings
    # that are numbers by using list comprehensions.
    #
    # So if the length of the list is greater then 0 it means there
    # are numbers in the list.
    if len([s for s in List1 if isdigit(s)]) > 0:
        print('You sentence contains numbers... retry!')
        continue

    word = input("What word do you want to find? ")
    word = word.lower()
    length = len(List1)

    counter = 0

    while counter < length:
        if word == List1[counter]:
            print("Word Found In Position ",counter)
            counter += 1
        elif word != List1[counter]:
            counter += 1
        else:
            print("That word is not in the sentence")

rawDescription: Hi I was wondering if there was a data type in Python that only allows letters to be inputed and not numbers


code:
rules = [
    Rule(SgmlLinkExtractor(allow=()), follow=True),
    Rule(SgmlLinkExtractor(allow=()), callback='parse_item')
]

rawDescription: scrapy crawling just 1 level of a web-site

description: Scrapy crawling just 1 level of a web-site


rawDescription: Hide imported modules to interpreter

description: Hide imported modules to interpreter


code:
actual_hosts = set()
for result in results.ResultsReader(job.results()):
    for hosts in results.values():
        actual_hosts.update(hosts)

rawDescription: Store OrderedDict Values to Set in Python


code:
def purify(numbers):
    numbers[:] = [x for x in numbers if not x % 2]
    return numbers

rawDescription: Python remove element in for loop

description: Python remove element in for loop


code:
def double_brace(string):
    string = string.replace('{','{{')
    string = string.replace('}','}}')
    return string

my_string = "Here come the braces : {a{b}c}d{e}f"
my_string = double_brace(my_string)
my_string += " : {}"
my_string = my_string.format(42)
print(my_string)

rawDescription: Python Alternative to Old String Formatting


code:
def dim(a):
    if not type(a) == list:
        return []
    return [len(a)] + dim(a[0])

rawDescription: Find the dimensions of a multidimensional Python array


code:
input_list = ['A','B','C/D','E']
[y for x in input_list for y in (x.split('/') if '/' in x else [x])]

rawDescription: Python list comprehension with adding more elements in one go


rawDescription: Using infinity in dynamic programming coins example - why does this not fail?


code:
from multipledispatch import dispatch

@dispatch(RDD)
def baz(x):
    return "RDD"

@dispatch(DataFrame)
def baz(x):
    return "DataFrame"

baz(sc.parallelize([]))
## 'RDD'

baz(sc.parallelize([("foo", 1)]).toDF())
## 'DataFrame'

rawDescription: Check Type: How to check if something is a RDD or a dataframe?


code:
Counter({
    'Question 4': 3,
    'Question 1': 2,
    'Question 3': 1
})

rawDescription: Search in a python list

description: Search in a python list


code:
figures=[manager.canvas.figure
         for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
for figure in figures:
    figure.gca().plot(x,y)

rawDescription: Matplotlib: Plotting the same graph in two different figures without writting the "plot(x,y)" line twice


code: from __future__ import division

rawDescription: How to change the data type from integer to float after applying a function in python

description: Change the data type from integer to float after applying a function in python


code:
@memoized
def packing(bins, objects):
    """
    Return a packing of `objects` into `bins`, or None if impossible.
    Both arguments are tuples of numbers, and the packing is
    returned in the form of a list giving the bin number for
    each object.

    >>> packing((4,5,6), (6,5,4))
    [2, 1, 0]
    >>> packing((4,5,6), (1,1,2,4,5))
    [0, 0, 0, 1, 2]
    """
    if not objects:
        return []
    o = objects[0]
    rest = objects[1:]
    for i, b in enumerate(bins):
        if o <= b:
            p = packing(bins[:i] + (b - o,) + bins[i+1:], rest)
            if p is not None:
                return [i] + p
    return None

rawDescription: "Ticket to Ride" board game logic for gray routes


code: pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

rawDescription: Scale an image in GTK

description: Scale an image in GTK


code:
A = Property.objects.get(id = 1)
A.get_city()

rawDescription: django model for city and places

description: Django model for city and places


code:
import matplotlib.pyplot as plt
import numpy as np
def setup_backend(backend='TkAgg'):
    import sys
    del sys.modules['matplotlib.backends']
    del sys.modules['matplotlib.pyplot']
    import matplotlib as mpl
    mpl.use(backend)  # do this before importing pyplot
    import matplotlib.pyplot as plt
    return plt

def animate():
    # http://www.scipy.org/Cookbook/Matplotlib/Animations
    mu, sigma = 100, 15
    N = 4
    x = mu + sigma * np.random.randn(N)
    rects = plt.bar(range(N), x, align='center')
    for i in range(50):
        x = mu + sigma * np.random.randn(N)
        for rect, h in zip(rects, x):
            rect.set_height(h)
        fig.canvas.draw()

plt = setup_backend()
fig = plt.figure()
win = fig.canvas.manager.window
win.after(10, animate)
plt.show()

rawDescription: Dynamically updating a bar plot in matplotlib


code:
key, *values = input().split()
map[key] = values

rawDescription: Python - get subset from 2nd, to last element


code:
def dict_factory(cursor, row):
    d = {}
    for idx,col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

rawDescription: Sqlite and Python -- return a dictionary using fetchone()?


rawDescription: How do I serialize IntEnum from enum34 to json in python?

description: Serialize IntEnum from enum34 to json in python


code:
import shutil
import sys
import tempfile

from contextlib import contextmanager

@contextmanager
def tempdir():
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        try:
            shutil.rmtree(path)
        except IOError:
            sys.stderr.write('Failed to clean up temp dir {}'.format(path))

rawDescription: How to remove file when program exits?

description: Remove file when program exits


code:
l = [0,1,2,3]
list(combinations(l, 2))

rawDescription: All pairs of pairs python

description: All pairs of pairs python


code:
from collections import Counter
sum((Counter(set(x)) for x in docDict.itervalues()), Counter())

rawDescription: How to count the documents which contain a specific word?

description: Count the documents which contain a specific word


code: super(School, self).build(*args)

rawDescription: Multiple Inheritance with same Base Classes in Python


code:
from sqlalchemy import create_engine
eng = create_engine("mssql+pyodbc://", creator=my_odbc_connection_function)

rawDescription: In SQLAlchemy, can I create an Engine from an existing ODBC connection?


code: df = df.loc[mask]

rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates


rawDescription: Python working with objects

description: Python working with objects


code: l2 = [ number*10 for number in l1 ]

rawDescription: Python- How to generate new list from variable in a loop?


rawDescription: Pandas - bucketing events close to each other


code:
import pysnmp
pysnmp.__version__

rawDescription: How to see the pysnmp version in Linux terminal without using pip

description: See the pysnmp version in Linux terminal without using pip


code:
with open("test.txt") as f:
    registros = [ast.literal_eval(x) for x in f if x.startswith('[')]

rawDescription: How to read just lists in a text file in Python?

description: Read just lists in a text file in Python


code:
import os, shutil

directorya = "exampledir"
directoryb = "exampledir2"
files = [file for file in os.listdir(directorya) if os.path.isfile(os.path.join(directorya, file))]
for file in files:
    if not os.path.exists(os.path.join(directoryb, file)):
        shutil.copy(os.path.join(directorya, file), directoryb)

rawDescription: Python - Copying only new files into another directory