code:
totalSizeOf = lambda obj: sum(map(sys.getsizeof, explore(obj, set())))
def explore(obj, memo):
    loc = id(obj)
    if loc not in memo:
        memo.add(loc)
        yield obj
        # Handle instances with slots.
        try:
            slots = obj.__slots__
        except AttributeError:
            pass
        else:
            for name in slots:
                try:
                    attr = getattr(obj, name)
                except AttributeError:
                    pass
                else:
                    #yield from explore(attr, memo)
                    for bar in explore(attr, memo):
                        yield bar
        # Handle instances with dict.
        try:
            attrs = obj.__dict__
        except AttributeError:
            pass
        else:
            #yield from explore(attrs, memo)
            for bar in explore(attrs, memo):
                yield bar
        # Handle dicts or iterables.
        for name in 'keys', 'values', '__iter__':
            try:
                attr = getattr(obj, name)
            except AttributeError:
                pass
            else:
                for item in attr():
                    #yield from explore(item, memo)
                    for bar in explore(item, memo):
                        yield bar

rawDescription: Guppy/Heapy on Windows with Python 2.7.6


code:
import numpy as np
import itertools

arr = np.array([[[1,2], [3,4]],
                [[5,6], [7,8]]])

for p in itertools.permutations(arr.reshape(-1, 2)):
    print(np.array(p).reshape(arr.shape))

rawDescription: Numpy Permutations of a 3D Matrix

description: Numpy Permutations of a 3D Matrix


rawDescription: Python regex insert

description: Python regex insert


rawDescription: How to use scipy.optimize minimize_scalar when objective function has multiple arguments?

description: Use scipy.optimize minimize_scalar when objective function has multiple arguments


code:
keyStrings = { Key.CTRL  : "control-key",
               Key.ALT   : "alt-key",
               Key.SHIFT : "shift-key" }

print(keyStrings[myKey])

rawDescription: Printing (writing) Sikuli key constants

description: Printing (writing) Sikuli key constants


code:
from sqlalchemy import (
    Column,
    Table,
    Integer,
    Date,
    String,
    ForeignKey,
)

from sqlalchemy import create_engine

from sqlalchemy.orm import sessionmaker

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import relationship, backref

engine = create_engine('sqlite:///data.sqlite')
DBSession = sessionmaker(bind=engine)

Base = declarative_base()

class Match(Base):
    __tablename__ = 'data'

    id = Column(Integer, primary_key=True)
    date = Column(Date)
    tournament = Column(String)
    best_of = Column(Integer)
    score = Column(String)
    maps = relationship('Map')
    team1_id = Column(ForeignKey('team.id'))
    team2_id = Column(ForeignKey('team.id'))

    team1 = relationship('Team', primaryjoin='Match.team1_id == Team.id')
    team2 = relationship('Team', primaryjoin='Match.team2_id == Team.id')

class Map(Base):
    __tablename__ = 'map'

    id = Column(Integer, primary_key=True)
    match = Column(Integer, ForeignKey('data.id'))
    name = Column(String)
    score = Column(String)

lineup = Table('lineup',
               Base.metadata,
               Column('player_id', Integer, ForeignKey('player.id')),
               Column('team_id', Integer, ForeignKey('team.id')))

class Player(Base):
    __tablename__ = 'player'

    id = Column(Integer, primary_key=True)
    nickname = Column(String)

class Team(Base):
    __tablename__ = 'team'

    id = Column(Integer, primary_key=True)
    name = Column(String)

    players = relationship('Player', secondary=lineup, backref='teams')

rawDescription: SQLAlchemy relationships to same table

description: SQLAlchemy relationships to same table


code:
def update_binary_text(first,second):
    if buttonList[first][second]._photo == photo:
        buttonList[first][second]["image"] = photo1

# ...

def create_button(i, j):
    button = Button(game, borderwidth=0, highlightthickness=0, image=photo,
                    command = lambda i=i, j=j: update_binary_text(i,j))
    button._photo = photo
    return button

buttonList = [[create_button(i, j) for j in range(number)] for i in range(number)]

rawDescription: Tkinter Button with an If statement

description: Tkinter Button with an If statement


code:
import random

rand_cap = [chr(random.randint(65, 90)) for i in range(7)]
rand_small = [chr(random.randint(97, 122)) for i in range(7)]
rand_chars_list = rand_cap + rand_small

random.shuffle(rand_chars_list)

rand_chars = ''.join(rand_chars_list)

rawDescription: How to generate case insensitive string with random module

description: Generate case insensitive string with random module


rawDescription: How to change a Python 3 string into 'readable' text

description: Change a Python 3 string into 'readable' text


code:
old = np.random.random_integers(0, 100, size=(480, 640))
np.pad(old, pad_width=((0, 1), (0, 1)), mode='constant')
np.pad(old, pad_width=((0, 1), (0, 1)), mode='constant').shape

rawDescription: Numpy: add row and column

description: Numpy: add row and column


code:
# -*- coding: utf-8 -*-
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.maximize_window()

driver.get('https://polon.nauka.gov.pl/opi/aa/drh/zestawienie?execution=e1s1')
wait = WebDriverWait(driver, 30)

# paginate by 100
select = Select(driver.find_element_by_id("drhPageForm:drhPageTable:j_idt211:j_idt214:j_idt220"))
select.select_by_visible_text("100")

while True:
    # wait until there is no loading spinner
    wait.until(EC.invisibility_of_element_located((By.ID, "loadingPopup_content_scroller")))

    current_page = driver.find_element_by_class_name("rf-ds-act").text
    print("Current page: %d" % current_page)

    # TODO: collect the results

    # proceed to the next page
    try:
        next_page = driver.find_element_by_link_text(u"»")
        next_page.click()
    except NoSuchElementException:
        break

rawDescription: Mechanize and Python, clicking href="javascript:void(0);" links and getting the response back


code:
answer = 'yes'
print ("Please, think of a number between 1 and 200. I am about to try to guess it in 20 tries.")
while answer == "yes":
    NumOfTry = 20
    NumToGuess = 50
    LimitLow = 1
    LimitHigh = 200
    while NumOfTry != 0:
        try:
            print ("I try: ",NumToGuess)
            print ("Please type: 1 for my try is too high")
            print ("             2 for my try is too low")
            print ("             3 I guessed your number")
            HumanAnswer  = int (input("So did I guess right?"))
            if 1 < HumanAnswer > 3:
                print ("Please enter a valid answer. 1, 2 and 3 are the valid choice")
                NumOfTry = NumOfTry + 1
            if HumanAnswer == 1:
                LimitHigh = NumToGuess
                print ("Hmm, so your number is between ",LimitLow, "and ", LimitHigh)
                NumOfTry = NumOfTry - 1
                print (NumOfTry, "attempts left")
                NumToGuess = int (((LimitHigh - LimitLow)/2) + LimitLow)
                if NumToGuess <= LimitLow:
                    NumToGuess = NumToGuess + 1
                if LimitHigh - LimitLow == 2:
                    NumToGuess = LimitLow + 1
            elif HumanAnswer == 2:
                LimitLow = NumToGuess
                print ("Hmm, so your number is between ",LimitLow, "and ", LimitHigh)
                NumOfTry = NumOfTry - 1
                print (NumOfTry, "attempts left")
                NumToGuess = int (((LimitHigh - LimitLow)/2) + LimitLow)
                if NumToGuess <= LimitLow:
                    NumToGuess = NumToGuess + 1
                if LimitHigh - LimitLow == 2:
                    NumToGuess = LimitLow + 1
            elif HumanAnswer == 3:
                print ("Woo hoo! I won")
                NumOfTry = 0
                answer = input ('Do you want to play again? (yes=1/no=2)')
                if 'yes':
                    print ("ok")
                if 'no':
                    print ("thanks for playing")
        except:
            print("Out of tries!")

rawDescription: new to python, totally confused why this script wont work?

description: New to python, totally confused why this script wont work


code:
room_1_class_value = numpy.empty(len(room_1_indices[0]))
room_1_class_value.fill(1)

rawDescription: getting nonetype after using numpy.fill

description: Getting nonetype after using numpy.fill


code:
import StringIO
f = StringIO.StringIO() # create a file-like object
book = xlwt.Workbook()
sheet = book.add_sheet("XYZ")
book.save(f)

message = EmailMessage(subject="Subject", body="body",
         from_email="random@gmail.com",
         to=email_list)
message.attach('filename.xlsx', f.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") #get the stream and set the correct mimetype
message.send()

rawDescription: Create a File using xlwt and send email in Django application


code:
class PairEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Pair):
            return {"created": str(obj.created), "updated:": str(obj.updated), "find": obj.find, "replace": obj.replace, "tags": obj.tags, "rule": obj.rule}
        return json.JSONEncoder.default(self, obj)

rawDescription: simplejson + GAE serialize objects with fields names

description: Simplejson + GAE serialize objects with fields names


code:
class FileAlarmForm(ModelForm):

    def __init__(self,file,*args,**kwargs):
        super(FileAlarmForm, self).__init__(*args, **kwargs)
        p = Product.objects.get(id=file.product_id)
        self.fields['alarm_type'].widget = Select(attrs={'onchange':'updateAlarmImage'})
        self.fields['alarm_type'].queryset = Alarm.objects.filter(product=p)

rawDescription: Django populating a choice field

description: Django populating a choice field


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

xData=[5000,10000,20000, 15000]
yData=[20000,10000,5000, 15000]
radius_in_pixels=[100,200,100, 1000] # Circle takes radius as an argument. You could convert from area.

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

for x, y, r in zip(xData, yData, radius_in_pixels):
    ax.add_artist(Circle(xy=(x, y), radius = r))

plt.xlim(0, max(xData) + 200)
plt.ylim(0, max(yData) + 200)
plt.show()

rawDescription: How do I force scatter points real pixel values when plotting in pyplot/python?

description: Force scatter points real pixel values when plotting in pyplot/python


code: button2 = driver.find_element_by_xpath('//input[@value="Get Windspeed"]')

rawDescription: Accessing button using selenium in Python


code: predictedClassification = 1 if predictedClassification >= 0.5 else 0

rawDescription: More elegant way to do this?

description: More elegant way to do this


code:
sigma = np.ones(len(x))
sigma[[0, -1]] = 0.01
popt, pcov = curve_fit(model_func, x, y, p0=(0.1 ,1e-3, 0.1), sigma=sigma)

rawDescription: How to force specific points in curve fitting

description: Force specific points in curve fitting


code:
list1 = [ ['node1', 'pathA'], ['node2', 'pathA'], ['node3', 'pathB'], ['node4', 'pathC'], ['node5', 'pathA'] ]
result = [x for x in list1 if [y[1] for y in list1].count(x[1]) > 1]

rawDescription: create new list with duplicates of list in list - python

description: Create new list with duplicates of list in list - python


code:
from django.contrib.contenttypes.models import ContentType
model_type = ContentType.objects.get_for_model(modelA.field1)
model_type.model_class().objects.all() # this will get you all objects of the foreign key model

rawDescription: Django:how to access to ForeignKey's model?


rawDescription: String indexing - Why S[0][0] works and S[1][1] fails?


rawDescription: Python string format from current namespace


rawDescription: Python: check lists of variable lengths against a fixed "master" list of expected values


code:
data = []
for device in devices:
    data.append([device])
    for command in commands:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username="admin", password="test")
        stdin, stdout, stderr = ssh.exec_command(command)
        output= stdout.read()
        data[-1].append(output)
    data[-1] = tuple(data[-1])

rawDescription: Storing a nested FOR loop output in a 2D array in python


code:
#!/usr/bin/env python
import os, sys

print(os.path.basename(sys.argv[0]))

rawDescription: Detecting program's name Python 3

description: Detecting program's name Python 3


code:
import gettext

class MyClass(object):
    def __init__(self, locale_for_instance):
        self.lang = gettext.translation("appname", localedir, \
                                         locale=locale_for_instance)

    def some_method(self, arg):
        return self.lang.gettext("You called some method")

    def other_method(self, arg): # does the same thing
        _ = self.lang.gettext
        return _("You called some method")

rawDescription: Can I call and set the Python gettext module in a library and a module using it at the same time?

description: Call and set the Python gettext module in a library and a module using it at the same time


code:
kwargs = {whereconditionfield + "__" + whereoperator: arri}
myqs.objects.filter(**kwargs)

rawDescription: Can variables be used in a .filter of a queryset


rawDescription: Union of two variables to form a new one in Pandas Data Frame - Python


code:
import copy

queryset = sorted(
    chain(exercise_list),
    key=attrgetter('priority_score'),
    reverse=True)
newobj = copy.deepcopy(queryset)
recommendations.append(newobj)

rawDescription: Store the value of objects instead of a reference to the object itself


code:
print(chr(ord('a')+1))
# b

rawDescription: python "incrementing" a character string?

description: Python "incrementing" a character string


code:
L = [u'a\r\nb\r\nc\r\nd\r\ne']
L[0].split('\r\n')

rawDescription: textarea to list

description: Textarea to list


code:
def histeq(im,nbr_bins=256):
    """  Histogram equalization of a grayscale image.
         From http://programmingcomputervision.com/"""

    # get image histogram
    imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True)
    cdf = imhist.cumsum() # cumulative distribution function
    cdf = 1 * cdf / cdf[-1] # normalize (value component max is 1.0)

    # use linear interpolation of cdf to find new pixel values
    im2 = np.interp(im.flatten(),bins[:-1],cdf)

    return im2.reshape(im.shape), cdf

#equalise the intensity component
img_hsv[:,:,2], cdf = histeq(img_hsv[:,:,2])

#then convert back to RGB space
img_eq = colors.hsv_to_rgb(img_hsv)

rawDescription: Histogram Equalization based on HSI model


code:
greeting = "Hello World"

# Use this in versions prior to 2.6:
print("My first programm; %(greeting)s" % locals())

# Since Python 2.6, the recommended example is:
print("My first program; {greeting}".format(**locals()))

# Works in 2.x and 3.x:
from string import Template
print(Template("My first programm; $greeting").substitute(locals()))

rawDescription: GStrings in Python

description: GStrings in Python


code:
def very_very_long_function_name_that_we_want_to_test(argument):
     pass

# test:
testable = very_very_long_function_name_that_we_want_to_test

# This will call our "long function"
testable('test')

rawDescription: Can I remove the underscores from the name of a python test function

description: Remove the underscores from the name of a python test function


rawDescription: How to merge and split numpy array along the axis?

description: Merge and split numpy array along the axis


code:
import time

a=0
last_time_ms = int(round(time.time() * 1000))
while True:
    diff_time_ms = int(round(time.time() * 1000)) - last_time_ms
    if(diff_time_ms >= 4000):
        a += 1
        last_time_ms = int(round(time.time() * 1000))
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
            Intro.stop()
            TWD.stop()
    if a <= 3:
        screen.blit(pygame.image.load(images[a]).convert(),(0,0))
        Intro.play()
    if a == 4:
        Intro.stop()
        TWD.play()

    pygame.display.update()

rawDescription: Time delay in python/pygame without disrupting the game?


code:
parseme = "28-05-2014_02:44:32.630"

from datetime import datetime

datetime.strptime(parseme, '%d-%m-%Y_%H:%M:%S.%f')
Out[34]: datetime.datetime(2014, 5, 28, 2, 44, 32, 630000)

rawDescription: How to define a non ISO date parser in Python?

description: Define a non ISO date parser in Python


code:
import modA
import modB
import modC

rawDescription: Python dir() not displaying all modules in a package


code:
import bisect

class SortedList(list):
    def __contains__(self, elem):
        idx = bisect.bisect_left(self, elem)
        return idx < len(self) and self[idx] == elem

rawDescription: python implicit binary search

description: Python implicit binary search


code:
driver = webdriver.Firefox()
print('Firefox started')
print('Iterating links')
connection = pymysql.connect(host='.com', user='', password='', db='', cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor2:
    cursor2.execute("Delete from todaysmarkets")
for link in links:
    try:
        print('Fetching from link: ' + base + link)
        driver.get(base+link)
        print('Waiting for all the data to get loaded')
        element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CLASS_NAME,"current")))
        print('Parsing page')
        tree = html.fromstring(driver.page_source)
        names = tree.xpath('//*[@id="lpTable1"]/div[h3[text()=" Goal Supremacy and Goal Markets "]]/div/table/tbody/tr[not(@style="display: none;")]/td/span/text()')
        print(str(len(names)) + ' markets found')
        sells = tree.xpath('//*[@id="lpTable1"]/div[h3[text()=" Goal Supremacy and Goal Markets "]]/div/table/tbody/tr[not(@style="display: none;")]/td[3]/button/text()')
        buys = tree.xpath('//*[@id="lpTable1"]/div[h3[text()=" Goal Supremacy and Goal Markets "]]/div/table/tbody/tr[not(@style="display: none;")]/td[4]/button/text()')
        if(len(buys) != len(sells) or (len(buys) == 0 or len(sells) == 0)):
            print('Error fetching markets either suspended or does not exist')
            continue
        print('Putting markets into excel file')
        with connection.cursor() as cursor:
            for i in range(0, len(names)):
                cursor.execute(("INSERT INTO todaysmarkets(URL,Name,value) VALUES(%s,%s,%s)"), (base+link,names[i], str((float(sells[i])+float(buys[i]))/2.0)))

           # ws.append([names[i], str((float(sells[i])+float(buys[i]))/2.0)])
    finally:
        print('Saving the file with name markets.xlsx')

# Close driver at the end of the work
driver.quit()

rawDescription: python - closing firefox browser down when complete

description: Python - closing firefox browser down when complete


code:
result,data = self.M.uid('search', None, '(SENTSINCE {date})'.format(date=date),
    ('TO example+test1@gmail.com'))

rawDescription: Python IMAP - Read Gmail with '+' in email address


code:
with open('company_inf1.csv', 'rb') as inf :
    reader = csv.reader(inf, delimiter=',')
    reader.next() #skip header
    name, date, indus, nike1, nike2, nike3, paid, abbr = row
    print(name, date, indus, [nike1, nike2, nike3], paid, abbr)

rawDescription: How to remove Parentheses from string

description: Remove Parentheses from string


code: df[df.duplicated('c1') | df.duplicated('c1', take_last=True)]

rawDescription: Remove non-duplicated entries

description: Remove non-duplicated entries


code:
l = [1, 4, 22, 33]
dct = {1: 'red', 17: 'green', 33: 'blue'}  # don't name your own dictionary dict
[dct[16*((x-1)//16)+1] for x in l]

rawDescription: Finding values in a dictionary if key matches in a range


code:
def handle_CLIENT(self, data):
    self.transport.pauseProducing()
    def sendFirstLine():
        self.sendLine(r1.raw)
    def sendSecondLine():
        self.sendLine(r2.raw)
        # now that we've sent the second line we can accept more requests; if
        # we accept requests in the middle, we might send responses interleaved
        # with each other, which will probably break your client
        self.transport.resumeProducing()

    reactor.callLater(0, sendFirstLine)
    reactor.callLater(0.5, sendSecondLine)

rawDescription: Twisted multiple responses for single request


code:
cur_hour = None
for line in lines:
    dt = dateutil.parser.parse(line[0])
    hour = dt.hour
    if hour != cur_hour:
        outFile = open("%d.00.00.txt" % hour, "w")
        cur_hour = hour
    print >> outFile, ', '.join(line)

rawDescription: Saving the data for each hour into separate txt files?


code:
from django.shortcuts import redirect

urlpatterns = patterns('',
    url(r'^main.php$', php_redirects, name='php_main')
)

def php_redirects(request):
    page = request.GET.get('page')
    location = request.GET.get('location')
    # look up URL pattern to redirect to.
    targets = {
        '04rent': 'some_url_pattern_name',
    }
    redirect(target[page], location=location)

rawDescription: Django reg exp in urls.py

description: Django reg exp in urls.py


code: r'abc\dev\t'

rawDescription: How to write string literals in python without having to escape them?

description: Write string literals in python without having to escape them


code:
for column in ('name', 'synopsis', 'something', 'other'):
    if not getattr(title, column):
        setattr(title, column, data[column])

rawDescription: DRY version of python if statements

description: DRY version of python if statements


code:
degree = len(z) - 1
vol_calibrated = sum(vol**(degree-i) * coeff for i, coeff in enumerate(z))

rawDescription: Input into a polynomial regression formula with Python


code:
for virus in viruses[:]:
    # do stuff
    viruses.remove(virus)  # remove "virus" from the original list

rawDescription: Remove Element From List Without Index

description: Remove Element From List Without Index


code:
name = 'Bob'
return render.index(name)

rawDescription: How To Build a Template Engine

description: How To Build a Template Engine


code:
P = sniff(filter='ip6', count=0)
UDP in P
IPv6 in P
UDP in P[0]
IPv6 in P[0]
P[0][IPv6]
ICMPv6EchoRequest in P[0]
ICMPv6EchoRequest

rawDescription: Scapy - how to check packet type of sniffed packets


code:
def get_top_10_so():
    mylist = []
    for i in range(1000):
        val, df = gen_df()
        if len(mylist) < 10:
            mylist.append((val, df))
        else:
            mylist.sort(reverse=True)
            if mylist[-1][0] < val:
                mylist.pop()
                mylist.append((val, df))
    return mylist

def get_top_10_mine():
    mylist = [None] * 1000
    for i in range(1000):
        mylist[i] = gen_df()
    mylist.sort(key=lambda tup: tup[0], reverse=True)
    return mylist[:10]

rawDescription: Retain top-N elements as we loop across all elements


code:
with open("/path/to/myfile.txt", "rb") as myfile:
     data_to_read = "".join(myfile.readlines()[1:])
     ...

rawDescription: How do I read a text file into a string variable in Python starting at the second line?

description: Read a text file into a string variable in Python starting at the second line


rawDescription: How to select the rows where a condition is satisfied

description: Select the rows where a condition is satisfied


code:
import numpy as np
a = np.array([[1, 2, 8], [8, 2, 7], [7, 2, 5]])
np.insert(np.diff(a), 0, 0, axis=1)

rawDescription: subtraction operation on multidimensional arrays

description: Subtraction operation on multidimensional arrays


code:
class csv(CsvModel):
    mfr_code = adaptor_fields.CharField()
    main_photo_url = adaptor_fields.CharField()
    name = adaptor_fields.CharField()
    product_url = adaptor_fields.CharField()
    vendor = adaptor_fields.CharField(prepare=get_or_create_vendor)
    type = adaptor_fields.CharField(prepare=get_or_create_type)
    subtype = adaptor_fields.IgnoredField()
    description = adaptor_fields.CharField()
    specs = adaptor_fields.CharField()
    tags = adaptor_fields.CharField()
    stock = adaptor_fields.IntegerField(prepare=get_stock_value)
    price = adaptor_fields.IntegerField(prepare=format_usd)

    class Meta:
        delimiter = ','
        dbModel = Product
        update = {
            'keys': ['name']   # or mfr_code, main_photo_url, etc..., price
        }

rawDescription: Django-adaptors: How to use correctly the Update meta option


rawDescription: How do I repeat a single value of a list using python

description: Repeat a single value of a list using python


code:
from mock import Mock
real = ProductionClass()
real.method = Mock(return_value=3)
real.method(3, 4, 5, key='value')
real.method.assert_called_with(3, 4, 5, key='value')

rawDescription: Mock an object in a method that is not a parameter in python


code:
#!/usr/bin/env python3
import sys
from subprocess import Popen, PIPE, DEVNULL

with Popen([sys.executable, '-i'], stdin=PIPE, stdout=PIPE, stderr=DEVNULL,
           universal_newlines=True) as process:
    for i in range(10):
        print("{}**2".format(i), file=process.stdin, flush=True)
        square = process.stdout.readline()
        print(square, end='')

rawDescription: Real time read from subprocess.stdout on Windows


code: myList = [eval(str) for str in myList]

rawDescription: Get a list that is written as a string

description: Get a list that is written as a string


code:
myclip.write_videofile("test_1.webm", bitrate="50k") # low quality.
myclip.write_videofile("test_2.webm", bitrate="50000k") # high quality.

rawDescription: cliping a webm file using moviepy and ffmpeg parameters

description: Cliping a webm file using moviepy and ffmpeg parameters


code:
def checkboxes (self, state):
    suffix = self.sender().objectName()[-2:]
    enable = state == QtCore.Qt.Checked
    for prefix in 'mod', 'min', 'max':
        getattr(self, prefix + suffix).setEnabled(enable)

rawDescription: Python pyqt sender state handling

description: Python pyqt sender state handling


code:
actors={}
total=[]

with open('ID_actor','r') as f1:
    for line in f1:
        id, name = line.split()
        actors[name] = int(id)

with open('the other file','r') as f2:
    input = f2.read()
    items = input.split('#')
    for i in range(len(items)):
        items[i] = str(actors.get(name,name))

with open('m.dat','w') as f3:
    f3.write( '#'.join(items) )

rawDescription: giving unique values to string list

description: Giving unique values to string list


code:
#Import Tkinter
from Tkinter import *

#Main Frame
class Application(Frame):
    def __init__(self, master):  #initialize the grid and widgets
        Frame.__init__(self,master)
        self.grid()
        self.redFUN() #initialize the red frame's Function
        self.greenFUN() #initialize the green frame's Function
        self.widgets() #To show that you can still place non-Frame widgets
    def widgets(self):
        self.mylabel = Label (self, text = "Hello World!")
        self.mylabel.grid()
    def redFUN(self): #The 'self' means that it is an instance of the main frame
        #Init the red frame
        self.redFrame = Frame(root, width = 100, height = 50,pady = 5,
                              bg = "red")
        self.redFrame.grid()

    def greenFUN(self): #Child of the mainframe
        self.greenFrame = Frame(root, width = 100, height = 50,pady = 5,
                          bg = "green") #it is green!
        self.greenFrame.grid()

#These lines of code are used for the grid
root = Tk()
root.title("Frame Example")
root.geometry("300x300")
app = Application(root)

root.mainloop()

rawDescription: How to place widgets into different frames in Tkinter, using OOP

description: Place widgets into different frames in Tkinter, using OOP


code:
with open(os.path.abspath(os.path.join(os.path.dirname(__file__),'static', 'result', file_name + '_issues.json')), 'r+') as nInfo:
  count = 0
  for data in file_data:
      count += 1
      if count == 1:
        nInfo.seek(-2, 2)
      if file_data.index(data) != len(file_data):
        nInfo.write(',')
      nInfo.write(json.dumps(data, default=lambda a: '[%s,%s]'(str(type(a)), a.pk)))
  nInfo.write(']')
  nInfo.write(' ')

rawDescription: How to update the existing json file with json data python

description: Update the existing json file with json data python


code: Atemp = A[A != 0]

rawDescription: Efficient way to create an array of nonzero values in a numpy tensor?


code:
import itertools
x='abc'
y='123'
[letter+num for letter,num in itertools.product(x,y)]

rawDescription: Some ways to combine sets in python

description: Some ways to combine sets in python


rawDescription: bash commands from within python

description: Bash commands from within python


code:
import time

# ...

def readCoefficients(self):
    global a0_MSB;
    global a0_LSB;
    global b1_MSB;
    global b1_LSB;
    global b2_MSB;
    global b2_LSB;
    global c12_MSB;
    global c12_LSB;

    max_retries = 15

    a0_MSB = self.readretry(Pressure.MPL115A2_REGISTER_A0_COEFF_MSB+0, max_retries)
    a0_LSB = self.readretry(Pressure.MPL115A2_REGISTER_A0_COEFF_LSB+0, max_retries)

    b1_MSB = self.readretry(Pressure.MPL115A2_REGISTER_B1_COEFF_MSB+0, max_retries)
    b1_LSB = self.readretry(Pressure.MPL115A2_REGISTER_B1_COEFF_LSB+0, max_retries)

    b2_MSB = self.readretry(Pressure.MPL115A2_REGISTER_B2_COEFF_MSB+0, max_retries)
    b2_LSB = self.readretry(Pressure.MPL115A2_REGISTER_B2_COEFF_LSB+0, max_retries)

    c12_MSB = self.readretry(Pressure.MPL115A2_REGISTER_C12_COEFF_MSB+0, max_retries)
    c12_LSB = self.readretry(Pressure.MPL115A2_REGISTER_C12_COEFF_LSB+0, max_retries)

    def readretry(self, address, max_retries):
        for i in range(max_retries):
            try:
                return Pressure.bus.read_byte_data(
                    Pressure.MPL115A2_ADDRESS,
                    address
                )
            except IOError as e:
                # print(e)
                time.sleep(0.1)
        else:
            raise IOError("Reading failed after multiple tries")

rawDescription: Handle multiple IO errors

description: Handle multiple IO errors


code: date, color, quantity = line[breakpoint:].split()

rawDescription: Split python string by space starting at certain character


code: results = [[item.strip().strip("\xa0") if item is not None else None for item in sublist] for sublist in results]

rawDescription: Removing characters from a list

description: Removing characters from a list


code:
for m in MyList:
    MyLargeRec[m][6]+=1

rawDescription: Conditionally add 1 to int element of a NumPy record array


code:
import ast
x = ast.literal_eval(stdin.readline())

rawDescription: python store lines from stdin directly to list objects

description: Python store lines from stdin directly to list objects


code:
class MyDialog(QDialog):
    def __init__(self, strt, parent=None):
        QDialog.__init__(self, parent)
        self.smallWidgets = list()
        self.setMinimumWidth(450)
        self.setMinimumHeight(600)

        self.setupLayout()
        self.setupScrollArea()
        self.addWidgetButton = QPushButton(self.containerWidget)
        self.addWidgetButton.setText("Add new widget")
        self.layout.addWidget(self.addWidgetButton)

        self.connect(self.addWidgetButton, QtCore.SIGNAL("clicked()"), self.addNewWidget)

    def setupLayout(self):
        self.containerWidget = QWidget(self)
        self.widgetHeight = 120
        self.containerWidget.setGeometry(QRect(0,0,450,self.widgetHeight))

        self.layout = QVBoxLayout()
        self.containerWidget.setLayout(self.layout)

    def setupScrollArea(self):
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scrollArea.setMaximumWidth(440)
        self.scrollArea.setMinimumHeight(600)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setWidget(self.containerWidget)

    def addNewWidget(self):
        newWidget = SmallWidget(self.containerWidget)
        widgetPosition = len(self.smallWidgets)
        self.layout.insertWidget(widgetPosition, newWidget)
        self.smallWidgets.append(newWidget)

        self.widgetHeight += 80
        self.containerWidget.resize(450,self.widgetHeight)

rawDescription: Qt Widget with slider

description: Qt Widget with slider


code:
self.row=Frame(root)
self.programs=(('description1',p1),('description2',p2))
for naem, callback in self.programs:
    self.b = Button(self.row, text=self.program[0],
                    command=lambda callback=callback: callback())  # <---
    self.row.pack(side=TOP, fill=X, padx=5, pady=5)
    self.b.pack(side=LEFT, padx=5, pady=5)

rawDescription: Tkinter Button commands in loops execut always last command


rawDescription: Reshaping a numpy array

description: Reshaping a numpy array


code:
import csv

with open('input_file.txt') as f:
   reader = csv.reader(f)
   names = [line[0] for line in reader]

with open('new_file.txt','w') as f:
   for name in names:
      f.write('{0}\n'.format(name))

rawDescription: Python Regex Find Pattern, Remove Rest of String, Write new String to File


code:
with open("input1.txt") as f, open("input2.txt") as f2,open("output.txt","w") as f3:
    f2.next() # skip header to avoid writing  A B C twice
    for line in f:
        f3.write(line)
    f3.write("\n") # separate last line from file 1 and first of file 2
    for line in f2:
        f3.write(line)

rawDescription: Python: Joining files in a list

description: Python: Joining files in a list


code:
@cherrypy.expose
def interlocked(self, _=None):
    cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
    if _:
        data = 'retry: 400\ndata: ' + str(self.isInterlocked) + '\n\n'
        return data
    else:
        def content():
            data = 'retry: 400\ndata: ' + str(self.isInterlocked) + '\n\n'
            return data
        return content()
interlocked._cp_config = {'response.stream': True, 'tools.encode.encoding':'utf-8'}

rawDescription: How to have multiple clients listen to a server sent event?

description: Have multiple clients listen to a server sent event


code: getattr(obj, 'func')(*arr)     # where obj is the namespace that hold func

rawDescription: PHPs call_user_func_array in Python

description: PHPs call_user_func_array in Python


code:
def guarded_op():
    with lock:
        print("Now doing 1 op")
        another_op()

def another_op():
    with lock:
        print("Now did the another op")

rawDescription: How does python Rlock work and what is the owner of Rlock?


code: __init__(self, other=None)

rawDescription: how to view class variables from an inner class in python

description: View class variables from an inner class in python


code:
class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)

    def __getitem__(self, key):
        return super(CaseInsensitiveDict, self).__getitem__(key.lower())

rawDescription: Case insensitive dictionary

description: Case insensitive dictionary


code:
a = input("Letter: ")
b = input("Input: ")
a=a.lower()
b=b.lower()
words = [word for word in b.split() if a in word]
print(len(words))
print(' '.join(words))

rawDescription: Counting words in a String in Python

description: Counting words in a String in Python


code:
for name, value in request.POST.iteritems():
    ModelName(**dict( [ (name, value) ] )).save()

rawDescription: Django, save data from form without having to manually set each field to save?


code:
df = pd.DataFrame(list(range(5)), index=pd.date_range('10/1/14', periods=5))
print(df.to_csv(date_format='%d-%b_%Y'))

rawDescription: Pandas to_csv -- date formatting other than 2 digits


code:
for index, row in df.iterrows():
    rownum = 1
    for cell in row:
        if index==5 and rownum==5:
           do_stuff()
        rownum+=1

rawDescription: If cell[2,5] is not cell[5,5] in pandas (not value but cell)


code:
level = {
    1: logging.ERROR,
    2: logging.WARNING,
    3: logging.INFO,
    4: logging.DEBUG
}.get(opts.verbosity, logging.DEBUG)

rawDescription: Python: How to logging.setLevel verbosity from OptionParser type='count'?


code:
from flaskext.sqlalchemy import SQLAlchemy
import psycopg2
import psycopg2.extras

class _SQLAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        """This method adds option to support hstore on psycopg2"""

        if info.drivername == "postgres":
            def _connect():
                conn = psycopg2.connect(user=info.username,
                                        host=info.host,
                                        port=info.port,
                                        dbname=info.database,
                                        password=info.password)
                psycopg2.extras.register_hstore(conn)
                return conn
            options["creator"] = _connect
        SQLAlchemy.apply_driver_hacks(self, app, info, options)

rawDescription: How to use Postgres' Hstore column with flask-sqlalchemy?

description: Use Postgres' Hstore column with flask-sqlalchemy


rawDescription: Regex replacing part of link

description: Regex replacing part of link


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(projection='ortho',
              lat_0=0, lon_0=0)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()

x, y = map(0, 0)

map.plot(x, y, marker='D',color='m')

plt.show()

rawDescription: How to visualize spatial data using python

description: Visualize spatial data using python


code:
uniques = np.unique(list1)
shuffled = uniques.copy()
np.random.shuffle(shuffled)

result = list2.copy()
for orig, new in zip(uniques, shuffled):
    result[np.where(list1==orig)] = list2[np.where(list1==new)]

rawDescription: python: shuffle list in respect to other attribute

description: Python: shuffle list in respect to other attribute


code:
from collections import Counter
list((Counter(l2) - Counter(l1)).elements())

rawDescription: Faster way to get the difference of two lists without set


code:
import json
obj = json.loads('{"a": 12, "b": null}')
obj

rawDescription: Scraping a javascript / json object from a webpage using BeautifulSoup?


code:
url = urllib.urlopen('http://www.stackoverflow.com/')
code = url.getcode()

rawDescription: How to get HTTP return code from python urllib's urlopen?

description: Get HTTP return code from python urllib's urlopen


rawDescription: Get a python map with the title of the column and the column of data from a data file


code:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np

#dummy data
x = 8
y = 15
mat = []
mat.append(np.arange(x * y).reshape((x, y)) / float(x * y) )
mat.append(np.arange(x * y).reshape((y, x)).T / float(x* y))
mat.append(np.arange(y) * np.arange(x)[:,np.newaxis] / float(99))

# NOTE: this data is approximately in the RGB range. If yours isn't, normalize,
# here or in your makeRGB function.
# (The colormap normalizes single-valued data).

fig, axs = plt.subplots(figsize=(7,4), nrows=3, ncols=3,
                        gridspec_kw={'hspace':0.6})

axs[0,0].imshow(mat[0], cmap='Reds', interpolation='nearest')
axs[0,1].imshow(mat[1], cmap='Greens', interpolation='nearest')
axs[0,2].imshow(mat[2], cmap='Blues', interpolation='nearest')
axs[0,0].set_xlabel('Reds Colormap')
axs[0,1].set_xlabel('Greens Colormap')
axs[0,2].set_xlabel('Blues Colormap')

def asOneHue(mat, hue):
    """
    Use a single-valued matrix to represent one hue in a RGB file.'
    """
    RGBout = np.zeros((len(mat),len(mat[0]),3))
    RGBout[:,:,i] = mat
    return RGBout

for i in (0,1,2):
    axs[1,i].imshow(asOneHue(mat[i],i))
axs[1,0].set_xlabel('Reds bitmap')
axs[1,1].set_xlabel('Greens bitmap')
axs[1,2].set_xlabel('Blues bitmap')

# different ways to combine 3 values
def makeRGB0(mats):
    RGBout = np.zeros((len(mats[0]),len(mats[0][0]),3))
    #RGBout = np.ones((len(mats[0]),len(mats[0][0]),3))
    for i in (0,1,2):
        RGBout[:,:,i] = mats[i]
    return RGBout

axs[2,0].imshow(makeRGB0(mat))
axs[2,0].set_xlabel('Color layers')

def makeRGB1(mats):
    RGBout = np.zeros((len(mats[0]),len(mats[0][0]),3))
    i,j,k = RGBout.shape

    for x in range(i):
        for y in range(j):
            RGBout[x,y] = (mats[0][x][y] / 2,
                           mats[1][x][y],
                           1 - mats[2][x][y])
    return RGBout

axs[2,1].imshow(makeRGB1(mat))
axs[2,1].set_xlabel('Algebraic')

def makeRGB2(mats):
    RGBout = np.zeros((len(mats[0]),len(mats[0][0]),3))
    i,j,k = RGBout.shape
    for x in range(i):
        for y in range(j):
            if mats[0][x][y] > .8:
                RGBout[x,y] = (mats[0][x][y],
                               0,
                               0)
            elif mats[1][x][y] > .8:
                    RGBout[x,y] = (0,
                                   mats[1][x][y],
                                   0)
            else:
                    RGBout[x,y] = (mats[0][x][y],
                                   mats[1][x][y],
                                   mats[2][x][y])
    return RGBout

axs[2,2].imshow(makeRGB2(mat))
axs[2,2].set_xlabel('If-else')

plt.show()

rawDescription: Custom coloration for matrix in matplotlib


code:
import csv

total = 0
zeros = 0
ones = 0
with open('path/to/file') as infile:
    for row in csv.reader(infile):
        total += 1
        if row[-1] == '0': zeros += 1
        if row[-1] == '1': ones += 1

# do some division to calculate priors

rawDescription: Count how many row with last item is 1 or 0 in CSV file Python


code:
from flask import Flask, redirect, request, render_template
app = Flask("app_name")

@app.route('/', methods=["GET", "POST"])
def login_route():
    if request.method == "GET":
        return render_template("login_page.html")
    elif request.method == "POST":
        # Login user
        return redirect("main_page", code=303)

@app.route("/")
def main_page():
    return "I'm the main page."

app.run(host="0.0.0.0", port=5001)

rawDescription: How to route user to another url Jinja

description: Route user to another url Jinja


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

fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = np.array([5,5,5,5,10,10,10,10,15,15,15,15,20,20,20,20])
X = sequence_containing_x_vals.reshape((4,4))

sequence_containing_y_vals = np.array([1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4])
Y = sequence_containing_y_vals.reshape((4,4))

sequence_containing_z_vals = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
Z = sequence_containing_z_vals.reshape((4,4))

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.hot)

pyplot.show()

rawDescription: Connect points in a three dimensional plot


code:
#! /usr/bin/python3.2

def trackable (cls):
    cls._tracked = {}

    oSetter = cls.__setattr__
    def setter (self, k, v):
        try: self.initialized
        except: return oSetter (self, k, v)
        try: self.k
        except:
            if not self in self.__class__._tracked:
                self.__class__._tracked [self] = []
            self.__class__._tracked [self].append (k)
        return oSetter (self, k, v)
    cls.__setattr__ = setter

    oInit = cls.__init__
    def init (self, *args, **kwargs):
        o = oInit (self, *args, **kwargs)
        self.initialized = 42
        return o
    cls.__init__ = init

    oGetter = cls.__getattribute__
    def getter (self, k):
        if k == 'tracked': return self.__class__._tracked [self]
        return oGetter (self, k)
    cls.__getattribute__ = getter

    return cls

@trackable
class Team:
    def __init__ (self, name, region):
        self.name = name
        self.region = region

#set name and region during initialization
t = Team ('A', 'EU')

#set rank and ELO outside (hence trackable)
#in your "aggregate" functions
t.rank = 4 # a new team attribute
t.ELO = 14 # a new team attribute

#see witch attributes have been created after initialization
print (t.tracked)

rawDescription: Python: showing attributes assigned to a class object in the class code


code:
def stricmp(str1, str2):
    str1 = str1.lower()
    str2 = str2.lower()
    if str1 == str2:
        return 0
    elif str1 < str2:
        return -1
    else:
        return 1

db = sqlite3.connect(':memory:')
# SQLite's default NOCASE collation is ASCII-only
# Override it with a (mostly) Unicode-aware version
db.create_collation('NOCASE', stricmp)

rawDescription: Sort order in SQLite3 with umlauts

description: Sort order in SQLite3 with umlauts


code:
if request.method=='POST':
    url = request.form['url']
    maxDepth = request.form['depth']
    numberOfRelated = request.form['numberOfRelated']
    values = crawling(url,maxDepth,numberOfRelated)
    return render_template('index.html',var=values) # 1
return render_template('index.html',var=values) # 2

rawDescription: How to call a different render after a form submission

description: Call a different render after a form submission


code:
import os
import os.path
def get_dir_md5(dir_root):
    """Build a tar file of the directory and return its md5 sum"""

    hash = hashlib.md5()
    for dirpath, dirnames, filenames in os.walk(dir_root, topdown=True):

        dirnames.sort(key=os.path.normcase)
        filenames.sort(key=os.path.normcase)

        for filename in filenames:
            filepath = os.path.join(dirpath, filename)

            # If some metadata is required, add it to the checksum

            # 1) filename (good idea)
            # hash.update(os.path.normcase(os.path.relpath(filepath, dir_root))

            # 2) mtime (possibly a bad idea)
            # st = os.stat(filepath)
            # hash.update(struct.pack('d', st.st_mtime))

            # 3) size (good idea perhaps)
            # hash.update(bytes(st.st_size))

            f = open(filepath, 'rb')
            for chunk in iter(lambda: f.read(65536), b''):
                hash.update(chunk)

    return hash.hexdigest()

rawDescription: Determine whether any files have been added, removed, or modified in a directory


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

x, y=range(10), range(10)
sca=plt.scatter(x,y)
raw_input()
sca._sizes=(5+np.arange(10))*10 #you can set you markers to different sizes
plt.draw()

rawDescription: Update marker sizes of a scatter plot

description: Update marker sizes of a scatter plot


code:
def fill(dir, x, y):
    base = matrix[y][x]
    if x < cols-1:
        best = base + cache[2, x + 1, y]
    else:
        best = base
    if dir != 0 and y > 0:
        best = max(best, base + cache[1, x, y - 1])
    if dir != 1 and y < rows - 1:
        best = max(best, base + cache[0, x, y + 1])
    cache[dir, x, y] = best

def maxsum(dir, x, y):
    for i in range(cols - 1, -1, -1):
        for j in range(rows - 1, -1, -1):
            fill(0, i, j)
        for j in range(rows):
            fill(1, i, j)
        for j in range(rows):
            fill(2, i, j)
    return cache[dir, x, y]

rawDescription: How do i convert the following recursive dp to iterative

description: Convert the following recursive dp to iterative


code: daten, werte = (list(t) for t in zip(*sorted(zip(daten, werte), key=lambda x : datetime.datetime.strptime(x[0], "%d. %b %Y"))))

rawDescription: sorting two lists depending on each other, one with dates (python)

description: Sorting two lists depending on each other, one with dates (python)


rawDescription: I how can I return objects in Django?

description: I how can I return objects in Django


code:
import logging
from types import FunctionType, MethodType

logger = logging.getLogger(__name__)
applied_patches = []

class PatchingError(Exception):
    pass

def patch(subcls, cls):
    if not subcls in applied_patches:
        logger.info("Monkeypatching %s methods into %s", subcls, cls)
        for methodname in subcls.__dict__:
            if methodname.startswith('_'):
                logger.debug('Skipping methodname %s', methodname)
                continue
            # TODO treat modified init
            elif hasattr(cls, methodname):
                raise PatchingError(
                    "%s alrady has methodname %s, cannot overwrite!",
                    cls, methodname)
            else:
                method = getattr(subcls, methodname)
                logger.debug("Adding %s %s", type(method), methodname)
                method = get_raw_method(methodname, method)
                setattr(cls, methodname, method)
        applied_patches.append(subcls)

def get_raw_method(methodname, method):
    # The following wouldn't be necessary in Python3...
    # http://stackoverflow.com/q/18701102/321973
    if type(method) == FunctionType:
        logger.debug("Making %s static", methodname)
        method = staticmethod(method)
    else:
        assert type(method) == MethodType
        logger.debug("Un-bounding %s", methodname)
        method = method.__func__
    return method

rawDescription: Should a plugin adding new instance-methods monkey-patch or subclass/mixin and replace the parent?


rawDescription: Replacing all the hyphens in xml tags with underscore using BeautifulSoup in python


code:
texts = [text1, text2]
counts = [Counter(text) for text in texts]
all_words = sorted(set().union(*counts))
vecs = [[count.get(word, 0) for word in all_words] for count in counts]
vecs[0]
vecs[1]

rawDescription: Fill and align vector with 0

description: Fill and align vector with 0


code:
def f_FactorialTailZeros(v_Num):
    if v_Num < 5:
        return 0
    return v_Num // 5 + f_FactorialTailZeros(v_Num // 5)

rawDescription: Python Better Way to Express This Recursive Function


code:
from collections import Counter
[x*c for x,c in Counter([1, 2, 1, 3, 3]).items()]

rawDescription: python: sum similar values in list

description: Python: sum similar values in list


code:
def expand(order, kappa, theta):
    n = np.arange(order)
    return np.sum((kappa + n/2 + (-1)**n)*np.cos(n*theta/2) -
                  n/2*np.cos((n-4)*theta/2))

rawDescription: Function specific expansion series

description: Function specific expansion series


code:
def multiply_digits(lst):
    res = []
    for x in lst:
        if res and res[-1] * x < 10:
            res[-1] *= x
        else:
            res.append(x)
    return res

rawDescription: Multiply digits in list

description: Multiply digits in list


code:
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail

class SendEmail(webapp.RequestHandler):
    def post(self):
        name = self.request.get('name', '')
        email = self.request.get('email', '')
        tempSubject = self.request.get('subject', '')
        msg = self.request.get('message', '')

        if name is None:
            self.response.out.write("Error: You did not enter a name.")
        elif email is None:
            self.response.out.write("Error: You did not enter an email.")
        elif tempSubject is None:
            self.response.out.write("Error: You did not enter a subject.")
        elif msg is None:
            self.response.out.write("Error: You did not enter a message.")
        else:
            _subject = "Message from: " + name + ", Re: " + tempSubject
            msg += "\n\nI can be reached at "
            msg += email

            message = mail.EmailMessage(sender = "foo@bar.com", to = "bar@foo.com")
            message.subject = _subject
            message.body = msg
            message.send()

            self.redirect('/')

def runApp():
    application = webapp.WSGIApplication([('/email', SendEmail)], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    runApp()

rawDescription: Python Error while using Google Apps Engine


code:
import nltk
nltk.word_tokenize("Hello! Hi, I am debating this predicament called life. Can you help me?")

rawDescription: need help with splitting a string in python

description: Need help with splitting a string in python


code:
class ContactDetailView(PostMessageView):
    template_name = 'my_home/contact_detail.html'

    @property
    def url_redirect(self):
        return self.request.build_absolute_uri(self.request.path)

rawDescription: Python beginner with class variables

description: Python beginner with class variables


rawDescription: Python3: How to print an item in a string of a list in a data structure


rawDescription: Issue combining columns in Dataframe?

description: Issue combining columns in Dataframe


rawDescription: Python regular expression: find "com" or "org"


code:
import win32ui
import win32gui
import win32con
import win32api

ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)

large, small = win32gui.ExtractIconEx("C:\Program Files (x86)\Malwarebytes' Anti-Malware\mbam.exe",0)
win32gui.DestroyIcon(small[0])

hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap( hdc, ico_x, ico_x )
hdc = hdc.CreateCompatibleDC()

hdc.SelectObject( hbmp )
hdc.DrawIcon( (0,0), large[0] )

hbmp.SaveBitmapFile( hdc, 'icon.bmp')

rawDescription: How to extract 32x32 icon bitmap data from EXE and convert it into a PIL Image object?

description: Extract 32x32 icon bitmap data from EXE and convert it into a PIL Image object


code:
df['days'] = df.index.get_level_values('date').days_in_month
df

rawDescription: iterate through each index item in level=1 in multi-index pandas

description: Iterate through each index item in level=1 in multi-index pandas


code:
# Reading credentials
store = oauth2client.file.Storage(cred_path)
credentials = store.get()

# Writing credentials
creds = client.AccessTokenCredentials(access_token, user_agent)
creds.access_token = access_token
creds.refresh_token = refresh_token
creds.client_id = client_id
creds.client_secret = client_secret

# For some reason it does not save all the credentials,
# so write them to a json file manually instead
with open(credential_path, "w") as f:
        f.write(creds.to_json)

rawDescription: Is it possible to store authentication token in a separate file?


code:
solrquery = "(.................. )"
solr.search([solrquery],facet = 'on' ,** {'facet.field' : ['fieldname']})

rawDescription: how add facet to pysolr query

description: How add facet to pysolr query


code:
from urllib.parse import urlparse
urlparse("http://twitter.com")
r = urlparse("http://twitter.com")
r.scheme + '://' + r.netloc

rawDescription: Parsing site/domain name from URL string


code:
from timeit import Timer
ts = Timer("s.decode('utf-8')", "s = 'ééé'")
ts.timeit()
tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'")
tu.timeit()

rawDescription: unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)

description: Unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)


code: l = [item(i, 0) for i in range(10)]

rawDescription: Enumerating namedtuples

description: Enumerating namedtuples


code:
def coins(num):
    lst = [random.randrange(2) for i in range(num)]
    lst = [(i, len(list(j))) for i, j in itertools.groupby(lst)]
    tails = max(j for i, j in lst if i)
    heads = max(j for i, j in lst if not i)
    return {1: tails, 0: heads}

rawDescription: Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)


code: import os

rawDescription: Importing both a module and submodule. Reason to have two imports?


code:
def __init__(self, init_dict, init_val=0):
    super().__init__()
    self.init_val = init_val
    self.update(init_dict)
    # Here init_dict is a dictionary or a dictionary like object

rawDescription: self-assign a dict-comprehension to a class from dict

description: Self-assign a dict-comprehension to a class from dict


code:
import my_app.func_store as store
import json

func = getattr(store, self.conditional)
params = json.loads(self.conditional_params)
if func(**params):
    function_send_email()

rawDescription: Django, store function in database

description: Django, store function in database


code: from settings_mail import *

rawDescription: Put part of setting in another file

description: Put part of setting in another file


code:
bookset=Book.objects.all()
user = User.objects.create_user('testuser',email='1@gmail.com')
user.entitledBooks=bookset
user.save()

rawDescription: Using Django's custom user model (Django1.6)


code:
with PdfPages('kde.pdf') as pdf_pages:
    for i in range(1, 114):
        for j in range(0, 113):
            x=t1.iloc[:, i]
            y=t1.iloc[:, j]
            joint_grid = sns.jointplot(x=x, y=y, kind="kde", dropna=True)
            pdf_pages.savefig(joint_grid.fig)

rawDescription: How to save multiple seaborn plots to the same pdf/png file?

description: Save multiple seaborn plots to the same pdf/png file


code: final = [x[:2] + [[float(f) for f in x[2:]]] for x in woot]

rawDescription: Using list comprehension to "merge" a list within a list


code:
from distutils.core import setup
import py2exe

setup(window=['hello.py'])

rawDescription: Executable python program - disable cmd line?


code: aName,pName,value = element.split(',')

rawDescription: Serialize collection to parse in python

description: Serialize collection to parse in python


code:
rows = 3
cols = 3
result = [[int(raw_input("row: %d col: %d  => " % (row, col)))
           for col in xrange(cols)] for row in xrange(rows)]

rawDescription: Shortest way to input each and every element of a 2D Matrix


code:
import random

DOMAIN_LOW = 0
DOMAIN_HIGH = 100

elements = list()
numbers_generated = 0

while True:
    numbers_generated += 1
    random_num = random.randint(DOMAIN_LOW, DOMAIN_HIGH)

    if random_num not in elements:
        elements.append(random_num)

    if len(elements) == DOMAIN_HIGH - DOMAIN_LOW:
        break
print(elements)
print(numbers_generated)

rawDescription: all elements in domain[n] are witnessed in Python

description: All elements in domain[n] are witnessed in Python


rawDescription: writing the calculated data into a file

description: Writing the calculated data into a file


code: plot.savefig('hanning(%d).pdf' % num)

rawDescription: Putting a variable inside a string (python)


code:
import inspect
import StringIO
inspect.findsource(StringIO.StringIO)[1]

rawDescription: Python introspection: How to get an 'unsorted' list of object attributes?


code:
relay_sets = [
    [[80100, 'a']],
    [[75000, 'b']],
    [[64555, 'c']],
    [[55000, 'd'], [44000, 'e']],
    [[39000, 'f'], [2000, 'g']],
    [[2000, 'h'], [999, 'i'], [999, 'j']],
    [[999, 'k'], [999, 'l'], [343, 'm']]
]

def prob_using_relay(relay, relaysets):
    if isinstance(relaysets[0], int):
        return int(relaysets[0] == relay)
    return sum(prob_using_relay(relay, relayset) for relayset in relaysets) / len(relaysets)

print(prob_using_relay(80100, relay_sets))

rawDescription: Duplicate strings in nested lists

description: Duplicate strings in nested lists


code: xrange(len(strval))

rawDescription: How do I get same result without using enumerate?

description: Get same result without using enumerate


code:
from itertools import product
s = "xyz"
[dict(zip(s,v)) for v in product(range(1,6),repeat=len(s))]
len(_)

rawDescription: Creating all combinations from a variable-sized list


rawDescription: Problems with making time delay

description: Problems with making time delay


code:
import imp
somectrl = imp.load_source("somectrl", "path1/ProjectA/src/ctrl/somectrl.py")
someclass = imp.load_source("someclass", "path2/ProjectA/src/someclass.py")

rawDescription: Python : importing different module with same name


code: np.array(range(1, len(newdates)+1))

rawDescription: How to create an array of array indexes?

description: Create an array of array indexes


code:
from facepy import GraphAPI
import json

group_id = "YOUR_GROUP_ID"
access_token = "YOUR_ACCESS_TOKEN"

graph = GraphAPI(access_token)

# https://facepy.readthedocs.org/en/latest/usage/graph-api.html
data = graph.get(group_id + "/feed", page=False, retry=3, limit=800)

with open('content.json', 'w') as outfile:
  json.dump(data, outfile, indent = 4)

rawDescription: Facebook Graph API: Download all posts for Group I have Admin rights to


code:
myText = ''

for entry in conn.execute('SOME SQL QUERY'):
    myText += '|{:10s}| AssetID |{:40s}| Description |{:40s}| Room Description |{:5s}| Labelled |{:10s}| Condition'.format(*entry)
    myText += '\n'

rawDescription: Converting SQL data into a QTextDocument and then outputting a pdf


code:
import inspect
def foo(): pass

def bar(**kwargs): pass

inspect.getargspec(foo).keywords is None
inspect.getargspec(bar).keywords is None
inspect.getargspec(bar).keywords

rawDescription: Distinguish between f() and f(**kwargs) in Python 2.7


code:
def chunkit(lst, n):
    newn = int(len(lst)/n)
    for i in xrange(0, n-1):
        yield lst[i*newn:i*newn+newn]
    yield lst[n*newn-newn:]

def getDescriptions(ids):
    friends = chunkit(ids, 3)
    while (True):
        try:
            fids = friends.next()
            sids = ','.join(map(str, fids))
            r = requests.get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='+API_KEY+'&steamids=' + sids)
            data = r.json()
            # Do something with the data variable
        except StopIteration:
            break

rawDescription: Grabbing values of an array in sets of 100


rawDescription: Python Pandas: Transform multiindex dataframe


code:
from collections import OrderedDict
from bokeh.charts import Scatter, output_file, show

# (dict, OrderedDict, lists, arrays and DataFrames of (x, y) tuples are valid inputs)
xyvalues = OrderedDict()
xyvalues['python'] = [(1, 2), (3, 3), (4, 7), (5, 5), (8, 26)]
xyvalues['pypy'] = [(1, 12), (2, 23), (4, 47), (5, 15), (8, 46)]
xyvalues['jython'] = [(1, 22), (2, 43), (4, 10), (6, 25), (8, 26)]

scatter = Scatter(xyvalues, title="Scatter", legend="top_left", ylabel='Languages')

output_file('scatter.html')
show(scatter)

rawDescription: How do I show legend for different colors in bokeh scatter plot?

description: Show legend for different colors in bokeh scatter plot


code:
#pygame.transform.scale(background, (1200,800))  #or some size x,y here.
background = pygame.transform.scale(background, (1200,800))

rawDescription: transforming images in pygame

description: Transforming images in pygame


code: ds.map(json.loads).apply(lambda x: pd.Series([x["a"] if "a" in x else None, x["b"] if "b" in x else None]))

rawDescription: generalized series splitting (one to many mapping) in pandas

description: Generalized series splitting (one to many mapping) in pandas


code: [tag.attrs for tag in soup.findAll(True) if tag.string]

rawDescription: BeautifulSoup: extracting HTML tag attributes


code:
# ...
for set in sets:
    for id in set:
        if id not in ids_count:
            ids_count[id] = 0
        ids_count[id] += 1

rawDescription: Redis: best way to count occurrence of item in sets


code:
for i, chunk in enumerate(pd.read_fwf(...)):
    first = i == 0
    chunk.to_csv(outfile, header=first, mode='a')

rawDescription: Pandas to_csv index=False not working

description: Pandas to_csv index=False not working


code:
from numpy import ma
data
M
mdata = ma.masked_array(data, mask=~M.astype(bool))
mdata
mdata.std(axis=0)

rawDescription: Numpy standard deviation under a mask

description: Numpy standard deviation under a mask


code:
domains = [...]

pattern = "email NOT LIKE '%{0}'"
conditions = " AND ".join([pattern.format(domain) for domain in domains])
query = "SELECT * FROM users WHERE " + conditions

rawDescription: Handle multiple parameter in SQL query using MySQLdb


code:
inputFile = open("in.txt", "r")
log = []
for line in inputFile:
    if line in log and line[0:5] != "Jan 1":
        pass
    else:
        log.append(line)
inputFile.close()

outFile = open("out.txt", "w")

for item in log:
    outFile.write(item)
outFile.close()

rawDescription: How to remove the duplicate lines retaining first occurences

description: Remove the duplicate lines retaining first occurences


code:
import os
from subprocess import *

def run_cmd(cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()[0]
        return output

rawDescription: store Os.system result in variable

description: Store Os.system result in variable


code:
import flask
import flask.ext.sqlalchemy
import flask.ext.restless
from flask.json import JSONEncoder
import sqlalchemy_utils
import arrow

app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(sqlalchemy_utils.ArrowType)

class ArrowJSONEncoder(JSONEncoder):
    def default(self, obj):
        try:
            if isinstance(obj, arrow.Arrow):
                return obj.format('YYYY-MM-DD HH:mm:ss ZZ')
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj)

app.json_encoder = ArrowJSONEncoder

db.create_all()
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Event, methods=['GET','POST'])

app.run()

rawDescription: Serializing Python Arrow objects for the Flask-Restless API


code:
df[df > df.quantile(0.8)].dropna()
list(df[df > df.quantile(0.8)].dropna().index)

rawDescription: Creating percentile buckets in pandas

description: Creating percentile buckets in pandas


code: cost = min(x for x in (t_data.sd_retail_price, t_data.hd_retail_price, 100000) if x)

rawDescription: Get min value, not null

description: Get min value, not null


code:
def count_even_leaves(bnt):
    if not isinstance(bnt,tuple):
        return (bnt+1)%2
    evens = count_even_leaves(bnt[0])
    evens += count_even_leaves(bnt[1])
    return evens

rawDescription: Count number of even leaves in a Binary Number Tree


code:
import pandas as pd
import matplotlib.pyplot
import numpy as np

test_df_1 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
ax = test_df_1.plot(kind='bar')
test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))

x = np.array([r.get_x() for r in ax.patches])
w = np.array([r.get_width() for r in ax.patches])

ax.hlines(test_df_2.values.T.ravel(), x, x + w, color="red", lw=2)

rawDescription: Matplotlib, plotting multiple individual hline on barplot from a pandas dataframe


code: plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

rawDescription: autofmt_xdate deletes x-axis labels of all subplots

description: Autofmt_xdate deletes x-axis labels of all subplots


code:
def filtering(a_list):
    results = []
    for i, item in enumerate(a_list):
        if re.search(r'\d{0,1}\s+Contacts;\s*', item) is not None:
            results.extend(a_list[i+1:i+6])

rawDescription: Isolate N values from a list after obtaining a specific match with a regex


rawDescription: How do I make a regex that only matches integers?

description: Make a regex that only matches integers


code:
import time
from ptrace.linux_proc import *  # For the searchProcessByName func
from ptrace.binding import *     # For ptrace funcs

def checkVal(value):
    # Check value bounds and such here
    if value is good:
        return True

def main():
    pid = searchProcessByName("nameofprocess") #or pid = 56437
    addr = 0x32323232 # Note: poke/peek_text requires the address to be aligned
    while True:       # This may require some modifications to your new value as well
        newVal = input("What do you want the new value to be?")
        if checkVal(newVal):
            ptrace_attach(pid) # Attach
            time.sleep(.001) # For some reason, I needed this for it to work
            ptrace_peektext(pid,addr) # Read word at addr
            ptrace_poketext(pid,addr,newVal) # Write newVal at addr
            ptrace_detach(pid) # Let the process resume

rawDescription: Python-Ptrace - What happens after PtraceProcess.cont()?


code:
import itertools

newballs = []
removed = set()
for b1, b2 in itertools.combinations(balls, 2):
    if b1 not in removed and b2 not in removed:
        if b1.does_collide(b2):
            removed.add(b1)
            removed.add(b2)
            newballs.append(b1.collide(b2))

balls = [b for b in balls if b not in removed] + newballs

rawDescription: How to check if balls in a list collide, and remove them from list

description: Check if balls in a list collide, and remove them from list


code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT

_user32 = ctypes.WinDLL('user32', use_last_error=True)

_MessageBoxW = _user32.MessageBoxW
_MessageBoxW.restype = UINT  # default return type is c_int, this is not required
_MessageBoxW.argtypes = (HWND, LPWSTR, LPWSTR, UINT)

MB_OK = 0
MB_OKCANCEL = 1
MB_YESNOCANCEL = 3
MB_YESNO = 4

IDOK = 0
IDCANCEL = 2
IDABORT = 3
IDYES = 6
IDNO = 7

def MessageBoxW(hwnd, text, caption, utype):
    result = _MessageBoxW(hwnd, text, caption, utype)
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return result

def main():
    try:
        result = MessageBoxW(None, "text", "caption", MB_YESNOCANCEL)
        if result == IDYES:
            print("user pressed ok")
        elif result == IDNO:
            print("user pressed no")
        elif result == IDCANCEL:
            print("user pressed cancel")
        else:
            print("unknown return code")
    except WindowsError as win_err:
        print("An error occurred:\n{}".format(win_err))

if __name__ == "__main__":
    main()

rawDescription: How to specify what actually happens when Yes/No is clicked with ctypes MessageBoxW?

description: Specify what actually happens when Yes/No is clicked with ctypes MessageBoxW


code:
from sklearn.ensemble import GradientBoostingRegressor
from multiprocessing import Pool
from itertools import repeat

def train_model(params):
    model, data, target = params
    # since Pool args accept once argument, we need to pass only one
    # and then unroll it as above
    model.fit(data, target)
    return model

if __name__ == '__main__':
    gb1 = GradientBoostingRegressor(n_estimators=10)
    gb2 = GradientBoostingRegressor(n_estimators=100)

    live_data # Pandas DataFrame object
    target    # Numpy array object

    po = Pool(2) # 2 is numbers of process we want to spawn
    gb, gb2 = po.map_async(train_model,
                 zip([gb1,gb2], repeat(data), repeat(target))
                 # this will zip in one iterable object
              ).get()
    # get will start the processes and execute them
    po.terminate()
    # kill the spawned processes

rawDescription: Train two models concurrently

description: Train two models concurrently


code: ' '.join(x for x in text.split() if not x.startswith('@'))

rawDescription: remove elements from a list that begin with a specific character

description: Remove elements from a list that begin with a specific character


rawDescription: Fill pytable using SQL query

description: Fill pytable using SQL query


code:
n = int(input('How many tracks are in the album?: '))

f=open("directory","w")

for i in range(n):

    line = raw_input('Next Track: ')
    f.write("Track Name/Rating: " + line +"\n")
f.close()

rawDescription: Enter each line user inputs with file. functions


rawDescription: Using grid_propagate(False) in Python Tkinter


code:
class MyCloudinaryField(CloudinaryField):
    def upload_options(self, model_instance):
       return {'public_id': model_instance.supplier.user.id + "-" + model_instance.designNumber}

rawDescription: cloudinary cloudinary.models.CloudinaryField add public_id to the field

description: Cloudinary cloudinary.models.CloudinaryField add public_id to the field


code:
def any_func(former_id):
    pass

def get_id_from_file():
    file = open(r'C:/Users/my.name/Documents/test.txt', 'r')
    farmer_id = file.readline()
    return farmer_id

farmerid = get_id_from_file()
any_func(farmerid)

rawDescription: Pass the value of a variable to a function in Python3


code:
def zip_to_df(zip_file):
    with zipfile.ZipFile(zip_file, 'r') as myzip:
        return pd.concat((log_as_df(loglife, myzip)
                             for logfile in myzip.namelist()),
                         ignore_index=True)

def log_as_df(logfile, myzip):
    with myzip.open(logfile, 'r') as f:
        contents = f.readlines()[-2]
        return pd.read_json(contents)

df = pd.concat(map(zip_to_df, glob.glob('*.zip')), ignore_index=True)

rawDescription: Combinging Multiple Json Objects as one DataFrame in Python Pandas


rawDescription: what is best way to indentify that the length of tuple in a list is 0 using python

description: What is best way to indentify that the length of tuple in a list is 0 using python


rawDescription: Finding upper/lower triangular form of arbitrary matrix n*n - python


code:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None)

    def setupUi(self):
        self.setObjectName(_fromUtf8("self"))
        self.resize(184, 165)
        self.centralwidget = QtGui.QWidget(self)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 40, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 184, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(self)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        self.setStatusBar(self.statusbar)

        self.retranslateUi()
        QtCore.QObject.connect(self.pushButton , QtCore.SIGNAL("clicked()"),self.gone)
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        self.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "PushButton", None, QtGui.QApplication.UnicodeUTF8))

    def gone(self):
        self.mw2 = Ui_MainWindow1()
        self.mw2.setupUi()
        self.mw2.show()

class Ui_MainWindow1(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None)

    def setupUi(self):
        self.setObjectName(_fromUtf8("self"))
        self.resize(170, 175)
        self.centralwidget = QtGui.QWidget(self)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(40, 60, 101, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 170, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(self)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        self.setStatusBar(self.statusbar)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        self.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("MainWindow", "This is second", None, QtGui.QApplication.UnicodeUTF8))

def startmain():
    app = QtGui.QApplication(sys.argv)
    ui = Ui_MainWindow()
    ui.setupUi()
    ui.show()
    app.exec_()

if __name__ == "__main__":
    import sys
    startmain()

rawDescription: Empty QMainWindow, PyQt

description: Empty QMainWindow, PyQt


code: q = max(q, p[i] + rod_cutting_memoization_aux(p,n-i-1,r))

rawDescription: recursion confusion - rod cutting algorithm

description: Recursion confusion - rod cutting algorithm


code:
import hashlib
query = "" #your query here
cache_key = str(int(hashlib.md5(query.lower()).hexdigest(), 16))

rawDescription: Memcache key generation from the query

description: Memcache key generation from the query


code:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.ticker import FuncFormatter

sns.set()
fig, ax0 = plt.subplots(1,1)
data = np.array([[10.01,20.20],[-0.23,0.],[23.1049,-100.000000]])
ax = sns.heatmap(data, annot=True, fmt = '.1f', square=1, linewidth=1.)
for t in ax.texts: t.set_text(t.get_text() + " %")
plt.show()

rawDescription: Adding units to heatmap annotation in Seaborn


code:
ids = ['location_id','score']

def foo(d):
    return pd.Series(d['number_of_males'].values*['male'] +
                     d['number_of_females'].values*['female'])

pd.melt(df.groupby(ids).apply(foo).reset_index(), id_vars=ids).drop('variable', 1)

#Out[13]:
#   location_id  score   value
#0            1     20    male
#1            2     45    male
#2            1     20    male
#3            2     45  female
#4            1     20  female
#5            2     45  female

rawDescription: create a new dataframe from an aggregated dataframe

description: Create a new dataframe from an aggregated dataframe


code:
def OnRun(self,event):
    path = "/path/to/youtube-dl.py"
    url = "http://www.youtube.com/"
    subprocess.Popen(path, url, "--extract-audio", "--audio-format", "mp3")

rawDescription: Run a cmd command with a simple button in wxpython


code:
from csv import reader

with open('test.xml') as inputfile:
    xml = inputfile.read()

with open('test.csv') as csvfile:
    for row in reader(csvfile, delimiter=';'):
        xml = xml.replace('{{%s}}' % row[0], row[1])

with open('output.xml', 'w') as outputfile:
    outputfile.write(xml)

rawDescription: Find and replace in xml file with Python


code:
...
ax1.tick_params(direction='inout')
ax1.set_xticklabels(varLabels, rotation=45, ha='right')
ax1.set_yticklabels(varLabels, rotation=45, va='top')
...

rawDescription: Rotated axis labels are placed incorrectly (matplotlib)


code:
hxs = HtmlXPathSelector(response)

namesubs = hxs.select("//div[@class='namesub']")
for namesub in namesubs:
    item = MyItem()
    item["info"] = namesub.select('.//span[@class="info"]/text()').extract()[0]

    yield item

rawDescription: using scrapy parsing a website under same div

description: Using scrapy parsing a website under same div


code:
for x,y,z,i in zip(xcod,ycod,zcod,range(len(xcod))):
    ax.text(x,y,z,i)

rawDescription: Label points in 3d plot using matplotlib


code:
def update_data():
    global data
    data += 1

rawDescription: Updating shared data with Twisted

description: Updating shared data with Twisted


code:
class ImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Image

    image = factory.LazyAttribute(
            lambda _: ContentFile(
                factory.django.ImageField()._make_data(
                    {'width': 1024, 'height': 768}
                ), 'example.jpg'
            )
        )

rawDescription: How to make FactoryBoy's ImageField generate image before save() is called?

description: Make FactoryBoy's ImageField generate image before save() is called


code: weight = list(reversed(range(1,27)))

rawDescription: Any way to shorten statements in python

description: Any way to shorten statements in python


code:
cursor = db.cursor()
cursor.execute("INSERT INTO pybank (account_number,user_name, user_age, user_dob, amount) VALUES (%s, %s, %s, %s, %s)", (self.account_number + 1, self.user_name, self.user_age, self.user_dob, self.total_amount))

rawDescription: Python - MySQLdb - data not inserted into table


code:
s = " I want to detect both March 20, 2013 and February 2013 3 and list them"

import  re

print(re.findall(r"([A-Z][a-z\s\d]+, \d+|[A-Z][a-z\s]+\d+)",s))
['March 20,2013', 'February 2013']

rawDescription: Detect the dates from text in text file. And then list them out using python


code:
REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ",
}

rawDescription: Set DatetimeField format of django rest framework configuration


code:
import random

def main():
    sum_num = 0
    for count in range(6):
        randnums = random.randrange(1,10)
        sum_num = sum_num + randnums
        print(randnums, end='')
    print(sum_num)

main()

rawDescription: Sum random numbers

description: Sum random numbers


code: [a for a in data if 1 < a < 10]

rawDescription: Indexing ranges with where() in Python arrays


code: 'something {first_alpha} something {last}'.format(first_alpha = 'then', last = 'else')

rawDescription: Problems formatting a string - Python 2.7.3


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

rawDescription: rotating the z-axis in matplotlib 3d figure

description: Rotating the z-axis in matplotlib 3d figure


code: frame = WebDriverWait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'sg-legacy-iframe')))

rawDescription: How to access elements of page after login selenium?

description: Access elements of page after login selenium


code: x = Slider.value()  # x contains the integer value of the slider

rawDescription: Accessing slider value directly in variable


code:
class SomeClass(object):
    def __init__(self, field):
        self.field = field

    def build_new(self):
        self.__init__(True)

rawDescription: Python: How to call the constructor from within member function


rawDescription: What is the the purpose this bracket: [0] in Python


code:
from matplotlib import pyplot
import matplotlib as mpl
fig = pyplot.figure(figsize=(8,3))
ax1 = fig.add_axes([0.05, 0.70, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.35, 0.9, 0.15])
cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=5, vmax=10)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm,
                                orientation='horizontal')
cb1.set_label('Negative spacing')
cb1.set_ticks([5.5, 7.5, 9.5])
cb1.ax.xaxis.set_tick_params(pad=-15)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
                            orientation='horizontal')
cb2.set_label('Far away')
cb2.set_ticks([5.5, 7.5, 9.5])
cb2.ax.xaxis.set_tick_params(pad=30)
pyplot.savefig('colorbar-ticklabels.png')

description: Python/Matplotlib colorbar-ticklabel distance


code:
import os, os.path, EditHeader2

folder1 = 'editedheaders'
folder2 = 'editedheaders/1'

extensions = ('.txt', '.tfw', 'your extensions here ...')

for filename in os.listdir(folder1):
    infilename = os.path.join(folder1, filename)
    if not os.path.isfile(infilename): continue
    base, extension = os.path.splitext(filename)
    if os.path.splitext(filename)[1] in extensions:
        infile = open(infilename, 'r')
        outfile = open(os.path.join(folder2, '{}'.format(base, extension)), 'w')
        EditHeader2.edit(infile, outfile)

rawDescription: Replace the values in text files in a directory in Python


code:
import msvcrt as ms

while True:
    if ms.kbhit():
        print(ms.getch())

rawDescription: Keypress detection

description: Keypress detection


code:
def maketransformer(file): #contains arbitrary stuff that takes too long

    data = gdal.Open(file)
    output_wkt = data.GetProjection()
    srs_out = osr.SpatialReference()
    srs_out.ImportFromWkt(output_wkt)

    transformer = osr.CoordinateTransformation(srs_out)
    return transformer

transformer = maketransformer('data/w001001.adf')

for tuple in shapefilepoints:
    getelevation(transformer.Transform(tuple))

rawDescription: How do I "freeze" an object, I.E. compute it once and then reference it later without computing it again?


code:
for k in dict2.keys():
    dict2[k] = [x for x in dict2[k] if x[1] not in idlist]
    if not dict2[k]:
        del dict2[k]

rawDescription: Python dictionary iteration

description: Python dictionary iteration


code:
SPIDER_MIDDLEWARES = {
    'yourprojectname.middlewares.deltafetch.DeltaFetch': 100,
}

DELTAFETCH_ENABLED = True

rawDescription: Enabling deltafetch in scrapy

description: Enabling deltafetch in scrapy


code:
import Cookie
import cookielib
cookiejar =cookielib.LWPCookieJar()

br = mechanize.Browser()
br.set_cookiejar(cookiejar)
br.open("https://mysite.com/")
br.select_form(nr=0)
#do stuff here
response = br.submit()
html = response.read()

#now that i have the login cookie i can do this...
br.open("https://mysite.com/")
html = response.read()

rawDescription: Are cookies kept in a Mechanize browser between opening URLs?


code:
class index:
    def POST(self):
        yield pPbuffer
        r.set('a','b')

rawDescription: Using web.py return a post request and do further processing after the response


rawDescription: Meaning of a variable declaration in PyMC


code:
# The heading
print("Times: " , end="")
for number in range(1,10):
    print(number,end="\t")
print()

# The double for-loop
for multiplum in range(1,9):
    print(multiplum, end="      ") # First column
    for number in range(1,10):
        print(multiplum*number, end="\t") # Next 9 columns
    print()

rawDescription: Printing multiplication table

description: Printing multiplication table


code:
for i, j in replace.items():
    if i in originalText:
        newText = originalText.replace(i,j)
        print(newText.upper())
        break
else:
    print(originalText.upper())

rawDescription: Having trouble translating strings

description: Having trouble translating strings


code:
L1 = [2,3,4]
L2 = [1,2]
[i for i in L1 if i in L2]
S1 = set(L1)
S2 = set(L2)
S1.intersection(S2)

rawDescription: How to check if one of the following items is in a list?

description: Check if one of the following items is in a list


rawDescription: Is this a Json variant? [{ID:0,N:'3ergy',SIP:'',


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

# Some things to make your script run when I don't have your data
slope1,slope1_err='this','that'
logngal   = np.linspace(0,1,20)
logm200   = np.random.rand(20)
x_pred    = np.linspace(0,1,20)
curve_y_1 = 0.5*(np.sin(logngal)/2.+np.cos(logngal))
upper     = np.sin(x_pred)/2.
lower     = np.cos(x_pred)
# end of sample data

fig2 = plt.figure(figsize=(8,6))
ax1 = fig2.add_subplot(111)

pscat  = ax1.scatter((logngal),(logm200), c='r',label='$0.0<z<1.0$')
pplot, = ax1.plot((logngal),(curve_y_1),'y',linewidth=2,label='$slope=%s \pm %s$'%(slope1,slope1_err))

ax1.fill_between(x_pred, lower, upper,color='#888888', alpha=0.5)

p1 = mpatches.Rectangle((0, 0), 1, 1, fc="#888888",alpha=0.5)

handles = [p1,pplot,pscat]
labels  = ['$1\sigma\/confidence\/limts$',pplot.get_label(),pscat.get_label()]

ax1.legend(handles,labels)

fig2.show()

rawDescription: Using a proxy artist inside a legend, matplotlib, Python


code:
from collections import namedtuple
import Tkinter as tk

Rect = namedtuple('Rect', 'x0, y0, x1, y1')

class ImageMapper(object):
    def __init__(self, image, img_rects):
        self.width, self.height = image.width(), image.height()
        self.img_rects = img_rects

    def find_rect(self, x, y):
        for i, r in enumerate(self.img_rects):
            if (r.x0 <= x <= r.x1) and (r.y0 <= y <= r.y1):
                return i
        return None

class Demo(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.msg_text = tk.StringVar()
        self.msg = tk.Message(self, textvariable=self.msg_text, width=100)
        self.msg.grid(row=0, column=0)

        self.picture = tk.PhotoImage(file='archipelago2.gif')
        img_rects = [Rect(0, 26, 80, 78),
                     Rect(89, 26, 183, 78),
                     Rect(119, 120, 168, 132),
                     Rect(126, 74, 219, 125),
                     Rect(134, 135, 219, 164),
                     Rect(0, 148, 21, 164)]
        self.imagemapper = ImageMapper(self.picture, img_rects)
        # use Label widget to display image
        self.image = tk.Label(self, image=self.picture, borderwidth=0)
        self.image.bind('<Button-1>', self.image_click)
        self.image.grid(row=1, column=0)

        self.quitButton = tk.Button(self, text='Quit', command=self.quit)
        self.quitButton.grid(row=2, column=0)

    def image_click(self, event):
        hit = self.imagemapper.find_rect(event.x, event.y)
        self.msg_text.set('{} clicked'.format('nothing' if hit is None else
                                              'rect[{}]'.format(hit)))

app = Demo()
app.master.title('Image Mapper')
app.mainloop()

rawDescription: Hide a Button Under an Image TKinter

description: Hide a Button Under an Image TKinter


code:
import sys
import apiclient.discovery
import oauth2client.client
import httplib2
import pprint

# see example for using service account here:
#   https://developers.google.com/drive/delegation
def main (argv):
    scopes = ('https://www.googleapis.com/auth/admin.directory.orgunit')
    service_account_email = 'xxx@developer.gserviceaccount.com'
    acting_as_user = 'yyy@zzz' # must have the privileges to view the org units
    f = file('key.p12', 'rb')
    key = f.read()
    f.close()
    credentials = oauth2client.client.SignedJwtAssertionCredentials(
        service_account_email,
        key,
        scope=scopes,
        sub=acting_as_user
        )
    http = httplib2.Http()
    http = credentials.authorize(http)
    directoryservice = apiclient.discovery.build('admin', 'directory_v1', http=http)
    response = directoryservice.orgunits().list(customerId='my_customer').execute(http=http)
    pprint.pprint(response)

if __name__ == '__main__':
    main(sys.argv)

rawDescription: What is the proper way to authenticate with Google to use Google Directory API in the Admin SDK?


code:
execution_guard_enabled=true
# it is milliseconds
org.neo4j.server.webserver.limit.executiontime=20000

rawDescription: how do I abort a query in py2neo?

description: Abort a query in py2neo


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.edit = QtGui.QTextEdit(self)
        self.undo = QtGui.QPushButton('Undo')
        self.redo = QtGui.QPushButton('Redo')
        self.insert = QtGui.QPushButton('Set Html')
        layout.addWidget(self.edit)
        layout.addWidget(self.undo)
        layout.addWidget(self.redo)
        layout.addWidget(self.insert)
        self.undo.clicked.connect(self.edit.undo)
        self.redo.clicked.connect(self.edit.redo)
        self.insert.clicked.connect(self.handleInsert)
        self.edit.append('One')
        self.edit.append('Two')
        self.edit.append('Three')

    def handleInsert(self):
        cursor = QtGui.QTextCursor(self.edit.document())
        cursor.select(QtGui.QTextCursor.Document)
        cursor.insertHtml("""
Some HTML text
""")

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

rawDescription: Accessing QTextHtmlImporter in PyQt4

description: Accessing QTextHtmlImporter in PyQt4


code:
import kivy
from kivy.app import App

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button

from kivy.properties import ObjectProperty
from kivy.properties import NumericProperty

class AppScreen(FloatLayout):
    app = ObjectProperty(None)

class MainMenu(AppScreen):
    pass

class ScoreScreen(AppScreen):
    count_r = NumericProperty(0)
    score = NumericProperty(0)

    # This is making a new WordComprehension object, and thus will not have
    # the correct value of score. We no longer need this is we are binding properties
    # together.
    #def get_score(self):
    #    wordcomp = WordComprehension()
    #    self.score = wordcomp.count_r

class WordComprehension(AppScreen):
    count_r = NumericProperty(0)
    count_w = NumericProperty(0)

    def do_something(self):
        self.count_r += 1

class InterfaceApp(App):
    def build(self):
        self.screens = {}
        self.screens["wordcomp"] = WordComprehension(app=self)
        self.screens["menu"] = MainMenu(app=self)
        self.screens["score"] = ScoreScreen(app=self)
        self.root = FloatLayout()
        self.goto_screen("menu")

        # Bind the two properties together. Whenever count_r changes in the wordcomp
        # screen, the score property in the score screen will reflect those changes.
        self.screens["wordcomp"].bind(count_r=self.screens["score"].setter('score'))

        return self.root

    def goto_screen(self, screen_name):
        self.root.clear_widgets()
        self.root.add_widget(self.screens[screen_name])

if __name__ == "__main__":
    InterfaceApp().run()

rawDescription: How to pass properties from one class to another in kivy

description: Pass properties from one class to another in kivy


code:
from PySide.QtGui import *

class Window(QMainWindow):
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)

        self.scene = QGraphicsScene()
        self.view1 = QGraphicsView(self.scene, self)
        self.view2 = QGraphicsView(self.scene, self)

        self.view1.setFrameShape(QFrame.NoFrame)
        self.view2.setFrameShape(QFrame.NoFrame)

        widget = QWidget(self)
        layout = QGridLayout(widget)
        layout.addWidget(self.view1, 0, 0)
        layout.addWidget(self.view2, 0, 1)

        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self.setCentralWidget(widget)

        self.scene.addLine(0, 0, 1000, 1000)

if __name__ == "__main__":
    app = QApplication(())
    window = Window()
    window.showMaximized()
    app.exec_()

rawDescription: PySide (Qt) - Layout not working

description: PySide (Qt) - Layout not working


code:
class ClassA(db.Model):
    name = db.StringProperty()

    def __get_classBdeleted(self):
        return self.classB_set.filter('deleted_flag =', 'True')

    classBdeleted = property(__get_classBdeleted)

class ClassB(db.Model):
    name = db.StringProperty()
    deleted_flag = db.BooleanProperty()
    classA = db.ReferenceProperty(ClassA)

rawDescription: How to change the default property on a set in python and Google AppEngine

description: Change the default property on a set in python and Google AppEngine


rawDescription: Python: sort the list

description: Python: sort the list


code:
def cycle(input_list):
    return input_list[1:] + input_list[:1]

rawDescription: Move elements in a list one position backward without mutating the original list


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

INPUT = np.array(
[[1,   3,   -2]
,[2,   1,   -3]
,[3,   1,   1]
,[2,   2,   3]
,[1,   2,   2]
,[2,   3,   0]])

# get ranges
xmin = INPUT[:,0].min()
xmax = INPUT[:,0].max()
ymin = INPUT[:,1].min()
ymax = INPUT[:,1].max()
zmin = INPUT[:,2].min()
zmax = INPUT[:,2].max()

# create array for image : zmax+1 is the default value
shape = (xmax-xmin+1,ymax-ymin+1)
img = np.ma.array(np.ones(shape)*(zmax+1))

for inp in INPUT:
    img[inp[0]-xmin,inp[1]-ymin]=inp[2]

# set mask on default value
img.mask = (img==zmax+1)

# set a gray background for test
img_bg_test =  np.zeros(shape)
cmap_bg_test = plt.get_cmap('gray')
plt.imshow(img_bg_test,cmap=cmap_bg_test,interpolation='none')

# plot
cmap = plt.get_cmap('jet')
plt.imshow(img,cmap=cmap,interpolation='none',vmin=zmin,vmax=zmax)
plt.colorbar()

plt.imsave("test.png",img)
plt.show()
plt.close()

rawDescription: values at coordinates to image

description: Values at coordinates to image


code: t = (s,) + tuple(l)

rawDescription: Create a tuple from a variable and a list


code:
import csv, youtube_dl

with open("filelist.csv", "r") as f_filelist:
    csv_filelist = csv.reader(f_filelist, delimiter="\t")

    for cols in csv_filelist:
        video_name = cols[0]
        part = cols[1]
        youtube_url = cols[2]

        ydl_opts = {"outtmpl" : r"{}_{}.%(ext)s".format(video_name, part)}

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([youtube_url])

rawDescription: How can I pass parameters to --output in youtube-dl?

description: Pass parameters to --output in youtube-dl


code:
def init(self):
    """initialise dialog"""
    # Button-3 is right click on windows
    self.tree.bind("<Button-3>", self.popup)

def popup(self, event):
    """action in event of button 3 on tree view"""
    # select row under mouse
    iid = self.tree.identify_row(event.y)
    if iid:
        # mouse pointer over item
        self.tree.selection_set(iid)
        self.contextMenu.post(event.x_root, event.y_root)
    else:
        # mouse pointer not over item
        # occurs when items do not fill frame
        # no action required
        pass

rawDescription: python tkinter treeview right click (Button-3) event to select item in treeview

description: Python tkinter treeview right click (Button-3) event to select item in treeview


code:
class ScoreChanged(Event):
    ...

class Character(ListenerMixin):
    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, new):
        old = self._score
        self._score = new
        self.fire_event(ScoreChanged(self, old, new))

protag = Character()
scoreboard = Scoreboard()
scoreboard.listen_event(protag, ScoreChanged, scoreboard.on_score_change)

protag.score += 10

rawDescription: Python - can I wrap attribute assignment without writing a getter/setter