code:
import subprocess

proc = subprocess.Popen("pstree",stdout=subprocess.PIPE)
proc.communicate()[0]

proc = subprocess.Popen(["ps" ,"aux"],stdout=subprocess.PIPE)
proc.communicate()[0]

rawDescription: How to list all types (running, zombie, etc.) of processes currently in linux with native python library

description: List all types (running, zombie, etc.) of processes currently in linux with native python library


code:
class PurchaseOrder(models.Model):
    product = models.ManyToManyField('Product', null =True)

    def get_products(self):
        return "<br />".join([p.products for p in self.product.all()])
    get_products.allow_tags = True

rawDescription: Getting HTML to linebreak in django admin's display


code:
import inspect

def logging(filename=False, level=DEFAULT_LOG_LEVEL):
    if filename is False:
        caller_file = inspect.getouterframes(inspect.currentframe())[1][3]
        # prints /home/foo/project/my_test.py
    ...

rawDescription: Python OS get current File name on imported module


code:
s = '{"key1": "value1", "key2": "value2", "key3": "value3",' + \
    ' "tableName": "my_table", "key5": "value5", "key6":"value6"}'

# using regular expressions
#   (quick and dirty)

import re
s = re.sub(
    '(?<="tableName":)\s*"(.*?)"',
    lambda match: ' "{}_temp"'.format(match.group(1)),
    s
)

# OR

# using ast.literal_eval
#   (less efficient but more bomb-proof)

import ast
d = ast.literal_eval(s)                     # parse to dict
d["tableName"] = d["tableName"] + "_temp"   # update field
s = str(d)                                  # cast back to string

rawDescription: Search and replace a word in a string in python


code:
class MyOpener(OpenerDirector):
    def __new__(cls, param1, param2):
        # init myHandler
        opener = build_opener(myHandler)
        opener.__class__ = MyOpener
        # further initialization
        return opener

rawDescription: Pythonic way of subclassing OpenerDirector


code:
from .models import Service,Carousel

class ServiceListView(generic.ListView):
    model = Service
    queryset = Service.objects.published()

    def get_context_data(self, **kwargs):
        context = super(ServiceListView, self).get_context_data(**kwargs)
        context['carousel_list'] = Carousel.objects.published()
        return context

rawDescription: Django - Listing many different models in one page


code:
from django.db import connection
connection.queries

rawDescription: How many queries are being generated?

description: How many queries are being generated


code:
lst = [(1, 4), (3, 8), (9, 2), (5, 6), (7, 0)]
next(y if 8 == x else x for x,y in lst if 8 in (x,y))
next(x[1] if 8 == x[0] else x[0] for x in lst if 8 in x)

rawDescription: Get paired element from a list of tuples in Python


code:
import subprocess
import threading
import time

def process(*args):
    return_code, threshold = None, 5

    def reader():
        try:
            while 1:
                process.status_check_time = time.time()
                process.process.stdout.readline()
        except:
            pass

    try:
        return_code = process.process.poll()
        curr_time = time.time()

        if return_code != None:
            raise Exception()

        if curr_time - process.status_check_time > threshold:
            process.process.kill()
            raise Exception()
    except:
        process.process = subprocess.Popen(args, bufsize = 0, shell = False, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
        (threading.Thread(target = reader)).start()

    return return_code

rawDescription: IPC mechanisms for python

description: IPC mechanisms for python


code:
from __future__ import division, print_function

def subtract_months(m):
    '''subtracts specified number of months from current date

    Parameters
    ----------
    m : integer
        how many months to subtract from today's date

    Returns
    -------
    date : datetime value'''

    yr  = dt.date.today().year
    mon = dt.date.today().month - m
    day = dt.date.today().day

    # test whether we went into another year
    if mon<=0:
        yr  -=  1
        mon = 12 + mon

    # test whether we have exceeded maximum number of days in month
    if day>calendar.monthrange(yr,mon)[1]:
        day = calendar.monthrange(yr,mon)[1]

    return dt.date(yr,mon,day)

import pandas as pd
import datetime as dt
import calendar

dates = pd.date_range('20160101','20170101',freq='1D')
data  = pd.np.random.randint(0,100,(5,367))

df = pd.DataFrame(data=data,index=list('ABCDE'),columns=dates)

# now add a new column
df['Last 3 Months'] = df.T.truncate(before=subtract_months(3),after=dt.date.today()).sum(axis=0)

rawDescription: Pandas calculate last few months data in new column


code:
import sys

memo = set()

def getsizeof(memo, obj):
    location = id(obj)
    if location in memo:
        return 0
    memo.add(location)
    total = sys.getsizeof(obj)
    if isinstance(obj, dict):
        for key in obj:
            total += getsizeof(memo, key)
            total += getsizeof(memo, obj[key])
    elif isinstance(obj, (list, tuple)):
        for item in obj:
            total += getsizeof(memo, item)
    elif isinstance(obj, (int, str)):
        pass
    elif hasattr(obj, '__slots__') and not hasattr(obj, '__dict__'):
        for name in obj.__slots__:
            total += getsizeof(memo, getattr(obj, name))
    else:
        raise TypeError('Unknown: ' + repr(type(obj)))
    return total

rawDescription: Is there a memory profiler for python2.7?


code:
hour, min, sec = "22:17:46.476000".split(":")
d3 = datetime.timedelta(hours=int(hour), minutes=int(minutes), seconds=float(sec))

rawDescription: Manipulation with datetime in python

description: Manipulation with datetime in python


code:
def on_change_code_id(self, cr, uid, ids, code_id, context=None):

    list_lines = []
    result = {'value': {}}
    req_obj = self.pool.get('code.requisition')

    data = req_obj.browse(cr, uid, code_id)

    for line in data.line_ids:
        list_lines.append({'product_id': line.product_id.id or False,
                           'product_qty': line.product_qty or 0,
                           'name': line.product_id.name,
                           'product_uom': line.product_uom_id.id,
                           'date_planned': time.strftime('%Y-%m-%d')
                        })

    result['value']['order_line'] = list_lines

    return result

rawDescription: set values for many2one child fields by function?

description: Set values for many2one child fields by function


code:
import pytest

@pytest.fixture
def fixture1():
    return "I'm fixture 1"

@pytest.fixture(scope='module')
def fixture2():
    return "I'm fixture 2"

@pytest.fixture(params=[1, 2])
def all_fixtures(request):
    your_fixture = request.getfuncargvalue("fixture{}".format(request.param))
    # here you can call your_fixture.do_something()
    your_fixture += " with something"
    return your_fixture

def test_all(all_fixtures):
    assert 0, all_fixtures

rawDescription: How can I access a pytest fixture by a string?

description: Access a pytest fixture by a string


rawDescription: Add the Http_X_Forwarded_For header in a request in python


code:
def half(x):

    if type(x) == float:
        return x / 2

    if type(x) == int:
        return x // 2

    if type(x) in (tuple, str):
         return x[:len(x)//2]

rawDescription: Division with str, float, int, and tuples


rawDescription: Create a Dictionary from a Dataframe With the Index as the Keys


code:
url = 'http://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss'
describe_text = urlopen(url).read()
description = findall('<description>(.+)</description>',describe_text)
global myVariable
myVariable = 1
x = description[myVariable]

#Button Functions
def next_button_description():
   global myVariable
   myVariable = myVariable + 1
   x = description[myVariable]
   return x

rawDescription: How to change list position in a loop

description: Change list position in a loop


code: [bean for bean in beans if bean.type == 'coffee']

rawDescription: Returns values from a for loop in python


code:
import wx
import wx.grid as gridlib

########################################################################
class RegularPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("pink")

########################################################################
class GridPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.grid = gridlib.Grid(self, style=wx.BORDER_SUNKEN)
        self.grid.CreateGrid(25,8)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.grid, 1, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        notebook = wx.Notebook(self)

        page = wx.SplitterWindow(notebook)
        notebook.AddPage(page, "Splitter")
        hSplitter = wx.SplitterWindow(page)

        panelOne = GridPanel(hSplitter)
        panelTwo = GridPanel(hSplitter)
        hSplitter.SplitVertically(panelOne, panelTwo)
        hSplitter.SetSashGravity(0.5)

        panelThree = RegularPanel(page)
        page.SplitHorizontally(hSplitter, panelThree)
        page.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Nested Splitters",
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: How to create a wxpython notebook with 2 panels splitted horizontally?

description: Create a wxpython notebook with 2 panels splitted horizontally


code:
desc=[d[0] for d in cursor.description]
result=[dict(zip(desc, line)) for line in cursor]

rawDescription: cx_Oracle query results to nested dictionary

description: Cx_Oracle query results to nested dictionary


code:
class LanguageChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
        self.language = kwargs.pop('language', None)
        super(LanguageChoiceField, self).__init__(*args, **kwargs)

    def label_from_instance(self, obj):
         # return the field you want to display
         if self.language:
             return getattr(obj, self.language)
         return obj.en

class RegistrationForm(forms.ModelForm):
    # your code
    self.fields['native'] = LanguageChoiceField(language=this_language, queryset=...)

rawDescription: How to iterate specific table column in django form

description: Iterate specific table column in django form


code:
u=BeautifulSoup('α')
u
u.p.contents[0]
u.p.contents[0].output_ready(formatter='html')

rawDescription: Convert BeautifulSoup NavigableString to use html entities


code:
import datetime
import matplotlib.pyplot as plt

x = ['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
    'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']
y = range(4)

x = [datetime.datetime.strptime(elem, '%a %b %d %H:%M:%S %Y') for elem in x]

(fig, ax) = plt.subplots(1, 1)
ax.plot(x, y)
fig.show()

rawDescription: How to plot timestamps in python using matplotlib?

description: Plot timestamps in python using matplotlib


code:
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

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

vertices = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

tupleList = zip(x, y, z)

poly3d = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))]
ax.scatter(x,y,z)
ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.5))
ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=0.2, linestyles=':'))

plt.show()

rawDescription: Transparency for Poly3DCollection plot in matplotlib


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

R, P = np.mgrid[:10, :2*np.pi:np.pi/50]
N = 50
plt.contourf(R*np.cos(P), R*np.sin(P), R, N) # <--- need better function
plt.pcolormesh(R*np.cos(P), R*np.sin(P), R) # <--- exactly what I want
# plt.imshow(R*np.cos(P), R*np.sin(P), R) #      something like this
plt.show()

rawDescription: Python / PyPlot- How can I specify the x/y-axis on plt.imshow?


code:
from django.contrib import admin, messages

class ExampleAdmin(admin.ModelAdmin):
    list_display = ('whatever', 'etc')

    def save_model(self, request, obj, form, change):
        obj.save()
        storage = messages.get_messages(request)
        for message in storage:
            # Examine message here.
            pass

rawDescription: Examine current messages in Django admin.py


code:
import re
re.search(r'^Stream\:\s([^\n]+)', f.read(), re.MULTILINE).group(1)

rawDescription: python: extracting (regex) pattern in a file without going through line by line (multiline search)

description: Python: extracting (regex) pattern in a file without going through line by line (multiline search)


code:
from functional import compose
from operator import attrgetter, itemgetter
my_list.sort(key=compose(itemgetter(item), attrgetter('attr')))

rawDescription: pythonic way of composing itemgetter and attrgetter?

description: Pythonic way of composing itemgetter and attrgetter


code:
from atexit import register

class BlaFile:
    def __init__(self, file_name):
        self.file_name = file_name
        self.file = open(file_name, 'rb')
        register(self.file.close)

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

    def do_stuff_with_file(self):
        return self.file.read(1)

rawDescription: Should a context object work when used without 'with'?


code: df.loc[df.isnull().any(axis=1), :] = np.nan

rawDescription: Pandas replace all items in a row with NaN if one value is NaN


code:
from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        form = driver.find_element_by_name("move")
        break
    except NoSuchElementException:
        continue

button = form.find_element_by_xpath("following-sibling::button")
button.click()

rawDescription: Selenium with Python - Wait indefinitely until an input box is present


code:
def func(dna_template):
    dna2rna =  {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
    # take every base and translate it to rna and join all rna-bases to a string
    return ''.join(dna2rna.get(base) for base in dna_template)

func('ATCG')

Out:'UAGC'

rawDescription: Use a dictionary to provide the mapping of DNA to RNA bases


rawDescription: Get the path of the current TTY in Python


code: [foo.bar for foo in foos]

rawDescription: Return a List of Member Variables from a List of Objects?


code:
arr = [1, 2, 3, 4, 5, 6, 7]
selected = [arr[i] for i in [0, 4, 2]]
selected

rawDescription: Select arrays from a list

description: Select arrays from a list


code: tags = fields.ToManyField('django_app.api.TagsResource', attribute=lambda bundle: bundle.obj.tags.filter(tags__deleted=0))

rawDescription: Tastypie, filtering many to many relationships


code: alist = [ x['name'] for x in anime.info['Genre']]

rawDescription: Output loop result into a list

description: Output loop result into a list


code:
import logilab.common.compat
from logilab.common.compat import builtins
logilab.common.compat.__file__

rawDescription: Running Pylint on Windows -> ImportError: cannot import from builtins


code:
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
somestr = p.stdout.readline()

rawDescription: Getting a string from subprocess.call?

description: Getting a string from subprocess.call


code: __path__.extend([os.path.join(__path__[0],chr(y)) for y in range(ord('a'),ord('z')+1)])

rawDescription: Add a subdirectory to a python namespace


code:
import sys
sys.path.insert( 0, '../a' )
import Util

rawDescription: Python access to Parent Directory

description: Python access to Parent Directory


code:
df = df.set_index(df['yr'].apply(lambda x: datetime.datetime(x, 1, 1)))
df = df.resample('A')

df['lagval'] = df['val'].shift(1)
df = df[pd.notnull(df['yr'])]

rawDescription: Using shift() with unevenly spaced data

description: Using shift() with unevenly spaced data


code:
budget = 0
itemCost = 0
cartTotal = 0

on = "TRUE"

print("Hello! Welcome to the best grocery store ever!")
budget = float(input("What is your budget for today?"))
while on == "TRUE" :
    itemCost = input("Please tell me the cost of the most recent item in your cart. Type ALL DONE to quit. ")
    if itemCost == "ALL DONE" :
        on = "FALSE"

    elif itemCost.isdigit() :
        cartTotal += float(itemCost)
        if cartTotal < budget :
            print("Ok, the items in your cart cost a total of ", cartTotal)
            print ("Your budget is ", budget, " you have spent ", cartTotal, " you have ", budget - cartTotal, " left over.")
        else :
            print("You are a horrible budgeter!")
            break
    else :
        print("Invalid entry!") #If neither a number nor ALL DONE was entered, this happens
        continue

rawDescription: How to add multiple user inputs in Python

description: Add multiple user inputs in Python


code:
import matplotlib.cm as cm

ab = np.array(abundance)
gs = np.array(grain_size)
ab_norm = ab/ab.max()*100
plt.matshow([ab_norm], cmap=cm.gist_rainbow_r)
plt.xticks(range(7), gs)
plt.yticks(range(1), ["abundance"])
plt.colorbar()
plt.show()

rawDescription: 2D Heat Map using matplot lib

description: 2D Heat Map using matplot lib


code:
class A(object):
  foo = 'bar'  # Notice that this isn't in an __init__ function definition

a = A()        # Just creating two distinct instances of A
b = A()
A.foo = 'baz'  # Now, I'm setting the class attribute
b.foo
a.foo

rawDescription: Most pythonic way to handle both (1) general properties of a type of object with (2) individual properties of an instance of that object


code:
class Ray:
    def __init__(name, *other_args):
        self.name = name

    def __repr__(self):
        return '<Ray({!r}, ....>'.format(self.name)

rawDescription: Return the name of a variable rather than its object reference code


rawDescription: Checking if all elements of a List of Lists are in another List of Lists Python


code: return next(dictionary.itervalues())

rawDescription: Pythonic way to access arbitrary element from dictionary


rawDescription: A configuration file that can be read by python and shell


code:
confirm_links = 'To confirm this order'
deny_links = '\nTo deny this order'
email=EmailMessage('title_text',  confirm_links+deny_links, to=['youremail@gmail.com'])
email.content_subtype = "html"
email.send()

rawDescription: Making a program that sends an email which hyperlinks text in django


code:
# sqlite (filename) CELERY_RESULT_BACKEND = ‘db+sqlite:///results.sqlite’
# mysql CELERY_RESULT_BACKEND = ‘db+mysql://scott:tiger@localhost/foo’
# postgresql CELERY_RESULT_BACKEND = ‘db+postgresql://scott:tiger@localhost/mydatabase’
# oracle CELERY_RESULT_BACKEND = ‘db+oracle://scott:tiger@127.0.0.1:1521/sidname’

rawDescription: What are some of the fastest ways to process this?


code:
import time
import concurrent.futures

x = [3, 1, 2]

def sleeper(secs):
    time.sleep(secs)
    print('I slept for {} seconds'.format(secs))
    return secs

# returns in the order given
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    print(list(executor.map(sleeper, x)))

# I slept for 1 seconds
# I slept for 2 seconds
# I slept for 3 seconds
# [3, 1, 2]

# returns in the order completed
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    futs = [executor.submit(sleeper, secs) for secs in x]
    print([fut.result() for fut in concurrent.futures.as_completed(futs)])

# I slept for 1 seconds
# I slept for 2 seconds
# I slept for 3 seconds
# [1, 2, 3]

rawDescription: Python's `concurrent.futures`: Iterate on futures according to order of completion


code:
class Toy(object):
    def __init__(self, x):
        self.x = abs(x)
    def __repr__(self):
        return 'Toy({})'.format(self.x)
    @classmethod
    def from_string(cls, s):
        return cls(int(s))

Toy.from_string('5')

rawDescription: What's the best way to extend the functionality of factory-produced classes outside of the module in python?


code:
s1 = pd.Series(np.random.randint(-10, 10, 5))
s2 = pd.Series(np.random.randint(-10, 10, 5))
s1.combine(s2, f)

rawDescription: Is it possible to apply user defined functions to series in pandas?


code:
import matplotlib.pyplot as plt
plt.bar(pos_freq['pos'], pos_freq['freq'])
plt.show()

rawDescription: python plot frequency with continuous integer labeled x-axis

description: Python plot frequency with continuous integer labeled x-axis


rawDescription: How to prevent text overlap on tkinter canvas

description: Prevent text overlap on tkinter canvas


code:
def clear_list(l):
    out = []
    for ll in l:
        if ll is None:
            continue
        if isinstance(ll, list):
             ll = clear_list(ll)
             if not ll:
                 continue
        out.append(ll)
    return out

rawDescription: Clean list or list of lists of all None or Empty lists in Python


code:
class IndexHandler(RequestHandler):
    @asynchronous
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        self.remaining = 3
        self.responses = {}
        client.fetch("http://localhost/b.php", functools.partial(self.on_response, 'b'))
        client.fetch("http://localhost/c.php", functools.partial(self.on_response, 'c'))
        client.fetch("http://localhost/d.php", functools.partial(self.on_response, 'd'))

    def on_response(self, key, response):
        self.responses[key] = response
        self.remaining -= 1
        if self.remaining == 0:
            self.write(self.responses['b'].body)
            self.write(self.responses['c'].body)
            self.write(self.responses['d'].body)
            self.finish()

rawDescription: python tornado async client fetch call with call back fails some times

description: Python tornado async client fetch call with call back fails some times


rawDescription: How to access multiple fields from a numpy.array?

description: Access multiple fields from a numpy.array


code:
def dashrepl(matchobj):
    if matchobj.group(0) == '-': return ' '
    else: return '-'
re.sub('-{1,2}', dashrepl, 'pro----gram-files')

rawDescription: Python using result of function for Regular Expression Substitution


code:
def on_click(self, event):
    tree = event.widget
    item_name = tree.identify_row(event.y)
    if item_name:
        tags = tree.item(item_name, 'tags')
        if tags and (tags[0] == 'selectable'):
            tree.selection_set(item_name)

rawDescription: Making a node in Tkinter Treeview unselectable


code:
def book(request):
    if request.method == 'POST':
        formset = ArticleFormSet(request.POST)
        if formset.is_valid():
            for data in formset.cleaned_data:
                Article.objects.create(title=data['title'])
            return HttpResponseRedirect(reverse('firstapp.views.book'))
    else:
        formset = ArticleFormSet()
    return render_to_response('get.html',{'formset': formset},
                              context_instance = RequestContext(request))

rawDescription: formset for multiple form

description: Formset for multiple form


code:
class PendingApplicationView(ListView):
    def get_queryset(self):
        return Application.objects.filter(status='IP', principle_investigator=self.request.user)

# url pattern
url(r'^application/pending/$', PendingApplicationView.as_view()),

rawDescription: Django: Accessing Logged in User when specifying Generic View in urlpatterns


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

data = np.random.random((20, 3))

plt.imshow(data, interpolation='none', aspect=3./20)

plt.xticks(range(3), ['a', 'b', 'c'])

plt.jet()
plt.colorbar()

plt.show()

rawDescription: Qualitative heatmap plot python

description: Qualitative heatmap plot python


code:
import ToBuildOrNot
needsBuild = ToBuildOrNot.run() # or whatever you call your top-level function

rawDescription: How do scan a script for return values from a upper script in python?


code:
from nltk.corpus import wordnet as wn

def penn2morphy(penntag, returnNone=False):
    morphy_tag = {'NN':wn.NOUN, 'JJ':wn.ADJ,
                  'VB':wn.VERB, 'RB':wn.ADV}
    try:
        return morphy_tag[penntag[:2]]
    except:
        return None if returnNone else ''

rawDescription: Python: map NLTK Stanford POS tags to WordNet POS tags


code:
elem = obr.webframe.findAllElements('.qust input').toList()[1]
js_click = """
           var evt = document.createEvent("MouseEvents");
           evt.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, this);
           this.dispatchEvent(evt);
           """
elem.evaluateJavaScript(js_click)

rawDescription: PyQt - Form does not submit

description: PyQt - Form does not submit


code:
from multiprocessing import Pool

# you could define `func`, `a` here

if __name__=="__main__":
    p = Pool() # use all available CPU cores
    b = p.map(func, a)

rawDescription: Parallelizing multiplication of vectors-like computation in python


rawDescription: How do I store a numpy array as an object in a pandas dataframe?

description: Store a numpy array as an object in a pandas dataframe


code:
regex_keywords = re.findall(r"This|Words|Annotate", string, re.I)
highlight(string, regex_keywords)

rawDescription: Untangle re.findall capturing groups: 'list' object has no attribute 'join'


code: fn = os.path.join(os.path.dirname(__file__), 'my_file')

rawDescription: Python - how to refer to relative paths of resources when working with code repository


code:
names = ['john', 'george', 'ringo', 'paul']
print("', '".join(names))

rawDescription: Change a list to a string with specific formatting


code:
data = [...]
worksheet.set_column(0, len(data), 15, formater)

rawDescription: python xlsxwriter, set border dynamically

description: Python xlsxwriter, set border dynamically


code:
import __builtin__
__builtin__.list = set
list()
[]

rawDescription: Creating a list in Python- something sneaky going on?


code:
import time
import subprocess
import queue
import threading

TIMEOUT_POLLINGINTERVAL = 0.5

class ShellCall():
    def __init__(self):
        self._popen = None
        """ :type: subprocess.Popen """
        self._stdOutQueue = None
        """ :type: queue.Queue """
        self._stdErrQueue = None
        """ :type: queue.Queue """
        self._stdOut = []
        self._stdErr = []

    def __del__(self):
        if self._popen and self._popen.poll() is None:
            self._popen.kill()

    def call(self, command, shell=False):
        """
        Execute a shell command

        :param command: command to be executed
        :type command: str | list[str]
        :param shell: If shell is True, the specified command will be executed through the shell
        :type shell: bool
        :rtype: None
        """
        if shell:
            command = command.encode('utf-8')
        else:
            command = [item.encode('utf-8') for item in command]
        self._popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell, bufsize=0)
        self._stdOutQueue = self._getAsyncReadQueue(self._popen.stdout)
        self._stdErrQueue = self._getAsyncReadQueue(self._popen.stderr)

    def _getAsyncReadQueue(self, sourcePipe):
        """
        Create a thread to read from pipe in asynchronous mode, get queue to receive data from pipe

        :param sourcePipe: Pipe to read from
        :type sourcePipe: pipe
        :return: Queue to receive read data
        :rtype: queue.Queue
        """
        newQueue = queue.Queue()
        newThread = threading.Thread(target=self._enqueueOutput, args=(sourcePipe, newQueue))
        newThread.daemon = True  # thread dies with the program
        newThread.start()
        return newQueue

    @staticmethod
    def _enqueueOutput(sourcePipe, outputQueue):
        """
        Read from pipe and write to the queue

        :param sourcePipe: Pipe to read from
        :type sourcePipe: pipe
        :param outputQueue: Queue to write to
        :type outputQueue: queue.Queue
        """
        for line in iter(sourcePipe.readline, b''):
            outputQueue.put(line)

    def waitNotNoneReturnCode(self, timeout, *, checkCallback=None):
        """
        Wait until any return code

        :param timeout: Timeout for executed command (sec). If timeout expired - ShellException raised
        :type timeout: float
        :param checkCallback: Any callable that will be used to check is shell call finished
        :type checkCallback: callable
        :rtype: None
        """
        self._wait(timeout, notNoneReturnCode=True, checkCallback=checkCallback)

    def waitNoErrorReturnCode(self, timeout, *, checkCallback=None):
        """
        Wait until success return code '0'. Otherwise raise ShellException

        :param timeout: Timeout for executed command (sec). If timeout expired - ShellException raised
        :type timeout: float
        :param checkCallback: Any callable that will be used to check is shell call finished
        :type checkCallback: callable
        :rtype: None
        """
        self._wait(timeout, notNoneReturnCode=True, noErrorReturnCode=True, checkCallback=checkCallback)

    def waitNoStdErr(self, timeout, *, checkCallback=None):
        """
        Wait until success return code '0' and empty stderr. Otherwise raise ShellException

        :param timeout: Timeout for executed command (sec). If timeout expired - ShellException raised
        :type timeout: float
        :param checkCallback: Any callable that will be used to check is shell call finished
        :type checkCallback: callable
        :rtype: None
        """
        self._wait(timeout, notNoneReturnCode=True, noErrorReturnCode=True, noStdErr=True, checkCallback=checkCallback)

    def waitStdOut(self, timeout, *, checkCallback=None):
        """
        Wait until success return code '0', empty stderr and not empty stdout. Otherwise raise ShellException

        :param timeout: Timeout for executed command (sec). If timeout expired - ShellException raised
        :type timeout: float
        :param checkCallback: Any callable that will be used to check is shell call finished
        :type checkCallback: callable
        :rtype: None
        """
        self._wait(timeout, notNoneReturnCode=True, noErrorReturnCode=True,
                   noStdErr=True, stdOut=True, checkCallback=checkCallback)

    def _wait(self, timeout, *, pollingTime=TIMEOUT_POLLINGINTERVAL,
              notNoneReturnCode=False, noErrorReturnCode=False, noStdErr=False, stdOut=False, checkCallback=None):
        """
        Raise ShellException if conditions not satisfied (see :func:`checkCallResults`).
        Raise ShellException if conditions not satisfied too long.

        :param timeout: Timeout for executed command (sec). If timeout expired - ShellException raised
        :type timeout: float
        :param pollingTime: Time interval length to check result of command execution
        :type pollingTime: float
        :rtype: None
        """
        startTime = time.time()
        while True:
            if self._checkCallResults(notNoneReturnCode=notNoneReturnCode, noErrorReturnCode=noErrorReturnCode,
                                      noStdErr=noStdErr, stdOut=stdOut, checkCallback=checkCallback):
                return
            # exception due to timeout
            if time.time() - startTime > timeout:
                raise ShellException('Shell call not finished too long', self)
            time.sleep(pollingTime)

    def _checkCallResults(self, notNoneReturnCode=False, noErrorReturnCode=False,
                          noStdErr=False, stdOut=False, checkCallback=None):
        """
        Raise ShellException if noErrorReturnCode=True and shell call return not 0 return call
        Raise ShellException if noStdErr=True and shell call print anything to stderr

        :param notNoneReturnCode: return True only if shell call return any return call
        :type notNoneReturnCode: bool
        :param noErrorReturnCode: return True only if shell call return 0 return code
        :type noErrorReturnCode: bool
        :param noStdErr: return True only if shell call print nothing to stderr
        :type noStdErr: bool
        :param stdOut: return True only if shell call print anything to stdout
        :type stdOut: bool
        :param checkCallback: Any callable that will be used to check is shell call finished,
                              positional arguments, keyword arguments
        :type checkCallback: callable, args, kwargs
        :return: True if conditions are satisfied
        :rtype: bool
        """
        # exceptions
        if noErrorReturnCode:
            if self.getReturnCode() is not None and self.getReturnCode() > 0:
                raise ShellException('Shell call finished with error return code', self)
        if noStdErr:
            if len(self.getStdErr()) > 0:
                raise ShellException('Shell call have non-empty stderr', self)
        # break loop
        notNoneReturnCodeCondition = (self.getReturnCode() is not None) if notNoneReturnCode else True
        noErrorReturnCodeCondition = (self.getReturnCode() == 0) if noErrorReturnCode else True
        notStdErrCondition = (len(self.getStdErr()) == 0) if noStdErr else True
        stdOutCondition = (len(self.getStdOut()) > 0) if stdOut else True
        callbackCondition = checkCallback() if checkCallback else True
        if notNoneReturnCodeCondition and noErrorReturnCodeCondition and \
                notStdErrCondition and stdOutCondition and callbackCondition:
            return True
        else:
            return False

    def getReturnCode(self):
        """
        Get return code of the process

        :return: return code of the child process or None if process is not terminated yet
        :rtype: int|None
        """
        return self._popen.poll()

    def getStdOut(self):
        """
        Get list with stdout lines

        :rtype: list[str]
        """
        self._stdOut += self._readAllQueue(self._stdOutQueue)
        return self._stdOut

    def getStdErr(self):
        """
        Get list with stderr lines

        :rtype: list[str]
        """
        self._stdErr += self._readAllQueue(self._stdErrQueue)
        return self._stdErr

    @staticmethod
    def _readAllQueue(sourceQueue):
        lines = []
        try:
            while True:
                line = sourceQueue.get_nowait()  # or q.get(timeout=.1)
                line = line.decode('utf-8').rstrip()
                lines.append(line)
        except queue.Empty:
            return lines

    def __repr__(self):
        stdOut = str.join(' ', self.getStdOut())
        stdOut = (stdOut[:1000] + '...') if len(stdOut) > 1000 else stdOut
        stdErr = str.join(' ', self.getStdErr())
        stdErr = (stdErr[:1000] + '...') if len(stdErr) > 1000 else stdErr
        return '<ShellCall(command={}, ReturnCode={}, stdout="{}", stderr="{}")>'. \
            format(self._popen.args, self.getReturnCode(), stdOut, stdErr)

class ShellException(Exception):
    def __init__(self, description, shellCall):
        """
        :param description: test description of the error
        :type description: str
        :param shellCall: shell call object used to execute a command
        :type shellCall: ShellCall
        :rtype: None
        """
        super(Exception, self).__init__(description, shellCall)

    def getShellCall(self):
        """
        Get shell call object used to execute a command

        :rtype: ShellCall
        """
        description, shellCall = self.args
        return shellCall

rawDescription: Hard kill a python sub-thread

description: Hard kill a python sub-thread


code:
import weakref
class A(object): pass
a = A()
A.__weakref__
descriptor = A.__dict__['__weakref__']
descriptor.__get__(None, A)
a = A()
a.__weakref__ is None
descriptor.__get__(a) is None
wr = weakref.ref(a)  # add a weak reference
wr
a.__weakref__
descriptor.__get__(a)

rawDescription: Why is class.__weakref__ not None, while instance.__weakref__ is None?


code:
encoded = data.encode('UTF-8')
count = len(encoded)
msb, lsb = divmod(count, 256) # split to two bytes
outfile.write(chr(msb))
outfile.write(chr(lsb))
outfile.write(encoded)

rawDescription: Creating Java DataInputStream data in Python


code:
d = {}
with open(f) as fin:
    for l in fin:
        x = l.split()
        d[x[0][:-1]] = int(x[1])
return d

rawDescription: Python comprehension consolidation

description: Python comprehension consolidation


code:
def group(seq, sep):
    g = []
    for element in seq:
        if element == sep:
            yield g
            g = []
            continue
        g.append(element)
    yield g

List1 = [1, "/", 2, "/", 3]
List2 = [11, "/", 12, 13, 14, "/", 15, 16, 17, 18]

List1_grouped = list(group(List1, "/"))
List2_grouped = list(group(List2, "/"))
# List1_grouped = [[1], [2], [3]]
# List2_grouped = [[11], [12, 13, 14], [15, 16, 17, 18]]

for index, items in zip(List1_grouped, List2_grouped):
    for item in items:
        print(index[0], item)
# 1 11
# 2 12
# 2 13
# 2 14
# 3 15
# 3 16
# 3 17
# 3 18

rawDescription: combine different long lists with determine in python

description: Combine different long lists with determine in python


code:
def foo():
    num = int(input("Type a number: "))             # ^
    while (num != 9999):                            # |
       add = 0                                      # |
       counter = 0                                  # |
       while (num != 0):                            # |
          add = add + num                           # |
          counter += 1                              # LOCAL
          num = int(input("Type another value: "))  # |
       print(round(soma/contador,3))                # |
       num = int(                                   # |
          input((                                   # |
              "Next sequence of values. "           # |
              "Type a number: "                     # |
          ))                                        # |
       )                                            # V

rawDescription: Understanding while in python

description: Understanding while in python


code:
def parse(flie):
    pass
    # this is where you parse the file.

lower = raw_input("Enter start: ") # assume int
upper = raw_input("Enter end: ") # assume int and >= lower
files = [str(i)+'.txt' for i in range(int(lower),int(upper)+1)]

for file in files:
    parse(file)

rawDescription: python use raw_input for range filenames

description: Python use raw_input for range filenames


code:
for cnt in range(n):
    old_guess = guess
    guess = (guess + x/guess)/2
    print ("Improvement", cnt+1, ": next guess is", guess)
    if abs(old_guess-guess) < 0.00001:
        break

print()
print ("The final guess (after {0} improvements) is {1}".format(cnt+1, guess))
print ("math.sqrt(x) returns {0}".format(math.sqrt(x)))

rawDescription: how do i edit this newton method in python to loop until the difference between consecutive guesses is less than 0.00001?

description: Edit this newton method in python to loop until the difference between consecutive guesses is less than 0.00001


code: return '<img src="%s" width="100" height="100" />' % self.logo.url

rawDescription: How to get Django ImageField name

description: Get Django ImageField name


code:
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
ciphertext = obj.encrypt(message)
ciphertext
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
obj2.decrypt(ciphertext)

rawDescription: Encrypt file in python with aes

description: Encrypt file in python with aes


code:
import time
import curses

ENTER_KEY = (curses.KEY_ENTER, ord('\n'), ord('\r'))

def run(win, timeout=3): # timeout in seconds
    curses.echo()
    win.timeout(0) # Non-block read.

    line = 0
    while True:
        win.addstr(line, 0, "Enter something: ")
        s = []
        start = time.time()
        run = True
        while run:
            c = win.getch()
            time_taken = time.time() - start

            if c < 0:
                pass
            elif c in ENTER_KEY:
                break
            else:
                s.append(chr(c))

            if time_taken >= timeout:
                # Out of time.
                s.append(-1)
                run = False

        if len(s) == 0:
            break
        if s[-1] == -1:
            s.pop()
        answer = ''.join(s)
        win.addstr(line + 1, 0, "Your input was: %s" % answer)
        line += 2

curses.wrapper(run)

rawDescription: Unix Python - Get terminal input without pressing enter after timeout


code: docopt('./myapp [-a [-b BVAL] | -c]')

rawDescription: Python ArgumentParser nested arguments

description: Python ArgumentParser nested arguments


code:
file = ['page1.txt', 'page2.txt', 'page3.txt', 'page4.txt']
pagecount = len(file)
page = 1                    # initialize to a default page

if inp == '1':
    page = 1
    read(file[page-1])      # pages are 1-4, subscripts are 0-3

# ... pages 2-4 go here

elif inp == '+':              # whatever key you use for Next
    page = min(page+1, pagecount)    # don't go beyond last page
    read(file[page-1])

elif inp == '-':              # switch statements use "if .. elif .. elif .. else"
    page = max(page-1, 1)
    read(file[page-1])

rawDescription: Next and Previous Logic in e-reader application in Python?


code:
ax = gca()
ax.xaxis.set_major_formatter(FuncFormatter(myfunc))

rawDescription: plt.figure() vs subplots in Matplotlib

description: Plt.figure() vs subplots in Matplotlib


code: [list(x[1]) for x in itertools.groupby(['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'], lambda x: x=='|') if not x[0]]

rawDescription: Make Python Sublists from a list using a Separator


code:
from flask import request
request.headers.get('User-Agent')

rawDescription: How do I get the user agent with Flask?

description: Get the user agent with Flask


code:
class FooView(TemplateView):
    def get_context_data(self, **kwargs):
        bar = self.bar

    def post(self, request, id, *args, **kwargs):
        self.bar = Bar.objects.get(id=id)
        ...

rawDescription: Django: Passing variable from get_context_data() to post()


code:
like = browser.find_elements_by_class_name('like_picto_unselected')
for x in range(0,len(like)):
    if like[x].is_displayed():
        like[x].click()

rawDescription: Using Selenium in Python to click through all elements with the same class name


rawDescription: Python regex - how to detect repetitions


code:
def modify(path):
    out = []
    f = open(path)
    for line in f:
        if some_condition:
            out.append(edited_line) #make sure it has a \n at the end
        else:
            out.append(original_line)
    f.close()
    with open(path,'w') as f:
        for line in out:
            f.write(line)

rawDescription: Appends text file instead of overwritting it


code:
class CourseUpdateView(UpdateView):
    # [...] your dispatch method

    def get_object(self):
        # it doesn't matter how many times get_object is called per request
        # it should not do more than one request
        if not hasattr(self, '_object'):
            self._object = super(CourseUpdateView, self).get_object()
        return self._object

rawDescription: Django Class Based View: Validate object in dispatch


code:
from collections import defaultdict

d = defaultdict(int)

with open('file') as fh:
    for line in fh:
        word, count = line.split()
        d[word] += count

rawDescription: Python summing frequencies in a file

description: Python summing frequencies in a file


code:
import pandas
mixture = [dict(lda1[x]) for x in corpus1]
pandas.DataFrame(mixture).to_csv("output.csv")

rawDescription: How to save gensim LDA topics output to csv along with the scores?

description: Save gensim LDA topics output to csv along with the scores


code: fileList = server_handler.outfiles

rawDescription: Removing elements from list and importing list into another code


code: cidrs = netaddr.ip_range_to_cidrs(ip_start, ip_end)

rawDescription: List of IP addresses in Python to a list of CIDR


code:
from selenium.webdriver.common.action_chains import ActionChains

canvas = self.driver.find_element_by_id("myCanvas")
drawing = ActionChains(self.driver)\
    .click_and_hold(canvas)\
    .move_by_offset(-10, -15)\
    .move_by_offset(20, 32)\
    .move_by_offset(10, 25)\
    .release()
drawing.perform()

rawDescription: Can I use Selenium Python to draw on a canvas?

description: Use Selenium Python to draw on a canvas


code:
df['platform'] = df.apply(
    lambda k: httpagentparser.detect(k['useragent']).get('platform', {}).get('name'),
    axis=1
)

rawDescription: How to add columns to pandas dataframe based on dictionary keys?

description: Add columns to pandas dataframe based on dictionary keys


code:
from fabric.api import hosts, env

@hosts(['ec2-54-xxx.xxx.xxx.compute-1.amazonaws.com'])
def bootstrap():
    env.user = "ubuntu"
    env.key_filename = "/home/ubuntu/omg.pem"

rawDescription: Python Fabric - No hosts found. Please specify (single) host string for connection:


code:
with open('a 100mb or so file') as fin:
    filedata = fin.read()

rawDescription: Why do python programs run very slow the first time?


code:
import pandas as pd
import random
import matplotlib.pyplot as plt

n = 100
# this is probably a strange way to generate random data; please feel free to correct it
df = pd.DataFrame({"X": [random.choice(["A","B","C"]) for i in range(n)],
                   "Y": [random.choice(["a","b","c"]) for i in range(n)],
                   "Z": [random.gauss(0,1) for i in range(n)]})
grouped = df.groupby(["X", "Y"])

df2 = pd.DataFrame({col:vals['Z'] for col,vals in grouped})

meds = df2.median()
meds.sort(ascending=False)
df2 = df2[meds.index]
df2.boxplot()

plt.show()

rawDescription: How can I sort a boxplot in pandas by the median values?

description: Sort a boxplot in pandas by the median values


code:
expected_return = MagicMock()

def fake_filter(**kwargs):
    if 'tags__name__in' in kwargs:
        raise FieldError()
    if 'tags__icontains' in kwargs:
        return expected_return
    raise ValueError("Neither expected kwarg present")

mock_queryset = MagicMock()
mock_queryset.filter = fake_filter

rawDescription: Django / Python unittest side_effect usage


code:
from numpy import linspace,meshgrid,pi,cos,sin
from matplotlib.pyplot import figure, show

x=linspace(0,100);y=linspace(0,100)
X,Y=meshgrid(x,y)
Z=cos(3*pi*X)+sin(6*pi*Y)

fig=figure()
ax=fig.add_subplot(111)
pc=ax.pcolormesh(X,Y,Z,vmin=0.3,vmax=0.6)
fig.colorbar(pc)
show()

rawDescription: Adjusting pcolormesh colorbar to focus on a specific plot region?


code:
Music.objects.filter(releaseday__lte=today) \
             .extra({'vrank': 'CASE WHEN hotrank=0 THEN 11 ELSE hotrank END'}) \
             .order_by('vrank','-releaseday')

rawDescription: Ordering a queryset while ignoring a value


code:
n=3
N=2
df_list=[]
for i in range(n):
    df_list.append(pd.concat([df.apply(np.random.choice, axis=1) for i in range(N)], ignore_index=True))
new_df = pd.concat(df_list, axis=1, ignore_index=True).T

rawDescription: randomly select one element on every row

description: Randomly select one element on every row


code:
import functools
l = [1, 2, 3]
my_gen = functools.partial(next, iter(l))
my_gen()
my_gen()
my_gen()
my_gen()

rawDescription: Creating a generator in python

description: Creating a generator in python


code: dictionary = dict(zip(destinations, re.split(r'\t', line)))

rawDescription: Splitting a string based on a list

description: Splitting a string based on a list


code:
drinks = ['cola', 'water', 'beer', 'wine']

drink = raw_input ("What did you drink? %s" % ', '.join(drinks))

if drink in drinks:
    print('you chose ' + drink)
else:
    print('invalid choice')

rawDescription: Printing out Python list

description: Printing out Python list


code:
# ...Code, imports...
@app.route('/cvolume/')
def volume():
    return 'Hello world!'

@app.route('/volume/')
def volume_2():
    return 'Hello You!'

@app.route('/test/')
def test():
    return redirect(url_for('volume'))

rawDescription: Would changing URL route in flask break the code?


code:
from mpl_toolkits.basemap import Basemap, cm
import numpy as np
import matplotlib.pyplot as plt

# create figure and axes instances
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
# create polar stereographic Basemap instance.
m = Basemap(projection='stere',lon_0=0,lat_0=30.,lat_ts=45.,\
            width=10000000, height=4000000,
            rsphere=6371200.,resolution='l',area_thresh=10000)
m.drawcoastlines()
m.drawstates()
m.drawcountries()
# draw parallels.
parallels = np.arange(0.,90,5.)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
# draw meridians
merid_values = np.arange(0.,360.,10.)
meridians = m.drawmeridians(merid_values,labels=[0,0,0,1],fontsize=10)
for m in meridians:
    try:
        meridians[m][1][0].set_rotation(45)
    except:
        pass
plt.show()

rawDescription: Rotating Basemap Meridian labels on x-axis


code:
center_a = center.tolist()   # Convert numpy array into list
center_b = center_1.tolist() # Convert numpy array into list
np.allclose(center_b,center_a,rtol=1e-04, atol=1e-04)

rawDescription: Truncating all the elements(floats) in a numpy.ndarray


rawDescription: Does python execute imports on importation


rawDescription: Creating a Regex That Applies to multiple lengths of strings and characters


code:
def filters_by_distance(i):
    '''Generate filters by distance from i'''
    sorted_indices = sorted(range(len(filters)), key=lambda j: abs(j-i))
    return (filters[j] for j in sorted_indices)

rawDescription: python iterating through lists

description: Python iterating through lists


code:
def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        if len(o) == 0:
            yield ''
        for value in o:
            for subvalue in traverse(value):
                yield subvalue
    else:
        yield o

rawDescription: Flattening nested list

description: Flattening nested list


code:
dict = {};

dict[key] = value;

rawDescription: How can i name object "keys" programmatically in JavaScript?

description: Name object "keys" programmatically in JavaScript


code: plt.ylim(0, df2.shape[1])

rawDescription: Centering ticks on row of a heatmap

description: Centering ticks on row of a heatmap


code:
from django.contrib.gis.db import models

class Location(models.Model):
    ...
    objects = models.GeoManager()

rawDescription: Getting geodjango query to return distance as an attribute?


code:
records = []
for record in SeqIO.parse(open(file, 'rU'), 'fasta', generic_protein):
    record_id = re.sub(r'\d+_(\d+_\d\#\d+)_\d+', r'\1', record.id)

    if ( not reference_sequence ):
      reference_sequence = record.seq
      reference_name     = record_id
      #continue
    records.append([reference_name, record_id, compare_seqs(reference_sequence, record.seq)])

with csv.writer(open('file.csv', 'w')) as fp:
    fp.writerows(records)  # note that it's not writerow but writerows which allows you to write muptiple rows

rawDescription: Writing list to CSV

description: Writing list to CSV


code:
guess = raw_input("Enter your guess: ")
try:
    guess = int(guess)
except ValueError:
    guess = float(guess)

rawDescription: Is it possible to turn a raw_input into a either a float or an int depending on what the user enters?


code:
def recipe_edit(request, pk):
    recipe = get_object_or_404(Recipe, pk=pk)
    if request.method == "POST":
        form = RecipeForm(request.POST, instance=recipe)
        if form.is_valid():
            recipe = form.save(commit=False)
            recipe.user = request.user
            recipe.save()
            return redirect('recipe_detail', pk=recipe.pk)
    else:
        form = RecipeForm(instance=recipe)
    return render(request, 'recipe_edit.html', {'form': form, 'recipe':recipe})

rawDescription: How to update an existing record instead of creating a new one in django?

description: Update an existing record instead of creating a new one in django


code:
#!/usr/bin/python
from PIL import Image
import sys

img = Image.open(sys.argv[1])
img = img.convert("RGBA")

pixdata = img.load()

# Clean the background noise, if color != white, then set to black.

for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] == (255, 255, 255, 255):
            pixdata[x, y] = (0, 0, 0, 255)

rawDescription: Replacing a single color in PIL?

description: Replacing a single color in PIL


rawDescription: Selecting pandas cells with None value

description: Selecting pandas cells with None value


code:
import datetime
import calendar

def validate_date(year, month, date):
    """Returns True if valid date else False"""
    try:
        datetime.datetime(year, month, date)
        return True
    except ValueError:
        return False

rawDescription: Date Validity and Leap Year Checker

description: Date Validity and Leap Year Checker


code:
directory, base = os.path.split(filename)
new_filename = os.path.join(directory, 'analyzed_' + filename)

rawDescription: How to create the output text file in the respective sub directories in Python?

description: Create the output text file in the respective sub directories in Python


code:
def get_initial(self):
    super(PurchaseCreate, self).get_initial()
    try:
        latest_tag = Purchase.objects.latest('tag').tag
        print(latest_tag)
        next_tag = latest_tag + 1
    except:
        next_tag = 1
    initial = {'tag': next_tag}
    return initial

rawDescription: Django- Updating data sent from a generic CBV? (Refreshing a view's variable)


code:
class Singleton(type):
    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        cls.INSTANCE = None

    def __call__(cls, *args, **kwargs):
        if cls.INSTANCE is None:
            cls.INSTANCE = super().__call__(*args, **kwargs)
        return cls.INSTANCE

rawDescription: dict synonym for parameter in Singleton pattern. Assignment to reserved built-in symbol warning

description: Dict synonym for parameter in Singleton pattern. Assignment to reserved built-in symbol warning


code:
print("""\
Usage: x
""")
print("""
Usage: x
""")

rawDescription: Using python's print("""\""")

description: Using python's print("""\""")


code: web_site = on[:-4] if on.endswith('.com') else on

rawDescription: How to determine what value a variable is assigned to

description: Determine what value a variable is assigned to


code: re.sub(r'\d+"', "", strin)

rawDescription: Remove a number using regex

description: Remove a number using regex


rawDescription: Newbie to Python syntax - Error - suspect use of single/double quotes


code:
import os
dir_of_current_module = os.path.dirname(__file__)

rawDescription: Command line tool in python in a fixed root directory


rawDescription: What's the get_Text() equivalent in python bindings for Selenium/Webdriver


code:
s = wn.synsets('pretty')[0]
s.lemma_names

rawDescription: How to access the nltk/wordnet Synset object?

description: Access the nltk/wordnet Synset object


code: df['Test'] = df['OnsetTime'] * df['BinaryCol']

rawDescription: python pandas if 1 in column A, use value of column B in same row

description: Python pandas if 1 in column A, use value of column B in same row


rawDescription: extract column value based on another column pandas dataframe

description: Extract column value based on another column pandas dataframe


code:
from pymongo import Connection
connection = Connection()

# Get your DB
db = connection.my_database

# Get your collection
cars = db.cars

# Create some objects
import datetime
car = {"brand": "Ford",
       "model": "Mustang",
       "date": datetime.datetime.utcnow()}

# Insert it
cars.insert(car)

rawDescription: Python database WITHOUT using Django (for Heroku)


code:
#!/usr/bin/python2 -u

from __future__ import print_function
import sys, numpy

def read_pnm_from_stream( fd ):
   pnm = type('pnm',(object,),{}) ## create an empty container
   pnm.header = fd.readline()
   pnm.magic = pnm.header.split()[0]
   pnm.maxsample = 1 if ( pnm.magic == 'P4' ) else 0
   while ( len(pnm.header.split()) < 3+(1,0)[pnm.maxsample] ): s = fd.readline() ; pnm.header += s if ( len(s) and s[0] != '#' ) else ''
   pnm.width, pnm.height = [int(item) for item in pnm.header.split()[1:3]]
   pnm.samples = 3 if ( pnm.magic == 'P6' ) else 1
   if ( pnm.maxsample == 0 ): pnm.maxsample = int(pnm.header.split()[3])
   pnm.pixels = numpy.fromfile( fd, count=pnm.width*pnm.height*pnm.samples, dtype='u1' if pnm.maxsample < 256 else '>u2' )
   pnm.pixels = pnm.pixels.reshape(pnm.height,pnm.width) if pnm.samples==1 else pnm.pixels.reshape(pnm.height,pnm.width,pnm.samples)
   return pnm

if __name__ == '__main__':

## read image
 # src = read_pnm_from_stream( open(filename) )
   src = read_pnm_from_stream( sys.stdin )
 # print("src.header="+src.header.strip(), file=sys.stderr )
 # print("src.pixels="+repr(src.pixels), file=sys.stderr )

## write image
   dst=src
   dst.pixels = numpy.array([ dst.maxsample-i for i in src.pixels ],dtype=dst.pixels.dtype) ## example image processing
 # print("dst shape: "+str(dst.pixels.shape), file=sys.stderr )
   sys.stdout.write(("P5" if dst.samples==1 else "P6")+"\n"+str(dst.width)+" "+str(dst.height)+"\n"+str(dst.maxsample)+"\n");
   dst.pixels.tofile( sys.stdout ) ## seems to work, I'm not sure how it decides about endianness

## view using Image
   import Image
   viewable = dst.pixels if dst.pixels.dtype == numpy.dtype('u1') else numpy.array([ x>>8 for x in dst.pixels],dtype='u1')
   Image.fromarray(viewable).show()

## view using scipy
   import scipy.misc
   scipy.misc.toimage(dst.pixels).show()

rawDescription: Python and 16-bit PGM

description: Python and 16-bit PGM


rawDescription: Python get certain coordinate from list

description: Python get certain coordinate from list


code:
for root, dirs, files in os.walk(path, '*.txt'):
    out = open(os.path.join(root, '..', '..'), 'a')
    out.write(...)

rawDescription: using walk function in python

description: Using walk function in python


code:
import pandas as pd
import numpy as np

# An example data set
df = pd.DataFrame({"sentences": [
    "two long pieces of metal fixed together, each of which bends a different amount when they are both heated to the same temperature",
    "the temperature at which a liquid boils",
    "a system for measuring temperature that is part of the metric system, in which water freezes at 0 degrees and boils at 100 degrees",
    "a unit for measuring temperature. Measurements are often expressed as a number followed by the symbol °",
    "a system for measuring temperature in which water freezes at 32º and boils at 212º"
]})

# Create a new series which is a list of words in each "sentences" column
df['words'] = df['sentences'].apply(lambda sentence: sentence.split(" "))

# This is all the words in the dataset. Each word will be its own index (level of the MultiIndex)
names = np.unique(df['words'].sum())

# Create an array of tuples, one tuple for each row of data
# Each tuple contains True if the row has that word in it, and False if it does not
values = df['words'].map(
    lambda words: np.vectorize(
        lambda word:
            True if word in words else False)(names)
)

# Make a multindex
index = pd.MultiIndex.from_tuples(values, names=names)

# Add the MultiIndex without creating a new data frame
df.set_index(index, inplace=True)

# Find all the rows that have the word 'temperature'
xs = df.xs(True, level='temperature')

print(xs.to_string(index=False))

rawDescription: Grouping a row into multiple groups with pandas


code:
import imaplib, logging
from time import sleep

USERNAME = 'YOUR_USERNAME_HERE' # For gmail, this is your full email address.
PASSWORD = 'YOUR_PASSWORD_HERE'
CHECK_DELAY = 60 # In seconds

LOGGING_FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(filename='imapTest.log', format=LOGGING_FORMAT, level=logging.INFO)

logging.info("Connecting to IMAP server...")
imap = imaplib.IMAP4_SSL('imap.gmail.com')
imap.login(USERNAME, PASSWORD)
logging.info("Connected to IMAP server.")

def get_command_messages():
    logging.info("Checking for new commands.")
    imap.check()
    # Search the inbox (server-side) for messages containing the subject 'COMMAND' and which are from you.
    # Substitute USERNAME below for the sending email address if it differs.
    typ, data = imap.search(None, '(FROM "%s" SUBJECT "COMMAND")' %(USERNAME))
    return data[0]

def delete_messages(message_nums):
    logging.info("Deleting old commands.")
    for message in message_nums.split():
        imap.store(message, '+FLAGS', '\\DELETED')
    imap.expunge()

# Select the inbox
imap.select()

# Delete any messages left over that match commands, so we are starting 'clean'.
# This probably isn't the nicest way to do this, but saves checking the DATE header.
message_nums = get_command_messages()
delete_messages(message_nums)

try:
    while True:
        sleep(CHECK_DELAY)
        # Get the message body and sent time. Use BODY.PEEK instead of BODY if you don't want to mark the message as read, but we're deleting it anyway below.
        message_nums = get_command_messages()
        if message_nums:
            # search returns space-separated message IDs, but we need them comma-separated for fetch.
            typ, messages = imap.fetch(message_nums.replace(' ', ','), '(BODY[TEXT])')
            logging.info("Found %d commands" %(len(messages[0])))
            for message in messages[0]:
                # You now have the message body in the message variable.
                # From here, you can check against it to perform commands, e.g:
                if 'shutdown' in message:
                    print("I got a shutdown command!")
                    # Do stuff
            delete_messages(message_nums)
finally:
    try:
        imap.close()
    except:
        pass
    imap.logout()

rawDescription: how to sign request tokens?

description: Sign request tokens


code:
from itertools import product

def value_from_key(sheet, key):
    for row_index, col_index in product(xrange(sheet.nrows), xrange(sheet.ncols)):
        if sheet.cell(row_index, col_index).value == key:
            return sheet.cell(row_index+1, col_index).value

value = value_from_key(sheet, 'COLOR')

rawDescription: Get cell by column name using xlrd

description: Get cell by column name using xlrd


code:
import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print('Goodbye!\n\n\n\n\n')

rawDescription: Countdown Clock: 01:05

description: Countdown Clock: 01:05


code:
for i in dict1:
    if i not in dict2:
        dict2[i] = dict1[i]
#=> {1: 'ef', 2: 'cd', 3: 'gh'}

rawDescription: Choosing which value to replace in a dictionary when replacing duplicate keys?


code:
img = cv2.imread('source to image here')
cv2.resize(img,fx=scaleX,fy=scaleY, interpolation = cv2.INTER_CUBIC)

rawDescription: opencv2: bicubic interpolation while resizing image

description: Opencv2: bicubic interpolation while resizing image


code:
import binascii
gsm = ("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?"
       "¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ`¿abcdefghijklmnopqrstuvwxyzäöñüà")
ext = ("````````````````````^```````````````````{}`````\\````````````[~]`"
       "|````````````````````````````````````€``````````````````````````")

def gsm_encode(plaintext):
    result = []
    for c in plaintext:
        idx = gsm.find(c)
        if idx != -1:
            result.append(chr(idx))
            continue
        idx = ext.find(c)
        if idx != -1:
            result.append(chr(27) + chr(idx))
    return ''.join(result).encode('hex')

def gsm_decode(hexstr):
    res = hexstr.decode('hex')
    res = iter(res)
    result = []
    for c in res:
        if c == chr(27):
            c = next(res)
            result.append(ext[ord(c)])
        else:
            result.append(gsm[ord(c)])
    return ''.join(result)

code = gsm_encode("Hello World {}")
print(code)
# 64868d8d903a7390938d853a1b281b29
print(gsm_decode(code))
# Hello World {}

rawDescription: decode 7-bit GSM

description: Decode 7-bit GSM


code:
if v.get():
    rb()
else:
    root.unbind('<KeyPress-b>')
    root.unbind('<KeyPress-s>')

rawDescription: How do I quit a keyboard event in Tkinter?

description: Quit a keyboard event in Tkinter


rawDescription: What is the associativity of Python's ** operator?


code:
def getInfos(currentDir):
    infos = []
    for root, dirs, files in os.walk(currentDir): # Walk directory tree
        for f in files:
            infos.append(FileInfo(f,root))
    return infos

rawDescription: Python program to traverse directories and read file information


code:
h1 = Host("hostName1")  #After __init__:h1.filelist -> Host.filelist
h1.AddInfo("h1")        #After AddInfo: h1.filelist -> Host.filelist
h1.Cleanup()            #After Cleanup: h1.filelist is a new list

h2 = Host("hostName2")  #After __init__:h2.filelist -> Host.filelist (which already has 'h1' inserted)
h2.AddInfo("h2")        #After AddInfo: h2.filelist -> Host.filelist

rawDescription: static class variables

description: Static class variables


code:
looking_for = iter(when_to_change_the_mode)
current = next(looking_for)
for l in listA:
    do_something(current)
    if l == current:
        current = next(looking_for)

rawDescription: How to get the item currently pointed at by iterator without incrementing?

description: Get the item currently pointed at by iterator without incrementing


code:
import bge

def main():
    cam = bge.logic.getCurrentScene().active_camera
    obj = bge.logic.getCurrentController().owner
    obj.worldPosition.y = cam.worldPosition.y
    obj.worldPosition.z = cam.worldPosition.z

main()

rawDescription: Is it possible to parent to only one or two axes in Blender?


code:
# generator function to crawl web pages
def crawler():
    while iStillHaveWebPagesToCrawl():
        someStrings = getSomeStringsFromAWebPage()
        for aString in someStrings:
            yield aString

def oneStringAtATime():
    for aString in crawler():
        doSomethingWith( aString )

rawDescription: Explaining python generator for a long list


rawDescription: Deleting a few list items inside of dictionary


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

def normalise(series):
    max_value = max(series)
    min_value = min(series)
    return (series - min_value) / (max_value - min_value)

if __name__ == "__main__":
    L1 = [np.sin(i*.01) for i in range(350)]
    L2 = [np.sin(i*.01) + 1 for i in range(350)]
    L3 = 100*[np.sin(i*.01) + 1 for i in range(350)]

    norm_L1 = normalise(L1)
    norm_L2 = normalise(L2)
    norm_L3 = normalise(L3)

    # Correlate the normalised signals
    alignment = R.dtw(norm_L1, norm_L2, keep=True)
    correlation1 = alignment.rx('normalizedDistance')[0][0]

    alignment = R.dtw(norm_L1, norm_L3, keep=True)
    correlation2 = alignment.rx('normalizedDistance')[0][0]

rawDescription: Dynamic Time Wrap (DTW) normalizing, python implementation


code: [main_list[x] for x in indexes]

rawDescription: Picking out items from a python list which have specific indexes


code:
import mock
import unittest

import utils

class TestA(unittest.TestCase):

    def setUp(self):
        pass

    def test_method_a(self):
        method_b_patcher = mock.patch('utils.method_b', return_value=None)
        method_b_patcher.start()
        actual_result = utils.method_a()
        method_b_patcher.stop()

    def test_method_b(self):
        actual_result = utils.method_b()
        self.assertTrue(actual_result)

rawDescription: How to apply @mock.patch for method and keep access to original method within one or more Tests?

description: Apply @mock.patch for method and keep access to original method within one or more Tests


code:
def insert(outer, inner, pos):
  outer[pos:pos] = inner

rawDescription: How do I insert a list into another list in python?

description: Insert a list into another list in python


rawDescription: Variable of a different Variable

description: Variable of a different Variable


code:
from binascii import hexlify, unhexlify
key     = ']\n\x80\xd8\x13J\xe1\x96w\x82Kg\x1e\x83\x8a\xf4'
hexlify(key)
unhexlify(hexlify(key))

rawDescription: Unable to understand the string representation


code: from imports import *

rawDescription: how to move all those imports to standalone file

description: Move all those imports to standalone file


rawDescription: Sorting the order of entire columns in numpy


code:
http = httplib2.Http()
# get cookie_value here
headers = {'Cookie':cookie_value}
response, content = http.request("http://www.theURL.com", 'GET', headers=headers)

rawDescription: Python create cookies and then load a page with the cookies


code:
def some_function():
    pass

def other_function():
    pass

init_value = 0    # This code here is run immediately.
buffer = None

rawDescription: Is there an equivalent of C's main() in a Python module?


code:
class Form(object):
    class Meta:
        model = None
        method = "POST"

    def __init__(self, *args, **kwargs):
        if self.__class__ != Form:
            self.Meta.__bases__ += (Form.Meta,)
        # other __init__ code here.

class SubForm(Form):
    class Meta:
        model = 'User'

rawDescription: Dynamically add base class?

description: Dynamically add base class


rawDescription: Deleting an Object from Collection in SQLAlchemy


code:
theuser = UserTable.get_by_key_name(Theusername)
theuser.isVerified = True
theuser.put()

rawDescription: Boolean value inconsistent

description: Boolean value inconsistent


code:
hero = random.choice(names)
# stuff
while some_condition:
    # do stuff
    print(hero) # or formatted string
    # do other stuff

rawDescription: python assign a variable to a randomly selected string

description: Python assign a variable to a randomly selected string


code:
import random

RANDOMID = random.randit(0, 1<<32)

rawDescription: Generating a cache busting key in Plone based on the process start-up timestamp


code:
x = 634124502600000000
secs = x / 10.0 ** 7
secs
import datetime
delta = datetime.timedelta(seconds=secs)
delta
ts = datetime.datetime(1,1,1) + delta
ts

rawDescription: python: c# binary datetime encoding

description: Python: c# binary datetime encoding


rawDescription: Sort a 2D numpy array by the median value of the rows


code: min(points, key=lambda p: (lambda x,y: (x*x + y*y))(*p))

rawDescription: What is the good python3 equivalent for auto tuple unpacking in lambda?


rawDescription: get everything after last character occurrence python

description: Get everything after last character occurrence python


code: e_weight.a = weight_list

rawDescription: python graph-tool load csv file

description: Python graph-tool load csv file


code:
PROPORTIONAL_FONT_FAMILY = ("MS", "Sans", "Serif")
MONOSPACE_FONT_FAMILY    = ("Courier")

PROPORTIONAL_FONT_SIZE  = 10
MONOSPACE_FONT_SIZE     =  9
TEXT_ENTRY_FONT_SIZE    = 12

rawDescription: Python EasyGUI module: how to change the font


code:
with open("samplefile.txt") as inf, open("samplefileout.txt", "w") as outf:
    for line in inf:
        if line.startswith("Subject: ") or line.startswith("From: "):
            outf.write(line)
        elif line.startswith("Date: "):
            outf.write(line)
            skip =     next(inf, "")    # skip blank line
            outf.write(next(inf, ""))   # 2
            outf.write(next(inf, ""))   # 3
            outf.write(next(inf, ""))   # 4

rawDescription: Python text parsing - how to capture and write multiple lines


code:
from matplotlib.image import imread
image = imread(image_path)

rawDescription: Opening Images as Arrays

description: Opening Images as Arrays


rawDescription: Building advanced list combinations

description: Building advanced list combinations


code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals,print_function
import re

unicode_rainbow_dictionary = {
    '\u00A0':' ',
    '\uFB01':'fi',
}

strings = ["This contains the\xa0annoying non-breaking space","This is fine!","This is not ﬁne!"]

for string in strings:
    for regex in unicode_rainbow_dictionary:
        result = re.search(regex,string)
        if result:
            print("Epic fail! There is a rogue character in '"+string+"'")
        else:
            print(string)

rawDescription: Customized non-ascii characters flagger

description: Customized non-ascii characters flagger


code:
asker = ['Jack','Jack','Jack','Jill']
answerer = ['Jill','John','Jason','John']
finalList = zip(asker, answerer)
finalList

rawDescription: How to match parentheses and comma formatting in list, python

description: Match parentheses and comma formatting in list, python


code:
s = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
re.sub(r"\b(?<!')(\w+)(?!')\b", lambda match: match.group(1).lower(), s)

rawDescription: Python: Convert entire string to lowercase except for substrings in quotes


code:
def find_max(my_list):
    m = max([find_max(x) if type(x) is list else x for x in my_list])
    return m

rawDescription: Python Recursion - Finding sum of max and min in a nested array


code:
class OrderedMeta(type):
    @classmethod
    def __prepare__(metacls, name, bases):
        return OrderedDict()

    def __new__(cls, name, bases, clsdict):
        c = type.__new__(cls, name, bases, clsdict)
        c._orderedKeys = clsdict.keys()
        return c

class Person(metaclass=OrderedMeta):
    name = None
    date_of_birth = None
    nationality = None
    gender = None
    address = None
    comment = None

for member in Person._orderedKeys:
    if not getattr(Person, member):
        print(member)

rawDescription: Iterate through class members in order of their declaration


code:
import glob
from bs4 import BeautifulSoup

path = 'myurlfiles/*.html'

urls = []
for file_name in glob.iglob(path):
    with open(file_name) as f:
        soup = BeautifulSoup(f)
        urls += [link['href'] for link in soup.find_all('a', {'href': True})]

with open("url.csv", "wb") as f:
    f.write("\n".join(urls))

rawDescription: Python/BS - Getting URLs from html files stored in a directory, save to CSV


code:
browser.find_elements_by_xpath(
    "//span[contains(text(), 'secs') or contains(text(), 'mins') or contains(text(), 'hrs')]")

rawDescription: How can I find specific but obscure elements in Selenium, without a parser like Beautiful Soup?

description: Find specific but obscure elements in Selenium, without a parser like Beautiful Soup


code:
import wx

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)

        self.panel = wx.Panel(self)

        main_sizer = wx.BoxSizer(wx.VERTICAL)

        # Title
        self.centred_text = wx.StaticText(self.panel, label="Title")
        main_sizer.Add(self.centred_text, 0, wx.ALIGN_CENTRE | wx.ALL, 3)

        # Grids
        content_sizer = wx.BoxSizer(wx.HORIZONTAL)
        grid_1 = wx.GridSizer(12, 2, 0, 0)
        grid_1.AddMany(wx.StaticText(self.panel, label=str(i)) for i in xrange(24))
        content_sizer.Add(grid_1, 1, wx.EXPAND | wx.ALL, 3)
        grid_2 = wx.GridSizer(10, 3, 0, 0)
        grid_2.AddMany(wx.StaticText(self.panel, label=str(i)) for i in xrange(30))
        content_sizer.Add(grid_2, 1, wx.EXPAND | wx.ALL, 3)

        main_sizer.Add(content_sizer, 1, wx.EXPAND)

        self.panel.SetSizer(main_sizer)

        self.Show()

if __name__ == "__main__":

    app = wx.App(False)
    Frame(None)
    app.MainLoop()

rawDescription: wxpython layout with sizers

description: Wxpython layout with sizers


code:
graph = facebook.GraphAPI(access_token)
profile = graph.get_object('me')
args = {'fields' : 'id,name,email', }
profile = graph.get_object('me', **args)

rawDescription: Request fields in Python Facebook SDK

description: Request fields in Python Facebook SDK


code:
import pylab

# datetimes = [datetime(...), ...]

pylab.plot([dt.date() for dt in datetimes],
           [dt.hour + dt.minute/60. for dt in datetimes],
           ',')

rawDescription: Scatter plot of dates and times

description: Scatter plot of dates and times


code:
import pandas as pd
x = pd.cut(np.arange(0,20), 10)
np.array(map(lambda t:t[1:-1].split(","), x.levels), float)

rawDescription: How can I get a suitable representation of levels in pandas.cut?

description: Get a suitable representation of levels in pandas.cut


code:
#!/usr/bin/env python
import logging
from multiprocessing.pool import ThreadPool
from subprocess import call

windowsize = 10
cmd = ["./myscript.sh", "/usr/share/file1.txt", "/usr/share/file2.txt"]

def run(i):
    return i, call(cmd)

logging.basicConfig(format="%(asctime)-15s %(message)s", datefmt="%F %T",
                    level=logging.INFO)
pool = ThreadPool(windowsize)
for i, rc in pool.imap_unordered(run, range(100)):
    logging.info('%s-th command returns %s', i, rc)

rawDescription: Starting and waiting for multiple jobs started in background


code:
with open("cran.all.1400") as abstracts:
    inside = False
    abstract_list = []
    for line in abstracts:
        if line.startswith(".W"):
            inside = True
            abstract_list.append("")
        elif line.startswith(".I"):
            inside = False
        elif inside:
            abstract_list[-1] += line

rawDescription: StopIteration given by a file iteration that uses nested loops


rawDescription: Removing duplicates from dataframe with index + row matching


rawDescription: Correct usage of regex lookahead in python


code:
from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB
tb = TB()
tb.feed("<p>Hello world")
e= tb.close()
e.find(".//{http://www.w3.org/1999/xhtml}p")

rawDescription: Parse HTML via XPath

description: Parse HTML via XPath


code: d.groupby(d.Job.map(lambda x: 'Physician' if 'Physician' in x else x)).sum()

rawDescription: How do I count the number of occurrences of a string in a Dataframe field?

description: Count the number of occurrences of a string in a Dataframe field


code:
import struct
struct.pack('4B', 4, 6, 7, 8,)

rawDescription: struct in python

description: Struct in python


code:
#!/usr/bin/env python
import logging, signal, sys, time
import multiprocessing as mp # `pip install multiprocessing` on Python <2.6

class AddProcessNameFilter(logging.Filter):
    """Add missing on Python 2.4 `record.processName` attribute."""
    def filter(self, r):
        r.processName = getattr(r, 'processName', mp.current_process().name)
        return logging.Filter.filter(self, r)

def print_dot():
    while True:
        mp.get_logger().info(".")
        time.sleep(1)

def main():
    logger = mp.log_to_stderr()
    logger.setLevel(logging.INFO)
    logger.addFilter(AddProcessNameFilter()) # fix logging records

    # catch TERM signal to allow finalizers to run and reap daemonic children
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(-signal.SIGTERM))

    # create daemonic child processes
    processes = [mp.Process(target=print_dot) for _ in range(2)]
    for p in processes:
        p.daemon = True
        p.start()
    print_dot()

if __name__=="__main__":
    mp.freeze_support()
    main()

rawDescription: Python close children when closing main process


rawDescription: Python - Best data structure for incredibly large matrix


code:
class Note(TestCase):
    def setUp(self):
        self.client = Client()
        self.new_user = User.objects.create_user('blah', 'blah@blah.com', 'blah')
        self.new_user.save()
        self.client.login(username='blah', password='blah')

    def tearDown(self):
        self.client.logout()
        self.new_user.delete()

    def test_noteshow(self):
        response = self.client.get('/note/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, '/note/noteshow.html')

rawDescription: How can I do such a typical unittest?

description: Do such a typical unittest


code: {{ secrets | to_nice_yaml( width=50, explicit_start=True, explicit_end=True) }}

rawDescription: Ansible write variables into YAML file

description: Ansible write variables into YAML file


code:
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
target = [1,5]

any(x for x in (a+b+c) if x in target)

True

rawDescription: Logic rules of Python's `if` clause

description: Logic rules of Python's `if` clause


code: SOUTH_TESTS_MIGRATE = False

rawDescription: How do I fake certain south migration in django tests(in a custom test runner)?

description: Fake certain south migration in django tests(in a custom test runner)


code:
#!/usr/bin/env python

import sys,os,re

print ('Searcing for a line in /etc/pam.d/common-password\n')

pass_file = open('/root/p_file/common-password', 'r').readlines()

for i in pass_file:

    if re.search(r"password        required        pam_unix2.so use_authok\n", i):

        sys.exit("Sending exit code 0")

    else:

        sys.exit(2)

if __name__=='__main__':
    main(sys.argv)

rawDescription: Match multiple lines in a file using python


code:
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'birthday')
    list_display_links = ('first_name', 'last_name')

rawDescription: Change clickable field in Django admin list_display


code: all(func(input) for func in filters)

rawDescription: Pythonic way to apply a list of functions?


code:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]

rawDescription: Python wildcard search in string

description: Python wildcard search in string


code: "Driver={Sybase IQ};UID=username; PWD=*******; ServerName=SERVERNAME; CommLinks=SharedMemory,TCPIP{host=server.sg.planet.com;port=111}"

rawDescription: how do I query Sybase IQ server using odbc?

description: Query Sybase IQ server using odbc


code:
d = {}
with open('in.txt') as f:
    data = f.readlines()
for x in data:
    x = x.strip()
    if not x:
        continue
    name = x.split(':')[0].strip()
    score = int(x.split(':')[-1].split('/')[0].strip())
    if name not in d:
        d[name] = {}
        d[name]['score'] = 0
        d[name]['count'] = 0
    d[name]['count'] += 1
    d[name]['score'] = (d[name]['score'] + score) / float(d[name]['count'])

ds = sorted(d.keys(), key=lambda k: d[k]['score'], reverse=True)

for x in ds:
    print('{0}: {1}'.format(x, d[x]['score']))

rawDescription: Finding the average number

description: Finding the average number


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(z,t):
    xi = z[0]
    yi = z[1]

    f1 = -t*yi-xi
    f2 = 2*xi-yi**3
    return [f1,f2]

# Initial Conditions
x0 = 1.
y0 = 1.
#t= np.linspace(0,20.,1000)
t = np.linspace(0, 10., 100)

# Solve the ODEs
soln = odeint(f,[x0,y0],t)
x = soln[:,0]
y = soln[:,1]

ax = plt.axes()
#plt.plot(x,y)
plt.plot(t,x)
# Put those axes at their 0 value position
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#plt.axis([-0.085, 0.085, -0.05, 0.07])
plt.show()

rawDescription: Parametric plot of solution of 2x2 diff. system in python, Mathematica


code:
from datetime import datetime

def day_type(d):
    if d in (datetime(2014, 1, 1),
            datetime(2014, 5, 26),
            datetime(2014, 7, 4),
            datetime(2014, 9, 1),
            datetime(2014, 11, 27),
            datetime(2014, 12, 25)):
        return 3         # return type 3, holidays
    elif d.weekday() in [0, 1, 2, 3, 4]:
        return 1         # return type 1, weekdays
    else:
        return 2         # return type 2, weekends

rawDescription: New If Statement after If Else Block In a Function Return Unexpected Results


code:
from pattern.web import URL, DOM

url = URL("http://temelelektronik.net")
dom = DOM(url.download())
for anchor in dom.by_tag('a'):
    print(anchor.href)

rawDescription: How to get all links from php page using python and mechanize

description: Get all links from php page using python and mechanize


rawDescription: Inline parsing in BeautifulSoup in Python


code:
class NewThingHandler(BaseRequestHandler):
    def get(self, thing):
        self.redirect('/admin/')
    def post(self, thing):
        this_module = sys.modules[__name__]
        ThisModel = getattr(this_module, thing)
        arguments = {}
        for property in ThisModel.properties().keys():
            if type(ThisModel._properties[property]) is db.DateProperty:
                this_date = map(int, self.request.get(property).split('/'))
                this_date = datetime.date(this_date[2], this_date[0], this_date[1])
                arguments[property] = this_date
                continue
            arguments[property] = self.request.get(property)

        new_thing = ThisModel(**arguments)
        new_thing.put()
        self.redirect('/admin/')

rawDescription: How can I create an entity in the GAE datastore of a type determined at runtime?

description: Create an entity in the GAE datastore of a type determined at runtime


code: blurred = cv2.blur(img,(3,3))

rawDescription: Calculate mean across area in a 2D array


code:
from collections import OrderedDict

anyname = OrderedDict()

rawDescription: Django: Keep order when translating list to custom dictionary


code:
from django.template import Context, Template
t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
output = t.render(c)

rawDescription: Django - get HTML output into a variable


code:
with open('%s.xls' % (filename,)) as f:
    f.write(excelStr)

rawDescription: Export to Excel from django shell

description: Export to Excel from django shell


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

x = np.linspace(0, 100, 100)

y1 = x**2

plt.plot(x, y1)

line = plt.gca().get_lines()
x_data = lines[0].get_data()[0]
y1_data = lines[0].get_data()[1]

rawDescription: Get data from shown plot in matplotlib and pass it to a probability density function


code:
s = 'Mary'
out = []
length = len(s) # in this case length=4

# for i in range(0, 4):
# i = 0
out.append(s[0])    # s[0] = 'M', out = ['M']
print(''.join(out)) # print('M')
# if i < length - 1: => if 0 < 3:
# loc(i + 1) => loc(1)
# for j in range(1, 4):
# j = 1
out.append(s[1])    # s[1] = 'a', out = ['M', 'a']
print(''.join(out)) # print('Ma')
# if j < length - 1: => if 1 < 3:
# loc(j + 1) => loc(2)
# for k in range(2, 4):
# k = 2
out.append(s[2])    # s[2] = 'r', out = ['M', 'a', 'r']
print(''.join(out)) # print ('Mar')
# if k < length - 1: => if 2 < 3:
# loc(k + 1) => loc(3)
# for l in range(3, 4):
# l = 3
out.append(s[3])    # s[3] = 'y', out = ['M', 'a', 'r', 'y']
print(''.join(out)) # print('Mary')
# if l < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'a', 'r']
# end of for l in range(3, 4)
del out[-1] # out = ['M', 'a']
# k = 3, now in for k in range(2, 4):
out.append(s[3])    # s[3] = 'y', out = ['M', 'a', 'y']
print(''.join(out)) # print('May')
# if k < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'a']
# end of for k in range(2, 4)
del out[-1] # out = ['M']
# j = 2, now in for j in range (1, 4):
out.append(s[2])    # s[2] = 'r', out = ['M', 'r']
print(''.join(out)) # print('Mr')
# if j < length - 1: => if 2 < 3:
# loc(j + 1) => loc(3)
# for m in range(3, 4)
# m = 3
out.append(s[3])    # s[3] = 'y', out = ['M', 'r', 'y']
print(''.join(out)) # print('Mry')
# if m < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'r']
# end of for m in range(3, 4)
del out[-1] # out = ['M']
# j = 3, now in for j in range (1, 4):
out.append(s[3])    # s[3] = 'y', out = ['M', 'y']
print(''.join(out)) # print('My')
# if j < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M']
# end of for j in range(1, 4)
del out[-1] # out = []
# i = 1

#... you get the rest

rawDescription: Can someone help me understand the following python program?


code:
from ctypes import *
from ctypes.wintypes import *
import struct

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 3112
address = 0x2411918

buffer = c_char_p(b"The data goes here")
val = c_int()
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
    memmove(ctypes.byref(val), buffer, ctypes.sizeof(val))
    print("Success:" + str(val.value))
else:
    print("Failed.")

CloseHandle(processHandle)

rawDescription: Python - Converting byte address (from ReadProcessMemory) to string?


code: matshow(board_prob, cmap=cm.Spectral_r, interpolation='none', vmin=0, vmax=1)

rawDescription: Heatmap with matplotlib using matshow

description: Heatmap with matplotlib using matshow


code:
class EnumMC(type):
  def __contains__(self, val):
    return val in self.__dict__

def enum(*sequential, **named):
  enums = dict(zip(sequential, range(len(sequential))), **named)
  return EnumMC('Enum', (), enums)

MyEnum = enum('FOO', 'BAR', 'JIMMY')
def func(my_enum_value):  # expects one of the MyEnum values
    if not my_enum_value in MyEnum:
        raise ValueError()

func('FOO')
func('QUUX')

rawDescription: Python: Make a dynamically created class (as in the class itself) iterable?


code:
from datetime import datetime
from dateutil.relativedelta import relativedelta

if __name__ == '__main__':

    t1 = datetime(year=2015, day=19, month=9, hour=2, minute=35)
    t2 = t1 + relativedelta(minutes=56)

    print(t2.strftime('%H:%m'))

rawDescription: How to add hours and minutes between them

description: Add hours and minutes between them


code:
def retrieve_sub_array(element):
 for sub_array in array:
  if element in sub_array:
   return sub_array

rawDescription: Python | extracting elements from 2D array


code:
def dominates(row, rowCandidate):
    return all(r >= rc for r, rc in zip(row, rowCandidate))

def cull(pts, dominates):
    dominated = []
    cleared = []
    remaining = pts
    while remaining:
        candidate = remaining[0]
        new_remaining = []
        for other in remaining[1:]:
            [new_remaining, dominated][dominates(candidate, other)].append(other)
        if not any(dominates(other, candidate) for other in new_remaining):
            cleared.append(candidate)
        else:
            dominated.append(candidate)
        remaining = new_remaining
    return cleared, dominated

rawDescription: Fast calculation of Pareto front in Python


rawDescription: Regex to extra part of the url

description: Regex to extra part of the url


code: [a in b for a, b in zip(x, y)]

rawDescription: Testing for string inclusion on Lists and Tuples


rawDescription: Accessing a XAMPP mysql via Python

description: Accessing a XAMPP mysql via Python


code:
articles = ArticleTracking.objects.filter(date__range=(start_date, end_date))
articles = articles.values('story_id', 'url', 'headline').annotate(count = Count('story_id')).order_by('-count')[:20]

rawDescription: How to Group by id and Order By count in Django


rawDescription: Why I cannot save file with Chinese characters when using Python 2.7.11 IDLE?


code:
import numpy as np
hist, bin_edges = np.histogram(np.random.randint(0,10,100), normed=True)
bin_edges
hist
np.cumsum(hist)

rawDescription: How to get the cumulative distribution function with NumPy?

description: Get the cumulative distribution function with NumPy


code:
from win32com.client import DispatchEx
xl = DispatchEx("Excel.Application")
xl.Workbooks.Open("c:/excel_file.xls")
xl.ActiveWorkbook.ActiveSheet.Columns(1).AutoFilter(1)
xl.ActiveWorkbook.Close(SaveChanges=1)
xl.Quit()
del xl # ensure excel.exe process ends

rawDescription: How to create an excel file with an autofilter in the first row with xlwt?

description: Create an excel file with an autofilter in the first row with xlwt


code:
principal = Principal(app)

@principal.identity_loader
def load_identity_when_session_expires():
    if hasattr(current_user, 'id'):
        return Identity(current_user.id)

rawDescription: Flask-Principal, Flask-Login, remember_me and identity_loaded


code:
for label in pipedinfoDF.index.unique():
    group = pipedinfoDF.loc[label]

rawDescription: python pandas groupby after sorted multindex not correct

description: Python pandas groupby after sorted multindex not correct


code:
optionParse.add_argument('-n', result='store', required=True, dest='num_locs', type=int, help='Number of locations')

results = optionParse.parse_args()
num_locs = results.num_locs

rawDescription: Accessing option data

description: Accessing option data


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

def my_lines(ax, pos, *args, **kwargs):
    if ax == 'x':
        for p in pos:
            plt.axvline(p, *args, **kwargs)
    else:
        for p in pos:
            plt.axhline(p, *args, **kwargs)

bits = [0,1,0,1,0,0,1,1,1,0,0,1,0]
data = np.repeat(bits, 2)
clock = 1 - np.arange(len(data)) % 2
manchester = 1 - np.logical_xor(clock, data)
t = 0.5 * np.arange(len(data))

plt.hold(True)
my_lines('x', range(13), color='.5', linewidth=2)
my_lines('y', [0.5, 2, 4], color='.5', linewidth=2)
plt.step(t, clock + 4, 'r', linewidth = 2, where='post')
plt.step(t, data + 2, 'r', linewidth = 2, where='post')
plt.step(t, manchester, 'r', linewidth = 2, where='post')
plt.ylim([-1,6])

for tbit, bit in enumerate(bits):
    plt.text(tbit + 0.5, 1.5, str(bit))

plt.gca().axis('off')
plt.show()

rawDescription: Can we draw digital waveform graph with Pyplot in python or Matlab?


code:
from scipy.stats import t
t.sf(3.078, 1)

rawDescription: Finding Two-Tailed P Value from t-distribution and Degrees of Freedom in Python


code:
import re
import urlparse
from scrapy.http import XmlResponse
from scrapy.utils.gz import gunzip, is_gzipped
from scrapy.contrib.spiders import SitemapSpider

# downloader middleware
class SitemapWithoutSchemeMiddleware(object):
    def process_response(self, request, response, spider):
        if isinstance(spider, SitemapSpider):
            body = self._get_sitemap_body(response)

            if body:
                scheme = urlparse.urlsplit(response.url).scheme
                body = re.sub(r'<loc>\/\/(.+)<\/loc>', r'<loc>%s://\1</loc>' % scheme, body)
                return response.replace(body=body)

        return response

    # this is from scrapy's Sitemap class, but sitemap is
    # only for internal use and it's api can change without
    # notice
    def _get_sitemap_body(self, response):
        """Return the sitemap body contained in the given response, or None if the
        response is not a sitemap.
        """
        if isinstance(response, XmlResponse):
            return response.body
        elif is_gzipped(response):
            return gunzip(response.body)
        elif response.url.endswith('.xml'):
            return response.body
        elif response.url.endswith('.xml.gz'):
            return gunzip(response.body)

rawDescription: Parsing the urls in sitemap with different url format using sitemap spider in scrapy, python


code:
from collections import defaultdict

# Count numbers in a dictionary that defaults to zero if a key does not exist yet
counter = defaultdict(int)

with open("filename", "rU") as f:
    for line in f:
        info = line.split()
        date, time, unused, number, id = info[:5]
        counter[id, number] += 1

for (id, number), count in counter.items():
    print("The combination id=%s, number=%s occurred %d times" % (id, number, count))

rawDescription: counting when a occurs with b in files and lists in python

description: Counting when a occurs with b in files and lists in python


code:
client = Client(applicant_ptr=applicant)
client.save_base(raw=True)

rawDescription: Django workflow to convert model superclass to subclass


code:
def A():
    ...
    B(list(mylist))  # shallow copy of mylist
    ...

rawDescription: Lists in Python

description: Lists in Python


code:
dfA = pd.DataFrame(['a','b','c'],columns=['A'])
dfB = pd.DataFrame(range(3),columns=['B'])
dfA['key'] = 1
dfB['key'] = 1
pd.merge(dfB, dfA, on='key').ix[:, ('A','B')]

rawDescription: pandas - extending the DataFrame by adding another levels

description: Pandas - extending the DataFrame by adding another levels


code:
A = (0, 1, 2)
B = (0, 3, 1, 4, 2)
b_iter = iter(B)
all(a in b_iter for a in A)

rawDescription: Ordered subsets test

description: Ordered subsets test


code:
# Execute the template string in a temporary namespace and
# support tracing utilities by setting a value for frame.f_globals['__name__']

rawDescription: Code object has unexpected file name during import when using sys.settrace()


code:
def on_button_clicked(self, widget):
    self.button.hide()
    self.spinner.show()
    self.spinner.start()
    GLib.timeout_add_seconds (5, self.processing_finished)

def processing_finished(self):
    self.spinner.stop()
    self.spinner.hide()
    self.button.show()

rawDescription: Gtk widget shows up with delay

description: Gtk widget shows up with delay


rawDescription: Python: Normalize multidimensional array