code:
import threading
import webbrowser
import BaseHTTPServer
import SimpleHTTPServer

FILE = 'frontend.html'
PORT = 8080

class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """The test example handler."""

    def do_POST(self):
        """Handle a post request by returning the square of the number."""
        length = int(self.headers.getheader('content-length'))
        data_string = self.rfile.read(length)
        try:
            result = int(data_string) ** 2
        except:
            result = 'error'
        self.wfile.write(result)

def open_browser():
    """Start a browser after waiting for half a second."""
    def _open_browser():
        webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))
    thread = threading.Timer(0.5, _open_browser)
    thread.start()

def start_server():
    """Start the server."""
    server_address = ("", PORT)
    server = BaseHTTPServer.HTTPServer(server_address, TestHandler)
    server.serve_forever()

if __name__ == "__main__":
    open_browser()
    start_server()

rawDescription: How to implement a minimal server for AJAX in Python?

description: Implement a minimal server for AJAX in Python


code:
fig, ax = plt.subplots()
ax.scatter(int_dist, int_time, c='orange', s=150)
ax.scatter(ext_dist, ext_time, c='black', s=150)
ax.set_yticks(tick_location)
ax.set_yticklabels(time)
plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.ylabel('Time')
plt.title('Seems to work...')
plt.show()

rawDescription: Fixed y axis in Python plotting times in 12 hr format


code:
import re
text = r'''    20530 mark@ucvxcx.gov
    20530 kidafd@gmail.com
    20530 vladfeodsaf@usdodfaadj.govv
    20530 syadfadsbil.vvbvx@vnvnvn.gov
    20004 safdbnvis9dfg@infdda.gov
    20530 vhlhsdlf8dlfha@vbvbcxbUI.GOV
    90012-3308  h.james@asdfad.gov
    90012-3308  madsfl.hjlkdjd@pkdoi.gov
    90012 mark.fraser@ruskgb.zx'''
re.compile(r'([\d\-]+)\s+[\w@\.]+').findall(text)

rawDescription: Data Nitro and regular expression (Python)


code:
from somewhere import something

@app.route('/')
def index():
    return render_template('index.html', something=something)

rawDescription: Get a reference to a list in a python module and iterate over it


code:
import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

rawDescription: Python replace multiple strings

description: Python replace multiple strings


code: result = ', '.join(iterable)

rawDescription: Does python have an equivalent to C#'s Enumerable.Aggregate?


code:
import pygame
from pygame.locals import *

import math
import numpy

def generate_sound(freq):

    #setup our numpy array to handle 16 bit ints, which is what we set our mixer to expect with "bits" up above
    buf = numpy.zeros((n_samples, 2), dtype = numpy.int16)
    max_sample = 2**(bits - 1) - 1

    for s in range(n_samples):
        t = float(s)/sample_rate    # time in seconds
        buf[s][0] = int(round(max_sample*math.sin(2*math.pi*freq*t)))        # left
        buf[s][1] = int(round(max_sample*0.5*math.sin(2*math.pi*freq*t)))    # right

    return pygame.sndarray.make_sound(buf)

bits = 16
#the number of channels specified here is NOT
#the channels talked about here http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_num_channels

pygame.mixer.pre_init(44100, -bits, 2)
pygame.init()

size = (1200, 720)
screen = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF)

duration = 1.0          # in seconds

#this sounds totally different coming out of a laptop versus coming out of headphones

sample_rate = 44100

n_samples = int(round(duration*sample_rate))

#default frequency - not used
sound = None
sound_261_6 = generate_sound(261.6)
sound_293_7 = generate_sound(293.7)

#This will keep the sound playing forever, the quit event handling allows the pygame window to close without crashing
_running = True
while _running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            _running = False

        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                _running = False
            elif event.key == K_a:
                if not sound:
                    sound = sound_261_6
                    sound.play()

            elif event.key == K_s:
                if not sound:
                    sound = sound_261_6
                    sound.play()

        if event.type == KEYUP:
            if sound:
                sound.stop()
                sound = None

pygame.quit()

rawDescription: Placeholder to set different frequencies of sin wave output to each key press


code:
def reverse(self, copy=True):
    """Return the reverse of the graph.

    The reverse is a graph with the same nodes and edges
    but with the directions of the edges reversed.

    Parameters
    ----------
    copy : bool optional (default=True)
        If True, return a new DiGraph holding the reversed edges.
        If False, reverse the reverse graph is created using
        the original graph (this changes the original graph).
    """
    if copy:
        H = self.__class__(name="Reverse of (%s)"%self.name)
        H.add_nodes_from(self)
        H.add_edges_from( (v,u,deepcopy(d)) for u,v,d
                          in self.edges(data=True) )
        H.graph=deepcopy(self.graph)
        H.node=deepcopy(self.node)
    else:
        self.pred,self.succ=self.succ,self.pred
        self.adj=self.succ
        H=self
    return H

rawDescription: Overhead in networkx reverse function?

description: Overhead in networkx reverse function


code:
from os import listdir
from os.path import isfile, join
files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

rawDescription: How to know when the last file in a directory python

description: Know when the last file in a directory python


rawDescription: Python: have a user-defined function as an input while keeping the source-code inaccessible?


code: w = Worm(screen, width/2, height/2, 100, (4,4)) # REVISED

rawDescription: colliderect() triggers unexpectedly

description: Colliderect() triggers unexpectedly


code:
while pygame.mixer.music.get_busy():
    pygame.time.Clock().tick(30000)
    # you can break out the loop and change the file to be played after this.

rawDescription: How to play multiple mp3 files one after the other using pygame?

description: Play multiple mp3 files one after the other using pygame


rawDescription: Read into a bytearray at an offset?

description: Read into a bytearray at an offset


rawDescription: Filter pandas dataframe based on values in multiple columns


code:
import os
import subprocess

proc = subprocess.Popen(cmd, shell=True)
pid, sts = os.waitpid(proc.pid, 0)

# you may check on this process later and kill it if it's taking too long
if proc.poll() in [whatever, ...]:
    os.kill(proc.pid)

rawDescription: Python os.system() automaticly exit when command is not finished yet


rawDescription: Python: unpacking string of integers to complex numbers


rawDescription: Using same function as instance and classmethod in python


code:
class DictArray:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._data = {}

    def _validate_coords(self, x, y):
        if not (0 <= x < self.width and 0 <= y < self.height):
            raise IndexError((x, y))

    def __getitem__(self, x_y):
        self._validate_coords(*x_y)
        return self._data.get(x_y, 0)

    def __setitem__(self, x_y, value):
        self._validate_coords(*x_y)
        if value == 0:
            try:
                del self._data[x_y]
            except KeyError:
                pass
        else:
            self._data[x_y] = value

rawDescription: Hashing in Python dictionaries

description: Hashing in Python dictionaries


code:
def sort_id(var):
    return var[0]
def sort_game1(var):
    return var[1]
def sort_game2(var):
    return var[2]

sorted(user_scores, key = sort_id) # gets sorted on id
sorted(user_scores, key = sort_game1) # gets sorted on game 1
sorted(user_scores, key = sort_game2) # gets sorted on game2

rawDescription: User inputs values; need to store them in array without numpy and sort based on columns-Python


rawDescription: How to change a string to hex

description: Change a string to hex


code:
import json

people = json.load(open("authors.json"))

for person in people:
    author = person.get('author')
    # If there is no author key then author will be None
    if not author:
        # Try to get the first name and last name
        fname, lname = person.get('authorFirstName'), person.get('authorLastName')
        # If both first name and last name keys were present, then combine the data into a single author name
        if fname and lname:
            author = "{} {}".format(fname, lname)

    # Now we either have an author because the author key existed, or we built it from the first and last names.
    if author is not None:
        print("Author is {}".format(author))
    else:
        print("{} does not have an author".format(person))

rawDescription: Python, properly handle Key Errors when parsing JSON object


code:
#!/usr/bin/python

import csv
import re

file2_list = []

with open('2.csv', 'r') as fh2:
    reader = csv.reader(fh2)
    for row in reader:
        if re.search(r'\d', row[0]):
            file2_list = row
            break

with open('1.csv', 'r') as fh1:
    reader = csv.reader(fh1)
    for row in reader:
        if not re.search(r'[^\d]', row[0]):

            result = []

            for i,v in enumerate(row):
                result.append(int(v) * int(file2_list[i]))

            print(sum(result))

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


code: "/directory/date/2011/2009-01-11 This is a file's path/file.MOV"

rawDescription: Fastest way to replace elements of a file's path and extension?


code:
class MyView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(MyClass, self).get_context_data(**kwargs)
        context['new_key'] = self.some_custom_method()
        return kwargs

rawDescription: understanding python self and init

description: Understanding python self and init


code: List1[:] = [sub * c[sub[0]]+sub for sub in List1]

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


code:
class DeprecationHelper(object):
    def __init__(self, new_target):
        self.new_target = new_target

    def _warn(self):
        from warnings import warn
        warn("Get with the program!")

    def __call__(self, *args, **kwargs):
        self._warn()
        return self.new_target(*args, **kwargs)

    def __getattr__(self, attr):
        self._warn()
        return getattr(self.new_target, attr)

OldClsName = DeprecationHelper(NewClsName)

rawDescription: How to warn about class (name) deprecation

description: Warn about class (name) deprecation


code:
serverMBean = getMBean("Servers/"+ServerName)
serverMBean.setCluster(None)
serverMBean.setMachine(None)
delete(ServerName,'Server')

rawDescription: Anyone tried Cluster automation with WLST?


code:
if selection == 2:
    members = add_member(members)

rawDescription: Reload a function in python?

description: Reload a function in python


code:
investor = Investor.objects.all()[0]
investor.categories.add(category_instance_one, category_instance_two)
investor.categories.all() # retrieves all categories that this investor has

rawDescription: Adding multiple tags to model

description: Adding multiple tags to model


code: data['title'] = data.apply(lambda row: "Sheet{}_Row{}_Column{}_Cell{}".format(row['Sheet'], row['Row'], row['Column'], row['Cell']) , axis=1)

rawDescription: New column from previous columns in Pandas


rawDescription: Sphinx autodoc functionality on Python-C-Extension


code:
assert to_name("abcd123") == "abcd123"
assert to_name("Lorem ipsum dolor sit amet") == "lorem_ipsum_dolor_sit_amet"
assert to_name(u"unicode-żółć") == "unicode_____"
assert to_name("123abcd") == "_23abcd"

rawDescription: Arbitrary string to valid Python name

description: Arbitrary string to valid Python name


rawDescription: Can I sort text by its numeric value in Python?

description: Sort text by its numeric value in Python


rawDescription: How to sort a dictionary by descending order numerically

description: Sort a dictionary by descending order numerically


code:
import pylab as pl

palette = pl.array([[180, 0, 0], [255, 150, 0], [255, 200, 0], [0, 128, 0]])

img = pl.imread('lena.jpg')[:, :, :3].astype('float')
R, G, B = img[:, :, 0].copy(), img[:, :, 1].copy(), img[:, :, 2].copy()
dist = pl.inf * R

for i in range(len(palette)):
    new_dist = pl.square(img[:, :, 0] - palette[i, 0]) \
             + pl.square(img[:, :, 1] - palette[i, 1]) \
             + pl.square(img[:, :, 2] - palette[i, 2])
    R[new_dist < dist] = palette[i, 0]
    G[new_dist < dist] = palette[i, 1]
    B[new_dist < dist] = palette[i, 2]
    dist = pl.minimum(dist, new_dist)

pl.clf()
pl.subplot(1, 2, 1)
pl.imshow(img.astype('uint8'))
pl.subplot(1, 2, 2)
pl.imshow(pl.dstack((R, G, B)))

rawDescription: Working on multidimensional arrays

description: Working on multidimensional arrays


code:
import itertools as IT
groupby = IT.groupby
def using_groupby(a):
    return [list(v) for k,v in groupby(a,np.isfinite) if k]

rawDescription: numpy: split 1D array of chunks separated by nans into a list of the chunks

description: Numpy: split 1D array of chunks separated by nans into a list of the chunks


code:
for week in range(nb_week):
    for day in daysofweek:
        hour = -1
        while hour < 0 or hour > 24:
            hour = input("Enter the number of hours for week " +str(week) + " " + day + ": ")
        hours[week, day] = hour

rawDescription: Python: nested loops not behaving how I want them to


code:
forms.py

class Form(forms.Form):
    field_1a = forms.CharField()
    field_1b = forms.CharField()
    field_2a = forms.CharField()
    field_2b = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(Form, self).__init__(*args, **kwargs)
        helper1 = FormHelper()
        helper1.form_tag = False
        helper1.layout = Layout(
            Div(
                Field('field_1a'),
                Field('field_1b')
            )
        )

        helper2 = FormHelper()
        helper2.form_tag = False
        helper2.disable_csrf = True
        helper2.layout = Layout(
            Div(
                Field('field_2a'),
                Field('field_2b')
            )
        )

rawDescription: Django Crispy Form Split Field Layouts

description: Django Crispy Form Split Field Layouts


code: nw = word[:i] + x + word[i+1:]

rawDescription: word ladder in python

description: Word ladder in python


code:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10,10))
data[[2, 5, 7], [5, 8, 1]] = np.nan

plt.imshow(data)
plt.show()

rawDescription: cleaning blurred border between good and bad data in matplotlib imshow

description: Cleaning blurred border between good and bad data in matplotlib imshow


code:
s = 'hey-you...are you ok?'
re.split("["+"\\".join(d)+"]", s)

rawDescription: Python removing delimiters from strings

description: Python removing delimiters from strings


code:
import tkinter

root = tkinter.Tk()
nos = tkinter.Entry()
nos.pack()

def getnum():
    nums = int(nos.get())
    print (nums)
but = tkinter.Button(text = 'enter', command = getnum).pack()

root.mainloop()

rawDescription: How to store numbers from a tkinter entrybox into an existing variable?

description: Store numbers from a tkinter entrybox into an existing variable


code:
import csv

with open('transposed.csv', 'wb') as destfile:
    writer = csv.writer(destfile)
    writer.writerow(['time', 'device', 'value'])
    with open('data.csv', 'rb') as sourefile:
        for d in csv.DictReader(sourcefile):
            time = d.pop('time')
            for device, value in sorted(d.items()):
                row = [time, device, value]
                writer.writerow(row)

rawDescription: Python - Transpose columns to rows within data operation and before writing to file


code:
low = np.inf
high = -np.inf

# find the overall min/max
for chunk in pd.read_table('/path/to/my/dataset.txt', header=None, chunksize=1000):
    low = np.minimum(chunk.iloc[:, 2].min(), low)
    high = np.maximum(chunk.iloc[:, 2].max(), high)

rawDescription: How to build (or precompute) a histogram from a file too large for memory?

description: Build (or precompute) a histogram from a file too large for memory


code: blocks.groupby('name').apply(lambda x: (x.index[0], x.index[-1]))

rawDescription: distinct contiguous blocks in pandas dataframe

description: Distinct contiguous blocks in pandas dataframe


code:
user = User('Bob')
user.name
user.update('name', 'Rob')
user.name
user.insert('age', 12)
user.age

rawDescription: How is it possible to access fields of a class in its base class?


code:
from pprint import pprint
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
pprint(mydict)
d = dict(zip("kjihgfedcba",range(11)))
pprint(d)

rawDescription: Readably print out a python dict() sorted by key


code:
tables = [t for t in soup.select('table.main')
          if not t.find_parents('table', class_='main')]

rawDescription: Select tag which are not already selected as descendants of the same elements


code: timeit.timeit(stmt='functions.function(list)', setup='import functions; list = gets list from file', number=100)

rawDescription: Timing python function

description: Timing python function


rawDescription: module holding variables, mutable vs immutable

description: Module holding variables, mutable vs immutable


code:
class BaseClass(object):
    def m1(self):
        return 1

class MyClass(BaseClass):
    def m1(self):
        return super(MyClass, self).m1()

rawDescription: Python : method resolution order of old-style (or classic) and new-style objects


code:
ts = pd.Series( [True, True, False, False, True, True, True, False, True ] )
pd.rolling_sum( ts, window=2 ) >= 2

rawDescription: More Efficient way to check values of neighboring rows in pandas dataframe for stock backtesting


rawDescription: Python nested for loop in RGB average

description: Python nested for loop in RGB average


code:
class Segmentation_Form(ModelForm):
    Rules = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=models.segmentation_Rules.Segmentation_Rules_CHOICES)

rawDescription: Show multiple choices to admin in django


code:
from sklearn.feature_extraction.text import CountVectorizer
ngram_vectorizer = CountVectorizer(analyzer="word", ngram_range=(2,2),
                                   token_pattern=u"(?u)\\b\\w+\\b",min_df=1)
ngram_vectorizer.fit_transform(['HE GAVE IT TO I'])
print(ngram_vectorizer.get_feature_names())

rawDescription: CountVectorizer ignoring 'I'

description: CountVectorizer ignoring 'I'


code:
l = [True, "and", False, "or", False, "or", False, "or", True, "and", False, "or", False, "or", False]
eval(' '.join([ str(z) for z in l]))

rawDescription: Easy way to check precedence of ( "and", "or") in python


code:
from lxml import html

x = html.fromstring(h)
div = x.xpath("//*[@id='ANALYSIS']")[0]
out = [b.text + "," +  b.xpath("./following::text()[1]")[0].lstrip(",") for b in div.xpath(".//b[@class='black']")]

rawDescription: Python: pulling bold text and the text that follows


code:
from __future__ import division

maxval = a[-1]
weights = [elem / maxval for elem in a]

rawDescription: Change from list of integers to weights between 0 and 1?


code: return self.from_float(p)

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

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


code: dir(module)

rawDescription: How to find out what methods, properties, etc a python module possesses

description: Find out what methods, properties, etc a python module possesses


code: print("".join(["Y" if randomNumber[ind]==ele else "N"  for ind, ele in enumerate(Guess)]))

rawDescription: Python multiple number guessing game

description: Python multiple number guessing game


code:
from string import Template
t = Template("$filename $directory $counter")
t.substitute(filename="file.py", directory="/home", counter=42)
t.substitute(filename="file2.conf", directory="/etc", counter=8)

rawDescription: Python library for string formatting with custom placeholders


rawDescription: Remove formatting from strings

description: Remove formatting from strings


code:
for person, ages, residency in zip(name,age,resident):
    if residency == 0:
        print("name is {0}, age is {1} and they do not live in place".format(person, ages))

rawDescription: Searching lists then calling same place from other lists


code:
import sys, time

sys.stdout.write(sys.argv[1] + " start time\t" + str(time.time()) + '\n')
time.sleep(2)
sys.stdout.write(sys.argv[1] + " end time\t" + str(time.time()))

rawDescription: Recover output of 2 python scripts with subprocess


rawDescription: PyQt4 application: buttons suddenly no longer works


code: df['dummy'] = 0

rawDescription: How do I get the index of each item in a groupby object in Pandas?

description: Get the index of each item in a groupby object in Pandas


rawDescription: Disregarding a line while calculating frequency in python


code:
a = np.array(['ABC', 'D', 'EFGHI'])
array_view = a.view('uint8').reshape(a.size, a.dtype.itemsize)
abc(array_view)

rawDescription: cython: memory view of ndarray of strings (or direct ndarray indexing)

description: Cython: memory view of ndarray of strings (or direct ndarray indexing)


code:
from distutils.core import setup
import py2exe

setup(script_args = ['py2exe'],
      windows=[{'script':'test.py'}],
      options = {'py2exe': {'compressed':1,
                            'bundle_files': 1,
                            'excludes': ['Tkconstants', 'Tkinter']
                            },
                 },
      zipfile = None)

rawDescription: Using Numpy creates a tcl folder when using py2exe


code:
dwarf_items = {'coins': 30, 'power': 11, 'Knives': 20, 'beer': 10, 'pistol': 2}
caves = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
drop_chance = 0.4  # change this to make it more or less likely an item will drop
cache = {}
for cave in caves:
    if dwarf_items and random.random() < drop_chance:
        item = random.choice(dwarf_items.keys())
        cache[cave] = {item: dwarf_items.pop(item)}
    else:
        cache[cave] = {}

rawDescription: Combine dictionary

description: Combine dictionary


code:
data
reference

rawDescription: Classify elements of a numpy array using a second array as reference


code: 6 /dev/fd/3

rawDescription: use subprocess.Popen to run a unix tool that requires multiple input redirects

description: Use subprocess.Popen to run a unix tool that requires multiple input redirects


code:
l = [['g,g', 'g,g'], ['d,d', 'd,d,d', 'd,d'], ['s,s', 's,s']]
output = [ (x, y, z, v) for z, l1 in enumerate(l[::-1]) for y, l2 in enumerate(l1) for x, v in enumerate(l2.split(',')) ]

rawDescription: Python: converting a nested list into a simple list with coord positions


rawDescription: Django dynamic model fields

description: Django dynamic model fields


code:
with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

rawDescription: What is an alternative to execfile in Python 3.0?


code:
class TimelineViewSet(viewsets.ModelViewSet):
    """
    API endpoint that lists all tweet/article objects in rev-chrono.
    """
    def list(self, request):
        queryset = list(itertools.chain(Tweet.objects.all(), Article.objects.all()))
        serializer = TimelineSerializer(queryset, many=True)
        return Response(serializer.data)

rawDescription: Return results from multiple models with Django REST Framework


code:
import re
shipname = soup.find_all('tr', class_="attacker")[0].find_all('a', href=re.compile('/ship/'))[0].img.get('alt')

rawDescription: How do I efficiently web-scrape these abnormal values?

description: Efficiently web-scrape these abnormal values


code:
a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

rawDescription: Python list iterator behavior and next(iterator)


code:
grey = im.convert('L')
width,height = im.size
impix = im.load()
whitepix = white.load()
greypix = grey.load()
for y in range(height):
    for x in range(width):
        greypix[x,y] = min(255, max(255 * impix[x,y][0] / whitepix[x,y][0], 255 * impix[x,y][2] / whitepix[x,y][3], 255 * impix[x,y][4] / whitepix[x,y][5]))

rawDescription: What processing steps should I use to clean photos of line drawings?


code:
import functools

def f(n, z, max_depth, factors=(), depth=0):
    res = []
    if depth == max_depth:
        product = functools.reduce(lambda x, y: x*y, factors, 1)
        if product > z:
            res.append(factors)
    else:
        for i in range(1, n):
            new_factors = factors + (i,)
            res.extend(f(i, z, factors=new_factors, depth=depth+1, max_depth=max_depth))
    return res

z = np.e ** 10
n = int(np.log(z))

print(f(n, z, max_depth=8))

rawDescription: Arbitrary number of nested loops dependent on the previous loop in Python


code: YYYdefdef

rawDescription: Unable to read huge (20GB) file from CPython


code:
list1 = ["a","b","c"]
dict1 = {7:"d",8:"e",9:"f"}
dict1.update(dict(enumerate(list1)))
dict1

rawDescription: How to add list to dictionary by using index of list as key and item of list as value?

description: Add list to dictionary by using index of list as key and item of list as value


rawDescription: Why can two functions with the same `id` have different attributes?


code:
seen = set()
b = [t for t in a if tuple(sorted(t)) not in seen and not seen.add(tuple(sorted(t)))]

rawDescription: Find unique tuples in a list(ignore order) while preserving the others' original order in python?


code:
from functools import reduce
print(reduce(lambda x, y: x + 1, myString, 0))

rawDescription: Reading the length of a string without using a built-in function?


rawDescription: Algorithm in Python To Solve This Problem


code:
class Node(object):
    __slots__ = ('x', 'y')

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

    def __repr__(self):
        return '{0.__class__.__name__}({0.x!r}, {0.y!r})'.format(self)

rawDescription: Use _replace method of namedtuple to update the fields of other data structures containing the nt


code:
from functools import partial

class WhateverThisIs(object):

    ...

    @staticmethod
    def validate_card(card, duration=None):
        if card.emergency_level != 'first':
            return False
        if duration is not None and card.duration <= duration:
            return False
        return True

    def countEmergency(self, card_ids, duration=None):
        return len(filter(partial(self.validate_card, duration=duration), card_ids))

rawDescription: Python - adding conditions in if only they are specified (domain)?


code:
Output
['text0 text1', ['item1', 'item2', ['sub1', 'sub2']], 'text2 sib']

rawDescription: Python, lxml - access text

description: Python, lxml - access text


code:
weapon = []
bool(weapon) == True
weapon.append("sword")
bool(weapon) == True

rawDescription: Why is a list containing objects False when value tested?


code:
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

description: VtkRenderWindowInteractor stalling program


code:
if something:
    do_stuff()

rawDescription: PYTHON - Restart same for loop iteration


code:
d1 = { 'a': 1, 'b': 2, 'c': 3 }
d2 = { 'a': 1, 'b': 5, 'd': 4 }
d3 = {}
def add_dict(target, d):
    for key in d:
        target.setdefault(key, set([])).add(d[key])

add_dict(d3, d1)
add_dict(d3, d2)

rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


rawDescription: Custom Django template tag to look up a string username and return it as a user object


rawDescription: Vectorized Splitting of String on Character Count using Numpy or Pandas


code:
[{"name": "ACCA - Association of Chartered Certified Accountants"},
{"name": "Accounting"},
{"name": "Accounting"},
{"name": "Accounting and Advertising"},
{"name": "Accounting and Human Resource Management"},
{"name": "Accounting and Law"},
{"name": "Accounting and Management"},
{"name": "Accounting and Managerial Finance"},
{"name": "Accounting and Marketing"},
{"name": "Accounting with Finance"},
{"name": "Advertising"},
{"name": "Advertising and Human Resource Management"},
{"name": "Advertising with Computing"},
{"name": "Advertising with Drama"},
{"name": "Advertising with Human Resource Management"},
{"name": "Advertising with Psychology"},
...]

rawDescription: Crawl spider not crawling ~ Rule Issue

description: Crawl spider not crawling ~ Rule Issue


code:
from xml.dom import minidom
def newwritexml(self, writer, indent= '', addindent= '', newl= ''):
    if len(self.childNodes)==1 and self.firstChild.nodeType==3:
        writer.write(indent)
        self.oldwritexml(writer) # cancel extra whitespace
        writer.write(newl)
    else:
        self.oldwritexml(writer, indent, addindent, newl)

minidom.Element.oldwritexml= minidom.Element.writexml
minidom.Element.writexml= newwritexml

rawDescription: Python xml minidom. generate <text>Some text</text> element


code:
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)
while True:
    try:
        wait.until(EC.presence_of_element_located((By.XPATH, "//select[@name='servers']/option")))
    except TimeoutException:
        break
    # rest of the code

rawDescription: While statement not evaluating to false for Selenium Webdriver


code: df['NAMES'], df['NAME_NBR'] = zip(*[s.split('_') for s in df['NAMES']])

rawDescription: How to move duplicate rows into columns with python

description: Move duplicate rows into columns with python


code:
sql='''
SELECT p.price, t.date
FROM ( {t} ) t
LEFT JOIN price p
ON p.date = t.date
WHERE p.id = ?
'''.format(t=' UNION ALL '.join('SELECT {d!r} date'.format(d=d) for d in date))

cursor.execute(sql,[id])
result=cursor.fetchall()

rawDescription: Query Sqlite for multiple arguments at once and handling missing values


code:
import numpy as np
import pandas as pd

ns5min=5*60*1000000000   # 5 minutes in nanoseconds
pd.DatetimeIndex(((df.index.astype(np.int64) // ns5min + 1 ) * ns5min))

rawDescription: Pandas: Timestamp index rounding to the nearest 5th minute


code:
with open(filename, 'r') as f:
    contents = f.read()

rawDescription: How to use the same line of code in all functions?

description: Use the same line of code in all functions


code:
import csv
import collections

def unique():
    rows = list(csv.reader(open('try.csv', 'r'), delimiter=','))
    result = collections.OrderedDict()
    for r in rows:
        key = (r[1],r[6])  ## The pair (r[1],r[6]) must be unique
        if key not in result:
            result[key] = r

    return result.values()

from pprint import pprint
pprint(unique())

rawDescription: Python to extract unique CSV rows

description: Python to extract unique CSV rows


code:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from satchmo_store.contact.models import Organization

class MyOrganization(Organization):
    vat_number   = models.CharField(_('VAT'), max_length=12)

rawDescription: Insert a new field in a specific admin view?


code:
def anno(*args):
    for idx in xrange(248956422):
        elm = "0"

        for st, end, tag in args:
             for j in range(0, len(st)):
                 if st <= idx < end[j]:
                      elm = tag

        yield tag

rawDescription: Memoryerror with too big list

description: Memoryerror with too big list


code:
import pywinauto
app = pywinauto.Application().connect_(path='process_name.exe')
app.MainDialog.ClickInput(coords=(953, 656))

rawDescription: Python: Click by coordinate inside a window


code:
# datetimeindex makes convenient manipulations
date = pd.DatetimeIndex(df1['date'])

# compute df2: totals by month
df1['month'] = date.to_period('M')
df2 = df1[df1['is_buy'] == 1].groupby(['id', 'month']).sum()

# compute df3: totals by last seven days
from datetime import timedelta
is_last_seven = date.to_period('M') != (date + timedelta(days=7)).to_period('M')
df3 = df1[(df1['is_buy'] == 1) & is_last_seven].groupby(['id', df1.month + 1]).sum()

# join the results
result = df2.join(df3, rsuffix='_last_seven')

rawDescription: pandas count values for last 7 days from each date

description: Pandas count values for last 7 days from each date


code:
a = [ 'x1_{}'.format(x) for x in range(1,101)]
a = zip(a,a)
a = [i for j in a for i in j]

rawDescription: Python: creating string array with integers


code:
# arrays of x- and y-coordinates
velx = np.cos(angles)
vely = np.sin(angles)

# create (x, y) pairs and convert to np.array
vel = np.array(list(zip(velx, vely)))

rawDescription: Defining velocity in a boid simulation

description: Defining velocity in a boid simulation


code:
result = {name:float(val) for name,val in r}
result

rawDescription: Python string parsing name and number

description: Python string parsing name and number


code: [G.edges(component) for component in nx.connected_components(G.to_undirected()) if len(G.edges(component)) > 0 and 'n' not in component]

rawDescription: How to list specific node/edge in networkx?

description: List specific node/edge in networkx


code:
# Create a set of ids from another file
with open("another.txt") as another_file:
    ids = {lin.split(',')[3] for lin in another_file}

with open("mainfile.txt") as file:
    for line in file:
        record_id = line.split(',')[0]
        mas_list.append(record_id)
        # Check if the record_id is in the set of ids from another file
        if record_id in ids:
            mas_list.append("some data")

rawDescription: python nested loop using loops and files

description: Python nested loop using loops and files


code:
tbl = soup.find("table")
out = (tag.find('a') for tag in tbl.find_all("tr")[6:])

for a in out:
    print(a["href"])

rawDescription: BeautifulSoup Iteration not working

description: BeautifulSoup Iteration not working


rawDescription: lexical analysis python

description: Lexical analysis python


code:
if request.is_ajax():
    return json_response
else:
    return HttpResponseForbidden('Only AJAX please!')

rawDescription: Django-ratings and Jquery integration?

description: Django-ratings and Jquery integration


rawDescription: Is it possible for matplotlib's alpha transparency values to "sum" to 1?


code:
import argparse
cmd = argparse.ArgumentParser()
cmd.add_argument('-D', action='append', default = [])
print(cmd.parse_args())

rawDescription: How to parse CMake-style arguments with python argparse?

description: Parse CMake-style arguments with python argparse


code:
def profile(f, currently_evaluating=set()):
    #`currently_evaluating` will persist across all decorated functions, due to "mutable default argument" behavior.
    #see also http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument
    def g(x):
        #don't bother timing it if we're already doing so
        if f in currently_evaluating:
            return f(x)
        else:
            start_time = time.clock()
            currently_evaluating.add(f)
            try:
                value = f(x)
            finally:
                currently_evaluating.remove(f)
            end_time = time.clock()
            print('time taken: {time}'.format(time=end_time-start_time))
            return value
    return g

rawDescription: Python: Counting executing time of a recursion function with decorator


code:
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('author_name', 'text', 'parent')
        widgets = {
            'parent': forms.HiddenInput,
        }

rawDescription: Is any way to create hidden form field in CreateView form?


code:
from random import random

class AlleleGenerator(object):
    def __init__(self, p):
        """construct class and creates list to select from"""
        self.p = p
    def next(self):
        """Returns p or q based on allele frequency"""
        return 'p' if random() < self.p else 'q'
    def __call__(self):
        return self.next()

rawDescription: Robust weighted random string generator

description: Robust weighted random string generator


code: NEW_FIELD = 5    # if the sixth field is the one with the objectionable name

rawDescription: How can I rename the field names of a .dbf file when reading it with dbfpy?

description: Rename the field names of a .dbf file when reading it with dbfpy


code:
if os.path.exists(adresse) :
    with open(adresse,"r") as f,open("temp.csv" "a+") as temp:
        writer = csv.writer(temp,delimiter = ",")
        reader = csv.reader(f , delimiter = ",")
        for ind, line in enumerate(reader):
            if ind == 2:
                continue
            else:
               temp.writerow(line)
        temp.seek(0)
        with open(adresse,"w") as out:
            reader = csv.reader(temp , delimiter = ",")
            writer = csv.writer(out,delimiter = ",")
            for row in reader:
                writer.writerow(line)

rawDescription: How to remove the second line of a CSV file using Python

description: Remove the second line of a CSV file using Python


code: frames = [a, b, c]

rawDescription: Concatenate Pandas DataFrames with Multiindex columns and irregular timestamps


rawDescription: Using Flask-SQLAlchemy in Blueprint models without reference to the app


code:
import re
s = "2839 WYATT WY"
re.sub(r'\bWY$', 'WAY', s)

rawDescription: How do I replace a portion of a string using python regex

description: Replace a portion of a string using python regex


code:
# untested
def json_expandvars(o):
    if isinstance(o, dict):
       return {json_expandvars(k): json_expandvars(v) for k, v in o.items()}
    elif isinstance(o, list):
       return [json_expandvars(v) for v in o]
    elif isinstance(o, basestring):
       return os.path.expandvars(o)
    else:
       return o

json_dict = json_expandvars(json.loads(json_str))

rawDescription: How to expand environment variable in python while escaping special characters?

description: Expand environment variable in python while escaping special characters


code:
def uploadmodel_file_upload_to(instance, filename):
    return '%s/%s/%s' % (settings.PROTECTED_MEDIA_ROOT, instance.user.username,
        filename)

rawDescription: protecting user uploaded files django

description: Protecting user uploaded files django


code:
s = io.StringIO('abcZZZdefZZZghiZZZjklZZZmnoZZZpqr')
d = delimited(s, 'ZZZ', bufsize=2)
list(d)

rawDescription: How to read records terminated by custom separator from file in python?

description: Read records terminated by custom separator from file in python


code:
mls = unary_union(lr)
mls.geom_type  # MultiLineString'

rawDescription: Splitting self-intersecting polygon only returned one polygon in shapely in Python


code: return '{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)

rawDescription: How can I display timedelta in hours:min:sec?

description: Display timedelta in hours:min:sec


code:
[
    'ls -l /dev',
    'ls -l /home/dir',
    'ls -l /home/ramana/',
    'ls -l /home/ramana/xyz/',
    'ls -l /home/ramana/xyz/abc',
    'ls -l /home/ramana/xxx/',
    'ls -l /home/ramana/xxx/def'
]

rawDescription: How to avoid redundancy when sending commands via pexpect?

description: Avoid redundancy when sending commands via pexpect


code:
def changeColour(widget):
    widget.config(bg="white")

#...

LM = Button(root, width=16, height=8, bg = "red", command = lambda: changeColour(LM))
LM.place(x=10, y=150)

rawDescription: How can I configure multiple buttons with one function in Tkinter?

description: Configure multiple buttons with one function in Tkinter


code:
urlpatterns = patterns('locate.views.views',
    url(r'^',  'index'),
)

rawDescription: Django sub-directory views and import all files from __init__.py


code:
largest = components.pop(0)
num_isolated = G.order() - len(largest)

rawDescription: Find and count the number of isolated and semi-isolated nodes in a network


code: script, first, second, third = argv

rawDescription: Python terminology: things to left of "= argv" in Learn Python the Hard Way exercise 13


code:
TEMPLATE_DIRS = (
    # Don't forget to use absolute paths, not relative paths.
    "/path/to/Projects/templates",
    #other dirs ...
)

rawDescription: How do you extend a Django project root HTML file in project apps?

description: Extend a Django project root HTML file in project apps


rawDescription: Cycle Through List Items

description: Cycle Through List Items


code:
values = {}
with open('file2.txt') as in_:
    for _ in range(3):
        # This is ugly, but it's a quick hack. I'd improve it later.
        cur_dict = next(in_).strip()
        values[cur_dict] = {}
        for __ in range(4):
            key, value = next(in_).strip().split(',')
            values[cur_dict][key] = int(value)

rawDescription: Manipulating text files

description: Manipulating text files


code:
import gzip
from subprocess import Popen, PIPE
from threading import Thread

def f(input, output):
    for line in iter(input.readline, ''):
        output.write(line)

p = Popen(["sort"], bufsize=-1, stdin=PIPE, stdout=PIPE)
Thread(target=f, args=(p.stdout, gzip.open('out.gz', 'wb'))).start()

for s in "cafebabe":
    p.stdin.write(s+"\n")
p.stdin.close()

rawDescription: python subprocess with gzip

description: Python subprocess with gzip


code: count

rawDescription: Compare Characters Within a String

description: Compare Characters Within a String


code:
Metaclass
def set_properties_meta(properties):
    def meta(name, bases, attrs):
        cls = type(name, bases, attrs)
        set_pyqtproperties(cls, properties)
        return cls
    return meta

rawDescription: Can anyone help condense this Python code?


rawDescription: Unexpected behaviour of np.sum which acts as np.ravel


rawDescription: Python combine overlapping time ranges in csv file


code:
def with_callback(control, fun):
    def inner():
        return fun(control)
    control['command'] = inner
    return control

...
b = with_callback(Button(text="click me"), test_callback)

rawDescription: How to return instance of button pressed in Python-based TKinter

description: Return instance of button pressed in Python-based TKinter


code: df['kw']

rawDescription: mixing 3 dimenional and 2 dimensional data in a pandas dataframe

description: Mixing 3 dimenional and 2 dimensional data in a pandas dataframe


rawDescription: Use same string format for multiple items in Python 3


code: instance_method = f.method

rawDescription: Different way to create an instance method object in Python


code:
def api(request):
  jobnum = request.GET.get('jobnum')
  job_list = Job.objects.filter(jobnum=jobnum)
  json_data = job_list.values()
  return HttpResponse(json_data)

rawDescription: Using jquery variable to get specific ajax request


code:
up = arr > threshold
new_arr = np.zeros_like(arr)
new_arr[up] = 255

rawDescription: What's the fastest way to threshold a numpy array?


code: user_input_list = input("Enter your name and age:").split(' ')

rawDescription: How to assign user input to a variable or list

description: Assign user input to a variable or list


code:
lst = (1,2,3)
all(isinstance(n, int) for n in lst)
lst = (1,2,'3')
all(isinstance(n, int) for n in lst)

rawDescription: Test type of elements python tuple/list

description: Test type of elements python tuple/list


code:
for row in data.splitlines():
    args = [int(u) for u in row.split('x')]
    func(*args)

rawDescription: How to pass several arguments to a function from a list in Python line by line

description: Pass several arguments to a function from a list in Python line by line


code:
with con:
    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute(
        "select u.user_id, t.type_id, sum(u.preference)/count(u.preference)"
        "from user_preference u, item_type_pairs t"
        "where t.item_id = u.item_id group by u.user_id, t.type_id;"
    )
    rows = cur.fetchall()

rawDescription: How to transfer SQL Group by results to a Pandas dataframe

description: Transfer SQL Group by results to a Pandas dataframe


code:
[('Load-Files', 'a,b,c'), ('Export-Files', 'x,y,z')]

# Python code starts here
while 1:
    do_stuff()

rawDescription: Reading raw section with ConfigParser

description: Reading raw section with ConfigParser


code:
array
array + np.array([5, 10])

rawDescription: Python Numpy Addition

description: Python Numpy Addition


code: df

rawDescription: reshape dataframe from multiple columns to one

description: Reshape dataframe from multiple columns to one


code: args.foo = 'bar'

rawDescription: Confusing code involving lambda function


rawDescription: Selenium: get coordinates or dimensions of element with Python


code:
class loginWindow(Toplevel):
    def __init__(self, title, parent):
        Toplevel.__init__(self, parent)
        ...

    def login(self):
       if access:
            # Close Toplevel window and lunch root window
            self.destroy()
            main()

class main(Toplevel):
    def __init__(self, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)
        ...

root = Tk()
root.withdraw()

loginWindow('title', root)

root.mainloop()

rawDescription: Two windows: First Login after that main program


rawDescription: "tkinter.filedialog" does not recognize files without a suffix in its name


code:
def average_data(list_of_tuples):

    stock_data = [float(t[1]) for t in list_of_tuples]
    stock_sum = sum(stock_data)
    return stock_sum / len(list_of_tuples)

rawDescription: Averaging a list of tuples from CSV file


code:
from mock import patch

@patch("package.function")
def test():
    do_stuff()

rawDescription: Automocking for Python?

description: Automocking for Python


code:
import sys
sys.modules['world'] = __import__('fakeworld')
execfile('example1.py')

rawDescription: How to suppress execution of statement in script called with execfile?

description: Suppress execution of statement in script called with execfile


rawDescription: Django sort queryset according to related objects


code:
from importlib import import_module

# e.g., test("gupshup")
def test(modulename):
    module = import_module(module_name)
    module.test()

rawDescription: How do I import a module only when needed?

description: Import a module only when needed


rawDescription: function_exists in PHP for python3

description: Function_exists in PHP for python3


code:
with open('spam.adpcm', 'rb') as f:
    state = None
    while True:
        adpcm = f.read(BLOCKSIZE)
        if not adpcm:
            return
        pcm, state = audioop.adpcm2lin(adpcm, 2, state)
        yield pcm

rawDescription: Play ADPCM streams with Pygame

description: Play ADPCM streams with Pygame


rawDescription: Deleting a character in an element of a 2D list in Python


rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


code:
def remove_last_element(iterable):
    iterator = iter(iterable)
    try:
        prev = next(iterator)
        while True:
            cur = next(iterator)
            yield prev
            prev = cur
    except StopIteration:
        return

rawDescription: Python scan file line by line and remove last line in the same loop


code:
import numpy as np
from mayavi import mlab

X = np.array([0, 1, 0, 1, 0.75])
Y = np.array([0, 0, 1, 1, 0.75])
Z = np.array([1, 1, 1, 1, 2])

# Define the points in 3D space
# including color code based on Z coordinate.
pts = mlab.points3d(X, Y, Z, Z)

# Triangulate based on X, Y with Delaunay 2D algorithm.
# Save resulting triangulation.
mesh = mlab.pipeline.delaunay2d(pts)

# Remove the point representation from the plot
pts.remove()

# Draw a surface based on the triangulation
surf = mlab.pipeline.surface(mesh)

# Simple plot.
mlab.xlabel("x")
mlab.ylabel("y")
mlab.zlabel("z")
mlab.show()

rawDescription: Python the simplest way to plot 3d surface


code:
import numpy as np
a = np.array([1, 2, 3, 1])
unique_elements = np.unique(a)
result = unique_elements[..., None] == a
unique_elements
result

rawDescription: Convert 1-D array of discrete values to n-D array of continuous values in Numpy


code:
from itertools import permutations

# Any iterable will do. I am using a tuple.
for permutation in permutations(('a', 'b', 'c')):  # Use your strings
    print(permutation)  # Change print() to whatever you need to do with the permutation

rawDescription: How to run code on all possible combination of 3 strings

description: Run code on all possible combination of 3 strings


code:
q = db.Query(Post)
q.filter('receiver =', uId)

rawDescription: App Engine Data store understanding no Sql


code: p = subprocess.Popen(command_list)

rawDescription: Execute Subprocess in Background

description: Execute Subprocess in Background


rawDescription: Why does the value of a variable changes on appending to python list as a list?


code:
import re
s = "I have a string ^submarine I want to be able to detect ^marines as a match"
kw = "^submarine"
r  = re.compile(r"(?<!\w)[{0}]+(?!\w)".format(re.escape(kw)))
print(r.findall(s))

rawDescription: Efficient unordered substing matching

description: Efficient unordered substing matching


rawDescription: Python script calling PHP script while passing $_GET parameters


code:
if errors.text: # skips empty strings
    fixedText = errors.text.split("\n")[0]

rawDescription: python find if newline is in string

description: Python find if newline is in string


code:
text = "The quick brown fox jumps over the lazy dog"
interval = 3
chunks = [text[idx:idx+interval] for idx in range(0, len(text), interval)]
chunks
term='o'
term_counts = [chunk.count(term) for chunk in chunks]
term_counts
chunks_with_counts = zip(chunks, term_counts)
list(chunks_with_counts)

rawDescription: How can I look inside of different chunks of strings in my Python program?

description: Look inside of different chunks of strings in my Python program


code:
def kmer_count(k,*args):
  f = {}
  for dna in args:
    for x in range(len(dna)+1-k):
        kmer = dna[x:x+k]
        f[kmer] = f.get(kmer, 0) + 1
    yield(f)

rawDescription: Python find kmers in large lists

description: Python find kmers in large lists


code:
def question(attempt, answer):
    score = 0
    #if attempt is true, add 1 to score
    #if attempt is false, do nothing to score
    if attempt == answer:
        score += 1
        return score
    print("Your score is %r." % score)

rawDescription: Where to define variable working with function


code:
if a is None:
    try:
        a = long(_hexlify(_urandom(16)), 16)
    except NotImplementedError:
        import time
        a = long(time.time() * 256) # use fractional seconds

rawDescription: Python's random: What happens if I don't use seed(someValue)?


code: json_obj = {"numFound":1,"start":0,"rows":3,"briefRecords":[{"progressivoId":0,"codiceIdentificativo":"IT\\ICCU\\LO1\\0120590","autorePrincipale":"Savoia, Carlo","titolo":"Per la inaugurazione dell'Asilo infantile Strozzi nei locali della caserma Filippini già convento della Vittoria / parole di mons. Carlo Savoia","pubblicazione":"Mantova : Tip. Eredi Segna, 1870","livello":"Monografia","tipo":"Testo a stampa","numeri":[],"note":[],"nomi":[],"luogoNormalizzato":[],"localizzazioni":[],"citazioni":[]}],"facetRecords":[{"facetName":"level","facetLabel":"Livello bibliografico","facetValues":[["Monografia","m","1"]]},{"facetName":"tiporec","facetLabel":"Tipo di documento","facetValues":[["Testo a stampa","a","1"]]},{"facetName":"nomef","facetLabel":"Autore","facetValues":[["savoia, carlo","savoia, carlo","1"]]},{"facetName":"soggettof","facetLabel":"Soggetto","facetValues":[["mantova - asili infantili","mantova - asili infantili","1"]]},{"facetName":"luogof","facetLabel":"Luogo di pubblicazione","facetValues":[["mantova","mantova","1"]]},{"facetName":"lingua","facetLabel":"Lingua","facetValues":[["italiano","ita","1"]]},{"facetName":"paese","facetLabel":"Paese","facetValues":[["italia","it","1"]]}]}

rawDescription: Parsing a complex JSON object with Python: search a specific key/value pair


code:
def customRound(num, d = [0.0, 0.25, 0.75, 1.0]): # you can change this list to any e.g. [0.0, 0.1, 0.4, 0.9, 1.0]
     dec = num%1
     r = num - dec
     round_dec = min([(abs(i - dec),i) for i in d])[1]
     return r + round_dec

rawDescription: Python Rounding

description: Python Rounding


code:
lobdict = {}
for k in list_dict_vals[0].keys():
   lobdict[k] = cursor.var(cx_Oracle.CLOB, arraysize=len(list_dict_vals))
for rownum, row in enumerate(list_dict_values):
  for key, val in row.iteritems():
     lob = lobdict[key]
     lob.setvalue(rownum, val)
     row[key] = lob
...
InsertChunk()

rawDescription: executemany of CLOB elements on cx_Oracle

description: Executemany of CLOB elements on cx_Oracle


code:
#openserver.py

import sublime, sublime_plugin
import os
import webbrowser
import re
import os2emxpath
import logging
import sys

class OpenserverCommand(sublime_plugin.TextCommand):
   def run(self,edit):
    file_path = self.view.file_name()

    settings = sublime.load_settings('Openserver.sublime-settings')

    file = os2emxpath.normpath(file_path)

    url = re.sub(settings.get('file_path_prefix'), settings.get('url_prefix'), file)
    #logging.warning(url)

    #webbrowser.open_new(url)
    if sys.platform=='win32':
        os.startfile(url)
    elif sys.platform=='darwin':
        subprocess.Popen(['open', url])
    else:
        try:
            subprocess.Popen(['xdg-open', url])
        except OSError:
            logging.warning(url)

rawDescription: Replace string in Python and open browser with result


code:
def draw(x):
    if not hasattr(draw, 'counter'):
         draw.counter = 0
    draw.counter += 1
    #  body

rawDescription: Count number of times function with varying arguments executed, then reset count when ENTER key pressed


code:
cols_to_include = df.columns[~df.columns.str.contains('foo')]
for col in cols_to_include:
  col_unique_count = df[col].nunique()

rawDescription: Conditionally iterate over columns in Pandas


rawDescription: How to extract numbers from string using regular expression in Python except when within brackets?

description: Extract numbers from string using regular expression in Python except when within brackets


code:
def magic_view(request):
    Employee.objects.on(request.company).all()

rawDescription: Django: limiting model data

description: Django: limiting model data


code:
class A(object): pass
class B(A) : pass
a = A()
b = B()

rawDescription: Why use isinstance() instead of type()?

description: Why use isinstance() instead of type()


code: df

rawDescription: Pandas newbie: How do I assign values based on content of columns?


rawDescription: SQLAlchemy ORM Inserting Related Objects without Selecting Them


code: df.values == 'present'

rawDescription: Pandas: extract and select data from columns using a pattern


code:
def f():
   ...
f = category(Test)(f)

rawDescription: How can I know from where the method is called?

description: Know from where the method is called


code:
newlist = []
for x in mylist: # sic!
    newlist.append((x - min_val) / (max_val - min_val))

rawDescription: List is not showing up

description: List is not showing up


code:
from people import Person
from bulbs.neo4jserver import Graph
g = Graph()
g.add_proxy("people", Person)
james = g.people.create(name="James")
james.eid
james.name
james = g.people.get(james.eid)
james.age = 34
james.save()
nodes = g.people.index.lookup(name="James")

rawDescription: How to Emulate Assignment Operator Overloading in Python?


rawDescription: Need a way to load embedded, escaped JSON strings in Python


code:
code = pow(msg, 65537, 5551201688147)               # encode using a public key
plaintext = pow(code, 109182490673, 5551201688147)  # decode using a private key

rawDescription: Private/Public Encryption in Python with Standard Library


code: list(dictionary.keys()) * 3

rawDescription: Extracting keys-values from dictionary

description: Extracting keys-values from dictionary


code:
def is_ascii(s):
    try:
        s.decode('ascii')
        return True
    except UnicodeDecodeError:
        return False

[s for s in ['william', 'short', '\x80', 'twitter', '\xaa',
             '\xe2', 'video', 'guy', 'ray']
 if is_ascii(s)]

rawDescription: How to remove all the escape sequences from a list of strings?

description: Remove all the escape sequences from a list of strings


code:
class Concatenation:
    def __init__(self, lst1, lst2):
        self.lst1 = lst1
        self.lst2 = lst2
        self.cachedlen = len(lst1) + len(lst2)

    def __getitem__(self, i):
        if not isinstance(i, int): raise TypeError(i)
        elif not (0 <= i < len(self)): raise IndexError(i)
        elif i < len(self.lst1): return self.lst1[i]
        else: return self.lst2[i - len(self.lst1)]

    def __len__(self): return self.cachedlen

class Mapper:
    def __init__(self, f, lst):
        self.f = f
        self.lst = lst

    def __getitem__(self, i): return self.f(self.lst[i])

    def __len__(self): return len(self.lst)

rawDescription: Generating 3 billion-th element of a sequence in python


code:
class CMixin:
    def method3(self):
        return self.method1()+self.method2()

class C1(A,B, CMixin):
    pass

class C2(A2,B, CMixin):
    pass

rawDescription: Changing base class in a inheritance hierarchy


code:
class PointOnUnitCircle(Point):

    def __init__(self, x, y):
        if not self._on_unit_circle(x, y):
            raise ValueError('({}, {}) not on unit circle'.format(x, y))
        super(PointOnUnitCircle, self).__init__(x, y)

    @staticmethod
    def _on_unit_circle(x, y):
        """Whether the point x, y lies on the unit circle."""
        raise NotImplementedError

    @classmethod
    def from_angle(cls, angle):
        return cls.from_mag_angle(1, angle)

    @classmethod
    def from_mag_angle(cls, mag, angle):
        # note that switching these parameters would allow a default mag=1
        if mag != 1:
            raise ValueError('magnitude must be 1 for unit circle')
        return super(PointOnUnitCircle, cls).from_mag_angle(1, angle)

rawDescription: Use inherited class method within __init__


code:
def limit(f, eps=1.0e-11):
  for next_value, previous_value in next_prev(f):
    if abs(next_value - previous_value) < eps:
      return next_value

rawDescription: Recurrence sequence in Java / Python / Mathematica


code:
def left(i):
    return 2 * i      # this is 1-based tree. Since your first element is stored in 0th cell, here is an error

def right(i):
    return 2 * i + 1    # same, this's 1-based

def HeapSize(A):
    return len(A) - 1

def MaxHeapify(A, i):
    l = left(i)
    r = right(i)
    if l <= HeapSize(A) and A[l] > A[i]:
            largest = l       # always keep 4 white space (or tab) as indent in Python, don't mix up
    else:
            largest = i
    if r <= HeapSize(A) and A[r] > A[largest]:
            largest = r
    if largest != i:
            A[i], A[largest] = A[largest], A[i]
            MaxHeapify(A, largest)

def BuildMaxHeap(A):
    for i in range(HeapSize(A) // 2, 0, -1):     # the last non-leaf element is (HeapSize(A)-1) // 2
            MaxHeapify(A, i)

def HeapSort(A):
    BuildMaxHeap(A)
    for i in range(HeapSize(A), 1, -1):   # e.g. range(3,1,-1) gives you [3,2], you miss the 1st element
            A[i], A[1] = A[1], A[i]     # swap with A[0], unless you don't use the 0th element of array
            MaxHeapify(A, 1)      # here is essential error for the algorithm. Since you're doing in-place sorting, you'd not swap the largest element to end of heap then MaxHeapify the WHOLE ARRAY again. I.e. you have to MaxHeapify the heap EXCLUDING the last element

rawDescription: Buggy Heap Sort

description: Buggy Heap Sort


code:
def IterateServer(self):
    for key in self.servers:
        try:
            tmp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tmp_sock.connect((self.host, key))
        except socket.error as msg:
            # Didn't work! Entry in dict stays as None
            continue
        # Did work! Update the dict with our open socket.
        self.servers[key] = tmp_sock
        print('Connect' + str(key))

rawDescription: Client-side Socket on Python, how to contact multiple server?


code: yourarray.reshape(12, 2)

rawDescription: How to concatenate 2 np.ndarray's?

description: Concatenate 2 np.ndarray's


code:
y = np.empty_like(s)
y[:2] = [0, k]
y[2:], zo = lfilter(b, a, s[2:], zi=zi)

rawDescription: python recursive vectorization with timeseries

description: Python recursive vectorization with timeseries


code:
from django.db import transaction

@transaction.commit_manually
def add_preferences(user, preferences):
  user.preference.clear()
  for pref in preferences:
    user.preference.add(pref)
  transaction.commit()

rawDescription: A help in concept and a database query question (Django/Python)


code:
class Table1(Base):
    __tablename__ = 'table1'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    rel_table2 = relationship('Table2', backref='table1')

class Table2(Base):
    __tablename__ = 'table2'
    id = Column(Integer, primary_key=True)
    table1_id = Column(ForeignKey(Table1.id))
    name = Column(String)

    rel_table3 = relationship('Table3', backref='table2')

class Table3(Base):
    __tablename__ = 'table3'
    id = Column(Integer, primary_key=True)
    table2_id = Column(ForeignKey(Table2.id))
    name = Column(String)

rawDescription: SQLAlchemy - delete grandchildren

description: SQLAlchemy - delete grandchildren


code:
padded_width = max(len(x) for x in my_dict.iterkeys()) + 1
for key in my_dict:
    print(key.ljust(padded_width) + my_dict[key])

rawDescription: how to neatly print a dictionary

description: Neatly print a dictionary


code:
import os
loadavg = os.getloadavg()[0]

rawDescription: Change the number of processes to spawn depending on the CPU usage in Python


code:
with open("infile.txt") as f:
    for line in f:
        detector(line.strip())

rawDescription: Python One-Shot, level-trigger, edge-trigger


code: a[i, j]

rawDescription: How to extract a list of elements given by their indices from a numpy array efficiently?

description: Extract a list of elements given by their indices from a numpy array efficiently


code:
import matplotlib.backends.backend_qt4agg as backend
from matplotlib.figure import Figure

fig = Figure()
ax = fig.add_subplot(111)

manager = backend.new_figure_manager_given_figure(1, fig)
manager.show()
backend.show.mainloop()

rawDescription: Prevent matplotlib statefulness

description: Prevent matplotlib statefulness


code:
import pickle

unique_genes_list = ["a", "ab", "ac", "ad"]
with open('some/path', 'rb') as in_pickle:
    old_data = pickle.load(in_pickle) ## ["a", "ab", "ac"]

## Adds 'ad' and any other new data
old_data.extend([x for x in unique_genes_list if not x in old_data])

## Save the new combined data
with open('some/path', 'wb') as out_pickle:
    pickle.dump(old_data, out_pickle) ## dumps ["a", "ab", "ac", "ad"] overwriting old pickle

rawDescription: python pickle: dump only unique list to pickled file

description: Python pickle: dump only unique list to pickled file


rawDescription: Filter a pandas dataframe using values from a dict


code:
my_list = [['one', 'two'], ['three', 'four', 'two']]
l = [item for inner_list in my_list for item in inner_list if item == 'two']
l

rawDescription: How to find all occurrences of an element in a list?

description: Find all occurrences of an element in a list


code:
candidates = []
for e in lst:
    for i in range(100):
        candidates.append('{}{:02d}'.format(e[:6], i))

rawDescription: Append itertools.product() results to variable in Python


code:
common_user = CommonUser.objects.get(id=id)
common_user.__class__ = Client
common_user.save()

rawDescription: "Create" child model from base model in django


rawDescription: regular expression for ipaddress and mac address

description: Regular expression for ipaddress and mac address


code: a.reshape(-1, 1) + b

rawDescription: Add two arrays without using for. Python


code:
def pad(x, p):
    return ('%0'+str(p+(x<0 and 1 or 0))+'d%s') % (x,str(x-int(x))[x<0 and 2 or 1:])

rawDescription: Most pythonic way to pad a float left of the decimal point


code:
while True:
    reroll = input("Input 'roll' to roll the dice.")
    if reroll == "roll":
        print("The Dice has been rolled", sum(picked), "times.")
        for i in range(7, 1, -1):
            print ("You rolled", i, picked[i], "times")

rawDescription: How can I show a variable on command that is updating constantly?

description: Show a variable on command that is updating constantly


code:
def base64_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = base64.decodestring(input)
    return (output, len(input))

rawDescription: Python: base64.b64decode() vs .decode?

description: Python: base64.b64decode() vs .decode


code:
# iconSize to be reused
iconSize = Gtk.IconSize.LARGE_TOOLBAR

# ...

openIcon = Gtk.Image.new_from_icon_name("document-open", iconSize)
self.fileOpen = Gtk.ToolButton.new(openIcon, "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)

rawDescription: What is the non-deprecated way to display a stock icon in GTK3?


rawDescription: Python reshape list to ndim array

description: Python reshape list to ndim array


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,

    'server.ssl_module'            : 'pyopenssl',
    'server.ssl_certificate'       : '/path/to/certs/domain.com.crt',
    'server.ssl_certificate_chain' : '/path/to/certs/ssl123_ca_bundle.pem',
    'server.ssl_private_key'       : '/path/to/certs/domain.com.key',
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return 'Is this secure?'

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: CherryPy SSL Chained Certificates

description: CherryPy SSL Chained Certificates


code:
import argparse
parser = argparse.ArgumentParser(description='''Some text''')
subparsers = parser.add_subparsers()

query_p = subparsers.add_parser("query", help="Query with a list of terms")
query_p.add_argument("terms")
query_p.add_argument("--json", help="output in JSON format, use only with -q", action="store_true")

index_p = subparsers.add_parser("index", help="index a file")
index_p.add_argument("indexfile", help="file to index")

args = parser.parse_args()

rawDescription: Argparse mutally exclusive by subgrouping


rawDescription: Can I dynamically change order_by attributes in my query call?

description: Dynamically change order_by attributes in my query call


code:
class D( B, C ):
    foo = B.foo
    bar = C.bar

rawDescription: Python multiple inheritance questions

description: Python multiple inheritance questions


code:
characters = []
for character in x:
    characters.append(str(test[character]))

rawDescription: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

description: Make a 'while' loop print the results of the loop's conditional into a single line(concatenated)


code: df.DATE.shift() != df.DATE

rawDescription: pandas DataFrame delete contiguous duplicates

description: Pandas DataFrame delete contiguous duplicates


rawDescription: Converting an html page to binary format in python


code:
sortA = [(n,max(s)) for n,s in scores.items()]
sortA.sort(key=lambda x: x[0])
for name, highScore in sortA:
    print(name, highScore)

rawDescription: Outputting Highest/Average Score From List Of 3 (Value) For Each Student (Key) In A Dictionary Sorted From Highest To Lowest?


code: [("|".join(values), ) for values in zipped]

rawDescription: Zip string-subset from tuples in a list

description: Zip string-subset from tuples in a list


code:
list(mix_lists('abcd', [1, 2, 3]))
list(mix_lists('abcd', [1, 2, 3], offset=3))
list(mix_lists('abcd', [1, 2, 3], offset=6))

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


code:
for i in range(int(math.ceil(df.scale / 3000))):
  # i will contain 0, 1, 2, ...
  # letter will contain 'A', 'B', 'C', ...
  letter = chr(ord('A') + i)

rawDescription: Change count into an array of letters, python


code:
class Inner:

    def __init__(self, context, hierarchy):
        self.children = []
        next_level = hierarchy[0]
        next_level_contexts = get_contexts(next_level)
        for context in next_level_contexts:
            child_context = parent_context.new_child().update(context)
            if next_level == hierarchy[-1]:
                self.children.append(Leaf(context))
            else:
                self.children.append(Inner(child_context, hierarchy[1:]))

    def do_something(self):
        # this will do something on the left-most leaf
        self.children[0].so_something()

    def prune(self):
        # this will remove the left-most leaf
        if isinstance(self.children[0], Leaf):
            self.children.pop(0)
        else:
            self.children[0].prune()
            if not self.children[0]:
                self.children.pop(0)

    def __bool__(self):
        return bool(self.children)

class Leaf:

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

    def do_something():
        do_something(**self.context)

rawDescription: Workarounds to suspend (serialize) and resume a recursive generator stack?


code:
# ...
my_bar = Bar()
api.add_resource(views.ApiPage, '/api/my/end/point/',
                 resource_class_kwargs={'bar': my_bar})

rawDescription: Flask Restful add resource parameters

description: Flask Restful add resource parameters


code: d

rawDescription: Merging part of tuples in Python

description: Merging part of tuples in Python


code:
import csv
import math
import os
import re

LOCATION = os.path.dirname(os.path.abspath(__file__))
afinn_filename = os.path.join(LOCATION, '/AFINN/AFINN-111DK.txt')

pattern_split = re.compile(r"\W+")

with open(afinn_filename, encoding='utf8', newline='') as infile:
    reader = csv.reader(infile, delimiter='\t')
    afinn = {key: int(score) for key, score in reader}

def sentiment(text):
    words = pattern_split.split(text.lower().strip())
    if not words:
        return 0
    sentiments = [afinn.get(word, 0) for word in words]
    return sum(sentiments) / math.sqrt(len(sentiments))

# Print result
text = "ånd ånd med fløde... :)asd "
id = 999
split = "###"
print('{sentiment:6.2f}{split}{id}{split}{text}'.format(
    sentiment=sentiment(text), id=id, split=split, text=text))

rawDescription: python re.compile and split with ÆØÅ charcters

description: Python re.compile and split with ÆØÅ charcters


code:
with open("filename.txt", "r+b") as f:
    fourbytes = [ord(b) for b in f.read(4)]
    fourbytes[0] = fourbytes[1]  # whatever, manipulate your bytes here
    f.seek(0)
    f.write("".join(chr(b) for b in fourbytes))

rawDescription: Simple edit to a binary file in python

description: Simple edit to a binary file in python


code:
Master =[23,5, 6, 34, 11, 23]
List_check = [23, 6, 11]
[Master.index(item) for item in Master if item in List_check]

rawDescription: Append index of items in one list to another in Python 2.7


code:
for i, old_coord in enumerate(start_points):
    new_coord = self.nearest_neighbor(old_coord)
    pygame.draw.line(screen, self.get_col(old_coord), old_coord, new_coord, 2)
    start_points[i] = new_coord
    pygame.display.flip()

rawDescription: drawing lines from a list in pygame

description: Drawing lines from a list in pygame


rawDescription: Printing key values of multi level dictionary in python


code:
class BackwardsTree(Tree):
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        # Swap the left and right subtrees
        self.right = left
        self.left = right

bt = BackwardsTree.from_list([1,2,3,4,5,6])

rawDescription: Python passing instance of class by reference


code:
def getApproximateArialStringWidth(st):
    size = 0 # in milinches
    for s in st:
        if s in 'lij|\' ': size += 37
        elif s in '![]fI.,:;/\\t': size += 50
        elif s in '`-(){}r"': size += 60
        elif s in '*^zcsJkvxy': size += 85
        elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
        elif s in 'BSPEAKVXY&UwNRCHD': size += 112
        elif s in 'QGOMm%W@': size += 135
        else: size += 50
    return size * 6 / 1000.0 # Convert to picas

rawDescription: Roughly approximate the width of a string of text in Python?


rawDescription: Python linesplitting into sections

description: Python linesplitting into sections


code:
@property
def position(self):
    return self._position

@position.setter
def position(self, position):
    self._position = position  # do checking before this if needed
    self._x = position[0]
    self._y = position[1]

rawDescription: property of class doesnt restrict the attribute

description: Property of class doesnt restrict the attribute


code:
class Wall(pygame.sprite.Sprite):
    def __init__(self, color=None, x=None, y=None, width=None, height=None, wall=None):
        pygame.sprite.Sprite.__init__(self)
        # check parameters are valid
        assert any([color and x and y and width, wall]), "invalid arguments"
        # assign parameters from given wall or parameters
        x      = x or wall.rect_x
        y      = y or wall.rect_y
        color  = color or wall.color
        height = height or wall.height
        width  = width or wall.width
        ...

rawDescription: Python - how to copy object (so it would not reference old object) without using deepcopy?


rawDescription: How to counter at even numbers only

description: Counter at even numbers only


rawDescription: Python unit tests: type checking custom class type


code:
orig = [10, 20, 30]
arr = orig              # Second reference to the same list.
arr[:] = []             # Clears the one list, so that arr and orig are empty
orig

rawDescription: Difference between arr[:]=[] and arr[]=[] in python3.x?


code:
class RampUp:
    def __init__(self):
        self.value = 0
        self.target = 0
        self.next = self.__next__
        self.calc = None

    def __iter__(self):
        return self

    def __next__(self):
        if self.value == self.target:
            return self.value
        else:
            self.value = self.calc(self.value, self.target)
            return self.value

rawDescription: Ramping Joystick values over time

description: Ramping Joystick values over time


code: d = dict((key, value) for (key, value) in iterable)

rawDescription: Create a dictionary with list comprehension in Python


rawDescription: Showing page count with ReportLab

description: Showing page count with ReportLab


code:
words = ['abc', 'cab', 'cafe', 'goo', 'face']
from itertools import groupby
[list(group) for key,group in groupby(sorted(words,key=sorted),sorted)]

rawDescription: Finding and grouping anagrams by Python

description: Finding and grouping anagrams by Python


code:
import re

re.findall(r'[a-zA-Z]+',input_string)

rawDescription: Parsing Sentences (or other longer strings) in Python (ProblemSetQuestion) How to proceed?


code:
from ast import parse, NodeVisitor, literal_eval
import importlib
import inspect

mod = "test"
mod = importlib.import_module(mod)
p = parse(inspect.getsource(mod))

class FindCall(NodeVisitor):
    def __init__(self, *args):
        if len(args) < 1:
            raise ValueError("Must supply at least ine target function")
        self.result = {arg: []for arg in args}

    def visit_Call(self, node):
        if node.func.id in self.result:
            self.result[node.func.id].append(map(literal_eval, node.args))
        # visit the children
        self.generic_visit(node)

fc = FindCall("foobar")
fc.visit(p)
print(fc.result)

rawDescription: Getting method calls and their arguments from method object


rawDescription: Numpy difference between neighboring elements


code:
import numpy as np
import mpmath as mp
small_number = mp.besseli(400, 2)  # This is an mpf number
# Note that creating a list using `range` and then converting it
# to an array is not very efficient. Do this instead:
A = np.arange(600)
result = small_number * A  # Array of dtype object, ie, it contains mpf numbeers

rawDescription: How to mpf an array?

description: Mpf an array


rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
month_index =df.index.to_period('M')

min_day_in_month_index = pd.to_datetime(df.set_index(new_index, append=True).reset_index(level=0).groupby(level=0)['level_0'].min())

custom_month_starts =CustomBusinessMonthBegin(calendar = min_day_in_month_index)

rawDescription: Convert daily pandas stock data to monthly data using first trade day of the month


rawDescription: How do I delete and create new lines simultaneously

description: Delete and create new lines simultaneously


code: df.agg(F.count(df.var3), F.max(df.var3), ) # etc...

rawDescription: Spark reduceByKey on several different values


code:
inv = []

inv.append('Item1')

rawDescription: python text rpg inventory system

description: Python text rpg inventory system


code: d['foo']

rawDescription: How to set default value to all keys of a dict object in python?

description: Set default value to all keys of a dict object in python


code:
i = 0
while i < 5:
    print(i)
    if condition:
        do_something()
        # don't increment here, so we stay on the same value for i
    else:
        # only increment in the case where we're not "moving backwards"
        i += 1

rawDescription: Moving back an iteration in a for loop

description: Moving back an iteration in a for loop


code:
req = mechanize.Request("https://www.site.com/path/" + url, " ")
req.add_header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7")
req.add_header("Referer", "https://www.site.com/path")
cj.add_cookie_header(req)
res = mechanize.urlopen(req)

rawDescription: How do I get Python's Mechanize to POST an ajax request?

description: Get Python's Mechanize to POST an ajax request


code:
for t in itertools.combinations(x,3):
  if all(len(col) == len(set(col)) for col in zip(*t)):
    print(repr(t))

rawDescription: Finding unique solution puzzle python

description: Finding unique solution puzzle python


code:
dnaSeq = raw_input("Enter a space-separated DNA string:").split()
dnaSeq

rawDescription: Python .split list is callable but index is out of range?


code: list(enumerate(zip(list1, list2)))

rawDescription: python iterating two lists in a tuple and comparing a integer between tem

description: Python iterating two lists in a tuple and comparing a integer between tem


code:
import sys

for fn in sys.argv[1:]:
    with open(fn,'r') as file:

        lines = file.readlines()

        # creates a list or pairs (21st char, line) within a list
        lines = [ [line[21:22], line ] for line in lines ]

        # sorts lines based on key (21st char)
        lines.sort()

        # brings back list of lines to its original state,
        # but the order is not reverted since it is already sorted
        lines = [ line[1] for line in lines ]

        filename = 'file'
        prev = 0
        for line in lines:
            if line[21:22] != prev:
                # creates a new file
                file = open(filename + line[21:22] + '.txt', 'w')
            else:
                # appends to the file
                file = open(filename + line[21:22] + '.txt', 'a')

            file.write(line)
            prev = line[21:22]

rawDescription: file separation on the basis of matching character

description: File separation on the basis of matching character


code: {'MyClass.my_other_method': ('prop3', 'prop4'), 'MyClass.my_method': ('prop1', 'prop2')}

rawDescription: Auto-register class methods using decorator


rawDescription: Python: re.sub pattern and replacement wildcard


code:
for var, value in zip(change_vars_list, change_values_list):
    outdata = outdata.replace(var, value)

rawDescription: re.sub - multi value and multi lines substitution

description: Re.sub - multi value and multi lines substitution


code:
n_successful = 0
while not results.empty():
    ip = results.get()
    print(ip)
    n_successful += 1

print('Total of {} hosts successful'.format(n_successful))

rawDescription: Documentation for understanfing

description: Documentation for understanfing


code:
def removearticles(text):
  re.sub('(\s+)(a|an|and|the)(\s+)', '\1\3', text)

rawDescription: Remove all articles, connector words, etc., from a string in Python


code:
def reverse_sublist(lst, start, end):
    lst[start:end] = reversed(lst[start:end])

rawDescription: Replacing two elements of a list in place with a function [python 3]


rawDescription: Howto list files on a smartcard with pyscard


code:
import numpy as np

data = [np.arange(8).reshape(2, 4), np.arange(10).reshape(2, 5)]
np.savez('mat.npz', *data)

container = np.load('mat.npz')
data = [container[key] for key in container]

rawDescription: NumPy save some arrays at once

description: NumPy save some arrays at once


code:
from django.contrib import admin

from modules.common.models import *

class EmailAdmin(admin.ModelAdmin):
    """
    Admin part for managing the the Email model
    """
    list_display = ['to', 'subject', 'ok',]
    list_filter = ['ok']
    readonly_fields = ['when', 'to', 'subject', 'body', 'ok']
    search_fields = ['subject', 'body', 'to']

    def has_delete_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return False

admin.site.register(Email, EmailAdmin)

rawDescription: How can I log all outgoing email in Django?

description: Log all outgoing email in Django


code:
from tkinter import filedialog
filedialog

rawDescription: filedialog, tkinter and opening files

description: Filedialog, tkinter and opening files


code:
# contents of conftest.py
from PIL import ImageChops, ImageDraw, Image
import pytest
import os
import py.path
import math
import operator

def rms_diff(im1, im2):
    """Calculate the root-mean-square difference between two images
    Taken from: http://snipplr.com/view/757/compare-two-pil-images-in-python/
    """
    h1 = im1.histogram()
    h2 = im2.histogram()

    def mean_sqr(a,b):
        if not a:
            a = 0.0
        if not b:
            b = 0.0
        return (a-b)**2

    return math.sqrt(reduce(operator.add, map(mean_sqr, h1, h2))/(im1.size[0]*im1.size[1]))

class ImageDiff:
    """Fixture used to make sure code that generates images continues to do so
    by checking the difference of the genereated image against known good versions.
    """

    def __init__(self, request):
        self.directory = py.path.local(request.node.fspath.dirname) / request.node.fspath.purebasename
        self.expected_name = (request.node.name + '.png')
        self.expected_filename = self.directory / self.expected_name

    def check(self, im, max_threshold=0.0):
        __tracebackhide__ = True
        local = py.path.local(os.getcwd()) / self.expected_name
        if not self.expected_filename.check(file=1):
            msg = '\nExpecting image at %s, but it does not exist.\n'
            msg += '-> Generating here: %s'
            im.save(str(local))
            pytest.fail(msg % (self.expected_filename, local))
        else:
            expected = Image.open(str(self.expected_filename))
            rms_value = rms_diff(im, expected)
            if rms_value > max_threshold:
                im.save(str(local))
                msg = '\nrms_value %s > max_threshold of %s.\n'
                msg += 'Obtained image saved at %s'
                pytest.fail(msg % (rms_value, max_threshold, str(local)))

@pytest.fixture
def image_diff(request):
    return ImageDiff(request)

rawDescription: Carrying out unit testing in python on a method that implements ImageDraw


code:
def create(request):
   if request.method == 'POST':
    form = ItemForm(request.POST)
    if form.is_valid():
      # the shoplist object
      form.save(commit=False)
      form.cleaned_date['from_list'] = your_shoplist_object
      form.save()
#...
#...

rawDescription: dont get how to make connection

description: Dont get how to make connection


code: [['red apple', 'red banana'], ['house is green']]

rawDescription: Searching list using keywords from other list?


code:
# urllib2
URLError: timeout('timed out',)

# Requests
Timeout: TimeoutError("HTTPConnectionPool(host='localhost', port=12346): Request timed out. (timeout=4)",)

rawDescription: How to prevent blocking forever on urlopen

description: Prevent blocking forever on urlopen


code:
from pprint import pprint
from bs4 import BeautifulSoup

input_string = """peanut butter1

peanut butter2

2.0 to 6.0 mg of 17β-estradiol and

0.020 mg of ethinylestradiol;

0.25 to 0.30 mg of drospirenone and
peanut butter3

peanut butter4"""

soup = BeautifulSoup(input_string, 'html.parser')

result = []
for item in soup.find_all(text=True):
    value = item.strip()
    if value:
        parent = 'no tag' if item.parent.parent is None else item.parent.name
        result.append([parent, value])

pprint(result)

rawDescription: Use Beautifulsoup to turn <ul> <li> and unbounded items into a list


rawDescription: Rectangular border widths for sizer in wxPython


code: print("The volume of the cylinder is {}cm\u00b3".format(volume))

rawDescription: Two Decimals in Python?

description: Two Decimals in Python


rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code:
import numpy
numpy.std(myList)

rawDescription: finding standard deviation down a column of data in python

description: Finding standard deviation down a column of data in python


rawDescription: Python modules, referencing other modules within the same package?


rawDescription: How do I properly use the sub function of regular expression in Python?

description: Properly use the sub function of regular expression in Python


code: text

rawDescription: Strip all html lines/code from string in python


code:
def get_success_url(self):
   url = reverse('success')
   # maybe use urlencode for more complicated parameters
   return "%s?foo=%s" % (url, self.request.POST['bar'])

rawDescription: Confirming generic FormView POST success back to user with POST data


code:
lines={}
for i in range(2,6):
   lines[i]=linecache.getline('/tmp/lines.txt', i).strip()

lines

rawDescription: numpy - Python - Selectively import parts of the .txt file

description: Numpy - Python - Selectively import parts of the .txt file


code: return render(response, self.template_name, context)

rawDescription: How to include a function call in a Django template?

description: Include a function call in a Django template


code: multiples = [value for value in range(high, low-1, -1) if value % num == 0]

rawDescription: Count even and odd numbers and the totals (python)


rawDescription: Django filter ManyToMany field

description: Django filter ManyToMany field


code:
df2.columns
df2.columns.get_values()

rawDescription: Using Python to Combine CSV Elements From Columns to Rows


rawDescription: Placing a numpy record array inside another record array python


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

# You probably provided some python-paths (places to look for python modules)
# in your eclipse configuration. You'll need to add those path's to the wsgi
# script too.

os.path.append(PROJECT_DIR)
os.path.append(PROJECT_DIR + '/lib')
os.path.append(PROJECT_DIR + '/src')

# You probably have this set in eclipse too:
os.environ['DJANGO_SETTINGS_MODULE'] = 'production_setting'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

rawDescription: How to publish (in a server) a pydev app using eclipse?

description: Publish (in a server) a pydev app using eclipse


code:
def foo():
    global bar
    do_stuff(bar)

foo()
foo()

rawDescription: Why doesn't Python have static variables?


rawDescription: submit request (post) internally in python-eve

description: Submit request (post) internally in python-eve


code:
from itertools import chain
sum(chain.from_iterable(d.values() for d in numbers.values()))

rawDescription: Sum of values across all nested dictionaries in python


code:
num = np.datetime64(datetime.datetime.now())
num
df = pd.DataFrame({"Time":[num]})
df
pd.read_csv(StringIO(df.to_csv(index=False)),parse_dates=['Time'])
pd.read_csv(StringIO(df.to_csv(index=False)),parse_dates=['Time']).Time.values

rawDescription: pandas to_csv and then read_csv results to numpy.datetime64 messed up due to utc

description: Pandas to_csv and then read_csv results to numpy.datetime64 messed up due to utc


code:
dt = datetime.datetime(year, month, day, hour, minute, second)
unix_time = time.mktime(dt.timetuple())

rawDescription: using cython to generate a unix timestamp

description: Using cython to generate a unix timestamp


code:
def weighted_choice_compile(items):
    """returns a function that fetches a random item from items

    items is a list of tuples in the form (item, weight)"""
    weight_total = sum((item[1] for item in items))
    def choice(uniform = random.uniform):
        n = uniform(0, weight_total)
        for item, weight in items:
            if n < weight:
                return item
            n = n - weight
        return item
    return choice

rawDescription: Probability distribution in Python

description: Probability distribution in Python


code:
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers()

rawDescription: Python argparse: How to insert newline the help text in subparser?


code: allRows = table.find_all('tr')[1:-1]

rawDescription: The second row and third row should be a single row


rawDescription: How to find the difference between 3 lists that may have duplicate numbers

description: Find the difference between 3 lists that may have duplicate numbers


code:
from collections import defaultdict
filltaxlist = open("file with query number.txt", "rw")
fulltaxa = open("output file with hit line match", "rw")

possibles = {}
for i, line in enumerate(filltaxalist):
    line = line.strip()
    taxid = re.split("\t", line)
    lookup = taxid[5] # this value is a number and I need the exact match only so I covert it to an integer
    int1 = int(lookup)
    possibles[int1] = i

output_lines = defaultdict(list)
for line in open("File to search.txt", "r"):
    data = re.split(',', line)
    hit = int(data[0]) # every value in this file is a number separated by a ,
    if hit in possibles:
        output_lines[possibles[hit]].append(line)

fulltaxa.writelines(line for lines in output_lines.values() for line in lines)

rawDescription: How can I make this search faster in python?

description: Make this search faster in python


code:
query = urlparse.parse_qs(split_url.query, keep_blank_values=True)
query

rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
# This file is setup.py
import setuptools

SOURCE = '''
def main():
    print('Hello, world!')
'''

def prepare():
    with open('my_mod.py', 'w') as f:
        f.write(SOURCE)

prepare()

setuptools.setup(
    name = 'woo',
    version = '0.1',
    url = 'http://dummy.com/',
    author = 'Me',
    author_email = 'me@dummy.com',
    py_modules=['my_mod'],
    entry_points={
        'console_scripts':['myprog = my_mod:main']
   }
)

rawDescription: console_scripts entry point ignored?

description: Console_scripts entry point ignored


code:
from collections import Counter
L=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,1,2,3]
[k for k,v in Counter(L).items() if v==1]

rawDescription: Remove BOTH items from list, if one value appears multiple times (Python)


rawDescription: Creating an empty deque in Python with a max length?


code: df['year'].values #returns an array

rawDescription: basic panda questions related to slicing and aggregating tables

description: Basic panda questions related to slicing and aggregating tables


code:
a, b = np.ogrid[0:K-N+1, 0:N]
data[a+b]

rawDescription: Creating an overlap array with conditions - Python


code: self.__stats[hostid] = _Statistics(ncpus, rworker)

rawDescription: When using Parallel Python, is there any way to tell on which machine the job has run?


code:
new_path = path + '.{obj}'.format(obj=f)
_traverse_output(f, v, fields, row, new_path)

rawDescription: Python Recursively Maintain Keyed Depth

description: Python Recursively Maintain Keyed Depth


rawDescription: Python counting in a tuple list

description: Python counting in a tuple list


code:
# Add to imports
import datetime

# fetch date and you can give this, not hard coded string value.
datetime.datetime.today()

rawDescription: How to set wxpython Grid top headers?

description: Set wxpython Grid top headers


rawDescription: matching quoted strings and unquoted words

description: Matching quoted strings and unquoted words


code:
ax = graph_by_common_users.plot(kind='barh', width=0.5, figsize=(10,20))
[label.set_rotation(25) for label in ax.get_xticklabels()]

rects = ax.patches
labels = [int(round(graph_by_common_users.loc[i, y])) \
for y in graph_by_common_users.columns.tolist() \
for i in graph_by_common_users.index]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_width()+20, rect.get_y() - 0.25 + rect.get_height(), label, fontsize=8)

    handles, labels = ax.get_legend_handles_labels()
    # sort both labels and handles by labels
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
    ax.legend(handles, labels)

rawDescription: Sort strings in column and print graph

description: Sort strings in column and print graph


rawDescription: Extract text value in xml using python

description: Extract text value in xml using python


code:
f1 = Foo()
f2 = Foo()
Foo.ls.append(1)
f1.ls.append(1)
f1.ls
f2.ls

rawDescription: some confusion with variables declared by python class

description: Some confusion with variables declared by python class


code:
for key, value in x.items():
   if key == "key2":
      list_of_values.append(value)

rawDescription: Adding dictionary values to a list?

description: Adding dictionary values to a list


code: lst = words(3)

rawDescription: Being Pythonic: Collecting arbitrary strings - indexer


code:
for bits in itertools.product([0, 1], repeat=3*n):
    rs = [(i,) + bits[3*i:3*i+3] for i in range(n)]
    # do something with the list of r tuples here

rawDescription: itertools.product - return list instead of tuple

description: Itertools.product - return list instead of tuple


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'myproject.context_processors.django_version',
)

rawDescription: Django template tag to display Django version


rawDescription: Splitting string in Python starting from the first numeric character


code:
process_link.apply_async(args=[link1],
                         queue=queue1)

process_link.apply_async(args=[link2],
                         queue=queue2)

rawDescription: Create celery multiple queues

description: Create celery multiple queues


code:
import sys
import pexpect
import getpass

password = getpass.getpass("Enter password:")

child = pexpect.spawn('ssh -l root 10.x.x.x "ls /"')
i = child.expect([pexpect.TIMEOUT, "password:"])
if i == 0:
    print("Got unexpected output: %s %s" % (child.before, child.after))
    sys.exit()
else:
    child.sendline(password)
print(child.read())

rawDescription: unable to provide password to a process with subprocess [python]

description: Unable to provide password to a process with subprocess [python]


code:
value = integer % base
integer //= base

rawDescription: Divmod alternative method

description: Divmod alternative method


code:
from collections import Counter
a = ["a", "b", "aaa", "bb", "aa", "bbb", "", "a", "b"]
Counter(map(len, a))

rawDescription: Counting same length items in a list

description: Counting same length items in a list


code:
for data in data_all:
    data_string_sample=((data['utcdate']['mday']),(data['utcdate']['mon']),(data['utcdate']['year']),(data['utcdate']['hour']),(data['utcdate']['min']),(data['tempm']),(data['hum']),(data['pressurem']))

rawDescription: Python - Iterate through, and extract, elements of a dictionary type list


code: substring1 in string or substring2 in string or substring3 in string

rawDescription: If substring in string, when substring has multiple values


code:
newdata = [{'key':key, 'values': grp[['B','C']].values.tolist()}
           for key, grp in df.groupby('A')]

rawDescription: Pandas - turning a DF column into an Index but without duplication


code:
def writeFilesForEveryGroupsFromDict(aDict):
    for key in aDict:
        f = open(key + '.txt', 'w')
        f.write(aDict[key][0])

rawDescription: Python3 create files from dictionary

description: Python3 create files from dictionary


code: sorted_tuples = [edge.tuple for edge in G1.es[edgelist]]

rawDescription: iGraph Python, convert edge list to tuple and add.edges

description: IGraph Python, convert edge list to tuple and add.edges


rawDescription: Python3 Unicode Decode Error

description: Python3 Unicode Decode Error


code:
for line in BrowserInfo.splitlines():
    k,v = line.split(': ', 1)

rawDescription: Adding new key-value pairs to JSON files using Python


code: [sublist[-1] for sublist in example]

rawDescription: Python taking a certain string from a list