code:
import numpy as np
import cv2
import Tkinter as tk
import Image, ImageTk

#Set up GUI
window = tk.Tk()  #Makes main window
window.wm_title("Digital Microscope")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=500)
imageFrame.grid(row=0, column=0, padx=10, pady=2)

#Capture video frames
lmain = tk.Label(imageFrame)
lmain.grid(row=0, column=0)
cap = cv2.VideoCapture(0)
def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

#Slider window (slider controls stage position)
sliderFrame = tk.Frame(window, width=600, height=100)
sliderFrame.grid(row = 600, column=0, padx=10, pady=2)

show_frame()  #Display 2
window.mainloop()  #Starts GUI

rawDescription: Using OpenCV with Tkinter

description: Using OpenCV with Tkinter


code:
magic_reverse_mapping = {}

class MagicRegister(type):
   def __new__(meta, name, bases, dict):
      cls = type.__new__(meta, name, bases, dict)
      magic_reverse_mapping[dict['_internal_attribute']] = cls
      return cls

class A(object):
    __metaclass__ = MagicRegister
    _internal_attribute = 'A attribute'

afoo = magic_reverse_mapping['A attribute']()

rawDescription: Reverse mapping class attributes to classes in Python


rawDescription: Regex - matching numbers between hyphens


code:
class SocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        logging.info('WebSocket opened')
        clients.append(self)

    def on_close(self):
        logging.info('WebSocket closed')
        clients.remove(self)

rawDescription: Easiest way to push RabbitMQ events to browser using WebSockets in Python?


code:
from myapp.views import grid_handler, grid_config
...
url(r'^examplegrid/$', grid_handler, name='grid_handler'),
url(r'^examplegrid/cfg/$', grid_config, name='grid_config'),

rawDescription: does anyone have any examples of using jqGrid with twisted / python

description: Does anyone have any examples of using jqGrid with twisted / python


code:
def selectivelyCopy(inputFile,outputFile,predicate):
    linesCopied = 0
    for line in inputFile:
        if predicate(line): # test each line with the predicate function
            outputFile.write(line)
            linesCopied+=1
    inputFile.close()
    return linesCopied

rawDescription: selectively copying from an input file

description: Selectively copying from an input file


code:
class G:
    def __dir__(self):
            return ['c','b','a']

dir(G())

rawDescription: Implementing `__dir__` in Python: Does it need to return a list and does the list need to be sorted?


code:
dimensions=[15,25]
length=50
count=120000
type1_content=0.001

rawDescription: Time-efficient way for creation of many random stick coordinates with numpy


code: [(i, dict((k[1], n) for n, k in enumerate(j, 1))) for i, j in grouped]

rawDescription: How can I split a 2D array into an array with unique values and a dictionary?

description: Split a 2D array into an array with unique values and a dictionary


code:
for user in users:
    profiles = [profile for profile in user.profile.all()]

rawDescription: Using Django ORM to get a related model in a method


code: dictionary_map = {'foo': (Bar, 'some_method'), 'foo2': (Bar2, 'some_method')}

rawDescription: How to create dictionary mapping keys to class methods and initialize this object in the same time

description: Create dictionary mapping keys to class methods and initialize this object in the same time


code:
from subprocess import check_call

with open('/tmp/so_insert_report20150804.txt') as fd:
    for line in fd:
        c1, c2, c3, c4 = line.strip().split('|')
        check_call(['prosql', '-n', '/psd_apps/700p6/cus/so_insert.enq', c1, c3])

rawDescription: python, loop through a pipe delimited text file and run an sql

description: Python, loop through a pipe delimited text file and run an sql


code:
timestamp = form.cleaned_data['timestamp'] # get timestamp from form,
messages = Message.objects.filter(timestamp__gt=timestamp) # return only messages newer than timestamp

rawDescription: Ajax returning only new message

description: Ajax returning only new message


code:
from collections import namedtuple

TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))

rawDescription: Output object attributes and values in alphabetical order


code:
def findPeople(people, filter):
    ret = {}
    for k, v in people.items():
        if filter(v):
            ret[k] = v
    return ret

rawDescription: Searching 2 dimensional dictionary

description: Searching 2 dimensional dictionary


code: sqeuclidean = lambda x: np.inner(x, x)

rawDescription: NumPy calculate square of norm 2 of vector


rawDescription: Plone: How to change ownership of an archetype content?


rawDescription: Converting Python (PyKinect) Skeleton data to Points (X,Y)


rawDescription: Fastest way to substitute a set of characters in a string


rawDescription: Suppressing the output in libsvm (python)


code:
['Like',
 'Hate',
 'Like Big',
 'Like Medium',
 'Like Small',
 'Like Big Trucks',
 'Like Big Cars',
 'Like Medium Trucks',
 'Like Medium Cars',
 'Like Small Trucks',
 'Like Small Cars',
 'Hate Big',
 'Hate Medium',
 'Hate Small',
 'Hate Big Trucks',
 'Hate Big Cars',
 'Hate Medium Trucks',
 'Hate Medium Cars',
 'Hate Small Trucks',
 'Hate Small Cars',
 'Big Trucks',
 'Big Cars',
 'Medium Trucks',
 'Medium Cars',
 'Small Trucks',
 'Small Cars',
 'Trucks',
 'Cars']

rawDescription: Get combinations of words lists

description: Get combinations of words lists


code:
foo = Foo()
foo.bar
foo.baz  # foo.baz is called and returns max(foo.bar)
foo.bar.append(7)  # foo.baz is not called
foo.baz  # foo.baz is called and returns max(foo.bar)

rawDescription: Set Python class variable equal to the output of class function


code:
def calc(ImageDim, StadionDim, Point):
    return (Point[0] * StadionDim[0]/ImageDim[0], Point[1] * StadionDim[1]/ImageDim[1])

rawDescription: Real distance between two points over image


rawDescription: An elegant way to make a 2d array with all possible columns


code:
import operator, itertools
dict((key, sum(itertools.imap(operator.itemgetter(key), dictList)))
      for key in dictList[0])

rawDescription: How to create single Python dict from a list of dicts by summing values with common keys?

description: Create single Python dict from a list of dicts by summing values with common keys


code:
r = csv.reader(open('/tmp/test.csv')) # Here your csv file
lines = [l for l in r]

rawDescription: Change specific value in CSV file via Python


code: np.count_nonzero(simfourty48[0] > 350)

rawDescription: How do I get a count of values in an array, in a range or above a threshold value?

description: Get a count of values in an array, in a range or above a threshold value


code: {fname: coords_t(*data.replace('\n', ' ').split(' ')[:-1])}

rawDescription: Python reading text files for calculation


code:
stages = [True, False]

while True:
    process(Cursor, movie, music, stages)

    Effects.List.draw(screen)
    pygame.display.flip()

rawDescription: Not sure why key press is not doing anything


code:
from __future__ import absolute_import
from pep8 import *
MAX_LINE_LENGTH = 119

rawDescription: Elegant/proper way to wrap a python module


rawDescription: Extract Values from CSV file to then multiply with values from other CSV? Python


code:
class ResultsHandler(webapp.RequestHandler):
    def post(self):
        k = db.Key.from_path('Engineer', the_engineer_id) #will be an integer
        e = db.get(k)
        output = {'salary': e.salary}
        output = json.dumps(output) #json encoding
        self.response.write.out(output)

rawDescription: jquery.ajax post request to get data from app engine server

description: Jquery.ajax post request to get data from app engine server


code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(description='Sub description')
checkout = subparsers.add_parser('checkout', description='Checkout description')
checkout.add_argument('foo', help='This is the foo help')
parser.parse_args(['checkout', '--help'])

rawDescription: gem/git-style command line arguments in Python

description: Gem/git-style command line arguments in Python


code: first_3_reviews = Review.objects.filter(movie= movie)[:3]

rawDescription: How do you loop through a Django queryset in an html file?

description: Loop through a Django queryset in an html file


code:
class Foo:
    def loadings():
        load = dict(hi=1)
        if 'hi' in load:
            print(load['hi'])
            print({e:load[e] for e in load})
        return load
    loadings = loadings()

print(Foo.loadings)

rawDescription: Python scoping issue with dictionary comprehension inside class level code


code:
headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
    headers.setdefault( headername, defaultvalue )

rawDescription: Use cases for the 'setdefault' dict method


code: df['RA_wnd_4'] = pd.rolling_mean(df.price, 4, 1)

rawDescription: Python and Pandas - column that "count direction" and show "avarage until now"


code: data1 = data.astype('U24,i,f') # convert bytestring field to unicode

rawDescription: Numpy recarray writes byte literals tags to my csv file?


code:
class ContributionAdmin(admin.ModelAdmin):

    list_display = ('id','nlcc','subscriber','application_number',
                    'date','receipt_number','amount', 'status')

    def application_number(self, obj):
        return obj.subscriber.application_number
    application_number.short_description = "Subscriber's Application Number"

rawDescription: Django admin site : Help needed

description: Django admin site : Help needed


code:
cmap = plt.get_cmap('jet')
norm = mcolors.Normalize(vmin=Z.min(), vmax=Z.max())
plot = ax.plot_surface(
    X, Y, Z, rstride=1, cstride=1,
    facecolors=cmap(norm(Z)),
    linewidth=0, antialiased=False, alpha=0.5)

rawDescription: Spherical coordinates plot in matplotlib


code:
class Test1(TestBase):
    MYPARAMETER = 1
    def setUp(self):
        TestBase.setUp(self)
        # etc

class Test2(TestBase):
    MYPARAMETER = 17
    def setUp(self):
        TestBase.setUp(self)
        # etc

rawDescription: Customizable setUp for every test in a test class


code: out = np.where(((Z == S[:,None,None,:]).all(3)).any(0))

rawDescription: Find indices of specific rows in a 3d numpy array


code:
with open('infilename', 'r') as infile, open('outfilename', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        # strip all 0's from the front
        stripped_value = re.sub(r'^0+', '', row[5])
        # pad zeros on the left to smaller numbers to make them 4 digits
        row[5] = '%04d'%int(stripped_value)
        writer.writerow(row)

rawDescription: stripping the zeros in csv with python

description: Stripping the zeros in csv with python


code:
import  numpy as np
from operator import itemgetter
import csv
with open(filename) as f:
   from itertools import islice,imap
   r = csv.reader(f)
   np.genfromtxt(imap(itemgetter(1),islice(r,  start, end+1)))

rawDescription: load a certain number of rows from csv with numpy

description: Load a certain number of rows from csv with numpy


rawDescription: How to column stack arrays ignoring nan in Python?

description: Column stack arrays ignoring nan in Python


code:
sols = solve(sin(z) - 2, z)
sols
[i.rewrite(log) for i in sols]

rawDescription: How to solve sin(z)=2 in Sympy?

description: Solve sin(z)=2 in Sympy


code: [{'SnapshotId': s['SnapshotId'], 'StartTime':s['StartTime']}  for s in data['Snapshots']]

rawDescription: Query 2 keys from Python dict

description: Query 2 keys from Python dict


rawDescription: how to loop through list multiple times in Python

description: Loop through list multiple times in Python


rawDescription: Sorting Counter collection in python with secondary term (tie breaker)


code:
class myStruct():
    def __init__(self,s,a=1,b=1): ##Here you've set the default a and b values to 1
        self.a=a
        self.b=b
        self.s=s

rawDescription: Python multiprocessing: avoid communication via module between processes


code:
foo = Foo.new(...)   # make a new Foo
bar = foo.to_bar     # convert it to a Bar

rawDescription: Function name convention for "convert foo to bar"


code:
np.float_([1,2])
np.double is np.float_
np.complex_([1,2])
np.float32([1,2])
np.complex192([1,2])

rawDescription: Why numpy.double applies to a nested list and numpy.complex doesn't?


code:
...

D3 = {}
for k,v in D2.items():
    D3.setdefault(v, {}).update({k: D1[k]})  # equivalent

rawDescription: Restructuring Nested Dictionaries Python


rawDescription: Why am I not getting the the result of sorted function in expected order ?


code:
import django.contrib.admin.widgets
from django.utils.safestring import mark_safe

class NoAddingRelatedFieldWidgetWrapper(django.contrib.admin.widgets.RelatedFieldWidgetWrapper):

    def render(self, name, value, *args, **kwargs):
        from django.contrib.admin.views.main import TO_FIELD_VAR
        rel_to = self.rel.to
        info = (rel_to._meta.app_label, rel_to._meta.model_name)
        self.widget.choices = self.choices
        output = [self.widget.render(name, value, *args, **kwargs)]
        '''
        if self.can_add_related:
            related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name)
            url_params = '?%s=%s' % (TO_FIELD_VAR, self.rel.get_related_field().name)
            # TODO: "add_id_" is hard-coded here. This should instead use the
            # correct API to determine the ID dynamically.
            output.append(' '
                          % (related_url, url_params, name))
            output.append(''
                          % (static('admin/img/icon_addlink.gif'), _('Add Another')))
        '''
        return mark_safe(''.join(output))

# Monkeypatch
django.contrib.admin.widgets.RelatedFieldWidgetWrapper = NoAddingRelatedFieldWidgetWrapper

rawDescription: Django 1.7 removing Add button from inline form


code:
t=sorted(chain(*s))
t

rawDescription: Reorganise list in list python

description: Reorganise list in list python


code: b = zip(*(col for col in zip(*a) if col[0] == 2))

rawDescription: Create new list based on values taken from sublist


code:
import re
s = "http://whatever.org/?title=@Title@&note=@Note@"
re.sub(r"@(\w+?)@", r"{\1}", s)

rawDescription: Replacing "tokens" in Python string with alternate values


code:
cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)
# Compute set of abstract method names
abstracts = set(name
             for name, value in namespace.items()
             if getattr(value, "__isabstractmethod__", False))
for base in bases:
    for name in getattr(base, "__abstractmethods__", set()):
        value = getattr(cls, name, None)
        if getattr(value, "__isabstractmethod__", False):
            abstracts.add(name)
cls.__abstractmethods__ = frozenset(abstracts)

rawDescription: Actual difference in implementing/overriding using @abstractproperty and @abstractmethod


code:
with open('longWordList.txt') as fd:
    print('Suffixes: ')
    mx, mn = max(sfx_dict, key=len), min(sfx_dict, key=len)
    for ln in map(str.rstrip, fd):
        suf = ln[-mx:]
        for i in range(mx-1, mn-1, -1):
            if suf in sfx_dict:
                sfx_dict[suf] += 1
            suf = suf[-i:]
    for k,v in sfx_dict:
        print("Suffix = {} Count =  {}".format(k,v))

rawDescription: count suffixes appearing in the word file

description: Count suffixes appearing in the word file


code:
import io

with io.open('filename', encoding='utf-8') as file:
    text = file.read()

rawDescription: Unicode Characters in Twitter (Python)

description: Unicode Characters in Twitter (Python)


code:
import collections
test = collections.namedtuple('test', ['a', 'next'])

rawDescription: C struct python equivalent

description: C struct python equivalent


code:
for child in get_buttons_hbox(a).get_children():
    label = child.get_label()
    if label == 'gtk-apply':
        child.set_label('Start')

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

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


code:
from scipy.interpolate import interp2d
import numpy as np

x = 50
y = 150

a = np.random.uniform(0,10,(y, x))
b = interp2d(np.arange(x), np.arange(y), a)

rawDescription: Array from interpolated plot in python

description: Array from interpolated plot in python


code: hash

rawDescription: How does the dictionary add keys in python?


code:
def printer(event):
    print(event.x, event.y)
canvas.bind("<Button-1>", printer)

rawDescription: Simplest code to import a .gif

description: Simplest code to import a .gif


code:
class FlashCard:
    def __init__(self):
        self.commands = {'addQuestion':self.addQuestion}

    def addQuestion(self, phrase):
        answer = raw_input(phrase)

    def interpret(self, expressions):
        for expression in expressions.split('\n'):
            phrase, command = expression.rsplit(' ', 1)
            if command in self.commands:
                operator = self.commands[command]
                operator(phrase)
            else:
                raise RuntimeError('Invalid command')

expressions = '''testing this addQuestion
testing that addQuestion
testing error removeQuestion'''
i = FlashCard()
i.interpret(expressions)

rawDescription: Adding a string with spaces to a stack

description: Adding a string with spaces to a stack


code: something.action = tmp

rawDescription: Is there any way you can get back to the original function?


code:
def coalesce(*args):
   for a in args:
      if a is not None:
          return a

rawDescription: Efficiently select the best string from keys in a dict


code:
def example():
    pass

x = example # x is now a reference to the example
            # method. no invocation takes place
            # but later the method can be called as
            # x()

rawDescription: How to port a Python program to Ruby

description: Port a Python program to Ruby


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

data = np.array([1,3,70,924,3])

plt.bar(np.arange(data.size), data, clip_on=False)
plt.ylim([0, 300])

plt.show()

rawDescription: matplotlib - Allow bar to extend beyond chart limits?

description: Matplotlib - Allow bar to extend beyond chart limits


code:
import json

with open('scores.json', 'a') as f:
    try:
        scores = json.load(f)
    except ValueError:
        scores = {}
        # add user if not already in the dict with a list as a value
        scores.setdefault(name,[])
         # just append the latest score making sure when you have three to relace the last
        scores[name].append(whatever)
 #   do your logic replacing last score for each name or adding names

    with open('scores.json', 'w') as f:
       json.dump(scores,f)

rawDescription: Python: Only saving three latest scores

description: Python: Only saving three latest scores


code:
from collections import defaultdict
d = defaultdict(list)
for node in my_list:
    d[node['delim_type']].append(node['arcana_list'])

rawDescription: Reduce a list of 2-dicts, to a list unique by the one item, concatenating the other items in python3


code: a, b, *c = someseq

rawDescription: Multiple Unpacking Assignment in Python when you don't know the sequence length


code:
df = pd.DataFrame({'A': range(10), 'B': range(10), 'C': range(10)})
df[['A', 'B']].sum(axis=1)  # row sums

rawDescription: R with function in python

description: R with function in python


code:
orig =   (1.1,2.)
target = (1.1,7.)
shrinkA = 0.1 # given in points
shrinkB = 0.1
b = patches.ConnectionStyle('Arc')
path = b.connect( orig, target )
path = b._shrink( path, shrinkA, shrinkB )

rawDescription: How to get the exact shrink value when customizing arrow styles in annotate

description: Get the exact shrink value when customizing arrow styles in annotate


code:
def mytext(self):
        cursor = self.ui.editor_window.textCursor()
        textSelected = cursor.selectedText()
        s = textSelected.upper()
        self.ui.editor_window.append(s)

rawDescription: Select text of textEdit object with QTextCursor, QTextEdit


rawDescription: Numpy-y way to build a polynomial array from set of points


code:
[{'block1': {'othervalue': 32423432,
             'some_value': ['some', 'other', 'kind', 'of', 'data'],
             'value': 'data'},
  'block2': {'othervalue': 32423432,
             'some_value': ['some', 'other', 'kind', 'of', 'data'],
             'value': 'data'}}]

rawDescription: What's the best way(error proof / foolproof) to parse a file using python with following format?


code:
from datetime import datetime,timedelta
def main():
    time_Amount = timedelta( seconds = int(input('Enter time in seconds: ')))

    while (time_Amount == timedelta(seconds = 0)):
        time_Amount = timedelta( seconds = int(input("Enter a non-zero amount of seconds: ")))

    calc_time = datetime(1,1,1) + time_Amount
    print("--------Break Down--------")
    print("%d day(s), %d hour(s), %d minute(s), %d second(s)" %
          (calc_time.day-1, calc_time.hour, calc_time.minute, calc_time.second))

rawDescription: Variables not receiving amounts? Python

description: Variables not receiving amounts? Python


code: v = vec[:]

rawDescription: Having problems with python's random.shuffle


code:
for post in posts:
    ... # rest of code snippet you posted

print(sum(float(re.sub(r"[^\d.]", "", post.text)) for post in posts))

rawDescription: How to add up scraped strings representing integers?

description: Add up scraped strings representing integers


code:
#define FOO_A 0x3
#define FOO_B 0x5

rawDescription: How can I reference #defines in a C file from python?

description: Reference #defines in a C file from python


code:
import re
s = """"Matt"
{
    "Location"    "New York"
    "Age"         "22"
    "Items"
    {
        "Banana"    "2"
        "Apple"     "5"
        "Cat"       "1"
    }
}"""

# Put a colon after the first string in every line
s1 = re.sub(r'^\s*(".+?")', r'\1:', s, flags=re.MULTILINE)
# add a comma if the last non-whitespace character in a line is " or }
s2 = re.sub(r'(["}])\s*$', r'\1,', s1, flags=re.MULTILINE)

rawDescription: Parse Key Value Pairs in Python

description: Parse Key Value Pairs in Python


code:
def transpose(matrix):
    return [[matrix[j][i] for j, column in enumerate(row)] for i, row in enumerate(matrix)]

with open("Input.txt") as in_file:
    matrix = [[int(num) for num in line.split()] for line in in_file]

[sum(row) for row in transpose(matrix)]

rawDescription: ColSum of matrix from file python

description: ColSum of matrix from file python


code:
from scipy.sparse.linalg import lsqr
return_values = lsqr(A, b)
x = return_values[0]

rawDescription: Solve seemingly (but not actually!) overdetermined sparse linear system in Python


code:
vector_A = scipy.randn(4)
vector_B = scipy.zeros(4)
vector_A
vector_B
vector_C = vector_A > vector_B
vector_C
vector_C.sum()
vector_C.mean()
3 - vector_C

rawDescription: numpy.array boolean to binary?

description: Numpy.array boolean to binary


code:
pd.MultiIndex.from_product([pd.date_range(df['date'].min(), df['date'].max(), freq='D'),
                            df['colour'].unique()])

rawDescription: Re-index dataframe by new range of dates


code: coeffs[-k]

rawDescription: Energy for 1-D wavelet in Python

description: Energy for 1-D wavelet in Python


code:
def foo():
    funcstr=textwrap.dedent('''\
        def func(x, {p}):
            return x * 2*a + 4*b - 5*c
        ''')

rawDescription: Dynamically define a function

description: Dynamically define a function


code:
def split(row):
    character, positions = row
    return character == " "

def merge(group):
    letters, position_groups = zip(*group)
    return "".join(letters), next(iter(position_groups))

def group(value):
    return [merge(group) for isspace, group in
            itertools.groupby(value, key=split) if not isspace]

print({key: group(value) for key, value in old.items()})

rawDescription: Python dictionary merge values and delete previous


code: my_variable = copy.deepcopy(self.myinstance) # Deep copy

rawDescription: Python: How to I unbind a variable from instance in a class?


code:
def foo(a):
    a += 10

a = numpy.arange(10)
a
foo(a)
a

rawDescription: Numpy modify array in place?

description: Numpy modify array in place


code: rows = zip(list1, list2, list3, list4)

rawDescription: ForLoop Iterations as List Index in Django Template


code: from myproject import db

rawDescription: In Flask-SQLAlchemy, where do I initialise and store the database object?


code:
import foo

foo.Bar = superClassCreator()

rawDescription: python how to register dynamic class in module

description: Python how to register dynamic class in module


code:
import csv
import StringIO
results = "sku\tdelivered-price-gbp\tdelivered-price-euro\tid\n32850238\t15.53\t35.38\t258505\n"

data = list(csv.DictReader(StringIO.StringIO(results), delimiter='\t'))
print(data)

rawDescription: Building a dictionary from a tab delimited file in a pythonic way


code:
from pprint import pprint

from bs4 import BeautifulSoup

data = """

Title 1

Description 1

            stuff

 [ Right-click to download]

Title 2

Description 2

            stuff

 [ Right-click to download]

"""

soup = BeautifulSoup(data, "html.parser")

tracks = soup.find_all('div', {'class':"audioBoxWrap clearBoth"})
result = {
    "podcasts": [
        {
            "title": track.h3.get_text(strip=True),
            "description": track.p.get_text(strip=True),
            "link": track.a["href"]
        }
        for track in tracks
    ]
}
pprint(result)

rawDescription: BeautifulSoup scraping information from multiple divs using loops into JSON


code:
hasattr(zip_instance, 'send')
hasattr(zip_instance, 'throw')
hasattr(zip_instance, 'close')

rawDescription: Looking a instance's class hierarchy in Python


code:
memfile = StringIO.StringIO()
memfile.write(json.loads(serialized).encode('latin-1'))
memfile.seek(0)
a = numpy.load(memfile)

rawDescription: How can I serialize a numpy array while preserving matrix dimensions?

description: Serialize a numpy array while preserving matrix dimensions


code:
class y(object):
  def __init__(self, astring):
    self.s = astring
  @classmethod
  def fromlist(cls, alist):
    x = cls('')
    x.s = ','.join(str(s) for s in alist)
    return x
  def __repr__(self):
    return 'y(%r)' % self.s
y1 = y('xx')
y1
y2 = y.fromlist(range(3))
y2

rawDescription: What does classmethod do in this code?

description: What does classmethod do in this code


code:
def nearest_neighbors_sorted(x, y) :
    x, y = map(np.asarray, (x, y))
    y_idx = np.argsort(y)
    y = y[y_idx]
    nearest_neighbor = np.empty((len(x),), dtype=np.intp)
    for j, xj in enumerate(x) :
        idx = np.searchsorted(y, xj)
        if idx == len(y) or idx != 0 and y[idx] - xj > xj - y[idx-1] :
            idx -= 1
        nearest_neighbor[j] = y_idx[idx]
        y = np.delete(y, idx)
        y_idx = np.delete(y_idx, idx)
    return nearest_neighbor

rawDescription: finding nearest items across two lists/arrays in Python

description: Finding nearest items across two lists/arrays in Python


code:
import re
import base64

data = """
if (X1079) { clearTimeout (X1079); X1079 = null; }
X781 ('<FORM name="X58" method="POST" action="http://us23.chatzy.com/31039888252154">
<INPUT type="hidden" name="X1" value="218">

<INPUT type="hidden" name="X579" value="1">

<INPUT type="hidden" name="X691" value="MzEwMzk4ODgyNTIxNTQmMzEwMzk4ODgyNTIxNTQmMCZYMTY4JjE0MjI1NTY0MjcmVUZWS0VPUUEmYXl5JkZGRkZGRiYmMSYzJjEmdXdvb2RsZXM3Nzc2QGpvdXJyYXBpZGUuY29tJjd6c3AwJjE0MjI4MDM4NDMmJjAm">
</FORM>');"""

# Find length of characters starting with value=" and over 50 chars long
base64str = re.search("value=\"(\w{50,})\"", data).group(1)

# Decode
s = base64.decodebytes(base64str.encode()).decode(errors="ignore")

# Find section after 5th &
out = re.search("(.+?&){5}(.+?)&", s).group(2)

print(out)

rawDescription: What is the most efficient way at extracting a string out of a string?


code: a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i-1][1]]

rawDescription: How to select increasing elements of a list of tuples?

description: Select increasing elements of a list of tuples


code:
tf = tempfile.NamedTemporaryFile()
tf.name
tf = tempfile.NamedTemporaryFile()
tf.name

rawDescription: Best way to generate random file names in Python

description: Generate random file names in Python


rawDescription: Assigning a condition to a variable in Python


code:
data = MyContainerClass([1, 2, 3, 4, 5, 6, 7])
data[:5]
type(data[:5])
data.my_method()
data[:3].my_method()

rawDescription: Python: Is is possible to have a class method that acts on a slice of the class?


code:
result = []
for keyword in keywords.split(' '):
    result += list(Table.objects.filter(name__icontains=keyword))

rawDescription: Django query with contains and keywords

description: Django query with contains and keywords


code: result = pd.concat([sd, pos_count], axis=1); result

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code: AR = AR[~AR.PNR.isin(bad_values)]

rawDescription: Automating this: Finding and deleting rows in several dataframes


code:
def triple(x):
   return x * 3

def square(x):
   return x * x

def triple_square(x):
   return triple(square(x))

def triple_plus_square(x):
    return triple(x) + square(x)

def triple_plus_square_with_explaining_variables(x):
    tripled = triple(x)
    squared = square(x)
    return tripled + squared

rawDescription: Adding lambda functions with the same operator in python


rawDescription: Eclipse IDE: How to add this configuration during running?


code:
expected_element = 3
my_list = [...]
result_list = []
for i in range(len(my_list)):
    if my_list[i] == expected_element:
        result_list.append(i)

rawDescription: Python - finding value position in a list and outputting as a new list


code:
#!/usr/bin/python
import os
if __name__ == '__main__':
    os.chdir("/home/name/projects/python")
    os.system("pwd")
    os.system("/bin/bash")

rawDescription: Change directory in terminal using python


code:
g
np.kron(g, np.ones((3,3), dtype=int))

rawDescription: Rescale a numpy array

description: Rescale a numpy array


code:
def odd_even_sieve(x):
    output = x[:]
    even_index, odd_index = 0, 1
    for value in x:
        if value % 2 == 0:
            output[even_index] = value
            even_index += 2
        else:
            output[odd_index] = value
            odd_index += 2
    return output

rawDescription: Move odd and even numbers in list to odd and even positions


code: print(df.loc[idx, ['word', 'tag']])

rawDescription: python pandas, DF.groupby().agg(), column reference in agg()

description: Python pandas, DF.groupby().agg(), column reference in agg()


code: Point = collections.namedtuple('Point', 'x y')

rawDescription: storing list/tuples in sqlite database with sqlalchemy

description: Storing list/tuples in sqlite database with sqlalchemy


code: plt.hist(a, len(data1), normed=True,)

rawDescription: distribution for existing data

description: Distribution for existing data


rawDescription: Draw middle form of arabic character alone, Python PIL


code:
d = {'A':12, 'B':1, 'C':14, 'D':13, 'E':3, 'F': 4}

import itertools
for a, b, c in itertools.combinations(sorted(d, key=d.get), 3):
    if d[a] + d[b] == d[c]:
        print(a,b,c)

rawDescription: Comparing 2 values in dict to all other values


code:
class StudentAdmin(admin.ModelAdmin):

    @property
    def media(self):
        media = super(ProductAdmin, self).media
        css = {
            "all": (
                "css/your.css",
            )
        }
        media.add_css(css)
        return media

rawDescription: Changing entire background color of table cell in Django Admin


code: [replace_random('x x x x x', r'\bx\b', 'y') for _ in range(10)]

rawDescription: Replace a random instance of a substring in a string


rawDescription: Local and global variables in python functions


rawDescription: Pandas DataFrame get column combined max values


code:
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', help='Do A', action='store_true')
group.add_argument('-b', help='Do B', action='store_true')
args = parser.parse_args()
if args.a:
    print('A!')
if args.b:
    print('B!')

rawDescription: Using Python3 and the argparse module, can I disallow an argument if a different one was passed?


code:
from inplace import inplace

with inplace(inputfilename) as (ifh, ofh):
    for line in ifh:
        if line.startswith('for(') and line.endswith(';'):
            line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)
        ofh.write(line)

rawDescription: How do I check for next to next line while reading a file in python and strip the newline character at its end?

description: Check for next to next line while reading a file in python and strip the newline character at its end


rawDescription: python enumeration class for ORM purposes

description: Python enumeration class for ORM purposes


code:
class Variables:
    def __init__(self):
        self.value = 25
        self.unit = "m/s"

rawDescription: Is it possible to add an attribute to a variable in python?


code:
for d in dicts:
    score = d['Score']
    d['Score'] = score[0]/score[1] if score[1] != 0 else 0
    #d['Score'] = '{}/{}'.format(score[0], score[1]) if score[1] != 0 else '0'

rawDescription: How to read lines of dictionary and write to a CSV file

description: Read lines of dictionary and write to a CSV file


code: (df['Open'].diff() > 0).head()

rawDescription: New colum in pandas, based on another colums last value


code:
from twisted.internet.protocol import Protocol
class MyProtocol(Protocol):
    buffer = b""
    def dataReceived(self, data):
        messages, self.buffer = Message.parseStream(self.buffer + data)
        for message in messages:
            self.messageReceived(message)
    def messageReceived(self, message):
        "do something useful with a message"

rawDescription: Twisted protocol to handle concantenated TCP stream with custom frame structure?


code: col={i.lower() for i in col}

rawDescription: Searching for Phrase Keywords in MySQL

description: Searching for Phrase Keywords in MySQL


code:
class Klass:
    def __init__(self):
        self.a = 1
        self.b = 2
x = Klass()
setattr(x, 'a', 3)
x.a

rawDescription: How to set a Python object's field/member by name

description: Set a Python object's field/member by name


code:
def get(id, user_id=None):

    query = """SELECT *
               FROM USERS
               WHERE text LIKE %s AND
                     id = %s
            """
    values = [search_text, id]

    if user_id is not None:
        query += ' AND user_id = %s'
        values.append(user_id)

    results = DB.get(query, values)

rawDescription: In python, changing MySQL query based on function variables


rawDescription: How to display a value in a PyQt text field using matplotlib's object picking function?

description: Display a value in a PyQt text field using matplotlib's object picking function


code:
keys = {x[:2] for x in a}
[x for x in b if x[:2] in keys]

rawDescription: Python merge two arrays on specific columns


code:
MyApp/MyApp/Template/...
MyApp/App1/...
MyApp/App2/...
MyApp/Menu/...

rawDescription: Where do I include django-admin-tools menu for my project


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

n_features = 50

feature_names = ["feature_"+str(i) for i in range(n_features)]
weights = np.random.randn(n_features)

# select top 15 high and low features
indeces = np.argsort(weights)
n_top = 15
top = np.hstack((indeces[:n_top], indeces[-n_top:]))[::-1]

vmax = np.abs(weights).max()

plt.clf()
plt.imshow(weights[top].reshape((-1,1)),interpolation='nearest', cmap="seismic", vmin=-vmax, vmax=vmax)
plt.axes().xaxis.set_visible(False)
plt.colorbar()

tick_marks = np.arange(2 * n_top)
plt.yticks(tick_marks, [feature_names[i] for i in top])

rawDescription: Heat map of features and weights

description: Heat map of features and weights


code: func(xa, *args)

rawDescription: What is the difference between the following two statements?


rawDescription: 3D-plotting nested dictionaries made up of different length arrays


code:
mapper(Note, tb_notes)
mapper(Item, tb_items, properties={
        '_notesdict': relation(Note,
             collection_class=column_mapped_collection(tb_notes.c.name)),
    })

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
def InRange(number):
    return 0 < number < 6

rawDescription: Chained comparison number range in Python


code:
# Note: untested
times_files = [(os.path.getctime(f),f) for f in glob.glob(bDir+'*.[Dd][Mm][Pp]')]
newest = max(timed_files)[1] # grab the filename back out of the "max" tuple

rawDescription: Python max() takes no keyword arguments

description: Python max() takes no keyword arguments


rawDescription: Defining a dictionary of dictionaries with vectors as inner and outer keys


code:
def get_closest_cities(self, kms):
  cities = []
  #Find surrounding Cities of a given city within a given radius
  allcities = self.country.city_set
  for city in allcities:
    distance = HaversineDistance((self.location.lat, self.location.lon),(city.location.lat, city.location.lon))
    if not distance >= kms:
      cities.append((city.name, int(distance)))
  cities.remove(cities[0])
  return cities

rawDescription: Calculate distance between cities & find surrounding cities based on GeoPT, in Python on Google App Engine


rawDescription: Python, make a list for a for loop when parsing a CSV


rawDescription: TEXT compression in python

description: TEXT compression in python


code:
from django.db.models.signals import pre_save

class Article(models.Model):
    optional_attribute = models.CharField(max_length = 250)

    @classmethod
    def pre_save_handler(cls, sender, instance, **kwargs):
        if not instance.optional_attribute:
            instance.optional_attribute = 'Default'

pre_save.connect(Article.pre_save_handler, sender=Article)

rawDescription: How can I call a clean method before get_or_create saves to the database?

description: Call a clean method before get_or_create saves to the database


code:
@web.asynchronous
@gen.coroutine
def delete(self, _id):
    try:
        model = Model()
        model.delete(_id)
        self.set_status(204)
    except Exception as e:
        logging.error(e)
        self.set_status(500)
    self.finish()
    return

rawDescription: Python Tornado: Delete request never ends


rawDescription: Python -- import a module from a directory that's not a package


code:
size = self.canvas.size()
width, height = size.width(), size.height()
im = QImage(self.canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
im.save('test.png')

rawDescription: Python - matplotlib - PyQT: Copy image to clipboard


code:
class Rectangle(object):
    def __init__(self, canvas, coords, fill, outline=None):
        self.canvas = canvas
        self.outline = outline if outline is not None else fill
        self.fill = fill
        self.canvas_id = self.canvas.create_rectangle(
            coords, outline=self.outline, fill=self.fill)

rawDescription: Can rectangle be used as a parent class (tkinter)?


rawDescription: Skip first two characters in (key=lambda) sorting


rawDescription: finding non-numeric rows in dataframe in pandas?

description: Finding non-numeric rows in dataframe in pandas


code:
a_peek = PeekIterator(a)
b_peek = PeekIterator(b)
merged = [next(a_peek) if a_peek.peek() is not None and
                          (b_peek.peek() is None or a_peek.peek() <= b_peek.peek())
          else next(b_peek)
          for _ in range(len(a) + len(b))]

rawDescription: Python: Sorted merge using list comprehension


rawDescription: Python : To list files if my keyword contains using regular expression


code: "Mary has an {1} and a {0} or {1}".format(*uarray.astype('U'))

rawDescription: Numpy String Encoding

description: Numpy String Encoding


code:
class LogFormatterExponentFixed(LogFormatter):
    """
    Format values for log axis; using ``exponent = log_base(value)``
    """

    def __call__(self, x, pos=None):
        """Return the format for tick val *x* at position *pos*"""

        vmin, vmax = self.axis.get_view_interval()
        vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
        d = abs(vmax - vmin)
        b = self._base
        if x == 0:
            return '0'
        sign = np.sign(x)
        # only label the decades
        fx = math.log(abs(x)) / math.log(b)
        isDecade = is_close_to_int(fx)
        if not isDecade and self.labelOnlyBase:
            s = ''
        elif abs(fx) > 10000:
            s = '%1.0g' % fx
        elif abs(fx) < 1:
            s = '%1.0g' % fx
        else:
            # this is the added line
            fd = math.log(abs(d)) / math.log(b)
            s = self.pprint_val(fx, fd)
        if sign == -1:
            s = '-%s' % s

        return self.fix_minus(s)

rawDescription: matplotlib LogFormatterExponent -- 'e' in the exponent labels of cbar

description: Matplotlib LogFormatterExponent -- 'e' in the exponent labels of cbar


code:
#allocate memory (np.empty would work too and be marginally faster,
#                 but probably not worth mentioning).
a=np.zeros((3000,300),dtype=np.float32)
with open(filename) as f:
    for i,line in enumerate(f):
        a[i,:]=map(np.float32,line.split())

rawDescription: Convert a string list to float32 efficiently


code:
def httpstatus(self, url, data=None, **kwargs):
    # Don't forget to mention in documentation that all
    # extra arguments are passed to urlopen as is.
    urlopen(url, data, **kwargs)

rawDescription: How to use a default in a correct way

description: Use a default in a correct way


code:
@gen.coroutine
def _request_action(self):
    """ Function that incapsulates all actions, that should be performed in request
    """
    result = yield self.motor.col1.insert({"ex1": 1})
    raise gen.Return(result)  # that is how you can return result from coroutine

rawDescription: Encapsulating asynchronous actions in functions


code:
#Lambda function to test condition
test = lambda x: len(x)>=5 and ''.join(sorted(x))==x
#Returns list of elements for which test is True
filter(test, lowers)

rawDescription: making a string into a list within a list comprehension

description: Making a string into a list within a list comprehension


code:
try:
    record = cursor.next()
except StopIteration:
    print("Empty cursor!")

rawDescription: Can I just get the first item in a Cursor object (pymongo)?

description: Just get the first item in a Cursor object (pymongo)


rawDescription: How to split a single word using split()

description: Split a single word using split()


code: print('', end = '')

rawDescription: Creating a number list with nested For loops in Python


rawDescription: Search & Substitute numbers for list from a dictionary lookup


code:
rowb, colb = B[n,:], np.copy( B[:,n] )
colb[ n ] = 0

rawDescription: NumPy Matrix Multiplication Efficiency for Matrix With Known Structure


code: sorted(words, key=lambda x: 'a'+x if x.startswith('s') else 'b'+x)

rawDescription: sorting a list in python

description: Sorting a list in python


rawDescription: Mean function given a list of graphs

description: Mean function given a list of graphs


code:
valuelist=[]
for line_str in read_file:
     for cell in line_str.split(";"):
         valuelist.append(int(cell))
print(max(valuelist))
print(min(valuelist))

rawDescription: Sorting a list from a file, outputting in another file


rawDescription: Pandas(Python) to_clipboard with comma decimal parameter


code: fnmatch.filter( glob.glob('/../../nodes/*/views/assets/js/**/*'), '*.js' )

rawDescription: search in wildcard folders recursively in python

description: Search in wildcard folders recursively in python


code:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='/path/to/executeable/chrome/driver')

rawDescription: how can I use selenium with my normal browser

description: Use selenium with my normal browser


code:
import itertools

# ...

for a, b in itertools.combinations(seq, 2):
    compare(a, b)

rawDescription: What's the most Pythonic way to make all 2-way comparisons in a sequence?


code:
from collections import Counter
binary = bin(20)[2:]
Counter(binary)

rawDescription: count number of ones in a given integer

description: Count number of ones in a given integer


code:
with open("file.txt", "r") as chat:
    data=chat.read().splitlines(True) #split lines in the list
d = str(data[:1]) #take only first line from the list
dat=str(d).strip("[]") #remove the brackets "[]" that remained when string was extracted from the list
with open("file.txt", "w") as chat1:
    chat1.writelines(data[1:]) # writes all except the first line
chat.close()
chat1.close()
self.f = open('file.txt', 'rb')
self.response = self.client.put_file(str(dat[:-2]), self.f)  #str(dat[:-2]) -> i wanted to remove the newline char "\n"

rawDescription: How can i access gtk.Entry() in my GUI script from my other script? Python

description: Access gtk.Entry() in my GUI script from my other script? Python


code:
# first extract precipitation data for later use
precipitation = [data[i][1] for i in xrange(0, rows)]

# then test the range (i, i+m)
all_dry = all([(data==0) for data in precipitation[i:i+m]])
all_wet = not any([(data==0) for data in precipitation[i:i+m]])
# of course you can also use
all_wet = all([(data>0) for data in precipitation[i:i+m]])

rawDescription: How to Calculate Dry and Wet Spell in Python?

description: Calculate Dry and Wet Spell in Python


code:
def group(sequence, group_length, padding=None):
    if padding is not None:
        sequence += [padding]*(group_length-len(sequence)%group_length)
    return [sequence[i:i+group_length] for i in range(0, len(sequence), group_length)]

rawDescription: python split string every 3rd value but into a nested format

description: Python split string every 3rd value but into a nested format


code:
def get_last_of_type(type_, iterable):
    for el in reversed(iterable):
        if isinstance(el, type_):
            return el
    return None

rawDescription: Get last element of type string in a list


code:
Foo.bar()
foo = Foo()
foo.bar()

rawDescription: Are there any benefits from using a @staticmethod?


code: np.count_nonzero(fs[0:a] >= 0.75)

rawDescription: Want to count the number of values in a column that meet a condition


code:
SHIRT-RED
SHIRT-BLUE
SHIRT-GREEN
SHOE-RED
SHOE-BLUE

rawDescription: Using Python to manipulate data from a CSV only applying it to the first result


rawDescription: How does the axis parameter from NumPy work?


code:
c = CatchAll()
c ** 2
c._function
c._params

rawDescription: How to catch any method called on an object in python?

description: Catch any method called on an object in python


code:
# Create a solid, quadratic, red texture of 100px in size, using a RGBA color layout.
factory.from_color(0xFF000000, size=(100, 100),
                   masks=(0xFF000000,           # red channel
                          0x00FF0000,           # green channel
                          0x0000FF00,           # blue channel
                          0x000000FF))          # alpha channel

rawDescription: How do you access pySDL2 SoftwareSpriteRenderSystem Blendmode?

description: Access pySDL2 SoftwareSpriteRenderSystem Blendmode


code:
from itertools import groupby

[list(g) for _,g in groupby(numbers, lambda x: x//10)]
Out[3]: [[2, 8], [13, 15], [24, 26]]

rawDescription: Elegant way to slice a list with a condition


rawDescription: Getting AttributeError: sqrt in vq.whiten


rawDescription: Add subclass to super class' list when subclass is created in Python?


code: from urllib import unquote

rawDescription: Turn URL into String (decode URL)

description: Turn URL into String (decode URL)


code:
Time.at(1410627645).to_datetime.in_time_zone("Pacific Time (US & Canada)")
#=> Sat, 13 Sep 2014 10:00:45 PDT -07:00

rawDescription: Converting EPOC datetime to PST in python/ruby


rawDescription: Setting class variable during instatiation when using a factory in python


code:
np.random.seed(12345)
data = np.random.randint(0, 10, size=(10, 3, 2))
i, j, k = argrelmax(data, axis=0)

rawDescription: Scipy: Argrelmax Find Maxmima along Dimension in 3d Array


rawDescription: python find a pattern in string and enclose it in braces

description: Python find a pattern in string and enclose it in braces


rawDescription: How to wakeup thread from thread pool in python?

description: Wakeup thread from thread pool in python


code: map_dict = dict((t[1], t[0]) for t in tabela)

rawDescription: Compare string of bits with elements of a table python


code:
def countOf(x,L):
    filteredL = list(filter(lambda value: value[0] == x,L))
    return sum(list(map(lambda value: value[1], filteredL)))

rawDescription: weighted counting in python

description: Weighted counting in python


code:
def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero

rawDescription: Python.el mishandling my M-q indentations on docstrings


code: X = np.hstack((X, AllAlexaAndGoogleInfo))

rawDescription: Using ranking data in Logistic Regression


code: from SimpleCV.Color import Color

rawDescription: SimpleCV Code Completion with Eclipse

description: SimpleCV Code Completion with Eclipse


rawDescription: Generate tailor made thousand delimiter

description: Generate tailor made thousand delimiter


code: pincode = validated_pincode()

rawDescription: How to create generic modelform field validator for inherited model attributes in django?

description: Create generic modelform field validator for inherited model attributes in django


code:
# Imports
import csv
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
from collections import namedtuple
from operator import add, itemgetter
from pyspark import SparkConf, SparkContext
from pyspark.mllib.tree import RandomForest, RandomForestModel
from pyspark.mllib.util import MLUtils
from pyspark.mllib.linalg import SparseVector
from pyspark.mllib.regression import LabeledPoint
import shutil
import numpy

def parse(row):
    """
    Parses a row and returns a named tuple.
    """
    row[0]  = str(row[0])
    row[1]  = float(row[1])
    row[2]  = float(row[2])
    row[3]  = float(row[3])
    row[4]  = float(row[4])
    return LabeledPoint(row[4], row[:4])

def split(line):
    """
    Operator function for splitting a line with csv module
    """
    reader = csv.reader(StringIO(line), delimiter=';')
    return next(reader)

#save csv file on a spark cluster (RDD format)
data = sc.textFile("datafile").map(split).map(parse)

rawDescription: random forest with spark: get predicted values and R²

description: Random forest with spark: get predicted values and R²


code:
ax.set_title('This is a nice figure')
# or
plt.title('This is a nice figure')

rawDescription: Making networkx plot where edges only display edited numeric value, not field name


code:
from copy import copy
copy_of_A = copy(A)

rawDescription: Python list help

description: Python list help


code:
[[[[[[['"breast neoplasms"'], ['MeSH', 'Terms']],
     'or',
     [['breast', 'cancer'], ['Acknowledgments']],
     'or',
     [['breast', 'cancer'], ['Figure/Table', 'Caption']],
     'or',
     [['breast', 'cancer'], ['Section', 'Title']],
     'or',
     [['breast', 'cancer'], ['Body', '-', 'All', 'Words']],
     'or',
     [['breast', 'cancer'], ['Title']],
     'or',
     [['breast', 'cancer'], ['Abstract']],
     'or',
     [['breast', 'cancer'], ['Journal']]]]],
  'and',
  [[[[['prevention'], ['Acknowledgments']],
     'or',
     [['prevention'], ['Figure/Table', 'Caption']],
     'or',
     [['prevention'], ['Section', 'Title']],
     'or',
     [['prevention'], ['Body', '-', 'All', 'Words']],
     'or',
     [['prevention'], ['Title']],
     'or',
     [['prevention'], ['Abstract']]]]]]]

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
async def extract_links(url):
    data = await download(url)
    links = parse(data)
    # if search_in_very_big_file() takes much time to process,
    # all your running async funcs (somewhere else in code) will be friezed
    # you need to avoid this situation
    links_found = search_in_very_big_file(links)

rawDescription: When to use and when not to use Python 3.5 `await` ?


code:
_SimpleCData # _type_: 'P' for void *
_Pointer     # _type_: ctypes.c_int
_CFuncPtr    # _flags_, _restype_, _argtypes_, _check_retval_

rawDescription: Determining whether an object is a ctypes array


code: email = db.StringField(max_length=255, unique=True, regex=r'.*?boston\.edu$')

rawDescription: StringField in mongodb requirements

description: StringField in mongodb requirements


code:
[
    item
    for sublist in response
    for item in sublist
]

rawDescription: Python's list comprehensions and other better practices


code: logger = logging.getLogger(__name__)

rawDescription: How can I send the output of a Logger object in python to a file?

description: Send the output of a Logger object in python to a file


code:
import numpy as np
import pylab as plt

Intensity = np.loadtxt('bessel.txt')

plt.imshow(Intensity,vmax=0.01,cmap='hot')
plt.gray()
plt.show()

rawDescription: Density plot with python making a Diffraction pattern with Bessel Integrals but it wont stop running


code:
df1 = rdd1.toDF(("id1", "id2"))
df2 = rdd2.toDF(("id2_", "item_id"))

n_features = len(rdd3.first()) - 1
feature_names = ["x_{0}".format(i) for i in range(n_features)]

df3 = rdd3.toDF(["item_id_"] + feature_names)

rawDescription: Spark: Manipulation of Multiple RDDs

description: Spark: Manipulation of Multiple RDDs


code:
import matplotlib.pyplot as plt
test_y=range(10)
test_x=[8,13,59,8,81,2,5,6,2,3]

def subplotsave_test():
    for i in range(5):
        fig = plt.figure(i)
        txt = fig.suptitle('Page '+str(i)+' of '+str(5),fontsize='20')
        for j in range(16):
            plt.subplot(4,4,j+1)
            plt.plot(test_y,test_x)
        plt.savefig(str(i)+'.png',bbox_inches='tight',orientation='landscape')

if __name__ == '__main__':
    subplotsave_test()

rawDescription: Why doesn't this code save my figures with titles?


code:
# python_launched_from_nodejs.py
import sys

data = "this began life in python"
print(data)
sys.stdout.flush()

rawDescription: Call python script using node.js child_process


code:
def positionExtractor(alist):
    return tuple(alist[0:3])

def velocityExtractor(alist):
    velocity = tuple(alist[3:6])
    return velocity + (np.sqrt(sum(x**2 for x in velocity)),)

def forcesExtractor(alist):
    forces = tuple(alist[6:9])
    return forces + (np.sqrt(sum(x**2 for x in forces)),)

rawDescription: Code smell - if/else construct

description: Code smell - if/else construct


code:
def event_handler(event):
    gdb.execute("set scheduler-locking on") # to avoid parallel signals in other threads

    gdb.write("\n[ME] SIG " + event.stop_signal)
    frame = gdb.selected_frame()
    while frame:
        gdb.write("\n[ME] FN " + str(frame.name()))
        frame = frame.older()
    gdb.execute("set scheduler-locking off") # otherwise just this thread is continued, leading to a deadlock
    gdb.post_event(Executor("continue")) # and post the continue command to gdb

rawDescription: Continue after SIGNAL with a python script in gdb


code:
def f(func):
    return func()
def g():
    return 'sunflower seeds'
id(g)
g = f(g)
id(g)

rawDescription: Accessing function attribute created in a decorator outside that decorator


code:
class RepoLoader:
    def __init__(self, url, path):
        self.url = url
        self.path = path
        self._repo = None

    def fetch_repo(self):
        self._repo = git.Repo.clone_from(self.url, self.path)

    @property
    def repo(self):
        if self._repo is None:
            self.fetch_repo()
        return self._repo

compiler = RepoLoader(someurl, somepath)

rawDescription: Clone git repository and import object elsewhere


code:
import sys, pygame, math
from pygame.locals import *
pygame.init()

# Added HEIGHT and WIDTH as fixed variables

WIDTH = 800
HEIGHT = 600

SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))

car = pygame.transform.scale(pygame.image.load('Car.png').convert_alpha(), (64, 64))
pygame.display.set_caption('Car Game')
pygame.display.set_icon(car)
FPS = pygame.time.Clock()

carX  = 400
carY  = 100
angle = 90
speed = 0

while True:

    if angle == 360: angle = 0
    if  angle == -1: angle = 359

    SCREEN.fill((0,0,0))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[K_a] or keys[K_LEFT]:
        angle += speed
    elif keys[K_d] or keys[K_RIGHT]:
        angle -= speed
    if keys[K_w] or keys[K_UP]:
        speed += 1
    elif keys[K_s] or keys[K_DOWN]:
        speed -= 0.5

    carX += speed*math.cos(math.radians(angle))
    carY -= speed*math.sin(math.radians(angle))
    speed *= 0.95

    rotcar = pygame.transform.rotate(car, angle)
    position = rotcar.get_rect(center = (carX,carY))

    # Basically a copy/paste of the "draw"-function from the spacegame.zip

    wrap_around = False

    if position[0] <  0 :
        # off screen left
        position.move_ip(WIDTH, 0)
        wrap_around = True

    if position[0]  + rotcar.get_width() > WIDTH:
        # off screen right
        position.move_ip(-WIDTH, 0)
        wrap_around = True

    if position[1]  < 0:
        # off screen top
        position.move_ip(0, HEIGHT)
        wrap_around = True

    if position[1] + rotcar.get_height() > HEIGHT:
        # off screen bottom
        position.move_ip(0, -HEIGHT)
        wrap_around = True

    if wrap_around:

        SCREEN.blit(rotcar, position)

    position[0] %= WIDTH
    position[1] %= HEIGHT
    carX %= WIDTH
    carY %= HEIGHT

    SCREEN.blit(rotcar, position)

    pygame.display.update()
    FPS.tick(24)

rawDescription: Moving a sprite to the other side when a sprite moves off screen Pygame


code:
def byvalue(request,value='0.99'):
    try:
        value = float(value)
    except:
        ...

rawDescription: How Do I Use A Decimal Number In A Django URL Pattern?


code: SECURITY_MSG_INVALID_PASSWORD = ('Your username and password do not match our records', 'error'),

rawDescription: How to override Flask-Security default messages?

description: Override Flask-Security default messages


code:
import numpy as np

a = np.arange(100).reshape(10,10)
n1, n2 = np.arange(5), np.arange(5)

# Not what you want
b = a[n1, n2]  # array([ 0, 11, 22, 33, 44])

# What you want, but only for simple sequences
# Note that no copy of *a* is made!! This is a view.
b = a[:5, :5]

# What you want, but probably confusing at first. (Also, makes a copy.)
# np.meshgrid and np.ix_ are basically equivalent to this.
b = a[n1[:,None], n2[None,:]]

rawDescription: Subsetting a 2D numpy array

description: Subsetting a 2D numpy array


code:
a=sns.jointplot(x="volatility", y="return", data=data, size=10)
a.ax_joint.plot([0.2],[0.2],'ro')

rawDescription: Add data to a seaborn jointplot

description: Add data to a seaborn jointplot


code: profile.native_events_enabled = False

rawDescription: Selenium WebDriver - Disable Native Events (Enable Synthesized Events)


rawDescription: Conditional dataframe calculations based on a columns suffix


code: value.key in dict

rawDescription: python key in dict.keys() performance for large dictionaries

description: Python key in dict.keys() performance for large dictionaries


code:
injuries = {injury: df[df['Type'] == injury] for injury in df['Type'].unique()}

injuries['BROKEN PELVIS']  # is the same as df_a above

rawDescription: making multiple pandas data frames using a loop or list comprehension

description: Making multiple pandas data frames using a loop or list comprehension


code: ''.join([character for character in sentence if character not in vowels]) # returns string without vowels

rawDescription: Removing from vowels from a string

description: Removing from vowels from a string


code:
system_a_devices = {"host1.test.local": "Test 1 Group", "host5.testing.lan": "LAN Test Group", "server5.hello.local": "Hello Corporation, Inc.", "desktop1.corp.tld": "Corporate TLD, Ltd."}
system_b_devices = {"desktop1.corp.tld": "Corporate TLD, Ltd.", "host1.test.local": "Test One Group", "server6.hello.local": "Hello Corporation, Inc."}

rawDescription: Comparing Two Lists of Tuples Based On Each Tuple's First Value (But Returning ALL Tuple Values)


code:
import ctypes, time

# open the CD tray
ctypes.windll.winmm.mciSendStringW("set cdaudio door open", None, 0, None)

# try closing the tray
ctypes.windll.winmm.mciSendStringW("set cdaudio door closed", None, 0, None)

rawDescription: How can I eject a CD from MacOS with Python?

description: Eject a CD from MacOS with Python


code:
import example
assert(1 == example.spam1.id)
assert(2 == example.spam2.id)
assert(3 == spam3.id)

rawDescription: Set a python variable to a C++ object pointer with boost-python


code:
for bullet in bullets:
  if bullet[0]<0:
    bullets.remove(bullet)

rawDescription: How to create bullets in pygame?

description: Create bullets in pygame


code:
class BindingListEx(System.ComponentModel.BindingList[str]):
    pass

b = BindingListEx()
b
b.Add(3)
b.Add("cow")

rawDescription: Why am I getting a NullReferenceException when trying to subclass from an ObservableCollection or BindingList?


code:
from django.contrib.auth import get_user_model

class EmailAuthBackend(object):
    """
    Email Authentication Backend
    """

    def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = get_user_model().objects.get(email=username)
            if user.check_password(password):
                return user
        except get_user_model().DoesNotExist:
            return None

rawDescription: Django custom login never authenticates why?


code:
import re

import requests
from bs4 import BeautifulSoup

with requests.Session() as session:
    # extract the last page
    response = session.get("http://www.engineering.careers360.com/colleges/list-of-engineering-colleges-in-India?sort_filter=alpha")
    soup = BeautifulSoup(response.content, "html.parser")
    last_page = int(re.search("page=(\d+)", soup.select_one("li.pager-last").a["href"]).group(1))

    # loop over every page
    for page in range(last_page):
        response = session.get("http://www.engineering.careers360.com/colleges/list-of-engineering-colleges-in-India?sort_filter=alpha&page=%f" % page)
        soup = BeautifulSoup(response.content, "html.parser")

        # print the title of every search result
        for result in soup.select("li.search-result"):
            title = result.find("div", class_="title").get_text(strip=True)
            print(title)

rawDescription: How to scrape the next pages in python using Beautifulsoup

description: Scrape the next pages in python using Beautifulsoup


code:
from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt

def augmented_dendrogram(*args, **kwargs):

    ddata = dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        for i, d in zip(ddata['icoord'], ddata['dcoord']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            plt.plot(x, y, 'ro')
            plt.annotate("%.3g" % y, (x, y), xytext=(0, -8),
                         textcoords='offset points',
                         va='top', ha='center')

    return ddata

rawDescription: how to plot and annotate hierarchical clustering dendrograms in scipy/matplotlib

description: Plot and annotate hierarchical clustering dendrograms in scipy/matplotlib


code:
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *arg)

rawDescription: How can I isolate part of a string in a list of strings and sort the list with it? (in Python)

description: Isolate part of a string in a list of strings and sort the list with it? (in Python)


code:
#captcha/views.captcha_image
...
size = font.getsize(text)
size = (size[0] * 2, int(size[1] * 1.2))
...

rawDescription: Django Simple Captcha image size

description: Django Simple Captcha image size


rawDescription: Changing the Digit Color of QLCD Number

description: Changing the Digit Color of QLCD Number


code: subprocess.Popen(["/bin/bash", "myscript.sh", "var=11; ignore all", path_to_files])

rawDescription: python subprocess calling bash script - need to print the quotes out too

description: Python subprocess calling bash script - need to print the quotes out too


code:
x = np.random.random((3,3))
y = np.matrix(x)
type(y.I)
type(np.linalg.inv(x))

rawDescription: Scipy inv(A) vs A.I

description: Scipy inv(A) vs A.I


code:
import sys

from colorama import init
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import cprint
from pyfiglet import figlet_format

cprint(figlet_format('missile!', font='starwars'),
       'yellow', 'on_red', attrs=['bold'])

rawDescription: Is there a python library that allows to easily print ascii-art text?


rawDescription: Write the same nested loop n levels deep


code:
import platform
platform.architecture()

rawDescription: How to find system type using Python?

description: Find system type using Python


code:
def get_download_url(user):
    try:
        download = Download.objects.get(user=user)
        return download.download_url
    except Download.DoesNotExist:
        return None

rawDescription: Django restrict pages to certain users

description: Django restrict pages to certain users


code: br.select_form(predicate=lambda form: form.attrs['id'] == 'id-of-form')

rawDescription: Mechanize submit a form that creates a dynamic flie that needs to be downloaded


code:
from operator import itemgetter
set(map(itemgetter(0),l1)) & set(map(itemgetter(0),l2))

rawDescription: Comparing elements between elements in two lists of tuples


code: np.tile(2, array.shape)

rawDescription: Find float in ndarray

description: Find float in ndarray


code:
d = {(1, 2): False}
d[1, 2] = True
tuple(d.items())

rawDescription: Python modify tuple with lambda

description: Python modify tuple with lambda


rawDescription: How do I find all tuples with a specific value?

description: Find all tuples with a specific value


code:
x, y = np.mgrid[:2, :3]
np.vstack((x.ravel(),y.ravel())).T

rawDescription: numpy mgrid shapely for linestring coordinates

description: Numpy mgrid shapely for linestring coordinates


rawDescription: Loop through netcdf files and run calculations - Python or R


rawDescription: BeautifulSoup help, how to extract content from not proper tags text in html file?


rawDescription: Merging two arrays under numpy

description: Merging two arrays under numpy


rawDescription: how to write regular expression makes sure that there is no digits after

description: Write regular expression makes sure that there is no digits after


rawDescription: Not getting the right result using XPath with python scraper


code: newline = (oldline.rstrip()+" "+(str(score)))

rawDescription: Python: Storing data in a text file and appending particular/individual lines


code: fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.viewkeys() | fus_s]

rawDescription: How can I create a list from two dictionaries?

description: Create a list from two dictionaries


code: df.loc[df[1] == "string A"]

rawDescription: Indexing column values in pandas

description: Indexing column values in pandas


code:
class PromoNotification(models.Model):
    ...
    objects = PromoNotificationManager()

rawDescription: Django - Limit users who view the items

description: Django - Limit users who view the items


code:
a=['from src1 to dest2','from src3 to dest4','from src5 to dst6']
b=[['dest2','destb'],['dest4','locd'],['dest6','destf'],['dest8','desth']]
result = []
for x in a:
    for i,j in b:
        if i in x:
            result.append(re.sub(i,j,x))
            break
    else:
        result.append(x)
result

rawDescription: Python: Compare list of strings to list of tuples, and create a new list based on match or no match


code:
with open('foo.csv', 'w') as f:
    data.to_csv(f, index=True, header=True, decimal=',', sep=' ', float_format='%.3f')

rawDescription: pandas to_csv arguments float_format and decimal not working for index column

description: Pandas to_csv arguments float_format and decimal not working for index column


code:
Example
text = ("This is the first sentence. This is the second sentence? "
        "This is the third\n sentence!")
for limit in [100, 80, 50, 5]:
    print(truncate_paragraph(text, limit))

rawDescription: Function to return sentences under a given character count


code: app = webapp2.WSGIApplication([(r'/app1/myview', Handler),(r'/app1/myotherview', AnotherHandler)])

rawDescription: Url mapping in Google App Engine Python in multiple files


code:
def get_bin(n, step=0.05):
    return step * round(n / step)

rawDescription: Find closer number of a value considering given intervals - Python


code:
import numpy as np

def variable_blur(data, kernel_size):
    """ Blur with a variable window size
    Parameters:
      - data: 2D ndarray of floats or integers
      - kernel_size: 2D ndarray of integers, same shape as data
    Returns:
      2D ndarray
    """
    data_blurred = np.empty(data.shape)
    Ni, Nj = data.shape
    for i in range(Ni):
        for j in range(Nj):
            res = 0.0
            weight = 0
            sigma =  kernel_size[i, j]
            for ii in range(i - sigma, i+sigma+1):
                for jj in range(j - sigma, j+sigma+1):
                    if ii<0 or ii>=Ni or jj < 0 or jj >= Nj:
                        continue
                    res += data[ii, jj]
                    weight += 1
            data_blurred[i, j] = res/weight
    return data_blurred

data = np.random.rand(50, 20)
kernel_size = 3*np.ones((50, 20), dtype=np.int)
variable_blur(data, kernel_size)

rawDescription: High performance variable blurring in very big images using Python


code: {d['url'] for d in store}

rawDescription: Filtering python list of duplicated

description: Filtering python list of duplicated


rawDescription: How to label the x axis in fraction numbers?

description: Label the x axis in fraction numbers


code:
import numpy as np
vs = [np.r_[1,2,3.0],np.r_[4,5.0],np.r_[6,7,8.0]]
shape = map(len, vs)

 # specify the orientation of each vector
newshapes = np.diag(np.array(shape)-1)+1
reshaped = [x.reshape(y) for x,y in zip(vs, newshapes)]

# direct product
A = reduce(lambda a,b: a*b, reshaped, 1)
B = reduce(np.multiply, np.ix_(*vs))

np.all(A==B)

rawDescription: Numpy: outer product of n vectors

description: Numpy: outer product of n vectors


code:
for a in response.css(".result-title a"):
     print("".join(a.xpath(".//text()").extract()))

rawDescription: Extracting text within em tag in scrapy

description: Extracting text within em tag in scrapy


rawDescription: What is the class of this javascript button for use with selenium?


code: dateparse = lambda x: d(x) if d(x) < datetime.datetime.now() else d(x) - relativedelta(years=100)

rawDescription: pandas reading dates from csv in yy-mm-dd format

description: Pandas reading dates from csv in yy-mm-dd format


code:
import datetime
import time
timestamp = datetime.datetime.now().time() # Throw away the date information
time.sleep(1)
print (datetime.datetime.now().time() > timestamp) # >>> True (unless you ran this one second before midnight!)

# Or check if a time is between two other times
start = datetime.time(8, 30)
end = datetime.time(15)
print (start <= timestamp <= end) # >>> depends on what time it is

rawDescription: How to check in python if I'm in certain range of times of the day?

description: Check in python if I'm in certain range of times of the day


rawDescription: How to count in a row results from text file

description: Count in a row results from text file


code:
row = layout.row()
opname = "wm.simple_multi_operator"
row.operator(opname, text='A').param_one = 'A'
row.operator(opname, text='B').param_one = 'B'

# if you have more than one property for the operator
op_two = row.operator(opname, text='B / Mode Y')
op_two.param_one = 'B'
op_two.param_two = 'Mode Y'

rawDescription: Call a function in a class from different class


code:
a3d = a3d.reshape(a3d.shape + (1, 1))
a3d.shape

rawDescription: np.array ndmin argument: specify placement of added dimensions

description: Np.array ndmin argument: specify placement of added dimensions


code:
if blackJoker in hand:
    hand.remove(blackJoker)
    return [hand + [c] for c in cards]

rawDescription: python can't seem to get a list to return properly

description: Python can't seem to get a list to return properly


code: dups = list(dups.values())

rawDescription: In a list of tuples, return tuple[1] if tuple[0] is a duplicate of another tuple[0] in the list


code:
counter = 0
def increment_counter():
    global counter
    counter += 1
def decrement_counter():
    global counter
    counter -= 1

rawDescription: Why do we use classes in Python?

description: Why do we use classes in Python


code:
import numpy as np
np.set_printoptions(linewidth=200)

import pandas as pd
pd.options.display.width = 200

rawDescription: Pandas and NumPy default width change on startup


code:
arr = np.random.random((6,2,3,4,5,6))
result = np.einsum('ijklmi->ijklm', arr)
result2 = np.einsum('i...i->i...', arr)
assert np.allclose(result, result2)

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


code:
import socket
addresses = socket.getaddrinfo(host, None) # or host, port if you prefer

rawDescription: Resolve host name of wss protocol with socket?


code:
import re
import math
import timeit

from collections import Counter

WORD = re.compile(r'\w+')

def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in vec1.keys()])
    sum2 = sum([vec2[x] ** 2 for x in vec2.keys()])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator

def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)

class VectorResult(object):
    def __init__(self, cosine, text_1, text_2):
        self.cosine = cosine
        self.text_1 = text_1
        self.text_2 = text_2

    def __eq__(self, other):
        if self.cosine == other.cosine:
            return True
        return False

    def __le__(self, other):
        if self.cosine <= other.cosine:
            return True
        return False

    def __ge__(self, other):
        if self.cosine >= other.cosine:
            return True
        return False

    def __lt__(self, other):
        if self.cosine < other.cosine:
            return True
        return False

    def __gt__(self, other):
        if self.cosine > other.cosine:
            return True
        return False

def main():
    start = timeit.default_timer()
    texts = []
    with open('data.txt', 'r') as f:
        texts = f.readlines()

    cosmap = []
    i = 0
    out = []
    while i < len(texts):
        max_cosine = 0.0
        current = None
        for p in range(i + 1, len(texts)):
            if texts[i] in out or texts[p] in out:
                continue
            vector1 = text_to_vector(texts[i])
            vector2 = text_to_vector(texts[p])
            cosine = get_cosine(vector1, vector2)
            if cosine > max_cosine:
                current = VectorResult(cosine, texts[i], texts[p])
                max_cosine = cosine
        if current:
            out.extend([current.text_1, current.text_2])
            cosmap.append(current)
        i += 1

    cosmap = sorted(cosmap)

    for item in reversed(cosmap):
        print(item.cosine, item.text_1, item.text_2)

    end = timeit.default_timer()

    print("Similarity Sorting of {} strings lasted {} s.".format(len(texts), end - start))

if __name__ == '__main__':
    main()

rawDescription: Sorting string in order of high frequency terms from Inverted Index Elasticsearch


code:
def consumer(q):
    def helper():
        while True:
            items = [(q.get(),) for _ in range(10000)]
            conn.executemany("INSERT INTO table VALUES (?)", items)
            conn.commit()
    return helper

rawDescription: How do I continue iterating without having to wait output to finish?

description: Continue iterating without having to wait output to finish


rawDescription: Tkinter Canvas move item to top level

description: Tkinter Canvas move item to top level


code:
from module import Home

h = Home(3, 3000, 2)
h.show_info()

h2 = Home(2, 4000, 5)
h2.message = "Second Human habitation: {} bedrooms"

h2.show_info()

rawDescription: Inheritance and classes

description: Inheritance and classes


code:
with open('listOfFruits.txt', 'r') as f:
    fruits = set([line.rstrip() for line in f])
with open('allFruitData.txt', 'r') as f:
    data = {}
    for line in f:
        fruit = line.rstrip().split()[2]
        data[fruit] = line

fruits_not_in_file = set(data.keys()) - fruits
with open(outfile, 'w') as f:
    for fruit in fruits_not_in_lile:
        f.write(data[fruit])

rawDescription: Comparing 2 txt files and creating a new txt file from what is absent in 1 or the files


code:
def dataReceived(self, data):
    self.peer.transport.write(data)

rawDescription: How can I create a non-http proxy with Twisted

description: Create a non-http proxy with Twisted


code:
GetPosition()
GetState()
GetStep()
SetPosition(pos)
StepIt()

rawDescription: progress bar properties python2.72 pywinauto

description: Progress bar properties python2.72 pywinauto


code: sat = im.cumsum(1).cumsum(0)

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


rawDescription: Is there a way to inhibit rounding in python?


code:
tokens = line.split()
tokens
tokens[2]
tokens[5]

rawDescription: Extracting a specific PIECE of a line from a textfile(Python)


code:
from sqlalchemy.sql import table, column
t1 = table('t1', column('a'), column('b'))
t2 = table('t2', column('x'), column('y'))
print(t1.insert().from_select(['a', 'b'], t2.select().where(t2.c.y == 5)))

rawDescription: How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?


code:
d = np.zeros((2,2,2,2))
d.shape
d.ndim

rawDescription: missing dimension in numpy array shape

description: Missing dimension in numpy array shape


code:
# main.py

class Controller(FloatLayout):
    layout_content=ObjectProperty(None)

    def __init__(self, **kwargs):
        super(Controller, self).__init__(**kwargs)
        self.layout_content.bind(minimum_height=self.layout_content.setter('height'))

rawDescription: How do you scroll a GridLayout inside Kivy ScrollView?

description: Scroll a GridLayout inside Kivy ScrollView


code:
import pandas as pd
df1 = pd.read_csv("file1.csv", sep=r"\s+")
df2 = pd.read_csv("file2.csv", sep=r"\s+")
merged = df1.merge(df2.rename_axis({"Mon-id": "NAME"}))
merged.to_csv("merged.csv", index=False)

rawDescription: Comparing two files and printing similar lines


code:
xx = Mylist([1,2,3])
xx.map(lambda m: m*2).map(lambda m: m**2)

rawDescription: Clean code for sequence of map/filter/reduce functions


rawDescription: How to read file capabilities using Python?

description: Read file capabilities using Python


rawDescription: Google App Engine: Storing images in database (Python)


code:
from xml.etree.ElementTree import XMLParser, TreeBuilder

class MyTreeBuilder(TreeBuilder):

    def start(self, tag, attrs):
        print("<%s>" % tag)
        return TreeBuilder.start(self, tag, attrs)

    def data(self, data):
        print(repr(data))
        TreeBuilder.data(self, data)

    def end(self, tag):
        return TreeBuilder.end(self, tag)

text = """<xml>
The captial of <place pid="1">South Africa</place> is <place>Pretoria</place>.
</xml>"""

# ElementTree.fromstring()
parser = XMLParser(target=MyTreeBuilder())
parser.feed(text)
root = parser.close() # return an ordinary Element

rawDescription: Using Python's xml.etree to find element start and end character offsets


code:
class Foo(object):
    my_var = {'one': 1} # This a class variable

foo = Foo()
foo.my_var = {'two': 2} # Override class my_var with instance my_var
foo.my_var
Foo.my_var
foo.__class__.my_var # But you can still access the class variable like this.

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


rawDescription: Python Pandas - How to flatten a hierarchical index in columns


code:
request.session['selected_courses'] = {
   '2': [ {'first_name': 'Jon', 'last_name': 'Kan'}, ... ]
}

rawDescription: Deleting Session Variables Django

description: Deleting Session Variables Django


code: ['something1', 'something2', 'something12', 'something17', 'something25', 'something29']

rawDescription: How to correctly sort a string with a number inside?

description: Correctly sort a string with a number inside


code: [(i[1], i[0]) if i[0]>i[1] else i for i in lst]

rawDescription: Fastest way to sort tiny lists in python


code: Field('user_id', 'reference auth_user', requires=None)

rawDescription: web2py, one to many, not required relationship

description: Web2py, one to many, not required relationship


code:
#!/usr/bin/env python3

from flask import Flask, g, render_template
import sqlite3

app = Flask(__name__)

@app.route('/movies/genres/<name>/')
def test(name=None):
    g.db = connect_db()
    cur = g.db.execute('select id, name from movies where category = ?', [name])
    movies = [dict(id=row[0], movie_name=row[1]) for row in cur.fetchall()]
    g.db.close()
    return render_template('test.html', movies=movies, name=name)

def connect_db():
    return sqlite3.connect('example.db')

def init_db():
    conn = connect_db()
    c = conn.cursor()
    try:
        c.execute('create table movies (id int, name text, category text)')
        c.execute('insert into movies (id, name, category) values (?, ?, ?)', (1, 'Alien', 'sci-fi'))
        c.execute('insert into movies (id, name, category) values (?, ?, ?)', (2, 'Aliens', 'sci-fi'))
        c.execute('insert into movies (id, name, category) values (?, ?, ?)', (3, 'Prometheus', 'sci-fi'))
    except sqlite3.OperationalError as e:
        assert 'table movies already exists' in str(e)
    conn.commit()
    conn.close()

def main():
    init_db()
    app.run(debug=True)

if __name__ == '__main__':
    main()

rawDescription: Query sqlite using flask routing

description: Query sqlite using flask routing


code:
def timerEvent(self, evt):
        # get the cpu percentage usage
        result = self.get_cpu_usage()
        # append new data to the datasets
        self.user.append(result[0])
        #save the current time
        self.timeStamp.append(datetime.now())
        # update lines data using the lists with new data
        self.l_user.set_data(self.timeStamp, self.user)
        #rescale the x axis maintaining a 5 minutes window
        self.ax.set_xlim([datetime.now()-timedelta(seconds=5*60),datetime.now()])
        # force a redraw of the Figure, this might not update the x axis limits??
        self.fig.canvas.draw()
           #else, we increment the counter
        self.cnt += 1

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code:
if r.random() < 0.5:
    drawSet(pics,location)
else:
    drawSet(targetset,location)

rawDescription: Duplicating random visual stimuli in Python/Psychopy


code:
from myapplication.essay.models import Essay
from django.contrib import admin

class EssayAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    fieldsets = [
        (None, { 'fields': [('title','body')] } ),
    ]

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()

rawDescription: How to auto insert the current user when creating an object in django admin?

description: Auto insert the current user when creating an object in django admin


code: testPath = os.path.splitext(files)[0]

rawDescription: Can't get simple loop working right

description: Can't get simple loop working right


code:
# create some random data
df =pd.DataFrame({'letter': list('qwertyuiopasdfghjklzxcvbnm'),'value': np.random.randint(1,15,26)})

rawDescription: Python pandas: accumulate data frame rows by condition


rawDescription: how to filter given two datefields if they coincide with a from and to date in a model django

description: Filter given two datefields if they coincide with a from and to date in a model django


code:
def merge_ip_list_alt(ip_list):
    if not ip_list:
        return []
    orig = sorted(map(dot2int,ip_list))
    end, start = zip(*[x for x in zip(orig,orig[1:]) if x[0]+1!=x[1]]) or ((),())
    start = [int2dot(orig[0])] + map(int2dot,start)
    end = map(int2dot,end) + [int2dot(orig[-1])]
    return zip( start, end )

rawDescription: Python - convert list of IP addresses to a list of address ranges


rawDescription: Class 'list' does not define '__mod__', so the '%' operator cannot be used


code:
before
1
code
after
before
2
code
after
before
3
code
after

rawDescription: How do I make a contextmanager with a loop inside?

description: Make a contextmanager with a loop inside


rawDescription: matplotlib raw string line break in code

description: Matplotlib raw string line break in code


code: longest_strings = [s for s in stringlist if len(s) == maxlength]

rawDescription: Longest strings from list

description: Longest strings from list


rawDescription: How to sort a list based on dictionary values?

description: Sort a list based on dictionary values


code:
import csv
from itertools import izip_longest, izip

N = 5 # adapt as needed
values = range(1, 23) # use real values here

with open(path, 'wb') as fout:
    csvout = csv.writer(fout)
    rows = izip_longest(*[iter(values)] * N, fillvalue='')
    transposed = izip(*rows)
    csvout.writerows(transposed)

rawDescription: write 5M data to a csv file using file write operation

description: Write 5M data to a csv file using file write operation


rawDescription: How can i get .text section from PE file using pefile

description: Get .text section from PE file using pefile


code:
# helloworld.py
import webapp2

class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

class GoodbyePage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Goodbye, World.  Time to sleep.')

application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/goodbye', GoodbyePage),
], debug=True)

rawDescription: App Engine - Python - Open local HTML file from script


rawDescription: Python - How to copy content of USB(Flash) to system directory


code: BASE = 'http://www.whatever.com'

rawDescription: basic python module design question

description: Basic python module design question


rawDescription: python lists, appending something to the list changes the entire thing?

description: Python lists, appending something to the list changes the entire thing


code: mag_list = [value for value in var_s[4::3] if value != 99.]

rawDescription: Speed up python loop

description: Speed up python loop


code:
stats.exponweib.fit(data, floc=0, f0=1)
stats.weibull_min.fit(data, floc=0)

rawDescription: Fitting a Weibull distribution using Scipy


code:
# section defined with nesting
section = ident + nestedExpr()

rawDescription: Parsing text file in python using pyparsing


code:
class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))

rawDescription: sqlalchemy multiple foreignkey

description: Sqlalchemy multiple foreignkey


code:
doc = webview.page().mainFrame().documentElement()
select = doc.findFirst('select[name="birthday_m"]')

rawDescription: How to choose value from an option list using PyQt4.QtWebKit

description: Choose value from an option list using PyQt4.QtWebKit


rawDescription: Combine two columns to a datetime in pandas


code:
info = {'id': 'my_id'}
output = """<div class="form-group" id="{id}_container">""".format(**info)

rawDescription: string.template with arrays as placeholders

description: String.template with arrays as placeholders


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

fig, ax = plt.subplots()
x = [0, 10, 100, 1000]
y = [100, 20, 10, 50]
x = np.asarray(x) + 1
y = np.asarray(y)
ax.plot(x, y)
ax.set_xscale('log')
ax.set_xlim(x.min(), x.max())
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x-1)))
ax.xaxis.set_major_locator(ticker.FixedLocator(x))
plt.show()

rawDescription: Matplotlib logarithmic scale with zero value


code:
class GroupedAttribute(object):
    def __init__(self, group, obj):
        self.group = group
        self.obj = obj
    def __get__(self, obj, owner):
        return self.obj
    def __set__(self, obj, value):
        self.obj = value

class AttributeGroup(object):
    def __call__(self, obj):
        return GroupedAttribute(self, obj)
    def __get__(self, obj, owner):
        return BoundAttributeGroup(self, obj, owner)

class BoundAttributeGroup(object):
    def __init__(self, group, obj, owner):
        self.group = group
        self.obj = obj
        self.owner = owner
    def __dir__(self):
        items = dir(self.owner if self.obj is None else self.obj)
        return [item for item in items if
                getattr(self.owner.__dict__.get(item, None),
                        'group', None) is self.group]

rawDescription: python decorator for field

description: Python decorator for field


code:
from pyread import read_auto
read_auto(PATHFILE)

rawDescription: Automatic parsing of data in Python

description: Automatic parsing of data in Python


code: map(lambda x: None if x in none_items else x, string_list)

rawDescription: check for null fields in json python

description: Check for null fields in json python


code:
from sklearn.preprocessing import LabelBinarizer
from sklearn.tree import DecisionTreeClassifier
import numpy as np

rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code:
strings = [ 'abc', 'def', 'xyz' ]
defaults = { 'extra_key1':0, 'extra_key2':'no' }
result = [ { 'type': type }.update( defaults ) for type in strings ]

rawDescription: Creating a list of dictionaries with default values


rawDescription: A copy of a list is altered on operations on the original list


code: [('BEST1_HUMAN', '150', 'GGAAAggccc'), ('4F2_HUMAN', '365', 'gggacCTACA')]

rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


code: a.replace('.', '').decode('hex')

rawDescription: Python: convert a dot separated hex values to string?


rawDescription: python head and tail in one line

description: Python head and tail in one line


code: [list(item) for item in cnt.iteritems()]

rawDescription: Split the result of 'counter'

description: Split the result of 'counter'


rawDescription: Convert LinkedIn APIs time to a standard date in Python


rawDescription: Spearman rank correlation in Python with ties


rawDescription: Is it better to use globals or pass in arguments to map functions?


code:
total_us = []

with open('somefile.txt') as f:
    for line in f:
        if line.strip():
            bits = line.split('\t')
            total_us.append(bits[0])

print(total_us)

rawDescription: Append only numbers to a list from a mixed file


code:
for file in macTable:
    open(file, 'w')

rawDescription: Creating new text files with names from an array in Python


code:
import mylogger
mylogger.mycounter += 1

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


code:
for matrix in ttranspose:
    Q_by_transpose_ind = np.matmul(ttranspose, Qmatrix)
    Q_by_transpose.append(Q_by_transpose_ind)

rawDescription: element wise matrix multiplication python

description: Element wise matrix multiplication python


code:
B_matrices={}
for i in input_dict.keys():
    eigenvalues_of_A, eigenvectors_of_A = numpy.linalg.eig(input_dict[i]);
    B = eigenvectors_of_A[:,abs(eigenvalues_of_A).argsort()]
    B_matrices[i] = B

rawDescription: create module in python for diagonalizing matrix

description: Create module in python for diagonalizing matrix


code: sorted(l, key=lambda x: int(re.sub('\D', '', x)))

rawDescription: sort string by number inside

description: Sort string by number inside


rawDescription: Cannot forward an email with attachments using imap and smtplib


code: images.transpose([2,0,1])  # instead of the default [2,1,0]

rawDescription: reshape an array of images

description: Reshape an array of images


code:
with open('temp.log') as temp:
    temp.write('Temporary logging.')

# equal to:

temp = open('temp.log')
temp.write('Temporary logging.')
temp.close()

rawDescription: How to compare 2 txt files in Python

description: Compare 2 txt files in Python


code:
for i in lst_select:
  lbox.get(i)
  UsrFCList.append(i)

rawDescription: get multiple items chosen in a listbox and populate new list with the values, using Tkinter

description: Get multiple items chosen in a listbox and populate new list with the values, using Tkinter


rawDescription: Access Request Parameters in invoked script of Python CGIHTTPServer


code:
c = NP.ones((4, 3))
c.flags

rawDescription: Is there an "enhanced" numpy/scipy dot method?


code: self.button = Button(self, text="Change Colors", command=self.changeColor(self._image))

rawDescription: How to change the pixel color of a PhotoImage python

description: Change the pixel color of a PhotoImage python


code: image == color

rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


code:
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None

rawDescription: Two instances of django admin site - templates


rawDescription: multiplying numbers in a string

description: Multiplying numbers in a string


code:
for i, idmach in enumarate(machine):
  print("The data is %d from machine %d." % (results[i], idmach))

rawDescription: Tag extra information to differentiate numbers in a list


code:
import mp3play

sound = mp3play.load('sound.mp3')
sound.play()

rawDescription: Play music with PyGame without display

description: Play music with PyGame without display


code:
# inside html_utils.py

def image_to_html(image):
    return '<img src="%(path)s" title="%(title)s" alt="%(alt)s" />' % {
        'path': image.raw.path,
        'title': image.title,
        'alt': image.alt_text
    }

rawDescription: How can I efficiently render an image in Django?

description: Efficiently render an image in Django


code: lookup = dict((typeB.typeA,typeB) for typeB in typeBlist)

rawDescription: if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?

description: If typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause


code:
from __future__ import print_function #so we can use python 3 print function

class GParent(object):
    def gparent_testmethod(self):
        print("Grandparent test method ")

class Parent(GParent):
    def parent_testmethod(self): #
        print("Parent test method")

class Child(Parent):
    def child_testmethod(self):
        print("This is the child test method")

c = Child()
c.gparent_testmethod()
c.parent_testmethod()
c.child_testmethod()

rawDescription: Calling Parent method directly in Python


code:
import os

a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
   for filename in files:
     f = os.path.join(path, filename)
     a.write(str(f) + os.linesep)

rawDescription: Python: List all the file names in a directory and its subdirectories and then print the results in a txt file


rawDescription: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list?

description: In python, how to match Strings based on Regular Expression and get the non-matching parts as a list


code:
import collections

level = collections.namedtuple("level",["sale","xcost","ycost"])

levels_dict = {4 :level(sale4, cost1, cost2),
               5 :level(sale5, cost2, cost3)}

rawDescription: Python: how to avoid writing numerous if/elifs in a function?


rawDescription: convert list of dict to int [Python Code Academy]

description: Convert list of dict to int [Python Code Academy]


code: [(i,k) for i,j in INPUT for k in j]

rawDescription: merging n sorted lists of tuples in python

description: Merging n sorted lists of tuples in python


code:
def commonElements(a1, a2):
    return tuple(sorted(set(a1).intersection(set(a2))))

rawDescription: How do I find every element that is in both of two other lists?

description: Find every element that is in both of two other lists


code:
W(od)
W(od)
W(od)
W(od)
W(od)

rawDescription: Python Dictionary, make range associated with its values and return them