code:
idx = df.duplicated(['longitude', 'latitude'])
idx

rawDescription: MultiIndexing in pandas based on column conditions


code:
my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
next(v for k, v in my_dict.items() if 'c' in k)      # use .iteritems() python-2.x

rawDescription: Is it possible to assign the same value to multiple keys in a dict object at once?


code:
c.most_common(4)
c.most_common()[:4]

rawDescription: Selecting all top words in Python list using Counter


code:
def iter1d(a):
    return itertools.chain.from_iterable(
        numpy.rollaxis(a, axis, a.ndim).reshape(-1, dim)
        for axis, dim in enumerate(a.shape))

rawDescription: Iteration through all 1 dimensional subarrays of a multi-dimensional array


code:
class UpdateTester(object):
    def __init__(self, **kwargs):
        super(UpdateTester, self).__init__(**kwargs) # for multiple inheritence
        self.x = []

rawDescription: Updating Class Instance Attributes via SuperClass update() method


rawDescription: Python: How to revolve a surface around z axis and make a 3d plot?


code:
import math

def rint(x):
  x_int = int(x)
  x_rem = x - x_int  # this is problematic
  if (x_int % 2) == 1:
    return round(x)
  else:
    if x_rem <= 0.5:
      return math.floor(x)
    else:
      return math.ceil(x)

rawDescription: App Engine: Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore


code: sorted(some_list, key=lambda f: f % 1)

rawDescription: How can I sort a list by the decimals only?

description: Sort a list by the decimals only


code:
from collections import OrderedDict
choices  = OrderedDict(zip(range(1, len(choices)+ 1),choices))
for k,v in choices.items():
        msg = "%g: %s" % (k, v)
        print(msg)

while True:
    choose = int(input(warning + prompt))
    if choose in choices:
        return choose
    print("Invalid response '%s': try again" % choose)
    for k,v in choices.items():
        msg = "%g: %s" % (k, v)
        print(msg)

rawDescription: Python: Unable to quit menu - user input


rawDescription: Send request to page with windows-1251 encoding from python


code: print ("%.6f" % your_float).strip("0")

rawDescription: Python floating-point precision format specifier


code:
from itertools import count
endless_counter = count()
any(x > 10 for x in endless_counter)
# endless_counter last yielded 11, the first value over 10:
next(endless_counter)

rawDescription: How to achieve python's any() with a custom predicate?

description: Achieve python's any() with a custom predicate


rawDescription: Using matplotlib/pandas/python, I cannot visualize data as values per 30mins and per days


rawDescription: What are some good ways to set a path in a Multi-OS supported Python script


code:
import re

# This pattern should match correct data lines and should not
# match "continuation" lines (lines added by the unquoted newline).
# This pattern means: start of line, then a number, then white space,
# then another number, then more white space, then another number.

# This program won't work right if this pattern isn't correct.
pat = re.compile("^\d+\s+\d+\s+\d+")

def collect_lines(iterable):
    itr = iter(iterable)  # get an iterator

    # First, loop until we find a valid line.
    # This will skip the first line with the "header" info.
    line = next(itr)
    while True:
        line = next(itr)
        if pat.match(line):
            # found a valid line; hold it as cur
            cur = line
            break
    for line in itr:
        # Look at the line after cur.  Is it a valid line?
        if pat.match(line):
            # Line after cur is valid!
            yield cur  # output cur
            cur = line  # hold new line as new cur
        else:
            # Line after cur is not valid; append to cur but do not output yet.
            cur = cur.rstrip('\r\n') + line
    yield cur

data = """\
   JOB  REF Comment V2  Other
@@@1   3   45  This was a small job    NULL    sdnsdf
@@@2   4   456 This was a large job and I have to go onto a new line,
@@@    but I didn't properly escape so it's on the next row whoops!    NULL    NULL
@@@3   7   354 NULL    NULL    NULL
"""

lines = data.split('@@@')
for line in collect_lines(lines):
    print(">>>{}<<<".format(line))

rawDescription: Cleaning a tab delimited file with unescaped newlines


code: no_primes = {j for i in xrange(2,sqrt_n) for j in xrange(i*2, n, i)}

rawDescription: Python Get Access to locals() Back In 2.7 to Prevent Duplicates


rawDescription: Animating a rectangle in PyQT5: Why is QtCore not defined?


code:
import pysvn
client = pysvn.Client()
client.info('/tmp')

rawDescription: pysvn: How to find out if local dir is under version control?

description: Pysvn: How to find out if local dir is under version control


code:
x = numpy.array([[0, 1],
                 [3, 2]])
x.argmin(axis=0)
x.argmin(axis=1)

rawDescription: How to return all the minimum indices in numpy

description: Return all the minimum indices in numpy


rawDescription: Concatenate or print list elements with a trailing comma in Python


rawDescription: Using Python & Beautiful Soup, can I obtain a tag list filtered by whether background attr is set?


code:
"""
Wrapper functions to more user-friendly calling of certain math functions
whose output data-type is different than the input data-type in certain
domains of the input.

For example, for functions like log() with branch cuts, the versions in this
module provide the mathematically valid answers in the complex plane:

>>> import math
>>> from numpy.lib import scimath
>>> scimath.log(-math.exp(1)) == (1+1j*math.pi)
True

Similarly, sqrt(), other base logarithms, power() and trig functions are
correctly handled.  See their respective docstrings for specific examples.
"""

rawDescription: Relationship between scipy and numpy

description: Relationship between scipy and numpy


code:
from modX import *
called_by('is_A')  # changes modX
from modX import *  # do it again to get modified version

print("I love {}".format(my_string))  # -> I love spam

rawDescription: unify python script keeping specific parts

description: Unify python script keeping specific parts


code:
row_n = 0
col_n = 2
liststore[row_n][col_n] = 'new value'

rawDescription: pygtk - how update a gtk.liststore?

description: Pygtk - how update a gtk.liststore


code:
from django import forms
from .profiles.models import Profile, Specialty

class ProfileSearchForm(forms.ModelForm):
    specialties = forms.ModelMultipleChoiceField(queryset=Specialty.objects.all(), widget=forms.CheckboxSelectMultiple, required=False)

    class Meta:
        model = Profile
        fields = ('specialties',)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(ProfileSearchForm, self).__init__(*args, **kwargs)
        self.fields['specialties'].initial = self.request.GET.getlist('specialties')

rawDescription: How to search on a Many to Many field in Django?

description: Search on a Many to Many field in Django


rawDescription: Finding first non-digit character with .find in Python


code:
while True:
    #this is the menu
    menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2: ")
    if(menu=="1"):
        method1()
    if(menu=="2"):
        method2()

rawDescription: python restart the program after running a method

description: Python restart the program after running a method


code:
class weathersource():
    weathersourcelist = []

    def __init__(self, name):
        self.weathersourcelist.append(self)
        self.name = name

rawDescription: I want a classes __init__ to add the object to a list, but I want to prevent redundancy and "if self not in objectlist" isn't working


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

class ArticleAdmin(admin.ModelAdmin):

    def render_change_form(self, request, context, *args, **kwargs):
        """We need to update the context to show the button."""
        context.update({'show_save_and_copy': True})
        return super().render_change_form(request, context, *args, **kwargs)

    def response_post_save_change(self, request, obj):
        """This method is called by `self.changeform_view()` when the form
        was submitted successfully and should return an HttpResponse.
        """
        # Check that you clicked the button `_save_and_copy`
        if '_save_and_copy' in request.POST:
            # Create a copy of your object
            # Assuming you have a method `create_from_existing()` in your manager
            new_obj = self.model.objects.create_from_existing(obj)

            # Get its admin url
            opts = self.model._meta
            info = self.admin_site, opts.app_label, opts.model_name
            route = '{}:{}_{}_change'.format(*info)
            post_url = reverse(route, args=(new_obj.pk,))

            # And redirect
            return HttpResponseRedirect(post_url)
        else:
            # Otherwise, use default behavior
            return super().response_post_save_change(request, obj)

rawDescription: How do I add custom actions to a change model form in Django Admin?

description: Add custom actions to a change model form in Django Admin


code:
array1 = []
array2 = []
for line in lines:
    columns = line.split()
    array1.append(columns[1])
    array2.append(columns[2])

rawDescription: Reading specific sections of new lines

description: Reading specific sections of new lines


code:
pattern = r"""
BEGIN:VEVENT\n
DTSTART:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})\d{2}Z\n
DTEND:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})\d{2}Z\n
LOCATION:(.*?)\n
SUMMARY:\[(.*?):.*?\]\s(.*?)\s?\n
END:VEVENT
"""

s = re.findall(pattern, source, re.DOTALL | re.VERBOSE)
print(s)

rawDescription: python re.findall() only gives me one result

description: Python re.findall() only gives me one result


rawDescription: Pass bash file list to python CLI function


code: [u'food', u'drink']

rawDescription: How to see top n entries of term-document matrix after tfidf in scikit-learn

description: See top n entries of term-document matrix after tfidf in scikit-learn


rawDescription: Changing a function implementation in Python


main: {{ num_results }}, you just searched for {{ query }}

secondary: {{ num_results }}

rawDescription: Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?


code:
for line in fileinput.input():

    for pattern in patterns:
        line, n = re.subn(pattern, repl1, line)

        if n:
            break

    print(line, end="")

rawDescription: python regex only apply one replace

description: Python regex only apply one replace


code:
from openerp.addons.web.controllers import main

main.html_template = main.html_template.replace(
    '<title>OpenERP</title>',
    '<title>My Cool Company</title>'
    )

rawDescription: How can I change the browser title?

description: Change the browser title


rawDescription: Python - Exact Number of Arguments Defined by Variable


code: q = [ [ (1-i) * j for j in range(2) ] for i in range(2) ]

rawDescription: Python variable value reset out of loop

description: Python variable value reset out of loop


code:
class C(A, B):
    def __init__(self):
        A.__init__(self,4)
        B.__init__(self,4)

rawDescription: How can I call a particular base class method in Python?

description: Call a particular base class method in Python


code:
print([d2[k] for k in d2.viewkeys() - d1])
print([d1[k] for k in d1.viewkeys() - d2])

rawDescription: Find difference between two multi dimensional lists


code: bar = lambda y: foo (0, y)

rawDescription: How to copy a function and set a default parameter in Python?

description: Copy a function and set a default parameter in Python


code:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
[x for s in reversed(zip(*[iter(lst)]*3)) for x in s]

rawDescription: Manipulating a list by slicing in Python3.x


code:
if sortedJumble in sortedWords:
        print ("Your words are:")
        print ("\n".join(sortedWords[sortedJumble]))
        break

rawDescription: Print different results in Python a dictionary


code:
import networkx as nx
G = nx.DiGraph()
for d in pd.read_csv(path_to_edge_list,sep='\s+', header=None, names=['Node1', 'Node2', 'Weight'], chunksize=10000):
    G.add_weighted_edges_from([tuple(x) for x in d.values])

rawDescription: networkx - read edgelist in chunks (pandas)

description: Networkx - read edgelist in chunks (pandas)


code:
for s in ["button 1", "button 2", "button 3"]:
    b=Button(root, text=s, bg="white")
    b.pack()
    b.bind("<Enter>", SetColor)
    b.bind("<Leave>", ReturnColor)

rawDescription: How to bind multiple widgets with one "bind" in Tkinter?

description: Bind multiple widgets with one "bind" in Tkinter


code:
from random import randrange

def shuffle(items):  # mutates input list
    i = len(items)
    while i > 1:
        j = randrange(i)  # 0 <= j <= i
        items[j], items[i] = items[i], items[j]
        i = i - 1
    return

rawDescription: How do I randomize a list of strings with random.seed?

description: Randomize a list of strings with random.seed


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np
import csv

color_map = {'A':'r', 'B':'b', 'K':'k', 'C':'c'}
shape_map = {'dia':'^', 'cir':'o', 'bu':'.'}

with open('/tmp/dist.txt','r') as in_file:
    reader = csv.DictReader(in_file, delimiter=' ', skipinitialspace=True)
    data = []
    for r in reader:
        data.append([float(r['col1']),
                     float(r['col2']),
                     float(r['col3']),
                     color_map[r['col4']],
                     shape_map[r['col5']]])

rawDescription: How to change shapes/colours for 3d points with matplot3d

description: Change shapes/colours for 3d points with matplot3d


code:
z = re.finditer(r"(\S+).*(?:\sA\s|\sCNAME\s)", db)
z = [i.group(1) for i in z]

rawDescription: How to match an OR expression without grouping it?

description: Match an OR expression without grouping it


code:
class NodeVisitor(object):
    """
    A node visitor base class that walks the abstract syntax tree and calls a
    visitor function for every node found.  This function may return a value
    which is forwarded by the `visit` method.

    This class is meant to be subclassed, with the subclass adding visitor
    methods.

    Per default the visitor functions for the nodes are ``'visit_'`` +
    class name of the node.  So a `TryFinally` node visit function would
    be `visit_TryFinally`.  This behavior can be changed by overriding
    the `visit` method.  If no visitor function exists for a node
    (return value `None`) the `generic_visit` visitor is used instead.

    Don't use the `NodeVisitor` if you want to apply changes to nodes during
    traversing.  For this a special visitor exists (`NodeTransformer`) that
    allows modifications.
    """

    def visit(self, node):
        """Visit a node."""
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        return visitor(node)

    def generic_visit(self, node):
        """Called if no explicit visitor function exists for a node."""
        for field, value in iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        self.visit(item)
            elif isinstance(value, AST):
                self.visit(value)

rawDescription: What type of tree traversal does the ast module use?


code:
('file1', 'string1', 'string2')
('file2', 'string3', 'string4')
('file3', 'string5', 'string6')

rawDescription: Getting command line arguments as tuples in python


code:
Output
6

rawDescription: Is there a math nCr function in python?

description: Is there a math nCr function in python


code:
while verify:
    verify = False
    Name(SN)

rawDescription: Python27: Checking to see if user input is correct. When select Yes, returns name correctly. When select no, return is 'None'


rawDescription: Why are lists linked in Python in a persistent way?


code: list = list + ['four']

rawDescription: Why do copied dictionaries point to the same directory but lists don't?


code: instance.a = 1

rawDescription: Python list of variables inside a class

description: Python list of variables inside a class


code:
pairs = {'201': ['
Dunajská Streda	201
\n', '
Dunajský Klátov	201
\n'], '205': ['
Košolná	205
\n', '
Leopoldov	205
\n', '
Trnava	205
\n'], '705': ['
Pušovce	705
\n', '
Radatice	705
\n', '
Rokycany	705
\n'], '304': ['
Rudnianska Lehota	304
\n', '
Sebedražie	304
\n', '
Seč	304
\n', '
Šútovce	304
\n'], '305': ['
Selec	305
\n'], '103': ['
Modra	103
\n', '
Pezinok	103
\n'], '101': ['
Bratislava - Nové Mesto	101
\n', '
Bratislava - Podunajské Biskupice	101
\n'], '806': ['
Plechotice	806
\n', '
Trebišov	806
\n']}

rawDescription: Split dictionary by keys in Python

description: Split dictionary by keys in Python


code:
while running:
    # Handdle your events
    # update your state
    # draw to your display
    pygame.display.update()

rawDescription: Why balls cannot move in my code in Pygame when I code 'Pong'? Can Someone help me to check my code?


code:
from itertools import chain

list(chain.from_iterable(item for item in sorted(d.iteritems())))

rawDescription: Generator-expression, getting the same results of using append or extend in a for-loop


rawDescription: Python String to Escaped Hex

description: Python String to Escaped Hex


rawDescription: Copy value from one column based on the value of another column


rawDescription: Calculate conditional means in Pandas

description: Calculate conditional means in Pandas


code:
def average(tos, map_lst):
    """
    given
        tos: a sequence of N|user\tname\tAGE\n
        map_lst: a list with positions corresponding to those in tos, and values
                 indicating which group each tos element will be averaged with.
    return the groups of averages as a list of user\tname\tAVG\n
    """

    # get the leading nums
    nums = [s.partition('|')[0] for s in tos]

    # group them into lists that will be averaged together (based on the map)
    avg_groups = [[] for i in set(map_lst)]
    for i,n in zip(map_lst, nums):
        avg_groups[i].append(n)

    # generate the averages
    def fmt(tup):
        mid = tos[0].partition('|')[2].rpartition('\t')[0] # user\tname
        if len(tup) > 1:
            avg = '({0})/{1}'.format('+'.join(tup), len(tup))
        else:
            avg = str(tup[0])
        return "{0}\t{1}\n".format(mid, avg)

    return [fmt(l) for l in avg_groups]

rawDescription: function to compute averages and retrieve information over defined indexes in a tuple of strings

description: Function to compute averages and retrieve information over defined indexes in a tuple of strings


code:
import gc

...
for obj in gc.get_referrers(car):
     if not isinstance(obj, car): continue
     obj.drive()

rawDescription: Calling a method on all instances of an object


code:
for i in xrange(self.number_boxes):

    self.box[i].grid_remove()
    self.choice_title.grid_remove()

rawDescription: Deleting parts of a frame using grid_forget Tkinter


rawDescription: looping for a sum versus summing a list comprehension

description: Looping for a sum versus summing a list comprehension


code:
a = {}
for k in v:
    a[k] = d[k] if k in d else 0

rawDescription: Simple syntax error in Python if else dict comprehension


rawDescription: looking for a SIGNAL in tablewidget

description: Looking for a SIGNAL in tablewidget


code:
# previous self.vbox_tags layout goes bye-bye
self.vbox_tags = QtGui.QVBoxLayout()

if self.tags != None:
    ...
else:
    # clearing a new empty one
    self.clearLayout(self.vbox_tags)

rawDescription: My widgets don't want to disappear

description: My widgets don't want to disappear


code:
class stock_picking_out(osv.Model):
    _name = 'stock.picking.out'
    _inherit = 'stock.picking.out'
    _columns = { 'my_custom_field': fields.related(
        'sale_id', 'my_custom_field', type='char',
        readonly=True, string='field description'),
    }
class stock_picking(osv.Model):
    _name = 'stock.picking'
    _inherit = 'stock.picking'
    _columns = { 'my_custom_field': fields.related(
        'sale_id', 'my_custom_field', type='char',
        readonly=True, string='field description'),
    }

rawDescription: OpenERP-v7: Add custom field to delivery order from sale order


code:
class cMyDates:
    def __init__(self, Week_Start, Week_End, Week_Num, Month_Num, Month, Year, Day_Num):
        self.Week_Start  = Week_Start
        self.Week_End    = Week_End
        self.Week_Num    = Week_Num
        self.Month_Num   = Month_Num
        self.Month       = Month
        self.Year        = Year
        self.Day_Num     = Day_Num

rawDescription: Python - can text file data be stored in code?


code:
class A:

     def __init__(self, x):
          self.x = x

class B(A):

     def __init__(self, x, y):
          A.__init__(self, x)
          self.y = y

rawDescription: What is the purpose of calling __init__ directly?


rawDescription: Pythononly pings 1 out of 2 IP's (Subprocess)


code:
pathname = r"C:\windows\system32\test.txt"
os.path.split(pathname)

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

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


rawDescription: Counting similarities among two pandas dataframes


code:
a = np.array([[0, 1, 2], [2, 1, 3], [0, 1, 3]])
chg = np.array([3, 0, 2, 1])
inverse_chg=chg.take(chg)
print(inverse_chg.take(a))

rawDescription: Replace value in an array by its index in a list


code:
from collections import defaultdict
from itertools import groupby
import csv

entries = defaultdict(list)
csv_files = [(0, 'PV.csv', 'PV'), (1, 'Dwell.csv', 'Dwel'), (2, 'Session.csv', 'Sess'), (3, 'Elapsed.csv', 'Elap')]

for index, filename, shortname in csv_files:
    f_input = open(filename, 'rb')
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        row[:] = [col for col in row if col]
        entries[(row[0], row[1])].append((index, shortname, row[2:]))

    f_input.close()

f_output = open('finalFile.csv', 'wb')
csv_output = csv.writer(f_output)
csv_output.writerow(header[:2] + ['Var'] + header[2:4])

for key in sorted(entries.keys()):
    for k, g in groupby(sorted(entries[key]), key=lambda x: x[1]):
        var_group = list(g)
        if len(var_group[0][2]):
            up = var_group[0][2][0]
            for entry in var_group:
                for pair in zip(*[iter(entry[2])]*2):
                    csv_output.writerow([key[0], key[1], entry[1], up, pair[1]])
                    up = int(pair[1]) + 1

f_output.close()

rawDescription: Add new column in a csv file and manipulate on the on records


code:
import numpy as np
import matplotlib

x = np.linspace(-1, 1, 201)

L = np.polynomial.legendre.legval(x, np.identity(50))

plt.plot(x, L.T)

rawDescription: python: integrating a piecewise function

description: Python: integrating a piecewise function


rawDescription: Python compare list and store in new variable


rawDescription: Correspondence between a "ij" meshgrid and a long meshgrid


code:
M.A
sparse.triu(M).A

rawDescription: Python Scipy How to traverse upper/lower trianglar portion non-zeros from csr_matrix


code: result

rawDescription: Getting id names with beautifulsoup

description: Getting id names with beautifulsoup


code:
total = 0                           #Have total number
bigNumber = str(123456789)          #Convert our big number to a string
startPlace = 2                      #Start
endPlace = 4                        #End
for i in xrange(startPlace,endPlace):    #have i keep track of where we are, between start and end
    total = total + int(bigNumber[i])    #Get that one spot, and add it to the total
print(total)                       #Print our total

rawDescription: How does one add the digits of a large number?

description: Add the digits of a large number


code:
def tab_level(astr):
    """Count number of leading tabs in a string
    """
    return len(astr)- len(astr.lstrip('\t'))

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


code: interesting_vals = frozenset([dictA[5] for dictA in listA if 5 in dictA])

rawDescription: Python: How to iterate lists of dictionaries Fast


rawDescription: how to make kivy widgets make a pause

description: Make kivy widgets make a pause


code: [f(x) for x in list]

rawDescription: List Comprehensions in Python : efficient selection in a list


code:
result = {}
for key, v1, v2 in inputlist:
    minimum, maximum = result.get(key, (float('inf'), float('-inf')))
    if v1 < minimum:
        minimum = v1
    if v2 > maximum:
        maximum = v2
    result[key] = (minimum, maximum)

result

rawDescription: Can Python's comprehensions make groups?

description: Can Python's comprehensions make groups


code: [[domain,myList.count(domain)] for domain in set(myList)]

rawDescription: How to count similar domains in emails and print every domain only once[python]?

description: Count similar domains in emails and print every domain only once[python]


code:
def binary_insert(self,list_in):
    self._root = binary_insert(list_in,0,len(list_in) - 1)

rawDescription: Confusion with recursion and property setters in Python


rawDescription: Python: Remove Sublists from List if Same Including/Not Including Order


code:
def window(i, n = 2):
    return list(zip(*(i[p:] for p in range(n))))

rawDescription: get items 2 by 2 from a list in Python

description: Get items 2 by 2 from a list in Python


rawDescription: how to get some fields list by sqlalchemy?

description: Get some fields list by sqlalchemy


code:
from pykeyboard import PyKeyboard
keyboard = PyKeyboard()
keyboard.tap_key("a")

rawDescription: Generate keystrokes in Linux from Python3


code:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--check', action='store_true', dest="check")
group.add_argument('--nocheck', action='store_false', dest="check")
parser.parse_args(["--check"])
parser.parse_args(["--nocheck"])

rawDescription: How to manage precedence in argparse?

description: Manage precedence in argparse


code:
import subprocess
mydir="c:\\"
subprocess.Popen('explorer '+mydir)

rawDescription: Python: Open a modules source code in Finder/Windows explorer


code:
import json

data = '''
{
    "components": [
        {
            "self": "MY URL",
            "id": "ID",
            "name": "NAME",
            "description": "THIS IS DESC",
            "isAssigneeTypeValid": false
        },
        {
            "self": "MY URL 2",
            "id": "ID",
            "name": "name",
            "isAssigneeTypeValid": false
        },
        {
            "self": "URL 3",
            "id": "ID",
            "name": "NAME 3",
            "description": "DESC",
            "isAssigneeTypeValid": false
        }
    ]
}
'''

datas = json.loads(data)
for d in datas['components']:
    print(json.dumps(d))

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

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


code:
from io import TextIOWrapper, BytesIO

# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)

rawDescription: how do i block stdout from showing my password during my subprocess call in python

description: Block stdout from showing my password during my subprocess call in python


code:
mod = "test1"
mod = importlib.import_module(mod)
p = ast.parse(inspect.getsource(mod))

for n in p.body:
    if isinstance(n, ast.Expr):
        for node in ast.walk(n):
            if isinstance(node, ast.Call):
                print(node.lineno)

rawDescription: Comment Python function calls in a string with source code


code:
def handle(self, type, *args, **kwargs):
    func = getattr(self, 'handle_%s' % type, None)
    if func is None:
        raise Exception("No handler for type %r" % type)
    return func(*args, **kwargs)

rawDescription: Dictionary or If statements, Jython

description: Dictionary or If statements, Jython


rawDescription: Set differences on columns between dataframes


code:
counts_and_means.columns = counts_and_means.columns.droplevel()
counts_and_means

rawDescription: Pandas: Aggregating and applying multiple functions to same column


code:
from itertools import groupby
for k, g in groupby(sorted(a, key=lambda x: x[0]), key=lambda x: x[0]):
    print(list(g))

rawDescription: Iterating trough list and comparing dicts inside of list


code: re.split(r'[Hh]ello | moon', 'Hello moon')

rawDescription: Is there a way to make python str.partition ignore case?


code:
import numpy as np

data = [[361, 4, 1],
        [259, 3, 2],
        [361, 2, 3],
        [259, 1, 4]]
data = np.array(data)
persons = data[:,0]
testIds = data[:,1]
sortKey = persons + 1.0*testIds / max(testIds)

data = data[np.argsort(sortKey)]

#If this is not the same for everyone this will not be possible with numpy
testsPerPerson = np.count_nonzero(data[:,0][data[:,0] == data[0,0]])

scores = data[:,-1].reshape(testsPerPerson, data.shape[0]/testsPerPerson)

rawDescription: Numpy, sorting based on column twice

description: Numpy, sorting based on column twice


code:
with open('ratings.txt', 'rb') as f:
    for line in f:
        a = line.strip().split("|")

rawDescription: Trying to read information in a file into two lists in Python


rawDescription: Weird behavior specifying date limits with pandas


code:
def __setattr__(self, name, value):
    object.__setattr__(self, name, value)

rawDescription: I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined


code:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(myIndex)
import json
output = json.dumps(myIndex,sort_keys=True,indent=4, separators=(',', ': '))
print(output)
myRecoveredIndex = json.loads(output)
list(myRecoveredIndex.keys())

rawDescription: How to write an index that I have crated to a file in Python

description: Write an index that I have crated to a file in Python


code:
B={}
gbl = globals()
for i in range(1,N+1):
       B[i]=gbl['A_' + str(i)]

rawDescription: Going through names of a set of matrices in Python


code:
from fabric.io import OutputLooper
from datetime  import datetime

def newFlush(self, text):
    stamp = datetime.now().strftime("%a %b %d %H:%M:%S - ")
    print(stamp + text)

OutputLooper._flush = newFlush

rawDescription: Fabric log format to display date and time


code:
from itertools import tee
fst, snd = tee(iter(my_list))
next(snd, None)
d = dict(zip(fst, snd))

rawDescription: Is there a way to get the next item in a list by knowing the current item's value?


code:
self.label = Label()
self.label.pack(side=LEFT)

rawDescription: How to control if a component exists in a Tk object/window?

description: Control if a component exists in a Tk object/window


code:
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims  = [f for f in files if f[2].lower() not in IMAGE_TYPES]

rawDescription: Python: split a list based on a condition?


code:
class Container:
    def __getitem__(self, item):
        try:
            id = int(item)
            return DBSession.query(self.cls).filter_by(id=id).one()
        except (NoResultFound, ValueError):
            raise KeyError(item)

rawDescription: Using singleton classes in domain model traversal in Pyramid


code:
from scipy.sparse import csr_matrix
X = csr_matrix(np.arange(10).reshape(2, 5), dtype=np.float)
X.A

rawDescription: How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?

description: Operate elementwise on a matrix of type scipy.sparse.csr_matrix


code:
def same_diff(a, b):
    sames = []
    diffs = []
    i = 0
    j = 0
    while i < len(a) and j < len(b):
        if a[i] == b[j]:
            sames.append(a[i])
            i += 1
            j += 1
        elif a[i] > b[j]:
            diffs.append(b[j])
            j += 1
        else:
            diffs.append(a[i])
            i += 1
    diffs += a[i:]
    diffs += b[j:]
    return sames, diffs

a = (1,2,3,6,7,11,13)
b = (2,3,4,6,7,9)

same_diff(a, b)
# ([2, 3, 6, 7], [1, 4, 9, 11, 13])

rawDescription: Align two lists and do action on aligned and miss-aligned objects


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

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


rawDescription: Python 3.3 list assistance

description: Python 3.3 list assistance


code: result = [word for word in word_counts if word_counts[word] > 1]

rawDescription: Find duplicates in string, and return single result for only duplicates


code:
myColourList[minId] = "red"
myColourList[maxId] = "green"

rawDescription: How to colour maixum and minimun of each bar in bar graph in python?

description: Colour maixum and minimun of each bar in bar graph in python


code:
import subprocess
subprocess.call(["python", "myscript.py"])
subprocess.call(["python", "myscript2.py"])

rawDescription: Python - how do I call external python programs?


code:
x=np.arange(10,20)
idx = np.nonzero(x%2)
idx
x[idx]

rawDescription: How to retrieve the array elements in a tuple in numpy

description: Retrieve the array elements in a tuple in numpy


rawDescription: Implementing a bit-swap hack in Python

description: Implementing a bit-swap hack in Python


code:
import scipy.spatial as sp
x = np.linspace(0, Lx, Nx)
y = np.linspace(0, Ly, Ny)
z = np.linspace(0, Lz, Nz)

#Manipulate x,y,z here to obtain the dimensions you are looking for

center=np.array([x0,y0,z0])

#First mask the obvious points- may actually slow down your calculation depending.
x=x[abs(x-x0)<cutoff]
y=y[abs(y-y0)<cutoff]
z=z[abs(z-z0)<cutoff]

#Generate grid of points
X,Y,Z=np.meshgrid(x,y,z)
data=np.vstack((X.ravel(),Y.ravel(),Z.ravel())).T

distance=sp.distance.cdist(data,center.reshape(1,-1)).ravel()
points_in_sphere=data[distance<cutoff]

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

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


code:
from numpy.lib.stride_tricks import as_strided
win = as_strided(rel, shape=(rel.shape[0]-79, 80), strides=rel.strides*2)

rawDescription: Pandas time series operations

description: Pandas time series operations


code:
popt, pcov = curve_fit(func, x, y, p0=guess)
fit = func(x, *popt)

rawDescription: fit multiple gaussians to the data in python

description: Fit multiple gaussians to the data in python


code:
code
with open('input.txt',encoding='utf8') as f:
    while True:
        data = f.read(2)   # reads 2 Unicode codepoints, not bytes.
        if not data: break
        print(ascii(data))

rawDescription: Python 3- check if buffered out bytes form a valid char


code:
import re

new_doc = [re.sub(r'|'.join(exclude),'',sent) for sent in documents]
new_doc

rawDescription: Deleting words from text list

description: Deleting words from text list


code: notepad = notepad + 1

rawDescription: Adding to local variables (integers) in Python


code: import pandas as pd

rawDescription: Creating Horizontal Bar Plot With Time-Series Data in Python


code: psimaps = np.sum(featureParams*features[..., None, None], axis=2, keepdims=True) + transitiveParams

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

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


rawDescription: How to remove quotation list in python

description: Remove quotation list in python


rawDescription: Elementwise logical checks using numpy arrays


rawDescription: Summing Attribute in a list of Python Objects


code:
V = [1,2,3,4,5]

f = open('Qin.txt')     # values in Qin.txt: 1, 3, 2
fdata = map(float, f.readlines())
f.close()

g = open('Qout.txt')    # values in Qout.txt: 4, 5, 5
gdata = map(float, g.readlines())
g.close()

output = [[v+fdata[i]-y for v in V] for i,y in enumerate(gdata)]

rawDescription: How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are in the txt files?

description: Loop through a list changing the list elements at each time step, adding or subtracting input values that are in the txt files


code: ((k,v) for k,v in a.items() if k[2] == 'l1p')

rawDescription: Get elements of a tuple-indexed dictionary specifying only one field of the tuple


rawDescription: How to compare dates from Excel sheets for value filling purposes on python

description: Compare dates from Excel sheets for value filling purposes on python


code: return output_list, key_list

rawDescription: Python No Action on 2nd Statement After 'IF'


code:
left.merge(right, how='left',
          left_on=['A', 'B', 'C'],
          right_on=['AA', 'BB', 'CC'])[['A', 'B', 'C', 'DD']]

rawDescription: How to merge two data frames based on different column names

description: Merge two data frames based on different column names


code:
corrected_names = []
for row in cursor.execute('SELECT name FROM company'):
    corrected_names.append(row[0].replace(',', ''))

rawDescription: (Python) How to edit existing rows in a SQL DB?


code:
HOUR_CHOICES = [('1', '8am'), ('2', '10am')]

class TestForm(Form):
     hour = SelectField(u'Hour', choices=HOUR_CHOICES)

rawDescription: Get selected text from a form using wtforms SelectField


code:
from pkg_resources import load_entry_point

load_entry_point('Sphinx==0.5.1', 'console_scripts', 'sphinx-build')()

rawDescription: access eggs in python?

description: Access eggs in python


rawDescription: Using Npyscreen not for the whole terminal


rawDescription: How to plot with different linestyles in pylab

description: Plot with different linestyles in pylab


code: numberedBox = dict((b.number, b) for b in Boxes)

rawDescription: How to access a specific class instance by attribute in python?

description: Access a specific class instance by attribute in python


code:
import operator
get_first = operator.itemgetter(0)
sorted_dict = collections.OrderedDict(sorted(ordered_dict.items(),
                                             key=get_first))

rawDescription: Ordered Dictionary is not sorting

description: Ordered Dictionary is not sorting


code:
from django.template import RequestContext
def home(request):
    extra_context = {}
    projects = projectBuildTests.objects.all()
    extra_context['projects'] = projects
    return render_to_response('testrunner/home.html', extra_context, context_instance=RequestContext(request))

rawDescription: Django Model Loop

description: Django Model Loop


code: from your_path_class import YourClass

rawDescription: Access ORM models from different classes in Odoo/OpenERP


code:
def rfid_formatter(value):
    str_value = str(value)
    for s in range(10 - len(str_value)):
        str_value = "0" + str_value
    return str_value

rawDescription: Python reading Wiegand dropping Zeros

description: Python reading Wiegand dropping Zeros


code:
from pylab import rcParams
rcParams['figure.figsize'] = 8, 2

rawDescription: matplotlib: Don't compress plot in the horizontal direction

description: Matplotlib: Don't compress plot in the horizontal direction


code:
# Create a Variable object, specifying the variable by name
varObj = datasetObj.varlist['bdate']
# Create a Variable object, specifying the variable by index
varObj = datasetObj.varlist[3]

rawDescription: How to find the index value of a variable in SPSS Python

description: Find the index value of a variable in SPSS Python


code:
SPIDER_MIDDLEWARES = {
    'scrapy.spidermiddlewares.offsite.OffsiteMiddleware': None,
    'myproject.middlewares.SimpleOffsiteMiddleware': 500,
}

rawDescription: How to work with a very large "allowed_domains" attribute in scrapy?

description: Work with a very large "allowed_domains" attribute in scrapy


code: gzipfile = gzip.GzipFile(fileobj=fileobj, mode='w')

rawDescription: Pass io.BytesIO object to gzip.GzipFile and write to GzipFile


code: (np.dot(V_over_WH.T, W) / W.sum(axis=0)).T

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code: word = re.findall("start;(.+?);", string)

rawDescription: regex, how to exlude search in match

description: Regex, how to exlude search in match


code:
def fewest_items_closest_sum_with_repetition(items, goal):
    """
    Given an array of items
      where each item is 0 < item <= goal
      and each item can be used 0 to many times

    Find the highest achievable sum <= goal

    Return any shortest (fewest items) sequence
      which adds to that sum.
    """
    assert goal >= 0, "Invalid goal"
    # remove any duplicate or invalid items
    items = set(item for item in items if 0 < item <= goal)
    # sort descending (work with largest values first)
    items = sorted(items, reverse=True)

    # start with the no-item sequence
    best   = {0: []}
    active = {0: []}
    # while we have further seeds to work from
    while active:
        nactive = {}
        for item in items:
            for total, seq in active.items():
                # find next achievable sum
                ntotal = total + item
                # if it is a valid subgoal and has not already been found
                if (ntotal <= goal and ntotal not in best):
                    # save it
                    best[ntotal] = nactive[ntotal] = [item] + seq
                    if ntotal == goal:
                        # best possible solution has been found!
                        break
        active = nactive

    # return the best solution found
    return best[max(best)]

rawDescription: reaching the goal number

description: Reaching the goal number


code:
import numpy as np
index = df['b'].index[df['b'].apply(np.isnan)]

rawDescription: Python - find integer index of rows with NaN in pandas


rawDescription: merging 2D slices into 3D volume in python

description: Merging 2D slices into 3D volume in python


rawDescription: python strong/weak dynamic/static type language?

description: Python strong/weak dynamic/static type language


rawDescription: How to specify size (dimension) of .eps when exported from matplotlib using savefig()

description: Specify size (dimension) of .eps when exported from matplotlib using savefig()


code:
import wave
import audioop

wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))

rawDescription: What type of file is the "sound fragment" parameter for audioop?


rawDescription: round exponential float to 2 decimals

description: Round exponential float to 2 decimals


code:
import wx

class frameMain(wx.Frame):
    """The main application frame."""
    def __init__(self,
                 parent=None,
                 id=-1,
                 title='TITLE',
                 pos=wx.DefaultPosition,
                 size=wx.Size(550, 400),
                 style=wx.DEFAULT_FRAME_STYLE):
        """Initialize the Main frame structure."""
        wx.Frame.__init__(self, parent, id, title, pos, size, style)
        self.Center()
        self.CreateStatusBar()

        self.buildMainMenu()

    def buildMainMenu(self):
        """Creates the main menu at the top of the screen."""
        self.MainMenu = wx.MenuBar()

        # Establish menu item IDs.
        menuID_File = 'exit'
        menuID_Help = 'about'
        menuID_ALL = [menuID_File,
                      menuID_Help]

        # Make a dictionary of the menu item IDs.
        self.menuID = {item: wx.NewId() for item in menuID_ALL}

        # Create the menus.

        self.menu_helper('File', self.menuID['exit'], 'Exit',
                         'Exit application', self.onExit)

        self.menu_helper('Help', self.menuID['about'], 'About',
                         'About the application.', self.onAbout)

        # Install the Main Menu.
        self.SetMenuBar(self.MainMenu)

    def menu_helper(self, menu, menu_id, name, help, handler, sep=True):
        """
        """
        menu_obj = wx.Menu()
        if sep:
            menu_obj.AppendSeparator()
        menu_item = menu_obj.Append(menu_id, name, help)
        self.Bind(wx.EVT_MENU, handler, menu_item)
        self.MainMenu.Append(menu_obj, menu)

    #----------------------------------------------------------------------
    def onExit(self, event):
        pass

    def onAbout(self, event):
        pass

if __name__ == '__main__':
    app = wx.App(False)
    frame = frameMain()
    frame.Show()
    app.MainLoop()

rawDescription: Automating a wxPython main menu setup?

description: Automating a wxPython main menu setup


code: return [key for key, value in my_dict.items() if value >= n]

rawDescription: How to return a list of words that occur n or more times in a text?

description: Return a list of words that occur n or more times in a text


code:
movies = {'007: Spectre': 2015}, {'Terminator Genesis': 2015}
rest_movies = {'Bridge of Spies': 2015}, {'Star Wars': 2015}

movie_to_find = 'Star Wars'

if movie_to_find in movies:
    print(movies[movie_to_find])
elif movie_to_find in rest_movies:
    print(rest_movies[movie_to_find])

rawDescription: Efficient way to find unique value in one of few lists


rawDescription: How to merge two arrays together, concatenating the corresponding elements?

description: Merge two arrays together, concatenating the corresponding elements


code:
# Read the input data once.
with open('C:/TestReq_100 Records.txt', 'r') as ipf:
    ipdata = ipf.read()
# Add a newline to the end of the file if there isn't already one present.
# Without this, the last and first lines of the input might become single lines.
if ipdata[-1] != '\n':
    ipdata += '\n'
# Write to the output file multiple times.
with open('processed.txt', 'w') as opf:
    for i in xrange(10):
        opf.write(ipdata)

rawDescription: writing to a file with python

description: Writing to a file with python


code:
import pythoncom
import win32com.client

### ... inside the thread function ...
x = win32com.client.Dispatch("someCOMobject")
win32com.CoInitialize()
# com calls here
win32com.CoUninitialize()

rawDescription: How to launch win32 applications in separate threads in Python

description: Launch win32 applications in separate threads in Python


code:
f = open('test.json', 'w')
df.to_json(f)
print >> f
json.dump(metadata, f)

rawDescription: Saving Pandas DataFrame and meta-data to JSON format


code:
class ScaledLabel(QtGui.QLabel):
    def __init__(self, *args, **kwargs):
        QtGui.QLabel.__init__(self)
        self._pixmap = QtGui.QPixmap(self.pixmap())

    def resizeEvent(self, event):
        self.setPixmap(self._pixmap.scaled(
            self.width(), self.height(),
            QtCore.Qt.KeepAspectRatio))

rawDescription: How to Autoresize QLabel pixmap keeping ratio without using classes?


code:
if msg.has_key('From'):
    msg.replace_header('From', f)
else:
    msg['From'] = f

rawDescription: bug in my mail sending pogram in python

description: Bug in my mail sending pogram in python


code:
class Player:
  def __init__(self, assetId, maxBid, minPrice, maxPrice):
    self.assetId = assetId
    self.maxBid = maxBid
    self.minPrice = minPrice
    self.maxPrice = maxPrice

rawDescription: How can I create a list of players in python

description: Create a list of players in python


code:
def height_by_gender_and_agegroup(p):
    key = p.gender, p.age //10
    val = p.height
    return (key, val)  # note the optional parentheses to denote a tuple

ret = height_by_gender_and_agegroup(person)
key = ret[0]
val = ret[1]  # "key, val =" is just a shortcut for this

rawDescription: returning multiple values in python

description: Returning multiple values in python


rawDescription: A set of unique lists

description: A set of unique lists


code:
import json

@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(json.loads(request.data))

rawDescription: Flask request and application/json content type


code:
@compiles(CreateView, 'sqlite')
def visit_create_view(element, compiler, **kw):
    return "CREATE VIEW IF NOT EXISTS %s AS %s" % (
         element.name,
         compiler.process(element.select, literal_binds=True)
         )

rawDescription: How to create an SQL View with SQLAlchemy?

description: Create an SQL View with SQLAlchemy


code:
vars     = ['mean','media','mode'] #again matching the order of the lists in S1
data_dict = dict(zip( vars,S1.iteritems()))
D1       = pandas.DataFrame.from_dict(data_dict)

rawDescription: Pandas How to convert from series to a data frame


rawDescription: Counting Syllables In String

description: Counting Syllables In String


code:
import cloudstorage as gcs
import webapp2
import cgi
import MySQLdb
import os
import logging
import time

from google.appengine.api import mail
from google.appengine.api import images
from google.appengine.ext import blobstore

class UploadImageHandler(webapp2.RequestHandler):
    def post(self):
        self.response.headers.add_header(ACCESS_CONTROL, '*')

        f = self.request.POST['image']
        fname = '/your-bucket-name/%s' % f.filename;

        gcs_file = gcs.open(fname, 'w', content_type="image/jpeg")
        gcs_file.write(self.request.get('image'))
        gcs_file.close()

rawDescription: Using PhoneGap + Google App Engine to Upload and Save Images


rawDescription: Reshaping/Combining several sub-matrices to one matrix in multi-dimensional space


code: OK = (B4X1 < dataX) & (dataX < B4X2) & (B4Y1 < dataY) & (dataY < B4Y2)

rawDescription: Finding indices that fall between given ranges


code: (mysum + dup)(3, 3)

rawDescription: Weird function/class casting in Python. Why do we have it?


code:
soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

rawDescription: How to find tags with only certain attributes - BeautifulSoup

description: Find tags with only certain attributes - BeautifulSoup


code:
pl.figure("Share values")
# ... some plots ...
pl.figure("Profits")
# ... some plots ...

pl.figure("Share values")  # Selects the first figure again

rawDescription: Matplotlib: how to set the current figure?


rawDescription: How to sort a numpy array into a specific order, specified by a separate list, based on the relative sizes of the values in the array

description: Sort a numpy array into a specific order, specified by a separate list, based on the relative sizes of the values in the array


code:
input = {'table':'favorite_actors', 'columnA':'Brent', 'columnB':'Spiner'}
query, params = prepareinsert(input)
cursor.execute(query, params)

rawDescription: Using pythons dictionary's to create a generic MySQL insert string


code: MyException = type("MyException", (Exception, ), {})

rawDescription: Python metaclasses configure classes. But can we configure metaclasses?


rawDescription: What causes Python's __main__ to disappear when embedding with Boost.Python


code:
import numpy as np
a = np.ones((16,16))
slice = a[:8,:8]
slice.shape
a = np.ones((3,16))
slice = a[:8,:8]
slice.shape

rawDescription: Slicing an image array into sub array

description: Slicing an image array into sub array


code:
x = set()
while True:
    data = input()
    if data.lower() == "done":
        break
    x.add(data)
x = list(x)

rawDescription: How to remove duplicate from string/mixed list

description: Remove duplicate from string/mixed list


code: overlap = ''.join(('1' if (bitmask1[n] == bitmask2[n] == '1') else '0') for n in range(7))

rawDescription: Python, SQLAlchemy: Storing business hours as binary bitmask


code: (s1.isnull() == s2.isnull()).all() and (s1[s1.notnull()] == s2[s2.notnull()]).all()

rawDescription: Comparing pandas.Series for equality when they contain nan?


code:
m_pos = event.GetPosition()  # position tuple
self.richText.HitTest(m_pos)
#now code here to test if the column and row positions are within your parameters#

rawDescription: How can I bind mouse event like leftdown on one word of TextCtrl. see the code start with #?

description: Bind mouse event like leftdown on one word of TextCtrl. see the code start with #


code: [e for e in text if e.endswith((".",".com",".net",".org",".edu",".gov"))]

rawDescription: Criteria for combining two list items

description: Criteria for combining two list items


code:
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
for text in textcollection:
    myprocess.stdin.write(text + '\n')
    while True:
        myoutputtext = ''
        try:
            myoutputtext += myprocess.stdout.read()
        except IOError:
            pass
        if validate_output(myoutputtext):
            break
        time.sleep(.1)    # short sleep before attempting another read

rawDescription: Persistent python subprocess

description: Persistent python subprocess


code:
for i in range(0, npoints, window_skip):
    block = np.fft.fft(newdata[i:i+window_size])
    block = block[:, np.newaxis]                    #turn into column vector (n, 1)

    if j == 0:
        FFT_out = block
        j = 1
    else:
        FFT_out = np.hstack((FFT_out, block))
        j = j + 1

rawDescription: Trying to get Python to concatenate generated column vectors to form a two dimensional array. It's not working


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
data= np.random.random((5, 4))
df = pd.DataFrame(data, index=Index, columns=Cols)

# Values from 0-0.5 will be red and 0.5-1 will be green
cmap, norm = mcolors.from_levels_and_colors([0, 0.5, 1], ['red', 'green'])

plt.pcolor(df, cmap=cmap, norm=norm)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

rawDescription: Color a heatmap in Python/Matplotlib according to requirement


code: return [x[:5] for x in mylist]

rawDescription: Return sublists of List of lists

description: Return sublists of List of lists


code:
def blockshaped(arr, nrows, ncols):
    need_reshape = False
    if arr.ndim > 2:
        need_reshape = True
    if need_reshape:
        orig_shape = arr.shape
        arr = arr.reshape(-1, arr.shape[-1])
    h, w = arr.shape
    out = (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1, 2)
               .reshape(-1, nrows, ncols))
    if need_reshape:
        new_shape = list(out.shape)
        new_shape[0] //= orig_shape[0]
        out = out.reshape([-1,] + new_shape)
    return out

rawDescription: Python - Get "subarrays" of 3d array

description: Python - Get "subarrays" of 3d array


code:
cur = db.cursor()
Xs = 24
Ys = 67
Zs = 95
variables = ['a','b','c','d','e','f','g','h']
sql = ("INSERT INTO mytable (X, Y, Z, " +
       ', '.join(variables) +
       ') VALUES ({0})').format(','.join(['%s'] * (len(variables) + 3)))

for x in range(Xs):
    for y in range(Ys):
        values = []
        for z in range(Zs):
            values = [x, y, z]
            for variable in variables:
                values.append(data[variable][x][y][z])
            cur.execute(sql, values)

rawDescription: Fastest way to combine and normalise data from mutiple multi-dimensional arrays


code:
from itertools import izip_longest
v1 = [1,2,3,4]
v2 = [1,2,3,4,5]
[a + b for a, b in izip_longest(v1, v2, fillvalue=0)]
def addVectors(v1, v2):
    min_length = min(len(v1), len(v2))
    result = [a + b for a, b in zip(v1, v2)]
    return result + v1[min_length:] + v2[min_length:]

addVectors(v1, v2)

rawDescription: Add sum of values of two lists into new one


code:
class MyModel(models.Model):
    # Blah blah
    active = CustomManager()

rawDescription: Modify default queryset in django

description: Modify default queryset in django


rawDescription: How many elements may python dictionary hold?


code:
import dill
dill.detect.trace(True)
dill.dumps(dict(zip(list('abcde'),[1,2,3,4,5])))

def foo(x):
  def bar(y):
    return x+y
  return bar

dill.dumps(foo)

dill.detect.trace(False)

rawDescription: Delete a Variable that has been Pickled

description: Delete a Variable that has been Pickled


code:
urls = ["http://92.230.38.21/ios/Channel767/Hotbird.mp3", "http://92.230.38.21/ios/Channel9798/Coldbird.mp3"]
for url in urls:
    print(url.split("/")[-1].split(".")[0])

rawDescription: Find string with regular expression in python


code: __getitem__, __setitem__

rawDescription: What is the pythonic way to implement a parse tree for custom format?


rawDescription: Find dependency/execution order of several statements


code:
regex = re.compile(r"\d{4}-\d{4}")
regex.sub(lambda m: '({0})'.format(m.group(0)), "Alan Turing 1912-1954")

rawDescription: Adding parentheses around a string matched by a regex in Python


code: print('this {} a prime number'.format('is' if is_prime(2) else 'is not'))

rawDescription: python shorthand method for a if-else based on the function's return

description: Python shorthand method for a if-else based on the function's return


code:
class C:
    ...
    ...
    @x.setter
    def x(self, value):
        self._x = value
        log('x set to {}'.format(value))

rawDescription: Using @property versus accessing variables directly


code:
content = file.read()
name = 'abst'
if name in content:
    slice = content.find(name)
    slice = slice, slice + len(name)

rawDescription: How to find substring in file?

description: Find substring in file


code:
def speak(self):
    return ANIMAL_SOUNDS[self.animal_type]

rawDescription: Choosing a method based on a field value in a Django model


code:
def getdiameter(self):
    return self.r * 2

def setdiameter(self, d):
    self.r = d / 2

d = property(getdiameter, setdiameter)

rawDescription: Object attributes that are linked to others: how to maintain consistency?


code:
class NA_(object):
    instance = None # Singleton (so `val is NA` will work)
    def __new__(self):
        if NA_.instance is None:
            NA_.instance = super(NA_, self).__new__(self)
        return NA_.instance
    def __str__(self): return "NA"
    def __repr__(self): return "NA_()"
    def __and__(self, other):
        if self is other or other:
            return self
        else:
            return other
    __rand__ = __and__
    def __or__(self, other):
        if self is other or other:
            return other
        else:
            return self
    __ror__ = __or__
    def __xor__(self, other):
        return self
    __rxor__ = __xor__
    def __eq__(self, other):
        return self is other
    __req__ = __eq__
    def __nonzero__(self):
        raise TypeError("bool(NA) is undefined.")
NA = NA_()

rawDescription: How to do boolean algebra on missing values?

description: Do boolean algebra on missing values


code: ops = {"+":operator.add, "*":operator.mul} #etc.

rawDescription: Z3Py: getting the function corresponding to each operator e.g. '*', '==', '-'


code: CalledStatistics['CountryCode'] = {'CallDuration', 'CallPrice', 'NumberOfTimesCalled'}

rawDescription: Python Adding multiple data points in a dict from CSV file


code:
import numpy as np

s1 = np.row_stack((set1))
s2 = np.row_stack((set2))
s3 = np.row_stack((set3))
s4 = np.row_stack((set4))

sums = s4[None,None,None,:,:] + s3[None,None,:,None,:] + s2[None,:,None,None,:] + s1[:,None,None,None,:]
count = (sums.reshape(-1,s1.shape[1])==0).all(1).sum()

rawDescription: Finding sets of vectors that sum to zero


code:
def gen_pattern(n):
    if n == 0:
        yield 0
    else:
        yield from gen_pattern(n-1)
        yield n
        yield from gen_pattern(n-1)

rawDescription: Using print() inside recursive functions in Python3


code:
from intervaltree import IntervalTree

t = IntervalTree()
for length, obj in zip(data['Length'], data['Object']):
    t[length-tolerance:length+tolerance] = obj

result = {}
for length in data['Length']:
    objs = [iv.data for iv in t[length]]
    result[length] = objs

rawDescription: pandas DataFrame.groupby with a tolerance

description: Pandas DataFrame.groupby with a tolerance


code:
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import auth

class AutoLogout:
  def process_request(self, request):
    if not request.user.is_authenticated() :
      #Can't log out if not logged in
      return

    try:
      if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
        auth.logout(request)
        del request.session['last_touch']
        return
    except KeyError:
      pass

    request.session['last_touch'] = datetime.now()

rawDescription: How can I detect user is inactive for 5 seconds in order to assign session key?

description: Detect user is inactive for 5 seconds in order to assign session key


code:
mask = np.ones_like(X, dtype='bool')
mask[np.arange(X.shape[0]), idx] = 0

rawDescription: Numpy array, removing one arbitrary element per row


code:
from pandas.tseries.offsets import CustomBusinessDay
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
mydate + bday_us

Out[13]: Timestamp('2014-12-26 00:00:00')

rawDescription: performance of pandas custom business day offset

description: Performance of pandas custom business day offset


code:
L = [(1,0,0), (1,1,0)]

def make_vars(L):
    for i, item in enumerate(L, start=1):
        globals()['t{0}'.format(i)] = item

make_vars(L)
print(t1)
# (1, 0, 0)

rawDescription: How to iteratively create new variables to store the ith value of a list

description: Iteratively create new variables to store the ith value of a list


code:
combined={}
for k, v in zip(amr_list, zip(pssr_list, inservice_list)):
    combined.setdefault(k, []).append(v)

rawDescription: Mapping data from excel with Python

description: Mapping data from excel with Python


code:
for idx,triplet in enumerate(sod_hng_hhl_lst):
    name,type,number = triplet
    new_number = number * 2
    # change just the number in the triplet
    sod_hng_hhl_lst[idx][2] = new_number

rawDescription: spliting list and adding values

description: Spliting list and adding values


code: tck = splrep(x, y, w=np.ones(len(x_spl)), s=0)

rawDescription: scipy splrep() with weights not fitting the given curve

description: Scipy splrep() with weights not fitting the given curve


code: d = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

rawDescription: list of tuples to dictionary of dictionaries

description: List of tuples to dictionary of dictionaries


code:
def require_super(func):
    f_name = func.func_name
    other_names = func.func_code.co_names
    if not all(val in other_names for val in [f_name, 'super']):
        warnings.warn("Super must be defined on function: " + f_name)
    return func

rawDescription: How to enforce (with a warning) that parent functions are called by the children that override them?

description: Enforce (with a warning) that parent functions are called by the children that override them


code:
import numpy as np
from numpy.random import normal
import matplotlib.pyplot as plt
from scipy.stats import norm

# gaussian distributed random numbers with mu =4 and sigma=2
x = normal(4, 2, 10000)

mean = np.mean(x)
sigma = np.std(x)

x -= mean

x_plot = np.linspace(min(x), max(x), 1000)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.hist(x, bins=50, normed=True, label="data")
ax.plot(x_plot, norm.pdf(x_plot, mean, sigma), 'r-', label="pdf")

ax.legend(loc='best')

x_ticks = np.arange(-4*sigma, 4.1*sigma, sigma)
x_labels = [r"${} \sigma$".format(i) for i in range(-4,5)]

ax.set_xticks(x_ticks)
ax.set_xticklabels(x_labels)

plt.show()

rawDescription: Python - Matplotlib: normalize axis when plotting a Probability Density Function


code:
import subprocess
subprocess.call('dir', shell=True, cwd='somepath')

rawDescription: How to send a list of commands using 'os.system('command')' to CMD in python

description: Send a list of commands using 'os.system('command')' to CMD in python


code:
with open('output.csv', 'wb') as fh:
    writer = csv.writer(fh, delimiter='\t')
    for (asset_id, prop), prop_values in data.iteritems():
        prop_values = ", ".join(prop_values)
        writer.writerow([asset_id, prop, prop_values])

rawDescription: Process CSV in Python

description: Process CSV in Python


rawDescription: Commas and strings in Python 2.7 string.format()


code: misspelled_word_list = list( set(sentence_list).difference(words) )

rawDescription: How to check if my list has an item from another list(dictionary)?

description: Check if my list has an item from another list(dictionary)


code:
import errno
try:
    with open('/dev/tty', 'w') as tty:
        tty.write('prompt> ')
except IOError as exc:
    if exc.errno == errno.ENXIO:
        pass # no /dev/tty available
    else:
        pass # something else went wrong

rawDescription: Save a Python script's output with > in bash while using raw_input()


code:
class CreateFatherView(CreateView):
    template_name = 'father_create.html'
    model = Father
    form_class = FatherForm # the parent object's form

    # On successful form submission
    def get_success_url(self):
        return reverse('father-created')

    # Validate forms
    def form_valid(self, form):
        ctx = self.get_context_data()
        inlines = ctx['inlines']
        if inlines.is_valid() and form.is_valid():
            self.object = form.save() # saves Father and Children
            return redirect(self.get_success_url())
        else:
            return self.render_to_response(self.get_context_data(form=form))

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))

    # We populate the context with the forms. Here I'm sending
    # the inline forms in `inlines`
    def get_context_data(self, **kwargs):
        ctx = super(CreateFatherView, self).get_context_data(**kwargs)
        if self.request.POST:
            ctx['form'] = FatherForm(self.request.POST)
            ctx['inlines'] = FatherInlineFormSet(self.request.POST)
        else:
            ctx['form'] = Father()
            ctx['inlines'] = FatherInlineFormSet()
        return ctx

rawDescription: Multiple Forms and Formsets in CreateView


code: lineup_students(data) == res

rawDescription: Python 2 - sorting strings respecting the lenght of the string and the alpabetical order


code:
import multiprocessing.connection
import subprocess
import sys, os, time

port = int(sys.argv[1])
conn = multiprocessing.connection.Client(('localhost', port), authkey="secret")

while True:
    try:
        obj = conn.recv()
        print("received: %s\n" % str(obj))
        sys.stdout.flush()
    except EOFError:  ## connection closed
        break

rawDescription: Python multiprocessing: How can I RELIABLY redirect stdout from a child process?


code:
def do_tasks(b):
    tasks = []
    for a in b:
        tasks.append(c.delay(a))
    return [t.get() for t in tasks]

rawDescription: Add n tasks to celery queue and wait for the results


code:
def f(df):
    mask = np.cumsum((df.hasTattoo == "Y").values) <= 1
    return df[mask]

df.groupby("person").apply(f)

rawDescription: Using pandas to drop all observations in a group after a condition has been met


rawDescription: Scipy's Optimize Curve Fit Limits

description: Scipy's Optimize Curve Fit Limits


code: ccys = [audcad, audchf, audjpy]

rawDescription: How to reference/iterate multiple lists in Python

description: Reference/iterate multiple lists in Python


code:
try: from urlparse import urljoin # Python2
except ImportError: from urllib.parse import urljoin # Python3
urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html")

rawDescription: Resolving a relative url path to its absolute path


code:
arr[tup][mask]
arr[tup][mask1]

rawDescription: how to replace only zeros of a numpy array using a mask

description: Replace only zeros of a numpy array using a mask


code:
delta = datetime.now() - datetime(1601,1,1,0,0)
delta.seconds + delta.days * 86400 + delta.microseconds / 1000000.

rawDescription: Calculating the number of seconds since 1601


rawDescription: What is :: (double colon) in numpy like in myarray[0::3]?


code:
(r'^/(?P<kind>blog)/$', 'view.stuff'),
(r'^/(?P<kind>news)/$', 'view.stuff'),

rawDescription: Reusing a Django app within a single project


code: decoded = json.loads(encoded, 'gbk')

rawDescription: How to convert a JSON string into a Python data structure

description: Convert a JSON string into a Python data structure


rawDescription: Python load txt into array with string

description: Python load txt into array with string


rawDescription: Python -- Check if object is instance of any class from a certain module


code:
from selenium import webdriver

dr = webdriver.PhantomJS()
dr.get("http://propertymap.sfplanning.org/")

dr.switch_to.frame(0)

dr.find_element_by_id("addressInput").send_keys("whatever")
dr.find_element_by_xpath("//input[@title='Search button']").click()

rawDescription: Selenium webdriver with python to scrape dynamic page cannot find element


code:
import matplotlib.pyplot as plt
from matplotlib.cbook import get_sample_data

im = plt.imread(get_sample_data('grace_hopper.jpg'))

fig, ax = plt.subplots()
ax.plot(range(10))

# Place the image in the upper-right corner of the figure
#--------------------------------------------------------
# We're specifying the position and size in _figure_ coordinates, so the image
# will shrink/grow as the figure is resized. Remove "zorder=-1" to place the
# image in front of the axes.
newax = fig.add_axes([0.8, 0.8, 0.2, 0.2], anchor='NE', zorder=-1)
newax.imshow(im)
newax.axis('off')

plt.show()

rawDescription: how to insert a small image on the corner of a plot with matplotlib?

description: Insert a small image on the corner of a plot with matplotlib


code:
s = 'I love {0} and {1}, she loves {0} and {1}'
s.format("apples", "oranges")

rawDescription: python about multiple %s in a string

description: Python about multiple %s in a string


rawDescription: matplotlib matshow labels

description: Matplotlib matshow labels


code:
plt.annotate(' ',xy=(0, 0),  # theta, radius
            xytext = (-np.pi/10,len(data)/6.),
            textcoords='data',
            arrowprops=dict(facecolor='red', shrink=0.05))
plt.annotate(' ',xy=(np.pi/4.2, 1.355*max(r)),  # theta, radius
            xytext = (np.pi/4.2, 1.2*max(r)),
            textcoords='data',
            arrowprops=dict(facecolor='blue', shrink=0.05))

rawDescription: matplotlib: polar plots with a 'notch'

description: Matplotlib: polar plots with a 'notch'


code:
for line in rows[1:]:
    numSlashes = line.count('/')
    total += numSlashes + 1

rawDescription: Python: How to count items in a specific column


code:
def some_dark_magic_with_iterable(curs, nelems):
    res = curs.fetchmany(nelems)
    while res:
        yield res
        res = curs.fetchmany(nelems)

rawDescription: Take a few elements from an iterable, do something, take a few elements more, and so on


rawDescription: Running a separate function alongside a loop in Python


code:
def get_attr_from_context(ctx, attr_str):
    attrs = iter(attr_str.split('.'))
    ans = ctx.get(next(attrs))
    for attr in attrs:
        ans = getattr(ans, attr)
    return ans

# Prints 'Test'
print(get_attr_from_context(C, 'person.name'))

rawDescription: Evaluate variable in context

description: Evaluate variable in context


rawDescription: Pandas, unexpected behavior of .resample('B')


code:
self.font = SOME_BASE_FONT
self.labelName.config(font = self.font)

rawDescription: Python/Tkinter: expanding fontsize dynamically to fill frame


code:
from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
from ctypes.wintypes import LPWSTR, LPCWSTR
GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32))

argc = c_int(0)
argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))

rawDescription: Python - sys.argv special symbol (€, ¢, ₪, etc…)


rawDescription: Python float to Decimal conversion

description: Python float to Decimal conversion


code: [ _ for _ in itertools.compress([1,2,3,4,5],[False,True,True,False,True]) ]

rawDescription: Find the indices of elements greater than x


code:
"""
This code provide an example of how to connect to LDAP (specifically, Active Directory)
using Python 3.

Requires python-ldap3, available via the following command:
pip install git+https://github.com/rbarrois/python-ldap.git@py3
"""

import ldap

LDAP_URI = 'ldap://ldap.server.com'
LDAP_DN = 'dc=server,dc=com'
LDAP_USERNAME = 'ldap_user@server.com'
LDAP_PASSWORD = ''
USER_NAME = 'username-to-test'
USER_IN_GROUP = 'CN=SomeGroup,DC=server,DC=com'
USER_NOT_IN_GROUP = 'CN=SomeGroupThatDoesNotExist,DC=server,DC=com'

try:
    # Connect to LDAP / Active Directory
    ldap_con = ldap.initialize(LDAP_URI)
    ldap_con.protocol_version = 3
    ldap_con.set_option(ldap.OPT_REFERRALS, 0)
    ldap_con.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)

    # sAMAAccountName is Active Directory's 'username'
    user_filter='(&(objectCategory=person)(objectClass=user)(sAMAccountName=' + USER_NAME + '))'
    attrs = ['memberOf']

    # Perform the search.
    ldap_user = ldap_con.search_s(LDAP_DN, ldap.SCOPE_SUBTREE, user_filter, attrs)

    # Active Directory returns a list of byte literals. Convert them to strings in a more sensibly named list.
    ldap_groups = []
    for value in ldap_user[0][1]['memberOf']:
        ldap_groups.append(value.decode('utf-8'))

    # Print the LDAP groups the user above is a member of, one per line.
    for value in ldap_groups:
        print(value)

    # Perform check to see whether a user is in a group, or explicitly, a user it not in a group.
    if USER_IN_GROUP in ldap_groups:
         print(USER_NAME + " is a member of " + USER_IN_GROUP)
    else:
         print(USER_NAME + " is not a member of " + USER_IN_GROUP)

    if USER_NOT_IN_GROUP in ldap_groups:
         print(USER_NAME + " is a member of " + USER_NOT_IN_GROUP)
    else:
         print(USER_NAME + " is not a member of " + USER_NOT_IN_GROUP)

    # Unbind from LDAP / Active Directory.
    ldap_con.unbind()
except ldap.LDAPError:
    print(ldap.LDAPError)

rawDescription: Pulling data from external Active Directory in Django


code:
class CustomUserAdmin(UserAdmin):

    def get_changelist(self, request, **kwargs):
        return CustomUserChangeList

rawDescription: Django contrib admin views limit customization


rawDescription: Python - matplotlib: find intersection of lineplots


code:
file_name = 'lex_parser'
class_name = 'LexParser'

Parser = getattr(__import__(file_name), class_name)

rawDescription: Dynamically import and create class instance


code:
import csv
ll = [[1,2,3],[3,4,5],[4,2,1]]
with open('a.csv','w') as f:
    writer = csv.writer(f)
    for x in zip(*ll):
        writer.writerow(x)

rawDescription: How to export a list with different size from python to excel

description: Export a list with different size from python to excel


code:
import operator

operator.add(1, 2)
(lambda x,y : x+y)(1, 2)

rawDescription: lambda in python

description: Lambda in python


rawDescription: Hack the in operator to return non booleans


rawDescription: extracting numbers from a string in a list via regex

description: Extracting numbers from a string in a list via regex


code:
def diagonals(a):
    rows, cols = a.shape
    if cols > rows:
        a = a.T
        rows, cols = a.shape
    fill = numpy.zeros(((cols - 1), cols), dtype=a.dtype)
    stacked = numpy.vstack((a, fill, a))
    major_stride, minor_stride = stacked.strides
    strides = major_stride, minor_stride * (cols + 1)
    shape = (rows + cols - 1, cols)
    return numpy.lib.stride_tricks.as_strided(stacked, shape, strides)

rawDescription: Find diagonals sums in numpy (faster)

description: Find diagonals sums in numpy (faster)


rawDescription: How determine encoding of datetime.strftime(...) in Python?


code:
import pandas as pd
import numpy as np

data = pd.read_csv('data_file.csv')
grouped_measured_power = data.groupby([' Rate', ' Frequency'])[' Measured_Power']
result = grouped_measured_power.aggregate({'min': np.min,
                                           'max': np.max,
                                           'average': np.mean})

rawDescription: Find min,max in csv file in python

description: Find min,max in csv file in python


code:
from my_other_script import get_input

def move():
    global board
    direction = "x"
    while direction != "a" and direction != "w" and direction != "s" and direction != "d":
          direction = get_input(board)
          if direction == "a":
             left()
          elif direction == "w":
             up()
          elif direction == "s":
             down()
          elif direction == "d":
             right()

rawDescription: Use program to input in a different program?


code:
import autopy

autopy.mouse.move(800, 300)
autopy.mouse.smooth_move(100, 600)

rawDescription: simulate cursor motion from X,Y to X,Y

description: Simulate cursor motion from X,Y to X,Y


code:
my_dict = dict((k, []) for k in keys )
my_dict
my_dict['k3'].append(1)
my_dict

rawDescription: Add items to a dictionary of lists

description: Add items to a dictionary of lists


code:
f = foo()
f.position.x, f.position.y
f.update((1, 2))
f.position.x, f.position.y

rawDescription: Method argument conversion: 'tuple' has no attribute 'attribute'


code:
from subprocess import check_call, STDOUT, CalledProcessError, call

with open("stdout.txt","w") as f, open("stderr.txt","w") as f2:
    try:
        check_call(['ls', '-l'], stdout=f, stderr=f2)
    except CalledProcessError as e:
        print(e.message)

rawDescription: How to execute and save result of an OS command to a file

description: Execute and save result of an OS command to a file


code:
import nltk
text = "Hello, this is my sentence. It is a very basic sentence with not much information in it"
tokenized_text = nltk.word_tokenize(text)
stopwords = nltk.corpus.stopwords.words('english')
filtered_tokenized_text = [word for word in tokenized_text if word not in stopwords]
filtered_word_freq = nltk.FreqDist(filtered_tokenized_text)
filtered_word_freq

rawDescription: Dropping specific words out of an NLTK distribution beyond stopwords


rawDescription: How to remove numeric character in my input text?

description: Remove numeric character in my input text


rawDescription: Is it necessary to include __init__ as the first function everytime in a class in Python?


rawDescription: Regular expression that finds and replaces non-ascii characters with Python


code:
words = []
while True:
   y = input()
   if y == "###":
     break
   y = y.lower()
   y = y.split()
   words.extend(y)

print(words)

rawDescription: Parsing multiple lines in Python

description: Parsing multiple lines in Python


code: df = df.set_index(['IDX1', 'IDX2', 'IDX3'])

rawDescription: How can I use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place?

description: Use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place


code:
import csv

symbol = ["msft", "cvx", "baba"]
header = ["symbol","ev_ebitda","asset"]

with open('output.csv', 'wb') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=header)
    csv_output.writeheader()

    for s in symbol:
        row = {'asset': 60, 'ev_ebitda': 40, 'symbol': s}
        csv_output.writerow(row)

rawDescription: Outputting Multi-row CSV Files from Multiple Dictionaries


code: indexed_sentence = [Sentence.index(x) for x in Sentence]

rawDescription: Replace the words in a list with the position of each word


code:
{'address': {'city': 'Madison',
  'clinic': '1 South Park UW Health Clinic',
  'country': 'United States of America',
  'country_code': 'us',
  'county': 'Dane County',
  'neighbourhood': 'Preglers Addition',
  'postcode': '53715',
  'road': 'Braxton Place',
  'state': 'Wisconsin',
  'suburb': 'Monona Bay'},
 'display_name': '1 South Park UW Health Clinic, Braxton Place, Preglers Addition, Monona Bay, Madison, Dane County, Wisconsin, 53715, United States of America',
 'lat': '43.06697945',
 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright',
 'lon': '-89.4000472713021',
 'osm_id': '102236889',
 'osm_type': 'way',
 'place_id': '2569590902'}

rawDescription: Is there a way to pull coordinates that fall in a certain state out of an array of lats and lons in python


code:
def add_position_to_content(lint):
    lint[:] = [elem + index for index, elem in enumerate(lint)]
    return lint

rawDescription: add the position of the element to the element in the list

description: Add the position of the element to the element in the list


code:
class SomeModelSerializer(serializers.HyperlinkedModelSerializer):
    _links = HALNestedLinksField(['revalidate'], # you detail_route names
                                 view_name='somemodel-detail')
    class Meta:
        model = SomeModel
        fields = ('url',
                  'date',
                  '_links') # do not forget it

rawDescription: @list_route and @detail_route nested routes do not appear in Browseable API


code: from . import makesoup

rawDescription: Python 3: module in same directory as script: "ImportError: No module named"


rawDescription: How to find index of a character after space in python

description: Find index of a character after space in python


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

rawDescription: list comprehension on multiple lists of lists

description: List comprehension on multiple lists of lists


code:
class MultitextureWidget(Widget):
    def __init__(self, **kwargs):
        self.canvas = RenderContext()
        self.canvas.shader.fs = fs_multitexture
        with self.canvas:
            Color(1, 1, 1)
            BindTexture(source='mtexture2.png', index=1)
            Rectangle(size=(150, 150), source='mtexture1.png', pos=(500, 200))

        self.canvas['texture1'] = 1
        super(MultitextureWidget, self).__init__(**kwargs)
        Clock.schedule_interval(self.update_glsl, 0)

    def update_glsl(self, *largs):
        self.canvas['projection_mat'] = Window.render_context['projection_mat']
        self.canvas['modelview_mat'] = Window.render_context['modelview_mat']

rawDescription: Kivy, Mask Widget Canvas

description: Kivy, Mask Widget Canvas


code:
processes = []
for i in range(4):
    p = Process(target=fonction, args=((process_id),filearg[file],t0))
    p.start()
    proc = psutil.Process(p.pid)
    proc.set_cpu_affinity([i])
    processes.append(p)

# Wait for *all* the child processes to terminate.
for p in processes:
    p.join()

rawDescription: p.join() in Python 2

description: P.join() in Python 2


code:
s = df["Pos"].apply(lambda x: pd.Series(1, pos_to_gene[x])).stack(0)
s

rawDescription: Adding list of values to rows, turning the dataframe into long format afterwards


code:
d = RandomChoiceDict()
for x in range(10**6):  # populate with some values
    d[x] = x**2

d.popitem_random()  # remove and return random item
132545 in d
d.popitem_random()

rawDescription: How to get a random value in a very large python dictionary

description: Get a random value in a very large python dictionary


rawDescription: protein sequence coding

description: Protein sequence coding


code:
label = getattr(self, 'label%d' % i)
label.modify_font(self.__font_small)

rawDescription: Optimize python code for working with object names


code:
def f (tree, path):
    return count (byPath (tree, path) )

for path in ['top.middle.XX.nested', 'top.last.XX.nested.XX.first', 'top.last.XX.nested.XX.second', 'other']:
    print (path, f (x, path) )

rawDescription: Count non-empty end-leafs of a python dicitonary/array data structure - recursive algorithm?


code:
import string
morse_alphabet = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.."
morse_letters = dict(zip(string.ascii_lowercase, morse_alphabet.split()))

def t(code):
    return filter(None, (morse_letters.get(c.lower()) for c in code))

rawDescription: How to improve efficiency in loops?

description: Improve efficiency in loops


code:
records = data.split('\n\n')
len(records)
records[0][:50]

rawDescription: Python 3.5 Regular expressions cannot read text file


code:
import serial

class mySerial(serial.Serial):
    def __del__(self):
        pass

ser = mySerial()
# rest of script the same

rawDescription: How do I override PySerial's "__del__" method in Python?

description: Override PySerial's "__del__" method in Python


code:
fileitem = form["userfile"]
if fileitem.file:
    # It's an uploaded file; count lines
    linecount = 0
    while 1:
        line = fileitem.file.readline()
        if not line: break
        linecount = linecount + 1

rawDescription: How does cgi.FieldStorage store files?

description: How does cgi.FieldStorage store files


code:
import struct
from IPy import IP
address = IP(struct.unpack('<I', struct.pack('>I', int(i, 16)))[0])
#Converts 'B91A210A' to IP('10.33.26.185')

rawDescription: Python: get MAC address of default gateway


code:
ts = pd.Series(pd.to_datetime(['2013-02-21 10:12:14.3']))
ts
ts.dt.dayofyear

rawDescription: How to find the number of the day in a year based on the actual dates using Pandas?

description: Find the number of the day in a year based on the actual dates using Pandas


code:
def point_is_in_mask(mask, point):
    # this is just pseudocode
    return mask.contains(point)

rawDescription: how to mask the specific array data based on the shapefile

description: Mask the specific array data based on the shapefile


code:
import sys
from PyQt4 import QtGui, QtCore

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.model = QtGui.QStandardItemModel()

        for k in range(0, 4):
            parentItem = self.model.invisibleRootItem()
            for i in range(0, 4):
                item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i))
                parentItem.appendRow(item)
                parentItem = item

        self.view = QtGui.QTreeView()
        self.view.setModel(self.model)
        self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove)

        self.setCentralWidget(self.view)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: QTreeView with drag and drop support in PyQt


code: plot(data)

rawDescription: Python - Plotting a graph from an array where the data in the array is from a data file


rawDescription: Python subprocesscall of a zip.exe

description: Python subprocesscall of a zip.exe


code:
if len(threadlist) > 0 :
  for server in threadlist :
    ...

rawDescription: My first python program: can you tell me what I'm doing wrong?


rawDescription: Integer to bitfield as a list

description: Integer to bitfield as a list


rawDescription: replace blanks in numpy array

description: Replace blanks in numpy array


rawDescription: Find the division remainder of a number

description: Find the division remainder of a number


code: a = [i for i in range(10)]

rawDescription: Why isn't my solution to Project Euler 9 working?


code:
from scrapy.utils import log

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
})
log.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
    'loggers': {
        'scrapy': {
            'level': 'ERROR',
        }
    }
})

rawDescription: Getting Scrapy Loggers

description: Getting Scrapy Loggers


code:
unpack_commands = sensor_info['sensor_info']['unpack_commands']
sql_statement = sensor_info['database_query']

# Unpack the data from the incoming serial data
params = data.unpack(unpack_commands)

Database().write_data(sql_statement, params)

rawDescription: Storing python dictionary in json file and substitute values upon reading


code: zip(b, zip(*a))

rawDescription: How to iterate for specific elements in a list?

description: Iterate for specific elements in a list


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))
finally:
    ff.quit()

rawDescription: Selenium: understanding wait

description: Selenium: understanding wait


code:
from _threading_local import local
import threading
import time

l = local()

def f():
   global l
   l.ok = "HMM"
   time.sleep(50)

if __name__ == "__main__":
    l.ok = 'hi'
    t = threading.Thread(target=f)
    t.start()
    for t in threading.enumerate():
        for item in t.__dict__:
           if isinstance(item, tuple):
               print("Thread's local is %s" % t.__dict__[item])

rawDescription: Python: Getting all the items out of a `threading.local`


code:
import requests
from bs4 import BeautifulSoup

urls = [
    'https://www.hl7.org/fhir/valueset-activity-reason.html',
    'https://www.hl7.org/fhir/valueset-age-units.html'
]

for url in urls:
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')

    h2 = soup.find(lambda elm: elm.name == "h2" and "Content Logical Definition" in elm.text)
    table = None
    for sibling in h2.find_next_siblings():
        if sibling.name == "table":
            table = sibling
            break
        if sibling.name == "h2":
            break
    print(table)

rawDescription: using bs4 to find a html tag (h2) having text

description: Using bs4 to find a html tag (h2) having text


code: A_csc.data = A_csc.data * v[A_csc.indices]

rawDescription: How to best row-scale a SciPy sparse matrix?

description: Best row-scale a SciPy sparse matrix


code:
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

import rsa

from boto.cloudfront.distribution import Distribution

from textwrap import dedent

# The private key provided in the Boto tests
pk_key = dedent("""
    -----BEGIN RSA PRIVATE KEY-----
    MIICXQIBAAKBgQDA7ki9gI/lRygIoOjV1yymgx6FYFlzJ+z1ATMaLo57nL57AavW
    hb68HYY8EA0GJU9xQdMVaHBogF3eiCWYXSUZCWM/+M5+ZcdQraRRScucmn6g4EvY
    2K4W2pxbqH8vmUikPxir41EeBPLjMOzKvbzzQy9e/zzIQVREKSp/7y1mywIDAQAB
    AoGABc7mp7XYHynuPZxChjWNJZIq+A73gm0ASDv6At7F8Vi9r0xUlQe/v0AQS3yc
    N8QlyR4XMbzMLYk3yjxFDXo4ZKQtOGzLGteCU2srANiLv26/imXA8FVidZftTAtL
    viWQZBVPTeYIA69ATUYPEq0a5u5wjGyUOij9OWyuy01mbPkCQQDluYoNpPOekQ0Z
    WrPgJ5rxc8f6zG37ZVoDBiexqtVShIF5W3xYuWhW5kYb0hliYfkq15cS7t9m95h3
    1QJf/xI/AkEA1v9l/WN1a1N3rOK4VGoCokx7kR2SyTMSbZgF9IWJNOugR/WZw7HT
    njipO3c9dy1Ms9pUKwUF46d7049ck8HwdQJARgrSKuLWXMyBH+/l1Dx/I4tXuAJI
    rlPyo+VmiOc7b5NzHptkSHEPfR9s1OK0VqjknclqCJ3Ig86OMEtEFBzjZQJBAKYz
    470hcPkaGk7tKYAgP48FvxRsnzeooptURW5E+M+PQ2W9iDPPOX9739+Xi02hGEWF
    B0IGbQoTRFdE4VVcPK0CQQCeS84lODlC0Y2BZv2JxW3Osv/WkUQ4dslfAQl1T303
    7uwwr7XTroMv8dIFQIPreoPhRKmd/SbJzbiKfS/4QDhU
    -----END RSA PRIVATE KEY-----""")

# Initializing keys in a global context
cryptography_private_key = serialization.load_pem_private_key(
    pk_key,
    password=None,
    backend=default_backend())

# Instantiate a signer object using PKCS 1v 15, this is not recommended but required for Amazon
def sign_with_cryptography(message):
    signer = cryptography_private_key.signer(
        padding.PKCS1v15(),
        hashes.SHA1())

    signer.update(message)
    return signer.finalize()

# Initializing the key in a global context
rsa_private_key = rsa.PrivateKey.load_pkcs1(pk_key)

def sign_with_rsa(message):
    signature = rsa.sign(str(message), rsa_private_key, 'SHA-1')

    return signature

# All this information comes from the Boto tests.
url = "http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes"
expected_url = "http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes&Expires=1258237200&Signature=Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_&Key-Pair-Id=PK123456789754"
message = "PK123456789754"
expire_time = 1258237200

class CryptographyDistribution(Distribution):
    def _sign_string(
            self,
            message,
            private_key_file=None,
            private_key_string=None):
        return sign_with_cryptography(message)

class RSADistribution(Distribution):
    def _sign_string(
            self,
            message,
            private_key_file=None,
            private_key_string=None):
        return sign_with_rsa(message)

cryptography_distribution = CryptographyDistribution()
rsa_distribution = RSADistribution()

cryptography_url = cryptography_distribution.create_signed_url(
    url,
    message,
    expire_time)

rsa_url = rsa_distribution.create_signed_url(
    url,
    message,
    expire_time)

assert cryptography_url == rsa_url == expected_url, "URLs do not match"

rawDescription: How to cope with the performance of generating signed URLs for accessing private content via CloudFront?

description: Cope with the performance of generating signed URLs for accessing private content via CloudFront


code:
import pandas as pd
df = pd.DataFrame([[0,0],[1,1],[2,1]])
df1 = pd.DataFrame([['A', 'B', 'C'],['D', 'E', 'F']])

df2 = df1.reset_index(drop=False)
#    index  0  1  2
# 0      0  A  B  C
# 1      1  D  E  F

df3 = pd.melt(df2, id_vars=['index'])
#    index variable value
# 0      0        0     A
# 1      1        0     D
# 2      0        1     B
# 3      1        1     E
# 4      0        2     C
# 5      1        2     F

result = pd.merge(df, df3, left_on=[0,1], right_on=['variable', 'index'])
result = result[[0, 1, 'value']]
print(result)

rawDescription: Pandas: set the value of a column in a row to be the value stored in a different df at the index of its other rows


code:
def fill(matrix, x, y, color1, color2):
    def fill(matrix, x, y, color1, color2):

        matWidth = len(matrix)
        matHeight = len(matrix[0])
        if x < 0 or y < 0 or x >= matWidth or y >= matHeight:
            return

        if matrix[x][y] == color2 or matrix[x][y] != color1:
            return
        if matrix[x][y] == color1:
            matrix[x][y] = color2

        fill(matrix, x - 1, y, color1, color2)
        fill(matrix, x + 1, y, color1, color2)
        fill(matrix, x, y - 1, color1, color2)
        fill(matrix, x, y + 1, color1, color2)
    fill(matrix, x, y, color1, color2)
    return matrix

rawDescription: Need help to modify flood fill algorithm


code: print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='')

rawDescription: Python : correct use of set_completion_display_matches_hook


code: sum(ord(character) - 96 for character in name.lower() if character != " ")

rawDescription: Numerical value of a name

description: Numerical value of a name


code:
def with_for_loop(qX, trainX, k):
    def distance(p1,p2):
        sum_of_squares = sum([(p1[i] - p2[i])**2.0 for i in range(len(p1))])
        return np.sqrt(sum_of_squares)

    k_nearest_neighbors = [np.array(sorted([(distance(qX[i],trainX[j]),trainX[j][-1])
                                            for j in range(len(trainX))],key=lambda t: t[0]))[:k]
                           for i in range(len(qX))]
    return [np.average([j[1] for j in i])
            for i in k_nearest_neighbors]

def with_broadcasting(qX, trainX, k):
    D = np.sum((qX[:, None, :] - trainX[None, :, :2]) ** 2, -1)
    ind = np.argpartition(D, k, axis=1)[:, :k]
    return trainX[ind, 2].mean(1)

# Test the results:
np.random.seed(0)
trainX = np.random.rand(100, 3)
qX = np.random.rand(50, 2)

np.allclose(with_for_loop(qX, trainX, 4),
            with_broadcasting(qX, trainX, 4))
# True

rawDescription: Calculating distance between a set of points using np matrix calculations


code:
s1 = [f for f in filenames if 0 < int(f[5:9]) <= 800]
s2 = [f for f in filenames if 800 < int(f[5:9]) <= 1600]
s3 = [f for f in filenames if 1600 < int(f[5:9]) <= 2400]

rawDescription: globbing a range with padded 0's- python

description: Globbing a range with padded 0's- python


code:
networks = sns.load_dataset("brain_networks", index_col=0, header=[0, 1, 2])
network_labels = networks.columns.get_level_values("network")
network_pal = sns.cubehelix_palette(network_labels.unique().size,
                                    light=.9, dark=.1, reverse=True,
                                    start=1, rot=-2)
network_lut = dict(zip(map(str, network_labels.unique()), network_pal))

network_colors = pd.Series(network_labels).map(network_lut)

rawDescription: How to express classes on the axis of a heatmap in Seaborn

description: Express classes on the axis of a heatmap in Seaborn


code:
first_val = split_data[0]
second_val = split_data[1]

rawDescription: Receive multiple values via pyserial and display in Python GUI


code:
from __future__ import division
def spreadout(X, Y):
    ratio = len(X) / len(Y)
    result = []
    while X or Y:
        if not Y or len(X)/len(Y) >= ratio:
            result.append(X.pop())
        else:
            result.append(Y.pop())
    return result

rawDescription: Python - "properly" organise (spread out) x and y data


code:
m = re.search("The weather is (\d+) degrees with a humidity of (\d+)%", str)
matched = m.groups()

rawDescription: How to use regex to reference specific parts?

description: Use regex to reference specific parts


code:
fo_as_string = fo.read()
lines = fo_as_string.splitlines()

rawDescription: How to modify file contents as string whilst having access to methods effecting lines within string?

description: Modify file contents as string whilst having access to methods effecting lines within string


code:
my_dic = {'colour': ['foo', 'bar'], 'number': [42, 81]}
for value in my_dic.values():
    del value[:]
my_dic

rawDescription: clearing a dictionary but keeping the keys

description: Clearing a dictionary but keeping the keys