code:
import sys
from PyQt4 import QtCore, QtGui

class MyWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setGeometry(200,100,300,300)

        self.selectionList = ['Jim', 'John', 'Harry', 'Charles']

        self.pushbutton = QtGui.QPushButton('Input', self)
        self.pushbutton.setGeometry(50,75, 100, 25)
        self.pushbutton1 = QtGui.QPushButton('Select', self)
        self.pushbutton1.setGeometry(50,150, 100, 25)

        self.pushbutton.clicked.connect(self.getInput)
        self.pushbutton1.clicked.connect(self.getSelection)

    def getInput(self):
        text = QtGui.QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
        if text[1]:
            username = text[0]
            print(username)

    def getSelection(self):
        sel = QtGui.QInputDialog.getItem(self, 'Text Selection Dialog', 'Select your name:', self.selectionList, current=0, editable=False)
        if sel[1]:
            username = sel[0]
            print(username)

app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())

rawDescription: link QInputDialog text to a variable

description: Link QInputDialog text to a variable


rawDescription: value counts of a Database chunk by chunk using pandas

description: Value counts of a Database chunk by chunk using pandas


code:
def aggregate_flights(flights):
    out = []
    last_id = ''
    for row in flights:
        if row[-2] != last_id and len(out) > 0:
            yield (last_id,out)
            out = []
        last_id = row[-2]
        out.append((row[3],row[4])) #2-tuple of (start,end)
    yield (last_id,out)

rawDescription: Find first and last list within a list with a matching property


rawDescription: How does Python handle equality checking?


code:
import sys, os, sys, time, datetime, threading, select, logging, logging.handlers
import configparser, traceback, re, socket, hashlib
# local .py
sys.path.append('/var/vse/python')
import _util, _webby, _sni, _cams_db, _cams_threaded_server, _cams_bot
# ...

def start_courier(config):
    # default values
    host = '::'
    port = 2345

    configp = config['configp']

    host = configp.get('main', 'relay msp hostport')

    # require ipv6 addresses be specified in [xx:xx:xx] notation, therefore
    # it is safe to look for :nnnn at the end
    if ':' in host and not host.endswith(']'):
        port = host.split(':')[-1]
        try:
            port = int(port, 10)
        except:
            port = 2345
        host = host.split(':')[:-1][0]

    server = _cams_threaded_server.ThreadedTCPServer((host, port), _cams_threaded_server.ThreadedTCPRequestHandler, config)
    t = threading.Thread(target=server.serve_forever, name='courier')
    t.start()

rawDescription: issues with socket programming - python

description: Issues with socket programming - python


rawDescription: Python Hex File Write

description: Python Hex File Write


code:
class ABSerializer(serializers.ModelSerializer):

    class Meta:
        model = A
        fields = ['name', 'age', 'salary']
        related_fields = ['b']

    salary = serializer.IntegerField(source='b.salary') # this is your related_name

    def update(self, instance, validated_data):
        # Handle related objects
        for related_obj_name in self.Meta.related_fields:

            # Validated data will show the nested structure
            data = validated_data.pop(related_obj_name)
            related_instance = getattr(instance, related_obj_name)

            # Same as default update implementation
            for attr_name, value in data.items():
                setattr(related_instance, attr_name, value)
            related_instance.save()
        return super(ABSerializer,self).update(instance, validated_data)

rawDescription: Django rest framework one to one relation


code:
REPLACE = { letter: str(index) for index, letter in enumerate('oizeasgtb') }

def Leet2(word):
    letters = [ REPLACE.get(l, l) for l in word.lower() ]
    return ''.join(letters)

rawDescription: 'leet' program - getting all permutations


rawDescription: Python - Unpivot data

description: Python - Unpivot data


code:
from django.template import RequestContext

def view(request):
    my_data_dictionary = {}
    # code here
    return render_to_response('template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

def view(request):
    # code here
    return render_to_response('template.html', {},
                          context_instance=RequestContext(request))

rawDescription: Django - template - User in never authenticated


code:
cw=matplotlib.cm.get_cmap('coolwarm',8*(len(clevs)+1))
cw_vals=cw(np.arange(8*(len(clevs)+1)))
new_cw_vals=np.zeros([len(clevs),cw_vals.shape[1]],dtype=np.float128)
new_cw_vals_t = np.float128(cw_vals[4::8,:])
new_cw_vals_b = np.float128(cw_vals[12::8,:])
for i in np.arange(new_cw_vals.shape[0]):
    if clevs[i] < 0.0:
        new_cw_vals[i,:]=np.float32(new_cw_vals_t[i,:])
    else:
        new_cw_vals[i,:]=np.float32(new_cw_vals_b[i,:])
newcmap = matplotlib.colors.LinearSegmentedColormap.from_list("newcw", new_cw_vals)
newcnorm=matplotlib.colors.Normalize(newcmap,clip=False)

rawDescription: Color differences between contour and contourf in matplotlib


code:
def my_circle_scatter_radii(axes, x_array, y_array, radii_array, **kwargs):
    for (x, y, r) in zip(x_array, y_array, radii_array):
        circle = pylab.Circle((x,y), radius=r, **kwargs)
        axes.add_patch(circle)
    return True

rawDescription: Plot/scatter position and marker size in the same coordinates


code:
fig = plt.figure(figsize=(xinch,yinch/.8))

ax = plt.axes([0., 0., 1., .8], frameon=False, xticks=[],yticks=[])
ax.imshow(img, interpolation='none')
ax.set_title('Matplotlib is fun!', size=16, weight='bold')

plt.savefig('D:\\mpl_logo_with_title.png', dpi=dpi)

rawDescription: Setting the size of the plotting canvas in Matplotlib


code:
self.image, self.speed, self.hp = image, speed, hp
self.rect = self.image.get_rect().move(x, y)

rawDescription: How to Create Instance Attributes By Lopping Over __init__ Arguments?


code:
s = "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014"
re.findall(r'\b[A-Z]\S+(?:\s+[A-Z]\S+){1,}|(?<=-\s)\S+', s)

rawDescription: Python regex delimiting a string

description: Python regex delimiting a string


code:
import sys, time

for c in "Hello there!":
    sys.stdout.write(c)
    sys.stdout.flush()
    time.sleep(0.1)
print

rawDescription: How to make Python print one character at a time on the same line?

description: Make Python print one character at a time on the same line


code:
for pid, grp in DF.groupby('pid'):
    print(pid, grp.timestamp.min(), grp.timestamp.max())

# Prints:
# (99, 10, 100)
# (3014, 20, 200)

rawDescription: Python Pandas: Comparison of Min Max Values Per Group


code:
from random import Random
from package.file import gen_age
import unittest

class AgeTest(unittest.TestCase):

    def setUp(self):
        self.random = Random(666)

    @patch('package.file.random')
    def test_gen_age(self, random):
        random.randint._mock_side_effect = self.random.randint
        self.assertEqual(gen_age(), 53)

rawDescription: How to validate a unit test with random values

description: Validate a unit test with random values


code:
class maybelist(list):

    def __init__(self, *args):
        super().__init__(*args)
        self._extras = dict()

    def __setitem__(self, index, val):
        try:
            super().__setitem__(index, val)
            return
        except TypeError:
            # Index is not an integer, store in dict
            self._extras[index] = val
            return
        except IndexError:
            pass
        distance = index - len(self)
        if distance > 0:
            # Put 'None' in empty slots if need be
            self.extend((None,) * distance)
        self.append(val)

    def __getitem__(self, index):
        try:
            return super().__getitem__(index)
        except TypeError:
            return self._extras[index]

    def __str__(self):
        return str([item for item in self])

    def __len__(self):
        return super().__len__() + len(self._extras)

    def __iter__(self):
        for item in itertools.chain(super().__iter__(), self._extras):
            yield item

rawDescription: What is the overhead of using a dictionary instead of a list?


code:
from requests import Request, Session

with Session() as s:
    req = Request('POST', POST_ENDPOINT)
    prepped = req.prepare()
    prepare_body_with_size(prepped, files)
    response = s.send(prepped)

rawDescription: Is there a Python HTTP client that lets you set the size in Content-Disposition for posting files?


rawDescription: How to get every single permutation of a string?

description: Get every single permutation of a string


code:
texts = build_text_list(html)
print(texts[0])
parent = texts[0].getparent()
print(parent.tag)
print(texts[1])
print(texts[1].getparent().tag)

rawDescription: python lxml.html: proper way to iterate through text with .tail in docstring order

description: Python lxml.html: proper way to iterate through text with .tail in docstring order


code:
def contact_user(A,B,C):
  ser.write("ATDT411\r")  # Attention - Dial Tone 411
  time.sleep(5)  # Wait for modem to finish dialing
  pygame.mixer.music.load(A)
  pygame.mixer.music.play()  # Play attention chime
  time.sleep(2)  # Wait long enough for first message chime to play before moving on
  pygame.mixer.music.load(B)
  pygame.mixer.music.play(1) # Play next message
  time.sleep(2)  # Wait long enough for second message to play before moving on
  pygame.mixer.music.load(C) # Load last message
  pygame.mixer.music.queue(C)  # Queue second instance of last message
  pygame.mixer.music.play()  # Play last message twice
  time.sleep(10)  # Wait long enough for last message to play
  ser.write("ATH\r")  # Attention - Hang up line
  ser.write("ATZ\r")  # Attention - Reset modem
  ser.close()

rawDescription: python pygame threading

description: Python pygame threading


rawDescription: How to calculate a rolling count of a categorical variable in pandas

description: Calculate a rolling count of a categorical variable in pandas


code:
import sys

print(sys.getsizeof(zipped))    # => 524 bytes
print(sys.getsizeof(item))      # => 52 bytes

rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code:
self.listWidget.setViewMode(QtGui.QListView.IconMode)
item = QtGui.QListWidgetItem()
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/sameold/capture_14.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item.setIcon(icon)
self.listWidget.addItem(item)

rawDescription: Populating list with images in PYQT

description: Populating list with images in PYQT


code:
import json
from collections import OrderedDict

def get_json():
    file_name = raw_input("Enter name of JSON File: ")
    with open(file_name) as json_file:
        json_data = json.load(json_file, object_pairs_hook=OrderedDict)
    return json_data

rawDescription: refrencing certain values in a list

description: Refrencing certain values in a list


code: thread.start_new_thread(saveData,(slice1, slice2, slice3, dset))

rawDescription: executing a method at the same time in python

description: Executing a method at the same time in python


code:
class general:
    def __init__(self, msgs=[]):
        self.msgs = msgs

rawDescription: why is this code generating three array values instead of one? python 3.x

description: Why is this code generating three array values instead of one? python 3.x


code:
df.sort_index(by=['Date', 'Time'], inplace=True)
df.index = np.arange(1, len(df) + 1)

rawDescription: Python: Assigning timestamps to dataframe using separate date and time values in dataset


code:
out = []
for div in soup.findAll('li',{'class':'has-sub'}):
        out.append(tuple(x["href"] for x in div.find_all('a',href=True)))

rawDescription: how to select specific words and put them into tuple - list?

description: Select specific words and put them into tuple - list


rawDescription: Python: replace multiple values of a Matrix


code:
ofile.write('\t'.join(['{}-{}'.format(*pair) for pair in zip(a, b)]) + '\n')
ofile.write('\t'.join(map(str, c)) + '\n')

rawDescription: Return back to previous line in a text file


code: matches: [('56242', 'saddelmageri')]

rawDescription: Python regexp find two keywords in a line


rawDescription: Can any one help me to learn reverse url in django


code:
distributor=self
while distributor.has_downline():
    for person in distributor.downline:
        distributor = person

rawDescription: MLM downline distribution count

description: MLM downline distribution count


code:
import datetime
import time

before = datetime.datetime.now()  # don't convert to string!

time.sleep(5)  # do some stuff....

after = datetime.datetime.now()

delta = after - before
# delta is a datetime.timedelta object.

print(delta)
# which by default stringifies to %H:%M:%S.%f

rawDescription: Subtract one strftime string from another


code: {key: ' '.join(map(str, value)) for key, value in d2.items()}

rawDescription: Split string value of a dictionary

description: Split string value of a dictionary


rawDescription: How to determine the priority actions for a every unique user using pandas

description: Determine the priority actions for a every unique user using pandas


code:
import requests

url = 'https://www.tumblr.com/api/write'
data = {'email': your_email, 'password': your_password, 'type': 'photo'}
files = {'data': open('your_image.jpg')}

requests.post(url, data=data, files=files)

rawDescription: Post picture from directory to tumblr via python


code:
def testTestA_and_TestB(self):
    # test code from testTestA
    ...
    # test code from testTestB

rawDescription: Django TestCase testing order

description: Django TestCase testing order


code:
temp=[value]
valueslist.append(temp)

rawDescription: dictionary to list of tuples with smallest value

description: Dictionary to list of tuples with smallest value


code:
with subprocess.Popen(['/path/to/binary', '-p', 's']) as proc:
    stdout, stderr = proc.communicate()

rawDescription: Python subprocess passes one argument only


code:
import os
path='/my/path/'
l1=[2,0,1]
l2=[['a.txt','b.txt','c.txt'],['d.txt','f.txt','g.txt'],['h.txt','i.txt','j.txt']]
[[os.path.join(path, 'list%d'%l1_index, l2_value) for l2_value in l2[l1_index]] for l1_index in l1]

rawDescription: Creating nested lists with a list comprehension


code: table = soup.find('tbody').find('tr', {'class': 'zone-dedicated-availability'})

rawDescription: Python BeautifulSoup find span inside class


code:
import subprocess as sp
import os
import importlib

my_env = os.environ

rawDescription: Compiling C++ code using Python interpreter running under windows shell


code:
from pyparsing import *

def marker(key):
    return Combine(CaselessLiteral(key) + Word(nums))

pat    = marker("a")
visit  = marker("r")
clone  = marker("clone")
primer = marker("ba") | marker("primer")
sep    = oneOf("- _").suppress()
other  = Word(alphanums + ":")

file_ext = Literal(".").suppress() + Word(alphanums)
EOL    = LineEnd().suppress()

tokens = [pat("pat"),
          visit("visit"),
          clone("clone"),
          primer("primer"),
          sep,other]
grammar = OneOrMore(MatchFirst(tokens)) + file_ext + EOL

rawDescription: Pyparsing strings where the order is unknown and some items may be missing


code:
def MagicServer2():
    return GenericServer2(MagicCards)

rawDescription: Parallel Subclassing in Python? Using Subclasses in a Subclass


code:
self.app_data = {...}
page1 = Page1(self.notebook, self.app_data)
page2 = Page2(self.notebook, self.app_data)

rawDescription: TTK Notebook Share data between imported tabs


code:
averages = []
while True:
    form = input(
        'If you would like to view form 1 please enter "1".If you would like to view form 2 please enter "2" and If you would like to view form 3 please enter "3"')
    if form not in {"1", "2", "3"}:
        print("Invalid choice")
    else:
        break

if form == "1":
    sort = input(
        'If you would like the names sorted alphabetically enter "a".If you would like the scores sorted from highest to lowesr please enter "b" and If you would like the average scores sorted from highest to lowest please enter "c"')
    with  open("Form1.csv") as f:
        read_file = csv.reader(f)
        if sort == "a":
            sorted_file = sorted(read_file)
            for each_line in sorted_file:
                each_line.sort()
                print(each_line)
        elif sort == 'b':
            for line in read_file:
                integers = (line[0:4])
                integers.sort(reverse=True)
                print(integers)
        elif sort == 'c':
            for line in read_file:
                values = (line[2:4])
                values = list(map(int, values))
                average = (sum(values) / len(values))
                averages.append(average)
            averages.sort(reverse=True)
            print(averages)
elif form == "2":
    sort = input('If you would like the names sorted alphabetically enter "a".If you would like the scores sorted from highest to lowesr please enter "b" and If you would like the average scores sorted from highest to lowest please enter "c"')
    with open('Form2.csv') as f:
        read_file = csv.reader(f)
    if sort == "a":
        sorted_file = sorted(read_file)
        for each_line in sorted_file:
            each_line.sort()
            print(each_line)
    elif sort == 'b':
        for line in read_file:
            integers = (line[0:4])
            integers.sort(reverse = True)
            print(integers)

    elif sort == 'c':
        for line in read_file:
            values = (line[2:4])
            values = list(map(int, values))
            average = (sum(values)/len(values))
            averages.append(average)
            averages.sort(reverse = True)
            print(averages)
elif form == "3":
    sort = input(
        'If you would like the names sorted alphabetically enter "a".If you would like the scores sorted from highest to lowesr please enter "b" and If you would like the average scores sorted from highest to lowest please enter "c"')
    with open("Form3.csv") as f:
        read_file = csv.reader(f)
        if sort == "a":
            sorted_file = sorted(read_file)
            for each_line in sorted_file:
                each_line.sort()
                print(each_line)
        elif sort == 'b':
            for line in read_file:
                integers = (line[0:4])
                integers.sort(reverse=True)
                print(integers)
        elif sort == 'c':
            for line in read_file:
                values = (line[2:4])
                values = list(map(int, values))
                average = (sum(values) / len(values))
                averages.append(average)
            averages.sort(reverse=True)
            print(averages)

rawDescription: In my code i am getting a name error saying the name 'sort' is not defined


code:
import csv;

dict={};
with open('training_data.csv','rU') as f:
    reader = csv.reader(f,skipinitialspace=True);
    for line in reader:
        try:
            dict[line[2]].append("\n"+line[3].replace("\n", ", "));
        except:
            dict[line[2]]=[line[3].replace("\n", ", ")];

with open('training_result.csv','w') as f:
    writer = csv.writer(f, delimiter=',',dialect='excel-tab');
    for key in dict:
        writer.writerow([key,','.join(dict[key])]);

rawDescription: universal new line mode in csv reader make csv writer write mistake line break in file

description: Universal new line mode in csv reader make csv writer write mistake line break in file


code: example(lambda n: n * n)

rawDescription: How can I pass functions or operators as arguments to a function in Python?

description: Pass functions or operators as arguments to a function in Python


code:
Example
salt, hashed = 'qb', '1Y.qWr.DHs6'
print(decrypt(salt + hashed))
# -> e2e4
assert crypt('e2e4', 'qb') == (salt + hashed)

rawDescription: How to encrypt all possible strings in a defined character set python?

description: Encrypt all possible strings in a defined character set python


code:
lower = [(d-L)/2+1 for d in y.shape]
upper = [(d+L)/2+1 for d in y.shape]
y[lower[0]:upper[0],:,:] # middle of axis 0
y[:,lower[1]:upper[1],:] # middle of axis 1
y[:,:,lower[2]:upper[2]] # middle of axis 2

rawDescription: which are the high frequency terms in numpy.fftn?

description: Which are the high frequency terms in numpy.fftn


code: print (''.join(final1))

rawDescription: How do I loop through a list?

description: Loop through a list


code:
S = "ABCDE"
fixed_dict = {m: list(itertools.combinations(S,m)) for m in range(len(S)+1)}
def find2(m, d):
    return random.sample(fixed_dict[m], d)

rawDescription: Python- exact number of subsets

description: Python- exact number of subsets


code:
import  csv
from collections import OrderedDict
d  = OrderedDict()

with open("in.txt") as f:
    for k, _, v in csv.reader(f, delimiter=" "):
        d.setdefault(k, []).append(v)

rawDescription: convert data table format in python

description: Convert data table format in python


code:
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, nodelist=["A", "B"], node_size=1000, node_color='#A0CBE2', font_size=20, width=2)
nx.draw_networkx(G, pos=pos, nodelist=["C"], node_size=2000, node_color='#FF0000', font_size=20, width=2,)
nx.draw_networkx(G, pos=pos, nodelist=["D"], node_size=3000, node_color='#FFFF00', font_size=20, width=2)

rawDescription: How to determine specific color and size of chosen nodes in Networkx graph plot

description: Determine specific color and size of chosen nodes in Networkx graph plot


code:
filename="myFileName.something"
name=filename.split(".")[0]
myCommand="rungms %s.inp 13-64 1 0 %s.out"%(name,name)

rawDescription: Get name of file for command line

description: Get name of file for command line


code:
def my_parsedate(text):
    return datetime.datetime(*eut.parsedate(text)[:6])

rawDescription: How do I parse an HTTP date-string in Python?

description: Parse an HTTP date-string in Python


code:
def sum_axis_i(arr, axis, i):
    idx = (np.s_[:],) * axis + (i,)
    return arr[idx].sum()

rawDescription: select all dimensions of an ndarray but one

description: Select all dimensions of an ndarray but one


code: mylist = [row[0] for row in result]

rawDescription: How can I fetch mysql single column list results directly into a list in python?

description: Fetch mysql single column list results directly into a list in python


rawDescription: Python Pandas Conditional Sums

description: Python Pandas Conditional Sums


code:
class MyCustomWriteForm(BaseWriteForm):
    recipients = autocomplete_light.ChoiceField(
        'UserAutocomplete', label='recipients')

    class Meta(BaseWriteForm.Meta):
        fields = ('recipients', 'subject', 'body')

rawDescription: django-postman + django-ajax-selects usage

description: Django-postman + django-ajax-selects usage


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-d', type=int, nargs='?')
parser.add_argument('-c', type=int, nargs='?')
parser.add_argument('args', type=int, nargs='*')

print(parser.parse_args())

rawDescription: Argparse : Formatting arguments

description: Argparse : Formatting arguments


code:
last_ip_raw = c.execute('SELECT ip FROM dl ORDER BY id DESC LIMIT 1')
last_ip_tup = c.fetchone()
last_ip = str("%s" % last_ip_tup)

rawDescription: Download counter: cgi FieldStorage reset pressed button values


code:
s = "<word1></word1> <word2>worda</word2> <word3>wordb</word3> <word4></word4>"
s.replace(">", "> ").replace("<", " <").split()

rawDescription: Splitting a string into multiple strings in Python


rawDescription: Pythonic iteration over multiple lists in parallel


code: print(*filtered_list, sep='\n')

rawDescription: Searching items in two lists

description: Searching items in two lists


code:
def weekday_index(d):
    return (d.day + 6) // 7

rawDescription: Python: weekday position of following months


code: MyFormSet = formset_factory(MyForm, formset=RequiredFormSet)

rawDescription: Django formsets: make first required?

description: Django formsets: make first required


code:
@register.filter( name='safewrap' )
def safewrap( val, arg ):
    return val.format( arg )
safewrap.is_safe = True

rawDescription: Django Localization: How To Make 'po' file without HTML?


rawDescription: How to tell if a date is between two other dates in Python?

description: Tell if a date is between two other dates in Python


code:
import itertools
numbers = [1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2]
list(k for k, g in itertools.groupby(numbers))

rawDescription: Grouping a series in Python

description: Grouping a series in Python


rawDescription: Python instance of class defined inside a method is still able to use local variables inside the method when called outside the method


rawDescription: How to introduce the attributes of an object in python by calling a method in __init__ method?

description: Introduce the attributes of an object in python by calling a method in __init__ method


code: [{key: val.strip() for key, val in i.items()} for i in listofdict]

rawDescription: How to delete characters from string values of dictionaries in list?

description: Delete characters from string values of dictionaries in list


rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


rawDescription: Finding a set in a Dictionary fitting a certain criteria


code:
names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
names_dict = dict((name,index)
                  for index,lst in enumerate(names)
                  for name in lst)
names_dict

rawDescription: Python Golf: what's the most concise way of turning this list of lists into a dictionary:


code:
import time

image1 = ("image1.png")
image2 = ("image2.png")
image3 = ("image3.png")
alarm = '17:37:00'

class Robot():
    # Automaticly executes when class is called.
    def __init__(self):
        # Wait until it is time for the alarm to go off.
        while (True):
            # Look what time it is right now [24 hour format].
            currentTime = time.strftime("%H:%M:%S")
            if (currentTime == alarm):
                print('It is time!')
                # Call another definition.
                self.startWork()
                # Exit the (while) loop to finsih the script.
                break;

    # Find and click the image.
    def startWork(self):
        while not exists(image1):
            # We didn't see the image, sleep for 1 second.
            wait(1)
        # When the code gets here, image1 has appeared.
        imageLoc1 = find(image1)
        imageLoc1.click()
        # Now we are going to look if we see eather image2 or image3
        while not exists(image2) or not exists(image3):
            wait(1)
        # Image2 or image3 is seen.
        if exists(image2):
            imageLoc2 = find(image2)
            imageLoc2.click()
        elif exists(image3):
            imageLoc3 = find(image3)
            imageLoc3.click()

# Run class
Robot()

rawDescription: sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working?

description: Sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working


code:
r'\textbf{This and that} plus \textbf{val}'.format(val='6')
r'\textbf{{This and that}} plus \textbf{{{val}}}'.format(val='6')

rawDescription: Format a string that has extra curly braces in it


code:
removed = [o for o in old if o[0] not in [n[0] for n in new]]
added = [n for n in new if n[0] not in [o[0] for o in old]]

rawDescription: python compare difference between two lists

description: Python compare difference between two lists


code:
a = open('testfile.txt')
line = a.readline()
line
print(line)

rawDescription: Reading Regular Expressions from a text file


code:
def datetime_to_float(d):
    return d.timestamp()

rawDescription: python datetime to float with millisecond precision [Solved]

description: Python datetime to float with millisecond precision [Solved]


code:
slice(None, 5, None)
slice(5, 15, None)
slice(5, 15, 3)
3
slice(5, None, 3)
slice(None, None, 2)
slice(None, None, None)

rawDescription: numpy.array indices via argparse - How to do it properly?

description: Numpy.array indices via argparse - How to do it properly


code: p[s] == np.arange(n)

rawDescription: How to invert a permutation array in numpy

description: Invert a permutation array in numpy


rawDescription: Writing from one file to another python

description: Writing from one file to another python


code: df

rawDescription: creating multiple dataframes which contain subsets of an orginal pandas dataframe

description: Creating multiple dataframes which contain subsets of an orginal pandas dataframe


rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


rawDescription: Numpy boolean index mask for conditional subtraction of existing values


rawDescription: How to expose a filtered reverse relationship in Django REST API framework?

description: Expose a filtered reverse relationship in Django REST API framework


code:
rmlag = lambda xs: np.argmax(xs[::-1])
pd.rolling_apply(ts, func=rmlag, window=3, min_periods=0).astype(int)

rawDescription: Using Pandas To Find the Number Of Periods Since the Rolling High


code:
nli._insert_at(nli.stack[:-1], 10)
nli.nested_list
nli.get_item()

rawDescription: Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list


lulz: only for the

bar: test

foo: foo

rawDescription: Easier way to create a JSON object from an SQLObject


code:
string = 'German apple is good. Apple is nice. Where is the apple? English apple have worms. English people are nice.'
re.sub(r'(?i)(?:English )?(?:(?<!German )\bapple\b)', r'German apple', string)

rawDescription: How to find/replace standalone words or words with certain adjectives?

description: Find/replace standalone words or words with certain adjectives


code:
colors = []
for value in dictionary.keys(): # keys are the names of the boys
    if winner == value:
        colors.append('r')
    else:
        colors.append('b')

bar(ind,num,width,color=colors)

rawDescription: how to change the color of a single bar if condition is True matplotlib

description: Change the color of a single bar if condition is True matplotlib


code:
Input
ABCDE1
FGHIJ
ABCDE
FGHI

rawDescription: Python - How can I change bytes in a file


rawDescription: Convert from 24 bit signed to latitude / longitude?


rawDescription: Matching only some words in query using Django Haystack


code:
def justify(n):
    return n / 1<<(n.bit_length()-1)

rawDescription: Bitwise operations to produce power of two in Python


code:
def extend_with_openid_shutdown_ack(self, realm, return_to=None, immediate=False):
    message = consumer.AuthRequest.getMessage(self, realm, return_to, immediate)
    message.setArg(consumer.BARE_NS, 'openid_shutdown_ack','2015-04-20')
    return message

rawDescription: passing openid_shutdown_ack parameter to my applicion using the Python OpenID library

description: Passing openid_shutdown_ack parameter to my applicion using the Python OpenID library


code:
from PIL import ImageFile, BmpImagePlugin

_i16, _i32 = BmpImagePlugin.i16, BmpImagePlugin.i32

class BmpAlphaImageFile(ImageFile.ImageFile):
    format = "BMP+Alpha"
    format_description = "BMP with full alpha channel"

    def _open(self):
        s = self.fp.read(14)
        if s[:2] != 'BM':
            raise SyntaxError("Not a BMP file")
        offset = _i32(s[10:])

        self._read_bitmap(offset)

    def _read_bitmap(self, offset):

        s = self.fp.read(4)
        s += ImageFile._safe_read(self.fp, _i32(s) - 4)

        if len(s) not in (40, 108, 124):
            # Only accept BMP v3, v4, and v5.
            raise IOError("Unsupported BMP header type (%d)" % len(s))

        bpp = _i16(s[14:])
        if bpp != 32:
            # Only accept BMP with alpha.
            raise IOError("Unsupported BMP pixel depth (%d)" % bpp)

        compression = _i32(s[16:])
        if compression == 3:
            # BI_BITFIELDS compression
            mask = (_i32(self.fp.read(4)), _i32(self.fp.read(4)),
                    _i32(self.fp.read(4)), _i32(self.fp.read(4)))
            # XXX Handle mask.
        elif compression != 0:
            # Only accept uncompressed BMP.
            raise IOError("Unsupported BMP compression (%d)" % compression)

        self.mode, rawmode = 'RGBA', 'BGRA'

        self.size = (_i32(s[4:]), _i32(s[8:]))
        direction = -1
        if s[11] == '\xff':
            # upside-down storage
            self.size = self.size[0], 2**32 - self.size[1]
            direction = 0

        self.info["compression"] = compression

        # data descriptor
        self.tile = [("raw", (0, 0) + self.size, offset,
            (rawmode, 0, direction))]

rawDescription: Load RGBA bitmap with PIL

description: Load RGBA bitmap with PIL


code:
import multiprocessing

class TaskThread(object):
    def __init__(self, manager):
        self.queue = manager.Queue()

    def __call__(self):
        print("in TaskThread.__call__")
        self.queue.put(1)

if __name__ == "__main__":
    pool=multiprocessing.Pool(4)
    m = multiprocessing.Manager()
    task=TaskThread(m)
    result = pool.apply_async(task)
    result.get()
    print(task.queue.get())

rawDescription: Is it possible to apply a callable object to a pool of processes?


code: data.loc[condition, 'x'] = 1

rawDescription: Pandas logical indexing on a single column of a dataframe to assign values


rawDescription: Finding the maximum return value of a function and the corresponding input for a given number of inputs


code:
if cond1 == 'val1' and cond2 == 'val2' and \
   cond3 == 'val3' and cond4 == 'val4':
    do_something

rawDescription: Python style: multiple-line conditions in IFs


code:
from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

rawDescription: How do you run your own code alongside Tkinter's event loop?

description: Run your own code alongside Tkinter's event loop


code:
if x < 0 or x > sw-120:
    dx = -dx
    x += dx
if y < -85 or y > sh-175:
    dy = -dy
    y += dy

rawDescription: Moving object across screen in Pygame

description: Moving object across screen in Pygame


code:
import pandas as pd
data = pd.DataFrame({"x":[1,2,3], "y": [3,2,1]})

rawDescription: ipython-notebook: print rmagic plots as svg

description: Ipython-notebook: print rmagic plots as svg


code:
a = ['cinema','host','aab','train']
b = ['iceman', 'shot', 'bab', 'rain']
anagram_solver(a, b)

rawDescription: Anagram check in Python

description: Anagram check in Python


code:
from itertools import groupby
with open("foo.txt") as f:
    grouped, data = groupby(map(str.rstrip,f), key=lambda x: x.strip().startswith("BARCODE")), []
    for k,v in grouped:
        if not k:
            data.append("".join(v)+"".join(next(grouped)[1]))

print(data[0])
print()
print(data[1])

rawDescription: Convert multiple lines to single line and store in a variable for further analysis


code: sdev = sqrt(sum((y - np.polyval(fit, x))**2)/(len(y) - 1))

rawDescription: Python numpy polynomial fit: How to draw region of uncertainty curve?


code:
f = ViewClass.as_view()
f = condition(...)(f)

rawDescription: Using ETag / Last-Modified decorators with Django's class-based generic views


code:
for line in iter(arpA_req.stdout.readline, ''):
    print(line)

rawDescription: Subprocess arp -a yielding less results than cmd arp -a


code:
db = {}
db['new_user'] = 'password'

with open('database.db', 'wb') as fh:
    pickle.dump(db, fh)

rawDescription: Remember variables after code execution

description: Remember variables after code execution


code:
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

class MyFrame(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.txt = tk.Text(self)
        self.txt.pack()
        self.txt.insert(0.0, 'hello\nworld')
        self.btn = tk.Button(self, text='add_term', command=self.add_term)
        self.btn.pack()
        self.txt.tag_config('term', background='red')

    def add_term(self):
        self.txt.insert(tk.SEL_FIRST,'\\term{')
        self.txt.insert(tk.SEL_LAST,'}' )
        self.txt.tag_add('term', tk.SEL_FIRST + '-6c', tk.SEL_FIRST)
        self.txt.tag_add('term', tk.SEL_LAST, tk.SEL_LAST + '+1c')

root = tk.Tk()
f = MyFrame(root)
f.pack()
root.mainloop()

rawDescription: Adding coloured text to selected text - Tkinter


code:
import matplotlib.pyplot as plt
plt.ion()
plt.imshow(a, cmap='gray', interpolation='none')

rawDescription: "Simplest" way to graphically represent a matrix


code:
"""
>>> from models import *

Create some food records

>>> weed = Food(name="weed")
>>> weed.save()

>>> burger = Food(name="burger")
>>> burger.save()

>>> pet_food = Food(name="Pet food")
>>> pet_food.save()

John the farmer likes burgers

>>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12")
>>> john.save()
>>> john.foods.create(food=burger)
<ConsumedFood: ConsumedFood object>

Wilma the cow eats weed

>>> wilma = Cow(farmer=john)
>>> wilma.save()
>>> wilma.foods.create(food=weed)
<ConsumedFood: ConsumedFood object>

Felix the cat likes pet food

>>> felix = Cat(name="felix")
>>> felix.save()
>>> pet_food.eaters.create(eaten_by=felix)
<ConsumedFood: ConsumedFood object>

What food john likes again ?
>>> john.foods.all()[0].food.name
u'burger'

Who's getting pet food ?
>>> living_thing = pet_food.eaters.all()[0].eaten_by
>>> isinstance(living_thing,Cow)
False
>>> isinstance(living_thing,Cat)
True

John's farm is in fire ! He looses his cow.
>>> wilma.delete()

John is a lot poorer right now
>>> john.foods.clear()
>>> john.foods.create(food=pet_food)
<ConsumedFood: ConsumedFood object>

Who's eating pet food now ?
>>> for consumed_food in pet_food.eaters.all():
...    consumed_food.eaten_by
<Cat: Cat object>
<Person: Person object>

Get the second pet food eater
>>> living_thing = pet_food.eaters.all()[1].eaten_by

Try to find if it's a person and reveal his name
>>> if isinstance(living_thing,Person): living_thing.first_name
u'John'

"""

rawDescription: How can one get the set of all classes with reverse relationships for a model in Django?


code:
W = tf.Variable(...)

embedding_saver = tf.train.Saver({"name_of_variable_in_other_model": W})

# ...
sess = tf.Session()
embedding_saver.restore(sess, "checkpoint_filename.ckpt")

rawDescription: Using a pre-trained word embedding (word2vec or Glove) in TensorFlow


code:
if player == player1:
   score1=score1+1
if player == player2:
   score2=score2+1

rawDescription: Modifying code avoiding break statements


code:
def findall(target, key, start=0):
  for match in iter(lambda: find(target, key, start), -1):
    yield match
    start = match + 1

rawDescription: Assigning value in a while comparison expression


rawDescription: In Python, how do I find common words from two lists while preserving word order?


rawDescription: How can I make a "tuple of an ndarray of ndarrays"?

description: Make a "tuple of an ndarray of ndarrays"


rawDescription: confusion in output of local and global variables in python

description: Confusion in output of local and global variables in python


rawDescription: Python: list directory using user input as directory name not working


code: count = {x:sum([1 for char in vowels if char==x])for x in 'aeiouy'}

rawDescription: Vowel counter in a text file

description: Vowel counter in a text file


code:
class A(object):
    def __init__(self, class_b):
        self.class_b = class_b
        ...

class B(object):
    def __init__(self, class_c):
        ...

...

rawDescription: Automocking for Python?

description: Automocking for Python


code:
class ReleaseArchiveView(BaseZipView):
    model = Release

    def get_files(self):
        sounds =  Sound.objects.filter(release__slug=self.kwargs.get('slug'))
        return [s.file.file for s in sounds if s.file.name]

rawDescription: Returning File Fields through Many to Many Relationship in Django for Zipview


code:
def genIndexList(length, ID):
   indexInfoList = []
   id0 = str(ID)[0]
   for i in xrange(length):
       i3 = format(decimalToBase3(i), '012d')
       p = sum(map(int, id0 + i3[::2])) % 3
       indexInfoList.append('{}{}{}'.format(ID, i3, p))
   return indexInfoList

rawDescription: Improve efficiency of modules

description: Improve efficiency of modules


rawDescription: How to extract percentage every 10 seconds from this lines?

description: Extract percentage every 10 seconds from this lines


code:
def dict_into_list(self):
    result = {}
    for each_key, each_item in self.__dict__.items():
        print(type(each_key), type(each_item))
        if inspect.isfunction(each_item) == False:
            result[each_key] = each_item
    return result

rawDescription: Adding items to a list if it's not a function


code: {k: [i for i in v if i != 'E'] for k, v in mydict.iteritems() if k != 'E'}

rawDescription: Pythonic way to delete an item completely from a dictionary


rawDescription: Python: elegant way to split a string in order to pick the last element when the len of string is unknown


rawDescription: Type-Checking in Functions between Python 2.7 and Python 3.3


code:
def get_sorted_indices(l):
    sorted_positions = sorted(range(len(l)), key=l.__getitem__)
    result = [None for _ in range(len(l))]
    for new_index, old_index in enumerate(sorted_positions):
        result[old_index] = new_index
    return result

rawDescription: Given a "jumbled" list L, get a list where each element is the index of the corresponding element of L, if L was sorted


code:
def f_wrapper(option=True):
    gen = f()
    if option:
        return gen    # return the generator unchanged
    return list(gen)  # return all values of the generator as a list

rawDescription: Optional yield or return in python3. How to?


rawDescription: Convert String to Int without int()

description: Convert String to Int without int()


code: map(sum, arra)

rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


rawDescription: Base conversion for an array of integers


code: propertyDict = {k: v for k, v in propertyDict.iteritems() if v}

rawDescription: Python Create dictionary if properties are found


code:
for elem in b:
    if elem == a:
        return True

rawDescription: Find tuple structure containing an unknown value inside a list


code: imat = [list(m) for m in zip(*mat)]

rawDescription: Python Array Cleanup Issues

description: Python Array Cleanup Issues


code: longitudes = np.linspace(0, 2*np.pi, N_POINTS)

rawDescription: Matplotlib plot_surface spurious faces

description: Matplotlib plot_surface spurious faces


code:
import sys

sys.modules["mymodule"] = mymodule

rawDescription: Purpose and usage of PyModule_New

description: Purpose and usage of PyModule_New


code:
def main():
    print("<------Initializing Updating Process------>")
    srcFile ='abc_20160301_(file1).csv'
    update2new(srcFile) #the return is NOT captured here
    print('\nSuccessfully Executed [ {}]......'.format(str(srcFile)),end='\n')
    print ("OK")

rawDescription: Why fuction's not returning value?

description: Why fuction's not returning value


code:
while current_frame <= max_frames:
    # ... do stuff
    time.sleep(1./25)

rawDescription: Limit loop frame rate

description: Limit loop frame rate


code: numpy.dot(M[:,0], numpy.ones((1, R)))

rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
from operator import iadd

result = reduce(iadd, [[k] * v for k, v in d.iteritems() if v > 0], [])

rawDescription: Removing Elements in A from B

description: Removing Elements in A from B


rawDescription: Merge 2 arrays vertical to tuple Numpy

description: Merge 2 arrays vertical to tuple Numpy


code:
import datetime
d = datetime.datetime.today()
d.isoformat(' ')
d.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Date formate conversion in Python

description: Date formate conversion in Python


rawDescription: Certain Power of Sum of Digits of N == N (running too slowly)


code: rows, cols = np.nonzero(diff < .5)

rawDescription: Searching for a line in a jpg file Python


code:
figw, figh = 16.0, 8.0
fig, axes = plt.subplots(ncols=6, nrows=2, sharex=True, sharey=True,
                         figsize=(figw, figh))
plt.subplots_adjust(left=1/figw, right=1-1/figw, bottom=1/figh, top=1-1/figh)

rawDescription: Adjusting space around figure with subplots


code:
import re
token = re.search("accounts.google.com/Captcha\?ctoken=([^\"]+)", html).group(1)
url = "https://accounts.google.com/Captcha?ctoken=" + token

rawDescription: How do I submit a request for a new Google account?

description: Submit a request for a new Google account


code: result = [ l for l in l2 if (l[0],) in l1]

rawDescription: Merging list of tuples in python

description: Merging list of tuples in python


code:
Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

rawDescription: Combining queries in django

description: Combining queries in django


code:
for package in mpl_packages:
    if isinstance(package, str):
        print_raw('')
        print_raw(package.upper())
    else:
        try:
            result = package.check()
            if result is not None:
                message = 'yes [%s]' % result
                print_status(package.name, message)
        except setupext.CheckFailed as e:
            msg = str(e).strip()
            if len(msg):
                print_status(package.name, 'no  [%s]' % msg)
            else:
                print_status(package.name, 'no')
            if not package.optional:
                required_failed.append(package)
        else:
            good_packages.append(package)
            if isinstance(package, setupext.OptionalBackendPackage):
                if default_backend is None:
                    default_backend = package.name

rawDescription: How to know the enabled features of a matplotlib installation?

description: Know the enabled features of a matplotlib installation


code: scrollview = ScrollView(size_hint=(None, None), size=(400, 400), pos_hint={'center_x': .5, 'center_y': .5})

rawDescription: Making a gridview inside of an scrollview, that is the size of the screen


code: reader_input = io.TextIOWrapper(urlopen(url), encoding='utf8', newline='')

rawDescription: Is there a better way to do csv/namedtuple with urlopen?


rawDescription: python addition 2 digit number

description: Python addition 2 digit number


code:
while itemq.isEmpty():
        cond.wait()

rawDescription: python threads - how do "condition.wait" and "condition.notifyAll" work

description: Python threads - how do "condition.wait" and "condition.notifyAll" work


code:
class bound_int(int):
    def __new__(cls, value, obj):
        val = int.__new__(cls, value)
        val.obj = obj
        return val
    def getAttributes(self):
        return self.obj.somePyClassProp

rawDescription: How to know which next attribute is requested in python

description: Know which next attribute is requested in python


code:
from collections import namedtuple
MyTuple = namedtuple('MyTuple', ('owner', 'type'))
d3 = {'key': MyTuple('owner', 'type')}
d3['key'].owner
d3['key'].type

rawDescription: Multiple Values for a single key in a dictionary


rawDescription: The fractions are incomplete

description: The fractions are incomplete


code:
# Get unique elements and their counts
unq,counts = np.unique(a,return_counts=True)

# Get the positions of unique elements in a.
# Use those positions to index into counts array for final output.
out = counts[np.searchsorted(unq,a.ravel())]

rawDescription: How to count num of elements vector with numpy python

description: Count num of elements vector with numpy python


rawDescription: How does one get an Enum's members into the global namespace?

description: Get an Enum's members into the global namespace


code:
temp[:,1:] = my_array
temp[:,0] = np.arange(1, len(my_array)+1)

rawDescription: Formatting a NumPy array

description: Formatting a NumPy array


code:
with open('file1', 'w') as f1, open('file2', 'w') as f2, open('file3', 'w') as f3:
    for entry in List1:
        if len(entry) == 7:
            f1.write(entry)
        elif len(entry) == 8:
            f2.write(entry)
        elif len(entry) == 9:
            f3.write(entry)

rawDescription: Extract elements from a list and sorting them by length


code:
def foo():
    pass

foo_decorated = decorator_expr(foo)

rawDescription: Decorated function along with original, without having to re-write the function


code: re.sub(r'{([^{}]+)}', lambda m: str(data[m.group(1)]), template_text)

rawDescription: python - replace string entry with a dictionary entry

description: Python - replace string entry with a dictionary entry


code:
m = line.split("¬")[2].split()
firstname = m[0]
surname = m[-1]
initials = m[1:-1] # Maybe just keep this as a list?

rawDescription: Parsing name and address information with differing number of spaces


code:
a = arange(50)
b = ones(50) * 2
a
b
a * b
(a * b).sum()

rawDescription: Computing complex math equations in python


code: 2840,test_category_labeling_highlight,84,3635,0,Other,"{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}",8,7,FALSE

rawDescription: How can I extract a JSON object from a CSV file in Python?

description: Extract a JSON object from a CSV file in Python


code:
def get_key_(start):
    offset = start - int(start)
    def get_key(x):
        w = int(x) + offset
        return w if x >= w else int(x - 1) + offset
    return get_key

rawDescription: Using Apache-Spark to analyze time series


code:
from itertools import islice
with open("Input.txt") as in_f, open("Output.txt", "w") as out_file:
    for line in ([i.rstrip()] + map(str.rstrip, islice(in_f, 3)) for i in in_f):
        out_file.write("\t".join(line) + "\n")

rawDescription: Python CSV transpose data in one column to rows


code: lambda cls, v: cls.setAttribute( cls, column, v )

rawDescription: python create class methods on the fly

description: Python create class methods on the fly


code:
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)

rawDescription: How do I go straight to template, in Django's urls.py?

description: Go straight to template, in Django's urls.py


code:
from collections import Counter
a = [1,2,5,5,8,8,5,7,8]

rawDescription: get most common element but if frequencies match, get lower element

description: Get most common element but if frequencies match, get lower element


code:
from heapq import heapify, heappop
user_input = raw_input("Enter numbers to be sorted: ")
data = user_input.split(",")
data = map(str.strip, data)
new_data = []

heapify(data)
for i in range(len(data)):
    print(data)
    new_data.append(heappop(data))

print(new_data)

rawDescription: Heapsort not working in Python for list of strings using heapq module


code:
from ftplib import FTP

def func(hostname, username, password):
    ftp = FTP(hostname, username, password)

    ftp.retrbinary('RETR README', open('README', 'wb').write)

rawDescription: Mocking FTP in unit test

description: Mocking FTP in unit test


code:
dfrm.index = range(len(dfrm))
dfrm

rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code:
from collections import OrderedDict
from io import StringIO

s = '''Jakub Scored: 10
Dan Scored: 10
Jake Scored: 9
Harry Scored: 5'''

f = StringIO(s)

dictionary = {}
for line in f:
    firstpart, secondpart = line.strip().split(':')
    dictionary[firstpart.strip()] = secondpart.strip()
f.close()

sorted_dict = OrderedDict(sorted(dictionary.items()))

print(sorted_dict)
# OrderedDict([('Dan Scored', '10'), ('Harry Scored', '5'), ('Jake Scored', '9'), ('Jakub Scored', '10')])

rawDescription: Alphabetically sorting a dictionary

description: Alphabetically sorting a dictionary


code:
import iso8601
datetimetext, tz = s.rsplit(None, 1)  # only grab the timezone portion.
timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:]))
dt = datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)

rawDescription: Comparing dates in Python - how to handle time zone modifiers


code:
rawdict.data = '{2}'
print(rawdict._buffer)
# deque(['{1}', '{2}'], maxlen=5)

rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


code: insert = tree_operation(insert)

rawDescription: Higher order functions in tree traversal


code:
import functools
import collections

import flask

BreadCrumb = collections.namedtuple('BreadCrumb', ['path', 'title'])

def breadcrumb(view_title):
    def decorator(f):
        @functools.wraps(f)
        def decorated_function(*args, **kwargs):
            # Put title into flask.g so views have access and
            # don't need to repeat it
            flask.g.title = view_title
            # Also put previous breadcrumbs there, ready for view to use
            session_crumbs = flask.session.setdefault('crumbs', [])
            flask.g.breadcrumbs = []
            for path, title in session_crumbs:
                flask.g.breadcrumbs.append(BreadCrumb(path, title))

            # Call the view
            rv = f(*args, **kwargs)

            # Now add the request path and title for that view
            # to the list of crumbs we store in the session.
            flask.session.modified = True
            session_crumbs.append((flask.request.path, view_title))
            # Only keep most recent crumbs (number should be configurable)
            if len(session_crumbs) > 3:
                session_crumbs.pop(0)

            return rv
        return decorated_function
    return decorator

rawDescription: Implementing breadcrumbs in Python using Flask?


code:
from copy import deepcopy

def srt(args):
    for ind, sub in enumerate(args, 1):
        sub.sort()
        yield ind, sub

d = defaultdict(defaultdict)
orig = [list1, list2, list3, list4, list5, list6]

all_best = defaultdict(int)

subs = sorted(srt(deepcopy(orig)), key=itemgetter(1))
for ind, ele in subs:
    best, partner = None, None
    for i2, ele2 in subs:
        if ind == i2:
            continue
        _int = len(set(ele).intersection(ele2))
        if best is None or best < _int:
            best = _int
            partner = i2
            if all_best[ind] < best:
                all_best[ind] = best
    d[ind][partner] = best
    d[partner][ind] = best

grouped = []

used = set()
for k, v in (d.items()):
    if all(val == all_best[_k] for _k, val in v.items()):
        best = [k] + list(v)
        if not any(s in used for s in best):
            grouped.append(best)
        used.update(best)

print(grouped)
print([[orig[ind-1] for ind in grp] for grp in grouped])

rawDescription: compare multiple lists in python

description: Compare multiple lists in python


code:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

rawDescription: Render HTML to PDF in Django site

description: Render HTML to PDF in Django site


code:
def combs3(iterable, elt2ec, k, maxec):
    # Generate all k-combinations from `iterable` spanning no
    # more than `maxec` equivalence classes.
    elts = tuple(iterable)
    n = len(elts)
    ec = [None] * n  # ec[i] is equiv class ordinal of elts[i]
    ec2j = {} # map equiv class to its ordinal
    for i, elt in enumerate(elts):
        thisec = elt2ec[elt]
        j = ec2j.get(thisec)
        if j is None:
            j = len(ec2j)
            ec2j[thisec] = j
        ec[i] = j
    countec = [0] * len(ec2j)
    del ec2j

    def inner(i, j, totalec):
        if i == k:
            yield result
            return
        for j in range(j, jbound[i]):
            thisec = ec[j]
            thiscount = countec[thisec]
            newtotalec = totalec + (thiscount == 0)
            if newtotalec <= maxec:
                countec[thisec] = thiscount + 1
                result[i] = j
                yield from inner(i+1, j+1, newtotalec)
                countec[thisec] = thiscount

    jbound = list(range(n-k+1, n+1))
    result = [None] * k
    for _ in inner(0, 0, 0):
         yield (elts[i] for i in result)

rawDescription: Efficient combinations of N colored elements with restriction in the number of colors


code:
def get_year(input_sequence):
    year, prefix, index, suffix = input_sequence
    return year

rawDescription: Why do some Python functions have an extra set of parenthesis around the argument list?


code:
# Defining the Digraph method #
def digraphs(s):
    dictionary = {}

    for count in range(len(s)):
        string = s[count:count + 2]
        dictionary['/' + string + '/'] = s.count(string)

    return dictionary
#--End of the Digraph Method---#

rawDescription: Cannot get dictionary keys to look like i want them to


code: majority_x[inds, :]

rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


rawDescription: Create a "wrapped" ndarray from a given array


code:
for row in rows:
    cols = row.findAll('td')
    ...

rawDescription: How do I find an element with a certain class in a web page with BeautifulSoup?

description: Find an element with a certain class in a web page with BeautifulSoup


rawDescription: Python: how the get the consecutive n-size pieces in a string?


code:
a = my_new_generator()
next(a)

rawDescription: Where is the best place to put support functions in a class?


rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


rawDescription: Finding Integers With A Certain Property - Project Euler Problem 221


rawDescription: Python magic function, how does it work?

description: Python magic function, how does it work


code:
try:
    create_temp_file()
finally:
    delete_temp_file()

rawDescription: Best way to clean a temporary files if script can be interrupted

description: Clean a temporary files if script can be interrupted


code: [row[:-1] + (rank,) for rank, row in enumerate(sorted(rows, reverse=True), start=1)]

rawDescription: Sort and rank list python and write back to MySQL using python


code:
import re

FORMATS_TYPES = {
    'd': int,
    'f': float,
    's': str,
}

FORMATS_REGEXES = {
    'd': re.compile(r'(?:\s|\b)*([+-]?\d+)(?:\s|\b)*'),
    'f': re.compile(r'(?:\s|\b)*([+-]?\d+\.?\d*)(?:\s|\b)*'),
    's': re.compile(r'\b(\w+)\b'),
}

FORMAT_FIELD_REGEX = re.compile(r'%(s|d|f)')

def scan_input(format_string, stream, max_size=float('+inf'), chunk_size=1024):
    """Scan an input stream and retrieve formatted input."""

    chunk = ''
    format_fields = format_string.split()[::-1]
    while format_fields:
        fields = FORMAT_FIELD_REGEX.findall(format_fields.pop())
        if not chunk:
            chunk = _get_chunk(stream, chunk_size)

        for field in fields:
            field_regex = FORMATS_REGEXES[field]
            match = field_regex.search(chunk)
            length_before = len(chunk)
            while match is None or match.end() >= len(chunk):
                chunk += _get_chunk(stream, chunk_size)
                if not chunk or length_before == len(chunk):
                    if match is None:
                        raise ValueError('Missing fields.')
                    break
            text = match.group(1)
            yield FORMATS_TYPES[field](text)
            chunk = chunk[match.end():]

def _get_chunk(stream, chunk_size):
    try:
        return stream.read(chunk_size)
    except EOFError:
        return ''

rawDescription: Python Stream Extraction

description: Python Stream Extraction


code:
class Abc:

    def __init__(self,root):
        p1Buzz = Button(root, text = "P1 BUZZ", command = self.buzzed)
        p1Buzz.pack()
        self.p1A = Button(root, text = "A")
        self.p1A.config(state='disabled')
        self.p1A.pack()

    def buzzed(self):
        self.p1A.config(state='normal')

if __name__ == '__main__':
    root = Tk()
    myapp = Abc(root)
    root.mainloop()

rawDescription: Disabling button state from other method


code:
def autoproperty(name, can_get=True, can_set=True, allow_null=False, default_value=0):
    attribute_name = '_' + name
    def getter(self):
        return getattr(self, attribute_name, default_value)
    def setter(self, value):
        if not allow_null and value is None:
            raise ValueError('Cannot set {} to None'.format(name))
        setattr(self, attribute_name, value)

    prop = property(getter if can_get else None, setter if can_set else None)

    def decorator(cls):
        setattr(cls, name, prop)
        return cls

    return decorator

rawDescription: Create a class level decorator to automatically add a property


rawDescription: How to remove comma from list in python

description: Remove comma from list in python


code: {{ (spygames / games|length * 100) | round(0) | int }}

rawDescription: Order of Operations for Jinja2 Filters?

description: Order of Operations for Jinja2 Filters


code:
from collections import OrderedDict

result = OrderedDict(zip(cursor.description, data))

rawDescription: Preserve ordering when consolidating two lists into a dict


code:
for i in self._commands:
    if input.startswirh( i):
        return self._commands[i](...)
print('Invalid command')
return False

rawDescription: text based game in python

description: Text based game in python


code:
intersections = np.hstack((mu1,mu2))[...,None]*rays[:,None,:]
distances = np.sqrt((intersections**2).sum(2))

rawDescription: Avoiding numpy loops while calculating intersections


code:
with tf.Graph().as_default() as g_1:
  input = tf.placeholder(tf.float32, name="input")
  y = f(input)
  # NOTE: using identity to get a known name for the output tensor.
  output = tf.identity(y, name="output")

gdef_1 = g_1.as_graph_def()

with tf.Graph().as_default() as g_1:
  input = tf.placeholder(tf.float32, name="input")
  z = g(input)
  output = tf.identity(y, name="output")

gdef_2 = g_2.as_graph_def()

rawDescription: Tensorflow: How to replace a node in a calculation graph?


code:
df1['count'] = df1.groupby('Date').cumcount()
df1
df2['count'] = df2.groupby('Date').cumcount()
df2

rawDescription: Pandas join/merge 2 dataframes using date as index


code:
# Extracting javscript object (a json like object)
start_tag = 'InitAppTagModal( 251570,'
end_tag = '],'
startIndex = html.find(start_tag) + len(start_tag)
endIndex = html.find(end_tag, startIndex) + len(end_tag) - 1
raw_data = html[startIndex:endIndex]

# Load raw data as python json object
data = json.loads(raw_data)

rawDescription: Missing source page information using urllib2


code:
ext = X509.new_extension('1.2.3.4',
                         'ASN1:UTF8String:Some random data')
# If required: ext.set_critical(1)
cert.add_ext(ext)

rawDescription: Create arbitrary X509 extensions with M2Crypto


rawDescription: Re-write loop to assign a number to every row in a column


code: [days_dict[day] for day in days_order[start:end]]

rawDescription: Python: get items from list between 2 known items


code:
class Friend(object):
  def __init__(self, friend_list):
    self.friend_list = list(friend_list)

f1 = Friend('ABCD')
f2 = Friend('CDEF')
f3 = Friend('AGHIJKLMN')
my_friends = [f1, f2, f3]
set().union(*(f.friend_list for f in my_friends))

rawDescription: Which method is better for combining multiple lists without duplicates?


code:
import numpy as np
np.tril(np.ones((n, n), dtype=int), -1)

rawDescription: How to set lower triangular matrix of 0-1?

description: Set lower triangular matrix of 0-1


code: sorted(map(list, product([0, 1], repeat=dimension)), key=sum)

rawDescription: For-loop to fill in node positions in an array for a cube


code:
import numpy as np
XL = np.linspace(X.min(),X.max(),100)
YL = np.linspace(Y.min(),Y.max(),100)
ZL = np.linspace(Z.min(),Z.max(),100)

ax.plot(XL,0*XL,-100,zdir='z',color='k',lw=5)
ax.plot(0*YL,YL,-100,zdir='z',color='k',lw=5)

ax.plot(YL,0*YL,-40,zdir='x',color='k',lw=5)
ax.plot(0*ZL,ZL,-40,zdir='x',color='k',lw=5)

ax.plot(XL,0*XL,40,zdir='y',color='k',lw=5)
ax.plot(0*ZL,ZL,40,zdir='y',color='k',lw=5)

rawDescription: Adding axis to offset contour plots

description: Adding axis to offset contour plots


rawDescription: Python Login: Error reading Text file

description: Python Login: Error reading Text file


code:
x.ix[(x.groupby(pd.Grouper(key='Timestamp', freq='5T'))['Volume'].transform('sum') > 65000)
     &
     (x.Timestamp.dt.hour==9)
     &
     (x.Timestamp.dt.minute>=30) & (x.Timestamp.dt.minute<=34)].set_index('Timestamp')

rawDescription: Select certain dates from Pandas dataframe


code:
@classmethod
def from_xml(cls, xml_file):
    x, y, z  = cls.__import_something_from_xml(xml_file)
    return cls(x,y,z)

rawDescription: split up classmethods in python

description: Split up classmethods in python


code:
import operator
sorted_dicts = sorted(dicts, key=operator.itemgetter("diff"))

rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


code:
df = DataFrame(np.random.randn(100,2),columns=['A','B'])
df.to_hdf('test.h5','df',mode='w',format='table')
store = pd.HDFStore('test.h5')
nrows = store.get_storer('df').nrows
nrows
r = np.random.randint(0,nrows,size=10)
r
pd.read_hdf('test.h5','df',where=pd.Index(r))

rawDescription: PyTables read random subset

description: PyTables read random subset


code:
class Object:
    def __init__(self):
        self.Command = "Script Command"

    def printCommand(self):
        print(self.Command)

class ObjectList(list):
    def printCommand(self):
        for Object in self:
            Object.printCommand()

lst = ObjectList()
lst.append(Object())
lst.append(Object())

lst.printCommand()

rawDescription: Extending a python list class to perform additional functions on its contents?


code:
print("Updating: . . ")
sdl2.SDL_SetWindowPosition(W.window, X, Y)

rawDescription: Updating Window position in PySDL2 (Help!)


rawDescription: Difference between having and not having parenthesis in if statements


code:
records = Model.search([]) #Get all the records you wan to write.
Model.write(records, {'state': 'new_state'})

rawDescription: How to change value of a selection using Python on Tryton

description: Change value of a selection using Python on Tryton


code: args, kwargs = my_call

rawDescription: Remove call() when using Mock

description: Remove call() when using Mock


code:
pattern = re.compile(r"([01]+)\1+")
print(pattern.search("11010").group())

rawDescription: Python Regex to find reccuring patterns or binary strings


code:
data_small = np.random.randint(0, 100, size=(100, 100, 10))
all(np.allclose(i1, i2)
    for i1, i2 in zip(get_indices_simple(data_small),
                      get_indices_sparse(data_small)))
# True

rawDescription: faster alternative to numpy.where?

description: Faster alternative to numpy.where


code:
from matplotlib import rc
rc('text', usetex=True)

rawDescription: Uniform spacing with Matplotlib and TeX

description: Uniform spacing with Matplotlib and TeX


code:
elem = doc.findFirst("div#hplogo")
qstring = elem.attribute('style')
regexp = QRegExp("^(.*:)?url\((.*)\)")
if regexp.indexIn(qstring) > -1:
    imageURL = regexp.capturedTexts()[-1]

rawDescription: Parsing HTML using QWebElement, how to extract an image?


code:
sort_key = lambda f: ( len(f)<=5, f )
sorted(fruits, key = sort_key, reverse = True)

rawDescription: Sorting a list of string by descending order using `key` argument without `reverse=True`?


code:
LEVEL_CHOICES = (
    (0, _('Unknown')),
    (1, _('Standard level')),
    (2, _('Professional level')),
    (3, _('Native speaker level')),
)

level = models.IntegerField(choices=LEVEL_CHOICES, default=0,
                        help_text=_('Choose a level'))

rawDescription: How to set hierarchy on Django objects of the same class?

description: Set hierarchy on Django objects of the same class


code:
def get(self):
    z = self.request.get( 'imageSrc' )
    logging.info(z)
    self.response.write( "<!DOCTYPE html>" .format( z ) )

def post(self):
    pass

rawDescription: python gae Render an image returned from ajax post json format

description: Python gae Render an image returned from ajax post json format


code:
a = ["Asia/Pacific", "North America", "India,Asia/Pacific", "China, Asia/Pacific", "New Delhi, India, Asia/Pacific", "Bangalore, India,Asia/Pacific",  "Shangai, China, Asia/Pacific", "US, North America", "New York, US, North America"]
sorted(a, key=lambda p: map(str.strip, p.split(',')[::-1]))

rawDescription: Ordering a list according to hierarchy

description: Ordering a list according to hierarchy


rawDescription: Python regular expression: extract multiple matching groups


code:
walked_directory = 'D:\folder\build'
found_file = 'D:\other\subfolder\build\a.h'
destination_directory = 'D:\other\subfolder'
destination_file = found_file.replace('walked_directory', 'destination_directory')

rawDescription: Copy all files with certain extension, while maintaining directory tree


code:
# from grako/semantics.py
class GrakoSemantics(ModelBuilderSemantics):
    def __init__(self, grammar_name):
        super(GrakoSemantics, self).__init__(
            baseType=grammars.Model,
            types=grammars.Model.classes()
        )
        self.grammar_name = grammar_name
        self.rules = OrderedDict()
...

rawDescription: Grako "code" generation

description: Grako "code" generation


code: res

rawDescription: Return only single occurrences of a string


code:
def mix_lists(l1, l2, offset=0):
    """ Mix two lists evenly, generating the elements of the mixed list. """
    m, n = len(l1), len(l2)
    for i in range(m + n):
        q, r = divmod(i * n + offset, m + n)
        yield l1[i - q] if r < m else l2[q]

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


code:
tree = etree.fromstring('<section> outer <section> inner </section> </section>')
etree.strip_tags(tree, 'section')
etree.tostring(tree)

rawDescription: Why won't lxml strip section tags?

description: Why won't lxml strip section tags


rawDescription: What does the Star operator mean in Python?


code:
a = map(float, range(100))
sys.getsizeof(a) + sys.getsizeof(a[0])*len(a)

rawDescription: python loads more memory than the actual size of the file

description: Python loads more memory than the actual size of the file


code:
class Something(object):
    def __init__(self, values_dict):
        self.values_dict = values_dict
    def __getattribute__(self, name):
        try:
            ## by default trying to access "normal" object's attributes
            return super(Something, self).__getattribute__(name)
        except AttributeError:
            ## in case that it's not "normal" attribute, taking them from our dict
            value = self.values_dict.get(name)
            if value is None:
                ## it wasn't in the dict, re-raise the AttributeError
                raise
            else:
                return value

rawDescription: How does string to identifier binding work in python?


code:
plt.setp(ax2.get_yticklabels(), color='darkgreen')
plt.setp(ax.get_yticklabels(), color='darkblue')

rawDescription: Add second axis to polar plot

description: Add second axis to polar plot


code:
wordlist ['b', 'c', 'g', 'i', 'l', 'm', 'n', 'r', 's', 'v']
leftlist ['b', 'c', 'g', 'i', 'l']
rightlist ['m', 'n', 'r', 's', 'v']

wordlist ['m', 'n', 'r', 's', 'v']
leftlist ['m', 'n']
rightlist ['r', 's', 'v']

wordlist ['m', 'n']
leftlist ['m']
rightlist ['n']

wordlist ['m']
True
4

rawDescription: Why is my implementation of binary search very inefficient?


code:
rows, cols = np.where(np.isnan(ar))
cols = (cols[:, None] + np.arange(1, N+1)).reshape(-1)
# Handle indices out of range by repeating the last column
cols = np.clip(cols, 0, ar.shape[1] - 1)
rows = np.repeat(rows, N)
result = ar[rows, cols].reshape(-1, 2)

rawDescription: Selecting values in ndarray occuring after a NaN


code:
import array
values = array.array('I')
values.itemsize
values.fromlist([i for i in range(100)])
len(values.tobytes())

rawDescription: Pack 4 byte integers into bytearray or array


code:
results = df.groupby(["X", "Y", "Z", "F"]).size()
results.reset_index()

rawDescription: Adding Column Headers to new pandas dataframe


rawDescription: Use list of strings elements as arrays

description: Use list of strings elements as arrays


code:
queryargs = [Q(name__contains=i) for i in lst]
queryset = User.objects.filter(*queryargs)

rawDescription: How to perform AND condition in django queryset?

description: Perform AND condition in django queryset


code:
def minimum_mem(limit):
    import sys
    if sys.platform == 'darwin': # or BSD in general?
        from subprocess import check_output
        mem = int(check_output(['sysctl', '-n', 'hw.memsize']))
    else: # linux
        with open("/proc/meminfo") as f:
            for line in f:
                if line.startswith("MemTotal"):
                    mem = 1024 * int(line.split()[1])
                    break
    return mem >= limit

kB = 1024.
MB = 1024 * kB
GB = 1024 * MB

rawDescription: Handling various resource requirements in an IPython cluster


code:
def naive_dac(arr, length):
    if length == 1:
        return 0

    count = naive_dac(arr, length - 1)
    for i in range(0, length):
        if arr[i] > arr[length-1]:
            count += 1
    return count

rawDescription: Average Time Complexity

description: Average Time Complexity


code:
from string import split
def rec_split(s, *tokens):
    if tokens == ():
        return s
    else:
      return map(lambda x: rec_split(x, *tokens[1:]), split(s, tokens[0]))

rawDescription: How to create a function that can split a string an arbitrary number of times depending on input arguments?

description: Create a function that can split a string an arbitrary number of times depending on input arguments


code: df.query('fold >=2 | fold <=-0.6')

rawDescription: Pandas: How to extract rows of a dataframe matching Filter1 OR filter2


code:
from functools import partial
self.fileButton.clicked.connect(partial(self.select_file, self.fileButton))

rawDescription: Click event is sent immediately after I start application (PySide and Python)


code:
res = [] #our result list
for row in matrix:
    rr = row + [True]  #row with an extra True at the end so index always works
    row_res = []       #result for this row
    for n in range(len(row) - 1):
        #if x is True, calculate the relative index of the next true
        x = rr[n+1:].index(True) if rr[n] else 0
        row_res.append(x)
    row_res.append(0)  #add an extra 0 at the end for the last element
    res.append(row_res)

rawDescription: Count number of Falses in 2d list until encountering True (Python)


code: {k: set(d1.get(k, [])) | set(d2.get(k, [])) for k in d1.viewkeys() | d2}

rawDescription: Merge two dictionaries in python with lists as values


code:
mrows = matrix.shape[0]
prows = pattern.shape[0]
out = (pattern[:,None,:] == matrix[None,:,:]).reshape(prows,-1).sum(1)/mrows

rawDescription: Numpy matrix row comparison

description: Numpy matrix row comparison


code:
def sgn_pbc(x, y, Lbox):
    d = abs(x-y)
    if d <= Lbox/2.:
        return sgn(x, y)
    else:
        return sgn(y, x)

rawDescription: efficient sign function in python for case of periodic boundary conditions

description: Efficient sign function in python for case of periodic boundary conditions


code:
from .meta import DBSession
from .foo import Foo
from .moo import Moo

rawDescription: How do I split models.py into different files for different models in Pyramid?

description: Split models.py into different files for different models in Pyramid


code:
class Door:
    def __init__ (self, position, colour, creaking = True):
        print (position, colour, creaking)

objDefs = [...,
          {'class': Door, 'kwargs': {'position': (2, 3), 'colour': 'black'} },
          ...]

#Here you actually iterate over objDefs
objDef = objDefs [1]
obj = objDef ['class'] (**objDef ['kwargs'] )

rawDescription: Use composition, strategy pattern and dictionnary to better instatiate class stored in dictionnary


code:
for x in range(0, len(timestamps)):
    table.append(timestamp)
    for datapoint in data:
        table.append(datapoint)

rawDescription: Generating HTML tables where more items have one key asnd must fit on the same row


code:
results = root.xpath(
    "//*[re:test(local-name(), '^TEXT.*')]",
    namespaces={'re': "http://exslt.org/regular-expressions"})

rawDescription: lxml find tags by regex

description: Lxml find tags by regex


code: l[i] if i < len(l) else None

rawDescription: Get value at list/array index or "None" if out of range in Python


code:
coeffs = find_coeffs(
        [(0, 0), (256, 0), (256, 256), (0, 256)],
        [(0, 0), (256, 0), (new_width, height), (xshift, height)])

img.transform((width, height), Image.PERSPECTIVE, coeffs,
        Image.BICUBIC).save(sys.argv[3])

rawDescription: How does perspective transformation work in PIL?


code:
class Bar:
    def __init__(self, foo_):
        self.foo_dict = {}
        self.foo = foo_

    @property
    def foo(self):
        return self.foo_dict["foo_key"]

    @foo.setter
    def foo(self, value):
        self.foo_dict["foo_key"] = value

    def show(self):
        print("foo={} ; foo_dict['foo_key']={}".format(
                        self.foo, self.foo_dict["foo_key"]))

b = Bar(1)
b.show()
b.foo = 2
b.show()
b.foo_dict["foo_key"] = 3
b.show()

rawDescription: How to keep variable and dictionary that contains it consistent?

description: Keep variable and dictionary that contains it consistent


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''The Westin Peachtree Plaza, Atlanta

Sheraton Atlanta Hotel

''', 'lxml')
[element.get_text(strip=True) for element in soup.select('a.propertyName > span')]

rawDescription: Parsing HTML span with Beautiful Soup

description: Parsing HTML span with Beautiful Soup


code:
from itertools import zip_longest
my_dict = {1:[1,2,3],4:[5,6,7,8],8:[9,10,11,38,99]}
for row in zip_longest(*([key] + value for key, value in sorted(my_dict.items())), fillvalue=' '):
    print(*row)

rawDescription: How can I print a dictionary in table format?

description: Print a dictionary in table format


code:
def matchats(l, r):
    """Match two strings with @ representing exactly 1 char"""
    if len(l) != len(r): return False
    for i, c1 in enumerate(l):
        c2 = r[i]
        if c1 == "@" or c2 == "@": continue
        if c1 != c2: return False
    return True

rawDescription: elegant way to match two wildcarded strings

description: Elegant way to match two wildcarded strings


code:
string.strip("'") # strips single quotes away
string.strip('"') # strips double quotes
string.strip("'\"") # both single and double quotes. The double quote in the middle is 'escaped' by the backslash character

rawDescription: Removing string quotations without slicing?


code: duplicated_items = [key for key, count in c.iteritems() if count > 1]

rawDescription: how to find whether this python list within list contains duplicates or not?

description: Find whether this python list within list contains duplicates or not


rawDescription: Can I extend list in Python with prepend elements instead append?

description: Extend list in Python with prepend elements instead append


code:
df = pd.DataFrame({'A':list('aaabbbbccc'), 'B':[1,1,0,1,1,0,0,1,0,0]})
df.groupby('A').sum()
df.groupby('A').apply(lambda x: x[x['B'] > 0]['B'].sum())
df.groupby('A').agg(lambda x: np.sum(x[x > 0]))

rawDescription: Count the number of matched element in pandas


code:
import json
with open('output.txt', 'r') as in_file:
    your_list = json.load(in_file)

rawDescription: Python write complex nest list into file as it is


code:
for x in xrange(low_x, low_x+2):
    for y in xrange(low_y, low_y+2):
        data[x][y] = average

rawDescription: Shorter way to manipulate region of two-dimensional list


code: aggregate = [y[inds == i].sum() for i in np.unique(inds)]

rawDescription: Binning values of a function in Python (numpy)


rawDescription: check if the value in a dict is not empty?

description: Check if the value in a dict is not empty


code:
for day in 'monday', 'tuesday', 'wednesday', 'thursday':
    getattr(schedule.every(), day).at(x).do(doADayofWeekTask)

rawDescription: Genericise Function call

description: Genericise Function call


code: qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

rawDescription: SQLAlchemy: how to filter date field?

description: SQLAlchemy: how to filter date field


rawDescription: Datetime to Second Conversion

description: Datetime to Second Conversion


code:
import numpy as np
import timeit
import itertools as IT
import pandas as pd

def using_empty(x):
    x = np.asarray(x)
    result = np.empty(x.shape + (2,))
    result[..., 0] = x
    result[..., 1] = np.log(x)
    return result

def using_concat(x):
    x = np.asarray(x)
    return np.concatenate([x, np.log(x)], axis=-1).reshape(x.shape+(2,), order='F')

def using_stack(x):
    x = np.asarray(x)
    return np.stack([x, np.log(x)], axis=x.ndim)

def using_ufunc(x):
    return np.array([x, np.log(x)])
using_ufunc = np.vectorize(using_ufunc, otypes=[np.ndarray])

tests = [np.arange(600),
         np.arange(600).reshape(20,30),
         np.arange(960).reshape(8,15,8)]

# check that all implementations return the same result
for x in tests:
    assert np.allclose(using_empty(x), using_concat(x))
    assert np.allclose(using_empty(x), using_stack(x))

timing = []
funcs = ['using_empty', 'using_concat', 'using_stack', 'using_ufunc']
for test, func in IT.product(tests, funcs):
    timing.append(timeit.timeit(
        '{}(test)'.format(func),
        setup='from __main__ import test, {}'.format(func), number=1000))

timing = pd.DataFrame(np.array(timing).reshape(-1, len(funcs)), columns=funcs)
print(timing)

rawDescription: efficient numpy array creation

description: Efficient numpy array creation


code:
{
    "format": "{levelname} - {asctime} - {module} - {message}",
    "style": "{",
}

rawDescription: use str.format() in django logging

description: Use str.format() in django logging


code:
def do_edit_whatever(obj):
    # Populate the fields here
    if obj.id is None:
        db.session.add(obj)
    db.session.commit()

rawDescription: Update database using scoped_session.add() in Pyramid & SQLAlchemy


code:
while True:
    investment = float(input('Enter your initial investment: '))
    if 1000 <= investment <= 100000:
        break
    else:
        print("Investment must be between $1,000 and $100,000")

#Annual interest rate
apr = 3.0 / 100.0
amount = investment

for yr in range(5):
    amount = (amount) * (1. + apr)
    print('After {:>2d} year{} you have:   $ {:>10.2f}'.format(yr, 's,' if yr > 1 else ', ', amount))

rawDescription: How to loop through a percentage investment?

description: Loop through a percentage investment


code:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button

class Container(FloatLayout):
    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)

        anchor_rb = AnchorLayout(anchor_x='right', anchor_y='bottom')
        btn = Button(text='Hello World', size=(100, 100), size_hint=(None, None))
        anchor_rb.add_widget(btn)
        self.add_widget(anchor_rb)

        anchor_lc = AnchorLayout(anchor_x='left', anchor_y='center')
        lbl = Label(text="Am i a Label ?", size=(100, 100), size_hint=(None, None))
        anchor_lc.add_widget(lbl)
        self.add_widget(anchor_lc)

class MyJB(App):
    def build(self):

        parent = Container()

        return parent

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

rawDescription: Anchor Layout to show many widgets in a screen at relative positions


code:
class SubMenu(QMenuBar):
    def __init__(self, parent=None):
        super(SubMenu, self).__init__(parent)
        self.addAction("File")
        self.addAction("View")
        self.setStyleSheet("""QMenuBar {
             background-color: blue;
        }""")
        self.resize(320, 240)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = SubMenu()
    m.show()
    app.exec_()

rawDescription: Styling The Menu Bar in PyQT4

description: Styling The Menu Bar in PyQT4


rawDescription: Self reference for assertions while unittesting


code: urls = [span.a["href"] for span in soup.findAll('span') if span.a]

rawDescription: Search html using BeautifulSoup in Python


code:
with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for line in istr:
            line = line.rstrip('\n') + 'S'
            print(line, file=ostr)

rawDescription: Append Text (Single Letter) to the end of each line in a text file


code: success: deferredData.resolve()

rawDescription: Undefined result from Deferred AJAX request to Flask


code: JINJA_FILTERS = {'dict_replace': dict_replace}

rawDescription: How to perform multiple replacements on string in Jinja2?

description: Perform multiple replacements on string in Jinja2


code:
reg = ClassRegistry()
reg.add_file_classes("/var/imports/foo.py", ["baz", "monkey"])
reg.add_file_classes("/var/imports/bar.py", ["ape"])

rawDescription: Dynamic module import of class list from module given its full path


code:
[
{'company': {'employee': {'age': 1, 'name': 'aaaaaaaaaa', 'others': {'grade': 'C'}}}},
{'company': {'employee': {'age': 99, 'name': 'aaaaaaaaaa', 'others': {'grade': 'C'}}}}
]

rawDescription: Generate all combinations from a nested python dictionary and segregate them


code: hello

rawDescription: Attach random value

description: Attach random value


rawDescription: Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes


code: super_list = [[MyClass() for j in xrange(5)] for i in xrange(100)]

rawDescription: Lists of lists of custom objects in Python


code:
D = defaultdict(list)
D[5].append(3)
D[5]

rawDescription: How to read python dictionary and tuples

description: Read python dictionary and tuples


code:
cnx = mysqldb.cursor()
cnx.execute("SHOW TABLES")

tables = cnx.fetchall()   #  [('table1',), ('table2',), ...]
self.list_customers = [list(rec) for rec in tables]
...

rawDescription: Pul MySql Database values to liststore - Python3 and Mysql.connector


code:
with open('sample_state_geo.csv', 'rb') as geo_file:
    with open('outputfile.csv', 'wd') as outfile:
        reader = csv.reader(geo_file, delimiter='\t')
        geo_header = next(reader, None)  # grab header
        geo_header.pop(6) # no need to list LOGRECNO header twice

        writer = csv.writer(outfile, delimiter='\t')
        writer.writerow(census_header + geo_header)

        for row in reader:
            if row[6] not in census:
                # no census data for this LOGRECNO entry
                continue
            # new row is all of the census data plus all of geo minus column 7
            newrow = census[row[6]] + row[:6] + row[7:]
            writer.writerow(newrow)

rawDescription: How can I merge two csv files by a common column, in the case of unequal rows?

description: Merge two csv files by a common column, in the case of unequal rows


code:
samples = 'SX00182'
[x if not x.isdigit() else str((int(x) + 1) % 10) for x in samples]

rawDescription: Python: add 1 to each digit that is an integer


code: plt.plot(x, y, 'o', ms=3, mew=0, alpha=0.3)

rawDescription: matplotlib remove unseen shapes

description: Matplotlib remove unseen shapes


rawDescription: Display a decimal in scientific notation


code:
import glob, sys, re

def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
    return [int(text) if text.isdigit() else text.lower()
            for text in re.split(_nsre, s)]

for file in sorted(glob.iglob(sys.argv[1] + '/*.xml'), key=natural_sort_key):
    with open(file) as x:
        f = x.read()

rawDescription: Python multiprocessing text extraction performance issue vs Perl equivalent


code: C = A * B

rawDescription: Multiply two Pandas dataframes with same shape and same columns names


code: B = MetaClass(B.__name__, B.__bases__, B.__dict__)

rawDescription: Is there a way to set metaclass after the class definition?


code:
seconds = [pair[1] for pair in pairs]
ordered = [s for s in main_streets if s not in seconds]
if len(ordered) > 1:
    raise Exception("Error: There is not one continuous chain.")

rawDescription: How to classify a list of objects having an intersecting list of values

description: Classify a list of objects having an intersecting list of values


code:
county = get_field_value(driver, "county")
print(county)  # prints "Harris County"

rawDescription: How to use Selenium to get the housing data

description: Use Selenium to get the housing data


rawDescription: django unit test for logged in or anonymous user

description: Django unit test for logged in or anonymous user


code: your_list.sort(key=attrgetter('the name of your int'))

rawDescription: Quick Method for Sorting User Defined Classes


code:
def sum_v1_v2_into_v(list_of_dicts):
    for d in list_of_dicts:
        v1 = d.pop('v1')
        v2 = d.pop('v2')
        d['v'] = v1 + v2

rawDescription: How to replace dict values with their sum

description: Replace dict values with their sum


code:
lis = (2,6,4,8,7,9,14,3)
dic = dict(zip(lis, lis[1:]))
dic[4]
dic[7]
dic.get(100, 'not found') #dict.get can handle key errors

rawDescription: Most efficient way of finding the next element in a tuple


code:
new_tag = Tag.object.create(slug=tag)
TagStatus.objects.create(status=status, tag=new_tag, user=user)

rawDescription: Django object isn't saving username with get_or_create()


code:
STATIC_PATHS = [
    'images',
    'extra/robots.txt',
    'extra/favicon.ico'
]
EXTRA_PATH_METADATA = {
    'extra/robots.txt': {'path': 'robots.txt'},
    'extra/favicon.ico': {'path': 'favicon.ico'}
}

rawDescription: How to add a favicon to a Pelican blog?

description: Add a favicon to a Pelican blog


code:
def contiguous(seq):
    seq = iter(seq)
    all(x is None for x in seq)        # Burn through any Nones at the beginning
    any(x is None for x in seq)        # and the first group
    return all(x is None for x in seq) # everthing else (if any) should be None.

rawDescription: Pythonic way to determine whether not null list entries are 'continuous'


code:
def remove(rem,my_string):
    return re.sub(".*"+rem+".*\n?","",my_string)

remove("VVV",my_string)
remove("XXX",my_string)
remove("BBB",my_string)
remove("CCCC",my_string)

rawDescription: Removing pattern matched line from multiline string in python


rawDescription: Compare 1st element in list of lists and write number of repeated values


code: pixelR, pixelR, pixelR = pixelValueTuple

rawDescription: How do I change each pixel

description: Change each pixel


code:
tags = np.zeros((10,),dtype=dtype)
tags

rawDescription: Store ten most related items in structured array Python


code:
out = np.empty((3, 4))
for r, j in enumerate(a):
    for c, k in enumerate(b):
        out[r, c] = my_func(j, k)

out

rawDescription: vectorize a function for numpy, that correlates each element of one vector with each element of another

description: Vectorize a function for numpy, that correlates each element of one vector with each element of another


rawDescription: A cleaner way to generate a list of running IDs


code:
def most_common_line_len(filename):
    with open('somefile.txt') as f:
        return Counter(map(lambda line: len(line.rstrip()),
                           (line for line in f))).most_common(1)[0][0]

rawDescription: find the most common length of text line in a file with various line sizes present using python

description: Find the most common length of text line in a file with various line sizes present using python


code:
import email

[ (text, encoding) ] = email.header.decode_header(incode)
result = text.decode(encoding)

rawDescription: Python decoding from iso-8859-5

description: Python decoding from iso-8859-5


code:
def send_static_file(self, filename):
    if not current_user.is_authenticated():
        abort(401)
    return super(Flask, self).send_static_file(filename)

rawDescription: Python : Flask : Catch All Url for login_required


code:
list = ['LnNlbHBtYXhlIGVzdSBvdCBlZXJmIGxlZUYgLnNldGlzYmV3IGNpZmZhcnQgaGdpaCBubyBub2l0YXNpbGFtcm9uZWQgZm8gdHBlY25vYyBlaHQgZWJpcmNzZUQgLjQ=', 'ZWxpZiBlbm8gbmkgZWIgdHN1TSApaXYgICAg', 'c25vaXRhY2lmaWNlcHMgOC1QRVAgdGVlbSB0c3VNICl2ICAgIA==', 'Ni4yIG5vaHR5UCBodGl3IGtyb3cgdHN1TSApdmkgICAg', 'c2VsdWRvbSByZWh0byB5YiBlbGJhdHJvcG1pIGViIGRsdW9ocyBzc2FsQyApaWlpICAgIA==']
s = ''.join(list)
s = s.decode('base64', 'strict')
print (s[::-1])

rawDescription: Decoding reversed mulitline string encoded in base64 format automatically


code: array = copy.deepcopy(new_list)

rawDescription: Python 3.3.4. How to swap values within an array


code:
dfrm_test
dfrm_test["A"].apply(np.frompyfunc((lambda x: x[0:2]), 1, 1))
pandas.version.version
dfrm_test["A"].apply(lambda x: x[0:2])

rawDescription: Python Pandas: How to broadcast an operation using apply without writing a secondary function


code:
D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}}
key_list = ['key1', 'key2', 'key4']
sub = D
for i in key_list[:-1]:
    sub = sub[i]
del sub[key_list[-1]]
D

rawDescription: Dynamically delete an item from a nested dictionary


code:
dfg = df.groupby('bin').count()
dfg

rawDescription: python grouping similar categorical values

description: Python grouping similar categorical values


rawDescription: Numpy's __array_interface__ not returning dict


code:
string = "I have 9 sheep in my garageVideo games are super cool. Some peanuts can sing, though they taste a whole lot better than they sound!"
result = regex.split("(?V1)(?<=[a-z])(?=[A-Z])|(?<=[.!?]) +(?=[A-Z])", string)
print(result)

rawDescription: Split Sentence on Punctuation or Camel-Case


code: form = SQLFORM(db.some_table)

rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


rawDescription: Complex numbers usage in python

description: Complex numbers usage in python


rawDescription: XPATH: If there is element with certain value assume "phone" then get it's sibling value


code:
def days(i: int) -> int:
    return 60 * 60 * 24 * i

df_casted.where(unix_timestamp() - col("ts").cast("long") < days(7))

rawDescription: PySpark: filtering a DataFrame by date field in range where date is string


code:
import ctypes

foo = ctypes.CDLL('./foo.so')
foo.main()

rawDescription: Python C extension link with a custom shared library


code:
def print_frame(n, m, c):
    print(c * m)
    for i in range(1, n - 1):
        print(c, ' ' * (m - 2), c, sep='')
    print(c * m)

rawDescription: Printing a frame in python

description: Printing a frame in python


code:
import os

file_dict = {}  # create a dictionary
os.chdir(os.path.join(os.path.expanduser('~'), directory_name))
for key in [file for file in os.listdir(os.getcwd()) if os.path.isfile(file)]:
    value = open(key).readlines()[0].split()[0]
    file_dict[key] = value

rawDescription: Loop through files in a subdirectory, append filenames as dictionary keys


rawDescription: Python - Convert array with list with different sizes to string


code: len(cars) - 1 == 3

rawDescription: Pass dbf data to sentence and save as text file using Python 2.7


rawDescription: How can I call all items in a list item?

description: Call all items in a list item


rawDescription: Django Many to Many Fields - OK with large datasets?


code:
normalized = set(map(normalize, set_of_lists))
len(normalized)

rawDescription: Check if two nested lists are equivalent upon substitution


code:
hottest_cake_ids = Bakery.objects.annotate(hottest_cake_id=Max('cake__id')).values_list('hottest_cake_id', flat=True)
hottest_cakes = Cake.objects.filter(id__in=hottest_cake_ids)

rawDescription: Django Query That Get Most Recent Objects From Different Categories


code:
BuiltinFunctionType, BuiltinMethodType
DictProxyType
EllipsisType
FrameType
GeneratorType
GetSetDescriptorType
MemberDescriptorType
NoneType
NotImplementedType
TracebackType

rawDescription: Where can I find documentation for calling the various types in Python's types module?


code:
# helper function to keep the code DRY
def get_numbers(message):
    try:
        # this is called list comprehension
        return [int(x) for x in input(message).split()]
    except:
        # input can produce errors such as casting non-ints
        print("Error while reading numbers")
        return []

def main():
     # 1: create the list - wait for at least two numbers
     nums = []
     while len(nums) < 2:
         nums.extend(get_numbers("Enter numbers please: "))
     # only keep two first numbers, this is called slicing
     nums = nums[:2]
     # summarize using the built-in standard 'sum' function
     numSum = sum(nums)
     numProduct = nums[0] * nums[1]
     print("sum = ",numSum)
     print("product = ",numProduct)

main()

rawDescription: Python Basic Input Confusion

description: Python Basic Input Confusion


rawDescription: Django: Get related model class from parent model class