code:
import csv

csv_files = ["1.csv", "2.csv", "3.csv"]

data = {}

for csv_file_name in csv_files:
    with open(csv_file_name, 'rb') as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in list(csv_reader)[1::]:
            if row[0] in data:
                data[row[0]] += int(row[1])
            else:
                data[row[0]] = int(row[1])

with open('output.csv', 'w') as csvfile:
    fieldnames = ['id', 'count']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()

    for key, value in data.items():
        writer.writerow({"id": key, "count": value})

rawDescription: merge csv files in Python

description: Merge csv files in Python


code:
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

rawDescription: How to test with Python's unittest that a warning has been thrown?

description: Test with Python's unittest that a warning has been thrown


code:
from django.shortcuts import get_object_or_404

thread = get_object_or_404(Thread, pk=id)

rawDescription: Best practice to get related list of object to another object in Django


rawDescription: How can I convert a float to a string, but to the sixth decimal - Python

description: Convert a float to a string, but to the sixth decimal - Python


code:
import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

rawDescription: Using subprocess to run Python script on Windows


code:
...
my_request1 = Request(url=myurl1, callback=self.parse_pricing)
yield my_request1
my_request2 = Request(url=myurl2, callback=self.parse_pricing)
yield my_request2
...

rawDescription: Scrapy Deploy Doesn't Match Debug Result


code:
for k in sorted(class1.keys()):
    print("{name} : {score}".format(name=k, score=class1[k][-3:]))

rawDescription: Dictionary Keys in Alphabetical Order with multiple values


code:
s = 'hi'
[ord(c) for c in s]

rawDescription: Convert string to ASCII value python

description: Convert string to ASCII value python


code: q = Kind.all()

rawDescription: How to Fetch all Entity Types in AppEngine

description: Fetch all Entity Types in AppEngine


code:
import numpy as np
import pylab
import scipy.stats as stats

measurements = np.random.normal(loc = 20, scale = 5, size=100)
stats.probplot(measurements, dist="norm", plot=pylab)
pylab.show()

rawDescription: Quantile-Quantile Plot using SciPy

description: Quantile-Quantile Plot using SciPy


code:
def multisplit(s, delims):
    pos = 0
    for i, c in enumerate(s):
        if c in delims:
            yield s[pos:i]
            pos = i + 1
    yield s[pos:]
list(multisplit('hello there[my]friend', ' []'))

rawDescription: python split string on multiple delimeters without regex

description: Python split string on multiple delimeters without regex


code:
import time
time.time()

rawDescription: High-precision clock in Python

description: High-precision clock in Python


code:
class Foo(object):
    def __init__(self, msg):
        self.msg = msg
    def speak(self):
        print(self.msg)

tell_me = Foo.speak
tell_me(Foo("hello!"))

rawDescription: Is it possible to create an instance method object based on the associate class?


rawDescription: Receiving hexadecimal values from socket instead of strings on SocketServer


code:
from __future__ import division
import numpy
import pprint

training = {"outlook":{"sunny":{"yes":2,"no":3},"overcast":{"yes":4,"no":0},"rainy":{"yes":3,"no":2}},\
        "temperature":{"yes":[83,70,68,64,69,75,75,72,81],"no":[85,80,65,72,71]},\
        "humidity":{"yes":[86,96,80,65,70,80,70,90,75],"no":[85,90,70,95,91]},\
        "windy":{"false":{"yes":6,"no":2},"true":{"yes":3,"no":3}},\
        "play":{"yes":9,"no":5}}
processed = {}
total_yes = training["play"]["yes"]
total_no = training["play"]["no"]
total_all = training["play"]["no"]+training["play"]["yes"]

def main():
    for k,v in training.iteritems():
        if (k=='outlook'):
            pass
        if(k != "play"):
            for k2,v2 in v.iteritems():
                if((k2 == "yes") & isinstance(v2,list)):
                    processed[k] = {"yes":{"mean":numpy.mean(v2),"std":numpy.std(v2,ddof=1)}}
                elif((k2 == "no") & isinstance(v2,list)):
                    processed[k].update({"no":{"mean":numpy.mean(v2),"std":numpy.std(v2,ddof=1)}})
                else:
                    if k not in processed:
                        processed[k] = {}

                    for i,j in v2.iteritems():
                        if(i == "yes"):
                            p_yes = j/total_yes
                            processed[k].update({k2:{"yes":p_yes,"no":(1-p_yes)}})

        else:
            processed[k] = {"yes":total_yes/total_all,"no":total_no/total_all}

    pp = pprint.PrettyPrinter(indent=3)
    pp.pprint(processed)

if __name__ == '__main__':
    main()

rawDescription: Python : nested iteritems loop only run once


code:
import re

matches = re.findall(r'(\w+):\s*(\d+)', my_string)
# [('first', '1'), ('second', '2')]

matches = [(x[0], int(x[1])) for x in matches]
# [('first', 1), ('second', 2)]

d = dict(matches)
# {'first': 1, 'second': 2}

rawDescription: Best way to convert str 'key: value\r\nkey:value\r\n' to dict, python

description: Convert str 'key: value\r\nkey:value\r\n' to dict, python


code:
config= None
for loc in os.curdir, os.path.expanduser("~"), "/etc/myproject", os.environ.get("MYPROJECT_CONF"):
    try:
        with open(os.path.join(loc,"myproject.conf")) as source:
            config.readfp( source )
    except IOError:
        pass

rawDescription: Where to put a configuration file in Python?


code:
for op in [('+', operator.add), ('-', operator.sub), ('*', operator.mul), ('/', operator.div)]:
    print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))

rawDescription: Iterate through a sequence of operators

description: Iterate through a sequence of operators


code:
import os.path
os.path.getctime('file1') < os.path.getctime('file2')

rawDescription: Check if the file is newer then some other file?


code:
import datetime

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

with open(timeStamped('myfile.txt'),'w') as outf:
    outf.write('data!')

rawDescription: Python - Add Date Stamp To Text File

description: Python - Add Date Stamp To Text File


rawDescription: Converting string that looks like a list into a real list - python


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

# Some fake data
outname10 = 'test.png'
convolution_locale = np.random.rand(250,250)
convolution_mask_locale = np.random.rand(250,250)
convolution_grande = np.random.rand(250,250)
convolution_mask_grande = np.random.rand(250,250)

# use a nice colormap
plt.viridis()

# Create the figure and subplot instances
fig10, (ax1, ax2, ax3) = plt.subplots(1,3)

step1 = convolution_locale - convolution_mask_locale
fig_step1 = ax1.imshow(step1, interpolation='nearest')
fig10.colorbar(fig_step1,ax=ax1)
ax1.set_xlabel("X (arcmin)")
ax1.set_ylabel("Y (arcmin)")

step2 = convolution_grande - convolution_mask_grande
fig_step2 = ax2.imshow(step2, interpolation='nearest')
fig10.colorbar(fig_step2,ax=ax2)
ax2.set_xlabel("X (arcmin)")
ax2.set_ylabel("Y (arcmin)")

S_N_map = step1 - step2
fig_S_N_map = ax3.imshow(S_N_map, interpolation='nearest')
fig10.colorbar(fig_S_N_map,ax=ax3)
ax3.set_xlabel("X (arcmin)")
ax3.set_ylabel("Y (arcmin)")

# Create space for labels between subplots
fig10.set_tight_layout(True)

fig10.savefig(outname10)

rawDescription: Several colorbars instead one

description: Several colorbars instead one


code: item = list[int(thing) - 1]

rawDescription: Pythonic way to perform a large case/switch


code:
objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

rawDescription: How to create multiple class objects with a loop in python?

description: Create multiple class objects with a loop in python


code:
import csv

with open('checkfile.csv', 'rb') as checkfile:
    product_result = {
        record['ProductCode']: record for record in csv.DictReader(checkfile)}

with open('infile.csv', 'rb') as infile:
    with open('outfile.csv', 'wb') as outfile:
        reader = csv.DictReader(infile)
        writer = csv.DictWriter(outfile, reader.fieldnames)
        writer.writeheader()
        for item in reader:
            record = product_result.get(item['SKU'], None)
            if record:
                item['ChannelProfileID'] = record[' Stock']  # ???
                item['CostPrice'] = record[' CostPrice']
            else:
                item['ChannelProfileID'] = None
                item['CostPrice'] = None
            writer.writerow(item)

rawDescription: Merge CSV files in Python using Python Dictionary


code:
from flask.ext.login import current_user

@app.route(...)
def main_route():
    if current_user.is_authenticated():
         return render_template("main_for_user.html")
    else:
         return render_template("main_for_anonymous.html")

rawDescription: Flask-Login check if user is authenticated without decorator


code:
try:
  import optparse
except ImportError:
  import external.optparse as optparse

rawDescription: conditional command-line arguments [ possibly using getopt()?? ]

description: Conditional command-line arguments [ possibly using getopt()?? ]


code:
cur = 0
res = []
with open("file.txt") as f:
    for line in f:
        if line.strip() == '0':
            cur += 1
        else:
            res.append(cur)
            cur = 0

rawDescription: Count number of specific elements in between other elements in list


code:
entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
    for key in entries:
        if key in the_dict:
            del the_dict[key]

rawDescription: Removing multiple keys from a dictionary safely


code: [isvowel(ch) for ch in string].index(True)

rawDescription: In Python, how can I use string.find to find the first occurence of a vowel and do something with it?


code:
class hashabledict(dict):
    def __hash__(self):
        return hash(tuple(sorted(self.items())))

rawDescription: Python hashable dicts

description: Python hashable dicts


code: formatter = logging.Formatter('[num-%d] %%(levelname)s %%(message)s' % (num,))

rawDescription: Partial String Formatting in Python Logging Formatters


code:
import gzip
content = "Lots of content here"
real_f = open('/home/joe/file.txt.gz', 'wb')
f = gzip.GZipFile('file.txt.gz', fileobj = realf)
f.write(content)
f.close()
real_f.close()

rawDescription: Python gzip folder structure when zipping single file


code:
for x in xrange(1,6): # starts at 1 and goes to 5
    print ("value" + str(x) + ".png")
value1.png
value2.png
value3.png
value4.png
value5.png

rawDescription: Saving figures in a loop

description: Saving figures in a loop


code:
heap = []
counter = itertools.count()
for i in range(10):
    heapq.heappush(heap, (i, -next(counter), str(i) + ' oldest'))
    heapq.heappush(heap, (i, -next(counter), str(i) + ' newest'))

heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)

rawDescription: Tie breaking in a priority queue using python


code: output = response.read()

rawDescription: How can I read()/write() against a python HTTPConnection?

description: Read()/write() against a python HTTPConnection


code:
import timeit

def timefunc(function, *args):
    def wrap():
        function(*args)
    t = timeit.Timer(wrap)
    return t.timeit(100)

def test(arg):
    foo = arg

print(timefunc(test, 'bar'))

rawDescription: How do I pass *args to my timeit.Timer object?

description: Pass *args to my timeit.Timer object


code:
from django.db.models import Count

query = models.Host.objects.filter(
    host_id=host.id,
    timestamp__gt=datetime.datetime.strptime(from_time,'%Y-%m-%d'),
    timestamp__lt=datetime.datetime.strptime(to_time, '%Y-%m-%d'),
    server__isnull=False).values('server').annotate(server_count=Count('server'))

rawDescription: How to write this query in Django

description: Write this query in Django


code:
def fry(spam):
  spam += 1

eggs = 3
fry(eggs)
eggs # still 3!

rawDescription: Python C API: Call a Python function with argument(s) passed by reference


rawDescription: I can't solve expression involving str.find()


code:
def depth(x):
    if type(x) is dict and x:
        return 1 + max(depth(x[a]) for a in x)
    if type(x) is list and x:
        return 1 + max(depth(a) for a in x)
    return 0

rawDescription: How to find the maximum "depth" of a python dictionary or JSON object?

description: Find the maximum "depth" of a python dictionary or JSON object


code:
def all_unexpired_sessions_for_user(user):
    user_sessions = []
    all_sessions  = Session.objects.filter(expire_date__gte=datetime.datetime.now())
    for session in all_sessions:
        session_data = session.get_decoded()
        if user.pk == session_data.get('_auth_user_id'):
            user_sessions.append(session.pk)
    return Session.objects.filter(pk__in=user_sessions)

def delete_all_unexpired_sessions_for_user(user, session_to_omit=None):
    session_list = all_unexpired_sessions_for_user(user)
    if session_to_omit is not None:
        session_list.exclude(session_key=session_to_omit.session_key)
    session_list.delete()

rawDescription: Most optimized way to delete all sessions for a specific user in Django?


rawDescription: wrap strings in html tags python

description: Wrap strings in html tags python


code:
import numpy as np
int(np.asscalar(x.shape[1].eval()))

rawDescription: Get the value of tensor in theano

description: Get the value of tensor in theano


code:
a
a.x2 = a.x2.shift(1)
a

rawDescription: How to shift a column in Pandas DataFrame

description: Shift a column in Pandas DataFrame


rawDescription: Double integral with function and sampled data Python


code:
import boto.ec2
from boto.manage.cmdshell import sshclient_from_instance

# Connect to your region of choice
conn = boto.ec2.connect_to_region('us-west-2')

# Find the instance object related to my instanceId
instance = conn.get_all_instances(['i-12345678'])[0].instances[0]

# Create an SSH client for our instance
#    key_path is the path to the SSH private key associated with instance
#    user_name is the user to login as on the instance (e.g. ubuntu, ec2-user, etc.)
ssh_client = sshclient_from_instance(instance,
                                     '<path to SSH keyfile>',
                                     user_name='ec2-user')
# Run the command. Returns a tuple consisting of:
#    The integer status of the command
#    A string containing the output of the command
#    A string containing the stderr output of the command
status, stdout, stderr = ssh_client.run('ls -al')

rawDescription: Boto Execute shell command on ec2 instance


code:
req = urllib2.Request(url=url,
                      data=xml_string,
                      headers={'Content-Type': 'application/xml'})
urllib2.urlopen(req)

rawDescription: How to POST an xml element in python

description: POST an xml element in python


code:
while current_index<256:
    url = "http://www.imdb.com/search/title?at=0&sort=user_rating&start="\
    +str(current_index)+"&title_type=feature&year=2005,2014"
    ...
    ...
    current_index+=50
return final_list

rawDescription: reading multiple webpages using loop

description: Reading multiple webpages using loop


code:
def itemIsDict(item):
    return isinstance(item, dict)

rawDescription: python: printing a list, & special-casing dicts

description: Python: printing a list, & special-casing dicts


rawDescription: Grouping by a ForeignKey, and ForeignKeys that are another 'step' away


code:
if specials:
  special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))]
else:
  special_smoothies = smoothies[:]

rawDescription: How should I write this string-prefix check so that it's idiomatic Python?


code:
info = np.zeros(shape=(no_of_label+1,19),dtype=float)

for i in np.arange(1,no_of_label+1,1):
    info[i-1] = [C[0],C[1],C[2],i,int(round(C[0]-b)),int(round(C[1]-b)),int(round(C[2]-b)),int(round(C[0]+b)),int(round(C[1]+b)),int(round(C[2]+b)),volume,0,0,0,0,0,0,0,0]

np.savetxt(save_path+Folder+'/Data_'+Folder+'.csv',information,fmt = '%10.5f' ,delimiter=",",header='Xpos,Ypos,Zpos,NodeNumber,BoundingBoxTopX,BoundingBoxTopY,BoundingBoxTopZ,BoundingBoxBottomX,BoundingBoxBottomY,BoundingBoxBottomZ,BoxVolume,Xdisp,Ydisp,Zdisp,Xrot,Yrot,Zrot,CC,Error',comments='')

rawDescription: How to create a table in Python that has headers (text), filled with values (int and float)

description: Create a table in Python that has headers (text), filled with values (int and float)


rawDescription: Can custom formatting through the % operator be done in Python?


code:
for i, data in enumerate(csv_stuff):
    rec = MyORMObject()
    rec.set_stuff(data)
    session.add(rec)
    if i % 1000 == 0:
        session.flush()
session.commit() # flushes everything remaining + commits

rawDescription: Reading large files using SQLalchemy

description: Reading large files using SQLalchemy


code:
import matplotlib.pyplot as plt

def my_plot_1(ax=None):
    if ax is None:
      ax = plt.gca()
    ax.plot([1, 2, 3], 'b-')

def my_plot_2(ax=None):
    if ax is None:
      ax = plt.gca()
    ax.plot([3, 2, 1], 'ro')

def my_combo_plot():
    ax1 = plt.subplot(1,2,1)
    ax2 = plt.subplot(1,2,2)
    my_plot_1(ax1)
    my_plot_2(ax2)

rawDescription: matplotlib - duplicate plot from one figure to another?

description: Matplotlib - duplicate plot from one figure to another


code:
import locale
locale.setlocale(locale.LC_ALL, "C")
yourList.sort(cmp=locale.strcoll)

rawDescription: Is Python's sort function the same as Linux's sort with LC_ALL=C


code:
from selenium.webdriver import ActionChains

elem = driver.find_element_by_css_selector("#imagecpt")

action_chain = ActionChains(driver)
action_chain.move_to_element(elem)
action_chain.perform()

loc, size = elem.location_once_scrolled_into_view, elem.size
left, top = loc['x'], loc['y']

width, height = size['width'], size['height']
box = (int(left), int(top), int(left + width), int(top + height))

screenshot = driver.get_screenshot_as_base64()
img = Image.open(StringIO.StringIO(base64.b64decode(screenshot)))

captcha = img.crop(box)
captcha.save('captcha.png', 'PNG')

rawDescription: Python Selenium capture captcha in a scroll down page


code:
serializer = MyModelSerializer(object)
data = serializer.data
data['any_key'] = 'Any Value'
return Response(data)

rawDescription: How to add fields not in the model Django Restframework

description: Add fields not in the model Django Restframework


code:
line(x, y)
circle(x, y, size=8, alpha=0)

rawDescription: adding tooltips to line plots in bokeh

description: Adding tooltips to line plots in bokeh


code:
a = range(10)
a
del a[-1]
a

rawDescription: How to remove an element from a list by index in Python?

description: Remove an element from a list by index in Python


code:
# -*- coding: utf-8 -*-

import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt

plt.plot(range(10))
# you might need to change this to be a font that you know works for your gylphs
# that you have installed
plt.xlabel(u'وَبَوِّئْنا', name='Arial')

plt.savefig('test.jpg',format='jpg')

rawDescription: generating a JPG with matplotlib with UTF-8 labels when DISPLAY is undefined in python

description: Generating a JPG with matplotlib with UTF-8 labels when DISPLAY is undefined in python


code:
def isWordGuessed(secretWord, lettersGuessed):
    return set(secretWord) <= set(lettersGuessed)

rawDescription: How to find if a secret word contains all the characters from a list?

description: Find if a secret word contains all the characters from a list


code:
data2['merged'] = data2['dashcoin']

# LEAVE OUT FIRST ELEMENT
for coin in coins[1:]:
      data2['merged'] = data2['merged'].merge(data2[coin], on='timestamp')

rawDescription: Merging dataframes together in a for loop


code: assert len(function_returns_list()) == 0, "the list is non empty"

rawDescription: assertTrue() in pytest to assert empty lists

description: AssertTrue() in pytest to assert empty lists


code:
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    if self.default:
        # At this point self.pk will exist whether
        # this was a new or updated instance.
        # Using update() allows this to run in a single query
        # (plus the query for super().save(), of course).
        OptionModel.objects.exclude(pk=self.pk).update(default=False)

rawDescription: When one option set to True all others set to False (BooleanField)


code:
class ComposerCorrection(models.Model):
    wrong_name = models.CharField(max_length=100, unique=True)
    canonical_name = models.CharField(max_length=100)

def correct_name(name):
    try:
        return ComposerCorrection.objects.get(wrong_name=name).canonical_name
    except ComposerCorrection.DoesNotExist:
        return name

rawDescription: How to handle data correction in Django (but this isn't Django-specific!)

description: Handle data correction in Django (but this isn't Django-specific!)


rawDescription: How to standardize/normalize a date with pandas/numpy?

description: Standardize/normalize a date with pandas/numpy


code:
import concurrent.futures

def foo():
    a = 5

    with ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(dosomething)
        future.add_done_callback(on_something_done)
        #print(future.result())

    #continue without waiting dosomething()
    #future.cancel() #To cancel dosomething
    #future.done() #return True if done.

    return a

def on_something_done(future):
    print(future.result())

rawDescription: How to execute a Python function within a function and not stop the execution

description: Execute a Python function within a function and not stop the execution


code:
line="a sentence with a few words"
line.split()

rawDescription: How to Break a sentence into a few words

description: Break a sentence into a few words


code: [y - x for x,y in zip(L,L[1:])]

rawDescription: Subtracting the current and previous item in a list


code:
from csv import DictReader

with open("abc.csv") as f:
    a1 = [row["a"] for row in DictReader(f)]

with open("bac.csv") as f:
    a2 = [row["a"] for row in DictReader(f)]

# a1 == a2 == ['1', '4', '7']

rawDescription: Convert CSV column to list

description: Convert CSV column to list


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(your_text)
description = soup.find('a').string

rawDescription: extracting specific content from html page

description: Extracting specific content from html page


code:
import math
math.ceil(float(177)/10)

rawDescription: Calculation to get page count based on # of items


code:
dates=['January 26, 1991', 'February 29, 2012', 'December 10, 2094']
def converter(x):
   x=x.split()
   dic={'January':'01','February':'02','March':'03','April':'04','May':'05','June':'06',
         'July':'07','August':'08','September':'09','October':'10','November':'11','December':'12'
        }
   month,day,year=dic[x[0]],x[1][:-1],x[2]
   if len(day)==1:
     day='0'+day

   return month+day+year

new_lis=[]

for x in dates:
   new_lis.append(converter(x))

print(new_lis)

['01261991', '02292012', '12102094']

rawDescription: How can I change textual dates to numbered ones in Python?

description: Change textual dates to numbered ones in Python


rawDescription: django make ModelChoiceField non-editable

description: Django make ModelChoiceField non-editable


code:
class ImageInline(admin.TabularInline):
    model = Image
    ...

class QuestionAdmin(admin.ModelAdmin):
    list_display = ('content', 'category', )
    list_filter = ('category',)
    fields = ('content', 'category', 'quiz', 'explanation')

    search_fields = ('content', 'explanation')
    filter_horizontal = ('quiz',)

    inlines = [AnswerInline, ImageInline]

rawDescription: Adding 2 models inside a Admin Manager

description: Adding 2 models inside a Admin Manager


rawDescription: The proper usage of all () function

description: The proper usage of all () function


code:
if hasattr(myClassInstance, 'methodName'):
    ...  # Whatever you want to do as a result.

rawDescription: How to verify Class attribute or method exists

description: Verify Class attribute or method exists


code:
import matplotlib
from tkinter import *

def main():

    fig = matplotlib.figure.Figure(figsize=(16.8, 8.0))

    root = Tk()
    w = Label(root, text="Close this and it will not hang!")
    w.pack()
    root.mainloop()

    print('Code *does* reach this point')

if __name__ == '__main__':
    main()

rawDescription: Tkinter/Matplotlib backend conflict causes infinite mainloop


code:
from bokeh.plotting import *
from numpy import pi

# define starts/ends for wedges from percentages of a circle
percents = [0, 0.3, 0.4, 0.6, 0.9, 1]
starts = [p*2*pi for p in percents[:-1]]
ends = [p*2*pi for p in percents[1:]]

# a color for each pie piece
colors = ["red", "green", "blue", "orange", "yellow"]

p = figure(x_range=(-1,1), y_range=(-1,1))

p.wedge(x=0, y=0, radius=1, start_angle=starts, end_angle=ends, color=colors)

# display/save everythin
output_file("pie.html")
show(p)

rawDescription: How do I create a pie chart using Bokeh?

description: Create a pie chart using Bokeh


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

list1 = [1,2,3,4]
list2 = [4,3,2,1]
list3 = [4,1,2,4]

somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

gs = gridspec.GridSpec(4,1)

if not somecondition:
    ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(gs[:2, :])
    ax.plot(list1)
    ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
    ax = plt.subplot(gs[3, :]) #create the second subplot, that MIGHT be there
    ax.plot(list3)
plt.show()

rawDescription: Matplotlib: adding a third subplot in the plot


code:
def rotationToVtk(R):
    '''
    Concert a rotation matrix into the Mayavi/Vtk rotation paramaters (pitch, roll, yaw)
    '''
    def euler_from_matrix(matrix):
        """Return Euler angles (syxz) from rotation matrix for specified axis sequence.
        :Author:
          `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_

        full library with coplete set of euler triplets (combinations of  s/r x-y-z) at
            http://www.lfd.uci.edu/~gohlke/code/transformations.py.html

        Note that many Euler angle triplets can describe one matrix.
        """
        # epsilon for testing whether a number is close to zero
        _EPS = np.finfo(float).eps * 5.0

        # axis sequences for Euler angles
        _NEXT_AXIS = [1, 2, 0, 1]
        firstaxis, parity, repetition, frame = (1, 1, 0, 0) # ''

        i = firstaxis
        j = _NEXT_AXIS[i+parity]
        k = _NEXT_AXIS[i-parity+1]

        M = np.array(matrix, dtype='float', copy=False)[:3, :3]
        if repetition:
            sy = np.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k])
            if sy > _EPS:
                ax = np.arctan2( M[i, j],  M[i, k])
                ay = np.arctan2( sy,       M[i, i])
                az = np.arctan2( M[j, i], -M[k, i])
            else:
                ax = np.arctan2(-M[j, k],  M[j, j])
                ay = np.arctan2( sy,       M[i, i])
                az = 0.0
        else:
            cy = np.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i])
            if cy > _EPS:
                ax = np.arctan2( M[k, j],  M[k, k])
                ay = np.arctan2(-M[k, i],  cy)
                az = np.arctan2( M[j, i],  M[i, i])
            else:
                ax = np.arctan2(-M[j, k],  M[j, j])
                ay = np.arctan2(-M[k, i],  cy)
                az = 0.0

        if parity:
            ax, ay, az = -ax, -ay, -az
        if frame:
            ax, az = az, ax
        return ax, ay, az
    r_yxz = pl.array(euler_from_matrix(R))*180/pi
    r_xyz = r_yxz[[1, 0, 2]]
    return r_xyz

rawDescription: Correct conversion from rotation matrix to (pitch, roll, yaw) for Mayavi/Vtk


code:
def move():
    if some_condition:
        return
    ...
    root.after(1000, move)

rawDescription: Stopping a Tkinter window without closing it


code:
class BaseModel(models.Model):
    # some fields here

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        first_declared_field = self.__class__._meta.fields[1].name

        if self.__class__.objects.count():
            latest = getattr(self.__class__.objects.order_by('-' + first_declared_field)[0], first_declared_field)
        else:
            latest = 'XXX00000'

        field_value = first_declared_field.name.split('_')[0].upper() + str(int(latest[3:]) + 1).zfill(5)
        setattr(self, first_declared_field, field_value)

        super(BaseModel, self).save(*args, **kwargs)

class SomeChildModel(BaseModel):
    pass

rawDescription: Django multiple similar models

description: Django multiple similar models


rawDescription: For certain rows, copying values of a set of columns to another, of the same data frame


code:
sqlalchemy.orm.Query(AlphabetTable) \
    .filter(AlphabetTable.letter.in_("gack")) \
    .order_by(sqlalchemy.sql.expression.case(((AlphabetTable.letter == "g", 1),
                                              (AlphabetTable.letter == "a", 2),
                                              (AlphabetTable.letter == "c", 3),
                                              (AlphabetTable.letter == "k", 4))))

rawDescription: SQLAlchemy ORDER BY FIELD()

description: SQLAlchemy ORDER BY FIELD()


code:
import os

def get_files(path, option_dirs, option_subdirs, option_no_ro, option_no_hid):
    outfiles = []
    for root, dirs, files in os.walk(path):
        if option_no_hid:
            # In linux, hidden files start with .
            files = [ f for f in files if not f.startswith('.') ]
        if option_no_ro:
            # Use os.path.access to check if the file is readable
            # We have to use os.path.join(root, f) to get the full path
            files = [ f for f in files if os.access(os.path.join(root, f), os.R_OK) ]
        if option_dirs:
            # Use os.path.join again
            outfiles.extend([ os.path.join(root, f) for f in files ])
        else:
            outfiles.extend(files)
        if not option_subdirs:
            # If we don't want to get subdirs, then we just exit the first
            # time through the for loop
            return outfiles
    return outfiles

rawDescription: Python - get list of all files from a folder (with more options)


code: map(partial(cosine,v=A), M.transpose())

rawDescription: map a function to all columns for Scipy/numpy matrix

description: Map a function to all columns for Scipy/numpy matrix


code:
for x in reads_array:
    alignments =pairwise2.align.globalms(str(refseq.seq).upper(),str(x.seq),2,-1,-5,-0.05)
    sorted_alignments = sorted(alignments, key=operator.itemgetter(2))

    result.write(format_alignment(*sorted_alignments[0]))
    aligned_reads.append(x)

rawDescription: reporting the best alignment with pairwise2

description: Reporting the best alignment with pairwise2


code: [item[2] for item in viewData]

rawDescription: List of tuples not indexing as expected

description: List of tuples not indexing as expected


code: df2['store'] + df2['style'] + df2['color'].astype(str) + df2['size'].astype(str)

rawDescription: concatenate values of string column and long column in panda dataframe

description: Concatenate values of string column and long column in panda dataframe


code:
a = ("This is a really long\n"
     "line of text that I\n"
     "need to show to the user.")

print(a)

rawDescription: How to make paragraphs readable within python code

description: Make paragraphs readable within python code


code:
import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
main = QtGui.QMainWindow()
menubar = QtGui.QMenuBar()

menus = []
submenus = {}
for x in range(10):
    # top menus
    menu = QtGui.QMenu('Top %d' % x)
    menus.append(menu)

    # set direction
    menu.setLayoutDirection(QtCore.Qt.RightToLeft)

    # add to menubar
    menubar.addMenu(menu)

    for y in range(5):
        # a sub-menu
        submenu = QtGui.QMenu('Level 1 - %d' % y)

        # some dummy actions
        submenu.addAction('Level 2 - 1')
        submenu.addAction('Level 2 - 2')

        # keep reference
        submenus[(x,y)] = submenu
        # add to the top menu
        menu.addMenu(submenu)

main.setMenuBar(menubar)
main.show()

sys.exit(app.exec_())

rawDescription: PyQt QMenu dropdown direction

description: PyQt QMenu dropdown direction


code:
reader = csv.reader(f1)
rows = list(reader)
cols = zip(*rows)
Min = cols[1]
Mean = cols[2]
Max = cols[3]

# or if you really want numpy.arrays
Min = numpy.array(cols[1]) #dtype will be auto-assigned
Mean = numpy.array(cols[2]) #dtype will be auto-assigned
Max = numpy.array(cols[3]) #dtype will be auto-assigned

rawDescription: Writing string entries in a csv to an array in python?


code:
from itertools import product
lst = [ [1,2,3], [4,5,6], [7,8,9] ]

list(product(*lst))

rawDescription: Manipulation of large lists in python

description: Manipulation of large lists in python


code:
last_seconds = None
while True:
    # Run game
    r = int(pygame.time.get_ticks)
    seconds = r / 1000
    if seconds != last_seconds:
        print(seconds)
        last_seconds = seconds

rawDescription: Pygame - Printing out seconds using Time


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# generate dummy data (graphene tight binding band structure)
kvec = np.linspace(-np.pi,np.pi,101)
kx,ky = np.meshgrid(kvec,kvec)
E = np.sqrt(1+4*np.cos(3*kx/2)*np.cos(np.sqrt(3)/2*ky) + 4*np.cos(np.sqrt(3)/2*ky)**2)

# plot full dataset
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(kx,ky,E,cmap='viridis',vmin=-E.max(),vmax=E.max(),rstride=1,cstride=1)
ax.plot_surface(kx,ky,-E,cmap='viridis',vmin=-E.max(),vmax=E.max(),rstride=1,cstride=1)

# focus on Dirac cones
Elim = 1  #threshold
E[E>Elim] = np.nan

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#ax.plot_surface(kx2,ky2,E2,cmap='viridis',vmin=-Elim,vmax=Elim)
#ax.plot_surface(kx2,ky2,-E2,cmap='viridis',vmin=-Elim,vmax=Elim)
ax.plot_surface(kx,ky,E,cmap='viridis',rstride=1,cstride=1,vmin=-Elim,vmax=Elim)
ax.plot_surface(kx,ky,-E,cmap='viridis',rstride=1,cstride=1,vmin=-Elim,vmax=Elim)

plt.show()

rawDescription: Only plot part of a 3d figure using matplotlib


code:
[Pers1]
name = Alice
sex = female
tags.COMPANY = Macrosoft
tags.EMPLOYEE_SINCE = 1/5/2005

rawDescription: Can I use configparser to make a dictionary of dictionaries?

description: Use configparser to make a dictionary of dictionaries


code:
a = np.arange(8).reshape(2,2,2)
np.dstack((a, a))
np.dstack((a, a)).shape

rawDescription: Attach two 3d numpy arrays in Python

description: Attach two 3d numpy arrays in Python


code:
def prime_list(X, Y):
    Z = []
    while X <= Y:
        if is_prime(X):
            Z.append(X)
        X = X + 1
    return Z

rawDescription: Python: Removing unnecessary brackets?

description: Python: Removing unnecessary brackets


code:
import urllib
from json import loads # JSON parser

jsontext = urllib.urlopen("https://io.winmasters.com/Feeds/api/event/282576?lang=el").read()
data = loads(jsontext) # Parse the JSON

odds = [[b['odds'] for b in a['children']] for a in data['children']]

rawDescription: Downloading a web page and searching a text with python


code:
doc = {
       'name': name,
       'postDate': datetime.datetime.now(),
       'valid': "true",
       'suggest': {
           "input": name,
           'output': name,
           'payload': {'domain_id': id}
           }
       }
es = elasticsearch.Elasticsearch()
res = es.index(index=ES_INDEX_NAME, doc_type=ES_DOC_TYPE, id=id, body=doc, timeout=30)

rawDescription: ElasticSearch ConnectionPool using elasticsearch-py library


code:
dict = {'a':'4', 'b':"|3"}

str = "ab"

for i in range(len(str)):

    print(dict[str[i]])

rawDescription: L33Tify.py Converting characters with a dictionay


code:
all_animals = Animals.objects.prefetch_related('categories')
categories = [animal.categories.all() for animal in all_animals]

rawDescription: How to get all children of queryset in django?

description: Get all children of queryset in django


code:
from itertools import chain
from django.db.models import Q, Count

qs = House.objects.all()
q = {'room__beds__gt': 0}
qs_with = qs.filter(Q(**q)).annotate(bedrooms=Count('room'))
qs_without = qs.filter(~Q(**q)).extra(select={'bedrooms': 0})
qs_all = chain(qs_with, qs_without)

rawDescription: Django ORM: count related objects with a feature


code:
handlers = {'SIGTERM': self.bus.exit,
        'SIGHUP': self.handle_SIGHUP,
        'SIGUSR1': self.bus.graceful,
       }

rawDescription: Make CherryPy exit immediately upon receiving a keyboard interrupt?


code:
class _Helper(object):
    """Define the built-in 'help'.
    This is a wrapper around pydoc.help (with a twist).

    """

    def __repr__(self):
        return "Type help() for interactive help, " \
               "or help(object) for help about object."
    def __call__(self, *args, **kwds):
        import pydoc
        return pydoc.help(*args, **kwds)

rawDescription: Redirect python interactive help()

description: Redirect python interactive help()


rawDescription: How to truncate matrix using NumPy (Python)

description: Truncate matrix using NumPy (Python)


code:
from string import ascii_uppercase as uppercase

replacement_set = uppercase[13:] + uppercase[:13]

rawDescription: Why is this mini program saying that the list index is out of range?


rawDescription: How do I remove all punctuation that follows a string?

description: Remove all punctuation that follows a string


code:
import re

pat = re.compile(r'cat|Dog', re.I)
db.collection.find({ "Animal": {'$regex': pat}})

rawDescription: Find substrings in PyMongo

description: Find substrings in PyMongo


code:
import feedparser
llog = feedparser.parse("http://languagelog.ldc.upenn.edu/nll/?feed=atom")

with open('myblog.txt', 'w') as outfile:
    for entry in llog.entries:
        ## Do your processing here
        content = entry.content[0].value
        clean_content = nltk.word_tokenize(nltk.html_clean(content))
        outfile.write(clean_content)

rawDescription: how to 'clean' all the entries in a feedparser feed


rawDescription: Python one-line "for" expression

description: Python one-line "for" expression


code:
import time
date = input('Date (mm/dd/yyyy): ')
try:
  valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
  print('Invalid date!')

rawDescription: How can I validate a date in Python 3.x?

description: Validate a date in Python 3.x


code:
from tkinter import *

def change_labels():
    print(days)

    in1 = int(input('how many days?'))

    # remove all old days
    days.clear()

    for a in range(in1):
        in2 = input('type in another day:  ')
        days.append(in2)

    krofl = (days[0], '-', days[-1])
    firstlast.set(krofl)

    # it is simpler to remove all labels and create new labels

    # remove all old labels
    for l in labels:
        l.grid_forget()

    # create new labels
    for number, name in enumerate(days):
        karamel = Label(Fenster, text=name)
        karamel.grid(row=number, column=6)
        labels.append(karamel)

# ---

presetdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']

# copy list
days = presetdays[:]

# ---

Fenster = Tk()
Fenster.title("some title")
Fenster.minsize(width=800, height=900)
Fenster.resizable(width=FALSE, height=FALSE)

firstlast = StringVar()
firstlast.set(str("preset value"))

lab1_1 = Label(Fenster, text='Zeitspanne:')
lab1_1.grid(row=0, column=0)

lab1_2 = Label(Fenster, textvariable = firstlast)
lab1_2.grid(row=0, column=1)

but1 = Button(Fenster, text='Change', command=change_labels)
but1.grid(row=0, column=2)

# --- create labels first time

labels = []

for number, name in enumerate(days):
    karamel = Label(Fenster, text=name)
    karamel.grid(row=number, column=6)
    labels.append(karamel)

Fenster.mainloop()

rawDescription: updating range of for loop with button

description: Updating range of for loop with button


code: worksheetObject.portrait = False

rawDescription: Setting an excel sheet in landscape mode from XLWT


code:
def replace_underscores(a_dict, replace_char):
    for k, v in a_dict.items():
        if not isinstance(v, dict):
            if v and '_' in v:
                a_dict[k] = v.replace('_', replace_char)
        else:
            replace_underscores(v, replace_char)

rawDescription: Find and replace part of dictionary values in python


code: "foo bar asdf".split(' ')

rawDescription: How to split string where spaces are?

description: Split string where spaces are


code:
row,col=3,5
i=0
while i <= row :
    j=0
    while j <= col:
        if i+j==0 : print('{:4s}'.format(''),end='') #corner
        elif i*j==0 : print('{:4d}'.format(i+j),end='') # border
        else : print('{:4d}'.format(i*j),end='') # table
        j=j+1
    print()
    i=i+1

rawDescription: Python multiplication table with while loops only


rawDescription: using a for loop with xrange() on a multiple lists

description: Using a for loop with xrange() on a multiple lists


code:
'abc'.isalpha()
'123'.isalpha()
'ab1c'.isalpha()
'123'.isalnum()

rawDescription: How to have a type check for a string

description: Have a type check for a string


code:
t = Tree() # Creates an empty tree
r1 = t.add_child(name="r1")
lookup = {"r1": r1}

def sort_pairs(pair):
    # Extract integer after "r".
    return int(pair[0][1:])

for pair in sorted(pairs_list, key=sort_pairs):
    parentname = pair[0]
    childname = pair[1]
    if childname not in lookup:
        if parentname in lookup:
            # Add child.
            newchild = lookup[parentname].add_child(name = childname)
            lookup.add(childname, newchild)
        else:
            raise RuntimeError('Must not happen.')

rawDescription: How can I create a tree using the python package ete2 using strings stored in a list?

description: Create a tree using the python package ete2 using strings stored in a list


code:
def get_queryset(self, request):
    # use our manager, rather than the default one
    qs = self.model.objects.get_query_set()

    # we need this from the superclass method
    ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)
    if ordering:
        qs = qs.order_by(*ordering)
    return qs

rawDescription: Django - specify which model manager Django admin should use


code: [ x if -10 <= float(x) <= 10 else 'NaN' for x in row]

rawDescription: Replacing csv data based on conditions (python)


code:
class SkipCase(unittest.TestCase):
    def runTest(self):
        raise unittest.SkipTest("Test would take to long.")

new_suite = unittest.TestSuite()

blacklist = [
    'test_some_test_that_should_be_skipped',
    'test_another_test_that_should_be_skipped'
]

for test_group in suite._tests:
    for test in test_group:
        if test._testMethodName in blacklist:
            testName = test._testMethodName
            setattr(test, testName, getattr(SkipCase(), 'runTest'))
        new_suite.addTest(test)

rawDescription: Removing tests from unittest suite

description: Removing tests from unittest suite


code:
placeholders = ','.join(['?'] * df1['ID'].count())
query = ("select * from Table2 where ID in ({}) "
         "and StatusCd in ('104', '106', '112', '115')").format(placeholders)
df2 = psql.frame_query(query, params=df1['ID'].tolist())

rawDescription: Pass object to python SQL

description: Pass object to python SQL


rawDescription: Python symmetric pair data type

description: Python symmetric pair data type


code:
import re
import os

FOLDER_PATH = "."   #set your path here
for filename in os.listdir(FOLDER_PATH):
    newname = re.sub("(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.jpg"
                , r"\1-\2-\3 \4-\5-\6.jpg"
                , filename)
    if (newname != filename and (not os.path.exists(os.path.join(FOLDER_PATH, newname)))):
        os.rename(os.path.join(FOLDER_PATH, filename), os.path.join(FOLDER_PATH, newname))

rawDescription: How can i rename an android phone's .jpg file in a specific pattern using python 3?

description: Rename an android phone's .jpg file in a specific pattern using python 3


code:
subprocess.Popen(args,
                 stdin=open("textfile"),
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 env={'LANG':'de_DE@euro'})

rawDescription: Python - Constructing a subprocess.popen with redirection


code:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6))
for ax in axes[-1, :]:
    ax.set_ylabel('My Ylabel')

fig.tight_layout()

rawDescription: Common label on python subplots

description: Common label on python subplots


code:
browser.find_element_by_xpath('//input[contains(@name, "user")]')
browser.find_element_by_xpath('//input[@name="user" or @name="username"]')

rawDescription: Python and Selenium find element with non exact name


code:
def proposal_create_view2(request):
    if request.method == 'POST':
        form = ProposalForm(data=request.POST)
        if form.is_valid():
            mysaved_model = form.save()
            response = {}
            response['proposalID'] = mysaved_model.id #or .pk
            return render(request , 'my_template_file.html' , response)

            #return response statement is NOT valid as you need to return an HttpResponse not a dict

rawDescription: Return Primary Key after saving to a model in Django


code:
if event.type == PG.KEYDOWN and keystate[PL.K_UP]:
    key_up_pressed = True
elif event.type == PG.KEYUP and keystate[PL.K_UP]:
    key_up_pressed = False

rawDescription: Pygame hold key down causes an infinite loop


rawDescription: Python: How to round 123 to 100 instead of 100.0?


code:
from matplotlib import pyplot
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import string

with open('barplt.txt') as infile:
    x = [float(value) for value in infile.readline().strip().split()]
    y = [float(value) for value in infile.readline().strip().split()]

plt.bar(y, x, width=0.1)
plt.xlabel('slack')
plt.ylabel('traces')
plt.title(r'Histogram of Slack')

# Tweak spacing to prevent clipping of ylabel
plt.savefig('igor.png')

rawDescription: Convert text histogram to Image using python


code:
s = set("123 ABC")
t = set("135 AZ")
intersect = s & t # or s.intersection(t)
exclusion = s ^ t # or s.symmetric_difference(t)
a_minus_b = s - t # or s.difference(t)
b_minus_a = t - s # or t.difference(s)

rawDescription: Python: Get common characters from strings


code:
if form.validate_on_submit():
    campaign = Campaign()
    form.populate_obj(campaign)

rawDescription: Form validation with WTForms and and autofill SQLAlchemy model with form data in Flask


code: return werkzeug.wrappers.Response(json_response, headers=[('Access-Control-Allow-Origin', '*'), ('Content-Length', len(json_response))])

rawDescription: How to configure CORS to OpenERP 7?

description: Configure CORS to OpenERP 7


code: ' '.join('< {} >'.format(' '.join(items)) for items in A_board)

rawDescription: manipulate python lists into strings

description: Manipulate python lists into strings


code:
args = parser.parse_args()
if ('LoadFiles' in vars(args) and
    'SourceFolder' not in vars(args) and
    'SourceFile' not in vars(args)):

    parser.error('The -LoadFiles argument requires the -SourceFolder or -SourceFile')

rawDescription: Arguments that are dependent on other arguments with Argparse


code:
mystery2("smith-jones")
mystery2("no hyphen")
mystery2("----")
mystery2("abcd----")
mystery2(["first-name", "second----------name", "-", "no hyphen"])
mystery2("")
mystery2([])

rawDescription: Need help in describing what the function does overall


code:
from flask import Flask
from flask.ext import restful

app = Flask(__name__)
api = restful.Api(app)

class ParseText(restful.Resource):
    def get(self, text):
        output = text.upper()
        return output

api.add_resource(ParseText, '/<string:text>')

if __name__ == '__main__':
    app.run(debug=True) # debug=True is for testing to see if calls are working.

rawDescription: Calling Python scripts in Meteor

description: Calling Python scripts in Meteor


code:
while (userin!="c" or low == high):
    userin = raw_input()

rawDescription: How do I check if a string with a user given input is equal to a certain letter/ word in Python

description: Check if a string with a user given input is equal to a certain letter/ word in Python


code:
class QuestionSerializer(serializers.Serializer):
    def __init__(self, *args, **kwargs):
        remove_fields = kwargs.pop('remove_fields', None)
        super(QuestionSerializer, self).__init__(*args, **kwargs)

        if remove_fields:
            # for multiple fields in a list
            for field_name in remove_fields:
                self.fields.pop(field_name)

class QuestionWithoutTopicView(generics.RetrieveAPIView):
        serializer_class = QuestionSerializer(remove_fields=['field_to_remove1' 'field_to_remove2'])

rawDescription: Dynamically exclude or include a field in Django REST framework serializer


code:
from matplotlib.pyplot import *
ds = [1,2,3]
dc = [1.1, 1.9, 3.2]
asim = [1.5, 2.2, 3.1]
ac = [1.6, 2.15, 3.1]

categories = ['simulated', 'calculated']

p1, = plot(ds, 'ko', label='D simulated')
p2, = plot(dc, 'k:', label='D calculated')
p3, = plot(asim, 'b+', label='A simulated')
p4, = plot(ac, 'b-', label='A calculated')
p5, = plot([0], marker='None',
           linestyle='None', label='dummy-tophead')
p7, = plot([0],  marker='None',
           linestyle='None', label='dummy-empty')

leg3 = legend([p5, p1, p2, p5, p3, p4],
              [r'$D_{etc}$'] + categories + [r'$A_{etc}$'] + categories,
              loc=2, ncol=2) # Two columns, vertical group labels

leg4 = legend([p5, p7, p5, p7, p1, p2, p3, p4],
              [r'$D_{etc}$', '', r'$A_{etc}$', ''] + categories + categories,
              loc=4, ncol=2) # Two columns, horizontal group labels

gca().add_artist(leg3)

#If there isn't a big empty spot on the plot, two legends:
#leg1 = legend([p1, p2], categories, title='D_etc', loc=0)
#leg2 = legend([p3, p4], categories, title='A_etc', loc=4)
#gca().add_artist(leg2)

show()

rawDescription: Custom legend in matplotlib

description: Custom legend in matplotlib


code:
import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        list = ['one','disable me','two']

        self.listbox = tk.Listbox(self,height=len(list))
        for item in list:
            self.listbox.insert(tk.END, item)
        self.listbox.pack()
        self.disable_item(1)

    def disable_item(self,index):
        self.listbox.itemconfig(index, fg="gray")
        self.listbox.bind("<<ListboxSelect>>",
                          lambda event, index=index: self.no_selection(event, index))

    def no_selection(self, event, index):
        if self.listbox.curselection()[0] in str(index):
            self.listbox.selection_clear(index)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Is it possible to disable elements in a listbox?


code:
school_records = db.school.find()
for i in school_records:
    for teacher in i['teachers']:
        db.individual.insert(teacher)

rawDescription: Mongo DB: How do I turn an array of documents into individual documents?


code:
retrieveddata1 = retrieveddata2 = retrieveddata3 = None
filename = "datosdeusuario.txt"
for line in open(filename, 'r'):
    retrieved = json.loads(line)
    if retrieved[0] == 'jonh connor':
        retrieveddata1 = retrieved[0]
        retrieveddata2 = retrieved[1]
        retrieveddata3 = retrieved[2]
        break

rawDescription: How to retrieve a specific string from a specific list from a file with JSON in Python

description: Retrieve a specific string from a specific list from a file with JSON in Python


code:
import subprocess as sp
import sys

interpreter_path = sys.executable
p = sp.Popen([interpreter_path, script_to_test])
(stdout, stderr) = p.communicate(input = testinput)

rawDescription: Unit testing keypresses and terminal output in Python?


code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

x = np.arange(0,5,1)
plt.subplot(221).contour(X, Y, Z)
plt.subplot(224).plot(x, x*2)
plt.subplot(223).plot(x, np.sqrt(x))
plt.show()

rawDescription: python: It is possible to create 3 subplots (on both axis)?

description: Python: It is possible to create 3 subplots (on both axis)


code:
from SimpleCV import *

lakeimg = Image('http://i.stack.imgur.com/ku8F8.jpg') #load this image from web, or could be locally if you wanted.
invimg = lakeimg.invert() #we invert because blobs looks for white blobs, not black
lakes = invimg.findBlobs() # you can always change parameters to find different sized blobs
if lakes: lakes.draw() #if it finds blobs then draw around them
invimg.show() #display the image

rawDescription: How to detect a black lake on a white snowy background in an aerial image?

description: Detect a black lake on a white snowy background in an aerial image


rawDescription: How to jump to the same line in two huge text files?

description: Jump to the same line in two huge text files


code:
from visual import *
import math

def make_grid(unit, n):
    nunit = unit * n
    f = frame()
    for i in xrange(n+1):
        if i%5==0:
            color = (1,1,1)
        else:
            color = (0.5, 0.5, 0.5)

        curve(pos=[(0,i*unit,0), (nunit, i*unit, 0)],color=color,frame=f)
        curve(pos=[(i*unit,0,0), (i*unit, nunit, 0)],color=color,frame=f)
    return f

arrow(pos=(0,0,0), axis=(5,0,0), color=(1,0,0), shaftwidth=0.1)
arrow(pos=(0,0,0), axis=(0,5,0), color=(0,1,0), shaftwidth=0.1)
arrow(pos=(0,0,0), axis=(0,0,5), color=(0,0,1), shaftwidth=0.1)
grid_xy = make_grid(0.5, 10)
grid_xz = make_grid(0.5, 10)
grid_xz.rotate(angle=pi/2, axis=(1,0,0), origin=(0,0,0))
grid_yz = make_grid(0.5, 10)
grid_yz.rotate(angle=-pi/2, axis=(0,1,0), origin=(0,0,0))
sphere(radius=0.3)

obj = arrow(pos=(0,0,0), axis=(1,2,3), shaftwidth=0.3)
th = 0
while True:
    rate(20)
    obj.axis = (3*math.cos(th), 3*math.sin(th), 2)
    th += 0.04

rawDescription: I need to plot a simple animated arrow vector in 3 dimensional space


code:
import numpy as np
def group_min(groups, data):
    # sort with major key groups, minor key data
    order = np.lexsort((data, groups))
    groups = groups[order] # this is only needed if groups is unsorted
    data = data[order]
    # construct an index which marks borders between groups
    index = np.empty(len(groups), 'bool')
    index[0] = True
    index[1:] = groups[1:] != groups[:-1]
    return data[index]

#max is very similar
def group_max(groups, data):
    order = np.lexsort((data, groups))
    groups = groups[order] #this is only needed if groups is unsorted
    data = data[order]
    index = np.empty(len(groups), 'bool')
    index[-1] = True
    index[:-1] = groups[1:] != groups[:-1]
    return data[index]

rawDescription: Group by max or min in a numpy array

description: Group by max or min in a numpy array


code:
from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale

def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component
                                                      # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)

if __name__ == '__main__':
    import os
    import sys

    input_image_path = 'Dn3CeZB.png'
    print('tinting "{}"'.format(input_image_path))

    root, ext = os.path.splitext(input_image_path)
    suffix = '_result_py{}'.format(sys.version_info[0])
    result_image_path = root+suffix+ext

    print('creating "{}"'.format(result_image_path))
    result = image_tint(input_image_path, '#383D2D')
    if os.path.exists(result_image_path):  # delete any previous result file
        os.remove(result_image_path)
    result.save(result_image_path)  # file name's extension determines format

    print('done')

rawDescription: Python 3, changing colour of an image

description: Python 3, changing colour of an image


code:
import sys
if sys.version_info[0]<3:
    import Tkinter as tk
else:
    import tkinter as tk

#Root window
root = tk.Tk()

#Tab override handler
def overrideTab(*args):
    root.bind('<Tab>', stopTab)

def stopTab(event=None, *args):
    if ctrlChk4.get()==1:
        print('Tab is overridden')
        return "break"
    else:
        print('Tab is not overridden') #Note that it still prints this.

#Control variable
ctrlChk4 = tk.IntVar()
ctrlChk4.trace('w',overrideTab)

#GUI widgets
fra1  = tk.Frame(root)
chk1 = tk.Checkbutton(fra1,
                      text='First checkbutton')
chk2 = tk.Checkbutton(fra1,
                      text='Second checkbutton')
chk3 = tk.Checkbutton(fra1,
                      text='Third checkbutton')
chk4 = tk.Checkbutton(fra1,
                      text='Tab override',
                      variable=ctrlChk4)

fra1.grid(row=0,column=0,sticky=tk.W,padx=10,pady=10)
chk1.grid(row=0,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk2.grid(row=1,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk3.grid(row=2,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))
chk4.grid(row=3,column=0,sticky=tk.W,padx=(10,0),pady=(5,0))

tk.mainloop()

rawDescription: Python Tkinter - recovering original default key binding


rawDescription: matplotlib Plot multiple scatter plots, each colored by different thrid variable

description: Matplotlib Plot multiple scatter plots, each colored by different thrid variable


code:
test['index'] = range(len(test) / 2) * 2
test[:10]
test[-10:]
df = test.pivot(index='index', columns='variable', values='value')
df['Name'] = test['Name']
df[:10]
(iris[["SepalLength", "SepalWidth", "Name"]] == df[["SepalLength", "SepalWidth", "Name"]]).all()

rawDescription: unmelting a pandas dataframe in Python?

description: Unmelting a pandas dataframe in Python


code:
cb = plt.colorbar(im, ticks=[], label="Values (0-1)")
cb.ax.text(0.5, -0.01, '0', transform=cb.ax.transAxes,
    va='top', ha='center')
cb.ax.text(0.5, 1.0, '1', transform=cb.ax.transAxes,
    va='bottom', ha='center')

rawDescription: Putting tick values on top and bottom of matplotlib colorbar


code:
for key in sorted(dict1.keys()):    # iterkeys() in Python2
    value1 = dict1[key]
    value2 = dict2[key]
    plot(key, value1)
    plot(key, value2)

rawDescription: Plotting multiple data related to a value


code:
def getCats(request):
    cats=Category.objects.filter(parent=None)
    s=u'
'
    for cat in cats:
        s += hiararchy(cat,True)
    s+=u'
'
    return HttpResponse(simplejson.dumps(s),mimetype='application/json')

def hiararchy(cat,flag):
    if cat.parent and flag:
        return hiararchy(cat.parent,True)
    else:
        if cat.children.count()>0:
            s=u'
%s'%(cat.name)
            for child in cat.children.all():
                s+=u'
%s

'%(hiararchy(child,False))
            return s
        else:
            return u'
%s
'%(cat.name)

rawDescription: recursion in view

description: Recursion in view


code:
str = input('')
str = str.split(',')
for choice in str:
    if choice == "1":
        print("Swimming")
    ...

rawDescription: How Do I Take a Variable No of inputs in python?


code:
bad_words = ['bad', 'naughty']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

rawDescription: Remove lines that contain certain string


code:
def post_article(sample):      #sample is the http request
    json_data = sample.read()
    data = json.loads(json_data)
    a = data['title']
    response_data = {}
    response_data['title'] = a
    return HttpResponse(json.dumps(response_data), content_type="application/json")

rawDescription: how to read json data in django?

description: Read json data in django


code:
import maya.mel
import maya.cmds as cmds
cmds.file(new=True, f=True)
cmds.polyCube()
cmds.polyPlane(sx = 21, sy = 22)
cmds.xform(t= (.0005, .015, .0005)) # note units - my maya is working in meters...
mel.eval("createNCloth 0;")
maya.mel.eval("createNCloth 0;")
cmds.select('pCube1')
maya.mel.eval("makeCollideNCloth")
cmds.playbackOptions(animationStartTime=0)
cmds.playbackOptions(animationEndTime=100)
cmds.play(f=True)
cmds.bakeResults('pPlane1', simulation=True, t=(1,20), disableImplicitControl=True, sb = 1, shape=True, cp=True )

# use openMaya to set the frame - cmds.currentTime does not
# stick in standalone:
import maya.OpenMaya as om
om.MGlobal.viewFrame(20)
# delete the cloth solution
cmds.delete('nCloth1', 'nRigid1')
# delete the orphaned shape
cmds.delete('pPlaneShape1')
cmds.file(rename = "C:/test/cloth.mb")
cmds.file(save=True)

rawDescription: Maya : Different behaviours in standalone and embedded mode


code:
UUU
UIU
UUU

rawDescription: What's a good way to render outlined fonts?


code:
dependency_links=[
      "svn://example.com/package3/svn/trunk#egg=package3"
  ]

rawDescription: Pip and resolving repository requirements


code:
def function(status):
    if function.wasCalled == True:
        status = 1
    function.wasCalled = True
    return status

function.wasCalled = False
status = 0

print(function(status))
print(function(status))
print(function(status))
print(function(status))
print(function(status))
print(function(status))

rawDescription: Updating a variable in a function

description: Updating a variable in a function


code:
import tkinter

root = tkinter.Tk()
root.title('Timer')
root.state('zoomed')

sec = 0
doTick = True

def tick():
    global sec
    if not doTick:
        return
    sec += 0.1
    sec = round(sec,1)
    timeLabel.configure(text=sec)
    root.after(100, tick)

def stop():
    global doTick
    doTick = False

def start():
    global doTick
    doTick = True
    # Perhaps reset `sec` too?
    tick()

timeLabel = tkinter.Label(root, fg='green',font=('Helvetica',150))
timeLabel.pack()

startButton = tkinter.Button(root, text='Start', command=start)
startButton.pack()

stopButton = tkinter.Button(root, text='Stop', command=stop)
stopButton.pack()

root.mainloop()

rawDescription: How to stop a timer (python)

description: Stop a timer (python)


code: pattern = re.compile("(%s)" % "|".join(re.escape(term) for term in dictionary))

rawDescription: Extract terminology from sentences quickly


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

phi = np.linspace(0,2*np.pi, 256).reshape(256, 1) # the angle of the projection in the xy-plane
theta = np.linspace(0, np.pi, 256).reshape(-1, 256) # the angle from the polar axis, ie the polar angle
radius = 4

# Transformation formulae for a spherical coordinate system.
x = radius*np.sin(theta)*np.cos(phi)
y = radius*np.sin(theta)*np.sin(phi)
z = radius*np.cos(theta)

fig = plt.figure(figsize=plt.figaspect(1))  # Square figure
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, color='b')

rawDescription: Ellipsoid creation in Python

description: Ellipsoid creation in Python


code:
from time import time

time_started = time()
messages_sent = 0.
MAX_PER_SEC = 70

for user in _10000_users:
    msg = generate_message(user)
    if messages_sent / (time() - time_started) >= MAX_PER_SEC:  # Rate condition
        sleep(0.1)
    ses.send_message(msg)
    messages_sent += 1

rawDescription: Rate-limiting my program from sending too many SES emails via SQS


code:
theListOfChars = ['a', 'b', 'x', 'd', 's']
''.join(theListOfChars)

rawDescription: How can I optimally concat a list of chars to a string?

description: Optimally concat a list of chars to a string


rawDescription: Python/Numpy: Setting values to index ranges


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

x = np.linspace(-3,3,100)
y = np.linspace(-3,3,100)
u = -1-x**2+y[:,np.newaxis]
v = 1+x-y[:,np.newaxis]**2
speed = np.sqrt(u*u + v*v)

plt.figure()
plt.subplot(121)
streamplot(x, y, u, v, density=1, INTEGRATOR='RK4', color='b')
plt.subplot(122)
streamplot(x, y, u, v, density=(1,1), INTEGRATOR='RK4', color=u,
           linewidth=5*speed/speed.max())
plt.show()

rawDescription: how to plot streamlines , when i know u and v components of velocity(numpy 2d arrays), using a plotting program in python?

description: Plot streamlines , when i know u and v components of velocity(numpy 2d arrays), using a plotting program in python


rawDescription: Convert array element to float

description: Convert array element to float


code:
persons = []

for human in world:
     attributes = {}
     attributes['name'] = human['name']
     attributes['eye_color'] = human['eyes']
     persons.append(attributes)

rawDescription: Understanding Python Lists and Dictionaries using the example


code:
import dis
def foo():
    return [i//2 for i in range(20)]

dis.dis(foo)

rawDescription: Do python list comprehensions get converted to pure C?


code:
(r'^my_url/$', 'login', {'redirect': admin}),
(r'^my_other_url/$', 'login', {'redirect': beta}),

rawDescription: django - reusing a login template

description: Django - reusing a login template


rawDescription: Finding numbers after a certain keyword using Python


code:
import numpy as np

noise = np.random.normal(0,1,100)

# 0 is the mean of the normal distribution you are choosing from
# 1 is the standard deviation of the normal distribution
# 100 is the number of elements you get in array noise

rawDescription: adding noise to a signal in python

description: Adding noise to a signal in python


code:
import numpy as np
import h5py
import time

f = h5py.File('myfile1.mat','r')
#print f.keys()
test = f['db/path']
st = test[0][0]
obj = f[st]
str1 = ''.join(chr(i) for i in obj[:])
print( str1 )

rawDescription: How convert this type of data <hdf5 object reference> to something more readable in the python?


code:
def get_kwargs(view_name):
    resolver = urlresolvers.get_resolver()
    patterns = resolver.reverse_dict.getlist(view_name)
    kwargs = []
    for possibility, pattern, defaults in patterns:
        for result, params in possibility:
            kwargs.append(params)
    return kwargs

rawDescription: Django - get names of parameters needed to reverse url


code: copied = copy.deepcopy(my_obj)(b=77)

rawDescription: How to change method calling order in python?

description: Change method calling order in python


code:
import sys
file_path = sys.argv[1]

with open(file_path,"r") as f:
    for line in f:
        print(line)

rawDescription: Python User Input Within Shell

description: Python User Input Within Shell


code:
import subprocess
subprocess.Popen([ZOOKEEPER_START_SERVER, ZOOKEEPER_CONFIG], creationflags=subprocess.CREATE_NEW_CONSOLE)

rawDescription: Opening and executing multiple concurrent Windows command prompts from Python


code:
import inspect
class A(object):
    b = 1
    def __init__(self):
        self.c = 1
a = A()
inspect.getmembers(a)
dir(a)
a.__class__.__dict__

rawDescription: Inheritance and __dict__ in python 3

description: Inheritance and __dict__ in python 3


code:
class TaskListPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        tasks_query = Task.all()
        tasks = tasks_query.fetch(1000)
        if user:
          url = users.create_logout_url(self.request.uri)
        else:
          url = users.create_login_url(self.request.uri)
        template_values = {
          'tasks': tasks,
          'url': url
          }
        path = os.path.join(os.path.dirname(__file__), self.template_name())
        self.response.out.write(template.render(path, template_values))

class MainPage(TaskListPage):
    def template_name(self):
        return 'index.html'

class Gadget(TaskListPage):
    def template_name(self):
        return 'gadget.xml'

rawDescription: How to refactor this Python code?

description: Refactor this Python code


code:
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

rawDescription: How can I convert HTML into text without markup in Python?

description: Convert HTML into text without markup in Python


code:
pyplot.bar(hist1_flux[1], hist1_flux[0],
           width=hist1_flux[1][1] - hist1_flux[1][0])

rawDescription: Python histograms: Manually normalising counts and re-plotting as histogram


code:
import win32com.shell.shell as win32shell

def disable_UAC():
    command1 = 'reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA'
    win32shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + command1)
    command2 = 'reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f'
    win32shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + command2)

rawDescription: Turn UAC off with python

description: Turn UAC off with python


code:
df
df.divide(df.ix[0] / 100)

rawDescription: Python: Pandas Divide DataFrame by first row


code:
uuidmap = {}
for d in L:
  if d['color'] not in uuidmap:
    uuidmap[d['color']] = generateUUID()
  d['UUID'] = uuidmap[d['color']]

rawDescription: create UUIDs for unique key-value pairs while preserving dict integrity

description: Create UUIDs for unique key-value pairs while preserving dict integrity


code:
next(key for key,val in globals().items() if val is x and not key.startswith('_'))

b = a
#do you want b or a as the name now?

rawDescription: Python create a function to write an object to file quickly


code:
np.typecodes
np.sctypes

rawDescription: What are the available datatypes for 'dtype' with numpy's loadtxt an genfromtxt?


code:
mainWidget = QtGui.QWidget()
mainWidget.setLayout(layout)

scrollWidget = QtGui.QScrollArea()
scrollWidget.setWidget(mainWidget)
scrollWidget.setWidgetResizable(True) # <---------------

self.setCentralWidget(scrollWidget)

rawDescription: Trouble getting QMainWindow to scroll

description: Trouble getting QMainWindow to scroll


code:
from scipy.sparse.csgraph import connected_components

# convert to datetime, so min() and max() work
df.startDate = pd.to_datetime(df.startDate)
df.endDate = pd.to_datetime(df.endDate)

def reductionFunction(data):
    # create a 2D graph of connectivity between date ranges
    start = data.startDate.values
    end = data.endDate.values
    graph = (start <= end[:, None]) & (end >= start[:, None])

    # find connected components in this graph
    n_components, indices = connected_components(graph)

    # group the results by these connected components
    return data.groupby(indices).aggregate({'startDate': 'min',
                                            'endDate': 'max',
                                            'shipNo': 'first'})

df.groupby(['Cust']).apply(reductionFunction).reset_index('Cust')

rawDescription: Pandas combining rows based on dates

description: Pandas combining rows based on dates


rawDescription: Filter Python list of lists by another list


rawDescription: What is sympy version of math.modf in python's built-in module?


code: re.sub(r'(<form.*?action=")([^"]+)', r'\1newlogin.php',  content)

rawDescription: How to search for a word and then replace text after it using regular expressions in python?

description: Search for a word and then replace text after it using regular expressions in python


code:
my_array = np.arange(3 * 4 * 5).reshape((3, 4, 5))
for ij in np.ndindex(my_array.shape[:2]):
    i,j=ij
    print(i,j)

rawDescription: Numpy.ndarray: iteration by specific axes of an array


code:
import tkinter as tk

class MainWindow():
    def __init__(self, parent):
        top = self.top = tk.Toplevel(parent)
        self.myLabel = tk.Label(top, text='Enter a Grouping Name')
        self.myLabel.pack()
        self.myEntryBox = tk.Entry(top)
        self.myEntryBox.focus_set()
        self.myEntryBox.pack()
        self.mySubmitButton = tk.Button(top, text='OK', command=self.DestWin)
        self.mySubmitButton.pack()
    def DestWin(self):
        # call callback function setting value in MyFrame
        self.callback(self.myEntryBox.get())
        self.top.destroy()

    def set_callback(self, a_func):
        self.callback = a_func

class MyFrame(tk.Frame):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.pack()

        self.myLabel1 = tk.Label(parent, text='Click OK to enter the group name')
        self.myLabel1.pack()
        self.mySubmitButton1 = tk.Button(parent, text='OK', command=self.get_group_name)
        self.mySubmitButton1.pack()

    def get_group_name(self):
        mw = MainWindow(None)

        # provide callback to MainWindow so that it can return results to MyFrame
        mw.set_callback(self.set_label)

    def set_label(self, astr = ''):
        self.myLabel1['text'] = astr

root = tk.Tk()

mf = MyFrame(root)

root.mainloop()

rawDescription: Python Tkinter Input Box

description: Python Tkinter Input Box


code:
def __init__(self, name):
    self.name = name

myObjectClass = myClass("myObjectClass")

rawDescription: How to get the variable name of a Python object class

description: Get the variable name of a Python object class


code:
d = {}
for i, part in enumerate(s1.split('=')):
    if i == 0:
        metric = part
    else:
        d[metric], _, metric = part.partition(' ')

rawDescription: complex string split with multiple spaces

description: Complex string split with multiple spaces


code:
with open('C:/Comparison.txt', 'w') as f:
  json.dump(full_json, f)

rawDescription: Can't write long JSON output to text file


code:
import urllib2
from bs4 import BeautifulSoup

wfo = list()

def main():
    wfo = [i.strip() for i in open('C:\Python27\wfo.txt') if i[:-1]]
    soup = BeautifulSoup(urllib2.urlopen('http://mesonet.agron.iastate.edu/cow/?syear=2009&smonth=9&sday=12&shour=12&eyear=2012&emonth=9&eday=12&ehour=12&wfo=ABQ&wtype%5B%5D=TO&hail=1.00&lsrbuffer=15&ltype%5B%5D=T&wind=58').read())
    elements = soup.find_all("span")
    find_verify = soup.find_all('th')

    far= float(elements[1].text)
    pod= float(elements[2].text)
    verified = (find_verify[13].text[:-1])

rawDescription: Python Web-Scraping using Beautiful Soup on a messy Site


code: np.savetxt("file.txt", output, fmt='%10.5f', delimiter='\t')

rawDescription: savetxt How change the type from float64 to int or double

description: Savetxt How change the type from float64 to int or double


code:
from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))

rawDescription: Self-referential Queries in Django

description: Self-referential Queries in Django


code: lst2 = [(x, y) for (x, y) in lst if y != (4, 5)]

rawDescription: Python built-in list: remove one item

description: Python built-in list: remove one item


code: list_per_page = 1000

rawDescription: Django admin action for items selected over several pages


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

def angle(dir):
    """
    Returns the angles between vectors.

    Parameters:
    dir is a 2D-array of shape (N,M) representing N vectors in M-dimensional space.

    The return value is a 1D-array of values of shape (N-1,), with each value
    between 0 and pi.

    0 implies the vectors point in the same direction
    pi/2 implies the vectors are orthogonal
    pi implies the vectors point in opposite directions
    """
    dir2 = dir[1:]
    dir1 = dir[:-1]
    return np.arccos((dir1*dir2).sum(axis=1)/(
        np.sqrt((dir1**2).sum(axis=1)*(dir2**2).sum(axis=1))))

tolerance = 70
min_angle = np.pi*0.22
filename = os.path.expanduser('~/tmp/bla.data')
points = np.genfromtxt(filename).T
print(len(points))
x, y = points.T

# Use the Ramer-Douglas-Peucker algorithm to simplify the path
# http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
# Python implementation: https://github.com/sebleier/RDP/
simplified = np.array(rdp.rdp(points.tolist(), tolerance))

print(len(simplified))
sx, sy = simplified.T

# compute the direction vectors on the simplified curve
directions = np.diff(simplified, axis=0)
theta = angle(directions)
# Select the index of the points with the greatest theta
# Large theta is associated with greatest change in direction.
idx = np.where(theta>min_angle)[0]+1

fig = plt.figure()
ax =fig.add_subplot(111)

ax.plot(x, y, 'b-', label='original path')
ax.plot(sx, sy, 'g--', label='simplified path')
ax.plot(sx[idx], sy[idx], 'ro', markersize = 10, label='turning points')
ax.invert_yaxis()
plt.legend(loc='best')
plt.show()

rawDescription: calculate turning points / pivot points in trajectory (path)

description: Calculate turning points / pivot points in trajectory (path)


code:
lis = sorted(word_freq.items(), key = lambda x:x[1], reverse = True)
for word,freq in lis:
    print ("%-10s %d" % (word, freq))

rawDescription: sort list by frequency-value in python

description: Sort list by frequency-value in python


rawDescription: Regex to remove all punctuation and anything enclosed by brackets


code:
import random, string

NUM_CHARS = 6 # how long the string should be
textbank = string.ascii_uppercase * NUM_CHARS

while True:
    word = random.sample(textbank,NUM_CHARS)
    for letter in word:
        press_key_however_you_do_it(letter)
        # I have no idea how you're implementing this, but you do
    press_key_however_you_do_it(" ")

rawDescription: Random six letter string in Python

description: Random six letter string in Python


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

def main():
    pid=os.fork()
    if pid==0:
        showFigure()

def showFigure():
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x)
    plt.figure()
    plt.plot(x, y)
    plt.title('Simple test')
    plt.show()

if __name__ == '__main__':
    main()

rawDescription: Plot a figure and exit but leave figure window open


rawDescription: Different python modules give identical co_code objects


code: tags = [repo.tag(r.object.sha) for r in repo.iter_refs(subspace='refs')]

rawDescription: Is there a way to get Tag objects instead of Reference ones when listing tags from a repository?


code:
import scipy.stats as ss
def makeCumZScoreMap(ratingType, frame, lg, season, dateObj):
    zScoreDict =  {}
    sampleFrame = frame[(frame.League == lg) & (frame.Season == season) & (frame.Date <= dateObj)]
    rating = sampleFrame.groupby(['Team'])[ratingType].mean()
    for x, y in dict(pd.Series(ss.zscore(rating, ddof=1), rating.index)).iteritems():
        zScoreDict[x] =  y
    frame['Zscore'] = frame['Team'].map(zScoreDict)
    return frame

rawDescription: Pandas making cumulative Z scores map onto dataframe


code:
import wx

def alignToBottomRight(win):
    dw, dh = wx.DisplaySize()
    w, h = win.GetSize()
    x = dw - w
    y = dh - h
    win.SetPosition((x, y))

app = wx.PySimpleApp()
frame = wx.MiniFrame(None, title="My PopUp", size=(200,300), style=wx.DEFAULT_MINIFRAME_STYLE|wx.CLOSE_BOX)
alignToBottomRight(frame)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

rawDescription: how to set wxPython main frame bottom right on screen?

description: Set wxPython main frame bottom right on screen


code:
s=sp()
s
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()
s.next()

rawDescription: Python: generator fail

description: Python: generator fail


code:
class Foo(object):
    def __init__(self):
        # statically analysable
        self.bla = 3

        # still, but more difficult
        if SOME_CONSTANT > 123:
            self.x = 123
        else:
            self.y = 321

    def do_something(self):
        import random
        setattr(self, "attr%s" % random.randint(1, 100), "hello, world of dynamic languages!")

    foo = Foo()
    foo2 = Foo()
    # only `bla`, `x`, and `y` attrs in existence so far
    foo2.do_something()
    # now there's an attribute with a random name out there
    # in order to detect it, we'd have to get all instances of Foo existence at the moment, and individually inspect every attribute on them.

rawDescription: How to access calls to self from python class functions

description: Access calls to self from python class functions


code:
def obj_create(self, bundle, request=None, **kwargs):
    bundle = super(MycustomeResource, self).obj_create(bundle, request)

    '''
    operations with your object bundle.obj
    '''
    return bundle

rawDescription: Django tastypie , how to access the object created by post_list in ModelResource class


code:
import decimal
decimal.Decimal('54.10') % decimal.Decimal('0.10')

rawDescription: how to test if a number is divisible by a decimal less than 1? (54.10 % .10)

description: Test if a number is divisible by a decimal less than 1? (54.10 % .10)


code:
with open('list_of_dics.txt', 'r') as infile:
    d = json.load(infile)

rawDescription: How can I read a file that contains a list of dictionaries into python?

description: Read a file that contains a list of dictionaries into python


code:
def message(self):
   self.inp.set(random.choice(messages))

rawDescription: Python: How does one recieve a random string, and display it into a label (tkinter)?


code:
b =[]

for fn in t:
    a=[]
    for line in open(fn,"r"):
        line=line.strip()
        a.append(line)
    b.append(set(a))

CommonRegions = set.intersection(*b)
print(CommonRegions)

rawDescription: creating python lists on the fly and comparing them

description: Creating python lists on the fly and comparing them


rawDescription: More efficient way of transforming items in a list


code:
import os
# if file does not exist write header
if not os.path.isfile('filename.csv'):
   df.to_csv('filename.csv',header ='column_names')
else: # else it exists so append without writing the header
    df.to_csv('filename.csv',mode = 'a',header=False)

rawDescription: Panda's Write CSV - Append vs. Write

description: Panda's Write CSV - Append vs. Write


code:
test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]

from collections import defaultdict
d = defaultdict(list)

for i, j in test:
    d[i].append(j)

d

rawDescription: How to convert a list containing duplicate values to a dictionary with a list as the value?

description: Convert a list containing duplicate values to a dictionary with a list as the value


code:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy

N = 20
n = numpy.random.normal(size=(N, 2))
Z = linkage(n)

# implicit interface
dendrogram(Z)
ax = plt.gca()
ax.tick_params(axis='x', which='major', labelsize=15)
ax.tick_params(axis='y', which='major', labelsize=8)
plt.savefig('t.png')

# explicit interface
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
dendrogram(Z, ax=ax)
ax.tick_params(axis='x', which='major', labelsize=15)
ax.tick_params(axis='y', which='major', labelsize=8)
fig.savefig('t.png')

rawDescription: How to get a bigger font size for x-axis tick labels in scipy-generated dedrogram?

description: Get a bigger font size for x-axis tick labels in scipy-generated dedrogram


rawDescription: Matrix Multiplication of a Pandas DataFrame and Series


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import numpy as np

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

u = np.linspace(0, 1, 100)
v = np.linspace(1, 0, 100)

x = np.outer(np.ones_like(u), v)
y = np.outer(v, u)
z = 1 - x - y
f = 0.8*x + 0.6*y + 0.9*z

norm = Normalize (f.min(), f.max())
m = plt.cm.ScalarMappable()
m.set_array([])
fcolors = m.to_rgba(f)

ax.view_init(azim=45)
ax.plot_surface(x, y, z, norm=norm, rstride=2, cstride=2, facecolors=fcolors, shade=False)

plt.show()

rawDescription: Python plot 3d surface drawing

description: Python plot 3d surface drawing


code:
def good_ratio(a):
    return fuzz.ratio(a, 'good')

with open('qwer.txt', 'r') as my_file:
   my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
   print(my_sum/my_len)

rawDescription: python finding average fuzzy ratio of all lines

description: Python finding average fuzzy ratio of all lines


code:
import sys, math
from PyQt5 import QtCore, QtGui, QtWidgets

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.pen = QtGui.QPen(QtGui.QColor(0,0,0))                      # set lineColor
        self.pen.setWidth(3)                                            # set lineWidth
        self.brush = QtGui.QBrush(QtGui.QColor(255,255,255,255))        # set fillColor
        self.polygon = self.createPoly(8,150,0)                         # polygon with n points, radius, angle of the first point

    def createPoly(self, n, r, s):
        polygon = QtGui.QPolygonF()
        w = 360/n                                                       # angle per step
        for i in range(n):                                              # add the points of polygon
            t = w*i + s
            x = r*math.cos(math.radians(t))
            y = r*math.sin(math.radians(t))
            polygon.append(QtCore.QPointF(self.width()/2 +x, self.height()/2 + y))

        return polygon

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        painter.drawPolygon(self.polygon)

app = QtWidgets.QApplication(sys.argv)

widget = MyWidget()
widget.show()

sys.exit(app.exec_())

rawDescription: Drawing a polygon in PyQt

description: Drawing a polygon in PyQt


code:
from win32com.client import constants
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")

d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',
 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',
 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',
 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey',
 'x':'x-ray', 'y':'yankee', 'z':'zulu'}
speaker.speak("Hello.. Please write a line you want me to say")
print ("Type your text now:")
inp = input()
print ("Outputting...")
result = ' '.join(d[c.lower()] for c in inp)
speaker.speak(result)

rawDescription: Working with words, and need to translate ABC to Alpha, Bravo, Charlie


code:
def readFile(filename):
    print("Reading file: %s" % (filename))
    f=open(filename,'r').readlines()
    for i in f:
        if i.startswith('+'):
            readFile(i[1:].rstrip())
        else:
            print(i)

rawDescription: Recursive function for reading file in Python2.7


code: your_list = [[int(j) for j in i.split()] for i in ' '.join(data).split('<>')]

rawDescription: breaking a list in to lists in python?

description: Breaking a list in to lists in python


rawDescription: Regex for colorcoding strings

description: Regex for colorcoding strings


code:
s = int(input("Starting number of organisms: "))
i = float(input("Average daily increase[%]: "))/100.0
d = int(input("Number of days to multiply: "))
first = True
print("Day Approximate\tPopulation")
for d in range(s, d + 1):
    if first:
        print(1, '\t', s)
        first = False
    add = s * i
    s = s + add
    print(d - 1, '\t', s)

rawDescription: How can I get the loop to display the initial inputs and how to accept percentages '%' as output

description: Get the loop to display the initial inputs and how to accept percentages '%' as output


code:
df["rank"] = df.groupby("group_ID")["value"].rank("dense", ascending=False)
df

rawDescription: Ranking order per group in Pandas

description: Ranking order per group in Pandas


code:
activate_this = os.path.join(path_to_my_site, "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))

rawDescription: Running Django in Virtualenv using Apache with Mod_Python and Multiple Python installations


code:
def get_companies():
        create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
        headers = {'content-type': 'application/json'}
        create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)
        if create_get_recent_companies_response.status_code == 200:

            while True:
                for i in create_get_recent_companies_response.json()[u'companies']:
                    companyName = i[u'properties'][u'name'][u'value']
                    print("{companyName}".format(companyName=companyName))
                offset = create_get_recent_companies_response.json()[u'offset']
                hasMore = create_get_recent_companies_response.json()[u'has-more']
                if not hasMore:
                    break
                else:
                    create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset)
                    create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)

        else:
            print("Something went wrong, check the supplied field values.\n")
            print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4))

rawDescription: Unable to loop through paged API responses with Python


code:
def __str__(self):
    return unicode(self).encode('utf-8')

rawDescription: __unicode__ not called on some objects in Django/Python project when getting string representation


rawDescription: Linking wxpython to run drpython

description: Linking wxpython to run drpython


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

# some random numbers for demonstration
data = np.random.normal(0, 1, (100, 2))
value = np.random.normal(0, 1, 100)

polygons = [
    Polygon([(0, 0), (0, 3), (-3, 3), (-3, 0)], closed=True),
    Polygon([(0, 0), (0, -3), (-3, -3), (-3, 0)], closed=True),
    Polygon([(0, 0), (0, 3), (3, 3), (3, 0)], closed=True),
    Polygon([(0, 0), (0, -3), (3, -3), (3, 0)], closed=True),
]

poly_values = []
for poly in polygons:
    mask = np.array([poly.contains_point(xy) for xy in data])
    poly_values.append(value[mask].sum())

coll = PatchCollection(polygons, cmap='magma')
coll.set_array(np.array(poly_values))

fig, ax = plt.subplots()
ax.add_collection(coll)
points = ax.scatter(data[:, 0], data[:, 1], c=value, cmap='viridis', linewidth=0)
fig.colorbar(coll, label='polygons')
fig.colorbar(points, label='points')
plt.show()

rawDescription: Plotting Shapefiles which color decided by the scatter point data within


rawDescription: Use Django ORM to select rows if a value is in a range stored in columns


code:
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""

# loop the entire game while the user wishes to play
while user_wants_to_play:
    # Create the combination
    # Test the combination

    # Game isn't done when started
    game_done = False
    tries_left = 10  # Arbitrary number I chose

    while not game_done:
        # Play the game
        print("Scoreboard")

        # Subtract one to tries left
        tries_left -= 1

        if game_done:
            print("You won!")

        elif tries_left == 0:
            print("You lost!")
            game_done = True

        # if users answer was 'n'
    ans = input("Play again? Y/N \n")
    if ans.strip().upper() == 'N':
        user_wants_to_play = False

rawDescription: Unable to get out of loops

description: Unable to get out of loops


code:
import os
import glob

filename = max(glob.iglob("c:/csvfiles/*.csv"), key=os.path.getmtime)

rawDescription: Python return filepath/filename of most recent csv file stored in directory


code:
file = open("test","ab")
file.seek(50,0)
dumped= cPickle.dumps(object)
file.write(dumped)
file.close()

rawDescription: cPickle.dump always dumping at end of file

description: CPickle.dump always dumping at end of file


code:
import sys
from PyQt4.QtGui import *

if __name__ == '__main__':
    app = QApplication(sys.argv)

    widget = QWidget()

    mainWindow = QMainWindow(widget)
    mainWindow.show()

    sys.exit(app.exec_())

rawDescription: Hide PyQt app from taskbar

description: Hide PyQt app from taskbar


code:
import datetime

def myfunc(num_of_months):
    today = datetime.date.today()
    num_of_months = today.year * 12 + today.month - 1 - num_of_months
    year = num_of_months / 12
    month = num_of_months % 12 + 1
    return year, month

rawDescription: Getting a year and month from a number of a months in Python


code: [s[:-1]+f for (f,s) in zip(first_array, second_array)]

rawDescription: Integer Manipulation of arrays python

description: Integer Manipulation of arrays python


code:
dbconnection = connect(...)
while True:
    ...
    socket.send(handler(data, dbconnection))

rawDescription: How-To - Update Live Running Python Application


code:
import Tkinter as tk
import Image,ImageDraw

class ImageGenerator:
    def __init__(self,parent,posx,posy,*kwargs):
        self.parent = parent
        self.posx = posx
        self.posy = posy
        self.sizex = 200
        self.sizey = 200
        self.b1 = "up"
        self.xold = None
        self.yold = None
        self.drawing_area=tk.Canvas(self.parent,width=self.sizex,height=self.sizey)
        self.drawing_area.place(x=self.posx,y=self.posy)
        self.drawing_area.bind("<Motion>", self.motion)
        self.drawing_area.bind("<ButtonPress-1>", self.b1down)
        self.drawing_area.bind("<ButtonRelease-1>", self.b1up)
        self.button=tk.Button(self.parent,text="Done!",width=10,bg='white',command=self.save)
        self.button.place(x=self.sizex/7,y=self.sizey+20)
        self.button1=tk.Button(self.parent,text="Clear!",width=10,bg='white',command=self.clear)
        self.button1.place(x=(self.sizex/7)+80,y=self.sizey+20)

        self.image=Image.new("RGB",(200,200),(255,255,255))
        self.draw=ImageDraw.Draw(self.image)

    def save(self):
        filename = "temp.jpg"
        self.image.save(filename)

    def clear(self):
        self.drawing_area.delete("all")
        self.image=Image.new("RGB",(200,200),(255,255,255))
        self.draw=ImageDraw.Draw(self.image)

    def b1down(self,event):
        self.b1 = "down"

    def b1up(self,event):
        self.b1 = "up"
        self.xold = None
        self.yold = None

    def motion(self,event):
        if self.b1 == "down":
            if self.xold is not None and self.yold is not None:
                event.widget.create_line(self.xold,self.yold,event.x,event.y,smooth='true',width=3,fill='blue')
                self.draw.line(((self.xold,self.yold),(event.x,event.y)),(0,128,0),width=3)

        self.xold = event.x
        self.yold = event.y

if __name__ == "__main__":
    root=tk.Tk()
    root.wm_geometry("%dx%d+%d+%d" % (400, 400, 10, 10))
    root.config(bg='white')
    ImageGenerator(root,10,10)
    root.mainloop()

rawDescription: Python Tkinter save canvas as image using PIL


code: x, y = np.broadcast_arrays(*np.ogrid[0:2,0:3])

rawDescription: indexing into numpy's mgrid

description: Indexing into numpy's mgrid


code:
def setUp(self):
    # Assume test will fail
    self.test_failed = True

def tearDown(self):
    if self.test_failed:
        self.save_screenshot()

def test_something(self):
    # do some tests
    # Last line of the test:
    self.test_failed = False

rawDescription: Create screenshot only on test failure

description: Create screenshot only on test failure


rawDescription: Inspect.getsourcelines(None.__str__) throws confusing TypeError


rawDescription: Python - Sum a List of Numbers

description: Python - Sum a List of Numbers


rawDescription: Order a QuerySet by aggregate field value


code:
location = Location.objects.get(pk="some_location_id")
descendants = location.get_descendants().values_list('id', flat=True)
building_list = Building.objects.filter(title__icontains='house',
                                        location__in=descendants)

rawDescription: Query with difficult conditions in the project using mptt