code:
def compile(self):
    command = self.compiler_command
    self.console = sp.call(command, env=my_env)

def include(self):
    module = __import__(self.module_name)
    return module

def set_setup(self):
    dependencies = ""
    for elem in self.dep:
        dependencies = dependencies + ",'"+elem+".c'"
    filename = "setup.py"
    target = open (filename, 'w')
    line1 = "from distutils.core import setup, Extension"
    line2 = "\n"
    line3 = "module1 = Extension('"
    line4 = self.module_name
    line5 = "', sources = ['"+self.file+"'"+dependencies+"])\n"
    line6 = "setup (name = 'PackageName',"
    line7 = "version = '1.0',"
    line8 = "description = 'This is the code generated package.',"
    line9 = "ext_modules = [module1])"
    target.write(line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9)
    target.close()

rawDescription: Compiling C++ code using Python interpreter running under windows shell


rawDescription: Is it possible to break Python Tornado's urls into multiple files?


code: [x for x in list2 if x >= 0]

rawDescription: Difference between normal looping of list and using slice?


code:
d={}
for elem in xmlTree.iter():
  # skipping root element
  if elem.tag == xmlTree.getroot().tag:
    continue
  # this is supposed to be my temporary list
  for child in elem:
      d.setdefault(elem.tag,[]).append(child.tag)
print(tableWColumns)

rawDescription: Generating dictionary of lists in a loop (3.2.3)


code: return all(x % num == 0 for num in nums)

rawDescription: Trying to check a condition for every element in a list of integers


code:
with open('C:/Users/User/OneDrive/Documents/Date.csv') as file1, \
     open('C:/Users/User/OneDrive/Documents/Price.csv') as file2, \
     open('C:/Users/User/OneDrive/Documents/Output.csv', 'w') as output:
    reader1 = csv.DictReader(file1)
    reader2 = csv.DictReader(file2)
    writer = csv.DictWriter(output, ['ID', 'Date', 'Price'])
    writer.writeheader()  # Optional if you want the header

    for row1, row2 in zip(reader1, reader2):
        row1.update(row2)
        writer.writerow(row1)

rawDescription: Adding another column to a CSV file w/ python


code:
def arg(*args, **kwargs):
    def _decorator(func):
        def _wrapper(*args1, **kwargs1):
            # check for funcs args
            for k,v in kwargs.items():
                print("For key - ",k,v == kwargs1.get(k))
            func(*args1, **kwargs1)
        return _wrapper
    return _decorator
@arg(l = 1)
def b(l):
    print("In B", l)
b(l=1)
b(l=2)

rawDescription: Create a decorator that has access to both the arguments and function


code:
def onUpdate(self, event):
    team = self.TeamList.GetValue()
    if team == "Tigers":
        self.EmpList.append(some_list)

rawDescription: Adding items to wxpython combobox...?

description: Adding items to wxpython combobox...


code:
while 10 < a < 20:
    whatever

rawDescription: Is there a greater than but less than function in python?


rawDescription: Python string.strip stripping too many characters


rawDescription: How to decrement a list index in a loop

description: Decrement a list index in a loop


code:
class Doctor(Model):
   name = CharField(...)

   @property
   def masked_name(self):
       return self.name[3:]

   # To access to property you just use doctor.masked_name on an instance of the Doctor class (it's a property, you don't have to call doctor.masked_name())

rawDescription: Remove first 3 characters from a field in the database


rawDescription: Form an unordered list with regex

description: Form an unordered list with regex


code:
def check(s):
    if len(s) != 19:
        return False
    spl = s.split()
    if len(spl) != 4 or not all(len(x) == 4 for x in spl):
        return False
    a = s.replace(" ","")
    try:
         a = list(map(int,a))
    except ValueError:
        return False
    return sum(a) % 10 == 0

rawDescription: Python efficiency query

description: Python efficiency query


code:
class Dog:
  # ...
  def __del__(self):
    print('*** deleting {} ***'.format(self.name))

rawDescription: Is it possible to reference a class instance without using the variable it's stored in?


rawDescription: How can I duplicate this simple matlab plot functionality with mathplotlib?

description: Duplicate this simple matlab plot functionality with mathplotlib


code: df.Babys += 1

rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code:
import string
import itertools

def tokenize(s):
    tokens = []
    for k,v in itertools.groupby(s, lambda c: c in string.punctuation):
        tokens.extend("".join(v).split())
    return tokens

rawDescription: Python Not Removing Char From String

description: Python Not Removing Char From String


code:
reader = csv.DictReader(f, dialect='excel')

for current_row, next_row in pairwise(reader):
    if current_row[column] == next_row[column]:
        dosomething()

rawDescription: Python 3: Checking next value of an iterator without iterating


code:
sandb = stars_and_bars(star_count=3, bar_count=2)
for result in sandb:
    print(''.join(result))

rawDescription: How can i create a permutation with a limit on specific characters efficently?

description: Create a permutation with a limit on specific characters efficently


code:
import copy
new_list = copy.copy(old_list)

rawDescription: How to clone or copy a list in Python?

description: Clone or copy a list in Python


code:
def LengthDir(length, angle):
  radian_angle = angle * math.pi / 180
  return (length * math.cos(radian_angle), length * math.sin(radian_angle))

rawDescription: python - 2 math questions

description: Python - 2 math questions


code:
from fractions import Fraction

def can_be_represented(num, den):
    f = Fraction(num, den)
    return Fraction.from_float(float(f)) == f

rawDescription: How to determine if a decimal fraction can be represented exactly as Python float?

description: Determine if a decimal fraction can be represented exactly as Python float


code:
cols = map(lambda i: colour[i], nums)
cols

rawDescription: How to generate a list of 50 random colours in python?

description: Generate a list of 50 random colours in python


code: cmd = 'md5sum "' + path + '"'

rawDescription: Check md5sum of all files in a directory in python


code:
def gather_dict(view, name):
    """gather dictionaries from a DirectView"""
    merged = {}
    for d in view.pull(name):
        merged.update(d)
    return merged

gather_dict(dv, 'test')

rawDescription: Parallelize function on dictionary in IPython


code: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')

rawDescription: Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape


code: ['note', 'to', 'from', 'heading', 'body']

rawDescription: List of distinct XML element names using BeautifulSoup


code:
from itertools import chain, izip_longest,ifilter
obj = object()
from collections import OrderedDict

print([list(ifilter(lambda x: x is not obj, OrderedDict.fromkeys(chain.from_iterable(tup))))
       for tup in (tup for tup in izip_longest(l1,l2,fillvalue=[obj]))])

rawDescription: Combining 2 lists in strange way

description: Combining 2 lists in strange way


code: values.sort(key=lambda x: int(x[0]))

rawDescription: how to add and sort multidimentional array in python?

description: Add and sort multidimentional array in python


code:
u = dense_reduced
w = np.hstack((np.arange(u.shape[0]).reshape(-1,1),u))
np.savetxt('dense.txt', w, fmt=["%i #"]+ ["%.10s, "]*(u.shape[1]-1)+["%.10s"])

rawDescription: Write data to file

description: Write data to file


code:
colourstepblue = 255.0/(cols*rows)
colours = [x*colourstepblue for x in range(cols*rows)]

rawDescription: I need some help drawing coloured squares in a certain order with pygame for python 3.2


rawDescription: take a subset of a pandas data frame based on the column names

description: Take a subset of a pandas data frame based on the column names


code:
class A(object):
    def __init__(self, number):
        self.number = number

rawDescription: Fastest and pythonic way of deletion of objects in this code


code:
#! /usr/bin/python3.2

import argparse

if __name__ == '__main__':
    p = argparse.ArgumentParser (description = 'What your program does.')
    p.add_argument ('dir', metavar = 'dir', type = str, help = 'The directory')
    p.add_argument ('old', metavar = 'old', type = str, help = 'The old value')
    p.add_argument ('new', metavar = 'new', type = str, help = 'The new value')
    args = p.parse_args ()

rawDescription: Python 3: test command line arguments

description: Python 3: test command line arguments


code:
fstr = 'def f(%s): pass'%(', '.join(['arg%d'%i for i in range(5000)]))
exec(fstr)
f

rawDescription: What is a maximum number of arguments in a Python function?


code: dftask['TimeWindowDuration'] = (dftask['LatestEnd'] - dftask['EarliestStart']).dt.seconds

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


code:
for field in fields:
    field.clear()

rawDescription: PySide: how to clean `QLineEdit` field with a button click?


code:
from datetime import datetime, date
from io import StringIO
from algebraixlib.io.csv import import_csv
from algebraixlib.mathobjects import Set, Couplet
import algebraixlib.algebras.sets as sets
import algebraixlib.algebras.clans as clans

# Sample CSV as a string
mycsvfile = """col1,col2
1,date(01-01-2015)
2,date(01-01-2018)
3,date(04-01-2015)"""

rawDescription: Comparing date object in a Couplet between two dates


code:
from bs4 import BeautifulSoup
broken = '''\
<table>
    <tr> <th> header1 </th> <th> header2 </th> </tr>
    <th> missing1 </th> <th> missing2 </th>
    <tr> <td> data1 </td> <td> data2 </td> </tr>
</table>
'''
BeautifulSoup(broken, 'html.parser').select('table tr')
BeautifulSoup(broken, 'lxml').select('table tr')
BeautifulSoup(broken, 'html5lib').select('table tr')

rawDescription: Table with missing <tr> around a row: can I parse it?


code:
import os
import time

def main():
    for i in range(100):
        pid = os.fork()
        if pid:
            #print 'created new process %d' % pid
            continue
        else:
            time.sleep(1)
            return

if __name__ == '__main__':
    main()

rawDescription: Python threading vs. multiprocessing in Linux


rawDescription: Find words in a file then grab the x,y coordinates next to the text


code:
class MyForm(forms.Form):
    foo = forms.CharField(max_length=100)

rawDescription: Storing dynamic form in a model

description: Storing dynamic form in a model


code:
def f():
    print(foo)

foo = 23
f()

rawDescription: Use a Variable in a Function Without Passing as an Argument


code:
sender = context.socket(zmq.PUB)
sender.setsockopt(zmq.LINGER, 100)

rawDescription: issue when implementing a non-blocking publishing mechanism with zeromq

description: Issue when implementing a non-blocking publishing mechanism with zeromq


code: a = global_dict["foo"]

rawDescription: Using a global dictionary with threads in Python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

import cherrypy
from cherrypy.lib import static

path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  },
  '/font' : {
    'tools.corsstaticdir.on'  : True,
    'tools.corsstaticdir.dir' : os.path.join(path, 'font'),
    # This is a workaround for CherryPy flaw  where they set ``section``
    # tool config variable in ``cherrypy._cpdispatch.Dispatcher.set_conf``
    # exclusivety for ``staticdir`` tool (http://goo.gl/EGIIvA).
    'tools.corsstaticdir.section' : '/font',
  }
}

def corsstaticdir(section, dir, root = '', match = '', content_types = None, index = '', debug = False):
  cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
  return static.staticdir(section, dir, root, match, content_types, index, debug)

cherrypy.tools.corsstaticdir = cherrypy._cptools.HandlerTool(corsstaticdir)

class App:

  @cherrypy.expose
  def index(self):
    return static.serve_file(os.path.join(path, 'index.html'))

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: Cherrypy handling "no 'Access-Control-Allow-Origin' header is present" error


code:
def show_table(table):
    new_string = ''

    widths = [max([len(col) for col in cols]) for cols in zip(*table)]

    for i in table:
        for j in range(len(i)):
            new_string += '| {:{}} '.format(i[j], widths[j])
        new_string += '|\n'

    return new_string

rawDescription: Use string format create a 2D list

description: Use string format create a 2D list


code:
somefile.jpg
somefile_rotated.jpg

rawDescription: Rotating images using PHP and jQuery the fast way


code:
from dateutil.parser import parse
dt = parse("2013-12-02 22:00:00" + "GMT+0800")
dt.isoformat()

rawDescription: Get tz offset from sting

description: Get tz offset from sting


rawDescription: how can I get href links from html code

description: Get href links from html code


code:
urlpatterns = [
    url(r'^foo/search/', views.foo, name='foo'),
]

rawDescription: Pass <input> value to Django view

description: Pass <input> value to Django view


rawDescription: Can I combine custom django-admin commands?

description: Combine custom django-admin commands


code:
if __name__=="__main__":
   import doctest; doctest.testmod()

rawDescription: Why can I not paste the output of Pythons REPL without manual-editing?


code:
import re

def returnmatches(text,headers,footers):
    """headers is a list of headers
footers is a list of footers
text is the text to search"""
    for header,footer in zip(headers,footers):
        pattern = r"{}\w+?{}".format(header,footer)
        try:
            yield re.search(pattern,input_text).group()
        except AttributeError:
            # handle no match
            pass

rawDescription: How to cut out matched string

description: Cut out matched string


code: url = "http://{servername}:8080/api/{environment}/{component}.get?query=(name LIKE '%{componentname}%')".format(servername, environment, component, componentname)

rawDescription: python - replace values in url

description: Python - replace values in url


code: s.replace(" ", "")

rawDescription: How to strip all whitespace from string

description: Strip all whitespace from string


code:
diff = end_time - start_time
diff

rawDescription: Why does timedelta function return 0 seconds when datetimes are perfect number of days apart?


code:
from kivy.app import App
from kivy.uix.label import Label

from kivy.lang import Builder

Builder.load_string('''
<MyLabel>:
    text: 'Hello World'
''')

class MyLabel(Label): pass
class AwesomeApp(App):
    def build(self):
        return MyLabel()

if __name__ == "__main__":
    AwesomeApp().run()

rawDescription: Python not finding kv file

description: Python not finding kv file


code:
output = open(outfile, 'wb')
subprocess.Popen(args, stdout=output, stderr=output)

rawDescription: Running Java Application using Popen

description: Running Java Application using Popen


code: from django import forms

rawDescription: How to paginate a filtered queryset in listview

description: Paginate a filtered queryset in listview


code:
df = pd.DataFrame(data=np.random.random((433,80)) + np.arange(433)[:, np.newaxis],
                  columns=['col-%d' % x for x in range(80)])

rawDescription: Pandas: how to concisely detrend subset of columns


code:
x = linspace(0,9,10)+.5
y = linspace(0,9,10)+.5   # your array
x,y=meshgrid(x,y)
x=x.flatten()
y=y.flatten()

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

line, = ax.plot(x, y, 'b',picker=10)
line.set_visible(False)
ax.pcolormesh(np.random.randn(10,10))

def onpick(event):

    if event.artist!=line:  #check that you clicked on the object you wanted
        return True
    if not len(event.ind):  #check the index is valid
        return True
    ind = event.ind[0]

    ax.plot(x[ind],y[ind],'ro')

    fig.canvas.draw()
    return True

fig.canvas.mpl_connect('pick_event', onpick)
fig.show()

rawDescription: Can matplotlib pick_event return array indeces rather than values or pixels?


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


code:
def simple():
    a = int(input("What's one of the angles?"))
    b = int(input("What's the other angle in the triangle?"))
    c = (a + b)
    d = 180
    f = int(180 - c)
    print(f)

rawDescription: A simple looping command In Python

description: A simple looping command In Python


rawDescription: How do I take an integer from a list intending to use it?

description: Take an integer from a list intending to use it


code: dict((k, mydict[k]) for k in keys_to_select)

rawDescription: Selecting dictionary items by key efficiently in Python


code:
a = np.arange(1, 7).reshape((3,2))
a
[tuple(row) for row in a]

rawDescription: What is the easiest way to make tuples of the rows in an array?


code: map(lambda nested: nested[1], my_list)

rawDescription: Iterate over a list of tuples

description: Iterate over a list of tuples


code:
built_database = env.Command(target, sources,
                             Action('mySqlite3', 'Generating $TARGET with sqlite3'))

rawDescription: How to specify a COMSTR for the Command Builder in 'scons'

description: Specify a COMSTR for the Command Builder in 'scons'


code:
Output
{
    "Kathmandu": {
        "Casualties": {
            "Dead Female": "600",
            "Dead Male": "621",
            "Total No. of Houses": "436344",
            "Total Population": "1744240"
        },
        "geoInfo": {
            "Dev Region": "Central",
            "Zone": "Bagmati",
            "geography": "Hill"
        }
    },
    "Sindhupalchok": {
        "Casualties": {
            "Dead Female": "1943",
            "Dead Male": "1497",
            "Total No. of Houses": "66688",
            "Total Population": "287798"
        },
        "geoInfo": {
            "Dev Region": "Central",
            "Zone": "Bagmati",
            "geography": "Mountain"
        }
    }
}

rawDescription: Convert CSV to restructured JSON in Python


code:
import copy
c = copy.copy(x)
id(c)
id(x)

rawDescription: Is copy.copy different from assignment in python


code: db.session.query(Post, Users).join(Users).filter(Post.area == id, Users.id == Post.user_id).all()

rawDescription: How to serialize SqlAlchemy join query to JSON?

description: Serialize SqlAlchemy join query to JSON


code:
for component in sorted(data):
    print(component)
    print('-----')
    for key in sorted(data[component]):
        print(key, data[component][key])

rawDescription: How to associate elements in a set with multiple dict entries

description: Associate elements in a set with multiple dict entries


rawDescription: mapping to the max a variable number of lists

description: Mapping to the max a variable number of lists


code:
def get_tree(base_page, dest_dict):
    dest_dict = { 'title': base_page.title, 'content': base_page.content }
    children = base_page.children
    if children:
        dest_dict['children'] = {}
        for child in children:
            get_tree(child, dest_dict)
    else:
        return

rawDescription: Creating a tree from self referential tables in SQLalchemy


code:
sp_sample = sp_sample[0]
for d in sp_sample:
    d['v'] *= 100

rawDescription: How to modify a Python JSON objects array

description: Modify a Python JSON objects array


code: ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

rawDescription: Random string generation with upper case letters and digits in Python


code:
import Queue

qM = Queue.Queue()
qP = Queue.Queue()

with open('txt') as line:
    for source in line:
        result = source.strip().split(";")
        qM.put(result[0])
        qP.put(result[1])
        print(result[0])
        print(result[1])
        print('----')

rawDescription: After splitting add newline

description: After splitting add newline


code:
while True:
    x = x + 1
    y = x ** 2
    total = total + y
    if total >= n:
        break
print(total)

rawDescription: How to calculate the value of the sum of squares defined as 1^2 + 2^2 + 3^2 + ... +n2 until a user specified sum has been reached

description: Calculate the value of the sum of squares defined as 1^2 + 2^2 + 3^2 + ... +n2 until a user specified sum has been reached


rawDescription: Merge list of dict into one dict in python


code:
import random
def three_random_squared_average():
    while(True):
        a, b, c = random.random(), random.random(), random.random()
        z = square_of_average(a, b, c)
        if(z > 0.5625):
            break
    return z

rawDescription: Random function with break command in Python


rawDescription: Check to ensure a string does not contain multiple values


code: field.widget = field.hidden_widget

rawDescription: How do you dynamically hide form fields in Django?

description: Dynamically hide form fields in Django


code:
print(regex.search(r'(?b)I_AM_(?:ERE){e<=3}', bigString).group(0))
# I_AM_THE

rawDescription: How to find a substring using partial matching

description: Find a substring using partial matching


code:
repeated = np.repeat(positions, counts, 0)
rdistances_r = distance.pdist(repeated)

hr, br = np.histogram(rdistances, bins=bins)

In [83]: h
Out[83]: array([11, 22, 27, 43, 67, 46, 40,  0, 19,  0])

In [84]: hr
Out[84]: array([36, 22, 27, 43, 67, 46, 40,  0, 19,  0])

rawDescription: Multiply number of distances in distance matrix prior to histogram binning


code:
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager
from scipy import stats

from sklearn import svm
from sklearn.covariance import EllipticEnvelope

# Example settings
n_samples = 200
outliers_fraction = 0.25
clusters_separation = [0, 1, 2]

# define two outlier detection tools to be compared
classifiers = {
    "One-Class SVM": svm.OneClassSVM(nu=0.95 * outliers_fraction + 0.05,
                                     kernel="rbf", gamma=0.1),
    "robust covariance estimator": EllipticEnvelope(contamination=.1)}

# Compare given classifiers under given settings
xx, yy = np.meshgrid(np.linspace(-7, 7, 500), np.linspace(-7, 7, 500))
n_inliers = int((1. - outliers_fraction) * n_samples)
n_outliers = int(outliers_fraction * n_samples)
ground_truth = np.ones(n_samples, dtype=int)
ground_truth[-n_outliers:] = 0

# Fit the problem with varying cluster separation
for i, offset in enumerate(clusters_separation):
    np.random.seed(42)
    # Data generation
    X1 = 0.3 * np.random.randn(0.5 * n_inliers, 2) - offset
    X2 = 0.3 * np.random.randn(0.5 * n_inliers, 2) + offset
    X = np.r_[X1, X2]
    # Add outliers
    X = np.r_[X, np.random.uniform(low=-6, high=6, size=(n_outliers, 2))]

    # Fit the model with the One-Class SVM
    plt.figure(figsize=(10, 5))
    for i, (clf_name, clf) in enumerate(classifiers.items()):
        # fit the data and tag outliers
        clf.fit(X)
        y_pred = clf.decision_function(X).ravel()
        threshold = stats.scoreatpercentile(y_pred,
                                            100 * outliers_fraction)
        y_pred = y_pred > threshold
        n_errors = (y_pred != ground_truth).sum()
        # plot the levels lines and the points
        Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        subplot = plt.subplot(1, 2, i + 1)
        subplot.set_title("Outlier detection")
        subplot.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7),
                         cmap=plt.cm.Blues_r)
        a = subplot.contour(xx, yy, Z, levels=[threshold],
                            linewidths=2, colors='red')
        subplot.contourf(xx, yy, Z, levels=[threshold, Z.max()],
                         colors='orange')
        b = subplot.scatter(X[:-n_outliers, 0], X[:-n_outliers, 1], c='white')
        c = subplot.scatter(X[-n_outliers:, 0], X[-n_outliers:, 1], c='black')
        subplot.axis('tight')
        subplot.legend(
            [a.collections[0], b, c],
            ['learned decision function', 'true inliers', 'true outliers'],
            prop=matplotlib.font_manager.FontProperties(size=11))
        subplot.set_xlabel("%d. %s (errors: %d)" % (i + 1, clf_name,n_errors))
        subplot.set_xlim((-7, 7))
        subplot.set_ylim((-7, 7))
    plt.subplots_adjust(0.04, 0.1, 0.96, 0.94, 0.1, 0.26)

plt.show()

rawDescription: Remove Outliers from dataset

description: Remove Outliers from dataset


code:
x,y = zip(*s)
plt.scatter(x,y)

rawDescription: Make scatter plot from set of points in tuples


code:
import random

final_question_list = []
for learning_obj, question_list in learning_dict.items():
  random_question = random.choice(question_list)
  final_question_list.append(random_question)

rawDescription: Randomly Generating Exam Questions. Numbers based on Number + Letter associated with Questions


code: a = Phrase("content", [u"first",u"document"])

rawDescription: whoosh exact match for a phrase

description: Whoosh exact match for a phrase


code:
websites = [Website(parser_one, urls[0], 23),
            Website(parser_two, urls[1], 42),
            # ...
           ]

rawDescription: Most appropriate way to combine features of a class to another?


code:
def choose_best1(dict_list):
    df = pandas.DataFrame.from_records(dict_list)
    return df.sort(['bits', 'date']).irow(-1).to_dict()

def choose_best2(dict_list):
    srted = sorted(dict_list, key=lambda k: (k['bits'], k['date']))
    return srted[-1]

rawDescription: Max value in Dictionary of List of Dictionaries in Python


code:
import matplotlib.font_manager as font_manager
print(sorted(font_manager.findSystemFonts()))

rawDescription: Unicode character render

description: Unicode character render


code:
@app.route('/analysis/<filename>')
def analysis(filename):
    x = pd.DataFrame(np.random.randn(20, 5))
    return render_template("analysis.html", name=filename, data=x.to_html())
                                                                # ^^^^^^^^^

rawDescription: Pandas Dataframe display on a webpage

description: Pandas Dataframe display on a webpage


code:
i, j = numpy.meshgrid(range(ncols), range(nrows))
result = f(data, i, j)

rawDescription: Get Index of 2D array in Python

description: Get Index of 2D array in Python


rawDescription: Python 2.7 - Adding unicode strings to list


code:
for line in infile:
    data = [x if x.isalpha() else float(x) for x in line.split()]

rawDescription: Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?


code:
np.random.seed(1)
a = np.random.choice(list("AABC"), size=(3,9))
a

rawDescription: Check for invariant columns in a numpy array


code:
def find_rec(node, element):
    for item in node.findall('saybye'):
        yield item
        for child in find_rec(item, element):
            yield child

list(find_rec(ET.parse("h.xml"), 'saybye'))

rawDescription: ElementTree - findall to recursively select all child elements


code:
locale.setlocale(locale.LC_NUMERIC, 'English')
print(locale.format('%.2f', 32757121.33, True))
locale.setlocale(locale.LC_NUMERIC, 'German')
print(locale.format('%.2f', 32757121.33, True))

rawDescription: How can I print a float with thousands separators?

description: Print a float with thousands separators


code:
import fileinput
import sys
for line in fileinput.input("test.txt",inplace=True):
    # replaces all occurrences of apples in each line with oranges
    sys.stdout.write(line.replace("apples","oranges"))

rawDescription: Overwritting characters from a file in Python


code:
def myquery(self, table):
  self.query(table).filter_by(specified_field = 'some_value')

session.__class__.some_arbitrarily_filtered_query = myquery

rawDescription: Persistent where clause SQLAlchemy

description: Persistent where clause SQLAlchemy


code:
import tkinter as tk

root = tk.Tk()
btn = tk.Button(root,
                bg='#000000',
                fg='#b7f731',
                relief='flat',
                text='hello button',
                width=20)
btn.pack()

root.mainloop()

rawDescription: How to change the color of ttk button

description: Change the color of ttk button


code:
p = argparse.ArgumentParser()
sp = p.add_subparsers(dest='cmdstr')
sp1 = sp.add_parser('cmd1')
sp1.set_defaults(cmd=lambda:'cmd1')
sp2 = sp.add_parser('cmd2')
sp2.set_defaults(cmd=lambda:'cmd2')

p.parse_args(['cmd1']).cmd()
# Out[25]: 'cmd1'

rawDescription: Call function based on argparse

description: Call function based on argparse


code:
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
   return ''.join(random.choice(chars) for _ in range(size))
id_generator()
id_generator(3, "6793YUIO")

rawDescription: Random string generation with upper case letters and digits in Python


code:
MONGO_DBS = {
    'default': {
        'alias': 'default',         # the alias that Documents refer to
        'name': 'default',          # the name of the database to connect to
        'host': 'localhost',        # the host
        'port': 27017,              # the port
        'username': '',             # not implemented
        'password': '',             # not implemented
        'enabled': False,           # whether or not we connect to this database
    },
}

rawDescription: latest django and mongo engine, do you need to edit settings.py to install it?

description: Latest django and mongo engine, do you need to edit settings.py to install it


code:
class C(P):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.c = c

rawDescription: Passing arguments to superclass constructor without repeating them in childclass constructor


code:
import timeit
def long_to_coefs2(long_repr, window, n):
    win_length = long_repr.bit_length() // window
    if win_length < 256:
        return long_to_coefs(long_repr, window, n)
    else:
        half_len = win_length // 2
        least = long_repr & (((2**window) ** half_len) - 1)
        up = long_repr >> (window * half_len)
        return long_to_coefs2(least, window, n) + long_to_coefs2(up, window, n)

long_repr = coefs_to_long([1,2,3,1024,512, 0, 3] * 456, 13)
# original function
timeit.timeit('long_to_coefs(long_repr, 13, 1025)', 'from __main__ import long_to_coefs, long_repr', number=1000)/1000
timeit.timeit('long_to_coefs2(long_repr, 13, 1025)', 'from __main__ import long_to_coefs2, long_repr', number=1000)/1000
0.005114212036132813 / _
long_repr = coefs_to_long([1,2**33,3**17,1024,512, 0, 3] * 456, 40)
timeit.timeit('long_to_coefs(long_repr, 13, 1025)', 'from __main__ import long_to_coefs, long_repr', number=1000)/1000
timeit.timeit('long_to_coefs2(long_repr, 13, 1025)', 'from __main__ import long_to_coefs2, long_repr', number=1000)/1000
0.04037192392349243 / _

rawDescription: Optimize conversion between list of integer coefficients and its long integer representation


rawDescription: How to find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)

description: Find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)


code: my_dict2 = {y:x for x,y in my_dict.iteritems()}

rawDescription: switching keys and values in a dictionary in python

description: Switching keys and values in a dictionary in python


code:
def rearrange_dict(dict_1, root):
    dict_2 = {root: []}
    for x in dict_1[root]:
        if x in dict_1:
            for z in dict_1[x]:
                dict_2[root].append(x + "." + z)
        else:
          dict_2[root].append(x)
    return dict_2

dict_1 ={'a' : ['Va', 'Vb','Vc'] , 'Vb' : ['Vx','Vy','Vz'] , 'Vc':['Vp','Vq','Vr']}
root = 'a'
print(rearrange_dict(dict_1, root))

rawDescription: How to rearrange the elements contained in lists in a dictionary

description: Rearrange the elements contained in lists in a dictionary


code:
class QuestionsAnswered(db.Model):
    answered = db.ListProperty(db.Key)

rawDescription: Filtering a query by an entity's child in app engine (python)


code:
#!/usr/bin/env python
import os, pexpect

class zz:
    def __init__(self):
        child = pexpect.spawn ('/home/usr/Desktop/b.sh')
        # grab the first screen from 'less'
        child.read(1)
        child.send('q')

z = zz()

rawDescription: Quit Less with Pexpect

description: Quit Less with Pexpect


code: os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')

rawDescription: Renaming file on server with python

description: Renaming file on server with python


code:
def modifyValues(l):
    for i,x in enumerate(l):   # Use enumerate here.
        if x == 1:
            l[i] = 'a'
        elif x == 2:
            l[i] = 'b'
        elif x == 3:
            l[i] = 'c'
    print (l)

rawDescription: Changing values in list: Python

description: Changing values in list: Python


code:
dict(chain.from_iterable(((k1, v1), (k2, v2)) for k1, v1, k2, v2 in data))
dict(chain.from_iterable(((k1, v), (k2, v)) for k1, k2, v, _ in data))

rawDescription: Python: dict comprehension with multiple key-value pairs in the same time


rawDescription: Sorting lists in dictionary

description: Sorting lists in dictionary


code:
sun = Sun()
sun.compute('2011/05/04')
Ecliptic(sun).lon

rawDescription: How to calculate longitude using PyEphem

description: Calculate longitude using PyEphem


code:
output = open("yourfile.txt", "w")
files = []
for filename in filenames:
    files.append(open(filename, "r"))
num_files = len(files)
num_empty = 0
while True:
    num_empty = 0
    line = []
    for file in files:
        item = file.readline() # returns empty string after EOF
        if not item:
            item = "None" # or other marker value
            num_empty += 1
        line.append(item)
    if num_empty == num_files:
        break
    output.write("\t".join([x.strip() for x in line]))
    output.write("\n")
for file in files:
    file.close()
output.close()

rawDescription: Merge tab-delimited files horizontally with files of different row lengths


code:
lst = ["aq", "bs", "ce"]
if any(s in "aqwerqwerqwer" for s in lst):
    print(True)
if any(s in "qweqweqwe" for s in lst):
    print(True)

rawDescription: Check if a string contains at least one of the strings in a list


rawDescription: Log-sum-exp trick on a sparse matrix in scipy


code:
from django.db.models import Count
active_users = users.annotate(num_events=Count('event')).order_by('-num_events')

rawDescription: Most efficient Django query to return results spanning multiple tables


code:
def mycmp(a,b):
    return cmp(time.mktime(time.strptime(a.split('\t')[-2],'%d/%m/%y %H:%M:%S')),
               time.mktime(time.strptime(b.split('\t')[-2],'%d/%m/%y %H:%M:%S')))

output = [ line.rstrip() for line in output] # not list(output) , to avoid the problem of newline of the last line of each file
output.sort(mycmp)

for line in output:
    fm.write(line+'\n')

rawDescription: How to merge only the unique lines from file_a to file_b?

description: Merge only the unique lines from file_a to file_b


code:
parser.add_argument('pos',nargs='+')
args = ...
args.pos # a list, possibly empty
foo(*args.pos, **vars(args))

rawDescription: Unpacking arguments from argparse

description: Unpacking arguments from argparse


code:
from myapp import app, manager, attach_extensions

@manager.command
def debug():
    app.config.from_pyfile("debug.cfg")
    attach_extensions(app)
    app.run()

rawDescription: Flask extensions & its configuration

description: Flask extensions & its configuration


rawDescription: Python 2 lists of positive integers finding prime number


code:
from __future__ import print_function

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

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

#Test
userCards = ['AC', 'KD', '4C', '4S', '7H']
show_hand(userCards)

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

description: Print user friendly poker hand in python


code:
def split_words(mystring):
    current = []
    for c in mystring:
        if c in string.ascii_letters:
            current.append(c)
        else:
            if current:
                yield ''.join(current)
max(split_words(mystring), key=len)

rawDescription: Python: Find the longest word in a string


rawDescription: How to get most informative features for scikit-learn classifier for different class?

description: Get most informative features for scikit-learn classifier for different class


code:
import binascii
binascii.hexlify(b'\x7d\xfe\x7d\xfe')
binascii.hexlify(b'}\xfe}\xfe')

rawDescription: Python wav format parsing: Non-standard data frame output


code:
fill_cols = ['C1', 'C2', 'C3', 'C4']
df['C1'] = df[fill_cols].bfill(axis='columns')['C1']

rawDescription: Pandas - replacing NaN values using values from other columns


code:
#Your imports
from flask import Flask, render_template
from bokeh.embed import components
from bokeh.plotting import figure

@app.route('/')
def homepage():
    title = 'home'
    from bokeh.plotting import figure

    #First Plot
    p = figure(plot_width=400, plot_height=400, responsive = True)
    p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)

    #Second Plot
    p2 = figure(plot_width=400, plot_height=400,responsive = True)
    p2.square([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="olive", alpha=0.5)

    script, div = components(p)
    script2, div2 = components(p)

    return render_template('index.html', title = title, script = script,
    div = div, script2 = script2, div2 = div2)

rawDescription: Embedding multiple bokeh HTML plots into flask


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

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


code:
import numpy
# 1 dimension array of 1M random var's uniformly distributed between 1 and 2
numpyarray = numpy.random.rand(1e6) + 1
# pass to poisson
poissonarray = numpy.random.poisson(lam=numpyarray)
poissonarray

rawDescription: Python/Numpy/Scipy: Draw Poisson random values with different lambda


code:
class MainFrame(tk.Frame):
    def __init__(self,parent):
        tk.Frame.__init__(self,parent)
        self.x=my_label(self)
        self.up=my_update(self, self.x) # <-- pass another child to constructor
        self.grid()

rawDescription: tkinter : how to call a method of a child from another child

description: Tkinter : how to call a method of a child from another child


code:
import operator

class op(object):

    def __init__(self, op, arg):
        self.op = op
        self.value = self._get_val(arg)

    def _get_val(self, arg):
        try:
            return arg.value
        except AttributeError:
            return arg

    def __repr__(self):
        return str(self.value)

    def __call__(self, arg):
        self.value = self.op(self.value,
                             self._get_val(arg))
        return self

    def __getitem__(self, key):
        self.value = self.op(self.value,
                             -1 * self._get_val(key))
        return self

class mul(op):

    def __init__(self, arg):
        super(mul, self).__init__(operator.mul, arg)

rawDescription: is it possible to add some new syntax in javascript?

description: Is it possible to add some new syntax in javascript


code:
#!/usr/bin/env python
# -*- coding: latin-1 -*-

import sys
import imp
import shutil

sh_filename, runner_filename, tar_archive, dst_filename = sys.argv[1:]

runner = imp.load_module("tarfile_runner",
                        open(runner_filename, 'U'),
                        runner_filename,
                        ('.py', 'U', imp.PY_SOURCE))

sh_lines = open(sh_filename, 'r').readlines()
runner_lines = open(runner_filename, 'r').readlines()

sh_block = ''.join(sh_lines)
runner_block = ''.join(runner_lines)

if runner.SENTINEL in runner_block or runner.SENTINEL in sh_block:
    raise ValueError("Can't have the sentinel inside the runner module")
if not runner_block.endswith('\n') or not sh_block.endswith('\n'):
    raise ValueError("Trailing newline required in both headers")

to_pos = len(sh_lines) + len(runner_lines)
from_pos = len(sh_lines) + 1

sh_block = sh_block.replace("@@TO@@", str(to_pos))
sh_block = sh_block.replace("@@FROM@@", str(from_pos))

dst = open(dst_filename, 'wb')

dst.write(sh_block)
dst.write(runner_block)
dst.write(runner.SENTINEL)

shutil.copyfileobj(open(tar_archive, 'rb'), dst)

dst.flush()
dst.close()

rawDescription: Packing Python files into a single .py script


code: X[idx1[idx2] == np.arange(len(X))]

rawDescription: Interleave two numpy arrays based on element distances (python)


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


code:
a = np.random.random((10,))
b = a.copy()
b.sort()
d = np.diff(b)
result = b[d>TOL]

rawDescription: Find unique elements of floating point array in numpy (with comparison using a delta value)


code:
x = str()
x.upper()

rawDescription: Types and functions with same name in Python 3.X?


code:
TextArea = Text()
ScrollBar = Scrollbar(root)
ScrollBar.config(command=TextArea.yview)
TextArea.config(yscrollcommand=ScrollBar.set)
ScrollBar.pack(side=RIGHT, fill=Y)
TextArea.pack(expand=YES, fill=BOTH)

rawDescription: Multiple line text entry box in python

description: Multiple line text entry box in python


code: decode ('elloXHWEY orldXwWEY isXthWEY isWAY eatXgrWEY')

rawDescription: Convert piglatin to english?

description: Convert piglatin to english


code:
def uneven_chunker(iterable, chunk_list):
    group_maker = iter(iterable)
    for chunk_size in chunk_list:
        yield itertools.islice(group_maker, chunk_size)

rawDescription: Uneven chunking in python

description: Uneven chunking in python


rawDescription: Assigning values to two dimensional array from two one dimensional ones


code:
import string
import random
from itertools import islice, cycle
def randstr():
    return ''.join(islice(cycle(string.ascii_lowercase),
                          random.randint(1, 50))).title()
randstr()
randstr()
randstr()

rawDescription: Generate in flight string from [A-z]

description: Generate in flight string from [A-z]


code:
{'fruit': [{'color': 'red', 'name': 'apple'},
           {'color': 'orange', 'name': 'orange', 'size': 'medium'},
           {'color': 'red', 'name': 'strawberry', 'size': 'small'}]}

rawDescription: Python: Add JSON into Existing JSON

description: Python: Add JSON into Existing JSON


code: combined_sounds = sum(pydubobjects, AudioSegment.empty())

rawDescription: Concating a list of objects in Python for Pydub module


code: bytearray(array.array(b'L', [256]))

rawDescription: When creating a Python bytearray from NumPy array, where does the extra data come from?


code:
for project in Projects:
    project[2:4] = {
        'CT': lambda: [project[0]+project[1], '222'],
        'MA': lambda: ['123', None],
        'ME': lambda: ['12323', '333'],
        'RI': lambda: ['asdf', '3333']
    }[project[1]]()

rawDescription: Most efficient way to recode these multiple if statements


code:
INFILE = 'C:/Users/kdalton/Documents/Minicomm.txt'
list(get_time_deltas(INFILE))

rawDescription: How do I create a list of timedeltas in python?

description: Create a list of timedeltas in python


code: allowed_domains = ["bbc.com"]

rawDescription: scrapy rules generating single link

description: Scrapy rules generating single link


code:
def injectArguments(inFunction):
    """
    This function allows to reduce code for initialization
    of parameters of a method through the @-notation
    You need to call this function before the method in this way:
    @injectArguments
    """
    def outFunction(*args, **kwargs):
        _self = args[0]
        _self.__dict__.update(kwargs)
        # Get all of argument's names of the inFunction
        _total_names = \
            inFunction.func_code.co_varnames[1:inFunction.func_code.co_argcount]
        # Get all of the values
        _values = args[1:]
        # Get only the names that don't belong to kwargs
        _names = [n for n in _total_names if not kwargs.has_key(n)]

        # Match names with values and update __dict__
        d={}
        for n, v in zip(_names,_values):
            d[n] = v
        _self.__dict__.update(d)
        inFunction(*args,**kwargs)

    return outFunction

rawDescription: python: __init__ template

description: Python: __init__ template


rawDescription: how to flatten a 2D list to 1D without using numpy?

description: Flatten a 2D list to 1D without using numpy


code:
while threading.active_count() > 0:
    # ... look for new requests to handle ...
    time.sleep(0.1)

    # or try joining your threads with a timeout
    #for thread in my_threads:
    #    thread.join(0.1)

rawDescription: Parent Thread exiting before Child Threads [python]


code:
itertools.starmap(operator.add,
                  itertools.izip_longest(self, other, fillvalue=0))

rawDescription: Is there any way that I can turn this into a list comprehension


code:
vocabulary = joblib.load('vocabulary.pkl')
vect= CountVectorizer(ngram_range=(1,3), binary =True, stop_words = 'english', vocabulary = vocabulary)

rawDescription: Using sklearn logistic regression on new text when CountVectorizer has been used - need same number of sparse matrix features


code:
import subprocess

class Base:
    call = staticmethod(subprocess.call)
    def __init__(self):
        self.call(["echo","bar"])

instance = Base()
print (instance.call(['echo','foo']))

rawDescription: Python 3 - function data member of class


rawDescription: Using URLS that accept slashes as part of the parameter in Django


code:
alttype = np.dtype([('f0', 'U12'), ('f1', 'U3'), ('f2', 'U2'), ('f3', '<f8'), ('f4', 'U9')])
all_data_u = np.genfromtxt(csv_file, dtype=alttype, delimiter=',')

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


code:
import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)
t0 = time.time()

while True:
    a = ser.read()
    if a == b'2' or a == b'1':
        t1 = time.time()
        try:
            print(1 / ((t1-t0)/60))
        except ZeroDivisionError:
            pass
        t0 = t1
    else:
        break

rawDescription: Calculating revolutions per minute in Python from an Arduino


code: edges = g.es.select(name="Route69")

rawDescription: Find all vertices with the same edge attribute


code:
ax.annotate('...Additional information...',  # Your string

            # The point that we'll place the text in relation to
            xy=(0.5, 0),
            # Interpret the x as axes coords, and the y as figure coords
            xycoords=('axes fraction', 'figure fraction'),

            # The distance from the point that the text will be at
            xytext=(0, 10),
            # Interpret `xytext` as an offset in points...
            textcoords='offset points',

            # Any other text parameters we'd like
            size=14, ha='center', va='bottom')

rawDescription: Python: displaying a line of text outside a matplotlib chart


code:
import os
import shutil
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        sys.stdout.buffer.write(b"Content-Type: image/png\n\n")
        shutil.copyfileobj(f, sys.stdout.buffer)

rawDescription: Output binary data from CGI in Python 3

description: Output binary data from CGI in Python 3


code: makeRanks(d)

rawDescription: How to create a function (Iteration/Recursion) to run over a dictionary of tuples in Python?

description: Create a function (Iteration/Recursion) to run over a dictionary of tuples in Python


code:
def yieldContext(l, func):
    l = [''] + l + ['']
    return [' '.join(l[i-1:i+2]).strip() for i, s in enumerate(l) if func(s)]

rawDescription: Joining the previous and next sentence using python


code:
from collections import Counter

vote_counter = Counter()

for can1, can2 in combinations(candidates, 2):
    count1, count2 = 0, 0

    for ballot in ballots:
        if ballot.index(can1) < ballot.index(can2):
            count1 += 1
        else:
            count2 += 1

    if count1 > count2:
        vote_counter[can1] += 1
    elif count1 < count2:
        vote_counter[can2] += 1
    else:
        vote_counter[can1] += 0.5
        vote_counter[can2] += 0.5

rawDescription: Pairwise Comparison: comparing sublists within one list


code:
def using_loop(X, Y):
    output = np.zeros(X.shape)
    for i in range(X.shape[0]):
        output[i][Y[i]] = X[i]
    return output

def using_indexing(X, Y):
    output = np.zeros(X.shape)
    I = np.arange(X.shape[0])[:, np.newaxis]
    output[I, Y] = X
    return output

X2 = np.tile(X, (100,1))
Y2 = np.tile(Y, (100,1))

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

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


code: mapping = {'encode_b64': base64.encodestring, 'encode_url': urllib.quote_plus, 'encode_hex': lambda s: s.encode('hex')}

rawDescription: Execute var python

description: Execute var python


code:
from functools import partial

def SomeMethod(sc):
    someValue = rand()
    V = sc.broadcast(someValue)
    A = sc.parallelize().map(partial(worker, V=V))

rawDescription: PySpark broadcast variables from local functions


code:
board = []

for x in range(5):
    board.append(["O"] * 5)

rawDescription: Сodecademy 18/19 Battleship

description: Сodecademy 18/19 Battleship


code:
parser = argparse.ArgumentParser(description="")
parser.add_argument('k', help='k index', type=int)
parser.add_argument('j', help='j', type=int, nargs='?')
for inputs in (['5'], ['5', '2']):
    args = parser.parse_args(inputs)
    if args.j is not None:
       print("got a j")
    else:
       print("No j")

rawDescription: How to know if optional argument was passed?

description: Know if optional argument was passed


code:
df_a = pd.DataFrame([[1], [2]], columns=['A'])
df_b = pd.DataFrame([[3], [4]], columns=['B'])
df_a.join(df_b)

rawDescription: pandas join DataFrame force suffix?

description: Pandas join DataFrame force suffix


code:
def list2dict(list_):
    set_ = set(list_)
    return {word:list_.index(word) for word in set_}

rawDescription: Speed issues when converting list to dictionary


rawDescription: Sorting variable number of columns/rows

description: Sorting variable number of columns/rows


rawDescription: Override namespace in Python

description: Override namespace in Python


code:
def get_page_list(url):
    return make_list(cleanup(get_text(get_page(url))))

things = get_page_list(url)
stuff = get_page_list(another_url)
spam = get_page_list(eggs)

rawDescription: cleaning up nested function calls

description: Cleaning up nested function calls


code: import tkinter as tk

rawDescription: Tkinter adding line number to text widget


code:
def roundup(x):
    return x if x % 100 == 0 else x + 100 - x % 100

rawDescription: Python round up integer to next hundred

description: Python round up integer to next hundred


code:
d
d2 = d.copy()
d2.sort(axis=0)
d2

rawDescription: Sort individual components of a list in python


code: save_file = open(os_path, 'wb')

rawDescription: Pylons Uploading Distorted Images on Windows


rawDescription: how to disable the window maximize icon using PyQt4?

description: Disable the window maximize icon using PyQt4


rawDescription: what is most concise way to transfer variables to python string.format?

description: What is most concise way to transfer variables to python string.format


code:
stored_values = {}
for line in sources:
    # find all the tokens and strip them at the same time
    tokens = [t.strip() for t in line.split("\t")]

    new_id, new_values = tokens[0], tokens[1:]

    # check if the id is already stored
    if new_id in stored_values.keys():
        # Evaluate the items in the two lists to see if they are equal
        values_are_equal = True
        for stored_val , new_val in zip(stored_values[new_id], new_values):
            if not stored_val == new_val:
                values_are_equal = False

        if values_are_equal:
            # Do whatever needs to be done if both duplicate id and values
            pass
        if not values_are_equal:
            print("ID '{}', has a duplicate entry with different values".format(new_id))
            print("Stored Entry:  " + str(stored_values[new_id]))
            print("Current Entry: " + str(new_values))
            # Do whatever else needs to be done if duplicate id but different values

    # Finally if this is a new id, then add just add it
    else:
        stored_values[new_id] = new_values

rawDescription: Best way to create a dictionary for a later comparison of the elements

description: Create a dictionary for a later comparison of the elements


code:
from azure.storage import TableService,Entity

import struct

ts=TableService(account_name='user',account_key='key')

tasks=ts.query_entities('Events', filter=None, select=None, top=10,next_partition_key=None, next_row_key=None)

task = tasks[0]

columns = [ column for column in dir(task) if not str.startwith(column, '__')]

rawDescription: How to get all columns in azure table using python?

description: Get all columns in azure table using python


code:
p= Product( "iPhone", "Apple", 350 )
p.save()
f= Feature( "mp3 capacity", "16Gb", p )
f.save()

rawDescription: Django - designing models with virtual fields?


rawDescription: Why I cannot pass my parameter python

description: Why I cannot pass my parameter python


rawDescription: Nested dict in python, searhing based on inner key get inner value and parent key


rawDescription: Splitting a CSV file by range of datetimes


code:
d = datetime.datetime(2015, 9, 17)
for i in range(33):
    d += datetime.timedelta(days=1)
    print("copy  dlr_2014_198_bk_todel from 'http://www/sms_sending18.179.67.198_{}_utf.csv.gz' CREDENTIALS delimiter '\t' emptyasnull escape gzip".format(datetime.datetime.strftime(d, '%Y_%m_%d')))

rawDescription: generate date range to be used in a loop

description: Generate date range to be used in a loop


code:
# second div's xpath: (//table/tr/td/div)[2]
second_div = driver.find_element_by_xpath("(//table/tr/td/div)[2]")

rawDescription: my xpath is not working

description: My xpath is not working


rawDescription: Cut a Substring of a String which was read by serial in Python


code:
import csv
with open('file') as f:
    reader = csv.reader(f)
    for line in reader:
        print(line)

rawDescription: Splitting string by comma in python

description: Splitting string by comma in python


code:
def filter_queryset(self, qs):
    # use request parameters to filter queryset

    # simple example:
    user_id = self.request.GET.get('id', None)
    if user_id:
        qs = qs.filter(id=user_id)
    return qs

rawDescription: Url arguments with Django ajax datatable?


code:
range(m)
[i % n for i in range(m)]
[keyword[i % n] for i in range(m)]

rawDescription: How can I get an alphabetic input to match another alphabetic input in length?

description: Get an alphabetic input to match another alphabetic input in length


code:
with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

rawDescription: What's perfect counterpart in Python for "while not eof"


code:
def check_wizard_create_payment_pick_buy_cart(wizard):
    """
    Check if the previous form has an address selected
    """
    cleaned_data = wizard.get_cleaned_data_for_step(FORM_ID_SAVED_BUSINESS_PAYMENT_PICK) or {}
    create_new_payment_ind = cleaned_data.get(FORM_FIELD_NAME) or ''
    if create_new_payment_ind != '':
        return True
    else:
        return False

rawDescription: Django form wizard dispatcher

description: Django form wizard dispatcher


code:
from itertools import groupby
from operator import itemgetter

longdat = [
    {"id":"cat", "name" : "best meower", "value": 10},
    {"id":"cat", "name" : "cleanest paws", "value": 8},
    {"id":"cat", "name" : "fanciest", "value": 9},
    {"id":"dog", "name" : "smelly", "value": 9},
    {"id":"dog", "name" : "dumb", "value": 9},
]

getid = itemgetter('id')
result = [
    dict([['id', key]] + [[d['name'], d['value']] for d in grp])
    for key, grp in groupby(sorted(longdat, key=getid), key=getid)
]
print(result)

rawDescription: iterative long-to-wide python one-liner (or two) using groupby

description: Iterative long-to-wide python one-liner (or two) using groupby


code:
import time
import pprint

pprint.pprint(sorted(x, key=func))

rawDescription: Python sort 2-D list by time string

description: Python sort 2-D list by time string


code: return monthdays[1]

rawDescription: Python Lambda if statements

description: Python Lambda if statements


rawDescription: How to make a selective RNG for a game in Python?

description: Make a selective RNG for a game in Python


code: p_values = np.einsum('ij,ij->i', values[v], w)

rawDescription: Interpolation with Delaunay Triangulation (n-dim)


code: line = line.strip(' \n' '\r')

rawDescription: Class and Array Problems

description: Class and Array Problems


code:
t1 = Test()
t1.table
t1.add_to_table(3)
t1.table

rawDescription: Appending objects to a list

description: Appending objects to a list


code:
with open("jobs_done.json") as inp:
    job_done_count = json.load(inp)['jobs_done']

rawDescription: implement a global configure in Python

description: Implement a global configure in Python


code:
findbetween('abc', 'abcabcabcabc')
findbetween(r'', 'abcdef')
findbetween(r'ab', 'abcabcabc')
findbetween(r'b', 'abcabcabc')
findbetween(r'(?<=(.))(?!\1)', 'aaaaaaaaaaaabbbbbbbbbbbbkkkkkkk')

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


code:
with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

rawDescription: Python 2.7 - Write and read a list from file


code:
first_dict_idx = 0
first_container_number = lcontainers311[first_idx]['ContainerNumber']

rawDescription: How to access multiple dictionaries in list with Python

description: Access multiple dictionaries in list with Python


code: data = [line.strip() for line in open(filename)]

rawDescription: Matching list items to items at the other end of the same list?


code:
meta_dict = {}
for meta_type in np.unique(a['meta']):
    meta_dict[meta_type] = a[a['meta']==meta_type]

rawDescription: Split numpy recarray based on value in one column


rawDescription: Sorting an array of arrays in Python

description: Sorting an array of arrays in Python


code: apple = Fruit("apple", 2)

rawDescription: Pythonic way of inheriting many classes?

description: Pythonic way of inheriting many classes


rawDescription: Dictionary with named values?

description: Dictionary with named values


rawDescription: Creating minimal LaTeX syntax from reStructuredText with docutils


code:
import os
import subprocess

pipe_rfd, pipe_wfd = os.pipe()

print(pipe_rfd, pipe_wfd)

p = subprocess.Popen(
    ["./test.sh", str(pipe_rfd)],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    close_fds=False,                           # make sure file descriptors are kept open in subprocess
    preexec_fn = lambda: os.close(pipe_wfd)    # make sure write end is closed in child
)

p.stdin.write(b'spam\n')
p.stdin.close()

os.write(pipe_wfd, b'eggs\n')
os.close(pipe_wfd)

print('out:', p.stdout.read())
print('err:', p.stderr.read())

rawDescription: How can I read/write from/to file descriptors in Python3's Popen?

description: Read/write from/to file descriptors in Python3's Popen


code:
import os

paths = [
    ("/test/file1.txt", "content1"),
    ("/test/file2.txt", "content2"),
    ("/file3.txt", "content3"),
    ("/test1/test2/test3/file5.txt", "content5"),
    ("/test2/file4.txt", "content4")
]

def deepupdate(original, update):
    for key, value in original.items():
        if key not in update:
            update[key] = value
        elif isinstance(value, dict):
            deepupdate(value, update[key])
    return update

def traverse(key, value):
    directory = os.path.dirname(key)
    filename = os.path.basename(key)
    if directory == "/":
        return value if isinstance(value, dict) else {filename: value}
    else:
        path, directory = os.path.split(directory)
        return traverse(path, {directory: {filename: value}})

result = {}
for key, value in paths:
    result = deepupdate(result, traverse(key, value))

print(result)

rawDescription: Map path list to files structure

description: Map path list to files structure


code:
if not request.user.is_authenticated():
    # LoginView.login_view will return a HttpResponse object
    return LoginView.login_view(request)
else:
    ...

rawDescription: Django: HttpResponseRedirect not working


code: cursor.execute("... WHERE name =('"+str(n[1])+"')")

rawDescription: Calculation using a sqlite db in python

description: Calculation using a sqlite db in python


rawDescription: Python: passing a function with parameters as parameter


rawDescription: How do I monitor the change of my gtalk status message?

description: Monitor the change of my gtalk status message


code:
import requests

session = requests.Session()
session.trust_env = False

response = session.get('http://www.stackoverflow.com')

rawDescription: requests: how to disable / bypass proxy

description: Requests: how to disable / bypass proxy


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

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

    def __contains__(self, key):
        return key in self.parent

    def __iter__(self):
        return iter(self.parent)

rawDescription: Subclassing datatypes that have views in Python2.7 and Python3


code:
from __future__ import division
import multiprocessing as mp
import time

def foo(x):
    time.sleep(0.1)
    return x

def log_result(retval):
    results.append(retval)
    if len(results) % (len(data)//10) == 0:
        print('{:.0%} done'.format(len(results)/len(data)))

if __name__ == '__main__':
    pool = mp.Pool()
    results = []
    data = range(200)
    for item in data:
        pool.apply_async(foo, args=[item], callback=log_result)
    pool.close()
    pool.join()
    print(results)

rawDescription: How to keep track of status with multiprocessing and pool.map?

description: Keep track of status with multiprocessing and pool.map


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


code: twofreq = len([i for i in range(len(dna)-1) if dna[i:i+2] == dinucleotide]) / float((len(dna) - 1))

rawDescription: Frequencies not adding up to one

description: Frequencies not adding up to one


rawDescription: Understanding nested lists in Python

description: Understanding nested lists in Python


code: earnings["USD"]

rawDescription: Most concise way to define multiple variables


code:
import sys
arr = ["a","b","c"] #random number of elements
for i in range(len(arr)):
    lam = lambda val=arr[i]: sys.stdout.write("%s\n"%val)
    but = Button(None,text="Press Here",command=lam).pack()

rawDescription: Create a random number of function

description: Create a random number of function


code:
class Obj:
    def __init__(self, name, freq):
        self.freq = freq
        self.name = name

    def __repr__(self):
        return self.name

obj1 = Obj('obj1',42)
obj2 = Obj('obj2',42)
obj3 = Obj('obj3',6)
obj4 = Obj('obj4',6)
obj5 = Obj('obj5',6)
obj6 = Obj('obj6',332)
obj7 = Obj('obj7',123)

x = [obj2, obj1, obj5, obj3, obj4]
y = {obj1:40, obj2:50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20}

print(sorted(x, key=lambda i: (i.freq, y.get(i, 0)), reverse=True))

rawDescription: Python: sort list based on value present in dictionary


code:
def getImei(N):
    part = ''.join(str(random.randrange(0,9)) for _ in range(N-1))
    res = luhn_residue('{}{}'.format(part, 0))
    return '{}{}'.format(part, -res%10)

rawDescription: Generate IMEI in python

description: Generate IMEI in python


code:
# get an array of indices that will sort the first column in ascending order
order = np.argsort(a[:, 0])

# index into the row dimension of a
a_sorted = a[order]

print(a_sorted)
# [[   1.4  112.2]
#  [   5.2    4.3]
#  [ 200.2    6.2]]

rawDescription: numpy.partition() with 2-D Array

description: Numpy.partition() with 2-D Array


code:
def timeout(seconds, function, *args, **kwargs):
    with multiprocessing.pool.ThreadPool(processes=1) as pool:
        result = pool.apply_async(function, args, kwargs)
        try:
            result.get(timeout=seconds)
        except multiprocessing.TimeoutError:
            print("Process timed out")
    print("Pool terminated")

rawDescription: multiprocessing threadpool not terminating as expected

description: Multiprocessing threadpool not terminating as expected


code:
from tornado.escape import json_encode
obj = {
    'foo': 'bar',
     '1': 2,
     'false': True
    }
self.write(json_encode(obj))

rawDescription: tornado write a Jsonp object

description: Tornado write a Jsonp object


code:
subparsers = parser.add_subparsers()
parser_1 = subparsers.add_parser(...)
parser_1.set_default(func=do_command_one)

parser_k = subparsers.add_parser(...)
parser_k.set_default(func=do_command_k)

args = parser.parse_args()
if args.func:
    args.func(args)

rawDescription: How to handle CLI subcommands with argparse

description: Handle CLI subcommands with argparse


code:
def recursively_empty(e):
   if e.text:
       return False
   return all((recursively_empty(c) for c in e.iterchildren()))

rawDescription: Python lxml - How to remove empty repeated tags


code:
for record in data:
    record['sum'] = sum(record[entry] for entry in
                        ['Cucumber','Carrot','Runner Bean'])
sorted_data = sorted(data, key=itemgetter('sum'), reverse=True)

rawDescription: Ordered dictionary Sum and Top 3 of the Ordered dictionary sum


rawDescription: Remove border around image in Pygame

description: Remove border around image in Pygame


code:
# setup.py
from distutils.core import setup, Extension
example_module = Extension('_test',
                           sources=['test_wrap.cxx'])
setup (name = 'test',
       ext_modules = [example_module],
       py_modules = ["test"])

rawDescription: Interacting SWIG modules with and without `-builtin`


code:
import numpy as np

def check(x):
    if isinstance(x,list):
        if len(x) == 2:
            if all(isinstance(ele, (int, float)) and np.isinf(ele) == False and np.isnan(ele) == False for ele in x):
                return True
    return False

rawDescription: Check if dictionary key is filled with list of 2 numbers


code:
def fortran_callback(future):
    print(future.run_type, future.jid)
    return "Fortran finished executing"

def fortran_execute():

    from concurrent.futures import ProcessPoolExecutor as Pool

    args = "sleep 2; echo complete"

    pool = Pool(max_workers=1)
    future = pool.submit(subprocess.call, args, shell=1)
    future.run_type = "run_type"
    future.jid = "jid"
    future.add_done_callback(fortran_callback)

    print("Fortran executed")

if __name__ == '__main__':
    import subprocess
    fortran_execute()

rawDescription: Python concurrent.futures using subprocess with a callback


code:
class UserMessage(db.Model):

    user = db.ReferenceProperty(User)
    message = db.ReferenceProperty(Message)

rawDescription: AppEngine data strategy to handle a large index per user?


code:
for k in family:
    if k != 'son':
        del family[k]

rawDescription: How to delete all other keys but keep 1 key in the dictionary

description: Delete all other keys but keep 1 key in the dictionary


code:
import numpy
from numba import vectorize, float64
@vectorize([float64(float64)])
def f(x):
    return 1 / (1 + numpy.exp(-x))

rawDescription: Opencv python: apply arbitrary function to each pixel without iterating


code: charset = CHAR_OPTIONS[args.c]

rawDescription: clarification with argparse in python 3.2 please

description: Clarification with argparse in python 3.2 please


rawDescription: Access to widget in GTK+

description: Access to widget in GTK+


code:
image
threshold

rawDescription: Thresholded pixel indices of a NumPy array


code:
sortx = np.argsort(X)
plt.plot(X[sortx], Y[sortx], marker='.')
plt.show()

rawDescription: Python maplotlib sine curve with random.randn


code: map(f, range(10))

rawDescription: Is there a simple process-based parallel map for python?


code:
#!/usr/bin/python3

class myReserve():
    def __init__(self, initName):
        self.myList = dict()
        self.myName = initName
        self.setList()

    def setList(self):
        if self.myName == "fruit":
            self.myList[0] = "Orange"
            self.myList[1] = "Lemon"
        elif self.myName == "vegetable":
            self.myList[0] = "Tomato"
            self.myList[1] = "Carrot"
        #If neither fruit nor vegetable
        #myList should be empty.

myStore = dict()
myStore[0] = myReserve("fruit")
myStore[1] = myReserve("vegetable")
myStore[2] = myReserve("spices")

print(myStore[0].myList)

rawDescription: Python3: How to create a dict of different objets of the same class?


code:
delay_channel.basic_publish(exchange='',
                      routing_key='hello_delay',
                      body="test",
                      properties=pika.BasicProperties(delivery_mode=2))

rawDescription: How to create a delayed queue in RabbitMQ?

description: Create a delayed queue in RabbitMQ


code:
for i in content:
   name,*scores=i.split()

rawDescription: String split in python

description: String split in python


code:
solution = problems.get(problem)
# if KeyError: solution is None

rawDescription: Python - Searching a dictionary for strings


code: set(['paper'])

rawDescription: common between all csv columns

description: Common between all csv columns


code:
df
g2 = df[df.c4 == 2]
g2
gb = g2.groupby(['c2', 'c3'])
sub = gb.apply(lambda x: x.val.iloc[0] - x.val.iloc[1])
sub
sub.unstack()

rawDescription: how to perform calculations across specific rows and columns of a crosstabulation in pandas?

description: Perform calculations across specific rows and columns of a crosstabulation in pandas


code: new_list_joined = ['~'.join(x) for x in new_list]

rawDescription: Sorting a list of strings by their components


code:
for i in lines:
    outfile.write(" ".join(i) + "\n")

rawDescription: Write to a file

description: Write to a file


code:
def keys_of_value(d, value):
    return [key for key, val in d.items() if val == value]

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

description: Get all item with specific value from dict


code:
s.rank(pct=True).max()
s.tail(7)
s[s != u'-'].rank(pct=True).max()

rawDescription: why aren't pandas "rank" percentiles bounded between 0 and 1?

description: Why aren't pandas "rank" percentiles bounded between 0 and 1


code:
class foo(object):
    def __init__(self):
        self.dates = []

    def _makeRangeDates(self,desde,ultima_carga):
        dates = []
        for fechaRequest in rrule(DAILY, dtstart=desde, until=ultima_carga):
            dates.append(fechaRequest)
        return self.dates

rawDescription: what is the correct way to return a value inside of a method? in python

description: What is the correct way to return a value inside of a method? in python


rawDescription: Unable to fully remove border of PyQt QGraphicsView


rawDescription: Python program that is given a line read from a text file and displays the one number found


code:
f = Foo()
x = f.big_calc_result
y = f.bic_calc_result  # Look mom, this happened really quick

rawDescription: Check whether class variable has been defined


code:
# Wait for at most 30 seconds for the thread to complete.
t.join(30)

# Always signal the event. Whether the thread has already finished or not,
# the result will be the same.
e.set()

# Now join without a timeout knowing that the thread is either already
# finished or will finish "soon."
t.join()

rawDescription: Most Pythonic way to kill a thread after some period of time


rawDescription: Toeplitz matrix using numpy/scipy

description: Toeplitz matrix using numpy/scipy


code:
import curses
curses.initscr()
curses.noecho()    # don't echo the keys on the screen
curses.cbreak()    # don't wait enter for input

window = curses.newwin(10, 10, 0, 0)  # create a 10x10 window
window.box()       # Draw the box outside the window
cur_x = 1
cur_y = 1
while True:
    window.addch(cur_y, cur_x, '@')
    window.refresh()
    inchar = window.getch()
    window.addch(cur_y, cur_x, ' ')
    # W,A,S,D used to move around the @
    if inchar == ord('w'):
        cur_y -= 1
    elif inchar == ord('a'):
        cur_x -= 1
    elif inchar == ord('d'):
        cur_x += 1
    elif inchar == ord('s'):
        cur_y += 1
    elif inchar == ord('q'):
        # stop the program when Q is entered.
        break
curses.endwin()

rawDescription: Ascii art that is continually replaced

description: Ascii art that is continually replaced


code:
class Wrapper(object):
    def __init__(self, value):
        object.__setattr__(self, 'value', value)

    def __setattr__(self, name, value):
        setattr(self.value, name, value)

rawDescription: Clean way to disable `__setattr__` until after initialization


rawDescription: Use numpy arrays to count similar tuples


rawDescription: Python some special products of a given list


rawDescription: question related to reverse function and kwargs

description: Question related to reverse function and kwargs


code:
def mod1(a,m,i):
    if m*i == a:
        return 0
    elif m*i < a:
        return mod1(a,m,i+1)
    else:
        return a-m*(i-1)

print(mod1(20,6,1))

rawDescription: Modulo operation recursive

description: Modulo operation recursive


code:
from collections import deque

def truncate(iterable, num):
    buffer = deque(maxlen=num)
    iterator = iter(iterable)

    # Initialize buffer
    for n in range(num):
        buffer.append(next(iterator))

    for item in iterator:
        yield buffer.popleft()
        buffer.append(item)

truncated_range20 = truncate(range(20), 5)

print(list(truncated_range20))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

rawDescription: Skip last 5 line in a file using python

description: Skip last 5 line in a file using python


code:
from selenium.webdriver.support.wait import WebDriverWait

td_list = WebDriverWait(driver, 10).until(lambda driver: driver.find_elements_by_css_selector("#my_table tr td"))
for td in td_list:
    if(td.text == "Adams grocery"):
        td.click()

rawDescription: Python Selenium click on a specific row in a table containing the right data in a column


code:
# ...
def my_method(self):
  return self.value

rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


code:
from functools import reduce  # Python 3 compatibility
result = reduce(lambda a, b: a.funca(b), alist)

rawDescription: Need a better way to make the function acts on adjacent elements of a list


code:
userInput = input()
for line in userInput.split(' '):
    fw.write(line)

rawDescription: Input in python on more than one line

description: Input in python on more than one line


code:
args = [], args2 = [a,b] # or ..
args = [a], args2 = [b]  # or ..
args = [a,b], args2 = []

rawDescription: Is there a way to use more than 1 variable length arguments (*args) in a Python function?


code:
print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']

rawDescription: Python openpyxl select sheet

description: Python openpyxl select sheet


code:
category = "C"
category2 = "C2"

namelist = [
  [['blah blah blah string blah blah blah blah blah blah', 'another string, blah blah blah, string string', 'string string string'],
   category
  ],
  [['string string another string, blah', 'more words, more words, etc', 'yet again, here we go'],
   category2
  ]
]

wordlist = "blah string words".split()

rawDescription: Trying to manipulate data, assign a list to the first item in a higher list, second item will be information about that list


code:
# filename: console_tunnels.py
import json
import argparse
from sshtunnel import SSHTunnelForwarder
from time import sleep

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('ipython_json',
                        type=str,
                        help='ipython kernel json file')
    parser.add_argument('--host',
                        type=str,
                        help='hostname',
                        default='awsinstance')
    parser.add_argument('-k',
                        '--private_key',
                        type=str,
                        help='private_key',
                        default='/home/reckoner/.ssh/id_rsa')
    parser.add_argument('-u',
                        '--username',
                        type=str,
                        help='username',
                        default='reckoner')
    args = parser.parse_args()
    ports_keys = ['stdin_port', 'control_port', 'hb_port', 'shell_port',
                  'iopub_port']
    d = json.load(open(args.ipython_json))
    addresses = [('127.0.0.1', d[i]) for i in ports_keys]

    with SSHTunnelForwarder(
        ssh_username=args.username,
        local_bind_addresses=addresses,
        remote_bind_addresses=addresses,
        ssh_private_key=args.private_key,
        ssh_address=args.host, ):
        while True:
            # press Ctrl-C for stopping
            sleep(0.5)

rawDescription: Connect to remote kernel on AWS using local qtconsole?


rawDescription: Getting Actual String from Python XML parsing


code:
n=3
div=10240
a=rand(n*div,1)
b=rand(1,n*div)
import pickle

def calculate(i,j):
    u=dot(a[i*div:(i+1)*div,:],b[:,j*div:(j+1)*div])
    return u

def save(i,j,u):
     with open('data'+str(i)+str(j)+'.pk','wb') as f :
                   pickle.dump(u,f)

def timecount(f,args):
   t0=time.time()
   res=f(*args)
   return res,time.time()-t0

def multidot():
  tcalc,tsave=0,0
  for i in range(n):
    for j in range(n):
        print (i,j)
        u,dt=timecount(calculate,(i,j))
        tcalc+=dt
        _,dt=timecount(save,(i,j,u))
        tsave+=dt
  print('dot time',tcalc)
  print('save time',tsave)

rawDescription: multiplying two huge matrices using numpy.dot

description: Multiplying two huge matrices using numpy.dot


rawDescription: How to write output of web scrape to column instead of rows in Beautiful Soup

description: Write output of web scrape to column instead of rows in Beautiful Soup


code:
p=argparse.ArgumentParser()
p.add_argument('-longargument')
p.parse_args(['-long','test'])
p.parse_args(['-l','test'])

rawDescription: Single dash for argparse long options

description: Single dash for argparse long options


rawDescription: How to access dir() Python attributes on a module object?

description: Access dir() Python attributes on a module object


code:
class Post(models.Model):
    name = models.CharField(max_length=20)

class Vote(models.Model):
    post = models.ForeignKey(Post)
    value = models.IntegerField()
    type = models.CharField(max_length=2, choices=(("AW", "Awesomeness"), ("US", "Usefulness")))

rawDescription: Order by dig-like rating in django

description: Order by dig-like rating in django


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

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


rawDescription: Change float to string without decimal places


code:
import itertools

i, j = 10, 20
with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in itertools.islice(spamreader, i, j+1):
        print (', '.join(row))

rawDescription: How to loop through specific range of rows with Python csv reader?

description: Loop through specific range of rows with Python csv reader


rawDescription: create timestemps for given data

description: Create timestemps for given data


code:
letter_dict = {}
alphaString = ['a', 'b', 'c', 'd', 'e']
for letter in alphaString:
    letter_dict[letter] = []

rowOfValues = ["alpha", "bravo", "charlie", "delta", "echo"]
#Length of rowOfValues supposed to be same length as alphaString
#There would be many rows being run through a bigger loop that includes this code, but I'll keep it to just this one row for simplicity

for i in range (0, len(alphaString)):
    if rowOfValues[i] not in letter_dict[alphaString[i]]: #Ex. if "alpha" not in list a
            letter_dict[alphaString[i]].append(rowOfValues[i]) #Ex.  a.append("alpha")

rawDescription: Python: creating a variable using retrieved string name


code:
class spam(object):
    eggs = None #// if you need this line at all though

x = spam()
x.eggs = []
x.eggs.add(...)

rawDescription: Pythonic way to "flatten" object hierarchy to nested dicts?


code: grid = [[0 for x in range(9)] for y in range(9)]

rawDescription: Sudoku Neural Network

description: Sudoku Neural Network


code:
def flatten_all(iterable):
    stack = [iter(iterable)]
    while stack:
        try:
            elem  = stack[-1].next()
            if not isinstance(elem, list):
                yield elem
            else:
                stack.append(iter(elem))
        except StopIteration:
            stack.pop()

rawDescription: Python: multilevel nested lists

description: Python: multilevel nested lists


rawDescription: Extracting Unique String Combinations from List of List in Python


rawDescription: How to preserve column names starting with a minus when using numpy.genfromtxt?

description: Preserve column names starting with a minus when using numpy.genfromtxt


code: w =  OptionMenu(c, var, *OPTIONS)

rawDescription: Populate Tkinter OptionMenu with list of unknown length, i.e. list of serial ports


code: foo="$(scriptthatprintssomething)"

rawDescription: How do I pass a Python Variable to Bash?

description: Pass a Python Variable to Bash


rawDescription: Defining python loggers for shared modules


rawDescription: Numpy - create matrix with rows of vector


code:
from contextlib import contextmanager

from sys import stdout
from io import StringIO
from functools import partial

class ConsoleWriter:

    def __init__(self, out=stdout, fmt=None):
        self._out = out
        self._fmt = fmt

    @property
    @contextmanager
    def batch(self):
        original_out = self._out
        self._out = StringIO()
        try:
            yield self
        except Exception as e:
            # There was a problem. Ignore batch commands.
            # (do not swallow the exception though)
            raise
        else:
            # no problem
            original_out.write(self._out.getvalue())
        finally:
            self._out = original_out

    @contextmanager
    def verbose(self, fmt="VERBOSE: {!r}"):
        original_fmt = self._fmt
        self._fmt = fmt
        try:
            yield self
        finally:
            # don't care about errors, just restore end
            self._fmt = original_fmt

    def __getattr__(self, attr):
        """creates function that writes capitalised attribute three times"""
        return partial(self.write, attr.upper()*3)

    def write(self, arg):
        if self._fmt:
            arg = self._fmt.format(arg)
        print(arg, file=self._out)

rawDescription: Python multiple context managers in one class


rawDescription: Using ctypes to write callbacks that pass-in pointer to pointer parameters to be used as output-parameter


_lang: fr

_type: bar

__text: Test

_type: foo

_type: baz

_name: bob

__text: test

_lang: bz

_name: frank

_lang: ar

_name: alive

rawDescription: xml to json with attributes for php or python

description: Xml to json with attributes for php or python


code:
def mgenfromtxt(fname,cache=True,**karg):
    if cache==False and isinstance(fname, basestring) and numpy.DataSource()._isurl(fname):
       ds=numpy.DataSource(None)
       fhd = iter(ds.open(fname,'rbUD'))
       l1=numpy.genfromtxt(fhd,**karg)
       fhd.close()
       del ds
       return l1
    else:
       return(numpy.genfromtxt(fname,**karg))

rawDescription: genfromtxt: how to disable caching

description: Genfromtxt: how to disable caching


code: exits = rooms['bedroom'].roomExits

rawDescription: Is there a way to find objects in a list without iterating through the list?


rawDescription: Regular Expression for a pattern of 45 hex numbers OR 48 hex numbers - Python


code:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randint(5, size=(5,4)), columns=list('ABCD'))
print(df)
#    A  B  C  D
# 0  4  0  3  3
# 1  3  1  3  2
# 2  4  0  0  4
# 3  2  1  0  1
# 4  1  0  1  4
dct = {func.__name__:df.apply(func) for func in (pd.Series.nunique, pd.Series.count)}
print(pd.concat(dct, axis=1))

rawDescription: Pandas Compute Unique Values per Column as Series


code:
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_fields = ['id', 'username', 'email', 'first_name', 'last_name']

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    filter_fields = ['user_id', 'location', 'title', 'website']

    def get_queryset(self):
        return super(UserProfileViewSet, self).get_queryset().filter(
            user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=user)

rawDescription: Django REST: create CRUD operations for OneToOne Field


rawDescription: Sorting with two digits in string - Python


code:
class DailyObj(models.Model):
    ...
    def total_crores(self):
        return self.Total_Rec / 10000000

rawDescription: Divide option in django model query

description: Divide option in django model query


rawDescription: python: convert to HTML special characters

description: Python: convert to HTML special characters


code:
lst = [[]] * 3
lst
# The ids of the items in `lst` are the same
id(lst[0])
id(lst[1])
id(lst[2])

rawDescription: Best and/or fastest way to create lists in python


code:
staticwin.clear()   #clean the window
staticwin.addstr(1, 1, "insert-text-here", curses.color_pair(RED_TEXT))
staticwin.box()     #re-draw the box
staticwin.refresh()

rawDescription: (python) How to create static text in curses


code:
players = {playerA, playerB}
active_player = {playerA}

active_player = players - active_player

rawDescription: Get the other element from pair

description: Get the other element from pair


code:
string = "I would like to install treehouses at my yard"
string.count("tall tree")
string.count(" tall tree ")
string = "The see a stall tree outside. A man is under the tall trees"
string.count(" tall tree ")
string = "I see a tall tree outside. A man is under the tall tree"
string.count(" tall tree ")

rawDescription: NLTK count frequency of sub phrase

description: NLTK count frequency of sub phrase


code: counts = pd.DataFrame(df['full_name'].value_counts(), columns=['num_unique'])

rawDescription: Pandas create column containing a row count


code:
boys = 'Jim','Jeff'
girls = 'Bonnie', 'Buffy'
out = []
for b in boys:
   for g in girls:
      out.append((b,g))
out
out = []
for b in boys:
   for g in girls:
       if b[-1] not in g:
           out.append((b,g))
out
b
g
out = []
for b in boys:
    if b[-1] not in g:
        for g in girls:
           out.append((b,g))
out

rawDescription: Positioning of conditional statement within a python list comprehension with multiple iterables


code:
arguments = vars(args)
arguments
foo(arguments['arg2'], arguments['arg1'])
foo(arguments['arg2'], arguments)
foo(arguments['arg2'], **arguments)
foo(*arguments, **arguments)
foo(*arguments.values(), **arguments)

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


code:
mask = ((1 << end) - 1)
result = (number & mask) >> start

rawDescription: Getting a specific group of binary numbers in an Int?


rawDescription: Django specific sql query

description: Django specific sql query


code: logger = logger or logging.getLogger('dummy') #without configuring dummy before.

rawDescription: Implementing an optional logger in code

description: Implementing an optional logger in code


rawDescription: List of all available matplotlib backends


code: max(files, key=filetimestamp)

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
from lxml import html
my_tree = html.fromstring(web_pg)
elements = [item for item in my_tree.iter()]

rawDescription: How to read text from a website in Python

description: Read text from a website in Python


rawDescription: Count number of distinct items in a list without using a hash table


rawDescription: How to improve selection performance with PySide.QtCore.QAbstractItemModel and QTreeView?

description: Improve selection performance with PySide.QtCore.QAbstractItemModel and QTreeView


code:
def getFile(request):
    fileContent = "Your name is %s" % request.GET['name']
    res = HttpResponse(fileContent)
    res['Content-Disposition'] = 'attachment; filename=yourname.txt'
    return res

rawDescription: generating a file with django to download with javascript/jQuery

description: Generating a file with django to download with javascript/jQuery


code:
from copy import deepcopy

log_data = {
    'esp': deepcopy(generic_dict),
    'por': deepcopy(generic_dict),
    'sui': deepcopy(generic_dict),
    'ben': deepcopy(generic_dict),
    'mex': deepcopy(generic_dict),
    'arg': deepcopy(generic_dict),
}

rawDescription: How can I properly copy nested dictionary objects?

description: Properly copy nested dictionary objects


code:
from pathlib import Path
class Dir:
    def __init__(self, path):
        self.path = Path(path)

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

description: Get the proper capitalization for a path


code: num_appearances = [df.item_id.apply(lambda s: k in s).sum() for k in unique_items]

rawDescription: how to calculate ratio on some condition in pandas dataframe

description: Calculate ratio on some condition in pandas dataframe


code: function(["please", 0, "work this time", 2.3])

rawDescription: Why would Python's variable length arguments be used over passing in a list/dictionary?


code:
df = df['quantity'].unstack('status')
df = df.reindex(columns=labels[::-1], index=df.index[::-1])
print(df)

rawDescription: Grouping data by value ranges

description: Grouping data by value ranges


code:
def input(a, b, c) :
    if a <= b <= c or c <= b <= a :
      return b
    elif b <= a <= c or c <= a <= b :
      return a
    else:
      return c

rawDescription: Middle value using python 3

description: Middle value using python 3


rawDescription: Get attribute of object from relationship in sqlalchemy


code:
a = np.arange(5)
b = a[::2]
a.flags['OWNDATA']
b.flags['OWNDATA']

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

description: Verify when a copy is made in Python


code:
g1 = df1.groupby(['cnpj','num_doc']).sum()
g2 = df2.groupby(['cnpj','num_doc']).sum()
joined = g1.join(g2).fillna(0)
joined
joined['diff'] = joined['bc_icms'] - joined['vlr_item']
joined

rawDescription: How can I get the difference between the conditional sum of values from 2 dataframes?

description: Get the difference between the conditional sum of values from 2 dataframes


code:
from http import cookiejar  # Python 2: import cookielib as cookiejar
class BlockAll(cookiejar.CookiePolicy):
    return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
    netscape = True
    rfc2965 = hide_cookie2 = False

rawDescription: How to disable cookie handling with the Python requests library?

description: Disable cookie handling with the Python requests library


code:
for x in range(60):
    Grid.columnconfigure(grid, x, weight=1)

for y in range(30):
    Grid.rowconfigure(grid, y, weight=1)

rawDescription: How to create a self resizing grid of buttons in tkinter?

description: Create a self resizing grid of buttons in tkinter


code: s.system("gs -q -dSAFER  -sDEVICE=png16m -r500 -dBATCH -dNOPAUSE  -dFirstPage=%d -dLastPage=%d -sOutputFile=/xx.png %s" %(i,i,self.id,i,pdfname))

rawDescription: How to convert the pdf files into png format using ghostscript in python

description: Convert the pdf files into png format using ghostscript in python


rawDescription: Aggregation on aggregated values

description: Aggregation on aggregated values


code:
import os
import subprocess

subprocess.call([os.environ.get('SHELL', '/bin/sh') +
    ' -i < /dev/tty > /dev/tty 2>&1'], shell=True)

rawDescription: How can I exec an interactive shell from Jython?

description: Exec an interactive shell from Jython


code:
if __name__ == '__main__':
    import multy
    multy.func(2)

rawDescription: Python multiprocessing: call module with multiprocessing from another script with passing variable


code: sql_string = ",".join("'%s'"%i for i in sys.argv[1].split(","))

rawDescription: Python, How to take a comma separated sys argv, and make it like '1','2' (for MySQL "IN" Query)


rawDescription: Python custom list prefilled with static elements


code:
a = [1,2,3]
b = a
b.append('hello')
b is a
b == a
b
a

rawDescription: How to get the name of lists for comparison purposes

description: Get the name of lists for comparison purposes


code:
import astropy
from astropy.cosmology import WMAP9 as cosmo
dir(astropy)

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

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


code:
#!/usr/bin/env python

import csv

data = [
    dict(lat=1, lon=1, val=10),
    dict(lat=1, lon=2, val=20),
    dict(lat=2, lon=1, val=30),
    dict(lat=2, lon=2, val=40),
    dict(lat=3, lon=1, val=50),
    dict(lat=3, lon=2, val=60),
]

# get a unique list of all longitudes
headers = list({d['lon'] for d in data})
headers.sort()

# make a dict of latitudes
data_as_dict = {}
for item in data:
    # default value: a list of empty strings
    lst = data_as_dict.setdefault(item['lat'], ['']*len(headers))
    # get the longitute for this item
    lon = item['lon']
    # where in the line should it be?
    idx = headers.index(lon)
    # save value in the list
    lst[idx]=item['val']

# in the actual file, we start with an extra header for the latitude
headers.insert(0,'latitude')

with open('latitude.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(headers)
    lats = data_as_dict.keys()
    lats.sort()
    for latitude in lats:
        # a line starts with the latitude, followed by list of values
        l = data_as_dict[latitude]
        l.insert(0, latitude)
        writer.writerow(l)

rawDescription: Structuring .csv in Python

description: Structuring .csv in Python


code:
def remove_employee(self, employee_id):
        self.employees = list(filter(lambda x: x.get_employee_id() != employee_id))

rawDescription: Search a list containing class objects and remove the class object that matches an instance variable of class object


code:
mn = min(nl, key=itemgetter(1))[1]
temp = []
best = float("inf")
for ele in nl:
    if mn < ele[1] < best:
        best = ele[1]
        temp = []
        out.append(ele)
    elif ele[1] == best:
        temp.append(ele)
print(temp)

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

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


code:
#!/usr/bin/python
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

class MyQProcess(QWidget):
  def __init__(self):
   super(QWidget, self).__init__()

   # Add the UI components (here we use a QTextEdit to display the stdout from the process)
   layout = QVBoxLayout()
   self.edit = QTextEdit()
   self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
   layout.addWidget(self.edit)
   self.setLayout(layout)

   # Add the process and start it
   self.process = QProcess()
   self.setupProcess()

   # Show the widget
   self.show()

  def setupProcess(self):
    # Set the channels
    self.process.setProcessChannelMode(QProcess.MergedChannels)
    # Connect the signal readyReadStandardOutput to the slot of the widget
    self.process.readyReadStandardOutput.connect(self.readStdOutput)
    # Run the process with a given command
    self.process.start("df -h")

  def __del__(self):
    # If QApplication is closed attempt to kill the process
    self.process.terminate()
    # Wait for Xms and then elevate the situation to terminate
    if not self.process.waitForFinished(10000):
      self.process.kill()

  @pyqtSlot()
  def readStdOutput(self):
    # Every time the process has something to output we attach it to the QTextEdit
    self.edit.append(QString(self.process.readAllStandardOutput()))

def main():
    app = QApplication(sys.argv)
    w   = MyQProcess()

    return app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Start QProcess from within QDialog that is used as a progress monitor


code:
for i in xrange(height/2):
    mid_pixel_top_half = img[i][width/2]
    R, G, B = mid_pixel_top_half[2], mid_pixel_top_half[1], mid_pixel_top_half[0]
    if (R<border_threshold_R) and (G<border_threshold_G) and (B<border_threshold_B):
        top_border_height+=1
    else:
        break

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


rawDescription: Best Pythonic way to conditionally append lists


rawDescription: Python: Find in list

description: Python: Find in list


rawDescription: Mapping a 'fake' object in SQLAlchemy

description: Mapping a 'fake' object in SQLAlchemy


code:
import csv
import numpy as np

# Pull in all the raw data.
with open('TEMPO3.2F-0215_s00116.dat', 'rb') as f:
    raw = np.fromfile(f, np.float64)

# Throw away the nan entries.
raw = raw[1::2]

# Check its a multiple of six so we can reshape it.
if raw.size % 6:
    raise ValueError("Data size not multiple of six.")

# Reshape and take the transpose to manipulate it into the
# same shape as your CSV. The conversion to integer is also
# so the CSV file is the same.
data = raw.reshape((6, raw.size/6)).T.astype('int')

# Dump it out to a CSV.
with open('test.csv', 'w') as f:
    w = csv.writer(f)
    w.writerows(data)

rawDescription: Equivalent of Matlab's fread() 'float64' in Python