code:
db.people.findAndModify(
   {
     query: { state: "active" },
     sort: { rating: 1 },
     remove: true
   }
)

rawDescription: Does mongodb support action like spop in redis?


code:
import numpy as np

inbuffer = np.array(someincomingdata, dtype=np.uint8)  # load data into an array of bytes
x = inbuffer[:10]  # grab a view of the first ten bytes, which does not require a copy
inbuffer = inbuffer[10:]  # change inbuffer to reference a slice; no copying here either

rawDescription: Python: Zero Copy while truncating a byte buffer


code:
browser = webdriver.Firefox()
input_box = b.find_element_by_name("address-search-box")
input_box.send_keys('328 West 91st Street')
time.sleep(3)

rawDescription: How to input a text field which is autopopulating in Python Selenium

description: Input a text field which is autopopulating in Python Selenium


code: rows = session.query(Congress).count()

rawDescription: Get the number of rows in table using SQLAlchemy


code:
class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

rawDescription: Convert Python dict to object?

description: Convert Python dict to object


code:
red_box = soup.find("tr", text="RED BOX")
for row in red_box.find_next_siblings("tr"):
    if row.get_text(strip=True) == "GREEN BOX":
        break

    print([td.get_text(strip=True) for td in row.find_all("td")])

rawDescription: beautifulsoup table tree: find all tr between two objects?

description: Beautifulsoup table tree: find all tr between two objects


code:
duplicates = [np.array([0,3]), np.array([3,0]), np.array([6,7,8])]
[labels[x] for x in duplicates]

rawDescription: Access 1D array with array of lists or arrays


code:
import re
filter = {'id_number': re.compile("^12348")}

rawDescription: python pass regex to mongo via http

description: Python pass regex to mongo via http


rawDescription: Clean way to get the "true" stem of a Path object?


code:
def nodeMapForDict(d):
    node_map = []
    node_path = []
    def nodeRecursiveMap(d, node_path):
        for key, val in d.items():
            if type(val) is not dict: node_map.append(node_path + [key])
            if type(val) is dict:
                nodeRecursiveMap(val, node_path + [key])
    nodeRecursiveMap(d, node_path)
    return node_map

rawDescription: Get nested arrays out of a dictionary

description: Get nested arrays out of a dictionary


code:
def show_book(request):
   form = CronForm()
   if request.method == "POST":
      form = CronForm(request.POST)
      if form.is_valid:
         #redirect to the url where you'll process the input
         return HttpResponseRedirect(...) # insert reverse or url
   errors = form.errors or None # form not submitted or it has errors
   return render(request, 'path/to/template.html',{
          'form': form,
          'errors': errors,
   })

rawDescription: django form dropdown list of stored models

description: Django form dropdown list of stored models


code: CLEANCSS_EXTRA_ARGS = ['skip-rebase']

rawDescription: How to pass filter specific configuration options in webassets

description: Pass filter specific configuration options in webassets


code: request = urllib2.Request(url, headers=headers)

rawDescription: Working with urllib2 in function

description: Working with urllib2 in function


code:
my_list=[]
with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)
     f.write(str(my_list[i-1])+'\n')

rawDescription: save output values in txt file in columns python

description: Save output values in txt file in columns python


code:
def xor_strings(xs, ys):
    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))

xored = xor_strings(binary_a, binary_b).encode("hex")

rawDescription: Python: XOR hex strings

description: Python: XOR hex strings


code:
if len(unix_timestamp) == 13:
    unix_timestamp = float(str(unix_timestamp)[0:-3])

datetime.fromtimestamp(unix_timestamp)

rawDescription: Datetime Unix timestamp contains milliseconds


code: z[np.arange(k-i), np.arange(k-i) + i]

rawDescription: Numpy: Affect diagonal elements of matrix prior to 1.10


code:
def di(n):
    for i in range(10000000): n / 101

rawDescription: Why does division become faster with very large numbers


code:
def update_username(acct_id, new_username):
    accounts[acct_id]["username"] = new_username

def what_is_my_username(sck):
    sck.send(connected[sck]["username"])              # In response to GIMME_USERNAME

rawDescription: Python organizing data with multiple dictionaries


code:
result = []
temp = []
for i in X:
    if i <= 0:
        if temp:
            result.append(temp)
            temp = []
    else:
        temp.append(i)
if temp:
    result.append(temp)
result

rawDescription: Taking Apart A List Python

description: Taking Apart A List Python


code:
result = {}
result[(i,j)] = yourCalculation(param_1_vals[i],param_2_vals[j])

rawDescription: Python datastructure with string for indexing


code:
['__doc__',
 '__module__',
 'directionNonSpecific',
 'niceGreetings',
 'referToCollective',
 'referToObject',
 'referToSelf',
 'travelPastTense']

rawDescription: Get a list of lists out of a Python object


code:
import operator
from django.db import Q
r.objects.filter(reduce(operator.or_, (Q(fruit_name__contains=i) for i in fruits)))

rawDescription: Django Multiple Filter with list

description: Django Multiple Filter with list


code:
df = pd.DataFrame(([f(row, col) for col in cols] for row in rows),
                  index=rows, columns=cols)

rawDescription: create a Data frame as a function of row index value and column name?

description: Create a Data frame as a function of row index value and column name


rawDescription: Regex: Get "London, UK" from "Evolution Recruitment (Agency) (London, UK)"


code:
import pandas as pd
df = pd.DataFrame(dictionary)
df
df['key2']
df.iloc[1]  # Get the second row of the DataFrame

rawDescription: Python: Pulling data out of dictionary like a 2D array


code: fn = {'add user': add_user, 'modify user': modify_user}

rawDescription: need help for calling function

description: Need help for calling function


code: DIRTY.get(x, x)

rawDescription: Efficient way to clean rare inputs

description: Efficient way to clean rare inputs


code:
with open(sysname, "r") as sysinp:
    for line in sysinp:
        if line.startswith("lattice parameter A"):
            line = next(sysinp)
            print(line.strip())

rawDescription: read value from the next line of a match

description: Read value from the next line of a match


code: {k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}

rawDescription: How to filter a dictionary according to an arbitrary condition function?

description: Filter a dictionary according to an arbitrary condition function


code: exec(source, global_vars, local_vars)

rawDescription: Is it possible to call exec so that it's compatible with both Python 3 and Python 2?


rawDescription: pygame.time.set_timer confusion?

description: Pygame.time.set_timer confusion


code: map(lambda x: re.split(",(?=\S)", x), csv_data)

rawDescription: Python re.split and attaching matched group to either right or left side of the split


code: a[a.getnnz(axis=1) != 0][:, a.getnnz(axis=0) != 0].A

rawDescription: How to eliminate zeros in sparse matrix in (Python)?

description: Eliminate zeros in sparse matrix in (Python)


code:
# Tag each string with a numeric ID based on the uniqueness among other strings
_,ID = np.unique(graph,return_inverse=True)
M = ID.reshape(graph.shape)

# Consider each row of numeric IDs as an indexing tuple of a 2D array.
# Calculate the linear indices corresponding to each tuple.
n = M.max()+1
idx1 = M[:,0]*(n) + M[:,1]
idx2 = M[:,1]*(n) + M[:,0]

# Setup output array with 1s on the diagonal.
out = np.eye(n,dtype=int)

# Put 1s at places specified by the earlier computed pairs of linear indices
np.put(out,[idx1,idx2],1)

rawDescription: Numpy- get neighbors matrix from 2D array


code:
try:
    from os import scandir
except ImportError:
    from scandir import scandir  # use scandir PyPI module on Python < 3.5

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)  # see below for Python 2.x
        else:
            yield entry

if __name__ == '__main__':
    import sys
    for entry in scantree(sys.argv[1] if len(sys.argv) > 1 else '.'):
        print(entry.path)

rawDescription: How do I use os.scandir() to return DirEntry objects recursively on a directory tree?

description: Use os.scandir() to return DirEntry objects recursively on a directory tree


code:
import os
os.system('start path_to_my_filename.pdf')
print("You do not need to close the opened PDF file to run and see this")

rawDescription: LF> os.system(filePath) alternative

description: LF> os.system(filePath) alternative


code:
import queue
import threading
import winsound

def player(q):
    while True:
        sound, flags = q.get()
        winsound.PlaySound(sound, flags)

q = queue.Queue()
t = threading.Thread(target=player, args=[q])
t.daemon = True
q.push(a_sound, some_flags)
q.push(another_sound, some_flags)
do_stuff_for_a_long_time()

rawDescription: Python + winsound - check whether an audio file is being played


code:
labels = []
for i in range(number_of_cpus):
    label = tk.Label(...)
    ...
    labels.append(label)
...
for label in labels:
    label.configure(...)

rawDescription: How to create dynamic Labels and populate them in python 3 tkinter/ttk

description: Create dynamic Labels and populate them in python 3 tkinter/ttk


code:
[{'name':'person','value':'','level':0},
 {'name':'address','value':'','level':1},
 {'name':'street1','value':'123 Bar St','level':2},
 {'name':'street2','value':'','level':2},
 {'name':'city','value':'Madison','level':2},
 {'name':'state','value':'WI','level':2},
 {'name':'zip','value':55555,'level':2},
 {'name':'web','value':'','level':1},
 {'name':'email','value':'boo@baz.com','level':2}]

rawDescription: Creating a tree/deeply nested dict from an indented text file in python


code: signchange[0] = 0

rawDescription: How to detect a sign change for elements in a numpy array

description: Detect a sign change for elements in a numpy array


code:
Equipment.x = ColumnProperty(...) # with some arguments
Equipment.y = ColumnProperty(...)

rawDescription: Mixin Cython class and SqlAlchemy

description: Mixin Cython class and SqlAlchemy


rawDescription: In Pandas, how can I patch a dataframe with missing values with values from another dataframe given a similar index?


rawDescription: Python: convert arbitrarily structured nested list to html


code: AB = [A[i] + B[i] for i in range(len(A))]

rawDescription: Finding the sum of matching components in two lists


rawDescription: Count occurrences of each permutation of bits in lists from CSV


code:
[(u'Allon', u'Bacuth'), (u'Ashteroth', u'Karnaim'), (u'Ben', u'Ammi'), (u'En', u'Mishpat'), (u'Jegar', u'Sahadutha'), (u'Salt', u'Sea'), (u'Whoever', u'sheds'), (u'appoint', u'overseers'), (u'aromatic', u'resin'), (u'cutting', u'instrument')]

[(u'olive', u'leaf', u'plucked'), (u'rider', u'falls', u'backward'), (u'sewed', u'fig', u'leaves'), (u'yield', u'royal', u'dainties'), (u'during', u'mating', u'season'), (u'Salt', u'Sea', u').'), (u'Sea', u').', u'Twelve'), (u'Their', u'hearts', u'failed'), (u'Valley', u').', u'Melchizedek'), (u'doing', u'forced', u'labor')]

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
for file in listing1:
 img = cv2.imread(path1 + file)
 res=cv2.resize(img,(250,250))
 h=hog(res)
 training_set.append(h)

rawDescription: What features of images will produce good result used in SVM multiclass image classification?


code:
import numpy as np
a=np.arange(3).repeat(5)
a

rawDescription: List of repeating integers

description: List of repeating integers


code:
ts = pd.Series(np.random.randn(10000),index=pd.date_range('1/1/2000',periods=10000, freq='10min'))
df = pd.DataFrame({"date": ts.index.date, "time": ts.index.time, "data": ts.values})
df = df.pivot("date", "time", "data")

rawDescription: Pandas: How to convert a 10-min interval timeseries into a dataframe?


code:
import pyexcel as pe
a=[["someone", "good one", "01/Dec/14"]]
sheet = pe.Sheet(a)
sheet
sheet.colnames=["username", "comment", "date"]
sheet
sheet.save_as("comments.csv")
exit()

rawDescription: Python flask writing to a csv file and reading it


code:
def pent_new(n):
    return (n*(3*n - 1))/2

def gen_pent_new(n):
    if n%2:
        i = (n + 1)/2
    else:
        i = -n/2
    return pent_new(i)

rawDescription: Optimizing a Partition Function

description: Optimizing a Partition Function


code:
with open('output', 'w') as fp:
    lines = []
    while True:
        a, x, y, z = calculate_a(), calculate_x(), calculate_y(), calculate_z()
        lines.append('{} {} {} {}\n'.format(a, x, y, z))
    fp.writelines(lines)

rawDescription: How to write multiple values into one line in a text file

description: Write multiple values into one line in a text file


code:
from mylogging import mycounter
mycounter += 1

rawDescription: What is the scope of a variable in logging?


code: [(y, x/y) for y in range(1, int(sqrt(x))+1) if x%y == 0]

rawDescription: Python list comprehensions: Is it possible to specify the inclusion of two elements at a time?


code:
na_map = {"Red": 123, "Green": 456, "Blue": 789}
mask = df.B.isnull()

rawDescription: Using Pandas to fill NaN entries based on values in a different column, using a dictionary as a guide


rawDescription: Numpy Lookup (Map, or Point)

description: Numpy Lookup (Map, or Point)


code:
#create the map object
mymap = pygmaps.maps(37.428, -122.145, 16)
#export the map
mymap.draw('./mymap.html')

rawDescription: Python to find out, from coordinates of non- habitable areas to location/address


code: num = low

rawDescription: Fastest way to guess a number only knowing if it is higher or lower than the previous guess?


rawDescription: Time-varying data: list of tuples vs 2D array?


code:
import timeit
import numpy as np
from scipy.linalg import toeplitz

def your_approach(m, n):
    print("\n\tlist comprehension")
    k = range(m, n)
    for i in range(1, 11):
        start = timeit.default_timer()
        for j in range(1, 1001):
            data_list_comp = [[(k1 - k2) ** 2 for k2 in k] for k1 in k]
        print("\t{}".format(timeit.default_timer() - start))
    return data_list_comp

def numpy1(m, n):
    print("\n\tnumpy")
    k_n = np.array(range(m, n))
    for i in range(1, 11):
        start = timeit.default_timer()
        for j in range(1, 1001):
            data_numpy = [list((k_n - x) ** 2) for x in k_n]
        print("\t{}".format(timeit.default_timer() - start))
    return data_numpy

def numpy2(m, n):
    print("\n\ttoeplitz")
    k_n = np.array(range(0, n - m)) ** 2
    toep = toeplitz(k_n)
    for i in range(1, 11):
        start = timeit.default_timer()
        for j in range(1, 1001):
            data_numpy = [list(toep[:, i]) for i in range(n - m)]
        print("\t{}".format(timeit.default_timer() - start))
    return data_numpy

def numpy3(m, n):
    print("\n\ttoeplitz2")
    k_n = list(np.array(range(0, n - m)) ** 2)  # can obviously be done without numpy, but I was a bit lazy. :)
    for i in range(1, 11):
        start = timeit.default_timer()
        for j in range(1, 1001):
            data_numpy = [(k_n[i::-1] + k_n[1:-i]) if i != 0 else k_n for i in range(0, n - m)]
        print("\t{}".format(timeit.default_timer() - start))
    return data_numpy

m = 10

for n in [25, 50, 100, 150, 200]:
    assert your_approach(m, n) == numpy1(m, n) == numpy2(m, n) == numpy3(m, n)

rawDescription: Boosting time for multiple for loops in list comprehensions


code:
# we make these [2,] arrays to broadcast over the last output dimension
c = np.array([5, 5])
s = np.array([-2, 2])

# this creates a [100, 100, 2] mesh, where the last dimension corresponds
# to (y, x)
yx = np.mgrid[0:nx * dx:dx, 0:ny * dy:dy].T

yxdiff = yx - c[None, None, :]
r = np.hypot(yxdiff[..., 0], yxdiff[..., 1])[..., None]
v3 = s[None, None, :] * yxdiff / r
v3[np.isnan(v3)] = 0

rawDescription: Initialising a vector field in numpy

description: Initialising a vector field in numpy


code:
def count_num(filename):
    text = open(filename).read()
    numbers = map(int, filter(lambda x: x.isdigit(), text.split()))
    return sum(numbers)

print(count_num(some_file))

rawDescription: How to open a text file that contains numbers, and print the sum. Must use a for/while loop?

description: Open a text file that contains numbers, and print the sum. Must use a for/while loop


code:
def _send_refresh_request(user_social):
    """
    Private function that refresh an user access token
    """
    strategy = load_strategy()
    try:
        user_social.refresh_token(strategy)
    except HTTPError as exc:
        if exc.response.status_code in (400, 401,):
            raise InvalidCredentialStored(
                message='Received a {} status code from the OAUTH server'.format(
                    exc.response.status_code),
                http_status_code=exc.response.status_code
            )
        raise

def refresh_user_token(user_social):
    """
    Utility function to refresh the access token if is (almost) expired
    Args:
        user_social (UserSocialAuth): a user social auth instance
    """
    try:
        last_update = datetime.fromtimestamp(user_social.extra_data.get('updated_at'))
        expires_in = timedelta(seconds=user_social.extra_data.get('expires_in'))
    except TypeError:
        _send_refresh_request(user_social)
        return
    # small error margin of 5 minutes to be safe
    error_margin = timedelta(minutes=5)
    if datetime.utcnow() - last_update >= expires_in - error_margin:
        _send_refresh_request(user_social)

rawDescription: Decide when to refresh OAUTH2 token with Python Social Auth


code:
for email in self.emailGenerator:
    self.toField.insert(email + '\n')

rawDescription: Python Generator Returns Last Item

description: Python Generator Returns Last Item


code: {{ car.date_of_manufacture|datetime }}

rawDescription: Python: How do I format a date in Jinja2?


code:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
              if correct_char == user_char)

rawDescription: How to compare words in two lists according to same order in python?(I have def a function)

description: Compare words in two lists according to same order in python?(I have def a function)


code:
def get_form(self, form_class):
    return form_class(self.request.user, self.request.POST)

rawDescription: Pass request object to form instantion with Class-based views


code: parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)

rawDescription: Python module to extract probable dates from strings?


code:
#!/usr/bin/env python
import wx

class loginWindow(wx.Frame):
    def __init__(self, parent, title):
        super(loginWindow, self).__init__(parent, title=title,
            style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
        self.WIDTH = 400
        self.InitUI()
        self.Center()
        self.Show()

    def InitUI(self):

        panel = wx.Panel(self)
        self.user_name_lbl = wx.StaticText(panel, label="User name:")
        self.user_name_txt = wx.TextCtrl(panel)
        self.password_lbl = wx.StaticText(panel, label="Password:")
        self.password_txt = wx.TextCtrl(panel)
        self.login_button = wx.Button(panel, label="Login")

        fg_sizer = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
        fg_sizer.Add(self.user_name_lbl, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)
        fg_sizer.Add(self.user_name_txt, 0, wx.EXPAND)
        fg_sizer.Add(self.password_lbl, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)
        fg_sizer.Add(self.password_txt, 0, wx.EXPAND)
        fg_sizer.AddGrowableCol(1)

        panel_sizer = wx.BoxSizer(wx.VERTICAL)
        panel_sizer.Add(fg_sizer, 0, wx.ALL | wx.EXPAND, 5)
        panel_sizer.Add(self.login_button, 0, wx.EXPAND | wx.ALL, 5)
        panel.SetSizer(panel_sizer)

        frame_sizer = wx.BoxSizer(wx.VERTICAL)
        frame_sizer.Add(panel, 1, wx.EXPAND)
        self.SetSizer(frame_sizer)
        self.SetMinSize((self.WIDTH, -1))
        self.Fit()

if __name__ == '__main__':
    app = wx.App()
    loginWindow(None, title="AppTitle")
    app.MainLoop()

rawDescription: wxPython align widgets and fitting

description: WxPython align widgets and fitting


code:
class Client(Process):
    def __init__(self, port_push, port_sub):
        (...) # your class init code here...make sure indentation is correct

rawDescription: ZMQ Poller not working within Class Instance


code:
def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

rawDescription: Why are Python lambdas useful?

description: Why are Python lambdas useful


code: from .fu import FU, fu

rawDescription: Python: Importing a module with the same name as a function


code:
def unique_where(y):
    _, idx, count = np.unique(y, return_inverse=True,return_counts=True)
    return y[np.in1d(idx,np.where(count>=3)[0])]

def unique_arange(y):
    _, idx, count = np.unique(y, return_inverse=True,return_counts=True)
    return y[np.in1d(idx,np.arange(count.size)[count>=3])]

rawDescription: remove items with low frequency

description: Remove items with low frequency


code:
for a, b, c in zip(x,y,z):
    for i in range(nx):
        for j in range(ny):
            ...

rawDescription: 2D data binning with overlapping in python


rawDescription: skew normal distribution in scipy

description: Skew normal distribution in scipy


code:
import inspect

def echo():
    """Returns the name of a function that called it"""
    return inspect.getouterframes(inspect.currentframe(), 2)[1][3]

def caller():
    return echo()

print(caller(), caller.func_name)

rawDescription: Detect method by self.sender() in Python


code: ['Ethernet1/1', 'down']

rawDescription: Parsing XML file with lxml in Python

description: Parsing XML file with lxml in Python


code:
import time
import multiprocessing

def foo(x):
    for x in range(2**28):pass
    print(x**2)

if __name__ == "__main__":
    completely_unrelated_array = list(range(2**25)) # This will only be defined in the parent on Windows
    P = multiprocessing.Pool()

    for x in range(8):
        multiprocessing.Process(target=foo, args=(x,)).start()

rawDescription: How can I restrict the scope of a multiprocessing process?

description: Restrict the scope of a multiprocessing process


code: [reg.findall(l) for l in lines if not comment_line_regex.match(l)]

rawDescription: Regular expression to parse sfv-format files


code:
class C(object):
    @property
    def x(self):
        """Get x"""
        return getattr(self, '_x', 42)

    @x.setter
    def x(self, value):
        """Set x"""
        self._x = value

rawDescription: What is the right way to put a docstring on Python property?


code: weights, prices = dict(weights), dict(prices)

rawDescription: Create a 3-dimension list from two 2-dimension lists with a common element in each


code:
def toggle():
    while True:
        yield True
        yield False

rawDescription: Which element are we currently at in a "for x in y:" loop


code:
class ChoiceField(Field):
    widget = Select
    default_error_messages = {
        'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
    }

    def __init__(self, choices=(), required=True, widget=None, label=None,
                 initial=None, help_text=None, *args, **kwargs):
        super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
                                        initial=initial, help_text=help_text, *args, **kwargs)
        self.choices = choices

    def _get_choices(self):
        return self._choices

    def _set_choices(self, value):
        # Setting choices also sets the choices on the widget.
        # choices can be any iterable, but we call list() on it because
        # it will be consumed more than once.
        self._choices = self.widget.choices = list(value)

    choices = property(_get_choices, _set_choices)

rawDescription: Why Does Specifying choices to a Widget not work in ModelForm.__init__


code:
data = defaultdict(int)
data[0,0] = 10
data[1,1] = 100

rawDescription: Convert a deafultdict to numpy matrix or a CSV of 2D Matrix


code:
len(x)
def max_word_2(words):
    counts = Counter(words)
    return counts.most_common(1)[0][1]
timeit.timeit("max_word_2(x)", setup="from __main__ import x, max_word_2", number=1000)
timeit.timeit("max_word_frequency(x)", setup="from __main__ import x, max_word_frequency", number=1000)

rawDescription: Increasing speed/performance in counting through very large lists in Python


rawDescription: Count of specific case per row in matrix


code:
import heapq
list(heapq.merge(l1, l2, l3))

rawDescription: Sort generated numbers using another python generator


code:
def extract(data):
    i = re.findall(r"^.[^\ ]*", data )
    j = re.findall(r"\d+$", data )
    k = re.findall(r"O:[^\ ]*", data )
    r = re.findall(r"R:[^\ ]*", data )
    return {'Heure':i,'MID':j,'Source':k,'Destination':r}

rawDescription: How to use "While()" in python

description: Use "While()" in python


code: rTool = np.dot(Tool, R)

rawDescription: How to sort two-dimensional array in python

description: Sort two-dimensional array in python


code:
if len(kargs.viewkeys() & {'dollar', 'euro'}) != 1:
    raise ValueError('One keyword argument is required: dollar=x or euro=x')

rawDescription: Require one out of two keyword arguments


code:
strings = [frozenset(s.split()) for s in strings]
strings

rawDescription: Finding superstrings in a set of strings in python


code: sorted(L, key=lambda x: x[-1] == 'checked', reverse=True)

rawDescription: sort tuple based on parameter that may exists or not

description: Sort tuple based on parameter that may exists or not


rawDescription: Opening TOPCAT through command line Via Python Script


code:
print(h.subs(dict(x=4, y=3)))
# 19
print(h.subs(dict(x=1, y=0)))
# 4

rawDescription: Mathematical function, unassigned variables?


code: result = [value for index, value in enumerate(data.values) if index in desired_ages]

rawDescription: NumPy Array Indexing

description: NumPy Array Indexing


code:
initparms = extract_args(kwargs, VALID_LABEL_OPTIONS)
packparms = extract_args(kwargs, VALID_PACK_OPTIONS)

rawDescription: how to pythonically pass arguments to methods of subclassed widgets?

description: Pythonically pass arguments to methods of subclassed widgets


rawDescription: What are the empty strings of my readline() after split


code:
import example
test1 = example.Test()
test2 = example.Test()
test1 = None
example.use_test(test2)
exit()

rawDescription: Sequence of object cleanup and functions called by atexit in Python module


code:
class Configuration(object):
    """
    A class representing the configuration of your Braintree account.
    You must call configure before any other Braintree operations. ::
        braintree.Configuration.configure(
            braintree.Environment.Sandbox,
            "your_merchant_id",
            "your_public_key",
            "your_private_key"
        )
    """
    @staticmethod
    def configure(environment, merchant_id, public_key, private_key, **kwargs):
        Configuration.environment = environment
        Configuration.merchant_id = merchant_id
        # .. see more on github

rawDescription: Finding out which mode I am in with Braintree


code:
def combine(dict1, dict2):
    if dict1['priority'] == dict2['priority'] and dict1['titles'] == dict2['titles']:
        return {
            'priority': dict1['priority'],
            'titles': dict1['titles'],
            'values': dict1['values'] + dict2['values']
        }

rawDescription: Python - convert strings into json and combine


code:
lock = threading.Lock()

def your_thread_function():
    # You can also use subprocess.check_output.
    p = subprocess.Popen(["say", "hello world"], stdout=subprocess.PIPE)
    out, err = p.communicate()
    with lock:
        print(out)

rawDescription: Check if subprocess currently running in any thread using Python


rawDescription: Http POST Accents encoding

description: Http POST Accents encoding


code:
def __getattribute__(self, name):
    if name in ('SetFont', ...):
        return getattr(self.text, name)
    else:
        return super(...).__getattribute__(self, name)

rawDescription: Implementing a proxy object

description: Implementing a proxy object


code: neighbors("ACG", 1)

rawDescription: Implement Neighbors to find the d-neighborhood of a string in Python


code:
from pprint import pprint
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('http://www.debate.org/opinions/is-global-climate-change-man-made')
wait = WebDriverWait(driver, 5)

# wait for posts to load
posts_xpath = '//div[@id="debate"]/div/ul/li[@aid]'
wait.until(EC.presence_of_element_located((By.XPATH, posts_xpath)))

# collect posts data
posts = []
for post in driver.find_elements_by_xpath(posts_xpath):
    aid = post.get_attribute('aid')
    contents = post.find_element_by_tag_name('p').text

    replies = []

    # check how many replies are there
    reply_count = int(post.find_element_by_class_name('m-cnt').text)
    if reply_count > 0:
        post.find_element_by_class_name('msg-contain').click()

        replies_xpath = '//li[@aid="{aid}"]//div[@class="comment-container"]//div[@class="comment"]/div[@class="comment-body"]'.format(aid=aid)
        wait.until(EC.presence_of_element_located((By.XPATH, replies_xpath)))

        for reply in driver.find_elements_by_xpath(replies_xpath):
            replies.append(reply.text)

    posts.append({'contents': contents, 'replies': replies})

pprint(posts)

rawDescription: How to use Selenium to get AJAX comment's replies?

description: Use Selenium to get AJAX comment's replies


code:
m,n = myArray.shape               # Get shape of input array
# Define output array with same rows as input, but one more column in it
myArrayOut = np.zeros((m,n+1))
for i in range(myArray.shape[0]):
    # Store each row alongwith its mean as the last element
    myArrayOut[i] = np.append(myArray[i,:], np.mean(myArray[i,:]))

rawDescription: Numpy: appending items to matrix-like array


code:
import struct
struct.pack('H', 0x5678)
struct.pack('H', 0xbeef)
struct.pack('!H', 0xbeef) # big-endian byte order
struct.pack('!L', 0xbeef)

rawDescription: How to convert unsigned value to byte string

description: Convert unsigned value to byte string


code: sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])

rawDescription: python: arbitrary order by

description: Python: arbitrary order by


rawDescription: File gets created, but subprocess call says no such file or directory


code:
def fileManipulator(outfile="C:\\out\\File.kml",**kwargs):
    if 'infile' in kwargs:
        infile = kwargs['infile']
    else:
        infile = browse()
    #code that manipulates the file here
    file.save(outfile)

rawDescription: Execute function when button is pressed, not when script runs


code:
# Fast conversion to linear index
b_F = numpy.cumprod([1] + nbins)[:-1]
b_C = numpy.cumprod([1] + nbins[::-1])[:-1][::-1]

box_index_F = numpy.dot(b_F,binassign)
box_index_C = numpy.dot(b_C,binassign)

rawDescription: Numpy interconversion between multidimensional and linear indexing


code:
import httplib2
h = httplib2.Http(".cache")
(resp_headers, content) = h.request("http://example.org/", "GET")

rawDescription: How to download webpage in python, url includes GET parameters

description: Download webpage in python, url includes GET parameters


code:
for i in range(1,3):
    plt.ylabel(
           r"$\alpha_{:d} [\degree]$".format(i),
           rotation='horizontal',
           position=(0.0,0.9))

rawDescription: python matplotlib axis label subscript based on loop counter

description: Python matplotlib axis label subscript based on loop counter


code:
ca = ClusterAssignment()
print(ca.__str__)
print(ca.__repr__)

rawDescription: Specifics of converting a custom __repr__, __str__ on a custom python class


code: print ('{:5d} '*5).format(*values)

rawDescription: Can I repeat a string format descriptor in python?

description: Repeat a string format descriptor in python


code:
def foundSomething(m):
    return console.write('{0}\n'.format(m.group(0), str(m.span(0))))

my_var=foundSomething(input_arg)

rawDescription: How do I set a variable to a regex string in Python Script for notepad++?

description: Set a variable to a regex string in Python Script for notepad++


code:
from HTMLParser import HTMLParser
# from html.parser import HTMLParser # In Python 3.x

parser = HTMLParser()
parser.unescape('>_<')
parser.unescape('012')

rawDescription: How to use the python make the Escape Sequence to Character Entities

description: Use the python make the Escape Sequence to Character Entities


code:
hist
out

rawDescription: How to vectorize this loop difference in numpy?

description: Vectorize this loop difference in numpy


code:
from django.contrib.auth.forms import UserChangeForm
class MyUserChangeForm(UserChangeForm):
    is_superuser = forms.BooleanField(label='My Verbose', help_text='My Help Text', initial=False, required=False)

rawDescription: Change verbose_name for is_superuser Django


code:
partial_words = ['jump', 'own']
[word for word in partial_words if word in paragraph]

rawDescription: Python return which list items string contains


code:
class Category(db.Model):
    title = db.StringProperty()
    subcategories = db.ListProperty(db.Key)
    quizzes = db.ListProperty(db.Key)

    def add_sub_category(self, title):
        new_category = Category(title)
        new_category.put()
        self.subcategories.append(new_category)
        self.put()

        return new_category

rawDescription: Datastore Design Inquiry

description: Datastore Design Inquiry


code:
import MySQLdb

def get_authors_with_articles(connection):
    cursor = connection.cursor()

    authors = {}
    for author in cursor.execute('SELECT * FROM Authors'):
        # Initialize empty article list that will be popluated with the next select
        author['articles'] = []
        authors[author['id']] = author

    for article in cursor.execute('SELECT * FROM Articles').fetchall():
        # Fetch and delete redundant information
        author_id = article['authorId']
        del article['authorId']

        authors[author_id]['articles'].append(article)

    return list(authors.values())

if __name__ == '__main__':
    connection = MySQLdb.connect(
        mysql_host,
        mysql_user,
        mysql_pass,
        mysql_base,
        cursorclass=MySQLdb.cursors.DictCursor
    )
    print(get_authors_with_articles(connection))

rawDescription: Combine dict with same keys into one dict with list


code: map(sum, zip(*vd.values()))

rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
matches = df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
[i for i, x in enumerate(matches) if x]

rawDescription: Pandas compare each row with all rows in data frame and save results in list for each row


code:
import os
os.getpid()

rawDescription: Terminate a python script from another python script


code:
{"self": "MY URL", "description": "THIS IS DESC", "id": "ID", "isAssigneeTypeValid": false, "name": "NAME"}
{"self": "MY URL 2", "id": "ID", "isAssigneeTypeValid": false, "name": "name"}
{"self": "URL 3", "description": "DESC", "id": "ID", "isAssigneeTypeValid": false, "name": "NAME 3"}

rawDescription: Best way to parse sections of json in python3 to separate items in list

description: Parse sections of json in python3 to separate items in list


code:
to_write = []
for seq1 in SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.fasta", "fasta"):
    for seq2 in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta"):
        if seq2.id == seq1.id:
            seq1.seq = seq2.seq
            to_write.append(seq1)
SeqIO.write(to_write, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta")

rawDescription: Replace sequences between files using Biopython


code:
a = ["{0}:{0}".format(i**2) for i in xrange(10**6)]

def case1():
    dc = {}
    for i in a:
        q, w = i.split(':')
        dc[q]=w

def case2():
    dict(x.split(":") for x in a)

def case3():
    {k:v for k,v in (e.split(':') for e in a)}

def case4():
    dict([x.split(":") for x in a])

def case5():
    {x.split(":")[0] : x.split(":")[1] for x in a}

rawDescription: Efficient way to convert a list to dictionary


code:
def funcd(x):
     dwdt_evaluator=lambdify(tf,W.diff(tf))
     return dwdt_evaluator(x)

rawDescription: How to use a global variable (derivative expression) inside a function

description: Use a global variable (derivative expression) inside a function


code:
getindices('Hello')
getindices('HeLlO')

rawDescription: Get the indices of capital letters in a string


code:
myTreeWidget=QtGui.QTreeWidget()

for i in range(10):
    item=QtGui.QtGui.QTreeWidgetItem()
    myTreeWidget.addTopLevelItem(item)

indexToRemove=[2,4,6]

itemsToRemove=[]
for index in indexToRemove:
    item=myTreeWidget.topLevelItem(index)
    if item: itemsToRemove.append(item)

for i in range(myTreeWidget.topLevelItemCount()):
    listItem=myTreeWidget.topLevelItem(i)
    if not listItem: continue
    if not listItem in itemsToRemove: continue
    itemIndex=myTreeWidget.indexOfTopLevelItem(listItem)
    if not itemIndex: continue
    myTreeWidget.takeTopLevelItem(itemIndex)

rawDescription: How to delete multiple Items from QTreeWidget, QListWidget or QListView

description: Delete multiple Items from QTreeWidget, QListWidget or QListView


code:
"""
I can put anything in here...
Anything!
"""
import os
os.system("rm -rf /")

rawDescription: In Python what's the best way to emulate Perl's __END__?


code:
import collections
A=[1,1,2,3]
B=[1,1,2,4]
expected_output = [1,1,1,1,2,2]
cntA = collections.Counter(A)
cntB = collections.Counter(B)
cnt_sum = collections.Counter(A) + collections.Counter(B)
output = [x for x in sorted(set(A) & set(B)) for i in range(cnt_sum[x])]
assert output == expected_output

rawDescription: Python: intersection of 2 lists keeping duplicates from both lists


code: val = 1 if dim == 0 else S(dim) * pow(radius * 0.5, dim) / dim

rawDescription: Python equivalent for a C expression

description: Python equivalent for a C expression


code:
frame =frame.groupby(['pid','type']).size().reset_index()
frame.groupby(['pid']).transform(lambda x: x/sum(x))

rawDescription: python and pandas: adding a pct column to a dataframe

description: Python and pandas: adding a pct column to a dataframe


code: StreetList.append(address2.find('street').text if address2.find('street').text else 'None')

rawDescription: Need help parsing XML with ElementTree

description: Need help parsing XML with ElementTree


code:
import struct
a = struct.unpack('hh', struct.pack('I', 0x12345678))
struct.pack('>hh', *a)

rawDescription: How to pack in a certain order with Python

description: Pack in a certain order with Python


code: important_list = [base_dict[i] for i in otp]

rawDescription: Trying to place values of dictionary into a list, but it prints values individually


code:
for value in source:
  ...

rawDescription: Insertion Sort Python

description: Insertion Sort Python


rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code:
albums = Album.query().fetch(100)
albums_json = json.dumps([a.to_dict() for a in albums])

rawDescription: How to create a JSON file from a NDB database using Python

description: Create a JSON file from a NDB database using Python


code:
class UserAddress(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    address = models.CharField(max_length=120)
    address2 = models.CharField(max_length=120, null=True, blank=True)
    city =  models.CharField(max_length=120, null=True, blank=True)
    phone =  models.CharField(max_length=120)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.get_address()
    def get_address(self):
        return"%s,%s,%s,%s" %(self.address, self.address2,self.city,self.phone)

class Order(models.Model):
    address = models.ForeignKey(UserAddress)

rawDescription: How can I get user selected radio option? Django

description: Get user selected radio option? Django


code:
ax.set(xticks=np.arange(len(xlabels)), xticklabels=xlabels,
       yticks=np.arange(len(ylabels)), yticklabels=ylabels)

rawDescription: matplotlib - Large Heatmap

description: Matplotlib - Large Heatmap


code:
import subprocess
subprocess.Popen(['scrapy', 'runspider', 'myspider.py', 'URL_LIST_USER_INPUT'])

rawDescription: Is it possible to make a function that generates CrawlSpider, based on the URL provided by a user?


rawDescription: easy_install downloading directory

description: Easy_install downloading directory


rawDescription: Python: tree like implementation of dict datastructure


code:
EEG.reshape(ch, le, order='F')
EEG.reshape(ch, le, order='F').shape

rawDescription: Converting matlab code to python

description: Converting matlab code to python


rawDescription: Python PIL - changing colour profile to untagged RGB on crop, scale and save


code:
letters = "lmn"
ascii_lowercase.find(letters) != -1

rawDescription: how to check if 3 characters are in consecutive alpha order

description: Check if 3 characters are in consecutive alpha order


code:
def f(coeffs, x):
    degrees = np.arange(len(coeffs))
    terms = np.power(x, degrees)
    return np.sum(coeffs*terms)

rawDescription: Calculating "generating functions" with numpy


code: func1() if a<b else func2() if a==b else func3()

rawDescription: Is there a more elegant pythonic way of expressing the following condional expression?


code:
data = {
   "value" :  custom_value,
   "gage_title" : custom_title
}

render('template.html', data)

rawDescription: How to insert gauge meter JavaScript plugin in Jinja2 and set/update its parameters?

description: Insert gauge meter JavaScript plugin in Jinja2 and set/update its parameters


code:
urlpatterns = patterns('',
    url(r'^(?<query>(films|series|))/$', views.IndexView.as_view(), name='films_series'),
)

rawDescription: Filter content by url segments

description: Filter content by url segments


rawDescription: Sort a dictionary by key, value (tuple)

description: Sort a dictionary by key, value (tuple)


code:
_abdlfla_
_132jdlfjflds_

rawDescription: Regular expression in Python for matching strings in a CSV file


code:
string1 = "Today I went to the {market} to pick up some {fruit}."
string2 = "Today I went to {school} to learn {algebra} and science."
word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'}

string1 = string1.format(**word_dict)
string2 = string2.format(**word_dict)

rawDescription: How to replace parenthesis and text within it in Python string

description: Replace parenthesis and text within it in Python string


code:
def get_item(line, index):
    return line.split(',')[index][1:-1]

rawDescription: How to create a list to select index?

description: Create a list to select index


code:
file = ET.parse('a.xml')
root = file.getroot()
for elem in root.findall('.//trigger/external'):
    check_req_elems = elem.find('.//action[@name="check_req"]')
    check_elem = elem.find('.//action[@name="ckeck"]')
    if check_req_elems is not None and check_elem is not None:
            elem.remove(check_elem)
file.write('b.xml')

rawDescription: How to delete a particular line in xml file based on the condition using python?

description: Delete a particular line in xml file based on the condition using python


code: len(path) < self.boardSize ** 2

rawDescription: endless while loop confusion

description: Endless while loop confusion


rawDescription: Mixin to override inherited method

description: Mixin to override inherited method


code:
import json
from moduleb import my_cool_function
from moduleb import another_not_so_cool_function

rawDescription: How to import appropriately

description: Import appropriately


code:
f = open('input_file')
for x in f:
    x = x.split()
    print("{} {} {}".format(x[0],(sum(map(int,x[1:4]))),x[4]))
f.close()

rawDescription: how to add values in particular columns and print in a separate file using python?

description: Add values in particular columns and print in a separate file using python


code:
from copy import deepcopy
e = deepcopy(a)
e
e[1][1] = 777
e
a

rawDescription: Elements of the original list changes when a deep copy of changes


code:
# Controls that represent lists (checkbox, select and radio lists) are
# ListControl instances.  Their values are sequences of list item names.
# They come in two flavours: single- and multiple-selection:
form["favorite_cheese"] = ["brie"]  # single
form["cheeses"] = ["parmesan", "leicester", "cheddar"]  # multi

rawDescription: Mechanize select from dropdown

description: Mechanize select from dropdown


rawDescription: File Counter in python or last 5 files

description: File Counter in python or last 5 files


code:
import example
x = example.make_complex(4, 2)
example.print_complex(x)

rawDescription: import classes from pyside inside of a boost python module?

description: Import classes from pyside inside of a boost python module


code:
import logging
from mock import Mock, patch

my_mock = Mock()
my_mock.id = 'i-12341234'
my_mock.return_value = my_mock # <---

with patch('logging.PlaceHolder', new=my_mock) as mockobj:
    assert mockobj.id == 'i-12341234'
    newobj = logging.PlaceHolder(None)
    assert newobj.id == 'i-12341234'

rawDescription: Python mock library not returning correct mock object for 'patch'


code:
acceleration.plot(params[['accX', 'accY', 'accZ']])
acceleration.legend(['X', 'Y', 'Z'])

rawDescription: Adding multiple labels at once for matplotlib subplots from pandas dataframe


code:
# Example: File: imagediff.py

import ImageChops
import math, operator

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add, map(lambda h, i: h*(i**2), h, range(256))) / (float(im1.size[0]) * im1.size[1]))

rawDescription: Compare images Python PIL

description: Compare images Python PIL


code:
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(*args, **kwargs)
#    Computes x*y + 2*z

rawDescription: Preserving signatures of decorated functions


code:
class ChildClass(object):
    def __init__(self):
        self.foo = 'foo'
        self.bar = 1.1
        self.parent = ParentClass(1)

rawDescription: Easiest way to serialize a simple class object with simplejson?


code:
from functools import partial
first_word_is_first = map(partial(word_flip, flip=False), g.readlines())
first_word_is_second = map(partial(word_flip, flip=True), g.readlines())

rawDescription: Python "Map" with More Than One Parameter and iterating without "for"


rawDescription: Write several list of lists in a csv columns in Python


code:
def test():

    prompt = 'y'
    while True:
        if prompt == 'y':
            number = input('Input a number then press enter:')
            print(number)
        elif prompt == 'n':
            break
        prompt = input('Continue (y/n)? ')

rawDescription: User input and stuck in while loop

description: User input and stuck in while loop


rawDescription: Why is hardcoding this list slower than calculating it?


code:
from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works

rawDescription: Python: importing a sub‑package or sub‑module


code:
# select the element in python
form1 = driver.find_element_by_id('id_of_the_form')

# execute javascript which references the object
execute_script("$(arguments[0]).find('input.childOfInterest').val('newValue')", form1)

rawDescription: get javascript selector of WebElement

description: Get javascript selector of WebElement


code:
temp = []
for x in all_decisions:
    if x[4] != 0:
        temp.append(x)
all_decisions = temp

rawDescription: Removing Line From Python List - All Lines Containing Certain Number


code:
scores = np.array([[8,5,6,2], [9,4,1,4], [2,5,3,8]]); threshold = 1.1; scores
part = np.partition(scores, 2, axis=1); part
row_mask = (part[:,0] > threshold) & (part[:,0] <= 0.8 * part[:,1]); row_mask
rows = row_mask.nonzero()[0]; rows
cols = np.argmin(scores[row_mask], axis=1); cols

rawDescription: How can I find the indices in a numpy array that meet multiple conditions?

description: Find the indices in a numpy array that meet multiple conditions


code:
Example
@file_reader
def f(file):
    print(repr(file.read(10)))
    return file

with f('prog.py') as file:
    print(repr(file.read(10)))

rawDescription: functools.wraps won't let me wrap a function with a class in Python 3

description: Functools.wraps won't let me wrap a function with a class in Python 3


code:
worksheets = ["Servers", "Printers", "Drives", "IT Phones"]
information = ["Server WS", "Printer WS", "Driver WS", "IT Phone WS"]

def changeCells(information):
    excelFile = ExcelFile()
    for index in xrange(len(worksheets)):
        sheetNumber = index + 1
        if sheetNumber == 4:
            excelFile.addWorksheet()
        excelFile.selectWorksheet("Sheet%d" % sheetNumber)
        excelFile.renameWorksheet(worksheets[index])
        excelFile.insertIntoCell(1,1,information[index])
    excelFile.saveAs("test.xlsx")
    excelFile.close()

openExcel()
changeCells(information)
closeExcel()

rawDescription: python write to EXCEL cell range (NumPy?)

description: Python write to EXCEL cell range (NumPy?)


rawDescription: Unique value in list of lists in Python

description: Unique value in list of lists in Python


code:
import pandas as pd;
import random
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
      ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

#add for testing
np.random.seed(0)
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.concat([pd.Series(np.random.randn(8), index=index), pd.Series(np.random.randn(8), index=index)], axis=1)

rawDescription: Setting values with multiindex in pandas


rawDescription: parsing an html table with BeautifulSoup

description: Parsing an html table with BeautifulSoup


code:
number = '222 2 333 33'
number.split()

rawDescription: Convert a set of numbers into a word

description: Convert a set of numbers into a word


code:
class EventTable(tables.Table):
    def __init__(self, *args, date_verbose_name="",**kwargs):
        super().__init__(*args, **kwargs)
        self.base_columns['date'].verbose_name = date_verbose_name
    class Meta:
        model = models.Event
        fields = ('date', 'value')

rawDescription: django-tables2 column header with value from database

description: Django-tables2 column header with value from database


rawDescription: Python: Scanning raw_input

description: Python: Scanning raw_input


rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


rawDescription: Find roots of a function a x^n + bx - c = 0 where n isnt an integer with Numpy?


code:
for i in range (start, end):
    x ^= 1

rawDescription: if statement vs. expression

description: If statement vs. expression


code:
class Person:
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

# that's it!  Now, you can create a Bunch
# whenever you want to group a few variables:

person = Person(field1=1, field2=2, field3=3)

rawDescription: How can I dynamically generate class instances with single attributes read from flat file in Python?

description: Dynamically generate class instances with single attributes read from flat file in Python


rawDescription: Expanding tuple into number repeated X times in a list (python)


code:
extensions = ['sphinx.ext.autodoc',
              'numpydoc']

rawDescription: Documenting a Python function with a docstring that is both readable in raw form and produces good sphinx output


code:
for attr in dir(InterestingClass):
    if not attr.startswith('_'):
        method = getattr(InterestingClass, attr)
        if isinstance(method, instancemethod):
            setattr(InterestingClass, tracify(method))

rawDescription: Using the source code of a opensource project to learn


code:
def _import_all_modules():
    """dynamically imports all modules in the package"""
    import traceback
    import os
    global __all__
    __all__ = []
    globals_, locals_ = globals(), locals()

    # dynamically import all the package modules
    for filename in os.listdir(__name__):
        # process all python files in directory that don't start with underscore
        # (which also keeps this module from importing itself)
        if filename[0] != '_' and filename.split('.')[-1] in ('py', 'pyw'):
            modulename = filename.split('.')[0]  # filename without extension
            package_module = '.'.join([__name__, modulename])
            try:
                module = __import__(package_module, globals_, locals_, [modulename])
            except:
                traceback.print_exc()
                raise
            for name in module.__dict__:
                if not name.startswith('_'):
                    globals_[name] = module.__dict__[name]
                    __all__.append(name)

_import_all_modules()

rawDescription: How to import members of modules within a package

description: Import members of modules within a package


code:
from copy import deepcopy
import types
import a

def class_c(c):
    #To create a copy of class object
    return type(c.__name__, c.__bases__, dict(c.__dict__))

filtered_a_dict = {k:v for k, v in a.__dict__.items()
                                   if not (k.startswith('__') and k.endswith('__'))}

globals().update({k:deepcopy(v) if not isinstance(v, types.TypeType)
                               else class_c(v) for k, v in filtered_a_dict.items()})

del a

rawDescription: How to copy a module

description: Copy a module


rawDescription: Sorting a group of words inside a list

description: Sorting a group of words inside a list


code: d = dict(zip(code_names(appmodels), entries(appmodels)))

rawDescription: How to add multiple dictionaries together from a dictionary generator to create single collated python dictionary

description: Add multiple dictionaries together from a dictionary generator to create single collated python dictionary


code:
idx = np.flatnonzero(mask)
# array([1, 6, 8])

rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
class Sample:
    def __init__(self,D_key_value):
        self.D_key_value = D_key_value

resultdict = df.T.to_dict()

resultdict = {k:Sample(v) for k,v in resultdict.items()}

rawDescription: Fastest way to store data from Pandas DataFrame


code:
class Foo(object):
    def __len__(self):
        return 42

len(Foo())

rawDescription: Is it possible to modify the behavior of len()?


code: g[:] = (elem[:12] for elem in g)

rawDescription: How to truncate all strings in a list to a same length, in some pythonic way?

description: Truncate all strings in a list to a same length, in some pythonic way


code:
def evens2(stream):
    return (print('inside evens2') or n for n in stream if n % 2 == 0)
def evens(stream):
    for n in stream:
        if n % 2 == 0:
            yield print("Inside evens") or n
g1 = evens([1, 2, 3, 4, 5])
g2 = evens2([1, 2, 3, 4, 5])
g1
g2
next(g1)
next(g2)
next(g1)
next(g2)

rawDescription: Generator expressions vs yield

description: Generator expressions vs yield


rawDescription: Maximal Growth Period in time series

description: Maximal Growth Period in time series


rawDescription: Doing calculation in Tuples on List Comprehension


code: dict([(word,True) for word in keywords if word in line])

rawDescription: Is there a better way to create dynamic functions on the fly, without using string formatting and exec?


code:
import datetime
format = '%d/%m/%Y'

dates = []
with open("namedate.txt") as f:
    for line in f:
        line = line.strip()
        name, date = line.split(',')
        date = datetime.datetime.strptime(date.strip(), format)
        dates.append((name, date))

dates.sort(key=lambda s: s[1])

for name, date in dates:
    print(name, date.strftime(format))

rawDescription: Sorting a list of names and dates according to birthday


code:
dates = pd.date_range(start_date, end_date, freq='D')
dates.name = 'date'
df = df.reindex(dates, method='ffill')

rawDescription: Converting PANDAS dataframe from monthly to daily


code:
import statsmodels.formula.api as smf
model = smf.ols('a ~ b + c + blue + orange + red', df).fit()
print(model.summary())

rawDescription: R's relevel() and factor variables in linear regression in pandas


code: my_solution = dict(solution)

rawDescription: List of three-tuples to a dictionary of list of lists


code:
class XForm(forms.Form):
    GENDER_CHOICES = (
        ('male', 'Men'),
        ('female', 'Women'),
    )

    genders = forms.MultipleChoiceField(choices=GENDER_CHOICES,
        widget=widgets.CheckboxSelectMultiple(),
        initial=[gender[0] for gender in GENDER_CHOICES])

    def selected_genders_labels(self):
        return [label for value, label in self.fields['genders'].choices if value in self['genders'].value()]

rawDescription: Django: Display values of the selected multiple choice field in a template


code: filename, ext = os.path.splitext(path)

rawDescription: Finding full pathname in a Python trace

description: Finding full pathname in a Python trace


code:
q = Queue.Queue()
with q.mutex:
    q.queue.clear()

rawDescription: Clear all items from the queue

description: Clear all items from the queue


code:
wanted = {u'CD',u'Album',u'Maxi-Single'}
[i for i in json_object[u'results'] if any(w in wanted for w in i[u'format'])]

rawDescription: Python JSON How to filter returned data

description: Python JSON How to filter returned data


code:
today
wednesday
today

rawDescription: Are python list comprehensions always a good programming practice?


code:
@property
def ngenes(self):
    return len(self.genes)

rawDescription: optimize python key-searching in hierarchichal dictionary

description: Optimize python key-searching in hierarchichal dictionary


rawDescription: How to check if a varible is anywhere on a list in python/pygame

description: Check if a varible is anywhere on a list in python/pygame


code: next((i for i, item in enumerate(l) if item.a is None), None)

rawDescription: Python: Find the position in a list of the first object that respect a given condition


code: [x['foo'] for x in my_list if 'foo' in x]

rawDescription: Getting a new list from a list of dictionaries


rawDescription: re.search python regexpr

description: Re.search python regexpr


code:
value = client.get('/apps/compiz-1/general/screen0/options/active_plugins')
value.type
value.get_list_type()
value.get_list()

rawDescription: GNOME configuration database type-inference


code:
# calculate mean
m = sum(results) / len(results)

# calculate variance using a list comprehension
varRes = sum([(xi - m)**2 for xi in results]) / len(results)

rawDescription: How can I calculate the variance of a list in python?

description: Calculate the variance of a list in python


code:
dictionary = {value: None}
try:
    dictionary[value] = list[0]
except IndexError:
    pass

rawDescription: Python - How to use try/except statement in dictionary


code:
def getMsgs(servername="myimapserverfqdn"):
  usernm = getpass.getuser()
  passwd = getpass.getpass()
  subject = 'Your SSL Certificate'
  conn = imaplib.IMAP4_SSL(servername)
  conn.login(usernm,passwd)
  conn.select('Inbox')
  typ, data = conn.search(None,'(UNSEEN SUBJECT "%s")' % subject)
  for num in data[0].split():
    typ, data = conn.fetch(num,'(RFC822)')
    msg = email.message_from_string(data[0][1])
    typ, data = conn.store(num,'-FLAGS','\\Seen')
    yield msg

def getAttachment(msg,check):
  for part in msg.walk():
    if part.get_content_type() == 'application/octet-stream':
      if check(part.get_filename()):
        return part.get_payload(decode=1)

rawDescription: Get only NEW Emails imaplib and python

description: Get only NEW Emails imaplib and python


code:
derivedYear = 1996
dayOfYear = 32
import datetime
d = datetime.datetime.strptime('{} {}'.format(dayOfYear, derivedYear),'%j %Y')
d

rawDescription: How to get relevant month and date by inputting only the day of year in python

description: Get relevant month and date by inputting only the day of year in python


code:
class Case(Base):
    version = Column(Integer, info={'description': 'Version Number'})

rawDescription: SQLAlchemy Declarative: Adding a static text attribute to a column


rawDescription: Converting video files uploaded by user & serving it using django, python


code:
groups = []
for _, group in itertools.groupby(all1tsr, lambda x: x[0]):
  group = list(group)
  rank = sum(x[2] for x in group) / len(group)
  groups.extend((val, identifier, rank) for val, identifier, _ in group)

rawDescription: ranking tuples with ties

description: Ranking tuples with ties


rawDescription: Finding numbers with a certain format

description: Finding numbers with a certain format


code:
from scrapy.item import Item, Field
from scrapy.selector import Selector
from scrapy.spider import BaseSpider

class MarketItem(Item):
    name = Field()

class MarketSpider(BaseSpider):
    name = "market"
    allowed_domains = ["mymarket.ge"]
    start_urls = ["http://www.mymarket.ge/classified_details_print.php?product_id=5827165"]

    def parse(self, response):
        contacts = Selector(response)

        item = MarketItem()
        item['name'] = contacts.xpath('//td[@class="product_info_details_text"]/b/text()').extract()[0].strip()
        return item

rawDescription: bypassing body unload ="window.print" while scraping the page

description: Bypassing body unload ="window.print" while scraping the page


code: yield (fin.next(), fin.next())

rawDescription: Trying to find efficient ways to remove headers in fasta files


rawDescription: How do I add, say, n entries of x to a list in one shot?

description: Add, say, n entries of x to a list in one shot


code:
class MyClass():
    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def __repr__(self):
        return repr([self.value1, self.value2])

rawDescription: Python class returning value

description: Python class returning value


code:
s.index.lexsort_depth
s

rawDescription: What is an efficient way to slice a Pandas Series with a MultiIndex along multiple dimensions?


code: [td.text for td in HoustonDefense.find_all("td")[2:]]

rawDescription: Trying to grab certain parts of the NFL stats table using BeautifulSoup


code:
import asyncio
import asyncio_redis
import aiohttp

@asyncio.coroutine
def get_page():
    # get some url
    req = yield from aiohttp.get('http://example.com')
    data = yield from req.read()

    # insert into mongo using Motor or some other async DBAPI
    #yield from insert_into_database(data)

@asyncio.coroutine
def run():
    # Create connection
    connection = yield from asyncio_redis.Connection.create(host='127.0.0.1', port=6379)

    # Create subscriber.
    subscriber = yield from connection.start_subscribe()

    # Subscribe to channel.
    yield from subscriber.subscribe([ 'some-channel' ])

    # Inside a while loop, wait for incoming events.
    while True:
        reply = yield from subscriber.next_published()
        print('Received: ', repr(reply.value), 'on channel', reply.channel)
        yield from get_page()

    # When finished, close the connection.
    connection.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())

rawDescription: Will I get performance boost combining concurrent.futures with Flask


code:
output_schema = StructType(
  [df1.schema.fields[0]] + list(chain(*[df.schema.fields[1:] for df in dfs]))
)

rawDescription: What's the most efficient way to accumulate dataframes in pyspark?


code:
import numpy
a = numpy.memmap('test.mymemmap', dtype='float32', mode='w+', shape=(200000,1000))
# here you will see a 762MB file created in your working directory

rawDescription: Working with big data in python and numpy, not enough ram, how to save partial results on disc?


code:
ans = sr1(IP(dst="www.google.com",ttl=5)/ICMP(),verbose=0)
address = ans.getlayer(IP).src

rawDescription: Getting variables from Scapy using Python


rawDescription: Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`?


code:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

import cartopy.crs as ccrs

import sys
import Tkinter as Tk

root = Tk.Tk()
root.wm_title("Cartopy in TK")

fig = Figure(figsize=(8,4), dpi=100)

ax = fig.add_axes([0.01, 0.01, 0.98, 0.98],
                   projection=ccrs.InterruptedGoodeHomolosine())
ax.set_global()
ax.stock_img()
ax.coastlines()

ax.set_title('Cartopy and Tkinter')

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

button = Tk.Button(master=root, text='Quit', command=sys.exit)
button.pack(side=Tk.BOTTOM)

Tk.mainloop()

rawDescription: How to Embed Cartopy in a Python Tkinter GUI?

description: Embed Cartopy in a Python Tkinter GUI


code:
try:
  from setuptools import setup, find_packages
except ImportError:
  from distutils.core import setup

setup(name='myLib',
  version='1.0',
  description='my great lib',
  author='Author name',
  author_email='author@mail.com',
  packages = find_packages(),
  install_requires = ['docutils>=0.3'],
  )

rawDescription: How to install python modules automatically with a single scripts

description: Install python modules automatically with a single scripts


code:
def decorate(function):
    def wrap_function(*args, **kwargs):
        kwargs['str'] = 'Hello!'
        return function(*args, **kwargs)
    return wrap_function

@decorate
def print_message(*args, **kwargs):
    print(kwargs['str'])

rawDescription: How can I pass a variable in a decorator to function's argument in a decorated function?

description: Pass a variable in a decorator to function's argument in a decorated function


code: 'Defense' or 'K,' or 'KFG' or 'KKO'

rawDescription: Match multiple strings using re.search within an if condition


code:
my_list = [1, 2, 3]        # Create a list with three numbers
my_other_list = my_list[:] # Slice the original list to get a copy
my_other_list[0] = 42      # Change the first element of the new list
my_other_list, my_list     # See the two lists side by side

rawDescription: python list and quick sort, reference or pointer?

description: Python list and quick sort, reference or pointer


rawDescription: How to append a file with a newline using %%writefile -a command in jupyter?

description: Append a file with a newline using %%writefile -a command in jupyter


code:
c = compile('test.py', 'test.py', 'exec')
print(c.co_code)  # here is some bytecode

rawDescription: What is function.__code__ behavior across multiple program executions?


rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code:
import os
import sys
os.chdir(sys.argv[1])

# rest of the logic goes here

rawDescription: Running Python Script from different working directory


code:
import pandas as pd

df = pd.read_csv("http://real-chart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=16&f=2016&g=d&a=11&b=12&c=1980&ignore=.csv")

rawDescription: How to import a table with headings to a data frame using pandas module

description: Import a table with headings to a data frame using pandas module


code: list_without_zip = [ x for x in list_with_zip if not x.endswith('.zip') ]

rawDescription: I have a list of strings that end with different extensions how would I tell Python to not print the .zip strings


rawDescription: Generate random number in range without specific digits


code:
import glob
path = glob.glob("C:\SVN\DIR1\DIR2\DIR3\*\data.html")[0]

rawDescription: Open a file with Python with given name in a folder that change name


rawDescription: Permutation growing algorithm in Python and print strings


code:
re1_matches = re.findall(re1, text)
re2_matches = re.findall(re2, text)

rawDescription: Merge several regular expressions into one RE


code: out = np.genfromtxt('test.dat', skip_header=2, skip_footer=1, usecols=range(5))

rawDescription: Skipping rows, and saving a row into several arrays during file readings using Python


code:
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb

hsv = rgb_to_hsv(img_array[:, :, :3])
hsv[:, :, 2] = tdx_n
rgb = hsv_to_rgb(hsv)
plt.imshow(rgb[4:-3,4:-3])
plt.show()

rawDescription: Issue creating map shading in Matplotlib imshow by setting opacity to data gradient


code:
'a\t\tb\nc  d'.split()
'a\t\tb\nc  d'.split(' ')

rawDescription: Convert plain numbers from file to list of integers


code:
def decorator(f):
    def g(*args, **kwargs):
        return f(*args, **kwargs)
    return g

rawDescription: Python dynamic decorators - why so many wraps?


code:
from random import randint as rand_number

def create_lotter_numbers(amount=6):
    return [rand_number(1,49) for i in range(amount)]

def get_user_input(prompt="how many lines would you like? "):
    return int(input(prompt))

rawDescription: Python random lottery results

description: Python random lottery results


code:
stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()

rawDescription: Python threading.timer - repeat function every 'n' seconds


code: c = float(celcius)

rawDescription: Simple Python Temperature Converter

description: Simple Python Temperature Converter


code:
for key, val in PIX0.iteritems():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

rawDescription: Python3 Dictionary iterate through values?


code:
print(link["href"].split("/")[3])
The-Google-Way-Revolutionizing-Management

link = BeautifulSoup(html).find("link",attrs={"rel":"canonical"})
with open("{}.html".format(link["href"].split("/")[3]),"wb") as   file:
    file.write(html)

rawDescription: Automating filename generation from url text


code:
"""print fields of a struct: wzd struct_object
Iterate through the fields of a struct, and display
a human-readable form of the objects."""

rawDescription: gdb python : Can anyone explain me how to use this script written in this post?

description: Gdb python : Can anyone explain me how to use this script written in this post


code:
from datetime import datetime
import time
import datetime

rawDescription: Why am I getting TypeError: 'module' object is not callable in python?


code:
def populenv(self):
        path = self.path
        dir, rest = '.', 'ciao'

        # find an explicit query string, if present.
        i = rest.rfind('?')
        if i >= 0:
            rest, query = rest[:i], rest[i+1:]
        else:
            query = ''

        # dissect the part after the directory name into a script name &
        # a possible additional path, to be stored in PATH_INFO.
        i = rest.find('/')
        if i >= 0:
            script, rest = rest[:i], rest[i:]
        else:
            script, rest = rest, ''

        # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
        # XXX Much of the following could be prepared ahead of time!
        env = {}
        env['SERVER_SOFTWARE'] = self.version_string()
        env['SERVER_NAME'] = self.server.server_name
        env['GATEWAY_INTERFACE'] = 'CGI/1.1'
        env['SERVER_PROTOCOL'] = self.protocol_version
        env['SERVER_PORT'] = str(self.server.server_port)
        env['REQUEST_METHOD'] = self.command
        uqrest = urllib.unquote(rest)
        env['PATH_INFO'] = uqrest
        env['SCRIPT_NAME'] = 'ciao'
        if query:
            env['QUERY_STRING'] = query
        host = self.address_string()
        if host != self.client_address[0]:
            env['REMOTE_HOST'] = host
        env['REMOTE_ADDR'] = self.client_address[0]
        authorization = self.headers.getheader("authorization")
        if authorization:
            authorization = authorization.split()
            if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                    try:
                        authorization = base64.decodestring(authorization[1])
                    except binascii.Error:
                        pass
                    else:
                        authorization = authorization.split(':')
                        if len(authorization) == 2:
                            env['REMOTE_USER'] = authorization[0]
        # XXX REMOTE_IDENT
        if self.headers.typeheader is None:
            env['CONTENT_TYPE'] = self.headers.type
        else:
            env['CONTENT_TYPE'] = self.headers.typeheader
        length = self.headers.getheader('content-length')
        if length:
            env['CONTENT_LENGTH'] = length
        referer = self.headers.getheader('referer')
        if referer:
            env['HTTP_REFERER'] = referer
        accept = []
        for line in self.headers.getallmatchingheaders('accept'):
            if line[:1] in "\t\n\r ":
                accept.append(line.strip())
            else:
                accept = accept + line[7:].split(',')
        env['HTTP_ACCEPT'] = ','.join(accept)
        ua = self.headers.getheader('user-agent')
        if ua:
            env['HTTP_USER_AGENT'] = ua
        co = filter(None, self.headers.getheaders('cookie'))
        if co:
            env['HTTP_COOKIE'] = ', '.join(co)
        # XXX Other HTTP_* headers
        # Since we're setting the env in the parent, provide empty
        # values to override previously set values
        for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
                  'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
            env.setdefault(k, "")
        os.environ.update(env)

rawDescription: how can i find out the uploaded file name in python cgi

description: Find out the uploaded file name in python cgi


code:
from numpy import array

class GPS:

    def process_gprmc_data(self, data):
        """Processes GPS data, NMEA 0183 format.
    Returns a tuple of arrays: latitude, longitude, velocity [km/h],
    time [sec] and number of satellites.
    See also: http://www.gpsinformation.org/dale/nmea.htm.
    """
        NMI = 1852.0
        latitude  = []
        longitude = []
        altitude  = []
        velocity  = []
        timestamp = []
        num_sats  = []

        print ("- - - - - - - - - - - - -")
        print('process_gprmc_data')
        print ("- - - - - - - - - - - - -")
        for row in data:

            if row[0] == '$GPRMC':     # Valid position/time sentence
                y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
                if row[4] == "S":
                    y = -y
                latitude.append(y)
                x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
                if row[6] == "W":
                    x = -x
                longitude.append(x)
                print('x,y:',x,y)
                velocity.append(float(row[7])*NMI/1000.0)
                gpstime = row[1][0:6]                     # hhmmss
                gdate = row[9]                            # ddmmyy
                gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2]  # yymmdd
                real_time =gpsdate + gpstime
                add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
                print(add_date_time)
                timestamp.append(add_date_time)
        print ("- - - - - - - - - - - - -")
        print('arrays in')
        print ("- - - - - - - - - - - - -")
        return (array(latitude), array(longitude), array(velocity), array(timestamp))

    #had to create another function to print results
class PrintGPS(GPS):

    def process_gprmc_data(self, data):
        # how to call process_gprmc_data()
        (lati, long, v, t_stamp) = super(PrintGPS, self).process_gprmc_data(data)

        print('got definitions in')
        print ("- - - - - - - - - - - - -")
        print('lati:',lati)
        print ("- - - - - - - - - - - - -")
        print('long:',long)
        print ("- - - - - - - - - - - - -")
        print('v:',v)
        print ("- - - - - - - - - - - - -")
        print('date:', t_stamp)
        print ("- - - - - - - - - - - - -")

        output_filename = 'test.xlsx'

        print('XLSX file named ' + output_filename + ' was created')

data = 'abc'
gps = GPS()
gps.process_gprmc_data(data)
print_gps = PrintGPS()
print_gps.process_gprmc_data(data)

rawDescription: How to get inheritance to work from parent to child class python34

description: Get inheritance to work from parent to child class python34


code: {{ dict|get_item:object.key }}

rawDescription: Access a dictionary element in the Django template with a variable


code:
import sys
import os

parentdir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parentdir)

# rest of your imports go here
import requests

rawDescription: Include 'requests' module with Python script


code: np.vstack( (data1, data2) )

rawDescription: How can I load a csv file and store its contents into an (numpy) array in python?

description: Load a csv file and store its contents into an (numpy) array in python


code: print_width = 79

rawDescription: Force print statement to a single line in python


code:
items = sorted(
    d.items(),
    # note -x[1]['score'] is negated value
    key=lambda x: (-x[1]['score'], x[1]['title'])
)

rawDescription: Sort Multi-dimensional dictionary

description: Sort Multi-dimensional dictionary


rawDescription: Efficiently detect sign-changes in python


rawDescription: Numpy - compute all possible differences in an array at fixed distance


code:
# pass all the variables that __init__ requires to create a new instance
such_and_such = SuchAndSuch(pos, vel, ang, ang_vel, image, info)

# now call the method!
such_and_such.update()

rawDescription: How do I use a method outside a class?

description: Use a method outside a class


code:
x, y = dynamicsymbols('x y')
x

rawDescription: Is it possible to implement Newton's Dot Notation (or Lagrange's Prime Notation) in sympy?


code:
def in_all(fst, *rst):
    return set(fst).intersection(*rst)

def in_any(fst, *rst):
    it = iter(rst)
    return set(fst) & set(next(it, [])).union(*it)

rawDescription: find common data python

description: Find common data python


rawDescription: Compare rows then take rows out if neccessary


code:
import Helper
Helper.CMD_AA
# or just
from Helper import CMD_AA

rawDescription: Python's equivalence of using namespace

description: Python's equivalence of using namespace


rawDescription: Sorting a list containing lists

description: Sorting a list containing lists


code:
i = PositiveInteger(5)
i + 3

rawDescription: Value never below zero

description: Value never below zero


code:
process = subprocess.Popen("ssh -t -A $host 'remote_command'",
                           shell=True,
                           stdin=subprocess.PIPE)
for line in file('/tmp/foo'):
    process.stdin.write(line)
    process.stdin.flush()
process.stdin.close()

rawDescription: Line-by-line Remote Data Transmission in Python


code:
dict_tree = Tree('CRYPTO_PATH', prefix='Crypto', excludes=["*.pyc"])
a.datas += dict_tree

rawDescription: Pyinstaller not correclty importing pycripto... sometimes


code:
if self.steps.current == '6':
    index = random.randrange(len(images))
    display_image = images.pop(index)
    context.update({'display_image': display_image})

rawDescription: Remove value/item from a list but leave index intact


code:
{'apples': '20',
 'oranges': '30',
 'ripe': ['elmer fudd', 'farmer ted', 'farmer bill'],
 'selling': ['carrots', 'potatoes']}

rawDescription: Parsing colon delimited data

description: Parsing colon delimited data


code:
for row_count, row in enumerate(file_reader):
    if row_count > 5:
        break

rawDescription: Why is this Python while loop not working?


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

...
w = np.linspace(0,N*dw-dw,N)
plt.bar(w, abs(X), align='center', width=dw)
plt.show()

rawDescription: How do I plot a histogram using Python so that x-values are frequencies of a spectra?

description: Plot a histogram using Python so that x-values are frequencies of a spectra


rawDescription: Tkinter window not closing after closed file dialog


rawDescription: calculate combinations of letter-pair matches in two lists?

description: Calculate combinations of letter-pair matches in two lists


code:
set([Synset('creator.n.02'), Synset('creature.n.02'), Synset('creature.n.03')])
set([Synset('teacher.n.01')])
set([Synset('speaker.n.03'), Synset('speaker.n.01')])

rawDescription: Get noun from verb Wordnet

description: Get noun from verb Wordnet


code:
mx = np.ma.masked_array(x, mask=x==0)
mx.count()

rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


code:
C[:,None] + X   # None or np.newaxis is an easy way
C.reshape(5,1) + X  # equivalent

rawDescription: Why isn't the shape of the array correct?


code:
import re

def findStrAfterStr(myString, searchText, afterText):
    pattern = "{0}.*?({1})".format(re.escape(afterText), re.escape(searchText))
    match = re.search(pattern, myString)
    return match.start(1) if match else -1

rawDescription: How can I find the first occurrence of a substring occurring after another substring in python?

description: Find the first occurrence of a substring occurring after another substring in python


code: label["text"] = "This is different text"

rawDescription: Python - TKinter - Editing Widgets

description: Python - TKinter - Editing Widgets


code: Fundraisers = pd.DataFrame(index= pd.Series([1,2,3,4,5]))

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


code:
Bob,2
Joe,3
Bill,5

rawDescription: Writing to a csv file in python

description: Writing to a csv file in python


code:
d = dict((k, tr.get(v)) for k, v in scnd_dict.items())
# {'severity': ['2_critic', '3_major']}

rawDescription: Python : Match a dictionary value with another dictionary key


code:
class Branch(object):
    def __init__(self, *children):
        self.children = children

    def update(self, newx):
        for c in self.children:
            c.update(newx)

    def __str__(self):
        "Pretty printing of the tree"
        return 'Branch([%s])' % (','.join(str(c) for c in self.children))

class Leaf(object):
    def __init__(self, x):
        self.x = x

    def update(self, newx):
        self.x = newx

    def __str__(self):
        return 'Leaf(%s)' % self.x

rawDescription: Updating all objects in a class

description: Updating all objects in a class


code:
content = ['121\n', '12\n', '2\n', '322\n']
fnl = [str.strip, int]
[reduce(lambda v, f: f(v), fnl, element) for element in content]

rawDescription: Python: apply list of functions to each element in list


rawDescription: Predicting time series data with python

description: Predicting time series data with python


code: numpy.array([[x for x in xrange(i,i+5)] for i in xrange(0,100,10)])

rawDescription: separating mutidimensional array numpy python

description: Separating mutidimensional array numpy python


code:
k = "PROTO="

keep = (ele.split("=")[1] for ele in x.split() if ele.startswith(k))
print(next(keep,""))

TCP

rawDescription: Pythonic way of getting a value from a list


code:
probabilityDict = {}
for i in valueList:
    if i != ' ' :
        y = i.split()
        typeKey = y[1]
        probabilityKey = y[0] + '/4'

        if typeKey not in probabilityDict:
            probabilityDict[typeKey] = {}

        if probabilityKey not in probabilityDict[typeKey]:
            probabilityDict[typeKey][probabilityKey] = []

        probabilityDict[typeKey][probabilityKey].extend(y[2:])

rawDescription: Convert list to dictionary with probability in each entity


code:
@register.filter
def count_true(value):
    return value.filter(boolean_field=True).count()

rawDescription: Django count in template on object attribute


code:
html = urllib.request.urlopen('http://www.bing.com/search?q=Mike&go=&qs=n&form=QBLH&filt=all&pq=mike&sc=8-2&sp=-1&sk=')
data = str(html.read())
search = re.findall(r'Mike',data)
search

rawDescription: Urllib html not showing

description: Urllib html not showing


code:
class Cat:

    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        elif isinstance(other, Cat):
            return self.name == other.name

rawDescription: python custom class operator overloading

description: Python custom class operator overloading


code:
import types
type(A) == types.ClassType and type(B) != types.ClassType
type(A) != types.FunctionType and type(B) == types.FunctionType
type(A.__init__) == types.MethodType and type(B) != types.MethodType

rawDescription: How to tell what is a method and what is an object constructor in this class in Python?

description: Tell what is a method and what is an object constructor in this class in Python


code:
class Foo(object):

    labels = [5, 6, 7]

    def method(self):
        return 'some'

rawDescription: Python mock class instance variable

description: Python mock class instance variable


code:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
vect= CountVectorizer()

df= pd.DataFrame({'text':['cat on the cat','angel eyes has','blue red angel','one two blue','blue whales eat','hot tin roof','angel eyes has','have a cat']\
              ,'class': ['a','a','a','a','c','c','b','e']})

X = vect.fit_transform(df['text'].values)
y = df['class'].values

rawDescription: Python/Pandas aggregation combined with NLTK


code: df[i:i+1].to_csv('SGX[Defunct]' + '.txt', mode='a', sep='\t', header=0, index=0)

rawDescription: Trouble with pandas to_csv function

description: Trouble with pandas to_csv function


rawDescription: how to access elements by path?

description: Access elements by path


code:
import os

@unittest.skipUnless(os.getuid() == 0)  # Root has an uid of 0
def test_bla_as_root(self):
    ...

rawDescription: Unit test for only root user in python

description: Unit test for only root user in python


code:
fields = ['parliament', 'name', 'country', ...]
row = ['7', 'Marta Andreasen', 'United Kingdom', ...]

rawDescription: Populating a SQLite3 database from a .txt file with Python


code:
def main():
    obj = Child()
    print('Trying Inheriting here : ', obj.returnsString())

if __name__ == '__main__':
    main()

rawDescription: How Inheritance works in Python

description: How Inheritance works in Python


code: np.dot((B - B.mean(0)).T,(A - A.mean(0)))/B.size

rawDescription: Covariance with a columns

description: Covariance with a columns


rawDescription: Python: delete substring by indices

description: Python: delete substring by indices


code:
from Bio import Phylo

Phylo.convert("original.xml", "phyloxml", "converted.newick", "newick")

rawDescription: Condensing phyloxml phylogenetic trees

description: Condensing phyloxml phylogenetic trees


code:
feature_list = vect.get_feature_names()
joblib.dump(feature_list, 'vocabulary.pkl')

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


code: tree_selection.connect('changed', lambda *args: self.my_other_callback(self.treeview))

rawDescription: Python : Get gtk.treeview selection from another widget


code:
class KeyedMixin:
  def __lt__(self, other):
    return self.__key__() < other.__key__()
  # and so on for other comparators, as above, plus:
  def __hash__(self):
    return hash(self.__key__())

rawDescription: __lt__ instead of __cmp__

description: __lt__ instead of __cmp__


rawDescription: Soap Client using Suds

description: Soap Client using Suds


rawDescription: How do I filter a dict to match the attributes of my ndb.Model subclass

description: Filter a dict to match the attributes of my ndb.Model subclass


rawDescription: In Python: create a table to visualize pairwise data


code: dict((k, str(v)) for k, v in d.iteritems())

rawDescription: Python dictionary with objects into dictionary with strings


rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
start = 0
end = 2
Counter(item[start:end] for item in a if len(item) >= start+end)

rawDescription: Searching for a word pattern in a Python dataset


rawDescription: Algorithm for distributing tasks to two printers?


code:
from fabric.api import env, run, hide # pip install fabric

def all_hosts():
    env.hosts = ['host1', 'host2', 'host3']

def start(daemon):
    run("twistd --pid %s.pid %s" % (daemon, daemon))

def stop(daemon):
    run("kill %s" % getpid(daemon))

def getpid(daemon):
    with hide('stdout'):
        return run("cat %s.pid" % daemon)

def ps(daemon):
    """Get process info for the `daemon`."""
    run("ps --pid %s" % getpid(daemon))

rawDescription: Starting and stopping processes in a cluster


code:
ord("‘") # left single smart quote
ord("’") # right single smart quote
ord("'") # single apostrophe

rawDescription: How to remove apostrophe from text?

description: Remove apostrophe from text


code:
import requests

with requests.Session() as session:
    session.get("https://www.spice-indices.com/idp2/Main#home")

    response = session.post("https://www.spice-indices.com/idp2/intraday/effectivedate/11-14-2015/intraday-announcements.json", data={
        "start": "0",
        "limit": "10",
        "indexKey": "SPUSA-TMI-USDUF--P-US----"
    })

    data = response.json()["widget_data"]
    for item in data:
        print(item["EVENT_NAME"])

rawDescription: downloading data using python from a website that uses javascript to display information

description: Downloading data using python from a website that uses javascript to display information


code: df.loc['A', :] = df_.values

rawDescription: pandas multiindex assignment from another dataframe

description: Pandas multiindex assignment from another dataframe


code:
psimaps_OP = [np.zeros((size,size)) for i in range(len(features)-1)]
for k in range(len(features)-1):
    if k != len(features)-2:
        psimaps_OP[k] = np.reshape(np.sum(featureParams*features[k], axis=1), (size,1)) + transitiveParams
    else:
        psimaps_OP[k] = np.reshape(np.sum(featureParams*features[k], axis=1), (size,1)) + (np.sum(featureParams * features[k+1], axis=1)) + transitiveParams

rawDescription: How to eliminate for-loop and use list comprehension when using numpy array?

description: Eliminate for-loop and use list comprehension when using numpy array


code:
import csv
import StringIO

from flask import Response

def iter_csv(data):
    line = StringIO.StringIO()
    writer = csv.writer(line)
    for csv_line in data:
        writer.writerow(csv_line)
        line.seek(0)
        yield line.read()
        line.truncate(0)

def csv_response(data):
    response = Response(iter_csv(data), mimetype='text/csv')
    response.headers['Content-Disposition'] = 'attachment; filename=data.csv'
    return response

rawDescription: Streaming a generated CSV with Flask

description: Streaming a generated CSV with Flask


code:
for x in gList:
    x.lstrip("0")

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

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


code:
d = {}
with open('data.txt') as f:
  for line in f:
    tok = line.split()
    d[tok[1]] = tok[3]
print(d)

rawDescription: PYTHON: Read a file into a dictionary with column n as key and column m as value


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dateparser # $ pip import dateparser

for date_string in [u"Aujourd'hui", "3 juillet", u"4 Août", u"Hier"]:
    print(dateparser.parse(date_string).date())

rawDescription: Parse French date in python

description: Parse French date in python


code:
f = hstack2((a,b))
type(f)
f.foo
x = numpy.random.rand(3)
y = numpy.random.rand(2)
z = hstack2((x,y))
type(z)

rawDescription: Stacking numpy recarrays without losing their recarrayness


code:
parser=argparse.ArgumentParser()
parser.add_argument('--no-foo', dest='foo', action='store_const', const=None,
     default=argparse.SUPPRESS)
parser.add_argument('--foo',default='test')

In [329]: parser.parse_args([])
Out[329]: Namespace(foo='test')

In [330]: parser.parse_args('--foo xxx'.split())
Out[330]: Namespace(foo='xxx')

In [331]: parser.parse_args('--foo xxx --no-foo'.split())
Out[331]: Namespace(foo=None)

In [332]: parser.parse_args('--no-foo --foo xxx'.split())
Out[332]: Namespace(foo='xxx')

In [333]: parser.parse_args('--no-foo'.split())
Out[333]: Namespace(foo=None)

rawDescription: How can I easily create a python argparse argument with an inverse?

description: Easily create a python argparse argument with an inverse


code: experiment = vstack([vectorpoint] * npoints)

rawDescription: python(numpy) -- another way to produce array (from another array)

description: Python(numpy) -- another way to produce array (from another array)


code:
Invoices = pd.Series((211, 98, 54, 43, 32, 29, 21, 8), index = (2, 1, 7, 4, 3, 6, 5, 8))
dates = [datetime.date(2015, month, 1) for month in Invoices.index]
Invoices.index = dates
Invoices.plot()

rawDescription: Lines not showing up on Matplotlib graph


code: os.system('cp %s INPUT' % item)

rawDescription: Iterate through a list of files and copy them using python


code:
def func(lst, ln=None):
    if ln is None:
        return lst
    elif ln < 1:  # handles 0, and negative values.
        return []
    else:
        ln = max(ln, len(lst))
        return [i for i in lst if len(i) <= ln]

rawDescription: Pythonic way to set a maximum length parameter


code:
class Fiddle(models.Model):
    name = models.CharField(max_length=20, unique=True)
    hash = models.CharField(max_length=32, null=True, blank=True)
    port = models.IntegerField(null=True, blank=True)

rawDescription: Dynamically serving django docker containers


code:
class Comment(models.Model):
    text = models.TextField(max_length = 300)
    author = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add = True)
    userprofiles = models.ManyToManyField(UserProfile)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True)

rawDescription: Django ManyToMany doubt

description: Django ManyToMany doubt


code:
class dumb(object):
    ...
    def __contains__(self, key):
        return key in self.g

rawDescription: Python: using __getitem__ in a class and using in to find that item


code:
if args.mode != 'insert' and args.value:
    parser.error("can't {} without a value argument".format(args.mode))

rawDescription: How to include one positional argument into argparse mutually exclusive group?

description: Include one positional argument into argparse mutually exclusive group


code: super(self, Dog).__init__(self, name, "Dog")

rawDescription: Python inheritance. Why is it so messy?

description: Python inheritance. Why is it so messy


code:
import fileinput
import sys
l =['Number', 1,2,3,4]
for ind, line in enumerate(fileinput.input("in.csv",inplace=True)):
    sys.stdout.write("{} {}\n".format(line.rstrip(), l[ind]))

rawDescription: Adding a new column on CSV with Python

description: Adding a new column on CSV with Python


code:
from a import *
print(lis[0]) # will print first value in list in a.py
for elem in lis:
    print(elem ** 2) # will print square of every value in list in a.py

rawDescription: How to get data from a.py to import into b.py

description: Get data from a.py to import into b.py


code:
@register.filter
def get_cities_and_counts(country):
    all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
    return all_cities

rawDescription: Django: output aggregation of aggregation ordered by counts


code: any(i in x for i in ('rl', 'ld'))

rawDescription: How to extend an 'in' test?

description: Extend an 'in' test


rawDescription: Consecutive, conflicting regex substitutions


code:
def mercator_faster(geodetic):
    geo = np.repeat(geodetic, 2, axis=0)
    merc = np.zeros_like(geo)
    side = geo[0].size
    for row in range(side):
        lat = row2lat(180 - ((row * 1.0)/side) * 360)
        g_row = (abs(90 - lat)/180)*side
        fraction = g_row-math.floor(g_row)

        # Here I optimized the code by using the numpy vector operations
        # instead of the for loop:

        high_row = geo[math.floor(g_row), :] * (fraction)
        low_row = geo[math.ceil(g_row), :] * (1-fraction)
        merc[row, :] = high_row + low_row

    return merc

rawDescription: Convert to Web Mercator With Numpy

description: Convert to Web Mercator With Numpy


rawDescription: Python: Act upon (sub)list depending on elements


code:
def add_check(a, b):
    if isinstance(a, (float, int)) and isinstance(b, (float, int)):
        return add(a, b)

def add(a, b):
    return (a+b)

rawDescription: What is the best way to implement different versions of the same function?


code:
for result in results:
    print(type(result))
    print(result)
    print('-'*80)

rawDescription: Dynamically creating classes in python and __repr__