code:
import urllib2
import BeautifulSoup
import MySQLdb

f = urllib2.urlopen('http://www.python.org/')
soup=BeautifulSoup.BeautifulSoup(f.read())
title=soup.find('title')
print(title.string)

connection=MySQLdb.connect(
    host='HOST',user='USER',
    passwd='PASS',db='MYDB')
cursor=connection.cursor()

sql='''CREATE TABLE IF NOT EXISTS foo (
           fooid int(11) NOT NULL AUTO_INCREMENT,
           title varchar(100) NOT NULL,
           PRIMARY KEY (fooid)
       )'''
cursor.execute(sql)

sql='INSERT INTO foo (title) VALUES (%s)'
args=[title.string]
cursor.execute(sql,args)
cursor.close()
connection.close()

rawDescription: Getting contents of title tags with Python script


code:
other_to_tup = [(x, 'val') for x in other_df.columns]
other_df.columns = pd.MultiIndex.from_tuples(other_to_tup)
p = pd.merge(new_df, other_df, left_index=True, right_index=True)
p

rawDescription: Pandas merge hierarchical dataframes and maintain hierarchy


code: ids = [int(s.split("/")[3]) for s in id_arr]

rawDescription: Python string extraction

description: Python string extraction


code:
s='aria-label="like this video along with **3,358,980** other people"'
print(re.search(r"([\d,]+)", s).group(0))

rawDescription: Searching a variable pattern using Python


code:
import collections
d = collections.defaultdict(list)
d['key'].append(1)
d
d['key'].append(2)
d

rawDescription: Initialise or append dictionary list in python


code: sorted(table_data, key=lambda x: int(x[0][4:]))

rawDescription: Sorting list of lists by numerical suffix at end of string in first element


code:
train['Year'] = train.Dates.dt.year
train['Month'] = train.Dates.dt.month

rawDescription: python datetime extract hour minute fast

description: Python datetime extract hour minute fast


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background="gray")

        frame = tk.Frame(background="white", borderwidth=1, relief="sunken",
                         highlightthickness=1)
        frame.pack(side="top", fill="x", padx=4, pady=4)

        entry = tk.Entry(frame, borderwidth=0, highlightthickness=0, background="white")
        entry.image = tk.PhotoImage(data=cancelImageData)
        imageLabel = tk.Label(frame, image=entry.image)
        imageLabel.pack(side="right", fill="y")
        entry.pack(side="left", fill="both", expand=True)

cancelImageData = '''
    R0lGODlhEAAQAPcAAAAAAAAAMwAAZgAAmQAAzAAA/wArAAArMwArZgArmQArzAAr
    /wBVAABVMwBVZgBVmQBVzABV/wCAAACAMwCAZgCAmQCAzACA/wCqAACqMwCqZgCq
    mQCqzACq/wDVAADVMwDVZgDVmQDVzADV/wD/AAD/MwD/ZgD/mQD/zAD//zMAADMA
    MzMAZjMAmTMAzDMA/zMrADMrMzMrZjMrmTMrzDMr/zNVADNVMzNVZjNVmTNVzDNV
    /zOAADOAMzOAZjOAmTOAzDOA/zOqADOqMzOqZjOqmTOqzDOq/zPVADPVMzPVZjPV
    mTPVzDPV/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYAmWYAzGYA/2YrAGYr
    M2YrZmYrmWYrzGYr/2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA
    /2aqAGaqM2aqZmaqmWaqzGaq/2bVAGbVM2bVZmbVmWbVzGbV/2b/AGb/M2b/Zmb/
    mWb/zGb//5kAAJkAM5kAZpkAmZkAzJkA/5krAJkrM5krZpkrmZkrzJkr/5lVAJlV
    M5lVZplVmZlVzJlV/5mAAJmAM5mAZpmAmZmAzJmA/5mqAJmqM5mqZpmqmZmqzJmq
    /5nVAJnVM5nVZpnVmZnVzJnV/5n/AJn/M5n/Zpn/mZn/zJn//8wAAMwAM8wAZswA
    mcwAzMwA/8wrAMwrM8wrZswrmcwrzMwr/8xVAMxVM8xVZsxVmcxVzMxV/8yAAMyA
    M8yAZsyAmcyAzMyA/8yqAMyqM8yqZsyqmcyqzMyq/8zVAMzVM8zVZszVmczVzMzV
    /8z/AMz/M8z/Zsz/mcz/zMz///8AAP8AM/8AZv8Amf8AzP8A//8rAP8rM/8rZv8r
    mf8rzP8r//9VAP9VM/9VZv9Vmf9VzP9V//+AAP+AM/+AZv+Amf+AzP+A//+qAP+q
    M/+qZv+qmf+qzP+q///VAP/VM//VZv/Vmf/VzP/V////AP//M///Zv//mf//zP//
    /wAAAAAAAAAAAAAAACH5BAEAAPwALAAAAAAQABAAAAiWAPcJHEiwYEFpCBMiNLhP
    WjZz4CB+A5dN2sGH2TJm+7ax4kCHEOlx3EgPHEeLDc1loydwokB6G1EJlEYRHMt6
    +1hW/IaSpreN+/ThzIYq5kyKGffV07ePpzSeMzl+UypU6aunMhtSdCcwI0t606A2
    3PjN3VVXK2NO+/iKIzZp0xB+Q4Xt4re7te4WZSgNVV+EfhkKLhgQADs=
'''

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Add an image to Tkinter Entry

description: Add an image to Tkinter Entry


code:
from os import system,fork,getpid
from glob import glob
from subprocess import call
from multiprocessing import Process

def caller(filename):
  pid=getpid()
  call(["callgrind_control","--instr=on",str(pid)],shell=True)
  execfile(filename,{})
  call(["callgrind_control","--instr=off",str(pid)],shell=True)

for filename in glob("py/*.py"):
  p=Process(target=caller,args=(filename,))
  p.start()
  p.join()

rawDescription: stopping instrumentation in callgrind

description: Stopping instrumentation in callgrind


code:
import module
f = module.__dict__["func_name"]
# f is now a function and can be called:
f()

rawDescription: How to change the string to class object in another file

description: Change the string to class object in another file


code:
import pygame
from pygame import mixer

# to use the event queue, this is required.
pygame.init()

mixer.init()

# or some other event id. This just has to be the same here and below.
mixer.music.set_endevent(pygame.USEREVENT + 1)
mixer.music.load('foo.mp3')
mixer.music.play()

ev = 0

while ev != pygame.USEREVENT + 1:
  ev = pygame.event.wait()

rawDescription: mp3 audio played from interactive python, but not from bash

description: Mp3 audio played from interactive python, but not from bash


rawDescription: Are all python magic methods available to all objects


rawDescription: "Trailing" One-Hot Encode

description: "Trailing" One-Hot Encode


code:
import sframe as sf
from scipy.sparse import csr_matrix

x = sf.SFrame({'users': [{'123': 1.0, '122': 5},
                         {'134': 3.0, '123': 10}]})
x = x.add_row_number('row_id')
x = x.stack('users')
A = csr_matrix((x['X3'], (x['row_id'], x['X2'])),
               shape=(2, 135))

rawDescription: sFrame into scipy.sparse csr_matrix

description: SFrame into scipy.sparse csr_matrix


code:
# Get a cursor for the entire collection
docs = db.collection.find()

for doc in docs:
    # Get all documents that have a common element
    related_docs = db.collection.find({"$or": [
        {"color": doc["color"]},
        {"name": doc["name"]},
        {"age": doc["age"]},
        ]})

    # Record the relationships in whatever structure you're using
    for related_doc in related_docs:
        store_relationship(doc, related_doc)

rawDescription: Getting all relations in DB by using rdflib


code:
self.tableWidget.itemDoubleClicked.connect(self.OpenLink)

def OpenLink(self,item):
    if item.column() == 1:
        webbrowser.open('www.google.com')

rawDescription: Link QTableWidget cells to webpages

description: Link QTableWidget cells to webpages


code:
from multiprocessing import Pool
p = Pool()                                   #number of processes = number of CPUs
keys, values= zip(*d.iteritems())            #ordered keys and values
processed_values= p.map( f, values )         #apply the function f to each set and wait for result
#then proceed to join the three sets

rawDescription: Python multiprocessing for each key in dictionary


code: unused_ips = [addr for addr in nova.floating_ips.list() if addr.instance_id is None]

rawDescription: Nova Python Client - List available IP addresses


code:
a = 3
globals().keys()
globals()['a']
id(globals()['a'])
id(a)

rawDescription: How are a name and its reference value related?


code:
# copied from http://www.kosbie.net/cmu/fall-10/15-110/koz/misc-demos/src/semi-transparent-stipple-demo.py

# semi-transparent-stipple-demo.py
# note: stipple only works for some objects (like rectangles)
# and not others (like ovals).  But it's better than nothing...

from Tkinter import *

def redrawAll(canvas):
    canvas.delete(ALL)
    # draw a red rectangle on the left half
    canvas.create_rectangle(0, 0, 250, 600, fill="red")
    # draw semi-transparent rectangles in the middle
    canvas.create_rectangle(200,  75, 300, 125, fill="blue", stipple="")
    canvas.create_rectangle(200, 175, 300, 225, fill="blue", stipple="gray75")
    canvas.create_rectangle(200, 275, 300, 325, fill="blue", stipple="gray50")
    canvas.create_rectangle(200, 375, 300, 425, fill="blue", stipple="gray25")
    canvas.create_rectangle(200, 475, 300, 525, fill="blue", stipple="gray12")

def init(canvas):
    redrawAll(canvas)

########### copy-paste below here ###########

def run():
    # create the root and the canvas
    root = Tk()
    canvas = Canvas(root, width=500, height=600)
    canvas.pack()
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    canvas.data = { }
    init(canvas)
    # set up events
    # root.bind("<Button-1>", mousePressed)
    # root.bind("<Key>", keyPressed)
    # timerFired(canvas)
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)

run()

rawDescription: Drawing basic shapes in python 2

description: Drawing basic shapes in python 2


code:
class SampleObject:

    def __init__(self):
        # ...
        self._total = None

    @property
    def total(self):
        """Compute or return the _total attribute."""
        if self._total is None:
            self.compute_total()

        return self._total

rawDescription: Calculate attribute if it doesn't exist

description: Calculate attribute if it doesn't exist


code:
df
df2
final = pd.merge(df,df2, how='outer', on=['Date', 'Hour', 'Make', 'Model'])
final
final.fillna(0, inplace=True)
final

rawDescription: How can I do a string object comparison between two csv files in Pandas (Python 2.7) and generate a new dataframe or csv file

description: Do a string object comparison between two csv files in Pandas (Python 2.7) and generate a new dataframe or csv file


code:
import re
re.sub(r"\s*problem\s*=\s*None\s*,?\s*", "", "abc( problem = None , )")
re.sub(r"\s*problem\s*=\s*None\s*,?\s*", "", "abc( problem = None  )")

rawDescription: Python regular expression to remove "problem=None," from "Abc(problem=None, fds=5, sff=(2, 1, 0))"


code:
def product_detail(request, id_category=None,id_product=None):
   actual_product = Product.objects.get(id = id_product)
   form_product_unit = Product_unitForm(data=request.POST or None,
       initial={'product': actual_product})

rawDescription: Django hide field from forms and add automatically field


code:
import signal
import os

os.kill(0, signal.CTRL_C_EVENT)

rawDescription: from python, cancelling C script using "ctr c" signal to command line

description: From python, cancelling C script using "ctr c" signal to command line


rawDescription: How do I convert a file stream to a data URI in Python?

description: Convert a file stream to a data URI in Python


code:
# Create one instance, seeded from current time, and export its methods
# as module-level functions.  The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.

rawDescription: Importing one module from different other modules only executes it once. Why?


code:
icnt = 0
shpAS = []  # empty list to start
while icnt < (intNumLines):
    shpA = scribus.createText(strLeft, strTop, strWidth, strHeight)
    scribus.setText(strTextA, shpA)
    icnt += 1
    shpAS.append(shpA)  # add new textbox at the end of the list

rawDescription: List of Variables in Python

description: List of Variables in Python


code:
from sqlalchemy.dialects.postgresql import array

# First write the subquery.  array() function is used for Pg ARRAY literals.
subq = db.session.query(
    db.func.unnest(array([1])).label('model_id'),
    db.func.unnest(array([2])).label('quantity')
).subquery()

# Now when you have the subquery, you can use it as if it were a Table object.
q = db.session.query(db.func.sum(ProductModel.mass * subq.c.quantity)).\
    join(subq, ProductModel.id == subq.c.model_id).\
    group_by(ProductModel.id)

rawDescription: SQLAlchemy: Join to subquery with no from field


code:
dicts = [d1, d2, d3]
allkeys = set(x for d in dicts for x in d.keys())
super_dic = {k:[d.get(k, 0) for d in dicts] for k in allkeys}
super_dic

rawDescription: Merging dictionaries for same key in Python


code:
@register.inclusion_tag('tagging/lateral_menu.html', takes_context=True)
def lateral_menu(context):
    object = context.get("category") or context.get("product")

if object.__class__.__name__.lower() == "product":
    request = context.get("request")
    category=lfs.catalog.utils.get_current_product_category(request, object)
else:
    category = object

top_category=category
while top_category.parent is not None:
    top_category = category.parent

categories =top_category.get_all_children()
return {"category" :category, "top_category" : top_category, "categories" : categories }

rawDescription: django-lfs product template

description: Django-lfs product template


code: sum(1<<i for i, b in enumerate(x) if b)

rawDescription: Python/Numpy: Convert list of bools to unsigned int


code:
days_with_items_hash = {}
items = Items.objects.filter(
   datetime__month = 6,
   datetime__year = 2015
)
for item in items:
    days_with_item_hash[item.datetime.day] = True

days_with_item = days_with_item_hash.keys()

rawDescription: Django: Which days have objects?

description: Django: Which days have objects


code:
for sel in response.xpath('//*[@id="latestPosts"]/div/div/div'):
    item = AeonItem()
    item['primary_url'] = sel.xpath('./a/@href').extract()

    ...

rawDescription: Why is Scrapy returning duplicate results?


code:
for line in text:
    if line.startswith('JOHN'):
        john.append(line)
    elif line.startswith('MIKE'):
        mike.append(line)
    elif line.startswith('SARAH'):
        sarah.append(line)

rawDescription: Splitting a text

description: Splitting a text


code:
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def encode(num, alphabet=ALPHABET):
    """Encode a number in Base X

    `num`: The number to encode
    `alphabet`: The alphabet to use for encoding
    """
    if (num == 0):
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        rem = num % base
        num = num // base
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)

def decode(string, alphabet=ALPHABET):
    """Decode a Base X encoded string into the number

    Arguments:
    - `string`: The encoded string
    - `alphabet`: The alphabet to use for encoding
    """
    base = len(alphabet)
    strlen = len(string)
    num = 0

    idx = 0
    for char in string:
        power = (strlen - (idx + 1))
        num += alphabet.index(char) * (base ** power)
        idx += 1

    return num

rawDescription: Base 62 conversion in Python

description: Base 62 conversion in Python


code: sum(v<<i for i, v in enumerate(p[::-1]))

rawDescription: Bool array to integer

description: Bool array to integer


rawDescription: How to parse this type of text?

description: Parse this type of text


code:
def index():
    return "Python works!"

def command(command):
    return "this is a command %s!" %command

rawDescription: Python get URL from Apache

description: Python get URL from Apache


code:
from flask import Flask
app = Flask(__name__)
import sys
import time
import flask

@app.route('/')
def generated_response_example():
    n = 20
    def response_generator():
        for i in range(n):
            print >>sys.stderr, i
            yield "%03d\n" % i
            time.sleep(.2)

    print >>sys.stderr, "returning generator..."
    gen = response_generator()

    # the call to flask.make_response is not really needed as it happens imlicitly
    # if you return a tuple.
    return flask.make_response(gen ,"200 OK", {'Content-length': 4*n})

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

rawDescription: Python Flask + nginx fcgi - output large response?


code: trainer = RPropMinusTrainer(net, dataset=trndata, verbose=True, weightdecay=0.01)

rawDescription: How to implement regularization in pybrain

description: Implement regularization in pybrain


code:
def foo(): return
foo()
def bar(): pass
bar()

rawDescription: Should I return after using a function?

description: Should I return after using a function


code:
# Concatenating
def lem(file):
    lem = []
    for line in file:
        lem.append(line.split()[1])
    return ''.join(lem)
    # Returning a list is the same, just omit the ''.join()
# To use when using ''.join, just print the return value
print(lem(file))
# To use when returning a list, loop (as in the generator case below), or print the list itself as in the ''.join case and it will print the list's repr

# Generator
def lem(file):
    for line in file:
        yield line.split()[1]
# To use the generator, either loop and print:
for x in lem(file):
    print(x)
# Or splat the result generator to print if you're using Py3's print
# function (or using from __future__ import print_function on Py2)
print(*lem(file)) # Separates outputs with spaces; sep="\n" to put them on separate lines, sep="" to print them back-to-back, etc.
# Or to print (or assign) them all at once as a single string:
print(''.join(lem(file))) # Change '' to whatever string you want to put between all the outputs

rawDescription: function only returning the last item

description: Function only returning the last item


code:
def search (filetosearch, query):
    with open(filetosearch, 'r') as inF:
        for line in inF:
            if query in line:
                return True

    return False

rawDescription: Search File Function not working

description: Search File Function not working


code: libor.index.name = 'Date'

rawDescription: Renaming an index in a Pandas Series?

description: Renaming an index in a Pandas Series


code:
def index(request):

    EducationFormSet = formset_factory(
        Application,
        Education,
        form=EducationForm,
        extra=3,
    )

    if request.method == 'POST':
        application_form = ApplicationForm(request.POST)

        if application_form.is_valid():
            application = application_form.save(commit=False)
            education_formset = EducationFormSet(request.POST, instance=application)

            if education_formset.is_valid():
                application.save()
                education_formset.save()

                return HttpResponseRedirect(reverse('thanks_and_good_luck_view'))
        else:
            education_formset = EducationFormSet(request.POST)
    else:
        application_form = ApplicationForm()
        education_formset = EducationFormSet()

    return render_to_response(
        'applications/index.html',
        {
            'application_form': application_form,
            'education_formset': education_formset,
        },
        context_instance=RequestContext(request)
    )

rawDescription: Are Django inline formsets on initial submission of model forms possible?


code:
def get_middle(arr):
    n = arr.shape[0] / 2.0
    n_int = int(n)
    if n % 2 == 1:
        return arr[[n_int], [n_int]]
    else:
        return arr[n_int:n_int + 2, n_int:n_int + 2]

rawDescription: Fastest way to access middle four elements in Numpy array?


code:
from IPython.display import HTML
df = pd.DataFrame(range(5), columns=['a'])
df['a'] = df['a'].apply(lambda x: 'link'.format(x))
HTML(df.to_html(escape=False))

rawDescription: Insert a link inside a pandas table

description: Insert a link inside a pandas table


code: worksheet.freeze_panes(1, 1) # # Freeze the first row and column

rawDescription: how to freeze a row and a columns in an excel file using xlsxwriter in python

description: Freeze a row and a columns in an excel file using xlsxwriter in python


code:
import chardet
rawdata = open(infile, "r").read()
result = chardet.detect(rawdata)
charenc = result['encoding']

rawDescription: Character detection in a text file in Python using the Universal Encoding Detector (chardet)


code:
class ResultView(ListView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        if self.request.method == 'POST':
            form = InputForm(self.request.POST)
            if form.is_valid():
                name = form.cleaned_data['name']
                age = form.cleaned_data['age']
                return Result.filter(name=name, age=age)
        return super(ResultView, self).get_queryset()

rawDescription: django- how two def in the same views.py pass the data

description: Django- how two def in the same views.py pass the data


code:
from mapreduce import operation as op
def process(entity):
    entity.small = None
    yield op.db.Put(entity)

rawDescription: How to delete a db.BlobProperty from many entities?

description: Delete a db.BlobProperty from many entities


code:
import beatbox
from salesforce_bulk import SalesforceBulk

# log in to sandbox using beatbox
service = beatbox.PythonClient()

service.serverUrl = 'https://test.salesforce.com/services/Soap/u/20.0'
user = 'user@user.com'
password = 'secret'
token = '12345'

service.login(user, password+token)

# the _Client_serverUrl has the instance url + some
# SOAP stuff, so we need to strip that off
groups = service._Client__serverUrl.split('/')
instance_url = '/'.join(groups[:3])

# now we can use the instance_url and sessionId to
# log into Salesforce through SalesforceBulk
bulk = sfdc_bulk_connect(instance_url, service.sessionId)

rawDescription: How to login to the sandbox using salesforce Bulk API

description: Login to the sandbox using salesforce Bulk API


rawDescription: How to add option in Python code?

description: Add option in Python code


code:
@cache.cache('test', expire=10000)
def plus(x, y):
    return x + y

plus(8, 9)
plus(11, 12)

# invalidate plus(11, 12)
cache.invalidate(plus, 'test', 11, 12, expire=10000)

rawDescription: Beaker: how access a cache created by decorator programmatically?


code:
fields = ax.stackplot(df.index,df.field1,df.field2)
colors = [field.get_facecolor()[0] for field in fields]
patch1=mpl.patches.Patch(color=colors[0],label= 'field 1')
patch2=mpl.patches.Patch(color=colors[1], label ='field 2')

rawDescription: python matplotlib: add labels and set their colours correctly for a stackplot

description: Python matplotlib: add labels and set their colours correctly for a stackplot


code:
with open('mylist.txt') as mylist:
    proteins = set(line.strip() for line in mylist)

with open('mydict.txt') as mydict, open('result.txt', 'w') as output:
    for line in mydict:
        _, protein = line.strip().split()
        if protein in proteins:
            output.write(line)

rawDescription: Finding common elements between a list and a dictionary in python


code:
import pygame
import sys
import itertools

cloud_background = pygame.image.load('clouds.bmp')
brick_tile = pygame.image.load('brick_tile.png')

pink = (255, 64, 64)
w = 640
h = 480
screen = pygame.display.set_mode((w, h))
running = 1

def setup_background():
    screen.fill((pink))
    screen.blit(cloud_background,(0,0))
    brick_width, brick_height = brick_tile.get_width(), brick_tile.get_height()
    for x,y in itertools.product(range(0,610+1,brick_width),
                                 range(390,450+1,brick_height)):
        # print(x,y)
        screen.blit(brick_tile, (x, y))
    pygame.display.flip()

while running:
    setup_background()
    event = pygame.event.poll()
    if event.type == pygame.QUIT: sys.exit()

rawDescription: How do you cover an area in tiles(images) in python / pygame?

description: Cover an area in tiles(images) in python / pygame


code:
def filtercaps(infilename,outfilename):

  import csv
  list_of_words=[]
  list=[]
  with open(infilename) as inputfile:
      for row in csv.reader(inputfile):
          list.append(row)
      for l in list:
          if len(l) == 0:
              continue
          first_entry = l[0]
          first_letter = first_entry[0][0]
          if first_letter in 'qwertyuiopasdfghjklzxcvbnm':
              list_of_words.append(l)
  f = open(outfilename, "w")
  writer = csv.writer(f)
  for l in list_of_words:
      writer.writerow(l)
  f.close()

filtercaps("Enable1.txt","Enable2.txt")

rawDescription: Removing Capitalized Strings from Input File in Python3.4?


code:
db.events.aggregate([
    { '$match':
        { 'end':
            { '$gte': datetime.utcnow() - timedelta(days=3) }
        }
    },
    { '$project':
        {
            'timeDelta': {
                '$subtract': ['$end', datetime.utcnow()]
            }
        }
    },
    { '$project':
        {
            'absTimeDelta' : {
                '$cond' : [
                    { '$lte': ['$timeDelta', 0] },
                    { '$multiply' : ['$timeDelta', -1 ] },
                    '$timeDelta'
                ]
            }
        }
    },
    { '$sort':
        {
            'absTimeDelta' : 1
        }
    }
])

rawDescription: Sort documents in Mongodb query by dates closest to a field


code: struct.pack("b" * len(this_or_address_send_array), this_or_address_send_array)

rawDescription: How to add values depending on length of an array

description: Add values depending on length of an array


rawDescription: How to parse random key value pair string in Python?

description: Parse random key value pair string in Python


code:
from itertools import chain
list(chain.from_iterable(a))

rawDescription: Move elements out of sublists into new list


code:
import igraph
g = igraph.Graph([(0,1), (0,2), (2,1)])
igraph.plot(g, vertex_frame_color='red')

rawDescription: igraph python remove border

description: Igraph python remove border


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MultipleLocator

x_data = np.arange(97, 110)
y_data = np.random.rand(len(x_data))

def ord_to_char(v, p=None):
    return chr(int(v))

fig, ax = plt.subplots()
ax.plot(x_data, y_data, 'x')
ax.xaxis.set_major_formatter(FuncFormatter(ord_to_char))
ax.xaxis.set_major_locator(MultipleLocator(1))
plt.show()

rawDescription: Python: Plotting strings on x axis of matplot scatterplot yields "could not convert string to float"


code:
counter = 1
while (counter <= 5):
    if counter < 2:
        print("Less than 2")
    elif counter > 4:
        print("Greater than 4")
    counter += 1

rawDescription: While loop with if/else statement in Python


rawDescription: App Engine httplib.HTTPConnection deadline


code:
from functools import reduce
from operator import and_, or_

querysets = [q1, q2, q3, ...]  # List of querysets you want to combine.

# Objects that are present in *at least one* of the queries
combined_or_querysets = reduce(or_, querysets[1:], querysets[0])

# Objects that are present in *all* of the queries
combined_and_querysets = reduce(and_, querysets[1:], querysets[0])

rawDescription: How to combine two querysets when defining choices in a ModelMultipleChoiceField?

description: Combine two querysets when defining choices in a ModelMultipleChoiceField


code:
import random

greetings = ['hola', 'hello', 'GreeTinGs', 'hi', 'Hi', 'hey!','hey']
question = ['How are you?','How are you doing?']
responses = ['Okay',"I'm fine"]

while True:
        userInput = input(">WHAT:").casefold()
        if userInput.upper() in [x.upper() for x in greetings]:
            greetingsrandom = random.choice(greetings)
            print (greetingsrandom)
        elif userInput in [x.upper() for x in question]:
            responsesrandom = random.choice(responses)
            print (responsesrandom)
        else:
            print("I did not understand what you said")

rawDescription: Finding uppercase lowercase words from an input, Python3.


code:
class Main(object):
    def __init__(self,arg1,arg2):
        ...
    def run(self):
        pass

if __name__=='__main__':
    import optparse
    class CLI(object):
        def parse_options(self):
            usage = 'usage: %prog [options]'+__usage__
            parser = optparse.OptionParser(usage=usage)
            parser.add_option('-i', dest='arg1')
            parser.add_option('-j', dest='arg2')
            (self.opt, self.args) = parser.parse_args()
        def run(self):
            self.parse_options()
            Main(self.opt.arg1,self.opt.arg2).run()
    CLI().run()

rawDescription: script as module and executable

description: Script as module and executable


code:
def round_to(n, precision):
    correction = 0.5 if n >= 0 else -0.5
    return int( n/precision+correction ) * precision

def round_to_05(n):
    return round_to(n, 0.05)

rawDescription: Python - Round to nearest 05

description: Python - Round to nearest 05


code:
from tornado.template import Template
t = Template(my_template_string_from_database)
r = t.generate(key=value) #as we do in loader

rawDescription: Tornado template loader from string - Heroku


code:
strs= "abbbd cdda cbaa"
max(strs.split(),key=lambda x:x.count("b"))

rawDescription: Return the string with the highest occurrence of a specific character


code:
import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                       shell=True, preexec_fn=os.setsid)

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

rawDescription: How to terminate a python subprocess launched with shell=True

description: Terminate a python subprocess launched with shell=True


code:
mask = ~np.isnan(varx) & ~np.isnan(vary)
slope, intercept, r_value, p_value, std_err = stats.linregress(varx[mask], vary[mask])

rawDescription: Linear regression of arrays containing NANs in Python/Numpy


code:
import pandas as pd
import matplotlib.pyplot as plt

# Dummy data
x = range(1, 5)
y = [i**(0.5) for i in x]
ser = pd.Series(y, index=x)

ax1 = ser.plot(kind='bar')  # plot with pandas and assign to an axis object

# Grab the patches from the axis and plot the text near them, rounding to 1dp
for rect in ax1.patches:
    height = rect.get_height()
    ax1.text(rect.get_x()+rect.get_width()/2., 1.05*height, round(height, 1),
                ha='center', va='bottom')

rawDescription: How do I add text labels of bin contents when drawing bar charts using pandas DataFrames?

description: Add text labels of bin contents when drawing bar charts using pandas DataFrames


code:
for page in paging(service,
                   service.jobs().getQueryResults,
                   num_retries=num_retries,
                   **query_job['jobReference']):
  for row in page['rows']:
    # Each row is a dict with fields, 'f', containing
    # an array of table cells, one for each column
    # of the query output. Each cell is a dict
    # containing a value, 'v'.
    yield row['f'][0]['v']  # This query generates 1 column.

rawDescription: How can I generate a BigQuery result without JSON formatting?

description: Generate a BigQuery result without JSON formatting


code:
next_points = points[1:]
prev_points = points[:-1]

d_next = distance_function(next_points, points[:-1])
d_prev = distance_function(points[1:], prev_points)

rawDescription: Select all adjacent elements without copying the numpy array


rawDescription: Python noob for loop?

description: Python noob for loop


code:
class Helper:pass

# use name space
def one(a):
    a.x=1
    a.y=2
    a.z=3
    a.h=33
    a.j=454
    a.l=353
    a.m=898

def two(a):
    a.y=7

a=Helper()

one(a)
print(a.x,a.y)
two(a)
print(a.x,a.y)

#-------------------------------------------------------------------
# I think you have solution and dont need to read next lines :)
# next lines are just bonus ;)
#-------------------------------------------------------------------

# you could use more independent "namespaces"
b=Helper()
one(b)
print(b.y)
print(a.y)  # "namespace a" is unchanged

# if you like to see which attributes are defined you could use funciton dir
# (under python3 it is a little more complicated)
print(dir(a))
print(dir(b))

# please dont do next lines at home!!! :P:P:P (__builtins__ is special you could get unwanted results!)
one(__builtins__)

print(x) #

rawDescription: Python definition function parameter passing


code:
from contextlib import contextmanager

class X:
    def disable_me():
        print("do stuff")

def run_me(x):
    print("run_me")
    x.disable_me()

@contextmanager
def disable_function(obj, name):
    temp = getattr(obj, name)
    setattr(obj, name, lambda: None)
    yield
    setattr(obj, name, temp)

x = X()
with disable_function(x, "disable_me"):
    run_me(x)

rawDescription: Possible to Globally Replace A Function with a Context Manager in Python?


rawDescription: Is there a way to detect the order of a module's globals() in python?


code:
import re
email_list = "mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com"
re.split(r'[, ]*',email_list)

rawDescription: Python:- Split email from list of emails (comma, space separated)


code:
#!/usr/bin/env python

import pynotify

pynotify.init("MyApplication")

a = pynotify.Notification("Test notification", "Lorem ipsum op")
a.show()
raw_input("Press return to update the notification")
a.update("Updated notification", "Ipsum lorem still op")
a.show()

rawDescription: How to remove an obsolete pynotify notification?

description: Remove an obsolete pynotify notification


code:
for div in range(3, n, 2):
  if (n % div == 0):
    # not a prime
    n += 1
    break
else:
  ...

rawDescription: Python indentation, allignment of IFs and ELSEs


code:
if actor1[film1] in (actor1[film2], actor2[film2], actor3[film2]):
   FavActorScore += 5
if actor2[film1] in ( actor1[film2], actor2[film2], actor3[film2]):
   FavActorScore += 5
if actor3[film1] in (actor1[film2], actor2[film2], actor3[film2]):
   FavActorScore += 5

rawDescription: Adding to a int value with pre-existing dictionaries


code:
import sys
from PyQt4 import QtGui, uic

class TestGUI(QtGui.QMainWindow):
    def __init__(self):
        super(TestGUI, self).__init__()
        uic.loadUi('TEST.ui', self)
        self.actionAdd_Tab.triggered.connect(self.handleAddTab)

    def handleAddTab(self):
        contents = QtGui.QWidget(self.tabWidget)
        layout = QtGui.QVBoxLayout(contents)
        # add other widgets to the contents layout here
        # i.e. layout.addWidget(widget), etc
        self.tabWidget.addTab(contents, 'Tab One')

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = TestGUI()
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt4 menu acction to add new tab to QTabWidget


code:
import sys
sys.executable

rawDescription: Getting python.exe path at run time

description: Getting python.exe path at run time


code:
for i in range(0x2660, 0x2668):
    print(chr(i))

rawDescription: Python 3.x and printing Unicode symbols

description: Python 3.x and printing Unicode symbols


code:
from lxml import etree, objectify

metadata = '/Users/user1/Desktop/Python/metadata.xml'
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(metadata, parser)
root = tree.getroot()

####
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue  # (1)
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]
objectify.deannotate(root, cleanup_namespaces=True)
####

tree.write('/Users/user1/Desktop/Python/done.xml',
           pretty_print=True, xml_declaration=True, encoding='UTF-8')

rawDescription: Remove namespace and prefix from xml in python using lxml


code:
from PIL import Image, ImageDraw

img = Image.open('image.png')
img = img.convert("RGB") # Make sure we are in 8-bit RGB
draw = ImageDraw.Draw(img)

for y in range(img.height):
    for x in range(img.width):
        # getpixel returns a tuple with (R, G, B)
        if img.getpixel((x, y))[1] > 175: # If too green
            draw.point((x,y), '#000000') # Color syntax is CSS-like

img.save('test_edited.png', 'PNG')
# You can also use img.show() in a graphical environment

rawDescription: Changing png pixels selectively with PyPNG on Raspbian


code:
start = 4 # Index where you want to start.
Anew = A[:,:,:,start:start+2]

rawDescription: Crop part of np.array

description: Crop part of np.array


rawDescription: Pass scraped item as json to a PHP script


rawDescription: Python Numpy array conversion

description: Python Numpy array conversion


code:
def myfunc(value, values=None):
    if values is None:
        values = []
    values.append(value)
    return values

print(myfunc("item"))
print(myfunc("item"))

rawDescription: Clearing an optional argument at each call


code:
import re
url = 'https://www.advertise-example.com/ads/2022/presents'
int(re.search(r'\d+', url).group())

rawDescription: How to get an integer value from string(may be url) in python

description: Get an integer value from string(may be url) in python


code:
from PIL import Image, ImageDraw

im = Image.open("1.jpg")

x, y =  im.size
eX, eY = 30, 60 #Size of Bounding Box for ellipse

bbox =  (x/2 - eX/2, y/2 - eY/2, x/2 + eX/2, y/2 + eY/2)
draw = ImageDraw.Draw(im)
draw.ellipse(bbox, fill=128)
del draw

im.save("output.png")
im.show()

rawDescription: Python PIL: How to draw an ellipse in the middle of an image?


code:
import spynner

def content_ready(browser):
    if 'id="feedback-' in browser.html:
        return True

br = spynner.Browser()
br.load("http://www.venere.com/it/hotel/roma/hotel-ferrari/#reviews", wait_callback=content_ready)

with open("test.html", "w") as hf:
    hf.write(br.html.encode("utf-8"))

rawDescription: Spynner doesn't load html from URL

description: Spynner doesn't load html from URL


code:
num_times = int(input('How many times should display HB '))

for i in range(num_times):
    print('HB ', end='')
    if (i + 1)%3 == 0:
        print('\n')

rawDescription: How to make an item print three times then start a new row while keeping the name of user inputs

description: Make an item print three times then start a new row while keeping the name of user inputs


code:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

class ImprintPlusApp:

    def __init__(self, master):
        self.frame_header = ttk.Frame(master)
        self.frame_header.pack()

        ttk.Label(self.frame_header, text = "Bienvenidos a Imprint Plus Manager")

        self.frame_crearorden = ttk.Frame(master)
        self.frame_crearorden.pack()

        ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
        ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
        ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
        ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)

        self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
        self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
        self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
        self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)

        self.entry_name.grid(row = 0, column = 1, padx = 5)
        self.entry_email.grid(row = 2, column = 1, padx = 5)
        self.entry_numtc.grid(row = 4, column = 1, padx = 5)
        self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)

        ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
        ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 1, padx = 5)

    def submit(self):
        print ("Nombre: {}".format(self.entry_name.get()))
        print ("Email: {}".format(self.entry_name.get()))
        print ("Num Cel/Tel: {}".format(self.entry_name.get()))
        print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
        self.clear()
        messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")

    def clear(self):
        self.entry_name.delete(0, "end")
        self.entry_email.delete(0, "end")
        self.entry_numtc.delete(0, "end")
        self.entry_addinf.delete(1.0, "end")

def main():
    root = Tk()
    app = ImprintPlusApp(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: tkinter window is blank after executing code

description: Tkinter window is blank after executing code


code:
def check(n,a,i=0):
    if len(n) <= i:
        return True
    if int(n[i])>=a :
        return False
    else:
        return check(n,a,i+1)

n = str(input('enter no:'))
a = int(input('enter base:'))

print(check(n,a,i=0))

rawDescription: checking whether representation of number in a given base is valid

description: Checking whether representation of number in a given base is valid


code:
from django.utils.translation import ugettext_lazy as _
class Items(Model):
    __doc__ = _('translatable description for Items')

    def total(self):
        return self.__total
    total.__doc__ = _(""" Method: Count total order price""")

rawDescription: How to i18n method comment for displays django-admindoc

description: I18n method comment for displays django-admindoc


code:
def fib(n):
    print("Fibonacci: {0}".format(n))
    if n == 1:
        return 1
    elif n == 0:
        return 0
    else:
        return fib(n-1) + fib(n-2)

rawDescription: Python 3.3.4 function not computing past a certain argument


code:
from itertools import groupby
from operator import itemgetter
indices = ((x[0] for x in g) for _, g in groupby(enumerate(a), key=itemgetter(1)))
[[b[x] for x in lst] for lst in indices]

rawDescription: Splitting a list into groups determined by grouping of another list


code:
def save(self, *args, **kwargs):
    for project in self.cleaned_data.get('projects'):
        project.users.add(self.instance)
    return super(AssignProjectForm, self).save(*args, **kwargs)

rawDescription: ModelForm with a reverse ManytoMany field


code:
import os.path, time
time.ctime(os.path.getctime('test.png'))

rawDescription: Change 'Created Time' in yaml file to 'Current Time'


code: test = raw_input("Put in a word")

rawDescription: How to store an input(raw_input) in a variable to use it later in Python 2.7.9?

description: Store an input(raw_input) in a variable to use it later in Python 2.7.9


rawDescription: Picking the first group of regex map as a new column


code:
def load_file(self, source):
    if isinstance(source, str):
        import os.path
        if not os.path.exists(source):
            raise IOError("Cannot load_file('"
                + source
                + "'): does not exist")
        with open(source, "rb") as fh:
            header_bytes = fh.read(12)
            # ignore header
            self.code = marshal.load(fh)

        return self.code

rawDescription: Python 3 bytecode format

description: Python 3 bytecode format


code:
self.CreateStatusBar(2)
self.SetStatusText("A Custom StatusBar...", 1)
wx.CallLater(10000, self.SetStatusText, "", 1)

rawDescription: How to manage wx.StatusBar text in interactions with menus

description: Manage wx.StatusBar text in interactions with menus


code:
from cherrypy.lib.httputil import parse_query_string
parse_query_string(cherrypy.request.query_string)

rawDescription: Python cherrypy, get the query_string parsed


code:
pattern = "haha"
text = "hahahaha"
[i for i in range(len(text)-len(pattern)+1) if text[i:].startswith(pattern)]

rawDescription: Occurrences of a pattern in a string and its indices


code:
import sys
import cmd

message = cmd.raw_input("Enter something to encypt: ")
translated = ''

for i in range(len(message)):
    translated = translated + message[i]
    i = i - 1
print(translated)

rawDescription: Basic Encryption in Python

description: Basic Encryption in Python


code:
with open('numbers.txt') as file:
    lst = [line.strip() for line in file]

rawDescription: How do you read lines from a .txt file?

description: Read lines from a .txt file


code:
def redirect_to_login(*args, **kwargs):
    return args[0].redirect(users.create_login_url(args[0].request.path))

def admin_only(handler):
    def wrapped_handler(*args, **kwargs):
        user = users.get_current_user()
        if user:
            if authorized(user):
                return handler(args[0])
            else:
                logging.warning('An unauthorized user has attempted '
                                'to enter an authorized page')
                return redirect_to_login(*args, **kwargs)
        else:
            return redirect_to_login(*args, **kwargs)

    return wrapped_handler

rawDescription: getting redirect loop for admin_only decorator

description: Getting redirect loop for admin_only decorator


rawDescription: Use two columns for unique entry identification


code:
import numpy as np
a = np.random.rand(20)
a[4] = -np.inf
k = 10
a[np.isneginf(a)] = inf
result = a[np.argsort(a)[:k]]

rawDescription: Get smallest N values from numpy array ignoring inf and nan


code:
combined_dict = {key: {'first_dict': first_dict[key], 'second_dict': second_dict[key]}
                 for key in first_dict.viewkeys() & second_dict}

rawDescription: Combining Two Dictionaries by Like Keys

description: Combining Two Dictionaries by Like Keys


code:
self.auth.get_user_by_password(username, password, remember=False,
save_session=True)

rawDescription: GAE python webapp2 authentication setting max token age


code:
import numpy as np
import pandas as pd
from io import BytesIO
from flask import Flask, send_file

app = Flask(__name__)
@app.route('/')

def index():

    #create a random Pandas dataframe
    df_1 = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))

    #create an output stream
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')

    #taken from the original question
    df_1.to_excel(writer, startrow = 0, merge_cells = False, sheet_name = "Sheet_1")
    workbook = writer.book
    worksheet = writer.sheets["Sheet_1"]
    format = workbook.add_format()
    format.set_bg_color('#eeeeee')
    worksheet.set_column(0,9,28)

    #the writer has done its job
    writer.close()

    #go back to the beginning of the stream
    output.seek(0)

    #finally return the file
    return send_file(output, attachment_filename="testing.xlsx", as_attachment=True)

app.run(debug=True)

rawDescription: Excel export with Flask server and xlsxwriter


rawDescription: Converting a string of tuples to a list of tuples in Python


code:
person
[ {'initials':x,'name':y} for x,y in person ]

rawDescription: Converting a list of list to list of dictionary


code: commands = ['foo', 'bar', 'exit', 'hello world', 'add number']

rawDescription: python string split

description: Python string split


code:
import plotly.plotly as py
from plotly.graph_objs import *

trace1 = Scatter3d(
    x=[1, 2],
    y=[1, 2],
    z=[1, 2]
)
data = Data([trace1])
layout = Layout(
    scene=Scene(
        xaxis=XAxis(title='x axis title'),
        yaxis=YAxis(title='y axis title'),
        zaxis=ZAxis(title='z axis title')
    )
)
fig = Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='3d-scatter-with-axes-titles')

rawDescription: Show legend and label axes in plotly 3D scatter plots


code:
from rest_framework import serializers

class BlockRepresentationSerializer(serializers.ModelSerializer):
    # Some fields
    name = serializers.SerializerMethodField()

    class Meta:
        model = BlockRepresentation

    def get_name(self, obj):
        if obj.planeable:
            return obj.planeable.name
        return ''

rawDescription: Using ModelSerializer with joined records


code:
data = open("mini_nx.py").read().replace("nx.", "").splitlines()
data = [line for line in data if not line.strip().startswith("#")]

final_data = []
inside = False
for line in data:
    if not inside and line.strip().startswith('"""'):
        if line.strip().endswith('"""') and line.count('"""') > 1:
            final_data.append(line)
        else:
            line = line.rstrip('"')
            if '"' in line:
                line += '-"""'
            else:
                line += '"""-"""'
            final_data.append(line)
            inside = True
        continue
    if inside and line.endswith('"""'):
        inside = False
    elif not inside and line.strip():
        final_data.append(line)

with open("converted_mini_nx.py", "w") as f:
    f.write("\n".join(final_data))

rawDescription: how to delete python code that's not covered

description: Delete python code that's not covered


rawDescription: How to add newline to end of file.write()?

description: Add newline to end of file.write()


code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FuncFormatter

data = (0, 1890,865, 236, 6, 1, 2, 0 , 0, 0, 0 ,0 ,0 ,0, 0, 0)
ind = range(len(data))
width = 0.9   # the width of the bars: can also be len(x) sequence

# Add `aling='center'` to center bars on ticks
p1 = plt.bar(ind, data, width, align='center')
plt.xlabel('Duration 2^x')
plt.ylabel('Count')
plt.title('DBFSwrite')
plt.axis([0, len(data), -1, max(data)])

ax = plt.gca()

# Place tickmarks at every multiple of 1, i.e. at any integer
ax.xaxis.set_major_locator(MultipleLocator(1))
# Format the ticklabel to be 2 raised to the power of `x`
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: int(2**x)))
# Make the axis labels rotated for easier reading
plt.gcf().autofmt_xdate()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)

plt.savefig('myfig')

rawDescription: matplotlib naming the tick marks on x axis 1, 2, 4, 8, 16, etc

description: Matplotlib naming the tick marks on x axis 1, 2, 4, 8, 16, etc


code:
l=['diffuse systemic sclerosis', 'back', 'public on july 15 2008']
[i.split()[0] for i in l]

rawDescription: Get first word of all the list elements

description: Get first word of all the list elements


code: uniques = set(x for x in names.split(u', ') for names in input_list)

rawDescription: Quickest way to get unique values

description: Quickest way to get unique values


code:
import subprocess

# if the script don't need output.
subprocess.call("php /path/to/your/script.php")

# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()

rawDescription: Execute php code in Python

description: Execute php code in Python


code:
import cv2

canvas = np.zeros((480,640))

t = np.arange(0, 512, 1) # sample time axis from 1 to 512
nse = np.random.randn(len(t))

# some normalization to fit to canvas dimension
t = 640 * t / 512
nse = 480 * nse / nse.max()

pts = np.vstack((t,nse)).T.astype(np.int)

cv2.polylines(canvas, [pts], False, 255)

imshow(canvas, 'gray')

rawDescription: Python montage a plot on OpenCV image and record as video


code:
import matplotlib as mpl
mpl.use('Agg')

rawDescription: Is there any way to ask Basemap not show the plot?


code:
# ...
# I renamed new_protocol to new_protocol_form here
new_protocol_form = AddProtocol(request.POST, request.FILES)
if new_protocol_form.is_valid():
    # save() method of form returns instance
    new_protocol = new_protocol_form.save(commit=False)
    # assigning related field
    new_protocol.study = study
    new_protocol.save()
# ...

rawDescription: Django: Value being set to None after Object.get


code:
class Test(unittest.testcase):
    def cleanDB(self):
        """db cleaning code goes here"""
    def setUp(self):
        self.cleanDB()
        # Rest of setup code
    def tearDown(self):
        # tearDown code
        self.cleanDB()

rawDescription: call tearDown() in setUp()?

description: Call tearDown() in setUp()


code:
from socket import *
SERVER       = ('irc.boats.gov',6667)  # Server address

# Open up connections
connections = []
with open('accts.txt', 'r') as f:
    for line in f:
        s = socket(AF_INET,SOCK_STREAM)
        s.connect(SERVER)
        connections.append(s)
        s.send('PASS '+password+'\r\n')
        s.send('NICK '+nick+'\r\n')
        s.send('JOIN '+channel+'\r\n')

rawDescription: What is the best way to handle multiple socket connections


code:
arr= []

if input_value in arr:
  # reject action
  ...
else:
  # add to array
  arr.append(input_value)

  # save to file
  ...

rawDescription: unique write in to file using python

description: Unique write in to file using python


rawDescription: Natural sort of Unicode list by numbers before characters


code:
d = a.join(b,(F.abs(a['id_a'] - b['id_b']) < 2)).drop(b['grp'])

## == Physical Plan ==
## Project [id_a#2L,grp#1L,id_b#5L]
## +- Filter (abs((id_a#2L - id_b#5L)) < 2)
##    +- CartesianProduct
##       :- ConvertToSafe
##       :  +- Project [id#0L AS id_a#2L,(FLOOR((cast(id#0L as double) / 10.0)) * 10) AS grp#1L]
##       :     +- Scan ExistingRDD[id#0L]
##       +- ConvertToSafe
##          +- Project [id#3L AS id_b#5L]
##             +- Scan ExistingRDD[id#3L]

rawDescription: Does Spark SQL do predicate pushdown on filtered equi-joins?


code: ls(TCP, verbose=True)

rawDescription: Scapy TCP RST atack

description: Scapy TCP RST atack


code:
myList = [ "1", "2", "3" ]
myList = [ int(i) for i in myList ]

rawDescription: Python newbie array - list conversion

description: Python newbie array - list conversion


code:
from collections import Counter
with open('input') as fin:
    term_counts = [Counter(line.split()) for line in fin]

rawDescription: Python gets Killed (probably memory leak)


code:
class BuildingsSerializer(serializers.ModelSerializer):
    masterlisting_set = serializers.SerializerMethodField()

    def get_masterlisting_set(self, obj):
        return MasterListing.objects.filter(building=obj).values_list('pk',flat=True)

rawDescription: Django-REST Serializer: Queryset does not filter PrimaryKeyRelatedField results


rawDescription: caseless comparison of two unicode strings

description: Caseless comparison of two unicode strings


code:
# simplify the grid by making all items strings
puzzle = [
    ['A','B','C','D','E','F','G','H'],
    ['-','-','-','-','-','-','-','-','-'],
    ['.','1','.','.','1','1','1','0','|1'],
    ['1','.','.','1','0','0','.','0','|2'],
    ['1','0','.','0','1','1','.','0','|3'],
    ['0','0','1','.','1','1','.','1','|4'],
    ['0','0','0','1','1','0','0','0','|5'],
    ['1','0','0','0','0','.','0','.','|6'],
    ['1','1','0','.','.','.','.','.','|7'],
    ['1','0','1','1','1','.','1','0','|8'],
    ]

for row in puzzle:
    print(' '.join(row))

print()

for column in range(len(puzzle[0])):
    if column >= 2:
        # check rows, starting at the third column of the grid
        for row in range(2, len(puzzle)):
            # take three items and put them in a set
            block = set(puzzle[row][column - 2: column + 1])
            # check that the row block is valid and complete
            if len(block) == 1 and '.' not in block:
                print('ERROR: row %s, columns %s-%s' % (
                    row - 1, puzzle[0][column - 2], puzzle[0][column]))
    # check columns, starting at the third row of the grid
    for row in range(4, len(puzzle)):
        # take three items and put them in a set
        block = {puzzle[row - 2][column],
                 puzzle[row - 1][column],
                 puzzle[row][column]}
        # check that the column block is valid and complete
        if len(block) == 1 and '.' not in block:
            print('ERROR: column %s, rows %s-%s' % (
                puzzle[0][column], row - 3, row - 1))

rawDescription: How to vertically compare a multidimensional list in Python?

description: Vertically compare a multidimensional list in Python


code:
if NdeProc.is_alive():
    ...
else:
    ...

rawDescription: How to check if child process is still running?

description: Check if child process is still running


code:
import numpy as np
import matplotlib.pyplot as plt
plt.ion()

import random
t=0
r=3.0
n=0
A=[]
for x in range(10):
    for y in range(10):
        A.append([random.uniform(0,1),random.uniform(0,1)])

for m in range(len(A)):
    plt.plot(A[m][0],A[m][1], "x", color="blue")
    plt.draw()
plt.pause(1)

while n<=100:
    for m in range(len(A)):
        A[m][0]=r*A[m][0]*(1-A[m][0])
        A[m][1]=r*A[m][1]*(1-A[m][1])
    for m in range(len(A)):
        plt.plot(A[m][0],A[m][1], "x", color="blue")
    plt.draw()
    plt.pause(1)
    plt.clf()

rawDescription: Python - How do I animate my scatterplot?


code:
class PageAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(PageAdmin, self).get_queryset(request)
        return qs.filter(link__isnull=True)

admin.site.register(Page, PageAdmin)

rawDescription: Django admin exclude subclass

description: Django admin exclude subclass


code: newton_krylov(lambda k:F(k,1,2,3), ... )

rawDescription: How to pass additional arguments to scipy.optimize.newton_krylov?

description: Pass additional arguments to scipy.optimize.newton_krylov


rawDescription: How to keep child frames on top of parent

description: Keep child frames on top of parent


rawDescription: Exclude field from values() or values_list()


code:
data = np.genfromtxt("/home/.../.../.../all", delimiter=',', skip_header=True)

model = data[:,0]
fhr = data[:,1]
lats = data[:,2]
lons = data[:,3]

models = ['ANVI', 'BAMS', 'CLIP']
cols = ['r','g','b']

for i in range(len(models)):
    plt.plot(x[model==models[i]],y[model==models[i]],
             marker='o',linestyle='-',color=cols[i])
plt.show()

rawDescription: Correcting Trajectory Tracks in Matplotlib


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

from matplotlib.container import ErrorbarContainer

class re_order_errorbarHandler(matplotlib.legend_handler.HandlerErrorbar):
    """
    Sub-class the standard error-bar handler
    """
    def create_artists(self, *args, **kwargs):
        #  call the parent class function
        a_list = matplotlib.legend_handler.HandlerErrorbar.create_artists(self, *args, **kwargs)
        # re-order the artist list, only the first artist is added to the
        # legend artist list, this is the one that corresponds to the markers
        a_list = a_list[-1:] + a_list[:-1]
        return a_list

my_handler_map = {ErrorbarContainer: re_order_errorbarHandler(numpoints=2)}

fig, ax = plt.subplots()
x = np.linspace(0,10,100)
y = np.sin(x) + np.random.rand(100)
yerr = np.random.rand(100)

erbpl1 = ax.errorbar(x, y, yerr=yerr, fmt='o', label='A')
erbpl2 = ax.errorbar(x, 0.02*y, yerr=yerr, fmt='o', label='B')

leg = ax.legend(handler_map=my_handler_map)

lines = [erbpl1, erbpl2]
lined = dict()
# not strictly sure about ordering, but
for legline, origline in zip(leg.legendHandles, lines):
    legline.set_picker(5)  # 5 pts tolerance
    lined[legline] = origline

def onpick(event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibility
    legline = event.artist
    origline = lined[legline]
    for a in origline.get_children():
        vis = not a.get_visible()
        a.set_visible(vis)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled
    if vis:
        legline.set_alpha(1.0)
    else:
        legline.set_alpha(0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

rawDescription: python matplotlib errorbar legend picking

description: Python matplotlib errorbar legend picking


code:
import matplotlib.pyplot as plt

def callback_left_button(event):
    ''' this function gets called if we hit the left button'''
    print('Left button pressed')

def callback_right_button(event):
    ''' this function gets called if we hit the left button'''
    print('Right button pressed')

fig = plt.figure()

toolbar_elements = fig.canvas.toolbar.children()
left_button = toolbar_elements[6]
right_button = toolbar_elements[8]

left_button.clicked.connect(callback_left_button)
right_button.clicked.connect(callback_right_button)

rawDescription: Matplotlib make several graphics and use the arrow to change - Python


code: Redis.rpush('key', *seq)

rawDescription: How to push a whole sequence to redis in Python

description: Push a whole sequence to redis in Python


code: cset = ax.contour(X, Y, Z, zdir='y', offset=tlen, colors='r')

rawDescription: pyplot static color colormap

description: Pyplot static color colormap


rawDescription: Exporting a list to a CSV/space separated and each sublist in its own column


code:
Point(0, 120.4) # with evaluate=True, the Float is made Rational
_.n()  # evaluate the coordinates
print('G0 X{0} Y{1}'.format(x.x.n(),x.y.n()))  # from your example

rawDescription: Sympy: Point evaluate=False after a point rotate


code:
import timeit
def calculate(alist):
    (1 + len(alist)) // 2

def allocate(alist):
    len(alist[::2])

testlist = range(10**5)
timeit.timeit('f(testlist)', 'from __main__ import testlist, calculate as f', number=10000)
timeit.timeit('f(testlist)', 'from __main__ import testlist, allocate as f', number=10000)

rawDescription: Does reusing a list slice to get length cost additional memory?


code:
def rgb_to_hsv(arr):
    """
    convert rgb values in a numpy array to hsv values
    input and output arrays should have shape (M,N,3)
    """
    arr = arr.astype('float')  # <- add this line
    out = np.zeros(arr.shape, dtype=np.float)
    arr_max = arr.max(-1)
    ipos = arr_max > 0
    delta = arr.ptp(-1)
    s = np.zeros_like(delta)
    s[ipos] = delta[ipos] / arr_max[ipos]
    ipos = delta > 0
    # red is max
    idx = (arr[:, :, 0] == arr_max) & ipos
    out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
    # green is max
    idx = (arr[:, :, 1] == arr_max) & ipos
    out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
    # blue is max
    idx = (arr[:, :, 2] == arr_max) & ipos
    out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
    out[:, :, 0] = (out[:, :, 0] / 6.0) % 1.0
    out[:, :, 1] = s
    out[:, :, 2] = arr_max
    return out

rawDescription: hsv_to_rgb isn't the inverse of rgb_to_hsv on matplotlib

description: Hsv_to_rgb isn't the inverse of rgb_to_hsv on matplotlib


code: MSG_TERMINATOR = "\0"

rawDescription: How to assign a binary zero character to a variable in python?

description: Assign a binary zero character to a variable in python


code:
from datetime import datetime
datetime.strptime('PT8H30M', 'PT%HH%MM').time()

rawDescription: Incomprehensible time format

description: Incomprehensible time format


code:
class AjaxPickerWidget(HiddenInput):
  search_text_suffix = "_picker_text"

  def __init__(self, **kwargs):
    super(AjaxPickerWidget, self).__init__(**kwargs)
    self.search_text = None

  def render(self, name, value, attrs=None):
    start = '
' % (name) + \
             '<input class="search_box" name="%s%s" ' % (name, self.search_text_suffix)+ \
             'type="text" value="%s" />' % (self.search_text or "")
    end = super(AjaxPickerWidget, self).render(name, value, attrs=attrs) + '
'
    return '%s%s' % (start, end)

class MyForm(Form):
  requestor = CharField(widget = AjaxPickerWidget())

  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    # find picker text in POST data and tell the corresponding widget about it
    for name in self.data:
      if name.endswith(AjaxPickerWidget.search_text_suffix):
        field_name = name.split(AjaxPickerWidget.search_text_suffix)[0]
        self.fields[field_name].widget.search_text = self.data[name]

rawDescription: Key/value pairs in custom widget

description: Key/value pairs in custom widget


code:
import numpy as np
a = np.array([1,2,3,4])
np.square(a)
np.cumsum(np.square(a))

rawDescription: Numpy 1d Array CumSquare of the values

description: Numpy 1d Array CumSquare of the values


code:
raw = urlopen(url).read()
original = raw.decode('utf-8')
replacement = original.replace('\u201c', '"').replace('\u201d', '"').replace('\u2019', "'")
soup = BeautifulSoup(replacement)  # Don't need fromEncoding if we're passing in Unicode

rawDescription: BeautifulSoup isn't recognizing UTF-8 characters even after using "fromEncoding=UTF-8"


code:
extra_dirs = ['directory/to/watch',]
extra_files = extra_dirs[:]
for extra_dir in extra_dirs:
    for dirname, dirs, files in os.walk(extra_dir):
        for filename in files:
            filename = path.join(dirname, filename)
            if path.isfile(filename):
                extra_files.append(filename)
app.run(extra_files=extra_files)

rawDescription: Reload Flask app when template file changes


code:
#!/usr/bin/python
import sys
import zlib
f = open(sys.argv[1], "rb")
g = open(sys.argv[2], "wb")
z = zlib.decompressobj()
while True:
    buf = z.unconsumed_tail
    if buf == "":
        buf = f.read(8192)
        if buf == "":
            break
    got = z.decompress(buf)
    if got == "":
        break
    g.write(got)

rawDescription: How to inflate a partial zlib file

description: Inflate a partial zlib file


rawDescription: AND operator while assignment

description: AND operator while assignment


code:
case([
    (extract('hour', Child.end_time) < extract('hour', Hours.start_time), extract('hour', Child.end_time))
], else_=extract('hour', Child.end_time) + 24)

rawDescription: Using a ternary operator in a sqlalchemy filter statement


code:
import sys
sys.path.add(r'< full path to>eclipse/plugins/org.python.pydev_4.5.4.201601292234/pysrc')
import pydevd
pydevd.settrace()

rawDescription: Attach the PyDev interactive debugger to Python code running in PyXLL


code:
import unittest
import testtools

class MyTester(unittest.TestCase):
    def test_foo(self):
        self.assertEqual(1+2, 2)
    def test_foo2(self):
        self.assertEqual(1+2, 3)

class TracingStreamResult(testtools.StreamResult):
    def status(self, *args, **kwargs):
        print('{0[test_id]}: {0[test_status]}'.format(kwargs))

suite = unittest.TestLoader().loadTestsFromTestCase(MyTester)
concurrent_suite = testtools.ConcurrentStreamTestSuite(lambda: ((case, None) for case in suite))
result = TracingStreamResult()
result.startTestRun()
concurrent_suite.run(result)
result.stopTestRun()

rawDescription: A simple, working example for testtools ConcurrentStreamTestSuite


code:
import random
l = range(10)
l
random.shuffle(l)
l

rawDescription: elegant way to disorder a list

description: Elegant way to disorder a list


code:
requests.post("https://rest.ably.io/channels/channelname/messages",
    auth=('some_AP.aYYMcQ', 'VmGHauKOqo-35Zxo'), # Equivalent of -u
    json={ "name": "greeting", "data": "example" }) # Equivalent of --data

rawDescription: What is the python requests equivalent of the following curl command


rawDescription: matplotlib legend background color

description: Matplotlib legend background color


code:
import os

sv_name="(whatever it's named)"
today=datetime.date.today()
survey=sv_name.replace(" ","_")
date=str(today).replace(" ","_")
namedate=survey+str(date)

[os.rename(f,str(namedate+"_"+f)) for f in os.listdir('.') if not f.startswith('.')]

rawDescription: renaming files in a directory + subdirectories in python

description: Renaming files in a directory + subdirectories in python


code: A[np.arange(len(A)), B.flat] = aNumber

rawDescription: NumPy: Need a function where: f(target array, array of indicies, some number) -> target array with indicies filled in with some number


code:
import dis
def while_1():
    while 1:
        pass
def while_true():
    while True:
        pass
dis.dis(while_1)
dis.dis(while_true)

rawDescription: What's the difference between "while 1" and "while True"?


code:
def getDefined(module):
    print([x for x in dir(module) if
        getattr(module.__dict__[x], '__module__','')==module.__name__
    ])

rawDescription: Python console - inspect classes or functions defined in a particular module


code:
Timestaken4={}

for key,value in zip(NumberPlates,Timestaken2):
    Timestaken4[key]=value

print(Timestaken4)

rawDescription: key and value in zip

description: Key and value in zip


code:
def pretty_print(CL_output):
    columns = len(CL_output)//200+2
    lines = ("".join(s.ljust(20) for s in CL_output[i:i+columns-1])+CL_output[i:i+columns][-1] for i in range(0, len(CL_output), columns))
    return "\n".join(lines)

rawDescription: Modify print function for multiple columns - Python


code:
def dbset(self, name, value):
    self.transaction.append((name, self.database.get(name)))
    self.database[name]=value

def rollback(self):
    # undo all changes
    while self.transaction:
        name, old_value = self.transaction.pop()
        self.database[name] = old_value

def commit(self):
    # everything went fine, drop undo information
    self.transaction = []

rawDescription: python database implementation

description: Python database implementation


code:
import networkx as nx
import csv
import matplotlib.pyplot as plt;

file_edges=csv.reader(open('test.csv','rb'));

G=nx.Graph();
users=[];
video=[];
for row in file_edges:
    G.add_node(row[0],type='user');
    users.append(row[0]);
    G.add_node(row[1],type='video');
    video.append(row[1]);
    G.add_edge(row[0],row[1]);

pos=nx.spring_layout(G) # positions for all nodes
fig=plt.figure(1)
ax=fig.add_subplot(111);
nx.draw_networkx_nodes(G,pos=pos,nodelist=users,with_labels=True,node_size=150,node_color='red',node_shape='s', width=1.75,linewidths=0.2,font_size=5,font_family='serif')
nx.draw_networkx_nodes(G,pos=pos,nodelist=video,with_labels=True,node_size=150,node_color='blue',node_shape='s', width=1.75,linewidths=0.2,font_size=5,font_family='serif')
nx.draw_networkx_edges(G, pos=pos, edgelist=G.edges(), width=3, edge_color='black');
nx.draw_networkx_labels(G,pos,nodelabels=G.nodes(),font_size=8,font_family='serif',font_color='white',font_weight='bold')
ax.legend(['users','video'],loc=2,numpoints=1,scatterpoints=1,prop={'size':10}) # Scatterpoints will show the node marker (say square) only once
plt.gcf()
plt.axis('off')
plt.show()

rawDescription: From 2 column csv to 2 color NetworkX graph


code: from top_settings import *

rawDescription: django-admin cannot find settings file?

description: Django-admin cannot find settings file


code:
def resizeDialog(self):
    self.animation = QtCore.QPropertyAnimation(self, "size")
    # self.animation.setDuration(1000) #Default 250ms
    if self.size().width()==200:
        self.animation.setEndValue(QtCore.QSize(600,300))
    else:
        self.animation.setEndValue(QtCore.QSize(200,100))
    self.animation.start()

rawDescription: PyQt: How to animate dialog size

description: PyQt: How to animate dialog size


code:
from collections import Counter

items = [
    [1, 2, 3],
    [1, 2],
    [3, 2, 1]
]

c = Counter(frozenset(x) for x in items)
print(c) # Counter({frozenset([1, 2, 3]): 2, frozenset([1, 2]): 1})

rawDescription: Python: Creating a dictionary with key as a set and value as its count


code:
p = subprocess.Popen(
    ["scanx", "--udp", host],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
out, err = p.communicate()

rawDescription: Python - Execute Process -> Block till it exits & Supress Output


code:
import collections

with open("access_log.log","r") as arxiu_de_log:
    clean_log = [
        (line.split(' ')+[None]*10)[10]
        for line in arxiu_de_log]

counter = collections.Counter(clean_log)

for count in counter.most_common(50):
    print(str(count[1])+"\t"+ str(count[0]))

rawDescription: Need to count them items from a list

description: Need to count them items from a list


code:
import itertools
n=3
list(itertools.product([True, False], repeat=n))

rawDescription: Create 2^n combinations Python

description: Create 2^n combinations Python


rawDescription: How to get resulting subprocess command string

description: Get resulting subprocess command string


code:
import decorator

class FooType(type):
    def __init__(cls,name,bases,clsdict):
        @decorator.decorator
        def modify_stub(func, *args,**kw):
            return func(*args,**kw)+' + new'
        setattr(cls,'stub',modify_stub(clsdict['stub']))
class Foo(object):
    __metaclass__=FooType
    def stub(self,a,b,c):
        return 'original'

foo=Foo()
help(foo.stub)
# Help on method stub in module __main__:

# stub(self, a, b, c) method of __main__.Foo instance

print(foo.stub(1,2,3))
# original + new

rawDescription: How do I dynamically create a function with the same signature as another function?

description: Dynamically create a function with the same signature as another function


code:
import PyQt4.QtGui as gui, PyQt4.QtWebKit as web, PyQt4.QtCore as core

class MyMainWindow(gui.QMainWindow):

    proccessFinished = core.pyqtSignal()

    def __init__(self, parent=None):
        super(MyMainWindow,self).__init__()

        self.wv = web.QWebView()
        self.setCentralWidget(self.wv)

        #pass this main window to javascrip
        self.wv.page().mainFrame().addToJavaScriptWindowObject("mw", self)

        self.wv.setHtml("""

It works

            <input type=button value=click onClick=mw.doIt()></input>

        """)

    @core.pyqtSlot()
    def doIt(self):
        print('running a long process...')
        print('of course it should be on a thread...')
        print('and the signal should be emmited from there...')
        self.proccessFinished.emit()

app = gui.QApplication([])

mw = MyMainWindow()
mw.show()

app.exec_()

rawDescription: How to emit signal to a PyQtWebkitView javascript from the Application?

description: Emit signal to a PyQtWebkitView javascript from the Application


code:
req1 = urllib2.Request(url1)
response = urllib2.urlopen(req1)
cookie = response.headers.get('Set-Cookie')

# Use the cookie is subsequent requests
req2 = urllib2.Request(url2)
req2.add_header('cookie', cookie)
response = urllib2.urlopen(req2)

rawDescription: Keeping a session in python while making HTTP requests


code:
super_awesome = {}
for row in rows:    # these are the rows from MySQLdb
    col1 = super_awesome.get(row['col1'], {})    # get col1 or an empty dict
    col2 = col1.get(row['col2'], [])             # get col2 or an empty list
    col2.append(row)                             # append row to (col1,col2)
    col1[row['col2']] = col2                     # put col2 into col1
    super_awesome[row['col1']] = col1            # put col1 into super_awesome

rawDescription: Divide list of dictionary into sub dictionary in Python


code:
class OtherTable(DeclarativeBase, DatetimeBase):
    __tablename__ = 'other_table'

    blah = Column(Integer, primary_key=True)
    other_column = Column(Text)

    __table_args__ = (PrimaryKeyConstraint("blah", "inserted"),)

rawDescription: Reorder composite primary key in sqlalchemy


code:
lsts = [[22,23,24,25,23,23,22],[22,30,31,32,30,30],[31]]
from collections import Counter
c = Counter(x for lst in lsts for x in set(lst))
[x for x,y in c.items() if y > 1]

rawDescription: How to compare list of lists (with N items) for items that are repeated, but only in different lists

description: Compare list of lists (with N items) for items that are repeated, but only in different lists


code:
from django.apps import AppConfig

class ExampleAppConfig(AppConfig):
    name = 'example'
    verbose_name = "Example Application"

    def ready(self):
        # To avoid putting the signals code in the __init__.py file or
        # models.py file, we import the signals module here.
        # https://docs.djangoproject.com/en/1.7/topics/signals/#connecting-receiver-functions
        from example import signals

rawDescription: Signals do not work after registering

description: Signals do not work after registering


code:
from tkFileDialog import askopenfilename

fname = askopenfilename()

rawDescription: Saving file python

description: Saving file python


rawDescription: SQLAlchemy: return existing object instead of creating a new on when calling constructor


code:
import string
help(string.split)
help("".split)

rawDescription: string.split(text) or text.split() what's the difference?

description: String.split(text) or text.split() what's the difference


rawDescription: Python 3.4 - Regular Expressions For Matching Innermost curly brackets


code:
lis = ['gold', 'diamond', 'wood']
points = dict.fromkeys(lis,0)     #create a dict from the list with initial value as 0
with open("abc") as f:            #use with context manger to open filees
    for line in f:
        key,val = line.split()   # no need of regex
        if key in points:        #if key is present in points then increment it's value
            points[key] += int(val)   #use points[key] syntax to access a dict

points

rawDescription: Dealing with data in python

description: Dealing with data in python


code:
filename = "NNa{0}b{1}.pk1".format(a,b)
pickle.dump(nn, open(filename,'wb'))

rawDescription: How to save to different pickles from same python program?

description: Save to different pickles from same python program


code: hex(0x19c6acc6 & 0xffff)

rawDescription: Convert int to 16 bit unsinged short

description: Convert int to 16 bit unsinged short


code: [max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]

rawDescription: Find maximum with limited length in a list


code:
def w_space (s):
    vowels = "aeiouAEIOU"
    string = ""
    for a in s:
        if a in vowels:
            string += " "
        else:
            string += a
    return string

rawDescription: How do I convert all the vowels within a string to white-spaces in python

description: Convert all the vowels within a string to white-spaces in python


code:
def clean(filename,cleanfile,value,position):
    for lines in filename.readlines():
        line = lines.strip().split(",")
        if line[position] != value:
            cleanfile.write(",".join(line) + "\n")

clean(open("readFrom.txt", "r"), open("writeTo.txt", "w"), "-999", 3)

rawDescription: How do I remove lines from a file and move them to another file?

description: Remove lines from a file and move them to another file


code:
jstr = json.loads(my_string)
if jstr.get('response'):
    jstr_response = jstr.get('response')[1][0].get('name')

rawDescription: How to extract value with simplejson?

description: Extract value with simplejson


rawDescription: Create a structure array from a list in Numpy with string and integers


code:
import re

fn_match = re.match(r"(?P<function>\w+)\s?\((?P<arg>(?P<args>\w+(,\s?)?)+)\)", s)
fn_dict = fn_match.groupdict()
del fn_dict['args']
fn_dict['arg'] = [arg.strip() for arg in fn_dict['arg'].split(',')]

rawDescription: Regular expression to match function name and all arguments in Python


code:
config = {'global':
            {'server.socket_host': '0.0.0.0'}
}
quickstart(HelloWorld(), config=config)

rawDescription: Can't connect to local web server from Android device


code:
xx = np.array([-0.51, 51.2])
yy = np.array([0.33, 51.6])
means = [xx.mean(), yy.mean()]
stds = [xx.std() / 3, yy.std() / 3]
corr = 0.8         # correlation
covs = [[stds[0]**2          , stds[0]*stds[1]*corr],
        [stds[0]*stds[1]*corr,           stds[1]**2]]

m = np.random.multivariate_normal(means, covs, 1000).T
scatter(m[0], m[1])

rawDescription: Generating random correlated x and y points using Numpy


code:
a = 1234567.89
from string import maketrans
trans = maketrans('.,', ',.')
format(a, ',.2f').translate(trans)

rawDescription: Using DOT as thousand separator in python2.7


code:
import collections

def SimpleMode(arr):
    if not arr:
        return -1
    counts = collections.Counter(arr)
    return max(counts, key=lambda k: (counts[k], -arr.index(k)))

rawDescription: Why is my program faster than the one using a python built in function?


code:
f = open('put_your_text_file.csv', 'r')
num = sys.argv[2]
for i, line in enumerate(f.readlines()):
    if i == num:
        print(line)

rawDescription: Printing a Chosen Line from a File

description: Printing a Chosen Line from a File


rawDescription: Python: Searching/reading binary data

description: Python: Searching/reading binary data


code:
from __future__ import division  # this is important, otherwise 1/2 will be 0
import matplotlib.pyplot
from numpy import arange
from numpy import meshgrid
from numpy import sqrt
from numpy import real

delta = 0.01
xrange = arange(-7.0, 7.0, delta)
yrange = arange(-3.0, 3.0, delta)
x, y = meshgrid(xrange,yrange)

F1 = (((x/7) ** 2) * sqrt(abs(abs(x) - 3)/(abs(x) - 3)) + ((y / 3) ** 2) * sqrt(abs(y + (3 * sqrt(33)) / 7)/(y + (3 * sqrt(33)) / 7)) - 1)
F2 = (abs(x/2) - ((3 * sqrt(33) - 7)/112) * x**2 - 3 + sqrt(1 - (abs(abs(x) - 2) - 1) ** 2 ) - y)
F3 = (9 * sqrt(abs((abs(x) - 1) * (abs(x) - 3/4))/((1 - abs(x)) * (abs(x) - 3/4))) - 8 * abs(x) - y)
F4 = (3 * abs(x) + 0.75 * sqrt(abs((abs(x) - 3/4) * (abs(x) - 1/2))/((3/4 - abs(x)) * (abs(x) - 1/2))) - y)
F5 = ((9/4) * sqrt(abs((x - 1/2) * (x + 1/2))/((1/2 - x) * (1/2 + x))) - y)
F6 = ((6 * sqrt(10)) / 7 + (3/2 - abs(x)/2) * sqrt(abs(abs(x) - 1)/(abs(x) - 1)) - ((6 * sqrt(10))/ 14) * sqrt(4 - (abs(x) - 1) ** 2 ) - y)

for f in [F1,F2,F3,F4,F5,F6]:
    matplotlib.pyplot.contour(x, y, f, [0])
matplotlib.pyplot.show()

rawDescription: Matplotlib contour isn't working

description: Matplotlib contour isn't working


code:
UserNumbers=input("Enter number sequence separated by spaces: ")
nums = [int(i) for i in UserNumbers.split()]

rawDescription: How do I gather user numerical input into a list in Python?

description: Gather user numerical input into a list in Python


code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('tek')
stdin, stdout, stderr = ssh.exec_command('python --version')
stdin.flush()
data = stdout.readlines()
data
data = stderr.readlines()
data

rawDescription: Get Python Version from Remote Host with paramiko


code:
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

rawDescription: ExtJS, Flask and AJAX: cross-domain request


code:
prevLine = ""
for line in file:
    # do some work here
    prevLine = line

rawDescription: Read previous line in a file python

description: Read previous line in a file python


code:
total_inheritance = 1587654
administrator_percent = 0.025
parents = 2
children = 3
relatives = 10

# Lets subtract out the administrator's portion
initial_admin_amount = administrator_percent * total_inheritance
total_inheritance -= initial_admin_amount

# calculate portions
portions = relatives + 100 * children + 200 * parents
amount_per_portion = total_inheritance / portions

relatives_portion = amount_per_portion // 1
children_portion = 100 * relatives_portion // 1
parents_portion = 2 * children_portion // 1

# add the initial  amount back in
admin_portion = total_inheritance + initial_admin_amount
# subtract out all the handouts
admin_portion -= relatives * relatives_portion
admin_portion -= children * children_portion
admin_portion -= parents * parents_portion

print("Relatives get: ${} each".format(relatives_portion))
print("Children get: ${} each".format(children_portion))
print("Parents get: ${} each".format(parents_portion))
print("Administrator gets: ${} each".format(admin_portion))

rawDescription: Calculating administrator's portion

description: Calculating administrator's portion


code:
a = [(5, 3), (9, 0), (4, 6), (2, 2), (0, 0)]

from math import sqrt

def function(a):
    distances = []
    def compute(fp, sp):
        return sqrt((fp[0]-sp[0])**2 + (fp[1] - sp[1])**2)

    for p in a:
        b = a[:]
        b.remove(p)
        distances.append(compute(p, min(b, key=lambda x: compute(x, p))))

    return min(distances)

print(function(a))

rawDescription: PYTHON - Distance between closest pair in a list


code:
from inspect import currentframe

def ipsh():
    frame = currentframe().f_back
    msg = 'Stopped at {0.f_code.co_filename} and line {0.f_lineno}'.format(frame)
    ipshell(msg,stack_depth=2) # Go back one level!

rawDescription: Using IPython as an effective debugger

description: Using IPython as an effective debugger


code:
from PIL import Image
from django.core.files.base import ContentFile
import StringIO

class Post(models.Model):

    #...

    def save(self):

        thumb = Image.open(self.photo.file)
        thumb_io = StringIO.StringIO()
        thumb.save(thumb_io,format = thumb.format)
        self.thumbnail.save(self.photo.name, ContentFile(thumb_io.getvalue()), save=False)
        super(Post, self).save()

rawDescription: Auto-filling other ImageFields based on the first one


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

def polyfit2d(data, order=3):
    x = data.pv_ratio
    y = data.battery_ratio
    z = data.value

    ncols = (order + 1)**2
    G = np.zeros((x.size, ncols))

    ij = itertools.product(range(order+1), range(order+1))
    for k, (i,j) in enumerate(ij):
        G[:,k] = x**i * y**j
    m, _, _, _ = np.linalg.lstsq(G, z)

    y['fit'] = polyval2d(x, y, m)
    return m, y_fit

def polyval2d(x, y, m):
    order = int(np.sqrt(len(m))) - 1
    ij = itertools.product(range(order+1), range(order+1))
    z = np.zeros_like(x)
    for a, (i,j) in zip(m, ij):
        z += a * x**i * y**j
    return z

m, y_fit = polyfit2d(df, 7)

rawDescription: Scipy - How can I improve this curve fitting - finding the right function


code:
import fcntl, os, sys

# make stdin a non-blocking file
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

def enter_pressed():
    data = sys.stdin.read(1)
    return bool(data)

i = 0
while True:
    i += 1
    if enter_pressed():
        print(i)

rawDescription: On enter action?

description: On enter action


code:
my_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)
my_thread.setDaemon(True)
my_thread.start()

rawDescription: Translate `thread.start_new_thread(...)` to the new threading API


code:
# prepare data
datad = np.random.rand(2000000,2)-[0.5,  0.5] # Double
data = datad.astype(np.float32)
N, dim = data.shape[0], data.shape[1]
sigma = 0.04
i = 2
pos = np.array(data[i,:]) # float
posd = np.array(datad[i,:]) #double
dt = 0.005
resistant = 0.9995

kernelsource = """
__kernel void forceFinder(
    const int N,
    const int dim,
    const float sigma,
    __global float* datacl,
    __constant float* poscl,
    __global float* res)
{
    int i = get_global_id(0); // Global id;
    float f_sum ;
    int k;
    float sigma2 = sigma * sigma;
    if (i < N) {
        f_sum = 0.0;
        float t[2]; //INCREASE TO THE MAX "DIM" POSSIBLE
        for (k = 0; k < dim; k++){
            t = poscl[k] - datacl[i * dim + k];
        }
        for (k = 0; k < dim; k++){
            f_sum +=  pown(t,2);
        }
        for (k = 0; k < dim; k++){
            res[i * dim + k] = (-t) * exp(-f_sum/sigma2)/sigma2;
        }
    }
}
"""

# Setup PyOpenCl
platform = cl.get_platforms()[0]
device = platform.get_devices()[0] # Get the GPU ID
ctx = cl.Context([device])   # Tell CL to use GPU
queue = cl.CommandQueue(ctx) # Create a command queue for the target device.
program = cl.Program(ctx, kernelsource).build()
size = N * dim
datacl = data.reshape((size,))
rescl = np.empty(size).astype(np.float32)
rescl.fill(0.0)
datacl_buf = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf = datacl)
pos_buf = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf = pos)
rescl_buf = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, rescl.nbytes)
forceFinder = program.forceFinder
forceFinder.set_scalar_arg_dtypes([np.uint32, np.uint32, np.float32, None, None, None])
globalrange = (N, 1)
localrange = None

# Run CL
t0 = time.time()
forceFinder(queue, globalrange, localrange, N, dim, sigma, datacl_buf, \
            pos_buf, rescl_buf)
cl.enqueue_copy(queue, rescl, rescl_buf)
queue.finish()
result = rescl.reshape((N,dim))
t1 = time.time()
print (t1-t0)

rawDescription: OpenCL running slower than Cython (on CPU)


code:
dct = anagrams_from_list(process_file(filename))
for key, wordlist in dct.items():
  content = {}
  for key, wordlist in dct.iteritems():
    if not key in content:
      content[key] = wordlist
    else:
      content[key].extend(wordlist)

for k, v in content.iteritems():
  db[k] = v

rawDescription: Is shelve really slow and taking a lot of memory or am I doing something wrong?


code:
def nested_dict(tuple, value=10):
    if len(tuple) is 1:
        return { tuple[0] : value }
    return { tuple[0] : nested_dict(tuple[1:], value=value) }

rawDescription: Python: Nested dictionary with arbitrary number of levels


code:
from email.utils import make_msgid
make_msgid()

rawDescription: How do I create a message-id for email in python?

description: Create a message-id for email in python


code:
user = get_user()
if user is None:
    return None

rawDescription: python - pythonic way to check assignment and exit if None

description: Python - pythonic way to check assignment and exit if None


code:
mystr = 'foo7bar'
mystr[:mystr.index('7')]

rawDescription: Python strip a string at a certain spot

description: Python strip a string at a certain spot


code:
cache = []
for line in searchfile:
    cache.append(line)
    if "hypothetical" in cache[line].lower():
        print(cache[-9])

rawDescription: Parsing for keyword and finding related line in array


code: x = sorted(x, key = lambda x: x["date"])

rawDescription: Sort list of dictionaries by date in Python 3.4


code:
def initUI(self):

    topHBoxLayout = QHBoxLayout(self)
    topHBoxLayout.setContentsMargins(0,0,0,0)

    sstObjWrapper = QSplitter(Qt.Horizontal)
    sstObjWrapper.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    sstFrame  = QFrame()
    sstFrame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    sstFrame.setMinimumSize(QSize(100, 100))
    self.colorFrame(sstFrame, 'red')

    # --- sst frame ---

    objectivesFrame = QFrame()
    objectivesFrame.setMinimumSize(QSize(100, 100))
    objectivesFrame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    self.colorFrame(objectivesFrame, 'green')

    sstObjWrapper.addWidget(sstFrame)
    sstObjWrapper.addWidget(objectivesFrame)

    tmp1  = QFrame(self)
    tmp1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    tmp1.setMinimumSize(QSize(200, 200))
    self.colorFrame(tmp1, 'purple')

    tmp2  = QFrame(self)
    tmp2.setMinimumSize(QSize(100, 100))
    tmp2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
    self.colorFrame(tmp2, 'blue')

    plotConsoleSplitter = QSplitter(Qt.Vertical)
    plotConsoleSplitter.addWidget(tmp1)
    plotConsoleSplitter.addWidget(tmp2)
    plotConsoleSplitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    objPlotSplitter = QSplitter(Qt.Horizontal)
    objPlotSplitter.addWidget(sstObjWrapper)
    objPlotSplitter.addWidget(plotConsoleSplitter)

    objPlotSplitter.setStretchFactor ( 0, 0 )
    objPlotSplitter.setStretchFactor ( 1, 1 )

    topHBoxLayout.addWidget(objPlotSplitter)

    self.setLayout(topHBoxLayout)
    self.setGeometry(300, 300, 300, 200)
    self.setWindowTitle('')
    self.show()

rawDescription: PyQt5 resize only one child widget when window is resized


code:
class A():
    def __init__(self):
        self.x = 0

class B():
    def __init__(self):
        self.x = 1

class Container():
    def __init__(self,objects):
        self.x = [obj.x for obj in objects]

a = A()
b = B()
c = Container([a,b])

c.x

[0,1]

rawDescription: Create multiple classes or multiple objects in Python?


code:
import re

with open('input') as fin:
    long_string = re.sub(r'\W', '', fin.read())
# HelloWorldMynameisSamIam12yearsoldandaboyIlikePizza

rawDescription: Python 3: Store the contents of a file into one big string


code: itertools.combinations(iterable, r)

rawDescription: Python code to pick out all possible combinations from a list?


code:
timesteps   = ncfile.variables['time']
dates_to_skip = set(['June 23th', 'May 28th', 'April 1st'])
filtered_timesteps = filter(lambda t: t not in dates_to_skip, timesteps)

rawDescription: python - how to check whether some given date exists in netcdf file

description: Python - how to check whether some given date exists in netcdf file


code:
import regex
m = regex.findall('(ATCT){e<=1}', 'ATCGATCGGCATGCAGTGCAGAAGTGACGAT')
print(m)

rawDescription: Fuzzy regex matching with python returns empty list


code:
import hashlib

sha256 = hashlib.sha256()
alreadyseen = set()
with open("sample.txt") as file:
    for line in file:
        pass # do something
        key = line if len(line) < 32 else sha256(line)
        if key not in alreadyseen:
            alreadyseen.add(key)
            print(line)

rawDescription: Optimise the removal of duplicate lines from a large file


code:
dir_path = os.path.join(self.feed, self.address)  # will return 'feed/address'
os.makedirs(dir_path)                             # create directory [current_path]/feed/address
output = open(os.path.join(dir_path, file_name), 'wb')

rawDescription: Writing to a new directory in Python without changing directory


code:
def chunks(file, delim='\n'):
    buf = bytearray(),
    while True:
        c = self.read(1)
        if c == '': return
        buf += c
        if c == delim:
            yield str(buf)
            buf = bytearray()

rawDescription: Change newline character .readline() seeks


code:
def get_right(self):
    return self.x + self.width
right = AliasProperty(get_right, bind=['x', 'width'])

rawDescription: What happens when I bind to an AliasProperty?


code: my_set = {'foo', 'bar', 'baz'}

rawDescription: Using Curly Braces to Initialize Set

description: Using Curly Braces to Initialize Set


code:
import dpkt
from dpkt.ip import IP
from dpkt.ethernet import Ethernet
import struct
import socket
import csv

def ip_to_str(address):
    return socket.inet_ntoa(address)

f = open('sample.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
c = csv.writer(open("a.csv", "wb"))  # <=== moved here
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        continue

    ip = eth.data
    do_not_fragment = bool(dpkt.ip.IP_DF)
    more_fragments = bool(dpkt.ip.IP_MF)
    fragment_offset = bool(dpkt.ip.IP_OFFMASK)

    Source = "%s" % ip_to_str(ip.src)
    Destination = "%s" % ip_to_str(ip.dst)
    Length = "%d" % (ip.len)
    TTL = "%d" % (ip.ttl)
    OFF = ip.off
    TOS = ip.tos
    Protocol = ip.p
    data = (Source, Destination, Length, TTL, TOS, OFF, Protocol)
    c.writerow(data)

rawDescription: print output in csv file python

description: Print output in csv file python


code:
from PySide import QtGui, QtCore
import time

class MyWidget(QtGui.QWidget):
  def __init__(self):
    QtGui.QWidget.__init__(self)
    layout = QtGui.QVBoxLayout(self)
    self.label = QtGui.QLabel()
    self.button_start = QtGui.QPushButton("Start")
    self.button_stop = QtGui.QPushButton("Stop")
    self.button_stop.setEnabled(False)
    self.button_pause = QtGui.QPushButton("Pause")
    self.button_pause.setEnabled(False)
    layout.addWidget(self.label)
    layout.addWidget(self.button_start)
    layout.addWidget(self.button_stop)
    layout.addWidget(self.button_pause)
    self.button_start.clicked.connect(self.processing)
    self.button_pause.clicked.connect(self.pause)
    self.button_stop.clicked.connect(self.stop)

  def processing(self):
    self.button_start.setEnabled(False)
    self.button_stop.setEnabled(True)
    self.button_pause.setEnabled(True)
    self.stop_requested = False
    self.paused = False
    i = 0
    while not self.stop_requested:
      QtGui.QApplication.processEvents()
      if self.paused:
        time.sleep(0.1)
      else:
        i += 1
        self.label.setText(unicode(i))
    self.button_start.setEnabled(True)
    self.button_stop.setEnabled(False)
    self.button_pause.setEnabled(False)

  def pause(self):
    self.paused = not self.paused

  def stop(self):
    self.stop_requested = True

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    widget = MyWidget()
    widget.show()
    sys.exit(app.exec_())

rawDescription: when and how to use PySide QEventLoop

description: When and how to use PySide QEventLoop


code:
class Angle(int):
  def __new__(cls, val):
    val %= 360
    inst = super(Angle, cls).__new__(cls, val)
    return inst

rawDescription: Seemingly trivial issue calling int's __init__ in python


code: list("".join(l) for l in itertools.product('ABCDEF', repeat=4))

rawDescription: Generating a list of all strings possible using 6 characters


code:
import fileinput
import sys

for line in fileinput.input(filename, inplace=True):
    if line.startswith('char id='):
        _, id_, rest = line.split(None, 2)
        id_ = int(id_.split('=')[1])
        id_ += 1  # adjust as needed
        line = 'char id={} {}'.format(id_, rest)

    sys.stdout.write(line)

rawDescription: Modify file using python

description: Modify file using python