code:
x = y = []
x is y       # Both point to the same object
x.append(1)  # list.extend modifies a list in-place
x,y          # both references to [] can see the modification
x = y = 1
x is y      #both points to the same object
x+=1        # only x gets modified, it now points to a new object 2
x,y         # y still points to the same object 1

rawDescription: Initializing 2D lists in Python: How to make deep copies of each row?


code:
import sys
import time

# Definitions
ROOT_SYMBOLIC_OBJECT = ":_KMainView"

# Object finding functions
def findSymbolic(symbolicName):
    # Note: give Squish symbolic name like ":Foobar"
    try:
        obj = findObject(symbolicName)
    except LookupError:
        sys.exc_clear()
        test.log("FAIL: Root object not found: " + symbolicName)
        sys.exit()

    return obj

def findRoot():
    return findSymbolic(ROOT_SYMBOLIC_OBJECT)

def findFlat(fromElement, findId, occurence, stopOnFail, verbose):
    start = time.time()
    result = None
    found = 0

    if fromElement and hasattr(fromElement, 'children'):
        children = object.children(fromElement)
        for child in children:
            if hasattr(child, 'id') and child.id == findId:
                found += 1
                if found == occurence:
                    result = child
                    break

    if result == None and stopOnFail:
        test.log("FAIL: findFlat: " + findId + " not found")
        sys.exit()

    if verbose:
        printElapsed("findFlat", findId, start)

    return result

def findRecursive(fromElement, findId, occurence):
    return findRecursiveWithOptions(fromElement, findId, occurence, True, False, True)

def findRecursiveWithOptions(fromElement, findId, occurence, stopOnFail, verbose, skipUnnamed):
    start = time.time()
    found = 0
    depth = -1

    obj, found, depth = objIter(fromElement, findId, occurence, verbose, skipUnnamed, found, depth)

    if found == occurence:
        printElapsed("findRecursive ok", findId, start)
        return obj

    printElapsed("findRecursive not found", findId, start)
    if stopOnFail:
        test.log("FAIL: findRecursive:" + findId + " not found.")
        sys.exit()

    return None

def objIter(fromElement, findId, occurence, verbose, skipUnnamed, found, depth):
    depth += 1

    if verbose:
        printObjIter(fromElement, depth)

    children = object.children(fromElement)
    for child in children:
        if hasattr(child, 'id'):
            if child.id == findId:
                found += 1
                if found == occurence:
                    return child, found, depth
        elif skipUnnamed:
            continue

        obj, found, depth = objIter(child, findId, occurence, verbose, skipUnnamed, found, depth)
        depth = depth - 1
        if found == occurence:
            return obj, found, depth

    return None, found, depth

def findRecursiveList(fromElement, findId):
    return findRecursiveListWithOptions(fromElement, findId, True, False, True)

def findRecursiveListWithOptions(fromElement, findId, stopOnFail, verbose, skipUnnamed):
    start = time.time()
    objList = []
    depth = -1

    objList, depth = objListIter(fromElement, findId, verbose, skipUnnamed, objList, depth)

    printElapsed("findRecursiveList", findId, start)
    return objList

def objListIter(fromElement, findId, verbose, skipUnnamed, objList, depth):
    depth += 1

    if verbose:
        printObjIter(fromElement, depth)

    children = object.children(fromElement)
    for child in children:
        if hasattr(child, 'id'):
            if child.id == findId:
                objList.append(child)
        elif skipUnnamed:
            continue

        objList, depth = objListIter(child, findId, verbose, skipUnnamed, objList, depth)
        depth = depth - 1

    return objList, depth

# Utilities
def printElapsed(functionName, objectId, start):
    elapsed = time.time() - start
    test.log(functionName + " - " + objectId + " in " + str(elapsed) + "s.")

def printObjIter(element, depth):
    dashes = "-" * depth

    if hasattr(element, 'id'):
        test.log(dashes + " " + str(element.id))
    else:
        test.log(dashes + " [unnamed]")

rawDescription: Get QML element in Squish by id or objectName using findObject() or waitForObject() without object map


code:
from scrapy.spider import Spider
from scrapy.selector import Selector
from Google.items import GoogleItem
import re
class DmozSpider(Spider):
    name = "google"
    allowed_domains = ["google.com"]
    start_urls = [
    "https://www.google.com/about/careers/search#!t=jo&jid=34154&",
    ]

    def parse(self, response):
        selector = Selector(response)
        item=GoogleItem()
        item['Description'] = selector.xpath("string(//div[@itemprop='description'])").extract()
        item['CompanyName'] = "Google"
        item ['JobDetailUrl'] = response.url
        item['Title'] = selector.xpath("//a[@class='heading detail-title']/span[@itemprop='name title']/text()").extract()
        item['City'] = selector.xpath("//a[@class='source sr-filter']/span[@itemprop='name']/text()").extract()
        item['State'] = selector.xpath("//a[@class='source sr-filter']/span[@itemprop='name']/text()").extract()
        item['Jobtype'] = selector.xpath(".//*[@id='75015001']/div[2]/div[7]/div[2]/div[5]/div[2]/text()").extract()

        yield item

rawDescription: How to write rejax and xpath for the below link?

description: Write rejax and xpath for the below link


rawDescription: How many times is a particular row present?


code: print(','.join(y for y in re.split("_|[^\w]", x) if y))

rawDescription: Cleaning away symbols/whitespace efficiently


code:
S = emcee.EnsembleSampler(Nwalkers, Ndim, lnprob_trunc_norm, args = (mean, bounds, C))

pos, prob, state = S.run_mcmc(pos, Nsteps)

rawDescription: Truncated multivariate normal in SciPy?

description: Truncated multivariate normal in SciPy


code:
state = State.objects.create(name='Some state', external_id=5)
state.fetch_cities_from_network()

rawDescription: how can i save data, retrieved from a url into my database

description: Save data, retrieved from a url into my database


code:
import csv
from operator import *
with open('foo.csv') as f: people = list(csv.DictReader(f))
[p['age'] for p in sorted(people, key=itemgetter('first')) if p['last'] == 'Smith']

rawDescription: Are there a tools that can help to treat files as tables in a database?


code:
per = 5
divbb = 69.46
divgr = 0.0527
tbondr = 0.0176
sp = 1430

total=0
pv=0

i = 1
while(abs(sp-total)) > 1:
    erp = i/10000.
    a = divbb
    b = divgr
    pv = 0
    temppv = 0
    print (sp-total, erp)
    for j in range(0, per):
        a=a * (1+b)
        temppv = a / pow((1+erp),j)
        pv=pv+temppv
    lastterm=(a*1+tbondr)/((erp-tbondr)*pow(1+erp,per))
    total=(pv+lastterm)
    i += 1

rawDescription: Beginner Python: Where to "while"?

description: Beginner Python: Where to "while"


rawDescription: Edit an element in a list - python

description: Edit an element in a list - python


code:
from random import sample

numbers = range(1,50) # 1-49

def generate_draw(balls=6,population=numbers):
    return sorted(sample(population,k=balls))

rawDescription: How can I loop a lottery number generator?

description: Loop a lottery number generator


code:
from twisted.internet.task import react
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import serverFromString

class ReadBytes(Protocol):
    def connectionMade(self):
        print("Incoming connection from {}".format(self.transport.getPeer()))

    def dataReceived(self, data):
        print("Received {}".format(data))

def main(reactor, description):
    endpoint = serverFromString(reactor, description)
    endpoint.listen(Factory.forProtocol(ReadBytes))
    return Deferred()

if __name__ == '__main__':
    react(main, [b"tcp:interface=127.0.0.1:port=4444"])

rawDescription: Cant receive Data using Asyncore Python

description: Cant receive Data using Asyncore Python


code:
from itertools import chain
modified_list=list(chain(*c))

rawDescription: Convert a binary to an array with each binary number


code: A

rawDescription: Convert triplets to matrix/dataframe in python


code:
#infinite loop to keep page open
while(True):

    #wait for event (from button)
    event = droid.eventWait().result

    #check for desired event  (close)
    if (event['name'] == 'close'):

        #exit
        sys.exit()

rawDescription: How can I close an opened HTML document in Android application?

description: Close an opened HTML document in Android application


code:
@login_required
def test(request):
    a = User.objects.filter(pk=request.user.id).select_related('profile').get()
    return render_to_response('test.html', {'a':a,})

rawDescription: How to select users based on their profile

description: Select users based on their profile


code: login()

rawDescription: Creating a dictionary to store pass and user


code:
numList = []

while len(numList) <= 1000:
    numList.append(1)

# the numList is already a thousand elements long, so the while loop
# body is NEVER executed.
while len(numList) <= 1000:
    numList.append(0)

rawDescription: Create a loop to change ints in a list to another int?


code:
question_list = Question.objects.distinct() \
                        .filter(category=category, is_approved=1,
                                answer__is_approved=1) \
                        .prefetch_related('answer_set')[:10]

rawDescription: How do we filter results from two tables using prefetch_related function in Django


code:
def update_logic():
    if player.lives < 5:
        return False
    # these are just examples, perhaps not valid in your game
    player.xdirection = 0
    player.ydirection = 0
    player.speed = 0
    player.hitting = False
    if player.damage_received_timer > 0:
        player.damage_received_timer -= 1
    if right_key_pressed:
        player.xdirection = 1
    if left_key_pressed:
        player.xdirection = -1
    if up_key_pressed:
        player.ydirection = -1
    if down_key_pressed:
        player.ydirection = +1
    if player.ydirection or player.xdirection:
        player.speed = 20
    if space_key_pressed:
        player.hitting = True
    # bla bla bla more logic
    return True

rawDescription: How do you create a new thread in python?

description: Create a new thread in python


code:
from collections import defaultdict
import io
import re
import pandas as pd
import pprint as pp

fn = r'D:\temp\.data\36671176.data'

def parse_header(filename):
    """
    parses useful (check `header_flt` variable) information from the header
           and saves it into `defaultdict`,
    generates `skiprow` list for `pd.read_csv()`,
    breaks after parsing the header, so the data block will NOT be read

    returns: parsed info as defaultdict obj, skiprows list
    """
    # useful header information that will be saved into defaultdict
    header_flt = r'TIMESTAMP|TIMEZONE|NAME|MODEL|SERIAL|FIRMWARE_VERSION|Trace TIMESTAMP:'

    with open(fn) as f:
        d = defaultdict(list)
        i = 0
        skiprows = []
        for line in f:
            line = line.strip()
            if line.startswith('!'):
                skiprows.append(i)
                # parse: `key` (first RegEx group)
                #    and `value` (second RegEx group)
                m = re.search(r'!\s+(' + header_flt + ')\s+(.*)\s*', line)
                if m:
                    # print(m.group(1), '->', m.group(2))
                    # save parsed `key` and `value` into defaultdict
                    d[m.group(1)] = m.group(2)
            elif line.startswith('BEGIN'):
                skiprows.append(i)
            else:
                # stop loop if line doesn't start with: '!' or 'BEGIN'
                break
            i += 1
        return d, skiprows

info, skiprows = parse_header(fn)

# parses data block, the header part will be skipped
# NOTE: `comment='E'` - will skip the footer row: "END"
df = pd.read_csv(fn, header=None, usecols=[0,1], names=['freq', 'dBm'],
                 skiprows=skiprows, skipinitialspace=True, comment='E',
                 error_bad_lines=False)

print(df)
print('-' * 60)
pp.pprint(info)

rawDescription: reading a complicated CSV file with python

description: Reading a complicated CSV file with python


code:
_location = "SERVER"

Records = Table(_location, metadata,
    Column('device', String(17), primary_key=True),
    Column('data1', Text()),
    Column('location', Text()),
    Column('data2', Text()),
    extend_existing=True
)
Base.metadata.create_all(bind=engine, checkfirst=True)

rawDescription: Python SQLAlchemy create dymanic unknown tables


code:
def g():
    yield [1,2,3]
    yield 1
    yield 2
    yield 3

gen = g()
gen.next()
gen.next()
gen.next()
gen.next()
gen.next()

rawDescription: Why yield returns an iterator?

description: Why yield returns an iterator


code:
import wx

class MyFrame(wx.Frame):
    """Frame class."""

    def  __init__(self, parent=None, id=-1,
                  pos=wx.DefaultPosition,
                  title='Hello, Tsukuyo!', size=(200,100)):
        """Create a Frame instanc."""
        wx.Frame.__init__(self, parent, id, title, pos, size)

        try:
            with open('Tsukuyo.jpg') as fh:
                data = fh.read()
        except IOError:
            dlg = wx.MessageDialog(self, "Can not open image 'Tsukuyo.jpg'.",
                                   "Error", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()

            self.Close()

class MyApp(wx.App):
    """Application class."""

    def OnInit(self):
        frame = MyFrame()
        frame.Show()
        return True

def main():
    app = MyApp()

if __name__ == "__main__":
    main()

rawDescription: wxPython: program quits but window remaines not responding after calling sys.exit

description: WxPython: program quits but window remaines not responding after calling sys.exit


code:
MvT101group.columns = MvT101group.columns.map(lambda x: str(x) + '_101')
MvT102group.columns = MvT102group.columns.map(lambda x: str(x) + '_102')

rawDescription: How should I subtract two dataframes and in Pandas and diplay the required output?


code:
d = OrderedDict((x,x) for x in reversed(range(10)) )
d
regular = dict((x,x) for x in reversed(range(10)))
regular

rawDescription: pythonic way for FIFO order in Dictionary

description: Pythonic way for FIFO order in Dictionary


code:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('1','2')
nx.draw(G)
plt.show()

rawDescription: open .dot formatted graph from python

description: Open .dot formatted graph from python


code:
import urllib
import threading

class Downloader:

    def __init__(self):
        self.stop_down = False
        self.thread = None

    def download(self, url, destination):
        self.thread = threading.Thread(target=self.__down, args=(url, destination))
        self.thread.start()

    def __down(self, url, dest):
        _continue = True
        handler = urllib.urlopen(url)
        self.fp = open(dest, "w")
        while not self.stop_down and _continue:
            data = handler.read(4096)
            self.fp.write(data)
            _continue = data
        handler.close()
        self.fp.close()

    def cancel(self):
        self.stop_down = True

rawDescription: downloading a file in python and cancel

description: Downloading a file in python and cancel


code:
from datetime import datetime
import pytz
local_date = datetime.now(pytz.timezone('US/Central'))  # use datetime here
local_date.date()                                       # now call date method

rawDescription: Change Timezone for Date object Python

description: Change Timezone for Date object Python


code:
teams = {'BOU' : 4, 'WAT' : 4, 'LEI' : 4, 'NOR' : 4, 'AVL' : 3, 'SUN' : 3, 'NEW' : 3, 'WBA' : 3, 'STK' : 2, 'SWA' : 2, 'EVE': 2, 'SOU' : 2, 'CPL' : 2, 'TOT': 2, 'ARS' : 1, 'CHE' : 1, 'MUN' : 1, 'LIV' : 1, 'MCI' : 1}

def read_fix(filename):
    """Reads a named fixtures-file and returns a list containing pairs of team names [["BOU","AVL"],["ARS","WHU"],...]"""
    matches=[] #create an empty list, this is part of a so called accumulator pattern
    with open(filename, "r") as fd:   #The with statement guarantees that the opened file is closed when the block ends.
        for line in fd:
            line = line.strip().split("#")  #You can chain multiple method-calls on one line, this does both white-space-stripping and splitting on #.
            if len(line)==2:   #Filter out only lines that contain a game (or well exactly one #, possibly dangerous)
                teams=line[1]  #Remember that python indexes lists and strings from 0
                matches.append([teams[0:3],teams[3:6]])  #split the part after the # into two parts, 3 letters each and add the pair to the list (this is the accumulation step of the accumulator-pattern)
    return matches

rawDescription: Data parsing, the pythonic way

description: Data parsing, the pythonic way


code:
association_table = Table('association', Base.metadata,
    Column('students_id', Integer, ForeignKey('student_ids.id')),
    Column('marks_id', Integer, ForeignKey('marks.id'))
)

class Marks(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'marks'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    mark = Column(Integer, nullable=False, unique=False)
    subject_fk = Column(Integer, ForeignKey('subjects.id'))
    subject = relationship('Subjects', foreign_keys=[subject_fk],uselist=False, backref='marks', innerjoin=False, post_update=False)

class Subjects(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'subjects'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    subject = Column(String(10, convert_unicode=True), nullable=False, unique=True)

class StudentIds(Base):
   __table_args__ = {'extend_existing': True}
   __tablename__ = 'student_ids'
   id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
   student_id = Column(String(50, convert_unicode=True), nullable=False,unique=False)

   junctionid = relationship("Junction", cascade='save-update',
                                 backref='student_ids', lazy='select', post_update=True)
   marks = relationship("Marks", secondary=association_table)

rawDescription: SQLAlchemy association confusion

description: SQLAlchemy association confusion


rawDescription: Proper way to read/write fortran order array with numpy


code:
@property_functions(f_1='property_1', f_2='property_2')
class MyClass(object):
    property_1 = 'foo'
    property_2 = 'bar'

rawDescription: How to define similar class-functions related to different class-properties inside __init__

description: Define similar class-functions related to different class-properties inside __init__


code:
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    # @note: renamed the column, so that can use the name 'region' for
    # relationship
    region_id = db.Column(db.Integer, db.ForeignKey('region.id'))

    # define relationship
    region = db.relationship('Region', backref='people')

class Region(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

rawDescription: setup relationship one-to-one in Flask + SQLAlchemy

description: Setup relationship one-to-one in Flask + SQLAlchemy


code:
lst = [1, 2, 3, 4]

def prize(L):
    pair_list = []
    C = 4

    # Creates a list of tuples (1, 2), (1, 3), etc
    for x in L:
        for y in L:
            # if x != y | To prevent 1 + 1 and 2 + 2 (following example)
            # (y, x) not in pair_list | Prevent inverted pairs
            if x != y and (y, x) not in pair_list:
                pair_list.append((x, y))

    # Return list tuples that add to constant
    return [(x, y) for x, y in pair_list if x + y == C]

print('Possible', prize(lst))

rawDescription: How to find the sum of each element in a list with each other element

description: Find the sum of each element in a list with each other element


code:
arr = np.zeros((N, M, T))
for it in xrange(T):
    arr[:,:,it] -= np.sum(arr[:,:,:it], axis=2)

rawDescription: python: multiple arithmetic operations for numpy array

description: Python: multiple arithmetic operations for numpy array


code: df['travel time'] = df['departure time'] - df['datetime']

rawDescription: How to Efficiently Process Time-Series Data in Pandas


rawDescription: Pandas pivot table Nested Sorting Part 3


code:
def show_pass():
    Password.configure(show="")

rawDescription: Tkinter Widget Attribute Update (using ttk frame)


code: table[hashes] = numpy.arange(len(hashes), dtype=numpy.uint32)

rawDescription: Higher-performance method do this type of insert from python?


rawDescription: Moving x-axis to the top of a plot in matplotlib


code:
current_former_x = former_x
current_former_y = former_y

rawDescription: How to make a free hand shape(random) on an image in python using opencv

description: Make a free hand shape(random) on an image in python using opencv


code:
from collections import OrderedDict
from itertools import tee

my_dict = OrderedDict([
    ('LAP0-1', 146.48),
    ('LAP1-1', 44.11),
    ('LAP2-1', 25.54),
    ('LAP3-1', 75.29),
    ('LAP5-2', 85.76),
    ('LAP6-2', 46.87)
])

# pairwise() from Itertools Recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for (key1, value1), (key2, value2) in pairwise(my_dict.items()):
    print("{} | {} ; {} | {}".format(key1, value1, key2, value2))

rawDescription: Python: Loop Dictionary, Two keys at a time


code:
import re
line = '''my name\t is "zyb\org"'''
replaced = re.sub(r'"(.*)\\(.*)"', r"\1\2", line)
print(replaced)

rawDescription: python regex match and replace escaped characters with in quotes

description: Python regex match and replace escaped characters with in quotes


code:
def setup_function(function):
    function.answer = 17

def teardown_function(function):
    del function.answer

def test_modlevel():
    assert modlevel[0] == 42
    assert test_modlevel.answer == 17

rawDescription: How to use xunit-style setup_function

description: Use xunit-style setup_function


code: listnotes.bind("<Return>", dosomething)   #to bind to your enterkey

rawDescription: selecting an item from listbox and using the name of the item later

description: Selecting an item from listbox and using the name of the item later


code: shape=='line' or True or True

rawDescription: Using If-elif-else statements with Python


code:
from pprint import pprint
result = {}
for current_dict in d:
    for key in current_dict:
        slots = {}
        for item in current_dict[key]:
            slots.setdefault(item.hour/3+1, [])
            slots[item.hour/3+1].append(item)
        result[key] = slots
pprint(result)

rawDescription: Grouping python list into timeslots of 3 hours


code:
try:
    min_num = int(fs[0])
    max_num = int(fs[0])
    for number in fs[1:]:

        if int(number) > max_num:
            max_num = int(number)

        if int(number) < min_num:
            min_num = int(number)
except ValueError:
    pass

print(max_num)
print(min_num)

rawDescription: How to find min and max in python?

description: Find min and max in python


code:
#coding:utf-8
import scrapy
from wikipedia.items import WikipediaItem

class CategoriesSpider(scrapy.Spider):
    name = "categories"
    allowed_domains = ["wikipedia.org"]

    def __init__(self, category=None, *args, **kwargs):
        super(CategoriesSpider, self).__init__(*args, **kwargs)
        if category is not None:
            self.start_urls = ['https://en.wikipedia.org/wiki/Category:%s' % category]

    def parse(self, response):
        sel = response.xpath
        item = WikipediaItem()

        categories_letters = sel('//div[@id="mw-pages"]/div/div/div[@class="mw-category-group"]')
        for letter in categories_letters:
            letter_name = ''.join(letter.xpath('.//h3/text()').extract()).replace(u'\xa0', u'')
            for category in letter.xpath('.//ul/li/a'):
                category_name = ''.join(category.xpath('.//@title').extract())
                category_url = ''.join(category.xpath('.//@href').extract())
                item['category_name'] = category_name
                item['category_url'] = category_url
                item['letter_name'] = letter_name
                yield item

rawDescription: Scraping in python

description: Scraping in python


code: cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))

rawDescription: Basic pySQLite example?

description: Basic pySQLite example


code:
import tkinter
import random

class Application(tkinter.Frame):

    @classmethod
    def main(cls):
        root = tkinter.Tk()
        frame = cls(root)
        frame.grid()
        root.mainloop()

    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.w = tkinter.Label(self, text='Hello, world!')
        self.w.grid()
        self.v = tkinter.Button(self, text='Press Me', command=self.click)
        self.v.grid()
        self.u = tkinter.Button(self, text='Me Too!',
                                command=lambda: external_mutator(self.w))
        self.u.grid()

    def click(self):
        self.w['text'] = external_function(3)

def external_function(ndigits):
    return round(random.random(), ndigits)

def external_mutator(widget):
    widget['text'] = external_function(6)
    print('Hello to you too!')  # shown on console if present

if __name__ == '__main__':
    Application.main()

rawDescription: is this bad programming practice in tkinter?

description: Is this bad programming practice in tkinter


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

import os

import cherrypy
from cherrypy.lib.static import serve_file

path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return serve_file(os.path.join(path, 'index.html'))

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def getData(self):
    return {
      'foo' : 'bar',
      'baz' : 'another one'
    }

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

rawDescription: How to call a python script with ajax in cherrypy app

description: Call a python script with ajax in cherrypy app


code:
def foo():
    pass

rawDescription: Python dummy statement for nothing or nop when indent expected


rawDescription: Implementing a class property that preserves the docstring


code:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from urlparse import urljoin

class CompItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    data = scrapy.Field()

class criticspider(CrawlSpider):
    name = "comp"
    allowed_domains = ["consumercomplaints.in"]
    start_urls = ["http://www.consumercomplaints.in/?search=delhivery"]
    rules = (
        Rule(
            SgmlLinkExtractor(allow=("search=delhivery&page=1/+",)),
            callback="parse",
            follow=True),
    )

    def parse(self, response):
        sites = response.xpath('//table[@width="100%"]')
        items = []

        for site in sites:
            item = CompItem()
            item['title'] = site.xpath('.//td[@class="complaint"]/a/span/text()').extract()[0]
            item['link'] = site.xpath('.//td[@class="complaint"]/a/@href').extract()[0]
            if item['link']:
                if 'http://' not in item['link']:
                    item['link'] = urljoin(response.url, item['link'])
                yield scrapy.Request(item['link'],
                                     meta={'item': item},
                                     callback=self.anchor_page)

            items.append(item)

    def anchor_page(self, response):
        old_item = response.request.meta['item']

        old_item['data'] = response.xpath('.//td[@class="compl-text"]/div/text()').extract()
        yield old_item

rawDescription: using scrapy extracting data inside links

description: Using scrapy extracting data inside links


rawDescription: Adding a Method to an Existing Object Instance


code:
def countVowels(s):
    s = s.lower() #so you don't have to worry about upper and lower cases
    vowels = 'aeiou'
    return {vowel:s.count(vowel) for vowel in vowels} #a bit inefficient, but easy to understand

rawDescription: Function that takes a string as input and counts the number of times the vowel occurs in the string


code:
for i in lista[1:]:
    final_score.setdefault(str(i[0:-2]), 0)
    final_score[str(i[0:-2])] += int(i[-2:]) # possible error location

rawDescription: How do I create a dictionary where I add points to names form a text file?

description: Create a dictionary where I add points to names form a text file


code:
import sympy
h = sympy.cos('x')
g = sympy.sin(h)
g
Out[245]: sin(cos(x))

rawDescription: How to do function composition in Sympy?

description: Do function composition in Sympy


rawDescription: OpenCV: setting all pixels of specific BGR value to another BGR value


code:
class MyInt(int):
    difference=lambda self: self.__sub__

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
subj = 'abc123 bbb22 cc'
rgx = re.compile(r'[a-z]+(\d+)?')
for match in re.finditer(rgx,subj):
    if match.group(1):
        print (match.group(1))

rawDescription: Testing not-empty Group captures

description: Testing not-empty Group captures


rawDescription: Having trouble with packing and unpacking frames in Tkinter


code:
class BaseFilterSet(object):
    (...)
    @property
    def qs(self):
        if not hasattr(self, '_qs'):
            qs = self.queryset.all()
            grouped_dict = {}
            for name, filter_ in self.filters.iteritems():
                try:
                    if self.is_bound:
                        data = self.form[name].data
                    else:
                        data = self.form.initial.get(name, self.form[name].field.initial)
                    val = self.form.fields[name].clean(data)
                    if filter_.grouped:
                        grouped_dict.update(filter_.filter_grouped(qs, val))
                    else:
                        qs = filter_.filter(qs, val)
                except forms.ValidationError:
                    pass

            if grouped_dict:
                qs = qs.filter(**grouped_dict)

        (...)
    return self._qs

rawDescription: Combine several filters into one filter() with django-filters


code:
obj = ['<','>','=','<=']
x ='a<=b'
result = {}
for i in obj:
    if i in x:
       result[i]="Present in string."
    else:
       result[i]="Not in string"

import pprint
pprint.pprint(result)

rawDescription: find string mathematical operator

description: Find string mathematical operator


code:
myArray = [['Student Name','Marks','Level'],['Johnny',68,4],['Jennifer',59,3],['William',34,2]]
mx = len(max((sub[0] for sub in myArray),key=len))

for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

rawDescription: How to line up columns when printing from 2d array in Python?

description: Line up columns when printing from 2d array in Python


code:
M, N = 12, 10
np.unravel_index(4, dims=(M, N))

rawDescription: Python, neighbors on a regular grid

description: Python, neighbors on a regular grid


code: idx = np.flatnonzero(mask)

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
class Node(object):
    isRoot = False
    left  = None
    right = None
    parent = None
    branch = None
    seq = 0

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

rawDescription: Python: Optimizing, or at least getting fresh ideas for a tree generator


rawDescription: Python Class Fields

description: Python Class Fields


code:
for xx in range(0, width, block_size):
    for yy in range(0, height, block_size):
        print ("---", xx, yy)
        offsetX = min(width, xx + block_size_half)
        offsetY = min(height, yy + block_size_half)

        r, g, b = matrix[xx + offsetX][yy + offsetY]

        for x in range(xx, min(xx + block_size, width)):
            for y in range(yy, min(yy + block_size, height)):
                print (x, y)
                matrix[x][y] = (r, g, b)

rawDescription: Python nested while-loop doesn't increment as expected


code:
BUFFER_SIZE = 1 << 20

def main():
    with get_file('Enter filename: ') as file:
        while True:
            position = file.tell()
            buffer = file.read(BUFFER_SIZE)
            if not buffer:
                return
            file.seek(position)
            file.write(buffer.upper())
        # The following code will not run but can replace the code in the loop.
        start = file.tell()
        buffer = file.read(BUFFER_SIZE)
        if not buffer:
            return
        stop = file.tell()
        assert file.seek(start) == start
        assert file.write(buffer.upper()) == len(buffer)
        assert file.tell() == stop

def get_file(prompt):
    while True:
        try:
            return open(input(prompt), 'r+b')
        except EOFError:
            raise SystemExit()
        except OSError as error:
            print(error)

if __name__ == '__main__':
    main()

rawDescription: Python: Writing to file using for loop

description: Python: Writing to file using for loop


code: x = [bah*2 for bah in buh]

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


rawDescription: Regex to find specific number using Python regex


code:
newext = c.X509Extension('nsComment', 0, 'tacos are delicious')
cert.add_extensions([newext])
cert.get_extension_count()
cert.get_extension(4)
cert.get_extension(4).get_data()

rawDescription: Extract the value of a X.509 certificate custom extension using PyOpenSSL


code:
ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])

print("0x%X" % ary[0])
# 0xCD

rawDescription: How to split 16-bit unsigned integer into array of bytes in python?

description: Split 16-bit unsigned integer into array of bytes in python


code:
upper = fields.Char(compute='_compute_upper', store=True)

@api.depends('name')
def _compute_upper(self):
    for rec in self:
        self.upper = self.name.upper() if self.name else False

rawDescription: How to set store trigger for computed fields in Odoo 8?

description: Set store trigger for computed fields in Odoo 8


rawDescription: MongoAlchemy Document Encode to JSON via Flask-MongoAlchemy


code: from django.forms.widgets import Textarea

rawDescription: Disabling Openlayers map in GeoDjango Admin


code: backend: Agg

rawDescription: Matplotlib can't suppress figure window

description: Matplotlib can't suppress figure window


code:
a = [1,2,3,4]
for loop in range(len(a) - 1, -1, -1):
    if a[loop] % 2 == 0:
        a.remove(a[loop])

rawDescription: python for loop with "reducing" list

description: Python for loop with "reducing" list


code:
def iso8601(value):
    # split seconds to larger units
    seconds = value.total_seconds()
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    days, hours, minutes = map(int, (days, hours, minutes))
    seconds = round(seconds, 6)

    ## build date
    date = ''
    if days:
        date = '%sD' % days

    ## build time
    time = u'T'
    # hours
    bigger_exists = date or hours
    if bigger_exists:
        time += '{:02}H'.format(hours)
    # minutes
    bigger_exists = bigger_exists or minutes
    if bigger_exists:
      time += '{:02}M'.format(minutes)
    # seconds
    if seconds.is_integer():
        seconds = '{:02}'.format(int(seconds))
    else:
        # 9 chars long w/leading 0, 6 digits after decimal
        seconds = '%09.6f' % seconds
    # remove trailing zeros
    seconds = seconds.rstrip('0')
    time += '{}S'.format(seconds)
    return u'P' + date + time

rawDescription: Convert a datetime.timedelta into ISO 8601 duration in Python?


code:
class ExitAutocall(IPyAutocall):
    """An autocallable object which will be added to the user namespace so that
    exit, exit(), quit or quit() are all valid ways to close the shell."""
    rewrite = False

    def __call__(self):
        self._ip.ask_exit()

rawDescription: Why can't exit() terminate the program immediately while in the readlines loop?


code: writer = UnicodeWriter(response, quoting=csv.QUOTE_ALL, encoding="utf-8-sig")

rawDescription: How can i add encoding to the python generated CSV file

description: Add encoding to the python generated CSV file


code:
def read(fileName):
    list2 =[]
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append(words[2])
    maximum = max(list2)
    infile.close()
    return maximum

def rinter(fileName, maximum):
    infile = open(fileName, "r")
    for line in infile:
        if maximum in line:
             print(line)

maximum = read("distances.txt")
newcode = rinter("winner.txt",maximum)

rawDescription: What am I doing wrong? Python Reading and Distinguishing


code:
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb')                  # file to send
session.storbinary('STOR kitten.jpg', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

rawDescription: Python Script Uploading files via FTP

description: Python Script Uploading files via FTP


code:
def constraint(func):
    func._is_constraint = True
    @wraps(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)
    return inner

rawDescription: Using a decorator to add return the inner function with a property added


code:
from datetime import datetime
from random import randint

# Create my test lists of 10 000 000 elements
test_0 = []
#nb_el = 10000000
nb_el = 1000
while (len(test_0) < nb_el):
    test_0.append(randint(0, 100))
test_1 = test_0[:] # clone list1
test_2 = test_0[:] # clone list1
test_3 = test_0[:] # clone list1

# Test #0
# Remove the 11th element and second last element
d1 = datetime.now()
del test_0[10]
d2 = datetime.now()
print('Test 0, 11th element: ' +
    str((d2-d1).microseconds / 1000000.0) + ' seconds')

d1 = datetime.now()
del test_0[nb_el-2]
d2 = datetime.now()
print('Test 0, second last element: '
    + str((d2-d1).microseconds / 1000000.0) + ' seconds')

# Test #1 | TOO SLOW TO BE RAN with 10 000 000 elements
# Delete every element where element is a multiple of 2
d1 = datetime.now()
for i in reversed(range(len(test_1))):
    if test_1[i] % 2 == 0:
        del test_1[i]
d2 = datetime.now()
print('Test 1: ' + str((d2-d1).microseconds / 1000000.0) + ' seconds')

# Test #2
# Create a new list with every element multiple of 2
# using list comprehension
d1 = datetime.now()
test_2_new = [x for x in test_2 if x % 2 == 0]
d2 = datetime.now()
print('Test 2: ' + str((d2-d1).microseconds / 1000000.0) + ' seconds')

# Test #3
# Create a new list with every element multiple of 2
# using for loop
d1 = datetime.now()
test_3_new = []
for i in range(len(test_3)):
    if test_3[i] % 2 == 0:
        test_3_new.append(test_3[i])
d2 = datetime.now()
print('Test 3: ' + str((d2-d1).microseconds / 1000000.0) + ' seconds')

rawDescription: Python: del in for loop

description: Python: del in for loop


code:
emails = [
    (u'Subject', u'Message.', u'from@example.com', [address])
    for name, address in recipients
]
send_mass_mail(emails)

rawDescription: Looping through to create a tuple

description: Looping through to create a tuple


code:
"Verdana"
"Comic Sans"
"Times New Roman", Times, serif

rawDescription: CSS parsing Python for finding font-family


code:
import numpy as np

def main():
    m = np.random.random((3, 4))
    mask = (m[2] > 0.5) & (m[2] < 0.8)  # put your conditions here
                                        # instead of 0.5 and 0.8 you can use
                                        # an array if you like
    m[:, mask]

if __name__ == '__main__':
    main()

rawDescription: Pulling data from a numpy array

description: Pulling data from a numpy array


code: answer = input("")

rawDescription: creating a list containing list of employees

description: Creating a list containing list of employees


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

ax = plt.subplot(111)
x = np.linspace(0, 10)
y = np.exp(x)
plt.plot(x, y)
pickle.dump(ax, file('myplot.pickle', 'w'))

rawDescription: Store and reload matplotlib.pyplot object


rawDescription: International Date "String" Is Subtracting Instead of Remaining in Its Original Format


rawDescription: Dealing with multiple python versions when python files have to use #!/bin/env python


code:
while True:
    newfiles = check_for_new_files()
    time.sleep(pollinterval)
    process(newfiles)

rawDescription: How do you check when a file is done being copied in Python?

description: Check when a file is done being copied in Python


code: re.split('[, ]*', test)

rawDescription: using non-greedy qualifiers in regular expression '*?'

description: Using non-greedy qualifiers in regular expression '*?'


code:
middlewares.py
from scrapy import log
from scrapy.exceptions import IgnoreRequest
from mybot.utils import connect_url_database

class DedupMiddleware(object):

    def __init__(self):
        self.db = connect_url_database()

    def process_request(self, request, spider):
        url = request.url
        if self.db.has(url):
            log.msg('ignore duplicated url: <%s>'%url, level=log.DEBUG)
            raise IgnoreRequest()

rawDescription: avoid scrapy revisit on a different run

description: Avoid scrapy revisit on a different run


code:
def set_up_axes(some, arguements):
    '''
    Factory to make configured axes (
    '''
    fig, ax = plt.subplots(1, 1) # or what ever layout you want
    ax.set_*(...)
    return fig, ax

my_norm = matplotlib.colors.Normalize(vmin, mmax) # or write a factory to do fancier stuff
fig, ax = set_up_axes(...)
ax.imshow(..., norm=my_norm)
fig2, ax2 = set_up_axes(...)
ax2.imshow(..., norm=mynorm)

rawDescription: Matplotlib: using a figure object to initialize a plot


code:
from some.very.long.package.name import \
                 LongName as OtherLongName

rawDescription: multiline import from X import Y as Z

description: Multiline import from X import Y as Z


code:
from multiprocessing import Process

def f():
    print('hello')

p = Process(target=f)
p.start()
p.join()

rawDescription: Using Python's multiprocessing.Process class


code: somelist+=[[x+f(x) for x in somelist[-1]]]

rawDescription: Loop over time and over list elements with python -- one-dimensional lake temperature model simulation


code: regions = [[(sl.start, sl.stop) for sl in sllist] for sllist in regions]

rawDescription: How to order points for Matplotlib's fill function?

description: Order points for Matplotlib's fill function


code:
class CallbackList(list):
     def fire(self, *args, **kwargs):
         for listener in self:
             listener(*args, **kwargs)

rawDescription: More pythonic way to manage a list of callbacks


code:
def test_function(df):
    ser = pd.Series(np.random.rand(len(df)))
    grouped = ser.groupby(df['A'])
    return grouped.first()

Ds = test_function(df)

rawDescription: Python Pandas working with dataframes in functions


code:
from PIL import Image
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse

def render_image_with_watermark(request, pk, text):

    # pk is the primary key of photo model
    photo = get_object_or_404(Photo, pk=pk)

    # watermark the photo and save it to a temp file
    tmp_name = tempfile.mktemp()

    # this function was introduced in:
    # http://www.pythoncentral.io/watermark-images-python-2x/
    add_watermark(photo.image_url, text, out_file=tmp_name, angle=23, opacity=0.25)

    # render the watermarked photo to response
    wrapper = FileWrapper(open(photo.image_url, 'rb'))
    response = StreamingHttpResponse(wrapper, 'image/jpeg')
    response['Content-Length'] = os.path.getsize(photo.image_url)
    response['Content-Disposition'] = 'attachment; filename=photo.jpg'

    return response

rawDescription: image watermark using PIL in django

description: Image watermark using PIL in django


code:
f = lambda rep, src: reduce(lambda l, e: l+rep*[e], src, [])
f(2, xrange(5))
f(3, ['a', 'b'])

rawDescription: Create a list of integers with duplicate values in Python


code:
def __is_prime(p, primes):
    return all((p % prime != 0) for prime in primes)
def __get_prime():
    primes = [3,5,7,11]
    for p in xrange(13, 50000, 2):
        if __is_prime(p, primes):
            primes.append(p)
    return primes[-1]
prime = delayed(__get_prime, int)

rawDescription: Delay load/calculate values in Python

description: Delay load/calculate values in Python


rawDescription: Diagonals in a non-square matrix - python


code:
def word_check(f_name, word):

    with open(f_name) as fi:
        for line in fi: # let Python deal with line iteration for you
            if line.startswith(word):
                return # return if the word exists

    # word didn't exist, so reopen the file in append mode
    with open(f_name, 'a') as fo:
        fo.write("{}\n".format(word))

    return

def main():

    f_name = "test.txt"

    with open(f_name, 'w') as fo:
        pass # just to create the empty file

    word_list = ['a', 'few', 'words', 'with', 'one',
                 'word', 'repeated', 'few'] # note that 'few' appears twice

    for word in word_list:
        word_check(f_name, word)

if __name__ == "__main__":
    main()

rawDescription: Reading a word from a file in a specific way


rawDescription: Merge Dictionaries with different TimeStamp


code:
import os,sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering

rawDescription: Output of python scripts displayed only at termination when using SSH?


code: vars()['k' + str(i)]=rate

rawDescription: Iteration over variable names in python?

description: Iteration over variable names in python


rawDescription: Filtering pandas in Python using 'where'


code:
import subprocess

cmd = ['ssh', 'user@machine2',
       'mkdir -p output/dir; cat - > output/dir/file.dat']

p = subprocess.Popen(cmd, stdin=subprocess.PIPE)

your_inmem_data = 'foobarbaz\0' * 1024 * 1024

for chunk_ix in range(0, len(your_inmem_data), 1024):
    chunk = your_inmem_data[chunk_ix:chunk_ix + 1024]
    p.stdin.write(chunk)

rawDescription: In Python, how to write a string to a file on a remote machine?


code:
import requests
from lxml.html import fromstring

tree = fromstring(requests.get("https://en.wikipedia.org/wiki/List_of_current_AFC_team_rosters").content)

for h3 in tree.xpath("//div[@id='mw-content-text']//h3[span/@class='mw-headline']"):
    team_name = h3.xpath(".//a/text()")[0]
    league_name = h3.xpath("preceding-sibling::h2[1]//a/text()")[0]
    players = h3.xpath("following-sibling::table[1]//ul/li/a/text()")

    print(league_name, team_name, players)

rawDescription: Extracting data with irregular pattern - Python Xpath


code:
from random import choice
reels = [reel1, reel2, ...]
outcome = [choice(reel) for reel in reels]

rawDescription: Effectively generate slot machine outcome


code:
def make_A():
    private = {}
    class A:
        def __init__(self):
            self.catch = 100
            private[self,'a'] = 1    # you can modify the private data
            private[self,'b'] = 2
            private[self,'z'] = 26
        def foo(self):
            print(private[self,'a']) # you can access the private data
    return A

rawDescription: Data Hiding in Python Class

description: Data Hiding in Python Class


code: if id2find in s['resumetext']: ...

rawDescription: Python program to search for specific strings in hash values (coding help)


code:
for l in csv.reader(open('foo.csv').readlines()[1: -1]):
    ...

rawDescription: Reading a specific number of lines of a .csv in python


rawDescription: Is there a way to 'search' in a pandas DataFrame for 2 specific numbers in columns and return the index if it exists?


code:
def countLeaves(root):
    if (root.get_left() is None) and (root.get_right() is None):  # we are a leaf
        return 1

    leftChild = root.get_left()
    if leftChild is not None:
        leftChildren = countLeaves(leftChild)
    else:
        leftChildren = 0

    rightChild = root.get_right()
    if rightChild is not None:
        rightChildren = countLeaves(rightChild)
    else:
        rightChildren = 0

    return leftChildren + rightChildren

rawDescription: Recursion counting leaves in binary trees


code:
m,n = a.shape
a[np.arange(m)[:,None],np.argpartition(a,n-2,axis=1)[:,:-2]] = 0

rawDescription: numpy matrix, setting 0 to values by sorting each row

description: Numpy matrix, setting 0 to values by sorting each row


code:
from test1 import MyClass
my_instance = MyClass()
data = my_instance.test()
print(data[1])

rawDescription: What is best way to access variables from different python modules?


code:
from nltk import RegexpParser
sent1 = ['The', 'pizza', 'was', 'awesome', 'and', 'brilliant']
sent2 = ['The', 'pizza', 'was', 'good', 'but', 'pasta', 'was', 'bad']
patterns = """
P: {<NN><VBD><JJ><CC><JJ>}
{<NN><VBD><JJ>}
"""
PChunker = RegexpParser(patterns)
PChunker.parse(pos_tag(sent1))
PChunker.parse(pos_tag(sent2))

rawDescription: How to use nltk regex pattern to extract a specific phrase chunk?

description: Use nltk regex pattern to extract a specific phrase chunk


code:
x = np.zeros(N, N) # x is any input data with those dimensions
W = DFT_matrix(N)
dft_of_x = W.dot(x).dot(W)

rawDescription: DFT matrix in python

description: DFT matrix in python


code:
b = [np.linspace(0, j, 10, endpoint=False) for j in a]
d = map(np.concatenate, zip(b, c))
d

rawDescription: Python: Produce increments from a list to form an array


rawDescription: Repeated Number in Python Regular expression


rawDescription: Webapp2 Jinja2 Dict in List in Dict

description: Webapp2 Jinja2 Dict in List in Dict


code: RetVal = Shell("<full path to python.exe> " & "ActiveWorkBook.Path & \<python script name>")

rawDescription: How to call python script on excel vba?

description: Call python script on excel vba


code:
@app.route('/login', methods=['GET', 'POST'])
def login():
  error=None
  if request.method=='POST':
    if request.form['username']!='admin' or request.form['password']!='1234':
      error ='Invalid Credentials. Please try again.'
    else:
      username=request.form['username']
      password=request.form['password']
      auth_url='http://192.168.206.133:5000/v2.0'
      token = generateToken(username=username, password=password, auth_url=auth_url)
      session["auth_token"] = token # store the token in the session here
      session["authenticated"] = True
      return redirect(url_for('getstats'))
  return render_template('login.html', error=error)

from functools import wraps

def authenticated_resource(function):
    @wraps(function)
    def decorated(*args, **kwargs):
        if session.get("authenticated"):
            return function(*args, **kwargs)
        return redirect(url_for("login"))
    return decorated

rawDescription: Generate auth token in login route and require it in other routes


code:
class structure:
    def __init__(self, handle):
        self.handle = handle

    def __hash__(self):
        return hash(self.handle)

    def __eq__(self, other):
        if not isinstance(other, structure):
            # only equality tests to other `structure` instances are supported
            return NotImplemented
        return self.handle == other.handle

rawDescription: Unique class instances in Python3

description: Unique class instances in Python3


code: common_emails = [ email for email in emails if coll.find_one({ 'email': email }) ]

rawDescription: Filter a list of elements for membership in MongoDB


rawDescription: Pandas: How to read ill formated time data?


code:
def my_x_axis_format(ax, dt):
    if dt>timedelta(days=6):
      intr=int(dt.days/6)
    else:
        intr=2
    #ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),interval=intr))
    ax.xaxis.set_minor_locator(dates.DayLocator(interval=intr))
    ax.xaxis.set_minor_formatter(dates.DateFormatter('%b%d'))
    years= matplotlib.dates.YearLocator() # every year
    yearsFmt = matplotlib.dates.DateFormatter('')
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)

rawDescription: format x-axis automatically

description: Format x-axis automatically


code:
import sys

# make sure bar is in sys.modules
import bar
# link this module to bar
sys.modules[__name__] = sys.modules['bar']

# Or simply
sys.modules[__name__] = __import__('bar')

rawDescription: Python how to alias module name (rename with preserving backward compatibility)


code:
def combo(df):
    for t in df.groupby('A').B:
        if len(t[1:][0])>1:
             yield it.combinations(t[1:][0], 2)

rawDescription: pandas: how to check for repeated values in one column and create a pairwise list of values from another column

description: Pandas: how to check for repeated values in one column and create a pairwise list of values from another column


code:
n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)

rawDescription: Python - ip <-> subnet match?

description: Python - ip <-> subnet match


rawDescription: Transforming Dataframe Columns in Python


code:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # pytz tzinfo representing local time
epoch = datetime(1970, 1, 1, tzinfo=pytz.utc)
x = {'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21)]}
x['time'] = [(local_timezone.localize(datetime(*tt), is_dst=None) - epoch).total_seconds()
             for tt in x['time']]

rawDescription: Converting values of dictionary to the timestamp format


code:
new_mac_tags = []
for tag in mac_tags:
    new_mac_tags += [tag, tag]

rawDescription: adding each member of an array again, right after itself

description: Adding each member of an array again, right after itself


code:
board = [[]]*11
#        ^^ this is called just once

board2 = []
for i in range(11):
    board2.append([])
#                 ^^ this is called 11 times, creating 11 different lists

rawDescription: What are the difference in these two 2d arrays?


code:
from itertools import izip,islice,tee,repeat

def sub_findre(s,substring,diffnumber):
    sublen=len(substring)
    zip_gen=(izip(substring,islice(s,i,i+sublen),repeat(i,sublen)) for i in xrange(len(s)))
    for z in zip_gen:
        l,z=tee(z)
        if sum(1 for i,j,_ in l if i==j)>=sublen-diffnumber:
            new=izip(*z)
            next(new)
            next(new)
            yield next(new)[0]

rawDescription: String regex two mismatches Python

description: String regex two mismatches Python


code:
xs = [3,2,1]
ys = [1,2,3]
points = zip(xs,ys)
points
sorted(points)

rawDescription: Python: sort a list and change another one consequently


code:
def sliceImage(I, a, b, *arg, **kws):
    from scipy import linspace, asarray
    from scipy.ndimage import map_coordinates
    from scipy.linalg import norm
    a = asarray(a)
    b = asarray(b)
    dst = norm(b - a) + 1
    return map_coordinates(I, (a[:,newaxis] * linspace(1, 0, dst) +
                               b[:,newaxis] * linspace(0, 1, dst)),
                           *arg, **kws)

rawDescription: Arbitrary image slice with python/numpy

description: Arbitrary image slice with python/numpy


code:
with open('initiator') as f:
  contentsI = f.read()
with open('other') as f:
  contentsO = f.read()

rawDescription: How to compare two files that have the same unsorted (and additional unimportant) content?

description: Compare two files that have the same unsorted (and additional unimportant) content


code:
CMS_TEMPLATES = (
    ('test.html', 'test.html'),
)

TEMPLATE_LOADERS = (
    'cmsplugin_filer_image.tests.utils.TestTemplateLoader',
)

rawDescription: Django create a template just for testing


code:
def str_join_concat(lst):
    res = ''.join(['\n%s' % elem for elem in lst])

timeit('f(l)', 'from __main__ import testlist as l, str_join_concat as f', number=10000)

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code:
running_std    = [Y[idx==k].std() for k in range(total_bins)]
plt.errorbar(bins-delta/2,running_median,
              running_std,fmt=None)

rawDescription: Running median of y-values over a range of x


rawDescription: From list to tree representation

description: From list to tree representation


code: to_compare = to_compare.translate(None, {"-"})

rawDescription: making difflib's SequenceMatcher ignore "junk" characters

description: Making difflib's SequenceMatcher ignore "junk" characters


code:
appliedFieldIP = [10,5,0,-5,-10,-5,0,5,10]
signalxIP = [2,1,0,-1,-2,-1,0,1,2]

zipped = list(zip(appliedFieldIP, signalxIP))
cutoff_index = appliedFieldIP.index(min(appliedFieldIP))+1
zipped2 = zipped[:cutoff_index]
# this aIP should be the same as aIP in your code
aIP = [pair[0] for pair in zipped2]
intermediate = list(filter(lambda x: x[0] <= 0 <= max(aIP), zipped2))
x2 = [pair[0] for pair in intermediate]
y2 = [pair[1] for pair in intermediate]

print(aIP)
print(x2)
print(y2)

rawDescription: Obtaining value from an array

description: Obtaining value from an array


code: [min(x) for x in lst]

rawDescription: How to pick the smallest value in a list when an iterative process is applied to the list

description: Pick the smallest value in a list when an iterative process is applied to the list


code:
if data[:2] == b'\xf0\x79':
    assert data[-1] == 0xf7, "Message did not end with F7 closing byte"
    version = tuple(data[2:4])
    message = data[4:-1].decode('utf-16-le')

rawDescription: Issues with Bytes from a Microcontroller in Python


code: val1, val2 = uInput()  #Assign using sequence unpacking

rawDescription: Python 3, Passing data from one function to another


code:
# write to a file
query_df.to_csv('test.csv', sep='\t')

# create subprocess command
subprocess_cmd = r'''cat test.csv | java -Xmx16g -jar snpeff.jar -t GRCh37.75 > out_file}'''.format(query_df)

rawDescription: Export Pandas Dataframe to subprocess as stdin


rawDescription: Check string for multiple occurrence of character in Python


rawDescription: Dictionary __gt__ and __lt__ implementation


rawDescription: how to receive regex from command line in python

description: Receive regex from command line in python


code:
import json

class Foobar(models.Model):
    foo = models.CharField(max_length=200)

    def setfoo(self, x):
        self.foo = json.dumps(x)

    def getfoo(self, x):
        return json.loads(self.foo)

rawDescription: Django: List field in model?

description: Django: List field in model


code:
_yellow = _green = _red = lambda msg: msg
if sys.stdout.isatty():
    try:
        from colors import yellow, green, red
    except ImportError:
        yellow, green, red = _yellow, _green, _red
else:
    yellow, green, red = _yellow, _green, _red

rawDescription: Import ansicolor python functions and use them only terminal


code:
import asyncio

class Sheep:
    _sem = asyncio.Semaphore(2)  # we have 2 avaliable sheeps at time

    def __init__(self, reason):
        self._reason = reason

    async def acquire(self):
        await type(self)._sem.acquire()
        print('acquire sheep ({})'.format(self._reason))

    def release(self):
        print('release sheep ({})'.format(self._reason))
        type(self)._sem.release()

    def locked(self):
        return type(self)._sem.locked()

class Gate:
    _sem = asyncio.Semaphore(1)  # we have 1 avaliable gate at time

    def __init__(self, reason):
        self._reason = reason

    async def acquire(self):
        await type(self)._sem.acquire()
        print('acquire gate ({})'.format(self._reason))

    def release(self):
        print('release gate ({})'.format(self._reason))
        type(self)._sem.release()

    def locked(self):
        return type(self)._sem.locked()

class MultiAcquire(asyncio.Task):
    _check_lock = asyncio.Lock()  # to suspend for creating task that acquires objects
    _release_event = asyncio.Event()  # to suspend for any object was released

    def __init__(self, locks):
        super().__init__(self._task_coro())
        self._locks = locks
        # Here we use decorator to subscribe all release() calls,
        # _release_event would be set in this case:
        for l in self._locks:
            l.release = self._notify(l.release)

    async def _task_coro(self):
        while True:
            # Create task to acquire all locks and break on success:
            async with type(self)._check_lock:
                if not any(l.locked() for l in self._locks):  # task would be created only if all objects can be acquired
                    task = asyncio.gather(*[l.acquire() for l in self._locks])  # create task to acquire all objects
                    await asyncio.sleep(0)  # start task without waiting for it
                    break
            # Wait for any release() to try again:
            await type(self)._release_event.wait()
        # Wait for task:
        return await task

    def _notify(self, func):
        def wrapper(*args, **kwargs):
            type(self)._release_event.set()
            type(self)._release_event.clear()
            return func(*args, **kwargs)
        return wrapper

async def spend(reason):
    sheep = Sheep(reason)
    gate = Gate(reason)
    await MultiAcquire([sheep, gate])  # block 1 sheep, 1 gate
    await asyncio.sleep(1)  # 1 second
    print('Spend sheep through a gate')
    sheep.release()
    gate.release()

async def feed(reason):
    sheep = Sheep(reason)
    await MultiAcquire([sheep])  # block 1 sheep
    await asyncio.sleep(2)  # 2 seconds
    print('Feed sheep')
    sheep.release()

async def main():
    await asyncio.gather(
        spend('spend 1'),
        feed('feed 1'),
        spend('spend 2')
    )  # spend 2 times, feed 1 time

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: Synchronous blocking of multiple resources


code:
from com import Communicator
from log import setup_logger

logger = setup_logger(__name__)

def foo():
    c = Communicator(logger)
    c.send('foo')

rawDescription: How to structure the Logging in this case (python)

description: Structure the Logging in this case (python)


code:
import sys
import socket

def print_menu():
    print("""\n\n0) Close the connection
3) Receive file""")

while 1:
    print_menu()
    message = input("\n-Select an option: ")

    if (message=="3"):
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.connect(('127.0.0.1', 9900))
        print("Connection established")
        sock.sendall(message.encode())
        localname=input("name with which you want to save the file:")
        file = open(localname, 'wb')
        path=input("insert remote path of file to be downloaded:")
        sock.sendall(path.encode())

        while 1:
           data=sock.recv(1024)
           if not data:break
           file.write(data)
        file.close()
        sock.close()

    elif(message=="0"):
         sock.sendall(message.encode())
         sock.close()
         break

rawDescription: python: not write last bytes tcp?

description: Python: not write last bytes tcp


code:
import inverse_regex
print(''.join(inverse_regex.ipermute('[a-z]')))
# abcdefghijklmnopqrstuvwxyz

rawDescription: Generate random string from regex character set


code:
def __init__(self, t):
    for field in t._fields:
        setattr(self, field, getattr(t, field))

rawDescription: Can a class inherit the properies of a namedtuple?


rawDescription: adjusting floats to maintain high precision

description: Adjusting floats to maintain high precision


code:
command = 'ffmpeg -i "concat:1.ts|2.ts" -vcodec copy -acodec copy temp.mp4'
output,error  = subprocess.Popen(
                    command, universal_newlines=True, shell=True,
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

rawDescription: Passing double quote shell commands in python to subprocess.Popen()?


rawDescription: Access last index value of dataframe

description: Access last index value of dataframe


code: df['col'] = pd.to_datetime(df['col'])

rawDescription: Convert DataFrame column type from string to datetime


rawDescription: Python heatmap from 3d coordinates

description: Python heatmap from 3d coordinates


code:
ax.xaxis.set_data_interval(0, 10)
ax.yaxis.set_data_interval(-5, 5)

rawDescription: matplotlib axis-independent version of set_xlim() and set_ylim()?

description: Matplotlib axis-independent version of set_xlim() and set_ylim()


code:
import ruamel.yaml as yaml
from ruamel.yaml.resolver import Resolver

yaml_str = """\
categories: {1: Yes, 2: No}
"""

for ch in list(u'yYnNoO'):
    del Resolver.yaml_implicit_resolvers[ch]

data = yaml.load(yaml_str, Loader=yaml.Loader)
print(data)

rawDescription: Can't parse YAML correctly

description: Can't parse YAML correctly


rawDescription: Set global minimum logging level across all loggers in Python/Django


rawDescription: Selecting items in a dictionary using python


code:
PHI, Z = np.meshgrid(phi, z)
CP = r * np.cos(PHI)
SP = r * np.sin(PHI)
XYZ = np.dstack([CP, SP, Z])
verts = np.stack(
    [XYZ[:-1, :-1], XYZ[:-1, 1:], XYZ[1:, 1:], XYZ[1:, :-1]], axis=-2).reshape(-1, 4, 3)

rawDescription: Rounding the edges of a cylinder in matplotlib poly3D


code: print("Your number is {a}.".format(a=a))

rawDescription: Need assistance on Print function

description: Need assistance on Print function


code:
df = pd.read_csv('http://pastebin.com/raw/yeHdk2Gq', index_col=0)\
       .reindex([round(i, 5) for i in np.arange(0.6, 3.5, 0.01)])\
       .interpolate(kind='cubic', axis=0)

rawDescription: Pandas: Reindexing dataframe won't keep initial values


code:
if suit not in ("Diamonds","Hearts","Clubs","Spades"):
    return "Wrong input"
else:
    return "Accepted"

rawDescription: Better way, of writing a Long "if" statements?


code:
import re
from string import whitespace
strs = re.search(r'List:(.*)(\s\S*\w+):', ph, re.DOTALL).group(1)
strs.translate(None, ':'+whitespace).split(',')

rawDescription: capturing the usernames after List: tag

description: Capturing the usernames after List: tag


rawDescription: PageRank python implementation, algorithm


code:
combined = playlist_songs[0]

for song in playlist_songs[1:]:
    combined = combined.append(song, crossfade=5000)

combined.export("/path/to/output.mp3", format="mp3")

rawDescription: Pydub concatenate mp3 in a directory

description: Pydub concatenate mp3 in a directory


code:
import math;

def memoize(f):
    memo = {}
    def helper(x):
        if x not in memo:
            memo[x] = f(x)
        return memo[x]
    return helper

@memoize
def coinProfit(n):
    a = math.floor(n/2)
    b = math.floor(n/3)
    c = math.floor(n/4)
    if a+b+c > n:
        nextProfit = coinProfit(a)+coinProfit(b)+coinProfit(c)
        if nextProfit > a+b+c:
            return nextProfit
        else:
            return a+b+c
    return n

rawDescription: My short recursive function takes too long to execute, how can I optimize it


code:
with open('output.txt', 'w') as output:
    process = subprocess.Popen('ping 127.0.0.1', stdout=output)
    process.communicate()

rawDescription: Output result of a ping with subprocess.call to a text file


code:
rows = []
for i in xrange(2):
    row = []
    for k in field.keys():
        row.append(field[k][i])
    rows.append(row)

rawDescription: Dictionary As Table In Django Template

description: Dictionary As Table In Django Template


code:
import re
def repetitions(s):
   r = re.compile(r"(.+?)\1+")
   for match in r.finditer(s):
       yield (match.group(1), len(match.group(0))/len(match.group(1)))

rawDescription: Detect repetitions in string

description: Detect repetitions in string


code:
class TestObj(object):
    def __init__(self, value, *args, **kwargs):
        self.value = value
        super().__init__(*args, **kwargs)

    def __eq__(self, other):
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)

rawDescription: Is there a comparison key for set objects?


code: {{ filter.avg }}

rawDescription: django-filter and aggregate functions

description: Django-filter and aggregate functions


code:
f = []
b = os.walk('C:\\Users\\username\\Desktop\\FOLDER')
for(dirpath, dirnames, filenames) in b:
    f.extend(filenames)
    break

rawDescription: remove extension in list python

description: Remove extension in list python


rawDescription: How to do an inverse `range`, i.e. create a compact range based on a set of numbers?

description: Do an inverse `range`, i.e. create a compact range based on a set of numbers


code: url_for('static', filename='module.js')

rawDescription: custom location for templates and static resources in flask

description: Custom location for templates and static resources in flask


rawDescription: pandas: filter intraday df by non-consecutive list of dates

description: Pandas: filter intraday df by non-consecutive list of dates


code:
class MeasurementList:

  def __init__(self, measurement_list):
    self.measurements = measurement_list

  def foo(self):
     print("there are %d measurements" % len(self.measurements))

rawDescription: Refer to a property from inside the class itself


rawDescription: Pandas dataframe into sparse dictionary of dictionaries


code:
from bs4 import BeautifulSoup
import requests

source_code = requests.get('http://en.wikipedia.org/wiki/Taylor_Swift_discography')
soup = BeautifulSoup(source_code.content)

table = soup.find('span', id='Singles').parent.find_next_sibling('table')
for single in table.find_all('th', scope='row'):
    print(single.text)

rawDescription: Obtaining column from wikipedia table using beautifulsoup


rawDescription: Counting DNA sequences with python/biopython


code:
import mpmath
mpmath.exp(-1200)
mpmath.mp.dps = 200
mpmath.exp(-1200)

rawDescription: Exponential of very small number in python


code:
inputFile = open('Members.txt', 'r')
inputFile = open('Members1.txt', 'r')
inputFile = open('Members2.txt', 'r')

rawDescription: How to open three files in loop, in python

description: Open three files in loop, in python


rawDescription: Pandas set_option - more than one option per line


code: list4 = [x for t in zip(list1, list2) for x in t]

rawDescription: Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists


code:
labels = range(1, nlbls+1)
labels

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


code:
def cube(x):
    if x >= 0:
        return x**(1/3)
    elif x < 0:
        return -(abs(x)**(1/3))

rawDescription: How to get the real cube root of a negative number in Python3?

description: Get the real cube root of a negative number in Python3


code:
import csv
with open('file.txt') as f:
    reader = csv.reader(f)
    rows = [row for row in reader]
rows

rawDescription: Convert list of lists of string to list of lists of int


code:
#!/usr/bin/env python2.7
# encoding: utf-8
'''
'''
FNAME = ...
for line in open(FNAME):
    row = line.split('\t')
    values = row[1:4]
    conditions = row[4:]

    for i, cond in enumerate(conditions):
        v = values[i % 3]
        # use cond and v to calculate your value

rawDescription: Python: Assign column ids and perform calc depending on column position and id


code:
a = np.array([True, True, True, True, False, False, False, True, True, True, True, True])
np.diff(a)
_.nonzero()

rawDescription: Is there a pythonic way to get the beginning and end indexes of clusters of identical values in an iterable?


code:
yourdict = {'date': ['2011-10-31', '2012-05-08'], 'id': ['18', '12'], 'status': ['completed', 'completed']}
keys = yourdict.keys()
[dict(zip(keys, col)) for col in zip(*yourdict.values())]

rawDescription: accessing individual elements from a python dictionary

description: Accessing individual elements from a python dictionary


Cost of using 10**9 over 1000000000


code:
test = []
for i in range(10):
    nested = []
    for j in range(15):
        nested.append(i * j)

rawDescription: Error in writing Python dictionary to a file


rawDescription: Python wrapping around on a list when list index is out of range


code:
server.fetch([456], ['BODY[TEXT]'])
# {456: {'BODY[TEXT]': "Hey Jon,\r\n\r\nYou recently entered a new contact email [snip]", 'SEQ': 456}}

rawDescription: Using IMAPClient how do you view the Senders address?


rawDescription: Python Numpy Loadtxt - Convert unix timestamp


code:
str = 'Apple'
str.lower()
str = 'APPLE'
str.lower()
str = 'AppLe'
str.lower()

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


code:
from django.db import models
from blog.models import Blog
from django.contrib import admin

class CommentInline(admin.TabularInline):
    model = Comment

class BlogAdmin(admin.ModelAdmin):
    list_display = ('title','created','updated',)
    search_fields = ['title','body',]
    list_filter = ('Date Created','Date Updated',)
    inlines = [CommentInline,]

class CommentAdmin(admin.ModelAdmin):
    list_display = ('post','author','body_first_60','created','updated',)
    list_filter = ('Date Created','Date Updated',)

admin.site.register(Blog, BlogAdmin)

rawDescription: How to add  Search_fields in Django

description: Add  Search_fields in Django


rawDescription: Indexing lines of text in a .txt file

description: Indexing lines of text in a .txt file


code: model.fit(data, x1=x1n, x2=x2n, params=params)

rawDescription: Python lmfit: Fitting a 2D Model

description: Python lmfit: Fitting a 2D Model


code:
def __init__(self, resources=[]):
    self._resources = resources

rawDescription: Python object initialization bug. Or am I misunderstanding how objects work?


code:
start_list.extend([i ** 2 for i in start_list]) # Append items from a new list
start_list += [i ** 2 for i in start_list]  # ditto, different spelling

rawDescription: How do I square each item in a list using append?

description: Square each item in a list using append


code:
import collections

data = {'1': collections.OrderedDict([('Klasa', '6A'), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)]),
        '2': collections.OrderedDict([('Klasa', ''), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)])}

rawDescription: How can I have the tkintertable table's columns sorted the way they are in the dictionary?

description: Have the tkintertable table's columns sorted the way they are in the dictionary


code: strresult = str(result)

rawDescription: Get array count of specific document in Pymongo


code:
kw = len(s)
k = int(s)

rawDescription: Python, string , integer

description: Python, string , integer


code:
with open("in.txt") as f:
    nums = map(int,("".join(x.rstrip().split()) for x in f))

rawDescription: Python: convert all values in csv row to number


code: t = css_soup.select("table.data")

rawDescription: How to use Beautiful Soup to select only one of multiple tables

description: Use Beautiful Soup to select only one of multiple tables


code: foo = [x for x in range(1000) if prime2(x)]

rawDescription: python - returning values for which if statement is true

description: Python - returning values for which if statement is true


code:
import csv

def first_word(value):
    return value.split(" ", 1)[0]

with open(inname, "r") as infile:
    with open(outname, "w", newline="") as outfile:
        in_csv = csv.reader(infile)
        out_csv = csv.writer(outfile)

        column_names = next(in_csv)
        out_csv.writerow(column_names)

        id_index = column_names.index("ID")
        name_index = column_names.index("NAME")

        try:
            row_1 = next(in_csv)
            written_row = False

            for row_2 in in_csv:
                if first_word(row_1[name_index]) == first_word(row_2[name_index]) and row_1[id_index] != row_2[id_index]:
                    if not written_row:
                        out_csv.writerow(row_1)

                    out_csv.writerow(row_2)
                    written_row = True
                else:
                    written_row = False

                row_1 = row_2
        except StopIteration:
            # No data rows!
            pass

rawDescription: Regular Expression, Matrix, CSV in Python


code: screen.blit(thing2, position)

rawDescription: How would I make a car move the direction it's pointing (After use of pygame.translation.rotate)


code:
from django.db.models import Func

class Extract(Func):
    """
    Performs extraction of `what_to_extract` from `*expressions`.

    Arguments:
        *expressions (string): Only single value is supported, should be field name to
                               extract from.
        what_to_extract (string): Extraction specificator.

    Returns:
        class: Func() expression class, representing 'EXTRACT(`what_to_extract` FROM `*expressions`)'.
    """

    function = 'EXTRACT'
    template = '%(function)s(%(what_to_extract)s FROM %(expressions)s)'

#Usage
Comment.objects.annotate(year=Extract(date, what_to_extract='year'),
                             month=Extract(date, what_to_extract='month')
                             ).values('year', 'month').annotate(Count('pk'))

rawDescription: Django count grouping by year/month without extra


code:
def foo():
    for x, y in zip_longest(range(10), range(10, 22)):
        if x is not None:
            yield x
        if y is not None:
            yield y

rawDescription: Is there a way in python to change the order in which yield from get's processed?


code:
key_words = ['Dog', 'Cat', 'Bird', 'Cow', ]

with open('list.csv') as oldfile, open('cleaned.csv', 'w') as cleaned, open("matched.csv", "w") as matched:
    for line in oldfile:
        if not any(key_word in line.split(",", 1)[0] for key_word in key_words):
            cleaned.write(line)
        else:
            matched.write(line)

rawDescription: Python script to clean .csv file based on array values


code:
for source, target in connections:
   Place.objects.get(data=source).connected_to.add(Place.objects.get(data=target))

rawDescription: Checking if ForeignKeys are equal to one another


code: ordered = list(list_dict[val] for val in ordering_list)

rawDescription: Python: using a dict to speed sorting of a list of tuples


code:
def str_extract(file, start, size, delimiter = None, index = None):
   file.seek(start)
   if (delimiter is not None and index is not None):
       delimiter = delimiter.decode('utf-16-le')  # or pass in Unicode
       return file.read(size).decode('utf-16-le').split(delimiter)[index]
   else:
       return file.read(size).decode('utf-16-le')

with open('filename', 'rb') as fobj:
    result = str_extract(fobj, 0, 0x20, b'\x00' * 4, 0)

rawDescription: Python: split bytes with a hexadecimal delimiter


code:
data, addr = s.recvfrom(1024)
ip = addr[0]
port = addr[1]

rawDescription: Python: How to convert the address recieved from a recvfrom() function to a string?


code:
TET_create_pvf(tet, pvfname, 0, data, length, "");
doc = TET_open_document(tet, pvfname, 0, docoptlist);

rawDescription: using PDFLib/TET alongwith boto to parse pdf on amazon s3

description: Using PDFLib/TET alongwith boto to parse pdf on amazon s3


code:
@asyncio.coroutine
def chain_to_coro(chain):
    return (yield from chain)

@asyncio.coroutine
def main():
    ch = chain(Browser()).go().click().go().text()
    coro = chain_to_coro(ch)

    results = yield from asyncio.gather(*[coro], return_exceptions=True)
    print(results)

rawDescription: Method chaining with asyncio coroutines

description: Method chaining with asyncio coroutines


rawDescription: Converting dict to list

description: Converting dict to list


rawDescription: python pandas timeseries: assign value to time (currently omitted from index)

description: Python pandas timeseries: assign value to time (currently omitted from index)


rawDescription: Extract parent and child node from python tree representation


rawDescription: How to get every nth column in pandas?

description: Get every nth column in pandas


code: dict((key, value) for key, value in [string.split(': ')])

rawDescription: Convert string from external file to Python dictionary


rawDescription: Index of max element from two lists

description: Index of max element from two lists


code:
T.C
t = T()
t.C

rawDescription: Python Docstrings in Subclasses

description: Python Docstrings in Subclasses


code: p = className.playerPrefs()

rawDescription: Importing functions from classes outside original file


code: [v for i, v in enumerate(a) if b[i]]

rawDescription: Mapping an array of booleans to an array of values and returning True instances in Python


code:
N = len(df.index)
N
4

rawDescription: Combine Rows in Pandas

description: Combine Rows in Pandas


code: print(*[s.encode('latin1').decode('unicode_escape') for s in all_strings])

rawDescription: How to read interpreted data strings in Python?

description: Read interpreted data strings in Python


code:
while(True):
    if (dem_arr[randx, randy] > -100):
        ...
        break#break from this while-loop.
    else:
        ...
        continue#go back and continue this while-loop.

rawDescription: Python: How to return a result from a conditional and then have it re-enter the conditional statement


code:
import sys
print(sys.argv)
input()

rawDescription: Associate file extension to python script, so that I can open the file by double click, in windows


code:
import numpy as np
dd = input("What is your desired degree for slices? ")

limits = range(0, 360, int(dd))

# Append 361 just so we get the last group
limits.append(361)

datasets = list()

# Convert to a numpy array
pos = np.array(posvcs)

# Now group everything
for k in range(len(limits) - 1):
    inrange = np.logical_and(pos[:,2] >= limits[k], pos[:,2] < limits[k+1])
    datasets.append(pos[inrange,2])

rawDescription: Python for & if loop not working?

description: Python for & if loop not working


code:
# Test Data
artists = [
    Artist(
        name='should match rock',
        genres=[Genre(name='rock'), Genre(name='pop')],
        songs=[Song(name='love'), Song(name='hate')]
    ),
    Artist(
        name='should NOT match',
        genres=[Genre(name='indie rock')],
        songs=[Song(name='elsewhere')]
    ),
]

db.session.add_all(artists)
db.session.commit()

rawDescription: SQLAlchemy: filter many-to-one relationship where the one object has a list containing a specific value


rawDescription: Python weave to speed up our code

description: Python weave to speed up our code


code:
class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        # made this an instance variable since we will need it later
        self.label = tk.Label(self, text= letter, font=TITLE_FONT)
        self.label.pack(side="top", fill="x", pady=10)

        # made this an instance variable since we will need it later
        self.choices = tk.Listbox(self, height="10", width="25")
        self.choices.insert(0, letter)
        self.choices.insert(1, "CPP")
        self.choices.pack(side="bottom", fill="x", pady=10)

        button = tk.Button(self, text="<",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

    # new method to update the label and choice list
    def update(self):
        self.label.text = letter
        self.choices.delete(0)
        self.choices.insert(0, letter)

rawDescription: Python & Tkinter Structure Issue

description: Python & Tkinter Structure Issue


code: [a] + other_list

rawDescription: What is the right way to create a list from variable and another list?


code:
import base64
original_txt = base64.b64decode(open("output.bin").read())

rawDescription: Writing binary type data in cells structure


rawDescription: tkinter >> how to get button references?

description: Tkinter >> how to get button references


code:
# Input: M scipy.sparse.csc_matrix
# Output: NetworkX Graph
def nx_graph_from_biadjacency_matrix(M):
    # Give names to the nodes in the two node sets
    U = [ "u{}".format(i) for i in range(M.shape[0]) ]
    V = [ "v{}".format(i) for i in range(M.shape[1]) ]

    # Create the graph and add each set of nodes
    G = nx.Graph()
    G.add_nodes_from(U, bipartite=0)
    G.add_nodes_from(V, bipartite=1)

    # Find the non-zero indices in the biadjacency matrix to connect
    # those nodes
    G.add_edges_from([ (U[i], V[j]) for i, j in zip(*M.nonzero()) ])

    return G

rawDescription: Plot bipartite graph using networkx in Python


rawDescription: python: find and replace numbers < 1 in text file

description: Python: find and replace numbers < 1 in text file


code:
VOWELS = "aeiou"

word = "james is funny"

for letter in word:
    if letter in VOWELS:
        print(letter, end='')
    else:
        print(' ', end='')

rawDescription: How to use Python to show only the letters from words with vowels

description: Use Python to show only the letters from words with vowels


code: y

rawDescription: pandas DataFrame - Getting hours in a Duration

description: Pandas DataFrame - Getting hours in a Duration


code:
class QueueLogger(Handler):
    def __init__(self, log_queue):
        """
        Initialize the handler with logging Queue.
        """
        Handler.__init__(self)
        self.log_queue = log_queue

    def emit(self, record):
        self.log_queue.put(record)

rawDescription: Why doesn't TimedRotatingFileHandler work properly and how to solve this issue(rotation is working, but missing logging lines) when log lines


code:
for entry, count in counts.items():
    print('{} {:2d}'.format(entry, count))

rawDescription: Count lines after line with specific character


code:
import requests
r = requests.get('http://try.discourse.org/user_actions.json?offset=0&username=discoursetestr1')
r.json()['user_actions'][0]

rawDescription: Unique attributes for certain data

description: Unique attributes for certain data


code:
class Command(BaseCommand):

    can_import_settings = True

    def handle(self, *args, **options):

        # Activate a fixed locale, e.g. Polish
        translation.activate('pl')

        # Or you can activate the LANGUAGE_CODE # chosen in the settings:
        #
        #from django.conf import settings
        #translation.activate(settings.LANGUAGE_CODE)

        # Your command logic here
        # ...

        translation.deactivate()

rawDescription: Django. i18N reverse url Issue

description: Django. i18N reverse url Issue


code:
from numba import jit

@jit(nopython=True)
def exponential_sum(A, k):
    total = A[0]
    yield total
    for i in xrange(1, len(A)):  # Use range in Python 3.
        total = total * k[i] + A[i]
        yield total

rawDescription: Pandas: Exponentially decaying sum with variable weights


code:
DATABASES = {
    'default': {
        'NAME': 'default',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': '',
    },
    'future': {
        'NAME': 'future',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': '',
    },
}

rawDescription: Django turn based browser game - database design to handle separate time steps


code:
happy
birthday

rawDescription: Python - Database query function with non-consistent arguments


code: obj = getattr(__import__(mod_name, globals=globals(), locals=locals(), fromlist=(obj_name), level=1), mod_name)

rawDescription: Import object from module of same name using __import__


rawDescription: how to make a function which tells if two lists are equivalent in python

description: Make a function which tells if two lists are equivalent in python


code:
def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    key = int(input()) # key input
    while True:
        if key >= 1 and key <= 26: #checking if key is in between range
            return key #giving back the key
        else: # this should run whenever the input is invalid
            print ("The key must be inbetween 1 and 26")
            break # to stop the loop
    getKey() # Recursion, to restart the function THEN THROW AWAY RESULT
    return None # This is what falling off the end of a function does.

key = getKey()
print(key) # this prints 'None'

rawDescription: Recursion in function causing return variable to equal 'None'


code:
probabilities = [0.0000003, 0.0000004, 0.0000005]
exp(sum(log(p) for p in probabilities))

rawDescription: Convert float to log space in python

description: Convert float to log space in python


code:
import Image

pil_image_obj = Image.open(model_instance.image_field)

rawDescription: how to go form django image field to PIL image and back?

description: Go form django image field to PIL image and back


rawDescription: Use multiple functions at once on a list


code:
with Pool() as p:
    processed = p.map(processItem, lst)

rawDescription: Multi threading read and write file using python


rawDescription: Return function name in python?

description: Return function name in python


rawDescription: How can I get a list of image URLs from a Markdown file in Python?

description: Get a list of image URLs from a Markdown file in Python


code:
import matplotlib.pyplot as plt
im = plt.imread('pic.jpg')
if im.shape[2] == 3:
    # Input image is three channels
    fig = plt.figure()
    fig.add_subplot(311)
    plt.hist(im[...,0].flatten(), 256, range=(0, 250), fc='b')
    fig.add_subplot(312)
    plt.hist(im[...,1].flatten(), 256, range=(0, 250), fc='g')
    fig.add_subplot(313)
    plt.hist(im[...,2].flatten(), 256, range=(0, 250), fc='r')
    plt.show()

rawDescription: How to use Pillow instead cv2?

description: Use Pillow instead cv2


code:
import random
import string

IDS = range(1, 100)
widgets = ['ITEM_%s' % (i, ) for i in range(10)]
thing_chars = list(string.uppercase + string.lowercase)

def get_thing():
    return "".join(random.sample(thing_chars, 10))

with open("yourfile.txt", "w") as out:
    for i in xrange(0, 16000):
        ID = random.choice(IDS)
        widget = random.choice(widgets)
        thing = get_thing()
        out.write("%s,%s,%s\n" % (ID, thing, widget))

rawDescription: Using Python to automate data cleanup, some issues


code:
from pprint import pprint
pprint(sorted(mycount.items(), key=lambda kv: [c[1] for c in kv[1].most_common()], reverse=True))

rawDescription: How can I sort data in python by the specific part of data?

description: Sort data in python by the specific part of data


code:
z.reshape(2,3,3, order='F').ravel(order='F')
z.reshape(2*3*3, order='F').ravel(order='F')
z.reshape(2*3,3, order='F').ravel(order='F')

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


code:
{ "nodes": [
  { "content": "hi" },
  { "indent": True },
  { "content": "how do you do" },
  { "outdent": True },
  { "content": "hi again" },
]}

rawDescription: render threaded comment tree in Jinja template

description: Render threaded comment tree in Jinja template


code:
x=np.arange(5)
i,j,data=[],[],[]
mask1=x%2==0
mask2=x%2!=0
i.append(x[mask1])
j.append((x*2)[mask1])
i.append(x[mask2])
j.append(x[mask2])
i=np.concatenate(i)
j=np.concatenate(j)
i
j
M=sparse.coo_matrix((x,(i,j)))
print(M)
M.A

rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


code:
if DEBUG:
    MIDDLEWARE_CLASSES += myapp.disable.DisableCSRF

rawDescription: Test post requests on django, csrf_token


code: df1 = df.reindex(index, method='ffill')

rawDescription: Python Pandas value-dependent column creation


code:
def spread(seq, N=None, X=1):
    """Yield successive subsequences of seq having at least X elements.

    If N is specified, the number of subsequences yielded will not exceed N.

    The first L % X subsequences yielded (where L = len(seq)) will be longer
    by 1 than the remaining ones.

    >>> list(spread('abcdefghij', 4, 3))
    ['abcd', 'efg', 'hij']
    >>> list(spread('abcdefghijklmnopqrstuvwxyz', 4, 7))
    ['abcdefghi', 'jklmnopqr', 'stuvwxyz']

    seq    any object supporting len(...) and slice-indexing
    N      a positive integer (default: L)
    X      a positive integer not greater than L (default: 1)
    """

    # All error-checking code omitted

    L = len(seq)       # length of seq
    assert 0 < X <= L

    if N is None: N = L
    assert 0 < N

    # A total of n subsequences will be yielded, the first r of which will
    # have length x + 1, and the remaining ones will have length x.

    # if we insist on using calculate()...
    # n, x = calculate(L, N, X)
    # r = L % n

    # ...but this entails separate computations of L//n and L%n; may as well
    # do both with a single divmod(L, n)
    n = min(L//X, N)
    x, r = divmod(L, n)

    start = 0
    stride = x + 1    # stride will revert to x when i == r
    for i in range(n):
        if i == r: stride = x
        finish = start + stride
        yield seq[start:finish]
        start = finish
    assert start == L

rawDescription: Split a file with no more than N chunks but with minimal length


text: some text 1

type: special

text: some text 2

text: some text 3

type: header

text: some text 4

text: some text 5

rawDescription: In Django template for mark next n elements


code:
import httplib
import sys
import urllib
from contextlib import closing

def call_closure_api(**kwargs):
    with closing(httplib.HTTPConnection('closure-compiler.appspot.com')) as conn:
        conn.request(
            'POST', '/compile',
            urllib.urlencode(kwargs.items()),
            headers={"Content-type": "application/x-www-form-urlencoded"}
        )
        return conn.getresponse().read()

call_closure_api(
    js_code=sys.argv[1],
    # feel free to introduce named constants for these
    compilation_level='WHITESPACE_ONLY',
    output_format='text',
    output_info='compiled_code'
)

rawDescription: Python library to access the Closure Compiler Service API


code:
import dis
dis.dis(compile('''\
if True:
    foo
else:
    pass
''', '<stdin>', 'exec'))
dis.dis(compile('''\
if True:
    foo
''', '<stdin>', 'exec'))

rawDescription: Is it best practice to include an else: pass statement at the end of a Python if or if/elif statement?


code: raw_input("Press Enter to exit")

rawDescription: Python time.sleep closes terminal

description: Python time.sleep closes terminal


code:
import inspect

def decallmethods(decorator, prefix='test_'):
  def dectheclass(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
      if name.startswith(prefix):
        setattr(cls, name, decorator(m))
    return cls
  return dectheclass

rawDescription: Applying python decorators to methods in a class


rawDescription: Matrix creation

description: Matrix creation


rawDescription: timing two algorithms (python) using timeit or time

description: Timing two algorithms (python) using timeit or time


code:
if __name__ == '__main__':
     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument('inputfile')
     args = parser.parse()
     with open(args.inputfile) as handler:
         for line in handler:
             print(line)

rawDescription: how to take a file as input stream in Python

description: Take a file as input stream in Python


code:
from os import remove
from shutil import move

remove('C:\\Users\\Tests.csv')
move('C:\\Users\\Test.txt', 'C:\\Users\\Tests.csv')

rawDescription: Force Overwrite in Os.Rename

description: Force Overwrite in Os.Rename


code:
composite_instance = Composite(component_instance)
composite_instance.composite_method(10)
composite_instance.composite_param_dict['a'] = 10
composite_instance.composite_method(10)

rawDescription: Using decorators in python to build a complex composite class from a set of simple component classes


code:
import my_class
MyClassA = my_class.MyClassA

ca = MyClassA()

rawDescription: Importing an own python file, Class not defined


rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


code:
def to_record(kvs):
    user, *vs = kvs  # For Python 2.x use standard indexing / splicing
    for item, value in vs:
        yield user, item, value

records = rdd.flatMap(to_record)

rawDescription: Convert a RDD of Tuples of Varying Sizes to a DataFrame in Spark


code:
from collections import Counter
def lone_sum(a, b, c):
    d = Counter([a, b, c])
    return sum(k for k in d if d[k]==1)

rawDescription: Python sum of non duplicate int

description: Python sum of non duplicate int


code:
from collections import OrderedDict
li= [11, 11, 2, 3, 4]
list(OrderedDict.fromkeys(li))

rawDescription: Removing repeated element from a list

description: Removing repeated element from a list


code:
hours, minutes = map(int, s.split(':'))
hours * 60 + minutes

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code:
imgfile = StringIO()
img.save(imgfile, format='PNG')
imagestring = imgfile.getvalue()

rawDescription: Converting binary file into PIL Image datatype in Google App Engine


code:
for line in fo:
    ...

rawDescription: why readline() is not efficient

description: Why readline() is not efficient


code: dict(zip(road,distance))

rawDescription: How to store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes?

description: Store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes