code:
DBXREFS:  ['BioProject:PRJNA42399 BioSample:SAMN02603066']
ANNOTATIONS:  ['comment', 'sequence_version', 'source', 'taxonomy', 'keywords', 'references', 'accessions', 'data_file_division', 'date', 'organism', 'gi']
FEATURES:  [SeqFeature(FeatureLocation(ExactPosition(0), ExactPosition(1001), strand=1), type='source'), SeqFeature(FeatureLocation(BeforePosition(0), ExactPosition(471), strand=1), type='gene'), SeqFeature(FeatureLocation(BeforePosition(0), ExactPosition(471), strand=1), type='CDS')]

rawDescription: How to create genbank flat file

description: Create genbank flat file


code:
def sim_time(self, record, datefmt=None):
    return datetime.datetime(2000,1,2,3,4,5,678).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3]

import logging
logging.Formatter.formatTime = sim_time

rawDescription: Python logging: override log time

description: Python logging: override log time


code:
# Input array
# Setup output array and use original loopy code
# Proposed approach
# Verify results

rawDescription: Numpy: argmax over multiple axes without loop


rawDescription: Matrix addition using triples representation in Python


code:
from __future__ import division
import numpy as np

test1 = np.random.random((5,5))
irow, icol = np.ogrid[0:test1.shape[0], 0:test1.shape[1]]
# could also do np.mgrid[[slice(0,d) for d in test1.shape]] to get
# a list of images for all dimensions

# to use iradius and itheta we need to get icol, irow centered
irow_centered = irow - test1.shape[0] / 2.0
icol_centered = icol - test1.shape[1] / 2.0

iradius = (icol_centered**2 + irow_centered**2)**0.5
itheta = np.arctan2(irow_centered, icol_centered)

rawDescription: Is there any python (numpy) synonym to i-variables (e.g., irow, iradius, itheta, etc.) in DM scripting?


rawDescription: Python: Why this tuple is printing the result and "None"? Also: Is there a better way to achieve the result?


rawDescription: Check number of columns numpy array that returns 1 if is a 1-dimensional array


code:
df.groupby(['link', 'type']).size().unstack(1)
df.groupby(['link', 'type']).size().unstack(1).fillna(0)

rawDescription: python: Working with pandas. Getting counts

description: Python: Working with pandas. Getting counts


code:
from PySide import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        super(Window, self).__init__()
        self.table = QtGui.QTableView(self)
        model =  QtGui.QStandardItemModel(rows, columns, self.table)
        for row in range(rows):
            for column in range(columns):
                item = QtGui.QStandardItem('(%d, %d)' % (row, column))
                model.setItem(row, column, item)
        self.table.setModel(model)
        self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self.table.installEventFilter(self)

    def eventFilter(self, source, event):
        if (source is self.table and
            event.type() == QtCore.QEvent.KeyPress and
            event == QtGui.QKeySequence.Copy):
            return True
        return super(Window, self).eventFilter(source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(5, 5)
    window.setGeometry(600, 300, 600, 250)
    window.show()
    sys.exit(app.exec_())

rawDescription: Disallow copy/paste in QTableView in pyside


code:
import itertools as IT
dates, vals = IT.izip(*data)
s = pd.Series(vals, index=dates)

rawDescription: python key value list to panda series

description: Python key value list to panda series


rawDescription: generate items from dictionary

description: Generate items from dictionary


code:
import csv
from itertools import izip_longest

with open(filename, 'wb') as outf:
    writer = csv.writer(outf)
    writer.writerows(izip_longest(x, y, fillvalue=''))

rawDescription: How to combine two list in to one with two columns

description: Combine two list in to one with two columns


rawDescription: Help using *args in tuple matching Python function


code:
import xlwt

book = xlwt.Workbook()
sheet = book.add_sheet("foobar")

# Put the header in the appropriate cells...
style = xlwt.easyxf('pattern: pattern solid, fore-colour yellow')
for col, text in enumerate(header):
    sheet.write(0, col, text, style)

# Now, let's write the contents

for row, data_in_row in enumerate(data):
    for col, text in enumerate(data_in_row):
        sheet.write(row + 1, col, text)

book.save("example.xls")

rawDescription: Looping through a list of hosts and commands in Paramiko and store the result in excel with column headers


code:
class Cursor(object):
    '''
    This is the object you use to interact with the database.
    '''
    ...
    def __iter__(self):
        return iter(self.fetchone, None)

rawDescription: Proper way to use PyMySql in a memory efficient generator


code:
def gradeScores(FinalGrade):
    if FinalGrade >= 90 and FinalGrade <= 100:
        return("You received an A")

    elif FinalGrade >= 80 and FinalGrade < 90:
        return("You received a B")

    elif FinalGrade >= 70 and FinalGrade < 80:
        return("You received a C")

    elif FinalGrade >= 60 and FinalGrade < 70:
        return("You received a D")

    else:
        return("Sorry, you received an F")

rawDescription: Calculate final letter grade in Python given 4 test scores


code:
class Foo:
    def __init__(self):
        self.a = 3
        self.b = 4
        self.c = 5

    def __getitem__(self, index):
        if index == 0:
            return self.a
        elif index == 1:
            return self.b
        elif index == 2:
            return self.c
        else:
            raise KeyError("Index must be 0, 1 or 2")

rawDescription: Access class variables with __repr__()

description: Access class variables with __repr__()


rawDescription: Python - create mask of unique values in array


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

# random data
N = 37
x = np.random.normal(loc=3.5, scale=1.25, size=N)
y = np.random.normal(loc=3.4, scale=1.5, size=N)
c = x**2 + y**2

# now sort it just to make it look like it's related
x.sort()
y.sort()

fig, ax = plt.subplots()
ax.scatter(x, y, s=25, c=c, cmap=plt.cm.coolwarm, zorder=10)

rawDescription: Adding y=x to a matplotlib scatter plot if I haven't kept track of all the data points that went in


code: num = sum(2**i for i, bit in enumerate(my_str) if bit == '1')

rawDescription: Binary to Decimal (mathematics way)

description: Binary to Decimal (mathematics way)


code:
"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

rawDescription: What to put in a python module docstring?


code: merged.loc[merged.indicator].pivot_table(values='value', index='index', columns=['items'], aggfunc=sum)

rawDescription: Pandas MultiIndex Operations on Sub-Index


code:
a = [[1,2,3],[4,5,6]]
from operator import itemgetter
map(itemgetter(0,2), a)

rawDescription: Get non-contiguous columns from a list of lists


code: o

rawDescription: Slicing through a grid in a spiral motion, returning xMin, xMax, yMin, yMax for each slice


code: Tkinter.Button (RegBox, text="Back", command=back).pack()

rawDescription: Register username and password

description: Register username and password


rawDescription: Timer Object in Python or anything like that


code: ['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]

rawDescription: List of dictionaries - how to format print output


code: return result[0] if result is not None else None

rawDescription: Unpack a tuple with a single element or return None if tuple is None


code: a == b

rawDescription: Sure-fire, simple way to compare two complex objects in Python?


code:
x = MyStr("hallo world")
x.upper()
x.split()

rawDescription: How to add my own method to the built-in str type?

description: Add my own method to the built-in str type


code: ['this is string constant + some numbers and " is also included ', 'and another "line" ']

rawDescription: Extracting string constant from source code in a string using regular expressions in Python


code:
import os
from nose.plugins import Plugin

case_options = None

class test_args(Plugin):
    """
    Attempting to add command line parameters.
    """
    name = 'test_args'
    enabled = True

    def options(self, parser, env=os.environ):
        super(test_args, self).options(parser, env)
        parser.add_option("--hostname",
                    action="store",
                    type="str",
                    help="The hostname of the server")

    def configure(self, options, conf):
        global case_options
        case_options = options

rawDescription: How to access plugin options within a test? (Python Nose)

description: Access plugin options within a test? (Python Nose)


code:
foo = ""
while (looping):
    #find n
    foo += str(n) + " "
outFile.write(foo)

rawDescription: How do i write the integers that in this file to the mynumbers.txt file?

description: Write the integers that in this file to the mynumbers.txt file


code:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel

class MyModel(models.Model):
    # other fields
    image = MyCustomImageField(sizes=(('small', '300x300'), ('large', '500x500')))

rawDescription: Django Save Image on different model fields


code:
reports_by_status = {'new': [],
     'read': [],
     'accepted': [],
     'deined': [],    # denied?
     'resubmitted': []}

for report in reports:
    d[report.status].append(report)

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
mock_filter_get_ids = Mock()
mock_filter_ids = Mock()
mock_model.objects.filter.side_effect = [mock_filter_get_ids, mock_filter_ids]
mock_filter_get_ids.filter.return_value.values_list.return_value.allow_filtering_return_value = [Mock_id]
mock_filter_ids.limit.return_value = mock_dict

rawDescription: Mock same method with different return value called twice in a function in python


code:
import os

print("starting script....\n")
link = raw_input('add link\n')
name = name = raw_input('add the name with flv extension\n')
command = 'wget -O ' + name + ' $(youtube-dl -g ' + link + ' )'
os.system(command)

rawDescription: Building a string and running it in terminal python


rawDescription: Python Sockets use function instead of global socket call


code:
for i in range(len(a)):
     lister.append(int(a[i]))
return sum(lister) % 10 == 0 or sum(lister) == 0

rawDescription: Python efficiency query

description: Python efficiency query


rawDescription: References and copies in python

description: References and copies in python


rawDescription: Python: Creating list of subarrays

description: Python: Creating list of subarrays


code:
fig, ax = plt.subplots()
ax.loglog(np.logspace(0, 5), np.logspace(0, 5)**2)
ax.xaxis.set_major_formatter(matplotlib.ticker.LogFormatterExponent())

rawDescription: What is the correct way to replace matplotlib tick labels with computed values?


code:
class Profile(BeautifulSoup):
    def __init__(self, page_source):
        super().__init__(page_source)
        self._cache = {}

    with_cache = cached_resource('_cache')

    @with_cache
    def username(self):
        return self.title.split(':')[0]

rawDescription: Is it okay for decorators to access private members of a class?


code:
item_id = Column(Integer, ForeignKey('items.id', onupdate='CASCADE', ondelete='CASCADE'))
item = relationship(Items, backref='attributes')

rawDescription: How to store and search list in SQLAlchemy?

description: Store and search list in SQLAlchemy


rawDescription: Sorting Multi-Index to full depth (Pandas)


code:
name_table = "test_table"  # name of the table that you want to get.

for line in old_db.iterdump():
    if name_table in line:
        query = line
        break

rawDescription: How to copy a sqlite table from a disk database to a memory database in python?

description: Copy a sqlite table from a disk database to a memory database in python


code:
myre = re.compile(r"\w{4,}", re.UNICODE)
myre.findall(u'Lorem, ipsum! dolör sit? amet...')

rawDescription: List of all words matching regular expression


code: d[["triggerid", "timestamp", "hw3"]]

rawDescription: csv parsing and manipulation using python

description: Csv parsing and manipulation using python


rawDescription: Dividing two columns of an unstacked dataframe


rawDescription: Short (and useful) python snippets

description: Short (and useful) python snippets


code: df['Visit_Number'] = df.groupby('IDs').cumcount() + 1

rawDescription: Time series analysis in pandas

description: Time series analysis in pandas


rawDescription: Selecting Subset of Pandas DataFrame

description: Selecting Subset of Pandas DataFrame


rawDescription: pandas replace zeros with previous non zero value

description: Pandas replace zeros with previous non zero value


rawDescription: Reducing the number of parameters a function takes in python


code:
from module1 import func

func(x)

rawDescription: Imporing a function from a module in a package in python


code: increasing_pixels = (myArray[0] <= myArray[1]) * (myArray[1] <= myArray[2])

rawDescription: python array processing: how to generate new values on pixel by pixel basis

description: Python array processing: how to generate new values on pixel by pixel basis


code: zeroMatrix = [[0] * Np for i in range(Np)]

rawDescription: How to preallocate a list of lists?

description: Preallocate a list of lists


rawDescription: Pandas: Combining values in multiple columns to create a new column


code:
from itertools import islice

def treatFiles(old_file, new_file, index, start, end):
    with open(old_file, 'r') as old, open(new_file, 'w') as new:
        sliced_file = islice(old, start - index, end - index)

        for line_number, line in enumerate(sliced_file, start=1):
            number, rest = line.split(',', 1)

            if number == '\n':
                new.write(line)
            else:
                new.write(str(line_number) + ',' + rest)

rawDescription: Improving a python code reading files

description: Improving a python code reading files


code: my_item = next((item for item in my_list if item['id'] == my_unique_id), None)

rawDescription: Python: get a dict from a list based on something inside the dict


code:
def myfunc():
    # do some stuff here
    # now we need some input...
    val = qt_input_dialogue()
    # do some more stuff here

rawDescription: Pause a python script until an event occurs without hanging/blocking the GUI


code:
def login(self, request):
    # check if login is correct and authenticate the user

    # redirect user
    return HttpResponseRedirect('/profiles/'+request.user.username)
    # OR better solution with reverse
    return HttpResponseRedirect(reverse('module.view_profile', args=(request.user.username,)))

rawDescription: django-profiles: How do I show the profile after login?

description: Django-profiles: How do I show the profile after login


rawDescription: numpy blit (copy part of an array to another one with a different size)

description: Numpy blit (copy part of an array to another one with a different size)


code:
links = driver.find_elements_by_xpath("//a[text() = 'View all hits in this text']")
for link in links:
   link.click()

rawDescription: Selenium in Python: Select the second element with given link text


code:
a = Object()
b = Object()
a.speed, b.speed
a.speed = 10
a.speed, b.speed

rawDescription: Changing variables in multiple Python instances


code:
a = []
b = []
c= []
for i, s in enumerate(lst):
    if s[6] == "A":
        a.append(i)
    elif s[6] == "B":
        b.append(i)
    elif s[6] == "C":
        c.append(i)

rawDescription: Python position of a character in a string in a list


code:
def comedy():
    print("comedy")

def political():
    print("political")

def philisophical():
    print("philisophical")

def tragedy():
    print("tragedy")

types = {"comedy":comedy,
         "political":political,
         "philisophical":philisophical,
         "tragedy":tragedy
        }

user_input = input()

types[user_input]()

rawDescription: How to choose between input in Python 3.2

description: Choose between input in Python 3.2


rawDescription: Getting the indices of the top k numbers by value in a numpy array?


rawDescription: Append elements of a set to a list in Python


rawDescription: How to decode a 'url-encoded' string in python

description: Decode a 'url-encoded' string in python


rawDescription: pandas: groupby and variable weights

description: Pandas: groupby and variable weights


code:
import myapp.main
import __main__

testing = vars(myapp.main) is not vars(__main__)

del myapp
del __main__

# import myapp.testing rather than myapp.main

rawDescription: Can I determine if an application is being run normally vs via a unittest in Python?

description: Determine if an application is being run normally vs via a unittest in Python


code:
i = 1
while (i<=64):
    print(i)
    i*=2

rawDescription: Modifying increment value in for loop

description: Modifying increment value in for loop


code:
def print_list(l,size):
    for n in range(0, len(l), size):
        values = [str(x[2]) for x in l[n:n+size]]
        print(' '.join(values))

rawDescription: Print list as array Python

description: Print list as array Python


code:
for name in files:
    if fnmatch.fnmatch(name, 'B.csv'):
        fileList.append(os.path.join(dirpath, name))
        break
else:
    for name in files:
        if fnmatch.fnmatch(name, 'A.csv'):
            fileList.append(os.path.join(dirpath, name))
            break

rawDescription: Searching recursively for files to add to list, but if one type of file is found ignore other type


rawDescription: How to zip lists in a list

description: Zip lists in a list


rawDescription: Selecting rows with a particualr year and month


code: total = sum(T)

rawDescription: Python, a sum() issue

description: Python, a sum() issue


code:
def get(self, key, default=None):
    """Return the value for key if key is in the dictionary, else default.

    :type key: T
    :type default: V | None
    :rtype: V
    """
    pass

rawDescription: How to create a method in Python

description: Create a method in Python


code:
from twisted.internet import reactor, protocol

PORT = 9000

class MyServer(protocol.Protocol):
    pass

class MyServerFactory(protocol.Factory):
    protocol = MyServer

factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()

rawDescription: Twisted server for multiple clients

description: Twisted server for multiple clients


code:
from __future__ import print_function
from itertools import imap, izip
print(*imap("".join,izip(*grid)),sep="\n")

rawDescription: How can I rotate this list of lists with python

description: Rotate this list of lists with python


code:
def clock_in_view(request):
    form = forms.ClockInForm()

    if request.method == 'POST':
        form = forms.ClockInForm(request.POST)
        if form.is_valid():
            try:
                driver = Driver.objects.get(driver_number=form.cleaned_data['driver_number'])
                time_in_instance = TimeClockIN()
                time_in_instance.timestamp = timezone.now()
                time_in_instance.driver = driver
                time_in_instance.save()
                messages.add_message(request, messages.SUCCESS,
                                    "Clocked IN")
                return HttpResponseRedirect(reverse('clockin'))
            except Driver.DoesNotExist:
                form = forms.ClockInForm()
    return render(request, 'clockinform.html', {'form': form})

rawDescription: ModelForm returning field is required, not saving to sqliteDB


code:
import wx
import math
from matplotlib import pyplot

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

        self.panel = wx.Panel(self)
        self.button1 = wx.Button(self.panel, label="Sine")
        self.button2 = wx.Button(self.panel, label="Cosine")

        self.button1.Bind(wx.EVT_BUTTON, self.DrawSine)
        self.button2.Bind(wx.EVT_BUTTON, self.DrawCosine)

        self.sizer = wx.BoxSizer()

        self.sizer.Add(self.button1)
        self.sizer.Add(self.button2)

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

    def Draw(self):
        x = [a*(math.pi/50) for a in range(100)]
        y = [self.f(a) for a in x]
        pyplot.plot(x, y)
        pyplot.grid(True, which='both', axis="both")
        pyplot.show()

    def DrawCosine(self, e):
        self.f = math.cos
        self.Draw()

    def DrawSine(self, e):
        self.f = math.sin
        self.Draw()

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

rawDescription: wxPython, PyQwt or C# for plotting graph and manually drawing lines on plot

description: WxPython, PyQwt or C# for plotting graph and manually drawing lines on plot


rawDescription: Python Tkinter Text/Scrollbar Widget not functioning as expected


code:
html = """
<body>
        <p>The prognosis of patients with rectal cancer has improved since the introduction of total mesorectal excision (TME) surgery [
            <xref ref-type="bibr" rid="CR1">1</xref>–
            <xref ref-type="bibr" rid="CR3">3</xref>]. Using this surgical technique the mesorectal compartment including the rectum and perirectal fat is completely excised by sharp dissection along the mesorectal fascia (MRF) [
            <xref ref-type="bibr" rid="CR1">1</xref>]. Additionally, large randomized trials have shown that neo-adjuvant therapy improves local tumor control even further, regardless of optimized surgical techniques [
            <xref ref-type="bibr" rid="CR3">3</xref>,
            <xref ref-type="bibr" rid="CR4">4</xref>]. The advances in rectal cancer treatment have provoked differentiated neo-adjuvant treatment strategies based on anatomical preoperative identifiable risk factors for local tumor recurrence as can be visualized with magnetic resonance imaging (MRI) [
            <xref ref-type="bibr" rid="CR5">5</xref>]. One of the most important risk factors is the tumor relationship to the MRF, which actually defines the surgical circumferential resection margin (CRM) in TME surgery [
            <xref ref-type="bibr" rid="CR6">6</xref>,
            <xref ref-type="bibr" rid="CR7">7</xref>]. Long courses of neo-adjuvant chemoradiation have emerged as the preferential treatment of patients with anticipated tumor invasion of the MRF on MRI in order to downstage/downsize the tumor and to obtain tumor free resection margins [
            <xref ref-type="bibr" rid="CR5">5</xref>].
            </p>

</body>
"""

import re
re.search('<xref ref-type="bibr" rid="CR3">3</xref>(.*)', a).group(1)

rawDescription: Extracting untagged text using beautifulsoup


code:
import codecs, threading, time
from functools import wraps

def log_time(logpath="log.txt", interval=5):

    def log_time_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            t = threading.Thread(target=func, args=args, kwargs=kwargs)
            log_entries = 0
            with codecs.open(logpath, "wb", "utf-8") as logfile:
               start_time = time.time()
               t.start()
               while t.is_alive():
                   elapsed_time = (time.time() - start_time)
                   if elapsed_time > interval * log_entries:
                       m, s = divmod(elapsed_time, 60)
                       h, m = divmod(m, 60)
                       logfile.write("Elapsed time: %2dh %2dm %2ds\n" %(h, m, s))
                       log_entries += 1
        return wrapper
    return log_time_decorator

rawDescription: Logging execution time with decorators

description: Logging execution time with decorators


code:
class Fruit:
    """ An Eatables Class"""
    def __init__(self, color="Black", shape="Round"): # Initailization
        self.color = color    # Set Class Variables to passed values
        self.shape = shape    # If no value passed, default to hard-coded ones.

Mango = Fruit("Raw Green", "Mangool")
# Above statement instantiates Class Fruit by passing variables as arguments.
# Thus, Mango is an **instance** of class **Fruit**

rawDescription: Creating instances in python

description: Creating instances in python


code: from __future__ import print_function

rawDescription: More elegant/Pythonic way of printing elements of tuple?


code:
import random

X = range(N)

random.seed() # uses system time to initialize random number generator, or you can pass in a deterministic seed as an argument if you want

# code to use to generate K pairs
A = random.sample(X,2*K) # now you have a list of 2*K unique elements from 0 to N-1
pairs = zip(A[0:K],A[K:(2*K)]) # now you have your pairs

rawDescription: getting the most 'diverse' set of pairs from a list in Python?

description: Getting the most 'diverse' set of pairs from a list in Python


code:
import sys

from twisted.internet import reactor, protocol
from twisted.python import log

log.startLogging(sys.stdout)

f = protocol.ClientFactory()
f.protocol = protocol.Protocol
reactor.connectTCP('localhost', 22, f)

g = protocol.ClientFactory()
g.noisy = False
g.protocol = protocol.Protocol
reactor.connectTCP('localhost', 25, g)

reactor.run()

rawDescription: Twisted starting/stopping factory/protocol less noisy log messages


code:
import socket
import sys

if __name__ == "__main__":
    sock = socket.socket()
    sock.bind(("localhost", 50839))
    sock.listen(1)

    client, address = sock.accept()

    buf = client.recv(1024)
    while (buf):
        sys.stdout.write(buf)
        buf = client.recv(1024)

    client.close()
    sock.close()

rawDescription: using python to send an image over TCP to c# server

description: Using python to send an image over TCP to c# server


code: pop = [[] for _ in range(popLen)]  # use xrange() in Python 2.x

rawDescription: Create sub-lists in lists in Python

description: Create sub-lists in lists in Python


code:
contourf(D1,cmap='Blues')
contourf(D2,cmap='Reds', alpha=0.66)
contourf(D2,cmap='Reds', alpha=0.33)

rawDescription: Combine multiple heatmaps in matplotlib

description: Combine multiple heatmaps in matplotlib


code:
import itertools
import numpy as np
from scipy.special import binom

def polynomial_features_with_cross_terms(X, order):
    """
    X: numpy ndarray
        Matrix of shape, `(n_samples, n_features)`, to be transformed.
    order: integer, default 2
        Order of polynomial features to be computed.

    returns: T, powers.
        `T` is a matrix of shape,  `(n_samples, n_poly_features)`.
        Note that `n_poly_features` is equal to:

           `n_features+order-1` Choose `n_features-1`

        See: https://en.wikipedia.org\
        /wiki/Stars_and_bars_%28combinatorics%29#Theorem_two

        `powers` is a matrix of shape, `(n_features, n_poly_features)`.
        Each column specifies the power by row of the respective feature,
        in the respective column of `T`.
    """
    n_samples, n_features = X.shape
    n_poly_features = int(binom(n_features+order-1, n_features-1))
    powers = np.zeros((n_features, n_poly_features))
    T = np.zeros((n_samples, n_poly_features), dtype=X.dtype)

    combos = itertools.combinations(range(n_features+order-1), n_features-1)
    for i,c in enumerate(combos):
        powers[:,i] = np.array([
            b-a-1 for a,b in zip((-1,)+c, c+(n_features+order-1,))
        ])

        T[:,i] = np.prod(np.power(X, powers[:,i]), axis=1)

    return T, powers

rawDescription: Scipy fitting polynomial model to some data


rawDescription: Downloading file to specified location with Selenium and python


code:
with open('path/to/input') as infile:
    answer = {}
    for line in infile:
        k,v = line.split()
        answer[k] = v

rawDescription: How to add to a dictionary through a text file

description: Add to a dictionary through a text file


code:
import numpy as np
import networkx as nx
b = np.matrix([[1,0,1],[0,1,1]])
r,s = b.shape
a = np.vstack( (np.hstack((np.zeros((r,r)),b)), np.hstack((b.T,np.zeros((s,s)) ))) )
G = nx.Graph(a)
G.edges()

rawDescription: Loading a biadjacency matrix in networkx


code:
data= """
B%2==1
N%2!=1
"""

rx = r"([A-Z]+)%(\d+)"

result = re.sub(rx, r"M(\1,\2)", data, 0, re.IGNORECASE | re.MULTILINE)

rawDescription: How do I write a regular expression to replace % by function?

description: Write a regular expression to replace % by function


code:
def prog_clock_func(list_of_times):
    for time in list_of_times:
        print(time[2:4])

prog_clock = ['3:10PM', '3:15']
prog_clock_func(prog_clock)

rawDescription: get the value from the strings in the list

description: Get the value from the strings in the list


code:
import jinja_filters

app = Flask(__name__)
app.jinja_env.filters['filter_name1'] = jinja_filters.filter_name1
app.jinja_env.filters['filter_name2'] = jinja_filters.filter_name2

rawDescription: How to import custom jinja2 filters from another file (and using Flask)?

description: Import custom jinja2 filters from another file (and using Flask)


rawDescription: printing a dictionary with specific format

description: Printing a dictionary with specific format


code:
s = "|Row 1|[[link|text|df[sdfl|kj]|foo]]|{{img|altText|{|}|bar}}|"
split_special(s)

rawDescription: Split string into list if separator is not enclosed


code:
[{'answer': 'SysteminfoScreen',
  'question': 'Fan offline information can be found on what Screen under General Menu? ',
  'correct_answer': 'SysteminfoScreen'},
 {'answer': 'qkview',
  'question': 'What is the tool for F5 BIGIP to get packet traces. ',
  'correct_answer': 'TCP Dump'},
 {'answer': 'Offline',
  'question': 'On a HTTP Health Monitor configuration. If Receive string and Disabling string matched and Reverse is enabled. What would be the status of pool members?',
  'correct_answer': 'Disabled'}]

rawDescription: Merge dictionaries from multiple lists in Python


code:
#get a list of the stopwords
stp = nltk.corpus.stopwords.words('english')

#from your text of words, keep only the ones NOT in stp
filtered_text = [w for w in text if not w in stp]

rawDescription: Fdist and top 10 function words

description: Fdist and top 10 function words


code:
def initializeGL(self):
    #    background color
    glClearColor(0,0.0,0,1)

    glEnable(GL_DEPTH_TEST)
    glShadeModel(GL_SMOOTH)
    glEnable(GL_NORMALIZE)
    glEnable(GL_CULL_FACE)

    #    lights settings
    glEnable( GL_LIGHTING )
    glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, 0 )
    glEnable( GL_LIGHT0 )
    light_pos_0 = np.array([0.0, 10.0, 10.0])
    glLightfv( GL_LIGHT0, GL_POSITION, light_pos_0 )
    glLightfv( GL_LIGHT0, GL_AMBIENT, [0.8, 0.8, 0.8, 1] )
    glLightfv( GL_LIGHT0, GL_DIFFUSE, [1, 1, 1, 0] )
    glLightfv( GL_LIGHT0, GL_SPECULAR, [1, 1, 1, 0] )

    #    camera
    self.camera = camera_view.View()
    #    viewing
    self.geometry()

rawDescription: modelview matrix not updated using pyopengl and pyqt

description: Modelview matrix not updated using pyopengl and pyqt


code: s = "".join(random.choice('ACUG') for x in xrange(3355))

rawDescription: Python: Random sequence

description: Python: Random sequence


rawDescription: random numbers with tkinter

description: Random numbers with tkinter


code:
import uuid

class Sentinel:
    def __init__(self):
        self.id = uuid.uuid4()

    def __eq__(self, other):
        if isinstance(other, Sentinel):
            return self.id == other.id

        return NotImplemented

rawDescription: Tell consumers to stop waiting for queue elements


rawDescription: How To Find Complex Roots of A Multivariate Polynomial Equation System (Python)


rawDescription: finding index of an item closest to the value in a list that's not entirely sorted

description: Finding index of an item closest to the value in a list that's not entirely sorted


code:
#Find values that are in range
in_range = [lo_lim1 <= v1 <= hi_lim1 and lo_lim2 <= v2 <= hi_lim2 for v1, v2 in zip(values1, values2)]

# code is unchanged from here
#Find runs of in-range values
runs = [sum(1 for _ in group) for v, group in groupby(in_range) if v]  # this is the same as yours

#Estimate total time spent in-range
total_time = sum(v if v > 1 else (Buffer_Value*sample_rate) for v in runs)

rawDescription: python generator expressions for two data sets

description: Python generator expressions for two data sets


code:
from datetime import datetime
import os

date = datetime.today().isoformat().split('T')[0]

mysql = "mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup-%s.sql" % date
gzip = "gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup-%s.gz" % date

os.popen3(mysql)
os.popen3(gzip)

rawDescription: Want to timestamp two files

description: Want to timestamp two files


rawDescription: How to scrape xml feed with xmlfeedspider

description: Scrape xml feed with xmlfeedspider


code:
# Set tolerance values for each column
tol = [1, 2, 10]

# Get absolute differences between a and b keeping their columns aligned
diffs = np.abs(np.asarray(a[:,None]) - np.asarray(b))

# Compare each row with the triplet from `tol`.
# Get mask of all matching rows and finally get the matching indices
x1,x2 = np.nonzero((diffs < tol).all(2))

rawDescription: Finding intersection of two matrices in Python within a tolerance?


code: list3 = [(l1[0], l1[1], l2) for l1, l2 in zip(list1, list2)]

rawDescription: Creating tuples of 3s

description: Creating tuples of 3s


code:
r = ","
x = ""
output = list()
import string

def find_word(filepath,keyword):
    doc = open(filepath, 'r')

    for line in doc:
        #Remove all the unneccessary characters
        line = line.replace("'", r)
        line = line.replace('`', r)
        line = line.replace('[', r)
        line = line.replace(']', r)
        line = line.replace('{', r)
        line = line.replace('}', r)
        line = line.replace('(', r)
        line = line.replace(')', r)
        line = line.replace(':', r)
        line = line.replace('.', r)
        line = line.replace('!', r)
        line = line.replace('?', r)
        line = line.replace('"', r)
        line = line.replace(';', r)
        line = line.replace(' ', r)
        line = line.replace(',,', r)
        line = line.replace(',,,', r)
        line = line.replace(',,,,', r)
        line = line.replace(',,,,,', r)
        line = line.replace(',,,,,,', r)
        line = line.replace(',,,,,,,', r)
        line = line.replace('#', r)
        line = line.replace('*', r)
        line = line.replace('**', r)
        line = line.replace('***', r)

        #Make the line lowercase
        line = line.lower()

        #Split the line after every r (comma) and name the result "word"
        words = line.split(r)

        #if the keyword (also in lowercase form) appears in the before created words list
        #then append the list output by the whole line in which the keyword appears

        global output
        if keyword.lower() in words:
            output.append(line)

    return output

rawDescription: Empty output after appending a list

description: Empty output after appending a list


code:
with open(filename) as fin, tempfile.NamedTemporaryFile(delete=False) as fout:
    for line in fin:
        fout.write(line[1:])
    outname = fout.name
os.remove(filename)
os.rename(outname, filename)

rawDescription: remove first char from each line in a text file

description: Remove first char from each line in a text file


code:
results = []
for i in range(1, 51):
    filename = 'hdf2.root.OM%02d' % i
    result = Fitter(filename, plot=False)
    results.append(result)

rawDescription: Loop a python script

description: Loop a python script


code:
with open('file.csv') as f:
    data = [[float(line[i:i+18]) for i in range(0, len(line), 18)] for line in f.readlines()]

rawDescription: Convert fixed-width, non-delimited float strings to comma separated values


code:
f1 = open('Test1.txt')
for line1 in f1:
    line1 = line1.strip()
    print(line1, end=" ")
    f2 = open('Test2.txt')
    for line2 in f2:
        line2 = line2.strip()
        line3 = line2.split(' ')
        if line1 == line3[0]:
            print(line3[1], end=" ")
    print()

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


code: new_dict = dict()

rawDescription: Creating a new dict in Python

description: Creating a new dict in Python


code: indexes[np.arange(a.size), inverse] = True

rawDescription: List of indices of every value

description: List of indices of every value


code:
set(['Bousfield G',
     'Bruner DW',
     'Burr GO',
     'Crawford GN',
     'Dong L',
     'Edwards PR',
     'Faber HK',
     'Fishbein M',
     'Gaffron H',
     'Gardner FT',
     'Gates RR',
     'Gould BS',
     'Greene HS',
     'Haas O',
     'Hatch MH',
     'Hill DK',
     'Howorth MB',
     'Hughes H',
     'Lake NC',
     'Lewis WH',
     'McClung CE',
     'Myers J',
     'Ratner B',
     'Ritter WE',
     'Rubin J',
     'Silverberg RJ',
     'Sumner FB',
     'Tytell AA'])

rawDescription: Counting number of elements in nested list


code:
func = input('>')  #raw_input on python2.x
function_dict[func]()

rawDescription: Using user input to call functions

description: Using user input to call functions


code:
cursor = conn.cursor()
cursor.execute('''
    select details.A.colA
    from main.A
    join details.A using ('key')
    where main.A.colB = 0 and main.A.colC = 1
    ''')

rawDescription: joining across databases with sqlite3 / pysqlite

description: Joining across databases with sqlite3 / pysqlite


code:
def lookup(data, id, age, age_offset=0.1):
    if id in data:
        return [value for x, value in data[id] if age <= x <= age+age_offset]
    else:
        return None

lookup(preprocessed, '1039', 68.0) # Note that I use floats for age
['42731,42781,V4501']

rawDescription: fetching values from dictionary. Range match on keys

description: Fetching values from dictionary. Range match on keys


rawDescription: What does int() function with 2 args do in Python


code:
# If available, use C implementation
try:
    from _heapq import *
except ImportError:
    pass

rawDescription: Python heapq - Python and C implementation? Which one is used?


code:
import matplotlib.pyplot as plt
fig, ax_arr = subplots(3, 1, sharex=True)

rawDescription: How can I remove xtics from an axis in matplotlib?

description: Remove xtics from an axis in matplotlib


code:
a.name
a.hostgroup
a.actions.split(',')
a.operations.split(',')

rawDescription: python - elegantly handle sequence of multiple arguments

description: Python - elegantly handle sequence of multiple arguments


code:
import selenium
selenium.__version__

rawDescription: How do I retrieve the version of Selenium currently installed, from Python

description: Retrieve the version of Selenium currently installed, from Python


code:
def union_size(sets):
    return len(set.union(*sets))

rawDescription: Setting Up A Recursive Function to Calculate Inclusion Exclusion in Python


code:
sent_tokenize("Hello SF Python. This is NLTK.")
["Hello SF Python.", "This is NLTK."]

rawDescription: Determine if a list of words is in a sentence?


code:
total = float(um(Counter(seq_record.seq).values()))
for key,val in sorted_dict.items():
    newval = round(val/total, 4)
    sorted_dict[key] = newval

rawDescription: Update the value of a dictionary with elements in the lists Python


code:
import numpy as np
ar.dtype.type == np.string_

rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


code:
temp = N
temp.next = N  # which means N.next = N
N = N.next     # but from above N = (N.next = N) -> N = N

rawDescription: merging two sorted linked lists into one linked list in python

description: Merging two sorted linked lists into one linked list in python


rawDescription: How to append a 3d list and print its contents?

description: Append a 3d list and print its contents


code:
class SomeBigClass():
    @staticmethod
    def swap_dict(instance_a, instance_b):
        instance_a.__dict__, instance_b.__dict__ = \
                instance_b.__dict__, instance_a.__dict__
    @classmethod
    def swap_slot(cls, instance_a, instance_b):
        values = []
        for attr in cls.__slots__:
            values.append(
                (attr,
                 getattr(instance_a, attr),
                 getattr(instance_b, attr),
                 ))
        for attr, val1, val2 in values:
            setattr(instance_a, attr, val2)
            setattr(instance_b, attr, val1)

rawDescription: Can I efficiently swap two class instances by swapping __dict__?

description: Efficiently swap two class instances by swapping __dict__


code: result

rawDescription: Create a Json from a tuple - python

description: Create a Json from a tuple - python


code:
def random_mix(seq_a, seq_b):
    iters = [iter(seq_a), iter(seq_b)]
    while True:
        it = random.choice(iters)
        try: yield it.next()
        except StopIteration:
            iters.remove(it)
            it = iters[0]
            for x in it: yield x

rawDescription: Random list with rules

description: Random list with rules


code:
line = proc.stdout.readline()
while '] Running application' not in line:
     line = proc.stdout.readline()

rawDescription: Using a Python script to start and stop the Google App Engine dev_appserver during continuous integration testing


rawDescription: Remove Part of String Before the Last Forward Slash


code:
tasks = [
   asyncio.ensure_future(alive()),
   asyncio.ensure_future(async_processing())
]
asyncio.get_event_loop().run_until_complete(asyncio.wait(tasks))

rawDescription: Python async websocket client with async timer


code:
import csv

file = 'yourcsv.csv'
found = False
username = input('Write your username: ')
password_csv = None
with open(file, newline='') as csvfile:
   reader = csv.reader(csvfile, delimiter=',')
   for row in reader:
      # row[0] is the first element, the username and row[1] the hash of the password
      if row[0] == username:
         password_csv = row[1]
         found = True
         break
if not found:
   print('The username is not in our DB.')

while True:
   passw = input('Let me your password: ')
   hash_passw = your_method_to_get_the_hash(passw)
   if hash_passw == password_csv:
      print('Congrats, you are logged.')
      break
   else:
      print('Wrong password dude, try again.')

rawDescription: Find password by username

description: Find password by username


code:
room = "|                     |"
chest = "[Chest]"
door = "Door"

rawDescription: How do I format code to print with the same width every time?

description: Format code to print with the same width every time


code:
def bag_of_words(words):
    """
    Change a document into a BOW feature vector represented by a dict object.
    """
    return dict([(word, True) for word in words])

def label_feats_from_corpus(corp, feature_detector=bag_of_words):
    """
    Change the corpus into a feature matrix. Sometimes the proceess is
    known as vectorization. The default is the use BOW features.
    """
    label_feats = defaultdict(list)
    for label in corp.categories():
        for fileid in corp.fileids(categories=[label]):
            feats = feature_detector(corp.words(fileids=[fileid]))
            label_feats[label].append(feats)
    return label_feats

def split_label_feats(lfeats, split=0.75):
    """
    Splits corpus into train and test portion.
    This module is used after using `label_feats_from_corpus`.
    """
    train_feats = []
    test_feats = []
    for label, feats in lfeats.iteritems():
        cutoff = int(len(feats) * split)
        train_feats.extend([(feat, label) for feat in feats[:cutoff]])
        test_feats.extend([(feat, label) for feat in feats[cutoff:]])
    return train_feats, test_feats

rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


code:
tier_d[test - 1] = data[summoners[test - 1]][0]['entries'][0]['leaguePoints']
tier_d[test - 1] = data[summoners[test - 1]][1]['entries'][0]['leaguePoints']

rawDescription: Navigate in Dictionaries

description: Navigate in Dictionaries


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

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


code:
reg = "ab11foo"

a,b,c = reg[:2],reg[2:4],reg[4:] # slice string into ll nn lll
# check a is all alpha characters, b is made up of 0123456789 and c is again alpha and length is correct
if all((a.isalpha(), b.isdigit(), c.isalpha(), len(c)== 3)):
       print("Valid reg")
else:
     print("Invalid reg")

rawDescription: Checking a string for a sequence of letters and numbers using values from a list (Python)


code:
def getPossibleSeats (line, row, num):
    if row != line[-1]:
        raise ValueError('Invalid row')

    for k, g in groupby(enumerate(line[:-1], 1), lambda x: x[1]):
        g = list(g)
        if k != '0' or len(g) < num:
            continue

        for i in range(len(g) - num + 1):
            yield ['{}{}'.format(row, s) for s, _ in g[i:i+num]]

rawDescription: Array item numbers for consecutive items


code: u'carbon    copolymers   \u066f III  \n      \u01e2  \u0714    \u0621  G\xe9otechnique  \n'

rawDescription: Remove all symbols while preserving string consistency


code:
x = ['  ROOT S . ', '  ROOT S ! ', '  ROOT is it true that S ? ', ' ', '  S   NP VP ', '  VP  Verb NP ', '  NP DT Noun ', '  NP NP PP ', '  PP Prep NP ', '  Noun Adj Noun ', ' ', '  Verb ate ', '  Verb wanted ', '  Verb kissed ', '  Verb understood ', '  Verb pickled ', ' ', '  DT the ', '  DT a ', '  DT  every ', ' ', '  Noun president ', '  Noun sandwich ', '  Noun pickle ', '  Noun chief of staff ', '  Noun floor ', ' ', '  Adj fine ', '  Adj delicious ', '  Adj perplexed ', '  Adj pickled ', ' ', '  Prep    with ', '  Prep on ', '  Prep under ', '  Prep    in ']

d = {}
for k, v in (s.lstrip().split(' ',1) for s in x if ' ' in s.lstrip()):
    if k in d:
        d[k]+='|' + v
    else:
        d[k]=v

rawDescription: List to Dictionary

description: List to Dictionary


code: parsedHtml = BeautifulSoup(pageContent, 'lxml')

rawDescription: Python 3: Can't properly encode and print a downloaded string with /xXX literals


code:
replace_dict = dict(one=1, two=2, three=3)
foo_list = foo.split(' ')
foo = ' '.join(replace_dict.get(k, k) for k in foo_list)

rawDescription: Shorten method chaining in Python variable


code: v = list(v)

rawDescription: how to pass a list as value and not as reference?

description: Pass a list as value and not as reference


code:
import urllib
urllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')

rawDescription: Python: saving image from web to disk

description: Python: saving image from web to disk


code:
words = ['Duration$', 'Noun$', 'Adjective$']
words = [word.rstrip("$") for word in words]
words
[word+"$" for word in words]

rawDescription: Removing last character from each element in array (Python)


rawDescription: Python IP Parsing

description: Python IP Parsing


code:
import logging
logger = logging.getLogger()
logger.debug('Heya')

rawDescription: Better logging system for entire package


code:
df = pd.read_clipboard(sep='\s\s+', header=None, parse_dates=[0], names=['Date', None])
df
df1 = df.set_index('Date')
df1

rawDescription: get previous value of pandas datetime index

description: Get previous value of pandas datetime index


rawDescription: python mysql in order number input to table id

description: Python mysql in order number input to table id


code:
## Rotate about the x-axis
library(rgl)
res <- turn3d(xs, f(xs))
plot3d(res, alpha=.5)
snapshot3d("temp.png")

rawDescription: Converting 2D images to 3D

description: Converting 2D images to 3D


rawDescription: Python merge lists

description: Python merge lists


rawDescription: How to convert pandas DataFrame result to user defined json format

description: Convert pandas DataFrame result to user defined json format


rawDescription: Operation on current, precedent, and succeeding element in a list


rawDescription: Reduce Two Pandas Series to a Single One


code:
team = ['Team C']

df[df.apply(lambda x: x.isin(team)).max(axis=1)]

rawDescription: modeling Game data in pandas

description: Modeling Game data in pandas


code: from file import classname

rawDescription: Per-class constants in Python

description: Per-class constants in Python


code:
index_wanted = [71, 102, 103, 179, 505, 506, 607]
from itertools import chain
df = DataFrame(np.random.randn(1000,2))

rawDescription: efficient way to find several rows above and below a subset of data

description: Efficient way to find several rows above and below a subset of data


code: return type(self)(p)

rawDescription: Can I let a superclass return reference to the "actual type"?

description: Let a superclass return reference to the "actual type"


code:
class APIAuth(requests.auth.AuthBase):
    def __call__(self, request):
        api_secret = settings.API_SHARED_SECRET
        api_key = settings.API_KEY
        request.prepare_url(request.url, dict(
            api_key=api_key,
            timestamp=int(time.time()*1000)))
        signature = base64.b64encode(hmac.new(
            api_secret,
            msg=unquote(request.full_url),
            digestmod=hashlib.sha256
            ).digest()).decode()
        request.headers['Authorization'] = "signature {0}".format(signature)
        return request

rawDescription: Modify request params with custom authentication


code:
df = df[["Date", "Time"] + list(df.columns[1:-1])]
df

rawDescription: Merge two CSV's with unique columns in python


rawDescription: Convert UTF-8 octets to unicode code points


code:
while True:
    for event in pygame.event.get():
        # Other event handling
        if V == 2:
            if event.type == event_500ms:
                if Blue == 1:
                    D.fill(BLUE)
                    Blue = 2
                elif Blue == 2:
                    D.fill(YELLOW)
                    Blue = 1
    # Other code

rawDescription: Flash event ceases upon input

description: Flash event ceases upon input


code:
class Guitarist(object):

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return "<{0}('{1}')>".format(self.__class__.__name__,
                                     "', '".join(self.__dict__.values()))

if __name__ == '__main__':
    print(Guitarist(fname='Jimi', lname='Hendrix', dob='11/27/1942'))

rawDescription: Python String Format args vs kwargs

description: Python String Format args vs kwargs


code:
my_input = input('Your phrase: ')
print(*reversed(my_input.split()))  # Python 3

rawDescription: Reverse an input using tuples Python

description: Reverse an input using tuples Python


code:
db.session.query(Item).\
    join(Order).join(Order.clients).\
    filter(Client.id == 42).\
    order_by(Item.timestamp)

rawDescription: How to do two-level many-to-many relationships?

description: Do two-level many-to-many relationships


code:
def do_something(attribute, objects):
    results = []
    for object in objects:
        if hasattr(object, attribute):
            results.append(getattr(object, attribute))
    return results

rawDescription: Passing a Django model attribute name to a function


code:
if __name__ == '__main__':
  instance = MyClass()

rawDescription: print to console in PyDev

description: Print to console in PyDev


code:
import re

df = pd.DataFrame({'col1':[3,4,5],'col2':['a,ben,c','a,r,ben','cat,dog'],'col3':[1,2,3]})

#In [220]: df
#Out[220]:
#   col1     col2  col3
#0     3  a,ben,c     1
#1     4  a,r,ben     2
#2     5  cat,dog     3

df['new'] = df.col2.apply(lambda x: re.sub(',?ben|ben,?', '', x))

#In [222]: df
#Out[222]:
#   col1     col2  col3      new
#0     3  a,ben,c     1      a,c
#1     4  a,r,ben     2      a,r
#2     5  cat,dog     3  cat,dog

rawDescription: How to write a return value of a function into new column of a pandas dataframe

description: Write a return value of a function into new column of a pandas dataframe


code: output

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

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


code:
uploads_url_patterns = patterns('',
    url(r'^uploads/view/(?P<file_name>[\w.]{0,256})$', ShowImageView.as_view(), name='show'),
)

rawDescription: Django URL Config - Match filename

description: Django URL Config - Match filename


code: partList = "".join([mylist[i] for i in indices])

rawDescription: Python lists: join list by index

description: Python lists: join list by index


code:
with file(os.path.join(os.dirname(__file__), "huge_static_data.json")) as in_f:
  something_large = json.load(in_f)

rawDescription: How to load an object into memory for entire django project to see?

description: Load an object into memory for entire django project to see


code:
def main():
    def f():
        nonlocal x
        x = input()
        return x
    x = ''
    print("Sin(" + f() + ")")

rawDescription: Input between print in python

description: Input between print in python


code:
df_new = df.reset_index()
df_new.groupby(['item_id']).X.agg(np.mean)

rawDescription: Indexing by row counts in a pandas dataframe


code:
def sum_of_squares_of_digits(value):
    return sum(int(c) ** 2 for c in str(value))

rawDescription: Python Sum of Squares Function

description: Python Sum of Squares Function


rawDescription: Getting name of attributes with Scrapy XPATH


code: start_urls = [str(get_url())]

rawDescription: Simple scrapy spider doesn't crawl

description: Simple scrapy spider doesn't crawl


code:
def read_file(name):
    with open(name) as in_fil:
        return [[item.strip() for item in l.rstrip().split(";")] for l in in_fil]

rawDescription: Generating a list of tuples and using it


rawDescription: Python - find average for columns with unique matching value in nested list


code: [' '.join(splitted_result)]

rawDescription: Splitting line on python

description: Splitting line on python


rawDescription: Python and numpy : subtracting line by line a 2-dim array from a 1-dim array


rawDescription: Applying a series of functions to a list


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

# an example graph type
def fig_barh(ylabels, xvalues, title=''):
    # create a new figure
    fig = plt.figure()

    # plot to it
    yvalues = 0.1 + np.arange(len(ylabels))
    plt.barh(yvalues, xvalues, figure=fig)
    yvalues += 0.4
    plt.yticks(yvalues, ylabels, figure=fig)
    if title:
        plt.title(title, figure=fig)

    # return it
    return fig

rawDescription: How to assign a plot to a variable and use the variable as the return value in a Python function

description: Assign a plot to a variable and use the variable as the return value in a Python function


code:
from datetime import datetime
a = datetime.strptime('26/01/12 23:50:32.123', '%d/%m/%y %H:%M:%S.%f')
a.microsecond

rawDescription: string to time with decimal seconds

description: String to time with decimal seconds


code:
for i in range(_your_number_of_classes_2_in_this_case):
    cl[5+i*8].set_linewidth(2.)

rawDescription: Styling of Pandas groupby boxplots

description: Styling of Pandas groupby boxplots


code: execfile(filename, globals, locals)

rawDescription: Alternative to execfile in Python 3?

description: Alternative to execfile in Python 3


rawDescription: Python Regular Expression for splitting key/value pairs separated by an equal sign when a value may or may not have quotes


rawDescription: Adding a tuple to a tuple of tuples

description: Adding a tuple to a tuple of tuples


rawDescription: Are class variables in the scope of instance methods or class methods?


code:
for z in lines:
    for index, l in enumerate(z):
        z[index] = l.split()

rawDescription: Python List Modifying Directly

description: Python List Modifying Directly


code:
def do_add(s, x):
  return len(s) != (s.add(x) or len(s))

rawDescription: Python: how to check if an item was added to a set, without 2x (hash, lookup)


rawDescription: How do I get each answer for each row with this conditional

description: Get each answer for each row with this conditional


code:
Methodist
Canadian
Ontario

rawDescription: BeautifulSoup Python script no longer working for mining a simple field


code: lines = ['~$ ' + line for line in command.split('\n')]

rawDescription: how to modify strings in a list of strings

description: Modify strings in a list of strings


code:
selected_full_paths = [files_to_show[listbox.get(i)]
                        for i in listbox.curselection()]

rawDescription: Attach data element to tkinter Listbox element


code: links = hxs.select("//div[@class='search-result af_panelGroupLayout']")

rawDescription: Extract text from an extracted new page from main page


code:
AJAX_LOOKUP_CHANNELS = {
    'alpha' : ('yoursite.yourapp.lookups', 'AlphaLookup'),
}

rawDescription: configuring ajax lookup in django ajax_lookup

description: Configuring ajax lookup in django ajax_lookup


code:
from PIL import Image
col = Image.open('sample.jpg')
gry = col.convert('L') # returns grayscale version.

rawDescription: Sum of colorvalues of an image

description: Sum of colorvalues of an image


code:
# Define global result_queue only in the main program.
import Queue
result_queue = Queue.Queue(100)  # pick a reasonable max size based on your problem

# Run this in as many threads as you like.
def consume_results():
    while True:
        a = result_queue.get()
        if a is None:
            break
        output(a.get())  # `output()` is your function

...
# main program passes out work, after starting threads
for i in range(1000):
    # the .put() will block so long as the queue is at its max size
    result_queue.put(pool.apply_async(calculate, args=(i,)))
# add sentinels to let threads know they're done
for i in range(number_of_threads_you_started):
    result_queue.put(None)

rawDescription: Concurrent.futures usage guide - a simple example of using both threading and processing


code:
def switch(self):
    if self.CheckVar_theta.get():
        self.entry11.config(state=DISABLED)
    else:
        self.entry11.config(state=NORMAL)

rawDescription: Python: Tkinter active and deactive entry space with checkutton


rawDescription: Delete a string in a dictionary after it's shown


code:
from collections import Counter
from itertools import chain

def di(d):
    counts = Counter(chain.from_iterable(
        [v] if isinstance(v, str) else v for v in d.itervalues()))
    return counts.most_common(1)[0]

rawDescription: find the maximum occurrence of a string in value for all keys in a dictionary

description: Find the maximum occurrence of a string in value for all keys in a dictionary


code: re.split('', 'abcabc')

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


code: [s[1] for s in sorted((key(s), s) for s in L)]

rawDescription: Sorting a list of tuples with 3 elements in python


code:
s1 = "foobar"
s2 = "fooba"
st1 = set(s1)

print(len(st1.intersection(s2)) == len(st1) - 1)
True

rawDescription: Finding words that contain all but one letter in string


code:
{str(key): value for (key, value) in zip(bins, count)}
import json
json.dumps(_)

rawDescription: Missed values when creating a dictionary with two values


code:
with open(filename, 'wb') as f:
    csv.writer(f).writerows(array)

rawDescription: How to save numpy array of Strings (with commas) to CSV?

description: Save numpy array of Strings (with commas) to CSV


rawDescription: Two list comparison in Python

description: Two list comparison in Python


code: result = s.split(':')

rawDescription: Python: RE only captures first and last match


code:
def post(self):
    my_arg = self.get_argument('my_arg')
    if not 7 <= my_arg <= 47:
        raise tornado.web.HTTPError(400)  # 400 Bad Request

rawDescription: Tornado set minmum and maximum values for get_argument


code:
df
df['ID'] = df['col1']
df = df.drop('col1',axis=1)
df['col1'] = (df.groupby('ID').cumcount() + 1)
df

rawDescription: How to use an input column as a major index in hierarchical indexing in pandas?

description: Use an input column as a major index in hierarchical indexing in pandas


code:
passed_or_failed = "Passed"
if average < 40:
    passed_or_failed = 'Failed'

print ("%s has: %s" % (Student, passed_or_failed))

rawDescription: Dividing in Python

description: Dividing in Python


code:
from collections import Counter
cnt = Counter("asbdasdbasdbadaasasdasadsa")
{k:cnt[k] for k in cnt if cnt[k] > 5}

rawDescription: removing least common elements from Counter

description: Removing least common elements from Counter


rawDescription: Get values from xml file using lxml

description: Get values from xml file using lxml


code:
zipp = [map(float,x.split()) for x in v]
zipp

rawDescription: Getting values out of a python dictionary


code: # The Toyota, Honda and BMW are red but the Mercedes is green.

rawDescription: Reduce redundant block of text

description: Reduce redundant block of text


code: print(x == 'NNP')

rawDescription: How do I check for a certain tag in Python NLTK?

description: Check for a certain tag in Python NLTK


rawDescription: Pandas series of datetimes in python

description: Pandas series of datetimes in python


code:
ITEM_PIPELINES = {
    'YourRootDirectory.NewPipleline.NewPipeline':800
#add any other pipelines you have
}

rawDescription: Passing scraped data in piplines __init__ scrapy for python


code: [ j.Mirror(mirPlane) for j in i ]

rawDescription: Nested list iterations

description: Nested list iterations


code: boto.emr.step.StreamingStep(name='a name', mapper='mapper name', combiner='combiner name')

rawDescription: how to skip argument in python when call method

description: Skip argument in python when call method


code:
foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
json_foo = json.dumps(foo)

rawDescription: Python http.client json request and response. How?


code:
def struct(**kwargs):
    return type('Struct', (object,), kwargs)

s = struct(a=5, b=7)
s.a

rawDescription: Is there an existing Python class that can hold any user attributes?


code:
def getValue(function, x):
    function = "{}({})".format(function, x)
    print(function)
    val=eval(function)
    print(val)

rawDescription: Executing mathematical user inputed statements as code in Python 3


code:
grid = SQLFORM.grid(db.image)
return dict(..., grid=grid)

rawDescription: Upload image in web2py to database from default controller following image blog example


rawDescription: Use Numpy Multidimensional Array Slicing Without Using the [slice,slice] Syntax?


rawDescription: Numpy, 1:M joins on Arrays

description: Numpy, 1:M joins on Arrays


rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


code:
https = suds.transport.https.HttpTransport()
opener = urllib2.build_opener(HTTPSudsPreprocessor)
https.urlopener = opener
suds.client.Client(URL, transport = https)

rawDescription: How to add http headers in suds 0.3.6?

description: Add http headers in suds 0.3.6


code:
import urllib2
import numpy as np

u = urllib2.urlopen('http://www.ndbc.noaa.gov/data/dart_deployment_realtime/23228.dart')
arr = np.loadtxt(u, skiprows=3)

rawDescription: How to read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python

description: Read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python


code: v = mahotas.convolve(r-w, pattern)

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


rawDescription: Script to compare a string in two different files


code: colors = [x for facet in facets for x in facet['color']]

rawDescription: OpenGL giving triangles colors in a list


code:
while not asyncresult.ready():
    time.sleep(1)

# Now the file is downloaded

rawDescription: Django-Execute function after Celery job completion


code:
turtles = []
turtles += [ turtle.Turtle() ]

i=0
for t in turtles:
  t.goto(data[i],data[i+1])
  i+=2

rawDescription: Can I use a variable in this context?

description: Use a variable in this context


code:
for tup in itertools.product([0,1,2,3], repeat = 3):
    vid(*tup)

rawDescription: Is it possible to use iterated values as method argument values?


code:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def showDocProfileOld(request, id):
   doctor = get_object_or_404(Doctor, id=id)

   return HttpResponseRedirect(reverse('showDocProfile', args=[doctor.slug]))

def showDocProfile(request, slug):
   doctor = get_object_or_404(Doctor, slug=slug)

   d = getVariables(request,dictionary={'page_name': "Dr." + doctor.name+"" })

   d.update({'doctor': doctor, 'doctors': Doctor.objects.all()})
   return render(request, 'm1/docprofile.html', d)

rawDescription: Django 1.6: Change URL structure

description: Django 1.6: Change URL structure


code:
def sort_the_stuff_key(item):
    try:
        return sort_month_names_key(item)
    except KeyError:
        return sort_day_week_key

def sort_the_stuff(some_iterable):
    return sorted(some_iterable, key=sort_the_stuff_key)

rawDescription: Sorting Numericly and by Month name

description: Sorting Numericly and by Month name


rawDescription: Concept of different systems of measurement in Django project


rawDescription: Beautifulsoup: How to find a string if tag or element not known?


code:
from pyspark.sql.functions import expr

(df1.join(df2, expr("array_contains(keywords, keyword)"))
    .groupBy("person", "type")
    .agg(avg("score")))

rawDescription: Pyspark join and operation on values within a list in column


code: print(*myList, sep='\n')

rawDescription: Pythonic way to print list items

description: Pythonic way to print list items


code: self.hello = Button(text="hello", on_press=lambda a:self.auth())

rawDescription: Bind function to Kivy button

description: Bind function to Kivy button


code:
class Model(Base):
    password = sa.Column(PasswordType(
        schemes=[
            'pbkdf2_sha512',
            'md5_crypt'
        ],
        deprecated=['md5_crypt']
    ))

rawDescription: SQLAlchemy & PassLib

description: SQLAlchemy & PassLib


code:
rng = pd.date_range('1/1/2011', periods=10000, freq='1Min')
df = pd.DataFrame(randint(size=len(rng), low=100, high = 500), index=rng)
df.columns = ['process_id']

rawDescription: counting records on per hour, per day and create multindex DataFrame as output

description: Counting records on per hour, per day and create multindex DataFrame as output


code:
from html.parser import HTMLParser

parser = HTMLParser()

with open(filename) as fileobj:
    for line in fileobj:
        line = parser.unescape(line)

rawDescription: How to decode 'xmlcharrefreplace' ascii to UTF-8 in python3?

description: Decode 'xmlcharrefreplace' ascii to UTF-8 in python3


code:
globals().update(a["data"])
var2

rawDescription: how to make child of a list become a variable in python

description: Make child of a list become a variable in python


code:
class ThumbnailSpec(ImageSpec):
    processors=[Thumbnail(200, 200, Anchor.CENTER, crop=True, upscale=False)]
    format='JPEG'
    options={'quality': 90}

    # put thumbnails into the "photos/thumbs" folder and
    # name them the same as the source file
    @property
    def cachefile_name(self):
        source_filename = getattr(self.source, 'name', None)
        s = "photos/thumbs/" + source_filename
        return s

register.generator('myapp:thumbnail', ThumbnailSpec)

rawDescription: Django Imagekit overwrite cachefile_name?


code:
id = PatientId.generate_patient_id_number()
# id is e.g. 'HSCM-E9E10C'

rawDescription: How can I use __init__() in python django

description: Use __init__() in python django


rawDescription: Using Flask-Cache to cache a lxml.html object


code:
for num in unsorted:
    byte_at_offset = (num & byte_check) >> offset*8
    buckets[byte_at_offset].append(num)

rawDescription: Pushing Radix Sort (and python) to its limits


code:
totals = df.groupby('state').size()
pivot = pd.pivot_table(df, rows='city', cols='state', aggfunc=len, fill_value=0) / totals

rawDescription: Make pivot tables in sql like in spss

description: Make pivot tables in sql like in spss


code:
import os
[i[0] for i in os.walk('/path/to/directory/') if i[0].split("/")[-1].startswith(X)]

rawDescription: Python: How can i find a directory that matches the first 3 characters from a string?


rawDescription: "Slicing" in Python Expressions documentation


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
import matplotlib.pyplot as plt

def plot(filename, x, y):
    plt.plot(x, y)
    plt.savefig(filename)
    return True

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(plot, 'plot')
server.serve_forever()

rawDescription: Standard ASCII File Format For Plotting from Matplotlib


code:
import scipy.interpolate as interpolate

x = [1,2,1,2,1,3,2,3,3]
y = [1,2,2,1,3,1,3,2,3]
z = [1,2,1,2,0,0,0,0,0]

kx, ky = 2, 2  # spline order
assert len(x) >= (kx+1)*(ky+1)

tck = interpolate.bisplrep(x, y, z, kx=kx, ky=ky)
print(interpolate.bisplev(1.5,1.5,tck))

rawDescription: Python: Bivariate Spline not on grid data


code:
def repeater(strings, k):
    seen = set()
    rep, ctr = None, None
    for i in range(len(strings) - k + 1):
        seq = tuple(strings[i:i+k])
        if rep:
            ctr += seq == rep
        elif seq in seen:
            rep, ctr = seq, 2
        else:
            seen.add(seq)
    return rep, ctr

rawDescription: Finding a repeating set of strings among a larger set


rawDescription: Python - extending properties like you'd extend a function


rawDescription: How can I get python logging.debug() messages to output to standard output?

description: Get python logging.debug() messages to output to standard output


code: resp,data = mail.uid('FETCH', '1:*' , '(RFC822)')

rawDescription: getting emails from gmail via python

description: Getting emails from gmail via python


code:
from numpy.core.umath_tests import inner1d
A = np.array([[1,2,3,4],[5,6,7,8]])
inner1d(A.T, A.T)

rawDescription: numpy: column-wise dot product

description: Numpy: column-wise dot product


code: [ './name[@val="1"]/Output{0}'.format(i)  for i in xrange(0,5)]

rawDescription: list of strings differ by suffix

description: List of strings differ by suffix


code:
mapping = [(self.btnPts, "PtsFile", self.label),
           (self.btnIll, "IllFile", self.label_2),
           (self.btnSigIll, "SigIll", self.label_3),
           (self.btn, "FutureFile", self.label_4)]

rawDescription: Calling the same function in pyqt when any button is clicked


code: 'TEXT WITH WHITESPACE           123.34645'.rsplit(None, 1)

rawDescription: choose numbers of different lengths

description: Choose numbers of different lengths


code:
from enthought.traits.api import HasStrictTraits, Instance, Property

class ExternalModel(object):
    foo = 'foo'

class TraitsModel(HasStrictTraits):
    _e = Instance(ExternalModel, ExternalModel())

    def __init__(self):
        '''
        >>> wrapper = TraitsModel()
        >>> wrapper.foo
        'foo'
        >>> wrapper._e.foo = 'bar'
        >>> wrapper.foo
        'bar'
        >>> wrapper.trait_names()
        ['trait_added', '_e', 'foo', 'trait_modified']
        '''
        HasStrictTraits.__init__(self)
        for trait in (name for name in dir(self._e) if not name.startswith('__')):
            self.__class__.add_class_trait(
                trait,
                Property(
                    lambda:getattr(self._e, trait),
                    lambda attr:setattr(self._e, trait, attr)
                )
            )

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: How can I wrap a non-Traits model for use with Python Traits?

description: Wrap a non-Traits model for use with Python Traits


code:
from operator import itemgetter
max(l,key=itemgetter(1))
max(l,key=itemgetter(1))[0]
min(l,key=itemgetter(1))[0]
min(l,key=itemgetter(1))
min(l,key=itemgetter(1))[0]

rawDescription: Returning .txt file contents

description: Returning .txt file contents


code:
def show_description(self,desired_item_id):
    self.item_info_model.setFilter('item_id = {}'.format(desired_item_id))
    self.item_info_mapper.toFirst()

rawDescription: QDataWidgetMapper-find index for sqlite database row in pyqt


rawDescription: Python: nested lists, extend & delete elements


code:
from django.core.exceptions import ObjectDoesNotExist

try:
    telnet_service = service.telnetservice
except (AttributeError, ObjectDoesNotExist):
    # You chose the wrong child type!
    telnet_service = None

rawDescription: ForeignKey to abstract class (generic relations)


code:
def predict(time, rdd):
    ...
    f = executor.submit(RDD.collect, pred)
    f.add_done_callback(submit_if_success)
    ...

rawDescription: How to avoid one Spark Streaming window blocking another window with both running some native Python code

description: Avoid one Spark Streaming window blocking another window with both running some native Python code


code:
a.value = 1
a.my_method()

rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


code:
sorted(l, key=lambda x: int(x.split(',')[0]))
sorted(l, key=lambda x: x.split(',')[1])

rawDescription: Python: Alphabetically sorting a list with letters and numbers in


code: m = __import__(a)

rawDescription: import userinputed string as a module in python

description: Import userinputed string as a module in python


code: code = re.sub('define MY_STRING\s+0', 'define MY_STRING 1', code);

rawDescription: How to substitute a numeric value in a string using Python?

description: Substitute a numeric value in a string using Python


code:
first_table = [
    ("Total agents"        , len(agentUserIdDict)),
    ("Total users"         , len(pure_user_dict)),
    ("Users with agent"    , len(pure_users_with_agents_dict)),
    ("Users with invites"  , len(user_id_invite_dict)),
    ("RUURL accounts"      , len(ruurl_set))
]
f.write(tabulate(first_table, headers = ["Category", "Total"]))

rawDescription: Setting the order of output for a table

description: Setting the order of output for a table


code:
ultrias = "am 17"
response = "Hi i am 17, did you know I am 17"
print(response.count(ultrias))

rawDescription: Python count everytime a string is found in another string


code:
import json

txt = open('demo.txt', 'rb')
data = json.load(txt)

rawDescription: Loading key value pairs from a file to mongodb in Python


code:
import numpy

# assuming you have a python list, you need to convert to a numpy array first
array = numpy.array(input_list)
# partition, slice back to the k smallest elements, convert back to a Python list
k_smallest = numpy.partition(array, k)[:k].tolist()

rawDescription: fastest method of getting k smallest numbers in unsorted list of size N in python?

description: Fastest method of getting k smallest numbers in unsorted list of size N in python


code:
def sliced_sum_op(a, b, c) :
    d = np.empty(a.shape[0])
    for i in xrange(a.shape[0]):
        d[i] = np.sum(a[i, b[i]:c[i]])
    return d

rawDescription: Sum between pairs of indices in 2d array


rawDescription: Django: Handling several forms in one submit, using class based views?


code:
from selenium import webdriver
driver = webdriver.PhantomJS()

driver.get('http://www.google.com.br')
handle = driver.execute_script('return window.open("http://www.pudim.com.br/", "any", "height = 450, width = 800, menubar=yes,scrollbars=yes,toolbar=yes,location=no,resizable=yes");')
driver.switch_to.window(driver.window_handles[1])
print(driver.current_url)

rawDescription: Switch window on Selenium

description: Switch window on Selenium


code:
http = httplib2.Http()
http = credentials.authorize(http)

service = build("blogger", "v2", http=http)

rawDescription: I have got the "Authorization code" for my app. But how can I use it to post in the blogger using gdata-python-client?


code: obj = capi.pygobject_new(pointer)

rawDescription: Create python object from memory address (using gi.repository)


code:
from operators import itemgetter
sorted_meta_lst = sorted(meta_lst, key=itemgetter(1))

rawDescription: Pythonic way to find highest values (and indexes) in list


code:
old_mode = ctypes.set_conversion_mode('utf-8', 'strict')
old_mode

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
from subprocess import Popen, PIPE
from PIL import Image, ImageFilter

proc = Popen('%s -sample 1x1 -optimize -progressive -qtables %s -outfile %s' % ('path/to/cjpeg', '/path/ta/qtable', 'out.jpg'), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
P = '6'
if im.mode == 'L':
    P = '5'
stdout, stderr = proc.communicate('P%s\n%s %s\n255\n%s' % (P, im.size[0], im.size[1], im.tostring()))

rawDescription: Determining JPG quality in Python (PIL)

description: Determining JPG quality in Python (PIL)


code:
class MyOtherInt(MyInt):
    def __iadd__(self, other):
        return self.__class__(self + other)

i = MyOtherInt(4)
i += 4
i
type(i)

rawDescription: Is it possible to be a virtual subclass of a built in type?


code:
def myfunc(x):
    x += 1

import dis
dis.dis(myfunc)

rawDescription: How many CPU cycles one addition take?

description: How many CPU cycles one addition take


code:
from __future__ import print_function
for word in "Monty Python":
    print(word,end='')

rawDescription: Strings Iteration - Printing a String Horizontally


code:
print(-7 & 0xFFFF)
print(-7 & 0xFFFFFFFF)

rawDescription: Detect int32 overflow using 0xFFFFFFFF masking in Python?


code: [0 if e == 1 else e for e in a]

rawDescription: Python: how do I replace all of the same elements in an int array?


rawDescription: Numpy - create matrix with rows of vector


rawDescription: Getting django's humanize working on App Engine


code:
sample = re.sub(r'\\b(.*?)\\b', r'
\1
', sample)
sample = re.sub(r'\\a(\s*\w+)', r'\1', sample)

rawDescription: Python: replace some tags to html tags in string


code:
with open(file_name) as f:
    for line in f:
        if line.strip():
            save_game.append(json.loads(line))

rawDescription: Python json.loads not able to parse json string


rawDescription: filling forward conditional result

description: Filling forward conditional result


code:
C=np.zeros((3,4),int)
N=np.arange(4)
C[:]=N
C

rawDescription: Vectorized element assignment involving comparisons between matrices in Numpy


code:
out = StringIO()
df.to_html(out,na_rep="Ted",float_format='{0:.2f}'.format)
out.getvalue()

rawDescription: pandas to_html no value representation

description: Pandas to_html no value representation


code: {'DataFile': 'scan1.dat', 'NumberOfChannels': 32}

rawDescription: Extracting variables from set of strings in python


code: numpy.savez('test.npz', a=a, b=b, positions=positions, forces=forces)

rawDescription: Save vectors to file in Python with NumPy


code:
def f():
   return 9992 is 9992
dis.dis(f)

rawDescription: Why is complex class not optimized to cache objects in Python?


code:
sql_expr = (
    "update {table} set {field} = " +
    "replace({field}, {str_to_repl}, {str_to_repl_with});"
).format(
    table=your_table_name,
    field=your_field_name,
    str_to_repl=your_string_to_replace,
    str_to_repl_with=your_string_to_replace_with,
)
session.execute(sql_expr)
session.commit()

rawDescription: SQLAlchemy query to find and replace a substring if it exists in a column


rawDescription: Braintree + Python: Configure credential at transaction level rather than module


rawDescription: Python split string on quotes

description: Python split string on quotes


code:
from operator import lt #used only for the default check_f
def split_by_time(reader,*split_times, check_f=lt):
    split_times = iter(split_times)
    split_time = next(split_times,None)
    current_data = {}
    for line in reader:
        row_time,*row_data = line
        if split_time is not None and check_f(split_time,row_time):
            yield current_data
            split_time = next(split_times,None)
            current_data = {}
        current_data[row_time] = row_data
    yield current_data

def check_limit(split_date, date_from_file):
    "convert the string date from file to a datetime object for comparison"
    return split_date < datetime.datetime.strptime(date_from_file,"%Y-%m-%d %H:%M")

times = list(split_by_time(f_reader,
                        week_ago,day_ago,
                        check_f=check_limit))

print("from before a week ago:\n",times[0])
print("from a week ago to a day ago:\n",times[1])
print("since yesterday:\n",times[2])

rawDescription: Iterate over . csv file --> write into two dictionaries


code:
def options (self):
    return {'Allow' : 'PUT' }, 200, \
    { 'Access-Control-Allow-Origin': '*', \
      'Access-Control-Allow-Methods' : 'PUT,GET' }

rawDescription: Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods


code: R,C

rawDescription: How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?

description: Check if one two-dimensional NumPy array contains a specific pattern of values inside it


code: element.set( "data-yes", str(int(yes_votes) + 1))

rawDescription: How can I modify the attributes of an SVG file from Python?

description: Modify the attributes of an SVG file from Python


code: calendar.monthrange(2015, 2)

rawDescription: How to get month interval using "datetime" in python?

description: Get month interval using "datetime" in python


code:
with open("test.csv","w") as f:
    wr = csv.writer(f)
    wr.writerow(["name"])
    for k, v in d.items():
        if v:
            wr.writerow([k.split(".")[0]])
            wr.writerows([[s.split(".")[0]] for s in v])

rawDescription: How to save JSON string into CSV or TXT in Python?

description: Save JSON string into CSV or TXT in Python


code:
support = """
#define ALIGNMENT 16
static void memxor(const char* in1, const char* in2, char* out, ssize_t n) {
    const char* end = in1 + n;
    while (in1 < end) {
       *out = *in1 ^ *in2;
       ++in1;
       ++in2;
       ++out;
    }
}
"""

code2 = """
PyObject* res = PyString_FromStringAndSize(NULL, real_size);

const ssize_t tail = (ssize_t)PyString_AS_STRING(res) % ALIGNMENT;
const ssize_t head = (ALIGNMENT - tail) % ALIGNMENT;

memxor((const char*)a, (const char*)b, PyString_AS_STRING(res), head);

const __m128i* pa = (__m128i*)((char*)a + head);
const __m128i* pend = (__m128i*)((char*)a + real_size - tail);
const __m128i* pb = (__m128i*)((char*)b + head);
__m128i xmm1, xmm2;
__m128i* pc = (__m128i*)(PyString_AS_STRING(res) + head);
while (pa < pend) {
    xmm1 = _mm_loadu_si128(pa);
    xmm2 = _mm_loadu_si128(pb);
    _mm_stream_si128(pc, _mm_xor_si128(xmm1, xmm2));
    ++pa;
    ++pb;
    ++pc;
}
memxor((const char*)pa, (const char*)pb, (char*)pc, tail);
return_val = res;
Py_DECREF(res);
"""

def inline_xor_nocopy(aa, bb):
    real_size = len(aa)
    a = numpy.frombuffer(aa, dtype=numpy.uint64)
    b = numpy.frombuffer(bb, dtype=numpy.uint64)
    return weave.inline(code2, ["a", "b", "real_size"],
                        headers = ['"emmintrin.h"'],
                        support_code = support)

rawDescription: Simple Python Challenge: Fastest Bitwise XOR on Data Buffers


code:
matfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                       'ut_constants.mat')

rawDescription: Python package setup with data files

description: Python package setup with data files


rawDescription: How to use distinct with pipeline in mongodb using python

description: Use distinct with pipeline in mongodb using python


rawDescription: Dictionary key in python are RegExp

description: Dictionary key in python are RegExp


rawDescription: How to remove more than one space when reading text file

description: Remove more than one space when reading text file


code: arc(center, radius, radius, 0, 2*math.pi, color)

rawDescription: Draw not-filled antialiased circles with pygame


rawDescription: openpyxl Fetch value from excel and store in key value pair

description: Openpyxl Fetch value from excel and store in key value pair


code:
for tag in soup.find_all('input', {'name': True}):
    tag['name'] = tag['name'].replace(' ', '')

rawDescription: bash script to replace spaces in html

description: Bash script to replace spaces in html


code:
myString = "hello world"
found = a.find('wor')
a = a[found: found+3]

rawDescription: Does python function str.find() returns string rather than index num


code:
c, v = string.split('.')
setattr(locals()[c], v, 2)

rawDescription: python access variable by name-as-string -inverse eval

description: Python access variable by name-as-string -inverse eval


code:
def do_something(foo_func):
    foo_func(refs=10, vars=2)

do_something(a.foo_helper)

rawDescription: Python: Decorator for deferred function call


code: row = numpy.array([0, 1, 2])

rawDescription: filtering elements of matrix by row in python scipy/numpy

description: Filtering elements of matrix by row in python scipy/numpy


code:
def foo(astr):
    # custom convert_arg_line_to_args method
    # convert 'names: [v1,v2]' into ['--names', v1, '--names', v2, ...]
    alist = []
    if ':' not in astr:
        return astr
    field,value = astr.split(':')
    value = value.strip()
    field = '--'+field
    if value.startswith('['):
        values = value[1:-1].split(',')
        for v in values:
            alist.extend([field,v.strip()])
    else:
        alist.extend([field, value])
    return alist

parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.convert_arg_line_to_args = foo  # could also do this with subclass
parser.add_argument('--names', action='append')
parser.add_argument('--ages', action='append')
parser.add_argument('--county', dest='county')
sample = "@stack28220581.yaml --name Ralph --age 40".split()
args = parser.parse_args(sample)
print(args)
# Namespace(ages=['22', '31', '40'], county='somewhere', names=['Bob', 'Jill', 'Ralph'])

rawDescription: How can I append the values from an input file to the command line options using argparse?

description: Append the values from an input file to the command line options using argparse


code: [len(set(x[1] for x in y)) for y in d]

rawDescription: How to unzip lists in lists in a list

description: Unzip lists in lists in a list


code: As = [type('A_{}'.format(i), (object,), {"num":i}) for i in range(10)]

rawDescription: Changing the bases of an object based on arguments to __init__


code:
import os

def get_block_range (filename, lookupValue):
    """
    Returns the index of the first line that contain ``lookupValue``
    and end of the file
    # here the value was at line 941 and the file had 1000 lines.

    >>> get_block_range('example.txt', 'example')
    (941, 1000)

    :rtype: tuple
    """
    if not os.path.getsize(filename):
        return None, 0

    with open(filename, 'r') as file:
        lookup_position = None

        for num, line in enumerate(file, 1):
            if lookup_position is None and lookupValue in line:
                lookup_position = num
        return lookup_position, num

rawDescription: How to find the line number of the end of file in python?

description: Find the line number of the end of file in python


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

description: Get the proper capitalization for a path


rawDescription: Get data between two tags in Python

description: Get data between two tags in Python


code:
for j in xrange(len(mu_d)): # mu_d has 121 values
    mu_d_j = mu_d[j]

rawDescription: Speeding up calculation of beta Pert distribution in Python


code: from nltk.tokenize.punkt import PunktWordTokenizer as PT

rawDescription: Utf-8 issues with python and nltk

description: Utf-8 issues with python and nltk


code:
final_array = np.zeros((6, 6))
final_array[paths[:-1], paths[1:]] = np.cumsum(vol_list)

rawDescription: Storing the values of an iteration to a numpy array - Python, Numpy


code:
command = ['path/to/executable', 'arg0', 'arg1', '...']
p = subprocess.Popen(command)
#do something

#kill if it's still alive
if p.poll() is None:
    p.kill()

rawDescription: Python 2.5 and Tskill

description: Python 2.5 and Tskill


code:
from itertools import permutations

def getPass():
    chars = '4$5%6^7&'
    for comb in permutations(chars):
       yield ''.join(comb)

for i in getPass():
    print(i)
    input('\ncontinue?')

rawDescription: Python itertools combinations iteration control


code:
for element in data:
    print(''.join(element))

rawDescription: List conversion/transformation

description: List conversion/transformation


code:
def univ_file_read(name, mode):
    # WARNING: ignores mode argument passed to this function
    return open(name, 'rU')

rawDescription: Python recognizing \r as a line delimiter


code: _.reindex_axis(np.arange(1, 10), 1)

rawDescription: pandas: groupby and unstack to create feature vector for classification

description: Pandas: groupby and unstack to create feature vector for classification


code:
class myStr(str):
    def __add__(self, other):
        return len(self) + len(other)

rawDescription: Classes: Alternative way of adding len()


code:
s = "10A"
from string import ascii_letters
print(int(s.translate(None,ascii_letters)))
10

rawDescription: Converting str to int in Python, only numbers w/o characters


code: [some_function(i) for i in seq]

rawDescription: When does using list comprehension in Python become inefficient?


code: idx = index_of_max(lists, key=lambda item: [sum(item)]+item)

rawDescription: Isolating lists based on value in python3


rawDescription: Scikit-learn train_test_split with indices


code:
l = [ ['a','b'], ['x','y'], ['a','y'], ['x', 'b'] ]
sorted(sorted(l, key=lambda x: x[1]), key=lambda x: x[0], reverse=True)

rawDescription: What is the pythonic way to sort a list with multiple attributes, such that the first is sorted reversely but the second is not?


code:
next_text = [ln.findNextSibling(text=True) for ln in links]
pprint(next_text)

rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code:
corrected_top_border_height = 0
corrected_bottom_border_height =0

for i in xrange(top_border_height):
    if iterate_line(img, border_threshold_R, border_threshold_G, border_threshold_B, i):
        corrected_top_border_height+=1
    else:
        break

for i in xrange(height-1, height-1-bottom_border_height, -1):
    if iterate_line(img, border_threshold_R, border_threshold_G, border_threshold_B, i):
        corrected_bottom_border_height+=1
    else:
        break

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


code:
class MongoDumps():
    def __init__(self, dBase, dumpCollection):
        self.dBase = dBase
        self.dumpCollection = dumpCollection
        client = MongoClient()
        self.db = getattr(client, dBase)
        self.collection = getattr(self.db, dumpCollection)

rawDescription: Can't connect to MongoDB database and collection through class variables


code:
from collections import defaultdict

# Because you are looking for a union of files, we can treat
#  the input data as a simple concatenation of all input files;
# If you were after intersection, we would have to deal with
#  each input file separately.
def chain_from_files(*filenames):
    for fname in filenames:
        with open(fname, "rb") as inf:
            for line in inf:
                yield line

# get the key and all related data for each line
def get_item(line):
    row = line.split()
    return row[1], (row[0], int(row[2]))    # <= returns a tuple ('abc', 2)

# iterate through the input,
# collect a list of related values for each key
def collect_items(lines, get_item):
    result = defaultdict(list)
    for line in lines:
        key, value = get_item(line)
        result[key].append(value)
    return result

# make an output-string for each key
# and its list of related values
def show_item(key, values):
    classes, nums = zip(*values)          # <= unpacks the tuples
    classes = '-'.join(sorted(set(classes)))
    average = float(sum(nums)) / len(nums)
    return "{} {} {}\n".format(classes, key, average)

def main():
    lines = chain_from_files(classA_infile, classB_infile, classC_infile)
    data  = collect_items(lines, get_item)

    with open(outputfile, "wb") as outf:
        for key,value in data.items():
            outf.write(show_item(key, value))

if __name__=="__main__":
    main()

rawDescription: Summing and Averaging values from multiple files in Python


code:
def say_hello(name=None):
    name = name if name is not None else "World"
    return "Greetings {name}!".format(name=name)

rawDescription: How to have different py files to handle different routes?

description: Have different py files to handle different routes


code:
def merge_lists(*lists):
    dicts = [dict(l) for l in lists]
    dates = set()
    for d in dicts:
        dates |= set(d.keys())
    dates = list(dates)
    dates.sort()
    merged_list = []
    for date in dates:
        item = [date]
        for d in dicts:
            item.append(d.get(date,0))
        merged_list.append(item)

    return merged_list

rawDescription: append to a key in a dictionary the union of other two keys using python

description: Append to a key in a dictionary the union of other two keys using python


code:
pattern = 'C:/Users/Desktop/bin/*.bin'
included = {'d{:03d}'.format(i) for i in range(15, 26)}  # a set
offset = len(os.path.dirname(pattern)) + 1

binary = sorted(f for f in glob.glob(pattern) if f[offset:offset + 4] in included)

rawDescription: python access selective files with glob module

description: Python access selective files with glob module


code:
srv = yield from whatever
return srv

rawDescription: Pros and cons of using return (yield from some_function())


code:
pat1 = r"Please check with the store to confirm holiday hours."
pat2 = r'\t'
combined_pat = r'|'.join((pat1, pat2))
stripped = re.sub(combined_pat, '', s2)

rawDescription: Python Regex sub() with multiple patterns


code:
def f(initialList):
    newList=[]
    for element in initialList:
        if not element.isalpha():
            break
        newList.append(element)
    return newList

rawDescription: Python - while all list elements result in true for .isalpha issue


code:
from itertools import product
list(product({1,-1},repeat=3))

rawDescription: How do I fill a list in python with elements from a specific set?

description: Fill a list in python with elements from a specific set


code:
from whoosh.index import create_in
from whoosh.fields import *

schema = Schema(title=TEXT(stored=True), content=TEXT)
ix = create_in("indexdir", schema)
writer = ix.writer()
writer.add_document(title=u"First document", content=u"This is the first document we've added!")
writer.add_document(title=u"Second document", content=u"The second one is even more interesting!")
writer.add_document(title=u"Third document", content=u"letter first, stamp second, mail third")
writer.add_document(title=u"Fourth document", content=u"stamp first, mail third")
writer.add_document(title=u"Fivth document", content=u"letter first,  mail third")
writer.add_document(title=u"Sixth document", content=u"letters first, stamps second, mial third wrong")
writer.add_document(title=u"Seventh document", content=u"stamp first, letters second, mail third")
writer.commit()

rawDescription: python fuzzy text search

description: Python fuzzy text search


code:
import requests
from lxml import etree

url = "http://sitename"
response = requests.get(url)
data = response.text
tree = etree.fromstring(data)
for leaf in tree:
    print(leaf.tag, leaf.attrib['id'], leaf.attrib['name'],
          leaf.attrib['description'], leaf.attrib['href'],
          leaf.attrib['webUrl'])

rawDescription: Python requests.get() looping through response?


code:
class Employee(db.Model):
    name = db.StringProperty()

rawDescription: How can I check if a particular value exists in a particular column in google app engine datastore?(python)

description: Check if a particular value exists in a particular column in google app engine datastore?(python)


rawDescription: python simple thread not working

description: Python simple thread not working


rawDescription: How to add a character to the end of every string in a list?

description: Add a character to the end of every string in a list


code:
# hold D's attributes (functions names, variables.)
attrs = [var for var in dir(D) if not var.startswith('__')]
# vars contents: ['another', 'bar', 'biz', 'foo']

for base in D.__mro__:
    for attr in attrs:
        if attr in base.__dict__:
            print("Attribute: '{}' defined in {}".format(attr, base))

rawDescription: How would I find where a function originates in source code?


code:
import cartopy.crs as ccrs
import cartopy.feature
import matplotlib.pyplot as plt
import numpy as np

rp = ccrs.RotatedPole(pole_longitude=-106.0 - 180,
                      pole_latitude=36,
                      globe=ccrs.Globe(semimajor_axis=6370000,
                                       semiminor_axis=6370000))
pc = ccrs.PlateCarree()

ax = plt.axes(projection=rp)
ax.coastlines('50m', linewidth=0.8)
ax.add_feature(cartopy.feature.LAKES,
               edgecolor='black', facecolor='none',
               linewidth=0.8)

# In order to reproduce the extent, we can't use cartopy's smarter
# "set_extent" method, as the bounding box is computed based on a transformed
# rectangle of given size. Instead, we want to emulate the "lower left corner"
# and "upper right corner" behaviour of basemap.
xs, ys, zs = rp.transform_points(pc,
                                 np.array([-139.08, 22.66]),
                                 np.array([-10.59, 46.59])).T
ax.set_xlim(xs)
ax.set_ylim(ys)

plt.show()

rawDescription: Plotting rotated pole projection in cartopy