rawDescription: zero padding numpy array

description: Zero padding numpy array


code:
mac = '1A2B3C4D5E6F'
hex_chunks = lambda s: [s[i: i+2] for i in range(0, len(s), 2)]
[m.decode('hex') for m in hex_chunks(mac)]

rawDescription: How to generate ODIN-1 in Python

description: Generate ODIN-1 in Python


code: getattr(df, keyword)

rawDescription: Passing an argument as a attribute in a function?


code:
rList = []
gList = []
bList = []

rawDescription: Why are my lists not being created properly in Python 2.7?


code:
s = select([1]).where(
         table1.c.col_a == table2.c.colb
       ).where(
         table1.c.colb == table2.c.colb
       ).limit(30)
s = exists(s)

rawDescription: SQLAlchemy Select with Exist limiting

description: SQLAlchemy Select with Exist limiting


rawDescription: get indices of original text from nltk word_tokenize

description: Get indices of original text from nltk word_tokenize


code:
def _get_logger(self):
    loglevel = logging.INFO
    l = logging.getLogger(__name__)
    if not getattr(l, 'handler_set', None):
        l.setLevel(logging.INFO)
        h = logging.StreamHandler()
        f = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        h.setFormatter(f)
        l.addHandler(h)
        l.setLevel(loglevel)
        l.handler_set = True
    return l

rawDescription: Python logging module is printing lines multiple times


code:
@app.route('/votes', methods=['POST'])
def votes():
    response = jsonify()
    response.status_code = 201
    response.headers['location'] = '/votes/1'
    response.autocorrect_location_header = False
    return response

rawDescription: How to return a relative URI Location header with Flask?

description: Return a relative URI Location header with Flask


code:
# Python Qt4 bindings for GUI objects
from PyQt4 import QtGui
# Numpy functions for image creation
import numpy as np
# Matplotlib Figure object
from matplotlib.figure import Figure
import matplotlib
matplotlib.use('Qt4Agg')
# import the Qt4Agg FigureCanvas object, that binds Figure to
# Qt4Agg backend. It also inherits from QWidget
from matplotlib.backends.backend_qt4agg \
import FigureCanvasQTAgg as FigureCanvas
# import the NavigationToolbar Qt4Agg widget
from matplotlib.backends.backend_qt4agg \
import NavigationToolbar2QTAgg as NavigationToolbar

class Qt4MplCanvas(FigureCanvas):

    def __init__(self, parent):
        # plot definition
        self.fig = Figure()
        self.axes = self.fig.add_subplot(111)
        t = np.arange(0.0, 3.0, 0.01)
        s = np.cos(2*np.pi*t)
        self.axes.plot(t, s)
        # initialization of the canvas
        FigureCanvas.__init__(self, self.fig)
        # set the parent widget
        self.setParent(parent)
        # we define the widget as expandable
        FigureCanvas.setSizePolicy(self,
        QtGui.QSizePolicy.Expanding,
        QtGui.QSizePolicy.Expanding)
        # notify the system of updated policy
        FigureCanvas.updateGeometry(self)

class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        # initialization of Qt MainWindow widget
        QtGui.QMainWindow.__init__(self)
        # set window title
        self.setWindowTitle("Matplotlib Figure in a Qt4 Window With NavigationToolbar")
        # instantiate a widget, it will be the main one
        self.main_widget = QtGui.QWidget(self)
        # create a vertical box layout widget
        vbl = QtGui.QVBoxLayout(self.main_widget)
        # instantiate our Matplotlib canvas widget
        qmc = Qt4MplCanvas(self.main_widget)
        # instantiate the navigation toolbar
        ntb = NavigationToolbar(qmc, self.main_widget)
        # pack these widget into the vertical box
        vbl.addWidget(qmc)
        vbl.addWidget(ntb)
        # set the focus on the main widget
        self.main_widget.setFocus()
        # set the central widget of MainWindow to main_widget
        self.setCentralWidget(self.main_widget)

#deleted the main function here

rawDescription: Get PyQt4 to open another Qt window when a button is pressed


rawDescription: Multiple text fields with id's in django


code:
COLORS = {
    'BLUE': bytearray(b'\x00\x00\xff'),
    'GREEN': bytearray(b'\x00\xff\x00'),
    'RED': bytearray(b'\xff\x00\x00')
}

rawDescription: How do I pass the argument correctly in Python

description: Pass the argument correctly in Python


code:
from setuptools import setup

setup(
  # ...
  data_files=[
    ('share/icons/hicolor/scalable/apps', ['data/mypackage.svg']),
    ('share/applications', ['data/mypackage.desktop'])
  ],
  entry_points={
    'console_scripts': ['startit=mypackage.cli:run']
  }
)

rawDescription: How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)?

description: Distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)


code: no_zero = [num for num in primes if '0' not in str(num)]

rawDescription: Project Euler #35: nicer way to test if an even integer is 'inside' an integer


code:
def myfunc(val=foobar):
    '''myfunc(val=foobar)

    Blah blah blah'''
    pass

rawDescription: Override function declaration in autodoc for sphinx


rawDescription: python string processing, strip out date-time patterns

description: Python string processing, strip out date-time patterns


code:
def f(x, y):
    if min(x, y) <= 0.3:
        return 1
    elif min(x, y) <= 0.6:
        return 2
    else:
        return 3

rawDescription: How to return value for different layers of (x,y) levels

description: Return value for different layers of (x,y) levels


code:
q = multiprocessing.Queue()
q.put(1)
q.put(2)
q.put(None)  # None is our sentinel, you could use 'Done', if you wanted
the_pool.map(thisworker, iter(q.get, None)) # This will call q.get() until None is returned

rawDescription: Iterable multiprocessing Queue not exiting


code:
class Foo():
    def __init__(self):
        self._spam = 0

    @property
    def spam(self):
        print("in the getter: ")
        return self._spam

    @spam.setter
    def spam(self, move):
        print("in the setter: ")
        self._spam = move + self._spam

f = Foo()
f.spam = 2
print(f.spam)

rawDescription: Python 2.7: How to build getter/setter functions to access class attributes without inheritance?


rawDescription: Subsetting stacked pandas dataframe

description: Subsetting stacked pandas dataframe


rawDescription: How can I recreate the following using list comprehensions?

description: Recreate the following using list comprehensions


rawDescription: .doc to pdf using python

description: .doc to pdf using python


code:
import bz2
data = 'QlpoOTFBWSZTWcl9Q1UAAABBBGAAQAAEACAAIZpoM00SrccXckU4UJDJfUNV'
with open('/tmp/testfile', 'w') as fdesc:
    fdesc.write(bz2.decompress(data.decode('base64')))

rawDescription: Embedding binary data in a script efficiently


code:
def make_upper(filename, new_filename):
    with open(filename) as infile:
        data = infile.read()
    with open(new_filename) as outfile:
        outfile.write(data.upper())

def main():
    user_in = input("What's the path to your file? ")
    path = user_in # just for clarity
    root, filename = os.path.split(user_in)
    head,tail = os.path.splitext(filename)
    new_filename = "UPPER{}{}".format(head,tail)
    new_path = os.path.join(root, new_filename)
    make_upper(path, new_path)

rawDescription: How do I change the name of a file path correctly in Python?

description: Change the name of a file path correctly in Python


code:
from collections import Counter
l1=[2,2,2,5,5,7]
Counter(l1).keys()
Counter(l1).values()
zip(Counter(l1).keys(), Counter(l1).values())
Counter(l1).items()

rawDescription: how to group elements in a list based on frequency into a tuple

description: Group elements in a list based on frequency into a tuple


code: list(itertools.chain.from_iterable(elem.split(', ') for elem in li))

rawDescription: Python List of Strings created from a list of one string


code:
social = request.user.social_auth.get(provider='MyOAuth')
backend = social.get_backend_instance()

rawDescription: How to get backend instance from python-social-auth

description: Get backend instance from python-social-auth


code:
p = re.compile(pattern)
bool(p.search("data_pt01_pr"))
bool(p.search("data_pt02_2"))
bool(p.search("data_pt01_01_pr"))
bool(p.search("data_pt22_22"))

rawDescription: How to match all words that does not contain two digits in a row?

description: Match all words that does not contain two digits in a row


code:
a = np.array([1, 2, 3])
b = a[0:2]
c = a.copy()
np.may_share_memory(a, b)
np.may_share_memory(a, c)
np.may_share_memory(b, c)

rawDescription: Definition and difference between a shared array view and a copy of array data?


code:
import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()

Application().start()

rawDescription: Can't figure out how to bind the enter key to a function in tkinter


code:
if __name__ == '__main__':
    opts = docopt(__doc__)
    opts['--comment'] == ['ASDF', 'QWERTY']
    opts['FILE'] == 'my_file'

rawDescription: How to specify one optional argument several times in docopt

description: Specify one optional argument several times in docopt


code:
with open("offsetfile.txt") as wordfile:
    wordgen = words(wordfile)
    for word in wordgen:
        if word in searchterms:   # searchterms should be a set() to make this fast
            break
    else:
        word = None               # makes sure word is None if the word wasn't found

    foundwords = [word, next(wordgen, None), next(wordgen, None)]

rawDescription: Read the next word in a file in python

description: Read the next word in a file in python


code: struct.unpack('f'*n, file.read(4*n))

rawDescription: Reading 32 bit signed ieee 754 floating points from a binary file with python?


code:
from pymongo import Connection
c = Connection("morton.local:27017", slave_okay=True)
d.command( "replSetInitiate", c );

rawDescription: python define replica set configuration

description: Python define replica set configuration


code:
from distutils.core import setup, Extension

lolan = Extension('lolan', sources = ['lolanmodule.c'])

setup (name = 'Example',
        version = '1.0',
        description = 'Just an exapmle',
        ext_modules = [lolan])

rawDescription: Using Python list in a C extension

description: Using Python list in a C extension


code:
from string import Formatter
yourstring = "My name is {myname}"
[fn for _, fn, _, _ in Formatter().parse(yourstring) if fn is not None]

rawDescription: How to get the variable names from the string for the format() method

description: Get the variable names from the string for the format() method


code:
df
pattern = 'a'
N = 2
idx = df[df.txt.str.contains(pattern)].index
filtered_idx = sorted(list(set([x for tup in zip(idx-N, idx+N) for x in range(tup[0], tup[1]+1)])))
df.loc[filtered_idx]

rawDescription: Equivalent of grep -C in Pandas

description: Equivalent of grep -C in Pandas


code:
int2meth = {1: "current_balance", 2: "deposit_funds",
            3: "withdraw_funds", 4: "__repr__"}

rawDescription: Python - Understanding __repr__

description: Python - Understanding __repr__


code:
# forms.py

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        widgets = {
            'user': forms.HiddenInput() # initial data MUST be used to assign this
        }

rawDescription: Improving Python/django view code

description: Improving Python/django view code


code:
from itertools import product

def foo(nums):
    return list(product(*((x, -x) for x in nums)))

rawDescription: python positive and negative number list possiblities

description: Python positive and negative number list possiblities


code:
import os
os.startfile(filename)

rawDescription: Open a text file window using Python

description: Open a text file window using Python


code:
@register_gw_method
def my_function():
    print('hi...')

@register_gw_method('say_hi')
def my_function():
    print('hi...')

rawDescription: Python - making decorators with optional arguments


code:
h_indices, w_indices = np.indices(shape=(h,w))
out_img = foo(img, h_indices, w_indices)

rawDescription: loop variable aware numpy's slicing and vectorized calculations

description: Loop variable aware numpy's slicing and vectorized calculations


code: x = lsqcurvefit(fun,x0,xdata,ydata);

rawDescription: Reducing difference between two graphs by optimizing more than one variable in MATLAB/Python?


code: currency, amount, _, multiplier =  re.match(r'(\D+)(\d+(\.\d+)?)([mMkK])', '$1.5k').groups()

rawDescription: Extract the number and following letter from regex


rawDescription: How to determine type from type aliasing?

description: Determine type from type aliasing


code: my_answer = item1['Title'][0].strip()

rawDescription: Extra characters Extracted with XPath and Python (html)


code:
from sklearn.feature_extraction import DictVectorizer
documents = [{"the":1, "boy":1, "ran":1}, {"the":1, "dog":1, "ran":1}]
X = vectorizer.fit_transform(documents)
X.toarray()
vectorizer.inverse_transform(X[0])

rawDescription: Counting with scipy.sparse

description: Counting with scipy.sparse


code:
def merger_try(a, b):
    if not a or not b:
        yield chain(a, b)
    iter_a, iter_b = iter(a), iter(b)
    prev_a, prev_b = next(iter_a), next(iter_b)
    while True:
        if prev_a >= prev_b:
            yield prev_b
            try:
                prev_b = next(iter_b)
            except StopIteration:
                yield prev_a
                break
        else:
            yield prev_a
            try:
                prev_a = next(iter_a)
            except StopIteration:
                yield prev_b
                break
    for ele in chain(iter_b, iter_a):
        yield ele

rawDescription: Better way for concatenating two sorted list of integers


code:
df = pd.DataFrame.from_records(df[1].tolist(), index=df[0],
                          columns=list('ABC')).reset_index()
df['C'] = pd.to_datetime(df['C'])
df

rawDescription: Reading csv containing a list in Pandas

description: Reading csv containing a list in Pandas


code:
dt = datetime.datetime.now()
#Now get rid of seconds and microseconds component:
dt = dt.replace(second=0, microsecond=0)

rawDescription: Can I easily get datetime with less resolution in Python?

description: Easily get datetime with less resolution in Python


code:
def get_buttons_hbox(assistant):
    # temporarily add a widget to the action area and get its parent
    label = gtk.Label('')
    assistant.add_action_widget(label)
    hbox = label.get_parent()
    hbox.remove(label)
    return hbox

rawDescription: How do I change the built-in button labels on a gtk.Assistant?

description: Change the built-in button labels on a gtk.Assistant


code:
result = mongo_result('spam') #spam is my collection's name.
for doc in result:
    print(doc)

{'_id': ObjectId('54dafa385a28b3f71731efbd'), 'name': 'search string'}
{'_id': ObjectId('54dafa3d5a28b3f71731efbe'), 'name': 'search string1'}
{'_id': ObjectId('54dafa3f5a28b3f71731efbf'), 'name': 'search string2'}

rawDescription: Error in mongo query execution through python when queries and collection name are varying


code:
__init__(self, args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)

rawDescription: fd in subprocess.Popen

description: Fd in subprocess.Popen


code:
lv_temp2 = LV.objects.all().order_by('id')
lv_temp4 = []
for lv_temp3 in lv_temp2:
    lv_temp4.append(lv_temp3.id)

rawDescription: Index, for loops and making things look cleaner


code:
import requests
from bs4 import BeautifulSoup, Tag
url = 'http://www.moneycontrol.com/stocks/fno/marketstats/options/active_calls/index.php'
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
table = soup.select_one("table.tblList")
cols = [th.text.strip() for th in table.select_one("tr") if isinstance(th, Tag)]
print(cols)
elems = [[td.text.strip() for td in row if isinstance(td, Tag)] for row in table.select("tr + tr")]
print(elems[0])
print(elems[-1])
len(elems)

rawDescription: Table extraction with Selenium and PhantomJS never finishes


code: itertools.islice(s, 1, None)

rawDescription: simple python list comprehension question

description: Simple python list comprehension question


code: df = df.loc[:, (df != 0).any(axis=0)]

rawDescription: Delete Column in Pandas based on Condition


code:
from os.path import abspath
abspath('.')

rawDescription: Python: changing IDLE's path in WIN7

description: Python: changing IDLE's path in WIN7


code:
#ElR is the first matrix and ShR is the second matrix
with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR)

with open("house.txt", "a") as fS: # <-- notice the a
    fS.writelines(','.join(str(j) for j in i) + '\n' for i in ShR)

rawDescription: Trying to write and read two matrices in text file


rawDescription: Remove occuring elements from multiple lists (shorten multiple lists) by value


code: sweepers = [player for player in players if player.running_speed >= running_min]

rawDescription: Menu Interface Player Records

description: Menu Interface Player Records


code:
fig, ax = plt.subplots(1,2)

# @jeanrjc solution, which might hide other objects in your plot
ax[0].plot([-1,1],[1,-1], 'r', zorder = -10)
filled_arc((0.,0.3), 1, 90, 180, ax[0], 'blue')
ax[0].set_title('version 1')

# simpler approach, which really is just the arc
ax[1].plot([-1,1],[1,-1], 'r', zorder = -10)
arc_patch((0.,0.3), 1, 90, 180, ax=ax[1], fill=True, color='blue')
ax[1].set_title('version 2')

# axis settings
for a in ax:
    a.set_aspect('equal')
    a.set_xlim(-1.5, 1.5)
    a.set_ylim(-1.5, 1.5)

plt.show()

rawDescription: How to draw a filled arc in matplotlib

description: Draw a filled arc in matplotlib


rawDescription: Find all combinations of a list of numbers with a given sum


code:
childrenScores = np.zeros(10, dtype=int)
...
for box in boxes:
    if box[0]:
        childrenScores[box[1]] += 1 # NumPy advanced indexing

rawDescription: What is the most effective way to incremente a large number of values in Python?


code: EvalString = "QtGui.QColor(QtCore.QString(" + ColorString +"))"

rawDescription: Qt - Format QColor to be used in Style Sheet?


code:
from collections import defaultdict
d = defaultdict(list)
for i, j in zip(df.A,df.B):
    d[i].append(j)

rawDescription: How to create a dictionary of lists from two columns in a dataframe

description: Create a dictionary of lists from two columns in a dataframe


code:
existing_provider = Provider.query.get(1) # or whatever
# update the rssfeed column
existing_provider.rssfeed = form.rssfeed.data
db.session.commit()

rawDescription: Flask-SQLAlchemy: How to conditionally insert or update a row


code:
class AorB:
    def __new__(cls, par=None):
        if cls is not AorB: return super().__new__(cls)
        return super().__new__(A) if par else super().__new__(B)

class A(AorB):
    def __init__(self, par):
        self.par = par

class B(AorB):
    def __init__(self, par=None):
        pass

rawDescription: Python sum of classes

description: Python sum of classes


code:
config = ['a b','c d']
[item.split() for item in config]

rawDescription: Iterate over a list to apply a method to each member


code:
def sanitize(lst):
    # predefined list
    b = {1, 2}
    return sorted(lst, key=lambda v: v in b)

rawDescription: Python list popping and appending

description: Python list popping and appending


code:
from django.utils import timezone

class MyModel(...):
    # fields ...
    date = models.DateField(...)

    def was_published_this_year(self):
        now = timezone.now()
        if now.year ==  self.date.year:
            return True
        else:
            return False

rawDescription: Compare datetime year to current year in django template


code:
def __init__(self, *args, **kwargs):
    is_staff = kwargs.pop('is_staff')
    super(AddMovementForm, self).__init__(*args, **kwargs)
    if is_staff:
        self.fields['status'].choices = STAFF_STATUS_CHOICES
    else:
        self.fields['status'].choices = STATUS_CHOICES

rawDescription: Django - limit the choices of a choice field in a form


rawDescription: Byte Array in Python

description: Byte Array in Python


rawDescription: Fetching names from DesignMatrix in patsy


code:
(eg)
class MinimumBalanceAccount(BankAccount, LoanAccount):
    def __init__(self, minimum_value):
        super(MinimumBalanceAccount, self).__init__() # Calls BankAccount.__init__()
        super(MinimumBalanceAccount, self).__init__() # Still calls the same

rawDescription: Why dual __init__ in python?

description: Why dual __init__ in python


rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


code:
import os
import hashlib

def sha1OfFile(filepath):
    sha = hashlib.sha1()
    with open(filepath, 'rb') as f:
        while True:
            block = f.read(2**10) # Magic number: one-megabyte blocks.
            if not block: break
            sha.update(block)
        return sha.hexdigest()

def hash_dir(dir_path):
    hashes = []
    for path, dirs, files in os.walk(dir_path):
        for file in sorted(files): # we sort to guarantee that files will always go in the same order
            hashes.append(sha1OfFile(os.path.join(path, file)))
        for dir in sorted(dirs): # we sort to guarantee that dirs will always go in the same order
            hashes.append(hash_dir(os.path.join(path, dir)))
        break # we only need one iteration - to get files and dirs in current directory
    return str(hash(''.join(hashes)))

rawDescription: Creating unique hash for directory in python


code:
def parse_file1():
   id_dict = {'at_id':'th3674','full_name':'Tom Harry'}
   f=open('ports.dat','a+')
   lines = f.readlines()
   if lines:
       last = lines[-1]
       last = last.replace(last.split('$')[0],id_dict['at_id'])
       last = last.replace(last.split('$')[1],id_dict['full_name'])
       last = split_colon(last)
       f.write('\n')
       f.write(last)

def split_colon(line):
    for i in range(2,5):
        key = line.split('$')[i]
        for j in range(4):
            v = key.split(':')[j]
            line = line.replace(v, str(int(v) + 1))
    return line

if __name__=='__main__':
    parse_file1()

rawDescription: Python appending after updating the line to a file


code:
a.shape = (3,1)
a
a.transpose()
a.dot(a.transpose())

rawDescription: Python: Differentiating between row and column vectors


rawDescription: How to remove escape sequence like '\xe2' or '\x0c' in python

description: Remove escape sequence like '\xe2' or '\x0c' in python


code:
tops = range(10)
reduce(lambda x, y: x + [y] if len(x) == 0 or y > x[-1] + threshold else x, sorted(tops), [])

rawDescription: How do I remove almost-duplicate integers from list?

description: Remove almost-duplicate integers from list


code: button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100)

rawDescription: How do I change button size in Python?

description: Change button size in Python


code:
coords = {}
coords['y1'] = [[255,255,255],[255,0,0]] #add dynamic keys to your dictionary and fill them with the right values

rawDescription: How to store arrays of pixels in Pygame

description: Store arrays of pixels in Pygame


code: [myDictionary.get(key) for key in keys]

rawDescription: Python dictionary get multiple values

description: Python dictionary get multiple values


code:
import csv
import sys
with open('filename.csv') as fin:
    csvout = csv.writer(sys.stdout, delimiter='|')
    for row in csv.reader(fin):
        csvout.writerow(row)

rawDescription: splitting file into smaller files using by number of fields

description: Splitting file into smaller files using by number of fields


code:
import re

def search(regex,letters):
    letters=set(letters)
    pattern=re.compile(regex)
    for word in content:
        word=word.strip()
        if(pattern.findall(word)):
            if set(word) >= letters:
                print(word)

#search(r'^(n|u|p|g|o|u|e|b|l){6}$')
#search(r'^t(i|a)[a-z]{3}')
content=["hello","helps","halts","random"]
search(r'^h(e|a)[a-z]{3}','hltsa') #returns: hello,helps,halts

rawDescription: selecting words that only have specific letters in them

description: Selecting words that only have specific letters in them


code:
#! /usr/bin/python
import argparse
import shutil

parser = argparse.ArgumentParser(description="Copy a file")
parser.add_argument('src', metavar="SOURCE", help="Source filename")
parser.add_argument('dst', metavar="DESTINATION", help="Destination filename")
args = parser.parse_args()

shutil.copyfile(args.src, args.dst)

rawDescription: How do I accept user input on command line for python script instead of prompt

description: Accept user input on command line for python script instead of prompt


code:
fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10,10)))
cb = fig.colorbar(im)
cb.formatter.set_powerlimits((0, 0))
cb.ax.yaxis.set_offset_position('right')
cb.update_ticks()
plt.show()

rawDescription: Matplotlib Colorbar scientific notation offset


rawDescription: indexing spherical subset of 3d grid data in numpy

description: Indexing spherical subset of 3d grid data in numpy


code:
import re
import itertools

rawDescription: get elements in "AND" in logic string with Python

description: Get elements in "AND" in logic string with Python


code:
a = [0, 3, 1, 6, 8, 1, 3, 3, 2, 10, 10]
dup={}
for i,x in enumerate(a):
    dup.setdefault(x,[]).append(i)
dup

rawDescription: Extract list of duplicate values and locations from array


code:
call.py
import sys, test
test.main()

rawDescription: Using sys.argv from another .py file - python


code:
dialog = ConfirmationDialog()
result = dialog.exec_()
if result:  # accepted
    return 'accepted'

rawDescription: PyQt QDialog return response yes or no

description: PyQt QDialog return response yes or no


rawDescription: How to stop a loop?

description: Stop a loop


code:
bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}

f = open('chr22.fa')
l = ''.join(line.strip() for line in f)
f.seek(0)

for line in f:
    fields = line.split('\t')
    gene_ID, chr, strand = fields[:2]

    start = int(fields[3])
    end = int(fields[4])

    if strand == '-':
        start, end = -(start + 1), -(end + 1)

    geneseq = ''.join(bc[base.upper()] for base in l[start:end])

rawDescription: Matching parts of lines in a file (python)


code: df.reset_index() # col_fill=['A', 'B'])

rawDescription: Pandas reindexing data frame issue

description: Pandas reindexing data frame issue


code:
from subprocess import Popen, PIPE
cmd = "/sbin/route -n"
gateway = Popen(cmd.split(), stdout=PIPE)
stdout, stderr = gateway.communicate()
exit_code = gateway.wait()
gw = [line.split()[1] for line in stdout.decode().split('\n') if 'UG' in line][0]

rawDescription: Setting Variable to Gateway IP

description: Setting Variable to Gateway IP


code:
blacklist = ('.jpg', '.jpeg', '.png')
filtered = [elem for elem in li if not elem.endswith(blacklist)]

rawDescription: FIltering more then one string with list comprehension


code:
a=a.astype(float)
a
np.logical_xor(a, np.zeros(a.shape))

rawDescription: Python numpy XOR return NotImplemented

description: Python numpy XOR return NotImplemented


code:
slices = [np.s_[3:6], np.s_[11:17]]
for s in slices:
    bools[s] = False

rawDescription: Insert repeated value across list slices


code: Counter({'led bulb': 2, 'earphones': 2, 'mobile': 2, 'memory card': 1, 'shoes': 1})

rawDescription: Fastest way to count the occurance of a string


rawDescription: scipy.optimize.minimize : compute hessian and gradient together

description: Scipy.optimize.minimize : compute hessian and gradient together


code:
ave_scores = {}
for name in sorted(entries):
    ave_score = total_scores[name] / entries[name]
    ave_scores[name] = ave_score

for name,ave_score in sorted(ave_scores.items(), key = itemgetter(1), reversed=True):
    print(name,ave_score)

rawDescription: Sorting data from a csv alphabetically, highest to lowest and average


code:
Donations.sort("day",inplace=True)
cumulative_amount = Donations.groupby('solicitor').amount.cumsum()
Fundraisers['first day'] = Donations[cumulative_amount>=30].groupby('solicitor').min().day

rawDescription: Python Pandas better way to find the date when amount is greater than a goal


rawDescription: Apply a pairwise shapely function on two numpy arrays of shapely objects


rawDescription: Static lists in Python for arithmetic manipulations


rawDescription: Is there an easy way to restart a python 3 code once it has ended?


code:
def metric(a, b):
    s = 0
    for x, y in zip(a,b):
        s += abs(x-y)
    return s / len(a)

rawDescription: Using Nearest Neighbor search on an n element object


code:
def add_missing(l):
    st = set(map(itemgetter(0), data))
    it = iter(l)
    start, end = min(st), max(st)
    for day in range((end - start).days + 1):
        dte = start + timedelta(days=day)
        if dte not in st:
            yield (dte, 0)
        else:
            yield next(it)

rawDescription: Python - fill the no-used dates

description: Python - fill the no-used dates


rawDescription: Accessing file path in the os

description: Accessing file path in the os


code:
result.sort(key=lambda x: (-len(x), x))
pprint.pprint(result)

rawDescription: Get all combinations of neighbour elements in list


code:
with open("test.txt") as f:
    for line in f:         #fetches  a single line each time
       line = line.strip() #remove newline or other whitespace charcters
       wl = len(line)
       print (wl)
       if wl == userLength:
         words = line
         print (words)

rawDescription: Length function in python is not working the way I want to


code:
if sys.version_info >= (3, 0):
    from urllib.parse import urlparse
if sys.version_info < (3, 0) and sys.version_info >= (2, 5):
    from urlparse import urlparse

rawDescription: python 2 and 3 extract domain from url

description: Python 2 and 3 extract domain from url


rawDescription: Remove all hex characters from string in Python


code:
x = list(range(8))
foo(x, 5, 2)

rawDescription: How to slice a list with START being larger than STOP

description: Slice a list with START being larger than STOP


code:
def clicked(self, mouse):
    if mouse.x >= self.x and mouse.x <= self.x+self.width:
        if mouse.y >= self.y and mouse.y <= self.y+self.height:
            return self
    return False

rawDescription: Naming/Calling Generated Object w/ Classes


code:
import requests

data= {"vrm": "SM59TXS"}

req = requests.post("https://www.vehiclecheck.co.uk/",data=data)

print(req.content)

rawDescription: manipulating web forms in python

description: Manipulating web forms in python


code:
import mytimer

def somefun():
    mytimer.start()

somefun()

rawDescription: Python creating timestamps at different locations/classes to log function block run time


code:
ctx.locals.blub3 = get_js_obj({'a':[1,2,3]})
ctx.locals.blub4 = get_js_obj([1,2,3])
ctx.eval("blub3.a.length")
ctx.eval("blub4.length")

rawDescription: Converting Python objects to JavaScript for PyV8


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
        'OPTIONS': {
            'client_flag': 0
        }
    }
}

rawDescription: change CLIENT_FOUND_ROWS flag in django for mysql-python (MySQLdb)?

description: Change CLIENT_FOUND_ROWS flag in django for mysql-python (MySQLdb)


code:
class VideoFeedMixin(object):
    def videoFeed(self):
        ...

rawDescription: Can't connect function imported outside of class qt


code: df['que'] = df.apply(lambda x : x['one'] if x['one'] >= x['two'] and x['one'] <= x['three'] else "", axis=1)

rawDescription: Compare two columns using pandas

description: Compare two columns using pandas


code:
# in colors/__init__.py
import blue
import red

rawDescription: Python call a package submodule with variable module name


code: min(a, key=lambda k: a[k] if isinstance(a[k], datetime) else datetime.max)

rawDescription: How to get the item with max date value in a python dictionary?

description: Get the item with max date value in a python dictionary


code:
_VALID_URL = r"""(?x)^
                 (
                     (?:https?://|//)                                    # http(s):// or protocol-independent URL
                     (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
                        (?:www\.)?deturl\.com/www\.youtube\.com/|
                        (?:www\.)?pwnyoutube\.com/|
                        (?:www\.)?yourepeat\.com/|
                        tube\.majestyc\.net/|
                        youtube\.googleapis\.com/)                        # the various hostnames, with wildcard subdomains
                     (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
                     (?:                                                  # the various things that can precede the ID:
                         (?:(?:v|embed|e)/(?!videoseries))                # v/ or embed/ or e/
                         |(?:                                             # or the v= param in all its forms
                             (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)?  # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
                             (?:\?|\#!?)                                  # the params delimiter ? or # or #!
                             (?:.*?&)?                                    # any other preceding param (like /?s=tuff&v=xxxx)
                             v=
                         )
                     ))
                     |youtu\.be/                                          # just youtu.be/xxxx
                     |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
                     )
                 )?                                                       # all until now is optional -> you can pass the naked ID
                 ([0-9A-Za-z_-]{11})                                      # here is it! the YouTube video ID
                 (?!.*?&list=)                                            # combined list/video URLs are handled by the playlist IE
                 (?(1).+)?                                                # if we found the ID, everything can follow
                 $"""

rawDescription: How does youtube-dl generate direct link?


code:
nd = df.values[i]
test = pd.DataFrame(data=[nd], index=None, columns=None)
test.to_csv('SGX[Defunct]' + '.txt', mode='a', sep='\t', header=0, index=0)

rawDescription: Trouble with pandas to_csv function

description: Trouble with pandas to_csv function


code:
last_day_dict = day_counts[-1]
date = last_day_dict['posted_day']
count = last_day_dict['dailycount']

rawDescription: How do I get the number of posts on each day with annotation in Django?

description: Get the number of posts on each day with annotation in Django


code:
bad_chars = ' \t\n\r'

def count_chars():
    with open('someclass.java', 'r') as javafile:
        for line in javafile:
            cleaned = filter(lambda c: c not in bad_chars, line)
            if cleaned:
                yield len(cleaned)

rawDescription: Get length of line in Java file using python


code: [[x for y in lst for x in y].count(z) for z in sorted(set([t[0] for t in lst]))]

rawDescription: Running through a list of tuples

description: Running through a list of tuples


rawDescription: How to Filter letters in a string in Python

description: Filter letters in a string in Python


rawDescription: How do I filter values in a Django form using ModelForm?

description: Filter values in a Django form using ModelForm


rawDescription: Pandas - group by consecutive ranges

description: Pandas - group by consecutive ranges


rawDescription: What is the correct syntax for using logical or boolean indexing with Pandas DataFrames?


code:
params = {
    'name_ffb': '',
    'ort_ffb': '',
    'strasse_ffb': '',
    'plz_ffb': '50000',
    'plz_ff2b': '50030',
    'land_ff': '',
    'rubrik_ff': '',
    'submit22': 'Suchen'
}
DATA = urllib.parse.urlencode(params)
DATA = DATA.encode('utf-8')

rawDescription: Trying to send a POST-request with urllib.request returns the same page


rawDescription: Convert AWK regex to Python script

description: Convert AWK regex to Python script


code:
START_VALUE = 200
all_combos = itertools.product(letters,repeat=9)

#start at START_VALUE and stop at None (the end)
combos = itertools.islice(all_combos,START_VALUE,None)

for i,password in enumerate(combos,start=START_VALUE):
    ...

rawDescription: Python itertools product start from certain


code:
user = ...# some code that creates or selects a user
class_ = ...# some code that creates or selects a class
# here is the addition
class_.participants.append(user)
session.commit()

rawDescription: Flask-SQLAlchemy - How to append a value to a column?


code:
import random
ba = bytearray([random.randint(0,255) for n in xrange(1000000)])
with open('randint.dat', 'w+') as f:
    f.write(ba)

rawDescription: Is Pythons random.randint statistically random?


code:
out = dict(list(a.items()) + list(b.items()))

print(out)
{'Paper': 3, 'cars': 1, 'Pens': 1, 'stores': 4, 'Pencils': 2, 'schools': 3, 'houses': 2}

rawDescription: combine two json dictionary python

description: Combine two json dictionary python


code:
def balance(self):
    return self.balance

rawDescription: Why does this class program not return the balance?


code:
def open_recipes(path):
    try:
        with open(path) as stream:
            return json.loads(stream.read())
    except FileNotFoundError:
        # start a new database
        return {}

def save_recipes(path, recipes):
    with open(path, 'w') as stream:
        stream.write(json.dumps(recipes, indent=2))

rawDescription: Python Programming - input/output

description: Python Programming - input/output


code: H, xedges, yedges = np.histogram2d(x, y, range=rang, bins=binsxy)

rawDescription: Find peak of 2d histogram

description: Find peak of 2d histogram


code:
@foo
def bar():
    pass

rawDescription: Decorating a function with a method (with arbitrary arguments)


code:
pylab.axis('scaled')
pylab.show()

rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
import importlib

TWO_FACTOR_BACKENDS = (
    'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
    'id.backends.TOTPBackend',
    'id.backends.HOTPBackend',
    #'id.backends.YubikeyBackend',
    #'id.backends.OneTimePadBackend',
    #'id.backends.EmailBackend',
)

backends = [getattr(importlib.import_module(mod), cls) for (mod, cls) in (backend.rsplit(".", 1) for backend in TWO_FACTOR_BACKENDS)]

rawDescription: Get python class object from string

description: Get python class object from string


code:
s = 'This is an [[example]] sentence. It is [[awesome]].'
s.replace('[[', '<b>').replace(']]', '</b>')

rawDescription: Python: Replace tags but preserve inner text?


code: all(i%j==0 for j in a_list_of_terms)

rawDescription: Check what numbers in a list are divisible by certain numbers?


code: map(lambda x: heapq.nsmallest(x,2)[1],  list_of_lists)

rawDescription: Is it possible to have multiple statements in a python lambda expression?


rawDescription: Sorting a complex structure of array of array


code:
def communicate(self, input=None):
    ...
    # Optimization: If we are only using one pipe, or no pipe at
    # all, using select() or threads is unnecessary.
    if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
        stdout = None
        stderr = None
        if self.stdin:
            if input:
                self.stdin.write(input)
            self.stdin.close()
        elif self.stdout:
            stdout = self.stdout.read()
            self.stdout.close()
        elif self.stderr:
            stderr = self.stderr.read()
            self.stderr.close()
        self.wait()
        return (stdout, stderr)

    return self._communicate(input)

rawDescription: Python subprocess Popen.communicate() equivalent to Popen.stdout.read()?


code:
from PyQt5.QtCore import pyqtSignal

universe_1 = [0 for i in range(512)]

class SpecialProcess(QThread):
    universeChanged = pyqtSignal()

    def __init__(self):
        super(SpecialProcess, self).__init__()
        self.start()

    def run(self):
        universe_1[:] = [randrange(0, 101, 2) for i in range(512)]
        self.universeChanged.emit()
        sleep(0.1)
        self.run()

rawDescription: Update QlistView with python list updated from another thread (pyqt5)


code:
import sympy as sy
a, b, c = sy.symbols('a:c')

a_expr = sy.sympify("b + 5")
b_expr = sy.sympify("c + 5")
c_expr = sy.sympify("5")

sy.solve([sy.Eq(a,a_expr), sy.Eq(b,b_expr), sy.Eq(c,c_expr)])

rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


rawDescription: How to dynamically change the filter in a pandas data with subgroups of another column?

description: Dynamically change the filter in a pandas data with subgroups of another column


code:
class Foo(object):
    pass

myobject = Foo()
myobject.foo = 'bar'

rawDescription: Python simple naked objects

description: Python simple naked objects


rawDescription: Where should I subtract 1 when generating random numbers as a list index?


rawDescription: Extracting a feature by feature name in scikit dict vectorizer


rawDescription: How to loop through list evalute first char of each item of list

description: Loop through list evalute first char of each item of list


code:
r"abcd\'"
print(r"abcd\'")

rawDescription: Python re substitute adds extra backslash chars


code:
def separate(p, L, idx=0):
    if idx == len(L):
        return [], []

    l1, l2 = separate(p, L, idx + 1)

    item = L[idx]

    if p(item):
        l1.append(item)
    else:
        l2.append(item)
    return l1, l2

rawDescription: How does a recursive function returns a tuple of lists?


code:
import os.path
os.curdir
startdir = os.path.abspath(os.curdir)
startdir

rawDescription: Does my code prevent directory traversal?


code:
from flask import Flask, request
app = Flask(__name__)

@app.route('/<pathVariable>/')
def test(pathVariable):

    test = pathVariable
    path = request.path
    script_root = request.script_root
    base_url = request.base_url
    url = request.url
    url_root = request.url_root
    url_rule = request.url_rule

    print ("test is: %s" %path)
    print ("path is: %s" %path)
    print ("script_root is: %s" %script_root)
    print ("base_url is: %s" %base_url)
    print ("url is: %s" %url)
    print ("url_root is: %s" %url_root)
    print ("url_rule is: %s" %url_rule)

    return render_template('/example.html', pathVariable=pathVariable)

if __name__ == '__main__':
    app.run()

rawDescription: Flask use URL variable in function

description: Flask use URL variable in function


code: curr.executemany('UPDATE test SET myCol= ?', myList)

rawDescription: How to update entire column with values in list using Sqlite3

description: Update entire column with values in list using Sqlite3


code:
flow = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope=scope,

            access_type = 'offline',
            approval_prompt='force',
            redirect_uri=self.request.relative_url('/admin/auth_return'))
# Get the url now
authorize_url = flow.step1_get_authorize_url()
# Save flow object in memcache for later retrieval on OAuth callback,
# and redirect this session to Google's OAuth 2.0 authorization site.
logging.info('saving flow for user ' + user.user_id())
memcache.set(user.user_id(), pickle.dumps(flow))
# redirect directly
self.redirect(authorize_url, abort=True)

rawDescription: Storing Credentials for Offline Access in Datastore


code:
from sklearn.preprocessing import LabelEncoder
import pandas as pd

data = pd.DataFrame()

data['age'] = [17,33,47]
data['gender'] = ['m','f','m']

enc = LabelEncoder()

print(data)
enc.fit(data['gender'])
data['gender'] = enc.transform(data['gender'])
print(data)

rawDescription: random forest with characters in scikit-learn/python

description: Random forest with characters in scikit-learn/python


rawDescription: Summing Attribute in a list of Python Objects


code: new_d = {k:v for k, v in d.items() if v == 3}

rawDescription: Performance of inverse dictionary mapping


code:
for person in sorted(cat1, key=lambda x: sum(cat1.get(x))/len(cat1.get(x)), reverse=True):
    print(person, sum(cat1.get(person))/len(cat1.get(person)))

rawDescription: How to sort python dictionary/list?

description: Sort python dictionary/list


code:
df
df.index

rawDescription: Pandas: read_csv with only HH:MM:SS in the index


rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
soup.p
soup.p.a

rawDescription: Splitting a BeautifulSoup into 2 Soup-Trees


code: another = l[2:5]   # another is [2, 3, 4]

rawDescription: Split list based on first character - Python


code: anyNA = frame[(frame.A.isnull()) | (frame.B.isnull()) | (frame.C.isnull())]

rawDescription: pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN

description: Pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN


code:
def __call__(self, environ, start_response):
    return self.wsgiapp(environ, start_response)

rawDescription: Python CherryPy server, what does cherrypy.Application do?


code:
def func(f):
    return f  # parenthesis unnecessary.
func(lambda x: x*2)(3)

rawDescription: accessing lambda value passed to function python

description: Accessing lambda value passed to function python


code:
"""Test Control Program

Usage:
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

Arguments:

      bits: 1 - on
            0 - off

"""
from docopt import docopt, DocoptExit

if __name__ == '__main__':
    try:
        arguments = docopt(__doc__, version='Test Control Program')
        print(arguments)
    except DocoptExit:
        print(__doc__)

rawDescription: Specify valid values for arguments using docopt


code:
import os
import datetime

data = "\n".join("testing\n" * 10 for x in xrange(10000000))
print("Size of data is %d bytes" % len(data))

print("open at %s" % str(datetime.datetime.now()))
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK)
print("write at %s" % str(datetime.datetime.now()))
os.write(fd, data)
print("close at %s" % str(datetime.datetime.now()))
os.close(fd)
print("end at %s" % str(datetime.datetime.now()))

rawDescription: How to write to a file using non blocking IO?

description: Write to a file using non blocking IO


code:
with open("a.txt") as a:
    with open("b.txt") as b:
        with open("c.txt", "w") as c:
            c.write("".join(set(a) - set(b)))

rawDescription: What's the fastest way to find unique lines from huge file A as compared to huge file B using python?


code:
#References to created DLL of python modules
clr.AddReference('StdLib')

rawDescription: IronPython: EXE compiled using pyc.py cannot import module "os"


code:
import numpy as np

# Parameters
R = 3  # Radius
M1,N1 = padded.shape
rowlen = N1 - R + 1
collen = M1 - R + 1

# Linear indices for the starting R x R block
idx1 = np.arange(R)[:,None]*N1 + np.arange(R)

# Offset (from the starting block indices) linear indices for all the blocks
idx2 = np.arange(collen)[:,None]*N1 + np.arange(rowlen)

# Finally, get the linear indices for all blocks
all_idx = idx1.ravel()[None,None,:] + idx2[:,:,None]

# Index into padded for the final output
out = padded.ravel()[all_idx]

rawDescription: Generalize stacking of array elements' neighbors into 3-D array


code:
for char in text:
    try:
        print("Character {0} found in row {1}".format(char, chars[char]))
    except KeyError:
        pass

rawDescription: Python string comparison whilst in loop

description: Python string comparison whilst in loop


code: [''.join(p) for p in itertools.product('LE', repeat=3)]

rawDescription: Combinations or permutations of input, for a given length


code:
players_table = Table('players', metadata,
  Column('id', Integer, primary_key=True),
  Column('name', String),
  Column('score', Integer)
)
metadata.create_all(engine) # create the table

rawDescription: Dynamic Table Creation and ORM mapping in SqlAlchemy


code:
ref_list = map(lambda x: x.strip(" \t\n"),ref_list)
input_list = map(lambda x: x.strip(" \t\n"),input_list)

rawDescription: python - find occurrences of strings from a reference file within an input file

description: Python - find occurrences of strings from a reference file within an input file


code: sql = "select * from dataBase where cus IN ({0})".format(', '.join(['%s'] * len(cus2)))

rawDescription: Remove Brackets from Python List for an SQL query


code:
mask = df.ticker != df.ticker.shift(1)
df['diffs'][mask] = np.nan

rawDescription: Computing diffs within groups of a dataframe


code:
coordinate_list = [ ]
for location in locations:
    coord = Coordinates(location.latitude, location.longitude)
    coordinate_list.extend([coord] * location.number_of_times)

rawDescription: Python: Repeat elements in a list comprehension?


code:
from collections import defaultdict
x = defaultdict(list)
for tup in data:
    x[tup[0]].append(tup[1:])

rawDescription: create a dict with unique keys and various list values from a tuple

description: Create a dict with unique keys and various list values from a tuple


rawDescription: Fastest way to rank items with multiple values and weightings


code:
fmt = MyFormatter()
hdlr = logging.StreamHandler(sys.stdout)

hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
logging.root.setLevel(DEBUG)

rawDescription: Modifying logging message format based on message logging level in Python3


rawDescription: django-endless with class based views example

description: Django-endless with class based views example


code:
import xml.etree.ElementTree as ET

e = ET.parse('mainDataSet.xml').getroot()
for word in e.findall('word'):
    word_id = word.attrib.get("id")
    if word_id:
        filename = "%s.xml" % word_id
        e_word = ET.parse(filename)
        e_word.getroot().attrib['title'] = word.attrib.get('title')
        e_word.write(filename)

rawDescription: Parse specific XML attribute from one file and append it to another iff another attribute is present in the second file


code:
tstamp = 1325178061  # right about now
from datetime import datetime
datetime.fromtimestamp(tstamp)

rawDescription: Conversion of unix epoch time to windows epoch time in python


code:
from collections import defaultdict, Counter
from itertools import combinations
persons = ["rob", "candice", "candice", "rob", "arnold", "ben", "ben", "ben", "arnold"]
fruits = ["orange", "orange", "mango", "mango", "orange", "orange", "banana", "mango", "banana"]
likes = defaultdict(set)
for person, fruit in zip(persons, fruits):
    likes[person].add(fruit)

likes
counts = Counter()
for person in likes:
    for combo in combinations(likes[person], 2):
        counts[frozenset(combo)] += 1

counts.most_common(1)[0][0]

rawDescription: comparing two lists and finding most preferred pairs

description: Comparing two lists and finding most preferred pairs


code:
class BaseTestSuite(unittest.TestSuite):
    xmlfile = None

    def addTest(self, test):
        if isinstance(test, BaseTestCase):
            test.xmlfile = self.xmlfile

        super(BaseTestSuite, self).addTest(test)

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code:
@app.task(bind=True)
def add(self, x, y):
    print('Approximate queue time: {0}'.format(
        time.time() - self.request.headers.get('time_sent', 0),
    ))
    return x + y

rawDescription: Why Celery does not embed a timestamp into the queued message?


code: x = 5   # like this

rawDescription: Python - Delete comments in a Python code


code:
def get_class_name(instance):
    return instance.__class__.__name__

rawDescription: Django custom user model with django-polymorphic


code:
class Line(Shape):
    def __init__(self, description):
        self.desc = description
    def number_of_edges(self, parameters):
        return 1

rawDescription: Python virtual classes: doing it right?

description: Python virtual classes: doing it right


code:
dt = datetime.datetime(year=2012, month=2, day=9)
time.mktime(dt.timetuple())

rawDescription: Python timestamp from day, month, year

description: Python timestamp from day, month, year


code: colors[a]

rawDescription: Indexing in numpy array

description: Indexing in numpy array


code: X = np.einsum('ik,jk->ij', np.conj(x), x)

rawDescription: Pairwise vdot using Numpy

description: Pairwise vdot using Numpy


code:
for p in site.select('.//*[contains(@class, "summary")]/p'):
    p.select('//text()').extract()

rawDescription: xpath selecting elements and iterating over the tag

description: Xpath selecting elements and iterating over the tag


code: [u'medicoes', u'veiculos', u'coord', u'modalidade', u'sentido', u'local', u'pistas', u'regime']

rawDescription: Convert JSON to SQLite in Python - How to map json keys to database columns properly?


code:
fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
ax.locator_params(prune='lower',axis='both')

rawDescription: Preventing xticks from overlapping yticks


code: [[["A"]+y for y in find_all_paths(G,x,"A")] for x in graph["A"]]

rawDescription: Find all paths in graph from A to N

description: Find all paths in graph from A to N


code:
def __str__(self):
    return unicode(self).encode('UTF-8')
cls.__str__ = __str__

rawDescription: define different function for different versions of python

description: Define different function for different versions of python


rawDescription: Pandas: Sorting columns by their mean value


code:
result = urllib2.urlopen('http://www.spiegel.de')
result.headers['content-length']

rawDescription: urllib2.urlopen(): getting the size of the content

description: Urllib2.urlopen(): getting the size of the content


rawDescription: Unable to retrieve element of desired XPATH using BeautifulSoup


code:
pd.set_option('display.height', some_value)
pd.set_option('display.max_rows', some_value)

rawDescription: Display Entire Dataset,Python

description: Display Entire Dataset,Python


rawDescription: MongoDB MapReduce, Date and % operator

description: MongoDB MapReduce, Date and % operator


code:
import pandas as pd
import numpy as np

from sklearn.base import TransformerMixin

class DataFrameImputer(TransformerMixin):

    def __init__(self):
        """Impute missing values.

        Columns of dtype object are imputed with the most frequent value
        in column.

        Columns of other types are imputed with mean of column.

        """
    def fit(self, X, y=None):

        self.fill = pd.Series([X[c].value_counts().index[0]
            if X[c].dtype == np.dtype('O') else X[c].mean() for c in X],
            index=X.columns)

        return self

    def transform(self, X, y=None):
        return X.fillna(self.fill)

data = [
    ['a', 1, 2],
    ['b', 1, 1],
    ['b', 2, 2],
    [np.nan, np.nan, np.nan]
]

X = pd.DataFrame(data)
xt = DataFrameImputer().fit_transform(X)

print('before...')
print(X)
print('after...')
print(xt)

rawDescription: Impute categorical missing values in scikit-learn


rawDescription: Python multiplicative inverse in GF(2) finite field


code:
from bs4 import BeautifulSoup

def iter_uniq_link(all_countries):
    seen = set()
    for c in all_countries:
        data_id = c.get('data-id')
        if data_id not in seen:
            seen.add(data_id)
            yield c

rawDescription: Extract unique elements from a list returned by BeautifulSoup


code:
@app.route("/<param1>", methods=["GET"])
def func1(param1):
    g.info = "Hello world"
    return func2()

def func2():
    if g.info == "Hello world":
        return "Hello world"
    return "mystring"

rawDescription: How to get parameters from root function

description: Get parameters from root function


code: pd.read_csv(path, header=None)

rawDescription: Converting a numpy.ndarray value from bytes to float


rawDescription: Python - Extra Excel chart series with win32com


rawDescription: Using pandas to plot data

description: Using pandas to plot data


code: print(sum(float(d['avgreturns'])* b for d,b in l))

rawDescription: Python: get dictionary value from a dictionary within a tuple within a list and do something with it


code:
total_lines = len(lines)
total_columns = len(line)

rawDescription: File and space in Python

description: File and space in Python


code:
def make_tree(path):
    tree = dict(name=os.path.basename(path), children=[])
    try: lst = os.listdir(path)
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = os.path.join(path, name)
            if os.path.isdir(fn):
                tree['children'].append(make_tree(fn))
            else:
                with open(fn) as f:
                    contents = f.read()
                tree['children'].append(dict(name=name, contents=contents))
    return tree

rawDescription: Display content of files in a particular directory using Flask


rawDescription: places to look for code to convert a data file to X12 format?

description: Places to look for code to convert a data file to X12 format


code:
if func == "QUIT":
    return

rawDescription: end daemon processes with multiprocessing module

description: End daemon processes with multiprocessing module


rawDescription: Probability tensor multiplication using pandas.DataFrame


code:
def pack_bigint(i):
    bl = (i.bit_length() + 7) // 8
    fmt = '<{}B'.format(bl)
    # ...

rawDescription: How to encode a long in Base64 in Python?

description: Encode a long in Base64 in Python


code:
def makelists(list_count):
    list_of_lists = []
    for _ in range(list_count):
        list_of_lists.append(list())
    return list_of_lists

rawDescription: Create lists python

description: Create lists python


code:
def average(arr, n):
    end =  n * int(len(arr)/n)
    return numpy.mean(arr[:end].reshape(-1, n), 1)

rawDescription: Subsampling/averaging over a numpy array


rawDescription: How to convert tree-form tuples to matrix-form tuples?

description: Convert tree-form tuples to matrix-form tuples


code:
import traceback

class Controller(object):
    def output_method(self, s):
        (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
        method_that_called_me = function_name
        self.output[method_that_called_me] = s

rawDescription: Python: Find out what method on derived class called base class method


code:
import re

my_string = """*select 65* description"""
match = re.match(r"^\*([a-z]+)\s+([0-9]+)\*", my_string)
specifier = match.group(1)
integer = int(match.group(2))

rawDescription: Matching a simple string using Regex?

description: Matching a simple string using Regex


code:
def get_primes():
    a = int(input("Look up to: "))

    # 'primes' is a more suitable name for a list of primes
    # we're only creating the list *once*, and we're not shadowing 'list'
    primes = list()

    for candidate in range(0, a):
        if prime(candidate) == True:
            print(candidate)
            print("adding to list")
            primes.append(candidate)

        else:
            print(num, "is not a prime")

    # use return to return a result
    return primes

rawDescription: How can I add the outcome of a function to a list in python?

description: Add the outcome of a function to a list in python


code:
#coding=utf8

import re

def remove_chars_iter(subj, chars):
    sc = set(chars)
    return ''.join([c for c in subj if c not in sc])

def remove_chars_re(subj, chars):
    return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_re_unicode(subj, chars):
    return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_translate_bytes(subj, chars):
    return subj.translate(None, ''.join(chars))

def remove_chars_translate_unicode(subj, chars):
    d = {ord(c):None for c in chars}
    return subj.translate(d)

import timeit, sys

def profile(f):
    assert f(subj, chars_to_remove) == test
    t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
    print ('{0:.3f} {1}'.format(t, f.__name__))

print (sys.version)
PYTHON2 = sys.version_info[0] == 2

print ('\n"plain" string:\n')

chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?' * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)
profile(remove_chars_re)

if PYTHON2:
    profile(remove_chars_translate_bytes)
else:
    profile(remove_chars_translate_unicode)

print ('\nunicode string:\n')

if PYTHON2:
    chars_to_remove = [u'δ', u'Γ', u'ж']
    subj = u'AжBδCΓ'
else:
    chars_to_remove = ['δ', 'Γ', 'ж']
    subj = 'AжBδCΓ'

subj = subj * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)

if PYTHON2:
    profile(remove_chars_re_unicode)
else:
    profile(remove_chars_re)

profile(remove_chars_translate_unicode)

rawDescription: Removing a list of characters in string

description: Removing a list of characters in string


code:
import urllib
from bs4 import BeautifulSoup as BS

url = '''https://archive.org/details/20070519_detroit2'''
#open and read page
page = urllib.urlopen(url)
html = page.read()
#create BeautifulSoup parse-able "soup"
soup = BS(html)
#get the src attribute from the video tag
video = soup.find("video").get("src")

rawDescription: How to find specific video html tag using beautiful soup?

description: Find specific video html tag using beautiful soup


code:
from django.db import models

class TestModel(models.Model):
    prop_a = models.TextField()
    prop_b = models.TextField()

    def __unicode__(self):
        return "{} {}".format(self.prop_a, self.prop_b)

rawDescription: Accessing Johnny Cache Data

description: Accessing Johnny Cache Data


code: df[['Sex', 'Survived', 'Age']].to_csv('D:\\Apps\\Coursera\\Kaggle-Titanic\\Swm\\result.csv', index=False)

rawDescription: Write to_csv with Python Pandas: Choose which column index to insert new data


code: pd.read_csv('your_file.txt', sep=' ')

rawDescription: Reading column delimited text data in python quickly


code:
np.logical_and(True, np.nan), np.logical_and(False, np.nan)
np.logical_and(np.nan, True), np.logical_and(np.nan, False)
np.logical_or(True, np.nan), np.logical_or(False, np.nan)
np.logical_or(np.nan, True), np.logical_or(np.nan, False)

rawDescription: Python numpy.nan and logical functions: wrong results


rawDescription: How to Join two separate text data files and align data over varying time intervals and avg


code: lib = cdll.LoadLibrary('spreadsort.so')

rawDescription: How to sort an array of integers faster than quicksort?

description: Sort an array of integers faster than quicksort


rawDescription: PyQT vs PyObjc / Cocoa-Python

description: PyQT vs PyObjc / Cocoa-Python


code:
a = np.array([1, 'x', np.nan], dtype=object)
b = np.array([1, 'x', np.nan], dtype=object)
a == b
a[2] == b[2]
type(a[2])
type(b[2])

rawDescription: Python numpy nan compare to true in arrays with strings


rawDescription: Python - find integer closest to 0 in list


code:
def matrixH0(k):
    return [[math.sqrt(n+m+1)/2. if abs(m-n)==1 else 0 for n in range(k)]
            for m in range(k)]

rawDescription: Adding values to a matrix with a for loop in python


code:
# Store the links we need in a list
links_to_keep = []
with open("Anilinks.txt", "r") as f:

     for line in f.readlines():
         if 'solidfiles.com' in line:
             links_to_keep.append(line)

# Write all the links in our list to the file
with open("Anilinks.txt", "w") as f:

    for link in links_to_keep:
        f.write(link)

rawDescription: Keep only certain lines in a text file using python


code:
for item in (color for idx, color in list_of_tuples if idx in items_to_pick):
    print(item)

rawDescription: Python, to pick specific elements from a list of tuples


code:
res2 = main1[np.in1d(array1, my_list1) & np.in1d(array2, my_list2) &
             np.in1d(array3, my_list3)]

rawDescription: Slice numpy array based on x number of other arrays


code: itertools.product(range(4), repeat=3)

rawDescription: Creating the Powerset of a set of Vectors in Python?


rawDescription: Why does hough transform for lines returning sinusoids divided halfway?


code:
d = dict()
hb1 = HashableBytearray('abcd')
hb2 = HashableBytearray('abcd')
d[hb1] = 0
d[hb2] = 1
d

rawDescription: Python quickly hash mutable object

description: Python quickly hash mutable object


code:
from geoalchemy2.elements import WKTElement
from app import models

def get_nearest(lat, lon):
    # find the nearest point to the input coordinates
    # convert the input coordinates to a WKT point and query for nearest point
    pt = WKTElement('POINT({0} {1})'.format(lon, lat), srid=4326)
    return models.Point.query.order_by(models.Point.geom.distance_box(pt)).first()

rawDescription: Flask with GeoAlchemy sample code

description: Flask with GeoAlchemy sample code


code:
classes = []

number_classes = int(input("How many classes did you take? "))
print()

for i in range(1, number_classes + 1):
    p = input("What is the name of class " + i)
    q = input("What grade did you get in that class? ")
    classes.append((p,q))

rawDescription: How can I increase number in input statement in python?

description: Increase number in input statement in python


code:
inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

rawDescription: Python: How to keep repeating a program until a specific input is obtained?


code:
import matplotlib
import pylab

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

rawDescription: scatter plot in matplotlib

description: Scatter plot in matplotlib


code:
from itertools import chain, izip_longest
subs = product("68", repeat=word.count("B"))
[''.join(chain(*izip_longest(word.split('B'), sub, fillvalue=''))) for sub in subs]

rawDescription: Create strings with all possible combinations


code:
ds1
ds2
out

rawDescription: Any function in numpy/pandas/python to search and replace


code:
def create_bar_function(add=add):
    ...

rawDescription: How to make function calls obey lexical scope in Python?

description: Make function calls obey lexical scope in Python


code:
from feeds.tasks import import_feed
import_feed.apply_async(args=['http://cnn.com/rss'],
                        queue='feed_tasks',
                        routing_key='feed.import')

rawDescription: Celery subtask bound to different application executed remotely


code: RDD.takeOrdered(5, key = lambda x: -x[0])

rawDescription: takeOrdered descending Pyspark

description: TakeOrdered descending Pyspark


code:
with open('latin.txt', 'r', encoding='latin1') as fdin, open('utf.txt',
        'w', encoding='utf8') as fdout:
    for line in fdin:
        fdout.write(line)

rawDescription: Python 3.4 / Notepad++ 6.5 Hex Characters Replacement


code:
mapping = {}
key = None
for item in soup.find_all('p'):
    if item.strong:
        key = item.strong.get_text(strip=True).rstrip(':')
        value = item.strong.next_sibling.strip()
    else:
        value = mapping[key] + ' ' + item.get_text(strip=True)
    mapping[key] = value

rawDescription: Using a nested element's text as a selector in BeautifulSoup


code: np.nonzero(B[:,None] == A)[1]

rawDescription: Finding indices of matches of one array in another array


code:
outputDict = {}
for k, v in dict1.items():
    if k in dict2:
        result[k] = v + (dict2[k][2],)

rawDescription: How to compare 2 dictionary of tuples to generate this list of dictionary?

description: Compare 2 dictionary of tuples to generate this list of dictionary


code:
if get_port.fetchone():
    do_something_here()

rawDescription: Checking for empty queryset in Python/MySQLdb


rawDescription: Can anybody explain me the numpy.indices()?


code: import utils.file_utils.read_file

rawDescription: Set DJANGO_SETTINGS_MODULE as an Enviroment Variable in Windows permanently


rawDescription: Python 3: Programmatically converting list of hex numbers to binary


code:
from scipy.optimize import fsolve
import numpy as np

def f(r):
    return 0.1 + 1 / (2 * r ** 2) - 2 / (3 * np.sqrt(r ** 3))

r = fsolve(f, 1)
f(r)

rawDescription: python numerically solving an equation with no sign change between the upper and lower bound

description: Python numerically solving an equation with no sign change between the upper and lower bound


code:
def read_matrix(filespec):
    from scipy.io import loadmat
    md = loadmat(filespec)
    # process md
    return md

rawDescription: Load many files into one array - Python

description: Load many files into one array - Python


code:
class ItemStatusHistory(models.Model):
    date = models.DateTimeField(auto_now=True)
    contact = models.ForeignKey(Contact, related_name="history")
    item = models.ForeignKey(StorageItem, related_name="history")
    status = models.ForeignKey(Status, related_name="history")
    user = models.ForeignKey(User, related_name="history")

rawDescription: Query for items using filter for most recent entry in a related table


code:
h = df.iloc[:2].astype(float)
h.groupby(np.arange(len(h.columns))//12, axis=1).mean()

rawDescription: loop for computing average of selected data in dataframe using pandas

description: Loop for computing average of selected data in dataframe using pandas


code:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Product(Base):
    __tablename__ = "product"
    id = sa.Column(sa.Integer, primary_key=True)
    actual = sa.Column(sa.String)
    target = sa.Column(sa.String)

rawDescription: SQLAlchemy (sql) conditionnal query

description: SQLAlchemy (sql) conditionnal query


rawDescription: Convert unicode representation of number to ascii string


code:
"""
Django settings for yourdjproject project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

ON_OPENSHIFT = False
if 'OPENSHIFT_REPO_DIR' in os.environ:
    ON_OPENSHIFT = True

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '60e32dn-za#y=x!551tditnset(o9b@2bkh1)b$hn&0$ec5-j7'

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yourapp',
    #more apps here
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'yourdjproject.urls'

WSGI_APPLICATION = 'yourdjproject.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

if ON_OPENSHIFT:
    DEBUG = True
    TEMPLATE_DEBUG = False
    ALLOWED_HOSTS = ['*']
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'youropenshiftgenerateddatabasename',
            'USER': os.getenv('OPENSHIFT_MYSQL_DB_USERNAME'),
            'PASSWORD': os.getenv('OPENSHIFT_MYSQL_DB_PASSWORD'),
            'HOST': os.getenv('OPENSHIFT_MYSQL_DB_HOST'),
            'PORT': os.getenv('OPENSHIFT_MYSQL_DB_PORT'),
            }
    }
else:
    DEBUG = True
    TEMPLATE_DEBUG = True
    ALLOWED_HOSTS = []
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', #If you want to use MySQL
            'NAME': 'yourlocaldbname',
            'USER': 'yourlocalusername',
            'PASSWORD': 'yourlocaluserpassword',
            'HOST': 'yourlocaldbhost',
            'PORT': '3306', #this will be the case for MySQL
        }
    }

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'yr-LC'
TIME_ZONE = 'Your/Timezone/Here'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'static'),)
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'templates'),)

rawDescription: Deploying a local django app using openshift


code:
sample = ['sample1.zip', 'sample2.zip', 'sample3.zip', 'sample4.zip',
          'sample1.txt', 'sample2.pdf', 'sample3.csv', 'sample4.xlsx']
[x for x in sample if not x.endswith('.zip')]

rawDescription: python evaluate bool within a list comprehension

description: Python evaluate bool within a list comprehension


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

def main():
    x = np.array([0.1, 0.3, 1.9])
    y = np.array([4, -9, 1])
    xi = np.linspace(-1, 3, 200)

    fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
    for ax in axes:
        ax.margins(0.05)
        ax.plot(x, y, 'ro')

    axes[0].plot(xi, np.interp(xi, x, y), color='blue')
    axes[1].plot(xi, nearest_interp(xi, x, y), color='green')

    kwargs = dict(x=0.95, y=0.9, ha='right', va='top')
    axes[0].set_title("Numpy's $interp$ function", **kwargs)
    axes[1].set_title('Nearest Interpolation', **kwargs)

    plt.show()

def nearest_interp(xi, x, y):
    idx = np.abs(x - xi[:,None])
    return y[idx.argmin(axis=1)]

main()

rawDescription: Extraploation with 'nearest' method in Python


code:
import sys
import zipfile

def unzip(path, root='/'):
    zh = zipfile.ZipFile(path, 'r')
    for name in zh.namelist():
        zh.extract(name, root)
    zh.close()

unzip(sys.argv[1])

rawDescription: Move required files where they need to go


rawDescription: How to map dict into another dict Python

description: Map dict into another dict Python


code:
def add_attributes(self, **kw):
    self.__dict__.update(kw)

rawDescription: Create Python class where the attributes is defined dynamically


code:
# in model
class Foo(models.Model):
    col1 = models.TextField(primary_key=True)
    col2 = models.TextField()
    col3 = models.TextField()

    class Meta:
        db_table = 'view_for_legacy_tables'

rawDescription: Can we query multiple tables across multiple oracle users and tabularize the rows in Django's Admin UI


code:
import win32con
win32gui.ShowWindow(firefox[0], win32con.SW_MINIMIZE)

rawDescription: How do I take out the focus or minimize a window with Python?

description: Take out the focus or minimize a window with Python


code: pd.formats.format.header_style = None

rawDescription: pandas xlsxwriter, format header

description: Pandas xlsxwriter, format header


rawDescription: Python3 strange list reversal

description: Python3 strange list reversal


code: map(lambda x: x.strip(), s.split(";"))

rawDescription: repeating a section of a regular expression?

description: Repeating a section of a regular expression


code:
...
return row

rawDescription: Python method doesn't run in class

description: Python method doesn't run in class


code:
from django.shortcuts import render_to_response, redirect
from myApp.models import MyModel

def editForm(request, model_pk):
    model = MyModel.objects.get(pk=model_pk)
    return render_to_response('formUpdate.html',{ 'model' : model })

def updateForm(request, model_pk):
    model = MyModel.objects.get(pk=model_pk)
    model.firstname = request.POST['firstname']
    model.lastname = request.POST['lastname']
    model.save()
    return redirect('home', message='your name has been updated')

rawDescription: django poplulate html form

description: Django poplulate html form


rawDescription: Best way to get last entries from Pandas data frame

description: Get last entries from Pandas data frame


rawDescription: round exponential float to 2 decimals

description: Round exponential float to 2 decimals


rawDescription: Checking for unique output in Python

description: Checking for unique output in Python


rawDescription: re match a pattern

description: Re match a pattern


rawDescription: Python Mulitprocessing

description: Python Mulitprocessing


code:
def evenlist(lst,y):
    return all(int(x) % y == 0 for x in lst)

rawDescription: In python, how can I can I code this sense: "when true for all members of the list, do this." [Solved]


code:
def map(user, item, score):
  emit(key=user, value=(score, item))

def compareValues(value1, value2):
  return -1 * compare(value1.score, value2.score)

def reduce(key, values):
  emit(key, values[0:5])

rawDescription: map-reduce to construct recommendation list

description: Map-reduce to construct recommendation list


code: country_ids = City.objects.values_list('city_country_id', flat=True).filter(id__in=list_cities)

rawDescription: How to retrieve elements that have the same foreign key from a list?

description: Retrieve elements that have the same foreign key from a list


code: city_found = find_city(cities, state)

rawDescription: python underscores: learn python the hard way exercise 40

description: Python underscores: learn python the hard way exercise 40


rawDescription: Is there ready to use multilingual string field for MongoEngine?


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.canvas = tk.Canvas(self, width=400, height=400)
        self.canvas.pack(fill="both", expand=True)

        self.canvas.bind("<1>", self.on_click)

    def on_click(self, event):
        self.draw_piece(event.x, event.y)
        self.after(2000, self.draw_piece, event.x+40, event.y+40, "green")

    def draw_piece(self, x, y, color="white"):
        self.canvas.create_oval(x-10, y-10, x+10, y+10, outline="black", fill=color)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How to call a function with delay in tkinter?

description: Call a function with delay in tkinter


code: soup.select('div ul.main li p.class_label + p')[0].text

rawDescription: Python : Extract HTML content

description: Python : Extract HTML content


rawDescription: Separate a set of sublists from within a list by a given element of a sublist


rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


code:
contains, position = 'A', 3
where = ["strpos(word, '%s') = %s" % (contains, position)]
Word.objects.filter(length = 4, word__contains = contains).extra(where = where)

rawDescription: Django DB design to glob words quickly

description: Django DB design to glob words quickly


code:
ArrayType = ctypes.c_double*DataLength.value
addr = ctypes.addressof(Data.contents)
a = np.frombuffer(ArrayType.from_address(addr))

rawDescription: How to convert pointer to c array to python array

description: Convert pointer to c array to python array


code:
import matplotlib.pyplot as plt

# tally = Counter({'H': 52, 'T': 48})

plt.bar(range(len(tally)), tally.values(), width=0.5, align='center')
plt.xticks(range(len(tally)), ['H', 'T'])
plt.show()

rawDescription: Tallying the outcome of a coin flip

description: Tallying the outcome of a coin flip


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

# insert actual data here...
Z = np.loadtxt('mslp.txt',delimiter=',')
X,Y = np.meshgrid(np.linspace(0,300000,Z.shape[1]),np.linspace(0,200000,Z.shape[0]))
p1,p2 = 1006,1018

# this is almost the same as the original, although it will produce
# [p1, p1+2, ...] instead of `[Z.min()+n, Z.min()+n+2, ...]`
levels = np.arange(np.maximum(Z.min(),p1),np.minimum(Z.max(),p2),2)

#control
plt.figure()
CS = plt.contour(X, Y, Z, colors='b', linewidths=2, levels=levels)

#modified
plt.figure()
CS = plt.contour(X, Y, Z, colors='b', linewidths=2, levels=levels)

for level in CS.collections:
    for kp,path in reversed(list(enumerate(level.get_paths()))):
        # go in reversed order due to deletions!

        # include test for "smallness" of your choice here:
        # I'm using a simple estimation for the diameter based on the
        #    x and y diameter...
        verts = path.vertices # (N,2)-shape array of contour line coordinates
        diameter = np.max(verts.max(axis=0) - verts.min(axis=0))

        if diameter<15000: # threshold to be refined for your actual dimensions!
            del(level.get_paths()[kp])  # no remove() for Path objects:(

# this might be necessary on interactive sessions: redraw figure
plt.gcf().canvas.draw()
plt.show()

rawDescription: How to remove/omit smaller contour lines using matplotlib

description: Remove/omit smaller contour lines using matplotlib


code:
line=file.readline() # stores the str line from the file
ine = '[' + line + ']'
line = line.replace('][', '],[')
line = ast.literal_eval(line)

rawDescription: String to list of list

description: String to list of list


rawDescription: Python console doesn't get updated (with PyCharm)


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

sent = "Hi, how are you?"
subent = " ".join(["".join(map(spubeak, re.split("(\W+)", nonblank)))
                   for nonblank in sent.split()])
print('"{}" → "{}"'.format(sent, subent))

rawDescription: Python: How to prepend the string 'ub' to every pronounced vowel in a string?


code: df.max() > 0

rawDescription: Python Pandas drop columns based on max value of column


rawDescription: Correct usage of \D in python?

description: Correct usage of \D in python


code:
from tkinter import *
from subprocess import call

pyprog = 'tem2.py'
def callpy(): call(['python', '-i', pyprog] )

root = Tk()
Button(root, text='Run', command=callpy).pack()
root.mainloop()

rawDescription: tkinter button to open new window and run script

description: Tkinter button to open new window and run script


code:
import builtins
range = builtins.range

rawDescription: How to restore a builtin when parameter has same name?

description: Restore a builtin when parameter has same name


code:
ax = sns.barplot(data=r, x='method', y='timing')
ax.tick_params(labelsize=16)
[ax.annotate(str(round(p.get_height(),2)), (p.get_x() + 0.2, p.get_height() + 5)) for p in ax.patches]
ax.set_xlabel('indexing method', size=20)
ax.set_ylabel('timing (microseconds)', size=20)

rawDescription: pandas df.loc[z,x]=y how to improve speed?

description: Pandas df.loc[z,x]=y how to improve speed


code:
def firstMonthInQuarter(month):
    return month - (month - 1) % 3

rawDescription: First month of quarter given month in Python


code: itemDict = {item[0]: item[1:] for item in items}

rawDescription: Python: List of lists to dictionary

description: Python: List of lists to dictionary


code:
def date_list(start, end):
    start = datetime.date(start.year, start.month, 1)
    end = datetime.date(end.year, end.month, 1)
    dates = [dt for dt in rrule(MONTHLY, dtstart=start, until=end)]
    return dates

rawDescription: How to create a date range until some date inclusive with python dateutils?

description: Create a date range until some date inclusive with python dateutils


code:
import xml.etree.cElementTree as et
some_number = int(input('input a number: '))
el = et.Element("number").text = some_number
tree = et.ElementTree(el)
tree.write("number.xml")

rawDescription: How to save input from python to XML

description: Save input from python to XML


code:
_offsets = (3, 1, 1, 1, 1, 1, 2)
def prev_weekday(adate):
    return adate - timedelta(days=_offsets[adate.weekday()])

rawDescription: Previous weekday in Python

description: Previous weekday in Python


rawDescription: Complex regex in Python

description: Complex regex in Python


code:
class Page(webapp2.RequestHandler):
    def get(self,page):
        numberOfPages = int(page)
        records_query = db.GqlQuery("SELECT * FROM Record order by date desc")
        records = records_query.fetch(numberOfPages * 10)
        records = records[((numberOfPages- 1) * 10):]
        if len(records) > 0:
            template_values = {
             'records': records,
            }
            path = os.path.join(os.path.dirname(__file__), 'posts.html')
            self.response.out.write(template.render(path, template_values))

rawDescription: How to asyncronously load posts from DB to django template on google app engine?

description: Asyncronously load posts from DB to django template on google app engine


code:
ax = subplot(1,1,1, projection="polar", aspect=1.)
ax.pcolormesh(theta, r, Z)

rawDescription: Problem with 2D interpolation in SciPy, non-rectangular grid


code:
class Dynamic:
    def __getitem__(self, name):
        return getattr(self, name)

    def __setitem__(self, name, value):
        setattr(self, name, value)

    def __delitem__(self, name):
        delattr(self, name)

    def __iter__(self):
        return self.__dict__.__iter__()

rawDescription: Dynamic objects in Python like in AS3

description: Dynamic objects in Python like in AS3


code:
from django.contrib.auth.models import User
from django.db import models

class Relationship(models.Model):
    from_user = models.ForeignKey(User, related_name='from_users')
    to_user = models.ForeignKey(User, related_name='to_users')

rawDescription: Django - access foreign key data in an annotated query


code: np.argwhere(x == np.min(x))

rawDescription: Numpy: get the column and row index of the minimum value of a 2D array


code:
def find_letter(item):
    lst = []
    item=list(item) #convert your string to list
    for index,letter in enumerate(item):
        if letter=='a':
            lst.append(letter) # add 'a' to your empty list
            item.pop(index) # remove 'a' from the original string
        item="".join(item) # convert back your list to a string
    return lst,item

rawDescription: Append/pop specific element of a string to the list when iterating over it


rawDescription: Split list into smaller lists

description: Split list into smaller lists


code:
import os
import sys

def main(discs):
    a, b, c = list(range(discs, 0, -1)), [], []
    line = '-' * len(repr(a))
    print(a, b, c, sep='\n')
    for source, destination in towers_of_hanoi(discs, a, b, c):
        destination.append(source.pop())
        print(line, a, b, c, sep='\n')

def towers_of_hanoi(count, source, via, destination):
    if count > 0:
        count -= 1
        yield from towers_of_hanoi(count, source, destination, via)
        yield source, destination
        yield from towers_of_hanoi(count, via, source, destination)

def trace(start, *names):
    def tracefunc(frame, event, arg):
        if event == 'call':
            code = frame.f_code
            name = code.co_name
            if name in names:
                level = -start
                args = ', '.join(repr(frame.f_locals[name]) for name in
                                 code.co_varnames[:code.co_argcount])
                while frame:
                    frame = frame.f_back
                    level += 1
                print('{}{}.{}({})'.format(
                    ' ' * (level * 4),
                    os.path.splitext(os.path.basename(code.co_filename))[0],
                    name, args))
                return tracefunc
    sys.settrace(tracefunc)

if __name__ == '__main__':
    trace(3, 'main', 'towers_of_hanoi')
    main(3)

rawDescription: How can I step to use the python debugger to break at every function call?

description: Step to use the python debugger to break at every function call


code:
class Detail:
    def __str__(self):
        return "string shown to users (on str and print)"
    def __repr__(self):
        return "string shown to developers (at REPL)"

rawDescription: How to print an object in Python

description: Print an object in Python


code:
PagerDuty.objects.create(
    user=User.objects.get(username='bob'),  # or create a new user
    mobile='...',
    # policy=PagerDutyPolicy.objects.get(policy_name='Team 1')  # or..
    policy=PagerDutyPolicy.objects.get(id=232)
)

rawDescription: django object get two fields into a list from a model

description: Django object get two fields into a list from a model


code: friends["John"][places["NY"]] += 1

rawDescription: Most efficient way to populate dictionary keys with dictionary


code:
def neighbor_min(a):
    rows, cols = a.shape
    ret = np.empty_like(a)

    # Fill in the center
    win_a = as_strided(a, shape=(m-2, n, 3),
                       strides=a.strides+a.strides[:1])
    win_a = win_a.min(axis=2)
    win_a = as_strided(win_a, shape=(m-2, n-2, 3),
                       strides=win_a.strides+win_a.strides[1:])
    ret[1:-1, 1:-1] = win_a.min(axis=2)

    # Fill the top, bottom, left and right borders
    win_a = as_strided(a[:2, :], shape=(2, cols-2, 3),
                       strides=a.strides+a.strides[1:])
    ret[0, 1:-1] = win_a.min(axis=2).min(axis=0)
    win_a = as_strided(a[-2:, :], shape=(2, cols-2, 3),
                       strides=a.strides+a.strides[1:])
    ret[-1, 1:-1] = win_a.min(axis=2).min(axis=0)
    win_a = as_strided(a[:, :2], shape=(rows-2, 2, 3),
                       strides=a.strides+a.strides[:1])
    ret[1:-1, 0] = win_a.min(axis=2).min(axis=1)
    win_a = as_strided(a[:, -2:], shape=(rows-2, 2, 3),
                       strides=a.strides+a.strides[:1])
    ret[1:-1, -1] = win_a.min(axis=2).min(axis=1)

    # Fill the corners
    ret[0, 0] = a[:2, :2].min()
    ret[0, -1] = a[:2, -2:].min()
    ret[-1, -1] = a[-2:, -2:].min()
    ret[-1, 0] = a[-2:, :2].min()

    return ret

rawDescription: Numpy: fast calculations considering items' neighbors and their position inside the array


rawDescription: Efficiently build a graph of words with given Hamming distance


code:
child.py
s = input()
s = s.upper()
print(s)

rawDescription: Python3 subprocess communicate example

description: Python3 subprocess communicate example


rawDescription: Cannot find python xlrd version

description: Cannot find python xlrd version


code: pd.concat(get_sumdf(area_tab) for area_tab in areas_tabs)

rawDescription: Create a summary Pandas DataFrame using concat/append via a for loop


code:
arr1 = np.array([dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 2)])
arr2 = np.array([1, 2, 3])
df = pd.DataFrame({'date': arr1, 'value': arr2})
df
df.drop_duplicates('date')

rawDescription: Find Unique Dates in Numpy Datetime Array


rawDescription: Modify csv files with Python

description: Modify csv files with Python


code: df[(df['days']>=from_day) & (df['days'] < from_day + plus_days)].data

rawDescription: Select day of month as start of date range using Pandas


code:
class Nonce(models.Model):
    """ Required for OpenID functionality """
    server_url = models.CharField(max_length=255)
    timestamp = models.IntegerField()
    salt = models.CharField(max_length=40)

    def __unicode__(self):
        return u"Nonce: %s for %s" % (self.salt, self.server_url)

class Association(models.Model):
    """ Required for OpenID functionality """
    server_url = models.TextField(max_length=2047)
    handle = models.CharField(max_length=255)
    secret = models.TextField(max_length=255) # Stored base64 encoded
    issued = models.IntegerField()
    lifetime = models.IntegerField()
    assoc_type = models.TextField(max_length=64)

    def __unicode__(self):
        return u"Association: %s, %s" % (self.server_url, self.handle)

rawDescription: Django + Google Federated Login

description: Django + Google Federated Login


code:
from package import ClassName
x = ClassName()

rawDescription: Import a module in Python

description: Import a module in Python


code:
d = shelve.open('filename')

d = hash['name']

rawDescription: Efficient way to store hash in a file

description: Efficient way to store hash in a file


code:
import hello_world
import print_text

rawDescription: py.test - How to inherit other tests

description: Py.test - How to inherit other tests


code:
class Category(Base):
    __tablename__ = 'category'

    @property
    def gifts(self):
        q = Gift.query.join(SubCategory).filter(SubCategory.category == self)
        return q.all()

rawDescription: How to access child of child from parent in sqlalchemy?

description: Access child of child from parent in sqlalchemy


code:
def Meta_Animal(name,*args,**kwargs):
    # I use class naming on this because it always produces a class
    if name.lower() in ['baily','daisy']:
        return Cat(name,*args, **kwargs)
    elif name.lower() in ['rocky']:
        return Dog(name,*args, **kwargs)
    else:
        raise NotImplementedError("That name is not an animal")

rawDescription: Most pythonic to call classes based on some value?


code:
from flask import Flask, render_template, abort
from flask.ext.mongokit import MongoKit, Document

from .home.views import mod as home_blueprint
from .users.views import mod as user_blueprint
from .forums.views import mod as forum_blueprint

def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Register blueprints
    app.register_blueprint(home_blueprint)
    app.register_blueprint(user_blueprint, url_prefix="/users")
    app.register_blueprint(forum_blueprint, url_prefix="/forums")

    db = MongoKit(app)

    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html')

    @app.errorhandler(500)
    def internal_error(exception):
        return "Some internal error has taken place.  Alert somebody!"

    return app,db

# Make sure you are calling create_app func below:
(app,db) = create_app()

rawDescription: Implementing MVC in Python? (using Flask and MongoKit)


code:
class Foo( object ):
        def __init__(self):
                print("foo init")
                self.foo_func()
        def foo_func(self):
                print("making bar")
                self.x = Bar()
        def foo_bar_func(self):
                self.x.bar_func()

class Fighters( Foo ):
        def __init__(self):
                print("fighters init")
                Foo.__init__(self)
        def func1(self):
                Foo.some_attribute
        def func2(self):
                Foo.someother_func()

class Bar(object):
        def __init__(self):
                print("bar init")
        def bar_func(self):
                #some stuff here
                print("bar bar_func")

rawDescription: Python: multi level inheritance

description: Python: multi level inheritance


rawDescription: Python - Group arrays by limiting number of elements in sub array


code:
def copy_file(option):
    infile_name= input("Please enter the name of the file to copy: ")
    infile = open(infile_name, 'r')
    outfile_name = input("Please enter the name of the new copy:  ")
    outfile = open(outfile_name, 'w')
    slist = infile.readlines()
    if option == 'statistics':
        for line in slist:
            outfile.write(line)
        infile.close()
        outfile.close()
        result = []
        blank_count = slist.count('\n')
        for item in slist:
            result.append(len(item))
        print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format(
            len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count)))

copy_file('statistics')

rawDescription: blank file while copying a file in python

description: Blank file while copying a file in python


code:
from shutil import copytree, ignore_patterns
ignore_func = ignore_patterns('.DS_Store', '*.txt')  # ignore .DS_Store and *.txt files
copytree('/path/to/dir/', '/other/dir', ignore=ignore_func)

rawDescription: Copying recursively files in Python

description: Copying recursively files in Python


code:
def ohlcsum(df):
    df = df.sort()
    return {
       'Open': df['Open'][0],
       'High': df['High'].max(),
       'Low': df['Low'].min(),
       'Close': df['Close'][-1],
       'Volume': df['Volume'].sum()
      }

rawDescription: Converting OHLC stock data into a different timeframe with python and pandas


code:
# if gathered in __init__
import mypackage
this_image = mypackage.png(...)
that_image = mypackage.jpeg(...)

rawDescription: Avoid double typing class names in python


code:
if item2:
    if item1["age"] != item2[0]["age"]:
        age_diff.append(item1["name"])
else:
    add.append(item1["name"])

rawDescription: Python - Log the changes needed for one list of dictionaries to be updated to another


code:
cw = CsvWriter(dataList)
for ou in many_outfiles:
  cw.doWrite(ou)

rawDescription: How to create a class from function

description: Create a class from function


code: print("\n".join(" ".join(map(str, t)) for t in algorithm("1 0^ 1* 1")))

rawDescription: how to implement this algorithm in python?

description: Implement this algorithm in python


code:
import csv
from collections import defaultdict

result = defaultdict(dict)
fieldnames = {"ID"}

for csvfile in ("file1.csv", "file2.csv", "file3.csv"):
    with open(csvfile, newline="") as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            id = row.pop("ID")
            for key in row:
                fieldnames.add(key) # wasteful, but I don't care enough
                result[id][key] = row[key]

rawDescription: Combining multiple CSV file into a single one