code:
name=u'Python Programming Language \u2013 Official Website'
url=u'http://www.python.org/'

rawDescription: python display unicode in html

description: Python display unicode in html


rawDescription: multiple Json objects in one file extract by python

description: Multiple Json objects in one file extract by python


code:
def index(request, my_param):
    return HttpResponse(my_param)

rawDescription: Simple Django request and response

description: Simple Django request and response


code:
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
plain_message="Hi, I'm going to be encrypted with a private key."
key = RSA.generate(4096)
signer = PKCS1_v1_5.new(key)
bin_enc_msg = signer.private_encrypt(plain_message.encode())

rawDescription: python rsa private-encrypt to comunicate with node.js

description: Python rsa private-encrypt to comunicate with node.js


code:
import psutil
import os
import subprocess

subprocess.Popen(['sleep', '30'])

parent_pid = os.getpid()
parent = psutil.Process(parent_pid)

for child in parent.children():
    print(child)    # do something here

rawDescription: How to "adopt" a child process in python

description: "adopt" a child process in python


code:
env = Environment()
# Builds sub/dir/foo from sub/dir/foo.c
env.Program(target = 'foo', source = 'foo.c')

rawDescription: Creating a Hierarchical Build with SCons


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("")
soup
new_link =  soup.new_tag("link")
new_link
new_link.attrs["href"] = "custom1.css"
new_link
soup.head.insert(0, new_link)
soup

rawDescription: How can I create a stylesheet external link using BeautifulSoup?

description: Create a stylesheet external link using BeautifulSoup


code:
def is_ascii(s):
    """Returns True if a string is ASCII, False otherwise."""
    try:
        s.encode('ASCII')
        return True
    except UnicodeEncodeError:
        return False

rawDescription: Is there a variable in python that holds all ASCII characters?


rawDescription: Python: adding namespaces in lxml

description: Python: adding namespaces in lxml


code:
import json
from twisted.web import server, resource
from twisted.python import log

class Root(resource.Resource):
    def getChild(self, path, request):
        # represents / on your web interface
        return self

class WebInterface(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        log.msg('GOT a GET request.')
        # read request.args if you need to process query args
        # ... call some internal service and get output ...
        return json.dumps(output)

class SpellingSite(server.Site):
    def __init__(self, *args, **kwargs):
        self.root = Root()
        server.Site.__init__(self, self.root, **kwargs)
        self.root.putChild('spell', WebInterface())

rawDescription: Python, Twisted, Django, reactor.run() causing problem


code:
text = re.sub(r'\.([\.]+)', r' DOTMULTI\1', text)

while re.search(r'DOTMULTI\.', text):
    text = re.sub(r'DOTMULTI\.([^\.])', r'DOTDOTMULTI \1', text)
    text = re.sub(r'DOTMULTI\.', 'DOTDOTMULTI', text)

rawDescription: What is the Python equivalence of Perl's DOTMULTI and DOTDOTMULTI


rawDescription: Pandas add column to df based on list of regex patterns


code:
from mako import TemplateLookup

template_lookup = TemplateLookup(directories=['.'])
template = template_lookup.get_template("index.mako")
whitespace_mess = template.render(somevar="no whitespace here")
cleaned_up_output = cleanup_whitespace(whitespace_mess)
return cleaned_up_output

rawDescription: Strip whitespace from Mako template output (Pylons)


rawDescription: How to launch a couple of python scripts from a first python script and then terminate them all at once?

description: Launch a couple of python scripts from a first python script and then terminate them all at once


code: dict(zip(name, hits))

rawDescription: Python loops:  Precise way to handle mapping matching lists


rawDescription: Adaptable descriptor in Python

description: Adaptable descriptor in Python


code:
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup('''\
<script type="text/javascript">window._sharedData = {"static_root":"\/\/d36xtkk24g8jdx.cloudfront.net\/bluebar\/a1968ef","platform":{"is_touch":false,"app_platform":"web"},"hostname":"instagram.com","entry_data":{"DesktopPPage":[{"canSeePrerelease":false,"viewer":null,"media":{"caption_is_edited":false,"code":"vF25LwCnL8","date":1415348305.0,"video_url":"http:\/\/videos-h-12.ak.instagram.com\/hphotos-ak-xap1\/10753251_876245142395032_328159772_n.mp4","caption":"2014 season teaser! Just a taste of some of the \ud83d\udd28\ud83d\udd28\ud83d\udd28 that got fumbled on \ud83d\udcf9 this season. Edit dropping fall 2017 @m.wilkie @sturhyssmith #snowboarding #springshred #bdpproteam #turoaparks #turoa #mtruapehu #seasonedit #wouldyouratherfightagoatwithahumanheadorahumanwithagoathead?","secure_video_url":"https:\/\/igcdn-videos-h-12-a.akamaihd.net\/hphotos-ak-xap1\/10753251_876245142395032_328159772_n.mp4","usertags":{"nodes":[]},"comments":{"nodes":[{"text":"Where do I buy tickets to the London premiere? #fanboy","viewer_can_delete":false,"id":"848487057151652334","user":{"username":"jamesbutchernz","profile_pic_url":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_1052126311_75sq_1391324963.jpg"}},{"text":"It's invites only @jamesbutchernz @m.wilkie is choosing too so chances are slim unless your smoking hot with low self esteem.","viewer_can_delete":false,"id":"849353938720944684","user":{"username":"bobeykrebner","profile_pic_url":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xpf1\/10584664_742398385822158_510451676_a.jpg"}},{"text":"It's lucky we all know I'm both of those. #easy","viewer_can_delete":false,"id":"849403857951420829","user":{"username":"jamesbutchernz","profile_pic_url":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_1052126311_75sq_1391324963.jpg"}},{"text":"Last I heard you were smoking hot and had the self esteem of Kanye West @jamesbutchernz what changed?","viewer_can_delete":false,"id":"849671858500038887","user":{"username":"bobeykrebner","profile_pic_url":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xpf1\/10584664_742398385822158_510451676_a.jpg"}},{"text":"You know what they say @bobeykrebner. Treat yourself like Kayne treats Kayne.","viewer_can_delete":false,"id":"849966794608898266","user":{"username":"jamesbutchernz","profile_pic_url":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_1052126311_75sq_1391324963.jpg"}}]},"shared_by_author":true,"likes":{"count":41,"viewer_has_liked":false,"nodes":[{"user":{"username":"claytonbenson","profile_pic_url":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_52633025_75sq_1359351765.jpg"}},{"user":{"username":"snowrev","profile_pic_url":"https:\/\/igcdn-photos-d-a.akamaihd.net\/hphotos-ak-xaf1\/10735284_1474262932842435_1018554144_a.jpg"}},{"user":{"username":"shayning_","profile_pic_url":"https:\/\/igcdn-photos-f-a.akamaihd.net\/hphotos-ak-xaf1\/10817775_319647074907693_836092401_a.jpg"}},{"user":{"username":"paused_future","profile_pic_url":"https:\/\/igcdn-photos-f-a.akamaihd.net\/hphotos-ak-xpa1\/10809941_1580815445475533_469492417_a.jpg"}},{"user":{"username":"kris_tayl0r","profile_pic_url":"https:\/\/igcdn-photos-e-a.akamaihd.net\/hphotos-ak-xaf1\/10802916_384369668395220_1244229274_a.jpg"}},{"user":{"username":"crazyshuz","profile_pic_url":"https:\/\/igcdn-photos-h-a.akamaihd.net\/hphotos-ak-xfp1\/10787707_905860216092359_425635869_a.jpg"}},{"user":{"username":"titstatertots","profile_pic_url":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xpf1\/10554089_855164584513369_706239607_a.jpg"}}]},"owner":{"username":"bobeykrebner","requested_by_viewer":false,"followed_by_viewer":false,"profile_pic_url":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xpf1\/10584664_742398385822158_510451676_a.jpg","has_blocked_viewer":false,"id":"1459690667","is_private":false},"is_video":true,"id":"848325528968131324","display_src":"http:\/\/photos-e.ak.instagram.com\/hphotos-ak-xfp1\/10748245_307748359428196_942078105_n.jpg"},"__get_params":{},"staticRoot":"\/\/d36xtkk24g8jdx.cloudfront.net\/bluebar\/a1968ef","__query_string":"?","prerelease":false,"__path":"\/p\/vF25LwCnL8\/","shortcode":"vF25LwCnL8"}]},"country_code":"AU","config":{"viewer":null,"csrf_token":"0bfa16595bdacb5bcfcb94441d0fb7ab"}};</script>
''')
script_tag = soup.find('script', text=re.compile('window\._sharedData'))
shared_data = script_tag.string.partition('=')[-1].strip(' ;')
import json
result = json.loads(shared_data)
from pprint import pprint
pprint(result)

rawDescription: Get a dict between tags from html request


rawDescription: How to set first N elements of array to zero?

description: Set first N elements of array to zero


code:
# Test Parser

from xml.dom.minidom import parse
import csv

def writeToCSV(myLibrary):
    csvfile = open('output.csv', 'w')
    fieldnames = ['title', 'author']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    books = myLibrary.getElementsByTagName("book")
    for book in books:
        titleValue = book.getElementsByTagName("title")[0].childNodes[0].data
        for author in book.getElementsByTagName("author"):
            authorValue = author.childNodes[0].data
            writer.writerow({'title': titleValue, 'author': authorValue})

doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]

# Get book elements in library
books = myLibrary.getElementsByTagName("book")

# Print each book's title
writeToCSV(myLibrary)

rawDescription: Python minidom - Parse XML file and write to CSV


code: cookies = {'NetflixCookies': 'true'}

rawDescription: passing in cookie python requests

description: Passing in cookie python requests


code: df.groupby('A').C.apply(lambda x: pd.Series([(x < 0).sum(), (x >= 0).sum()])).unstack()

rawDescription: How to count all positive and negative values in a pandas groupby?

description: Count all positive and negative values in a pandas groupby


code:
import re
def _hash(string):
    return 'HASHED: {}'.format(string[::-1])

sample = '''\
HASH("<stuff>")
'''
re.sub(r'HASH\((["\'])(.*?)\1\)', 'HASH({})'.format(_hash(r'\2')), sample)
def replace_with_hash(match):
    return 'HASH({})'.format(_hash(match.group(2)))

re.sub(r'HASH\((["\'])(.*?)\1\)', replace_with_hash, sample)

rawDescription: Getting the same sha1 hash with all strings


code:
def __new__(cls, obj=None):
    return super(mylist, cls).__new__(cls, obj)

rawDescription: Wrap an object into a derived class

description: Wrap an object into a derived class


code: float(sum(map(len, filtered))) / len(filtered)

rawDescription: real word count in NLTK

description: Real word count in NLTK


code:
from datetime import date
...
@register.filter
def future_dates_only(the_date):
   if the_date > date.today():
       return the_date
   else:
       return None

rawDescription: Django Templates: Display a date only if it's in the future


code:
def onchange_partner_id(self, cr, uid, ids, part, context=None):
    res = super(MyCustomModel, self).onchange_partner_id(cr, uid, ids, part, context)
    res['value'].update({'partner_contact_id': False})
    return res

rawDescription: How to filter contact person for partner in OpenERP?

description: Filter contact person for partner in OpenERP


code:
def foo(z):
    # Ensure that we use a contiguous array of complex64.  If the
    # call to foo(z, z.size) modifies z in place, and that is the
    # intended effect of the function, then the following line should
    # be removed. (The input z is then *required* to be a contiguous
    # array of np.complex64.)
    z = np.ascontiguousarray(z, dtype=np.complex64)
    # Call the C function.
    lib.foo(z, z.size)

rawDescription: How to interface a NumPy complex array with C function using ctypes?

description: Interface a NumPy complex array with C function using ctypes


code:
import re
with open("Input.txt") as open_file:
    data = open_file.read()
for key, value in wordReplacements.iteritems():
    data = re.sub(key, value, data)
with open("Input.txt", "wb") as open_file:
    open_file.write(data)

rawDescription: python replace word in text file without going line by line

description: Python replace word in text file without going line by line


code:
from django.contrib.auth.models import User

@rollback_db_changes
def test_allowed_access():
    user = User.objects.create(username='test_user')
    eq_(1, User.objects.count())

@rollback_db_changes
def test_allowed_access_2():
    user = User.objects.create(username='test_user')
    eq_(1, User.objects.count())

rawDescription: How can I clean up database changes made in django-nose test functions?

description: Clean up database changes made in django-nose test functions


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.layout import Layout

class Foo(Layout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.bind(pos=self.update)
        self.bind(size=self.update)
        self.update()

    def update(self, *args):
        print(self.size)
        self.canvas.clear()
        with self.canvas:
            pass

class MyApp(App):
    def build(self):
        return Foo()

MyApp().run()

rawDescription: How can I get widget's/layout's actual size in Kivy?

description: Get widget's/layout's actual size in Kivy


code:
def isclose(a, b, rtol=1e-05, atol=1e-08):
    return np.abs(a-b) <= (atol + rtol * np.abs(b))

rawDescription: Find float in ndarray

description: Find float in ndarray


code:
if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])

rawDescription: Python 3.x - How to check if "From:" header exists in an email file?


code:
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
# setting up the axes
fig = plt.figure(figsize=(8,8))
ax  = fig.add_subplot(111)
# now plot
alpha, loc, beta=5, 100, 22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = ax.hist(data, 100, normed=True)
rv = ss.gamma(alpha,loc,beta)
x = np.linspace(0,600)
h = ax.plot(x, rv.pdf(x), lw=2)
# show
plt.show()

rawDescription: python: plotting a histogram with a function line on top

description: Python: plotting a histogram with a function line on top


rawDescription: Why are integers immutable in Python?

description: Why are integers immutable in Python


code:
import csv

writer = csv.writer(open("out1.csv","w"))
writer.writerow(values[-2:])

rawDescription: python csv delimiter doesn't work properly

description: Python csv delimiter doesn't work properly


code: a = numpy.array([Register() for _ in range(4)])

rawDescription: Objects array with numpy

description: Objects array with numpy


rawDescription: Find all delimiters next to substring in string and replace in python


code: df.index = pd.MultiIndex.from_tuples([process_index(k) for k,v in df.iterrows()])

rawDescription: Coverting Index into MultiIndex (hierachical index) in Pandas


code:
re.search(r'\d+\.\d+', 'hello Rs. 150.00').group()
re.search(r'\d+\.\d+', 'hello Rs. 150.00 and some more text').group()

rawDescription: regex to escape a part of string

description: Regex to escape a part of string


rawDescription: Python select ith element in OrderedDict


code: relative_paths = [os.path.relpath(path, common_prefix) for path in paths]

rawDescription: Python: Get relative path from comparing two absolute paths


code:
old_list = ["hello", "my", "name", "is"]
user_input = "hello"
new_list = [item if item != user_input else "yes" for item in old_list]
new_list

rawDescription: Changing a string in a list of strings

description: Changing a string in a list of strings


code:
import numpy as np
result = np.empty_like(data1, dtype=float)
# Make an array of True-False values storing which indices are the same
indices = (data1==data2) * (data2==data3)
result[indices] = data1[indices]
result[~indices] = np.nan

rawDescription: Extraction of common element in given arrays to make a new array


code:
# Create the formset factory with an initial form (extra=1)
EntryForm_2Set = formset_factory(EntryForm_2,extra=1)
if request.method == 'POST':
    formset = EntryForm_2Set(request.POST,request.FILES)
    if formset.is_valid():
        instances = []
        for f in formset.forms:
            # get the new applicant instance
            inst = f.save()
            instances.append(inst)
        for i in instances:
            # amend the applicant instance
            i.applicant = request.session['applicant']
            i.save()
        num_entered = formset.total_form_count()
        entry_url = reverse(...) # some reversal
        return HttpResponseRedirect(entry_url)
else:
    formset = EntryForm_2Set()
template_dict['formset'] = formset
return render_to_response('submission-stage-two.html', template_dict, RequestContext(request))

rawDescription: How should cloned Django forms be collected on submission?


code:
import sys
import types

if sys.version_info[0] > 2:  # Python 3+
    create_bound_method = types.MethodType
else:
    def create_bound_method(func, obj):
        return types.MethodType(func, obj, obj.__class__)

class StrategyExample:
    def __init__(self, func=None):
        self.name = "Strategy Example 0"
        if func:
             self.execute = create_bound_method(func, self)

    def execute(self):
        print(self.name)

def executeReplacement1(self):
    print(self.name + " from execute 1")

def executeReplacement2(self):
    print(self.name + " from execute 2")

if __name__ == "__main__":
    strat0 = StrategyExample()
    strat1 = StrategyExample(executeReplacement1)
    strat1.name = "Strategy Example 1"
    strat2 = StrategyExample(executeReplacement2)
    strat2.name = "Strategy Example 2"

    strat0.execute()
    strat1.execute()
    strat2.execute()

rawDescription: How to write Strategy Pattern in Python differently than example in Wikipedia?

description: Write Strategy Pattern in Python differently than example in Wikipedia


code:
dict1 = {'foo':'bar', 'ham': 'eggs'}
dict2 = {'ham': 'spam', 'bar': 'baz'}
dict1.update((k, dict2[k]) for k in set(dict2).intersection(dict1))
dict1

rawDescription: Update dict without adding new keys?

description: Update dict without adding new keys


code:
z =  y[..., np.newaxis]
z.shape

rawDescription: Adding and multiplying columns of a numpy array with another array


code:
from datetime import datetime
dt = datetime.strptime("Wed, 23 July 2014 19:25:52 GMT", "%a, %d %B %Y %H:%M:%S %Z")
dt.strftime('%d/%m/%Y')
dt.strftime('%H/%M/%S')

rawDescription: Python Date / Time Regular Expression

description: Python Date / Time Regular Expression


code:
def makeArray():
    a = [1, 2, 3, 4]
    def addTo(arr):
        return f(a[math.floor(arr/4)]) * f(a[arr % 4])
    vecAdd = numpy.vectorize(addTo)
    return vecAdd(numpy.arange(4 * 4).reshape(4, 4))

rawDescription: Vectorized assignment of a 2-dimensional array


code: a[:] = b[:, :, np.newaxis] - c[np.newaxis, :, :] # memory explodes here

rawDescription: Memory growth with broadcast operations in NumPy


code:
#Protocol  Address          Age (min)   Hardware Addr   Type   Interface
#Internet  192.168.30.4           -     0010.600a.7026  ARPA   vlan20
#Internet  192.168.30.1           -     70ca.9b99.6a82  ARPA   vlan20

rawDescription: Make lists into further sublists

description: Make lists into further sublists


code:
import os
import tty
import pty

program = "python"

# command name in argv[0]
argv = [ "python", "foo.py" ]

pid, master_fd = pty.fork()

# we are in the child process
if pid == pty.CHILD:
    # execute the program
    os.execlp(program, *argv)

# else we are still in the parent, and pty.fork returned the pid of
# the child. Now you can read, write in master_fd, or use select:
# rfds, wfds, xfds = select.select([master_fd], [], [], timeout)

rawDescription: Detecting when a child process is waiting for input


code: np.copyto(b, c[...,None], where=b.mask)

rawDescription: How do I replace missing/masked data with a row mean with numpy

description: Replace missing/masked data with a row mean with numpy


code:
def highlight(self):
    lastline = self.text.index("end-1c").split(".")[0]
    tag = "odd"
    for i in range(1, int(lastline)):
        self.text.tag_add(tag, "%s.0" % i, "%s.0" % (i+1))
        tag = "even" if tag == "odd" else "odd"

rawDescription: Changing background color for every other line of text in a tkinter text box widget


code:
# in file myapp/forms.py
from django import forms
from registration.forms import RegistrationForm

class MyRegistrationForm(RegistrationForm):

    birth_date = ...
    photo = ...

rawDescription: Custom User's and implementations with forms


code:
from pyrabbit.api import Client
cl = Client('localhost:55672', 'guest', 'guest')
cl.get_messages('example_vhost', 'example_queue')

rawDescription: Getting number of messages in a RabbitMQ queue


code: df = pd.read_csv("myfile.csv", parse_dates=['mydates'], date_parser=dateparse)

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

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


code:
import re

# open the files
Old = open('/somelocation/old.html').read()
New = open('/somelocation/new.html').read()

# get the strings you want to swap
NewTableContents = re.findall(r'
([\s\S]+?)
',New)[0]
OldTableContents = re.findall(r'
([\s\S]+?)
',Old)[0]

# replace
Replace = Old.replace(OldTableContents,NewTableContents)

# output string to new file
File = open('/somelocation/oldHTMLWithNewTableContents.html','w')
File.write(Replace)
File.close()

rawDescription: Replace a specific block of HTML between 2 files with Python


code:
R,C = np.triu_indices(a.shape[0],1)
mask = (np.abs(a[R] - a[C]) < tolerance).all(axis=(1,2))
I,G = R[mask], C[mask]

rawDescription: Finding duplicate matrices in Python?

description: Finding duplicate matrices in Python


rawDescription: How can I create two views function in a models Django

description: Create two views function in a models Django


rawDescription: Smart handling of Python array with many indices


rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


code:
from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

rawDescription: Python + Django page redirect

description: Python + Django page redirect


code:
import numpy as np
A = np.array([[1,2,3],[4,5,6]])
b = np.array([4,4])
x, _, _, _ = np.linalg.lstsq(A,b)
x
np.dot(A,x)

rawDescription: Solve Singular Value Decomposition (SVD) in Python


code:
sets = [set([1,2,3]), set([2,3,4]), set([4,2])]
intersection_graph(sets)

rawDescription: construct graph from python set type

description: Construct graph from python set type


code:
class A(object): pass

a = A()
A.f = lambda self, x: 2 * x  # or a pickled function
a.f(1)
A.f = lambda self, x: 3 * x
a.f(1)

rawDescription: how to do an embedded python module for remote sandbox execution?

description: Do an embedded python module for remote sandbox execution


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

rawDescription: python how to make dynamic object name

description: Python how to make dynamic object name


code:
# set_repeat(delay, interval)
pygame.key.set_repeat(1, 10)
# A delay of 0 disables the repeat.
# The lower the interval, the faster the movement would be.

rawDescription: constant movement in pygame

description: Constant movement in pygame


code: df = df[col_start+col_add]

rawDescription: Pandas append list to list of column names


code:
major_students = {}
for major, student in zip(major_list, name_list):
    if major not in major_students:
        major_students[major] = []
    major_students[major].append(student)

rawDescription: Python program - Help pairing elements together without using a dictionary


rawDescription: Python: indexing pandas series by datetime


rawDescription: Searching and replacing in binary file

description: Searching and replacing in binary file


code: imsave(path, image)

rawDescription: Save image without rescaling

description: Save image without rescaling


code:
html_theme = 'theme' # use the theme in subdir 'theme'
html_theme_path = ['.'] # make sphinx search for themes in current dir

rawDescription: Customize sphinxdoc theme

description: Customize sphinxdoc theme


rawDescription: An easy way of printing a n-times-character string in Python


code:
y = ["animal","zoo","potato"]
s =  ["The animal farm on the left","I had potatoes for lunch"]

new = []
for x in s:
    if x not in new:
        new.append(x)
s = new

for words in s:
    for char in y:
        if char in words:
            print (words)
            break

rawDescription: For loop with If not working as expected


rawDescription: Python function for removing zeroes right of decimal, including decimal point?


code:
groups = itertools.groupby(initial, operator.itemgetter('query'))
print([process_group(group) for key, group in groups])

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


rawDescription: Pandas to_csv always substitute long numpy.ndarray with ellipsis


code:
R= arange(12).reshape(4, 3)
R
i= 1
row= R[i, ]
row
j= nonzero(row== max(row))[0][0]
j

rawDescription: Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy


code:
foo(x) # a=x, b=3, args=(), kwargs={}
foo(x, y) # a=x, b=y, args=(), kwargs={}
foo(x, b=y) # a=x, b=y, args=(), kwargs={}
foo(x, y, z, k) # a=x, b=y, args=(z, k), kwargs={}
foo(x, c=y, d=k) # a=x, b=3, args=(), kwargs={'c': y, 'd': k}
foo(x, c=y, b=z, d=k) # a=x, b=z, args=(), kwargs={'c': y, 'd': k}

rawDescription: Python 2.x - default arguments with *args and **kwargs


code:
np.dtype([('field_%d'%i, '<f8') for i in range(4)])

np.dtype({'formats':['f8']*4, 'names':['f%s'%i for i in range(4)]})

np.format_parser(['f8']*4,[],[]).dtype  # auto generate names

rawDescription: Is there a possibility to define dtype only once for all columns?


code:
class TagsASG(troposphere.AWSHelperFn):
    defaultPropagateAtLaunch=True
    manyType=[type([]), type(())]

    def __init__(self, **kwargs):
        self.tags = []
        for k, v in sorted(kwargs.iteritems()):
            if type(v) in self.manyType:
              propagate=str(v[1]).lower()
              v=v[0]
            else:
              propagate=str(self.defaultPropagateAtLaunch).lower()
            self.tags.append({
                'Key': k,
                'Value': v,
                'PropagateAtLaunch':propagate,
            })

    def JSONrepr(self):
        return self.tags

rawDescription: Using troposphere for cloud formation, how do I add "propagate at launch" to tags


code:
df =pd.concat([rep1.stack(),rep2.stack()],axis=1).reset_index().dropna()
df.columns =['GENE','TYPE','REP1','REP2']
df.sort(columns=['TYPE','GENE'], inplace=True)

rawDescription: How to melt two data frames in Pandas

description: Melt two data frames in Pandas


code:
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)

rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code:
# yourapp/management/commands/deletepost.py

from django.core.management.base import BaseCommand, CommandError
from yourapp.models import Post

class Command(BaseCommand):
    help = 'Describe your cmd here'

    def handle(self, *args, **options):
           Post.objects.annotate(...).filter(...).delete()

rawDescription: How to filter using an expression in Django

description: Filter using an expression in Django


rawDescription: Converting an open curve to a list of ordered pixels: a Python test code with numpy


code:
keys = ['CBA.AX','NAB.AX']
pd.concat([cba, nab], axis=1, keys=keys)

rawDescription: concat pandas DataFrame along timeseries indexes

description: Concat pandas DataFrame along timeseries indexes


rawDescription: Python Tkinter Text-Widget scroll to specific line


code:
import webbrowser
webbrowser.open('mailto:', new=1)

rawDescription: Python: launch default mail client on the system


code: is_digital = lambda offers: any(offer.get('digital') for offer in offers)

rawDescription: Reduce a list using lambda

description: Reduce a list using lambda


rawDescription: python tuple name same as value name

description: Python tuple name same as value name


code:
r'\b(\d{9}|\d{2}(?P<sep>[-:\s])\d{3}(?P=sep)\d(?:\d{3})?)\b'
#    ^ exactly nine digits
#         ^ or
#                             ^ sep not optional

rawDescription: regex conditional matching

description: Regex conditional matching


code:
year, week, dow = datetime.today().isocalendar()
result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]

rawDescription: Days/dates in a given week

description: Days/dates in a given week


code:
d = {}
with open("in.txt") as f:
    for line in f:
        spl = line.split(":")[2]
        d.setdefault(spl,[])
        d[spl].append(line)
repeated  =  [v for v in d.values() if len(v) > 1]

rawDescription: Identify duplicate values in specific fields of a multi line file in python


code: long_name_tag = bsObj.find('type', text='route').findPreviousSibling('long_name')

rawDescription: Look for XML tag value and select the parent which contains the requested tag value


code:
for date in Widget.objects.all().dates('sold','month'):
    values["%s_%s" % (date.year,date.month)] = Widget.objects.filter(sold__month=date.month,sold__year=date.year).aggregate(Sum('price'))

rawDescription: Calculate the total value of the Widgets sold each month for a particular year


rawDescription: sort dictionary by multiple keys and values are string,python

description: Sort dictionary by multiple keys and values are string,python


code: BeautifulSoup(markup, "lxml")

rawDescription: What's the relationship between 'BeautifulSoup' and 'lxml'?


code:
import configparser

conf = configparser.ConfigParser()

conf.read('FILE.INI')

rawDescription: Config file for Python with repeated sections/objects


code:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Company)
def chat_entry_created(sender, instance, created, **kwargs):
    if created:
        g = Group.objects.get(name='company')
        g.user_set.add(instance.user)

rawDescription: How to add a Group to every Instance of a Model

description: Add a Group to every Instance of a Model


code:
class Foo(object):
    bar = "bar"
    baz = 1
    class __metaclass__(type):
        def __iter__(self):
            for attr in dir(Foo):
                if not attr.startswith("__"):
                    yield attr

rawDescription: Python: Is it possible to make a class iterable using the standard syntax?


code:
values = (td.fetchText() for td in row)
writer.writerow(values)

rawDescription: Parsing HTML rows into CSV

description: Parsing HTML rows into CSV


code:
def after_6_hours():
    print('6 hours passed.')
    #Better return something

rawDescription: How to schedule a single-time event in Django in Heroku?

description: Schedule a single-time event in Django in Heroku


code: grid_copy = [x[:] for x in grid]

rawDescription: Python - function changing input list, although I made a copy


code: np.genfromtxt('File1.csv', delimiter='\t', names=True, usecols=("Time", "Profit"), unpack=True)

rawDescription: Extract columns using "genfromtxt"

description: Extract columns using "genfromtxt"


code:
def keys(self):
    return self._values.keys()

rawDescription: How to order xml with item fields in scrapy?

description: Order xml with item fields in scrapy


code:
def dictionary(words):
    return dict.fromkeys((word.strip() for word in words), 'yupp')

rawDescription: pulling a dictionary out of the function that created it (python)

description: Pulling a dictionary out of the function that created it (python)


code:
import matplotlib.pyplot as plt

def convert(string):
    plt.figure(frameon=False)
    plt.axes(frameon=0)
    if string[0] != '$' and string[-1] != '$':
        string = '$' + string + '$'
    plt.text(0.01, 0.8, string, fontsize=50)
    plt.xticks(())
    plt.yticks(())
    plt.savefig('D:/latex.png', bbox_inches='tight')
    plt.close()

rawDescription: Matplotlib Image fit to equation?

description: Matplotlib Image fit to equation


code:
for i in range(100):
    b1 = BoxLayout(orientation='horizontal', size_hint_y=None, height=40)
    (...)
    # Update b height
    b.height += b1.height

s.add_widget(b)
return(s)

rawDescription: Increase kivy scrollview window size with increase widget entries


code: {{ somedata | timeuntil | my_time_abbr }}

rawDescription: Django - Timeuntil Tag output abbreviation


code: response.content_type = "text/html"

rawDescription: Set http response Content-Type to "xml" in python


code: [print(input()) for _ in range(int(input()))]

rawDescription: exec in Python 3

description: Exec in Python 3


rawDescription: referring to self from within self in python

description: Referring to self from within self in python


code:
def literal_eval_to_array(literal):
    return np.array(ast.literal_eval(literal))

rawDescription: Pythonic way to convert a list with multiple types (including lists!)


rawDescription: fixed point iteration algorithm

description: Fixed point iteration algorithm


code:
s = df.Data
res = s.str.extract("(?P<experiment>.*?) (?P<first>.*?)-(?P<second>.*)")
res

rawDescription: Pandas splitting strings from text and then inputting into a dataframe


code: print(*iterable, sep="\n")

rawDescription: Is there any single function to print iterables values


rawDescription: How can I sum column values that corrispond to a specific value of another column in a pandas DataFrame?

description: Sum column values that corrispond to a specific value of another column in a pandas DataFrame


rawDescription: Django exclude(**kwargs) help

description: Django exclude(**kwargs) help


code: import random

rawDescription: How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?

description: Randomly pick an item from one of the lists inside a dictionary, and also get the key for the list


code:
def combine_arrays(A):
    return np.dstack(np.meshgrid(*A)).ravel('F').reshape(len(A),-1).T

rawDescription: Combine multi-dimentional data in numpy

description: Combine multi-dimentional data in numpy


code:
import matplotlib.pyplot as plt
import pandas as pd
from pandas.tools.plotting import table

ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df)  # where df is your data frame

plt.savefig('mytable.png')

rawDescription: How to save a pandas DataFrame table as a png

description: Save a pandas DataFrame table as a png


code:
def pop_at_index(seq,index):
    lst = list(seq)
    try:
        del lst[index]
    except IndexError:
        return seq
    return tuple(lst)

rawDescription: Remove number in a tuple

description: Remove number in a tuple


code:
collection = [line.split()[1] for line in open("/etc/mtab")
              if line.split()[1].startswith('/foo/bar')]

rawDescription: python way to get mounted filesystems

description: Python way to get mounted filesystems


code: x = m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS)

rawDescription: Gurobi, How to change a continuous variable to a binary variable


code:
class Particle():  # Python 3
    __slots__ = ['index', 'pos', 'vel', 'F']
    def __init__(self, index=0, pos=None, vel=None, F=None):
        # Particle index (identifier)
        self.index = index
        # Position 3-vector
        self.pos = np.array([0, 0, 0]) if pos is None else pos
        # Velocity 3-vector
        self.vel = np.array([0,0,0]) if vel is None else vel
        # Net force 3-vector (at particle)
        self.F = np.array([0, 0, 0]) if F is None else F

rawDescription: More memory efficient way to define many objects of the same type


code:
n = int(raw_input())
n

rawDescription: Python long integer input

description: Python long integer input


code:
import time

def make_ticker():
    start = time.time()
    def elapsed():
        now = time.time()
        return now-start
    return elapsed

rawDescription: Best way to make a counter based on time

description: Make a counter based on time


code: from firebase import atext

rawDescription: Distinguishing between Python modules of the same name / installing with different name?


rawDescription: Numpy array subtraction creates a matrix with different dimension. How to correct that?


code:
s = '''"
<c>
<d>Hello</d>
</c>
"'''

soup = BeautifulSoup(s, 'html.parser')
unwrapper(soup)

soup
Out[19]: "

Hello

"

rawDescription: BeautifulSoup4 parse everything except specific tags


code:
kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
]

rawDescription: Is this a cleanest way to write a long list in Python?


code:
class RegisteredUser(db.Model):
    """
    loads and pushes registered user data after they have signed up.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "RegisteredUser"

    #all of the columns in the database.
    registered_id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(70))
    last_name = db.Column(db.String(70))
    address_line_one = db.Column(db.String(256))
    address_line_two = db.Column(db.String(256))
    city = db.Column(db.String(50))

    """
    Now we're going to create all of the foreign keys for the RegisteredUser
    table. The db.relationship section allows us to easily and automatically
    join the other tables with registeredUser. The Join will only take place
    if you attempt to access columns from the State or country table.

    For more on Foreign keys using SQLAlchemy go to
    """
    state_id = db.Column(
            db.Integer,
            db.ForeignKey('State.state_id'),
            nullable=False)
    #retrives the users name for display purposes.
    state_by = db.relationship(
            'State',
            foreign_keys=[state_id],
            backref=db.backref('State', lazy='dynamic'))
    country_id = db.Column(
            db.Integer,
            db.ForeignKey('Country.country_id'),
            nullable=False)
    #retrives the users name for display purposes.
    country_by = db.relationship(
            'Country',
            foreign_keys=[country_id],)

    #this is the method and function style I've chosen when lines are too long
    def __init__(
            self,
            first_name,
            last_name,
            address_line_one,
            address_line_two,
            city,
            state_id,
            country_id):
        """
        Used to create a RegisteredUser object in the python server scope

        We will be calling these init functions every time we use
        RegisteredUser() as a 'function' call. It will create a SQLalchemy ORM
        object for us.
        """
        self.first_name = first_name
        self.last_name = last_name
        self.address_line_one = address_line_one
        self.address_line_two = address_line_two
        self.city = city
        self.state_id = state_id
        self.country_id = country_id

class State(db.Model):  # pylint: disable-msg=R0903
    """
    Holds State names for the database to load during the registration page.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "State"

    state_id = db.Column(db.Integer, primary_key=True)
    state_name = db.Column(db.String(10), unique=True)

    def __init__(self, state_name):
        """
        Used to create a State object in the python server scope
        """
        self.state_name = state_name

class Country(db.Model):  # pylint: disable-msg=R0903
    """
    Holds Country names for the database to load during the registration page.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "Country"

    country_id = db.Column(db.Integer, primary_key=True)
    #longest country length is currently 163 letters
    country_name = db.Column(db.String(256), unique=True)

    def __init__(self, country_name):
        """
        Used to create a Country object in the python server scope
        """
        self.country_name = country_name

def create_example_data():
    """
    Generates all of the demo data to be used later in the tutorial. This is
    how we can use our ORM objects to push data to the database.

    NOTE: create_example_data is called at the very bottom of the file.
    """
    #Create a bunch of state models and add them to the current session.
    #Note, this does not add rows to the database. We'll commit them later.
    state_model = State(state_name="WA")
    db.session.add(state_model)
    state_model = State(state_name="AK")
    db.session.add(state_model)
    state_model = State(state_name="LA")
    db.session.add(state_model)
    #Normally I load this data from very large CVS or json files and run This
    #sort of thing through a for loop.

    country_model = Country("USA")
    db.session.add(country_model)
    country_model = Country("Some_Made_Up_Place")
    db.session.add(country_model)
    # Interesting Note: things will be commited in reverse order from when they
    # were added.
    try:
        db.session.commit()
    except IntegrityError as e:
        print("attempted to push data to database. Not first run. continuing\
                as normal")

rawDescription: Creating flask form with selects from more than one table


rawDescription: Forcing immutability on an object

description: Forcing immutability on an object


code:
newqs = urllib.urlencode(qs, doseq=1)
newqs

rawDescription: Updating Query In URL With Urlib In Python


code:
import sys
def nested_scope_detector(func):
    frame = sys._getframe(1)
    nested_scope = frame.f_globals is not frame.f_locals
    redefinition = func.__name__ in frame.f_locals
    if nested_scope: print('{!r} is located in a nested scope.'.format(func))
    if redefinition: print('Redefining {!r}, previously bound to {!r}'.format(
        func.__name__, frame.f_locals[func.__name__]))
    return func

@nested_scope_detector
def foo(): pass

@nested_scope_detector
def foo(): pass

def bar():
    @nested_scope_detector
    def foo(): pass
    @nested_scope_detector
    def foo(): pass

bar()

rawDescription: Capture functions within a closure scope


rawDescription: Python parsing list of string

description: Python parsing list of string


code:
for value in tree.in_order():
    ...

rawDescription: Python in order traversal to a flat list


code:
url(r'^doctor/(?P<slug>[\w-]+)/$', views.showDocProfile, name='showDocProfile'),
url(r'^docprofile/(?P<id>\d+)/$', views.showDocProfileOld, name='showDocProfileOld'),

rawDescription: Django 1.6: Change URL structure

description: Django 1.6: Change URL structure


rawDescription: getting datetime from python string when tzinfo is present

description: Getting datetime from python string when tzinfo is present


code:
hours = dt.seconds / 60 / 60    # Returns number of hours between dates
weeks = dt.days / 7             # number of weeks between dates

rawDescription: How do I subtract two dates in Django/Python?

description: Subtract two dates in Django/Python


code:
data = data.split('|')[1]
data = data.split(',')
data = [d.split('-') for d in data]
data = [(int(d[0]), int(d[1])) for d in data]

positions = range(2, 17)
values = ['A' if any(data[j][1] >= i >= data[j][0] for j in range(len(data))) else 'B' for i in positions]

rawDescription: What is the best way make an array out of my data in python?


code:
def play_move(self, move, kiska_chance):
    m2 = list(list(l) for l in self.pos_matrix)
    x, y = move
    m2[x][y] = kiska_chance

    return m2

rawDescription: Instance variable gets modified automatically


rawDescription: Python Challenge level 17 in Python 3

description: Python Challenge level 17 in Python 3


code:
class MyGraph(nx.Graph):
    def __init__(self, data=None, val=None, **attr):
        super(MyGraph, self).__init__()
        self.val = val

rawDescription: inheriting networkx Graph and using nx.connected_component_subgraphs

description: Inheriting networkx Graph and using nx.connected_component_subgraphs


rawDescription: Aggregate numpy functions

description: Aggregate numpy functions


code:
class A(object):
    x = 0
@copyattributes(A)
class B(object):
    y = 0

B.y
B.x
dir(B)

rawDescription: Python decorator to add class-level variables


code: (cenx, ceny) = (img.shape[1]/2, img.shape[0]/2)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
import numpy as np
data = numpy.array(range(xmin, xmax))

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


code:
class Base(object):
    def get_crumbs(self):
        crumbs = []
        for cls in type(self).__mro__:
            crumbs.extend(getattr(cls, 'crumbs', ()))
        return tuple(crumbs)

rawDescription: Concatenate class variable through inheritance?


rawDescription: Tkinter: How to make a button center itself?


code:
import pandas as pd

data = {'Cities':['Madrid', 'Balbao'] * 3, 'Year':[1999] * 4 + [2000] * 2,
        'Month':['Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Jan'],
        'Mean_Temp':[7, 9, 9, 10, 6.8, 9.2]}

df = pd.DataFrame(data)
df = df[['Cities', 'Year', 'Month', 'Mean_Temp']]

#create dicitonary with the values from 1999
edf = df[df.Year == 1999]
keys = zip(edf.Cities, edf.Month)
values = edf.Mean_Temp
dictionary = dict(zip(keys, values))

def alter(row, dictionary):
    if row['Year'] == 2000 and row['Month'] == 'Jan':
        return dictionary[(row.Cities, row.Month)]
    else:
        return row['Mean_Temp']

df['Mean_Temp'] = df.apply(alter, args = (dictionary,), axis=1)

rawDescription: looping through columns and adjusting values pandas

description: Looping through columns and adjusting values pandas


rawDescription: How do I stop the QTreeWidget from moving the scroll position?

description: Stop the QTreeWidget from moving the scroll position


code: words = [word for line in My_list for word in line.split()]

rawDescription: Getting word count from a python list

description: Getting word count from a python list


code:
#!/usr/bin/env python
from flask import Flask, jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

@app.route('/')
def unicode_json():
    return jsonify({'text': u'\xd1'})

if __name__ == '__main__':
    app.debug = True
    app.run()

rawDescription: Python: how to prevent Unicode representation for Latin1 characters?


code:
import config

class MyFunctionsA(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

class MyFunctionsB(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

class MyFunctionsC(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

rawDescription: Passing a parameter between python classes


code:
import networkx as nx
G = nx.MultiDiGraph()
G.add_edge(1,2,color='green')
G.add_edge(1,2,color='red')
G.edges(data=True)
G.node[1]['layer1']=17
G.node[1]['layer2']=42
G.nodes(data=True)

rawDescription: NetworkX multi-directed graph possible?

description: NetworkX multi-directed graph possible


code: Pfinal = P0 * t + (1 - t) * P1

rawDescription: How can I draw a bezier curve using Python's PIL?

description: Draw a bezier curve using Python's PIL


code:
def upload_file(self, file_from, file_to):
    if file_from.lower().endswith(('.txt', '.csv')):
        with open(file_from, 'r') as f:
            self.connection_id.storelines('STOR {}'.format(file_to), f)
    else:
        with open(file_from, 'rb') as f:
            self.connection_id.storebinary('STOR {}'.format(file_to), f)

rawDescription: FTP_ASCII in Python

description: FTP_ASCII in Python


code:
import copy
color = {'blue': 1, 'red': [], 'green':[]}
original_colors = copy.deepcopy(color)

rawDescription: Comparing dictionary to itself? python

description: Comparing dictionary to itself? python


rawDescription: Unable to handle linspace properly

description: Unable to handle linspace properly


code:
import scipy.optimize

banana = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2
xopt = scipy.optimize.fmin(func=banana, x0=[-1.2,1])

rawDescription: numpy/scipy analog of matlab's fminsearch

description: Numpy/scipy analog of matlab's fminsearch


code:
file = open('file.csv','r')
copy = open('copy.csv','w')
for i in file:
    i = i.split()
    dummy = copy.write(str(i))

rawDescription: How to make Python file-writing faster with IDLE?

description: Make Python file-writing faster with IDLE


code: ['bananas apples y', 'apples oranges x z']

rawDescription: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python


code:
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    sfh = conn.makefile("r+b", bufsize=0)

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = sfh.readline().strip()
        if data == "hello":
                reply = 'OK...Hello back to you'
        else:
                reply = '01:OK - ' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

rawDescription: Simple Python Socket Server Not Taking Conditional Statement


code:
def bubbleSort(l):
  isSorted = False
  while not isSorted:
    isSorted = True
    for i in range(len(l)-1):
      if l[i] > l[i+1]:
        isSorted = False
        l[i], l[i+1] = l[i+1], l[i]

rawDescription: Bubble Sort following an algorithm

description: Bubble Sort following an algorithm


code:
def get_ranks(sd):
    #The first class in the list has rank 1
    k, val = sd[0]
    r = 1
    rank = {k: r}
    #The step size from one rank to the next. Normally
    #delta is 1, but it's increased if there are ties.
    delta = 1

    for k, v in sd[1:]:
        #Update the rank number if this value is
        #greater than the previous.
        if v > val:
            val = v
            r += delta
            delta = 1
        #Otherwise, update delta
        else:
            delta += 1
        rank[k] = r
    return rank

rawDescription: Retrieve the ranking of elements in various list to compute the weighted average of their ranking scores Python


rawDescription: Insertions algorithm in sequence python

description: Insertions algorithm in sequence python


code:
names = str.splitlines()[0].split(',')
types = ('i',) * 3
dtype = zip(names, types)

data = np.empty(2, dtype=dtype)
data[:] = np.genfromtxt(BytesIO(str.encode()), delimiter=',', dtype=dtype,
                        skiprows=1)
print(repr(data))
# array([(0, 0, 1), (1, 0, 2)],
#       dtype=[('x', '<i4'), ('-1', '<i4'), ('1', '<i4')])

rawDescription: How to preserve column names starting with a minus when using numpy.genfromtxt?

description: Preserve column names starting with a minus when using numpy.genfromtxt


code:
text = "Eggs with eggs, bacon and spam are good for breakfast... EGGS!"
replace_keep_case("eggs", "spam", text)

rawDescription: What's the best way to regex replace a string in python but keep its case?


code:
numbers = '0123456789'
alnum = numbers + 'abcdefghijklmnopqrstuvwxyz'

rawDescription: How to iterate through alpha and numeric numbers

description: Iterate through alpha and numeric numbers


code:
def yourview(request):
    yourform = SaleFilterForm(request.POST, user=request.user)

rawDescription: Django - can I get the current user when I'm not in a view function


code:
def map_data(mapping, key_factory_map, *args):
    return {key: get_value(mapping, key, factory, *args)
            for key, factory in key_factory_map.items()}

# …

test_model_data = map_data(kwargs, {
    'fk1': fk1_factory,
    'fk2': fk2_factory,
    # …

    }, i)

rawDescription: Using function value as kwargs.get() default


code: unique_categories = {item.strip() for row in cur for item in row[1].split(",")}

rawDescription: How to create a list while avoiding duplicate?

description: Create a list while avoiding duplicate


code:
single_arg = 'data2'
data = Data.objects.get(id=1)
setattr(data, single_arg, 100)
data.save()

rawDescription: Saving data to a column without deleting others in a Django script


code:
res = []
for i in range(1, len(w)):
    res.append((w[i-1], w[i]))

res

rawDescription: making a list of tuples from a string,,

description: Making a list of tuples from a string,,


rawDescription: How to delete all content of input.txt file after instance.save()?

description: Delete all content of input.txt file after instance.save()


code:
soup.find("p", class_=False, id=False).find_next_sibling(text=True)
soup.find("p", text="YO!").find_next_sibling(text=True)

rawDescription: Scraping elements without an id or class from a web page using Python BeautifulSoup


rawDescription: Status bar for csv file read

description: Status bar for csv file read


code:
from django.conf import settings

# Do something with `settings.DATA_ROOT`

rawDescription: Referencing relative directories outside of project


code:
def saveToFile(fileName, data):
    f = open(fileName, "w")
    f.write(data)
    f.close()

saveToFile("test.txt","This is my data")

rawDescription: Save variable a user input

description: Save variable a user input


code:
import sys
import os
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

rawDescription: How to make process to do some action upon user request in Python?

description: Make process to do some action upon user request in Python


rawDescription: Regex within html tags

description: Regex within html tags


code:
def write (mystr, path): pass

def doThis (f): f ()

def doThisString (mystr, path):
    doThis (lambda: write (mystr, path) )

rawDescription: Reference function's scope while inside another function


code:
regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """A \N{ARABIC SEMICOLON} B""")
regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """He said, "I don't!" """)

rawDescription: How to split string by space and treat special characters as a separate word in Python?

description: Split string by space and treat special characters as a separate word in Python


code:
from functools import total_ordering

@total_ordering
class cons:
    def __init__(self, head, tail=None):
        self.head = head
        self.tail = tail

    @classmethod
    def fromlist(self, l):
        if l == []:
            return None
        return cons(l[0], cons.fromlist(l[1:]))

    def tolist(self):
        if self.tail == None:
            return [self.head]
        else:
            return [self.head] + self.tail.tolist()

    def flip(self):
        if not self.tail == None:
            tmp = self.head
            self.head = self.tail.head
            self.tail.head = tmp

    def __lt__(self, other):
        if other == None:
            return True
        else:
            return self.head < other.head
    def __eq__(self, other):
        if other == None:
            return False
        else:
            return self.head == other.head

def llsort(head):
    changed = True
    while changed:
        changed = False
        current = head
        while current != None:
            if current > current.tail:
                current.flip()
                changed = True
            current = current.tail

rawDescription: Sorting a Sublist in a Linked List Python


rawDescription: Python regexp for data of byte numbers

description: Python regexp for data of byte numbers


code:
for text in "Hi. \nMy name is Alice.\n Let's code".split("\n"):
    run = makeelement('r')
    run.append(makeelement('t', tagtext=text))
    run.append(makeelement('br'))
    body.append(run)

rawDescription: Python Docx Carriage Return

description: Python Docx Carriage Return


code:
#!/usr/bin/env python
import subprocess
import sys

try:
    p = subprocess.Popen([executable, 'loop'])
except EnvironmentError as e: #
    sys.exit('failed to start %r, reason: %s' % (executable, e))
else:
    try: # wait for the child process to finish
        p.wait()
    except KeyboardInterrupt: # on Ctrl+C (SIGINT)
        #NOTE: the shell sends SIGINT (on CtrL+C) to the executable itself if
        #  the child process is in the same foreground process group as its parent
        sys.exit("interrupted")

rawDescription: python kill parent process but child process left

description: Python kill parent process but child process left


code:
import string
from itertools import chain
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews
from nltk import word_tokenize

stop = stopwords.words('english')

# Extracts the documents.
documents = [([w for w in movie_reviews.words(i) if w.lower() not in stop and w.lower() not in string.punctuation], i.split('/')[0]) for i in movie_reviews.fileids()]
# Extract the features.
word_features = FreqDist(chain(*[i for i,j in documents]))
word_features = word_features.keys()[:100]
# Converts documents to features.
train_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag in documents]
# Train the classifier.
classifier = NaiveBayesClassifier.train(train_set)

# Tag the test file.
with open('test.txt', 'r') as fin:
    for test_sentence in fin:
        # Tokenize the line.
        doc = word_tokenize(test_sentence.lower())
        featurized_doc = {i:(i in doc) for i in word_features}
        tagged_label = classifier.classify(featurized_doc)
        print(tagged_label)

rawDescription: Testing the NLTK classifier on specific file


code:
screen = ScreenShot()
image = screen.get_screenshot()
png_file = BytesIO()
image.save_to_callback(png_file.write)
data = png_file.getvalue()

rawDescription: Re-Construct a png image from a GDK Pixbuf


code:
import locale

...

locale.setlocale(locale.LC_ALL, '<desired local>')
# NOTE: using locale.setlocale(locale.LC_ALL, '') will use the machine's default locale defined in the LANG environment variable.

rawDescription: Python program and datetime Localization


code:
from string import maketrans

map = maketrans('aeiou', '0' * 5)
def str_translate(s, map):
    return s.translate(map)

rawDescription: Why is list element replacement slower than string element replacement in python?


code: board = [[[False] * 10] * 22] #Cast the boolean to a list

rawDescription: Defining large list-within- list array

description: Defining large list-within- list array


code:
def main():
    states1 = ["AL", "AK", "AR", "AZ", "CA", "CO", "CT", "DE", "FL", "GA"]
    for words in states1:
        print(words, end=" ")
    states2 = states1[3:7]

rawDescription: Loops/Functions and State abbreviations

description: Loops/Functions and State abbreviations


code:
from xml.etree.ElementTree import XML
single_item_data = XML("<stuff>1 2 3</stuff>").text

rawDescription: Looking to pull out data between two string


code: np.insert(np.delete(a, [1], 1), [1], b, axis=1)

rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code:
UPLOADED_PHOTOS_DEST = '/var/mypics/'
UPLOADED_PHOTOS_URL =  'http://localhost:5000/'

rawDescription: What does UPLOADS_DEFAULT_URL configuration value in flask uploads mean?


code:
def preserveMember(func):
    def dec(self):
        oldMember = self.myMember
        self.myMember = self.myMember[:]
        func(self)
        self.myMember = oldMember
    return dec

rawDescription: Python: a decorator to save and restore data member


rawDescription: Numpy from string (Difference of uint8 and uint16) [Combining two uint8 values to one uint16 value]


code:
for option in options:
    if options[option] is None:
        del(options[option])
# or otherwise only add the ones you actually want to filter on
# then
results = Orchard.objects.filter(**options)

rawDescription: Django: How do I use a string as the keyword in a Q() statement?


code: result = my_string.rsplit('_', 1)[0]

rawDescription: Remove Last instance of a character and rest of a string


code: curs.execute("SELECT my_col = ANY(%s) from my_table", (vals,))

rawDescription: Checking existence of list of python values in psycopg2/postgresql


code:
@app.template_filter('get_block')
def template_filter(block, file):
    html = render_template(file)
    # Then use regex or something to parse
    # or even simple splits (better with named blocks), like...
    content = html.split('{%% block %s %%}'%(block))[-1]
    content = content.split('{%% endblock %%}')[0]
    return content

rawDescription: Including Blocks from Jinja templates

description: Including Blocks from Jinja templates


code:
[v for v in d.values() if len(v) > T] # itervalues for python2
[[{'name': 'abc', 'id': 1}, {'name': 'bc', 'id': 1}, {'name': 'c', 'id': 1}]]

rawDescription: python efficient group by

description: Python efficient group by


code:
def main():
    num_file = open('numbers.txt', 'r')

    for num in num_file:
        print(num.rstrip('\n'), end='')

    num_file.close()
    print('End of file')

main()

rawDescription: Printing integers on the same line reading from a text file


code:
bool('')
bool('foo')

rawDescription: Python - Interesting boolean and string behavior


code:
def Lucas_Lehmer(p):
    s = 4
    M = 2 ** p - 1
    for _ in range(p - 2):
        s = ((s * s) - 2) % M
    return s == 0

Mersenne = [3]
prime = [3]

for i in range(3, 1000):
    t = (2 ** i) - 1
    Mersenne.append(t)

    if Lucas_Lehmer(i):
        prime.append(t)

failed = []

for number in Mersenne:
    if number not in prime:
        failed.append(number)

print('Failed:\n', failed, "\n")
print('Passed:\n', prime)

rawDescription: No value returned when range of tested values extended


code: NORTH_EAST = [x_coordinate + 1, y_coordinate - 1]

rawDescription: How to change the value of an int, and recover and use the new value?

description: Change the value of an int, and recover and use the new value


rawDescription: Converting set of string values to numeric values


code:
with open('text.txt') as f:
    dreader = csv.DictReader(f)
    for row in dreader:
        print(row)

rawDescription: Convert Comma Separated Values to Dict

description: Convert Comma Separated Values to Dict


code:
def makewalk(steps):
  position = 0
  walk = [position]
  for i in xrange(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)
  return walk # instead of simply printing it

rawDescription: how i can repeat loop for random walk?

description: How i can repeat loop for random walk


code:
if(reset_hist):
    History = []

rawDescription: How can I make an HTML button affect the data of a python script when pressed?

description: Make an HTML button affect the data of a python script when pressed


rawDescription: how to speed up enumerate for numpy array / how to enumerate over numpy array efficiently?

description: Speed up enumerate for numpy array / how to enumerate over numpy array efficiently


code:
import numpy as np
x = np.loadtxt('test.dat', dtype = np.float64)
print(x)

rawDescription: Numpy loadtxt rounding off numbers

description: Numpy loadtxt rounding off numbers


code: df['FORECAST'] = df.apply(lambda x: [df['PRICE'][x.name+1:x.name+horizon+1].reset_index(drop=True)], axis=1)

rawDescription: Apply function to pandas dataframe row using values in other rows


code:
value = 165340
numsplits = 5
result = ["{}-{}".format(i + value//numsplits*i, i + value//numsplits*i + value//numsplits) for i in range(numsplits)]

rawDescription: splitting a list dynamically with range and value to split

description: Splitting a list dynamically with range and value to split


code: ssq = np.sum(res**2)

rawDescription: numpy sum of squares for matrix

description: Numpy sum of squares for matrix


code: mask = df['date'] < df['date_threshold']

rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
for n in words:
    if n not in stop_words:
        filtered_sentence.append(' '+n)

rawDescription: How to read a CSV file line by line and store it to new CSV file on new row every time?

description: Read a CSV file line by line and store it to new CSV file on new row every time


code:
def func1():
    x = 3
    def func2():
        print("x=",x,"func2")
        y = 4
        def func3():
            nonlocal x  #try it with nonlocal commented out as well.  See the difference.
            print("x=",x,"func3")
            print("y=",y,"func3")
            z = 5
            print("z=",z,"func3")
            x = 10

        func3()

    func2()
    print("x=",x,"func1")

func1()

rawDescription: In Python what is a global statement?

description: In Python what is a global statement


code: dist = math.sqrt((circle1.x-circle2.x)**2 + (circle1.y-circle2.y)**2) - circle1.r - circle2.r

rawDescription: Distance between two objects

description: Distance between two objects


code:
from random import randint, choice
from string import ascii_lowercase

num_students = 100
max_name_len = 16

with open("rawgrade.txt", "w") as fil:

    # Create random people and grades for the test file
    for i in range(num_students):

        # Create the random name of the person
        ### this can probably be made simpler....
        namelen = randint(1, max_name_len)
        namestr = ''.join([choice(ascii_lowercase) for j in range(namelen)])

        # Create the random grade for the person
        grade = randint(0, 100)

        # Write to file
        fil.write(namestr + " " + str(grade) + "\n")

rawDescription: I have a piece of code that only works for numbers greater than 1000. Any explanation why?


code:
plt.figure(1, figsize=(8, 16))
ax1 = plt.subplot(211)
ax1.imshow(edges,cmap = 'gray')
ax2 = plt.subplot(212)
ax2.axis([0, edges.shape[1], edges.shape[0], 0])
ax2.plot(data[:,1])
plt.show()

rawDescription: OpenCV: fit the detected edges

description: OpenCV: fit the detected edges


code:
# using the list of datetimes from above make a list of strings with specific
# format.  datetime.strftime(format) returns a string in the specified format
short_dates = [d.strftime('%m/%d/%y') for d in dates]

spacing = 2
fig, ax = plt.subplots()
ax.plot(data['ABC'],'r-',label="ABC")
ax.plot(data['DEF'],'b-',label='DEF')
ax.set_xticks(np.arange(len(short_dates)))
ax.set_xticklabels(short_dates)
ax.legend(loc=4, fontsize=10)
plt.xticks(rotation=30)
# for each label in the list of xticklabels
# (we skip every n'th label in this list using [::n]):
# set to not visible
for label in ax.xaxis.get_ticklabels()[::spacing]:
    label.set_visible(False)
plt.show()

rawDescription: Matplotlib - adjusting date spacing on the x-axis


code:
pos = np.where(df.events == 1)[0]
neg = np.where(df.events == 0)[0]
plt.scatter(df.kipp_macht[pos], df.luftb_hydgr_add[pos], 'b+', label='pos')
plt.scatter(df.kipp_macht[neg], df.luftb_hydgr_add[neg], 'rx', label='neg')

rawDescription: Ploting matrix in matplotlib, while taking indexed data for positive and negative values, returns wrong plot axis or data


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


code:
row = 1
while row < height+1:
    row += 1

rawDescription: Converting for loops to while loops in python


code:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
        suffix = '.png',
        src_suffix = '.jpg')
env['BUILDERS']['ConvToPNG'] = ConvToPNG
pix_conversions = [env.ConvToPNG(jpg_src) for jpg_src in Glob('pix/img_*.jpg')]
env.AlwaysBuild(env.Alias('convert_all', pix_conversions))

rawDescription: SCons - convert all images in a directory


rawDescription: tkinter frame border not displaying

description: Tkinter frame border not displaying


code: ['text', 'more', 'words', 't']

rawDescription: Ignore optional suffix without preceding delimiter


code:
class CheatIter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return iter(self.data)

rawDescription: Python: the mechanism behind list comprehension


code: example_list = ["T","e","s","t"]

rawDescription: Python: More efficient way to break down string and append it to a list


code: newprefix = prefix[:]

rawDescription: How to make a shallow copy of a list in Python

description: Make a shallow copy of a list in Python


code: oldimage

rawDescription: NumPy - Image (matrix) thresholding using an intensity value matrix.


rawDescription: Python Numpy: how to count the number of true elements in a bool array


code:
def reversed_lines(self, file):
    "Generate the lines of file in reverse order."
    newline_char_set = set(['\r', '\n'])
    tail = ""
    for block in self.reversed_blocks(file):
        if block is not None and len(block)>0:
            # First split the whole block into lines and reverse the list
            reversed_lines = block.splitlines()
            reversed_lines.reverse()

            # If the last char of the block is not a newline, then the last line
            # crosses a block boundary, and the tail (possible partial line from
            # the previous block) should be added to it.
            if block[-1] not in newline_char_set:
                reversed_lines[0] = reversed_lines[0] + tail

            # Otherwise, the block ended on a line boundary, and the tail is a
            # complete line itself.
            elif len(tail)>0:
                reversed_lines.insert(0,tail)

            # Within the current block, we can't tell if the first line is complete
            # or not, so we extract it and save it for the next go-round with a new
            # block. We yield instead of returning so all the internal state of this
            # iteration is preserved (how many lines returned, current tail, etc.).
            tail = reversed_lines.pop()

            for reversed_line in reversed_lines:
                yield reversed_line

    # We're out of blocks now; if there's a tail left over from the last block we read,
    # it's the very first line in the file. Yield that and we're done.
    if len(tail)>0:
        yield tail

def reversed_blocks(self, file, blocksize=4096):
    "Generate blocks of file's contents in reverse order."

    # Jump to the end of the file, and save the file offset.
    file.seek(0, os.SEEK_END)
    here = file.tell()

    # When the file offset reaches zero, we've read the whole file.
    while 0 < here:
        # Compute how far back we can step; either there's at least one
        # full block left, or we've gotten close enough to the start that
        # we'll read the whole file.
        delta = min(blocksize, here)

        # Back up to there and read the block; we yield it so that the
        # variable containing the file offset is retained.
        file.seek(here - delta, os.SEEK_SET)
        yield file.read(delta)

        # Move the pointer back by the amount we just handed out. If we've
        # read the last block, "here" will now be zero.
        here -= delta

rawDescription: Read file line by line, but in reverse (last line first, then next to last, etc.)


code:
urlpatterns = patterns(
    '',
    url(
        r'^your-url/(?P<student_id>\d+)/$',
        CoursesListView.as_view()
    )
)

rawDescription: Create list in html page passed by detailview object in django


rawDescription: Dynamically add methods to a class in Python 3.0


rawDescription: Convert string to int in a list by removing floating (Python)


code:
class WeddingInviteResponseSerializer(serializers.Serializer):
    response = serializers.BooleanField(required=True)

rawDescription: How to expose model methods to django-rest-framework

description: Expose model methods to django-rest-framework


rawDescription: Built-in function to read __slots__

description: Built-in function to read __slots__


code: df['score'] = (df * weights).sum(axis=1)

rawDescription: Creating a weighted score column from Pandas pivot table


code: d = dict((x.key, x) for x in object_list)

rawDescription: Given two lists in python one with strings and one with objects, how do you map them?


code: [[u'Hot Dogs', u'Food Stands'], [u'Scandinavian', u'Breakfast & Brunch', u'Coffee & Tea'], [u'Burgers']]

rawDescription: Python Remove 2nd item from List within List


code:
import numpy as np
a = np.array(range(3*2*5*5)).reshape(3,2,5,5)

rawDescription: The most effective way to random flip every image in a numpy array


rawDescription: python tkinter tree get selected item values

description: Python tkinter tree get selected item values


code:
import csv

columns_001=['A','D']
f = open("data.csv")
reader = csv.reader(f)

# Get the headers and find the indices we want
headers = [i for i in reader.next()[0].split(' ') if i != '']
indices = [i for i in range(len(headers)) if headers[i] in columns_001]

wanted_times = ['15008', '15012']

result_001 = []
for row in reader:
    row = [i for i in row[0].split(' ') if i != '']

    # Get columns of interest and if they are the wanted values of DT
    cols_of_interest = [row[j] for j in indices if row[0] in wanted_times]
    if cols_of_interest:
        # Add DT
        cols = [row[0]]
        cols.extend(cols_of_interest)
        result_001.append(cols)

new_header = ['DT']
new_header.extend(columns_001)

rawDescription: When I read csv, I want to save specified row


rawDescription: Python script not working if i run it using full path


rawDescription: Python Json Parse

description: Python Json Parse


code:
out = {}
for key, value in original.iteritems():
    out[key[0].upper()] = out.get(key[0].upper(), 0) + value

rawDescription: How to add in a dictionary the values that have similar keys?

description: Add in a dictionary the values that have similar keys


rawDescription: How to create argument of type "list of pairs" with argparse?

description: Create argument of type "list of pairs" with argparse


code: next(x for x in seq if x % 100)

rawDescription: Understanding builtin next() function

description: Understanding builtin next() function


code:
class IndexView(generic.ListView):
  template_name = 'expcore/index.html'
  model = Activity
  context_object_name = 'activities_list'
  queryset = Activity.objects.all()

  def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['interviews_list'] = Interview.objects.all()
    return context

rawDescription: Having two Generic ListViews on the same page


producer: james

rawDescription: How to add documents to an array in a collection using PyMongo

description: Add documents to an array in a collection using PyMongo


code:
foo = "This is a string"
bar = ["this","3"], ["is","5"]
scores = {w: int(n) for w, n in bar}
bar_count = sum(scores.get(word, 0) for word in foo.lower().split())
# 8

rawDescription: Weighted count of words in string using python


code: [len(x) for x in s.split()]

rawDescription: How to get the length of words in a sentence?

description: Get the length of words in a sentence


rawDescription: Pandas set value in groupby

description: Pandas set value in groupby


code:
def your_view(request):
    mobilenumber = request.GET['mobilenumber']
    message = request.GET['message']
    receivedon = request.GET['receivedon']

    # Do what you need

rawDescription: How to get data sent by cloud telephony service using django url?

description: Get data sent by cloud telephony service using django url


code:
import os
from subprocess import STDOUT, check_call as x

with open(os.devnull, 'rb') as DEVNULL, open('output.txt', 'wb') as f:
    x(cmd, stdin=DEVNULL, stdout=f, stderr=STDOUT)

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
def get_list_of_vowel_count(name_list):
    vowels = "aeiouAEIOU"
    for name in name_list:
        yield len([c for c in name if c in vowels])

rawDescription: Counting vowels using nested loop in python


rawDescription: form numpy array from possible numpy array

description: Form numpy array from possible numpy array


code: len(Quests)  # To store this value once and before the code runs again.

rawDescription: Python v3 to store a len value and hold in a variable


code: new_matrix[t, conv[t, z, y, x], y, x] = temp[t, z, y, x]

rawDescription: Python numpy grid transformation using universal functions


code:
import collections
projects = collections.defaultdict(list)
contexts = collections.defaultdict(list)
with open('todo_list.txt') as todo_list:
    for line in todo_list:
        for item in re.findall(r'[+]\D\w+', line):
            projects[item].append(line)
        for item in re.findall(r'[@][A-Z]\w+', line):
            contexts[item].append(line)

rawDescription: Get text surrounding regex match with python


code:
a = ["wxyz", "abce", "abcd", "bcde"]
sorted(a)
sorted(a, key=lambda x:x[:3])

rawDescription: sort lines in text file, but only use the first N characters

description: Sort lines in text file, but only use the first N characters


code:
class DataitemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dataitem

    # Nested serializer
    mod = AssetModelSerializer()

    # Custom create()
    def create(self, validated_data):
        # First we create 'mod' data for the AssetModel
        mod_data = validated_data.pop('mod')
        asset_model = AssetModel.objects.create(**mod_data)

        # Now we create the Dataitem and set the Dataitem.mod FK
        dataitem = Dataitem.objects.create(mod=asset_model, **validated_data)

        # Return a Dataitem instance
        return dataitem

rawDescription: Writable nested serializer in django-rest-framework?


rawDescription: Python: How to convert a string containing hex bytes to a hex string


code:
ind = df.index
df.index = df.index.total_seconds()
df.interpolate(method="index")
df = df.interpolate(method="index")
df.index = ind
df

rawDescription: Cannot interpolate in pandas dataframe

description: Cannot interpolate in pandas dataframe


code:
import pandas
collection=['1.csv','2.csv','3.csv','4.csv']

result = None
for i in collection:
  csv=pandas.read_csv(i)
  if result is None:
    result = csv
  else:
    result = result.merge(csv, on='field1')

if result:
  result.to_csv('output2.csv',index=False)

rawDescription: Python for loop to read csv using pandas


rawDescription: Strip space on either side of word

description: Strip space on either side of word


code:
l[::-1]
l[slice(None,None,-1)]

rawDescription: Slice vs Stride while reversing string

description: Slice vs Stride while reversing string


code:
list_of_tuples = zip(a, b, c)
denormalized = [x for tup in list_of_tuples for x in tup]
plot(*denormalized)

rawDescription: Passing variable length parameters to a function in python


code:
class Availability(models.Model):
    WEEKDAY_CHOICES = (
        (0, 'Monday'),
        (1, 'Tuesday'),
        (2, 'Wednesday'),
        (3, 'Thursday'),
        (4, 'Friday'),
        (5, 'Saturday'),
        (6, 'Sunday'),
    )

    weekday = models.PositiveSmallIntegerField(choices=WEEKDAY_CHOICES)
    start_time = models.TimeField()
    end_time = moels.TimeField()

class Tutor(models.Model):
    available_times = models.ManyToManyField(Availability)

rawDescription: Maintaining teacher availability timings in database


code:
from itertools import groupby
from operator import itemgetter

grouper = itemgetter("dept", "sku")
result = []
for key, grp in groupby(sorted(input_data, key = grouper), grouper):
    temp_dict = dict(zip(["dept", "sku"], key))
    temp_dict["qty"] = sum(item["qty"] for item in grp)
    result.append(temp_dict)

from pprint import pprint
pprint(result)

rawDescription: Group by multiple keys and summarize/average values of a list of dictionaries


rawDescription: grouping by rows in python

description: Grouping by rows in python


rawDescription: Storing these vectors but which data structure to use in Python


code:
import nltk.tag, nltk.data
default_tagger = nltk.data.load(nltk.tag._POS_TAGGER)
model = {'select': 'VB'}
tagger = nltk.tag.UnigramTagger(model=model, backoff=default_tagger)

rawDescription: custom tagging with nltk

description: Custom tagging with nltk


code:
def t(self): a,b=20,20

dis.dis(t)

rawDescription: Is sequence unpacking atomic?

description: Is sequence unpacking atomic


rawDescription: Numpy - assign column data types (dtype) to existing array


code:
AUTHENTICATION_BACKENDS = [
  'django.contrib.auth.backends.ModelBackend',
  'app_name.auth.MyBackend'
]

rawDescription: How to Create A User Model Only Including Username in Django?


code: output

rawDescription: python dictionary with two running totals

description: Python dictionary with two running totals


code:
data = {
    'a': [95, 93, 90],
    'b': [643, 611, 610]
}
lst = list(data.items())
lst1 = list(zip(*[i[1] for i in lst]))
lst1
newlist = []
for aval, bval in lst1:
    newlist.append({lst[0][0]:aval , lst[1][0]:bval})
newlist

rawDescription: Iterate over list of values dictionary

description: Iterate over list of values dictionary


code: set_properties(player, {'x': 1, 'y': 10, 'name': 'John'})

rawDescription: more convenient way to assign variables to class object properties

description: More convenient way to assign variables to class object properties


code:
def test1(a,b,c): pass

def test2(spam, eggs): pass

def test3(): pass

from example import print_varnames
print_varnames(test1)
print_varnames(test2)
print_varnames(test3)

rawDescription: Getting argument list in a Boost:Python function


code:
import pandas as pd
column_list = ['a','b','c','d','e']  # populate this with your column names
df = pd.read_csv('example.csv', header=True, names=column_list)

rawDescription: How to read a CSV by column name using pandas in python?

description: Read a CSV by column name using pandas in python


code:
s = 'aabcc'
import re
re.sub("a([ab])","\\1", s)

rawDescription: translate 'aa' to 'a' and 'ab' to 'b' in python

description: Translate 'aa' to 'a' and 'ab' to 'b' in python


code:
class TestClass():
    saveDirectory = os.path.join(saveDir, 'TestClass')
    def __init__(self):
        pass # do something

rawDescription: Python get class name

description: Python get class name


code:
import collections
import itertools

x=[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]
y=[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]

result={}
for item in itertools.chain(x,y):
    result.setdefault(item[0],item[:1]).extend(item[1:])
result=result.values()
print(result)

rawDescription: Merging Two Outer Lists Based on Iterated Inner List Value


rawDescription: Django urls with empty values

description: Django urls with empty values


code:
class Translation (ndb.Expando):
    """ string_id: language, parent: question.key"""
    pass

rawDescription: What would be the appropiate design for storing content in multiple languages in Google App Engine?


code:
from itertools import groupby

listOut = []
for value, group in groupby(listIn):
    listOut.append(next(group))
    for i in group:
        listOut.append(i)
        break

rawDescription: pythonic way of removing similar items from list

description: Pythonic way of removing similar items from list


rawDescription: np.where on pd.DataFrame for dictionary of non-zero indicies

description: Np.where on pd.DataFrame for dictionary of non-zero indicies


code:
class User:
    ...
    tracks = ManyToManyField(Track)

rawDescription: Django Model Design. Want users to have "Collections" of other model instances


code:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

rawDescription: How can I find all subclasses of a given class in Python?

description: Find all subclasses of a given class in Python


code: open('deck.txt', 'w') # will overwrite it

rawDescription: Card Game Python, Saving a shuffled deck


code:
class bola(pygame.sprite.Sprite):

    def __init__(self, x, y, imagem_bola):
        pygame.sprite.Sprite.__init__(self)
        # always call convert() on loaded images
        # so the surface will have the right pixel format
        self.image = pygame.image.load(imagem_bola).convert()
        self.rect = self.image.get_rect(x=x, y=y)

rawDescription: Pygame - Getting a rectangle for a dynamically drawn object


rawDescription: Python dict.get() with multidimensional dict


rawDescription: Python: fast way to create a list of reps


code:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
     img = ['%s/%s'%(os.path.dirname(os.path.abspath(__file__)),line.strip()) for line in f]

rawDescription: Loading multiple images from a text file


rawDescription: Disable SSL certificate validation in Python


rawDescription: How to use argparse during runtime to conditionally get further input?

description: Use argparse during runtime to conditionally get further input


code:
class Demo:
     STARTED, LOADING, ACTIVE, ENDED = (2**x for x in range(4))

rawDescription: python define a state object

description: Python define a state object


rawDescription: What's the pythonic way to add a certain character after every X elements of a list?


code:
from imdb import IMDb
ia = IMDb()
movie = ia.get_movie('0108778')
movie['title']
movie['series years']

rawDescription: How to get page title in requests

description: Get page title in requests


code:
class postexamhandeler(webapp2.RequestHandler):
    def post(self):
        owner = self.request.get('owner')
        name = self.request.get('ename')
        date = self.request.get('edate')
        leangth = self.request.get('eleangth')
        pencil = self.request.get('epencil')
        pen = self.request.get('epen')
        calculator = self.request.get('ecalculator')
        ruller = self.request.get('eruller')
        type = self.request.get('etype')
        self.response.headers["Content-Type"] = "application/json"
        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.headers['charset'] = "utf-8"
        if len(name) > 0 and len(type) > 0:
            self.response.out.write('{ "response": "OK"}')
        else:
            self.response.out.write('{ "response": "ERROR"}')
        exm = makeexam(id= owner)
        exm.ename = name
        exm.edate = date
        exm.eleangth = leangth
        exm.epencil = pencil
        exm.epen = pen
        exm.ecalculator = calculator
        exm.eruller = ruller
        exm.etype = type
        exm.put()
        self.response.out.write('{ "response": "OK"}')

rawDescription: Having trouble with the same origin policy


code:
class InboundShipmentHeader(AmazonDataType):
    fields = {
        'name': 'ShipmentName',
        'address': 'ShipFromAddress',
        'fulfillment_center_id': 'DestinationFulfillmentCenterId',
        'label_preference': 'LabelPrepPreference',
        'cases_required': 'AreCasesRequired',
        'shipment_status': 'ShipmentStatus',
    }

class Address(AmazonDataType):
    fields = {
        'name': 'Name',
        'address': 'AddressLine1',
        'city': 'City'
    }

address = Address(prefix='ShipFromAddress')
address.name = 'Foo'

header = InboundShipmentHeader()
header.name = 'somevalue'
header.address = address
header.fulfillment_center_id = 'somevalue'
header.label_preference = 'somevalue'
header.cases_required = 'somevalue'
header.shipment_status = 'somevalue'

rawDescription: Most efficient way to add prefix to Python dictionary keys


rawDescription: Index of matching rows in Pandas DataFrame [Python]


code: pageReady = u'content.decode()'

rawDescription: Python Parsing data from site using lxml


code:
def myfunc(name, age, height):
    """Returns a growth-rate for the person based on age and height."""
    return height / age

rawDescription: Python helptip change text

description: Python helptip change text


code:
from tkinter import *

top = Tk()

for i in range(10):
    for j in range(10):

        mb=  Menubutton(top, text="Menu 1")
        mb.menu  =  Menu(mb)
        mb["menu"]  =  mb.menu

        helpmenu = Menu(mb.menu)
        nested_menu1 = Menu(helpmenu)
        nested_menu1.add_command(label='Stuff 1')
        nested_menu1.add_command(label='Stuff 2')

        nested_menu2 = Menu(helpmenu)
        nested_menu2.add_command(label='Stuff 3')
        nested_menu2.add_command(label='Stuff 4')

        menu2_nested = Menu(nested_menu2)
        menu2_nested.add_command(label='Stuff 5')
        nested_menu2.add_cascade(label='Nestception', menu=menu2_nested)

        helpmenu.add_cascade(label='1.0 Nested', menu=nested_menu1)
        helpmenu.add_cascade(label='2.0 Nested', menu=nested_menu2)

        mb.menu.add_cascade(label="Nested Menus", menu=helpmenu)
        mb.grid(row=i, column=j)

top.mainloop()

rawDescription: Adding a menu inside of a menubutton? Python


code:
low_bound = limits[:,:,0]
upp_bound = limits[:,:,1]

mask = np.any((low_bound[:,None,:] <= Y.T[:,:,None]) & ( Y.T[:,:,None] <= upp_bound[:,None,:]),axis=-1).T

rawDescription: From 1D graph to 2D mask

description: From 1D graph to 2D mask


code: response = self.client.get(reverse('payment:pay', args=[plan.payment_id]))

rawDescription: Django urlresolvers reverse for dynamically generated ids


code:
def get_urls(letters):
    url_dict = {}
    for letter in letters:
        top_url = "http://whatever.com/{}/".format(letter)
        result = re.findall("\/([a-z]+[0-9][0-9]\W[a-z]+)", str(urlopen(top_url).read()))
        url_dict[top_url] = result
    return url_dict

rawDescription: Loop to append a list of strings to the strings in another list


code: cursor.execute("""SELECT * FROM president""")

rawDescription: how can i display data in Tkinter treeview fetched from Mysql table using python

description: Display data in Tkinter treeview fetched from Mysql table using python


rawDescription: Python Regular expression Lookahead overshooting pattern


code:
def like(request):
    if request.is_ajax:
        r = Restaurant.objects.get(pk=1)
        r.food_likes +=1
        r.save()
        request.session['is_user_like'] = True
        return HttpResponse(str(r.food_likes))
    else:
        return redirect(request.META.get('HTTP_REFERER'))

rawDescription: prevent user from submitting likes or dislikes multiple times

description: Prevent user from submitting likes or dislikes multiple times


code: C = ['{0:.{1}f}'.format(b, len(a.partition('.')[2])) for a,b in zip(A,B)]

rawDescription: Python string formatting on the fly

description: Python string formatting on the fly


code: b[:, columns_ids] = a[:, columns_ids][b_rows]

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code:
def add(x, y):
    return x + y
sum = reduce(add, L)

rawDescription: Python programming functional vs. imperative code


rawDescription: Read each entire Column of CSV file using python (preferably by help of pandas )


code:
for key in patients[some_person].__dict__:
    value = patients[some_person].__dict__[key]
    # then continue as before

rawDescription: How to rewrite this Dictionary For Loop in Python?

description: Rewrite this Dictionary For Loop in Python


code:
user_says.set(user_says.get() + input_get + "\n")
ia_says.set(ia_says.get() + ia_answers + "\n")

rawDescription: Discussion with tkinter

description: Discussion with tkinter


code:
B = np.random.randint(1, 5, size=(100, 100, 100)).astype(np.double)
z, y, x = np.ogrid[-50:50, -50:50, -50:50]
mask = x**2 + y**2 + z**2 <= 20**2
B[~mask] = 0

struct = ndimage.generate_binary_structure(3, 3)
erode = ndimage.binary_erosion(mask, struct)
edges = mask ^ erode

nonzero_idx = np.vstack(np.where(mask)).T
nonzero_vals = B[mask]

tree = cKDTree(nonzero_idx)

edge_idx = np.vstack(np.where(edges)).T
neighbours = tree.query_ball_point(edge_idx, r=1, p=np.inf)

new_vals = np.hstack(np.mean(nonzero_vals[n]) for n in neighbours)

B_new = B.astype(np.double, copy=True)
B_new[edges] = new_vals

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
from social.pipeline.user import user_details

def populate_info(strategy, details, user=None, *args, **kwargs):
    if (kwargs['is_new']):
        user_details(strategy, details, user, args, kwargs)

rawDescription: Python Social Auth: Not change info for existant user when associating account


code:
def sum_until_found(lst, num):
    if num in lst:
        return sum(lst[:lst.index(num)])
    else:
        return "The number is not in the list!"

rawDescription: Sum a list of numbers until a number X is found


code:
import string
# read and validate alphabet
# read message
print(str.translate(message, str.maketrans(alphabet, string.ascii_uppercase)))

rawDescription: Decrypting Input?

description: Decrypting Input


rawDescription: Ordered Column Constrained Permutations Python


rawDescription: Better algorithm to riffle shuffle (or interleave) multiple lists of varying lengths


code:
-  MyAppFolder
-- Templates
---- images
---- js
---- css
---- fonts
---- assets

rawDescription: How to load .html page with python on app-engine

description: Load .html page with python on app-engine


code: results = MyModel.all().filter('foo =', 'bar').fetch(20)

rawDescription: The App Engine datastore can either return entire entities or only entity keys from a query?


code: pCurvatureAdjustment = ((1 / (1.0 - curvature)) - 1.0) * math.cos(pAngle)

rawDescription: Blending between an N-sided shape and a perfect circle with the same origin?


code:
next(i for i, array in enumerate([Di, Dj, Dk]) if ([5, 5] == array).all(1).any())
#>>> 1

rawDescription: Python - Uniquely determining which text file an element originated from


code:
#!/usr/bin/env python
import os
import random

print(os.getcwd())
os.chdir(random.choice([d for d in os.listdir(os.curdir) if os.path.isdir(d)]))
print(os.getcwd())

rawDescription: How to execute bash from within a python file?

description: Execute bash from within a python file


code:
def normalize(tree, row=0, col=0):
    try:
        node = tree[row][col]
        left  = normalize(tree, row+1, col*2)
        right = normalize(tree, row+1, col*2+1)
        return [node, left, right] if left or right else [node]
    except:
        return None # child index does not exist

rawDescription: Python convert list to tree representation format


code: result

rawDescription: python group by data based on one field of list

description: Python group by data based on one field of list


code: cells_with_enz_or_bio = cells_and_enzymes | cells_and_biochemicals

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
def create_board(self):
    ...
    cmd = lambda row=y, column=x: self.user_input(row, column)
    self.create_button(" O ", cmd, [x,y])

rawDescription: How to determine which button is pressed on a single tkinter object?

description: Determine which button is pressed on a single tkinter object


code:
from datetime import datetime
start = datetime(2013, 1, 1, 13, 37)  # 1:37 on 1/1/2013
ind = pd.date_range(start, periods=50, freq='6H')

rawDescription: Timeseries average with python

description: Timeseries average with python


code:
with open("test.txt") as f:
  connection = {(a, b) : c for a,b,c in (map(int, line.split()) for line in f)}

rawDescription: Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary


code:
teams = ['A','B','C']
goals = [12,1,9]
d = dict(enumerate([t for t,g in zip(teams, goals) for _ in range(g)], 1))
d[5]
d[13]
d[21]

rawDescription: making dictionary from some logic

description: Making dictionary from some logic


code:
from django.db.models import Max
AuthorizedEmail.objects.all().aggregate(Max('added'))

rawDescription: How to get max value in django ORM

description: Get max value in django ORM


rawDescription: How to extract, compare, and transform data from complicated strings using Python?

description: Extract, compare, and transform data from complicated strings using Python


code:
def gensifter(x):
    return (i*x for i in count(x))

rawDescription: Merged iterators produce obscure results


code:
class Baz(object):   # not derived from Foo
    bar = Foo.bar
Baz.bar
Baz.bar.im_class
Baz().bar
Baz().bar()

rawDescription: Not sure what the Python documentation says about user-defined method objects here


code:
import ast

# raw data
data = """
['Marilyn Manson', 'Web', 'Skydera Inc.', 'Stone Sour', 'The Smashing Pumpkins', 'Warner Bros. Entertainment','This is a good Beer']
['Voices Inside', 'Expressivista', 'The Kentucky Fried Movie', 'The Bridges of Madison County']
"""
# set threshold number of tokens
threshold = 3
# split into lines
lines = data.split('\n')
# parse non-blank lines into python lists
lists = [ast.literal_eval(line) for line in lines if line]
# for each list, keep only those tokens with less than `threshold` tokens
result = [[item for item in lst if len(item.split()) < threshold]
          for lst in lists]
# show result
for line in result:
    print(line)

rawDescription: How to split tokens, count number of tokens, and write in a file in python?

description: Split tokens, count number of tokens, and write in a file in python


code:
class EstablecimientoSerializer(serializers.ModelSerializer):
    categoria = serializers.RelatedField()

    class Meta:
        model = Establecimiento
        depth = 1
        fields = ('nombre', 'categoria',)

rawDescription: JSON from django rest Framework

description: JSON from django rest Framework


code:
def recAnswer(current, y, z, count):
    if count == z and current == y:
        return 1

    count += 1
    if count > z:
        return 0

    total = 0
    for i in dict.get(current):
        total += recAnswer(memo, i, y, z, count)

    return total

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code:
def myhostbecomevariables(*hosts):
    for host in hosts:
        print(host)

rawDescription: How do you create multiple variables from raw input in python?

description: Create multiple variables from raw input in python


code: a=float(a)

rawDescription: Bash variables to Python while executing bash script


code:
def sub(x,y):
  return x-y

map(sub, a, b)

rawDescription: How do you subtract list a from list b in Python?

description: Subtract list a from list b in Python